repo_name
stringclasses
6 values
pr_number
int64
512
78.9k
pr_title
stringlengths
3
144
pr_description
stringlengths
0
30.3k
author
stringlengths
2
21
date_created
timestamp[ns, tz=UTC]
date_merged
timestamp[ns, tz=UTC]
previous_commit
stringlengths
40
40
pr_commit
stringlengths
40
40
query
stringlengths
17
30.4k
filepath
stringlengths
9
210
before_content
stringlengths
0
112M
after_content
stringlengths
0
112M
label
int64
-1
1
dotnet/roslyn
55,290
Fix 'quick info' and 'use explicit type' for implicit lambdas
CyrusNajmabadi
2021-07-30T18:48:59Z
2021-08-03T18:56:45Z
3a5457c3b9483c7b2be1cf6899ee3564c8ade6cf
416765ff976b2a2776c0103d3c7033f9b1667f27
Fix 'quick info' and 'use explicit type' for implicit lambdas.
./src/EditorFeatures/Core/ExternalAccess/IntelliCode/IntentProcessor.cs
// Licensed to the .NET Foundation under one or more agreements. // 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.Composition; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.ExternalAccess.IntelliCode.Api; using Microsoft.CodeAnalysis.Features.Intents; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.ExternalAccess.IntelliCode { [Export(typeof(IIntentSourceProvider)), Shared] internal class IntentSourceProvider : IIntentSourceProvider { private readonly ImmutableDictionary<(string LanguageName, string IntentName), Lazy<IIntentProvider, IIntentProviderMetadata>> _lazyIntentProviders; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public IntentSourceProvider([ImportMany] IEnumerable<Lazy<IIntentProvider, IIntentProviderMetadata>> lazyIntentProviders) { _lazyIntentProviders = CreateProviderMap(lazyIntentProviders); } private static ImmutableDictionary<(string LanguageName, string IntentName), Lazy<IIntentProvider, IIntentProviderMetadata>> CreateProviderMap( IEnumerable<Lazy<IIntentProvider, IIntentProviderMetadata>> lazyIntentProviders) { return lazyIntentProviders.ToImmutableDictionary( provider => (provider.Metadata.LanguageName, provider.Metadata.IntentName), provider => provider); } public async Task<ImmutableArray<IntentSource>> ComputeIntentsAsync(IntentRequestContext intentRequestContext, CancellationToken cancellationToken) { var currentDocument = intentRequestContext.CurrentSnapshotSpan.Snapshot.GetOpenDocumentInCurrentContextWithChanges(); if (currentDocument == null) { throw new ArgumentException("could not retrieve document for request snapshot"); } var languageName = currentDocument.Project.Language; if (!_lazyIntentProviders.TryGetValue((LanguageName: languageName, IntentName: intentRequestContext.IntentName), out var provider)) { Logger.Log(FunctionId.Intellicode_UnknownIntent, KeyValueLogMessage.Create(LogType.UserAction, m => { m["intent"] = intentRequestContext.IntentName; m["language"] = languageName; })); return ImmutableArray<IntentSource>.Empty; } var currentText = await currentDocument.GetTextAsync(cancellationToken).ConfigureAwait(false); var originalDocument = currentDocument.WithText(currentText.WithChanges(intentRequestContext.PriorTextEdits)); var selectionTextSpan = intentRequestContext.PriorSelection; var results = await provider.Value.ComputeIntentAsync( originalDocument, selectionTextSpan, currentDocument, intentRequestContext.IntentData, cancellationToken).ConfigureAwait(false); if (results.IsDefaultOrEmpty) { return ImmutableArray<IntentSource>.Empty; } using var _ = ArrayBuilder<IntentSource>.GetInstance(out var convertedResults); foreach (var result in results) { var convertedIntent = await ConvertToIntelliCodeResultAsync(result, originalDocument, currentDocument, cancellationToken).ConfigureAwait(false); convertedResults.AddIfNotNull(convertedIntent); } return convertedResults.ToImmutable(); } private static async Task<IntentSource?> ConvertToIntelliCodeResultAsync( IntentProcessorResult processorResult, Document originalDocument, Document currentDocument, CancellationToken cancellationToken) { var newSolution = processorResult.Solution; // Merge linked file changes so all linked files have the same text changes. newSolution = await newSolution.WithMergedLinkedFileChangesAsync(originalDocument.Project.Solution, cancellationToken: cancellationToken).ConfigureAwait(false); // For now we only support changes to the current document. Everything else is dropped. var changedDocument = newSolution.GetRequiredDocument(currentDocument.Id); var textDiffService = newSolution.Workspace.Services.GetRequiredService<IDocumentTextDifferencingService>(); // Compute changes against the current version of the document. var textDiffs = await textDiffService.GetTextChangesAsync(currentDocument, changedDocument, cancellationToken).ConfigureAwait(false); if (textDiffs.IsEmpty) { return null; } return new IntentSource(processorResult.Title, textDiffs, processorResult.ActionName); } } }
// Licensed to the .NET Foundation under one or more agreements. // 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.Composition; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.ExternalAccess.IntelliCode.Api; using Microsoft.CodeAnalysis.Features.Intents; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.ExternalAccess.IntelliCode { [Export(typeof(IIntentSourceProvider)), Shared] internal class IntentSourceProvider : IIntentSourceProvider { private readonly ImmutableDictionary<(string LanguageName, string IntentName), Lazy<IIntentProvider, IIntentProviderMetadata>> _lazyIntentProviders; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public IntentSourceProvider([ImportMany] IEnumerable<Lazy<IIntentProvider, IIntentProviderMetadata>> lazyIntentProviders) { _lazyIntentProviders = CreateProviderMap(lazyIntentProviders); } private static ImmutableDictionary<(string LanguageName, string IntentName), Lazy<IIntentProvider, IIntentProviderMetadata>> CreateProviderMap( IEnumerable<Lazy<IIntentProvider, IIntentProviderMetadata>> lazyIntentProviders) { return lazyIntentProviders.ToImmutableDictionary( provider => (provider.Metadata.LanguageName, provider.Metadata.IntentName), provider => provider); } public async Task<ImmutableArray<IntentSource>> ComputeIntentsAsync(IntentRequestContext intentRequestContext, CancellationToken cancellationToken) { var currentDocument = intentRequestContext.CurrentSnapshotSpan.Snapshot.GetOpenDocumentInCurrentContextWithChanges(); if (currentDocument == null) { throw new ArgumentException("could not retrieve document for request snapshot"); } var languageName = currentDocument.Project.Language; if (!_lazyIntentProviders.TryGetValue((LanguageName: languageName, IntentName: intentRequestContext.IntentName), out var provider)) { Logger.Log(FunctionId.Intellicode_UnknownIntent, KeyValueLogMessage.Create(LogType.UserAction, m => { m["intent"] = intentRequestContext.IntentName; m["language"] = languageName; })); return ImmutableArray<IntentSource>.Empty; } var currentText = await currentDocument.GetTextAsync(cancellationToken).ConfigureAwait(false); var originalDocument = currentDocument.WithText(currentText.WithChanges(intentRequestContext.PriorTextEdits)); var selectionTextSpan = intentRequestContext.PriorSelection; var results = await provider.Value.ComputeIntentAsync( originalDocument, selectionTextSpan, currentDocument, intentRequestContext.IntentData, cancellationToken).ConfigureAwait(false); if (results.IsDefaultOrEmpty) { return ImmutableArray<IntentSource>.Empty; } using var _ = ArrayBuilder<IntentSource>.GetInstance(out var convertedResults); foreach (var result in results) { var convertedIntent = await ConvertToIntelliCodeResultAsync(result, originalDocument, currentDocument, cancellationToken).ConfigureAwait(false); convertedResults.AddIfNotNull(convertedIntent); } return convertedResults.ToImmutable(); } private static async Task<IntentSource?> ConvertToIntelliCodeResultAsync( IntentProcessorResult processorResult, Document originalDocument, Document currentDocument, CancellationToken cancellationToken) { var newSolution = processorResult.Solution; // Merge linked file changes so all linked files have the same text changes. newSolution = await newSolution.WithMergedLinkedFileChangesAsync(originalDocument.Project.Solution, cancellationToken: cancellationToken).ConfigureAwait(false); // For now we only support changes to the current document. Everything else is dropped. var changedDocument = newSolution.GetRequiredDocument(currentDocument.Id); var textDiffService = newSolution.Workspace.Services.GetRequiredService<IDocumentTextDifferencingService>(); // Compute changes against the current version of the document. var textDiffs = await textDiffService.GetTextChangesAsync(currentDocument, changedDocument, cancellationToken).ConfigureAwait(false); if (textDiffs.IsEmpty) { return null; } return new IntentSource(processorResult.Title, textDiffs, processorResult.ActionName); } } }
-1
dotnet/roslyn
55,290
Fix 'quick info' and 'use explicit type' for implicit lambdas
CyrusNajmabadi
2021-07-30T18:48:59Z
2021-08-03T18:56:45Z
3a5457c3b9483c7b2be1cf6899ee3564c8ade6cf
416765ff976b2a2776c0103d3c7033f9b1667f27
Fix 'quick info' and 'use explicit type' for implicit lambdas.
./src/VisualStudio/Core/Test/CodeModel/CSharp/CodeNamespaceTests.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Threading.Tasks Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Test.Utilities Imports Roslyn.Test.Utilities Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.CodeModel.CSharp Public Class CodeNamespaceTests Inherits AbstractCodeNamespaceTests #Region "Comment tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestComment1() Dim code = <Code> namespace $$N { } </Code> TestComment(code, String.Empty) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestComment2() Dim code = <Code> // Goo // Bar namespace $$N { } </Code> TestComment(code, "Goo" & vbCrLf & "Bar" & vbCrLf) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestComment3() Dim code = <Code> namespace N1 { } // Goo // Bar namespace $$N2 { } </Code> TestComment(code, "Bar" & vbCrLf) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestComment4() Dim code = <Code> namespace N1 { } // Goo /* Bar */ namespace $$N2 { } </Code> TestComment(code, "Bar" & vbCrLf) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestComment5() Dim code = <Code> namespace N1 { } // Goo /* Bar */ namespace $$N2 { } </Code> TestComment(code, "Bar" & vbCrLf) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestComment6() Dim code = <Code> namespace N1 { } // Goo /* Hello World! */ namespace $$N2 { } </Code> TestComment(code, "Hello" & vbCrLf & "World!" & vbCrLf) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestComment7() Dim code = <Code> namespace N1 { } // Goo /* Hello World! */ namespace $$N2 { } </Code> TestComment(code, "Hello" & vbCrLf & vbCrLf & "World!" & vbCrLf) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestComment8() Dim code = <Code> /* This * is * a * multi-line * comment! */ namespace $$N { } </Code> TestComment(code, "This" & vbCrLf & "is" & vbCrLf & "a" & vbCrLf & "multi-line" & vbCrLf & "comment!" & vbCrLf) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestComment9() Dim code = <Code> // Goo /// &lt;summary&gt;Bar&lt;/summary&gt; namespace $$N { } </Code> TestComment(code, String.Empty) End Sub #End Region #Region "DocComment tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestDocComment1() Dim code = <Code> /// &lt;summary&gt;Hello World&lt;/summary&gt; namespace $$N { } </Code> TestDocComment(code, "<doc>" & vbCrLf & "<summary>Hello World</summary>" & vbCrLf & "</doc>") End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestDocComment2() Dim code = <Code> /// &lt;summary&gt; /// Hello World /// &lt;/summary&gt; namespace $$N { } </Code> TestDocComment(code, "<doc>" & vbCrLf & "<summary>" & vbCrLf & "Hello World" & vbCrLf & "</summary>" & vbCrLf & "</doc>") End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestDocComment3() Dim code = <Code> /// &lt;summary&gt; /// Hello World ///&lt;/summary&gt; namespace $$N { } </Code> TestDocComment(code, "<doc>" & vbCrLf & " <summary>" & vbCrLf & " Hello World" & vbCrLf & "</summary>" & vbCrLf & "</doc>") End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestDocComment4() Dim code = <Code> /// &lt;summary&gt; /// Summary /// &lt;/summary&gt; /// &lt;remarks&gt;Remarks&lt;/remarks&gt; namespace $$N { } </Code> TestDocComment(code, "<doc>" & vbCrLf & "<summary>" & vbCrLf & "Summary" & vbCrLf & "</summary>" & vbCrLf & "<remarks>Remarks</remarks>" & vbCrLf & "</doc>") End Sub #End Region #Region "Set Comment tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetComment1() As Task Dim code = <Code> // Goo // Bar namespace $$N { } </Code> Dim expected = <Code> namespace N { } </Code> Await TestSetComment(code, expected, Nothing) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetComment2() As Task Dim code = <Code> // Goo /// &lt;summary&gt;Bar&lt;/summary&gt; namespace $$N { } </Code> Dim expected = <Code> // Goo /// &lt;summary&gt;Bar&lt;/summary&gt; // Bar namespace N { } </Code> Await TestSetComment(code, expected, "Bar") End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetComment3() As Task Dim code = <Code> // Goo // Bar namespace $$N { } </Code> Dim expected = <Code> // Blah namespace N { } </Code> Await TestSetComment(code, expected, "Blah") End Function #End Region #Region "Set DocComment tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetDocComment_Nothing() As Task Dim code = <Code> namespace $$N { } </Code> Dim expected = <Code> namespace N { } </Code> Await TestSetDocComment(code, expected, Nothing, ThrowsArgumentException(Of String)) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetDocComment_InvalidXml1() As Task Dim code = <Code> namespace $$N { } </Code> Dim expected = <Code> namespace N { } </Code> Await TestSetDocComment(code, expected, "<doc><summary>Blah</doc>", ThrowsArgumentException(Of String)) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetDocComment_InvalidXml2() As Task Dim code = <Code> namespace $$N { } </Code> Dim expected = <Code> namespace N { } </Code> Await TestSetDocComment(code, expected, "<doc___><summary>Blah</summary></doc___>", ThrowsArgumentException(Of String)) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetDocComment1() As Task Dim code = <Code> namespace $$N { } </Code> Dim expected = <Code> /// &lt;summary&gt;Hello World&lt;/summary&gt; namespace N { } </Code> Await TestSetDocComment(code, expected, "<doc><summary>Hello World</summary></doc>") End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetDocComment2() As Task Dim code = <Code> /// &lt;summary&gt;Hello World&lt;/summary&gt; namespace $$N { } </Code> Dim expected = <Code> /// &lt;summary&gt;Blah&lt;/summary&gt; namespace N { } </Code> Await TestSetDocComment(code, expected, "<doc><summary>Blah</summary></doc>") End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetDocComment3() As Task Dim code = <Code> // Goo namespace $$N { } </Code> Dim expected = <Code> // Goo /// &lt;summary&gt;Blah&lt;/summary&gt; namespace N { } </Code> Await TestSetDocComment(code, expected, "<doc><summary>Blah</summary></doc>") End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetDocComment4() As Task Dim code = <Code> /// &lt;summary&gt;FogBar&lt;/summary&gt; // Goo namespace $$N { } </Code> Dim expected = <Code> /// &lt;summary&gt;Blah&lt;/summary&gt; // Goo namespace N { } </Code> Await TestSetDocComment(code, expected, "<doc><summary>Blah</summary></doc>") End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetDocComment5() As Task Dim code = <Code> namespace N1 { namespace $$N2 { } } </Code> Dim expected = <Code> namespace N1 { /// &lt;summary&gt;Hello World&lt;/summary&gt; namespace N2 { } } </Code> Await TestSetDocComment(code, expected, "<doc><summary>Hello World</summary></doc>") End Function #End Region #Region "Set Name tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetName_SameName() As Task Dim code = <Code><![CDATA[ namespace N$$ { class C { } } ]]></Code> Dim expected = <Code><![CDATA[ namespace N { class C { } } ]]></Code> Await TestSetName(code, expected, "N", NoThrow(Of String)()) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetName_NewName() As Task Dim code = <Code><![CDATA[ namespace N$$ { class C { } } ]]></Code> Dim expected = <Code><![CDATA[ namespace N2 { class C { } } ]]></Code> Await TestSetName(code, expected, "N2", NoThrow(Of String)()) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetName_NewName_FileScopedNamespace() As Task Dim code = <Code><![CDATA[ namespace N$$; class C { } ]]></Code> Dim expected = <Code><![CDATA[ namespace N2; class C { } ]]></Code> Await TestSetName(code, expected, "N2", NoThrow(Of String)()) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetName_SimpleNameToDottedName() As Task Dim code = <Code><![CDATA[ namespace N1$$ { class C { } } ]]></Code> Dim expected = <Code><![CDATA[ namespace N2.N3 { class C { } } ]]></Code> Await TestSetName(code, expected, "N2.N3", NoThrow(Of String)()) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetName_DottedNameToSimpleName() As Task Dim code = <Code><![CDATA[ namespace N1.N2$$ { class C { } } ]]></Code> Dim expected = <Code><![CDATA[ namespace N3.N4 { class C { } } ]]></Code> Await TestSetName(code, expected, "N3.N4", NoThrow(Of String)()) End Function #End Region #Region "Remove tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestRemove1() As Task Dim code = <Code> namespace $$Goo { class C { } } </Code> Dim expected = <Code> namespace Goo { } </Code> Await TestRemoveChild(code, expected, "C") End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestRemove1_FileScopedNamespace() As Task Dim code = <Code> namespace $$Goo; class C { } </Code> Dim expected = <Code> namespace Goo; </Code> Await TestRemoveChild(code, expected, "C") End Function #End Region <WorkItem(858153, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/858153")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestChildren1() Dim code = <Code> namespace N$$ { class C1 { } class C2 { } class C3 { } } </Code> TestChildren(code, IsElement("C1", EnvDTE.vsCMElement.vsCMElementClass), IsElement("C2", EnvDTE.vsCMElement.vsCMElementClass), IsElement("C3", EnvDTE.vsCMElement.vsCMElementClass)) End Sub <WorkItem(858153, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/858153")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestChildren1_FileScopedNamespace() Dim code = <Code> namespace N$$; class C1 { } class C2 { } class C3 { } </Code> TestChildren(code, IsElement("C1", EnvDTE.vsCMElement.vsCMElementClass), IsElement("C2", EnvDTE.vsCMElement.vsCMElementClass), IsElement("C3", EnvDTE.vsCMElement.vsCMElementClass)) End Sub <WorkItem(150349, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/150349")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub NoChildrenForInvalidMembers() Dim code = <Code> namespace N$$ { void M() { } int P { get { return 42; } } event System.EventHandler E; } </Code> TestChildren(code, NoElements) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestTypeDescriptor_GetProperties() Dim code = <Code> namespace $$N { } </Code> TestPropertyDescriptors(Of EnvDTE.CodeNamespace)(code) End Sub Protected Overrides ReadOnly Property LanguageName As String Get Return LanguageNames.CSharp End Get End Property End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Threading.Tasks Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Test.Utilities Imports Roslyn.Test.Utilities Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.CodeModel.CSharp Public Class CodeNamespaceTests Inherits AbstractCodeNamespaceTests #Region "Comment tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestComment1() Dim code = <Code> namespace $$N { } </Code> TestComment(code, String.Empty) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestComment2() Dim code = <Code> // Goo // Bar namespace $$N { } </Code> TestComment(code, "Goo" & vbCrLf & "Bar" & vbCrLf) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestComment3() Dim code = <Code> namespace N1 { } // Goo // Bar namespace $$N2 { } </Code> TestComment(code, "Bar" & vbCrLf) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestComment4() Dim code = <Code> namespace N1 { } // Goo /* Bar */ namespace $$N2 { } </Code> TestComment(code, "Bar" & vbCrLf) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestComment5() Dim code = <Code> namespace N1 { } // Goo /* Bar */ namespace $$N2 { } </Code> TestComment(code, "Bar" & vbCrLf) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestComment6() Dim code = <Code> namespace N1 { } // Goo /* Hello World! */ namespace $$N2 { } </Code> TestComment(code, "Hello" & vbCrLf & "World!" & vbCrLf) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestComment7() Dim code = <Code> namespace N1 { } // Goo /* Hello World! */ namespace $$N2 { } </Code> TestComment(code, "Hello" & vbCrLf & vbCrLf & "World!" & vbCrLf) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestComment8() Dim code = <Code> /* This * is * a * multi-line * comment! */ namespace $$N { } </Code> TestComment(code, "This" & vbCrLf & "is" & vbCrLf & "a" & vbCrLf & "multi-line" & vbCrLf & "comment!" & vbCrLf) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestComment9() Dim code = <Code> // Goo /// &lt;summary&gt;Bar&lt;/summary&gt; namespace $$N { } </Code> TestComment(code, String.Empty) End Sub #End Region #Region "DocComment tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestDocComment1() Dim code = <Code> /// &lt;summary&gt;Hello World&lt;/summary&gt; namespace $$N { } </Code> TestDocComment(code, "<doc>" & vbCrLf & "<summary>Hello World</summary>" & vbCrLf & "</doc>") End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestDocComment2() Dim code = <Code> /// &lt;summary&gt; /// Hello World /// &lt;/summary&gt; namespace $$N { } </Code> TestDocComment(code, "<doc>" & vbCrLf & "<summary>" & vbCrLf & "Hello World" & vbCrLf & "</summary>" & vbCrLf & "</doc>") End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestDocComment3() Dim code = <Code> /// &lt;summary&gt; /// Hello World ///&lt;/summary&gt; namespace $$N { } </Code> TestDocComment(code, "<doc>" & vbCrLf & " <summary>" & vbCrLf & " Hello World" & vbCrLf & "</summary>" & vbCrLf & "</doc>") End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestDocComment4() Dim code = <Code> /// &lt;summary&gt; /// Summary /// &lt;/summary&gt; /// &lt;remarks&gt;Remarks&lt;/remarks&gt; namespace $$N { } </Code> TestDocComment(code, "<doc>" & vbCrLf & "<summary>" & vbCrLf & "Summary" & vbCrLf & "</summary>" & vbCrLf & "<remarks>Remarks</remarks>" & vbCrLf & "</doc>") End Sub #End Region #Region "Set Comment tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetComment1() As Task Dim code = <Code> // Goo // Bar namespace $$N { } </Code> Dim expected = <Code> namespace N { } </Code> Await TestSetComment(code, expected, Nothing) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetComment2() As Task Dim code = <Code> // Goo /// &lt;summary&gt;Bar&lt;/summary&gt; namespace $$N { } </Code> Dim expected = <Code> // Goo /// &lt;summary&gt;Bar&lt;/summary&gt; // Bar namespace N { } </Code> Await TestSetComment(code, expected, "Bar") End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetComment3() As Task Dim code = <Code> // Goo // Bar namespace $$N { } </Code> Dim expected = <Code> // Blah namespace N { } </Code> Await TestSetComment(code, expected, "Blah") End Function #End Region #Region "Set DocComment tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetDocComment_Nothing() As Task Dim code = <Code> namespace $$N { } </Code> Dim expected = <Code> namespace N { } </Code> Await TestSetDocComment(code, expected, Nothing, ThrowsArgumentException(Of String)) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetDocComment_InvalidXml1() As Task Dim code = <Code> namespace $$N { } </Code> Dim expected = <Code> namespace N { } </Code> Await TestSetDocComment(code, expected, "<doc><summary>Blah</doc>", ThrowsArgumentException(Of String)) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetDocComment_InvalidXml2() As Task Dim code = <Code> namespace $$N { } </Code> Dim expected = <Code> namespace N { } </Code> Await TestSetDocComment(code, expected, "<doc___><summary>Blah</summary></doc___>", ThrowsArgumentException(Of String)) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetDocComment1() As Task Dim code = <Code> namespace $$N { } </Code> Dim expected = <Code> /// &lt;summary&gt;Hello World&lt;/summary&gt; namespace N { } </Code> Await TestSetDocComment(code, expected, "<doc><summary>Hello World</summary></doc>") End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetDocComment2() As Task Dim code = <Code> /// &lt;summary&gt;Hello World&lt;/summary&gt; namespace $$N { } </Code> Dim expected = <Code> /// &lt;summary&gt;Blah&lt;/summary&gt; namespace N { } </Code> Await TestSetDocComment(code, expected, "<doc><summary>Blah</summary></doc>") End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetDocComment3() As Task Dim code = <Code> // Goo namespace $$N { } </Code> Dim expected = <Code> // Goo /// &lt;summary&gt;Blah&lt;/summary&gt; namespace N { } </Code> Await TestSetDocComment(code, expected, "<doc><summary>Blah</summary></doc>") End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetDocComment4() As Task Dim code = <Code> /// &lt;summary&gt;FogBar&lt;/summary&gt; // Goo namespace $$N { } </Code> Dim expected = <Code> /// &lt;summary&gt;Blah&lt;/summary&gt; // Goo namespace N { } </Code> Await TestSetDocComment(code, expected, "<doc><summary>Blah</summary></doc>") End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetDocComment5() As Task Dim code = <Code> namespace N1 { namespace $$N2 { } } </Code> Dim expected = <Code> namespace N1 { /// &lt;summary&gt;Hello World&lt;/summary&gt; namespace N2 { } } </Code> Await TestSetDocComment(code, expected, "<doc><summary>Hello World</summary></doc>") End Function #End Region #Region "Set Name tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetName_SameName() As Task Dim code = <Code><![CDATA[ namespace N$$ { class C { } } ]]></Code> Dim expected = <Code><![CDATA[ namespace N { class C { } } ]]></Code> Await TestSetName(code, expected, "N", NoThrow(Of String)()) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetName_NewName() As Task Dim code = <Code><![CDATA[ namespace N$$ { class C { } } ]]></Code> Dim expected = <Code><![CDATA[ namespace N2 { class C { } } ]]></Code> Await TestSetName(code, expected, "N2", NoThrow(Of String)()) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetName_NewName_FileScopedNamespace() As Task Dim code = <Code><![CDATA[ namespace N$$; class C { } ]]></Code> Dim expected = <Code><![CDATA[ namespace N2; class C { } ]]></Code> Await TestSetName(code, expected, "N2", NoThrow(Of String)()) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetName_SimpleNameToDottedName() As Task Dim code = <Code><![CDATA[ namespace N1$$ { class C { } } ]]></Code> Dim expected = <Code><![CDATA[ namespace N2.N3 { class C { } } ]]></Code> Await TestSetName(code, expected, "N2.N3", NoThrow(Of String)()) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetName_DottedNameToSimpleName() As Task Dim code = <Code><![CDATA[ namespace N1.N2$$ { class C { } } ]]></Code> Dim expected = <Code><![CDATA[ namespace N3.N4 { class C { } } ]]></Code> Await TestSetName(code, expected, "N3.N4", NoThrow(Of String)()) End Function #End Region #Region "Remove tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestRemove1() As Task Dim code = <Code> namespace $$Goo { class C { } } </Code> Dim expected = <Code> namespace Goo { } </Code> Await TestRemoveChild(code, expected, "C") End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestRemove1_FileScopedNamespace() As Task Dim code = <Code> namespace $$Goo; class C { } </Code> Dim expected = <Code> namespace Goo; </Code> Await TestRemoveChild(code, expected, "C") End Function #End Region <WorkItem(858153, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/858153")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestChildren1() Dim code = <Code> namespace N$$ { class C1 { } class C2 { } class C3 { } } </Code> TestChildren(code, IsElement("C1", EnvDTE.vsCMElement.vsCMElementClass), IsElement("C2", EnvDTE.vsCMElement.vsCMElementClass), IsElement("C3", EnvDTE.vsCMElement.vsCMElementClass)) End Sub <WorkItem(858153, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/858153")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestChildren1_FileScopedNamespace() Dim code = <Code> namespace N$$; class C1 { } class C2 { } class C3 { } </Code> TestChildren(code, IsElement("C1", EnvDTE.vsCMElement.vsCMElementClass), IsElement("C2", EnvDTE.vsCMElement.vsCMElementClass), IsElement("C3", EnvDTE.vsCMElement.vsCMElementClass)) End Sub <WorkItem(150349, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/150349")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub NoChildrenForInvalidMembers() Dim code = <Code> namespace N$$ { void M() { } int P { get { return 42; } } event System.EventHandler E; } </Code> TestChildren(code, NoElements) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestTypeDescriptor_GetProperties() Dim code = <Code> namespace $$N { } </Code> TestPropertyDescriptors(Of EnvDTE.CodeNamespace)(code) End Sub Protected Overrides ReadOnly Property LanguageName As String Get Return LanguageNames.CSharp End Get End Property End Class End Namespace
-1
dotnet/roslyn
55,290
Fix 'quick info' and 'use explicit type' for implicit lambdas
CyrusNajmabadi
2021-07-30T18:48:59Z
2021-08-03T18:56:45Z
3a5457c3b9483c7b2be1cf6899ee3564c8ade6cf
416765ff976b2a2776c0103d3c7033f9b1667f27
Fix 'quick info' and 'use explicit type' for implicit lambdas.
./src/VisualStudio/Core/Def/Implementation/VisualStudioWorkspaceContextService.cs
// Licensed to the .NET Foundation under one or more agreements. // 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; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Experiments; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.VisualStudio.Shell; namespace Microsoft.VisualStudio.LanguageServices.Implementation { [ExportWorkspaceService(typeof(IWorkspaceContextService), ServiceLayer.Host), Shared] internal class VisualStudioWorkspaceContextService : IWorkspaceContextService { /// <summary> /// Roslyn LSP feature flag name, as defined in the PackageRegistraion.pkgdef /// by everything following '$RootKey$\FeatureFlags\' and '\' replaced by '.' /// </summary> public const string LspEditorFeatureFlagName = "Roslyn.LSP.Editor"; // UI context defined by Live Share when connected as a guest in a Live Share session // https://devdiv.visualstudio.com/DevDiv/_git/Cascade?path=%2Fsrc%2FVS%2FContracts%2FGuidList.cs&version=GBmain&line=32&lineEnd=33&lineStartColumn=1&lineEndColumn=1&lineStyle=plain&_a=contents private static readonly Guid LiveShareGuestUIContextGuid = Guid.Parse("fd93f3eb-60da-49cd-af15-acda729e357e"); private readonly Workspace _workspace; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public VisualStudioWorkspaceContextService(VisualStudioWorkspace vsWorkspace) { _workspace = vsWorkspace; } public bool IsCloudEnvironmentClient() { var context = UIContext.FromUIContextGuid(VSConstants.UICONTEXT.CloudEnvironmentConnected_guid); return context.IsActive; } public bool IsInLspEditorContext() { var featureFlagService = _workspace.Services.GetRequiredService<IExperimentationService>(); var isInLspContext = IsLiveShareGuest() || IsCloudEnvironmentClient() || featureFlagService.IsExperimentEnabled(LspEditorFeatureFlagName); return isInLspContext; } /// <summary> /// Checks if the VS instance is running as a Live Share guest session. /// </summary> private static bool IsLiveShareGuest() { var context = UIContext.FromUIContextGuid(LiveShareGuestUIContextGuid); return context.IsActive; } } }
// Licensed to the .NET Foundation under one or more agreements. // 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; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Experiments; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.VisualStudio.Shell; namespace Microsoft.VisualStudio.LanguageServices.Implementation { [ExportWorkspaceService(typeof(IWorkspaceContextService), ServiceLayer.Host), Shared] internal class VisualStudioWorkspaceContextService : IWorkspaceContextService { /// <summary> /// Roslyn LSP feature flag name, as defined in the PackageRegistraion.pkgdef /// by everything following '$RootKey$\FeatureFlags\' and '\' replaced by '.' /// </summary> public const string LspEditorFeatureFlagName = "Roslyn.LSP.Editor"; // UI context defined by Live Share when connected as a guest in a Live Share session // https://devdiv.visualstudio.com/DevDiv/_git/Cascade?path=%2Fsrc%2FVS%2FContracts%2FGuidList.cs&version=GBmain&line=32&lineEnd=33&lineStartColumn=1&lineEndColumn=1&lineStyle=plain&_a=contents private static readonly Guid LiveShareGuestUIContextGuid = Guid.Parse("fd93f3eb-60da-49cd-af15-acda729e357e"); private readonly Workspace _workspace; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public VisualStudioWorkspaceContextService(VisualStudioWorkspace vsWorkspace) { _workspace = vsWorkspace; } public bool IsCloudEnvironmentClient() { var context = UIContext.FromUIContextGuid(VSConstants.UICONTEXT.CloudEnvironmentConnected_guid); return context.IsActive; } public bool IsInLspEditorContext() { var featureFlagService = _workspace.Services.GetRequiredService<IExperimentationService>(); var isInLspContext = IsLiveShareGuest() || IsCloudEnvironmentClient() || featureFlagService.IsExperimentEnabled(LspEditorFeatureFlagName); return isInLspContext; } /// <summary> /// Checks if the VS instance is running as a Live Share guest session. /// </summary> private static bool IsLiveShareGuest() { var context = UIContext.FromUIContextGuid(LiveShareGuestUIContextGuid); return context.IsActive; } } }
-1
dotnet/roslyn
55,290
Fix 'quick info' and 'use explicit type' for implicit lambdas
CyrusNajmabadi
2021-07-30T18:48:59Z
2021-08-03T18:56:45Z
3a5457c3b9483c7b2be1cf6899ee3564c8ade6cf
416765ff976b2a2776c0103d3c7033f9b1667f27
Fix 'quick info' and 'use explicit type' for implicit lambdas.
./src/VisualStudio/Core/Def/Implementation/Progression/GraphQueryManager.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.VisualStudio.GraphModel; using Roslyn.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Progression { using Workspace = Microsoft.CodeAnalysis.Workspace; internal class GraphQueryManager { private readonly Workspace _workspace; private readonly IAsynchronousOperationListener _asyncListener; /// <summary> /// This gate locks manipulation of <see cref="_trackedQueries"/>. /// </summary> private readonly object _gate = new(); private readonly List<ValueTuple<WeakReference<IGraphContext>, List<IGraphQuery>>> _trackedQueries = new(); // We update all of our tracked queries when this delay elapses. private ResettableDelay? _delay; internal GraphQueryManager(Workspace workspace, IAsynchronousOperationListener asyncListener) { _workspace = workspace; _asyncListener = asyncListener; } internal void AddQueries(IGraphContext context, List<IGraphQuery> graphQueries) { var asyncToken = _asyncListener.BeginAsyncOperation("GraphQueryManager.AddQueries"); var solution = _workspace.CurrentSolution; var populateTask = PopulateContextGraphAsync(solution, graphQueries, context); // We want to ensure that no matter what happens, this initial context is completed var task = populateTask.SafeContinueWith( _ => context.OnCompleted(), context.CancelToken, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default); if (context.TrackChanges) { task = task.SafeContinueWith( _ => TrackChangesAfterFirstPopulate(graphQueries, context, solution), context.CancelToken, TaskContinuationOptions.None, TaskScheduler.Default); } task.CompletesAsyncOperation(asyncToken); } private void TrackChangesAfterFirstPopulate(List<IGraphQuery> graphQueries, IGraphContext context, Solution solution) { var workspace = solution.Workspace; var contextWeakReference = new WeakReference<IGraphContext>(context); lock (_gate) { if (_trackedQueries.IsEmpty()) { _workspace.WorkspaceChanged += OnWorkspaceChanged; } _trackedQueries.Add(ValueTuple.Create(contextWeakReference, graphQueries)); } EnqueueUpdateIfSolutionIsStale(solution); } private void EnqueueUpdateIfSolutionIsStale(Solution solution) { // It's possible the workspace changed during our initial population, so let's enqueue an update if it did if (_workspace.CurrentSolution != solution) { EnqueueUpdate(); } } private void OnWorkspaceChanged(object sender, WorkspaceChangeEventArgs e) => EnqueueUpdate(); private void EnqueueUpdate() { const int WorkspaceUpdateDelay = 1500; var delay = _delay; if (delay == null) { var newDelay = new ResettableDelay(WorkspaceUpdateDelay, _asyncListener); if (Interlocked.CompareExchange(ref _delay, newDelay, null) == null) { var asyncToken = _asyncListener.BeginAsyncOperation("WorkspaceGraphQueryManager.EnqueueUpdate"); newDelay.Task.SafeContinueWithFromAsync(_ => UpdateAsync(), CancellationToken.None, TaskScheduler.Default) .CompletesAsyncOperation(asyncToken); } return; } delay.Reset(); } private Task UpdateAsync() { List<ValueTuple<IGraphContext, List<IGraphQuery>>> liveQueries; lock (_gate) { liveQueries = _trackedQueries.Select(t => ValueTuple.Create(t.Item1.GetTarget(), t.Item2)).Where(t => t.Item1 != null).ToList()!; } var solution = _workspace.CurrentSolution; var tasks = liveQueries.Select(t => PopulateContextGraphAsync(solution, t.Item2, t.Item1)).ToArray(); var whenAllTask = Task.WhenAll(tasks); return whenAllTask.SafeContinueWith(t => PostUpdate(solution), TaskScheduler.Default); } private void PostUpdate(Solution solution) { _delay = null; lock (_gate) { // See if each context is still alive. It's possible it's already been GC'ed meaning we should stop caring about the query _trackedQueries.RemoveAll(t => !IsTrackingContext(t.Item1)); if (_trackedQueries.IsEmpty()) { _workspace.WorkspaceChanged -= OnWorkspaceChanged; return; } } EnqueueUpdateIfSolutionIsStale(solution); } private static bool IsTrackingContext(WeakReference<IGraphContext> weakContext) { var context = weakContext.GetTarget(); return context != null && !context.CancelToken.IsCancellationRequested; } /// <summary> /// Populate the graph of the context with the values for the given Solution. /// </summary> private static async Task PopulateContextGraphAsync(Solution solution, List<IGraphQuery> graphQueries, IGraphContext context) { try { var cancellationToken = context.CancelToken; var graphBuilderTasks = graphQueries.Select(q => q.GetGraphAsync(solution, context, cancellationToken)).ToArray(); var graphBuilders = await Task.WhenAll(graphBuilderTasks).ConfigureAwait(false); // Perform the actual graph transaction using var transaction = new GraphTransactionScope(); // Remove any links that may have been added by a previous population. We don't // remove nodes to maintain node identity, matching the behavior of the old // providers. context.Graph.Links.Clear(); foreach (var graphBuilder in graphBuilders) { graphBuilder.ApplyToGraph(context.Graph, cancellationToken); context.OutputNodes.AddAll(graphBuilder.GetCreatedNodes(cancellationToken)); } transaction.Complete(); } catch (Exception ex) when (FatalError.ReportAndPropagateUnlessCanceled(ex)) { throw ExceptionUtilities.Unreachable; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.VisualStudio.GraphModel; using Roslyn.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Progression { using Workspace = Microsoft.CodeAnalysis.Workspace; internal class GraphQueryManager { private readonly Workspace _workspace; private readonly IAsynchronousOperationListener _asyncListener; /// <summary> /// This gate locks manipulation of <see cref="_trackedQueries"/>. /// </summary> private readonly object _gate = new(); private readonly List<ValueTuple<WeakReference<IGraphContext>, List<IGraphQuery>>> _trackedQueries = new(); // We update all of our tracked queries when this delay elapses. private ResettableDelay? _delay; internal GraphQueryManager(Workspace workspace, IAsynchronousOperationListener asyncListener) { _workspace = workspace; _asyncListener = asyncListener; } internal void AddQueries(IGraphContext context, List<IGraphQuery> graphQueries) { var asyncToken = _asyncListener.BeginAsyncOperation("GraphQueryManager.AddQueries"); var solution = _workspace.CurrentSolution; var populateTask = PopulateContextGraphAsync(solution, graphQueries, context); // We want to ensure that no matter what happens, this initial context is completed var task = populateTask.SafeContinueWith( _ => context.OnCompleted(), context.CancelToken, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default); if (context.TrackChanges) { task = task.SafeContinueWith( _ => TrackChangesAfterFirstPopulate(graphQueries, context, solution), context.CancelToken, TaskContinuationOptions.None, TaskScheduler.Default); } task.CompletesAsyncOperation(asyncToken); } private void TrackChangesAfterFirstPopulate(List<IGraphQuery> graphQueries, IGraphContext context, Solution solution) { var workspace = solution.Workspace; var contextWeakReference = new WeakReference<IGraphContext>(context); lock (_gate) { if (_trackedQueries.IsEmpty()) { _workspace.WorkspaceChanged += OnWorkspaceChanged; } _trackedQueries.Add(ValueTuple.Create(contextWeakReference, graphQueries)); } EnqueueUpdateIfSolutionIsStale(solution); } private void EnqueueUpdateIfSolutionIsStale(Solution solution) { // It's possible the workspace changed during our initial population, so let's enqueue an update if it did if (_workspace.CurrentSolution != solution) { EnqueueUpdate(); } } private void OnWorkspaceChanged(object sender, WorkspaceChangeEventArgs e) => EnqueueUpdate(); private void EnqueueUpdate() { const int WorkspaceUpdateDelay = 1500; var delay = _delay; if (delay == null) { var newDelay = new ResettableDelay(WorkspaceUpdateDelay, _asyncListener); if (Interlocked.CompareExchange(ref _delay, newDelay, null) == null) { var asyncToken = _asyncListener.BeginAsyncOperation("WorkspaceGraphQueryManager.EnqueueUpdate"); newDelay.Task.SafeContinueWithFromAsync(_ => UpdateAsync(), CancellationToken.None, TaskScheduler.Default) .CompletesAsyncOperation(asyncToken); } return; } delay.Reset(); } private Task UpdateAsync() { List<ValueTuple<IGraphContext, List<IGraphQuery>>> liveQueries; lock (_gate) { liveQueries = _trackedQueries.Select(t => ValueTuple.Create(t.Item1.GetTarget(), t.Item2)).Where(t => t.Item1 != null).ToList()!; } var solution = _workspace.CurrentSolution; var tasks = liveQueries.Select(t => PopulateContextGraphAsync(solution, t.Item2, t.Item1)).ToArray(); var whenAllTask = Task.WhenAll(tasks); return whenAllTask.SafeContinueWith(t => PostUpdate(solution), TaskScheduler.Default); } private void PostUpdate(Solution solution) { _delay = null; lock (_gate) { // See if each context is still alive. It's possible it's already been GC'ed meaning we should stop caring about the query _trackedQueries.RemoveAll(t => !IsTrackingContext(t.Item1)); if (_trackedQueries.IsEmpty()) { _workspace.WorkspaceChanged -= OnWorkspaceChanged; return; } } EnqueueUpdateIfSolutionIsStale(solution); } private static bool IsTrackingContext(WeakReference<IGraphContext> weakContext) { var context = weakContext.GetTarget(); return context != null && !context.CancelToken.IsCancellationRequested; } /// <summary> /// Populate the graph of the context with the values for the given Solution. /// </summary> private static async Task PopulateContextGraphAsync(Solution solution, List<IGraphQuery> graphQueries, IGraphContext context) { try { var cancellationToken = context.CancelToken; var graphBuilderTasks = graphQueries.Select(q => q.GetGraphAsync(solution, context, cancellationToken)).ToArray(); var graphBuilders = await Task.WhenAll(graphBuilderTasks).ConfigureAwait(false); // Perform the actual graph transaction using var transaction = new GraphTransactionScope(); // Remove any links that may have been added by a previous population. We don't // remove nodes to maintain node identity, matching the behavior of the old // providers. context.Graph.Links.Clear(); foreach (var graphBuilder in graphBuilders) { graphBuilder.ApplyToGraph(context.Graph, cancellationToken); context.OutputNodes.AddAll(graphBuilder.GetCreatedNodes(cancellationToken)); } transaction.Complete(); } catch (Exception ex) when (FatalError.ReportAndPropagateUnlessCanceled(ex)) { throw ExceptionUtilities.Unreachable; } } } }
-1
dotnet/roslyn
55,290
Fix 'quick info' and 'use explicit type' for implicit lambdas
CyrusNajmabadi
2021-07-30T18:48:59Z
2021-08-03T18:56:45Z
3a5457c3b9483c7b2be1cf6899ee3564c8ade6cf
416765ff976b2a2776c0103d3c7033f9b1667f27
Fix 'quick info' and 'use explicit type' for implicit lambdas.
./src/Compilers/Test/Resources/Core/SymbolsTests/Methods/ILMethods.dll
MZ@ !L!This program cannot be run in DOS mode. $PEL!O! ~% @@ `@(%S@  H.text  `.reloc @@B`%H ********( *.rp( *( *.rp( *(*.r=p( *(*BSJB v4.0.30319l4#~4#Strings`#US4#GUIDD@#BlobG %3* P un|n   P R T V X Z  \ ^ "` Jh &t J| & J & J JJJ! . .!(<Module>System.Runtime.CompilerServicesCompilationRelaxationsAttribute.ctorRuntimeCompatibilityAttributeSystemObjectConsoleWriteLineILMethods.dllmscorlibMetadataModifiersBaseVirtualDerivedNonVirtualDerived2OverrideM00M01M02M03M04M05M06M07M08M09M10M11M12M13M14M15MILMethodsBaseVirtual#DerivedNonVirtual!Derived2OverrideymweSH" B  z\V4TWrapNonExceptionThrowsP%n% `%_CorDllMainmscoree.dll% @ 5
MZ@ !L!This program cannot be run in DOS mode. $PEL!O! ~% @@ `@(%S@  H.text  `.reloc @@B`%H ********( *.rp( *( *.rp( *(*.r=p( *(*BSJB v4.0.30319l4#~4#Strings`#US4#GUIDD@#BlobG %3* P un|n   P R T V X Z  \ ^ "` Jh &t J| & J & J JJJ! . .!(<Module>System.Runtime.CompilerServicesCompilationRelaxationsAttribute.ctorRuntimeCompatibilityAttributeSystemObjectConsoleWriteLineILMethods.dllmscorlibMetadataModifiersBaseVirtualDerivedNonVirtualDerived2OverrideM00M01M02M03M04M05M06M07M08M09M10M11M12M13M14M15MILMethodsBaseVirtual#DerivedNonVirtual!Derived2OverrideymweSH" B  z\V4TWrapNonExceptionThrowsP%n% `%_CorDllMainmscoree.dll% @ 5
-1
dotnet/roslyn
55,290
Fix 'quick info' and 'use explicit type' for implicit lambdas
CyrusNajmabadi
2021-07-30T18:48:59Z
2021-08-03T18:56:45Z
3a5457c3b9483c7b2be1cf6899ee3564c8ade6cf
416765ff976b2a2776c0103d3c7033f9b1667f27
Fix 'quick info' and 'use explicit type' for implicit lambdas.
./src/EditorFeatures/VisualBasicTest/Recommendations/Declarations/HandlesKeywordRecommenderTests.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Recommendations.Declarations Public Class HandlesKeywordRecommenderTests <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub HandlesAfterMethodInClassTest() VerifyRecommendationsContain(<File> Class Goo Sub Goo() | |</File>, "Handles") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub HandlesAfterMethodInModuleTest() VerifyRecommendationsContain(<File> Module Goo Sub Goo() | |</File>, "Handles") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub HandlesAfterFunctionTest() VerifyRecommendationsContain(<File> Module Goo Function Goo() As Integer | |</File>, "Handles") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub HandlesNotAfterMethodInStructureTest() VerifyRecommendationsMissing(<File> Structure Goo Sub Goo() | |</File>, "Handles") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub HandlesNotAfterNewLineTest() VerifyRecommendationsMissing(<File> Class Goo Sub Goo() | </File>, "Handles") End Sub <WorkItem(577941, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/577941")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NoHandlesAfterIteratorTest() VerifyRecommendationsMissing(<File> Class C Private Iterator Function TestIterator() | </File>, "Handles") End Sub End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Recommendations.Declarations Public Class HandlesKeywordRecommenderTests <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub HandlesAfterMethodInClassTest() VerifyRecommendationsContain(<File> Class Goo Sub Goo() | |</File>, "Handles") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub HandlesAfterMethodInModuleTest() VerifyRecommendationsContain(<File> Module Goo Sub Goo() | |</File>, "Handles") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub HandlesAfterFunctionTest() VerifyRecommendationsContain(<File> Module Goo Function Goo() As Integer | |</File>, "Handles") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub HandlesNotAfterMethodInStructureTest() VerifyRecommendationsMissing(<File> Structure Goo Sub Goo() | |</File>, "Handles") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub HandlesNotAfterNewLineTest() VerifyRecommendationsMissing(<File> Class Goo Sub Goo() | </File>, "Handles") End Sub <WorkItem(577941, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/577941")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NoHandlesAfterIteratorTest() VerifyRecommendationsMissing(<File> Class C Private Iterator Function TestIterator() | </File>, "Handles") End Sub End Class End Namespace
-1
dotnet/roslyn
55,290
Fix 'quick info' and 'use explicit type' for implicit lambdas
CyrusNajmabadi
2021-07-30T18:48:59Z
2021-08-03T18:56:45Z
3a5457c3b9483c7b2be1cf6899ee3564c8ade6cf
416765ff976b2a2776c0103d3c7033f9b1667f27
Fix 'quick info' and 'use explicit type' for implicit lambdas.
./src/Scripting/CoreTestUtilities/ObjectFormatterFixtures/MockDesktopTask.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Diagnostics; using System.Threading.Tasks; namespace ObjectFormatterFixtures { /// <summary> /// Follows the shape of the Desktop version of <see cref="Task"/> relevant for debugger display. /// </summary> [DebuggerTypeProxy(typeof(MockTaskProxy))] [DebuggerDisplay("Id = {Id}, Status = {Status}, Method = {DebuggerDisplayMethodDescription}")] internal class MockDesktopTask { private readonly Action m_action; public MockDesktopTask(Action action) { m_action = action; } public int Id => 1234; public object AsyncState => null; public TaskCreationOptions CreationOptions => TaskCreationOptions.None; public Exception Exception => null; public TaskStatus Status => TaskStatus.Created; private string DebuggerDisplayMethodDescription => m_action.Method.ToString(); } internal class MockTaskProxy { private readonly MockDesktopTask m_task; public object AsyncState => m_task.AsyncState; public TaskCreationOptions CreationOptions => m_task.CreationOptions; public Exception Exception => m_task.Exception; public int Id => m_task.Id; public bool CancellationPending => false; public TaskStatus Status => m_task.Status; public MockTaskProxy(MockDesktopTask task) { m_task = task; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Diagnostics; using System.Threading.Tasks; namespace ObjectFormatterFixtures { /// <summary> /// Follows the shape of the Desktop version of <see cref="Task"/> relevant for debugger display. /// </summary> [DebuggerTypeProxy(typeof(MockTaskProxy))] [DebuggerDisplay("Id = {Id}, Status = {Status}, Method = {DebuggerDisplayMethodDescription}")] internal class MockDesktopTask { private readonly Action m_action; public MockDesktopTask(Action action) { m_action = action; } public int Id => 1234; public object AsyncState => null; public TaskCreationOptions CreationOptions => TaskCreationOptions.None; public Exception Exception => null; public TaskStatus Status => TaskStatus.Created; private string DebuggerDisplayMethodDescription => m_action.Method.ToString(); } internal class MockTaskProxy { private readonly MockDesktopTask m_task; public object AsyncState => m_task.AsyncState; public TaskCreationOptions CreationOptions => m_task.CreationOptions; public Exception Exception => m_task.Exception; public int Id => m_task.Id; public bool CancellationPending => false; public TaskStatus Status => m_task.Status; public MockTaskProxy(MockDesktopTask task) { m_task = task; } } }
-1
dotnet/roslyn
55,290
Fix 'quick info' and 'use explicit type' for implicit lambdas
CyrusNajmabadi
2021-07-30T18:48:59Z
2021-08-03T18:56:45Z
3a5457c3b9483c7b2be1cf6899ee3564c8ade6cf
416765ff976b2a2776c0103d3c7033f9b1667f27
Fix 'quick info' and 'use explicit type' for implicit lambdas.
./src/Analyzers/Core/Analyzers/RemoveRedundantEquality/RedundantEqualityConstants.cs
// Licensed to the .NET Foundation under one or more 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.RemoveRedundantEquality { internal static class RedundantEqualityConstants { public const string RedundantSide = nameof(RedundantSide); public const string Left = nameof(Left); public const string Right = nameof(Right); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace Microsoft.CodeAnalysis.RemoveRedundantEquality { internal static class RedundantEqualityConstants { public const string RedundantSide = nameof(RedundantSide); public const string Left = nameof(Left); public const string Right = nameof(Right); } }
-1
dotnet/roslyn
55,290
Fix 'quick info' and 'use explicit type' for implicit lambdas
CyrusNajmabadi
2021-07-30T18:48:59Z
2021-08-03T18:56:45Z
3a5457c3b9483c7b2be1cf6899ee3564c8ade6cf
416765ff976b2a2776c0103d3c7033f9b1667f27
Fix 'quick info' and 'use explicit type' for implicit lambdas.
./src/EditorFeatures/VisualBasicTest/Completion/CompletionProviders/SuggestionModeCompletionProviderTests.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.Completion Imports Microsoft.CodeAnalysis.Editor.UnitTests.Extensions Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis.Options Imports Microsoft.CodeAnalysis.VisualBasic.Completion.Providers Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Completion.CompletionProviders Public Class SuggestionModeCompletionProviderTests Inherits AbstractVisualBasicCompletionProviderTests <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestFieldDeclaration1() As Task Dim markup = <a>Class C $$ End Class</a> Await VerifyNotBuilderAsync(markup) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestFieldDeclaration2() As Task Dim markup = <a>Class C Public $$ End Class</a> Await VerifyBuilderAsync(markup) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestFieldDeclaration3() As Task Dim markup = <a>Module M Public $$ End Module</a> Await VerifyBuilderAsync(markup) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestFieldDeclaration4() As Task Dim markup = <a>Structure S Public $$ End Structure</a> Await VerifyBuilderAsync(markup) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestFieldDeclaration5() As Task Dim markup = <a>Class C WithEvents $$ End Class</a> Await VerifyBuilderAsync(markup) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestFieldDeclaration6() As Task Dim markup = <a>Class C Protected Friend $$ End Class</a> Await VerifyBuilderAsync(markup) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestParameterDeclaration1() As Task Dim markup = <a>Class C Public Sub Bar($$ End Sub End Class</a> Await VerifyBuilderAsync(markup) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestParameterDeclaration2() As Task Dim markup = <a>Class C Public Sub Bar(Optional goo as Integer, $$ End Sub End Class</a> Await VerifyNotBuilderAsync(markup) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestParameterDeclaration3() As Task Dim markup = <a>Class C Public Sub Bar(Optional $$ End Sub End Class</a> Await VerifyBuilderAsync(markup) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestParameterDeclaration4() As Task Dim markup = <a>Class C Public Sub Bar(Optional x $$ End Sub End Class</a> Await VerifyNotBuilderAsync(markup) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestParameterDeclaration5() As Task Dim markup = <a>Class C Public Sub Bar(Optional x As $$ End Sub End Class</a> Await VerifyNotBuilderAsync(markup) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestParameterDeclaration6() As Task Dim markup = <a>Class C Public Sub Bar(Optional x As Integer $$ End Sub End Class</a> Await VerifyNotBuilderAsync(markup) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestParameterDeclaration7() As Task Dim markup = <a>Class C Public Sub Bar(ByVal $$ End Sub End Class</a> Await VerifyBuilderAsync(markup) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestParameterDeclaration8() As Task Dim markup = <a>Class C Public Sub Bar(ByVal x $$ End Sub End Class</a> Await VerifyNotBuilderAsync(markup) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestParameterDeclaration9() As Task Dim markup = <a>Class C Sub Goo $$ End Class</a> Await VerifyNotBuilderAsync(markup) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestParameterDeclaration10() As Task Dim markup = <a>Class C Public Property SomeProp $$ End Class</a> Await VerifyNotBuilderAsync(markup) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestSelectClause1() As Task Dim markup = <a>Class z Sub bar() Dim a = New Integer(1, 2, 3) {} Dim goo = From z In a Select $$ End Sub End Class</a> Await VerifyBuilderAsync(markup) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestSelectClause2() As Task Dim markup = <a>Class z Sub bar() Dim a = New Integer(1, 2, 3) {} Dim goo = From z In a Select 1, $$ End Sub End Class</a> Await VerifyBuilderAsync(markup) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestForStatement1() As Task Dim markup = <a>Class z Sub bar() For $$ End Sub End Class</a> Await VerifyBuilderAsync(markup) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestForStatement2() As Task Dim markup = <a>Class z Sub bar() For $$ = 1 To 10 Next End Sub End Class</a> Await VerifyBuilderAsync(markup) End Function <WorkItem(545351, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545351")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestBuilderWhenOptionExplicitOff() As Task Dim markup = <a>Option Explicit Off Class C1 Sub M() Console.WriteLine($$ End Sub End Class </a> Await VerifyBuilderAsync(markup) End Function <WorkItem(546659, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546659")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestUsingStatement() As Task Dim markup = <a> Class C1 Sub M() Using $$ End Sub End Class </a> Await VerifyBuilderAsync(markup) End Function <WorkItem(734596, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/734596")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestOptionExplicitOffStatementLevel1() As Task Dim markup = <a> Option Explicit Off Class C1 Sub M() $$ End Sub End Class </a> Await VerifyBuilderAsync(markup) End Function <WorkItem(734596, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/734596")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestOptionExplicitOffStatementLevel2() As Task Dim markup = <a> Option Explicit Off Class C1 Sub M() a = $$ End Sub End Class </a> Await VerifyBuilderAsync(markup) End Function <WorkItem(960416, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/960416")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestReadonlyField() As Task Dim markup = <a> Class C1 Readonly $$ Sub M() End Sub End Class </a> Await VerifyBuilderAsync(markup) End Function <WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function NamespaceDeclarationName_Unqualified() As Task Dim markup = <a> Namespace $$ End Namespace </a> Await VerifyBuilderAsync(markup, CompletionTrigger.Invoke) End Function <WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function NamespaceDeclarationName_Qualified() As Task Dim markup = <a> Namespace A.$$ End Namespace </a> Await VerifyBuilderAsync(markup, CompletionTrigger.Invoke) End Function <WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function PartialClassName() As Task Dim markup = <a>Partial Class $$</a> Await VerifyBuilderAsync(markup, CompletionTrigger.Invoke) End Function <WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function PartialStructureName() As Task Dim markup = <a>Partial Structure $$</a> Await VerifyBuilderAsync(markup, CompletionTrigger.Invoke) End Function <WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function PartialInterfaceName() As Task Dim markup = <a>Partial Interface $$</a> Await VerifyBuilderAsync(markup, CompletionTrigger.Invoke) End Function <WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function PartialModuleName() As Task Dim markup = <a>Partial Module $$</a> Await VerifyBuilderAsync(markup, CompletionTrigger.Invoke) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TupleType() As Task Dim markup = <a> Class C Sub M() Dim t As (a$$, b) End Sub End Class</a> Await VerifyNotBuilderAsync(markup) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TupleTypeAfterComma() As Task Dim markup = <a> Class C Sub M() Dim t As (a, b$$) End Sub End Class</a> Await VerifyNotBuilderAsync(markup) End Function Private Function VerifyNotBuilderAsync(markup As XElement, Optional triggerInfo As CompletionTrigger? = Nothing, Optional useDebuggerOptions As Boolean = False) As Task Return VerifySuggestionModeWorkerAsync(markup, isBuilder:=False, triggerInfo:=triggerInfo, useDebuggerOptions:=useDebuggerOptions) End Function Private Function VerifyBuilderAsync(markup As XElement, Optional triggerInfo As CompletionTrigger? = Nothing, Optional useDebuggerOptions As Boolean = False) As Task Return VerifySuggestionModeWorkerAsync(markup, isBuilder:=True, triggerInfo:=triggerInfo, useDebuggerOptions:=useDebuggerOptions) End Function Private Async Function VerifySuggestionModeWorkerAsync(markup As XElement, isBuilder As Boolean, triggerInfo As CompletionTrigger?, Optional useDebuggerOptions As Boolean = False) As Task Dim code As String = Nothing Dim position As Integer = 0 MarkupTestFile.GetPosition(markup.NormalizedValue, code, position) Using workspaceFixture = New VisualBasicTestWorkspaceFixture() Dim options = workspaceFixture.GetWorkspace(ExportProvider).Options If useDebuggerOptions Then options = options. WithChangedOption(CompletionControllerOptions.FilterOutOfScopeLocals, False). WithChangedOption(CompletionControllerOptions.ShowXmlDocCommentCompletion, False) End If Dim document1 = workspaceFixture.UpdateDocument(code, SourceCodeKind.Regular) Await CheckResultsAsync(document1, position, isBuilder, triggerInfo, options) If Await CanUseSpeculativeSemanticModelAsync(document1, position) Then Dim document2 = workspaceFixture.UpdateDocument(code, SourceCodeKind.Regular, cleanBeforeUpdate:=False) Await CheckResultsAsync(document2, position, isBuilder, triggerInfo, options) End If End Using End Function Private Overloads Async Function CheckResultsAsync(document As Document, position As Integer, isBuilder As Boolean, triggerInfo As CompletionTrigger?, options As OptionSet) As Task triggerInfo = If(triggerInfo, CompletionTrigger.CreateInsertionTrigger("a"c)) Dim service = GetCompletionService(document.Project) Dim provider = Assert.Single(service.GetTestAccessor().GetAllProviders(ImmutableHashSet(Of String).Empty)) Dim context = Await service.GetTestAccessor().GetContextAsync( provider, document, position, triggerInfo.Value, options, CancellationToken.None) If isBuilder Then Assert.NotNull(context) Assert.NotNull(context.SuggestionModeItem) Else If context IsNot Nothing Then Assert.True(context.SuggestionModeItem Is Nothing, "group.Builder = " & If(context.SuggestionModeItem IsNot Nothing, context.SuggestionModeItem.DisplayText, "null")) End If End If End Function Friend Overrides Function GetCompletionProviderType() As Type Return GetType(VisualBasicSuggestionModeCompletionProvider) End Function End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.Threading Imports Microsoft.CodeAnalysis.Completion Imports Microsoft.CodeAnalysis.Editor.UnitTests.Extensions Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis.Options Imports Microsoft.CodeAnalysis.VisualBasic.Completion.Providers Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Completion.CompletionProviders Public Class SuggestionModeCompletionProviderTests Inherits AbstractVisualBasicCompletionProviderTests <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestFieldDeclaration1() As Task Dim markup = <a>Class C $$ End Class</a> Await VerifyNotBuilderAsync(markup) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestFieldDeclaration2() As Task Dim markup = <a>Class C Public $$ End Class</a> Await VerifyBuilderAsync(markup) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestFieldDeclaration3() As Task Dim markup = <a>Module M Public $$ End Module</a> Await VerifyBuilderAsync(markup) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestFieldDeclaration4() As Task Dim markup = <a>Structure S Public $$ End Structure</a> Await VerifyBuilderAsync(markup) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestFieldDeclaration5() As Task Dim markup = <a>Class C WithEvents $$ End Class</a> Await VerifyBuilderAsync(markup) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestFieldDeclaration6() As Task Dim markup = <a>Class C Protected Friend $$ End Class</a> Await VerifyBuilderAsync(markup) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestParameterDeclaration1() As Task Dim markup = <a>Class C Public Sub Bar($$ End Sub End Class</a> Await VerifyBuilderAsync(markup) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestParameterDeclaration2() As Task Dim markup = <a>Class C Public Sub Bar(Optional goo as Integer, $$ End Sub End Class</a> Await VerifyNotBuilderAsync(markup) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestParameterDeclaration3() As Task Dim markup = <a>Class C Public Sub Bar(Optional $$ End Sub End Class</a> Await VerifyBuilderAsync(markup) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestParameterDeclaration4() As Task Dim markup = <a>Class C Public Sub Bar(Optional x $$ End Sub End Class</a> Await VerifyNotBuilderAsync(markup) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestParameterDeclaration5() As Task Dim markup = <a>Class C Public Sub Bar(Optional x As $$ End Sub End Class</a> Await VerifyNotBuilderAsync(markup) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestParameterDeclaration6() As Task Dim markup = <a>Class C Public Sub Bar(Optional x As Integer $$ End Sub End Class</a> Await VerifyNotBuilderAsync(markup) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestParameterDeclaration7() As Task Dim markup = <a>Class C Public Sub Bar(ByVal $$ End Sub End Class</a> Await VerifyBuilderAsync(markup) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestParameterDeclaration8() As Task Dim markup = <a>Class C Public Sub Bar(ByVal x $$ End Sub End Class</a> Await VerifyNotBuilderAsync(markup) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestParameterDeclaration9() As Task Dim markup = <a>Class C Sub Goo $$ End Class</a> Await VerifyNotBuilderAsync(markup) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestParameterDeclaration10() As Task Dim markup = <a>Class C Public Property SomeProp $$ End Class</a> Await VerifyNotBuilderAsync(markup) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestSelectClause1() As Task Dim markup = <a>Class z Sub bar() Dim a = New Integer(1, 2, 3) {} Dim goo = From z In a Select $$ End Sub End Class</a> Await VerifyBuilderAsync(markup) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestSelectClause2() As Task Dim markup = <a>Class z Sub bar() Dim a = New Integer(1, 2, 3) {} Dim goo = From z In a Select 1, $$ End Sub End Class</a> Await VerifyBuilderAsync(markup) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestForStatement1() As Task Dim markup = <a>Class z Sub bar() For $$ End Sub End Class</a> Await VerifyBuilderAsync(markup) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestForStatement2() As Task Dim markup = <a>Class z Sub bar() For $$ = 1 To 10 Next End Sub End Class</a> Await VerifyBuilderAsync(markup) End Function <WorkItem(545351, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545351")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestBuilderWhenOptionExplicitOff() As Task Dim markup = <a>Option Explicit Off Class C1 Sub M() Console.WriteLine($$ End Sub End Class </a> Await VerifyBuilderAsync(markup) End Function <WorkItem(546659, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546659")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestUsingStatement() As Task Dim markup = <a> Class C1 Sub M() Using $$ End Sub End Class </a> Await VerifyBuilderAsync(markup) End Function <WorkItem(734596, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/734596")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestOptionExplicitOffStatementLevel1() As Task Dim markup = <a> Option Explicit Off Class C1 Sub M() $$ End Sub End Class </a> Await VerifyBuilderAsync(markup) End Function <WorkItem(734596, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/734596")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestOptionExplicitOffStatementLevel2() As Task Dim markup = <a> Option Explicit Off Class C1 Sub M() a = $$ End Sub End Class </a> Await VerifyBuilderAsync(markup) End Function <WorkItem(960416, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/960416")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestReadonlyField() As Task Dim markup = <a> Class C1 Readonly $$ Sub M() End Sub End Class </a> Await VerifyBuilderAsync(markup) End Function <WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function NamespaceDeclarationName_Unqualified() As Task Dim markup = <a> Namespace $$ End Namespace </a> Await VerifyBuilderAsync(markup, CompletionTrigger.Invoke) End Function <WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function NamespaceDeclarationName_Qualified() As Task Dim markup = <a> Namespace A.$$ End Namespace </a> Await VerifyBuilderAsync(markup, CompletionTrigger.Invoke) End Function <WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function PartialClassName() As Task Dim markup = <a>Partial Class $$</a> Await VerifyBuilderAsync(markup, CompletionTrigger.Invoke) End Function <WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function PartialStructureName() As Task Dim markup = <a>Partial Structure $$</a> Await VerifyBuilderAsync(markup, CompletionTrigger.Invoke) End Function <WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function PartialInterfaceName() As Task Dim markup = <a>Partial Interface $$</a> Await VerifyBuilderAsync(markup, CompletionTrigger.Invoke) End Function <WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function PartialModuleName() As Task Dim markup = <a>Partial Module $$</a> Await VerifyBuilderAsync(markup, CompletionTrigger.Invoke) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TupleType() As Task Dim markup = <a> Class C Sub M() Dim t As (a$$, b) End Sub End Class</a> Await VerifyNotBuilderAsync(markup) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TupleTypeAfterComma() As Task Dim markup = <a> Class C Sub M() Dim t As (a, b$$) End Sub End Class</a> Await VerifyNotBuilderAsync(markup) End Function Private Function VerifyNotBuilderAsync(markup As XElement, Optional triggerInfo As CompletionTrigger? = Nothing, Optional useDebuggerOptions As Boolean = False) As Task Return VerifySuggestionModeWorkerAsync(markup, isBuilder:=False, triggerInfo:=triggerInfo, useDebuggerOptions:=useDebuggerOptions) End Function Private Function VerifyBuilderAsync(markup As XElement, Optional triggerInfo As CompletionTrigger? = Nothing, Optional useDebuggerOptions As Boolean = False) As Task Return VerifySuggestionModeWorkerAsync(markup, isBuilder:=True, triggerInfo:=triggerInfo, useDebuggerOptions:=useDebuggerOptions) End Function Private Async Function VerifySuggestionModeWorkerAsync(markup As XElement, isBuilder As Boolean, triggerInfo As CompletionTrigger?, Optional useDebuggerOptions As Boolean = False) As Task Dim code As String = Nothing Dim position As Integer = 0 MarkupTestFile.GetPosition(markup.NormalizedValue, code, position) Using workspaceFixture = New VisualBasicTestWorkspaceFixture() Dim options = workspaceFixture.GetWorkspace(ExportProvider).Options If useDebuggerOptions Then options = options. WithChangedOption(CompletionControllerOptions.FilterOutOfScopeLocals, False). WithChangedOption(CompletionControllerOptions.ShowXmlDocCommentCompletion, False) End If Dim document1 = workspaceFixture.UpdateDocument(code, SourceCodeKind.Regular) Await CheckResultsAsync(document1, position, isBuilder, triggerInfo, options) If Await CanUseSpeculativeSemanticModelAsync(document1, position) Then Dim document2 = workspaceFixture.UpdateDocument(code, SourceCodeKind.Regular, cleanBeforeUpdate:=False) Await CheckResultsAsync(document2, position, isBuilder, triggerInfo, options) End If End Using End Function Private Overloads Async Function CheckResultsAsync(document As Document, position As Integer, isBuilder As Boolean, triggerInfo As CompletionTrigger?, options As OptionSet) As Task triggerInfo = If(triggerInfo, CompletionTrigger.CreateInsertionTrigger("a"c)) Dim service = GetCompletionService(document.Project) Dim provider = Assert.Single(service.GetTestAccessor().GetAllProviders(ImmutableHashSet(Of String).Empty)) Dim context = Await service.GetTestAccessor().GetContextAsync( provider, document, position, triggerInfo.Value, options, CancellationToken.None) If isBuilder Then Assert.NotNull(context) Assert.NotNull(context.SuggestionModeItem) Else If context IsNot Nothing Then Assert.True(context.SuggestionModeItem Is Nothing, "group.Builder = " & If(context.SuggestionModeItem IsNot Nothing, context.SuggestionModeItem.DisplayText, "null")) End If End If End Function Friend Overrides Function GetCompletionProviderType() As Type Return GetType(VisualBasicSuggestionModeCompletionProvider) End Function End Class End Namespace
-1
dotnet/roslyn
55,290
Fix 'quick info' and 'use explicit type' for implicit lambdas
CyrusNajmabadi
2021-07-30T18:48:59Z
2021-08-03T18:56:45Z
3a5457c3b9483c7b2be1cf6899ee3564c8ade6cf
416765ff976b2a2776c0103d3c7033f9b1667f27
Fix 'quick info' and 'use explicit type' for implicit lambdas.
./src/Scripting/Core/Hosting/AssemblyLoader/CoreAssemblyLoaderImpl.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Diagnostics; using System.IO; using System.Reflection; using System.Runtime.Loader; namespace Microsoft.CodeAnalysis.Scripting.Hosting { internal sealed class CoreAssemblyLoaderImpl : AssemblyLoaderImpl { private readonly LoadContext _inMemoryAssemblyContext; internal CoreAssemblyLoaderImpl(InteractiveAssemblyLoader loader) : base(loader) { _inMemoryAssemblyContext = new LoadContext(Loader, null); } public override Assembly LoadFromStream(Stream peStream, Stream pdbStream) { return _inMemoryAssemblyContext.LoadFromStream(peStream, pdbStream); } public override AssemblyAndLocation LoadFromPath(string path) { // Create a new context that knows the directory where the assembly was loaded from // and uses it to resolve dependencies of the assembly. We could create one context per directory, // but there is no need to reuse contexts. var assembly = new LoadContext(Loader, Path.GetDirectoryName(path)).LoadFromAssemblyPath(path); return new AssemblyAndLocation(assembly, path, fromGac: false); } public override void Dispose() { // nop } private sealed class LoadContext : AssemblyLoadContext { private readonly string _loadDirectoryOpt; private readonly InteractiveAssemblyLoader _loader; internal LoadContext(InteractiveAssemblyLoader loader, string loadDirectoryOpt) { Debug.Assert(loader != null); _loader = loader; _loadDirectoryOpt = loadDirectoryOpt; // CoreCLR resolves assemblies in steps: // // 1) Call AssemblyLoadContext.Load -- our context returns null // 2) TPA list // 3) Default.Resolving event // 4) AssemblyLoadContext.Resolving event -- hooked below // // What we want is to let the default context load assemblies it knows about (this includes already loaded assemblies, // assemblies in AppPath, platform assemblies, assemblies explciitly resolved by the App by hooking Default.Resolving, etc.). // Only if the assembly can't be resolved that way, the interactive resolver steps in. // // This order is necessary to avoid loading assemblies twice (by the host App and by interactive loader). Resolving += (_, assemblyName) => _loader.ResolveAssembly(AssemblyIdentity.FromAssemblyReference(assemblyName), _loadDirectoryOpt); } protected override Assembly Load(AssemblyName assemblyName) => null; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Diagnostics; using System.IO; using System.Reflection; using System.Runtime.Loader; namespace Microsoft.CodeAnalysis.Scripting.Hosting { internal sealed class CoreAssemblyLoaderImpl : AssemblyLoaderImpl { private readonly LoadContext _inMemoryAssemblyContext; internal CoreAssemblyLoaderImpl(InteractiveAssemblyLoader loader) : base(loader) { _inMemoryAssemblyContext = new LoadContext(Loader, null); } public override Assembly LoadFromStream(Stream peStream, Stream pdbStream) { return _inMemoryAssemblyContext.LoadFromStream(peStream, pdbStream); } public override AssemblyAndLocation LoadFromPath(string path) { // Create a new context that knows the directory where the assembly was loaded from // and uses it to resolve dependencies of the assembly. We could create one context per directory, // but there is no need to reuse contexts. var assembly = new LoadContext(Loader, Path.GetDirectoryName(path)).LoadFromAssemblyPath(path); return new AssemblyAndLocation(assembly, path, fromGac: false); } public override void Dispose() { // nop } private sealed class LoadContext : AssemblyLoadContext { private readonly string _loadDirectoryOpt; private readonly InteractiveAssemblyLoader _loader; internal LoadContext(InteractiveAssemblyLoader loader, string loadDirectoryOpt) { Debug.Assert(loader != null); _loader = loader; _loadDirectoryOpt = loadDirectoryOpt; // CoreCLR resolves assemblies in steps: // // 1) Call AssemblyLoadContext.Load -- our context returns null // 2) TPA list // 3) Default.Resolving event // 4) AssemblyLoadContext.Resolving event -- hooked below // // What we want is to let the default context load assemblies it knows about (this includes already loaded assemblies, // assemblies in AppPath, platform assemblies, assemblies explciitly resolved by the App by hooking Default.Resolving, etc.). // Only if the assembly can't be resolved that way, the interactive resolver steps in. // // This order is necessary to avoid loading assemblies twice (by the host App and by interactive loader). Resolving += (_, assemblyName) => _loader.ResolveAssembly(AssemblyIdentity.FromAssemblyReference(assemblyName), _loadDirectoryOpt); } protected override Assembly Load(AssemblyName assemblyName) => null; } } }
-1
dotnet/roslyn
55,290
Fix 'quick info' and 'use explicit type' for implicit lambdas
CyrusNajmabadi
2021-07-30T18:48:59Z
2021-08-03T18:56:45Z
3a5457c3b9483c7b2be1cf6899ee3564c8ade6cf
416765ff976b2a2776c0103d3c7033f9b1667f27
Fix 'quick info' and 'use explicit type' for implicit lambdas.
./src/Compilers/Core/Portable/Syntax/ISkippedTokensTriviaSyntax.cs
// Licensed to the .NET Foundation under one or more 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 { #pragma warning disable CA1200 // Avoid using cref tags with a prefix /// <summary> /// Represents structured trivia that contains skipped tokens. This is implemented by /// <see cref="T:Microsoft.CodeAnalysis.CSharp.Syntax.SkippedTokensTriviaSyntax"/> and /// <see cref="T:Microsoft.CodeAnalysis.VisualBasic.Syntax.SkippedTokensTriviaSyntax"/>. /// </summary> #pragma warning restore CA1200 // Avoid using cref tags with a prefix public interface ISkippedTokensTriviaSyntax { SyntaxTokenList Tokens { 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 { #pragma warning disable CA1200 // Avoid using cref tags with a prefix /// <summary> /// Represents structured trivia that contains skipped tokens. This is implemented by /// <see cref="T:Microsoft.CodeAnalysis.CSharp.Syntax.SkippedTokensTriviaSyntax"/> and /// <see cref="T:Microsoft.CodeAnalysis.VisualBasic.Syntax.SkippedTokensTriviaSyntax"/>. /// </summary> #pragma warning restore CA1200 // Avoid using cref tags with a prefix public interface ISkippedTokensTriviaSyntax { SyntaxTokenList Tokens { get; } } }
-1
dotnet/roslyn
55,290
Fix 'quick info' and 'use explicit type' for implicit lambdas
CyrusNajmabadi
2021-07-30T18:48:59Z
2021-08-03T18:56:45Z
3a5457c3b9483c7b2be1cf6899ee3564c8ade6cf
416765ff976b2a2776c0103d3c7033f9b1667f27
Fix 'quick info' and 'use explicit type' for implicit lambdas.
./src/Features/CSharp/Portable/Completion/CSharpCompletionService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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 System.Threading; using Microsoft.CodeAnalysis.Completion; using Microsoft.CodeAnalysis.CSharp.Completion.Providers; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CSharp.Completion { [ExportLanguageServiceFactory(typeof(CompletionService), LanguageNames.CSharp), Shared] internal class CSharpCompletionServiceFactory : ILanguageServiceFactory { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CSharpCompletionServiceFactory() { } [Obsolete(MefConstruction.FactoryMethodMessage, error: true)] public ILanguageService CreateLanguageService(HostLanguageServices languageServices) => new CSharpCompletionService(languageServices.WorkspaceServices.Workspace); } internal class CSharpCompletionService : CommonCompletionService { private readonly Workspace _workspace; [Obsolete(MefConstruction.FactoryMethodMessage, error: true)] public CSharpCompletionService(Workspace workspace) : base(workspace) { _workspace = workspace; } public override string Language => LanguageNames.CSharp; public override TextSpan GetDefaultCompletionListSpan(SourceText text, int caretPosition) => CompletionUtilities.GetCompletionItemSpan(text, caretPosition); private CompletionRules _latestRules = CompletionRules.Default; public override CompletionRules GetRules() { var options = _workspace.Options; var enterRule = options.GetOption(CompletionOptions.EnterKeyBehavior, LanguageNames.CSharp); var snippetRule = options.GetOption(CompletionOptions.SnippetsBehavior, LanguageNames.CSharp); // Although EnterKeyBehavior is a per-language setting, the meaning of an unset setting (Default) differs between C# and VB // In C# the default means Never to maintain previous behavior if (enterRule == EnterKeyRule.Default) { enterRule = EnterKeyRule.Never; } if (snippetRule == SnippetsRule.Default) { snippetRule = SnippetsRule.AlwaysInclude; } // use interlocked + stored rules to reduce # of times this gets created when option is different than default var newRules = _latestRules.WithDefaultEnterKeyRule(enterRule) .WithSnippetsRule(snippetRule); Interlocked.Exchange(ref _latestRules, newRules); return newRules; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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 System.Threading; using Microsoft.CodeAnalysis.Completion; using Microsoft.CodeAnalysis.CSharp.Completion.Providers; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CSharp.Completion { [ExportLanguageServiceFactory(typeof(CompletionService), LanguageNames.CSharp), Shared] internal class CSharpCompletionServiceFactory : ILanguageServiceFactory { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CSharpCompletionServiceFactory() { } [Obsolete(MefConstruction.FactoryMethodMessage, error: true)] public ILanguageService CreateLanguageService(HostLanguageServices languageServices) => new CSharpCompletionService(languageServices.WorkspaceServices.Workspace); } internal class CSharpCompletionService : CommonCompletionService { private readonly Workspace _workspace; [Obsolete(MefConstruction.FactoryMethodMessage, error: true)] public CSharpCompletionService(Workspace workspace) : base(workspace) { _workspace = workspace; } public override string Language => LanguageNames.CSharp; public override TextSpan GetDefaultCompletionListSpan(SourceText text, int caretPosition) => CompletionUtilities.GetCompletionItemSpan(text, caretPosition); private CompletionRules _latestRules = CompletionRules.Default; public override CompletionRules GetRules() { var options = _workspace.Options; var enterRule = options.GetOption(CompletionOptions.EnterKeyBehavior, LanguageNames.CSharp); var snippetRule = options.GetOption(CompletionOptions.SnippetsBehavior, LanguageNames.CSharp); // Although EnterKeyBehavior is a per-language setting, the meaning of an unset setting (Default) differs between C# and VB // In C# the default means Never to maintain previous behavior if (enterRule == EnterKeyRule.Default) { enterRule = EnterKeyRule.Never; } if (snippetRule == SnippetsRule.Default) { snippetRule = SnippetsRule.AlwaysInclude; } // use interlocked + stored rules to reduce # of times this gets created when option is different than default var newRules = _latestRules.WithDefaultEnterKeyRule(enterRule) .WithSnippetsRule(snippetRule); Interlocked.Exchange(ref _latestRules, newRules); return newRules; } } }
-1
dotnet/roslyn
55,290
Fix 'quick info' and 'use explicit type' for implicit lambdas
CyrusNajmabadi
2021-07-30T18:48:59Z
2021-08-03T18:56:45Z
3a5457c3b9483c7b2be1cf6899ee3564c8ade6cf
416765ff976b2a2776c0103d3c7033f9b1667f27
Fix 'quick info' and 'use explicit type' for implicit lambdas.
./src/Compilers/VisualBasic/Portable/Emit/SpecializedGenericMethodInstanceReference.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.Emit Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Namespace Microsoft.CodeAnalysis.VisualBasic.Emit ''' <summary> ''' Represents a generic method of a generic type instantiation, closed over type parameters. ''' e.g. ''' A{T}.M{S}() ''' A.B{T}.C.M{S}() ''' </summary> Friend NotInheritable Class SpecializedGenericMethodInstanceReference Inherits SpecializedMethodReference Implements Cci.IGenericMethodInstanceReference Private ReadOnly _genericMethod As SpecializedMethodReference Public Sub New(underlyingMethod As MethodSymbol) MyBase.New(underlyingMethod) Debug.Assert(underlyingMethod.ContainingType.IsOrInGenericType() AndAlso underlyingMethod.ContainingType.IsDefinition) _genericMethod = New SpecializedMethodReference(underlyingMethod) End Sub Public Function GetGenericMethod(context As EmitContext) As Cci.IMethodReference Implements Cci.IGenericMethodInstanceReference.GetGenericMethod Return _genericMethod End Function Public Function GetGenericArguments(context As EmitContext) As IEnumerable(Of Cci.ITypeReference) Implements Cci.IGenericMethodInstanceReference.GetGenericArguments Dim moduleBeingBuilt As PEModuleBuilder = DirectCast(context.Module, PEModuleBuilder) Return From arg In m_UnderlyingMethod.TypeArguments Select moduleBeingBuilt.Translate(arg, syntaxNodeOpt:=DirectCast(context.SyntaxNode, VisualBasicSyntaxNode), diagnostics:=context.Diagnostics) End Function Public Overrides ReadOnly Property AsGenericMethodInstanceReference As Cci.IGenericMethodInstanceReference Get Return Me End Get End Property Public Overrides Sub Dispatch(visitor As Cci.MetadataVisitor) visitor.Visit(DirectCast(Me, Cci.IGenericMethodInstanceReference)) 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.Emit Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Namespace Microsoft.CodeAnalysis.VisualBasic.Emit ''' <summary> ''' Represents a generic method of a generic type instantiation, closed over type parameters. ''' e.g. ''' A{T}.M{S}() ''' A.B{T}.C.M{S}() ''' </summary> Friend NotInheritable Class SpecializedGenericMethodInstanceReference Inherits SpecializedMethodReference Implements Cci.IGenericMethodInstanceReference Private ReadOnly _genericMethod As SpecializedMethodReference Public Sub New(underlyingMethod As MethodSymbol) MyBase.New(underlyingMethod) Debug.Assert(underlyingMethod.ContainingType.IsOrInGenericType() AndAlso underlyingMethod.ContainingType.IsDefinition) _genericMethod = New SpecializedMethodReference(underlyingMethod) End Sub Public Function GetGenericMethod(context As EmitContext) As Cci.IMethodReference Implements Cci.IGenericMethodInstanceReference.GetGenericMethod Return _genericMethod End Function Public Function GetGenericArguments(context As EmitContext) As IEnumerable(Of Cci.ITypeReference) Implements Cci.IGenericMethodInstanceReference.GetGenericArguments Dim moduleBeingBuilt As PEModuleBuilder = DirectCast(context.Module, PEModuleBuilder) Return From arg In m_UnderlyingMethod.TypeArguments Select moduleBeingBuilt.Translate(arg, syntaxNodeOpt:=DirectCast(context.SyntaxNode, VisualBasicSyntaxNode), diagnostics:=context.Diagnostics) End Function Public Overrides ReadOnly Property AsGenericMethodInstanceReference As Cci.IGenericMethodInstanceReference Get Return Me End Get End Property Public Overrides Sub Dispatch(visitor As Cci.MetadataVisitor) visitor.Visit(DirectCast(Me, Cci.IGenericMethodInstanceReference)) End Sub End Class End Namespace
-1
dotnet/roslyn
55,290
Fix 'quick info' and 'use explicit type' for implicit lambdas
CyrusNajmabadi
2021-07-30T18:48:59Z
2021-08-03T18:56:45Z
3a5457c3b9483c7b2be1cf6899ee3564c8ade6cf
416765ff976b2a2776c0103d3c7033f9b1667f27
Fix 'quick info' and 'use explicit type' for implicit lambdas.
./src/EditorFeatures/TestUtilities/Structure/AbstractSyntaxTriviaStructureProviderTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Shared.Collections; using Microsoft.CodeAnalysis.Structure; namespace Microsoft.CodeAnalysis.Editor.UnitTests.Structure { public abstract class AbstractSyntaxTriviaStructureProviderTests : AbstractSyntaxStructureProviderTests { internal abstract AbstractSyntaxStructureProvider CreateProvider(); internal sealed override async Task<ImmutableArray<BlockSpan>> GetBlockSpansWorkerAsync(Document document, int position) { var root = await document.GetSyntaxRootAsync(); var trivia = root.FindTrivia(position, findInsideTrivia: true); var outliner = CreateProvider(); using var actualRegions = TemporaryArray<BlockSpan>.Empty; var optionProvider = new BlockStructureOptionProvider( document.Project.Solution.Options, isMetadataAsSource: document.Project.Solution.Workspace.Kind == CodeAnalysis.WorkspaceKind.MetadataAsSource); outliner.CollectBlockSpans(trivia, ref actualRegions.AsRef(), optionProvider, CancellationToken.None); // TODO: Determine why we get null outlining spans. return actualRegions.ToImmutableAndClear(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Shared.Collections; using Microsoft.CodeAnalysis.Structure; namespace Microsoft.CodeAnalysis.Editor.UnitTests.Structure { public abstract class AbstractSyntaxTriviaStructureProviderTests : AbstractSyntaxStructureProviderTests { internal abstract AbstractSyntaxStructureProvider CreateProvider(); internal sealed override async Task<ImmutableArray<BlockSpan>> GetBlockSpansWorkerAsync(Document document, int position) { var root = await document.GetSyntaxRootAsync(); var trivia = root.FindTrivia(position, findInsideTrivia: true); var outliner = CreateProvider(); using var actualRegions = TemporaryArray<BlockSpan>.Empty; var optionProvider = new BlockStructureOptionProvider( document.Project.Solution.Options, isMetadataAsSource: document.Project.Solution.Workspace.Kind == CodeAnalysis.WorkspaceKind.MetadataAsSource); outliner.CollectBlockSpans(trivia, ref actualRegions.AsRef(), optionProvider, CancellationToken.None); // TODO: Determine why we get null outlining spans. return actualRegions.ToImmutableAndClear(); } } }
-1
dotnet/roslyn
55,290
Fix 'quick info' and 'use explicit type' for implicit lambdas
CyrusNajmabadi
2021-07-30T18:48:59Z
2021-08-03T18:56:45Z
3a5457c3b9483c7b2be1cf6899ee3564c8ade6cf
416765ff976b2a2776c0103d3c7033f9b1667f27
Fix 'quick info' and 'use explicit type' for implicit lambdas.
./src/Compilers/CSharp/Portable/Symbols/Source/TypeParameterConstraintClause.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Collections.ObjectModel; using System.Diagnostics; using System.Linq; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols { [Flags] internal enum TypeParameterConstraintKind { None = 0x00, ReferenceType = 0x01, ValueType = 0x02, Constructor = 0x04, Unmanaged = 0x08, NullableReferenceType = ReferenceType | 0x10, NotNullableReferenceType = ReferenceType | 0x20, /// <summary> /// Type parameter has no type constraints, including `struct`, `class`, `unmanaged` and is declared in a context /// where nullable annotations are disabled. /// Cannot be combined with <see cref="ReferenceType"/>, <see cref="ValueType"/> or <see cref="Unmanaged"/>. /// Note, presence of this flag suppresses generation of Nullable attribute on the corresponding type parameter. /// This imitates the shape of metadata produced by pre-nullable compilers. Metadata import is adjusted accordingly /// to distinguish between the two situations. /// </summary> ObliviousNullabilityIfReferenceType = 0x40, NotNull = 0x80, Default = 0x100, /// <summary> /// <see cref="TypeParameterConstraintKind"/> mismatch is detected during merging process for partial type declarations. /// </summary> PartialMismatch = 0x200, ValueTypeFromConstraintTypes = 0x400, // Not set if any flag from AllValueTypeKinds is set ReferenceTypeFromConstraintTypes = 0x800, /// <summary> /// All bits involved into describing various aspects of 'class' constraint. /// </summary> AllReferenceTypeKinds = NullableReferenceType | NotNullableReferenceType, /// <summary> /// Any of these bits is equivalent to presence of 'struct' constraint. /// </summary> AllValueTypeKinds = ValueType | Unmanaged, /// <summary> /// All bits except those that are involved into describilng various nullability aspects. /// </summary> AllNonNullableKinds = ReferenceType | ValueType | Constructor | Unmanaged, } /// <summary> /// A simple representation of a type parameter constraint clause /// as a set of constraint bits and a set of constraint types. /// </summary> internal sealed class TypeParameterConstraintClause { internal static readonly TypeParameterConstraintClause Empty = new TypeParameterConstraintClause( TypeParameterConstraintKind.None, ImmutableArray<TypeWithAnnotations>.Empty); internal static readonly TypeParameterConstraintClause ObliviousNullabilityIfReferenceType = new TypeParameterConstraintClause( TypeParameterConstraintKind.ObliviousNullabilityIfReferenceType, ImmutableArray<TypeWithAnnotations>.Empty); internal static TypeParameterConstraintClause Create( TypeParameterConstraintKind constraints, ImmutableArray<TypeWithAnnotations> constraintTypes) { Debug.Assert(!constraintTypes.IsDefault); if (constraintTypes.IsEmpty) { switch (constraints) { case TypeParameterConstraintKind.None: return Empty; case TypeParameterConstraintKind.ObliviousNullabilityIfReferenceType: return ObliviousNullabilityIfReferenceType; } } return new TypeParameterConstraintClause(constraints, constraintTypes); } private TypeParameterConstraintClause( TypeParameterConstraintKind constraints, ImmutableArray<TypeWithAnnotations> constraintTypes) { #if DEBUG switch (constraints & TypeParameterConstraintKind.AllReferenceTypeKinds) { case TypeParameterConstraintKind.None: case TypeParameterConstraintKind.ReferenceType: case TypeParameterConstraintKind.NullableReferenceType: case TypeParameterConstraintKind.NotNullableReferenceType: break; default: ExceptionUtilities.UnexpectedValue(constraints); // This call asserts. break; } Debug.Assert((constraints & TypeParameterConstraintKind.ObliviousNullabilityIfReferenceType) == 0 || (constraints & ~(TypeParameterConstraintKind.ObliviousNullabilityIfReferenceType | TypeParameterConstraintKind.Constructor | TypeParameterConstraintKind.Default | TypeParameterConstraintKind.PartialMismatch | TypeParameterConstraintKind.ValueTypeFromConstraintTypes | TypeParameterConstraintKind.ReferenceTypeFromConstraintTypes)) == 0); #endif this.Constraints = constraints; this.ConstraintTypes = constraintTypes; } public readonly TypeParameterConstraintKind Constraints; public readonly ImmutableArray<TypeWithAnnotations> ConstraintTypes; internal static SmallDictionary<TypeParameterSymbol, bool> BuildIsValueTypeMap(Symbol container, ImmutableArray<TypeParameterSymbol> typeParameters, ImmutableArray<TypeParameterConstraintClause> constraintClauses) { Debug.Assert(constraintClauses.Length == typeParameters.Length); var isValueTypeMap = new SmallDictionary<TypeParameterSymbol, bool>(ReferenceEqualityComparer.Instance); foreach (TypeParameterSymbol typeParameter in typeParameters) { isValueType(typeParameter, constraintClauses, isValueTypeMap, ConsList<TypeParameterSymbol>.Empty); } return isValueTypeMap; static bool isValueType(TypeParameterSymbol thisTypeParameter, ImmutableArray<TypeParameterConstraintClause> constraintClauses, SmallDictionary<TypeParameterSymbol, bool> isValueTypeMap, ConsList<TypeParameterSymbol> inProgress) { if (inProgress.ContainsReference(thisTypeParameter)) { return false; } if (isValueTypeMap.TryGetValue(thisTypeParameter, out bool knownIsValueType)) { return knownIsValueType; } TypeParameterConstraintClause constraintClause = constraintClauses[thisTypeParameter.Ordinal]; bool result = false; if ((constraintClause.Constraints & TypeParameterConstraintKind.AllValueTypeKinds) != 0) { result = true; } else { Symbol container = thisTypeParameter.ContainingSymbol; inProgress = inProgress.Prepend(thisTypeParameter); foreach (TypeWithAnnotations constraintType in constraintClause.ConstraintTypes) { TypeSymbol type = constraintType.IsResolved ? constraintType.Type : constraintType.DefaultType; if (type is TypeParameterSymbol typeParameter && (object)typeParameter.ContainingSymbol == (object)container) { if (isValueType(typeParameter, constraintClauses, isValueTypeMap, inProgress)) { result = true; break; } } else if (type.IsValueType) { result = true; break; } } } isValueTypeMap.Add(thisTypeParameter, result); return result; } } internal static SmallDictionary<TypeParameterSymbol, bool> BuildIsReferenceTypeFromConstraintTypesMap(Symbol container, ImmutableArray<TypeParameterSymbol> typeParameters, ImmutableArray<TypeParameterConstraintClause> constraintClauses) { Debug.Assert(constraintClauses.Length == typeParameters.Length); var isReferenceTypeFromConstraintTypesMap = new SmallDictionary<TypeParameterSymbol, bool>(ReferenceEqualityComparer.Instance); foreach (TypeParameterSymbol typeParameter in typeParameters) { isReferenceTypeFromConstraintTypes(typeParameter, constraintClauses, isReferenceTypeFromConstraintTypesMap, ConsList<TypeParameterSymbol>.Empty); } return isReferenceTypeFromConstraintTypesMap; static bool isReferenceTypeFromConstraintTypes(TypeParameterSymbol thisTypeParameter, ImmutableArray<TypeParameterConstraintClause> constraintClauses, SmallDictionary<TypeParameterSymbol, bool> isReferenceTypeFromConstraintTypesMap, ConsList<TypeParameterSymbol> inProgress) { if (inProgress.ContainsReference(thisTypeParameter)) { return false; } if (isReferenceTypeFromConstraintTypesMap.TryGetValue(thisTypeParameter, out bool knownIsReferenceTypeFromConstraintTypes)) { return knownIsReferenceTypeFromConstraintTypes; } TypeParameterConstraintClause constraintClause = constraintClauses[thisTypeParameter.Ordinal]; bool result = false; Symbol container = thisTypeParameter.ContainingSymbol; inProgress = inProgress.Prepend(thisTypeParameter); foreach (TypeWithAnnotations constraintType in constraintClause.ConstraintTypes) { TypeSymbol type = constraintType.IsResolved ? constraintType.Type : constraintType.DefaultType; if (type is TypeParameterSymbol typeParameter) { if ((object)typeParameter.ContainingSymbol == (object)container) { if (isReferenceTypeFromConstraintTypes(typeParameter, constraintClauses, isReferenceTypeFromConstraintTypesMap, inProgress)) { result = true; break; } } else if (typeParameter.IsReferenceTypeFromConstraintTypes) { result = true; break; } } else if (TypeParameterSymbol.NonTypeParameterConstraintImpliesReferenceType(type)) { result = true; break; } } isReferenceTypeFromConstraintTypesMap.Add(thisTypeParameter, result); return result; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Collections.ObjectModel; using System.Diagnostics; using System.Linq; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols { [Flags] internal enum TypeParameterConstraintKind { None = 0x00, ReferenceType = 0x01, ValueType = 0x02, Constructor = 0x04, Unmanaged = 0x08, NullableReferenceType = ReferenceType | 0x10, NotNullableReferenceType = ReferenceType | 0x20, /// <summary> /// Type parameter has no type constraints, including `struct`, `class`, `unmanaged` and is declared in a context /// where nullable annotations are disabled. /// Cannot be combined with <see cref="ReferenceType"/>, <see cref="ValueType"/> or <see cref="Unmanaged"/>. /// Note, presence of this flag suppresses generation of Nullable attribute on the corresponding type parameter. /// This imitates the shape of metadata produced by pre-nullable compilers. Metadata import is adjusted accordingly /// to distinguish between the two situations. /// </summary> ObliviousNullabilityIfReferenceType = 0x40, NotNull = 0x80, Default = 0x100, /// <summary> /// <see cref="TypeParameterConstraintKind"/> mismatch is detected during merging process for partial type declarations. /// </summary> PartialMismatch = 0x200, ValueTypeFromConstraintTypes = 0x400, // Not set if any flag from AllValueTypeKinds is set ReferenceTypeFromConstraintTypes = 0x800, /// <summary> /// All bits involved into describing various aspects of 'class' constraint. /// </summary> AllReferenceTypeKinds = NullableReferenceType | NotNullableReferenceType, /// <summary> /// Any of these bits is equivalent to presence of 'struct' constraint. /// </summary> AllValueTypeKinds = ValueType | Unmanaged, /// <summary> /// All bits except those that are involved into describilng various nullability aspects. /// </summary> AllNonNullableKinds = ReferenceType | ValueType | Constructor | Unmanaged, } /// <summary> /// A simple representation of a type parameter constraint clause /// as a set of constraint bits and a set of constraint types. /// </summary> internal sealed class TypeParameterConstraintClause { internal static readonly TypeParameterConstraintClause Empty = new TypeParameterConstraintClause( TypeParameterConstraintKind.None, ImmutableArray<TypeWithAnnotations>.Empty); internal static readonly TypeParameterConstraintClause ObliviousNullabilityIfReferenceType = new TypeParameterConstraintClause( TypeParameterConstraintKind.ObliviousNullabilityIfReferenceType, ImmutableArray<TypeWithAnnotations>.Empty); internal static TypeParameterConstraintClause Create( TypeParameterConstraintKind constraints, ImmutableArray<TypeWithAnnotations> constraintTypes) { Debug.Assert(!constraintTypes.IsDefault); if (constraintTypes.IsEmpty) { switch (constraints) { case TypeParameterConstraintKind.None: return Empty; case TypeParameterConstraintKind.ObliviousNullabilityIfReferenceType: return ObliviousNullabilityIfReferenceType; } } return new TypeParameterConstraintClause(constraints, constraintTypes); } private TypeParameterConstraintClause( TypeParameterConstraintKind constraints, ImmutableArray<TypeWithAnnotations> constraintTypes) { #if DEBUG switch (constraints & TypeParameterConstraintKind.AllReferenceTypeKinds) { case TypeParameterConstraintKind.None: case TypeParameterConstraintKind.ReferenceType: case TypeParameterConstraintKind.NullableReferenceType: case TypeParameterConstraintKind.NotNullableReferenceType: break; default: ExceptionUtilities.UnexpectedValue(constraints); // This call asserts. break; } Debug.Assert((constraints & TypeParameterConstraintKind.ObliviousNullabilityIfReferenceType) == 0 || (constraints & ~(TypeParameterConstraintKind.ObliviousNullabilityIfReferenceType | TypeParameterConstraintKind.Constructor | TypeParameterConstraintKind.Default | TypeParameterConstraintKind.PartialMismatch | TypeParameterConstraintKind.ValueTypeFromConstraintTypes | TypeParameterConstraintKind.ReferenceTypeFromConstraintTypes)) == 0); #endif this.Constraints = constraints; this.ConstraintTypes = constraintTypes; } public readonly TypeParameterConstraintKind Constraints; public readonly ImmutableArray<TypeWithAnnotations> ConstraintTypes; internal static SmallDictionary<TypeParameterSymbol, bool> BuildIsValueTypeMap(Symbol container, ImmutableArray<TypeParameterSymbol> typeParameters, ImmutableArray<TypeParameterConstraintClause> constraintClauses) { Debug.Assert(constraintClauses.Length == typeParameters.Length); var isValueTypeMap = new SmallDictionary<TypeParameterSymbol, bool>(ReferenceEqualityComparer.Instance); foreach (TypeParameterSymbol typeParameter in typeParameters) { isValueType(typeParameter, constraintClauses, isValueTypeMap, ConsList<TypeParameterSymbol>.Empty); } return isValueTypeMap; static bool isValueType(TypeParameterSymbol thisTypeParameter, ImmutableArray<TypeParameterConstraintClause> constraintClauses, SmallDictionary<TypeParameterSymbol, bool> isValueTypeMap, ConsList<TypeParameterSymbol> inProgress) { if (inProgress.ContainsReference(thisTypeParameter)) { return false; } if (isValueTypeMap.TryGetValue(thisTypeParameter, out bool knownIsValueType)) { return knownIsValueType; } TypeParameterConstraintClause constraintClause = constraintClauses[thisTypeParameter.Ordinal]; bool result = false; if ((constraintClause.Constraints & TypeParameterConstraintKind.AllValueTypeKinds) != 0) { result = true; } else { Symbol container = thisTypeParameter.ContainingSymbol; inProgress = inProgress.Prepend(thisTypeParameter); foreach (TypeWithAnnotations constraintType in constraintClause.ConstraintTypes) { TypeSymbol type = constraintType.IsResolved ? constraintType.Type : constraintType.DefaultType; if (type is TypeParameterSymbol typeParameter && (object)typeParameter.ContainingSymbol == (object)container) { if (isValueType(typeParameter, constraintClauses, isValueTypeMap, inProgress)) { result = true; break; } } else if (type.IsValueType) { result = true; break; } } } isValueTypeMap.Add(thisTypeParameter, result); return result; } } internal static SmallDictionary<TypeParameterSymbol, bool> BuildIsReferenceTypeFromConstraintTypesMap(Symbol container, ImmutableArray<TypeParameterSymbol> typeParameters, ImmutableArray<TypeParameterConstraintClause> constraintClauses) { Debug.Assert(constraintClauses.Length == typeParameters.Length); var isReferenceTypeFromConstraintTypesMap = new SmallDictionary<TypeParameterSymbol, bool>(ReferenceEqualityComparer.Instance); foreach (TypeParameterSymbol typeParameter in typeParameters) { isReferenceTypeFromConstraintTypes(typeParameter, constraintClauses, isReferenceTypeFromConstraintTypesMap, ConsList<TypeParameterSymbol>.Empty); } return isReferenceTypeFromConstraintTypesMap; static bool isReferenceTypeFromConstraintTypes(TypeParameterSymbol thisTypeParameter, ImmutableArray<TypeParameterConstraintClause> constraintClauses, SmallDictionary<TypeParameterSymbol, bool> isReferenceTypeFromConstraintTypesMap, ConsList<TypeParameterSymbol> inProgress) { if (inProgress.ContainsReference(thisTypeParameter)) { return false; } if (isReferenceTypeFromConstraintTypesMap.TryGetValue(thisTypeParameter, out bool knownIsReferenceTypeFromConstraintTypes)) { return knownIsReferenceTypeFromConstraintTypes; } TypeParameterConstraintClause constraintClause = constraintClauses[thisTypeParameter.Ordinal]; bool result = false; Symbol container = thisTypeParameter.ContainingSymbol; inProgress = inProgress.Prepend(thisTypeParameter); foreach (TypeWithAnnotations constraintType in constraintClause.ConstraintTypes) { TypeSymbol type = constraintType.IsResolved ? constraintType.Type : constraintType.DefaultType; if (type is TypeParameterSymbol typeParameter) { if ((object)typeParameter.ContainingSymbol == (object)container) { if (isReferenceTypeFromConstraintTypes(typeParameter, constraintClauses, isReferenceTypeFromConstraintTypesMap, inProgress)) { result = true; break; } } else if (typeParameter.IsReferenceTypeFromConstraintTypes) { result = true; break; } } else if (TypeParameterSymbol.NonTypeParameterConstraintImpliesReferenceType(type)) { result = true; break; } } isReferenceTypeFromConstraintTypesMap.Add(thisTypeParameter, result); return result; } } } }
-1
dotnet/roslyn
55,290
Fix 'quick info' and 'use explicit type' for implicit lambdas
CyrusNajmabadi
2021-07-30T18:48:59Z
2021-08-03T18:56:45Z
3a5457c3b9483c7b2be1cf6899ee3564c8ade6cf
416765ff976b2a2776c0103d3c7033f9b1667f27
Fix 'quick info' and 'use explicit type' for implicit lambdas.
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Extensions/SyntaxTriviaExtensions.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Extensions { internal static class SyntaxTriviaExtensions { public static bool MatchesKind(this SyntaxTrivia trivia, SyntaxKind kind) => trivia.Kind() == kind; public static bool MatchesKind(this SyntaxTrivia trivia, SyntaxKind kind1, SyntaxKind kind2) { var triviaKind = trivia.Kind(); return triviaKind == kind1 || triviaKind == kind2; } public static bool MatchesKind(this SyntaxTrivia trivia, params SyntaxKind[] kinds) => kinds.Contains(trivia.Kind()); public static bool IsSingleOrMultiLineComment(this SyntaxTrivia trivia) => trivia.IsKind(SyntaxKind.MultiLineCommentTrivia) || trivia.IsKind(SyntaxKind.SingleLineCommentTrivia); public static bool IsRegularComment(this SyntaxTrivia trivia) => trivia.IsSingleOrMultiLineComment() || trivia.IsShebangDirective(); public static bool IsWhitespaceOrSingleOrMultiLineComment(this SyntaxTrivia trivia) => trivia.IsWhitespace() || trivia.IsSingleOrMultiLineComment(); public static bool IsRegularOrDocComment(this SyntaxTrivia trivia) => trivia.IsRegularComment() || trivia.IsDocComment(); public static bool IsSingleLineComment(this SyntaxTrivia trivia) => trivia.Kind() == SyntaxKind.SingleLineCommentTrivia; public static bool IsMultiLineComment(this SyntaxTrivia trivia) => trivia.Kind() == SyntaxKind.MultiLineCommentTrivia; public static bool IsShebangDirective(this SyntaxTrivia trivia) => trivia.Kind() == SyntaxKind.ShebangDirectiveTrivia; public static bool IsCompleteMultiLineComment(this SyntaxTrivia trivia) { if (trivia.Kind() != SyntaxKind.MultiLineCommentTrivia) { return false; } var text = trivia.ToFullString(); return text.Length >= 4 && text[text.Length - 1] == '/' && text[text.Length - 2] == '*'; } public static bool IsDocComment(this SyntaxTrivia trivia) => trivia.IsSingleLineDocComment() || trivia.IsMultiLineDocComment(); public static bool IsSingleLineDocComment(this SyntaxTrivia trivia) => trivia.Kind() == SyntaxKind.SingleLineDocumentationCommentTrivia; public static bool IsMultiLineDocComment(this SyntaxTrivia trivia) => trivia.Kind() == SyntaxKind.MultiLineDocumentationCommentTrivia; public static string GetCommentText(this SyntaxTrivia trivia) { var commentText = trivia.ToString(); if (trivia.Kind() == SyntaxKind.SingleLineCommentTrivia) { if (commentText.StartsWith("//", StringComparison.Ordinal)) { commentText = commentText.Substring(2); } return commentText.TrimStart(null); } else if (trivia.Kind() == SyntaxKind.MultiLineCommentTrivia) { var textBuilder = new StringBuilder(); if (commentText.EndsWith("*/", StringComparison.Ordinal)) { commentText = commentText.Substring(0, commentText.Length - 2); } if (commentText.StartsWith("/*", StringComparison.Ordinal)) { commentText = commentText.Substring(2); } commentText = commentText.Trim(); var newLine = Environment.NewLine; var lines = commentText.Split(new[] { newLine }, StringSplitOptions.None); foreach (var line in lines) { var trimmedLine = line.Trim(); // Note: we trim leading '*' characters in multi-line comments. // If the '*' was intentional, sorry, it's gone. if (trimmedLine.StartsWith("*", StringComparison.Ordinal)) { trimmedLine = trimmedLine.TrimStart('*'); trimmedLine = trimmedLine.TrimStart(null); } textBuilder.AppendLine(trimmedLine); } // remove last line break textBuilder.Remove(textBuilder.Length - newLine.Length, newLine.Length); return textBuilder.ToString(); } else { throw new InvalidOperationException(); } } public static string AsString(this IEnumerable<SyntaxTrivia> trivia) { Contract.ThrowIfNull(trivia); if (trivia.Any()) { var sb = new StringBuilder(); trivia.Select(t => t.ToFullString()).Do(s => sb.Append(s)); return sb.ToString(); } else { return string.Empty; } } public static int GetFullWidth(this IEnumerable<SyntaxTrivia> trivia) { Contract.ThrowIfNull(trivia); return trivia.Sum(t => t.FullWidth()); } public static SyntaxTriviaList AsTrivia(this string s) => SyntaxFactory.ParseLeadingTrivia(s ?? string.Empty); public static bool IsWhitespaceOrEndOfLine(this SyntaxTrivia trivia) => IsWhitespace(trivia) || IsEndOfLine(trivia); public static bool IsEndOfLine(this SyntaxTrivia trivia) => trivia.Kind() == SyntaxKind.EndOfLineTrivia; public static bool IsWhitespace(this SyntaxTrivia trivia) => trivia.Kind() == SyntaxKind.WhitespaceTrivia; public static SyntaxTrivia GetPreviousTrivia( this SyntaxTrivia trivia, SyntaxTree syntaxTree, CancellationToken cancellationToken, bool findInsideTrivia = false) { var span = trivia.FullSpan; if (span.Start == 0) { return default; } return syntaxTree.GetRoot(cancellationToken).FindTrivia(span.Start - 1, findInsideTrivia); } public static IEnumerable<SyntaxTrivia> FilterComments(this IEnumerable<SyntaxTrivia> trivia, bool addElasticMarker) { var previousIsSingleLineComment = false; foreach (var t in trivia) { if (previousIsSingleLineComment && t.IsEndOfLine()) { yield return t; } if (t.IsSingleOrMultiLineComment()) { yield return t; } previousIsSingleLineComment = t.IsSingleLineComment(); } if (addElasticMarker) { yield return SyntaxFactory.ElasticMarker; } } #if false public static int Width(this SyntaxTrivia trivia) { return trivia.Span.Length; } public static int FullWidth(this SyntaxTrivia trivia) { return trivia.FullSpan.Length; } #endif public static bool IsPragmaDirective(this SyntaxTrivia trivia, out bool isDisable, out bool isActive, out SeparatedSyntaxList<SyntaxNode> errorCodes) { if (trivia.IsKind(SyntaxKind.PragmaWarningDirectiveTrivia)) { var pragmaWarning = (PragmaWarningDirectiveTriviaSyntax)trivia.GetStructure(); isDisable = pragmaWarning.DisableOrRestoreKeyword.IsKind(SyntaxKind.DisableKeyword); isActive = pragmaWarning.IsActive; errorCodes = pragmaWarning.ErrorCodes; return true; } isDisable = false; isActive = false; errorCodes = default; return false; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Extensions { internal static class SyntaxTriviaExtensions { public static bool MatchesKind(this SyntaxTrivia trivia, SyntaxKind kind) => trivia.Kind() == kind; public static bool MatchesKind(this SyntaxTrivia trivia, SyntaxKind kind1, SyntaxKind kind2) { var triviaKind = trivia.Kind(); return triviaKind == kind1 || triviaKind == kind2; } public static bool MatchesKind(this SyntaxTrivia trivia, params SyntaxKind[] kinds) => kinds.Contains(trivia.Kind()); public static bool IsSingleOrMultiLineComment(this SyntaxTrivia trivia) => trivia.IsKind(SyntaxKind.MultiLineCommentTrivia) || trivia.IsKind(SyntaxKind.SingleLineCommentTrivia); public static bool IsRegularComment(this SyntaxTrivia trivia) => trivia.IsSingleOrMultiLineComment() || trivia.IsShebangDirective(); public static bool IsWhitespaceOrSingleOrMultiLineComment(this SyntaxTrivia trivia) => trivia.IsWhitespace() || trivia.IsSingleOrMultiLineComment(); public static bool IsRegularOrDocComment(this SyntaxTrivia trivia) => trivia.IsRegularComment() || trivia.IsDocComment(); public static bool IsSingleLineComment(this SyntaxTrivia trivia) => trivia.Kind() == SyntaxKind.SingleLineCommentTrivia; public static bool IsMultiLineComment(this SyntaxTrivia trivia) => trivia.Kind() == SyntaxKind.MultiLineCommentTrivia; public static bool IsShebangDirective(this SyntaxTrivia trivia) => trivia.Kind() == SyntaxKind.ShebangDirectiveTrivia; public static bool IsCompleteMultiLineComment(this SyntaxTrivia trivia) { if (trivia.Kind() != SyntaxKind.MultiLineCommentTrivia) { return false; } var text = trivia.ToFullString(); return text.Length >= 4 && text[text.Length - 1] == '/' && text[text.Length - 2] == '*'; } public static bool IsDocComment(this SyntaxTrivia trivia) => trivia.IsSingleLineDocComment() || trivia.IsMultiLineDocComment(); public static bool IsSingleLineDocComment(this SyntaxTrivia trivia) => trivia.Kind() == SyntaxKind.SingleLineDocumentationCommentTrivia; public static bool IsMultiLineDocComment(this SyntaxTrivia trivia) => trivia.Kind() == SyntaxKind.MultiLineDocumentationCommentTrivia; public static string GetCommentText(this SyntaxTrivia trivia) { var commentText = trivia.ToString(); if (trivia.Kind() == SyntaxKind.SingleLineCommentTrivia) { if (commentText.StartsWith("//", StringComparison.Ordinal)) { commentText = commentText.Substring(2); } return commentText.TrimStart(null); } else if (trivia.Kind() == SyntaxKind.MultiLineCommentTrivia) { var textBuilder = new StringBuilder(); if (commentText.EndsWith("*/", StringComparison.Ordinal)) { commentText = commentText.Substring(0, commentText.Length - 2); } if (commentText.StartsWith("/*", StringComparison.Ordinal)) { commentText = commentText.Substring(2); } commentText = commentText.Trim(); var newLine = Environment.NewLine; var lines = commentText.Split(new[] { newLine }, StringSplitOptions.None); foreach (var line in lines) { var trimmedLine = line.Trim(); // Note: we trim leading '*' characters in multi-line comments. // If the '*' was intentional, sorry, it's gone. if (trimmedLine.StartsWith("*", StringComparison.Ordinal)) { trimmedLine = trimmedLine.TrimStart('*'); trimmedLine = trimmedLine.TrimStart(null); } textBuilder.AppendLine(trimmedLine); } // remove last line break textBuilder.Remove(textBuilder.Length - newLine.Length, newLine.Length); return textBuilder.ToString(); } else { throw new InvalidOperationException(); } } public static string AsString(this IEnumerable<SyntaxTrivia> trivia) { Contract.ThrowIfNull(trivia); if (trivia.Any()) { var sb = new StringBuilder(); trivia.Select(t => t.ToFullString()).Do(s => sb.Append(s)); return sb.ToString(); } else { return string.Empty; } } public static int GetFullWidth(this IEnumerable<SyntaxTrivia> trivia) { Contract.ThrowIfNull(trivia); return trivia.Sum(t => t.FullWidth()); } public static SyntaxTriviaList AsTrivia(this string s) => SyntaxFactory.ParseLeadingTrivia(s ?? string.Empty); public static bool IsWhitespaceOrEndOfLine(this SyntaxTrivia trivia) => IsWhitespace(trivia) || IsEndOfLine(trivia); public static bool IsEndOfLine(this SyntaxTrivia trivia) => trivia.Kind() == SyntaxKind.EndOfLineTrivia; public static bool IsWhitespace(this SyntaxTrivia trivia) => trivia.Kind() == SyntaxKind.WhitespaceTrivia; public static SyntaxTrivia GetPreviousTrivia( this SyntaxTrivia trivia, SyntaxTree syntaxTree, CancellationToken cancellationToken, bool findInsideTrivia = false) { var span = trivia.FullSpan; if (span.Start == 0) { return default; } return syntaxTree.GetRoot(cancellationToken).FindTrivia(span.Start - 1, findInsideTrivia); } public static IEnumerable<SyntaxTrivia> FilterComments(this IEnumerable<SyntaxTrivia> trivia, bool addElasticMarker) { var previousIsSingleLineComment = false; foreach (var t in trivia) { if (previousIsSingleLineComment && t.IsEndOfLine()) { yield return t; } if (t.IsSingleOrMultiLineComment()) { yield return t; } previousIsSingleLineComment = t.IsSingleLineComment(); } if (addElasticMarker) { yield return SyntaxFactory.ElasticMarker; } } #if false public static int Width(this SyntaxTrivia trivia) { return trivia.Span.Length; } public static int FullWidth(this SyntaxTrivia trivia) { return trivia.FullSpan.Length; } #endif public static bool IsPragmaDirective(this SyntaxTrivia trivia, out bool isDisable, out bool isActive, out SeparatedSyntaxList<SyntaxNode> errorCodes) { if (trivia.IsKind(SyntaxKind.PragmaWarningDirectiveTrivia)) { var pragmaWarning = (PragmaWarningDirectiveTriviaSyntax)trivia.GetStructure(); isDisable = pragmaWarning.DisableOrRestoreKeyword.IsKind(SyntaxKind.DisableKeyword); isActive = pragmaWarning.IsActive; errorCodes = pragmaWarning.ErrorCodes; return true; } isDisable = false; isActive = false; errorCodes = default; return false; } } }
-1
dotnet/roslyn
55,290
Fix 'quick info' and 'use explicit type' for implicit lambdas
CyrusNajmabadi
2021-07-30T18:48:59Z
2021-08-03T18:56:45Z
3a5457c3b9483c7b2be1cf6899ee3564c8ade6cf
416765ff976b2a2776c0103d3c7033f9b1667f27
Fix 'quick info' and 'use explicit type' for implicit lambdas.
./src/Features/Core/Portable/CodeFixes/AddExplicitCast/InheritanceDistanceComparer.cs
// Licensed to the .NET Foundation under one or more agreements. // 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; namespace Microsoft.CodeAnalysis.CodeFixes.AddExplicitCast { /// <summary> /// The item is the pair of target argument expression and its conversion type /// <para/> /// Sort pairs using conversion types by inheritance distance from the base type in ascending order, /// i.e., less specific type has higher priority because it has less probability to make mistakes /// <para/> /// For example: /// class Base { } /// class Derived1 : Base { } /// class Derived2 : Derived1 { } /// /// void Foo(Derived1 d1) { } /// void Foo(Derived2 d2) { } /// /// Base b = new Derived1(); /// Foo([||]b); /// /// operations: /// 1. Convert type to 'Derived1' /// 2. Convert type to 'Derived2' /// /// 'Derived1' is less specific than 'Derived2' compared to 'Base' /// </summary> internal sealed class InheritanceDistanceComparer<TExpressionSyntax> : IComparer<(TExpressionSyntax syntax, ITypeSymbol symbol)> where TExpressionSyntax : SyntaxNode { private readonly SemanticModel _semanticModel; public InheritanceDistanceComparer(SemanticModel semanticModel) { _semanticModel = semanticModel; } public int Compare((TExpressionSyntax syntax, ITypeSymbol symbol) x, (TExpressionSyntax syntax, ITypeSymbol symbol) y) { // if the argument is different, keep the original order if (!x.syntax.Equals(y.syntax)) { return 0; } else { var baseType = _semanticModel.GetTypeInfo(x.syntax).Type; var xDist = GetInheritanceDistance(baseType, x.symbol); var yDist = GetInheritanceDistance(baseType, y.symbol); return xDist.CompareTo(yDist); } } /// <summary> /// Calculate the inheritance distance between baseType and derivedType. /// </summary> private int GetInheritanceDistanceRecursive(ITypeSymbol baseType, ITypeSymbol? derivedType) { if (derivedType == null) return int.MaxValue; if (derivedType.Equals(baseType)) return 0; var distance = GetInheritanceDistanceRecursive(baseType, derivedType.BaseType); if (derivedType.Interfaces.Length != 0) { foreach (var interfaceType in derivedType.Interfaces) { distance = Math.Min(GetInheritanceDistanceRecursive(baseType, interfaceType), distance); } } return distance == int.MaxValue ? distance : distance + 1; } /// <summary> /// Wrapper function of [GetInheritanceDistance], also consider the class with explicit conversion operator /// has the highest priority. /// </summary> private int GetInheritanceDistance(ITypeSymbol? baseType, ITypeSymbol castType) { if (baseType is null) return 0; var conversion = _semanticModel.Compilation.ClassifyCommonConversion(baseType, castType); // If the node has the explicit conversion operator, then it has the shortest distance // since explicit conversion operator is defined by users and has the highest priority var distance = conversion.IsUserDefined ? 0 : GetInheritanceDistanceRecursive(baseType, castType); return distance; } } }
// Licensed to the .NET Foundation under one or more agreements. // 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; namespace Microsoft.CodeAnalysis.CodeFixes.AddExplicitCast { /// <summary> /// The item is the pair of target argument expression and its conversion type /// <para/> /// Sort pairs using conversion types by inheritance distance from the base type in ascending order, /// i.e., less specific type has higher priority because it has less probability to make mistakes /// <para/> /// For example: /// class Base { } /// class Derived1 : Base { } /// class Derived2 : Derived1 { } /// /// void Foo(Derived1 d1) { } /// void Foo(Derived2 d2) { } /// /// Base b = new Derived1(); /// Foo([||]b); /// /// operations: /// 1. Convert type to 'Derived1' /// 2. Convert type to 'Derived2' /// /// 'Derived1' is less specific than 'Derived2' compared to 'Base' /// </summary> internal sealed class InheritanceDistanceComparer<TExpressionSyntax> : IComparer<(TExpressionSyntax syntax, ITypeSymbol symbol)> where TExpressionSyntax : SyntaxNode { private readonly SemanticModel _semanticModel; public InheritanceDistanceComparer(SemanticModel semanticModel) { _semanticModel = semanticModel; } public int Compare((TExpressionSyntax syntax, ITypeSymbol symbol) x, (TExpressionSyntax syntax, ITypeSymbol symbol) y) { // if the argument is different, keep the original order if (!x.syntax.Equals(y.syntax)) { return 0; } else { var baseType = _semanticModel.GetTypeInfo(x.syntax).Type; var xDist = GetInheritanceDistance(baseType, x.symbol); var yDist = GetInheritanceDistance(baseType, y.symbol); return xDist.CompareTo(yDist); } } /// <summary> /// Calculate the inheritance distance between baseType and derivedType. /// </summary> private int GetInheritanceDistanceRecursive(ITypeSymbol baseType, ITypeSymbol? derivedType) { if (derivedType == null) return int.MaxValue; if (derivedType.Equals(baseType)) return 0; var distance = GetInheritanceDistanceRecursive(baseType, derivedType.BaseType); if (derivedType.Interfaces.Length != 0) { foreach (var interfaceType in derivedType.Interfaces) { distance = Math.Min(GetInheritanceDistanceRecursive(baseType, interfaceType), distance); } } return distance == int.MaxValue ? distance : distance + 1; } /// <summary> /// Wrapper function of [GetInheritanceDistance], also consider the class with explicit conversion operator /// has the highest priority. /// </summary> private int GetInheritanceDistance(ITypeSymbol? baseType, ITypeSymbol castType) { if (baseType is null) return 0; var conversion = _semanticModel.Compilation.ClassifyCommonConversion(baseType, castType); // If the node has the explicit conversion operator, then it has the shortest distance // since explicit conversion operator is defined by users and has the highest priority var distance = conversion.IsUserDefined ? 0 : GetInheritanceDistanceRecursive(baseType, castType); return distance; } } }
-1
dotnet/roslyn
55,290
Fix 'quick info' and 'use explicit type' for implicit lambdas
CyrusNajmabadi
2021-07-30T18:48:59Z
2021-08-03T18:56:45Z
3a5457c3b9483c7b2be1cf6899ee3564c8ade6cf
416765ff976b2a2776c0103d3c7033f9b1667f27
Fix 'quick info' and 'use explicit type' for implicit lambdas.
./src/Workspaces/Core/Portable/Classification/ISemanticClassificationCacheService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Composition; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.PersistentStorage; using Microsoft.CodeAnalysis.Serialization; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Classification { /// <summary> /// Service that can retrieve semantic classifications for a document cached during a previous session. This is /// intended to help populate semantic classifications for a host during the time while a solution is loading and /// semantics may be incomplete or unavailable. /// </summary> internal interface ISemanticClassificationCacheService : IWorkspaceService { /// <summary> /// Tries to get cached semantic classifications for the specified document and the specified <paramref /// name="textSpan"/>. Will return a <c>default</c> array not able to. An empty array indicates that there /// were cached classifications, but none that intersected the provided <paramref name="textSpan"/>. /// </summary> /// <param name="checksum">Pass in <see cref="DocumentStateChecksums.Text"/>. This will ensure that the cached /// classifications are only returned if they match the content the file currently has.</param> Task<ImmutableArray<ClassifiedSpan>> GetCachedSemanticClassificationsAsync( DocumentKey documentKey, TextSpan textSpan, Checksum checksum, CancellationToken cancellationToken); } [ExportWorkspaceService(typeof(ISemanticClassificationCacheService)), Shared] internal class DefaultSemanticClassificationCacheService : ISemanticClassificationCacheService { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public DefaultSemanticClassificationCacheService() { } public Task<ImmutableArray<ClassifiedSpan>> GetCachedSemanticClassificationsAsync(DocumentKey documentKey, TextSpan textSpan, Checksum checksum, CancellationToken cancellationToken) => SpecializedTasks.Default<ImmutableArray<ClassifiedSpan>>(); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Composition; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.PersistentStorage; using Microsoft.CodeAnalysis.Serialization; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Classification { /// <summary> /// Service that can retrieve semantic classifications for a document cached during a previous session. This is /// intended to help populate semantic classifications for a host during the time while a solution is loading and /// semantics may be incomplete or unavailable. /// </summary> internal interface ISemanticClassificationCacheService : IWorkspaceService { /// <summary> /// Tries to get cached semantic classifications for the specified document and the specified <paramref /// name="textSpan"/>. Will return a <c>default</c> array not able to. An empty array indicates that there /// were cached classifications, but none that intersected the provided <paramref name="textSpan"/>. /// </summary> /// <param name="checksum">Pass in <see cref="DocumentStateChecksums.Text"/>. This will ensure that the cached /// classifications are only returned if they match the content the file currently has.</param> Task<ImmutableArray<ClassifiedSpan>> GetCachedSemanticClassificationsAsync( DocumentKey documentKey, TextSpan textSpan, Checksum checksum, CancellationToken cancellationToken); } [ExportWorkspaceService(typeof(ISemanticClassificationCacheService)), Shared] internal class DefaultSemanticClassificationCacheService : ISemanticClassificationCacheService { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public DefaultSemanticClassificationCacheService() { } public Task<ImmutableArray<ClassifiedSpan>> GetCachedSemanticClassificationsAsync(DocumentKey documentKey, TextSpan textSpan, Checksum checksum, CancellationToken cancellationToken) => SpecializedTasks.Default<ImmutableArray<ClassifiedSpan>>(); } }
-1
dotnet/roslyn
55,290
Fix 'quick info' and 'use explicit type' for implicit lambdas
CyrusNajmabadi
2021-07-30T18:48:59Z
2021-08-03T18:56:45Z
3a5457c3b9483c7b2be1cf6899ee3564c8ade6cf
416765ff976b2a2776c0103d3c7033f9b1667f27
Fix 'quick info' and 'use explicit type' for implicit lambdas.
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/NamingStyles/Serialization/MutableNamingStyle.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using Microsoft.CodeAnalysis.NamingStyles; namespace Microsoft.CodeAnalysis.Diagnostics.Analyzers.NamingStyles { internal class MutableNamingStyle { public NamingStyle NamingStyle { get; private set; } public Guid ID => NamingStyle.ID; public string Name { get => NamingStyle.Name; set => NamingStyle = NamingStyle.With(name: value); } public string Prefix { get => NamingStyle.Prefix; set => NamingStyle = NamingStyle.With(prefix: value); } public string Suffix { get => NamingStyle.Suffix; set => NamingStyle = NamingStyle.With(suffix: value); } public string WordSeparator { get => NamingStyle.WordSeparator; set => NamingStyle = NamingStyle.With(wordSeparator: value); } public Capitalization CapitalizationScheme { get => NamingStyle.CapitalizationScheme; set => NamingStyle = NamingStyle.With(capitalizationScheme: value); } public MutableNamingStyle() : this(new NamingStyle(Guid.NewGuid())) { } public MutableNamingStyle(NamingStyle namingStyle) => NamingStyle = namingStyle; internal MutableNamingStyle Clone() => new(NamingStyle); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using Microsoft.CodeAnalysis.NamingStyles; namespace Microsoft.CodeAnalysis.Diagnostics.Analyzers.NamingStyles { internal class MutableNamingStyle { public NamingStyle NamingStyle { get; private set; } public Guid ID => NamingStyle.ID; public string Name { get => NamingStyle.Name; set => NamingStyle = NamingStyle.With(name: value); } public string Prefix { get => NamingStyle.Prefix; set => NamingStyle = NamingStyle.With(prefix: value); } public string Suffix { get => NamingStyle.Suffix; set => NamingStyle = NamingStyle.With(suffix: value); } public string WordSeparator { get => NamingStyle.WordSeparator; set => NamingStyle = NamingStyle.With(wordSeparator: value); } public Capitalization CapitalizationScheme { get => NamingStyle.CapitalizationScheme; set => NamingStyle = NamingStyle.With(capitalizationScheme: value); } public MutableNamingStyle() : this(new NamingStyle(Guid.NewGuid())) { } public MutableNamingStyle(NamingStyle namingStyle) => NamingStyle = namingStyle; internal MutableNamingStyle Clone() => new(NamingStyle); } }
-1
dotnet/roslyn
55,290
Fix 'quick info' and 'use explicit type' for implicit lambdas
CyrusNajmabadi
2021-07-30T18:48:59Z
2021-08-03T18:56:45Z
3a5457c3b9483c7b2be1cf6899ee3564c8ade6cf
416765ff976b2a2776c0103d3c7033f9b1667f27
Fix 'quick info' and 'use explicit type' for implicit lambdas.
./src/Compilers/VisualBasic/Test/Syntax/Syntax/SyntaxNormalizerTests.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System Imports System.Collections.Generic Imports System.Linq Imports System.Text Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities Imports Xunit Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests Public Class SyntaxNormalizerTests <WorkItem(546397, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546397")> <ConditionalFact(GetType(WindowsOnly))> Public Sub TestAllInVB() Dim allInVB As String = TestResource.AllInOneVisualBasicCode Dim expected As String = TestResource.AllInOneVisualBasicBaseline Dim node As CompilationUnitSyntax = SyntaxFactory.ParseCompilationUnit(allInVB) Dim actual = node.NormalizeWhitespace(" ").ToFullString() Assert.Equal(expected, actual) End Sub <Fact()> Public Sub TestNormalizeExpressions() TestNormalizeExpression("+1", "+1") TestNormalizeExpression("+a", "+a") TestNormalizeExpression("-a", "-a") TestNormalizeExpression("a", "a") TestNormalizeExpression("a+b", "a + b") TestNormalizeExpression("a-b", "a - b") TestNormalizeExpression("a*b", "a * b") TestNormalizeExpression("a/b", "a / b") TestNormalizeExpression("a mod b", "a mod b") TestNormalizeExpression("a xor b", "a xor b") TestNormalizeExpression("a or b", "a or b") TestNormalizeExpression("a and b", "a and b") TestNormalizeExpression("a orelse b", "a orelse b") TestNormalizeExpression("a andalso b", "a andalso b") TestNormalizeExpression("a<b", "a < b") TestNormalizeExpression("a<=b", "a <= b") TestNormalizeExpression("a>b", "a > b") TestNormalizeExpression("a>=b", "a >= b") TestNormalizeExpression("a=b", "a = b") TestNormalizeExpression("a<>b", "a <> b") TestNormalizeExpression("a<<b", "a << b") TestNormalizeExpression("a>>b", "a >> b") TestNormalizeExpression("(a+b)", "(a + b)") TestNormalizeExpression("((a)+(b))", "((a) + (b))") TestNormalizeExpression("(a)", "(a)") TestNormalizeExpression("(a)(b)", "(a)(b)") TestNormalizeExpression("m()", "m()") TestNormalizeExpression("m(a)", "m(a)") TestNormalizeExpression("m(a,b)", "m(a, b)") TestNormalizeExpression("m(a,b,c)", "m(a, b, c)") TestNormalizeExpression("m(a,b(c,d))", "m(a, b(c, d))") TestNormalizeExpression("m( , ,, )", "m(,,,)") TestNormalizeExpression("a(b(c(0)))", "a(b(c(0)))") TestNormalizeExpression("if(a,b,c)", "if(a, b, c)") TestNormalizeExpression("a().b().c()", "a().b().c()") TestNormalizeExpression("""aM5b"" Like ""a[L-P]#[!c-e]a?""", """aM5b"" Like ""a[L-P]#[!c-e]a?""") End Sub Private Sub TestNormalizeExpression(text As String, expected As String) Dim node = SyntaxFactory.ParseExpression(text) Dim actual = node.NormalizeWhitespace(" ").ToFullString() Assert.Equal(expected, actual) End Sub <Fact()> Public Sub TestTrailingComment() TestNormalizeBlock("Dim goo as Bar ' it is a Bar", "Dim goo as Bar ' it is a Bar" + vbCrLf) End Sub <Fact()> Public Sub TestOptionStatements() TestNormalizeBlock("Option Explicit Off", "Option Explicit Off" + vbCrLf) End Sub <Fact()> Public Sub TestImportsStatements() TestNormalizeBlock("Imports System", "Imports System" + vbCrLf) TestNormalizeBlock("Imports System.Goo.Bar", "Imports System.Goo.Bar" + vbCrLf) TestNormalizeBlock("Imports T2=System.String", "Imports T2 = System.String" + vbCrLf) TestNormalizeBlock("Imports <xmlns:db=""http://example.org/database"">", "Imports <xmlns:db=""http://example.org/database"">" + vbCrLf) End Sub <Fact(), WorkItem(546397, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546397")> Public Sub TestLabelStatements() TestNormalizeStatement("while a<b" + vbCrLf + "goo:" + vbCrLf + "c" + vbCrLf + "end while", "while a < b" + vbCrLf + "goo:" + vbCrLf + " c" + vbCrLf + "end while") End Sub <Fact(), WorkItem(546397, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546397")> Public Sub TestMethodStatements() TestNormalizeBlock("Sub goo()" + vbCrLf + "a()" + vbCrLf + "end Sub", "Sub goo()" + vbCrLf + " a()" + vbCrLf + "end Sub" + vbCrLf) TestNormalizeBlock("Function goo() as Integer" + vbCrLf + "return 23" + vbCrLf + "end function", "Function goo() as Integer" + vbCrLf + " return 23" + vbCrLf + "end function" + vbCrLf) TestNormalizeBlock("Function goo( x as System.Int32,[Char] as Integer) as Integer" + vbCrLf + "return 23" + vbCrLf + "end function", "Function goo(x as System.Int32, [Char] as Integer) as Integer" + vbCrLf + " return 23" + vbCrLf + "end function" + vbCrLf) TestNormalizeBlock("Sub goo()" + vbCrLf + "Dim a ( ) ( )=New Integer ( ) ( ) ( ){ }" + vbCrLf + "end Sub", "Sub goo()" + vbCrLf + " Dim a()() = New Integer()()() {}" + vbCrLf + "end Sub" + vbCrLf) End Sub <Fact(), WorkItem(546397, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546397")> Public Sub TestWithStatements() TestNormalizeBlock( <code> Sub goo() with goo .bar() end with end Sub</code>.Value, _ _ <code>Sub goo() with goo .bar() end with end Sub </code>.Value) End Sub <Fact(), WorkItem(546397, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546397")> Public Sub TestSyncLockStatements() TestNormalizeBlock("Sub goo()" + vbCrLf + "SyncLock me" + vbCrLf + "bar()" + vbCrLf + "end synclock" + vbCrLf + "end Sub", "Sub goo()" + vbCrLf + " SyncLock me" + vbCrLf + " bar()" + vbCrLf + " end synclock" + vbCrLf + "end Sub" + vbCrLf) End Sub <Fact(), WorkItem(546397, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546397")> Public Sub TestEventStatements() TestNormalizeBlock( <code> module m1 private withevents x as y private sub myhandler() Handles y.e1 end sub end module </code>.Value, _ <code>module m1 private withevents x as y private sub myhandler() Handles y.e1 end sub end module </code>.Value) End Sub <Fact(), WorkItem(546397, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546397")> Public Sub TestAssignmentStatements() TestNormalizeBlock("module m1" + vbCrLf + "sub s1()" + vbCrLf + "Dim x as Integer()" + vbCrLf + "x(2)=23" + vbCrLf + "Dim s as string=""boo""&""ya""" + vbCrLf + "end sub" + vbCrLf + "end module", _ _ "module m1" + vbCrLf + vbCrLf + " sub s1()" + vbCrLf + " Dim x as Integer()" + vbCrLf + " x(2) = 23" + vbCrLf + " Dim s as string = ""boo"" & ""ya""" + vbCrLf + " end sub" + vbCrLf + "end module" + vbCrLf) TestNormalizeBlock("module m1" + vbCrLf + vbCrLf + "sub s1()" + vbCrLf + "Dim x as Integer" + vbCrLf + "x^=23" + vbCrLf + "x*=23" + vbCrLf + "x/=23" + vbCrLf + "x\=23" + vbCrLf + "x+=23" + vbCrLf + "x-=23" + vbCrLf + "x<<=23" + vbCrLf + "x>>=23" + vbCrLf + "Dim y as string" + vbCrLf + "y &=""a""" + vbCrLf + "end sub" + vbCrLf + "end module", _ _ "module m1" + vbCrLf + vbCrLf + " sub s1()" + vbCrLf + " Dim x as Integer" + vbCrLf + " x ^= 23" + vbCrLf + " x *= 23" + vbCrLf + " x /= 23" + vbCrLf + " x \= 23" + vbCrLf + " x += 23" + vbCrLf + " x -= 23" + vbCrLf + " x <<= 23" + vbCrLf + " x >>= 23" + vbCrLf + " Dim y as string" + vbCrLf + " y &= ""a""" + vbCrLf + " end sub" + vbCrLf + "end module" + vbCrLf) TestNormalizeBlock("module m1" + vbCrLf + "sub s1()" + vbCrLf + "Dim s1 As String=""a""" + vbCrLf + "Dim s2 As String=""b""" + vbCrLf + "Mid$(s1,3,3)=s2" + vbCrLf + "end sub" + vbCrLf + "end module", _ _ "module m1" + vbCrLf + vbCrLf + " sub s1()" + vbCrLf + " Dim s1 As String = ""a""" + vbCrLf + " Dim s2 As String = ""b""" + vbCrLf + " Mid$(s1, 3, 3) = s2" + vbCrLf + " end sub" + vbCrLf + "end module" + vbCrLf) End Sub <Fact(), WorkItem(546397, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546397")> Public Sub TestCallStatements() TestNormalizeBlock("module m1" + vbCrLf + "sub s2()" + vbCrLf + "s1 ( 23 )" + vbCrLf + "s1 ( p1:=23 , p2:=23)" + vbCrLf + "end sub" + vbCrLf + "end module", _ _ "module m1" + vbCrLf + vbCrLf + " sub s2()" + vbCrLf + " s1(23)" + vbCrLf + " s1(p1:=23, p2:=23)" + vbCrLf + " end sub" + vbCrLf + "end module" + vbCrLf) TestNormalizeBlock("module m1" + vbCrLf + vbCrLf + "sub s2 ( Of T ) ( optional x As T=nothing )" + vbCrLf + "N1.M2.S2 ( ) " + vbCrLf + "end sub" + vbCrLf + "end module", _ _ "module m1" + vbCrLf + vbCrLf + " sub s2(Of T)(optional x As T = nothing)" + vbCrLf + " N1.M2.S2()" + vbCrLf + " end sub" + vbCrLf + "end module" + vbCrLf) End Sub <Fact()> Public Sub TestNewStatements() TestNormalizeBlock("Dim zipState=New With { Key .ZipCode=98112, .State=""WA"" }", "Dim zipState = New With {Key .ZipCode = 98112, .State = ""WA""}" + vbCrLf) End Sub <Fact(), WorkItem(546397, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546397"), WorkItem(546514, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546514")> Public Sub TestXmlAccessStatements() TestNormalizeBlock("Imports <xmlns:db=""http://example.org/database"">" + vbCrLf + "Module Test" + vbCrLf + "Sub Main ( )" + vbCrLf + "Dim x=<db:customer><db:Name>Bob</db:Name></db:customer>" + vbCrLf + "Console . WriteLine ( x .< db:Name > )" + vbCrLf + "End Sub" + vbCrLf + "End Module", _ "Imports <xmlns:db=""http://example.org/database"">" + vbCrLf + "" + vbCrLf + "Module Test" + vbCrLf + vbCrLf + " Sub Main()" + vbCrLf + " Dim x = <db:customer><db:Name>Bob</db:Name></db:customer>" + vbCrLf + " Console.WriteLine(x.<db:Name>)" + vbCrLf + " End Sub" + vbCrLf + "End Module" + vbCrLf) End Sub <Fact(), WorkItem(546397, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546397")> Public Sub TestNamespaceStatements() TestNormalizeBlock("Imports I1.I2" + vbCrLf + "Namespace N1" + vbCrLf + "Namespace N2.N3" + vbCrLf + "end Namespace" + vbCrLf + "end Namespace", _ _ "Imports I1.I2" + vbCrLf + "" + vbCrLf + "Namespace N1" + vbCrLf + " Namespace N2.N3" + vbCrLf + " end Namespace" + vbCrLf + "end Namespace" + vbCrLf) End Sub <Fact(), WorkItem(546397, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546397")> Public Sub TestNullableStatements() TestNormalizeBlock( <code> module m1 Dim x as Integer?=nothing end module</code>.Value, _ _ <code>module m1 Dim x as Integer? = nothing end module </code>.Value) End Sub <Fact(), WorkItem(546397, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546397")> Public Sub TestInterfaceStatements() TestNormalizeBlock("namespace N1" + vbCrLf + "Interface I1" + vbCrLf + "public Function F1() As Object" + vbCrLf + "End Interface" + vbCrLf + "Interface I2" + vbCrLf + "Function F2() As Integer" + vbCrLf + "End Interface" + vbCrLf + "Structure S1" + vbCrLf + "Implements I1,I2" + vbCrLf + "public Function F1() As Object" + vbCrLf + "Dim x as Integer=23" + vbCrLf + "return x" + vbCrLf + "end function" + vbCrLf + "End Structure" + vbCrLf + "End Namespace", _ _ "namespace N1" + vbCrLf + vbCrLf + " Interface I1" + vbCrLf + vbCrLf + " public Function F1() As Object" + vbCrLf + vbCrLf + " End Interface" + vbCrLf + vbCrLf + " Interface I2" + vbCrLf + vbCrLf + " Function F2() As Integer" + vbCrLf + vbCrLf + " End Interface" + vbCrLf + vbCrLf + " Structure S1" + vbCrLf + " Implements I1, I2" + vbCrLf + vbCrLf + " public Function F1() As Object" + vbCrLf + " Dim x as Integer = 23" + vbCrLf + " return x" + vbCrLf + " end function" + vbCrLf + " End Structure" + vbCrLf + "End Namespace" + vbCrLf) End Sub <Fact(), WorkItem(546397, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546397")> Public Sub TestEnumStatements() TestNormalizeBlock("Module M1" + vbCrLf + vbCrLf + "ENUM E1 as long" + vbCrLf + " goo=23" + vbCrLf + "bar " + vbCrLf + "boo=goo" + vbCrLf + "booya=1.4" + vbCrLf + "end enum" + vbCrLf + "end MODule", _ _ "Module M1" + vbCrLf + vbCrLf + " ENUM E1 as long" + vbCrLf + " goo = 23" + vbCrLf + " bar" + vbCrLf + " boo = goo" + vbCrLf + " booya = 1.4" + vbCrLf + " end enum" + vbCrLf + "end MODule" + vbCrLf) TestNormalizeBlock("class c1" + vbCrLf + "ENUM E1 as long" + vbCrLf + " goo=23" + vbCrLf + "bar " + vbCrLf + "boo=goo" + vbCrLf + "booya=1.4" + vbCrLf + "end enum" + vbCrLf + "end class", _ _ "class c1" + vbCrLf + vbCrLf + " ENUM E1 as long" + vbCrLf + " goo = 23" + vbCrLf + " bar" + vbCrLf + " boo = goo" + vbCrLf + " booya = 1.4" + vbCrLf + " end enum" + vbCrLf + "end class" + vbCrLf) TestNormalizeBlock("public class c1" + vbCrLf + vbCrLf + "ENUM E1 as long" + vbCrLf + " goo=23" + vbCrLf + "bar " + vbCrLf + "boo=goo" + vbCrLf + "booya=1.4" + vbCrLf + "end enum" + vbCrLf + "end class", _ _ "public class c1" + vbCrLf + vbCrLf + " ENUM E1 as long" + vbCrLf + " goo = 23" + vbCrLf + " bar" + vbCrLf + " boo = goo" + vbCrLf + " booya = 1.4" + vbCrLf + " end enum" + vbCrLf + "end class" + vbCrLf) TestNormalizeBlock("class c1" + vbCrLf + "public ENUM E1 as long" + vbCrLf + " goo=23" + vbCrLf + "bar " + vbCrLf + "boo=goo" + vbCrLf + "booya=1.4" + vbCrLf + "end enum" + vbCrLf + "end class", _ _ "class c1" + vbCrLf + vbCrLf + " public ENUM E1 as long" + vbCrLf + " goo = 23" + vbCrLf + " bar" + vbCrLf + " boo = goo" + vbCrLf + " booya = 1.4" + vbCrLf + " end enum" + vbCrLf + "end class" + vbCrLf) End Sub <Fact(), WorkItem(546397, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546397")> Public Sub TestDelegateStatements() TestNormalizeBlock("Module M1" + vbCrLf + "Dim x=Function( x ,y )x+y" + vbCrLf + "Dim y As Func ( Of Integer ,Integer ,Integer )=x" + vbCrLf + "end MODule", _ _ "Module M1" + vbCrLf + vbCrLf + " Dim x = Function(x, y) x + y" + vbCrLf + vbCrLf + " Dim y As Func(Of Integer, Integer, Integer) = x" + vbCrLf + "end MODule" + vbCrLf) TestNormalizeBlock("Module M1" + vbCrLf + "Dim x=Function( x ,y )" + vbCrLf + "return x+y" + vbCrLf + "end function" + vbCrLf + "Dim y As Func ( Of Integer ,Integer ,Integer )=x" + vbCrLf + "end MODule", _ _ "Module M1" + vbCrLf + vbCrLf + " Dim x = Function(x, y)" + vbCrLf + " return x + y" + vbCrLf + " end function" + vbCrLf + vbCrLf + " Dim y As Func(Of Integer, Integer, Integer) = x" + vbCrLf + "end MODule" + vbCrLf) TestNormalizeBlock("Module M1" + vbCrLf + "Dim x=Sub( x ,y )" + vbCrLf + "dim x as integer" + vbCrLf + "end sub" + vbCrLf + "Dim y As Action ( Of Integer ,Integer)=x" + vbCrLf + "end MODule", _ _ "Module M1" + vbCrLf + vbCrLf + " Dim x = Sub(x, y)" + vbCrLf + " dim x as integer" + vbCrLf + " end sub" + vbCrLf + vbCrLf + " Dim y As Action(Of Integer, Integer) = x" + vbCrLf + "end MODule" + vbCrLf) End Sub <Fact(), WorkItem(546397, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546397")> Public Sub TestSelectStatements() TestNormalizeBlock(" Module M1" + vbCrLf + "sub s1()" + vbCrLf + "select case goo" + vbCrLf + "case 23 " + vbCrLf + "return goo " + vbCrLf + "case 42,11 " + vbCrLf + "return goo " + vbCrLf + "case > 100 " + vbCrLf + "return goo " + vbCrLf + "case 200 to 300 " + vbCrLf + "return goo " + vbCrLf + "case 12," + vbCrLf + "13" + vbCrLf + "return goo " + vbCrLf + "case else" + vbCrLf + "return goo " + vbCrLf + "end select " + vbCrLf + "end sub " + vbCrLf + "end module ", _ _ "Module M1" + vbCrLf + vbCrLf + " sub s1()" + vbCrLf + " select case goo" + vbCrLf + " case 23" + vbCrLf + " return goo" + vbCrLf + " case 42, 11" + vbCrLf + " return goo" + vbCrLf + " case > 100" + vbCrLf + " return goo" + vbCrLf + " case 200 to 300" + vbCrLf + " return goo" + vbCrLf + " case 12, 13" + vbCrLf + " return goo" + vbCrLf + " case else" + vbCrLf + " return goo" + vbCrLf + " end select" + vbCrLf + " end sub" + vbCrLf + "end module" + vbCrLf) End Sub <Fact(), WorkItem(546397, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546397")> Public Sub TestIfStatement() ' expressions TestNormalizeStatement("a", "a") ' if TestNormalizeStatement("if a then b", "if a then b") TestNormalizeStatement("if a then b else c", "if a then b else c") TestNormalizeStatement("if a then b else if c then d else e", "if a then b else if c then d else e") TestNormalizeStatement("if a then b else if c then d else e", "if a then b else if c then d else e") TestNormalizeStatement("if " + vbTab + " a then b else if c then d else e", "if a then b else if c then d else e") TestNormalizeStatement("if a then" + vbCrLf + "b" + vbCrLf + "end if", "if a then" + vbCrLf + " b" + vbCrLf + "end if") TestNormalizeStatement("if a then" + vbCrLf + vbCrLf + vbCrLf + "b" + vbCrLf + "end if", "if a then" + vbCrLf + " b" + vbCrLf + "end if") TestNormalizeStatement("if a then" + vbCrLf + "if a then" + vbCrLf + "b" + vbCrLf + "end if" + vbCrLf + "else" + vbCrLf + "b" + vbCrLf + "end if", "if a then" + vbCrLf + " if a then" + vbCrLf + " b" + vbCrLf + " end if" + vbCrLf + "else" + vbCrLf + " b" + vbCrLf + "end if") ' line continuation trivia will be removed TestNormalizeStatement("if a then _" + vbCrLf + "b _" + vbCrLf + "else c", "if a then b else c") TestNormalizeStatement("if a then:b:end if", "if a then : b : end if") Dim generatedLeftLiteralToken = SyntaxFactory.IntegerLiteralToken("42", LiteralBase.Decimal, TypeCharacter.None, 42) Dim generatedRightLiteralToken = SyntaxFactory.IntegerLiteralToken("23", LiteralBase.Decimal, TypeCharacter.None, 23) Dim generatedLeftLiteralExpression = SyntaxFactory.LiteralExpression(SyntaxKind.NumericLiteralExpression, generatedLeftLiteralToken) Dim generatedRightLiteralExpression = SyntaxFactory.LiteralExpression(SyntaxKind.NumericLiteralExpression, generatedRightLiteralToken) Dim generatedRedLiteralExpression = SyntaxFactory.GreaterThanExpression(generatedLeftLiteralExpression, SyntaxFactory.Token(SyntaxKind.GreaterThanToken), generatedRightLiteralExpression) Dim generatedRedIfStatement = SyntaxFactory.IfStatement(SyntaxFactory.Token(SyntaxKind.IfKeyword), generatedRedLiteralExpression, SyntaxFactory.Token(SyntaxKind.ThenKeyword, "THeN")) Dim expression As ExpressionSyntax = SyntaxFactory.StringLiteralExpression(SyntaxFactory.StringLiteralToken("goo", "goo")) Dim callexpression = SyntaxFactory.InvocationExpression(expression:=expression) Dim callstatement = SyntaxFactory.CallStatement(SyntaxFactory.Token(SyntaxKind.CallKeyword), callexpression) Dim stmtlist = SyntaxFactory.List(Of StatementSyntax)({CType(callstatement, StatementSyntax), CType(callstatement, StatementSyntax)}) Dim generatedEndIfStatement = SyntaxFactory.EndIfStatement(SyntaxFactory.Token(SyntaxKind.EndKeyword), SyntaxFactory.Token(SyntaxKind.IfKeyword)) Dim mlib = SyntaxFactory.MultiLineIfBlock(generatedRedIfStatement, stmtlist, Nothing, Nothing, generatedEndIfStatement) Dim str = mlib.NormalizeWhitespace(" ").ToFullString() Assert.Equal("If 42 > 23 THeN" + vbCrLf + " Call goo" + vbCrLf + " Call goo" + vbCrLf + "End If", str) End Sub <Fact(), WorkItem(546397, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546397")> Public Sub TestLoopStatements() TestNormalizeStatement("while a<b" + vbCrLf + "c " + vbCrLf + "end while", "while a < b" + vbCrLf + " c" + vbCrLf + "end while") TestNormalizeStatement("DO until a(2)<>12" + vbCrLf + "Dim x = 12" + vbCrLf + " loop", _ _ "DO until a(2) <> 12" + vbCrLf + " Dim x = 12" + vbCrLf + "loop") TestNormalizeStatement("DO while a(2)<>12" + vbCrLf + "Dim x = 12" + vbCrLf + " loop", _ _ "DO while a(2) <> 12" + vbCrLf + " Dim x = 12" + vbCrLf + "loop") TestNormalizeStatement("DO " + vbCrLf + "Dim x = 12" + vbCrLf + " loop", _ _ "DO" + vbCrLf + " Dim x = 12" + vbCrLf + "loop") TestNormalizeStatement("DO " + vbCrLf + "Dim x = 12" + vbCrLf + " loop until a ( 2 ) <> 12 ", _ _ "DO" + vbCrLf + " Dim x = 12" + vbCrLf + "loop until a(2) <> 12") TestNormalizeStatement("For Each i In x" + vbCrLf + "Dim x = 12" + vbCrLf + " next", _ _ "For Each i In x" + vbCrLf + " Dim x = 12" + vbCrLf + "next") TestNormalizeStatement("For Each i In x" + vbCrLf + "For Each j In x" + vbCrLf + "Dim x = 12" + vbCrLf + " next j,i", _ _ "For Each i In x" + vbCrLf + " For Each j In x" + vbCrLf + " Dim x = 12" + vbCrLf + "next j, i") End Sub <Fact(), WorkItem(546397, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546397")> Public Sub TestExceptionsStatements() TestNormalizeStatement(" try" + vbCrLf + "dim x =23" + vbCrLf + "Catch e1 As Exception When 1>2" + vbCrLf + "dim x =23" + vbCrLf + "Catch" + vbCrLf + "dim x =23" + vbCrLf + "finally" + vbCrLf + "dim x =23" + vbCrLf + " end try", _ _ "try" + vbCrLf + " dim x = 23" + vbCrLf + "Catch e1 As Exception When 1 > 2" + vbCrLf + " dim x = 23" + vbCrLf + "Catch" + vbCrLf + " dim x = 23" + vbCrLf + "finally" + vbCrLf + " dim x = 23" + vbCrLf + "end try") End Sub <Fact(), WorkItem(546397, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546397")> Public Sub TestUsingStatements() TestNormalizeStatement(" Using r1 As R = New R ( ) , r2 As R = New R( )" + vbCrLf + "dim x =23" + vbCrLf + "end using", _ _ "Using r1 As R = New R(), r2 As R = New R()" + vbCrLf + " dim x = 23" + vbCrLf + "end using") End Sub <Fact()> Public Sub TestQueryExpressions() TestNormalizeStatement(" Dim waCusts = _" + vbCrLf + "From cust As Customer In Customers _" + vbCrLf + "Where cust.State = ""WA""", _ _ "Dim waCusts = From cust As Customer In Customers Where cust.State = ""WA""") End Sub <Fact(), WorkItem(546397, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546397")> Public Sub TestDefaultCasingForKeywords() Dim expected = "Module m1" + vbCrLf + vbCrLf + " Dim x = Function(x, y) x + y" + vbCrLf + vbCrLf + " Dim y As func(Of Integer, Integer, Integer) = x" + vbCrLf + "End Module" + vbCrLf Dim node As CompilationUnitSyntax = SyntaxFactory.ParseCompilationUnit(expected.ToLowerInvariant) Dim actual = node.NormalizeWhitespace(indentation:=" ", useDefaultCasing:=True).ToFullString() Assert.Equal(expected, actual) End Sub <Fact(), WorkItem(546397, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546397")> Public Sub TestComment() ' trailing whitespace will be aligned to the indent level (see second comment) ' when determining if there should be a separator between tokens, the current algorithm does not check if a token comes out ' of structured trivia. Because of that there is now a space at the end of structured trivia before the next token ' whitespace before comments get reduced to one (see comment after code), whitespace in trivia is maintained (see same comment) ' xml doc comments somehow contain \n in the XmlTextLiterals ... will not spend time to work around Dim input = "Module m1" + vbCrLf + " ' a nice comment" + vbCrLf + " ''' even more comments" + vbCrLf + "' and more comments " + vbCrLf + "#if false " + vbCrLf + " whatever? " + vbCrLf + "#end if" + vbCrLf + "' and more comments" + vbCrLf + " ''' structured trivia before code" + vbCrLf + "Dim x = Function(x, y) x + y ' trivia after code" + vbCrLf + "End Module" Dim expected = "Module m1" + vbCrLf + vbCrLf + " ' a nice comment" + vbCrLf + " ''' even more comments" + vbCrLf + vbCrLf + " ' and more comments " + vbCrLf + "#if false" + vbCrLf + " whatever? " + vbCrLf + "#end if" + vbCrLf + " ' and more comments" + vbCrLf + " ''' structured trivia before code" + vbCrLf + " Dim x = Function(x, y) x + y ' trivia after code" + vbCrLf + "End Module" + vbCrLf Dim node As CompilationUnitSyntax = SyntaxFactory.ParseCompilationUnit(input) Dim actual = node.NormalizeWhitespace(" ").ToFullString() Assert.Equal(expected, actual) End Sub <Fact(), WorkItem(546397, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546397")> Public Sub TestMultilineLambdaFunctionsAsParameter() ' trailing whitespace will be aligned to the indent level (see second comment) ' when determining if there should be a separator between tokens, the current algorithm does not check if a token comes out ' of structured trivia. Because of that there is now a space at the end of structured trivia before the next token ' whitespace before comments get reduced to one (see comment after code), whitespace in trivia is maintained (see same comment) ' xml doc comments somehow contain \n in the XmlTextLiterals ... will not spend time to work around Dim input = "Module m1" + vbCrLf + "Sub Main(args As String())" + vbCrLf + "Sub1(Function(p As Integer)" + vbCrLf + "Sub2()" + vbCrLf + "End Function)" + vbCrLf + "End Sub" + vbCrLf + "End Module" Dim expected = "Module m1" + vbCrLf + vbCrLf + " Sub Main(args As String())" + vbCrLf + " Sub1(Function(p As Integer)" + vbCrLf + " Sub2()" + vbCrLf + " End Function)" + vbCrLf + " End Sub" + vbCrLf + "End Module" + vbCrLf Dim node As CompilationUnitSyntax = SyntaxFactory.ParseCompilationUnit(input) Dim actual = node.NormalizeWhitespace(" ").ToFullString() Assert.Equal(expected, actual) End Sub <Fact(), WorkItem(546397, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546397")> Public Sub TestProperty() Dim input = <text>Property p As Integer Get End Get Set ( value As Integer ) End Set End Property</text>.Value.Replace(vbLf, vbCrLf) Dim expected = <text>Property p As Integer Get End Get Set(value As Integer) End Set End Property </text>.Value.Replace(vbLf, vbCrLf) TestNormalizeBlock(input, expected) End Sub Private Sub TestNormalizeStatement(text As String, expected As String) Dim node As StatementSyntax = SyntaxFactory.ParseExecutableStatement(text) Dim actual = node.NormalizeWhitespace(" ").ToFullString() Assert.Equal(expected, actual) End Sub Private Sub TestNormalizeBlock(text As String, expected As String) Dim node As CompilationUnitSyntax = SyntaxFactory.ParseCompilationUnit(text) Dim actual = node.NormalizeWhitespace(" ").ToFullString() expected = expected.Replace(vbCrLf, vbLf).Replace(vbLf, vbCrLf) ' in case tests use XML literals Assert.Equal(expected, actual) End Sub <Fact(), WorkItem(546397, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546397")> Public Sub TestStructuredTriviaAndAttributes() Dim source = "Module m1" + vbCrLf + " '''<x>...</x>" + vbCrLf + " <goo()>" + vbCrLf + " sub a()" + vbCrLf + " end sub" + vbCrLf + "End Module" + vbCrLf + vbCrLf Dim expected = "Module m1" + vbCrLf + vbCrLf + " '''<x>...</x>" + vbCrLf + " <goo()>" + vbCrLf + " sub a()" + vbCrLf + " end sub" + vbCrLf + "End Module" + vbCrLf Dim node As CompilationUnitSyntax = SyntaxFactory.ParseCompilationUnit(source) Dim actual = node.NormalizeWhitespace(indentation:=" ", useDefaultCasing:=False).ToFullString() Assert.Equal(expected, actual) End Sub <Fact(), WorkItem(531607, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531607")> Public Sub TestNestedStructuredTrivia() Dim trivia = SyntaxFactory.TriviaList( SyntaxFactory.Trivia( SyntaxFactory.ConstDirectiveTrivia( "constant", SyntaxFactory.LiteralExpression( SyntaxKind.NumericLiteralExpression, SyntaxFactory.Literal(1).WithTrailingTrivia(SyntaxFactory.Trivia(SyntaxFactory.SkippedTokensTrivia(SyntaxFactory.TokenList(SyntaxFactory.Literal("A"c))))))))) Dim expected = "#Const constant = 1 ""A""c" Dim actual = trivia.NormalizeWhitespace(indentation:=" ", elasticTrivia:=False, useDefaultCasing:=False).ToFullString() Assert.Equal(expected, actual) End Sub <Fact()> Public Sub TestCrefAttribute() Dim source = "''' <summary>" + vbCrLf + "''' <see cref = """"/>" + vbCrLf + "''' <see cref =""""/>" + vbCrLf + "''' <see cref= """"/>" + vbCrLf + "''' <see cref=""""/>" + vbCrLf + "''' <see cref = ""1""/>" + vbCrLf + "''' <see cref =""a""/>" + vbCrLf + "''' <see cref= ""Integer()""/>" + vbCrLf + "''' <see cref = ""a()""/>" + vbCrLf + "''' </summary>" + vbCrLf + "Module Program" + vbCrLf + "End Module" + vbCrLf Dim expected = "''' <summary>" + vbCrLf + "''' <see cref=""""/> " + vbCrLf + "''' <see cref=""""/> " + vbCrLf + "''' <see cref=""""/> " + vbCrLf + "''' <see cref=""""/> " + vbCrLf + "''' <see cref=""1""/> " + vbCrLf + "''' <see cref=""a""/> " + vbCrLf + "''' <see cref=""Integer()""/> " + vbCrLf + "''' <see cref=""a()""/> " + vbCrLf + "''' </summary>" + vbCrLf + "Module Program" + vbCrLf + "End Module" + vbCrLf Dim node As CompilationUnitSyntax = SyntaxFactory.ParseCompilationUnit(source) Dim actual = node.NormalizeWhitespace(indentation:=" ", useDefaultCasing:=False).ToFullString() Assert.Equal(expected, actual) End Sub <Fact()> Public Sub TestNameAttribute() Dim source = "''' <summary>" + vbCrLf + "''' <paramref name = """"/>" + vbCrLf + "''' <paramref name =""""/>" + vbCrLf + "''' <paramref name= """"/>" + vbCrLf + "''' <paramref name=""""/>" + vbCrLf + "''' <paramref name = ""1""/>" + vbCrLf + "''' <paramref name =""a""/>" + vbCrLf + "''' <paramref name= ""Integer()""/>" + vbCrLf + "''' <paramref name = ""a()""/>" + vbCrLf + "''' </summary>" + vbCrLf + "Module Program" + vbCrLf + "End Module" + vbCrLf Dim expected = "''' <summary>" + vbCrLf + "''' <paramref name=""""/> " + vbCrLf + "''' <paramref name=""""/> " + vbCrLf + "''' <paramref name=""""/> " + vbCrLf + "''' <paramref name=""""/> " + vbCrLf + "''' <paramref name=""1""/> " + vbCrLf + "''' <paramref name=""a""/> " + vbCrLf + "''' <paramref name=""Integer()""/> " + vbCrLf + "''' <paramref name=""a()""/> " + vbCrLf + "''' </summary>" + vbCrLf + "Module Program" + vbCrLf + "End Module" + vbCrLf Dim node As CompilationUnitSyntax = SyntaxFactory.ParseCompilationUnit(source) Dim actual = node.NormalizeWhitespace(indentation:=" ", useDefaultCasing:=False).ToFullString() Assert.Equal(expected, actual) End Sub <Fact> Public Sub TestEnableWarningDirective() Dim text = <![CDATA[ # enable warning[BC000],Bc123, BC456,_789' comment # enable warning # enable warning ,]]>.Value.Replace(vbLf, vbCrLf) Dim root = Parse(text).GetRoot() Dim normalizedRoot = root.NormalizeWhitespace(indentation:=" ", elasticTrivia:=True, useDefaultCasing:=True) Dim expected = <![CDATA[#Enable Warning [BC000], Bc123, BC456, _789 ' comment #Enable Warning #Enable Warning , ]]>.Value.Replace(vbLf, vbCrLf) Assert.Equal(expected, normalizedRoot.ToFullString()) End Sub <Fact> Public Sub TestDisableWarningDirective() Dim text = <![CDATA[Module Program # disable warning Sub Main() #disable warning bc123, Bc456,BC789 End Sub # disable warning[BC123], ' Comment End Module]]>.Value.Replace(vbLf, vbCrLf) Dim root = Parse(text).GetRoot() Dim normalizedRoot = root.NormalizeWhitespace(indentation:=" ", elasticTrivia:=True, useDefaultCasing:=True) Dim expected = <![CDATA[Module Program #Disable Warning Sub Main() #Disable Warning bc123, Bc456, BC789 End Sub #Disable Warning [BC123], ' Comment End Module ]]>.Value.Replace(vbLf, vbCrLf) Assert.Equal(expected, normalizedRoot.ToFullString()) End Sub <Fact> Public Sub TestNormalizeEOL() Dim code = "Class C" & vbCrLf & "End Class" Dim expected = "Class C" & vbLf & "End Class" & vbLf Dim actual = SyntaxFactory.ParseCompilationUnit(code).NormalizeWhitespace(" ", eol:=vbLf).ToFullString() Assert.Equal(expected, actual) End Sub <Fact> Public Sub TestNormalizeTabs() Dim code = "Class C" & vbCrLf & "Sub M()" & vbCrLf & "End Sub" & vbCrLf & "End Class" Dim expected = "Class C" & vbCrLf & vbCrLf & vbTab & "Sub M()" & vbCrLf & vbTab & "End Sub" & vbCrLf & "End Class" & vbCrLf Dim actual = SyntaxFactory.ParseCompilationUnit(code).NormalizeWhitespace(vbTab).ToFullString() Assert.Equal(expected, actual) End Sub End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System Imports System.Collections.Generic Imports System.Linq Imports System.Text Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities Imports Xunit Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests Public Class SyntaxNormalizerTests <WorkItem(546397, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546397")> <ConditionalFact(GetType(WindowsOnly))> Public Sub TestAllInVB() Dim allInVB As String = TestResource.AllInOneVisualBasicCode Dim expected As String = TestResource.AllInOneVisualBasicBaseline Dim node As CompilationUnitSyntax = SyntaxFactory.ParseCompilationUnit(allInVB) Dim actual = node.NormalizeWhitespace(" ").ToFullString() Assert.Equal(expected, actual) End Sub <Fact()> Public Sub TestNormalizeExpressions() TestNormalizeExpression("+1", "+1") TestNormalizeExpression("+a", "+a") TestNormalizeExpression("-a", "-a") TestNormalizeExpression("a", "a") TestNormalizeExpression("a+b", "a + b") TestNormalizeExpression("a-b", "a - b") TestNormalizeExpression("a*b", "a * b") TestNormalizeExpression("a/b", "a / b") TestNormalizeExpression("a mod b", "a mod b") TestNormalizeExpression("a xor b", "a xor b") TestNormalizeExpression("a or b", "a or b") TestNormalizeExpression("a and b", "a and b") TestNormalizeExpression("a orelse b", "a orelse b") TestNormalizeExpression("a andalso b", "a andalso b") TestNormalizeExpression("a<b", "a < b") TestNormalizeExpression("a<=b", "a <= b") TestNormalizeExpression("a>b", "a > b") TestNormalizeExpression("a>=b", "a >= b") TestNormalizeExpression("a=b", "a = b") TestNormalizeExpression("a<>b", "a <> b") TestNormalizeExpression("a<<b", "a << b") TestNormalizeExpression("a>>b", "a >> b") TestNormalizeExpression("(a+b)", "(a + b)") TestNormalizeExpression("((a)+(b))", "((a) + (b))") TestNormalizeExpression("(a)", "(a)") TestNormalizeExpression("(a)(b)", "(a)(b)") TestNormalizeExpression("m()", "m()") TestNormalizeExpression("m(a)", "m(a)") TestNormalizeExpression("m(a,b)", "m(a, b)") TestNormalizeExpression("m(a,b,c)", "m(a, b, c)") TestNormalizeExpression("m(a,b(c,d))", "m(a, b(c, d))") TestNormalizeExpression("m( , ,, )", "m(,,,)") TestNormalizeExpression("a(b(c(0)))", "a(b(c(0)))") TestNormalizeExpression("if(a,b,c)", "if(a, b, c)") TestNormalizeExpression("a().b().c()", "a().b().c()") TestNormalizeExpression("""aM5b"" Like ""a[L-P]#[!c-e]a?""", """aM5b"" Like ""a[L-P]#[!c-e]a?""") End Sub Private Sub TestNormalizeExpression(text As String, expected As String) Dim node = SyntaxFactory.ParseExpression(text) Dim actual = node.NormalizeWhitespace(" ").ToFullString() Assert.Equal(expected, actual) End Sub <Fact()> Public Sub TestTrailingComment() TestNormalizeBlock("Dim goo as Bar ' it is a Bar", "Dim goo as Bar ' it is a Bar" + vbCrLf) End Sub <Fact()> Public Sub TestOptionStatements() TestNormalizeBlock("Option Explicit Off", "Option Explicit Off" + vbCrLf) End Sub <Fact()> Public Sub TestImportsStatements() TestNormalizeBlock("Imports System", "Imports System" + vbCrLf) TestNormalizeBlock("Imports System.Goo.Bar", "Imports System.Goo.Bar" + vbCrLf) TestNormalizeBlock("Imports T2=System.String", "Imports T2 = System.String" + vbCrLf) TestNormalizeBlock("Imports <xmlns:db=""http://example.org/database"">", "Imports <xmlns:db=""http://example.org/database"">" + vbCrLf) End Sub <Fact(), WorkItem(546397, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546397")> Public Sub TestLabelStatements() TestNormalizeStatement("while a<b" + vbCrLf + "goo:" + vbCrLf + "c" + vbCrLf + "end while", "while a < b" + vbCrLf + "goo:" + vbCrLf + " c" + vbCrLf + "end while") End Sub <Fact(), WorkItem(546397, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546397")> Public Sub TestMethodStatements() TestNormalizeBlock("Sub goo()" + vbCrLf + "a()" + vbCrLf + "end Sub", "Sub goo()" + vbCrLf + " a()" + vbCrLf + "end Sub" + vbCrLf) TestNormalizeBlock("Function goo() as Integer" + vbCrLf + "return 23" + vbCrLf + "end function", "Function goo() as Integer" + vbCrLf + " return 23" + vbCrLf + "end function" + vbCrLf) TestNormalizeBlock("Function goo( x as System.Int32,[Char] as Integer) as Integer" + vbCrLf + "return 23" + vbCrLf + "end function", "Function goo(x as System.Int32, [Char] as Integer) as Integer" + vbCrLf + " return 23" + vbCrLf + "end function" + vbCrLf) TestNormalizeBlock("Sub goo()" + vbCrLf + "Dim a ( ) ( )=New Integer ( ) ( ) ( ){ }" + vbCrLf + "end Sub", "Sub goo()" + vbCrLf + " Dim a()() = New Integer()()() {}" + vbCrLf + "end Sub" + vbCrLf) End Sub <Fact(), WorkItem(546397, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546397")> Public Sub TestWithStatements() TestNormalizeBlock( <code> Sub goo() with goo .bar() end with end Sub</code>.Value, _ _ <code>Sub goo() with goo .bar() end with end Sub </code>.Value) End Sub <Fact(), WorkItem(546397, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546397")> Public Sub TestSyncLockStatements() TestNormalizeBlock("Sub goo()" + vbCrLf + "SyncLock me" + vbCrLf + "bar()" + vbCrLf + "end synclock" + vbCrLf + "end Sub", "Sub goo()" + vbCrLf + " SyncLock me" + vbCrLf + " bar()" + vbCrLf + " end synclock" + vbCrLf + "end Sub" + vbCrLf) End Sub <Fact(), WorkItem(546397, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546397")> Public Sub TestEventStatements() TestNormalizeBlock( <code> module m1 private withevents x as y private sub myhandler() Handles y.e1 end sub end module </code>.Value, _ <code>module m1 private withevents x as y private sub myhandler() Handles y.e1 end sub end module </code>.Value) End Sub <Fact(), WorkItem(546397, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546397")> Public Sub TestAssignmentStatements() TestNormalizeBlock("module m1" + vbCrLf + "sub s1()" + vbCrLf + "Dim x as Integer()" + vbCrLf + "x(2)=23" + vbCrLf + "Dim s as string=""boo""&""ya""" + vbCrLf + "end sub" + vbCrLf + "end module", _ _ "module m1" + vbCrLf + vbCrLf + " sub s1()" + vbCrLf + " Dim x as Integer()" + vbCrLf + " x(2) = 23" + vbCrLf + " Dim s as string = ""boo"" & ""ya""" + vbCrLf + " end sub" + vbCrLf + "end module" + vbCrLf) TestNormalizeBlock("module m1" + vbCrLf + vbCrLf + "sub s1()" + vbCrLf + "Dim x as Integer" + vbCrLf + "x^=23" + vbCrLf + "x*=23" + vbCrLf + "x/=23" + vbCrLf + "x\=23" + vbCrLf + "x+=23" + vbCrLf + "x-=23" + vbCrLf + "x<<=23" + vbCrLf + "x>>=23" + vbCrLf + "Dim y as string" + vbCrLf + "y &=""a""" + vbCrLf + "end sub" + vbCrLf + "end module", _ _ "module m1" + vbCrLf + vbCrLf + " sub s1()" + vbCrLf + " Dim x as Integer" + vbCrLf + " x ^= 23" + vbCrLf + " x *= 23" + vbCrLf + " x /= 23" + vbCrLf + " x \= 23" + vbCrLf + " x += 23" + vbCrLf + " x -= 23" + vbCrLf + " x <<= 23" + vbCrLf + " x >>= 23" + vbCrLf + " Dim y as string" + vbCrLf + " y &= ""a""" + vbCrLf + " end sub" + vbCrLf + "end module" + vbCrLf) TestNormalizeBlock("module m1" + vbCrLf + "sub s1()" + vbCrLf + "Dim s1 As String=""a""" + vbCrLf + "Dim s2 As String=""b""" + vbCrLf + "Mid$(s1,3,3)=s2" + vbCrLf + "end sub" + vbCrLf + "end module", _ _ "module m1" + vbCrLf + vbCrLf + " sub s1()" + vbCrLf + " Dim s1 As String = ""a""" + vbCrLf + " Dim s2 As String = ""b""" + vbCrLf + " Mid$(s1, 3, 3) = s2" + vbCrLf + " end sub" + vbCrLf + "end module" + vbCrLf) End Sub <Fact(), WorkItem(546397, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546397")> Public Sub TestCallStatements() TestNormalizeBlock("module m1" + vbCrLf + "sub s2()" + vbCrLf + "s1 ( 23 )" + vbCrLf + "s1 ( p1:=23 , p2:=23)" + vbCrLf + "end sub" + vbCrLf + "end module", _ _ "module m1" + vbCrLf + vbCrLf + " sub s2()" + vbCrLf + " s1(23)" + vbCrLf + " s1(p1:=23, p2:=23)" + vbCrLf + " end sub" + vbCrLf + "end module" + vbCrLf) TestNormalizeBlock("module m1" + vbCrLf + vbCrLf + "sub s2 ( Of T ) ( optional x As T=nothing )" + vbCrLf + "N1.M2.S2 ( ) " + vbCrLf + "end sub" + vbCrLf + "end module", _ _ "module m1" + vbCrLf + vbCrLf + " sub s2(Of T)(optional x As T = nothing)" + vbCrLf + " N1.M2.S2()" + vbCrLf + " end sub" + vbCrLf + "end module" + vbCrLf) End Sub <Fact()> Public Sub TestNewStatements() TestNormalizeBlock("Dim zipState=New With { Key .ZipCode=98112, .State=""WA"" }", "Dim zipState = New With {Key .ZipCode = 98112, .State = ""WA""}" + vbCrLf) End Sub <Fact(), WorkItem(546397, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546397"), WorkItem(546514, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546514")> Public Sub TestXmlAccessStatements() TestNormalizeBlock("Imports <xmlns:db=""http://example.org/database"">" + vbCrLf + "Module Test" + vbCrLf + "Sub Main ( )" + vbCrLf + "Dim x=<db:customer><db:Name>Bob</db:Name></db:customer>" + vbCrLf + "Console . WriteLine ( x .< db:Name > )" + vbCrLf + "End Sub" + vbCrLf + "End Module", _ "Imports <xmlns:db=""http://example.org/database"">" + vbCrLf + "" + vbCrLf + "Module Test" + vbCrLf + vbCrLf + " Sub Main()" + vbCrLf + " Dim x = <db:customer><db:Name>Bob</db:Name></db:customer>" + vbCrLf + " Console.WriteLine(x.<db:Name>)" + vbCrLf + " End Sub" + vbCrLf + "End Module" + vbCrLf) End Sub <Fact(), WorkItem(546397, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546397")> Public Sub TestNamespaceStatements() TestNormalizeBlock("Imports I1.I2" + vbCrLf + "Namespace N1" + vbCrLf + "Namespace N2.N3" + vbCrLf + "end Namespace" + vbCrLf + "end Namespace", _ _ "Imports I1.I2" + vbCrLf + "" + vbCrLf + "Namespace N1" + vbCrLf + " Namespace N2.N3" + vbCrLf + " end Namespace" + vbCrLf + "end Namespace" + vbCrLf) End Sub <Fact(), WorkItem(546397, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546397")> Public Sub TestNullableStatements() TestNormalizeBlock( <code> module m1 Dim x as Integer?=nothing end module</code>.Value, _ _ <code>module m1 Dim x as Integer? = nothing end module </code>.Value) End Sub <Fact(), WorkItem(546397, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546397")> Public Sub TestInterfaceStatements() TestNormalizeBlock("namespace N1" + vbCrLf + "Interface I1" + vbCrLf + "public Function F1() As Object" + vbCrLf + "End Interface" + vbCrLf + "Interface I2" + vbCrLf + "Function F2() As Integer" + vbCrLf + "End Interface" + vbCrLf + "Structure S1" + vbCrLf + "Implements I1,I2" + vbCrLf + "public Function F1() As Object" + vbCrLf + "Dim x as Integer=23" + vbCrLf + "return x" + vbCrLf + "end function" + vbCrLf + "End Structure" + vbCrLf + "End Namespace", _ _ "namespace N1" + vbCrLf + vbCrLf + " Interface I1" + vbCrLf + vbCrLf + " public Function F1() As Object" + vbCrLf + vbCrLf + " End Interface" + vbCrLf + vbCrLf + " Interface I2" + vbCrLf + vbCrLf + " Function F2() As Integer" + vbCrLf + vbCrLf + " End Interface" + vbCrLf + vbCrLf + " Structure S1" + vbCrLf + " Implements I1, I2" + vbCrLf + vbCrLf + " public Function F1() As Object" + vbCrLf + " Dim x as Integer = 23" + vbCrLf + " return x" + vbCrLf + " end function" + vbCrLf + " End Structure" + vbCrLf + "End Namespace" + vbCrLf) End Sub <Fact(), WorkItem(546397, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546397")> Public Sub TestEnumStatements() TestNormalizeBlock("Module M1" + vbCrLf + vbCrLf + "ENUM E1 as long" + vbCrLf + " goo=23" + vbCrLf + "bar " + vbCrLf + "boo=goo" + vbCrLf + "booya=1.4" + vbCrLf + "end enum" + vbCrLf + "end MODule", _ _ "Module M1" + vbCrLf + vbCrLf + " ENUM E1 as long" + vbCrLf + " goo = 23" + vbCrLf + " bar" + vbCrLf + " boo = goo" + vbCrLf + " booya = 1.4" + vbCrLf + " end enum" + vbCrLf + "end MODule" + vbCrLf) TestNormalizeBlock("class c1" + vbCrLf + "ENUM E1 as long" + vbCrLf + " goo=23" + vbCrLf + "bar " + vbCrLf + "boo=goo" + vbCrLf + "booya=1.4" + vbCrLf + "end enum" + vbCrLf + "end class", _ _ "class c1" + vbCrLf + vbCrLf + " ENUM E1 as long" + vbCrLf + " goo = 23" + vbCrLf + " bar" + vbCrLf + " boo = goo" + vbCrLf + " booya = 1.4" + vbCrLf + " end enum" + vbCrLf + "end class" + vbCrLf) TestNormalizeBlock("public class c1" + vbCrLf + vbCrLf + "ENUM E1 as long" + vbCrLf + " goo=23" + vbCrLf + "bar " + vbCrLf + "boo=goo" + vbCrLf + "booya=1.4" + vbCrLf + "end enum" + vbCrLf + "end class", _ _ "public class c1" + vbCrLf + vbCrLf + " ENUM E1 as long" + vbCrLf + " goo = 23" + vbCrLf + " bar" + vbCrLf + " boo = goo" + vbCrLf + " booya = 1.4" + vbCrLf + " end enum" + vbCrLf + "end class" + vbCrLf) TestNormalizeBlock("class c1" + vbCrLf + "public ENUM E1 as long" + vbCrLf + " goo=23" + vbCrLf + "bar " + vbCrLf + "boo=goo" + vbCrLf + "booya=1.4" + vbCrLf + "end enum" + vbCrLf + "end class", _ _ "class c1" + vbCrLf + vbCrLf + " public ENUM E1 as long" + vbCrLf + " goo = 23" + vbCrLf + " bar" + vbCrLf + " boo = goo" + vbCrLf + " booya = 1.4" + vbCrLf + " end enum" + vbCrLf + "end class" + vbCrLf) End Sub <Fact(), WorkItem(546397, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546397")> Public Sub TestDelegateStatements() TestNormalizeBlock("Module M1" + vbCrLf + "Dim x=Function( x ,y )x+y" + vbCrLf + "Dim y As Func ( Of Integer ,Integer ,Integer )=x" + vbCrLf + "end MODule", _ _ "Module M1" + vbCrLf + vbCrLf + " Dim x = Function(x, y) x + y" + vbCrLf + vbCrLf + " Dim y As Func(Of Integer, Integer, Integer) = x" + vbCrLf + "end MODule" + vbCrLf) TestNormalizeBlock("Module M1" + vbCrLf + "Dim x=Function( x ,y )" + vbCrLf + "return x+y" + vbCrLf + "end function" + vbCrLf + "Dim y As Func ( Of Integer ,Integer ,Integer )=x" + vbCrLf + "end MODule", _ _ "Module M1" + vbCrLf + vbCrLf + " Dim x = Function(x, y)" + vbCrLf + " return x + y" + vbCrLf + " end function" + vbCrLf + vbCrLf + " Dim y As Func(Of Integer, Integer, Integer) = x" + vbCrLf + "end MODule" + vbCrLf) TestNormalizeBlock("Module M1" + vbCrLf + "Dim x=Sub( x ,y )" + vbCrLf + "dim x as integer" + vbCrLf + "end sub" + vbCrLf + "Dim y As Action ( Of Integer ,Integer)=x" + vbCrLf + "end MODule", _ _ "Module M1" + vbCrLf + vbCrLf + " Dim x = Sub(x, y)" + vbCrLf + " dim x as integer" + vbCrLf + " end sub" + vbCrLf + vbCrLf + " Dim y As Action(Of Integer, Integer) = x" + vbCrLf + "end MODule" + vbCrLf) End Sub <Fact(), WorkItem(546397, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546397")> Public Sub TestSelectStatements() TestNormalizeBlock(" Module M1" + vbCrLf + "sub s1()" + vbCrLf + "select case goo" + vbCrLf + "case 23 " + vbCrLf + "return goo " + vbCrLf + "case 42,11 " + vbCrLf + "return goo " + vbCrLf + "case > 100 " + vbCrLf + "return goo " + vbCrLf + "case 200 to 300 " + vbCrLf + "return goo " + vbCrLf + "case 12," + vbCrLf + "13" + vbCrLf + "return goo " + vbCrLf + "case else" + vbCrLf + "return goo " + vbCrLf + "end select " + vbCrLf + "end sub " + vbCrLf + "end module ", _ _ "Module M1" + vbCrLf + vbCrLf + " sub s1()" + vbCrLf + " select case goo" + vbCrLf + " case 23" + vbCrLf + " return goo" + vbCrLf + " case 42, 11" + vbCrLf + " return goo" + vbCrLf + " case > 100" + vbCrLf + " return goo" + vbCrLf + " case 200 to 300" + vbCrLf + " return goo" + vbCrLf + " case 12, 13" + vbCrLf + " return goo" + vbCrLf + " case else" + vbCrLf + " return goo" + vbCrLf + " end select" + vbCrLf + " end sub" + vbCrLf + "end module" + vbCrLf) End Sub <Fact(), WorkItem(546397, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546397")> Public Sub TestIfStatement() ' expressions TestNormalizeStatement("a", "a") ' if TestNormalizeStatement("if a then b", "if a then b") TestNormalizeStatement("if a then b else c", "if a then b else c") TestNormalizeStatement("if a then b else if c then d else e", "if a then b else if c then d else e") TestNormalizeStatement("if a then b else if c then d else e", "if a then b else if c then d else e") TestNormalizeStatement("if " + vbTab + " a then b else if c then d else e", "if a then b else if c then d else e") TestNormalizeStatement("if a then" + vbCrLf + "b" + vbCrLf + "end if", "if a then" + vbCrLf + " b" + vbCrLf + "end if") TestNormalizeStatement("if a then" + vbCrLf + vbCrLf + vbCrLf + "b" + vbCrLf + "end if", "if a then" + vbCrLf + " b" + vbCrLf + "end if") TestNormalizeStatement("if a then" + vbCrLf + "if a then" + vbCrLf + "b" + vbCrLf + "end if" + vbCrLf + "else" + vbCrLf + "b" + vbCrLf + "end if", "if a then" + vbCrLf + " if a then" + vbCrLf + " b" + vbCrLf + " end if" + vbCrLf + "else" + vbCrLf + " b" + vbCrLf + "end if") ' line continuation trivia will be removed TestNormalizeStatement("if a then _" + vbCrLf + "b _" + vbCrLf + "else c", "if a then b else c") TestNormalizeStatement("if a then:b:end if", "if a then : b : end if") Dim generatedLeftLiteralToken = SyntaxFactory.IntegerLiteralToken("42", LiteralBase.Decimal, TypeCharacter.None, 42) Dim generatedRightLiteralToken = SyntaxFactory.IntegerLiteralToken("23", LiteralBase.Decimal, TypeCharacter.None, 23) Dim generatedLeftLiteralExpression = SyntaxFactory.LiteralExpression(SyntaxKind.NumericLiteralExpression, generatedLeftLiteralToken) Dim generatedRightLiteralExpression = SyntaxFactory.LiteralExpression(SyntaxKind.NumericLiteralExpression, generatedRightLiteralToken) Dim generatedRedLiteralExpression = SyntaxFactory.GreaterThanExpression(generatedLeftLiteralExpression, SyntaxFactory.Token(SyntaxKind.GreaterThanToken), generatedRightLiteralExpression) Dim generatedRedIfStatement = SyntaxFactory.IfStatement(SyntaxFactory.Token(SyntaxKind.IfKeyword), generatedRedLiteralExpression, SyntaxFactory.Token(SyntaxKind.ThenKeyword, "THeN")) Dim expression As ExpressionSyntax = SyntaxFactory.StringLiteralExpression(SyntaxFactory.StringLiteralToken("goo", "goo")) Dim callexpression = SyntaxFactory.InvocationExpression(expression:=expression) Dim callstatement = SyntaxFactory.CallStatement(SyntaxFactory.Token(SyntaxKind.CallKeyword), callexpression) Dim stmtlist = SyntaxFactory.List(Of StatementSyntax)({CType(callstatement, StatementSyntax), CType(callstatement, StatementSyntax)}) Dim generatedEndIfStatement = SyntaxFactory.EndIfStatement(SyntaxFactory.Token(SyntaxKind.EndKeyword), SyntaxFactory.Token(SyntaxKind.IfKeyword)) Dim mlib = SyntaxFactory.MultiLineIfBlock(generatedRedIfStatement, stmtlist, Nothing, Nothing, generatedEndIfStatement) Dim str = mlib.NormalizeWhitespace(" ").ToFullString() Assert.Equal("If 42 > 23 THeN" + vbCrLf + " Call goo" + vbCrLf + " Call goo" + vbCrLf + "End If", str) End Sub <Fact(), WorkItem(546397, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546397")> Public Sub TestLoopStatements() TestNormalizeStatement("while a<b" + vbCrLf + "c " + vbCrLf + "end while", "while a < b" + vbCrLf + " c" + vbCrLf + "end while") TestNormalizeStatement("DO until a(2)<>12" + vbCrLf + "Dim x = 12" + vbCrLf + " loop", _ _ "DO until a(2) <> 12" + vbCrLf + " Dim x = 12" + vbCrLf + "loop") TestNormalizeStatement("DO while a(2)<>12" + vbCrLf + "Dim x = 12" + vbCrLf + " loop", _ _ "DO while a(2) <> 12" + vbCrLf + " Dim x = 12" + vbCrLf + "loop") TestNormalizeStatement("DO " + vbCrLf + "Dim x = 12" + vbCrLf + " loop", _ _ "DO" + vbCrLf + " Dim x = 12" + vbCrLf + "loop") TestNormalizeStatement("DO " + vbCrLf + "Dim x = 12" + vbCrLf + " loop until a ( 2 ) <> 12 ", _ _ "DO" + vbCrLf + " Dim x = 12" + vbCrLf + "loop until a(2) <> 12") TestNormalizeStatement("For Each i In x" + vbCrLf + "Dim x = 12" + vbCrLf + " next", _ _ "For Each i In x" + vbCrLf + " Dim x = 12" + vbCrLf + "next") TestNormalizeStatement("For Each i In x" + vbCrLf + "For Each j In x" + vbCrLf + "Dim x = 12" + vbCrLf + " next j,i", _ _ "For Each i In x" + vbCrLf + " For Each j In x" + vbCrLf + " Dim x = 12" + vbCrLf + "next j, i") End Sub <Fact(), WorkItem(546397, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546397")> Public Sub TestExceptionsStatements() TestNormalizeStatement(" try" + vbCrLf + "dim x =23" + vbCrLf + "Catch e1 As Exception When 1>2" + vbCrLf + "dim x =23" + vbCrLf + "Catch" + vbCrLf + "dim x =23" + vbCrLf + "finally" + vbCrLf + "dim x =23" + vbCrLf + " end try", _ _ "try" + vbCrLf + " dim x = 23" + vbCrLf + "Catch e1 As Exception When 1 > 2" + vbCrLf + " dim x = 23" + vbCrLf + "Catch" + vbCrLf + " dim x = 23" + vbCrLf + "finally" + vbCrLf + " dim x = 23" + vbCrLf + "end try") End Sub <Fact(), WorkItem(546397, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546397")> Public Sub TestUsingStatements() TestNormalizeStatement(" Using r1 As R = New R ( ) , r2 As R = New R( )" + vbCrLf + "dim x =23" + vbCrLf + "end using", _ _ "Using r1 As R = New R(), r2 As R = New R()" + vbCrLf + " dim x = 23" + vbCrLf + "end using") End Sub <Fact()> Public Sub TestQueryExpressions() TestNormalizeStatement(" Dim waCusts = _" + vbCrLf + "From cust As Customer In Customers _" + vbCrLf + "Where cust.State = ""WA""", _ _ "Dim waCusts = From cust As Customer In Customers Where cust.State = ""WA""") End Sub <Fact(), WorkItem(546397, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546397")> Public Sub TestDefaultCasingForKeywords() Dim expected = "Module m1" + vbCrLf + vbCrLf + " Dim x = Function(x, y) x + y" + vbCrLf + vbCrLf + " Dim y As func(Of Integer, Integer, Integer) = x" + vbCrLf + "End Module" + vbCrLf Dim node As CompilationUnitSyntax = SyntaxFactory.ParseCompilationUnit(expected.ToLowerInvariant) Dim actual = node.NormalizeWhitespace(indentation:=" ", useDefaultCasing:=True).ToFullString() Assert.Equal(expected, actual) End Sub <Fact(), WorkItem(546397, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546397")> Public Sub TestComment() ' trailing whitespace will be aligned to the indent level (see second comment) ' when determining if there should be a separator between tokens, the current algorithm does not check if a token comes out ' of structured trivia. Because of that there is now a space at the end of structured trivia before the next token ' whitespace before comments get reduced to one (see comment after code), whitespace in trivia is maintained (see same comment) ' xml doc comments somehow contain \n in the XmlTextLiterals ... will not spend time to work around Dim input = "Module m1" + vbCrLf + " ' a nice comment" + vbCrLf + " ''' even more comments" + vbCrLf + "' and more comments " + vbCrLf + "#if false " + vbCrLf + " whatever? " + vbCrLf + "#end if" + vbCrLf + "' and more comments" + vbCrLf + " ''' structured trivia before code" + vbCrLf + "Dim x = Function(x, y) x + y ' trivia after code" + vbCrLf + "End Module" Dim expected = "Module m1" + vbCrLf + vbCrLf + " ' a nice comment" + vbCrLf + " ''' even more comments" + vbCrLf + vbCrLf + " ' and more comments " + vbCrLf + "#if false" + vbCrLf + " whatever? " + vbCrLf + "#end if" + vbCrLf + " ' and more comments" + vbCrLf + " ''' structured trivia before code" + vbCrLf + " Dim x = Function(x, y) x + y ' trivia after code" + vbCrLf + "End Module" + vbCrLf Dim node As CompilationUnitSyntax = SyntaxFactory.ParseCompilationUnit(input) Dim actual = node.NormalizeWhitespace(" ").ToFullString() Assert.Equal(expected, actual) End Sub <Fact(), WorkItem(546397, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546397")> Public Sub TestMultilineLambdaFunctionsAsParameter() ' trailing whitespace will be aligned to the indent level (see second comment) ' when determining if there should be a separator between tokens, the current algorithm does not check if a token comes out ' of structured trivia. Because of that there is now a space at the end of structured trivia before the next token ' whitespace before comments get reduced to one (see comment after code), whitespace in trivia is maintained (see same comment) ' xml doc comments somehow contain \n in the XmlTextLiterals ... will not spend time to work around Dim input = "Module m1" + vbCrLf + "Sub Main(args As String())" + vbCrLf + "Sub1(Function(p As Integer)" + vbCrLf + "Sub2()" + vbCrLf + "End Function)" + vbCrLf + "End Sub" + vbCrLf + "End Module" Dim expected = "Module m1" + vbCrLf + vbCrLf + " Sub Main(args As String())" + vbCrLf + " Sub1(Function(p As Integer)" + vbCrLf + " Sub2()" + vbCrLf + " End Function)" + vbCrLf + " End Sub" + vbCrLf + "End Module" + vbCrLf Dim node As CompilationUnitSyntax = SyntaxFactory.ParseCompilationUnit(input) Dim actual = node.NormalizeWhitespace(" ").ToFullString() Assert.Equal(expected, actual) End Sub <Fact(), WorkItem(546397, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546397")> Public Sub TestProperty() Dim input = <text>Property p As Integer Get End Get Set ( value As Integer ) End Set End Property</text>.Value.Replace(vbLf, vbCrLf) Dim expected = <text>Property p As Integer Get End Get Set(value As Integer) End Set End Property </text>.Value.Replace(vbLf, vbCrLf) TestNormalizeBlock(input, expected) End Sub Private Sub TestNormalizeStatement(text As String, expected As String) Dim node As StatementSyntax = SyntaxFactory.ParseExecutableStatement(text) Dim actual = node.NormalizeWhitespace(" ").ToFullString() Assert.Equal(expected, actual) End Sub Private Sub TestNormalizeBlock(text As String, expected As String) Dim node As CompilationUnitSyntax = SyntaxFactory.ParseCompilationUnit(text) Dim actual = node.NormalizeWhitespace(" ").ToFullString() expected = expected.Replace(vbCrLf, vbLf).Replace(vbLf, vbCrLf) ' in case tests use XML literals Assert.Equal(expected, actual) End Sub <Fact(), WorkItem(546397, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546397")> Public Sub TestStructuredTriviaAndAttributes() Dim source = "Module m1" + vbCrLf + " '''<x>...</x>" + vbCrLf + " <goo()>" + vbCrLf + " sub a()" + vbCrLf + " end sub" + vbCrLf + "End Module" + vbCrLf + vbCrLf Dim expected = "Module m1" + vbCrLf + vbCrLf + " '''<x>...</x>" + vbCrLf + " <goo()>" + vbCrLf + " sub a()" + vbCrLf + " end sub" + vbCrLf + "End Module" + vbCrLf Dim node As CompilationUnitSyntax = SyntaxFactory.ParseCompilationUnit(source) Dim actual = node.NormalizeWhitespace(indentation:=" ", useDefaultCasing:=False).ToFullString() Assert.Equal(expected, actual) End Sub <Fact(), WorkItem(531607, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531607")> Public Sub TestNestedStructuredTrivia() Dim trivia = SyntaxFactory.TriviaList( SyntaxFactory.Trivia( SyntaxFactory.ConstDirectiveTrivia( "constant", SyntaxFactory.LiteralExpression( SyntaxKind.NumericLiteralExpression, SyntaxFactory.Literal(1).WithTrailingTrivia(SyntaxFactory.Trivia(SyntaxFactory.SkippedTokensTrivia(SyntaxFactory.TokenList(SyntaxFactory.Literal("A"c))))))))) Dim expected = "#Const constant = 1 ""A""c" Dim actual = trivia.NormalizeWhitespace(indentation:=" ", elasticTrivia:=False, useDefaultCasing:=False).ToFullString() Assert.Equal(expected, actual) End Sub <Fact()> Public Sub TestCrefAttribute() Dim source = "''' <summary>" + vbCrLf + "''' <see cref = """"/>" + vbCrLf + "''' <see cref =""""/>" + vbCrLf + "''' <see cref= """"/>" + vbCrLf + "''' <see cref=""""/>" + vbCrLf + "''' <see cref = ""1""/>" + vbCrLf + "''' <see cref =""a""/>" + vbCrLf + "''' <see cref= ""Integer()""/>" + vbCrLf + "''' <see cref = ""a()""/>" + vbCrLf + "''' </summary>" + vbCrLf + "Module Program" + vbCrLf + "End Module" + vbCrLf Dim expected = "''' <summary>" + vbCrLf + "''' <see cref=""""/> " + vbCrLf + "''' <see cref=""""/> " + vbCrLf + "''' <see cref=""""/> " + vbCrLf + "''' <see cref=""""/> " + vbCrLf + "''' <see cref=""1""/> " + vbCrLf + "''' <see cref=""a""/> " + vbCrLf + "''' <see cref=""Integer()""/> " + vbCrLf + "''' <see cref=""a()""/> " + vbCrLf + "''' </summary>" + vbCrLf + "Module Program" + vbCrLf + "End Module" + vbCrLf Dim node As CompilationUnitSyntax = SyntaxFactory.ParseCompilationUnit(source) Dim actual = node.NormalizeWhitespace(indentation:=" ", useDefaultCasing:=False).ToFullString() Assert.Equal(expected, actual) End Sub <Fact()> Public Sub TestNameAttribute() Dim source = "''' <summary>" + vbCrLf + "''' <paramref name = """"/>" + vbCrLf + "''' <paramref name =""""/>" + vbCrLf + "''' <paramref name= """"/>" + vbCrLf + "''' <paramref name=""""/>" + vbCrLf + "''' <paramref name = ""1""/>" + vbCrLf + "''' <paramref name =""a""/>" + vbCrLf + "''' <paramref name= ""Integer()""/>" + vbCrLf + "''' <paramref name = ""a()""/>" + vbCrLf + "''' </summary>" + vbCrLf + "Module Program" + vbCrLf + "End Module" + vbCrLf Dim expected = "''' <summary>" + vbCrLf + "''' <paramref name=""""/> " + vbCrLf + "''' <paramref name=""""/> " + vbCrLf + "''' <paramref name=""""/> " + vbCrLf + "''' <paramref name=""""/> " + vbCrLf + "''' <paramref name=""1""/> " + vbCrLf + "''' <paramref name=""a""/> " + vbCrLf + "''' <paramref name=""Integer()""/> " + vbCrLf + "''' <paramref name=""a()""/> " + vbCrLf + "''' </summary>" + vbCrLf + "Module Program" + vbCrLf + "End Module" + vbCrLf Dim node As CompilationUnitSyntax = SyntaxFactory.ParseCompilationUnit(source) Dim actual = node.NormalizeWhitespace(indentation:=" ", useDefaultCasing:=False).ToFullString() Assert.Equal(expected, actual) End Sub <Fact> Public Sub TestEnableWarningDirective() Dim text = <![CDATA[ # enable warning[BC000],Bc123, BC456,_789' comment # enable warning # enable warning ,]]>.Value.Replace(vbLf, vbCrLf) Dim root = Parse(text).GetRoot() Dim normalizedRoot = root.NormalizeWhitespace(indentation:=" ", elasticTrivia:=True, useDefaultCasing:=True) Dim expected = <![CDATA[#Enable Warning [BC000], Bc123, BC456, _789 ' comment #Enable Warning #Enable Warning , ]]>.Value.Replace(vbLf, vbCrLf) Assert.Equal(expected, normalizedRoot.ToFullString()) End Sub <Fact> Public Sub TestDisableWarningDirective() Dim text = <![CDATA[Module Program # disable warning Sub Main() #disable warning bc123, Bc456,BC789 End Sub # disable warning[BC123], ' Comment End Module]]>.Value.Replace(vbLf, vbCrLf) Dim root = Parse(text).GetRoot() Dim normalizedRoot = root.NormalizeWhitespace(indentation:=" ", elasticTrivia:=True, useDefaultCasing:=True) Dim expected = <![CDATA[Module Program #Disable Warning Sub Main() #Disable Warning bc123, Bc456, BC789 End Sub #Disable Warning [BC123], ' Comment End Module ]]>.Value.Replace(vbLf, vbCrLf) Assert.Equal(expected, normalizedRoot.ToFullString()) End Sub <Fact> Public Sub TestNormalizeEOL() Dim code = "Class C" & vbCrLf & "End Class" Dim expected = "Class C" & vbLf & "End Class" & vbLf Dim actual = SyntaxFactory.ParseCompilationUnit(code).NormalizeWhitespace(" ", eol:=vbLf).ToFullString() Assert.Equal(expected, actual) End Sub <Fact> Public Sub TestNormalizeTabs() Dim code = "Class C" & vbCrLf & "Sub M()" & vbCrLf & "End Sub" & vbCrLf & "End Class" Dim expected = "Class C" & vbCrLf & vbCrLf & vbTab & "Sub M()" & vbCrLf & vbTab & "End Sub" & vbCrLf & "End Class" & vbCrLf Dim actual = SyntaxFactory.ParseCompilationUnit(code).NormalizeWhitespace(vbTab).ToFullString() Assert.Equal(expected, actual) End Sub End Class End Namespace
-1
dotnet/roslyn
55,290
Fix 'quick info' and 'use explicit type' for implicit lambdas
CyrusNajmabadi
2021-07-30T18:48:59Z
2021-08-03T18:56:45Z
3a5457c3b9483c7b2be1cf6899ee3564c8ade6cf
416765ff976b2a2776c0103d3c7033f9b1667f27
Fix 'quick info' and 'use explicit type' for implicit lambdas.
./src/Compilers/Core/Portable/SwitchConstantValueHelper.cs
// Licensed to the .NET Foundation under one or more agreements. // 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.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { /// <summary> /// Contains helper methods for switch statement label constants /// </summary> internal static class SwitchConstantValueHelper { public static bool IsValidSwitchCaseLabelConstant(ConstantValue constant) { switch (constant.Discriminator) { case ConstantValueTypeDiscriminator.Null: case ConstantValueTypeDiscriminator.SByte: case ConstantValueTypeDiscriminator.Byte: case ConstantValueTypeDiscriminator.Int16: case ConstantValueTypeDiscriminator.UInt16: case ConstantValueTypeDiscriminator.Int32: case ConstantValueTypeDiscriminator.UInt32: case ConstantValueTypeDiscriminator.Int64: case ConstantValueTypeDiscriminator.UInt64: case ConstantValueTypeDiscriminator.Char: case ConstantValueTypeDiscriminator.Boolean: case ConstantValueTypeDiscriminator.String: return true; default: return false; } } /// <summary> /// Method used to compare ConstantValues for switch statement case labels /// </summary> /// <param name="first"></param> /// <param name="second"></param> /// <returns>A value that indicates the relative order of the objects being compared. The return value has these meanings: /// Less than zero: first instance precedes second in the sort order. /// Zero: first instance occurs in the same position in the sort order as second. /// Greater than zero: first instance follows second in the sort order. /// </returns> public static int CompareSwitchCaseLabelConstants(ConstantValue first, ConstantValue second) { RoslynDebug.Assert(first != null); RoslynDebug.Assert(second != null); RoslynDebug.Assert(IsValidSwitchCaseLabelConstant(first)); RoslynDebug.Assert(IsValidSwitchCaseLabelConstant(second)); if (first.IsNull) { // first instance has ConstantValue Null. // If second instance ConstantValue is Null, both instances are equal. // Else, second instance is greater. return second.IsNull ? 0 : -1; } else if (second.IsNull) { // second instance has ConstantValue Null and first instance has non-null ConstantValue. // first instance is greater. return 1; } switch (first.Discriminator) { case ConstantValueTypeDiscriminator.SByte: case ConstantValueTypeDiscriminator.Int16: case ConstantValueTypeDiscriminator.Int32: case ConstantValueTypeDiscriminator.Int64: return first.Int64Value.CompareTo(second.Int64Value); case ConstantValueTypeDiscriminator.Boolean: case ConstantValueTypeDiscriminator.Byte: case ConstantValueTypeDiscriminator.UInt16: case ConstantValueTypeDiscriminator.UInt32: case ConstantValueTypeDiscriminator.UInt64: case ConstantValueTypeDiscriminator.Char: return first.UInt64Value.CompareTo(second.UInt64Value); case ConstantValueTypeDiscriminator.String: Debug.Assert(second.IsString); return string.CompareOrdinal(first.StringValue, second.StringValue); default: throw ExceptionUtilities.UnexpectedValue(first.Discriminator); } } public class SwitchLabelsComparer : EqualityComparer<object> { public override bool Equals(object? first, object? second) { RoslynDebug.Assert(first != null && second != null); var firstConstant = first as ConstantValue; if (firstConstant != null) { var secondConstant = second as ConstantValue; if (secondConstant != null) { if (!IsValidSwitchCaseLabelConstant(firstConstant) || !IsValidSwitchCaseLabelConstant(secondConstant)) { // We don't care about invalid case labels with duplicate value as // we will generate diagnostics for invalid case label. return firstConstant.Equals(secondConstant); } return CompareSwitchCaseLabelConstants(firstConstant, secondConstant) == 0; } } var firstString = first as string; if (firstString != null) { return string.Equals(firstString, second as string, System.StringComparison.Ordinal); } return first.Equals(second); } public override int GetHashCode(object obj) { var constant = obj as ConstantValue; if (constant != null) { switch (constant.Discriminator) { case ConstantValueTypeDiscriminator.SByte: case ConstantValueTypeDiscriminator.Int16: case ConstantValueTypeDiscriminator.Int32: case ConstantValueTypeDiscriminator.Int64: return constant.Int64Value.GetHashCode(); case ConstantValueTypeDiscriminator.Boolean: case ConstantValueTypeDiscriminator.Byte: case ConstantValueTypeDiscriminator.UInt16: case ConstantValueTypeDiscriminator.UInt32: case ConstantValueTypeDiscriminator.UInt64: case ConstantValueTypeDiscriminator.Char: return constant.UInt64Value.GetHashCode(); case ConstantValueTypeDiscriminator.String: return constant.RopeValue!.GetHashCode(); } } return obj.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.Collections.Generic; using System.Diagnostics; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { /// <summary> /// Contains helper methods for switch statement label constants /// </summary> internal static class SwitchConstantValueHelper { public static bool IsValidSwitchCaseLabelConstant(ConstantValue constant) { switch (constant.Discriminator) { case ConstantValueTypeDiscriminator.Null: case ConstantValueTypeDiscriminator.SByte: case ConstantValueTypeDiscriminator.Byte: case ConstantValueTypeDiscriminator.Int16: case ConstantValueTypeDiscriminator.UInt16: case ConstantValueTypeDiscriminator.Int32: case ConstantValueTypeDiscriminator.UInt32: case ConstantValueTypeDiscriminator.Int64: case ConstantValueTypeDiscriminator.UInt64: case ConstantValueTypeDiscriminator.Char: case ConstantValueTypeDiscriminator.Boolean: case ConstantValueTypeDiscriminator.String: return true; default: return false; } } /// <summary> /// Method used to compare ConstantValues for switch statement case labels /// </summary> /// <param name="first"></param> /// <param name="second"></param> /// <returns>A value that indicates the relative order of the objects being compared. The return value has these meanings: /// Less than zero: first instance precedes second in the sort order. /// Zero: first instance occurs in the same position in the sort order as second. /// Greater than zero: first instance follows second in the sort order. /// </returns> public static int CompareSwitchCaseLabelConstants(ConstantValue first, ConstantValue second) { RoslynDebug.Assert(first != null); RoslynDebug.Assert(second != null); RoslynDebug.Assert(IsValidSwitchCaseLabelConstant(first)); RoslynDebug.Assert(IsValidSwitchCaseLabelConstant(second)); if (first.IsNull) { // first instance has ConstantValue Null. // If second instance ConstantValue is Null, both instances are equal. // Else, second instance is greater. return second.IsNull ? 0 : -1; } else if (second.IsNull) { // second instance has ConstantValue Null and first instance has non-null ConstantValue. // first instance is greater. return 1; } switch (first.Discriminator) { case ConstantValueTypeDiscriminator.SByte: case ConstantValueTypeDiscriminator.Int16: case ConstantValueTypeDiscriminator.Int32: case ConstantValueTypeDiscriminator.Int64: return first.Int64Value.CompareTo(second.Int64Value); case ConstantValueTypeDiscriminator.Boolean: case ConstantValueTypeDiscriminator.Byte: case ConstantValueTypeDiscriminator.UInt16: case ConstantValueTypeDiscriminator.UInt32: case ConstantValueTypeDiscriminator.UInt64: case ConstantValueTypeDiscriminator.Char: return first.UInt64Value.CompareTo(second.UInt64Value); case ConstantValueTypeDiscriminator.String: Debug.Assert(second.IsString); return string.CompareOrdinal(first.StringValue, second.StringValue); default: throw ExceptionUtilities.UnexpectedValue(first.Discriminator); } } public class SwitchLabelsComparer : EqualityComparer<object> { public override bool Equals(object? first, object? second) { RoslynDebug.Assert(first != null && second != null); var firstConstant = first as ConstantValue; if (firstConstant != null) { var secondConstant = second as ConstantValue; if (secondConstant != null) { if (!IsValidSwitchCaseLabelConstant(firstConstant) || !IsValidSwitchCaseLabelConstant(secondConstant)) { // We don't care about invalid case labels with duplicate value as // we will generate diagnostics for invalid case label. return firstConstant.Equals(secondConstant); } return CompareSwitchCaseLabelConstants(firstConstant, secondConstant) == 0; } } var firstString = first as string; if (firstString != null) { return string.Equals(firstString, second as string, System.StringComparison.Ordinal); } return first.Equals(second); } public override int GetHashCode(object obj) { var constant = obj as ConstantValue; if (constant != null) { switch (constant.Discriminator) { case ConstantValueTypeDiscriminator.SByte: case ConstantValueTypeDiscriminator.Int16: case ConstantValueTypeDiscriminator.Int32: case ConstantValueTypeDiscriminator.Int64: return constant.Int64Value.GetHashCode(); case ConstantValueTypeDiscriminator.Boolean: case ConstantValueTypeDiscriminator.Byte: case ConstantValueTypeDiscriminator.UInt16: case ConstantValueTypeDiscriminator.UInt32: case ConstantValueTypeDiscriminator.UInt64: case ConstantValueTypeDiscriminator.Char: return constant.UInt64Value.GetHashCode(); case ConstantValueTypeDiscriminator.String: return constant.RopeValue!.GetHashCode(); } } return obj.GetHashCode(); } } } }
-1
dotnet/roslyn
55,290
Fix 'quick info' and 'use explicit type' for implicit lambdas
CyrusNajmabadi
2021-07-30T18:48:59Z
2021-08-03T18:56:45Z
3a5457c3b9483c7b2be1cf6899ee3564c8ade6cf
416765ff976b2a2776c0103d3c7033f9b1667f27
Fix 'quick info' and 'use explicit type' for implicit lambdas.
./src/Compilers/Test/Utilities/VisualBasic/CompilationTestUtils.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.Runtime.CompilerServices Imports System.Runtime.InteropServices Imports System.Text Imports System.Xml.Linq Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.Text Imports Roslyn.Test.Utilities Imports Roslyn.Test.Utilities.TestBase Imports Roslyn.Test.Utilities.TestMetadata Imports Xunit Friend Module CompilationUtils Private Function ParseSources(source As IEnumerable(Of String), parseOptions As VisualBasicParseOptions) As IEnumerable(Of SyntaxTree) Return source.Select(Function(s) VisualBasicSyntaxTree.ParseText(s, parseOptions)) End Function Public Function CreateCompilation( source As BasicTestSource, Optional references As IEnumerable(Of MetadataReference) = Nothing, Optional options As VisualBasicCompilationOptions = Nothing, Optional parseOptions As VisualBasicParseOptions = Nothing, Optional targetFramework As TargetFramework = TargetFramework.StandardAndVBRuntime, Optional assemblyName As String = Nothing) As VisualBasicCompilation references = TargetFrameworkUtil.GetReferences(targetFramework, references) Return CreateEmptyCompilation(source, references, options, parseOptions, assemblyName) End Function Public Function CreateEmptyCompilation( source As BasicTestSource, Optional references As IEnumerable(Of MetadataReference) = Nothing, Optional options As VisualBasicCompilationOptions = Nothing, Optional parseOptions As VisualBasicParseOptions = Nothing, Optional assemblyName As String = Nothing) As VisualBasicCompilation If options Is Nothing Then options = TestOptions.ReleaseDll End If ' Using single-threaded build if debugger attached, to simplify debugging. If Debugger.IsAttached Then options = options.WithConcurrentBuild(False) End If Dim trees = source.GetSyntaxTrees(parseOptions, assemblyName) Dim createCompilationLambda = Function() Return VisualBasicCompilation.Create( If(assemblyName, GetUniqueName()), trees, references, options) End Function ValidateCompilation(createCompilationLambda) Return createCompilationLambda() End Function Private Sub ValidateCompilation(createCompilationLambda As Func(Of VisualBasicCompilation)) CompilationExtensions.ValidateIOperations(createCompilationLambda) VerifyUsedAssemblyReferences(createCompilationLambda) End Sub Private Sub VerifyUsedAssemblyReferences(createCompilationLambda As Func(Of VisualBasicCompilation)) If Not CompilationExtensions.EnableVerifyUsedAssemblies Then Return End If Dim comp = createCompilationLambda() Dim used = comp.GetUsedAssemblyReferences() Dim compileDiagnostics = comp.GetDiagnostics() Dim emitDiagnostics = comp.GetEmitDiagnostics() Dim resolvedReferences = comp.References.Where(Function(r) r.Properties.Kind = MetadataImageKind.Assembly) If Not compileDiagnostics.Any(Function(d) d.DefaultSeverity = DiagnosticSeverity.Error) Then If resolvedReferences.Count() > used.Length Then AssertSubset(used, resolvedReferences) If Not compileDiagnostics.Any(Function(d) d.Code = ERRID.HDN_UnusedImportClause OrElse d.Code = ERRID.HDN_UnusedImportStatement) Then Dim comp2 = comp.RemoveAllReferences().AddReferences(used.Concat(comp.References.Where(Function(r) r.Properties.Kind = MetadataImageKind.Module))) comp2.GetEmitDiagnostics().Verify( emitDiagnostics.Select(Function(d) New DiagnosticDescription(d, errorCodeOnly:=False, includeDefaultSeverity:=False, includeEffectiveSeverity:=False)).ToArray()) End If Else AssertEx.Equal(resolvedReferences, used) End If Else AssertSubset(used, resolvedReferences) End If End Sub Private Sub AssertSubset(used As ImmutableArray(Of MetadataReference), resolvedReferences As IEnumerable(Of MetadataReference)) For Each reference In used Assert.Contains(reference, resolvedReferences) Next End Sub Public Function CreateEmptyCompilation( identity As AssemblyIdentity, source As BasicTestSource, Optional references As MetadataReference() = Nothing, Optional options As VisualBasicCompilationOptions = Nothing) As VisualBasicCompilation Dim trees = source.GetSyntaxTrees() Dim createCompilationLambda = Function() Return VisualBasicCompilation.Create(identity.Name, trees, references, options) End Function ValidateCompilation(createCompilationLambda) Dim c = createCompilationLambda() Assert.NotNull(c.Assembly) ' force creation of SourceAssemblySymbol DirectCast(c.Assembly, SourceAssemblySymbol).m_lazyIdentity = identity Return c End Function Public Function CreateCompilationWithMscorlib40( source As BasicTestSource, Optional references As IEnumerable(Of MetadataReference) = Nothing, Optional options As VisualBasicCompilationOptions = Nothing, Optional parseOptions As VisualBasicParseOptions = Nothing, Optional assemblyName As String = Nothing) As VisualBasicCompilation Return CreateCompilation(source, references, options, parseOptions, TargetFramework.Mscorlib40, assemblyName) End Function Public Function CreateCompilationWithMscorlib45( source As BasicTestSource, Optional references As IEnumerable(Of MetadataReference) = Nothing, Optional options As VisualBasicCompilationOptions = Nothing, Optional parseOptions As VisualBasicParseOptions = Nothing, Optional assemblyName As String = Nothing) As VisualBasicCompilation Return CreateCompilation(source, references, options, parseOptions, TargetFramework.Mscorlib45, assemblyName) End Function Public Function CreateCompilationWithMscorlib45AndVBRuntime( source As BasicTestSource, Optional references As IEnumerable(Of MetadataReference) = Nothing, Optional options As VisualBasicCompilationOptions = Nothing, Optional parseOptions As VisualBasicParseOptions = Nothing, Optional assemblyName As String = Nothing) As VisualBasicCompilation Return CreateCompilation(source, references, options, parseOptions, TargetFramework.Mscorlib45AndVBRuntime, assemblyName) End Function Public Function CreateCompilationWithWinRt(source As XElement) As VisualBasicCompilation Return CreateEmptyCompilationWithReferences(source, WinRtRefs) End Function Public Function CreateCompilationWithMscorlib40AndReferences(source As XElement, references As IEnumerable(Of MetadataReference), Optional options As VisualBasicCompilationOptions = Nothing, Optional parseOptions As VisualBasicParseOptions = Nothing) As VisualBasicCompilation Return CreateEmptyCompilationWithReferences(source, {CType(Net40.mscorlib, MetadataReference)}.Concat(references), options, parseOptions:=parseOptions) End Function ''' <summary> ''' ''' </summary> ''' <param name="source">The sources compile according to the following schema ''' &lt;compilation name="assemblyname[optional]"&gt; ''' &lt;file name="file1.vb[optional]"&gt; ''' source ''' &lt;/file&gt; ''' &lt;/compilation&gt; ''' </param> Public Function CreateCompilationWithMscorlib40(source As XElement, outputKind As OutputKind, Optional parseOptions As VisualBasicParseOptions = Nothing) As VisualBasicCompilation Return CreateEmptyCompilationWithReferences(source, {Net40.mscorlib}, New VisualBasicCompilationOptions(outputKind), parseOptions:=parseOptions) End Function ''' <summary> ''' ''' </summary> ''' <param name="source">The sources compile according to the following schema ''' &lt;compilation name="assemblyname[optional]"&gt; ''' &lt;file name="file1.vb[optional]"&gt; ''' source ''' &lt;/file&gt; ''' &lt;/compilation&gt; ''' </param> Public Function CreateCompilationWithMscorlib40AndVBRuntime( source As XElement, Optional additionalRefs As MetadataReference() = Nothing, Optional options As VisualBasicCompilationOptions = Nothing, Optional parseOptions As VisualBasicParseOptions = Nothing, Optional assemblyName As String = Nothing) As VisualBasicCompilation If additionalRefs Is Nothing Then additionalRefs = {} Dim references = {CType(Net40.mscorlib, MetadataReference), Net40.System, Net40.MicrosoftVisualBasic}.Concat(additionalRefs) Return CreateEmptyCompilationWithReferences(source, references, options, parseOptions:=parseOptions, assemblyName:=assemblyName) End Function Public Function CreateCompilationWithMscorlib40AndVBRuntime(source As IEnumerable(Of SyntaxTree), options As VisualBasicCompilationOptions, Optional assemblyName As String = Nothing) As VisualBasicCompilation Dim references = {MscorlibRef, SystemRef, MsvbRef} Return CreateEmptyCompilation(source.ToArray(), references, options:=options, assemblyName:=assemblyName) End Function Public Function CreateCompilationWithMscorlib40AndVBRuntime(source As XElement, options As VisualBasicCompilationOptions) As VisualBasicCompilation Return CreateCompilationWithMscorlib40AndVBRuntime(source, Nothing, options, parseOptions:=If(options Is Nothing, Nothing, options.ParseOptions)) End Function Public ReadOnly XmlReferences As MetadataReference() = {SystemRef, SystemCoreRef, SystemXmlRef, SystemXmlLinqRef} Public ReadOnly Net40XmlReferences As MetadataReference() = {Net40.SystemCore, Net40.SystemXml, Net40.SystemXmlLinq} Public ReadOnly Net451XmlReferences As MetadataReference() = {Net451.SystemCore, Net451.SystemXml, Net451.SystemXmlLinq} ''' <summary> ''' ''' </summary> ''' <param name="source">The sources compile according to the following schema ''' &lt;compilation name="assemblyname[optional]"&gt; ''' &lt;file name="file1.vb[optional]"&gt; ''' source ''' &lt;/file&gt; ''' &lt;/compilation&gt; ''' </param> Public Function CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( source As XElement, Optional references As IEnumerable(Of MetadataReference) = Nothing, Optional options As VisualBasicCompilationOptions = Nothing, Optional parseOptions As VisualBasicParseOptions = Nothing) As VisualBasicCompilation If references Is Nothing Then references = {} Dim allReferences = {CType(Net40.mscorlib, MetadataReference), Net40.System, Net40.MicrosoftVisualBasic}.Concat(references) If parseOptions Is Nothing AndAlso options IsNot Nothing Then parseOptions = options.ParseOptions End If Return CreateEmptyCompilationWithReferences(source, allReferences, options, parseOptions:=parseOptions) End Function ''' <summary> ''' ''' </summary> ''' <param name="source">The sources compile according to the following schema ''' &lt;compilation name="assemblyname[optional]"&gt; ''' &lt;file name="file1.vb[optional]"&gt; ''' source ''' &lt;/file&gt; ''' &lt;/compilation&gt; ''' </param> Public Function CreateCompilationWithMscorlib45AndVBRuntime( source As XElement, Optional references As IEnumerable(Of MetadataReference) = Nothing, Optional options As VisualBasicCompilationOptions = Nothing, Optional parseOptions As VisualBasicParseOptions = Nothing) As VisualBasicCompilation Dim allReferences = {MscorlibRef_v4_0_30316_17626, MsvbRef_v4_0_30319_17929}.Concat(If(references, {})) Return CreateEmptyCompilationWithReferences(source, allReferences, options, parseOptions:=parseOptions) End Function ''' <summary> ''' ''' </summary> ''' <param name="source">The sources compile according to the following schema ''' &lt;compilation name="assemblyname[optional]"&gt; ''' &lt;file name="file1.vb[optional]"&gt; ''' source ''' &lt;/file&gt; ''' &lt;/compilation&gt; ''' </param> Public Function CreateEmptyCompilationWithReferences(source As XElement, references As IEnumerable(Of MetadataReference), Optional options As VisualBasicCompilationOptions = Nothing, Optional parseOptions As VisualBasicParseOptions = Nothing, Optional assemblyName As String = Nothing) As VisualBasicCompilation Dim sourceTrees = ParseSourceXml(source, parseOptions, assemblyName) Return CreateEmptyCompilationWithReferences(sourceTrees, references, options, assemblyName) End Function Public Function ParseSourceXml(sources As XElement, parseOptions As VisualBasicParseOptions, Optional ByRef assemblyName As String = Nothing, Optional ByRef spans As IEnumerable(Of IEnumerable(Of TextSpan)) = Nothing) As IEnumerable(Of SyntaxTree) If sources.@name IsNot Nothing Then assemblyName = sources.@name End If Dim sourcesTreesAndSpans = From f In sources.<file> Select CreateParseTreeAndSpans(f, parseOptions) spans = From t In sourcesTreesAndSpans Select s = t.spans Return From t In sourcesTreesAndSpans Select t.tree End Function Public Function ToSourceTrees(compilationSources As XElement, Optional parseOptions As VisualBasicParseOptions = Nothing) As IEnumerable(Of SyntaxTree) Dim sourcesTreesAndSpans = From f In compilationSources.<file> Select CreateParseTreeAndSpans(f, parseOptions) Return From t In sourcesTreesAndSpans Select t.tree End Function Public Function CreateEmptyCompilationWithReferences(source As SyntaxTree, references As IEnumerable(Of MetadataReference), Optional options As VisualBasicCompilationOptions = Nothing, Optional assemblyName As String = Nothing) As VisualBasicCompilation Return CreateEmptyCompilationWithReferences({source}, references, options, assemblyName) End Function Public Function CreateEmptyCompilationWithReferences(source As IEnumerable(Of SyntaxTree), references As IEnumerable(Of MetadataReference), Optional options As VisualBasicCompilationOptions = Nothing, Optional assemblyName As String = Nothing) As VisualBasicCompilation If options Is Nothing Then options = TestOptions.ReleaseDll ' Using single-threaded build if debugger attached, to simplify debugging. If Debugger.IsAttached Then options = options.WithConcurrentBuild(False) End If End If Dim createCompilationLambda = Function() Return VisualBasicCompilation.Create(If(assemblyName, GetUniqueName()), source, references, options) End Function ValidateCompilation(createCompilationLambda) Return createCompilationLambda() End Function ''' <summary> ''' ''' </summary> ''' <param name="sources">The sources compile according to the following schema ''' &lt;compilation name="assemblyname[optional]"&gt; ''' &lt;file name="file1.vb[optional]"&gt; ''' source ''' &lt;/file&gt; ''' &lt;/compilation&gt; ''' </param> ''' <param name="ilSource"></param> ''' <returns></returns> ''' <remarks></remarks> Public Function CreateCompilationWithCustomILSource(sources As XElement, ilSource As XCData) As VisualBasicCompilation Return CreateCompilationWithCustomILSource(sources, ilSource.Value) End Function ''' <summary> ''' ''' </summary> ''' <param name="sources">The sources compile according to the following schema ''' &lt;compilation name="assemblyname[optional]"&gt; ''' &lt;file name="file1.vb[optional]"&gt; ''' source ''' &lt;/file&gt; ''' &lt;/compilation&gt; ''' </param> ''' <param name="ilSource"></param> ''' <returns></returns> ''' <remarks></remarks> Public Function CreateCompilationWithCustomILSource(sources As XElement, ilSource As String, Optional options As VisualBasicCompilationOptions = Nothing, Optional ByRef spans As IEnumerable(Of IEnumerable(Of TextSpan)) = Nothing, Optional includeVbRuntime As Boolean = False, Optional includeSystemCore As Boolean = False, Optional appendDefaultHeader As Boolean = True, Optional parseOptions As VisualBasicParseOptions = Nothing, Optional additionalReferences As IEnumerable(Of MetadataReference) = Nothing, <Out> Optional ByRef ilReference As MetadataReference = Nothing, <Out> Optional ByRef ilImage As ImmutableArray(Of Byte) = Nothing ) As VisualBasicCompilation Dim references = If(additionalReferences IsNot Nothing, New List(Of MetadataReference)(additionalReferences), New List(Of MetadataReference)) If includeVbRuntime Then references.Add(MsvbRef) End If If includeSystemCore Then references.Add(SystemCoreRef) End If If ilSource Is Nothing Then Return CreateCompilationWithMscorlib40AndReferences(sources, references, options, parseOptions) End If ilReference = CreateReferenceFromIlCode(ilSource, appendDefaultHeader, ilImage) references.Add(ilReference) Return CreateCompilationWithMscorlib40AndReferences(sources, references, options, parseOptions) End Function Public Function CreateReferenceFromIlCode(ilSource As String, Optional appendDefaultHeader As Boolean = True, <Out> Optional ByRef ilImage As ImmutableArray(Of Byte) = Nothing) As MetadataReference Using reference = IlasmUtilities.CreateTempAssembly(ilSource, appendDefaultHeader) ilImage = ImmutableArray.Create(File.ReadAllBytes(reference.Path)) End Using Return MetadataReference.CreateFromImage(ilImage) End Function Public Function GetUniqueName() As String Return Guid.NewGuid().ToString("D") End Function ' Filter text from within an XElement Public Function FilterString(s As String) As String s = s.Replace(vbCrLf, vbLf) ' If there are already "0d0a", don't replace them with "0d0a0a" s = s.Replace(vbLf, vbCrLf) Dim needToAddBackNewline = s.EndsWith(vbCrLf, StringComparison.Ordinal) s = s.Trim() If needToAddBackNewline Then s &= vbCrLf Return s End Function Public Function FindBindingText(Of TNode As SyntaxNode)(compilation As Compilation, fileName As String, Optional which As Integer = 0, Optional prefixMatch As Boolean = False) As TNode Dim tree = (From t In compilation.SyntaxTrees Where t.FilePath = fileName).Single() Dim bindText As String = Nothing Dim bindPoint = FindBindingTextPosition(compilation, fileName, bindText, which) Dim token = tree.GetRoot().FindToken(bindPoint, True) Dim node = token.Parent Dim hasMatchingText As Func(Of SyntaxNode, Boolean) = Function(n) n.ToString = bindText OrElse (prefixMatch AndAlso TryCast(n, TNode) IsNot Nothing AndAlso n.ToString.StartsWith(bindText)) While (node IsNot Nothing AndAlso Not hasMatchingText(node)) node = node.Parent End While If node IsNot Nothing Then While TryCast(node, TNode) Is Nothing If node.Parent IsNot Nothing AndAlso hasMatchingText(node.Parent) Then node = node.Parent Else Exit While End If End While End If Assert.NotNull(node) ' If this trips, then node wasn't found Assert.IsAssignableFrom(GetType(TNode), node) If Not prefixMatch Then Assert.Equal(bindText, node.ToString()) Else Assert.StartsWith(bindText, node.ToString) End If Return DirectCast(node, TNode) End Function Public Function FindBindingTextPosition(compilation As Compilation, fileName As String, ByRef bindText As String, Optional which As Integer = 0) As Integer Dim tree = (From t In compilation.SyntaxTrees Where t.FilePath = fileName).Single() Dim bindMarker As String If which > 0 Then bindMarker = "'BIND" & which.ToString() & ":""" Else bindMarker = "'BIND:""" End If Dim text As String = tree.GetRoot().ToFullString() Dim startCommentIndex As Integer = text.IndexOf(bindMarker, StringComparison.Ordinal) + bindMarker.Length Dim endCommentIndex As Integer = text.Length Dim endOfLineIndex = text.IndexOfAny({CChar(vbLf), CChar(vbCr)}, startCommentIndex) If endOfLineIndex > -1 Then endCommentIndex = endOfLineIndex End If ' There may be more than one 'BIND{1234...} marker per line Dim nextMarkerIndex = text.IndexOf("'BIND", startCommentIndex, endCommentIndex - startCommentIndex, StringComparison.Ordinal) If nextMarkerIndex > -1 Then endCommentIndex = nextMarkerIndex End If Dim commentText = text.Substring(startCommentIndex, endCommentIndex - startCommentIndex) Dim endBindCommentLength = commentText.LastIndexOf(""""c) If endBindCommentLength = 0 Then ' This cannot be 0 so it must be text that is quoted. Look for double ending quote ' 'Bind:""some quoted string"" endBindCommentLength = commentText.LastIndexOf("""""", 1, StringComparison.Ordinal) End If bindText = commentText.Substring(0, endBindCommentLength) Dim bindPoint = text.LastIndexOf(bindText, startCommentIndex - bindMarker.Length, StringComparison.Ordinal) Return bindPoint End Function Public Function FindBindingTextPosition(compilation As Compilation, fileName As String) As Integer Dim bindText As String = Nothing Return FindBindingTextPosition(compilation, fileName, bindText) End Function Public Function FindBindingStartText(Of TNode As SyntaxNode)(compilation As Compilation, fileName As String, Optional which As Integer = 0) As TNode Dim tree = (From t In compilation.SyntaxTrees Where t.FilePath = fileName).Single() Dim bindText As String = Nothing Dim bindPoint = FindBindingTextPosition(compilation, fileName, bindText, which) Dim token As SyntaxToken = tree.GetRoot().FindToken(bindPoint) Dim node = token.Parent While (node IsNot Nothing AndAlso node.ToString.StartsWith(bindText, StringComparison.Ordinal) AndAlso Not (TypeOf node Is TNode)) node = node.Parent End While Assert.NotNull(node) ' If this trips, then node wasn't found Assert.IsAssignableFrom(GetType(TNode), node) Assert.Contains(bindText, node.ToString(), StringComparison.Ordinal) Return DirectCast(node, TNode) End Function Friend Class SemanticInfoSummary Public Symbol As Symbol = Nothing Public CandidateReason As CandidateReason = CandidateReason.None Public CandidateSymbols As ImmutableArray(Of ISymbol) = ImmutableArray.Create(Of ISymbol)() Public AllSymbols As ImmutableArray(Of ISymbol) = ImmutableArray.Create(Of ISymbol)() Public [Type] As ITypeSymbol = Nothing Public ConvertedType As ITypeSymbol = Nothing Public ImplicitConversion As Conversion = Nothing Public MemberGroup As ImmutableArray(Of ISymbol) = ImmutableArray.Create(Of ISymbol)() Public [Alias] As IAliasSymbol = Nothing Public ConstantValue As [Optional](Of Object) = Nothing End Class <Extension()> Public Function GetSemanticInfoSummary(model As SemanticModel, node As SyntaxNode) As SemanticInfoSummary Dim summary As New SemanticInfoSummary ' The information that is available varies by the type of the syntax node. Dim semanticModel = DirectCast(model, VBSemanticModel) Dim symbolInfo As SymbolInfo If TypeOf node Is ExpressionSyntax Then symbolInfo = semanticModel.GetSymbolInfo(DirectCast(node, ExpressionSyntax)) summary.MemberGroup = semanticModel.GetMemberGroup(DirectCast(node, ExpressionSyntax)) summary.ConstantValue = semanticModel.GetConstantValue(DirectCast(node, ExpressionSyntax)) Dim typeInfo = semanticModel.GetTypeInfo(DirectCast(node, ExpressionSyntax)) summary.Type = DirectCast(typeInfo.Type, TypeSymbol) summary.ConvertedType = DirectCast(typeInfo.ConvertedType, TypeSymbol) summary.ImplicitConversion = semanticModel.GetConversion(DirectCast(node, ExpressionSyntax)) ElseIf TypeOf node Is AttributeSyntax Then symbolInfo = semanticModel.GetSymbolInfo(DirectCast(node, AttributeSyntax)) summary.MemberGroup = semanticModel.GetMemberGroup(DirectCast(node, AttributeSyntax)) Dim typeInfo = semanticModel.GetTypeInfo(DirectCast(node, AttributeSyntax)) summary.Type = DirectCast(typeInfo.Type, TypeSymbol) summary.ConvertedType = DirectCast(typeInfo.ConvertedType, TypeSymbol) summary.ImplicitConversion = semanticModel.GetConversion(DirectCast(node, AttributeSyntax)) ElseIf TypeOf node Is QueryClauseSyntax Then symbolInfo = semanticModel.GetSymbolInfo(DirectCast(node, QueryClauseSyntax)) Else Throw New NotSupportedException("Type of syntax node is not supported by GetSemanticInfo") End If Assert.NotNull(symbolInfo) summary.Symbol = DirectCast(symbolInfo.Symbol, Symbol) summary.CandidateReason = symbolInfo.CandidateReason summary.CandidateSymbols = symbolInfo.CandidateSymbols summary.AllSymbols = symbolInfo.GetAllSymbols() If TypeOf node Is IdentifierNameSyntax Then summary.Alias = semanticModel.GetAliasInfo(DirectCast(node, IdentifierNameSyntax)) End If Return summary End Function <Extension()> Public Function GetSpeculativeSemanticInfoSummary(model As SemanticModel, position As Integer, expression As ExpressionSyntax, bindingOption As SpeculativeBindingOption) As SemanticInfoSummary Dim summary As New SemanticInfoSummary ' The information that is available varies by the type of the syntax node. Dim semanticModel = DirectCast(model, VBSemanticModel) Dim symbolInfo As SymbolInfo symbolInfo = semanticModel.GetSpeculativeSymbolInfo(position, expression, bindingOption) summary.MemberGroup = semanticModel.GetSpeculativeMemberGroup(position, expression) summary.ConstantValue = semanticModel.GetSpeculativeConstantValue(position, expression) Dim typeInfo = semanticModel.GetSpeculativeTypeInfo(position, expression, bindingOption) summary.Type = DirectCast(typeInfo.Type, TypeSymbol) summary.ConvertedType = DirectCast(typeInfo.ConvertedType, TypeSymbol) summary.ImplicitConversion = semanticModel.GetSpeculativeConversion(position, expression, bindingOption) Assert.NotNull(symbolInfo) summary.Symbol = DirectCast(symbolInfo.Symbol, Symbol) summary.CandidateReason = symbolInfo.CandidateReason summary.CandidateSymbols = symbolInfo.CandidateSymbols summary.AllSymbols = symbolInfo.GetAllSymbols() If TypeOf expression Is IdentifierNameSyntax Then summary.Alias = semanticModel.GetSpeculativeAliasInfo(position, DirectCast(expression, IdentifierNameSyntax), bindingOption) End If Return summary End Function Public Function GetSemanticInfoSummary(compilation As Compilation, node As SyntaxNode) As SemanticInfoSummary Dim tree = node.SyntaxTree Dim semanticModel = DirectCast(compilation.GetSemanticModel(tree), VBSemanticModel) Return GetSemanticInfoSummary(semanticModel, node) End Function Public Function GetSemanticInfoSummary(Of TSyntax As SyntaxNode)(compilation As Compilation, fileName As String, Optional which As Integer = 0) As SemanticInfoSummary Dim node As TSyntax = CompilationUtils.FindBindingText(Of TSyntax)(compilation, fileName, which) Return GetSemanticInfoSummary(compilation, node) End Function Public Function GetPreprocessingSymbolInfo(compilation As Compilation, fileName As String, Optional which As Integer = 0) As VisualBasicPreprocessingSymbolInfo Dim node = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, fileName, which) Dim semanticModel = DirectCast(compilation.GetSemanticModel(node.SyntaxTree), VBSemanticModel) Return semanticModel.GetPreprocessingSymbolInfo(node) End Function Public Function GetSemanticModel(compilation As Compilation, fileName As String) As VBSemanticModel Dim tree = (From t In compilation.SyntaxTrees Where t.FilePath = fileName).Single() Return DirectCast(compilation.GetSemanticModel(tree), VBSemanticModel) End Function ''' <summary> ''' Create a parse tree from the data inside an XElement ''' </summary> ''' <param name="programElement">The program element to create the tree from according to the following schema ''' &lt;file name="filename.vb[optional]"&gt; ''' source ''' &lt;/file&gt; ''' </param> Public Function CreateParseTree(programElement As XElement) As SyntaxTree Return VisualBasicSyntaxTree.ParseText(FilterString(programElement.Value), path:=If(programElement.@name, ""), encoding:=Encoding.UTF8) End Function ''' <summary> ''' Create a parse tree from the data inside an XElement ''' </summary> ''' <param name="programElement">The program element to create the tree from according to the following schema ''' &lt;file name="filename.vb[optional]"&gt; ''' source ''' &lt;/file&gt; ''' </param> Public Function CreateParseTreeAndSpans(programElement As XElement, Optional parseOptions As VisualBasicParseOptions = Nothing) As (tree As SyntaxTree, spans As IList(Of TextSpan)) Dim codeWithMarker As String = FilterString(programElement.Value) Dim codeWithoutMarker As String = Nothing Dim spans As ImmutableArray(Of TextSpan) = Nothing MarkupTestFile.GetSpans(codeWithMarker, codeWithoutMarker, spans) Dim text = SourceText.From(codeWithoutMarker, Encoding.UTF8) Return (VisualBasicSyntaxTree.ParseText(text, parseOptions, If(programElement.@name, "")), spans) End Function ' Find a node inside a tree. Public Function FindTokenFromText(tree As SyntaxTree, textToFind As String) As SyntaxToken Dim text As String = tree.GetText().ToString() Dim position As Integer = text.IndexOf(textToFind, StringComparison.Ordinal) Dim node = tree.GetRoot().FindToken(position) Return node End Function ' Find a position inside a tree. Public Function FindPositionFromText(tree As SyntaxTree, textToFind As String) As Integer Dim text As String = tree.GetText().ToString() Dim position As Integer = text.IndexOf(textToFind, StringComparison.Ordinal) Return position End Function ' Find a node inside a tree. Public Function FindNodeFromText(tree As SyntaxTree, textToFind As String) As SyntaxNode Return FindTokenFromText(tree, textToFind).Parent End Function ' Find a node of a type inside a tree. Public Function FindNodeOfTypeFromText(Of TNode As SyntaxNode)(tree As SyntaxTree, textToFind As String) As TNode Dim node = FindNodeFromText(tree, textToFind) While node IsNot Nothing AndAlso Not TypeOf node Is TNode node = node.Parent End While Return DirectCast(node, TNode) End Function ' Get the syntax tree with a given name. Public Function GetTree(compilation As Compilation, name As String) As SyntaxTree Return (From t In compilation.SyntaxTrees Where t.FilePath = name).First() End Function ' Get the symbol with a given full name. It must be unambiguous. Public Function GetSymbolByFullName(compilation As VisualBasicCompilation, methodName As String) As Symbol Dim names = New List(Of String)() Dim offset = 0 While True ' Find the next "."c separator but skip the first character since ' the name may begin with "."c (in ".ctor" for instance). Dim separator = methodName.IndexOf("."c, offset + 1) If separator < 0 Then names.Add(methodName.Substring(offset)) Exit While End If names.Add(methodName.Substring(offset, separator - offset)) offset = separator + 1 End While Dim currentSymbol As Symbol = compilation.GlobalNamespace For Each name In names Assert.True(TypeOf currentSymbol Is NamespaceOrTypeSymbol, String.Format("{0} does not have members", currentSymbol.ToDisplayString(SymbolDisplayFormat.TestFormat))) Dim currentContainer = DirectCast(currentSymbol, NamespaceOrTypeSymbol) Dim members = currentContainer.GetMembers(name) Assert.True(members.Any(), String.Format("No members named {0} inside {1}", name, currentSymbol.ToDisplayString(SymbolDisplayFormat.TestFormat))) Assert.True(members.Length() <= 1, String.Format("Multiple members named {0} inside {1}", name, currentSymbol.ToDisplayString(SymbolDisplayFormat.TestFormat))) currentSymbol = members.First() Next Return currentSymbol End Function ' Check that the compilation has no parse or declaration errors. Public Sub AssertNoDeclarationDiagnostics(compilation As VisualBasicCompilation, Optional suppressInfos As Boolean = True) AssertNoDiagnostics(compilation.GetDeclarationDiagnostics(), suppressInfos) End Sub ''' <remarks> ''' Does not consider INFO diagnostics. ''' </remarks> <Extension()> Public Sub AssertNoDiagnostics(compilation As VisualBasicCompilation, Optional suppressInfos As Boolean = True) AssertNoDiagnostics(compilation.GetDiagnostics(), suppressInfos) End Sub ' Check that the compilation has no parse, declaration errors/warnings, or compilation errors/warnings. ''' <remarks> ''' Does not consider INFO and HIDDEN diagnostics. ''' </remarks> Private Sub AssertNoDiagnostics(diags As ImmutableArray(Of Diagnostic), suppressInfos As Boolean) If suppressInfos Then diags = diags.WhereAsArray(Function(d) d.Severity > DiagnosticSeverity.Info) End If If diags.Length > 0 Then Console.WriteLine("Unexpected diagnostics found:") For Each d In diags Console.WriteLine(ErrorText(d)) Next Assert.True(False, "Should not have any diagnostics") End If End Sub ' Check that the compilation has no parse, declaration errors, or compilation errors. <Extension()> Public Sub AssertNoErrors(compilation As Compilation) AssertNoErrors(compilation.GetDiagnostics()) End Sub ' Check that the compilation has no parse, declaration errors, or compilation errors. <Extension()> Public Sub AssertNoErrors(errors As ImmutableArray(Of Diagnostic)) Dim diags As ImmutableArray(Of Diagnostic) = errors.WhereAsArray(Function(e) e.Severity = DiagnosticSeverity.Error) If diags.Length > 0 Then Console.WriteLine("Unexpected errors found:") For Each d In diags Console.WriteLine(ErrorText(d)) Next Assert.True(False, "Should not have any errors") End If End Sub ''' <summary> ''' Check that a compilation has these declaration errors. ''' </summary> ''' <param name="compilation"></param> ''' <param name="errs">Expected errors according to this schema ''' &lt;error&gt;[full errors text]&lt;/error&gt;</param> ''' <param name="suppressInfos">True to ignore info-severity diagnostics.</param> ''' <remarks></remarks> <Extension()> Public Sub AssertTheseDeclarationDiagnostics(compilation As VisualBasicCompilation, errs As XElement, Optional suppressInfos As Boolean = True) AssertTheseDiagnostics(compilation.GetDeclarationDiagnostics(), errs, suppressInfos) End Sub <Extension()> Public Sub AssertTheseParseDiagnostics(compilation As VisualBasicCompilation, errs As XElement, Optional suppressInfos As Boolean = True) AssertTheseDiagnostics(compilation.GetParseDiagnostics(), errs, suppressInfos) End Sub ''' <summary> ''' Check that a compilation has these errors at Compile stage or before. ''' </summary> ''' <param name="compilation"></param> ''' <param name="errs">Expected errors according to this schema ''' &lt;error&gt;[full errors text]&lt;/error&gt;</param> ''' <param name="suppressInfos">True to ignore info-severity diagnostics.</param> ''' <remarks></remarks> <Extension()> Public Sub AssertTheseCompileDiagnostics(compilation As Compilation, Optional errs As XElement = Nothing, Optional suppressInfos As Boolean = True) If errs Is Nothing Then errs = <errors/> End If AssertTheseDiagnostics(DirectCast(compilation, VisualBasicCompilation).GetDiagnostics(CompilationStage.Compile), errs, suppressInfos) End Sub ''' <summary> ''' Check that a compilation has these errors during Emit. ''' </summary> ''' <param name="compilation"></param> ''' <param name="errs">Expected errors according to this schema ''' &lt;error&gt;[full errors text]&lt;/error&gt;</param> ''' <param name="suppressInfos">True to ignore info-severity diagnostics.</param> ''' <remarks></remarks> <Extension()> Public Sub AssertTheseEmitDiagnostics(compilation As Compilation, Optional errs As XElement = Nothing, Optional suppressInfos As Boolean = True) If errs Is Nothing Then errs = <errors/> End If Using assemblyStream As New MemoryStream() Using pdbStream As New MemoryStream() Dim diagnostics = compilation.Emit(assemblyStream, pdbStream:=pdbStream).Diagnostics AssertTheseDiagnostics(diagnostics, errs, suppressInfos) End Using End Using End Sub <Extension()> Public Sub AssertTheseDiagnostics(tree As SyntaxTree, errs As XElement, Optional suppressInfos As Boolean = True) AssertTheseDiagnostics(tree.GetDiagnostics().AsImmutable(), errs, suppressInfos) End Sub ''' <summary> ''' Check that a compilation has these declaration or compilation errors. ''' </summary> ''' <param name="compilation"></param> ''' <param name="errs">Expected errors according to this schema ''' &lt;error&gt;[full errors text]&lt;/error&gt;</param> ''' <param name="suppressInfos">True to ignore info-severity diagnostics.</param> ''' <remarks></remarks> <Extension()> Public Sub AssertTheseDiagnostics(compilation As Compilation, Optional errs As XElement = Nothing, Optional suppressInfos As Boolean = True) If errs Is Nothing Then errs = <errors/> End If AssertTheseDiagnostics(DirectCast(compilation, VisualBasicCompilation).GetDiagnostics(CompilationStage.Compile), errs, suppressInfos) End Sub <Extension()> Public Sub AssertTheseDiagnostics(compilation As Compilation, errs As XCData, Optional suppressInfos As Boolean = True) AssertTheseDiagnostics(DirectCast(compilation, VisualBasicCompilation).GetDiagnostics(CompilationStage.Compile), errs, suppressInfos) End Sub ' Check that a compilation has these declaration or compilation errors. <Extension()> Public Sub AssertTheseDiagnostics(compilation As Compilation, errs As String, Optional suppressInfos As Boolean = True) AssertTheseDiagnostics(DirectCast(compilation, VisualBasicCompilation).GetDiagnostics(CompilationStage.Compile), errs, suppressInfos) End Sub ''' <param name="errors"></param> ''' <param name="errs">Expected errors according to this schema ''' &lt;expected&gt;[full errors text]&lt;/expected&gt;</param> ''' <param name="suppressInfos">True to ignore info-severity diagnostics.</param> ''' <remarks></remarks> <Extension()> Public Sub AssertTheseDiagnostics(errors As ImmutableArray(Of Diagnostic), errs As XElement, Optional suppressInfos As Boolean = True) If errs Is Nothing Then errs = <errors/> End If Dim expectedText = FilterString(errs.Value) AssertTheseDiagnostics(errors, expectedText, suppressInfos) End Sub <Extension()> Public Sub AssertTheseDiagnostics(errors As ImmutableArray(Of Diagnostic), errs As XCData, Optional suppressInfos As Boolean = True) Dim expectedText = FilterString(errs.Value) AssertTheseDiagnostics(errors, expectedText, suppressInfos) End Sub Private Sub AssertTheseDiagnostics(errors As ImmutableArray(Of Diagnostic), expectedText As String, suppressInfos As Boolean) Dim actualText = DumpAllDiagnostics(errors.ToArray(), suppressInfos) If expectedText <> actualText Then Dim messages = ParserTestUtilities.PooledStringBuilderPool.Allocate() With messages.Builder .AppendLine() If actualText.StartsWith(expectedText, StringComparison.Ordinal) AndAlso actualText.Substring(expectedText.Length).Trim().Length > 0 Then .AppendLine("UNEXPECTED ERROR MESSAGES:") .AppendLine(actualText.Substring(expectedText.Length)) Assert.True(False, .ToString()) Else Dim expectedLines = expectedText.Split({vbCrLf, vbLf}, StringSplitOptions.RemoveEmptyEntries) Dim actualLines = actualText.Split({vbCrLf, vbLf}, StringSplitOptions.RemoveEmptyEntries) Dim appendedLines As Integer = 0 .AppendLine("MISSING ERROR MESSAGES:") For Each l In expectedLines If Not actualLines.Contains(l) Then .AppendLine(l) appendedLines += 1 End If Next .AppendLine("UNEXPECTED ERROR MESSAGES:") For Each l In actualLines If Not expectedLines.Contains(l) Then .AppendLine(l) appendedLines += 1 End If Next If appendedLines > 0 Then Assert.True(False, .ToString()) Else CompareLineByLine(expectedText, actualText) End If End If End With messages.Free() End If End Sub Private Sub CompareLineByLine(expected As String, actual As String) Dim expectedReader = New StringReader(expected) Dim actualReader = New StringReader(actual) Dim expectedPooledBuilder = PooledStringBuilderPool.Allocate() Dim actualPooledBuilder = PooledStringBuilderPool.Allocate() Dim expectedBuilder = expectedPooledBuilder.Builder Dim actualBuilder = actualPooledBuilder.Builder Dim expectedLine = expectedReader.ReadLine() Dim actualLine = actualReader.ReadLine() While expectedLine IsNot Nothing AndAlso actualLine IsNot Nothing If Not expectedLine.Equals(actualLine) Then expectedBuilder.AppendLine("<! " & expectedLine) actualBuilder.AppendLine("!> " & actualLine) Else expectedBuilder.AppendLine(expectedLine) actualBuilder.AppendLine(actualLine) End If expectedLine = expectedReader.ReadLine() actualLine = actualReader.ReadLine() End While While expectedLine IsNot Nothing expectedBuilder.AppendLine("<! " & expectedLine) expectedLine = expectedReader.ReadLine() End While While actualLine IsNot Nothing actualBuilder.AppendLine("!> " & actualLine) actualLine = actualReader.ReadLine() End While Assert.Equal(expectedPooledBuilder.ToStringAndFree(), actualPooledBuilder.ToStringAndFree()) End Sub ' There are certain cases where multiple distinct errors are ' reported where the error code and text span are the same. When ' sorting such cases, we should preserve the original order. Private Structure DiagnosticAndIndex Public Sub New(diagnostic As Diagnostic, index As Integer) Me.Diagnostic = diagnostic Me.Index = index End Sub Public ReadOnly Diagnostic As Diagnostic Public ReadOnly Index As Integer End Structure Private Function DumpAllDiagnostics(allDiagnostics As Diagnostic(), suppressInfos As Boolean) As String Return DumpAllDiagnostics(allDiagnostics.ToImmutableArray(), suppressInfos) End Function Friend Function DumpAllDiagnostics(allDiagnostics As ImmutableArray(Of Diagnostic), suppressInfos As Boolean) As String Dim diagnosticsAndIndices(allDiagnostics.Length - 1) As DiagnosticAndIndex For i = 0 To allDiagnostics.Length - 1 diagnosticsAndIndices(i) = New DiagnosticAndIndex(allDiagnostics(i), i) Next Array.Sort(diagnosticsAndIndices, Function(diag1, diag2) CompareErrors(diag1, diag2)) Dim builder = PooledStringBuilderPool.Allocate() With builder.Builder For Each e In diagnosticsAndIndices If Not suppressInfos OrElse e.Diagnostic.Severity > DiagnosticSeverity.Info Then .Append(ErrorText(e.Diagnostic)) End If Next End With Return builder.ToStringAndFree() End Function ' Get the text of a diagnostic. For source error, includes the text of the line itself, with the ' span underlined. Private Function ErrorText(e As Diagnostic) As String Dim message = e.Id + ": " + e.GetMessage(EnsureEnglishUICulture.PreferredOrNull) If e.Location.IsInSource Then Dim sourceLocation = e.Location Dim offsetInLine As Integer = 0 Dim lineText As String = GetLineText(sourceLocation.SourceTree.GetText(), sourceLocation.SourceSpan.Start, offsetInLine) Return message + Environment.NewLine + lineText + Environment.NewLine + New String(" "c, offsetInLine) + New String("~"c, Math.Max(Math.Min(sourceLocation.SourceSpan.Length, lineText.Length - offsetInLine + 1), 1)) + Environment.NewLine ElseIf e.Location.IsInMetadata Then Return message + Environment.NewLine + String.Format("in metadata assembly '{0}'" + Environment.NewLine, e.Location.MetadataModule.ContainingAssembly.Identity.Name) Else Return message + Environment.NewLine End If End Function ' Get the text of a line that contains the offset, and return the offset within that line. Private Function GetLineText(text As SourceText, position As Integer, ByRef offsetInLine As Integer) As String Dim textLine = text.Lines.GetLineFromPosition(position) offsetInLine = position - textLine.Start Return textLine.ToString() End Function Private Function CompareErrors(diagAndIndex1 As DiagnosticAndIndex, diagAndIndex2 As DiagnosticAndIndex) As Integer ' Sort by no location, then source, then metadata. Sort within each group. Dim diag1 = diagAndIndex1.Diagnostic Dim diag2 = diagAndIndex2.Diagnostic Dim loc1 = diag1.Location Dim loc2 = diag2.Location If Not (loc1.IsInSource Or loc1.IsInMetadata) Then If Not (loc2.IsInSource Or loc2.IsInMetadata) Then ' Both have no location. Sort by code, then by message. If diag1.Code < diag2.Code Then Return -1 If diag1.Code > diag2.Code Then Return 1 Return diag1.GetMessage(EnsureEnglishUICulture.PreferredOrNull).CompareTo(diag2.GetMessage(EnsureEnglishUICulture.PreferredOrNull)) Else Return -1 End If ElseIf Not (loc2.IsInSource Or loc2.IsInMetadata) Then Return 1 ElseIf loc1.IsInSource AndAlso loc2.IsInSource Then ' source by tree, then span start, then span end, then error code, then message Dim sourceTree1 = loc1.SourceTree Dim sourceTree2 = loc2.SourceTree If sourceTree1.FilePath <> sourceTree2.FilePath Then Return sourceTree1.FilePath.CompareTo(sourceTree2.FilePath) If loc1.SourceSpan.Start < loc2.SourceSpan.Start Then Return -1 If loc1.SourceSpan.Start > loc2.SourceSpan.Start Then Return 1 If loc1.SourceSpan.Length < loc2.SourceSpan.Length Then Return -1 If loc1.SourceSpan.Length > loc2.SourceSpan.Length Then Return 1 If diag1.Code < diag2.Code Then Return -1 If diag1.Code > diag2.Code Then Return 1 Return diag1.GetMessage(EnsureEnglishUICulture.PreferredOrNull).CompareTo(diag2.GetMessage(EnsureEnglishUICulture.PreferredOrNull)) ElseIf loc1.IsInMetadata AndAlso loc2.IsInMetadata Then ' sort by assembly name, then by error code Dim name1 = loc1.MetadataModule.ContainingAssembly.Name Dim name2 = loc2.MetadataModule.ContainingAssembly.Name If name1 <> name2 Then Return name1.CompareTo(name2) If diag1.Code < diag2.Code Then Return -1 If diag1.Code > diag2.Code Then Return 1 Return diag1.GetMessage(EnsureEnglishUICulture.PreferredOrNull).CompareTo(diag2.GetMessage(EnsureEnglishUICulture.PreferredOrNull)) ElseIf loc1.IsInSource Then Return -1 ElseIf loc2.IsInSource Then Return 1 End If ' Preserve original order. Return diagAndIndex1.Index - diagAndIndex2.Index End Function Public Function GetTypeSymbol(compilation As Compilation, semanticModel As SemanticModel, treeName As String, stringInDecl As String) As INamedTypeSymbol Dim tree = CompilationUtils.GetTree(compilation, treeName) Dim node = CompilationUtils.FindTokenFromText(tree, stringInDecl).Parent While Not (TypeOf node Is TypeStatementSyntax) node = node.Parent Assert.NotNull(node) End While Return DirectCast(semanticModel, VBSemanticModel).GetDeclaredSymbol(DirectCast(node, TypeStatementSyntax)) End Function Public Function GetEnumSymbol(compilation As Compilation, semanticModel As SemanticModel, treeName As String, stringInDecl As String) As INamedTypeSymbol Dim tree = CompilationUtils.GetTree(compilation, treeName) Dim node = CompilationUtils.FindTokenFromText(tree, stringInDecl).Parent While Not (TypeOf node Is EnumStatementSyntax) node = node.Parent Assert.NotNull(node) End While Return DirectCast(semanticModel, VBSemanticModel).GetDeclaredSymbol(DirectCast(node, EnumStatementSyntax)) End Function Public Function GetDelegateSymbol(compilation As Compilation, semanticModel As SemanticModel, treeName As String, stringInDecl As String) As NamedTypeSymbol Dim tree = CompilationUtils.GetTree(compilation, treeName) Dim node = CompilationUtils.FindTokenFromText(tree, stringInDecl).Parent While Not (TypeOf node Is MethodBaseSyntax) node = node.Parent Assert.NotNull(node) End While Return DirectCast(semanticModel.GetDeclaredSymbol(DirectCast(node, MethodBaseSyntax)), NamedTypeSymbol) End Function Public Function GetTypeSymbol(compilation As Compilation, treeName As String, stringInDecl As String, Optional isDistinct As Boolean = True) As List(Of INamedTypeSymbol) Dim tree = CompilationUtils.GetTree(compilation, treeName) Dim bindings = DirectCast(compilation.GetSemanticModel(tree), VBSemanticModel) Dim text As String = tree.GetText().ToString() Dim pos = 0 Dim node As SyntaxNode Dim symType = New List(Of INamedTypeSymbol) Do pos = text.IndexOf(stringInDecl, pos + 1, StringComparison.Ordinal) If pos >= 0 Then node = tree.GetRoot().FindToken(pos).Parent While Not (TypeOf node Is TypeStatementSyntax OrElse TypeOf node Is EnumStatementSyntax) If node Is Nothing Then Exit While End If node = node.Parent End While If Not node Is Nothing Then If TypeOf node Is TypeStatementSyntax Then Dim temp = bindings.GetDeclaredSymbol(DirectCast(node, TypeStatementSyntax)) symType.Add(temp) Else Dim temp = bindings.GetDeclaredSymbol(DirectCast(node, EnumStatementSyntax)) symType.Add(temp) End If End If Else Exit Do End If Loop If (isDistinct) Then symType = (From temp In symType Distinct Select temp Order By temp.ToDisplayString()).ToList() Else symType = (From temp In symType Select temp Order By temp.ToDisplayString()).ToList() End If Return symType End Function Public Function VerifyGlobalNamespace(compilation As Compilation, treeName As String, symbolName As String, ExpectedDispName() As String, isDistinct As Boolean) As List(Of INamedTypeSymbol) Dim tree = CompilationUtils.GetTree(compilation, treeName) Dim bindings1 = compilation.GetSemanticModel(tree) Dim symbols = GetTypeSymbol(compilation, treeName, symbolName, isDistinct) Assert.Equal(ExpectedDispName.Count, symbols.Count) ExpectedDispName = (From temp In ExpectedDispName Select temp Order By temp).ToArray() Dim count = 0 For Each item In symbols Assert.NotNull(item) Assert.Equal(ExpectedDispName(count), item.ToDisplayString()) count += 1 Next Return symbols End Function Public Function VerifyGlobalNamespace(compilation As VisualBasicCompilation, treeName As String, symbolName As String, ParamArray expectedDisplayNames() As String) As List(Of INamedTypeSymbol) Return VerifyGlobalNamespace(compilation, treeName, symbolName, expectedDisplayNames, True) End Function Public Function VerifyIsGlobal(globalNS1 As ISymbol, Optional expected As Boolean = True) As NamespaceSymbol Dim nsSymbol = DirectCast(globalNS1, NamespaceSymbol) Assert.NotNull(nsSymbol) If (expected) Then Assert.True(nsSymbol.IsGlobalNamespace) Else Assert.False(nsSymbol.IsGlobalNamespace) End If Return nsSymbol End Function Public Sub CheckSymbols(Of TSymbol As ISymbol)(symbols As ImmutableArray(Of TSymbol), ParamArray descriptions As String()) Assert.Equal(symbols.Length, descriptions.Length) Dim symbolDescriptions As String() = (From s In symbols Select s.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat)).ToArray() Array.Sort(descriptions) Array.Sort(symbolDescriptions) For i = 0 To descriptions.Length - 1 Assert.Equal(symbolDescriptions(i), descriptions(i)) Next End Sub Public Sub CheckSymbols(Of TSymbol As ISymbol)(symbols As TSymbol(), ParamArray descriptions As String()) CheckSymbols(symbols.AsImmutableOrNull(), descriptions) End Sub Public Sub CheckSymbol(symbol As ISymbol, description As String) Assert.Equal(symbol.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat), description) End Sub Public Function SortAndMergeStrings(ParamArray strings As String()) As String Array.Sort(strings) Dim builder = PooledStringBuilderPool.Allocate() With builder.Builder For Each item In strings If .Length > 0 Then .AppendLine() End If .Append(item) Next End With Return builder.ToStringAndFree() End Function Public Sub CheckSymbolsUnordered(Of TSymbol As ISymbol)(symbols As ImmutableArray(Of TSymbol), ParamArray descriptions As String()) Assert.Equal(symbols.Length, descriptions.Length) Assert.Equal(SortAndMergeStrings(descriptions), SortAndMergeStrings(symbols.Select(Function(s) s.ToDisplayString()).ToArray())) End Sub <Extension> Friend Function LookupNames(model As SemanticModel, position As Integer, Optional container As INamespaceOrTypeSymbol = Nothing, Optional namespacesAndTypesOnly As Boolean = False) As List(Of String) Dim result = If(namespacesAndTypesOnly, model.LookupNamespacesAndTypes(position, container), model.LookupSymbols(position, container)) Return result.Select(Function(s) s.Name).Distinct().ToList() End Function End Module
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.IO Imports System.Runtime.CompilerServices Imports System.Runtime.InteropServices Imports System.Text Imports System.Xml.Linq Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.Text Imports Roslyn.Test.Utilities Imports Roslyn.Test.Utilities.TestBase Imports Roslyn.Test.Utilities.TestMetadata Imports Xunit Friend Module CompilationUtils Private Function ParseSources(source As IEnumerable(Of String), parseOptions As VisualBasicParseOptions) As IEnumerable(Of SyntaxTree) Return source.Select(Function(s) VisualBasicSyntaxTree.ParseText(s, parseOptions)) End Function Public Function CreateCompilation( source As BasicTestSource, Optional references As IEnumerable(Of MetadataReference) = Nothing, Optional options As VisualBasicCompilationOptions = Nothing, Optional parseOptions As VisualBasicParseOptions = Nothing, Optional targetFramework As TargetFramework = TargetFramework.StandardAndVBRuntime, Optional assemblyName As String = Nothing) As VisualBasicCompilation references = TargetFrameworkUtil.GetReferences(targetFramework, references) Return CreateEmptyCompilation(source, references, options, parseOptions, assemblyName) End Function Public Function CreateEmptyCompilation( source As BasicTestSource, Optional references As IEnumerable(Of MetadataReference) = Nothing, Optional options As VisualBasicCompilationOptions = Nothing, Optional parseOptions As VisualBasicParseOptions = Nothing, Optional assemblyName As String = Nothing) As VisualBasicCompilation If options Is Nothing Then options = TestOptions.ReleaseDll End If ' Using single-threaded build if debugger attached, to simplify debugging. If Debugger.IsAttached Then options = options.WithConcurrentBuild(False) End If Dim trees = source.GetSyntaxTrees(parseOptions, assemblyName) Dim createCompilationLambda = Function() Return VisualBasicCompilation.Create( If(assemblyName, GetUniqueName()), trees, references, options) End Function ValidateCompilation(createCompilationLambda) Return createCompilationLambda() End Function Private Sub ValidateCompilation(createCompilationLambda As Func(Of VisualBasicCompilation)) CompilationExtensions.ValidateIOperations(createCompilationLambda) VerifyUsedAssemblyReferences(createCompilationLambda) End Sub Private Sub VerifyUsedAssemblyReferences(createCompilationLambda As Func(Of VisualBasicCompilation)) If Not CompilationExtensions.EnableVerifyUsedAssemblies Then Return End If Dim comp = createCompilationLambda() Dim used = comp.GetUsedAssemblyReferences() Dim compileDiagnostics = comp.GetDiagnostics() Dim emitDiagnostics = comp.GetEmitDiagnostics() Dim resolvedReferences = comp.References.Where(Function(r) r.Properties.Kind = MetadataImageKind.Assembly) If Not compileDiagnostics.Any(Function(d) d.DefaultSeverity = DiagnosticSeverity.Error) Then If resolvedReferences.Count() > used.Length Then AssertSubset(used, resolvedReferences) If Not compileDiagnostics.Any(Function(d) d.Code = ERRID.HDN_UnusedImportClause OrElse d.Code = ERRID.HDN_UnusedImportStatement) Then Dim comp2 = comp.RemoveAllReferences().AddReferences(used.Concat(comp.References.Where(Function(r) r.Properties.Kind = MetadataImageKind.Module))) comp2.GetEmitDiagnostics().Verify( emitDiagnostics.Select(Function(d) New DiagnosticDescription(d, errorCodeOnly:=False, includeDefaultSeverity:=False, includeEffectiveSeverity:=False)).ToArray()) End If Else AssertEx.Equal(resolvedReferences, used) End If Else AssertSubset(used, resolvedReferences) End If End Sub Private Sub AssertSubset(used As ImmutableArray(Of MetadataReference), resolvedReferences As IEnumerable(Of MetadataReference)) For Each reference In used Assert.Contains(reference, resolvedReferences) Next End Sub Public Function CreateEmptyCompilation( identity As AssemblyIdentity, source As BasicTestSource, Optional references As MetadataReference() = Nothing, Optional options As VisualBasicCompilationOptions = Nothing) As VisualBasicCompilation Dim trees = source.GetSyntaxTrees() Dim createCompilationLambda = Function() Return VisualBasicCompilation.Create(identity.Name, trees, references, options) End Function ValidateCompilation(createCompilationLambda) Dim c = createCompilationLambda() Assert.NotNull(c.Assembly) ' force creation of SourceAssemblySymbol DirectCast(c.Assembly, SourceAssemblySymbol).m_lazyIdentity = identity Return c End Function Public Function CreateCompilationWithMscorlib40( source As BasicTestSource, Optional references As IEnumerable(Of MetadataReference) = Nothing, Optional options As VisualBasicCompilationOptions = Nothing, Optional parseOptions As VisualBasicParseOptions = Nothing, Optional assemblyName As String = Nothing) As VisualBasicCompilation Return CreateCompilation(source, references, options, parseOptions, TargetFramework.Mscorlib40, assemblyName) End Function Public Function CreateCompilationWithMscorlib45( source As BasicTestSource, Optional references As IEnumerable(Of MetadataReference) = Nothing, Optional options As VisualBasicCompilationOptions = Nothing, Optional parseOptions As VisualBasicParseOptions = Nothing, Optional assemblyName As String = Nothing) As VisualBasicCompilation Return CreateCompilation(source, references, options, parseOptions, TargetFramework.Mscorlib45, assemblyName) End Function Public Function CreateCompilationWithMscorlib45AndVBRuntime( source As BasicTestSource, Optional references As IEnumerable(Of MetadataReference) = Nothing, Optional options As VisualBasicCompilationOptions = Nothing, Optional parseOptions As VisualBasicParseOptions = Nothing, Optional assemblyName As String = Nothing) As VisualBasicCompilation Return CreateCompilation(source, references, options, parseOptions, TargetFramework.Mscorlib45AndVBRuntime, assemblyName) End Function Public Function CreateCompilationWithWinRt(source As XElement) As VisualBasicCompilation Return CreateEmptyCompilationWithReferences(source, WinRtRefs) End Function Public Function CreateCompilationWithMscorlib40AndReferences(source As XElement, references As IEnumerable(Of MetadataReference), Optional options As VisualBasicCompilationOptions = Nothing, Optional parseOptions As VisualBasicParseOptions = Nothing) As VisualBasicCompilation Return CreateEmptyCompilationWithReferences(source, {CType(Net40.mscorlib, MetadataReference)}.Concat(references), options, parseOptions:=parseOptions) End Function ''' <summary> ''' ''' </summary> ''' <param name="source">The sources compile according to the following schema ''' &lt;compilation name="assemblyname[optional]"&gt; ''' &lt;file name="file1.vb[optional]"&gt; ''' source ''' &lt;/file&gt; ''' &lt;/compilation&gt; ''' </param> Public Function CreateCompilationWithMscorlib40(source As XElement, outputKind As OutputKind, Optional parseOptions As VisualBasicParseOptions = Nothing) As VisualBasicCompilation Return CreateEmptyCompilationWithReferences(source, {Net40.mscorlib}, New VisualBasicCompilationOptions(outputKind), parseOptions:=parseOptions) End Function ''' <summary> ''' ''' </summary> ''' <param name="source">The sources compile according to the following schema ''' &lt;compilation name="assemblyname[optional]"&gt; ''' &lt;file name="file1.vb[optional]"&gt; ''' source ''' &lt;/file&gt; ''' &lt;/compilation&gt; ''' </param> Public Function CreateCompilationWithMscorlib40AndVBRuntime( source As XElement, Optional additionalRefs As MetadataReference() = Nothing, Optional options As VisualBasicCompilationOptions = Nothing, Optional parseOptions As VisualBasicParseOptions = Nothing, Optional assemblyName As String = Nothing) As VisualBasicCompilation If additionalRefs Is Nothing Then additionalRefs = {} Dim references = {CType(Net40.mscorlib, MetadataReference), Net40.System, Net40.MicrosoftVisualBasic}.Concat(additionalRefs) Return CreateEmptyCompilationWithReferences(source, references, options, parseOptions:=parseOptions, assemblyName:=assemblyName) End Function Public Function CreateCompilationWithMscorlib40AndVBRuntime(source As IEnumerable(Of SyntaxTree), options As VisualBasicCompilationOptions, Optional assemblyName As String = Nothing) As VisualBasicCompilation Dim references = {MscorlibRef, SystemRef, MsvbRef} Return CreateEmptyCompilation(source.ToArray(), references, options:=options, assemblyName:=assemblyName) End Function Public Function CreateCompilationWithMscorlib40AndVBRuntime(source As XElement, options As VisualBasicCompilationOptions) As VisualBasicCompilation Return CreateCompilationWithMscorlib40AndVBRuntime(source, Nothing, options, parseOptions:=If(options Is Nothing, Nothing, options.ParseOptions)) End Function Public ReadOnly XmlReferences As MetadataReference() = {SystemRef, SystemCoreRef, SystemXmlRef, SystemXmlLinqRef} Public ReadOnly Net40XmlReferences As MetadataReference() = {Net40.SystemCore, Net40.SystemXml, Net40.SystemXmlLinq} Public ReadOnly Net451XmlReferences As MetadataReference() = {Net451.SystemCore, Net451.SystemXml, Net451.SystemXmlLinq} ''' <summary> ''' ''' </summary> ''' <param name="source">The sources compile according to the following schema ''' &lt;compilation name="assemblyname[optional]"&gt; ''' &lt;file name="file1.vb[optional]"&gt; ''' source ''' &lt;/file&gt; ''' &lt;/compilation&gt; ''' </param> Public Function CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( source As XElement, Optional references As IEnumerable(Of MetadataReference) = Nothing, Optional options As VisualBasicCompilationOptions = Nothing, Optional parseOptions As VisualBasicParseOptions = Nothing) As VisualBasicCompilation If references Is Nothing Then references = {} Dim allReferences = {CType(Net40.mscorlib, MetadataReference), Net40.System, Net40.MicrosoftVisualBasic}.Concat(references) If parseOptions Is Nothing AndAlso options IsNot Nothing Then parseOptions = options.ParseOptions End If Return CreateEmptyCompilationWithReferences(source, allReferences, options, parseOptions:=parseOptions) End Function ''' <summary> ''' ''' </summary> ''' <param name="source">The sources compile according to the following schema ''' &lt;compilation name="assemblyname[optional]"&gt; ''' &lt;file name="file1.vb[optional]"&gt; ''' source ''' &lt;/file&gt; ''' &lt;/compilation&gt; ''' </param> Public Function CreateCompilationWithMscorlib45AndVBRuntime( source As XElement, Optional references As IEnumerable(Of MetadataReference) = Nothing, Optional options As VisualBasicCompilationOptions = Nothing, Optional parseOptions As VisualBasicParseOptions = Nothing) As VisualBasicCompilation Dim allReferences = {MscorlibRef_v4_0_30316_17626, MsvbRef_v4_0_30319_17929}.Concat(If(references, {})) Return CreateEmptyCompilationWithReferences(source, allReferences, options, parseOptions:=parseOptions) End Function ''' <summary> ''' ''' </summary> ''' <param name="source">The sources compile according to the following schema ''' &lt;compilation name="assemblyname[optional]"&gt; ''' &lt;file name="file1.vb[optional]"&gt; ''' source ''' &lt;/file&gt; ''' &lt;/compilation&gt; ''' </param> Public Function CreateEmptyCompilationWithReferences(source As XElement, references As IEnumerable(Of MetadataReference), Optional options As VisualBasicCompilationOptions = Nothing, Optional parseOptions As VisualBasicParseOptions = Nothing, Optional assemblyName As String = Nothing) As VisualBasicCompilation Dim sourceTrees = ParseSourceXml(source, parseOptions, assemblyName) Return CreateEmptyCompilationWithReferences(sourceTrees, references, options, assemblyName) End Function Public Function ParseSourceXml(sources As XElement, parseOptions As VisualBasicParseOptions, Optional ByRef assemblyName As String = Nothing, Optional ByRef spans As IEnumerable(Of IEnumerable(Of TextSpan)) = Nothing) As IEnumerable(Of SyntaxTree) If sources.@name IsNot Nothing Then assemblyName = sources.@name End If Dim sourcesTreesAndSpans = From f In sources.<file> Select CreateParseTreeAndSpans(f, parseOptions) spans = From t In sourcesTreesAndSpans Select s = t.spans Return From t In sourcesTreesAndSpans Select t.tree End Function Public Function ToSourceTrees(compilationSources As XElement, Optional parseOptions As VisualBasicParseOptions = Nothing) As IEnumerable(Of SyntaxTree) Dim sourcesTreesAndSpans = From f In compilationSources.<file> Select CreateParseTreeAndSpans(f, parseOptions) Return From t In sourcesTreesAndSpans Select t.tree End Function Public Function CreateEmptyCompilationWithReferences(source As SyntaxTree, references As IEnumerable(Of MetadataReference), Optional options As VisualBasicCompilationOptions = Nothing, Optional assemblyName As String = Nothing) As VisualBasicCompilation Return CreateEmptyCompilationWithReferences({source}, references, options, assemblyName) End Function Public Function CreateEmptyCompilationWithReferences(source As IEnumerable(Of SyntaxTree), references As IEnumerable(Of MetadataReference), Optional options As VisualBasicCompilationOptions = Nothing, Optional assemblyName As String = Nothing) As VisualBasicCompilation If options Is Nothing Then options = TestOptions.ReleaseDll ' Using single-threaded build if debugger attached, to simplify debugging. If Debugger.IsAttached Then options = options.WithConcurrentBuild(False) End If End If Dim createCompilationLambda = Function() Return VisualBasicCompilation.Create(If(assemblyName, GetUniqueName()), source, references, options) End Function ValidateCompilation(createCompilationLambda) Return createCompilationLambda() End Function ''' <summary> ''' ''' </summary> ''' <param name="sources">The sources compile according to the following schema ''' &lt;compilation name="assemblyname[optional]"&gt; ''' &lt;file name="file1.vb[optional]"&gt; ''' source ''' &lt;/file&gt; ''' &lt;/compilation&gt; ''' </param> ''' <param name="ilSource"></param> ''' <returns></returns> ''' <remarks></remarks> Public Function CreateCompilationWithCustomILSource(sources As XElement, ilSource As XCData) As VisualBasicCompilation Return CreateCompilationWithCustomILSource(sources, ilSource.Value) End Function ''' <summary> ''' ''' </summary> ''' <param name="sources">The sources compile according to the following schema ''' &lt;compilation name="assemblyname[optional]"&gt; ''' &lt;file name="file1.vb[optional]"&gt; ''' source ''' &lt;/file&gt; ''' &lt;/compilation&gt; ''' </param> ''' <param name="ilSource"></param> ''' <returns></returns> ''' <remarks></remarks> Public Function CreateCompilationWithCustomILSource(sources As XElement, ilSource As String, Optional options As VisualBasicCompilationOptions = Nothing, Optional ByRef spans As IEnumerable(Of IEnumerable(Of TextSpan)) = Nothing, Optional includeVbRuntime As Boolean = False, Optional includeSystemCore As Boolean = False, Optional appendDefaultHeader As Boolean = True, Optional parseOptions As VisualBasicParseOptions = Nothing, Optional additionalReferences As IEnumerable(Of MetadataReference) = Nothing, <Out> Optional ByRef ilReference As MetadataReference = Nothing, <Out> Optional ByRef ilImage As ImmutableArray(Of Byte) = Nothing ) As VisualBasicCompilation Dim references = If(additionalReferences IsNot Nothing, New List(Of MetadataReference)(additionalReferences), New List(Of MetadataReference)) If includeVbRuntime Then references.Add(MsvbRef) End If If includeSystemCore Then references.Add(SystemCoreRef) End If If ilSource Is Nothing Then Return CreateCompilationWithMscorlib40AndReferences(sources, references, options, parseOptions) End If ilReference = CreateReferenceFromIlCode(ilSource, appendDefaultHeader, ilImage) references.Add(ilReference) Return CreateCompilationWithMscorlib40AndReferences(sources, references, options, parseOptions) End Function Public Function CreateReferenceFromIlCode(ilSource As String, Optional appendDefaultHeader As Boolean = True, <Out> Optional ByRef ilImage As ImmutableArray(Of Byte) = Nothing) As MetadataReference Using reference = IlasmUtilities.CreateTempAssembly(ilSource, appendDefaultHeader) ilImage = ImmutableArray.Create(File.ReadAllBytes(reference.Path)) End Using Return MetadataReference.CreateFromImage(ilImage) End Function Public Function GetUniqueName() As String Return Guid.NewGuid().ToString("D") End Function ' Filter text from within an XElement Public Function FilterString(s As String) As String s = s.Replace(vbCrLf, vbLf) ' If there are already "0d0a", don't replace them with "0d0a0a" s = s.Replace(vbLf, vbCrLf) Dim needToAddBackNewline = s.EndsWith(vbCrLf, StringComparison.Ordinal) s = s.Trim() If needToAddBackNewline Then s &= vbCrLf Return s End Function Public Function FindBindingText(Of TNode As SyntaxNode)(compilation As Compilation, fileName As String, Optional which As Integer = 0, Optional prefixMatch As Boolean = False) As TNode Dim tree = (From t In compilation.SyntaxTrees Where t.FilePath = fileName).Single() Dim bindText As String = Nothing Dim bindPoint = FindBindingTextPosition(compilation, fileName, bindText, which) Dim token = tree.GetRoot().FindToken(bindPoint, True) Dim node = token.Parent Dim hasMatchingText As Func(Of SyntaxNode, Boolean) = Function(n) n.ToString = bindText OrElse (prefixMatch AndAlso TryCast(n, TNode) IsNot Nothing AndAlso n.ToString.StartsWith(bindText)) While (node IsNot Nothing AndAlso Not hasMatchingText(node)) node = node.Parent End While If node IsNot Nothing Then While TryCast(node, TNode) Is Nothing If node.Parent IsNot Nothing AndAlso hasMatchingText(node.Parent) Then node = node.Parent Else Exit While End If End While End If Assert.NotNull(node) ' If this trips, then node wasn't found Assert.IsAssignableFrom(GetType(TNode), node) If Not prefixMatch Then Assert.Equal(bindText, node.ToString()) Else Assert.StartsWith(bindText, node.ToString) End If Return DirectCast(node, TNode) End Function Public Function FindBindingTextPosition(compilation As Compilation, fileName As String, ByRef bindText As String, Optional which As Integer = 0) As Integer Dim tree = (From t In compilation.SyntaxTrees Where t.FilePath = fileName).Single() Dim bindMarker As String If which > 0 Then bindMarker = "'BIND" & which.ToString() & ":""" Else bindMarker = "'BIND:""" End If Dim text As String = tree.GetRoot().ToFullString() Dim startCommentIndex As Integer = text.IndexOf(bindMarker, StringComparison.Ordinal) + bindMarker.Length Dim endCommentIndex As Integer = text.Length Dim endOfLineIndex = text.IndexOfAny({CChar(vbLf), CChar(vbCr)}, startCommentIndex) If endOfLineIndex > -1 Then endCommentIndex = endOfLineIndex End If ' There may be more than one 'BIND{1234...} marker per line Dim nextMarkerIndex = text.IndexOf("'BIND", startCommentIndex, endCommentIndex - startCommentIndex, StringComparison.Ordinal) If nextMarkerIndex > -1 Then endCommentIndex = nextMarkerIndex End If Dim commentText = text.Substring(startCommentIndex, endCommentIndex - startCommentIndex) Dim endBindCommentLength = commentText.LastIndexOf(""""c) If endBindCommentLength = 0 Then ' This cannot be 0 so it must be text that is quoted. Look for double ending quote ' 'Bind:""some quoted string"" endBindCommentLength = commentText.LastIndexOf("""""", 1, StringComparison.Ordinal) End If bindText = commentText.Substring(0, endBindCommentLength) Dim bindPoint = text.LastIndexOf(bindText, startCommentIndex - bindMarker.Length, StringComparison.Ordinal) Return bindPoint End Function Public Function FindBindingTextPosition(compilation As Compilation, fileName As String) As Integer Dim bindText As String = Nothing Return FindBindingTextPosition(compilation, fileName, bindText) End Function Public Function FindBindingStartText(Of TNode As SyntaxNode)(compilation As Compilation, fileName As String, Optional which As Integer = 0) As TNode Dim tree = (From t In compilation.SyntaxTrees Where t.FilePath = fileName).Single() Dim bindText As String = Nothing Dim bindPoint = FindBindingTextPosition(compilation, fileName, bindText, which) Dim token As SyntaxToken = tree.GetRoot().FindToken(bindPoint) Dim node = token.Parent While (node IsNot Nothing AndAlso node.ToString.StartsWith(bindText, StringComparison.Ordinal) AndAlso Not (TypeOf node Is TNode)) node = node.Parent End While Assert.NotNull(node) ' If this trips, then node wasn't found Assert.IsAssignableFrom(GetType(TNode), node) Assert.Contains(bindText, node.ToString(), StringComparison.Ordinal) Return DirectCast(node, TNode) End Function Friend Class SemanticInfoSummary Public Symbol As Symbol = Nothing Public CandidateReason As CandidateReason = CandidateReason.None Public CandidateSymbols As ImmutableArray(Of ISymbol) = ImmutableArray.Create(Of ISymbol)() Public AllSymbols As ImmutableArray(Of ISymbol) = ImmutableArray.Create(Of ISymbol)() Public [Type] As ITypeSymbol = Nothing Public ConvertedType As ITypeSymbol = Nothing Public ImplicitConversion As Conversion = Nothing Public MemberGroup As ImmutableArray(Of ISymbol) = ImmutableArray.Create(Of ISymbol)() Public [Alias] As IAliasSymbol = Nothing Public ConstantValue As [Optional](Of Object) = Nothing End Class <Extension()> Public Function GetSemanticInfoSummary(model As SemanticModel, node As SyntaxNode) As SemanticInfoSummary Dim summary As New SemanticInfoSummary ' The information that is available varies by the type of the syntax node. Dim semanticModel = DirectCast(model, VBSemanticModel) Dim symbolInfo As SymbolInfo If TypeOf node Is ExpressionSyntax Then symbolInfo = semanticModel.GetSymbolInfo(DirectCast(node, ExpressionSyntax)) summary.MemberGroup = semanticModel.GetMemberGroup(DirectCast(node, ExpressionSyntax)) summary.ConstantValue = semanticModel.GetConstantValue(DirectCast(node, ExpressionSyntax)) Dim typeInfo = semanticModel.GetTypeInfo(DirectCast(node, ExpressionSyntax)) summary.Type = DirectCast(typeInfo.Type, TypeSymbol) summary.ConvertedType = DirectCast(typeInfo.ConvertedType, TypeSymbol) summary.ImplicitConversion = semanticModel.GetConversion(DirectCast(node, ExpressionSyntax)) ElseIf TypeOf node Is AttributeSyntax Then symbolInfo = semanticModel.GetSymbolInfo(DirectCast(node, AttributeSyntax)) summary.MemberGroup = semanticModel.GetMemberGroup(DirectCast(node, AttributeSyntax)) Dim typeInfo = semanticModel.GetTypeInfo(DirectCast(node, AttributeSyntax)) summary.Type = DirectCast(typeInfo.Type, TypeSymbol) summary.ConvertedType = DirectCast(typeInfo.ConvertedType, TypeSymbol) summary.ImplicitConversion = semanticModel.GetConversion(DirectCast(node, AttributeSyntax)) ElseIf TypeOf node Is QueryClauseSyntax Then symbolInfo = semanticModel.GetSymbolInfo(DirectCast(node, QueryClauseSyntax)) Else Throw New NotSupportedException("Type of syntax node is not supported by GetSemanticInfo") End If Assert.NotNull(symbolInfo) summary.Symbol = DirectCast(symbolInfo.Symbol, Symbol) summary.CandidateReason = symbolInfo.CandidateReason summary.CandidateSymbols = symbolInfo.CandidateSymbols summary.AllSymbols = symbolInfo.GetAllSymbols() If TypeOf node Is IdentifierNameSyntax Then summary.Alias = semanticModel.GetAliasInfo(DirectCast(node, IdentifierNameSyntax)) End If Return summary End Function <Extension()> Public Function GetSpeculativeSemanticInfoSummary(model As SemanticModel, position As Integer, expression As ExpressionSyntax, bindingOption As SpeculativeBindingOption) As SemanticInfoSummary Dim summary As New SemanticInfoSummary ' The information that is available varies by the type of the syntax node. Dim semanticModel = DirectCast(model, VBSemanticModel) Dim symbolInfo As SymbolInfo symbolInfo = semanticModel.GetSpeculativeSymbolInfo(position, expression, bindingOption) summary.MemberGroup = semanticModel.GetSpeculativeMemberGroup(position, expression) summary.ConstantValue = semanticModel.GetSpeculativeConstantValue(position, expression) Dim typeInfo = semanticModel.GetSpeculativeTypeInfo(position, expression, bindingOption) summary.Type = DirectCast(typeInfo.Type, TypeSymbol) summary.ConvertedType = DirectCast(typeInfo.ConvertedType, TypeSymbol) summary.ImplicitConversion = semanticModel.GetSpeculativeConversion(position, expression, bindingOption) Assert.NotNull(symbolInfo) summary.Symbol = DirectCast(symbolInfo.Symbol, Symbol) summary.CandidateReason = symbolInfo.CandidateReason summary.CandidateSymbols = symbolInfo.CandidateSymbols summary.AllSymbols = symbolInfo.GetAllSymbols() If TypeOf expression Is IdentifierNameSyntax Then summary.Alias = semanticModel.GetSpeculativeAliasInfo(position, DirectCast(expression, IdentifierNameSyntax), bindingOption) End If Return summary End Function Public Function GetSemanticInfoSummary(compilation As Compilation, node As SyntaxNode) As SemanticInfoSummary Dim tree = node.SyntaxTree Dim semanticModel = DirectCast(compilation.GetSemanticModel(tree), VBSemanticModel) Return GetSemanticInfoSummary(semanticModel, node) End Function Public Function GetSemanticInfoSummary(Of TSyntax As SyntaxNode)(compilation As Compilation, fileName As String, Optional which As Integer = 0) As SemanticInfoSummary Dim node As TSyntax = CompilationUtils.FindBindingText(Of TSyntax)(compilation, fileName, which) Return GetSemanticInfoSummary(compilation, node) End Function Public Function GetPreprocessingSymbolInfo(compilation As Compilation, fileName As String, Optional which As Integer = 0) As VisualBasicPreprocessingSymbolInfo Dim node = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, fileName, which) Dim semanticModel = DirectCast(compilation.GetSemanticModel(node.SyntaxTree), VBSemanticModel) Return semanticModel.GetPreprocessingSymbolInfo(node) End Function Public Function GetSemanticModel(compilation As Compilation, fileName As String) As VBSemanticModel Dim tree = (From t In compilation.SyntaxTrees Where t.FilePath = fileName).Single() Return DirectCast(compilation.GetSemanticModel(tree), VBSemanticModel) End Function ''' <summary> ''' Create a parse tree from the data inside an XElement ''' </summary> ''' <param name="programElement">The program element to create the tree from according to the following schema ''' &lt;file name="filename.vb[optional]"&gt; ''' source ''' &lt;/file&gt; ''' </param> Public Function CreateParseTree(programElement As XElement) As SyntaxTree Return VisualBasicSyntaxTree.ParseText(FilterString(programElement.Value), path:=If(programElement.@name, ""), encoding:=Encoding.UTF8) End Function ''' <summary> ''' Create a parse tree from the data inside an XElement ''' </summary> ''' <param name="programElement">The program element to create the tree from according to the following schema ''' &lt;file name="filename.vb[optional]"&gt; ''' source ''' &lt;/file&gt; ''' </param> Public Function CreateParseTreeAndSpans(programElement As XElement, Optional parseOptions As VisualBasicParseOptions = Nothing) As (tree As SyntaxTree, spans As IList(Of TextSpan)) Dim codeWithMarker As String = FilterString(programElement.Value) Dim codeWithoutMarker As String = Nothing Dim spans As ImmutableArray(Of TextSpan) = Nothing MarkupTestFile.GetSpans(codeWithMarker, codeWithoutMarker, spans) Dim text = SourceText.From(codeWithoutMarker, Encoding.UTF8) Return (VisualBasicSyntaxTree.ParseText(text, parseOptions, If(programElement.@name, "")), spans) End Function ' Find a node inside a tree. Public Function FindTokenFromText(tree As SyntaxTree, textToFind As String) As SyntaxToken Dim text As String = tree.GetText().ToString() Dim position As Integer = text.IndexOf(textToFind, StringComparison.Ordinal) Dim node = tree.GetRoot().FindToken(position) Return node End Function ' Find a position inside a tree. Public Function FindPositionFromText(tree As SyntaxTree, textToFind As String) As Integer Dim text As String = tree.GetText().ToString() Dim position As Integer = text.IndexOf(textToFind, StringComparison.Ordinal) Return position End Function ' Find a node inside a tree. Public Function FindNodeFromText(tree As SyntaxTree, textToFind As String) As SyntaxNode Return FindTokenFromText(tree, textToFind).Parent End Function ' Find a node of a type inside a tree. Public Function FindNodeOfTypeFromText(Of TNode As SyntaxNode)(tree As SyntaxTree, textToFind As String) As TNode Dim node = FindNodeFromText(tree, textToFind) While node IsNot Nothing AndAlso Not TypeOf node Is TNode node = node.Parent End While Return DirectCast(node, TNode) End Function ' Get the syntax tree with a given name. Public Function GetTree(compilation As Compilation, name As String) As SyntaxTree Return (From t In compilation.SyntaxTrees Where t.FilePath = name).First() End Function ' Get the symbol with a given full name. It must be unambiguous. Public Function GetSymbolByFullName(compilation As VisualBasicCompilation, methodName As String) As Symbol Dim names = New List(Of String)() Dim offset = 0 While True ' Find the next "."c separator but skip the first character since ' the name may begin with "."c (in ".ctor" for instance). Dim separator = methodName.IndexOf("."c, offset + 1) If separator < 0 Then names.Add(methodName.Substring(offset)) Exit While End If names.Add(methodName.Substring(offset, separator - offset)) offset = separator + 1 End While Dim currentSymbol As Symbol = compilation.GlobalNamespace For Each name In names Assert.True(TypeOf currentSymbol Is NamespaceOrTypeSymbol, String.Format("{0} does not have members", currentSymbol.ToDisplayString(SymbolDisplayFormat.TestFormat))) Dim currentContainer = DirectCast(currentSymbol, NamespaceOrTypeSymbol) Dim members = currentContainer.GetMembers(name) Assert.True(members.Any(), String.Format("No members named {0} inside {1}", name, currentSymbol.ToDisplayString(SymbolDisplayFormat.TestFormat))) Assert.True(members.Length() <= 1, String.Format("Multiple members named {0} inside {1}", name, currentSymbol.ToDisplayString(SymbolDisplayFormat.TestFormat))) currentSymbol = members.First() Next Return currentSymbol End Function ' Check that the compilation has no parse or declaration errors. Public Sub AssertNoDeclarationDiagnostics(compilation As VisualBasicCompilation, Optional suppressInfos As Boolean = True) AssertNoDiagnostics(compilation.GetDeclarationDiagnostics(), suppressInfos) End Sub ''' <remarks> ''' Does not consider INFO diagnostics. ''' </remarks> <Extension()> Public Sub AssertNoDiagnostics(compilation As VisualBasicCompilation, Optional suppressInfos As Boolean = True) AssertNoDiagnostics(compilation.GetDiagnostics(), suppressInfos) End Sub ' Check that the compilation has no parse, declaration errors/warnings, or compilation errors/warnings. ''' <remarks> ''' Does not consider INFO and HIDDEN diagnostics. ''' </remarks> Private Sub AssertNoDiagnostics(diags As ImmutableArray(Of Diagnostic), suppressInfos As Boolean) If suppressInfos Then diags = diags.WhereAsArray(Function(d) d.Severity > DiagnosticSeverity.Info) End If If diags.Length > 0 Then Console.WriteLine("Unexpected diagnostics found:") For Each d In diags Console.WriteLine(ErrorText(d)) Next Assert.True(False, "Should not have any diagnostics") End If End Sub ' Check that the compilation has no parse, declaration errors, or compilation errors. <Extension()> Public Sub AssertNoErrors(compilation As Compilation) AssertNoErrors(compilation.GetDiagnostics()) End Sub ' Check that the compilation has no parse, declaration errors, or compilation errors. <Extension()> Public Sub AssertNoErrors(errors As ImmutableArray(Of Diagnostic)) Dim diags As ImmutableArray(Of Diagnostic) = errors.WhereAsArray(Function(e) e.Severity = DiagnosticSeverity.Error) If diags.Length > 0 Then Console.WriteLine("Unexpected errors found:") For Each d In diags Console.WriteLine(ErrorText(d)) Next Assert.True(False, "Should not have any errors") End If End Sub ''' <summary> ''' Check that a compilation has these declaration errors. ''' </summary> ''' <param name="compilation"></param> ''' <param name="errs">Expected errors according to this schema ''' &lt;error&gt;[full errors text]&lt;/error&gt;</param> ''' <param name="suppressInfos">True to ignore info-severity diagnostics.</param> ''' <remarks></remarks> <Extension()> Public Sub AssertTheseDeclarationDiagnostics(compilation As VisualBasicCompilation, errs As XElement, Optional suppressInfos As Boolean = True) AssertTheseDiagnostics(compilation.GetDeclarationDiagnostics(), errs, suppressInfos) End Sub <Extension()> Public Sub AssertTheseParseDiagnostics(compilation As VisualBasicCompilation, errs As XElement, Optional suppressInfos As Boolean = True) AssertTheseDiagnostics(compilation.GetParseDiagnostics(), errs, suppressInfos) End Sub ''' <summary> ''' Check that a compilation has these errors at Compile stage or before. ''' </summary> ''' <param name="compilation"></param> ''' <param name="errs">Expected errors according to this schema ''' &lt;error&gt;[full errors text]&lt;/error&gt;</param> ''' <param name="suppressInfos">True to ignore info-severity diagnostics.</param> ''' <remarks></remarks> <Extension()> Public Sub AssertTheseCompileDiagnostics(compilation As Compilation, Optional errs As XElement = Nothing, Optional suppressInfos As Boolean = True) If errs Is Nothing Then errs = <errors/> End If AssertTheseDiagnostics(DirectCast(compilation, VisualBasicCompilation).GetDiagnostics(CompilationStage.Compile), errs, suppressInfos) End Sub ''' <summary> ''' Check that a compilation has these errors during Emit. ''' </summary> ''' <param name="compilation"></param> ''' <param name="errs">Expected errors according to this schema ''' &lt;error&gt;[full errors text]&lt;/error&gt;</param> ''' <param name="suppressInfos">True to ignore info-severity diagnostics.</param> ''' <remarks></remarks> <Extension()> Public Sub AssertTheseEmitDiagnostics(compilation As Compilation, Optional errs As XElement = Nothing, Optional suppressInfos As Boolean = True) If errs Is Nothing Then errs = <errors/> End If Using assemblyStream As New MemoryStream() Using pdbStream As New MemoryStream() Dim diagnostics = compilation.Emit(assemblyStream, pdbStream:=pdbStream).Diagnostics AssertTheseDiagnostics(diagnostics, errs, suppressInfos) End Using End Using End Sub <Extension()> Public Sub AssertTheseDiagnostics(tree As SyntaxTree, errs As XElement, Optional suppressInfos As Boolean = True) AssertTheseDiagnostics(tree.GetDiagnostics().AsImmutable(), errs, suppressInfos) End Sub ''' <summary> ''' Check that a compilation has these declaration or compilation errors. ''' </summary> ''' <param name="compilation"></param> ''' <param name="errs">Expected errors according to this schema ''' &lt;error&gt;[full errors text]&lt;/error&gt;</param> ''' <param name="suppressInfos">True to ignore info-severity diagnostics.</param> ''' <remarks></remarks> <Extension()> Public Sub AssertTheseDiagnostics(compilation As Compilation, Optional errs As XElement = Nothing, Optional suppressInfos As Boolean = True) If errs Is Nothing Then errs = <errors/> End If AssertTheseDiagnostics(DirectCast(compilation, VisualBasicCompilation).GetDiagnostics(CompilationStage.Compile), errs, suppressInfos) End Sub <Extension()> Public Sub AssertTheseDiagnostics(compilation As Compilation, errs As XCData, Optional suppressInfos As Boolean = True) AssertTheseDiagnostics(DirectCast(compilation, VisualBasicCompilation).GetDiagnostics(CompilationStage.Compile), errs, suppressInfos) End Sub ' Check that a compilation has these declaration or compilation errors. <Extension()> Public Sub AssertTheseDiagnostics(compilation As Compilation, errs As String, Optional suppressInfos As Boolean = True) AssertTheseDiagnostics(DirectCast(compilation, VisualBasicCompilation).GetDiagnostics(CompilationStage.Compile), errs, suppressInfos) End Sub ''' <param name="errors"></param> ''' <param name="errs">Expected errors according to this schema ''' &lt;expected&gt;[full errors text]&lt;/expected&gt;</param> ''' <param name="suppressInfos">True to ignore info-severity diagnostics.</param> ''' <remarks></remarks> <Extension()> Public Sub AssertTheseDiagnostics(errors As ImmutableArray(Of Diagnostic), errs As XElement, Optional suppressInfos As Boolean = True) If errs Is Nothing Then errs = <errors/> End If Dim expectedText = FilterString(errs.Value) AssertTheseDiagnostics(errors, expectedText, suppressInfos) End Sub <Extension()> Public Sub AssertTheseDiagnostics(errors As ImmutableArray(Of Diagnostic), errs As XCData, Optional suppressInfos As Boolean = True) Dim expectedText = FilterString(errs.Value) AssertTheseDiagnostics(errors, expectedText, suppressInfos) End Sub Private Sub AssertTheseDiagnostics(errors As ImmutableArray(Of Diagnostic), expectedText As String, suppressInfos As Boolean) Dim actualText = DumpAllDiagnostics(errors.ToArray(), suppressInfos) If expectedText <> actualText Then Dim messages = ParserTestUtilities.PooledStringBuilderPool.Allocate() With messages.Builder .AppendLine() If actualText.StartsWith(expectedText, StringComparison.Ordinal) AndAlso actualText.Substring(expectedText.Length).Trim().Length > 0 Then .AppendLine("UNEXPECTED ERROR MESSAGES:") .AppendLine(actualText.Substring(expectedText.Length)) Assert.True(False, .ToString()) Else Dim expectedLines = expectedText.Split({vbCrLf, vbLf}, StringSplitOptions.RemoveEmptyEntries) Dim actualLines = actualText.Split({vbCrLf, vbLf}, StringSplitOptions.RemoveEmptyEntries) Dim appendedLines As Integer = 0 .AppendLine("MISSING ERROR MESSAGES:") For Each l In expectedLines If Not actualLines.Contains(l) Then .AppendLine(l) appendedLines += 1 End If Next .AppendLine("UNEXPECTED ERROR MESSAGES:") For Each l In actualLines If Not expectedLines.Contains(l) Then .AppendLine(l) appendedLines += 1 End If Next If appendedLines > 0 Then Assert.True(False, .ToString()) Else CompareLineByLine(expectedText, actualText) End If End If End With messages.Free() End If End Sub Private Sub CompareLineByLine(expected As String, actual As String) Dim expectedReader = New StringReader(expected) Dim actualReader = New StringReader(actual) Dim expectedPooledBuilder = PooledStringBuilderPool.Allocate() Dim actualPooledBuilder = PooledStringBuilderPool.Allocate() Dim expectedBuilder = expectedPooledBuilder.Builder Dim actualBuilder = actualPooledBuilder.Builder Dim expectedLine = expectedReader.ReadLine() Dim actualLine = actualReader.ReadLine() While expectedLine IsNot Nothing AndAlso actualLine IsNot Nothing If Not expectedLine.Equals(actualLine) Then expectedBuilder.AppendLine("<! " & expectedLine) actualBuilder.AppendLine("!> " & actualLine) Else expectedBuilder.AppendLine(expectedLine) actualBuilder.AppendLine(actualLine) End If expectedLine = expectedReader.ReadLine() actualLine = actualReader.ReadLine() End While While expectedLine IsNot Nothing expectedBuilder.AppendLine("<! " & expectedLine) expectedLine = expectedReader.ReadLine() End While While actualLine IsNot Nothing actualBuilder.AppendLine("!> " & actualLine) actualLine = actualReader.ReadLine() End While Assert.Equal(expectedPooledBuilder.ToStringAndFree(), actualPooledBuilder.ToStringAndFree()) End Sub ' There are certain cases where multiple distinct errors are ' reported where the error code and text span are the same. When ' sorting such cases, we should preserve the original order. Private Structure DiagnosticAndIndex Public Sub New(diagnostic As Diagnostic, index As Integer) Me.Diagnostic = diagnostic Me.Index = index End Sub Public ReadOnly Diagnostic As Diagnostic Public ReadOnly Index As Integer End Structure Private Function DumpAllDiagnostics(allDiagnostics As Diagnostic(), suppressInfos As Boolean) As String Return DumpAllDiagnostics(allDiagnostics.ToImmutableArray(), suppressInfos) End Function Friend Function DumpAllDiagnostics(allDiagnostics As ImmutableArray(Of Diagnostic), suppressInfos As Boolean) As String Dim diagnosticsAndIndices(allDiagnostics.Length - 1) As DiagnosticAndIndex For i = 0 To allDiagnostics.Length - 1 diagnosticsAndIndices(i) = New DiagnosticAndIndex(allDiagnostics(i), i) Next Array.Sort(diagnosticsAndIndices, Function(diag1, diag2) CompareErrors(diag1, diag2)) Dim builder = PooledStringBuilderPool.Allocate() With builder.Builder For Each e In diagnosticsAndIndices If Not suppressInfos OrElse e.Diagnostic.Severity > DiagnosticSeverity.Info Then .Append(ErrorText(e.Diagnostic)) End If Next End With Return builder.ToStringAndFree() End Function ' Get the text of a diagnostic. For source error, includes the text of the line itself, with the ' span underlined. Private Function ErrorText(e As Diagnostic) As String Dim message = e.Id + ": " + e.GetMessage(EnsureEnglishUICulture.PreferredOrNull) If e.Location.IsInSource Then Dim sourceLocation = e.Location Dim offsetInLine As Integer = 0 Dim lineText As String = GetLineText(sourceLocation.SourceTree.GetText(), sourceLocation.SourceSpan.Start, offsetInLine) Return message + Environment.NewLine + lineText + Environment.NewLine + New String(" "c, offsetInLine) + New String("~"c, Math.Max(Math.Min(sourceLocation.SourceSpan.Length, lineText.Length - offsetInLine + 1), 1)) + Environment.NewLine ElseIf e.Location.IsInMetadata Then Return message + Environment.NewLine + String.Format("in metadata assembly '{0}'" + Environment.NewLine, e.Location.MetadataModule.ContainingAssembly.Identity.Name) Else Return message + Environment.NewLine End If End Function ' Get the text of a line that contains the offset, and return the offset within that line. Private Function GetLineText(text As SourceText, position As Integer, ByRef offsetInLine As Integer) As String Dim textLine = text.Lines.GetLineFromPosition(position) offsetInLine = position - textLine.Start Return textLine.ToString() End Function Private Function CompareErrors(diagAndIndex1 As DiagnosticAndIndex, diagAndIndex2 As DiagnosticAndIndex) As Integer ' Sort by no location, then source, then metadata. Sort within each group. Dim diag1 = diagAndIndex1.Diagnostic Dim diag2 = diagAndIndex2.Diagnostic Dim loc1 = diag1.Location Dim loc2 = diag2.Location If Not (loc1.IsInSource Or loc1.IsInMetadata) Then If Not (loc2.IsInSource Or loc2.IsInMetadata) Then ' Both have no location. Sort by code, then by message. If diag1.Code < diag2.Code Then Return -1 If diag1.Code > diag2.Code Then Return 1 Return diag1.GetMessage(EnsureEnglishUICulture.PreferredOrNull).CompareTo(diag2.GetMessage(EnsureEnglishUICulture.PreferredOrNull)) Else Return -1 End If ElseIf Not (loc2.IsInSource Or loc2.IsInMetadata) Then Return 1 ElseIf loc1.IsInSource AndAlso loc2.IsInSource Then ' source by tree, then span start, then span end, then error code, then message Dim sourceTree1 = loc1.SourceTree Dim sourceTree2 = loc2.SourceTree If sourceTree1.FilePath <> sourceTree2.FilePath Then Return sourceTree1.FilePath.CompareTo(sourceTree2.FilePath) If loc1.SourceSpan.Start < loc2.SourceSpan.Start Then Return -1 If loc1.SourceSpan.Start > loc2.SourceSpan.Start Then Return 1 If loc1.SourceSpan.Length < loc2.SourceSpan.Length Then Return -1 If loc1.SourceSpan.Length > loc2.SourceSpan.Length Then Return 1 If diag1.Code < diag2.Code Then Return -1 If diag1.Code > diag2.Code Then Return 1 Return diag1.GetMessage(EnsureEnglishUICulture.PreferredOrNull).CompareTo(diag2.GetMessage(EnsureEnglishUICulture.PreferredOrNull)) ElseIf loc1.IsInMetadata AndAlso loc2.IsInMetadata Then ' sort by assembly name, then by error code Dim name1 = loc1.MetadataModule.ContainingAssembly.Name Dim name2 = loc2.MetadataModule.ContainingAssembly.Name If name1 <> name2 Then Return name1.CompareTo(name2) If diag1.Code < diag2.Code Then Return -1 If diag1.Code > diag2.Code Then Return 1 Return diag1.GetMessage(EnsureEnglishUICulture.PreferredOrNull).CompareTo(diag2.GetMessage(EnsureEnglishUICulture.PreferredOrNull)) ElseIf loc1.IsInSource Then Return -1 ElseIf loc2.IsInSource Then Return 1 End If ' Preserve original order. Return diagAndIndex1.Index - diagAndIndex2.Index End Function Public Function GetTypeSymbol(compilation As Compilation, semanticModel As SemanticModel, treeName As String, stringInDecl As String) As INamedTypeSymbol Dim tree = CompilationUtils.GetTree(compilation, treeName) Dim node = CompilationUtils.FindTokenFromText(tree, stringInDecl).Parent While Not (TypeOf node Is TypeStatementSyntax) node = node.Parent Assert.NotNull(node) End While Return DirectCast(semanticModel, VBSemanticModel).GetDeclaredSymbol(DirectCast(node, TypeStatementSyntax)) End Function Public Function GetEnumSymbol(compilation As Compilation, semanticModel As SemanticModel, treeName As String, stringInDecl As String) As INamedTypeSymbol Dim tree = CompilationUtils.GetTree(compilation, treeName) Dim node = CompilationUtils.FindTokenFromText(tree, stringInDecl).Parent While Not (TypeOf node Is EnumStatementSyntax) node = node.Parent Assert.NotNull(node) End While Return DirectCast(semanticModel, VBSemanticModel).GetDeclaredSymbol(DirectCast(node, EnumStatementSyntax)) End Function Public Function GetDelegateSymbol(compilation As Compilation, semanticModel As SemanticModel, treeName As String, stringInDecl As String) As NamedTypeSymbol Dim tree = CompilationUtils.GetTree(compilation, treeName) Dim node = CompilationUtils.FindTokenFromText(tree, stringInDecl).Parent While Not (TypeOf node Is MethodBaseSyntax) node = node.Parent Assert.NotNull(node) End While Return DirectCast(semanticModel.GetDeclaredSymbol(DirectCast(node, MethodBaseSyntax)), NamedTypeSymbol) End Function Public Function GetTypeSymbol(compilation As Compilation, treeName As String, stringInDecl As String, Optional isDistinct As Boolean = True) As List(Of INamedTypeSymbol) Dim tree = CompilationUtils.GetTree(compilation, treeName) Dim bindings = DirectCast(compilation.GetSemanticModel(tree), VBSemanticModel) Dim text As String = tree.GetText().ToString() Dim pos = 0 Dim node As SyntaxNode Dim symType = New List(Of INamedTypeSymbol) Do pos = text.IndexOf(stringInDecl, pos + 1, StringComparison.Ordinal) If pos >= 0 Then node = tree.GetRoot().FindToken(pos).Parent While Not (TypeOf node Is TypeStatementSyntax OrElse TypeOf node Is EnumStatementSyntax) If node Is Nothing Then Exit While End If node = node.Parent End While If Not node Is Nothing Then If TypeOf node Is TypeStatementSyntax Then Dim temp = bindings.GetDeclaredSymbol(DirectCast(node, TypeStatementSyntax)) symType.Add(temp) Else Dim temp = bindings.GetDeclaredSymbol(DirectCast(node, EnumStatementSyntax)) symType.Add(temp) End If End If Else Exit Do End If Loop If (isDistinct) Then symType = (From temp In symType Distinct Select temp Order By temp.ToDisplayString()).ToList() Else symType = (From temp In symType Select temp Order By temp.ToDisplayString()).ToList() End If Return symType End Function Public Function VerifyGlobalNamespace(compilation As Compilation, treeName As String, symbolName As String, ExpectedDispName() As String, isDistinct As Boolean) As List(Of INamedTypeSymbol) Dim tree = CompilationUtils.GetTree(compilation, treeName) Dim bindings1 = compilation.GetSemanticModel(tree) Dim symbols = GetTypeSymbol(compilation, treeName, symbolName, isDistinct) Assert.Equal(ExpectedDispName.Count, symbols.Count) ExpectedDispName = (From temp In ExpectedDispName Select temp Order By temp).ToArray() Dim count = 0 For Each item In symbols Assert.NotNull(item) Assert.Equal(ExpectedDispName(count), item.ToDisplayString()) count += 1 Next Return symbols End Function Public Function VerifyGlobalNamespace(compilation As VisualBasicCompilation, treeName As String, symbolName As String, ParamArray expectedDisplayNames() As String) As List(Of INamedTypeSymbol) Return VerifyGlobalNamespace(compilation, treeName, symbolName, expectedDisplayNames, True) End Function Public Function VerifyIsGlobal(globalNS1 As ISymbol, Optional expected As Boolean = True) As NamespaceSymbol Dim nsSymbol = DirectCast(globalNS1, NamespaceSymbol) Assert.NotNull(nsSymbol) If (expected) Then Assert.True(nsSymbol.IsGlobalNamespace) Else Assert.False(nsSymbol.IsGlobalNamespace) End If Return nsSymbol End Function Public Sub CheckSymbols(Of TSymbol As ISymbol)(symbols As ImmutableArray(Of TSymbol), ParamArray descriptions As String()) Assert.Equal(symbols.Length, descriptions.Length) Dim symbolDescriptions As String() = (From s In symbols Select s.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat)).ToArray() Array.Sort(descriptions) Array.Sort(symbolDescriptions) For i = 0 To descriptions.Length - 1 Assert.Equal(symbolDescriptions(i), descriptions(i)) Next End Sub Public Sub CheckSymbols(Of TSymbol As ISymbol)(symbols As TSymbol(), ParamArray descriptions As String()) CheckSymbols(symbols.AsImmutableOrNull(), descriptions) End Sub Public Sub CheckSymbol(symbol As ISymbol, description As String) Assert.Equal(symbol.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat), description) End Sub Public Function SortAndMergeStrings(ParamArray strings As String()) As String Array.Sort(strings) Dim builder = PooledStringBuilderPool.Allocate() With builder.Builder For Each item In strings If .Length > 0 Then .AppendLine() End If .Append(item) Next End With Return builder.ToStringAndFree() End Function Public Sub CheckSymbolsUnordered(Of TSymbol As ISymbol)(symbols As ImmutableArray(Of TSymbol), ParamArray descriptions As String()) Assert.Equal(symbols.Length, descriptions.Length) Assert.Equal(SortAndMergeStrings(descriptions), SortAndMergeStrings(symbols.Select(Function(s) s.ToDisplayString()).ToArray())) End Sub <Extension> Friend Function LookupNames(model As SemanticModel, position As Integer, Optional container As INamespaceOrTypeSymbol = Nothing, Optional namespacesAndTypesOnly As Boolean = False) As List(Of String) Dim result = If(namespacesAndTypesOnly, model.LookupNamespacesAndTypes(position, container), model.LookupSymbols(position, container)) Return result.Select(Function(s) s.Name).Distinct().ToList() End Function End Module
-1
dotnet/roslyn
55,290
Fix 'quick info' and 'use explicit type' for implicit lambdas
CyrusNajmabadi
2021-07-30T18:48:59Z
2021-08-03T18:56:45Z
3a5457c3b9483c7b2be1cf6899ee3564c8ade6cf
416765ff976b2a2776c0103d3c7033f9b1667f27
Fix 'quick info' and 'use explicit type' for implicit lambdas.
./src/VisualStudio/Core/Def/Implementation/ProjectSystem/VisualStudioWorkspaceImpl.AddMetadataReferenceUndoUnit.cs
// Licensed to the .NET Foundation under one or more agreements. // 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.IO; using System.Linq; using Microsoft.CodeAnalysis; using Microsoft.VisualStudio.OLE.Interop; namespace Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem { internal partial class VisualStudioWorkspaceImpl { private class AddMetadataReferenceUndoUnit : AbstractAddRemoveUndoUnit { private readonly string _filePath; public AddMetadataReferenceUndoUnit( VisualStudioWorkspaceImpl workspace, ProjectId fromProjectId, string filePath) : base(workspace, fromProjectId) { _filePath = filePath; } public override void Do(IOleUndoManager pUndoManager) { var currentSolution = Workspace.CurrentSolution; var fromProject = currentSolution.GetProject(FromProjectId); if (fromProject != null) { var reference = fromProject.MetadataReferences.OfType<PortableExecutableReference>() .FirstOrDefault(p => StringComparer.OrdinalIgnoreCase.Equals(p.FilePath, _filePath)); if (reference == null) { try { reference = MetadataReference.CreateFromFile(_filePath); } catch (IOException) { return; } var updatedProject = fromProject.AddMetadataReference(reference); Workspace.TryApplyChanges(updatedProject.Solution); } } } public override void GetDescription(out string pBstr) { pBstr = string.Format(FeaturesResources.Add_reference_to_0, Path.GetFileName(_filePath)); } } } }
// Licensed to the .NET Foundation under one or more agreements. // 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.IO; using System.Linq; using Microsoft.CodeAnalysis; using Microsoft.VisualStudio.OLE.Interop; namespace Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem { internal partial class VisualStudioWorkspaceImpl { private class AddMetadataReferenceUndoUnit : AbstractAddRemoveUndoUnit { private readonly string _filePath; public AddMetadataReferenceUndoUnit( VisualStudioWorkspaceImpl workspace, ProjectId fromProjectId, string filePath) : base(workspace, fromProjectId) { _filePath = filePath; } public override void Do(IOleUndoManager pUndoManager) { var currentSolution = Workspace.CurrentSolution; var fromProject = currentSolution.GetProject(FromProjectId); if (fromProject != null) { var reference = fromProject.MetadataReferences.OfType<PortableExecutableReference>() .FirstOrDefault(p => StringComparer.OrdinalIgnoreCase.Equals(p.FilePath, _filePath)); if (reference == null) { try { reference = MetadataReference.CreateFromFile(_filePath); } catch (IOException) { return; } var updatedProject = fromProject.AddMetadataReference(reference); Workspace.TryApplyChanges(updatedProject.Solution); } } } public override void GetDescription(out string pBstr) { pBstr = string.Format(FeaturesResources.Add_reference_to_0, Path.GetFileName(_filePath)); } } } }
-1
dotnet/roslyn
55,290
Fix 'quick info' and 'use explicit type' for implicit lambdas
CyrusNajmabadi
2021-07-30T18:48:59Z
2021-08-03T18:56:45Z
3a5457c3b9483c7b2be1cf6899ee3564c8ade6cf
416765ff976b2a2776c0103d3c7033f9b1667f27
Fix 'quick info' and 'use explicit type' for implicit lambdas.
./src/Compilers/Core/Portable/AdditionalTextFile.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Threading; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { /// <summary> /// Represents a non source code file. /// </summary> internal sealed class AdditionalTextFile : AdditionalText { private readonly CommandLineSourceFile _sourceFile; private readonly CommonCompiler _compiler; private readonly Lazy<SourceText?> _text; private IList<DiagnosticInfo> _diagnostics; public AdditionalTextFile(CommandLineSourceFile sourceFile, CommonCompiler compiler) { if (compiler == null) { throw new ArgumentNullException(nameof(compiler)); } _sourceFile = sourceFile; _compiler = compiler; _diagnostics = SpecializedCollections.EmptyList<DiagnosticInfo>(); _text = new Lazy<SourceText?>(ReadText); } private SourceText? ReadText() { var diagnostics = new List<DiagnosticInfo>(); var text = _compiler.TryReadFileContent(_sourceFile, diagnostics); _diagnostics = diagnostics; return text; } /// <summary> /// Path to the file. /// </summary> public override string Path => _sourceFile.Path; /// <summary> /// Returns a <see cref="SourceText"/> with the contents of this file, or <c>null</c> if /// there were errors reading the file. /// </summary> public override SourceText? GetText(CancellationToken cancellationToken = default) => _text.Value; /// <summary> /// Errors encountered when trying to read the additional file. Always empty if /// <see cref="GetText(CancellationToken)"/> has not been called. /// </summary> internal IList<DiagnosticInfo> Diagnostics => _diagnostics; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Threading; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { /// <summary> /// Represents a non source code file. /// </summary> internal sealed class AdditionalTextFile : AdditionalText { private readonly CommandLineSourceFile _sourceFile; private readonly CommonCompiler _compiler; private readonly Lazy<SourceText?> _text; private IList<DiagnosticInfo> _diagnostics; public AdditionalTextFile(CommandLineSourceFile sourceFile, CommonCompiler compiler) { if (compiler == null) { throw new ArgumentNullException(nameof(compiler)); } _sourceFile = sourceFile; _compiler = compiler; _diagnostics = SpecializedCollections.EmptyList<DiagnosticInfo>(); _text = new Lazy<SourceText?>(ReadText); } private SourceText? ReadText() { var diagnostics = new List<DiagnosticInfo>(); var text = _compiler.TryReadFileContent(_sourceFile, diagnostics); _diagnostics = diagnostics; return text; } /// <summary> /// Path to the file. /// </summary> public override string Path => _sourceFile.Path; /// <summary> /// Returns a <see cref="SourceText"/> with the contents of this file, or <c>null</c> if /// there were errors reading the file. /// </summary> public override SourceText? GetText(CancellationToken cancellationToken = default) => _text.Value; /// <summary> /// Errors encountered when trying to read the additional file. Always empty if /// <see cref="GetText(CancellationToken)"/> has not been called. /// </summary> internal IList<DiagnosticInfo> Diagnostics => _diagnostics; } }
-1
dotnet/roslyn
55,290
Fix 'quick info' and 'use explicit type' for implicit lambdas
CyrusNajmabadi
2021-07-30T18:48:59Z
2021-08-03T18:56:45Z
3a5457c3b9483c7b2be1cf6899ee3564c8ade6cf
416765ff976b2a2776c0103d3c7033f9b1667f27
Fix 'quick info' and 'use explicit type' for implicit lambdas.
./src/EditorFeatures/Test/Completion/TestFileSystemCompletionHelper.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Completion; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.UnitTests.Completion { internal sealed class TestFileSystemCompletionHelper : FileSystemCompletionHelper { internal static readonly CompletionItemRules CompletionRules = CompletionItemRules.Default; private readonly ImmutableArray<string> _directories; private readonly ImmutableArray<string> _files; private readonly ImmutableArray<string> _drives; public TestFileSystemCompletionHelper( ImmutableArray<string> searchPaths, string baseDirectoryOpt, ImmutableArray<string> allowableExtensions, IEnumerable<string> drives, IEnumerable<string> directories, IEnumerable<string> files) : base(Glyph.OpenFolder, Glyph.CSharpFile, searchPaths, baseDirectoryOpt, allowableExtensions, CompletionRules) { Assert.True(drives.All(d => d.EndsWith(PathUtilities.DirectorySeparatorStr))); Assert.True(directories.All(d => !d.EndsWith(PathUtilities.DirectorySeparatorStr))); _drives = ImmutableArray.CreateRange(drives); _directories = ImmutableArray.CreateRange(directories); _files = ImmutableArray.CreateRange(files); } protected override string[] GetLogicalDrives() => _drives.ToArray(); protected override bool IsVisibleFileSystemEntry(string fullPath) => !fullPath.Contains("hidden"); protected override bool DirectoryExists(string fullPath) => _directories.Contains(fullPath.TrimEnd(PathUtilities.DirectorySeparatorChar)); protected override IEnumerable<string> EnumerateDirectories(string fullDirectoryPath) => Enumerate(_directories, fullDirectoryPath); protected override IEnumerable<string> EnumerateFiles(string fullDirectoryPath) => Enumerate(_files, fullDirectoryPath); private static IEnumerable<string> Enumerate(ImmutableArray<string> entries, string fullDirectoryPath) { var withTrailingSeparator = fullDirectoryPath.TrimEnd(PathUtilities.DirectorySeparatorChar) + PathUtilities.DirectorySeparatorChar; return from d in entries where d.StartsWith(withTrailingSeparator) let nextSeparator = d.IndexOf(PathUtilities.DirectorySeparatorChar, withTrailingSeparator.Length) select d.Substring(0, (nextSeparator >= 0) ? nextSeparator : d.Length); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using Microsoft.CodeAnalysis.Completion; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.UnitTests.Completion { internal sealed class TestFileSystemCompletionHelper : FileSystemCompletionHelper { internal static readonly CompletionItemRules CompletionRules = CompletionItemRules.Default; private readonly ImmutableArray<string> _directories; private readonly ImmutableArray<string> _files; private readonly ImmutableArray<string> _drives; public TestFileSystemCompletionHelper( ImmutableArray<string> searchPaths, string baseDirectoryOpt, ImmutableArray<string> allowableExtensions, IEnumerable<string> drives, IEnumerable<string> directories, IEnumerable<string> files) : base(Glyph.OpenFolder, Glyph.CSharpFile, searchPaths, baseDirectoryOpt, allowableExtensions, CompletionRules) { Assert.True(drives.All(d => d.EndsWith(PathUtilities.DirectorySeparatorStr))); Assert.True(directories.All(d => !d.EndsWith(PathUtilities.DirectorySeparatorStr))); _drives = ImmutableArray.CreateRange(drives); _directories = ImmutableArray.CreateRange(directories); _files = ImmutableArray.CreateRange(files); } protected override string[] GetLogicalDrives() => _drives.ToArray(); protected override bool IsVisibleFileSystemEntry(string fullPath) => !fullPath.Contains("hidden"); protected override bool DirectoryExists(string fullPath) => _directories.Contains(fullPath.TrimEnd(PathUtilities.DirectorySeparatorChar)); protected override IEnumerable<string> EnumerateDirectories(string fullDirectoryPath) => Enumerate(_directories, fullDirectoryPath); protected override IEnumerable<string> EnumerateFiles(string fullDirectoryPath) => Enumerate(_files, fullDirectoryPath); private static IEnumerable<string> Enumerate(ImmutableArray<string> entries, string fullDirectoryPath) { var withTrailingSeparator = fullDirectoryPath.TrimEnd(PathUtilities.DirectorySeparatorChar) + PathUtilities.DirectorySeparatorChar; return from d in entries where d.StartsWith(withTrailingSeparator) let nextSeparator = d.IndexOf(PathUtilities.DirectorySeparatorChar, withTrailingSeparator.Length) select d.Substring(0, (nextSeparator >= 0) ? nextSeparator : d.Length); } } }
-1
dotnet/roslyn
55,290
Fix 'quick info' and 'use explicit type' for implicit lambdas
CyrusNajmabadi
2021-07-30T18:48:59Z
2021-08-03T18:56:45Z
3a5457c3b9483c7b2be1cf6899ee3564c8ade6cf
416765ff976b2a2776c0103d3c7033f9b1667f27
Fix 'quick info' and 'use explicit type' for implicit lambdas.
./src/Compilers/CSharp/Portable/Symbols/Synthesized/SynthesizedParameterSymbol.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Diagnostics; using Microsoft.CodeAnalysis.CSharp.Emit; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols { /// <summary> /// Represents a simple compiler generated parameter of a given type. /// </summary> internal abstract class SynthesizedParameterSymbolBase : ParameterSymbol { private readonly MethodSymbol? _container; private readonly TypeWithAnnotations _type; private readonly int _ordinal; private readonly string _name; private readonly RefKind _refKind; public SynthesizedParameterSymbolBase( MethodSymbol? container, TypeWithAnnotations type, int ordinal, RefKind refKind, string name = "") { RoslynDebug.Assert(type.HasType); RoslynDebug.Assert(name != null); RoslynDebug.Assert(ordinal >= 0); _container = container; _type = type; _ordinal = ordinal; _refKind = refKind; _name = name; } public override TypeWithAnnotations TypeWithAnnotations => _type; public override RefKind RefKind => _refKind; public sealed override bool IsDiscard => false; internal override bool IsMetadataIn => RefKind == RefKind.In; internal override bool IsMetadataOut => RefKind == RefKind.Out; public override string Name { get { return _name; } } public abstract override ImmutableArray<CustomModifier> RefCustomModifiers { get; } public override int Ordinal { get { return _ordinal; } } public override bool IsParams { get { return false; } } internal override bool IsMetadataOptional { get { return false; } } public override bool IsImplicitlyDeclared { get { return true; } } internal override ConstantValue? ExplicitDefaultConstantValue { get { return null; } } internal override bool IsIDispatchConstant { get { throw ExceptionUtilities.Unreachable; } } internal override bool IsIUnknownConstant { get { throw ExceptionUtilities.Unreachable; } } internal override bool IsCallerLineNumber { get { throw ExceptionUtilities.Unreachable; } } internal override bool IsCallerFilePath { get { throw ExceptionUtilities.Unreachable; } } internal override bool IsCallerMemberName { get { throw ExceptionUtilities.Unreachable; } } internal override int CallerArgumentExpressionParameterIndex { get { return -1; } } internal override FlowAnalysisAnnotations FlowAnalysisAnnotations { get { return FlowAnalysisAnnotations.None; } } internal override ImmutableHashSet<string> NotNullIfParameterNotNull { get { return ImmutableHashSet<string>.Empty; } } public override Symbol? ContainingSymbol { get { return _container; } } public override ImmutableArray<Location> Locations { get { return ImmutableArray<Location>.Empty; } } public override ImmutableArray<SyntaxReference> DeclaringSyntaxReferences { get { return ImmutableArray<SyntaxReference>.Empty; } } internal override void AddSynthesizedAttributes(PEModuleBuilder moduleBuilder, ref ArrayBuilder<SynthesizedAttributeData> attributes) { // Emit [Dynamic] on synthesized parameter symbols when the original parameter was dynamic // in order to facilitate debugging. In the case the necessary attributes are missing // this is a no-op. Emitting an error here, or when the original parameter was bound, would // adversely effect the compilation or potentially change overload resolution. var compilation = this.DeclaringCompilation; var type = this.TypeWithAnnotations; if (type.Type.ContainsDynamic() && compilation.HasDynamicEmitAttributes(BindingDiagnosticBag.Discarded, Location.None) && compilation.CanEmitBoolean()) { AddSynthesizedAttribute(ref attributes, compilation.SynthesizeDynamicAttribute(type.Type, type.CustomModifiers.Length + this.RefCustomModifiers.Length, this.RefKind)); } if (type.Type.ContainsNativeInteger()) { AddSynthesizedAttribute(ref attributes, moduleBuilder.SynthesizeNativeIntegerAttribute(this, type.Type)); } if (type.Type.ContainsTupleNames() && compilation.HasTupleNamesAttributes(BindingDiagnosticBag.Discarded, Location.None) && compilation.CanEmitSpecialType(SpecialType.System_String)) { AddSynthesizedAttribute(ref attributes, compilation.SynthesizeTupleNamesAttribute(type.Type)); } if (compilation.ShouldEmitNullableAttributes(this)) { AddSynthesizedAttribute(ref attributes, moduleBuilder.SynthesizeNullableAttributeIfNecessary(this, GetNullableContextValue(), type)); } if (this.RefKind == RefKind.RefReadOnly) { AddSynthesizedAttribute(ref attributes, moduleBuilder.SynthesizeIsReadOnlyAttribute(this)); } } internal override ImmutableArray<int> InterpolatedStringHandlerArgumentIndexes => ImmutableArray<int>.Empty; internal override bool HasInterpolatedStringHandlerArgumentError => false; } internal sealed class SynthesizedParameterSymbol : SynthesizedParameterSymbolBase { private SynthesizedParameterSymbol( MethodSymbol? container, TypeWithAnnotations type, int ordinal, RefKind refKind, string name) : base(container, type, ordinal, refKind, name) { } public static ParameterSymbol Create( MethodSymbol? container, TypeWithAnnotations type, int ordinal, RefKind refKind, string name = "", ImmutableArray<CustomModifier> refCustomModifiers = default, SourceComplexParameterSymbol? baseParameterForAttributes = null) { if (refCustomModifiers.IsDefaultOrEmpty && baseParameterForAttributes is null) { return new SynthesizedParameterSymbol(container, type, ordinal, refKind, name); } return new SynthesizedComplexParameterSymbol( container, type, ordinal, refKind, name, refCustomModifiers.NullToEmpty(), baseParameterForAttributes); } /// <summary> /// For each parameter of a source method, construct a corresponding synthesized parameter /// for a destination method. /// </summary> /// <param name="sourceMethod">Has parameters.</param> /// <param name="destinationMethod">Needs parameters.</param> /// <returns>Synthesized parameters to add to destination method.</returns> internal static ImmutableArray<ParameterSymbol> DeriveParameters(MethodSymbol sourceMethod, MethodSymbol destinationMethod) { var builder = ArrayBuilder<ParameterSymbol>.GetInstance(); foreach (var oldParam in sourceMethod.Parameters) { Debug.Assert(!(oldParam is SynthesizedComplexParameterSymbol)); //same properties as the old one, just change the owner builder.Add(Create( destinationMethod, oldParam.TypeWithAnnotations, oldParam.Ordinal, oldParam.RefKind, oldParam.Name, oldParam.RefCustomModifiers, baseParameterForAttributes: null)); } return builder.ToImmutableAndFree(); } public override ImmutableArray<CustomModifier> RefCustomModifiers { get { return ImmutableArray<CustomModifier>.Empty; } } internal override MarshalPseudoCustomAttributeData? MarshallingInformation { get { return null; } } } internal sealed class SynthesizedComplexParameterSymbol : SynthesizedParameterSymbolBase { private readonly ImmutableArray<CustomModifier> _refCustomModifiers; // The parameter containing attributes to inherit into this synthesized parameter, if any. private readonly SourceComplexParameterSymbol? _baseParameterForAttributes; public SynthesizedComplexParameterSymbol( MethodSymbol? container, TypeWithAnnotations type, int ordinal, RefKind refKind, string name, ImmutableArray<CustomModifier> refCustomModifiers, SourceComplexParameterSymbol? baseParameterForAttributes) : base(container, type, ordinal, refKind, name) { Debug.Assert(!refCustomModifiers.IsDefault); Debug.Assert(!refCustomModifiers.IsEmpty || baseParameterForAttributes is object); _refCustomModifiers = refCustomModifiers; _baseParameterForAttributes = baseParameterForAttributes; } public override ImmutableArray<CustomModifier> RefCustomModifiers { get { return _refCustomModifiers; } } public override ImmutableArray<CSharpAttributeData> GetAttributes() { return _baseParameterForAttributes?.GetAttributes() ?? ImmutableArray<CSharpAttributeData>.Empty; } public bool HasEnumeratorCancellationAttribute => _baseParameterForAttributes?.HasEnumeratorCancellationAttribute ?? false; internal override MarshalPseudoCustomAttributeData? MarshallingInformation => _baseParameterForAttributes?.MarshallingInformation; internal override bool IsMetadataOptional => _baseParameterForAttributes?.IsMetadataOptional == true; internal override ConstantValue? ExplicitDefaultConstantValue => _baseParameterForAttributes?.ExplicitDefaultConstantValue; internal override FlowAnalysisAnnotations FlowAnalysisAnnotations { get { Debug.Assert(_baseParameterForAttributes is null); return base.FlowAnalysisAnnotations; } } internal override ImmutableHashSet<string> NotNullIfParameterNotNull { get { Debug.Assert(_baseParameterForAttributes is null); return base.NotNullIfParameterNotNull; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Diagnostics; using Microsoft.CodeAnalysis.CSharp.Emit; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols { /// <summary> /// Represents a simple compiler generated parameter of a given type. /// </summary> internal abstract class SynthesizedParameterSymbolBase : ParameterSymbol { private readonly MethodSymbol? _container; private readonly TypeWithAnnotations _type; private readonly int _ordinal; private readonly string _name; private readonly RefKind _refKind; public SynthesizedParameterSymbolBase( MethodSymbol? container, TypeWithAnnotations type, int ordinal, RefKind refKind, string name = "") { RoslynDebug.Assert(type.HasType); RoslynDebug.Assert(name != null); RoslynDebug.Assert(ordinal >= 0); _container = container; _type = type; _ordinal = ordinal; _refKind = refKind; _name = name; } public override TypeWithAnnotations TypeWithAnnotations => _type; public override RefKind RefKind => _refKind; public sealed override bool IsDiscard => false; internal override bool IsMetadataIn => RefKind == RefKind.In; internal override bool IsMetadataOut => RefKind == RefKind.Out; public override string Name { get { return _name; } } public abstract override ImmutableArray<CustomModifier> RefCustomModifiers { get; } public override int Ordinal { get { return _ordinal; } } public override bool IsParams { get { return false; } } internal override bool IsMetadataOptional { get { return false; } } public override bool IsImplicitlyDeclared { get { return true; } } internal override ConstantValue? ExplicitDefaultConstantValue { get { return null; } } internal override bool IsIDispatchConstant { get { throw ExceptionUtilities.Unreachable; } } internal override bool IsIUnknownConstant { get { throw ExceptionUtilities.Unreachable; } } internal override bool IsCallerLineNumber { get { throw ExceptionUtilities.Unreachable; } } internal override bool IsCallerFilePath { get { throw ExceptionUtilities.Unreachable; } } internal override bool IsCallerMemberName { get { throw ExceptionUtilities.Unreachable; } } internal override int CallerArgumentExpressionParameterIndex { get { return -1; } } internal override FlowAnalysisAnnotations FlowAnalysisAnnotations { get { return FlowAnalysisAnnotations.None; } } internal override ImmutableHashSet<string> NotNullIfParameterNotNull { get { return ImmutableHashSet<string>.Empty; } } public override Symbol? ContainingSymbol { get { return _container; } } public override ImmutableArray<Location> Locations { get { return ImmutableArray<Location>.Empty; } } public override ImmutableArray<SyntaxReference> DeclaringSyntaxReferences { get { return ImmutableArray<SyntaxReference>.Empty; } } internal override void AddSynthesizedAttributes(PEModuleBuilder moduleBuilder, ref ArrayBuilder<SynthesizedAttributeData> attributes) { // Emit [Dynamic] on synthesized parameter symbols when the original parameter was dynamic // in order to facilitate debugging. In the case the necessary attributes are missing // this is a no-op. Emitting an error here, or when the original parameter was bound, would // adversely effect the compilation or potentially change overload resolution. var compilation = this.DeclaringCompilation; var type = this.TypeWithAnnotations; if (type.Type.ContainsDynamic() && compilation.HasDynamicEmitAttributes(BindingDiagnosticBag.Discarded, Location.None) && compilation.CanEmitBoolean()) { AddSynthesizedAttribute(ref attributes, compilation.SynthesizeDynamicAttribute(type.Type, type.CustomModifiers.Length + this.RefCustomModifiers.Length, this.RefKind)); } if (type.Type.ContainsNativeInteger()) { AddSynthesizedAttribute(ref attributes, moduleBuilder.SynthesizeNativeIntegerAttribute(this, type.Type)); } if (type.Type.ContainsTupleNames() && compilation.HasTupleNamesAttributes(BindingDiagnosticBag.Discarded, Location.None) && compilation.CanEmitSpecialType(SpecialType.System_String)) { AddSynthesizedAttribute(ref attributes, compilation.SynthesizeTupleNamesAttribute(type.Type)); } if (compilation.ShouldEmitNullableAttributes(this)) { AddSynthesizedAttribute(ref attributes, moduleBuilder.SynthesizeNullableAttributeIfNecessary(this, GetNullableContextValue(), type)); } if (this.RefKind == RefKind.RefReadOnly) { AddSynthesizedAttribute(ref attributes, moduleBuilder.SynthesizeIsReadOnlyAttribute(this)); } } internal override ImmutableArray<int> InterpolatedStringHandlerArgumentIndexes => ImmutableArray<int>.Empty; internal override bool HasInterpolatedStringHandlerArgumentError => false; } internal sealed class SynthesizedParameterSymbol : SynthesizedParameterSymbolBase { private SynthesizedParameterSymbol( MethodSymbol? container, TypeWithAnnotations type, int ordinal, RefKind refKind, string name) : base(container, type, ordinal, refKind, name) { } public static ParameterSymbol Create( MethodSymbol? container, TypeWithAnnotations type, int ordinal, RefKind refKind, string name = "", ImmutableArray<CustomModifier> refCustomModifiers = default, SourceComplexParameterSymbol? baseParameterForAttributes = null) { if (refCustomModifiers.IsDefaultOrEmpty && baseParameterForAttributes is null) { return new SynthesizedParameterSymbol(container, type, ordinal, refKind, name); } return new SynthesizedComplexParameterSymbol( container, type, ordinal, refKind, name, refCustomModifiers.NullToEmpty(), baseParameterForAttributes); } /// <summary> /// For each parameter of a source method, construct a corresponding synthesized parameter /// for a destination method. /// </summary> /// <param name="sourceMethod">Has parameters.</param> /// <param name="destinationMethod">Needs parameters.</param> /// <returns>Synthesized parameters to add to destination method.</returns> internal static ImmutableArray<ParameterSymbol> DeriveParameters(MethodSymbol sourceMethod, MethodSymbol destinationMethod) { var builder = ArrayBuilder<ParameterSymbol>.GetInstance(); foreach (var oldParam in sourceMethod.Parameters) { Debug.Assert(!(oldParam is SynthesizedComplexParameterSymbol)); //same properties as the old one, just change the owner builder.Add(Create( destinationMethod, oldParam.TypeWithAnnotations, oldParam.Ordinal, oldParam.RefKind, oldParam.Name, oldParam.RefCustomModifiers, baseParameterForAttributes: null)); } return builder.ToImmutableAndFree(); } public override ImmutableArray<CustomModifier> RefCustomModifiers { get { return ImmutableArray<CustomModifier>.Empty; } } internal override MarshalPseudoCustomAttributeData? MarshallingInformation { get { return null; } } } internal sealed class SynthesizedComplexParameterSymbol : SynthesizedParameterSymbolBase { private readonly ImmutableArray<CustomModifier> _refCustomModifiers; // The parameter containing attributes to inherit into this synthesized parameter, if any. private readonly SourceComplexParameterSymbol? _baseParameterForAttributes; public SynthesizedComplexParameterSymbol( MethodSymbol? container, TypeWithAnnotations type, int ordinal, RefKind refKind, string name, ImmutableArray<CustomModifier> refCustomModifiers, SourceComplexParameterSymbol? baseParameterForAttributes) : base(container, type, ordinal, refKind, name) { Debug.Assert(!refCustomModifiers.IsDefault); Debug.Assert(!refCustomModifiers.IsEmpty || baseParameterForAttributes is object); _refCustomModifiers = refCustomModifiers; _baseParameterForAttributes = baseParameterForAttributes; } public override ImmutableArray<CustomModifier> RefCustomModifiers { get { return _refCustomModifiers; } } public override ImmutableArray<CSharpAttributeData> GetAttributes() { return _baseParameterForAttributes?.GetAttributes() ?? ImmutableArray<CSharpAttributeData>.Empty; } public bool HasEnumeratorCancellationAttribute => _baseParameterForAttributes?.HasEnumeratorCancellationAttribute ?? false; internal override MarshalPseudoCustomAttributeData? MarshallingInformation => _baseParameterForAttributes?.MarshallingInformation; internal override bool IsMetadataOptional => _baseParameterForAttributes?.IsMetadataOptional == true; internal override ConstantValue? ExplicitDefaultConstantValue => _baseParameterForAttributes?.ExplicitDefaultConstantValue; internal override FlowAnalysisAnnotations FlowAnalysisAnnotations { get { Debug.Assert(_baseParameterForAttributes is null); return base.FlowAnalysisAnnotations; } } internal override ImmutableHashSet<string> NotNullIfParameterNotNull { get { Debug.Assert(_baseParameterForAttributes is null); return base.NotNullIfParameterNotNull; } } } }
-1
dotnet/roslyn
55,262
Fix LSP completions when all items have default commit characters
Fixes an exception stack trace seen in https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1362284 Also fixes behavior of promotion of commit characters to the list to include default commit characters
dibarbet
2021-07-30T02:43:35Z
2021-07-30T21:21:47Z
2f7dffa534aceb92e9767568e88535c926588d12
65ee073bf6cea571a68193793420ecee60752711
Fix LSP completions when all items have default commit characters. Fixes an exception stack trace seen in https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1362284 Also fixes behavior of promotion of commit characters to the list to include default commit characters
./src/Features/CSharp/Portable/Completion/CompletionProviders/SymbolCompletionProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // 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.Composition; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Completion; using Microsoft.CodeAnalysis.Completion.Log; using Microsoft.CodeAnalysis.Completion.Providers; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Utilities; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CSharp.Completion.Providers { [ExportCompletionProvider(nameof(SymbolCompletionProvider), LanguageNames.CSharp)] [ExtensionOrder(After = nameof(SpeculativeTCompletionProvider))] [Shared] internal partial class SymbolCompletionProvider : AbstractRecommendationServiceBasedCompletionProvider<CSharpSyntaxContext> { private static readonly Dictionary<(bool importDirective, bool preselect, bool tupleLiteral), CompletionItemRules> s_cachedRules = new(); static SymbolCompletionProvider() { for (var importDirective = 0; importDirective < 2; importDirective++) { for (var preselect = 0; preselect < 2; preselect++) { for (var tupleLiteral = 0; tupleLiteral < 2; tupleLiteral++) { var context = (importDirective: importDirective == 1, preselect: preselect == 1, tupleLiteral: tupleLiteral == 1); s_cachedRules[context] = MakeRule(context); } } } return; static CompletionItemRules MakeRule((bool importDirective, bool preselect, bool tupleLiteral) context) { // '<' should not filter the completion list, even though it's in generic items like IList<> var generalBaseline = CompletionItemRules.Default. WithFilterCharacterRule(CharacterSetModificationRule.Create(CharacterSetModificationKind.Remove, '<')). WithCommitCharacterRule(CharacterSetModificationRule.Create(CharacterSetModificationKind.Add, '<')); var importDirectiveBaseline = CompletionItemRules.Create(commitCharacterRules: ImmutableArray.Create(CharacterSetModificationRule.Create(CharacterSetModificationKind.Replace, '.', ';'))); var rule = context.importDirective ? importDirectiveBaseline : generalBaseline; if (context.preselect) rule = rule.WithSelectionBehavior(CompletionItemSelectionBehavior.HardSelection); if (context.tupleLiteral) rule = rule.WithCommitCharacterRule(CharacterSetModificationRule.Create(CharacterSetModificationKind.Remove, ':')); return rule; } } [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public SymbolCompletionProvider() { } protected override CompletionItemSelectionBehavior PreselectedItemSelectionBehavior => CompletionItemSelectionBehavior.HardSelection; protected override async Task<bool> ShouldPreselectInferredTypesAsync( CompletionContext? context, int position, OptionSet options, CancellationToken cancellationToken) { if (context != null && ShouldTriggerInArgumentLists(options)) { // Avoid preselection & hard selection when triggered via insertion in an argument list. // If an item is hard selected, then a user trying to type MethodCall() will get // MethodCall(someVariable) instead. We need only soft selected items to prevent this. if (context.Trigger.Kind == CompletionTriggerKind.Insertion && position > 0 && await IsTriggerInArgumentListAsync(context.Document, position - 1, cancellationToken).ConfigureAwait(false) == true) { return false; } } return true; } protected override bool IsInstrinsic(ISymbol s) => s is ITypeSymbol ts && ts.IsIntrinsicType(); public override bool IsInsertionTrigger(SourceText text, int characterPosition, OptionSet options) { return ShouldTriggerInArgumentLists(options) ? CompletionUtilities.IsTriggerCharacterOrArgumentListCharacter(text, characterPosition, options) : CompletionUtilities.IsTriggerCharacter(text, characterPosition, options); } internal override async Task<bool> IsSyntacticTriggerCharacterAsync(Document document, int caretPosition, CompletionTrigger trigger, OptionSet options, CancellationToken cancellationToken) { if (trigger.Kind == CompletionTriggerKind.Insertion && caretPosition > 0) { var result = await IsTriggerOnDotAsync(document, caretPosition - 1, cancellationToken).ConfigureAwait(false); if (result.HasValue) return result.Value; if (ShouldTriggerInArgumentLists(await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false))) { result = await IsTriggerInArgumentListAsync(document, caretPosition - 1, cancellationToken).ConfigureAwait(false); if (result.HasValue) return result.Value; } } // By default we want to proceed with triggering completion if we have items. return true; } public override ImmutableHashSet<char> TriggerCharacters { get; } = CompletionUtilities.CommonTriggerCharactersWithArgumentList; private static bool ShouldTriggerInArgumentLists(OptionSet options) => options.GetOption(CompletionOptions.TriggerInArgumentLists, LanguageNames.CSharp); protected override bool IsTriggerOnDot(SyntaxToken token, int characterPosition) { if (!CompletionUtilities.TreatAsDot(token, characterPosition)) return false; // don't want to trigger after a number. All other cases after dot are ok. return token.GetPreviousToken().Kind() != SyntaxKind.NumericLiteralToken; } /// <returns><see langword="null"/> if not an argument list character, otherwise whether the trigger is in an argument list.</returns> private static async Task<bool?> IsTriggerInArgumentListAsync(Document document, int characterPosition, CancellationToken cancellationToken) { var text = await document.GetTextAsync(cancellationToken).ConfigureAwait(false); if (!CompletionUtilities.IsArgumentListCharacter(text[characterPosition])) { return null; } var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var token = root.FindToken(characterPosition); if (!token.Parent.IsKind(SyntaxKind.ArgumentList, SyntaxKind.BracketedArgumentList, SyntaxKind.AttributeArgumentList, SyntaxKind.ArrayRankSpecifier)) { return false; } // Be careful, e.g. if we're in a comment before the token if (token.Span.End > characterPosition + 1) { return false; } // Only allow spaces between the end of the token and the trigger character for (var i = token.Span.End; i < characterPosition; i++) { if (text[i] != ' ') { return false; } } return true; } protected override (string displayText, string suffix, string insertionText) GetDisplayAndSuffixAndInsertionText(ISymbol symbol, CSharpSyntaxContext context) => CompletionUtilities.GetDisplayAndSuffixAndInsertionText(symbol, context); protected override CompletionItemRules GetCompletionItemRules(ImmutableArray<(ISymbol symbol, bool preselect)> symbols, CSharpSyntaxContext context) { var preselect = symbols.Any(t => t.preselect); s_cachedRules.TryGetValue(ValueTuple.Create(context.IsLeftSideOfImportAliasDirective, preselect, context.IsPossibleTupleContext), out var rule); return rule ?? CompletionItemRules.Default; } protected override CompletionItem CreateItem( CompletionContext completionContext, string displayText, string displayTextSuffix, string insertionText, ImmutableArray<(ISymbol symbol, bool preselect)> symbols, CSharpSyntaxContext context, SupportedPlatformData? supportedPlatformData) { var item = base.CreateItem( completionContext, displayText, displayTextSuffix, insertionText, symbols, context, supportedPlatformData); var symbol = symbols[0].symbol; // If it is a method symbol, also consider appending parenthesis when later, it is committed by using special characters. // 2 cases are excluded. // 1. If it is invoked under Nameof Context. // For example: var a = nameof(Bar$$) // In this case, if later committed by semicolon, we should have // var a = nameof(Bar); // 2. If the inferred type is delegate or function pointer. // e.g. Action c = Bar$$ // In this case, if later committed by semicolon, we should have // e.g. Action c = = Bar; if (symbol.IsKind(SymbolKind.Method) && !context.IsNameOfContext) { var isInferredTypeDelegateOrFunctionPointer = context.InferredTypes.Any(type => type.IsDelegateType() || type.IsFunctionPointerType()); if (!isInferredTypeDelegateOrFunctionPointer) { item = SymbolCompletionItem.AddShouldProvideParenthesisCompletion(item); } } else if (symbol.IsKind(SymbolKind.NamedType) || symbol is IAliasSymbol aliasSymbol && aliasSymbol.Target.IsType) { // If this is a type symbol/alias symbol, also consider appending parenthesis when later, it is committed by using special characters, // and the type is used as constructor if (context.IsObjectCreationTypeContext) item = SymbolCompletionItem.AddShouldProvideParenthesisCompletion(item); } return item; } protected override string GetInsertionText(CompletionItem item, char ch) { if (ch is ';' or '.' && SymbolCompletionItem.GetShouldProvideParenthesisCompletion(item)) { CompletionProvidersLogger.LogCustomizedCommitToAddParenthesis(ch); return SymbolCompletionItem.GetInsertionText(item) + "()"; } return base.GetInsertionText(item, ch); } } }
// Licensed to the .NET Foundation under one or more agreements. // 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.Composition; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Completion; using Microsoft.CodeAnalysis.Completion.Log; using Microsoft.CodeAnalysis.Completion.Providers; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Utilities; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CSharp.Completion.Providers { [ExportCompletionProvider(nameof(SymbolCompletionProvider), LanguageNames.CSharp)] [ExtensionOrder(After = nameof(SpeculativeTCompletionProvider))] [Shared] internal partial class SymbolCompletionProvider : AbstractRecommendationServiceBasedCompletionProvider<CSharpSyntaxContext> { private static readonly Dictionary<(bool importDirective, bool preselect, bool tupleLiteral), CompletionItemRules> s_cachedRules = new(); static SymbolCompletionProvider() { for (var importDirective = 0; importDirective < 2; importDirective++) { for (var preselect = 0; preselect < 2; preselect++) { for (var tupleLiteral = 0; tupleLiteral < 2; tupleLiteral++) { var context = (importDirective: importDirective == 1, preselect: preselect == 1, tupleLiteral: tupleLiteral == 1); s_cachedRules[context] = MakeRule(context); } } } return; static CompletionItemRules MakeRule((bool importDirective, bool preselect, bool tupleLiteral) context) { // '<' should not filter the completion list, even though it's in generic items like IList<> var generalBaseline = CompletionItemRules.Default. WithFilterCharacterRule(CharacterSetModificationRule.Create(CharacterSetModificationKind.Remove, '<')); var importDirectiveBaseline = CompletionItemRules.Create(commitCharacterRules: ImmutableArray.Create(CharacterSetModificationRule.Create(CharacterSetModificationKind.Replace, '.', ';'))); var rule = context.importDirective ? importDirectiveBaseline : generalBaseline; if (context.preselect) rule = rule.WithSelectionBehavior(CompletionItemSelectionBehavior.HardSelection); if (context.tupleLiteral) rule = rule.WithCommitCharacterRule(CharacterSetModificationRule.Create(CharacterSetModificationKind.Remove, ':')); return rule; } } [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public SymbolCompletionProvider() { } protected override CompletionItemSelectionBehavior PreselectedItemSelectionBehavior => CompletionItemSelectionBehavior.HardSelection; protected override async Task<bool> ShouldPreselectInferredTypesAsync( CompletionContext? context, int position, OptionSet options, CancellationToken cancellationToken) { if (context != null && ShouldTriggerInArgumentLists(options)) { // Avoid preselection & hard selection when triggered via insertion in an argument list. // If an item is hard selected, then a user trying to type MethodCall() will get // MethodCall(someVariable) instead. We need only soft selected items to prevent this. if (context.Trigger.Kind == CompletionTriggerKind.Insertion && position > 0 && await IsTriggerInArgumentListAsync(context.Document, position - 1, cancellationToken).ConfigureAwait(false) == true) { return false; } } return true; } protected override bool IsInstrinsic(ISymbol s) => s is ITypeSymbol ts && ts.IsIntrinsicType(); public override bool IsInsertionTrigger(SourceText text, int characterPosition, OptionSet options) { return ShouldTriggerInArgumentLists(options) ? CompletionUtilities.IsTriggerCharacterOrArgumentListCharacter(text, characterPosition, options) : CompletionUtilities.IsTriggerCharacter(text, characterPosition, options); } internal override async Task<bool> IsSyntacticTriggerCharacterAsync(Document document, int caretPosition, CompletionTrigger trigger, OptionSet options, CancellationToken cancellationToken) { if (trigger.Kind == CompletionTriggerKind.Insertion && caretPosition > 0) { var result = await IsTriggerOnDotAsync(document, caretPosition - 1, cancellationToken).ConfigureAwait(false); if (result.HasValue) return result.Value; if (ShouldTriggerInArgumentLists(await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false))) { result = await IsTriggerInArgumentListAsync(document, caretPosition - 1, cancellationToken).ConfigureAwait(false); if (result.HasValue) return result.Value; } } // By default we want to proceed with triggering completion if we have items. return true; } public override ImmutableHashSet<char> TriggerCharacters { get; } = CompletionUtilities.CommonTriggerCharactersWithArgumentList; private static bool ShouldTriggerInArgumentLists(OptionSet options) => options.GetOption(CompletionOptions.TriggerInArgumentLists, LanguageNames.CSharp); protected override bool IsTriggerOnDot(SyntaxToken token, int characterPosition) { if (!CompletionUtilities.TreatAsDot(token, characterPosition)) return false; // don't want to trigger after a number. All other cases after dot are ok. return token.GetPreviousToken().Kind() != SyntaxKind.NumericLiteralToken; } /// <returns><see langword="null"/> if not an argument list character, otherwise whether the trigger is in an argument list.</returns> private static async Task<bool?> IsTriggerInArgumentListAsync(Document document, int characterPosition, CancellationToken cancellationToken) { var text = await document.GetTextAsync(cancellationToken).ConfigureAwait(false); if (!CompletionUtilities.IsArgumentListCharacter(text[characterPosition])) { return null; } var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var token = root.FindToken(characterPosition); if (!token.Parent.IsKind(SyntaxKind.ArgumentList, SyntaxKind.BracketedArgumentList, SyntaxKind.AttributeArgumentList, SyntaxKind.ArrayRankSpecifier)) { return false; } // Be careful, e.g. if we're in a comment before the token if (token.Span.End > characterPosition + 1) { return false; } // Only allow spaces between the end of the token and the trigger character for (var i = token.Span.End; i < characterPosition; i++) { if (text[i] != ' ') { return false; } } return true; } protected override (string displayText, string suffix, string insertionText) GetDisplayAndSuffixAndInsertionText(ISymbol symbol, CSharpSyntaxContext context) => CompletionUtilities.GetDisplayAndSuffixAndInsertionText(symbol, context); protected override CompletionItemRules GetCompletionItemRules(ImmutableArray<(ISymbol symbol, bool preselect)> symbols, CSharpSyntaxContext context) { var preselect = symbols.Any(t => t.preselect); s_cachedRules.TryGetValue(ValueTuple.Create(context.IsLeftSideOfImportAliasDirective, preselect, context.IsPossibleTupleContext), out var rule); return rule ?? CompletionItemRules.Default; } protected override CompletionItem CreateItem( CompletionContext completionContext, string displayText, string displayTextSuffix, string insertionText, ImmutableArray<(ISymbol symbol, bool preselect)> symbols, CSharpSyntaxContext context, SupportedPlatformData? supportedPlatformData) { var item = base.CreateItem( completionContext, displayText, displayTextSuffix, insertionText, symbols, context, supportedPlatformData); var symbol = symbols[0].symbol; // If it is a method symbol, also consider appending parenthesis when later, it is committed by using special characters. // 2 cases are excluded. // 1. If it is invoked under Nameof Context. // For example: var a = nameof(Bar$$) // In this case, if later committed by semicolon, we should have // var a = nameof(Bar); // 2. If the inferred type is delegate or function pointer. // e.g. Action c = Bar$$ // In this case, if later committed by semicolon, we should have // e.g. Action c = = Bar; if (symbol.IsKind(SymbolKind.Method) && !context.IsNameOfContext) { var isInferredTypeDelegateOrFunctionPointer = context.InferredTypes.Any(type => type.IsDelegateType() || type.IsFunctionPointerType()); if (!isInferredTypeDelegateOrFunctionPointer) { item = SymbolCompletionItem.AddShouldProvideParenthesisCompletion(item); } } else if (symbol.IsKind(SymbolKind.NamedType) || symbol is IAliasSymbol aliasSymbol && aliasSymbol.Target.IsType) { // If this is a type symbol/alias symbol, also consider appending parenthesis when later, it is committed by using special characters, // and the type is used as constructor if (context.IsObjectCreationTypeContext) item = SymbolCompletionItem.AddShouldProvideParenthesisCompletion(item); } return item; } protected override string GetInsertionText(CompletionItem item, char ch) { if (ch is ';' or '.' && SymbolCompletionItem.GetShouldProvideParenthesisCompletion(item)) { CompletionProvidersLogger.LogCustomizedCommitToAddParenthesis(ch); return SymbolCompletionItem.GetInsertionText(item) + "()"; } return base.GetInsertionText(item, ch); } } }
1
dotnet/roslyn
55,262
Fix LSP completions when all items have default commit characters
Fixes an exception stack trace seen in https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1362284 Also fixes behavior of promotion of commit characters to the list to include default commit characters
dibarbet
2021-07-30T02:43:35Z
2021-07-30T21:21:47Z
2f7dffa534aceb92e9767568e88535c926588d12
65ee073bf6cea571a68193793420ecee60752711
Fix LSP completions when all items have default commit characters. Fixes an exception stack trace seen in https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1362284 Also fixes behavior of promotion of commit characters to the list to include default commit characters
./src/Features/LanguageServer/Protocol/Handler/Completion/CompletionHandler.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Completion; using Microsoft.CodeAnalysis.Completion.Providers; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Experiments; using Microsoft.CodeAnalysis.LanguageServer.Handler.Completion; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Text.Adornments; using Roslyn.Utilities; using LSP = Microsoft.VisualStudio.LanguageServer.Protocol; namespace Microsoft.CodeAnalysis.LanguageServer.Handler { /// <summary> /// Handle a completion request. /// </summary> internal class CompletionHandler : IRequestHandler<LSP.CompletionParams, LSP.CompletionList?> { private readonly ImmutableHashSet<char> _csharpTriggerCharacters; private readonly ImmutableHashSet<char> _vbTriggerCharacters; private readonly CompletionListCache _completionListCache; public string Method => LSP.Methods.TextDocumentCompletionName; public bool MutatesSolutionState => false; public bool RequiresLSPSolution => true; public CompletionHandler( IEnumerable<Lazy<CompletionProvider, CompletionProviderMetadata>> completionProviders, CompletionListCache completionListCache) { _csharpTriggerCharacters = completionProviders.Where(lz => lz.Metadata.Language == LanguageNames.CSharp).SelectMany( lz => GetTriggerCharacters(lz.Value)).ToImmutableHashSet(); _vbTriggerCharacters = completionProviders.Where(lz => lz.Metadata.Language == LanguageNames.VisualBasic).SelectMany( lz => GetTriggerCharacters(lz.Value)).ToImmutableHashSet(); _completionListCache = completionListCache; } public LSP.TextDocumentIdentifier? GetTextDocumentIdentifier(LSP.CompletionParams request) => request.TextDocument; public async Task<LSP.CompletionList?> HandleRequestAsync(LSP.CompletionParams request, RequestContext context, CancellationToken cancellationToken) { var document = context.Document; if (document == null) { return null; } // C# and VB share the same LSP language server, and thus share the same default trigger characters. // We need to ensure the trigger character is valid in the document's language. For example, the '{' // character, while a trigger character in VB, is not a trigger character in C#. if (request.Context != null && request.Context.TriggerKind == LSP.CompletionTriggerKind.TriggerCharacter && !char.TryParse(request.Context.TriggerCharacter, out var triggerCharacter) && !char.IsLetterOrDigit(triggerCharacter) && !IsValidTriggerCharacterForDocument(document, triggerCharacter)) { return null; } var completionOptions = await GetCompletionOptionsAsync(document, cancellationToken).ConfigureAwait(false); var completionService = document.GetRequiredLanguageService<CompletionService>(); var documentText = await document.GetTextAsync(cancellationToken).ConfigureAwait(false); var completionListResult = await GetFilteredCompletionListAsync(request, documentText, document, completionOptions, completionService, cancellationToken).ConfigureAwait(false); if (completionListResult == null) { return null; } var (list, isIncomplete, resultId) = completionListResult.Value; var lspVSClientCapability = context.ClientCapabilities.HasVisualStudioLspCapability() == true; var snippetsSupported = context.ClientCapabilities.TextDocument?.Completion?.CompletionItem?.SnippetSupport ?? false; var commitCharactersRuleCache = new Dictionary<ImmutableArray<CharacterSetModificationRule>, string[]>(CommitCharacterArrayComparer.Instance); // Feature flag to enable the return of TextEdits instead of InsertTexts (will increase payload size). // Flag is defined in VisualStudio\Core\Def\PackageRegistration.pkgdef. // We also check against the CompletionOption for test purposes only. Contract.ThrowIfNull(context.Solution); var featureFlagService = context.Solution.Workspace.Services.GetRequiredService<IExperimentationService>(); var returnTextEdits = featureFlagService.IsExperimentEnabled(WellKnownExperimentNames.LSPCompletion) || completionOptions.GetOption(CompletionOptions.ForceRoslynLSPCompletionExperiment, document.Project.Language); TextSpan? defaultSpan = null; LSP.Range? defaultRange = null; if (returnTextEdits) { // We want to compute the document's text just once. documentText = await document.GetTextAsync(cancellationToken).ConfigureAwait(false); // We use the first item in the completion list as our comparison point for span // and range for optimization when generating the TextEdits later on. var completionChange = await completionService.GetChangeAsync( document, list.Items.First(), cancellationToken: cancellationToken).ConfigureAwait(false); // If possible, we want to compute the item's span and range just once. // Individual items can override this range later. defaultSpan = completionChange.TextChange.Span; defaultRange = ProtocolConversions.TextSpanToRange(defaultSpan.Value, documentText); } var supportsCompletionListData = context.ClientCapabilities.HasCompletionListDataCapability(); var completionResolveData = new CompletionResolveData() { ResultId = resultId, }; var stringBuilder = new StringBuilder(); using var _ = ArrayBuilder<LSP.CompletionItem>.GetInstance(out var lspCompletionItems); foreach (var item in list.Items) { var completionItemResolveData = supportsCompletionListData ? null : completionResolveData; var lspCompletionItem = await CreateLSPCompletionItemAsync( request, document, item, completionItemResolveData, lspVSClientCapability, commitCharactersRuleCache, completionService, context.ClientName, returnTextEdits, snippetsSupported, stringBuilder, documentText, defaultSpan, defaultRange, cancellationToken).ConfigureAwait(false); lspCompletionItems.Add(lspCompletionItem); } var completionList = new LSP.VSCompletionList { Items = lspCompletionItems.ToArray(), SuggestionMode = list.SuggestionModeItem != null, IsIncomplete = isIncomplete, }; if (supportsCompletionListData) { completionList.Data = completionResolveData; } if (context.ClientCapabilities.HasCompletionListCommitCharactersCapability()) { PromoteCommonCommitCharactersOntoList(completionList); } var optimizedCompletionList = new LSP.OptimizedVSCompletionList(completionList); return optimizedCompletionList; // Local functions bool IsValidTriggerCharacterForDocument(Document document, char triggerCharacter) { if (document.Project.Language == LanguageNames.CSharp) { return _csharpTriggerCharacters.Contains(triggerCharacter); } else if (document.Project.Language == LanguageNames.VisualBasic) { return _vbTriggerCharacters.Contains(triggerCharacter); } // Typescript still calls into this for completion. // Since we don't know what their trigger characters are, just return true. return true; } static async Task<LSP.CompletionItem> CreateLSPCompletionItemAsync( LSP.CompletionParams request, Document document, CompletionItem item, CompletionResolveData? completionResolveData, bool supportsVSExtensions, Dictionary<ImmutableArray<CharacterSetModificationRule>, string[]> commitCharacterRulesCache, CompletionService completionService, string? clientName, bool returnTextEdits, bool snippetsSupported, StringBuilder stringBuilder, SourceText? documentText, TextSpan? defaultSpan, LSP.Range? defaultRange, CancellationToken cancellationToken) { if (supportsVSExtensions) { var vsCompletionItem = await CreateCompletionItemAsync<LSP.VSCompletionItem>( request, document, item, completionResolveData, supportsVSExtensions, commitCharacterRulesCache, completionService, clientName, returnTextEdits, snippetsSupported, stringBuilder, documentText, defaultSpan, defaultRange, cancellationToken).ConfigureAwait(false); vsCompletionItem.Icon = new ImageElement(item.Tags.GetFirstGlyph().GetImageId()); return vsCompletionItem; } else { var roslynCompletionItem = await CreateCompletionItemAsync<LSP.CompletionItem>( request, document, item, completionResolveData, supportsVSExtensions, commitCharacterRulesCache, completionService, clientName, returnTextEdits, snippetsSupported, stringBuilder, documentText, defaultSpan, defaultRange, cancellationToken).ConfigureAwait(false); return roslynCompletionItem; } } static async Task<TCompletionItem> CreateCompletionItemAsync<TCompletionItem>( LSP.CompletionParams request, Document document, CompletionItem item, CompletionResolveData? completionResolveData, bool supportsVSExtensions, Dictionary<ImmutableArray<CharacterSetModificationRule>, string[]> commitCharacterRulesCache, CompletionService completionService, string? clientName, bool returnTextEdits, bool snippetsSupported, StringBuilder stringBuilder, SourceText? documentText, TextSpan? defaultSpan, LSP.Range? defaultRange, CancellationToken cancellationToken) where TCompletionItem : LSP.CompletionItem, new() { // Generate display text stringBuilder.Append(item.DisplayTextPrefix); stringBuilder.Append(item.DisplayText); stringBuilder.Append(item.DisplayTextSuffix); var completeDisplayText = stringBuilder.ToString(); stringBuilder.Clear(); var completionItem = new TCompletionItem { Label = completeDisplayText, SortText = item.SortText, FilterText = item.FilterText, Kind = GetCompletionKind(item.Tags), Data = completionResolveData, Preselect = ShouldItemBePreselected(item), }; // Complex text edits (e.g. override and partial method completions) are always populated in the // resolve handler, so we leave both TextEdit and InsertText unpopulated in these cases. if (item.IsComplexTextEdit) { // Razor C# is currently the only language client that supports LSP.InsertTextFormat.Snippet. // We can enable it for regular C# once LSP is used for local completion. if (snippetsSupported) { completionItem.InsertTextFormat = LSP.InsertTextFormat.Snippet; } } // If the feature flag is on, always return a TextEdit. else if (returnTextEdits) { var textEdit = await GenerateTextEdit( document, item, completionService, documentText, defaultSpan, defaultRange, cancellationToken).ConfigureAwait(false); completionItem.TextEdit = textEdit; } // If the feature flag is off, return an InsertText. else { completionItem.InsertText = item.Properties.ContainsKey("InsertionText") ? item.Properties["InsertionText"] : completeDisplayText; } var commitCharacters = GetCommitCharacters(item, commitCharacterRulesCache, supportsVSExtensions); if (commitCharacters != null) { completionItem.CommitCharacters = commitCharacters; } return completionItem; static async Task<LSP.TextEdit> GenerateTextEdit( Document document, CompletionItem item, CompletionService completionService, SourceText? documentText, TextSpan? defaultSpan, LSP.Range? defaultRange, CancellationToken cancellationToken) { Contract.ThrowIfNull(documentText); Contract.ThrowIfNull(defaultSpan); Contract.ThrowIfNull(defaultRange); var completionChange = await completionService.GetChangeAsync( document, item, cancellationToken: cancellationToken).ConfigureAwait(false); var completionChangeSpan = completionChange.TextChange.Span; var textEdit = new LSP.TextEdit() { NewText = completionChange.TextChange.NewText ?? "", Range = completionChangeSpan == defaultSpan.Value ? defaultRange : ProtocolConversions.TextSpanToRange(completionChangeSpan, documentText), }; return textEdit; } } static string[]? GetCommitCharacters( CompletionItem item, Dictionary<ImmutableArray<CharacterSetModificationRule>, string[]> currentRuleCache, bool supportsVSExtensions) { // VSCode does not have the concept of soft selection, the list is always hard selected. // In order to emulate soft selection behavior for things like argument completion, regex completion, datetime completion, etc // we create a completion item without any specific commit characters. This means only tab / enter will commit. // VS supports soft selection, so we only do this for non-VS clients. if (!supportsVSExtensions && item.Rules.SelectionBehavior == CompletionItemSelectionBehavior.SoftSelection) { return Array.Empty<string>(); } var commitCharacterRules = item.Rules.CommitCharacterRules; // VS will use the default commit characters if no items are specified on the completion item. // However, other clients like VSCode do not support this behavior so we must specify // commit characters on every completion item - https://github.com/microsoft/vscode/issues/90987 if (supportsVSExtensions && commitCharacterRules.IsEmpty) { return null; } if (currentRuleCache.TryGetValue(commitCharacterRules, out var cachedCommitCharacters)) { return cachedCommitCharacters; } using var _ = PooledHashSet<char>.GetInstance(out var commitCharacters); commitCharacters.AddAll(CompletionRules.Default.DefaultCommitCharacters); foreach (var rule in commitCharacterRules) { switch (rule.Kind) { case CharacterSetModificationKind.Add: commitCharacters.UnionWith(rule.Characters); continue; case CharacterSetModificationKind.Remove: commitCharacters.ExceptWith(rule.Characters); continue; case CharacterSetModificationKind.Replace: commitCharacters.Clear(); commitCharacters.AddRange(rule.Characters); break; } } var lspCommitCharacters = commitCharacters.Select(c => c.ToString()).ToArray(); currentRuleCache.Add(item.Rules.CommitCharacterRules, lspCommitCharacters); return lspCommitCharacters; } static void PromoteCommonCommitCharactersOntoList(LSP.VSCompletionList completionList) { var commitCharacterReferences = new Dictionary<object, int>(); var mostUsedCount = 0; string[]? mostUsedCommitCharacters = null; for (var i = 0; i < completionList.Items.Length; i++) { var completionItem = completionList.Items[i]; var commitCharacters = completionItem.CommitCharacters; if (commitCharacters == null) { continue; } commitCharacterReferences.TryGetValue(commitCharacters, out var existingCount); existingCount++; if (existingCount > mostUsedCount) { // Capture the most used commit character counts so we don't need to re-iterate the array later mostUsedCommitCharacters = commitCharacters; mostUsedCount = existingCount; } commitCharacterReferences[commitCharacters] = existingCount; } Contract.ThrowIfNull(mostUsedCommitCharacters); // Promoted the most used commit characters onto the list and then remove these from child items. completionList.CommitCharacters = mostUsedCommitCharacters; for (var i = 0; i < completionList.Items.Length; i++) { var completionItem = completionList.Items[i]; if (completionItem.CommitCharacters == mostUsedCommitCharacters) { completionItem.CommitCharacters = null; } } } } private async Task<(CompletionList CompletionList, bool IsIncomplete, long ResultId)?> GetFilteredCompletionListAsync( LSP.CompletionParams request, SourceText sourceText, Document document, OptionSet completionOptions, CompletionService completionService, CancellationToken cancellationToken) { var position = await document.GetPositionFromLinePositionAsync(ProtocolConversions.PositionToLinePosition(request.Position), cancellationToken).ConfigureAwait(false); var completionListSpan = completionService.GetDefaultCompletionListSpan(sourceText, position); var completionTrigger = await ProtocolConversions.LSPToRoslynCompletionTriggerAsync(request.Context, document, position, cancellationToken).ConfigureAwait(false); var isTriggerForIncompleteCompletions = request.Context?.TriggerKind == LSP.CompletionTriggerKind.TriggerForIncompleteCompletions; (CompletionList List, long ResultId)? result; if (isTriggerForIncompleteCompletions) { // We don't have access to the original trigger, but we know the completion list is already present. // It is safe to recompute with the invoked trigger as we will get all the items and filter down based on the current trigger. var originalTrigger = new CompletionTrigger(CompletionTriggerKind.Invoke); result = await CalculateListAsync(request, document, position, originalTrigger, completionOptions, completionService, _completionListCache, cancellationToken).ConfigureAwait(false); } else { // This is a new completion request, clear out the last result Id for incomplete results. result = await CalculateListAsync(request, document, position, completionTrigger, completionOptions, completionService, _completionListCache, cancellationToken).ConfigureAwait(false); } if (result == null) { return null; } var resultId = result.Value.ResultId; var completionListMaxSize = completionOptions.GetOption(LspOptions.MaxCompletionListSize); var (completionList, isIncomplete) = FilterCompletionList(result.Value.List, completionListMaxSize, completionListSpan, completionTrigger, sourceText, document); return (completionList, isIncomplete, resultId); } private static async Task<(CompletionList CompletionList, long ResultId)?> CalculateListAsync( LSP.CompletionParams request, Document document, int position, CompletionTrigger completionTrigger, OptionSet completionOptions, CompletionService completionService, CompletionListCache completionListCache, CancellationToken cancellationToken) { var completionList = await completionService.GetCompletionsAsync(document, position, completionTrigger, options: completionOptions, cancellationToken: cancellationToken).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); if (completionList == null || completionList.Items.IsEmpty) { return null; } // Cache the completion list so we can avoid recomputation in the resolve handler var resultId = completionListCache.UpdateCache(request.TextDocument, completionList); return (completionList, resultId); } private static (CompletionList CompletionList, bool IsIncomplete) FilterCompletionList( CompletionList completionList, int completionListMaxSize, TextSpan completionListSpan, CompletionTrigger completionTrigger, SourceText sourceText, Document document) { var filterText = sourceText.GetSubText(completionListSpan).ToString(); // Use pattern matching to determine which items are most relevant out of the calculated items. using var _ = ArrayBuilder<MatchResult<CompletionItem?>>.GetInstance(out var matchResultsBuilder); var index = 0; var completionHelper = CompletionHelper.GetHelper(document); foreach (var item in completionList.Items) { if (CompletionHelper.TryCreateMatchResult<CompletionItem?>( completionHelper, item, editorCompletionItem: null, filterText, completionTrigger.Kind, GetFilterReason(completionTrigger), recentItems: ImmutableArray<string>.Empty, includeMatchSpans: false, index, out var matchResult)) { matchResultsBuilder.Add(matchResult); index++; } } // Next, we sort the list based on the pattern matching result. matchResultsBuilder.Sort(MatchResult<CompletionItem?>.SortingComparer); // Finally, truncate the list to 1000 items plus any preselected items that occur after the first 1000. var filteredList = matchResultsBuilder .Take(completionListMaxSize) .Concat(matchResultsBuilder.Skip(completionListMaxSize).Where(match => ShouldItemBePreselected(match.RoslynCompletionItem))) .Select(matchResult => matchResult.RoslynCompletionItem) .ToImmutableArray(); var newCompletionList = completionList.WithItems(filteredList); // Per the LSP spec, the completion list should be marked with isIncomplete = false when further insertions will // not generate any more completion items. This means that we should be checking if the matchedResults is larger // than the filteredList. However, the VS client has a bug where they do not properly re-trigger completion // when a character is deleted to go from a complete list back to an incomplete list. // For example, the following scenario. // User types "So" -> server gives subset of items for "So" with isIncomplete = true // User types "m" -> server gives entire set of items for "Som" with isIncomplete = false // User deletes "m" -> client has to remember that "So" results were incomplete and re-request if the user types something else, like "n" // // Currently the VS client does not remember to re-request, so the completion list only ever shows items from "Som" // so we always set the isIncomplete flag to true when the original list size (computed when no filter text was typed) is too large. // VS bug here - https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1335142 var isIncomplete = completionList.Items.Length > newCompletionList.Items.Length; return (newCompletionList, isIncomplete); static CompletionFilterReason GetFilterReason(CompletionTrigger trigger) { return trigger.Kind switch { CompletionTriggerKind.Insertion => CompletionFilterReason.Insertion, CompletionTriggerKind.Deletion => CompletionFilterReason.Deletion, _ => CompletionFilterReason.Other, }; } } private static bool ShouldItemBePreselected(CompletionItem completionItem) { // An item should be preselcted for LSP when the match priority is preselect and the item is hard selected. // LSP does not support soft preselection, so we do not preselect in that scenario to avoid interfering with typing. return completionItem.Rules.MatchPriority == MatchPriority.Preselect && completionItem.Rules.SelectionBehavior == CompletionItemSelectionBehavior.HardSelection; } internal static ImmutableHashSet<char> GetTriggerCharacters(CompletionProvider provider) { if (provider is LSPCompletionProvider lspProvider) { return lspProvider.TriggerCharacters; } return ImmutableHashSet<char>.Empty; } internal static async Task<OptionSet> GetCompletionOptionsAsync(Document document, CancellationToken cancellationToken) { // Filter out snippets as they are not supported in the LSP client // https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1139740 // Filter out unimported types for now as there are two issues with providing them: // 1. LSP client does not currently provide a way to provide detail text on the completion item to show the namespace. // https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1076759 // 2. We need to figure out how to provide the text edits along with the completion item or provide them in the resolve request. // https://devdiv.visualstudio.com/DevDiv/_workitems/edit/985860/ // 3. LSP client should support completion filters / expanders var documentOptions = await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false); var completionOptions = documentOptions .WithChangedOption(CompletionOptions.SnippetsBehavior, SnippetsRule.NeverInclude) .WithChangedOption(CompletionOptions.ShowItemsFromUnimportedNamespaces, false) .WithChangedOption(CompletionServiceOptions.IsExpandedCompletion, false); return completionOptions; } private static LSP.CompletionItemKind GetCompletionKind(ImmutableArray<string> tags) { foreach (var tag in tags) { if (ProtocolConversions.RoslynTagToCompletionItemKind.TryGetValue(tag, out var completionItemKind)) { return completionItemKind; } } return LSP.CompletionItemKind.Text; } internal TestAccessor GetTestAccessor() => new TestAccessor(this); internal readonly struct TestAccessor { private readonly CompletionHandler _completionHandler; public TestAccessor(CompletionHandler completionHandler) => _completionHandler = completionHandler; public CompletionListCache GetCache() => _completionHandler._completionListCache; } private class CommitCharacterArrayComparer : IEqualityComparer<ImmutableArray<CharacterSetModificationRule>> { public static readonly CommitCharacterArrayComparer Instance = new(); private CommitCharacterArrayComparer() { } public bool Equals([AllowNull] ImmutableArray<CharacterSetModificationRule> x, [AllowNull] ImmutableArray<CharacterSetModificationRule> y) { for (var i = 0; i < x.Length; i++) { var xKind = x[i].Kind; var yKind = y[i].Kind; if (xKind != yKind) { return false; } var xCharacters = x[i].Characters; var yCharacters = y[i].Characters; if (xCharacters.Length != yCharacters.Length) { return false; } for (var j = 0; j < xCharacters.Length; j++) { if (xCharacters[j] != yCharacters[j]) { return false; } } } return true; } public int GetHashCode([DisallowNull] ImmutableArray<CharacterSetModificationRule> obj) { var combinedHash = Hash.CombineValues(obj); return combinedHash; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Completion; using Microsoft.CodeAnalysis.Completion.Providers; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Experiments; using Microsoft.CodeAnalysis.LanguageServer.Handler.Completion; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Text.Adornments; using Roslyn.Utilities; using LSP = Microsoft.VisualStudio.LanguageServer.Protocol; namespace Microsoft.CodeAnalysis.LanguageServer.Handler { /// <summary> /// Handle a completion request. /// </summary> internal class CompletionHandler : IRequestHandler<LSP.CompletionParams, LSP.CompletionList?> { private readonly ImmutableHashSet<char> _csharpTriggerCharacters; private readonly ImmutableHashSet<char> _vbTriggerCharacters; private readonly CompletionListCache _completionListCache; public string Method => LSP.Methods.TextDocumentCompletionName; public bool MutatesSolutionState => false; public bool RequiresLSPSolution => true; public CompletionHandler( IEnumerable<Lazy<CompletionProvider, CompletionProviderMetadata>> completionProviders, CompletionListCache completionListCache) { _csharpTriggerCharacters = completionProviders.Where(lz => lz.Metadata.Language == LanguageNames.CSharp).SelectMany( lz => GetTriggerCharacters(lz.Value)).ToImmutableHashSet(); _vbTriggerCharacters = completionProviders.Where(lz => lz.Metadata.Language == LanguageNames.VisualBasic).SelectMany( lz => GetTriggerCharacters(lz.Value)).ToImmutableHashSet(); _completionListCache = completionListCache; } public LSP.TextDocumentIdentifier? GetTextDocumentIdentifier(LSP.CompletionParams request) => request.TextDocument; public async Task<LSP.CompletionList?> HandleRequestAsync(LSP.CompletionParams request, RequestContext context, CancellationToken cancellationToken) { var document = context.Document; if (document == null) { return null; } // C# and VB share the same LSP language server, and thus share the same default trigger characters. // We need to ensure the trigger character is valid in the document's language. For example, the '{' // character, while a trigger character in VB, is not a trigger character in C#. if (request.Context != null && request.Context.TriggerKind == LSP.CompletionTriggerKind.TriggerCharacter && !char.TryParse(request.Context.TriggerCharacter, out var triggerCharacter) && !char.IsLetterOrDigit(triggerCharacter) && !IsValidTriggerCharacterForDocument(document, triggerCharacter)) { return null; } var completionOptions = await GetCompletionOptionsAsync(document, cancellationToken).ConfigureAwait(false); var completionService = document.GetRequiredLanguageService<CompletionService>(); var documentText = await document.GetTextAsync(cancellationToken).ConfigureAwait(false); var completionListResult = await GetFilteredCompletionListAsync(request, documentText, document, completionOptions, completionService, cancellationToken).ConfigureAwait(false); if (completionListResult == null) { return null; } var (list, isIncomplete, resultId) = completionListResult.Value; var lspVSClientCapability = context.ClientCapabilities.HasVisualStudioLspCapability() == true; var snippetsSupported = context.ClientCapabilities.TextDocument?.Completion?.CompletionItem?.SnippetSupport ?? false; var commitCharactersRuleCache = new Dictionary<ImmutableArray<CharacterSetModificationRule>, string[]>(CommitCharacterArrayComparer.Instance); // Feature flag to enable the return of TextEdits instead of InsertTexts (will increase payload size). // Flag is defined in VisualStudio\Core\Def\PackageRegistration.pkgdef. // We also check against the CompletionOption for test purposes only. Contract.ThrowIfNull(context.Solution); var featureFlagService = context.Solution.Workspace.Services.GetRequiredService<IExperimentationService>(); var returnTextEdits = featureFlagService.IsExperimentEnabled(WellKnownExperimentNames.LSPCompletion) || completionOptions.GetOption(CompletionOptions.ForceRoslynLSPCompletionExperiment, document.Project.Language); TextSpan? defaultSpan = null; LSP.Range? defaultRange = null; if (returnTextEdits) { // We want to compute the document's text just once. documentText = await document.GetTextAsync(cancellationToken).ConfigureAwait(false); // We use the first item in the completion list as our comparison point for span // and range for optimization when generating the TextEdits later on. var completionChange = await completionService.GetChangeAsync( document, list.Items.First(), cancellationToken: cancellationToken).ConfigureAwait(false); // If possible, we want to compute the item's span and range just once. // Individual items can override this range later. defaultSpan = completionChange.TextChange.Span; defaultRange = ProtocolConversions.TextSpanToRange(defaultSpan.Value, documentText); } var supportsCompletionListData = context.ClientCapabilities.HasCompletionListDataCapability(); var completionResolveData = new CompletionResolveData() { ResultId = resultId, }; var stringBuilder = new StringBuilder(); using var _ = ArrayBuilder<LSP.CompletionItem>.GetInstance(out var lspCompletionItems); foreach (var item in list.Items) { var completionItemResolveData = supportsCompletionListData ? null : completionResolveData; var lspCompletionItem = await CreateLSPCompletionItemAsync( request, document, item, completionItemResolveData, lspVSClientCapability, commitCharactersRuleCache, completionService, context.ClientName, returnTextEdits, snippetsSupported, stringBuilder, documentText, defaultSpan, defaultRange, cancellationToken).ConfigureAwait(false); lspCompletionItems.Add(lspCompletionItem); } var completionList = new LSP.VSCompletionList { Items = lspCompletionItems.ToArray(), SuggestionMode = list.SuggestionModeItem != null, IsIncomplete = isIncomplete, }; if (supportsCompletionListData) { completionList.Data = completionResolveData; } if (context.ClientCapabilities.HasCompletionListCommitCharactersCapability()) { PromoteCommonCommitCharactersOntoList(completionList); } var optimizedCompletionList = new LSP.OptimizedVSCompletionList(completionList); return optimizedCompletionList; // Local functions bool IsValidTriggerCharacterForDocument(Document document, char triggerCharacter) { if (document.Project.Language == LanguageNames.CSharp) { return _csharpTriggerCharacters.Contains(triggerCharacter); } else if (document.Project.Language == LanguageNames.VisualBasic) { return _vbTriggerCharacters.Contains(triggerCharacter); } // Typescript still calls into this for completion. // Since we don't know what their trigger characters are, just return true. return true; } static async Task<LSP.CompletionItem> CreateLSPCompletionItemAsync( LSP.CompletionParams request, Document document, CompletionItem item, CompletionResolveData? completionResolveData, bool supportsVSExtensions, Dictionary<ImmutableArray<CharacterSetModificationRule>, string[]> commitCharacterRulesCache, CompletionService completionService, string? clientName, bool returnTextEdits, bool snippetsSupported, StringBuilder stringBuilder, SourceText? documentText, TextSpan? defaultSpan, LSP.Range? defaultRange, CancellationToken cancellationToken) { if (supportsVSExtensions) { var vsCompletionItem = await CreateCompletionItemAsync<LSP.VSCompletionItem>( request, document, item, completionResolveData, supportsVSExtensions, commitCharacterRulesCache, completionService, clientName, returnTextEdits, snippetsSupported, stringBuilder, documentText, defaultSpan, defaultRange, cancellationToken).ConfigureAwait(false); vsCompletionItem.Icon = new ImageElement(item.Tags.GetFirstGlyph().GetImageId()); return vsCompletionItem; } else { var roslynCompletionItem = await CreateCompletionItemAsync<LSP.CompletionItem>( request, document, item, completionResolveData, supportsVSExtensions, commitCharacterRulesCache, completionService, clientName, returnTextEdits, snippetsSupported, stringBuilder, documentText, defaultSpan, defaultRange, cancellationToken).ConfigureAwait(false); return roslynCompletionItem; } } static async Task<TCompletionItem> CreateCompletionItemAsync<TCompletionItem>( LSP.CompletionParams request, Document document, CompletionItem item, CompletionResolveData? completionResolveData, bool supportsVSExtensions, Dictionary<ImmutableArray<CharacterSetModificationRule>, string[]> commitCharacterRulesCache, CompletionService completionService, string? clientName, bool returnTextEdits, bool snippetsSupported, StringBuilder stringBuilder, SourceText? documentText, TextSpan? defaultSpan, LSP.Range? defaultRange, CancellationToken cancellationToken) where TCompletionItem : LSP.CompletionItem, new() { // Generate display text stringBuilder.Append(item.DisplayTextPrefix); stringBuilder.Append(item.DisplayText); stringBuilder.Append(item.DisplayTextSuffix); var completeDisplayText = stringBuilder.ToString(); stringBuilder.Clear(); var completionItem = new TCompletionItem { Label = completeDisplayText, SortText = item.SortText, FilterText = item.FilterText, Kind = GetCompletionKind(item.Tags), Data = completionResolveData, Preselect = ShouldItemBePreselected(item), }; // Complex text edits (e.g. override and partial method completions) are always populated in the // resolve handler, so we leave both TextEdit and InsertText unpopulated in these cases. if (item.IsComplexTextEdit) { // Razor C# is currently the only language client that supports LSP.InsertTextFormat.Snippet. // We can enable it for regular C# once LSP is used for local completion. if (snippetsSupported) { completionItem.InsertTextFormat = LSP.InsertTextFormat.Snippet; } } // If the feature flag is on, always return a TextEdit. else if (returnTextEdits) { var textEdit = await GenerateTextEdit( document, item, completionService, documentText, defaultSpan, defaultRange, cancellationToken).ConfigureAwait(false); completionItem.TextEdit = textEdit; } // If the feature flag is off, return an InsertText. else { completionItem.InsertText = item.Properties.ContainsKey("InsertionText") ? item.Properties["InsertionText"] : completeDisplayText; } var commitCharacters = GetCommitCharacters(item, commitCharacterRulesCache, supportsVSExtensions); if (commitCharacters != null) { completionItem.CommitCharacters = commitCharacters; } return completionItem; static async Task<LSP.TextEdit> GenerateTextEdit( Document document, CompletionItem item, CompletionService completionService, SourceText? documentText, TextSpan? defaultSpan, LSP.Range? defaultRange, CancellationToken cancellationToken) { Contract.ThrowIfNull(documentText); Contract.ThrowIfNull(defaultSpan); Contract.ThrowIfNull(defaultRange); var completionChange = await completionService.GetChangeAsync( document, item, cancellationToken: cancellationToken).ConfigureAwait(false); var completionChangeSpan = completionChange.TextChange.Span; var textEdit = new LSP.TextEdit() { NewText = completionChange.TextChange.NewText ?? "", Range = completionChangeSpan == defaultSpan.Value ? defaultRange : ProtocolConversions.TextSpanToRange(completionChangeSpan, documentText), }; return textEdit; } } static string[]? GetCommitCharacters( CompletionItem item, Dictionary<ImmutableArray<CharacterSetModificationRule>, string[]> currentRuleCache, bool supportsVSExtensions) { // VSCode does not have the concept of soft selection, the list is always hard selected. // In order to emulate soft selection behavior for things like argument completion, regex completion, datetime completion, etc // we create a completion item without any specific commit characters. This means only tab / enter will commit. // VS supports soft selection, so we only do this for non-VS clients. if (!supportsVSExtensions && item.Rules.SelectionBehavior == CompletionItemSelectionBehavior.SoftSelection) { return Array.Empty<string>(); } var commitCharacterRules = item.Rules.CommitCharacterRules; // VS will use the default commit characters if no items are specified on the completion item. // However, other clients like VSCode do not support this behavior so we must specify // commit characters on every completion item - https://github.com/microsoft/vscode/issues/90987 if (supportsVSExtensions && commitCharacterRules.IsEmpty) { return null; } if (currentRuleCache.TryGetValue(commitCharacterRules, out var cachedCommitCharacters)) { return cachedCommitCharacters; } using var _ = PooledHashSet<char>.GetInstance(out var commitCharacters); commitCharacters.AddAll(CompletionRules.Default.DefaultCommitCharacters); foreach (var rule in commitCharacterRules) { switch (rule.Kind) { case CharacterSetModificationKind.Add: commitCharacters.UnionWith(rule.Characters); continue; case CharacterSetModificationKind.Remove: commitCharacters.ExceptWith(rule.Characters); continue; case CharacterSetModificationKind.Replace: commitCharacters.Clear(); commitCharacters.AddRange(rule.Characters); break; } } var lspCommitCharacters = commitCharacters.Select(c => c.ToString()).ToArray(); currentRuleCache.Add(item.Rules.CommitCharacterRules, lspCommitCharacters); return lspCommitCharacters; } static void PromoteCommonCommitCharactersOntoList(LSP.VSCompletionList completionList) { var defaultCommitCharacters = CompletionRules.Default.DefaultCommitCharacters.Select(c => c.ToString()).ToArray(); var commitCharacterReferences = new Dictionary<object, int>(); var mostUsedCount = 0; string[]? mostUsedCommitCharacters = null; for (var i = 0; i < completionList.Items.Length; i++) { var completionItem = completionList.Items[i]; var commitCharacters = completionItem.CommitCharacters; if (commitCharacters == null) { // The commit characters on the item are null, this means the commit characters are actually // the default commit characters we passed in the initialize request. commitCharacters = defaultCommitCharacters; } commitCharacterReferences.TryGetValue(commitCharacters, out var existingCount); existingCount++; if (existingCount > mostUsedCount) { // Capture the most used commit character counts so we don't need to re-iterate the array later mostUsedCommitCharacters = commitCharacters; mostUsedCount = existingCount; } commitCharacterReferences[commitCharacters] = existingCount; } Contract.ThrowIfNull(mostUsedCommitCharacters); // Promoted the most used commit characters onto the list and then remove these from child items. completionList.CommitCharacters = mostUsedCommitCharacters; for (var i = 0; i < completionList.Items.Length; i++) { var completionItem = completionList.Items[i]; if (completionItem.CommitCharacters == mostUsedCommitCharacters) { completionItem.CommitCharacters = null; } } } } private async Task<(CompletionList CompletionList, bool IsIncomplete, long ResultId)?> GetFilteredCompletionListAsync( LSP.CompletionParams request, SourceText sourceText, Document document, OptionSet completionOptions, CompletionService completionService, CancellationToken cancellationToken) { var position = await document.GetPositionFromLinePositionAsync(ProtocolConversions.PositionToLinePosition(request.Position), cancellationToken).ConfigureAwait(false); var completionListSpan = completionService.GetDefaultCompletionListSpan(sourceText, position); var completionTrigger = await ProtocolConversions.LSPToRoslynCompletionTriggerAsync(request.Context, document, position, cancellationToken).ConfigureAwait(false); var isTriggerForIncompleteCompletions = request.Context?.TriggerKind == LSP.CompletionTriggerKind.TriggerForIncompleteCompletions; (CompletionList List, long ResultId)? result; if (isTriggerForIncompleteCompletions) { // We don't have access to the original trigger, but we know the completion list is already present. // It is safe to recompute with the invoked trigger as we will get all the items and filter down based on the current trigger. var originalTrigger = new CompletionTrigger(CompletionTriggerKind.Invoke); result = await CalculateListAsync(request, document, position, originalTrigger, completionOptions, completionService, _completionListCache, cancellationToken).ConfigureAwait(false); } else { // This is a new completion request, clear out the last result Id for incomplete results. result = await CalculateListAsync(request, document, position, completionTrigger, completionOptions, completionService, _completionListCache, cancellationToken).ConfigureAwait(false); } if (result == null) { return null; } var resultId = result.Value.ResultId; var completionListMaxSize = completionOptions.GetOption(LspOptions.MaxCompletionListSize); var (completionList, isIncomplete) = FilterCompletionList(result.Value.List, completionListMaxSize, completionListSpan, completionTrigger, sourceText, document); return (completionList, isIncomplete, resultId); } private static async Task<(CompletionList CompletionList, long ResultId)?> CalculateListAsync( LSP.CompletionParams request, Document document, int position, CompletionTrigger completionTrigger, OptionSet completionOptions, CompletionService completionService, CompletionListCache completionListCache, CancellationToken cancellationToken) { var completionList = await completionService.GetCompletionsAsync(document, position, completionTrigger, options: completionOptions, cancellationToken: cancellationToken).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); if (completionList == null || completionList.Items.IsEmpty) { return null; } // Cache the completion list so we can avoid recomputation in the resolve handler var resultId = completionListCache.UpdateCache(request.TextDocument, completionList); return (completionList, resultId); } private static (CompletionList CompletionList, bool IsIncomplete) FilterCompletionList( CompletionList completionList, int completionListMaxSize, TextSpan completionListSpan, CompletionTrigger completionTrigger, SourceText sourceText, Document document) { var filterText = sourceText.GetSubText(completionListSpan).ToString(); // Use pattern matching to determine which items are most relevant out of the calculated items. using var _ = ArrayBuilder<MatchResult<CompletionItem?>>.GetInstance(out var matchResultsBuilder); var index = 0; var completionHelper = CompletionHelper.GetHelper(document); foreach (var item in completionList.Items) { if (CompletionHelper.TryCreateMatchResult<CompletionItem?>( completionHelper, item, editorCompletionItem: null, filterText, completionTrigger.Kind, GetFilterReason(completionTrigger), recentItems: ImmutableArray<string>.Empty, includeMatchSpans: false, index, out var matchResult)) { matchResultsBuilder.Add(matchResult); index++; } } // Next, we sort the list based on the pattern matching result. matchResultsBuilder.Sort(MatchResult<CompletionItem?>.SortingComparer); // Finally, truncate the list to 1000 items plus any preselected items that occur after the first 1000. var filteredList = matchResultsBuilder .Take(completionListMaxSize) .Concat(matchResultsBuilder.Skip(completionListMaxSize).Where(match => ShouldItemBePreselected(match.RoslynCompletionItem))) .Select(matchResult => matchResult.RoslynCompletionItem) .ToImmutableArray(); var newCompletionList = completionList.WithItems(filteredList); // Per the LSP spec, the completion list should be marked with isIncomplete = false when further insertions will // not generate any more completion items. This means that we should be checking if the matchedResults is larger // than the filteredList. However, the VS client has a bug where they do not properly re-trigger completion // when a character is deleted to go from a complete list back to an incomplete list. // For example, the following scenario. // User types "So" -> server gives subset of items for "So" with isIncomplete = true // User types "m" -> server gives entire set of items for "Som" with isIncomplete = false // User deletes "m" -> client has to remember that "So" results were incomplete and re-request if the user types something else, like "n" // // Currently the VS client does not remember to re-request, so the completion list only ever shows items from "Som" // so we always set the isIncomplete flag to true when the original list size (computed when no filter text was typed) is too large. // VS bug here - https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1335142 var isIncomplete = completionList.Items.Length > newCompletionList.Items.Length; return (newCompletionList, isIncomplete); static CompletionFilterReason GetFilterReason(CompletionTrigger trigger) { return trigger.Kind switch { CompletionTriggerKind.Insertion => CompletionFilterReason.Insertion, CompletionTriggerKind.Deletion => CompletionFilterReason.Deletion, _ => CompletionFilterReason.Other, }; } } private static bool ShouldItemBePreselected(CompletionItem completionItem) { // An item should be preselcted for LSP when the match priority is preselect and the item is hard selected. // LSP does not support soft preselection, so we do not preselect in that scenario to avoid interfering with typing. return completionItem.Rules.MatchPriority == MatchPriority.Preselect && completionItem.Rules.SelectionBehavior == CompletionItemSelectionBehavior.HardSelection; } internal static ImmutableHashSet<char> GetTriggerCharacters(CompletionProvider provider) { if (provider is LSPCompletionProvider lspProvider) { return lspProvider.TriggerCharacters; } return ImmutableHashSet<char>.Empty; } internal static async Task<OptionSet> GetCompletionOptionsAsync(Document document, CancellationToken cancellationToken) { // Filter out snippets as they are not supported in the LSP client // https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1139740 // Filter out unimported types for now as there are two issues with providing them: // 1. LSP client does not currently provide a way to provide detail text on the completion item to show the namespace. // https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1076759 // 2. We need to figure out how to provide the text edits along with the completion item or provide them in the resolve request. // https://devdiv.visualstudio.com/DevDiv/_workitems/edit/985860/ // 3. LSP client should support completion filters / expanders var documentOptions = await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false); var completionOptions = documentOptions .WithChangedOption(CompletionOptions.SnippetsBehavior, SnippetsRule.NeverInclude) .WithChangedOption(CompletionOptions.ShowItemsFromUnimportedNamespaces, false) .WithChangedOption(CompletionServiceOptions.IsExpandedCompletion, false); return completionOptions; } private static LSP.CompletionItemKind GetCompletionKind(ImmutableArray<string> tags) { foreach (var tag in tags) { if (ProtocolConversions.RoslynTagToCompletionItemKind.TryGetValue(tag, out var completionItemKind)) { return completionItemKind; } } return LSP.CompletionItemKind.Text; } internal TestAccessor GetTestAccessor() => new TestAccessor(this); internal readonly struct TestAccessor { private readonly CompletionHandler _completionHandler; public TestAccessor(CompletionHandler completionHandler) => _completionHandler = completionHandler; public CompletionListCache GetCache() => _completionHandler._completionListCache; } private class CommitCharacterArrayComparer : IEqualityComparer<ImmutableArray<CharacterSetModificationRule>> { public static readonly CommitCharacterArrayComparer Instance = new(); private CommitCharacterArrayComparer() { } public bool Equals([AllowNull] ImmutableArray<CharacterSetModificationRule> x, [AllowNull] ImmutableArray<CharacterSetModificationRule> y) { for (var i = 0; i < x.Length; i++) { var xKind = x[i].Kind; var yKind = y[i].Kind; if (xKind != yKind) { return false; } var xCharacters = x[i].Characters; var yCharacters = y[i].Characters; if (xCharacters.Length != yCharacters.Length) { return false; } for (var j = 0; j < xCharacters.Length; j++) { if (xCharacters[j] != yCharacters[j]) { return false; } } } return true; } public int GetHashCode([DisallowNull] ImmutableArray<CharacterSetModificationRule> obj) { var combinedHash = Hash.CombineValues(obj); return combinedHash; } } } }
1
dotnet/roslyn
55,262
Fix LSP completions when all items have default commit characters
Fixes an exception stack trace seen in https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1362284 Also fixes behavior of promotion of commit characters to the list to include default commit characters
dibarbet
2021-07-30T02:43:35Z
2021-07-30T21:21:47Z
2f7dffa534aceb92e9767568e88535c926588d12
65ee073bf6cea571a68193793420ecee60752711
Fix LSP completions when all items have default commit characters. Fixes an exception stack trace seen in https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1362284 Also fixes behavior of promotion of commit characters to the list to include default commit characters
./src/Features/LanguageServer/ProtocolUnitTests/Completion/CompletionTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Completion; using Microsoft.CodeAnalysis.LanguageServer.Handler; using Microsoft.CodeAnalysis.LanguageServer.Handler.Completion; using Roslyn.Test.Utilities; using Xunit; using LSP = Microsoft.VisualStudio.LanguageServer.Protocol; namespace Microsoft.CodeAnalysis.LanguageServer.UnitTests.Completion { public class CompletionTests : AbstractLanguageServerProtocolTests { [Fact] public async Task TestGetCompletionsAsync_PromotesCommitCharactersToListAsync() { var clientCapabilities = new LSP.VSClientCapabilities { SupportsVisualStudioExtensions = true, TextDocument = new LSP.TextDocumentClientCapabilities() { Completion = new LSP.VSCompletionSetting() { CompletionList = new LSP.VSCompletionListSetting() { CommitCharacters = true, } } } }; var markup = @"class A { void M() { {|caret:|} } }"; using var testLspServer = CreateTestLspServer(markup, out var locations); var completionParams = CreateCompletionParams( locations["caret"].Single(), invokeKind: LSP.VSCompletionInvokeKind.Explicit, triggerCharacter: "\0", triggerKind: LSP.CompletionTriggerKind.Invoked); var document = testLspServer.GetCurrentSolution().Projects.First().Documents.First(); var expected = await CreateCompletionItemAsync(label: "A", kind: LSP.CompletionItemKind.Class, tags: new string[] { "Class", "Internal" }, request: completionParams, document: document, commitCharacters: CompletionRules.Default.DefaultCommitCharacters, insertText: "A").ConfigureAwait(false); var expectedCommitCharacters = expected.CommitCharacters; // Null out the commit characters since we're expecting the commit characters will be lifted onto the completion list. expected.CommitCharacters = null; var results = await RunGetCompletionsAsync(testLspServer, completionParams, clientCapabilities).ConfigureAwait(false); AssertJsonEquals(expected, results.Items.First()); var vsCompletionList = Assert.IsAssignableFrom<LSP.VSCompletionList>(results); Assert.Equal(expectedCommitCharacters, vsCompletionList.CommitCharacters.Value.First); } [Fact] public async Task TestGetCompletionsAsync() { var markup = @"class A { void M() { {|caret:|} } }"; using var testLspServer = CreateTestLspServer(markup, out var locations); var completionParams = CreateCompletionParams( locations["caret"].Single(), invokeKind: LSP.VSCompletionInvokeKind.Explicit, triggerCharacter: "\0", triggerKind: LSP.CompletionTriggerKind.Invoked); var document = testLspServer.GetCurrentSolution().Projects.First().Documents.First(); var expected = await CreateCompletionItemAsync(label: "A", kind: LSP.CompletionItemKind.Class, tags: new string[] { "Class", "Internal" }, request: completionParams, document: document, commitCharacters: CompletionRules.Default.DefaultCommitCharacters, insertText: "A").ConfigureAwait(false); var results = await RunGetCompletionsAsync(testLspServer, completionParams).ConfigureAwait(false); AssertJsonEquals(expected, results.Items.First()); } [Fact] public async Task TestGetCompletionsTypingAsync() { var markup = @"class A { void M() { A{|caret:|} } }"; using var testLspServer = CreateTestLspServer(markup, out var locations); var completionParams = CreateCompletionParams( locations["caret"].Single(), invokeKind: LSP.VSCompletionInvokeKind.Typing, triggerCharacter: "A", triggerKind: LSP.CompletionTriggerKind.Invoked); var document = testLspServer.GetCurrentSolution().Projects.First().Documents.First(); var expected = await CreateCompletionItemAsync(label: "A", kind: LSP.CompletionItemKind.Class, tags: new string[] { "Class", "Internal" }, request: completionParams, document: document, commitCharacters: CompletionRules.Default.DefaultCommitCharacters, insertText: "A").ConfigureAwait(false); var results = await RunGetCompletionsAsync(testLspServer, completionParams).ConfigureAwait(false); AssertJsonEquals(expected, results.Items.First()); } [Fact] public async Task TestGetCompletionsDoesNotIncludeUnimportedTypesAsync() { var markup = @"class A { void M() { {|caret:|} } }"; using var testLspServer = CreateTestLspServer(markup, out var locations); var solution = testLspServer.TestWorkspace.CurrentSolution; // Make sure the unimported types option is on by default. testLspServer.TestWorkspace.SetOptions(testLspServer.TestWorkspace.CurrentSolution.Options .WithChangedOption(CompletionOptions.ShowItemsFromUnimportedNamespaces, LanguageNames.CSharp, true) .WithChangedOption(CompletionServiceOptions.IsExpandedCompletion, true)); var completionParams = CreateCompletionParams( locations["caret"].Single(), invokeKind: LSP.VSCompletionInvokeKind.Explicit, triggerCharacter: "\0", triggerKind: LSP.CompletionTriggerKind.Invoked); var results = await RunGetCompletionsAsync(testLspServer, completionParams); Assert.False(results.Items.Any(item => "Console" == item.Label)); } [Fact] public async Task TestGetCompletionsDoesNotIncludeSnippetsAsync() { var markup = @"class A { {|caret:|} }"; using var testLspServer = CreateTestLspServer(markup, out var locations); var solution = testLspServer.TestWorkspace.CurrentSolution; solution = solution.WithOptions(solution.Options .WithChangedOption(CompletionOptions.SnippetsBehavior, LanguageNames.CSharp, SnippetsRule.AlwaysInclude)); var completionParams = CreateCompletionParams( locations["caret"].Single(), invokeKind: LSP.VSCompletionInvokeKind.Explicit, triggerCharacter: "\0", triggerKind: LSP.CompletionTriggerKind.Invoked); var results = await RunGetCompletionsAsync(testLspServer, completionParams); Assert.False(results.Items.Any(item => "ctor" == item.Label)); } [Fact] public async Task TestGetCompletionsWithPreselectAsync() { var markup = @"class A { void M() { A classA = new {|caret:|} } }"; using var testLspServer = CreateTestLspServer(markup, out var locations); var completionParams = CreateCompletionParams( locations["caret"].Single(), invokeKind: LSP.VSCompletionInvokeKind.Explicit, triggerCharacter: "\0", LSP.CompletionTriggerKind.Invoked); var document = testLspServer.GetCurrentSolution().Projects.First().Documents.First(); var expected = await CreateCompletionItemAsync("A", LSP.CompletionItemKind.Class, new string[] { "Class", "Internal" }, completionParams, document, preselect: true, commitCharacters: ImmutableArray.Create(' ', '(', '[', '{', ';', '.'), insertText: "A").ConfigureAwait(false); var results = await RunGetCompletionsAsync(testLspServer, completionParams).ConfigureAwait(false); AssertJsonEquals(expected, results.Items.First()); } [Fact] public async Task TestGetCompletionsIsInSuggestionMode() { var markup = @" using System.Collections.Generic; using System.Linq; namespace M { class Item { void M() { var items = new List<Item>(); items.Count(i{|caret:|} } } }"; using var testLspServer = CreateTestLspServer(markup, out var locations); var completionParams = CreateCompletionParams( locations["caret"].Single(), invokeKind: LSP.VSCompletionInvokeKind.Typing, triggerCharacter: "i", triggerKind: LSP.CompletionTriggerKind.Invoked); var results = (LSP.VSCompletionList)await RunGetCompletionsAsync(testLspServer, completionParams).ConfigureAwait(false); Assert.True(results.Items.Any()); Assert.True(results.SuggestionMode); } [Fact] public async Task TestGetDateAndTimeCompletionsAsync() { var markup = @"using System; class A { void M() { DateTime.Now.ToString(""{|caret:|}); } }"; using var testLspServer = CreateTestLspServer(markup, out var locations); var completionParams = CreateCompletionParams( locations["caret"].Single(), invokeKind: LSP.VSCompletionInvokeKind.Typing, triggerCharacter: "\"", triggerKind: LSP.CompletionTriggerKind.TriggerCharacter); var document = testLspServer.GetCurrentSolution().Projects.First().Documents.First(); var expected = await CreateCompletionItemAsync( label: "d", kind: LSP.CompletionItemKind.Text, tags: new string[] { "Text" }, request: completionParams, document: document, insertText: "d", sortText: "0000").ConfigureAwait(false); var results = await RunGetCompletionsAsync(testLspServer, completionParams).ConfigureAwait(false); AssertJsonEquals(expected, results.Items.First()); } [Fact] [WorkItem(50964, "https://github.com/dotnet/roslyn/issues/50964")] public async Task TestGetRegexCompletionsAsync() { var markup = @"using System.Text.RegularExpressions; class A { void M() { new Regex(""{|caret:|}""); } }"; using var testLspServer = CreateTestLspServer(markup, out var locations); var completionParams = CreateCompletionParams( locations["caret"].Single(), invokeKind: LSP.VSCompletionInvokeKind.Explicit, triggerCharacter: "\0", triggerKind: LSP.CompletionTriggerKind.Invoked); var solution = testLspServer.GetCurrentSolution(); var document = solution.Projects.First().Documents.First(); // Set to use prototype completion behavior (i.e. feature flag). var options = solution.Workspace.Options.WithChangedOption(CompletionOptions.ForceRoslynLSPCompletionExperiment, LanguageNames.CSharp, true); Assert.True(solution.Workspace.TryApplyChanges(solution.WithOptions(options))); var textEdit = GenerateTextEdit(@"\\A", startLine: 5, startChar: 19, endLine: 5, endChar: 19); var expected = await CreateCompletionItemAsync( label: @"\A", kind: LSP.CompletionItemKind.Text, tags: new string[] { "Text" }, request: completionParams, document: document, textEdit: textEdit, sortText: "0000").ConfigureAwait(false); var results = await RunGetCompletionsAsync(testLspServer, completionParams).ConfigureAwait(false); AssertJsonEquals(expected, results.Items.First()); } [Fact] [WorkItem(50964, "https://github.com/dotnet/roslyn/issues/50964")] public async Task TestGetRegexLiteralCompletionsAsync() { var markup = @"using System.Text.RegularExpressions; class A { void M() { new Regex(@""\{|caret:|}""); } }"; using var testLspServer = CreateTestLspServer(markup, out var locations); var completionParams = CreateCompletionParams( locations["caret"].Single(), invokeKind: LSP.VSCompletionInvokeKind.Explicit, triggerCharacter: "\\", triggerKind: LSP.CompletionTriggerKind.TriggerCharacter); var solution = testLspServer.GetCurrentSolution(); var document = solution.Projects.First().Documents.First(); // Set to use prototype completion behavior (i.e. feature flag). var options = solution.Workspace.Options.WithChangedOption(CompletionOptions.ForceRoslynLSPCompletionExperiment, LanguageNames.CSharp, true); Assert.True(solution.Workspace.TryApplyChanges(solution.WithOptions(options))); var textEdit = GenerateTextEdit(@"\A", startLine: 5, startChar: 20, endLine: 5, endChar: 21); var expected = await CreateCompletionItemAsync( label: @"\A", kind: LSP.CompletionItemKind.Text, tags: new string[] { "Text" }, request: completionParams, document: document, textEdit: textEdit, sortText: "0000").ConfigureAwait(false); var results = await RunGetCompletionsAsync(testLspServer, completionParams).ConfigureAwait(false); AssertJsonEquals(expected, results.Items.First()); } [Fact] [WorkItem(50964, "https://github.com/dotnet/roslyn/issues/50964")] public async Task TestGetRegexCompletionsReplaceTextAsync() { var markup = @"using System.Text.RegularExpressions; class A { void M() { Regex r = new(""\\{|caret:|}""); } }"; using var testLspServer = CreateTestLspServer(markup, out var locations); var completionParams = CreateCompletionParams( locations["caret"].Single(), invokeKind: LSP.VSCompletionInvokeKind.Typing, triggerCharacter: "\\", triggerKind: LSP.CompletionTriggerKind.TriggerCharacter); var solution = testLspServer.GetCurrentSolution(); var document = solution.Projects.First().Documents.First(); // Set to use prototype completion behavior (i.e. feature flag). var options = solution.Workspace.Options.WithChangedOption(CompletionOptions.ForceRoslynLSPCompletionExperiment, LanguageNames.CSharp, true); Assert.True(solution.Workspace.TryApplyChanges(solution.WithOptions(options))); var textEdit = GenerateTextEdit(@"\\A", startLine: 5, startChar: 23, endLine: 5, endChar: 25); var expected = await CreateCompletionItemAsync( label: @"\A", kind: LSP.CompletionItemKind.Text, tags: new string[] { "Text" }, request: completionParams, document: document, textEdit: textEdit, sortText: "0000").ConfigureAwait(false); var results = await RunGetCompletionsAsync(testLspServer, completionParams).ConfigureAwait(false); AssertJsonEquals(expected, results.Items.First()); } [Fact] [WorkItem(46694, "https://github.com/dotnet/roslyn/issues/46694")] public async Task TestCompletionListCacheAsync() { var markup = @"class A { void M() { {|caret:|} } }"; using var testLspServer = CreateTestLspServer(markup, out var locations); var cache = GetCompletionListCache(testLspServer); Assert.NotNull(cache); var testAccessor = cache.GetTestAccessor(); // This test assumes that the maximum cache size is 3, and will have to modified if this number changes. Assert.True(CompletionListCache.TestAccessor.MaximumCacheSize == 3); var completionParams = CreateCompletionParams( locations["caret"].Single(), invokeKind: LSP.VSCompletionInvokeKind.Explicit, triggerCharacter: "\0", triggerKind: LSP.CompletionTriggerKind.Invoked); // 1 item in cache await RunGetCompletionsAsync(testLspServer, completionParams).ConfigureAwait(false); var completionList = cache.GetCachedCompletionList(0).CompletionList; Assert.NotNull(completionList); Assert.True(testAccessor.GetCacheContents().Count == 1); // 2 items in cache await RunGetCompletionsAsync(testLspServer, completionParams).ConfigureAwait(false); completionList = cache.GetCachedCompletionList(0).CompletionList; Assert.NotNull(completionList); completionList = cache.GetCachedCompletionList(1).CompletionList; Assert.NotNull(completionList); Assert.True(testAccessor.GetCacheContents().Count == 2); // 3 items in cache await RunGetCompletionsAsync(testLspServer, completionParams).ConfigureAwait(false); completionList = cache.GetCachedCompletionList(0).CompletionList; Assert.NotNull(completionList); completionList = cache.GetCachedCompletionList(1).CompletionList; Assert.NotNull(completionList); completionList = cache.GetCachedCompletionList(2).CompletionList; Assert.NotNull(completionList); Assert.True(testAccessor.GetCacheContents().Count == 3); // Maximum size of cache (3) should not be exceeded - oldest item should be ejected await RunGetCompletionsAsync(testLspServer, completionParams).ConfigureAwait(false); var cacheEntry = cache.GetCachedCompletionList(0); Assert.Null(cacheEntry); completionList = cache.GetCachedCompletionList(1).CompletionList; Assert.NotNull(completionList); completionList = cache.GetCachedCompletionList(2).CompletionList; Assert.NotNull(completionList); completionList = cache.GetCachedCompletionList(3).CompletionList; Assert.NotNull(completionList); Assert.True(testAccessor.GetCacheContents().Count == 3); } [Fact] public async Task TestGetCompletionsWithDeletionInvokeKindAsync() { var markup = @"class A { void M() { {|caret:|} } }"; using var testLspServer = CreateTestLspServer(markup, out var locations); var completionParams = CreateCompletionParams( locations["caret"].Single(), invokeKind: LSP.VSCompletionInvokeKind.Deletion, triggerCharacter: "M", triggerKind: LSP.CompletionTriggerKind.Invoked); var document = testLspServer.GetCurrentSolution().Projects.First().Documents.First(); var expected = await CreateCompletionItemAsync("A", LSP.CompletionItemKind.Class, new string[] { "Class", "Internal" }, completionParams, document, commitCharacters: CompletionRules.Default.DefaultCommitCharacters).ConfigureAwait(false); var results = await RunGetCompletionsAsync(testLspServer, completionParams).ConfigureAwait(false); // By default, completion doesn't trigger on deletion. Assert.Null(results); } [Fact] public async Task TestDoNotProvideOverrideTextEditsOrInsertTextAsync() { var markup = @"abstract class A { public abstract void M(); } class B : A { override {|caret:|} }"; using var testLspServer = CreateTestLspServer(markup, out var locations); var completionParams = CreateCompletionParams( locations["caret"].Single(), invokeKind: LSP.VSCompletionInvokeKind.Explicit, triggerCharacter: "\0", triggerKind: LSP.CompletionTriggerKind.Invoked); var document = testLspServer.GetCurrentSolution().Projects.First().Documents.First(); var results = await RunGetCompletionsAsync(testLspServer, completionParams).ConfigureAwait(false); Assert.Null(results.Items.First().TextEdit); Assert.Null(results.Items.First().InsertText); } [Fact] public async Task TestDoNotProvidePartialMethodTextEditsOrInsertTextAsync() { var markup = @"partial class C { partial void Method(); } partial class C { partial {|caret:|} }"; using var testLspServer = CreateTestLspServer(markup, out var locations); var completionParams = CreateCompletionParams( locations["caret"].Single(), invokeKind: LSP.VSCompletionInvokeKind.Explicit, triggerCharacter: "\0", triggerKind: LSP.CompletionTriggerKind.Invoked); var document = testLspServer.GetCurrentSolution().Projects.First().Documents.First(); var results = await RunGetCompletionsAsync(testLspServer, completionParams).ConfigureAwait(false); Assert.Null(results.Items.First().TextEdit); Assert.Null(results.Items.First().InsertText); } [Fact] public async Task TestAlwaysHasCommitCharactersWithoutVSCapabilityAsync() { var markup = @"using System; class A { void M() { {|caret:|} } }"; using var testLspServer = CreateTestLspServer(markup, out var locations); var completionParams = CreateCompletionParams( locations["caret"].Single(), invokeKind: LSP.VSCompletionInvokeKind.Explicit, triggerCharacter: "\0", triggerKind: LSP.CompletionTriggerKind.Invoked); var document = testLspServer.GetCurrentSolution().Projects.First().Documents.First(); var results = await RunGetCompletionsAsync(testLspServer, completionParams, new LSP.VSClientCapabilities()).ConfigureAwait(false); Assert.NotNull(results); Assert.NotEmpty(results.Items); Assert.All(results.Items, (item) => Assert.NotNull(item.CommitCharacters)); } [Fact] public async Task TestSoftSelectedItemsHaveNoCommitCharactersWithoutVSCapabilityAsync() { var markup = @"using System.Text.RegularExpressions; class A { void M() { new Regex(""[{|caret:|}"") } }"; using var testLspServer = CreateTestLspServer(markup, out var locations); var completionParams = CreateCompletionParams( locations["caret"].Single(), invokeKind: LSP.VSCompletionInvokeKind.Typing, triggerCharacter: "[", triggerKind: LSP.CompletionTriggerKind.TriggerCharacter); var document = testLspServer.GetCurrentSolution().Projects.First().Documents.First(); var results = await RunGetCompletionsAsync(testLspServer, completionParams, new LSP.VSClientCapabilities()).ConfigureAwait(false); Assert.NotNull(results); Assert.NotEmpty(results.Items); Assert.All(results.Items, (item) => Assert.True(item.CommitCharacters.Length == 0)); } [Fact] public async Task TestLargeCompletionListIsMarkedIncompleteAsync() { var markup = @"using System; using System.Buffers; using System.Buffers.Binary; using System.Buffers.Text; using System.Collections; using System.Collections.Generic; using System.Collections.Immutable; using System.Collections.ObjectModel; using System.ComponentModel; using System.ComponentModel.Design; using System.Configuration; using System.Data; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Drawing; using System.Dynamic; using System.Globalization; using System.IO; using System.Linq; using System.Media; using System.Net; using System.Net.Http; using System.Net.Http.Json; using System.Text; using System.Threading; using System.Threading.Tasks; class A { void M() { T{|caret:|} } }"; using var testLspServer = CreateTestLspServer(markup, out var locations); var completionParams = CreateCompletionParams( locations["caret"].Single(), invokeKind: LSP.VSCompletionInvokeKind.Typing, triggerCharacter: "T", triggerKind: LSP.CompletionTriggerKind.Invoked); var results = await RunGetCompletionsAsync(testLspServer, completionParams).ConfigureAwait(false); Assert.Equal(1000, results.Items.Length); Assert.True(results.IsIncomplete); } [Fact] public async Task TestIncompleteCompletionListContainsPreselectedItemAsync() { var markup = @"using System; using System.Buffers; using System.Buffers.Binary; using System.Buffers.Text; using System.Collections; using System.Collections.Generic; using System.Collections.Immutable; using System.Collections.ObjectModel; using System.ComponentModel; using System.ComponentModel.Design; using System.Configuration; using System.Data; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Drawing; using System.Dynamic; using System.Globalization; using System.IO; using System.Linq; using System.Media; using System.Net; using System.Net.Http; using System.Net.Http.Json; using System.Text; using System.Threading; using System.Threading.Tasks; class A { class W { } void M() { W someW = new {|caret:|} } }"; using var testLspServer = CreateTestLspServer(markup, out var locations); var caretLocation = locations["caret"].Single(); var completionParams = CreateCompletionParams( caretLocation, invokeKind: LSP.VSCompletionInvokeKind.Typing, triggerCharacter: " ", triggerKind: LSP.CompletionTriggerKind.TriggerCharacter); var results = await RunGetCompletionsAsync(testLspServer, completionParams).ConfigureAwait(false); Assert.Equal(1000, results.Items.Length); Assert.True(results.IsIncomplete); var itemW = results.Items.Single(item => item.Label == "W"); Assert.True(itemW.Preselect); } [Fact] public async Task TestRequestForIncompleteListIsFilteredDownAsync() { var markup = @"using System; using System.Buffers; using System.Buffers.Binary; using System.Buffers.Text; using System.Collections; using System.Collections.Generic; using System.Collections.Immutable; using System.Collections.ObjectModel; using System.ComponentModel; using System.ComponentModel.Design; using System.Configuration; using System.Data; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Drawing; using System.Dynamic; using System.Globalization; using System.IO; using System.Linq; using System.Media; using System.Net; using System.Net.Http; using System.Net.Http.Json; using System.Text; using System.Threading; using System.Threading.Tasks; class A { void M() { T{|caret:|} } }"; using var testLspServer = CreateTestLspServer(markup, out var locations); var caretLocation = locations["caret"].Single(); await testLspServer.OpenDocumentAsync(caretLocation.Uri); var completionParams = CreateCompletionParams( caretLocation, invokeKind: LSP.VSCompletionInvokeKind.Typing, triggerCharacter: "T", triggerKind: LSP.CompletionTriggerKind.Invoked); var results = await RunGetCompletionsAsync(testLspServer, completionParams).ConfigureAwait(false); Assert.Equal(1000, results.Items.Length); Assert.True(results.IsIncomplete); Assert.Equal("T", results.Items.First().Label); await testLspServer.InsertTextAsync(caretLocation.Uri, (caretLocation.Range.End.Line, caretLocation.Range.End.Character, "a")); completionParams = CreateCompletionParams( locations["caret"].Single(), invokeKind: LSP.VSCompletionInvokeKind.Typing, triggerCharacter: "a", triggerKind: LSP.CompletionTriggerKind.TriggerForIncompleteCompletions); results = await RunGetCompletionsAsync(testLspServer, completionParams).ConfigureAwait(false); Assert.True(results.IsIncomplete); Assert.True(results.Items.Length < 1000); Assert.Contains("ta", results.Items.First().Label, StringComparison.OrdinalIgnoreCase); } [Fact] public async Task TestIncompleteCompletionListFiltersWithPatternMatchingAsync() { var markup = @"using System; using System.Buffers; using System.Buffers.Binary; using System.Buffers.Text; using System.Collections; using System.Collections.Generic; using System.Collections.Immutable; using System.Collections.ObjectModel; using System.ComponentModel; using System.ComponentModel.Design; using System.Configuration; using System.Data; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Drawing; using System.Dynamic; using System.Globalization; using System.IO; using System.Linq; using System.Media; using System.Net; using System.Net.Http; using System.Net.Http.Json; using System.Text; using System.Threading; using System.Threading.Tasks; class A { void M() { T{|caret:|} } }"; using var testLspServer = CreateTestLspServer(markup, out var locations); var caretLocation = locations["caret"].Single(); await testLspServer.OpenDocumentAsync(caretLocation.Uri); var completionParams = CreateCompletionParams( caretLocation, invokeKind: LSP.VSCompletionInvokeKind.Typing, triggerCharacter: "T", triggerKind: LSP.CompletionTriggerKind.Invoked); var results = await RunGetCompletionsAsync(testLspServer, completionParams).ConfigureAwait(false); Assert.Equal(1000, results.Items.Length); Assert.True(results.IsIncomplete); Assert.Equal("T", results.Items.First().Label); await testLspServer.InsertTextAsync(caretLocation.Uri, (caretLocation.Range.End.Line, caretLocation.Range.End.Character, "C")); completionParams = CreateCompletionParams( locations["caret"].Single(), invokeKind: LSP.VSCompletionInvokeKind.Typing, triggerCharacter: "C", triggerKind: LSP.CompletionTriggerKind.TriggerForIncompleteCompletions); results = await RunGetCompletionsAsync(testLspServer, completionParams).ConfigureAwait(false); Assert.True(results.IsIncomplete); Assert.True(results.Items.Length < 1000); Assert.Equal("TaiwanCalendar", results.Items.First().Label); } [Fact] public async Task TestIncompleteCompletionListWithDeletionAsync() { var markup = @"using System; using System.Buffers; using System.Buffers.Binary; using System.Buffers.Text; using System.Collections; using System.Collections.Generic; using System.Collections.Immutable; using System.Collections.ObjectModel; using System.ComponentModel; using System.ComponentModel.Design; using System.Configuration; using System.Data; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Drawing; using System.Dynamic; using System.Globalization; using System.IO; using System.Linq; using System.Media; using System.Net; using System.Net.Http; using System.Net.Http.Json; using System.Text; using System.Threading; using System.Threading.Tasks; class A { void M() { T{|caret:|} } }"; using var testLspServer = CreateTestLspServer(markup, out var locations); var caretLocation = locations["caret"].Single(); await testLspServer.OpenDocumentAsync(caretLocation.Uri); // Insert 'T' to make 'T' and trigger completion. var completionParams = CreateCompletionParams( caretLocation, invokeKind: LSP.VSCompletionInvokeKind.Typing, triggerCharacter: "T", triggerKind: LSP.CompletionTriggerKind.Invoked); var results = await RunGetCompletionsAsync(testLspServer, completionParams).ConfigureAwait(false); Assert.Equal(1000, results.Items.Length); Assert.True(results.IsIncomplete); Assert.Equal("T", results.Items.First().Label); // Insert 'ask' to make 'Task' and trigger completion. await testLspServer.InsertTextAsync(caretLocation.Uri, (caretLocation.Range.End.Line, caretLocation.Range.End.Character, "ask")); completionParams = CreateCompletionParams( locations["caret"].Single(), invokeKind: LSP.VSCompletionInvokeKind.Typing, triggerCharacter: "k", triggerKind: LSP.CompletionTriggerKind.TriggerForIncompleteCompletions); results = await RunGetCompletionsAsync(testLspServer, completionParams).ConfigureAwait(false); Assert.True(results.IsIncomplete); Assert.True(results.Items.Length < 1000); Assert.Equal("Task", results.Items.First().Label); // Delete 'ask' to make 'T' and trigger completion on deletion. await testLspServer.DeleteTextAsync(caretLocation.Uri, (caretLocation.Range.End.Line, caretLocation.Range.End.Character, caretLocation.Range.End.Line, caretLocation.Range.End.Character + 3)); completionParams = CreateCompletionParams( locations["caret"].Single(), invokeKind: LSP.VSCompletionInvokeKind.Deletion, triggerCharacter: "a", triggerKind: LSP.CompletionTriggerKind.TriggerForIncompleteCompletions); results = await RunGetCompletionsAsync(testLspServer, completionParams).ConfigureAwait(false); Assert.True(results.IsIncomplete); Assert.Equal(1000, results.Items.Length); Assert.True(results.IsIncomplete); Assert.Equal("T", results.Items.First().Label); // Insert 'i' to make 'Ti' and trigger completion. await testLspServer.InsertTextAsync(caretLocation.Uri, (caretLocation.Range.End.Line, caretLocation.Range.End.Character, "i")); completionParams = CreateCompletionParams( locations["caret"].Single(), invokeKind: LSP.VSCompletionInvokeKind.Typing, triggerCharacter: "i", triggerKind: LSP.CompletionTriggerKind.TriggerForIncompleteCompletions); results = await RunGetCompletionsAsync(testLspServer, completionParams).ConfigureAwait(false); Assert.True(results.IsIncomplete); Assert.True(results.Items.Length < 1000); Assert.Equal("Timeout", results.Items.First().Label); } [Fact] public async Task TestNewCompletionRequestDoesNotUseIncompleteListAsync() { var markup = @"using System; using System.Buffers; using System.Buffers.Binary; using System.Buffers.Text; using System.Collections; using System.Collections.Generic; using System.Collections.Immutable; using System.Collections.ObjectModel; using System.ComponentModel; using System.ComponentModel.Design; using System.Configuration; using System.Data; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Drawing; using System.Dynamic; using System.Globalization; using System.IO; using System.Linq; using System.Media; using System.Net; using System.Net.Http; using System.Net.Http.Json; using System.Text; using System.Threading; using System.Threading.Tasks; class A { void M() { T{|firstCaret:|} } void M2() { Console.W{|secondCaret:|} } }"; using var testLspServer = CreateTestLspServer(markup, out var locations); var firstCaret = locations["firstCaret"].Single(); await testLspServer.OpenDocumentAsync(firstCaret.Uri); // Make a completion request that returns an incomplete list. var completionParams = CreateCompletionParams( firstCaret, invokeKind: LSP.VSCompletionInvokeKind.Typing, triggerCharacter: "T", triggerKind: LSP.CompletionTriggerKind.Invoked); var results = await RunGetCompletionsAsync(testLspServer, completionParams).ConfigureAwait(false); Assert.Equal(1000, results.Items.Length); Assert.True(results.IsIncomplete); Assert.Equal("T", results.Items.First().Label); // Make a second completion request, but not for the original incomplete list. completionParams = CreateCompletionParams( locations["secondCaret"].Single(), invokeKind: LSP.VSCompletionInvokeKind.Typing, triggerCharacter: "W", triggerKind: LSP.CompletionTriggerKind.Invoked); results = await RunGetCompletionsAsync(testLspServer, completionParams).ConfigureAwait(false); Assert.False(results.IsIncomplete); Assert.True(results.Items.Length < 1000); Assert.Equal("WindowHeight", results.Items.First().Label); } [Fact] public async Task TestRequestForIncompleteListWhenMissingCachedListAsync() { var markup = @"using System; using System.Buffers; using System.Buffers.Binary; using System.Buffers.Text; using System.Collections; using System.Collections.Generic; using System.Collections.Immutable; using System.Collections.ObjectModel; using System.ComponentModel; using System.ComponentModel.Design; using System.Configuration; using System.Data; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Drawing; using System.Dynamic; using System.Globalization; using System.IO; using System.Linq; using System.Media; using System.Net; using System.Net.Http; using System.Net.Http.Json; using System.Text; using System.Threading; using System.Threading.Tasks; class A { void M() { Ta{|caret:|} } }"; using var testLspServer = CreateTestLspServer(markup, out var locations); var caretLocation = locations["caret"].Single(); var completionParams = CreateCompletionParams( locations["caret"].Single(), invokeKind: LSP.VSCompletionInvokeKind.Typing, triggerCharacter: "a", triggerKind: LSP.CompletionTriggerKind.TriggerForIncompleteCompletions); var results = await RunGetCompletionsAsync(testLspServer, completionParams).ConfigureAwait(false); Assert.True(results.IsIncomplete); Assert.True(results.Items.Length < 1000); Assert.Contains("ta", results.Items.First().Label, StringComparison.OrdinalIgnoreCase); } [Fact] public async Task TestRequestForIncompleteListUsesCorrectCachedListAsync() { var markup = @"using System; using System.Buffers; using System.Buffers.Binary; using System.Buffers.Text; using System.Collections; using System.Collections.Generic; using System.Collections.Immutable; using System.Collections.ObjectModel; using System.ComponentModel; using System.ComponentModel.Design; using System.Configuration; using System.Data; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Drawing; using System.Dynamic; using System.Globalization; using System.IO; using System.Linq; using System.Media; using System.Net; using System.Net.Http; using System.Net.Http.Json; using System.Text; using System.Threading; using System.Threading.Tasks; class A { void M1() { int Taaa = 1; T{|firstCaret:|} } void M2() { int Saaa = 1; {|secondCaret:|} } }"; using var testLspServer = CreateTestLspServer(markup, out var locations); var firstCaretLocation = locations["firstCaret"].Single(); await testLspServer.OpenDocumentAsync(firstCaretLocation.Uri); // Create request to on insertion of 'T' var completionParams = CreateCompletionParams( firstCaretLocation, invokeKind: LSP.VSCompletionInvokeKind.Typing, triggerCharacter: "T", triggerKind: LSP.CompletionTriggerKind.Invoked); var results = await RunGetCompletionsAsync(testLspServer, completionParams).ConfigureAwait(false); Assert.Equal(1000, results.Items.Length); Assert.True(results.IsIncomplete); Assert.Equal("T", results.Items.First().Label); Assert.Single(results.Items, item => item.Label == "Taaa"); // Insert 'S' at the second caret var secondCaretLocation = locations["secondCaret"].Single(); await testLspServer.InsertTextAsync(secondCaretLocation.Uri, (secondCaretLocation.Range.End.Line, secondCaretLocation.Range.End.Character, "S")); // Trigger completion on 'S' var triggerLocation = GetLocationPlusOne(secondCaretLocation); completionParams = CreateCompletionParams( triggerLocation, invokeKind: LSP.VSCompletionInvokeKind.Typing, triggerCharacter: "S", triggerKind: LSP.CompletionTriggerKind.Invoked); results = await RunGetCompletionsAsync(testLspServer, completionParams).ConfigureAwait(false); Assert.Equal(1000, results.Items.Length); Assert.True(results.IsIncomplete); Assert.Equal("Saaa", results.Items.First().Label); // Now type 'a' in M1 after 'T' await testLspServer.InsertTextAsync(firstCaretLocation.Uri, (firstCaretLocation.Range.End.Line, firstCaretLocation.Range.End.Character, "a")); // Trigger completion on 'a' (using incomplete as we previously returned incomplete completions from 'T'). triggerLocation = GetLocationPlusOne(firstCaretLocation); completionParams = CreateCompletionParams( triggerLocation, invokeKind: LSP.VSCompletionInvokeKind.Typing, triggerCharacter: "a", triggerKind: LSP.CompletionTriggerKind.TriggerForIncompleteCompletions); results = await RunGetCompletionsAsync(testLspServer, completionParams).ConfigureAwait(false); // Verify we get completions for 'Ta' and not from the 'S' location in M2 Assert.True(results.IsIncomplete); Assert.True(results.Items.Length < 1000); Assert.DoesNotContain(results.Items, item => item.Label == "Saaa"); Assert.Contains(results.Items, item => item.Label == "Taaa"); static LSP.Location GetLocationPlusOne(LSP.Location originalLocation) { var newPosition = new LSP.Position { Character = originalLocation.Range.Start.Character + 1, Line = originalLocation.Range.Start.Line }; return new LSP.Location { Uri = originalLocation.Uri, Range = new LSP.Range { Start = newPosition, End = newPosition } }; } } [Fact] public async Task TestCompletionRequestRespectsListSizeOptionAsync() { var markup = @"class A { void M() { {|caret:|} } }"; using var testLspServer = CreateTestLspServer(markup, out var locations); var completionParams = CreateCompletionParams( locations["caret"].Single(), invokeKind: LSP.VSCompletionInvokeKind.Explicit, triggerCharacter: "\0", triggerKind: LSP.CompletionTriggerKind.Invoked); var listMaxSize = 1; testLspServer.TestWorkspace.SetOptions(testLspServer.TestWorkspace.CurrentSolution.Options.WithChangedOption(LspOptions.MaxCompletionListSize, listMaxSize)); var results = await RunGetCompletionsAsync(testLspServer, completionParams).ConfigureAwait(false); Assert.True(results.IsIncomplete); Assert.Equal(listMaxSize, results.Items.Length); } private static Task<LSP.CompletionList> RunGetCompletionsAsync(TestLspServer testLspServer, LSP.CompletionParams completionParams) { var clientCapabilities = new LSP.VSClientCapabilities { SupportsVisualStudioExtensions = true }; return RunGetCompletionsAsync(testLspServer, completionParams, clientCapabilities); } private static async Task<LSP.CompletionList> RunGetCompletionsAsync( TestLspServer testLspServer, LSP.CompletionParams completionParams, LSP.VSClientCapabilities clientCapabilities) { return await testLspServer.ExecuteRequestAsync<LSP.CompletionParams, LSP.CompletionList>(LSP.Methods.TextDocumentCompletionName, completionParams, clientCapabilities, null, CancellationToken.None); } private static CompletionListCache GetCompletionListCache(TestLspServer testLspServer) { var dispatchAccessor = testLspServer.GetDispatcherAccessor(); var handler = (CompletionHandler)dispatchAccessor.GetHandler<LSP.CompletionParams, LSP.CompletionList>(LSP.Methods.TextDocumentCompletionName); Assert.NotNull(handler); return handler.GetTestAccessor().GetCache(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Completion; using Microsoft.CodeAnalysis.LanguageServer.Handler; using Microsoft.CodeAnalysis.LanguageServer.Handler.Completion; using Roslyn.Test.Utilities; using Xunit; using LSP = Microsoft.VisualStudio.LanguageServer.Protocol; namespace Microsoft.CodeAnalysis.LanguageServer.UnitTests.Completion { public class CompletionTests : AbstractLanguageServerProtocolTests { [Fact] public async Task TestGetCompletionsAsync_PromotesCommitCharactersToListAsync() { var clientCapabilities = new LSP.VSClientCapabilities { SupportsVisualStudioExtensions = true, TextDocument = new LSP.TextDocumentClientCapabilities() { Completion = new LSP.VSCompletionSetting() { CompletionList = new LSP.VSCompletionListSetting() { CommitCharacters = true, } } } }; var markup = @"class A { void M() { {|caret:|} } }"; using var testLspServer = CreateTestLspServer(markup, out var locations); var completionParams = CreateCompletionParams( locations["caret"].Single(), invokeKind: LSP.VSCompletionInvokeKind.Explicit, triggerCharacter: "\0", triggerKind: LSP.CompletionTriggerKind.Invoked); var document = testLspServer.GetCurrentSolution().Projects.First().Documents.First(); var expected = await CreateCompletionItemAsync(label: "A", kind: LSP.CompletionItemKind.Class, tags: new string[] { "Class", "Internal" }, request: completionParams, document: document, commitCharacters: CompletionRules.Default.DefaultCommitCharacters, insertText: "A").ConfigureAwait(false); var expectedCommitCharacters = expected.CommitCharacters; // Null out the commit characters since we're expecting the commit characters will be lifted onto the completion list. expected.CommitCharacters = null; var results = await RunGetCompletionsAsync(testLspServer, completionParams, clientCapabilities).ConfigureAwait(false); AssertJsonEquals(expected, results.Items.First()); var vsCompletionList = Assert.IsAssignableFrom<LSP.VSCompletionList>(results); Assert.Equal(expectedCommitCharacters, vsCompletionList.CommitCharacters.Value.First); } [Fact] public async Task TestGetCompletions_PromotesNothingWhenNoCommitCharactersAsync() { var clientCapabilities = new LSP.VSClientCapabilities { SupportsVisualStudioExtensions = true, TextDocument = new LSP.TextDocumentClientCapabilities() { Completion = new LSP.VSCompletionSetting() { CompletionList = new LSP.VSCompletionListSetting() { CommitCharacters = true, } } } }; var markup = @"namespace M {{|caret:|} }"; using var testLspServer = CreateTestLspServer(markup, out var locations); var completionParams = CreateCompletionParams( locations["caret"].Single(), invokeKind: LSP.VSCompletionInvokeKind.Explicit, triggerCharacter: "\0", triggerKind: LSP.CompletionTriggerKind.Invoked); var document = testLspServer.GetCurrentSolution().Projects.First().Documents.First(); var expected = await CreateCompletionItemAsync(label: "A", kind: LSP.CompletionItemKind.Class, tags: new string[] { "Class", "Internal" }, request: completionParams, document: document, commitCharacters: CompletionRules.Default.DefaultCommitCharacters, insertText: "A").ConfigureAwait(false); var expectedCommitCharacters = expected.CommitCharacters; // Null out the commit characters since we're expecting the commit characters will be lifted onto the completion list. expected.CommitCharacters = null; var results = await RunGetCompletionsAsync(testLspServer, completionParams, clientCapabilities).ConfigureAwait(false); Assert.All(results.Items, item => Assert.Null(item.CommitCharacters)); var vsCompletionList = Assert.IsAssignableFrom<LSP.VSCompletionList>(results); Assert.Equal(expectedCommitCharacters, vsCompletionList.CommitCharacters.Value.First); } [Fact] public async Task TestGetCompletionsAsync() { var markup = @"class A { void M() { {|caret:|} } }"; using var testLspServer = CreateTestLspServer(markup, out var locations); var completionParams = CreateCompletionParams( locations["caret"].Single(), invokeKind: LSP.VSCompletionInvokeKind.Explicit, triggerCharacter: "\0", triggerKind: LSP.CompletionTriggerKind.Invoked); var document = testLspServer.GetCurrentSolution().Projects.First().Documents.First(); var expected = await CreateCompletionItemAsync(label: "A", kind: LSP.CompletionItemKind.Class, tags: new string[] { "Class", "Internal" }, request: completionParams, document: document, commitCharacters: null, insertText: "A").ConfigureAwait(false); var results = await RunGetCompletionsAsync(testLspServer, completionParams).ConfigureAwait(false); AssertJsonEquals(expected, results.Items.First()); } [Fact] public async Task TestGetCompletionsTypingAsync() { var markup = @"class A { void M() { A{|caret:|} } }"; using var testLspServer = CreateTestLspServer(markup, out var locations); var completionParams = CreateCompletionParams( locations["caret"].Single(), invokeKind: LSP.VSCompletionInvokeKind.Typing, triggerCharacter: "A", triggerKind: LSP.CompletionTriggerKind.Invoked); var document = testLspServer.GetCurrentSolution().Projects.First().Documents.First(); var expected = await CreateCompletionItemAsync(label: "A", kind: LSP.CompletionItemKind.Class, tags: new string[] { "Class", "Internal" }, request: completionParams, document: document, commitCharacters: null, insertText: "A").ConfigureAwait(false); var results = await RunGetCompletionsAsync(testLspServer, completionParams).ConfigureAwait(false); AssertJsonEquals(expected, results.Items.First()); } [Fact] public async Task TestGetCompletionsDoesNotIncludeUnimportedTypesAsync() { var markup = @"class A { void M() { {|caret:|} } }"; using var testLspServer = CreateTestLspServer(markup, out var locations); var solution = testLspServer.TestWorkspace.CurrentSolution; // Make sure the unimported types option is on by default. testLspServer.TestWorkspace.SetOptions(testLspServer.TestWorkspace.CurrentSolution.Options .WithChangedOption(CompletionOptions.ShowItemsFromUnimportedNamespaces, LanguageNames.CSharp, true) .WithChangedOption(CompletionServiceOptions.IsExpandedCompletion, true)); var completionParams = CreateCompletionParams( locations["caret"].Single(), invokeKind: LSP.VSCompletionInvokeKind.Explicit, triggerCharacter: "\0", triggerKind: LSP.CompletionTriggerKind.Invoked); var results = await RunGetCompletionsAsync(testLspServer, completionParams); Assert.False(results.Items.Any(item => "Console" == item.Label)); } [Fact] public async Task TestGetCompletionsDoesNotIncludeSnippetsAsync() { var markup = @"class A { {|caret:|} }"; using var testLspServer = CreateTestLspServer(markup, out var locations); var solution = testLspServer.TestWorkspace.CurrentSolution; solution = solution.WithOptions(solution.Options .WithChangedOption(CompletionOptions.SnippetsBehavior, LanguageNames.CSharp, SnippetsRule.AlwaysInclude)); var completionParams = CreateCompletionParams( locations["caret"].Single(), invokeKind: LSP.VSCompletionInvokeKind.Explicit, triggerCharacter: "\0", triggerKind: LSP.CompletionTriggerKind.Invoked); var results = await RunGetCompletionsAsync(testLspServer, completionParams); Assert.False(results.Items.Any(item => "ctor" == item.Label)); } [Fact] public async Task TestGetCompletionsWithPreselectAsync() { var markup = @"class A { void M() { A classA = new {|caret:|} } }"; using var testLspServer = CreateTestLspServer(markup, out var locations); var completionParams = CreateCompletionParams( locations["caret"].Single(), invokeKind: LSP.VSCompletionInvokeKind.Explicit, triggerCharacter: "\0", LSP.CompletionTriggerKind.Invoked); var document = testLspServer.GetCurrentSolution().Projects.First().Documents.First(); var expected = await CreateCompletionItemAsync("A", LSP.CompletionItemKind.Class, new string[] { "Class", "Internal" }, completionParams, document, preselect: true, commitCharacters: ImmutableArray.Create(' ', '(', '[', '{', ';', '.'), insertText: "A").ConfigureAwait(false); var results = await RunGetCompletionsAsync(testLspServer, completionParams).ConfigureAwait(false); AssertJsonEquals(expected, results.Items.First()); } [Fact] public async Task TestGetCompletionsIsInSuggestionMode() { var markup = @" using System.Collections.Generic; using System.Linq; namespace M { class Item { void M() { var items = new List<Item>(); items.Count(i{|caret:|} } } }"; using var testLspServer = CreateTestLspServer(markup, out var locations); var completionParams = CreateCompletionParams( locations["caret"].Single(), invokeKind: LSP.VSCompletionInvokeKind.Typing, triggerCharacter: "i", triggerKind: LSP.CompletionTriggerKind.Invoked); var results = (LSP.VSCompletionList)await RunGetCompletionsAsync(testLspServer, completionParams).ConfigureAwait(false); Assert.True(results.Items.Any()); Assert.True(results.SuggestionMode); } [Fact] public async Task TestGetDateAndTimeCompletionsAsync() { var markup = @"using System; class A { void M() { DateTime.Now.ToString(""{|caret:|}); } }"; using var testLspServer = CreateTestLspServer(markup, out var locations); var completionParams = CreateCompletionParams( locations["caret"].Single(), invokeKind: LSP.VSCompletionInvokeKind.Typing, triggerCharacter: "\"", triggerKind: LSP.CompletionTriggerKind.TriggerCharacter); var document = testLspServer.GetCurrentSolution().Projects.First().Documents.First(); var expected = await CreateCompletionItemAsync( label: "d", kind: LSP.CompletionItemKind.Text, tags: new string[] { "Text" }, request: completionParams, document: document, insertText: "d", sortText: "0000").ConfigureAwait(false); var results = await RunGetCompletionsAsync(testLspServer, completionParams).ConfigureAwait(false); AssertJsonEquals(expected, results.Items.First()); } [Fact] [WorkItem(50964, "https://github.com/dotnet/roslyn/issues/50964")] public async Task TestGetRegexCompletionsAsync() { var markup = @"using System.Text.RegularExpressions; class A { void M() { new Regex(""{|caret:|}""); } }"; using var testLspServer = CreateTestLspServer(markup, out var locations); var completionParams = CreateCompletionParams( locations["caret"].Single(), invokeKind: LSP.VSCompletionInvokeKind.Explicit, triggerCharacter: "\0", triggerKind: LSP.CompletionTriggerKind.Invoked); var solution = testLspServer.GetCurrentSolution(); var document = solution.Projects.First().Documents.First(); // Set to use prototype completion behavior (i.e. feature flag). var options = solution.Workspace.Options.WithChangedOption(CompletionOptions.ForceRoslynLSPCompletionExperiment, LanguageNames.CSharp, true); Assert.True(solution.Workspace.TryApplyChanges(solution.WithOptions(options))); var textEdit = GenerateTextEdit(@"\\A", startLine: 5, startChar: 19, endLine: 5, endChar: 19); var expected = await CreateCompletionItemAsync( label: @"\A", kind: LSP.CompletionItemKind.Text, tags: new string[] { "Text" }, request: completionParams, document: document, textEdit: textEdit, sortText: "0000").ConfigureAwait(false); var results = await RunGetCompletionsAsync(testLspServer, completionParams).ConfigureAwait(false); AssertJsonEquals(expected, results.Items.First()); } [Fact] [WorkItem(50964, "https://github.com/dotnet/roslyn/issues/50964")] public async Task TestGetRegexLiteralCompletionsAsync() { var markup = @"using System.Text.RegularExpressions; class A { void M() { new Regex(@""\{|caret:|}""); } }"; using var testLspServer = CreateTestLspServer(markup, out var locations); var completionParams = CreateCompletionParams( locations["caret"].Single(), invokeKind: LSP.VSCompletionInvokeKind.Explicit, triggerCharacter: "\\", triggerKind: LSP.CompletionTriggerKind.TriggerCharacter); var solution = testLspServer.GetCurrentSolution(); var document = solution.Projects.First().Documents.First(); // Set to use prototype completion behavior (i.e. feature flag). var options = solution.Workspace.Options.WithChangedOption(CompletionOptions.ForceRoslynLSPCompletionExperiment, LanguageNames.CSharp, true); Assert.True(solution.Workspace.TryApplyChanges(solution.WithOptions(options))); var textEdit = GenerateTextEdit(@"\A", startLine: 5, startChar: 20, endLine: 5, endChar: 21); var expected = await CreateCompletionItemAsync( label: @"\A", kind: LSP.CompletionItemKind.Text, tags: new string[] { "Text" }, request: completionParams, document: document, textEdit: textEdit, sortText: "0000").ConfigureAwait(false); var results = await RunGetCompletionsAsync(testLspServer, completionParams).ConfigureAwait(false); AssertJsonEquals(expected, results.Items.First()); } [Fact] [WorkItem(50964, "https://github.com/dotnet/roslyn/issues/50964")] public async Task TestGetRegexCompletionsReplaceTextAsync() { var markup = @"using System.Text.RegularExpressions; class A { void M() { Regex r = new(""\\{|caret:|}""); } }"; using var testLspServer = CreateTestLspServer(markup, out var locations); var completionParams = CreateCompletionParams( locations["caret"].Single(), invokeKind: LSP.VSCompletionInvokeKind.Typing, triggerCharacter: "\\", triggerKind: LSP.CompletionTriggerKind.TriggerCharacter); var solution = testLspServer.GetCurrentSolution(); var document = solution.Projects.First().Documents.First(); // Set to use prototype completion behavior (i.e. feature flag). var options = solution.Workspace.Options.WithChangedOption(CompletionOptions.ForceRoslynLSPCompletionExperiment, LanguageNames.CSharp, true); Assert.True(solution.Workspace.TryApplyChanges(solution.WithOptions(options))); var textEdit = GenerateTextEdit(@"\\A", startLine: 5, startChar: 23, endLine: 5, endChar: 25); var expected = await CreateCompletionItemAsync( label: @"\A", kind: LSP.CompletionItemKind.Text, tags: new string[] { "Text" }, request: completionParams, document: document, textEdit: textEdit, sortText: "0000").ConfigureAwait(false); var results = await RunGetCompletionsAsync(testLspServer, completionParams).ConfigureAwait(false); AssertJsonEquals(expected, results.Items.First()); } [Fact] [WorkItem(46694, "https://github.com/dotnet/roslyn/issues/46694")] public async Task TestCompletionListCacheAsync() { var markup = @"class A { void M() { {|caret:|} } }"; using var testLspServer = CreateTestLspServer(markup, out var locations); var cache = GetCompletionListCache(testLspServer); Assert.NotNull(cache); var testAccessor = cache.GetTestAccessor(); // This test assumes that the maximum cache size is 3, and will have to modified if this number changes. Assert.True(CompletionListCache.TestAccessor.MaximumCacheSize == 3); var completionParams = CreateCompletionParams( locations["caret"].Single(), invokeKind: LSP.VSCompletionInvokeKind.Explicit, triggerCharacter: "\0", triggerKind: LSP.CompletionTriggerKind.Invoked); // 1 item in cache await RunGetCompletionsAsync(testLspServer, completionParams).ConfigureAwait(false); var completionList = cache.GetCachedCompletionList(0).CompletionList; Assert.NotNull(completionList); Assert.True(testAccessor.GetCacheContents().Count == 1); // 2 items in cache await RunGetCompletionsAsync(testLspServer, completionParams).ConfigureAwait(false); completionList = cache.GetCachedCompletionList(0).CompletionList; Assert.NotNull(completionList); completionList = cache.GetCachedCompletionList(1).CompletionList; Assert.NotNull(completionList); Assert.True(testAccessor.GetCacheContents().Count == 2); // 3 items in cache await RunGetCompletionsAsync(testLspServer, completionParams).ConfigureAwait(false); completionList = cache.GetCachedCompletionList(0).CompletionList; Assert.NotNull(completionList); completionList = cache.GetCachedCompletionList(1).CompletionList; Assert.NotNull(completionList); completionList = cache.GetCachedCompletionList(2).CompletionList; Assert.NotNull(completionList); Assert.True(testAccessor.GetCacheContents().Count == 3); // Maximum size of cache (3) should not be exceeded - oldest item should be ejected await RunGetCompletionsAsync(testLspServer, completionParams).ConfigureAwait(false); var cacheEntry = cache.GetCachedCompletionList(0); Assert.Null(cacheEntry); completionList = cache.GetCachedCompletionList(1).CompletionList; Assert.NotNull(completionList); completionList = cache.GetCachedCompletionList(2).CompletionList; Assert.NotNull(completionList); completionList = cache.GetCachedCompletionList(3).CompletionList; Assert.NotNull(completionList); Assert.True(testAccessor.GetCacheContents().Count == 3); } [Fact] public async Task TestGetCompletionsWithDeletionInvokeKindAsync() { var markup = @"class A { void M() { {|caret:|} } }"; using var testLspServer = CreateTestLspServer(markup, out var locations); var completionParams = CreateCompletionParams( locations["caret"].Single(), invokeKind: LSP.VSCompletionInvokeKind.Deletion, triggerCharacter: "M", triggerKind: LSP.CompletionTriggerKind.Invoked); var document = testLspServer.GetCurrentSolution().Projects.First().Documents.First(); var expected = await CreateCompletionItemAsync("A", LSP.CompletionItemKind.Class, new string[] { "Class", "Internal" }, completionParams, document, commitCharacters: CompletionRules.Default.DefaultCommitCharacters).ConfigureAwait(false); var results = await RunGetCompletionsAsync(testLspServer, completionParams).ConfigureAwait(false); // By default, completion doesn't trigger on deletion. Assert.Null(results); } [Fact] public async Task TestDoNotProvideOverrideTextEditsOrInsertTextAsync() { var markup = @"abstract class A { public abstract void M(); } class B : A { override {|caret:|} }"; using var testLspServer = CreateTestLspServer(markup, out var locations); var completionParams = CreateCompletionParams( locations["caret"].Single(), invokeKind: LSP.VSCompletionInvokeKind.Explicit, triggerCharacter: "\0", triggerKind: LSP.CompletionTriggerKind.Invoked); var document = testLspServer.GetCurrentSolution().Projects.First().Documents.First(); var results = await RunGetCompletionsAsync(testLspServer, completionParams).ConfigureAwait(false); Assert.Null(results.Items.First().TextEdit); Assert.Null(results.Items.First().InsertText); } [Fact] public async Task TestDoNotProvidePartialMethodTextEditsOrInsertTextAsync() { var markup = @"partial class C { partial void Method(); } partial class C { partial {|caret:|} }"; using var testLspServer = CreateTestLspServer(markup, out var locations); var completionParams = CreateCompletionParams( locations["caret"].Single(), invokeKind: LSP.VSCompletionInvokeKind.Explicit, triggerCharacter: "\0", triggerKind: LSP.CompletionTriggerKind.Invoked); var document = testLspServer.GetCurrentSolution().Projects.First().Documents.First(); var results = await RunGetCompletionsAsync(testLspServer, completionParams).ConfigureAwait(false); Assert.Null(results.Items.First().TextEdit); Assert.Null(results.Items.First().InsertText); } [Fact] public async Task TestAlwaysHasCommitCharactersWithoutVSCapabilityAsync() { var markup = @"using System; class A { void M() { {|caret:|} } }"; using var testLspServer = CreateTestLspServer(markup, out var locations); var completionParams = CreateCompletionParams( locations["caret"].Single(), invokeKind: LSP.VSCompletionInvokeKind.Explicit, triggerCharacter: "\0", triggerKind: LSP.CompletionTriggerKind.Invoked); var document = testLspServer.GetCurrentSolution().Projects.First().Documents.First(); var results = await RunGetCompletionsAsync(testLspServer, completionParams, new LSP.VSClientCapabilities()).ConfigureAwait(false); Assert.NotNull(results); Assert.NotEmpty(results.Items); Assert.All(results.Items, (item) => Assert.NotNull(item.CommitCharacters)); } [Fact] public async Task TestSoftSelectedItemsHaveNoCommitCharactersWithoutVSCapabilityAsync() { var markup = @"using System.Text.RegularExpressions; class A { void M() { new Regex(""[{|caret:|}"") } }"; using var testLspServer = CreateTestLspServer(markup, out var locations); var completionParams = CreateCompletionParams( locations["caret"].Single(), invokeKind: LSP.VSCompletionInvokeKind.Typing, triggerCharacter: "[", triggerKind: LSP.CompletionTriggerKind.TriggerCharacter); var document = testLspServer.GetCurrentSolution().Projects.First().Documents.First(); var results = await RunGetCompletionsAsync(testLspServer, completionParams, new LSP.VSClientCapabilities()).ConfigureAwait(false); Assert.NotNull(results); Assert.NotEmpty(results.Items); Assert.All(results.Items, (item) => Assert.True(item.CommitCharacters.Length == 0)); } [Fact] public async Task TestLargeCompletionListIsMarkedIncompleteAsync() { var markup = @"using System; using System.Buffers; using System.Buffers.Binary; using System.Buffers.Text; using System.Collections; using System.Collections.Generic; using System.Collections.Immutable; using System.Collections.ObjectModel; using System.ComponentModel; using System.ComponentModel.Design; using System.Configuration; using System.Data; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Drawing; using System.Dynamic; using System.Globalization; using System.IO; using System.Linq; using System.Media; using System.Net; using System.Net.Http; using System.Net.Http.Json; using System.Text; using System.Threading; using System.Threading.Tasks; class A { void M() { T{|caret:|} } }"; using var testLspServer = CreateTestLspServer(markup, out var locations); var completionParams = CreateCompletionParams( locations["caret"].Single(), invokeKind: LSP.VSCompletionInvokeKind.Typing, triggerCharacter: "T", triggerKind: LSP.CompletionTriggerKind.Invoked); var results = await RunGetCompletionsAsync(testLspServer, completionParams).ConfigureAwait(false); Assert.Equal(1000, results.Items.Length); Assert.True(results.IsIncomplete); } [Fact] public async Task TestIncompleteCompletionListContainsPreselectedItemAsync() { var markup = @"using System; using System.Buffers; using System.Buffers.Binary; using System.Buffers.Text; using System.Collections; using System.Collections.Generic; using System.Collections.Immutable; using System.Collections.ObjectModel; using System.ComponentModel; using System.ComponentModel.Design; using System.Configuration; using System.Data; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Drawing; using System.Dynamic; using System.Globalization; using System.IO; using System.Linq; using System.Media; using System.Net; using System.Net.Http; using System.Net.Http.Json; using System.Text; using System.Threading; using System.Threading.Tasks; class A { class W { } void M() { W someW = new {|caret:|} } }"; using var testLspServer = CreateTestLspServer(markup, out var locations); var caretLocation = locations["caret"].Single(); var completionParams = CreateCompletionParams( caretLocation, invokeKind: LSP.VSCompletionInvokeKind.Typing, triggerCharacter: " ", triggerKind: LSP.CompletionTriggerKind.TriggerCharacter); var results = await RunGetCompletionsAsync(testLspServer, completionParams).ConfigureAwait(false); Assert.Equal(1000, results.Items.Length); Assert.True(results.IsIncomplete); var itemW = results.Items.Single(item => item.Label == "W"); Assert.True(itemW.Preselect); } [Fact] public async Task TestRequestForIncompleteListIsFilteredDownAsync() { var markup = @"using System; using System.Buffers; using System.Buffers.Binary; using System.Buffers.Text; using System.Collections; using System.Collections.Generic; using System.Collections.Immutable; using System.Collections.ObjectModel; using System.ComponentModel; using System.ComponentModel.Design; using System.Configuration; using System.Data; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Drawing; using System.Dynamic; using System.Globalization; using System.IO; using System.Linq; using System.Media; using System.Net; using System.Net.Http; using System.Net.Http.Json; using System.Text; using System.Threading; using System.Threading.Tasks; class A { void M() { T{|caret:|} } }"; using var testLspServer = CreateTestLspServer(markup, out var locations); var caretLocation = locations["caret"].Single(); await testLspServer.OpenDocumentAsync(caretLocation.Uri); var completionParams = CreateCompletionParams( caretLocation, invokeKind: LSP.VSCompletionInvokeKind.Typing, triggerCharacter: "T", triggerKind: LSP.CompletionTriggerKind.Invoked); var results = await RunGetCompletionsAsync(testLspServer, completionParams).ConfigureAwait(false); Assert.Equal(1000, results.Items.Length); Assert.True(results.IsIncomplete); Assert.Equal("T", results.Items.First().Label); await testLspServer.InsertTextAsync(caretLocation.Uri, (caretLocation.Range.End.Line, caretLocation.Range.End.Character, "a")); completionParams = CreateCompletionParams( locations["caret"].Single(), invokeKind: LSP.VSCompletionInvokeKind.Typing, triggerCharacter: "a", triggerKind: LSP.CompletionTriggerKind.TriggerForIncompleteCompletions); results = await RunGetCompletionsAsync(testLspServer, completionParams).ConfigureAwait(false); Assert.True(results.IsIncomplete); Assert.True(results.Items.Length < 1000); Assert.Contains("ta", results.Items.First().Label, StringComparison.OrdinalIgnoreCase); } [Fact] public async Task TestIncompleteCompletionListFiltersWithPatternMatchingAsync() { var markup = @"using System; using System.Buffers; using System.Buffers.Binary; using System.Buffers.Text; using System.Collections; using System.Collections.Generic; using System.Collections.Immutable; using System.Collections.ObjectModel; using System.ComponentModel; using System.ComponentModel.Design; using System.Configuration; using System.Data; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Drawing; using System.Dynamic; using System.Globalization; using System.IO; using System.Linq; using System.Media; using System.Net; using System.Net.Http; using System.Net.Http.Json; using System.Text; using System.Threading; using System.Threading.Tasks; class A { void M() { T{|caret:|} } }"; using var testLspServer = CreateTestLspServer(markup, out var locations); var caretLocation = locations["caret"].Single(); await testLspServer.OpenDocumentAsync(caretLocation.Uri); var completionParams = CreateCompletionParams( caretLocation, invokeKind: LSP.VSCompletionInvokeKind.Typing, triggerCharacter: "T", triggerKind: LSP.CompletionTriggerKind.Invoked); var results = await RunGetCompletionsAsync(testLspServer, completionParams).ConfigureAwait(false); Assert.Equal(1000, results.Items.Length); Assert.True(results.IsIncomplete); Assert.Equal("T", results.Items.First().Label); await testLspServer.InsertTextAsync(caretLocation.Uri, (caretLocation.Range.End.Line, caretLocation.Range.End.Character, "C")); completionParams = CreateCompletionParams( locations["caret"].Single(), invokeKind: LSP.VSCompletionInvokeKind.Typing, triggerCharacter: "C", triggerKind: LSP.CompletionTriggerKind.TriggerForIncompleteCompletions); results = await RunGetCompletionsAsync(testLspServer, completionParams).ConfigureAwait(false); Assert.True(results.IsIncomplete); Assert.True(results.Items.Length < 1000); Assert.Equal("TaiwanCalendar", results.Items.First().Label); } [Fact] public async Task TestIncompleteCompletionListWithDeletionAsync() { var markup = @"using System; using System.Buffers; using System.Buffers.Binary; using System.Buffers.Text; using System.Collections; using System.Collections.Generic; using System.Collections.Immutable; using System.Collections.ObjectModel; using System.ComponentModel; using System.ComponentModel.Design; using System.Configuration; using System.Data; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Drawing; using System.Dynamic; using System.Globalization; using System.IO; using System.Linq; using System.Media; using System.Net; using System.Net.Http; using System.Net.Http.Json; using System.Text; using System.Threading; using System.Threading.Tasks; class A { void M() { T{|caret:|} } }"; using var testLspServer = CreateTestLspServer(markup, out var locations); var caretLocation = locations["caret"].Single(); await testLspServer.OpenDocumentAsync(caretLocation.Uri); // Insert 'T' to make 'T' and trigger completion. var completionParams = CreateCompletionParams( caretLocation, invokeKind: LSP.VSCompletionInvokeKind.Typing, triggerCharacter: "T", triggerKind: LSP.CompletionTriggerKind.Invoked); var results = await RunGetCompletionsAsync(testLspServer, completionParams).ConfigureAwait(false); Assert.Equal(1000, results.Items.Length); Assert.True(results.IsIncomplete); Assert.Equal("T", results.Items.First().Label); // Insert 'ask' to make 'Task' and trigger completion. await testLspServer.InsertTextAsync(caretLocation.Uri, (caretLocation.Range.End.Line, caretLocation.Range.End.Character, "ask")); completionParams = CreateCompletionParams( locations["caret"].Single(), invokeKind: LSP.VSCompletionInvokeKind.Typing, triggerCharacter: "k", triggerKind: LSP.CompletionTriggerKind.TriggerForIncompleteCompletions); results = await RunGetCompletionsAsync(testLspServer, completionParams).ConfigureAwait(false); Assert.True(results.IsIncomplete); Assert.True(results.Items.Length < 1000); Assert.Equal("Task", results.Items.First().Label); // Delete 'ask' to make 'T' and trigger completion on deletion. await testLspServer.DeleteTextAsync(caretLocation.Uri, (caretLocation.Range.End.Line, caretLocation.Range.End.Character, caretLocation.Range.End.Line, caretLocation.Range.End.Character + 3)); completionParams = CreateCompletionParams( locations["caret"].Single(), invokeKind: LSP.VSCompletionInvokeKind.Deletion, triggerCharacter: "a", triggerKind: LSP.CompletionTriggerKind.TriggerForIncompleteCompletions); results = await RunGetCompletionsAsync(testLspServer, completionParams).ConfigureAwait(false); Assert.True(results.IsIncomplete); Assert.Equal(1000, results.Items.Length); Assert.True(results.IsIncomplete); Assert.Equal("T", results.Items.First().Label); // Insert 'i' to make 'Ti' and trigger completion. await testLspServer.InsertTextAsync(caretLocation.Uri, (caretLocation.Range.End.Line, caretLocation.Range.End.Character, "i")); completionParams = CreateCompletionParams( locations["caret"].Single(), invokeKind: LSP.VSCompletionInvokeKind.Typing, triggerCharacter: "i", triggerKind: LSP.CompletionTriggerKind.TriggerForIncompleteCompletions); results = await RunGetCompletionsAsync(testLspServer, completionParams).ConfigureAwait(false); Assert.True(results.IsIncomplete); Assert.True(results.Items.Length < 1000); Assert.Equal("Timeout", results.Items.First().Label); } [Fact] public async Task TestNewCompletionRequestDoesNotUseIncompleteListAsync() { var markup = @"using System; using System.Buffers; using System.Buffers.Binary; using System.Buffers.Text; using System.Collections; using System.Collections.Generic; using System.Collections.Immutable; using System.Collections.ObjectModel; using System.ComponentModel; using System.ComponentModel.Design; using System.Configuration; using System.Data; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Drawing; using System.Dynamic; using System.Globalization; using System.IO; using System.Linq; using System.Media; using System.Net; using System.Net.Http; using System.Net.Http.Json; using System.Text; using System.Threading; using System.Threading.Tasks; class A { void M() { T{|firstCaret:|} } void M2() { Console.W{|secondCaret:|} } }"; using var testLspServer = CreateTestLspServer(markup, out var locations); var firstCaret = locations["firstCaret"].Single(); await testLspServer.OpenDocumentAsync(firstCaret.Uri); // Make a completion request that returns an incomplete list. var completionParams = CreateCompletionParams( firstCaret, invokeKind: LSP.VSCompletionInvokeKind.Typing, triggerCharacter: "T", triggerKind: LSP.CompletionTriggerKind.Invoked); var results = await RunGetCompletionsAsync(testLspServer, completionParams).ConfigureAwait(false); Assert.Equal(1000, results.Items.Length); Assert.True(results.IsIncomplete); Assert.Equal("T", results.Items.First().Label); // Make a second completion request, but not for the original incomplete list. completionParams = CreateCompletionParams( locations["secondCaret"].Single(), invokeKind: LSP.VSCompletionInvokeKind.Typing, triggerCharacter: "W", triggerKind: LSP.CompletionTriggerKind.Invoked); results = await RunGetCompletionsAsync(testLspServer, completionParams).ConfigureAwait(false); Assert.False(results.IsIncomplete); Assert.True(results.Items.Length < 1000); Assert.Equal("WindowHeight", results.Items.First().Label); } [Fact] public async Task TestRequestForIncompleteListWhenMissingCachedListAsync() { var markup = @"using System; using System.Buffers; using System.Buffers.Binary; using System.Buffers.Text; using System.Collections; using System.Collections.Generic; using System.Collections.Immutable; using System.Collections.ObjectModel; using System.ComponentModel; using System.ComponentModel.Design; using System.Configuration; using System.Data; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Drawing; using System.Dynamic; using System.Globalization; using System.IO; using System.Linq; using System.Media; using System.Net; using System.Net.Http; using System.Net.Http.Json; using System.Text; using System.Threading; using System.Threading.Tasks; class A { void M() { Ta{|caret:|} } }"; using var testLspServer = CreateTestLspServer(markup, out var locations); var caretLocation = locations["caret"].Single(); var completionParams = CreateCompletionParams( locations["caret"].Single(), invokeKind: LSP.VSCompletionInvokeKind.Typing, triggerCharacter: "a", triggerKind: LSP.CompletionTriggerKind.TriggerForIncompleteCompletions); var results = await RunGetCompletionsAsync(testLspServer, completionParams).ConfigureAwait(false); Assert.True(results.IsIncomplete); Assert.True(results.Items.Length < 1000); Assert.Contains("ta", results.Items.First().Label, StringComparison.OrdinalIgnoreCase); } [Fact] public async Task TestRequestForIncompleteListUsesCorrectCachedListAsync() { var markup = @"using System; using System.Buffers; using System.Buffers.Binary; using System.Buffers.Text; using System.Collections; using System.Collections.Generic; using System.Collections.Immutable; using System.Collections.ObjectModel; using System.ComponentModel; using System.ComponentModel.Design; using System.Configuration; using System.Data; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Drawing; using System.Dynamic; using System.Globalization; using System.IO; using System.Linq; using System.Media; using System.Net; using System.Net.Http; using System.Net.Http.Json; using System.Text; using System.Threading; using System.Threading.Tasks; class A { void M1() { int Taaa = 1; T{|firstCaret:|} } void M2() { int Saaa = 1; {|secondCaret:|} } }"; using var testLspServer = CreateTestLspServer(markup, out var locations); var firstCaretLocation = locations["firstCaret"].Single(); await testLspServer.OpenDocumentAsync(firstCaretLocation.Uri); // Create request to on insertion of 'T' var completionParams = CreateCompletionParams( firstCaretLocation, invokeKind: LSP.VSCompletionInvokeKind.Typing, triggerCharacter: "T", triggerKind: LSP.CompletionTriggerKind.Invoked); var results = await RunGetCompletionsAsync(testLspServer, completionParams).ConfigureAwait(false); Assert.Equal(1000, results.Items.Length); Assert.True(results.IsIncomplete); Assert.Equal("T", results.Items.First().Label); Assert.Single(results.Items, item => item.Label == "Taaa"); // Insert 'S' at the second caret var secondCaretLocation = locations["secondCaret"].Single(); await testLspServer.InsertTextAsync(secondCaretLocation.Uri, (secondCaretLocation.Range.End.Line, secondCaretLocation.Range.End.Character, "S")); // Trigger completion on 'S' var triggerLocation = GetLocationPlusOne(secondCaretLocation); completionParams = CreateCompletionParams( triggerLocation, invokeKind: LSP.VSCompletionInvokeKind.Typing, triggerCharacter: "S", triggerKind: LSP.CompletionTriggerKind.Invoked); results = await RunGetCompletionsAsync(testLspServer, completionParams).ConfigureAwait(false); Assert.Equal(1000, results.Items.Length); Assert.True(results.IsIncomplete); Assert.Equal("Saaa", results.Items.First().Label); // Now type 'a' in M1 after 'T' await testLspServer.InsertTextAsync(firstCaretLocation.Uri, (firstCaretLocation.Range.End.Line, firstCaretLocation.Range.End.Character, "a")); // Trigger completion on 'a' (using incomplete as we previously returned incomplete completions from 'T'). triggerLocation = GetLocationPlusOne(firstCaretLocation); completionParams = CreateCompletionParams( triggerLocation, invokeKind: LSP.VSCompletionInvokeKind.Typing, triggerCharacter: "a", triggerKind: LSP.CompletionTriggerKind.TriggerForIncompleteCompletions); results = await RunGetCompletionsAsync(testLspServer, completionParams).ConfigureAwait(false); // Verify we get completions for 'Ta' and not from the 'S' location in M2 Assert.True(results.IsIncomplete); Assert.True(results.Items.Length < 1000); Assert.DoesNotContain(results.Items, item => item.Label == "Saaa"); Assert.Contains(results.Items, item => item.Label == "Taaa"); static LSP.Location GetLocationPlusOne(LSP.Location originalLocation) { var newPosition = new LSP.Position { Character = originalLocation.Range.Start.Character + 1, Line = originalLocation.Range.Start.Line }; return new LSP.Location { Uri = originalLocation.Uri, Range = new LSP.Range { Start = newPosition, End = newPosition } }; } } [Fact] public async Task TestCompletionRequestRespectsListSizeOptionAsync() { var markup = @"class A { void M() { {|caret:|} } }"; using var testLspServer = CreateTestLspServer(markup, out var locations); var completionParams = CreateCompletionParams( locations["caret"].Single(), invokeKind: LSP.VSCompletionInvokeKind.Explicit, triggerCharacter: "\0", triggerKind: LSP.CompletionTriggerKind.Invoked); var listMaxSize = 1; testLspServer.TestWorkspace.SetOptions(testLspServer.TestWorkspace.CurrentSolution.Options.WithChangedOption(LspOptions.MaxCompletionListSize, listMaxSize)); var results = await RunGetCompletionsAsync(testLspServer, completionParams).ConfigureAwait(false); Assert.True(results.IsIncomplete); Assert.Equal(listMaxSize, results.Items.Length); } private static Task<LSP.CompletionList> RunGetCompletionsAsync(TestLspServer testLspServer, LSP.CompletionParams completionParams) { var clientCapabilities = new LSP.VSClientCapabilities { SupportsVisualStudioExtensions = true }; return RunGetCompletionsAsync(testLspServer, completionParams, clientCapabilities); } private static async Task<LSP.CompletionList> RunGetCompletionsAsync( TestLspServer testLspServer, LSP.CompletionParams completionParams, LSP.VSClientCapabilities clientCapabilities) { return await testLspServer.ExecuteRequestAsync<LSP.CompletionParams, LSP.CompletionList>(LSP.Methods.TextDocumentCompletionName, completionParams, clientCapabilities, null, CancellationToken.None); } private static CompletionListCache GetCompletionListCache(TestLspServer testLspServer) { var dispatchAccessor = testLspServer.GetDispatcherAccessor(); var handler = (CompletionHandler)dispatchAccessor.GetHandler<LSP.CompletionParams, LSP.CompletionList>(LSP.Methods.TextDocumentCompletionName); Assert.NotNull(handler); return handler.GetTestAccessor().GetCache(); } } }
1
dotnet/roslyn
55,262
Fix LSP completions when all items have default commit characters
Fixes an exception stack trace seen in https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1362284 Also fixes behavior of promotion of commit characters to the list to include default commit characters
dibarbet
2021-07-30T02:43:35Z
2021-07-30T21:21:47Z
2f7dffa534aceb92e9767568e88535c926588d12
65ee073bf6cea571a68193793420ecee60752711
Fix LSP completions when all items have default commit characters. Fixes an exception stack trace seen in https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1362284 Also fixes behavior of promotion of commit characters to the list to include default commit characters
./src/Features/CSharp/Portable/GenerateMember/GenerateParameterizedMember/CSharpGenerateParameterizedMemberService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeGeneration; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.GenerateMember.GenerateParameterizedMember; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Utilities; using Microsoft.CodeAnalysis.Utilities; namespace Microsoft.CodeAnalysis.CSharp.GenerateMember.GenerateMethod { internal abstract class CSharpGenerateParameterizedMemberService<TService> : AbstractGenerateParameterizedMemberService<TService, SimpleNameSyntax, ExpressionSyntax, InvocationExpressionSyntax> where TService : AbstractGenerateParameterizedMemberService<TService, SimpleNameSyntax, ExpressionSyntax, InvocationExpressionSyntax> { internal partial class InvocationExpressionInfo : AbstractInvocationInfo { private readonly InvocationExpressionSyntax _invocationExpression; public InvocationExpressionInfo(SemanticDocument document, State state) : base(document, state) { _invocationExpression = state.InvocationExpressionOpt; } protected override ImmutableArray<ParameterName> DetermineParameterNames(CancellationToken cancellationToken) { return Document.SemanticModel.GenerateParameterNames( _invocationExpression.ArgumentList, cancellationToken); } protected override RefKind DetermineRefKind(CancellationToken cancellationToken) => _invocationExpression.IsParentKind(SyntaxKind.RefExpression) ? RefKind.Ref : RefKind.None; protected override ITypeSymbol DetermineReturnTypeWorker(CancellationToken cancellationToken) { // Defer to the type inferrer to figure out what the return type of this new method // should be. var typeInference = Document.Document.GetLanguageService<ITypeInferenceService>(); var inferredType = typeInference.InferType( Document.SemanticModel, _invocationExpression, objectAsDefault: true, name: State.IdentifierToken.ValueText, cancellationToken: cancellationToken); return inferredType; } protected override ImmutableArray<ITypeParameterSymbol> GetCapturedTypeParameters(CancellationToken cancellationToken) { var result = new List<ITypeParameterSymbol>(); var semanticModel = Document.SemanticModel; foreach (var argument in _invocationExpression.ArgumentList.Arguments) { var type = argument.DetermineParameterType(semanticModel, cancellationToken); type.GetReferencedTypeParameters(result); } return result.ToImmutableArray(); } protected override ImmutableArray<ITypeParameterSymbol> GenerateTypeParameters(CancellationToken cancellationToken) { // Generate dummy type parameter names for a generic method. If the user is inside a // generic method, and calls a generic method with type arguments from the outer // method, then use those same names for the generated type parameters. // // TODO(cyrusn): If we do capture method type variables, then we should probably // capture their constraints as well. var genericName = (GenericNameSyntax)State.SimpleNameOpt; var semanticModel = Document.SemanticModel; if (genericName.TypeArgumentList.Arguments.Count == 1) { var typeParameter = GetUniqueTypeParameter( genericName.TypeArgumentList.Arguments.First(), s => !State.TypeToGenerateIn.GetAllTypeParameters().Any(t => t.Name == s), cancellationToken); return ImmutableArray.Create(typeParameter); } else { var list = ArrayBuilder<ITypeParameterSymbol>.GetInstance(); var usedIdentifiers = new HashSet<string> { "T" }; foreach (var type in genericName.TypeArgumentList.Arguments) { var typeParameter = GetUniqueTypeParameter( type, s => !usedIdentifiers.Contains(s) && !State.TypeToGenerateIn.GetAllTypeParameters().Any(t => t.Name == s), cancellationToken); usedIdentifiers.Add(typeParameter.Name); list.Add(typeParameter); } return list.ToImmutableAndFree(); } } private ITypeParameterSymbol GetUniqueTypeParameter( TypeSyntax type, Func<string, bool> isUnique, CancellationToken cancellationToken) { var methodTypeParameter = GetMethodTypeParameter(type, cancellationToken); return methodTypeParameter ?? CodeGenerationSymbolFactory.CreateTypeParameterSymbol(NameGenerator.GenerateUniqueName("T", isUnique)); } private ITypeParameterSymbol GetMethodTypeParameter(TypeSyntax type, CancellationToken cancellationToken) { if (type is IdentifierNameSyntax) { var info = Document.SemanticModel.GetTypeInfo(type, cancellationToken); if (info.Type is ITypeParameterSymbol typeParameter && typeParameter.TypeParameterKind == TypeParameterKind.Method) { return typeParameter; } } return null; } protected override ImmutableArray<RefKind> DetermineParameterModifiers(CancellationToken cancellationToken) { return _invocationExpression.ArgumentList.Arguments.Select( a => a.RefOrOutKeyword.Kind() == SyntaxKind.RefKeyword ? RefKind.Ref : a.RefOrOutKeyword.Kind() == SyntaxKind.OutKeyword ? RefKind.Out : RefKind.None).ToImmutableArray(); } protected override ImmutableArray<ITypeSymbol> DetermineParameterTypes(CancellationToken cancellationToken) => _invocationExpression.ArgumentList.Arguments.Select(a => DetermineParameterType(a, cancellationToken)).ToImmutableArray(); private ITypeSymbol DetermineParameterType( ArgumentSyntax argument, CancellationToken cancellationToken) { return argument.DetermineParameterType(Document.SemanticModel, cancellationToken); } protected override ImmutableArray<bool> DetermineParameterOptionality(CancellationToken cancellationToken) => _invocationExpression.ArgumentList.Arguments.Select(a => false).ToImmutableArray(); protected override bool IsIdentifierName() => State.SimpleNameOpt.Kind() == SyntaxKind.IdentifierName; protected override bool IsImplicitReferenceConversion(Compilation compilation, ITypeSymbol sourceType, ITypeSymbol targetType) { var conversion = compilation.ClassifyConversion(sourceType, targetType); return conversion.IsImplicit && conversion.IsReference; } protected override ImmutableArray<ITypeSymbol> DetermineTypeArguments(CancellationToken cancellationToken) { var result = ArrayBuilder<ITypeSymbol>.GetInstance(); if (State.SimpleNameOpt is GenericNameSyntax) { foreach (var typeArgument in ((GenericNameSyntax)State.SimpleNameOpt).TypeArgumentList.Arguments) { var typeInfo = Document.SemanticModel.GetTypeInfo(typeArgument, cancellationToken); result.Add(typeInfo.Type); } } return result.ToImmutableAndFree(); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeGeneration; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.GenerateMember.GenerateParameterizedMember; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Utilities; using Microsoft.CodeAnalysis.Utilities; namespace Microsoft.CodeAnalysis.CSharp.GenerateMember.GenerateMethod { internal abstract class CSharpGenerateParameterizedMemberService<TService> : AbstractGenerateParameterizedMemberService<TService, SimpleNameSyntax, ExpressionSyntax, InvocationExpressionSyntax> where TService : AbstractGenerateParameterizedMemberService<TService, SimpleNameSyntax, ExpressionSyntax, InvocationExpressionSyntax> { internal partial class InvocationExpressionInfo : AbstractInvocationInfo { private readonly InvocationExpressionSyntax _invocationExpression; public InvocationExpressionInfo(SemanticDocument document, State state) : base(document, state) { _invocationExpression = state.InvocationExpressionOpt; } protected override ImmutableArray<ParameterName> DetermineParameterNames(CancellationToken cancellationToken) { return Document.SemanticModel.GenerateParameterNames( _invocationExpression.ArgumentList, cancellationToken); } protected override RefKind DetermineRefKind(CancellationToken cancellationToken) => _invocationExpression.IsParentKind(SyntaxKind.RefExpression) ? RefKind.Ref : RefKind.None; protected override ITypeSymbol DetermineReturnTypeWorker(CancellationToken cancellationToken) { // Defer to the type inferrer to figure out what the return type of this new method // should be. var typeInference = Document.Document.GetLanguageService<ITypeInferenceService>(); var inferredType = typeInference.InferType( Document.SemanticModel, _invocationExpression, objectAsDefault: true, name: State.IdentifierToken.ValueText, cancellationToken: cancellationToken); return inferredType; } protected override ImmutableArray<ITypeParameterSymbol> GetCapturedTypeParameters(CancellationToken cancellationToken) { var result = new List<ITypeParameterSymbol>(); var semanticModel = Document.SemanticModel; foreach (var argument in _invocationExpression.ArgumentList.Arguments) { var type = argument.DetermineParameterType(semanticModel, cancellationToken); type.GetReferencedTypeParameters(result); } return result.ToImmutableArray(); } protected override ImmutableArray<ITypeParameterSymbol> GenerateTypeParameters(CancellationToken cancellationToken) { // Generate dummy type parameter names for a generic method. If the user is inside a // generic method, and calls a generic method with type arguments from the outer // method, then use those same names for the generated type parameters. // // TODO(cyrusn): If we do capture method type variables, then we should probably // capture their constraints as well. var genericName = (GenericNameSyntax)State.SimpleNameOpt; var semanticModel = Document.SemanticModel; if (genericName.TypeArgumentList.Arguments.Count == 1) { var typeParameter = GetUniqueTypeParameter( genericName.TypeArgumentList.Arguments.First(), s => !State.TypeToGenerateIn.GetAllTypeParameters().Any(t => t.Name == s), cancellationToken); return ImmutableArray.Create(typeParameter); } else { var list = ArrayBuilder<ITypeParameterSymbol>.GetInstance(); var usedIdentifiers = new HashSet<string> { "T" }; foreach (var type in genericName.TypeArgumentList.Arguments) { var typeParameter = GetUniqueTypeParameter( type, s => !usedIdentifiers.Contains(s) && !State.TypeToGenerateIn.GetAllTypeParameters().Any(t => t.Name == s), cancellationToken); usedIdentifiers.Add(typeParameter.Name); list.Add(typeParameter); } return list.ToImmutableAndFree(); } } private ITypeParameterSymbol GetUniqueTypeParameter( TypeSyntax type, Func<string, bool> isUnique, CancellationToken cancellationToken) { var methodTypeParameter = GetMethodTypeParameter(type, cancellationToken); return methodTypeParameter ?? CodeGenerationSymbolFactory.CreateTypeParameterSymbol(NameGenerator.GenerateUniqueName("T", isUnique)); } private ITypeParameterSymbol GetMethodTypeParameter(TypeSyntax type, CancellationToken cancellationToken) { if (type is IdentifierNameSyntax) { var info = Document.SemanticModel.GetTypeInfo(type, cancellationToken); if (info.Type is ITypeParameterSymbol typeParameter && typeParameter.TypeParameterKind == TypeParameterKind.Method) { return typeParameter; } } return null; } protected override ImmutableArray<RefKind> DetermineParameterModifiers(CancellationToken cancellationToken) { return _invocationExpression.ArgumentList.Arguments.Select( a => a.RefOrOutKeyword.Kind() == SyntaxKind.RefKeyword ? RefKind.Ref : a.RefOrOutKeyword.Kind() == SyntaxKind.OutKeyword ? RefKind.Out : RefKind.None).ToImmutableArray(); } protected override ImmutableArray<ITypeSymbol> DetermineParameterTypes(CancellationToken cancellationToken) => _invocationExpression.ArgumentList.Arguments.Select(a => DetermineParameterType(a, cancellationToken)).ToImmutableArray(); private ITypeSymbol DetermineParameterType( ArgumentSyntax argument, CancellationToken cancellationToken) { return argument.DetermineParameterType(Document.SemanticModel, cancellationToken); } protected override ImmutableArray<bool> DetermineParameterOptionality(CancellationToken cancellationToken) => _invocationExpression.ArgumentList.Arguments.Select(a => false).ToImmutableArray(); protected override bool IsIdentifierName() => State.SimpleNameOpt.Kind() == SyntaxKind.IdentifierName; protected override bool IsImplicitReferenceConversion(Compilation compilation, ITypeSymbol sourceType, ITypeSymbol targetType) { var conversion = compilation.ClassifyConversion(sourceType, targetType); return conversion.IsImplicit && conversion.IsReference; } protected override ImmutableArray<ITypeSymbol> DetermineTypeArguments(CancellationToken cancellationToken) { var result = ArrayBuilder<ITypeSymbol>.GetInstance(); if (State.SimpleNameOpt is GenericNameSyntax) { foreach (var typeArgument in ((GenericNameSyntax)State.SimpleNameOpt).TypeArgumentList.Arguments) { var typeInfo = Document.SemanticModel.GetTypeInfo(typeArgument, cancellationToken); result.Add(typeInfo.Type); } } return result.ToImmutableAndFree(); } } } }
-1
dotnet/roslyn
55,262
Fix LSP completions when all items have default commit characters
Fixes an exception stack trace seen in https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1362284 Also fixes behavior of promotion of commit characters to the list to include default commit characters
dibarbet
2021-07-30T02:43:35Z
2021-07-30T21:21:47Z
2f7dffa534aceb92e9767568e88535c926588d12
65ee073bf6cea571a68193793420ecee60752711
Fix LSP completions when all items have default commit characters. Fixes an exception stack trace seen in https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1362284 Also fixes behavior of promotion of commit characters to the list to include default commit characters
./src/VisualStudio/Xaml/Impl/Implementation/LanguageServer/Handler/Completion/CompletionResolveData.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using Microsoft.VisualStudio.LanguageServer.Protocol; namespace Microsoft.VisualStudio.LanguageServices.Xaml.LanguageServer.Handler { internal class CompletionResolveData { public Guid ProjectGuid { get; set; } public Guid DocumentGuid { get; set; } public Position Position { get; set; } public string DisplayText { get; set; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using Microsoft.VisualStudio.LanguageServer.Protocol; namespace Microsoft.VisualStudio.LanguageServices.Xaml.LanguageServer.Handler { internal class CompletionResolveData { public Guid ProjectGuid { get; set; } public Guid DocumentGuid { get; set; } public Position Position { get; set; } public string DisplayText { get; set; } } }
-1
dotnet/roslyn
55,262
Fix LSP completions when all items have default commit characters
Fixes an exception stack trace seen in https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1362284 Also fixes behavior of promotion of commit characters to the list to include default commit characters
dibarbet
2021-07-30T02:43:35Z
2021-07-30T21:21:47Z
2f7dffa534aceb92e9767568e88535c926588d12
65ee073bf6cea571a68193793420ecee60752711
Fix LSP completions when all items have default commit characters. Fixes an exception stack trace seen in https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1362284 Also fixes behavior of promotion of commit characters to the list to include default commit characters
./src/Features/Core/Portable/ExtractMethod/Extensions.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.ExtractMethod { internal static class Extensions { public static bool Succeeded(this OperationStatus status) => status.Flag.Succeeded(); public static bool FailedWithNoBestEffortSuggestion(this OperationStatus status) => status.Flag.Failed() && !status.Flag.HasBestEffort(); public static bool Failed(this OperationStatus status) => status.Flag.Failed(); public static bool Succeeded(this OperationStatusFlag flag) => (flag & OperationStatusFlag.Succeeded) != 0; public static bool Failed(this OperationStatusFlag flag) => !flag.Succeeded(); public static bool HasBestEffort(this OperationStatusFlag flag) => (flag & OperationStatusFlag.BestEffort) != 0; public static bool HasSuggestion(this OperationStatusFlag flag) => (flag & OperationStatusFlag.Suggestion) != 0; public static bool HasMask(this OperationStatusFlag flag, OperationStatusFlag mask) => (flag & mask) != 0x0; public static OperationStatusFlag RemoveFlag(this OperationStatusFlag baseFlag, OperationStatusFlag flagToRemove) => baseFlag & ~flagToRemove; public static ITypeSymbol? GetLambdaOrAnonymousMethodReturnType(this SemanticModel binding, SyntaxNode node) { var info = binding.GetSymbolInfo(node); if (info.Symbol == null) { return null; } var methodSymbol = info.Symbol as IMethodSymbol; if (methodSymbol?.MethodKind != MethodKind.AnonymousFunction) { return null; } return methodSymbol.ReturnType; } public static Task<SemanticDocument> WithSyntaxRootAsync(this SemanticDocument semanticDocument, SyntaxNode root, CancellationToken cancellationToken) => SemanticDocument.CreateAsync(semanticDocument.Document.WithSyntaxRoot(root), cancellationToken); /// <summary> /// get tokens with given annotation in current document /// </summary> public static SyntaxToken GetTokenWithAnnotation(this SemanticDocument document, SyntaxAnnotation annotation) => document.Root.GetAnnotatedNodesAndTokens(annotation).Single().AsToken(); /// <summary> /// resolve the given symbol against compilation this snapshot has /// </summary> public static T ResolveType<T>(this SemanticModel semanticModel, T symbol) where T : class, ITypeSymbol { // Can be cleaned up when https://github.com/dotnet/roslyn/issues/38061 is resolved var typeSymbol = (T?)symbol.GetSymbolKey().Resolve(semanticModel.Compilation).GetAnySymbol(); Contract.ThrowIfNull(typeSymbol); return (T)typeSymbol.WithNullableAnnotation(symbol.NullableAnnotation); } /// <summary> /// check whether node contains error for itself but not from its child node /// </summary> public static bool HasDiagnostics(this SyntaxNode node) { var set = new HashSet<Diagnostic>(node.GetDiagnostics()); foreach (var child in node.ChildNodes()) { set.ExceptWith(child.GetDiagnostics()); } return set.Count > 0; } public static bool FromScript(this SyntaxNode node) { if (node.SyntaxTree == null) { return false; } return node.SyntaxTree.Options.Kind != SourceCodeKind.Regular; } } }
// Licensed to the .NET Foundation under one or more agreements. // 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 System.Threading; using System.Threading.Tasks; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.ExtractMethod { internal static class Extensions { public static bool Succeeded(this OperationStatus status) => status.Flag.Succeeded(); public static bool FailedWithNoBestEffortSuggestion(this OperationStatus status) => status.Flag.Failed() && !status.Flag.HasBestEffort(); public static bool Failed(this OperationStatus status) => status.Flag.Failed(); public static bool Succeeded(this OperationStatusFlag flag) => (flag & OperationStatusFlag.Succeeded) != 0; public static bool Failed(this OperationStatusFlag flag) => !flag.Succeeded(); public static bool HasBestEffort(this OperationStatusFlag flag) => (flag & OperationStatusFlag.BestEffort) != 0; public static bool HasSuggestion(this OperationStatusFlag flag) => (flag & OperationStatusFlag.Suggestion) != 0; public static bool HasMask(this OperationStatusFlag flag, OperationStatusFlag mask) => (flag & mask) != 0x0; public static OperationStatusFlag RemoveFlag(this OperationStatusFlag baseFlag, OperationStatusFlag flagToRemove) => baseFlag & ~flagToRemove; public static ITypeSymbol? GetLambdaOrAnonymousMethodReturnType(this SemanticModel binding, SyntaxNode node) { var info = binding.GetSymbolInfo(node); if (info.Symbol == null) { return null; } var methodSymbol = info.Symbol as IMethodSymbol; if (methodSymbol?.MethodKind != MethodKind.AnonymousFunction) { return null; } return methodSymbol.ReturnType; } public static Task<SemanticDocument> WithSyntaxRootAsync(this SemanticDocument semanticDocument, SyntaxNode root, CancellationToken cancellationToken) => SemanticDocument.CreateAsync(semanticDocument.Document.WithSyntaxRoot(root), cancellationToken); /// <summary> /// get tokens with given annotation in current document /// </summary> public static SyntaxToken GetTokenWithAnnotation(this SemanticDocument document, SyntaxAnnotation annotation) => document.Root.GetAnnotatedNodesAndTokens(annotation).Single().AsToken(); /// <summary> /// resolve the given symbol against compilation this snapshot has /// </summary> public static T ResolveType<T>(this SemanticModel semanticModel, T symbol) where T : class, ITypeSymbol { // Can be cleaned up when https://github.com/dotnet/roslyn/issues/38061 is resolved var typeSymbol = (T?)symbol.GetSymbolKey().Resolve(semanticModel.Compilation).GetAnySymbol(); Contract.ThrowIfNull(typeSymbol); return (T)typeSymbol.WithNullableAnnotation(symbol.NullableAnnotation); } /// <summary> /// check whether node contains error for itself but not from its child node /// </summary> public static bool HasDiagnostics(this SyntaxNode node) { var set = new HashSet<Diagnostic>(node.GetDiagnostics()); foreach (var child in node.ChildNodes()) { set.ExceptWith(child.GetDiagnostics()); } return set.Count > 0; } public static bool FromScript(this SyntaxNode node) { if (node.SyntaxTree == null) { return false; } return node.SyntaxTree.Options.Kind != SourceCodeKind.Regular; } } }
-1
dotnet/roslyn
55,262
Fix LSP completions when all items have default commit characters
Fixes an exception stack trace seen in https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1362284 Also fixes behavior of promotion of commit characters to the list to include default commit characters
dibarbet
2021-07-30T02:43:35Z
2021-07-30T21:21:47Z
2f7dffa534aceb92e9767568e88535c926588d12
65ee073bf6cea571a68193793420ecee60752711
Fix LSP completions when all items have default commit characters. Fixes an exception stack trace seen in https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1362284 Also fixes behavior of promotion of commit characters to the list to include default commit characters
./src/Workspaces/Core/Portable/CodeGeneration/Symbols/CodeGenerationTypeParameterSymbol.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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; namespace Microsoft.CodeAnalysis.CodeGeneration { internal class CodeGenerationTypeParameterSymbol : CodeGenerationTypeSymbol, ITypeParameterSymbol { public VarianceKind Variance { get; } public ImmutableArray<ITypeSymbol> ConstraintTypes { get; internal set; } public bool HasConstructorConstraint { get; } public bool HasReferenceTypeConstraint { get; } public bool HasValueTypeConstraint { get; } public bool HasUnmanagedTypeConstraint { get; } public bool HasNotNullConstraint { get; } public int Ordinal { get; } public CodeGenerationTypeParameterSymbol( INamedTypeSymbol containingType, ImmutableArray<AttributeData> attributes, VarianceKind varianceKind, string name, NullableAnnotation nullableAnnotation, ImmutableArray<ITypeSymbol> constraintTypes, bool hasConstructorConstraint, bool hasReferenceConstraint, bool hasValueConstraint, bool hasUnmanagedConstraint, bool hasNotNullConstraint, int ordinal) : base(containingType?.ContainingAssembly, containingType, attributes, Accessibility.NotApplicable, default, name, SpecialType.None, nullableAnnotation) { this.Variance = varianceKind; this.ConstraintTypes = constraintTypes; this.Ordinal = ordinal; this.HasConstructorConstraint = hasConstructorConstraint; this.HasReferenceTypeConstraint = hasReferenceConstraint; this.HasValueTypeConstraint = hasValueConstraint; this.HasUnmanagedTypeConstraint = hasUnmanagedConstraint; this.HasNotNullConstraint = hasNotNullConstraint; } protected override CodeGenerationTypeSymbol CloneWithNullableAnnotation(NullableAnnotation nullableAnnotation) { return new CodeGenerationTypeParameterSymbol( this.ContainingType, this.GetAttributes(), this.Variance, this.Name, nullableAnnotation, this.ConstraintTypes, this.HasConstructorConstraint, this.HasReferenceTypeConstraint, this.HasValueTypeConstraint, this.HasUnmanagedTypeConstraint, this.HasNotNullConstraint, this.Ordinal); } public new ITypeParameterSymbol OriginalDefinition => this; public ITypeParameterSymbol ReducedFrom => null; public override SymbolKind Kind => SymbolKind.TypeParameter; public override void Accept(SymbolVisitor visitor) => visitor.VisitTypeParameter(this); public override TResult Accept<TResult>(SymbolVisitor<TResult> visitor) => visitor.VisitTypeParameter(this); public override TypeKind TypeKind => TypeKind.TypeParameter; public TypeParameterKind TypeParameterKind { get { return this.DeclaringMethod != null ? TypeParameterKind.Method : TypeParameterKind.Type; } } public IMethodSymbol DeclaringMethod { get { return this.ContainingSymbol as IMethodSymbol; } } public INamedTypeSymbol DeclaringType { get { return this.ContainingSymbol as INamedTypeSymbol; } } public NullableAnnotation ReferenceTypeConstraintNullableAnnotation => throw new System.NotImplementedException(); public ImmutableArray<NullableAnnotation> ConstraintNullableAnnotations => ConstraintTypes.SelectAsArray(t => t.NullableAnnotation); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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; namespace Microsoft.CodeAnalysis.CodeGeneration { internal class CodeGenerationTypeParameterSymbol : CodeGenerationTypeSymbol, ITypeParameterSymbol { public VarianceKind Variance { get; } public ImmutableArray<ITypeSymbol> ConstraintTypes { get; internal set; } public bool HasConstructorConstraint { get; } public bool HasReferenceTypeConstraint { get; } public bool HasValueTypeConstraint { get; } public bool HasUnmanagedTypeConstraint { get; } public bool HasNotNullConstraint { get; } public int Ordinal { get; } public CodeGenerationTypeParameterSymbol( INamedTypeSymbol containingType, ImmutableArray<AttributeData> attributes, VarianceKind varianceKind, string name, NullableAnnotation nullableAnnotation, ImmutableArray<ITypeSymbol> constraintTypes, bool hasConstructorConstraint, bool hasReferenceConstraint, bool hasValueConstraint, bool hasUnmanagedConstraint, bool hasNotNullConstraint, int ordinal) : base(containingType?.ContainingAssembly, containingType, attributes, Accessibility.NotApplicable, default, name, SpecialType.None, nullableAnnotation) { this.Variance = varianceKind; this.ConstraintTypes = constraintTypes; this.Ordinal = ordinal; this.HasConstructorConstraint = hasConstructorConstraint; this.HasReferenceTypeConstraint = hasReferenceConstraint; this.HasValueTypeConstraint = hasValueConstraint; this.HasUnmanagedTypeConstraint = hasUnmanagedConstraint; this.HasNotNullConstraint = hasNotNullConstraint; } protected override CodeGenerationTypeSymbol CloneWithNullableAnnotation(NullableAnnotation nullableAnnotation) { return new CodeGenerationTypeParameterSymbol( this.ContainingType, this.GetAttributes(), this.Variance, this.Name, nullableAnnotation, this.ConstraintTypes, this.HasConstructorConstraint, this.HasReferenceTypeConstraint, this.HasValueTypeConstraint, this.HasUnmanagedTypeConstraint, this.HasNotNullConstraint, this.Ordinal); } public new ITypeParameterSymbol OriginalDefinition => this; public ITypeParameterSymbol ReducedFrom => null; public override SymbolKind Kind => SymbolKind.TypeParameter; public override void Accept(SymbolVisitor visitor) => visitor.VisitTypeParameter(this); public override TResult Accept<TResult>(SymbolVisitor<TResult> visitor) => visitor.VisitTypeParameter(this); public override TypeKind TypeKind => TypeKind.TypeParameter; public TypeParameterKind TypeParameterKind { get { return this.DeclaringMethod != null ? TypeParameterKind.Method : TypeParameterKind.Type; } } public IMethodSymbol DeclaringMethod { get { return this.ContainingSymbol as IMethodSymbol; } } public INamedTypeSymbol DeclaringType { get { return this.ContainingSymbol as INamedTypeSymbol; } } public NullableAnnotation ReferenceTypeConstraintNullableAnnotation => throw new System.NotImplementedException(); public ImmutableArray<NullableAnnotation> ConstraintNullableAnnotations => ConstraintTypes.SelectAsArray(t => t.NullableAnnotation); } }
-1
dotnet/roslyn
55,262
Fix LSP completions when all items have default commit characters
Fixes an exception stack trace seen in https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1362284 Also fixes behavior of promotion of commit characters to the list to include default commit characters
dibarbet
2021-07-30T02:43:35Z
2021-07-30T21:21:47Z
2f7dffa534aceb92e9767568e88535c926588d12
65ee073bf6cea571a68193793420ecee60752711
Fix LSP completions when all items have default commit characters. Fixes an exception stack trace seen in https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1362284 Also fixes behavior of promotion of commit characters to the list to include default commit characters
./src/Features/CSharp/Portable/CodeFixes/RemoveInKeyword/RemoveInKeywordCodeFixProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Linq; 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.Editing; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.CSharp.CodeFixes.RemoveInKeyword { [ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.RemoveIn), Shared] internal class RemoveInKeywordCodeFixProvider : CodeFixProvider { private const string CS1615 = nameof(CS1615); // Argument 1 may not be passed with the 'in' keyword [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] public RemoveInKeywordCodeFixProvider() { } public override FixAllProvider GetFixAllProvider() => WellKnownFixAllProviders.BatchFixer; public override ImmutableArray<string> FixableDiagnosticIds => ImmutableArray.Create(CS1615); public override async Task RegisterCodeFixesAsync(CodeFixContext context) { var root = await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false); var diagnostic = context.Diagnostics.First(); var diagnosticSpan = diagnostic.Location.SourceSpan; var token = root.FindToken(diagnosticSpan.Start); var argumentSyntax = token.GetAncestor<ArgumentSyntax>(); if (argumentSyntax == null || argumentSyntax.GetRefKind() != RefKind.In) return; context.RegisterCodeFix( new MyCodeAction(ct => FixAsync(context.Document, argumentSyntax, ct)), context.Diagnostics); } private static async Task<Document> FixAsync( Document document, ArgumentSyntax argumentSyntax, CancellationToken cancellationToken) { var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var generator = document.GetRequiredLanguageService<SyntaxGenerator>(); return document.WithSyntaxRoot(root.ReplaceNode( argumentSyntax, generator.Argument(generator.SyntaxFacts.GetExpressionOfArgument(argumentSyntax)))); } private class MyCodeAction : CustomCodeActions.DocumentChangeAction { public MyCodeAction(Func<CancellationToken, Task<Document>> createChangedDocument) : base(CSharpFeaturesResources.Remove_in_keyword, createChangedDocument, CSharpFeaturesResources.Remove_in_keyword) { } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Linq; 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.Editing; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.CSharp.CodeFixes.RemoveInKeyword { [ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.RemoveIn), Shared] internal class RemoveInKeywordCodeFixProvider : CodeFixProvider { private const string CS1615 = nameof(CS1615); // Argument 1 may not be passed with the 'in' keyword [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] public RemoveInKeywordCodeFixProvider() { } public override FixAllProvider GetFixAllProvider() => WellKnownFixAllProviders.BatchFixer; public override ImmutableArray<string> FixableDiagnosticIds => ImmutableArray.Create(CS1615); public override async Task RegisterCodeFixesAsync(CodeFixContext context) { var root = await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false); var diagnostic = context.Diagnostics.First(); var diagnosticSpan = diagnostic.Location.SourceSpan; var token = root.FindToken(diagnosticSpan.Start); var argumentSyntax = token.GetAncestor<ArgumentSyntax>(); if (argumentSyntax == null || argumentSyntax.GetRefKind() != RefKind.In) return; context.RegisterCodeFix( new MyCodeAction(ct => FixAsync(context.Document, argumentSyntax, ct)), context.Diagnostics); } private static async Task<Document> FixAsync( Document document, ArgumentSyntax argumentSyntax, CancellationToken cancellationToken) { var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var generator = document.GetRequiredLanguageService<SyntaxGenerator>(); return document.WithSyntaxRoot(root.ReplaceNode( argumentSyntax, generator.Argument(generator.SyntaxFacts.GetExpressionOfArgument(argumentSyntax)))); } private class MyCodeAction : CustomCodeActions.DocumentChangeAction { public MyCodeAction(Func<CancellationToken, Task<Document>> createChangedDocument) : base(CSharpFeaturesResources.Remove_in_keyword, createChangedDocument, CSharpFeaturesResources.Remove_in_keyword) { } } } }
-1
dotnet/roslyn
55,262
Fix LSP completions when all items have default commit characters
Fixes an exception stack trace seen in https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1362284 Also fixes behavior of promotion of commit characters to the list to include default commit characters
dibarbet
2021-07-30T02:43:35Z
2021-07-30T21:21:47Z
2f7dffa534aceb92e9767568e88535c926588d12
65ee073bf6cea571a68193793420ecee60752711
Fix LSP completions when all items have default commit characters. Fixes an exception stack trace seen in https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1362284 Also fixes behavior of promotion of commit characters to the list to include default commit characters
./src/Compilers/CSharp/Test/Semantic/Semantics/ArglistTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Xunit; // "__arglist" is an undocumented keyword of the C# language. // // There are three places where __arglist may legally appear in C#. It may appear: // // 1) as the final "parameter" of a method declaration: // // static void M(int x, int y, __arglist) {} // // 2) As an expression in a method whose declaration includes an __arglist parameter: // // static void M(int x, int y, __arglist) { var ai = new ArgIterator(__arglist); } // // 3) As the "receiver" of a "call" syntax in the last position of a call to an __arglist method: // // C.M(1, 2, __arglist(3, 4, 5)); // // THE FIRST FORM // --------------- // // In its first form it may not appear: // // * In a generic method // * In a generic type // * In an iterator method declaration // * In a delegate declaration // * In a user-defined operator or conversion declaration // // UNDONE: We should ensure that __arglist methods may not be async. // // In metadata, such a method is referred to as a "varargs" method and is identified // by the calling convention of the method. // // THE SECOND FORM // --------------- // // The second form is a legal expression (almost) anywhere inside a method that includes // an __arglist parameter. It is an expression of type System.RuntimeArgumentHandle and // classified as a value. It is usually passed to the ctor of the ArgIterator type. // // Speaking of which, we should talk about some special types. // // RuntimeArgumentHandle, ArgIterator and TypedReference are "restricted" types: // // * A restricted type may not be converted to object. // * It is illegal to declare a field or property of a restricted type. // * A restricted type may not be used as a generic type argument. // * A method or delegate may not return a restricted type. // * Since a field may not be of a restricted type, a restricted type may not be used // in an anonymous method, lambda or query expression if it would have to be hoisted // to a field. // // The native compiler does not consistently enforce these rules. For example, // it allows: // // delegate void D(RuntimeArgumentHandle r); // static int M(__arglist) // { // D f = null; // f = x=>f(__arglist); // } // // Sure enough, C# 5 generates a display class with method: // // static int Anonymous(RuntimeArgumentHandle x) { return this.f(__arglist); } // // Which doesn't make any sense; the anonymous method is not an __arglist method. // // This should simply be illegal; Roslyn disallows __arglist used in the second // form inside any lambda or anonymous method. (Even if the lambda in question is // from a query transformation.) // // THE THIRD FORM // -------------- // // The third form may only appear as the last argument of a call to a varargs method. // // UNDONE: The third form may not appear in a method call inside an expression tree lambda. // // // "__reftype" is also an undocumented keyword of C#. It is treated as an operator which // takes as its sole operand an expression convertible to System.TypedReference. The result is // the System.Type associated with the type of the typed reference. // // "__makeref" is also an undocumented keyword of C#. It is treated as an operator which takes // as its sole operand an expression classified as a variable. The result is a TypedReference // to the variable. It is analogous to the "&" address-of operator. // // "__refvalue" is also an undocumented keyword of C#. It is badly named, as it has the semantics // of *dereference to produce a variable*. It is the opposite of the __makeref operator and is // analogous to the "*" dereference operator. The operator takes a TypedReference and a // type, and produces a variable of that type. // // namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class ArglistTests : CompilingTestBase { [Fact] public void ExpressionTreeTest() { var text = @" using System; using System.Linq.Expressions; public struct C { static void Main() { Expression<Func<bool>> ex1 = ()=>M(__makeref(S)); // CS7053 Expression<Func<Type>> ex2 = ()=>__reftype(default(TypedReference)); Expression<Func<int>> ex3 = ()=>__refvalue(default(TypedReference), int); Expression<Func<bool>> ex4 = ()=>N(__arglist()); } static int S = 678; public static bool M(TypedReference tr) { return true; } public static bool N(__arglist) { return true;} }"; var comp = CreateCompilationWithMscorlib40AndSystemCore(text); comp.VerifyDiagnostics( // (8,44): error CS8640: Expression tree cannot contain value of ref struct or restricted type 'TypedReference'. // Expression<Func<bool>> ex1 = ()=>M(__makeref(S)); // CS7053 Diagnostic(ErrorCode.ERR_ExpressionTreeCantContainRefStruct, "__makeref(S)").WithArguments("TypedReference").WithLocation(8, 44), // (8,44): error CS7053: An expression tree may not contain '__makeref' // Expression<Func<bool>> ex1 = ()=>M(__makeref(S)); // CS7053 Diagnostic(ErrorCode.ERR_FeatureNotValidInExpressionTree, "__makeref(S)").WithArguments("__makeref").WithLocation(8, 44), // (9,42): error CS7053: An expression tree may not contain '__reftype' // Expression<Func<Type>> ex2 = ()=>__reftype(default(TypedReference)); Diagnostic(ErrorCode.ERR_FeatureNotValidInExpressionTree, "__reftype(default(TypedReference))").WithArguments("__reftype").WithLocation(9, 42), // (9,52): error CS8640: Expression tree cannot contain value of ref struct or restricted type 'TypedReference'. // Expression<Func<Type>> ex2 = ()=>__reftype(default(TypedReference)); Diagnostic(ErrorCode.ERR_ExpressionTreeCantContainRefStruct, "default(TypedReference)").WithArguments("TypedReference").WithLocation(9, 52), // (10,41): error CS7053: An expression tree may not contain '__refvalue' // Expression<Func<int>> ex3 = ()=>__refvalue(default(TypedReference), int); Diagnostic(ErrorCode.ERR_FeatureNotValidInExpressionTree, "__refvalue(default(TypedReference), int)").WithArguments("__refvalue").WithLocation(10, 41), // (10,52): error CS8640: Expression tree cannot contain value of ref struct or restricted type 'TypedReference'. // Expression<Func<int>> ex3 = ()=>__refvalue(default(TypedReference), int); Diagnostic(ErrorCode.ERR_ExpressionTreeCantContainRefStruct, "default(TypedReference)").WithArguments("TypedReference").WithLocation(10, 52), // (11,44): error CS1952: An expression tree lambda may not contain a method with variable arguments // Expression<Func<bool>> ex4 = ()=>N(__arglist()); Diagnostic(ErrorCode.ERR_VarArgsInExpressionTree, "__arglist()").WithLocation(11, 44) ); } [ClrOnlyFact(ClrOnlyReason.Ilasm)] public void MakeRefTest01() { var text = @" using System; public struct C { static void Main() { int i = 1; Console.WriteLine(M(__makeref(i))); } static Type M(TypedReference tr) { return __reftype(tr); } }"; string expectedIL = @"{ // Code size 20 (0x14) .maxstack 1 .locals init (int V_0) //i IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldloca.s V_0 IL_0004: mkrefany ""int"" IL_0009: call ""System.Type C.M(System.TypedReference)"" IL_000e: call ""void System.Console.WriteLine(object)"" IL_0013: ret }"; var verifier = CompileAndVerify(source: text, expectedOutput: "System.Int32"); verifier.VerifyIL("C.Main", expectedIL); } [Fact] public void MakeRefTest02() { // A makeref is logically the same as passing a variable to a method that takes a ref/out parameter, // so we produce the same error messages. This differs from the native compiler, which either fails // to produce errors at all, or produces the error messages for a bad assignment. We should not produce // errors for bad assignments; first of all, making a ref does not do an assignment, and second, the // user might assume that it is the assignment to the local that is bad. var text = @" using System; public struct C { static void Main() { TypedReference tr1 = default(TypedReference); TypedReference tr2 = __makeref(tr1); // CS1601 TypedReference tr3 = __makeref(123); // CS1510 TypedReference tr4 = __makeref(P); // CS0206 TypedReference tr5 = __makeref(R); // CS0199 } static int P { get; set; } static readonly int R = 345; }"; // UNDONE: Test what happens when __makereffing a volatile field, readonly field, etc. var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (8,30): error CS1601: Cannot make reference to variable of type 'TypedReference' // TypedReference tr2 = __makeref(tr1); // CS1601 Diagnostic(ErrorCode.ERR_MethodArgCantBeRefAny, "__makeref(tr1)").WithArguments("System.TypedReference").WithLocation(8, 30), // (9,40): error CS1510: A ref or out value must be an assignable variable // TypedReference tr3 = __makeref(123); // CS1510 Diagnostic(ErrorCode.ERR_RefLvalueExpected, "123").WithLocation(9, 40), // (10,40): error CS0206: A property or indexer may not be passed as an out or ref parameter // TypedReference tr4 = __makeref(P); // CS0206 Diagnostic(ErrorCode.ERR_RefProperty, "P").WithArguments("C.P").WithLocation(10, 40), // (11,40): error CS0199: A static readonly field cannot be used as a ref or out value (except in a static constructor) // TypedReference tr5 = __makeref(R); // CS0199 Diagnostic(ErrorCode.ERR_RefReadonlyStatic, "R").WithLocation(11, 40) ); } [Fact] [WorkItem(23369, "https://github.com/dotnet/roslyn/issues/23369")] public void ArglistWithVoidMethod() { var text = @" public class C { void M() { M2(__arglist(1, M())); } void M2(__arglist) { } }"; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (6,25): error CS8361: __arglist cannot have an argument of void type // M2(__arglist(1, M())); Diagnostic(ErrorCode.ERR_CantUseVoidInArglist, "M()").WithLocation(6, 25) ); } [Fact] public void RefValueUnsafeToReturn() { var text = @" using System; class C { private static ref int Test() { int aa = 42; var tr = __makeref(aa); ref var r = ref Test2(ref __refvalue(tr, int)); return ref r; } private static ref int Test2(ref int r) { return ref r; } private static ref int Test3(TypedReference tr) { return ref __refvalue(tr, int); } }"; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (13,20): error CS8157: Cannot return 'r' by reference because it was initialized to a value that cannot be returned by reference // return ref r; Diagnostic(ErrorCode.ERR_RefReturnNonreturnableLocal, "r").WithArguments("r").WithLocation(13, 20), // (23,20): error CS8156: An expression cannot be used in this context because it may not be returned by reference // return ref __refvalue(tr, int); Diagnostic(ErrorCode.ERR_RefReturnLvalueExpected, "__refvalue(tr, int)").WithLocation(23, 20) ); } [Fact] public void MakeRefTest03_Dynamic_Bind() { var text = @" using System; public struct C { static void Main() { dynamic i = 1; Console.WriteLine(M(__makeref(i))); } static Type M(TypedReference tr) { return __reftype(tr); } }"; CreateCompilation(text).VerifyDiagnostics(); } [ClrOnlyFact(ClrOnlyReason.Ilasm)] public void RefTypeTest01() { var text = @" using System; using System.Reflection; public struct C { public string f; static void Main() { Type ctype = typeof(C); FieldInfo[] ffield = new FieldInfo[] {ctype.GetFields()[0] }; TypedReference tr = TypedReference.MakeTypedReference(new C(), ffield); Type type = M(tr); Console.WriteLine(type.ToString()); } static Type M(TypedReference tr) { return __reftype(tr); } }"; string expectedIL = @"{ // Code size 9 (0x9) .maxstack 1 IL_0000: ldarg.0 IL_0001: refanytype IL_0003: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0008: ret }"; var verifier = CompileAndVerify(source: text, expectedOutput: "System.String"); verifier.VerifyIL("C.M", expectedIL); } [Fact] public void RefTypeTest02() { var text = @" public struct C { static void Main() { System.Type t = __reftype(null); } }"; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (6,25): error CS0037: Cannot convert null to 'System.TypedReference' because it is a non-nullable value type // System.Type t = __reftype(null); Diagnostic(ErrorCode.ERR_ValueCantBeNull, "__reftype(null)").WithArguments("System.TypedReference") ); } [ConditionalFact(typeof(DesktopOnly), Reason = ConditionalSkipReason.RestrictedTypesNeedDesktop)] public void ArglistTest01() { var text = @" using System; public class C { static void Main() { } static void M(__arglist) { new ArgIterator(__arglist); } }"; string expectedIL = @"{ // Code size 9 (0x9) .maxstack 1 IL_0000: arglist IL_0002: newobj ""System.ArgIterator..ctor(System.RuntimeArgumentHandle)"" IL_0007: pop IL_0008: ret }"; var verifier = CompileAndVerify(source: text, expectedOutput: ""); verifier.VerifyIL("C.M(__arglist)", expectedIL); } [ConditionalFact(typeof(DesktopOnly), Reason = ConditionalSkipReason.RestrictedTypesNeedDesktop)] public void ArglistTest02() { var text = @" using System; public class C { static void Main() { M(1, __arglist(2, 3, true)); } static void M(int x, __arglist) { Console.Write(x); DumpArgs(new ArgIterator(__arglist)); new B(4); new D(6); } static void DumpArgs(ArgIterator args) { while(args.GetRemainingCount() > 0) { TypedReference tr = args.GetNextArg(); object arg = TypedReference.ToObject(tr); Console.Write(arg); } } static void M(uint x, __arglist) { } class B { public B(__arglist) { DumpArgs(new ArgIterator(__arglist)); } public B(int x) : this(__arglist(x, 5)) {} } class D : B { public D(int x) : base(__arglist(x, 7)) {} } }"; // Note that this IL is not quite right; here we are displaying the call as "void C.M(int, __arglist)". // The actual IL for this program should show the method ref as "void C.M(int, ..., int, int, bool)", // because that is the information that is actually encoded in the method ref. If we want to display // that then we'll need to add special code to the symbol display visitor that knows how to emit // the desired format. string expectedIL = @"{ // Code size 10 (0xa) .maxstack 4 IL_0000: ldc.i4.1 IL_0001: ldc.i4.2 IL_0002: ldc.i4.3 IL_0003: ldc.i4.1 IL_0004: call ""void C.M(int, __arglist) with __arglist( int, int, bool)"" IL_0009: ret } "; string expectedOutput = @"123True4567"; var verifier = CompileAndVerify(source: text, expectedOutput: expectedOutput); verifier.VerifyIL("C.Main", expectedIL); } [ConditionalFact(typeof(DesktopOnly), Reason = ConditionalSkipReason.RestrictedTypesNeedDesktop)] public void ArglistTest03() { // The native parser produces "type expected" when __arglist is preceded by an illegal // modifier. The Roslyn compiler produces the more informative "__arglist not valid" error. var text = @" static class C { static void M(int x, __arglist) {} static void N(params __arglist) {} static void O(ref __arglist) {} static void P(out __arglist) {} static void Q(this __arglist) {} static void Main() { M(1); M(2, 3); M(4, 5, 6); M(1, __arglist()); // no error M(1, __arglist(__arglist())); var x = __arglist(123); } static object R() { return __arglist(456); } static void S(int x) { S(__arglist(1)); } [MyAttribute(__arglist(2))] static void T() { object obj1 = new System.TypedReference(); object obj2 = (object)new System.ArgIterator(); // The native compiler produces: //'TypedReference' may not be used as a type argument // which is not a very descriptive error! There is no type argument here; // the fact that anonymous types are actually generic is an implementation detail. // Roslyn produces the far more sensible error: // cannot assign TypedReference to anonymous type property object obj3 = new { X = new System.TypedReference() }; } } public class MyAttribute : System.Attribute { public MyAttribute(__arglist) { } } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (5,26): error CS1669: __arglist is not valid in this context // static void N(params __arglist) {} Diagnostic(ErrorCode.ERR_IllegalVarArgs, "__arglist").WithLocation(5, 26), // (6,23): error CS1669: __arglist is not valid in this context // static void O(ref __arglist) {} Diagnostic(ErrorCode.ERR_IllegalVarArgs, "__arglist").WithLocation(6, 23), // (7,23): error CS1669: __arglist is not valid in this context // static void P(out __arglist) {} Diagnostic(ErrorCode.ERR_IllegalVarArgs, "__arglist").WithLocation(7, 23), // (8,24): error CS1669: __arglist is not valid in this context // static void Q(this __arglist) {} Diagnostic(ErrorCode.ERR_IllegalVarArgs, "__arglist").WithLocation(8, 24), // (11,9): error CS7036: There is no argument given that corresponds to the required formal parameter '__arglist' of 'C.M(int, __arglist)' // M(1); Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "M").WithArguments("__arglist", "C.M(int, __arglist)").WithLocation(11, 9), // (12,14): error CS1503: Argument 2: cannot convert from 'int' to '__arglist' // M(2, 3); Diagnostic(ErrorCode.ERR_BadArgType, "3").WithArguments("2", "int", "__arglist").WithLocation(12, 14), // (13,9): error CS1501: No overload for method 'M' takes 3 arguments // M(4, 5, 6); Diagnostic(ErrorCode.ERR_BadArgCount, "M").WithArguments("M", "3").WithLocation(13, 9), // (15,24): error CS0226: An __arglist expression may only appear inside of a call or new expression // M(1, __arglist(__arglist())); Diagnostic(ErrorCode.ERR_IllegalArglist, "__arglist()").WithLocation(15, 24), // (16,17): error CS0226: An __arglist expression may only appear inside of a call or new expression // var x = __arglist(123); Diagnostic(ErrorCode.ERR_IllegalArglist, "__arglist(123)").WithLocation(16, 17), // (20,16): error CS0226: An __arglist expression may only appear inside of a call or new expression // return __arglist(456); Diagnostic(ErrorCode.ERR_IllegalArglist, "__arglist(456)").WithLocation(20, 16), // (24,11): error CS1503: Argument 1: cannot convert from '__arglist' to 'int' // S(__arglist(1)); Diagnostic(ErrorCode.ERR_BadArgType, "__arglist(1)").WithArguments("1", "__arglist", "int").WithLocation(24, 11), // (27,18): error CS0226: An __arglist expression may only appear inside of a call or new expression // [MyAttribute(__arglist(2))] Diagnostic(ErrorCode.ERR_IllegalArglist, "__arglist(2)").WithLocation(27, 18), // (30,23): error CS0029: Cannot implicitly convert type 'System.TypedReference' to 'object' // object obj1 = new System.TypedReference(); Diagnostic(ErrorCode.ERR_NoImplicitConv, "new System.TypedReference()").WithArguments("System.TypedReference", "object").WithLocation(30, 23), // (31,23): error CS0030: Cannot convert type 'System.ArgIterator' to 'object' // object obj2 = (object)new System.ArgIterator(); Diagnostic(ErrorCode.ERR_NoExplicitConv, "(object)new System.ArgIterator()").WithArguments("System.ArgIterator", "object").WithLocation(31, 23), // (38,29): error CS0828: Cannot assign System.TypedReference to anonymous type property // object obj3 = new { X = new System.TypedReference() }; Diagnostic(ErrorCode.ERR_AnonymousTypePropertyAssignedBadValue, "X = new System.TypedReference()").WithArguments("System.TypedReference").WithLocation(38, 29)); } [Fact] public void ArglistTest04() { var text = @" using System; class error { static void Main() { Action a = delegate (__arglist) { }; } } "; CreateCompilation(text).VerifyDiagnostics( // (7,24): error CS1669: __arglist is not valid in this context // Action a = delegate (__arglist) { }; Diagnostic(ErrorCode.ERR_IllegalVarArgs, "__arglist")); } [ClrOnlyFact(ClrOnlyReason.Ilasm)] public void RefValueTest01() { var text = @" using System; public struct C { static void Main() { int i = 1; TypedReference tr = __makeref(i); Console.Write(i); Get(tr); Console.Write(i); Set(tr, 2); Console.Write(i); Ref(tr, 3); Console.Write(i); } static int Get(TypedReference tr) { return __refvalue(tr, int); } static void Set(TypedReference tr, int i) { __refvalue(tr, int) = i; } static void Ref(TypedReference tr, int i) { // The native compiler generates bad code for this; Roslyn gets it right. M(ref __refvalue(tr, int), i); } static void M(ref int x, int y) { x = y; } }"; string expectedGetIL = @"{ // Code size 8 (0x8) .maxstack 1 IL_0000: ldarg.0 IL_0001: refanyval ""int"" IL_0006: ldind.i4 IL_0007: ret }"; string expectedSetIL = @"{ // Code size 9 (0x9) .maxstack 2 IL_0000: ldarg.0 IL_0001: refanyval ""int"" IL_0006: ldarg.1 IL_0007: stind.i4 IL_0008: ret }"; string expectedRefIL = @"{ // Code size 13 (0xd) .maxstack 2 IL_0000: ldarg.0 IL_0001: refanyval ""int"" IL_0006: ldarg.1 IL_0007: call ""void C.M(ref int, int)"" IL_000c: ret }"; var verifier = CompileAndVerify(source: text, expectedOutput: "1123"); verifier.VerifyIL("C.Get", expectedGetIL); verifier.VerifyIL("C.Set", expectedSetIL); verifier.VerifyIL("C.Ref", expectedRefIL); } [ClrOnlyFact(ClrOnlyReason.Ilasm)] public void RefValueTest01a() { var text = @" using System; class Program { struct S1<T> { public T x; public void Assign(T i) { x = i; } } static void Main(string[] args) { int x = 0; var _ref = __makeref(x); __refvalue(_ref, int) = 42; System.Console.WriteLine(x); S1<int> s = new S1<int>(); _ref = __makeref(s); __refvalue(_ref, S1<int>).Assign(333); System.Console.WriteLine(s.x); __refvalue(_ref, S1<int>).x = 42; System.Console.WriteLine(s.x); S1<S1<int>> s1 = new S1<S1<int>>(); _ref = __makeref(s1); __refvalue(_ref, S1<S1<int>>).x.Assign(333); System.Console.WriteLine(s1.x.x); __refvalue(_ref, S1<S1<int>>) = default(S1<S1<int>>); System.Console.WriteLine(s1.x.x); __refvalue(_ref, S1<S1<int>>).x.x = 42; System.Console.WriteLine(s1.x.x); } } "; string expectedGetIL = @" { // Code size 202 (0xca) .maxstack 3 .locals init (int V_0, //x Program.S1<int> V_1, //s Program.S1<Program.S1<int>> V_2) //s1 IL_0000: ldc.i4.0 IL_0001: stloc.0 IL_0002: ldloca.s V_0 IL_0004: mkrefany ""int"" IL_0009: refanyval ""int"" IL_000e: ldc.i4.s 42 IL_0010: stind.i4 IL_0011: ldloc.0 IL_0012: call ""void System.Console.WriteLine(int)"" IL_0017: ldloca.s V_1 IL_0019: initobj ""Program.S1<int>"" IL_001f: ldloca.s V_1 IL_0021: mkrefany ""Program.S1<int>"" IL_0026: dup IL_0027: refanyval ""Program.S1<int>"" IL_002c: ldc.i4 0x14d IL_0031: call ""void Program.S1<int>.Assign(int)"" IL_0036: ldloc.1 IL_0037: ldfld ""int Program.S1<int>.x"" IL_003c: call ""void System.Console.WriteLine(int)"" IL_0041: refanyval ""Program.S1<int>"" IL_0046: ldc.i4.s 42 IL_0048: stfld ""int Program.S1<int>.x"" IL_004d: ldloc.1 IL_004e: ldfld ""int Program.S1<int>.x"" IL_0053: call ""void System.Console.WriteLine(int)"" IL_0058: ldloca.s V_2 IL_005a: initobj ""Program.S1<Program.S1<int>>"" IL_0060: ldloca.s V_2 IL_0062: mkrefany ""Program.S1<Program.S1<int>>"" IL_0067: dup IL_0068: refanyval ""Program.S1<Program.S1<int>>"" IL_006d: ldflda ""Program.S1<int> Program.S1<Program.S1<int>>.x"" IL_0072: ldc.i4 0x14d IL_0077: call ""void Program.S1<int>.Assign(int)"" IL_007c: ldloc.2 IL_007d: ldfld ""Program.S1<int> Program.S1<Program.S1<int>>.x"" IL_0082: ldfld ""int Program.S1<int>.x"" IL_0087: call ""void System.Console.WriteLine(int)"" IL_008c: dup IL_008d: refanyval ""Program.S1<Program.S1<int>>"" IL_0092: initobj ""Program.S1<Program.S1<int>>"" IL_0098: ldloc.2 IL_0099: ldfld ""Program.S1<int> Program.S1<Program.S1<int>>.x"" IL_009e: ldfld ""int Program.S1<int>.x"" IL_00a3: call ""void System.Console.WriteLine(int)"" IL_00a8: refanyval ""Program.S1<Program.S1<int>>"" IL_00ad: ldflda ""Program.S1<int> Program.S1<Program.S1<int>>.x"" IL_00b2: ldc.i4.s 42 IL_00b4: stfld ""int Program.S1<int>.x"" IL_00b9: ldloc.2 IL_00ba: ldfld ""Program.S1<int> Program.S1<Program.S1<int>>.x"" IL_00bf: ldfld ""int Program.S1<int>.x"" IL_00c4: call ""void System.Console.WriteLine(int)"" IL_00c9: ret }"; var verifier = CompileAndVerify(source: text, expectedOutput: @"42 333 42 333 0 42"); verifier.VerifyIL("Program.Main", expectedGetIL); } [Fact] public void RefValueTest02() { var text = @" using System; static class C { static void Main() { int a = 1; TypedReference tr = __makeref(a); int b = __refvalue(123, int); int c = __refvalue(tr, Main); int d = __refvalue(tr, double); __refvalue(tr, int) = null; } }"; // The native compiler produces // CS0118: 'C.Main()' is a 'method' but is used like a 'type' // instead of // CS0246: The type or namespace name 'Main' could not be found // The native compiler behavior seems better here; we might consider fixing Roslyn to match. var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (9,17): error CS0029: Cannot implicitly convert type 'int' to 'System.TypedReference' // int b = __refvalue(123, int); Diagnostic(ErrorCode.ERR_NoImplicitConv, "__refvalue(123, int)").WithArguments("int", "System.TypedReference"), // (10,32): error CS0246: The type or namespace name 'Main' could not be found (are you missing a using directive or an assembly reference?) // int c = __refvalue(tr, Main); Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Main").WithArguments("Main"), // (11,17): error CS0266: Cannot implicitly convert type 'double' to 'int'. An explicit conversion exists (are you missing a cast?) // int d = __refvalue(tr, double); Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "__refvalue(tr, double)").WithArguments("double", "int"), // (12,31): error CS0037: Cannot convert null to 'int' because it is a non-nullable value type // __refvalue(tr, int) = null; Diagnostic(ErrorCode.ERR_ValueCantBeNull, "null").WithArguments("int") ); } [Fact] public void RefValueTest03_Dynamic_Bind() { var text = @" using System; public struct C { static void Main() { dynamic i = 1; TypedReference tr = __makeref(i); Console.Write(i); Get(tr); Console.Write(i); Set(tr, 2); Console.Write(i); } static dynamic Get(TypedReference tr) { return __refvalue(tr, dynamic); } static void Set(TypedReference tr, dynamic i) { __refvalue(tr, dynamic) = i; } }"; CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics(); } [ClrOnlyFact(ClrOnlyReason.Ilasm)] public void RefValueTest04_optimizer() { var text = @" using System; public struct C { static void Main() { int k = 42; int i = 1; TypedReference tr1 = __makeref(i); __refvalue(tr1, int) = k; __refvalue(tr1, int) = k; int j = 1; TypedReference tr2 = __makeref(j); int l = 42; __refvalue(tr1, int) = l; __refvalue(tr2, int) = l; Console.Write(i); Console.Write(j); } }"; var verifier = CompileAndVerify(source: text, expectedOutput: "4242"); verifier.VerifyIL("C.Main", @" { // Code size 72 (0x48) .maxstack 3 .locals init (int V_0, //k int V_1, //i System.TypedReference V_2, //tr1 int V_3, //j int V_4) //l IL_0000: ldc.i4.s 42 IL_0002: stloc.0 IL_0003: ldc.i4.1 IL_0004: stloc.1 IL_0005: ldloca.s V_1 IL_0007: mkrefany ""int"" IL_000c: stloc.2 IL_000d: ldloc.2 IL_000e: refanyval ""int"" IL_0013: ldloc.0 IL_0014: stind.i4 IL_0015: ldloc.2 IL_0016: refanyval ""int"" IL_001b: ldloc.0 IL_001c: stind.i4 IL_001d: ldc.i4.1 IL_001e: stloc.3 IL_001f: ldloca.s V_3 IL_0021: mkrefany ""int"" IL_0026: ldc.i4.s 42 IL_0028: stloc.s V_4 IL_002a: ldloc.2 IL_002b: refanyval ""int"" IL_0030: ldloc.s V_4 IL_0032: stind.i4 IL_0033: refanyval ""int"" IL_0038: ldloc.s V_4 IL_003a: stind.i4 IL_003b: ldloc.1 IL_003c: call ""void System.Console.Write(int)"" IL_0041: ldloc.3 IL_0042: call ""void System.Console.Write(int)"" IL_0047: ret } "); } [Fact] public void TestBug13263() { var text = @"public class C { public void M() { var t = __makeref(delegate); } }"; var tree = Parse(text); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var root = tree.GetCompilationUnitRoot(); var clss = root.Members[0] as ClassDeclarationSyntax; var meth = clss.Members[0] as MethodDeclarationSyntax; var stmt = meth.Body.Statements[0] as LocalDeclarationStatementSyntax; var type = stmt.Declaration.Type; var info = model.GetSymbolInfo(type); Assert.Equal("TypedReference", info.Symbol.Name); } [WorkItem(545055, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545055")] [WorkItem(545056, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545056")] [Fact] public void MethodArgListParameterCount() { var text = @" class A { public void M1(__arglist) { } public void M2(int x, __arglist) { } public void M3(__arglist, int x) { } //illegal, but shouldn't break public void M4(__arglist, int x, __arglist) { } //illegal, but shouldn't break } "; var comp = CreateCompilation(text); var type = comp.GlobalNamespace.GetMember<NamedTypeSymbol>("A"); var m1 = type.GetMember<MethodSymbol>("M1"); Assert.Equal(0, m1.ParameterCount); Assert.Equal(0, m1.Parameters.Length); var m2 = type.GetMember<MethodSymbol>("M2"); Assert.Equal(1, m2.ParameterCount); Assert.Equal(1, m2.Parameters.Length); var m3 = type.GetMember<MethodSymbol>("M3"); Assert.Equal(1, m3.ParameterCount); Assert.Equal(1, m3.Parameters.Length); var m4 = type.GetMember<MethodSymbol>("M4"); Assert.Equal(1, m4.ParameterCount); Assert.Equal(1, m4.Parameters.Length); } [WorkItem(545055, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545055")] [WorkItem(545056, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545056")] [Fact] public void ILMethodArgListParameterCount() { var csharp = @" class Unused { } "; var il = @" .class public auto ansi beforefieldinit A extends [mscorlib]System.Object { .method public hidebysig instance vararg void M1() cil managed { ret } .method public hidebysig instance vararg void M2(int32 x) cil managed { ret } .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } } // end of class A "; var comp = CreateCompilationWithILAndMscorlib40(csharp, il); var type = comp.GlobalNamespace.GetMember<NamedTypeSymbol>("A"); var m1 = type.GetMember<MethodSymbol>("M1"); Assert.Equal(0, m1.ParameterCount); Assert.Equal(0, m1.Parameters.Length); var m2 = type.GetMember<MethodSymbol>("M2"); Assert.Equal(1, m2.ParameterCount); Assert.Equal(1, m2.Parameters.Length); } [WorkItem(545055, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545055")] [WorkItem(545056, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545056")] [Fact] public void OperatorArgListParameterCount() { var text = @" class A { public int operator +(__arglist) { return 0; } //illegal, but shouldn't break public int operator -(A a, __arglist) { return 0; } //illegal, but shouldn't break public int operator *(__arglist, A a) { return 0; } //illegal, but shouldn't break public int operator /(__arglist, A a, __arglist) { return 0; } //illegal, but shouldn't break } "; var comp = CreateCompilation(text); var type = comp.GlobalNamespace.GetMember<NamedTypeSymbol>("A"); var m1 = type.GetMember<MethodSymbol>(WellKnownMemberNames.UnaryPlusOperatorName); Assert.Equal(0, m1.ParameterCount); Assert.Equal(0, m1.Parameters.Length); var m2 = type.GetMember<MethodSymbol>(WellKnownMemberNames.SubtractionOperatorName); Assert.Equal(1, m2.ParameterCount); Assert.Equal(1, m2.Parameters.Length); var m3 = type.GetMember<MethodSymbol>(WellKnownMemberNames.MultiplyOperatorName); Assert.Equal(1, m3.ParameterCount); Assert.Equal(1, m3.Parameters.Length); var m4 = type.GetMember<MethodSymbol>(WellKnownMemberNames.DivisionOperatorName); Assert.Equal(1, m4.ParameterCount); Assert.Equal(1, m4.Parameters.Length); } [WorkItem(545055, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545055")] [WorkItem(545056, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545056")] [Fact] public void ConversionArgListParameterCount1() { var text = @" class A { public explicit operator A(__arglist) { return null; } //illegal, but shouldn't break } "; var comp = CreateCompilation(text); var type = comp.GlobalNamespace.GetMember<NamedTypeSymbol>("A"); var conversion = type.GetMember<MethodSymbol>(WellKnownMemberNames.ExplicitConversionName); Assert.Equal(0, conversion.ParameterCount); Assert.Equal(0, conversion.Parameters.Length); } [WorkItem(545055, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545055")] [WorkItem(545056, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545056")] [Fact] public void ConversionArgListParameterCount2() { var text = @" class A { public explicit operator A(int x, __arglist) { return null; } //illegal, but shouldn't break } "; var comp = CreateCompilation(text); var type = comp.GlobalNamespace.GetMember<NamedTypeSymbol>("A"); var conversion = type.GetMember<MethodSymbol>(WellKnownMemberNames.ExplicitConversionName); Assert.Equal(1, conversion.ParameterCount); Assert.Equal(1, conversion.Parameters.Length); } [WorkItem(545055, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545055")] [WorkItem(545056, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545056")] [Fact] public void ConversionArgListParameterCount3() { var text = @" class A { public explicit operator A(__arglist, A a) { return null; } //illegal, but shouldn't break } "; var comp = CreateCompilation(text); var type = comp.GlobalNamespace.GetMember<NamedTypeSymbol>("A"); var conversion = type.GetMember<MethodSymbol>(WellKnownMemberNames.ExplicitConversionName); Assert.Equal(1, conversion.ParameterCount); Assert.Equal(1, conversion.Parameters.Length); } [WorkItem(545055, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545055")] [WorkItem(545056, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545056")] [Fact] public void ConversionArgListParameterCount4() { var text = @" class A { public explicit operator A(__arglist, A a, __arglist) { return null; } //illegal, but shouldn't break } "; var comp = CreateCompilation(text); var type = comp.GlobalNamespace.GetMember<NamedTypeSymbol>("A"); var conversion = type.GetMember<MethodSymbol>(WellKnownMemberNames.ExplicitConversionName); Assert.Equal(1, conversion.ParameterCount); Assert.Equal(1, conversion.Parameters.Length); } [WorkItem(545055, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545055")] [WorkItem(545056, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545056")] [Fact] public void ConstructorArgListParameterCount1() { var text = @" class A { public A(__arglist) { } } "; var comp = CreateCompilation(text); var constructor = comp.GlobalNamespace.GetMember<NamedTypeSymbol>("A").GetMember<MethodSymbol>(WellKnownMemberNames.InstanceConstructorName); Assert.Equal(0, constructor.ParameterCount); //doesn't use syntax Assert.Equal(0, constructor.Parameters.Length); } [WorkItem(545055, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545055")] [WorkItem(545056, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545056")] [Fact] public void ConstructorArgListParameterCount2() { var text = @" class A { public A(int x, __arglist) { } } "; var comp = CreateCompilation(text); var constructor = comp.GlobalNamespace.GetMember<NamedTypeSymbol>("A").GetMember<MethodSymbol>(WellKnownMemberNames.InstanceConstructorName); Assert.Equal(1, constructor.ParameterCount); //doesn't use syntax Assert.Equal(1, constructor.Parameters.Length); } [WorkItem(545055, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545055")] [WorkItem(545056, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545056")] [Fact] public void ConstructorArgListParameterCount3() { var text = @" class A { public A(__arglist, int x) { } //illegal, but shouldn't break } "; var comp = CreateCompilation(text); var constructor = comp.GlobalNamespace.GetMember<NamedTypeSymbol>("A").GetMember<MethodSymbol>(WellKnownMemberNames.InstanceConstructorName); Assert.Equal(1, constructor.ParameterCount); //doesn't use syntax Assert.Equal(1, constructor.Parameters.Length); } [WorkItem(545055, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545055")] [WorkItem(545056, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545056")] [Fact] public void ConstructorArgListParameterCount4() { var text = @" class A { public A(__arglist, int x, __arglist) { } //illegal, but shouldn't break } "; var comp = CreateCompilation(text); var constructor = comp.GlobalNamespace.GetMember<NamedTypeSymbol>("A").GetMember<MethodSymbol>(WellKnownMemberNames.InstanceConstructorName); Assert.Equal(1, constructor.ParameterCount); //doesn't use syntax Assert.Equal(1, constructor.Parameters.Length); } [WorkItem(545055, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545055")] [WorkItem(545056, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545056")] [Fact] public void IndexerArgListParameterCount1() { var text = @" class A { public int this[__arglist] { get { return 0; } set { } } //illegal, but shouldn't break } "; var comp = CreateCompilation(text); var indexer = comp.GlobalNamespace.GetMember<NamedTypeSymbol>("A").GetMember<PropertySymbol>(WellKnownMemberNames.Indexer); Assert.Equal(0, indexer.ParameterCount); //doesn't use syntax Assert.Equal(0, indexer.Parameters.Length); var getter = indexer.GetMethod; Assert.Equal(0, getter.ParameterCount); Assert.Equal(0, getter.Parameters.Length); var setter = indexer.SetMethod; Assert.Equal(1, setter.ParameterCount); Assert.Equal(1, setter.Parameters.Length); } [WorkItem(545055, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545055")] [WorkItem(545056, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545056")] [Fact] public void IndexerArgListParameterCount2() { var text = @" class A { public int this[int x, __arglist] { get { return 0; } set { } } //illegal, but shouldn't break } "; var comp = CreateCompilation(text); var indexer = comp.GlobalNamespace.GetMember<NamedTypeSymbol>("A").GetMember<PropertySymbol>(WellKnownMemberNames.Indexer); Assert.Equal(1, indexer.ParameterCount); //doesn't use syntax Assert.Equal(1, indexer.Parameters.Length); var getter = indexer.GetMethod; Assert.Equal(1, getter.ParameterCount); Assert.Equal(1, getter.Parameters.Length); var setter = indexer.SetMethod; Assert.Equal(2, setter.ParameterCount); Assert.Equal(2, setter.Parameters.Length); } [WorkItem(545055, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545055")] [WorkItem(545056, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545056")] [Fact] public void IndexerArgListParameterCount3() { var text = @" class A { public int this[__arglist, int x] { get { return 0; } set { } } //illegal, but shouldn't break } "; var comp = CreateCompilation(text); var indexer = comp.GlobalNamespace.GetMember<NamedTypeSymbol>("A").GetMember<PropertySymbol>(WellKnownMemberNames.Indexer); Assert.Equal(1, indexer.ParameterCount); //doesn't use syntax Assert.Equal(1, indexer.Parameters.Length); var getter = indexer.GetMethod; Assert.Equal(1, getter.ParameterCount); Assert.Equal(1, getter.Parameters.Length); var setter = indexer.SetMethod; Assert.Equal(2, setter.ParameterCount); Assert.Equal(2, setter.Parameters.Length); } [WorkItem(545055, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545055")] [WorkItem(545056, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545056")] [Fact] public void IndexerArgListParameterCount4() { var text = @" class A { public int this[__arglist, int x, __arglist] { get { return 0; } set { } } //illegal, but shouldn't break } "; var comp = CreateCompilation(text); var indexer = comp.GlobalNamespace.GetMember<NamedTypeSymbol>("A").GetMember<PropertySymbol>(WellKnownMemberNames.Indexer); Assert.Equal(1, indexer.ParameterCount); //doesn't use syntax Assert.Equal(1, indexer.Parameters.Length); var getter = indexer.GetMethod; Assert.Equal(1, getter.ParameterCount); Assert.Equal(1, getter.Parameters.Length); var setter = indexer.SetMethod; Assert.Equal(2, setter.ParameterCount); Assert.Equal(2, setter.Parameters.Length); } [WorkItem(545086, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545086")] [ConditionalFact(typeof(DesktopOnly), Reason = ConditionalSkipReason.RestrictedTypesNeedDesktop)] public void BoxReceiverTest() { var text = @" using System; class C { static void Goo() { RuntimeArgumentHandle rah = default(RuntimeArgumentHandle); ArgIterator ai = default(ArgIterator); TypedReference tr = default(TypedReference); rah.GetType(); // not virtual ai.GetType(); // not virtual tr.GetType(); // not virtual rah.ToString(); // virtual, overridden on ValueType ai.ToString(); // virtual, overridden on ValueType tr.ToString(); // virtual, overridden on ValueType rah.GetHashCode(); // virtual, overridden on ValueType ai.GetHashCode(); // no error: virtual, overridden on ArgIterator tr.GetHashCode(); // no error: virtual, overridden on TypedReference } }"; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (11,9): error CS0029: Cannot implicitly convert type 'System.RuntimeArgumentHandle' to 'object' // rah.GetType(); // not virtual Diagnostic(ErrorCode.ERR_NoImplicitConv, "rah").WithArguments("System.RuntimeArgumentHandle", "object"), // (12,9): error CS0029: Cannot implicitly convert type 'System.ArgIterator' to 'object' // ai.GetType(); // not virtual Diagnostic(ErrorCode.ERR_NoImplicitConv, "ai").WithArguments("System.ArgIterator", "object"), // (13,9): error CS0029: Cannot implicitly convert type 'System.TypedReference' to 'object' // tr.GetType(); // not virtual Diagnostic(ErrorCode.ERR_NoImplicitConv, "tr").WithArguments("System.TypedReference", "object"), // (14,9): error CS0029: Cannot implicitly convert type 'System.RuntimeArgumentHandle' to 'System.ValueType' // rah.ToString(); // virtual, overridden on ValueType Diagnostic(ErrorCode.ERR_NoImplicitConv, "rah").WithArguments("System.RuntimeArgumentHandle", "System.ValueType"), // (15,9): error CS0029: Cannot implicitly convert type 'System.ArgIterator' to 'System.ValueType' // ai.ToString(); // virtual, overridden on ValueType Diagnostic(ErrorCode.ERR_NoImplicitConv, "ai").WithArguments("System.ArgIterator", "System.ValueType"), // (16,9): error CS0029: Cannot implicitly convert type 'System.TypedReference' to 'System.ValueType' // tr.ToString(); // virtual, overridden on ValueType Diagnostic(ErrorCode.ERR_NoImplicitConv, "tr").WithArguments("System.TypedReference", "System.ValueType"), // (17,9): error CS0029: Cannot implicitly convert type 'System.RuntimeArgumentHandle' to 'System.ValueType' // rah.GetHashCode(); // virtual, overridden on ValueType Diagnostic(ErrorCode.ERR_NoImplicitConv, "rah").WithArguments("System.RuntimeArgumentHandle", "System.ValueType") ); } [WorkItem(649808, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/649808")] [Fact] public void MissingArgumentsAndOptionalParameters_1() { var source = @"class A { internal A(object x, __arglist) { } internal static void M(object x, __arglist) { } } class B { internal B(object x = null, __arglist) { } internal static void M(object x = null, __arglist) { } } class C { internal C(object x, object y = null, __arglist) { } internal static void M(object x, object y = null, __arglist) { } } class D { internal D(object x = null, object y = null, __arglist) { } internal static void M(object x = null, object y = null, __arglist) { } } class E { static void M() { // No optional arguments. new A(__arglist()); new A(null, __arglist()); A.M(__arglist()); A.M(null, __arglist()); // One optional argument. new B(__arglist()); new B(null, __arglist()); B.M(__arglist()); B.M(null, __arglist()); // One required, one optional argument. new C(__arglist()); new C(null, __arglist()); new C(null, null, __arglist()); C.M(__arglist()); C.M(null, __arglist()); C.M(null, null, __arglist()); // Two optional arguments. new D(__arglist()); new D(null, __arglist()); new D(null, null, __arglist()); D.M(__arglist()); D.M(null, __arglist()); D.M(null, null, __arglist()); } }"; CreateCompilation(source).VerifyDiagnostics( // (26,13): error CS7036: There is no argument given that corresponds to the required formal parameter '__arglist' of 'A.A(object, __arglist)' // new A(__arglist()); Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "A").WithArguments("__arglist", "A.A(object, __arglist)").WithLocation(26, 13), // (28,9): error CS7036: There is no argument given that corresponds to the required formal parameter '__arglist' of 'A.M(object, __arglist)' // A.M(__arglist()); Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "M").WithArguments("__arglist", "A.M(object, __arglist)").WithLocation(28, 11), // (31,13): error CS7036: There is no argument given that corresponds to the required formal parameter '__arglist' of 'B.B(object, __arglist)' // new B(__arglist()); Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "B").WithArguments("__arglist", "B.B(object, __arglist)").WithLocation(31, 13), // (33,9): error CS7036: There is no argument given that corresponds to the required formal parameter '__arglist' of 'B.M(object, __arglist)' // B.M(__arglist()); Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "M").WithArguments("__arglist", "B.M(object, __arglist)").WithLocation(33, 11), // (36,13): error CS7036: There is no argument given that corresponds to the required formal parameter '__arglist' of 'C.C(object, object, __arglist)' // new C(__arglist()); Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "C").WithArguments("__arglist", "C.C(object, object, __arglist)").WithLocation(36, 13), // (37,13): error CS7036: There is no argument given that corresponds to the required formal parameter '__arglist' of 'C.C(object, object, __arglist)' // new C(null, __arglist()); Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "C").WithArguments("__arglist", "C.C(object, object, __arglist)").WithLocation(37, 13), // (39,9): error CS7036: There is no argument given that corresponds to the required formal parameter '__arglist' of 'C.M(object, object, __arglist)' // C.M(__arglist()); Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "M").WithArguments("__arglist", "C.M(object, object, __arglist)").WithLocation(39, 11), // (40,9): error CS7036: There is no argument given that corresponds to the required formal parameter '__arglist' of 'C.M(object, object, __arglist)' // C.M(null, __arglist()); Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "M").WithArguments("__arglist", "C.M(object, object, __arglist)").WithLocation(40, 11), // (43,13): error CS7036: There is no argument given that corresponds to the required formal parameter '__arglist' of 'D.D(object, object, __arglist)' // new D(__arglist()); Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "D").WithArguments("__arglist", "D.D(object, object, __arglist)").WithLocation(43, 13), // (44,13): error CS7036: There is no argument given that corresponds to the required formal parameter '__arglist' of 'D.D(object, object, __arglist)' // new D(null, __arglist()); Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "D").WithArguments("__arglist", "D.D(object, object, __arglist)").WithLocation(44, 13), // (46,9): error CS7036: There is no argument given that corresponds to the required formal parameter '__arglist' of 'D.M(object, object, __arglist)' // D.M(__arglist()); Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "M").WithArguments("__arglist", "D.M(object, object, __arglist)").WithLocation(46, 11), // (47,9): error CS7036: There is no argument given that corresponds to the required formal parameter '__arglist' of 'D.M(object, object, __arglist)' // D.M(null, __arglist()); Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "M").WithArguments("__arglist", "D.M(object, object, __arglist)").WithLocation(47, 11)); } [WorkItem(649808, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/649808")] [Fact] public void MissingArgumentsAndOptionalParameters_2() { var ilSource = @".class public sealed D extends [mscorlib]System.MulticastDelegate { .method public hidebysig specialname rtspecialname instance void .ctor(object o, native int m) runtime { } .method public hidebysig instance vararg void Invoke([opt] object o) runtime { } .method public hidebysig instance class [mscorlib]System.IAsyncResult BeginInvoke(class [mscorlib]System.AsyncCallback c, object o) runtime { } .method public hidebysig instance void EndInvoke(class [mscorlib]System.IAsyncResult r) runtime { } }"; var source = @"class C { static void M(D d) { d(null, __arglist()); d(__arglist()); } }"; var compilation = CreateCompilationWithILAndMscorlib40(source, ilSource); compilation.VerifyDiagnostics( // (6,9): error CS7036: There is no argument given that corresponds to the required formal parameter '__arglist' of 'D' // d(__arglist()); Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "d").WithArguments("__arglist", "D").WithLocation(6, 9)); } [Fact, WorkItem(1253, "https://github.com/dotnet/roslyn/issues/1253")] public void LambdaWithUnsafeParameter() { var source = @" using System; using System.Threading; namespace ConsoleApplication21 { public unsafe class GooBar : IDisposable { public void Dispose() { NativeOverlapped* overlapped = AllocateNativeOverlapped(() => { }); } private unsafe static NativeOverlapped* AllocateNativeOverlapped(IOCompletionCallback callback, object context, byte[] pinData) { return null; } } } "; CreateCompilation(source, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (12,44): error CS7036: There is no argument given that corresponds to the required formal parameter 'context' of 'GooBar.AllocateNativeOverlapped(IOCompletionCallback, object, byte[])' // NativeOverlapped* overlapped = AllocateNativeOverlapped(() => { }); Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "AllocateNativeOverlapped").WithArguments("context", "ConsoleApplication21.GooBar.AllocateNativeOverlapped(System.Threading.IOCompletionCallback, object, byte[])").WithLocation(12, 44) ); } [Fact, WorkItem(8152, "https://github.com/dotnet/roslyn/issues/8152")] public void DuplicateDeclaration() { var source = @" public class SpecialCases { public void ArgListMethod(__arglist) { ArgListMethod(__arglist("""")); } public void ArgListMethod(__arglist) { ArgListMethod(__arglist("""")); } } "; CreateCompilation(source, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (8,17): error CS0111: Type 'SpecialCases' already defines a member called 'ArgListMethod' with the same parameter types // public void ArgListMethod(__arglist) Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "ArgListMethod").WithArguments("ArgListMethod", "SpecialCases").WithLocation(8, 17), // (6,9): error CS0121: The call is ambiguous between the following methods or properties: 'SpecialCases.ArgListMethod(__arglist)' and 'SpecialCases.ArgListMethod(__arglist)' // ArgListMethod(__arglist("")); Diagnostic(ErrorCode.ERR_AmbigCall, "ArgListMethod").WithArguments("SpecialCases.ArgListMethod(__arglist)", "SpecialCases.ArgListMethod(__arglist)").WithLocation(6, 9), // (10,9): error CS0121: The call is ambiguous between the following methods or properties: 'SpecialCases.ArgListMethod(__arglist)' and 'SpecialCases.ArgListMethod(__arglist)' // ArgListMethod(__arglist("")); Diagnostic(ErrorCode.ERR_AmbigCall, "ArgListMethod").WithArguments("SpecialCases.ArgListMethod(__arglist)", "SpecialCases.ArgListMethod(__arglist)").WithLocation(10, 9) ); } [ConditionalFact(typeof(DesktopOnly), Reason = ConditionalSkipReason.RestrictedTypesNeedDesktop)] public void ArgListMayNotHaveAnOutArgument() { CreateCompilation(@" class Program { static void Test(__arglist) { var a = 1; Test(__arglist(out a)); } } ").VerifyDiagnostics( // (7,25): error CS8378: __arglist cannot have an argument passed by 'in' or 'out' // Test(__arglist(out a)); Diagnostic(ErrorCode.ERR_CantUseInOrOutInArglist, "a").WithLocation(7, 25)); } [Fact] public void ArgListMayNotHaveAnInArgument() { CreateCompilation(@" class Program { static void Test(__arglist) { var a = 1; Test(__arglist(in a)); } } ").VerifyDiagnostics( // (7,24): error CS8378: __arglist cannot have an argument passed by 'in' or 'out' // Test(__arglist(in a)); Diagnostic(ErrorCode.ERR_CantUseInOrOutInArglist, "a").WithLocation(7, 24)); } [ConditionalFact(typeof(WindowsDesktopOnly), Reason = ConditionalSkipReason.RestrictedTypesNeedDesktop)] public void ArgListMayHaveARefArgument() { CompileAndVerify(@" using System; class Program { static void Test(__arglist) { var args = new ArgIterator(__arglist); ref int a = ref __refvalue(args.GetNextArg(), int); a = 5; } static void Main() { int a = 0; Test(__arglist(ref a)); Console.WriteLine(a); } }", options: TestOptions.DebugExe, expectedOutput: "5"); } [ConditionalFact(typeof(DesktopOnly), Reason = ConditionalSkipReason.RestrictedTypesNeedDesktop)] public void ArgListMayHaveAByValArgument() { CompileAndVerify(@" using System; class Program { static void Test(__arglist) { var args = new ArgIterator(__arglist); int a = __refvalue(args.GetNextArg(), int); Console.WriteLine(a); } static void Main() { int a = 5; Test(__arglist(a)); } }", options: TestOptions.DebugExe, expectedOutput: "5"); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Xunit; // "__arglist" is an undocumented keyword of the C# language. // // There are three places where __arglist may legally appear in C#. It may appear: // // 1) as the final "parameter" of a method declaration: // // static void M(int x, int y, __arglist) {} // // 2) As an expression in a method whose declaration includes an __arglist parameter: // // static void M(int x, int y, __arglist) { var ai = new ArgIterator(__arglist); } // // 3) As the "receiver" of a "call" syntax in the last position of a call to an __arglist method: // // C.M(1, 2, __arglist(3, 4, 5)); // // THE FIRST FORM // --------------- // // In its first form it may not appear: // // * In a generic method // * In a generic type // * In an iterator method declaration // * In a delegate declaration // * In a user-defined operator or conversion declaration // // UNDONE: We should ensure that __arglist methods may not be async. // // In metadata, such a method is referred to as a "varargs" method and is identified // by the calling convention of the method. // // THE SECOND FORM // --------------- // // The second form is a legal expression (almost) anywhere inside a method that includes // an __arglist parameter. It is an expression of type System.RuntimeArgumentHandle and // classified as a value. It is usually passed to the ctor of the ArgIterator type. // // Speaking of which, we should talk about some special types. // // RuntimeArgumentHandle, ArgIterator and TypedReference are "restricted" types: // // * A restricted type may not be converted to object. // * It is illegal to declare a field or property of a restricted type. // * A restricted type may not be used as a generic type argument. // * A method or delegate may not return a restricted type. // * Since a field may not be of a restricted type, a restricted type may not be used // in an anonymous method, lambda or query expression if it would have to be hoisted // to a field. // // The native compiler does not consistently enforce these rules. For example, // it allows: // // delegate void D(RuntimeArgumentHandle r); // static int M(__arglist) // { // D f = null; // f = x=>f(__arglist); // } // // Sure enough, C# 5 generates a display class with method: // // static int Anonymous(RuntimeArgumentHandle x) { return this.f(__arglist); } // // Which doesn't make any sense; the anonymous method is not an __arglist method. // // This should simply be illegal; Roslyn disallows __arglist used in the second // form inside any lambda or anonymous method. (Even if the lambda in question is // from a query transformation.) // // THE THIRD FORM // -------------- // // The third form may only appear as the last argument of a call to a varargs method. // // UNDONE: The third form may not appear in a method call inside an expression tree lambda. // // // "__reftype" is also an undocumented keyword of C#. It is treated as an operator which // takes as its sole operand an expression convertible to System.TypedReference. The result is // the System.Type associated with the type of the typed reference. // // "__makeref" is also an undocumented keyword of C#. It is treated as an operator which takes // as its sole operand an expression classified as a variable. The result is a TypedReference // to the variable. It is analogous to the "&" address-of operator. // // "__refvalue" is also an undocumented keyword of C#. It is badly named, as it has the semantics // of *dereference to produce a variable*. It is the opposite of the __makeref operator and is // analogous to the "*" dereference operator. The operator takes a TypedReference and a // type, and produces a variable of that type. // // namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class ArglistTests : CompilingTestBase { [Fact] public void ExpressionTreeTest() { var text = @" using System; using System.Linq.Expressions; public struct C { static void Main() { Expression<Func<bool>> ex1 = ()=>M(__makeref(S)); // CS7053 Expression<Func<Type>> ex2 = ()=>__reftype(default(TypedReference)); Expression<Func<int>> ex3 = ()=>__refvalue(default(TypedReference), int); Expression<Func<bool>> ex4 = ()=>N(__arglist()); } static int S = 678; public static bool M(TypedReference tr) { return true; } public static bool N(__arglist) { return true;} }"; var comp = CreateCompilationWithMscorlib40AndSystemCore(text); comp.VerifyDiagnostics( // (8,44): error CS8640: Expression tree cannot contain value of ref struct or restricted type 'TypedReference'. // Expression<Func<bool>> ex1 = ()=>M(__makeref(S)); // CS7053 Diagnostic(ErrorCode.ERR_ExpressionTreeCantContainRefStruct, "__makeref(S)").WithArguments("TypedReference").WithLocation(8, 44), // (8,44): error CS7053: An expression tree may not contain '__makeref' // Expression<Func<bool>> ex1 = ()=>M(__makeref(S)); // CS7053 Diagnostic(ErrorCode.ERR_FeatureNotValidInExpressionTree, "__makeref(S)").WithArguments("__makeref").WithLocation(8, 44), // (9,42): error CS7053: An expression tree may not contain '__reftype' // Expression<Func<Type>> ex2 = ()=>__reftype(default(TypedReference)); Diagnostic(ErrorCode.ERR_FeatureNotValidInExpressionTree, "__reftype(default(TypedReference))").WithArguments("__reftype").WithLocation(9, 42), // (9,52): error CS8640: Expression tree cannot contain value of ref struct or restricted type 'TypedReference'. // Expression<Func<Type>> ex2 = ()=>__reftype(default(TypedReference)); Diagnostic(ErrorCode.ERR_ExpressionTreeCantContainRefStruct, "default(TypedReference)").WithArguments("TypedReference").WithLocation(9, 52), // (10,41): error CS7053: An expression tree may not contain '__refvalue' // Expression<Func<int>> ex3 = ()=>__refvalue(default(TypedReference), int); Diagnostic(ErrorCode.ERR_FeatureNotValidInExpressionTree, "__refvalue(default(TypedReference), int)").WithArguments("__refvalue").WithLocation(10, 41), // (10,52): error CS8640: Expression tree cannot contain value of ref struct or restricted type 'TypedReference'. // Expression<Func<int>> ex3 = ()=>__refvalue(default(TypedReference), int); Diagnostic(ErrorCode.ERR_ExpressionTreeCantContainRefStruct, "default(TypedReference)").WithArguments("TypedReference").WithLocation(10, 52), // (11,44): error CS1952: An expression tree lambda may not contain a method with variable arguments // Expression<Func<bool>> ex4 = ()=>N(__arglist()); Diagnostic(ErrorCode.ERR_VarArgsInExpressionTree, "__arglist()").WithLocation(11, 44) ); } [ClrOnlyFact(ClrOnlyReason.Ilasm)] public void MakeRefTest01() { var text = @" using System; public struct C { static void Main() { int i = 1; Console.WriteLine(M(__makeref(i))); } static Type M(TypedReference tr) { return __reftype(tr); } }"; string expectedIL = @"{ // Code size 20 (0x14) .maxstack 1 .locals init (int V_0) //i IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldloca.s V_0 IL_0004: mkrefany ""int"" IL_0009: call ""System.Type C.M(System.TypedReference)"" IL_000e: call ""void System.Console.WriteLine(object)"" IL_0013: ret }"; var verifier = CompileAndVerify(source: text, expectedOutput: "System.Int32"); verifier.VerifyIL("C.Main", expectedIL); } [Fact] public void MakeRefTest02() { // A makeref is logically the same as passing a variable to a method that takes a ref/out parameter, // so we produce the same error messages. This differs from the native compiler, which either fails // to produce errors at all, or produces the error messages for a bad assignment. We should not produce // errors for bad assignments; first of all, making a ref does not do an assignment, and second, the // user might assume that it is the assignment to the local that is bad. var text = @" using System; public struct C { static void Main() { TypedReference tr1 = default(TypedReference); TypedReference tr2 = __makeref(tr1); // CS1601 TypedReference tr3 = __makeref(123); // CS1510 TypedReference tr4 = __makeref(P); // CS0206 TypedReference tr5 = __makeref(R); // CS0199 } static int P { get; set; } static readonly int R = 345; }"; // UNDONE: Test what happens when __makereffing a volatile field, readonly field, etc. var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (8,30): error CS1601: Cannot make reference to variable of type 'TypedReference' // TypedReference tr2 = __makeref(tr1); // CS1601 Diagnostic(ErrorCode.ERR_MethodArgCantBeRefAny, "__makeref(tr1)").WithArguments("System.TypedReference").WithLocation(8, 30), // (9,40): error CS1510: A ref or out value must be an assignable variable // TypedReference tr3 = __makeref(123); // CS1510 Diagnostic(ErrorCode.ERR_RefLvalueExpected, "123").WithLocation(9, 40), // (10,40): error CS0206: A property or indexer may not be passed as an out or ref parameter // TypedReference tr4 = __makeref(P); // CS0206 Diagnostic(ErrorCode.ERR_RefProperty, "P").WithArguments("C.P").WithLocation(10, 40), // (11,40): error CS0199: A static readonly field cannot be used as a ref or out value (except in a static constructor) // TypedReference tr5 = __makeref(R); // CS0199 Diagnostic(ErrorCode.ERR_RefReadonlyStatic, "R").WithLocation(11, 40) ); } [Fact] [WorkItem(23369, "https://github.com/dotnet/roslyn/issues/23369")] public void ArglistWithVoidMethod() { var text = @" public class C { void M() { M2(__arglist(1, M())); } void M2(__arglist) { } }"; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (6,25): error CS8361: __arglist cannot have an argument of void type // M2(__arglist(1, M())); Diagnostic(ErrorCode.ERR_CantUseVoidInArglist, "M()").WithLocation(6, 25) ); } [Fact] public void RefValueUnsafeToReturn() { var text = @" using System; class C { private static ref int Test() { int aa = 42; var tr = __makeref(aa); ref var r = ref Test2(ref __refvalue(tr, int)); return ref r; } private static ref int Test2(ref int r) { return ref r; } private static ref int Test3(TypedReference tr) { return ref __refvalue(tr, int); } }"; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (13,20): error CS8157: Cannot return 'r' by reference because it was initialized to a value that cannot be returned by reference // return ref r; Diagnostic(ErrorCode.ERR_RefReturnNonreturnableLocal, "r").WithArguments("r").WithLocation(13, 20), // (23,20): error CS8156: An expression cannot be used in this context because it may not be returned by reference // return ref __refvalue(tr, int); Diagnostic(ErrorCode.ERR_RefReturnLvalueExpected, "__refvalue(tr, int)").WithLocation(23, 20) ); } [Fact] public void MakeRefTest03_Dynamic_Bind() { var text = @" using System; public struct C { static void Main() { dynamic i = 1; Console.WriteLine(M(__makeref(i))); } static Type M(TypedReference tr) { return __reftype(tr); } }"; CreateCompilation(text).VerifyDiagnostics(); } [ClrOnlyFact(ClrOnlyReason.Ilasm)] public void RefTypeTest01() { var text = @" using System; using System.Reflection; public struct C { public string f; static void Main() { Type ctype = typeof(C); FieldInfo[] ffield = new FieldInfo[] {ctype.GetFields()[0] }; TypedReference tr = TypedReference.MakeTypedReference(new C(), ffield); Type type = M(tr); Console.WriteLine(type.ToString()); } static Type M(TypedReference tr) { return __reftype(tr); } }"; string expectedIL = @"{ // Code size 9 (0x9) .maxstack 1 IL_0000: ldarg.0 IL_0001: refanytype IL_0003: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0008: ret }"; var verifier = CompileAndVerify(source: text, expectedOutput: "System.String"); verifier.VerifyIL("C.M", expectedIL); } [Fact] public void RefTypeTest02() { var text = @" public struct C { static void Main() { System.Type t = __reftype(null); } }"; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (6,25): error CS0037: Cannot convert null to 'System.TypedReference' because it is a non-nullable value type // System.Type t = __reftype(null); Diagnostic(ErrorCode.ERR_ValueCantBeNull, "__reftype(null)").WithArguments("System.TypedReference") ); } [ConditionalFact(typeof(DesktopOnly), Reason = ConditionalSkipReason.RestrictedTypesNeedDesktop)] public void ArglistTest01() { var text = @" using System; public class C { static void Main() { } static void M(__arglist) { new ArgIterator(__arglist); } }"; string expectedIL = @"{ // Code size 9 (0x9) .maxstack 1 IL_0000: arglist IL_0002: newobj ""System.ArgIterator..ctor(System.RuntimeArgumentHandle)"" IL_0007: pop IL_0008: ret }"; var verifier = CompileAndVerify(source: text, expectedOutput: ""); verifier.VerifyIL("C.M(__arglist)", expectedIL); } [ConditionalFact(typeof(DesktopOnly), Reason = ConditionalSkipReason.RestrictedTypesNeedDesktop)] public void ArglistTest02() { var text = @" using System; public class C { static void Main() { M(1, __arglist(2, 3, true)); } static void M(int x, __arglist) { Console.Write(x); DumpArgs(new ArgIterator(__arglist)); new B(4); new D(6); } static void DumpArgs(ArgIterator args) { while(args.GetRemainingCount() > 0) { TypedReference tr = args.GetNextArg(); object arg = TypedReference.ToObject(tr); Console.Write(arg); } } static void M(uint x, __arglist) { } class B { public B(__arglist) { DumpArgs(new ArgIterator(__arglist)); } public B(int x) : this(__arglist(x, 5)) {} } class D : B { public D(int x) : base(__arglist(x, 7)) {} } }"; // Note that this IL is not quite right; here we are displaying the call as "void C.M(int, __arglist)". // The actual IL for this program should show the method ref as "void C.M(int, ..., int, int, bool)", // because that is the information that is actually encoded in the method ref. If we want to display // that then we'll need to add special code to the symbol display visitor that knows how to emit // the desired format. string expectedIL = @"{ // Code size 10 (0xa) .maxstack 4 IL_0000: ldc.i4.1 IL_0001: ldc.i4.2 IL_0002: ldc.i4.3 IL_0003: ldc.i4.1 IL_0004: call ""void C.M(int, __arglist) with __arglist( int, int, bool)"" IL_0009: ret } "; string expectedOutput = @"123True4567"; var verifier = CompileAndVerify(source: text, expectedOutput: expectedOutput); verifier.VerifyIL("C.Main", expectedIL); } [ConditionalFact(typeof(DesktopOnly), Reason = ConditionalSkipReason.RestrictedTypesNeedDesktop)] public void ArglistTest03() { // The native parser produces "type expected" when __arglist is preceded by an illegal // modifier. The Roslyn compiler produces the more informative "__arglist not valid" error. var text = @" static class C { static void M(int x, __arglist) {} static void N(params __arglist) {} static void O(ref __arglist) {} static void P(out __arglist) {} static void Q(this __arglist) {} static void Main() { M(1); M(2, 3); M(4, 5, 6); M(1, __arglist()); // no error M(1, __arglist(__arglist())); var x = __arglist(123); } static object R() { return __arglist(456); } static void S(int x) { S(__arglist(1)); } [MyAttribute(__arglist(2))] static void T() { object obj1 = new System.TypedReference(); object obj2 = (object)new System.ArgIterator(); // The native compiler produces: //'TypedReference' may not be used as a type argument // which is not a very descriptive error! There is no type argument here; // the fact that anonymous types are actually generic is an implementation detail. // Roslyn produces the far more sensible error: // cannot assign TypedReference to anonymous type property object obj3 = new { X = new System.TypedReference() }; } } public class MyAttribute : System.Attribute { public MyAttribute(__arglist) { } } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (5,26): error CS1669: __arglist is not valid in this context // static void N(params __arglist) {} Diagnostic(ErrorCode.ERR_IllegalVarArgs, "__arglist").WithLocation(5, 26), // (6,23): error CS1669: __arglist is not valid in this context // static void O(ref __arglist) {} Diagnostic(ErrorCode.ERR_IllegalVarArgs, "__arglist").WithLocation(6, 23), // (7,23): error CS1669: __arglist is not valid in this context // static void P(out __arglist) {} Diagnostic(ErrorCode.ERR_IllegalVarArgs, "__arglist").WithLocation(7, 23), // (8,24): error CS1669: __arglist is not valid in this context // static void Q(this __arglist) {} Diagnostic(ErrorCode.ERR_IllegalVarArgs, "__arglist").WithLocation(8, 24), // (11,9): error CS7036: There is no argument given that corresponds to the required formal parameter '__arglist' of 'C.M(int, __arglist)' // M(1); Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "M").WithArguments("__arglist", "C.M(int, __arglist)").WithLocation(11, 9), // (12,14): error CS1503: Argument 2: cannot convert from 'int' to '__arglist' // M(2, 3); Diagnostic(ErrorCode.ERR_BadArgType, "3").WithArguments("2", "int", "__arglist").WithLocation(12, 14), // (13,9): error CS1501: No overload for method 'M' takes 3 arguments // M(4, 5, 6); Diagnostic(ErrorCode.ERR_BadArgCount, "M").WithArguments("M", "3").WithLocation(13, 9), // (15,24): error CS0226: An __arglist expression may only appear inside of a call or new expression // M(1, __arglist(__arglist())); Diagnostic(ErrorCode.ERR_IllegalArglist, "__arglist()").WithLocation(15, 24), // (16,17): error CS0226: An __arglist expression may only appear inside of a call or new expression // var x = __arglist(123); Diagnostic(ErrorCode.ERR_IllegalArglist, "__arglist(123)").WithLocation(16, 17), // (20,16): error CS0226: An __arglist expression may only appear inside of a call or new expression // return __arglist(456); Diagnostic(ErrorCode.ERR_IllegalArglist, "__arglist(456)").WithLocation(20, 16), // (24,11): error CS1503: Argument 1: cannot convert from '__arglist' to 'int' // S(__arglist(1)); Diagnostic(ErrorCode.ERR_BadArgType, "__arglist(1)").WithArguments("1", "__arglist", "int").WithLocation(24, 11), // (27,18): error CS0226: An __arglist expression may only appear inside of a call or new expression // [MyAttribute(__arglist(2))] Diagnostic(ErrorCode.ERR_IllegalArglist, "__arglist(2)").WithLocation(27, 18), // (30,23): error CS0029: Cannot implicitly convert type 'System.TypedReference' to 'object' // object obj1 = new System.TypedReference(); Diagnostic(ErrorCode.ERR_NoImplicitConv, "new System.TypedReference()").WithArguments("System.TypedReference", "object").WithLocation(30, 23), // (31,23): error CS0030: Cannot convert type 'System.ArgIterator' to 'object' // object obj2 = (object)new System.ArgIterator(); Diagnostic(ErrorCode.ERR_NoExplicitConv, "(object)new System.ArgIterator()").WithArguments("System.ArgIterator", "object").WithLocation(31, 23), // (38,29): error CS0828: Cannot assign System.TypedReference to anonymous type property // object obj3 = new { X = new System.TypedReference() }; Diagnostic(ErrorCode.ERR_AnonymousTypePropertyAssignedBadValue, "X = new System.TypedReference()").WithArguments("System.TypedReference").WithLocation(38, 29)); } [Fact] public void ArglistTest04() { var text = @" using System; class error { static void Main() { Action a = delegate (__arglist) { }; } } "; CreateCompilation(text).VerifyDiagnostics( // (7,24): error CS1669: __arglist is not valid in this context // Action a = delegate (__arglist) { }; Diagnostic(ErrorCode.ERR_IllegalVarArgs, "__arglist")); } [ClrOnlyFact(ClrOnlyReason.Ilasm)] public void RefValueTest01() { var text = @" using System; public struct C { static void Main() { int i = 1; TypedReference tr = __makeref(i); Console.Write(i); Get(tr); Console.Write(i); Set(tr, 2); Console.Write(i); Ref(tr, 3); Console.Write(i); } static int Get(TypedReference tr) { return __refvalue(tr, int); } static void Set(TypedReference tr, int i) { __refvalue(tr, int) = i; } static void Ref(TypedReference tr, int i) { // The native compiler generates bad code for this; Roslyn gets it right. M(ref __refvalue(tr, int), i); } static void M(ref int x, int y) { x = y; } }"; string expectedGetIL = @"{ // Code size 8 (0x8) .maxstack 1 IL_0000: ldarg.0 IL_0001: refanyval ""int"" IL_0006: ldind.i4 IL_0007: ret }"; string expectedSetIL = @"{ // Code size 9 (0x9) .maxstack 2 IL_0000: ldarg.0 IL_0001: refanyval ""int"" IL_0006: ldarg.1 IL_0007: stind.i4 IL_0008: ret }"; string expectedRefIL = @"{ // Code size 13 (0xd) .maxstack 2 IL_0000: ldarg.0 IL_0001: refanyval ""int"" IL_0006: ldarg.1 IL_0007: call ""void C.M(ref int, int)"" IL_000c: ret }"; var verifier = CompileAndVerify(source: text, expectedOutput: "1123"); verifier.VerifyIL("C.Get", expectedGetIL); verifier.VerifyIL("C.Set", expectedSetIL); verifier.VerifyIL("C.Ref", expectedRefIL); } [ClrOnlyFact(ClrOnlyReason.Ilasm)] public void RefValueTest01a() { var text = @" using System; class Program { struct S1<T> { public T x; public void Assign(T i) { x = i; } } static void Main(string[] args) { int x = 0; var _ref = __makeref(x); __refvalue(_ref, int) = 42; System.Console.WriteLine(x); S1<int> s = new S1<int>(); _ref = __makeref(s); __refvalue(_ref, S1<int>).Assign(333); System.Console.WriteLine(s.x); __refvalue(_ref, S1<int>).x = 42; System.Console.WriteLine(s.x); S1<S1<int>> s1 = new S1<S1<int>>(); _ref = __makeref(s1); __refvalue(_ref, S1<S1<int>>).x.Assign(333); System.Console.WriteLine(s1.x.x); __refvalue(_ref, S1<S1<int>>) = default(S1<S1<int>>); System.Console.WriteLine(s1.x.x); __refvalue(_ref, S1<S1<int>>).x.x = 42; System.Console.WriteLine(s1.x.x); } } "; string expectedGetIL = @" { // Code size 202 (0xca) .maxstack 3 .locals init (int V_0, //x Program.S1<int> V_1, //s Program.S1<Program.S1<int>> V_2) //s1 IL_0000: ldc.i4.0 IL_0001: stloc.0 IL_0002: ldloca.s V_0 IL_0004: mkrefany ""int"" IL_0009: refanyval ""int"" IL_000e: ldc.i4.s 42 IL_0010: stind.i4 IL_0011: ldloc.0 IL_0012: call ""void System.Console.WriteLine(int)"" IL_0017: ldloca.s V_1 IL_0019: initobj ""Program.S1<int>"" IL_001f: ldloca.s V_1 IL_0021: mkrefany ""Program.S1<int>"" IL_0026: dup IL_0027: refanyval ""Program.S1<int>"" IL_002c: ldc.i4 0x14d IL_0031: call ""void Program.S1<int>.Assign(int)"" IL_0036: ldloc.1 IL_0037: ldfld ""int Program.S1<int>.x"" IL_003c: call ""void System.Console.WriteLine(int)"" IL_0041: refanyval ""Program.S1<int>"" IL_0046: ldc.i4.s 42 IL_0048: stfld ""int Program.S1<int>.x"" IL_004d: ldloc.1 IL_004e: ldfld ""int Program.S1<int>.x"" IL_0053: call ""void System.Console.WriteLine(int)"" IL_0058: ldloca.s V_2 IL_005a: initobj ""Program.S1<Program.S1<int>>"" IL_0060: ldloca.s V_2 IL_0062: mkrefany ""Program.S1<Program.S1<int>>"" IL_0067: dup IL_0068: refanyval ""Program.S1<Program.S1<int>>"" IL_006d: ldflda ""Program.S1<int> Program.S1<Program.S1<int>>.x"" IL_0072: ldc.i4 0x14d IL_0077: call ""void Program.S1<int>.Assign(int)"" IL_007c: ldloc.2 IL_007d: ldfld ""Program.S1<int> Program.S1<Program.S1<int>>.x"" IL_0082: ldfld ""int Program.S1<int>.x"" IL_0087: call ""void System.Console.WriteLine(int)"" IL_008c: dup IL_008d: refanyval ""Program.S1<Program.S1<int>>"" IL_0092: initobj ""Program.S1<Program.S1<int>>"" IL_0098: ldloc.2 IL_0099: ldfld ""Program.S1<int> Program.S1<Program.S1<int>>.x"" IL_009e: ldfld ""int Program.S1<int>.x"" IL_00a3: call ""void System.Console.WriteLine(int)"" IL_00a8: refanyval ""Program.S1<Program.S1<int>>"" IL_00ad: ldflda ""Program.S1<int> Program.S1<Program.S1<int>>.x"" IL_00b2: ldc.i4.s 42 IL_00b4: stfld ""int Program.S1<int>.x"" IL_00b9: ldloc.2 IL_00ba: ldfld ""Program.S1<int> Program.S1<Program.S1<int>>.x"" IL_00bf: ldfld ""int Program.S1<int>.x"" IL_00c4: call ""void System.Console.WriteLine(int)"" IL_00c9: ret }"; var verifier = CompileAndVerify(source: text, expectedOutput: @"42 333 42 333 0 42"); verifier.VerifyIL("Program.Main", expectedGetIL); } [Fact] public void RefValueTest02() { var text = @" using System; static class C { static void Main() { int a = 1; TypedReference tr = __makeref(a); int b = __refvalue(123, int); int c = __refvalue(tr, Main); int d = __refvalue(tr, double); __refvalue(tr, int) = null; } }"; // The native compiler produces // CS0118: 'C.Main()' is a 'method' but is used like a 'type' // instead of // CS0246: The type or namespace name 'Main' could not be found // The native compiler behavior seems better here; we might consider fixing Roslyn to match. var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (9,17): error CS0029: Cannot implicitly convert type 'int' to 'System.TypedReference' // int b = __refvalue(123, int); Diagnostic(ErrorCode.ERR_NoImplicitConv, "__refvalue(123, int)").WithArguments("int", "System.TypedReference"), // (10,32): error CS0246: The type or namespace name 'Main' could not be found (are you missing a using directive or an assembly reference?) // int c = __refvalue(tr, Main); Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Main").WithArguments("Main"), // (11,17): error CS0266: Cannot implicitly convert type 'double' to 'int'. An explicit conversion exists (are you missing a cast?) // int d = __refvalue(tr, double); Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "__refvalue(tr, double)").WithArguments("double", "int"), // (12,31): error CS0037: Cannot convert null to 'int' because it is a non-nullable value type // __refvalue(tr, int) = null; Diagnostic(ErrorCode.ERR_ValueCantBeNull, "null").WithArguments("int") ); } [Fact] public void RefValueTest03_Dynamic_Bind() { var text = @" using System; public struct C { static void Main() { dynamic i = 1; TypedReference tr = __makeref(i); Console.Write(i); Get(tr); Console.Write(i); Set(tr, 2); Console.Write(i); } static dynamic Get(TypedReference tr) { return __refvalue(tr, dynamic); } static void Set(TypedReference tr, dynamic i) { __refvalue(tr, dynamic) = i; } }"; CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics(); } [ClrOnlyFact(ClrOnlyReason.Ilasm)] public void RefValueTest04_optimizer() { var text = @" using System; public struct C { static void Main() { int k = 42; int i = 1; TypedReference tr1 = __makeref(i); __refvalue(tr1, int) = k; __refvalue(tr1, int) = k; int j = 1; TypedReference tr2 = __makeref(j); int l = 42; __refvalue(tr1, int) = l; __refvalue(tr2, int) = l; Console.Write(i); Console.Write(j); } }"; var verifier = CompileAndVerify(source: text, expectedOutput: "4242"); verifier.VerifyIL("C.Main", @" { // Code size 72 (0x48) .maxstack 3 .locals init (int V_0, //k int V_1, //i System.TypedReference V_2, //tr1 int V_3, //j int V_4) //l IL_0000: ldc.i4.s 42 IL_0002: stloc.0 IL_0003: ldc.i4.1 IL_0004: stloc.1 IL_0005: ldloca.s V_1 IL_0007: mkrefany ""int"" IL_000c: stloc.2 IL_000d: ldloc.2 IL_000e: refanyval ""int"" IL_0013: ldloc.0 IL_0014: stind.i4 IL_0015: ldloc.2 IL_0016: refanyval ""int"" IL_001b: ldloc.0 IL_001c: stind.i4 IL_001d: ldc.i4.1 IL_001e: stloc.3 IL_001f: ldloca.s V_3 IL_0021: mkrefany ""int"" IL_0026: ldc.i4.s 42 IL_0028: stloc.s V_4 IL_002a: ldloc.2 IL_002b: refanyval ""int"" IL_0030: ldloc.s V_4 IL_0032: stind.i4 IL_0033: refanyval ""int"" IL_0038: ldloc.s V_4 IL_003a: stind.i4 IL_003b: ldloc.1 IL_003c: call ""void System.Console.Write(int)"" IL_0041: ldloc.3 IL_0042: call ""void System.Console.Write(int)"" IL_0047: ret } "); } [Fact] public void TestBug13263() { var text = @"public class C { public void M() { var t = __makeref(delegate); } }"; var tree = Parse(text); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var root = tree.GetCompilationUnitRoot(); var clss = root.Members[0] as ClassDeclarationSyntax; var meth = clss.Members[0] as MethodDeclarationSyntax; var stmt = meth.Body.Statements[0] as LocalDeclarationStatementSyntax; var type = stmt.Declaration.Type; var info = model.GetSymbolInfo(type); Assert.Equal("TypedReference", info.Symbol.Name); } [WorkItem(545055, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545055")] [WorkItem(545056, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545056")] [Fact] public void MethodArgListParameterCount() { var text = @" class A { public void M1(__arglist) { } public void M2(int x, __arglist) { } public void M3(__arglist, int x) { } //illegal, but shouldn't break public void M4(__arglist, int x, __arglist) { } //illegal, but shouldn't break } "; var comp = CreateCompilation(text); var type = comp.GlobalNamespace.GetMember<NamedTypeSymbol>("A"); var m1 = type.GetMember<MethodSymbol>("M1"); Assert.Equal(0, m1.ParameterCount); Assert.Equal(0, m1.Parameters.Length); var m2 = type.GetMember<MethodSymbol>("M2"); Assert.Equal(1, m2.ParameterCount); Assert.Equal(1, m2.Parameters.Length); var m3 = type.GetMember<MethodSymbol>("M3"); Assert.Equal(1, m3.ParameterCount); Assert.Equal(1, m3.Parameters.Length); var m4 = type.GetMember<MethodSymbol>("M4"); Assert.Equal(1, m4.ParameterCount); Assert.Equal(1, m4.Parameters.Length); } [WorkItem(545055, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545055")] [WorkItem(545056, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545056")] [Fact] public void ILMethodArgListParameterCount() { var csharp = @" class Unused { } "; var il = @" .class public auto ansi beforefieldinit A extends [mscorlib]System.Object { .method public hidebysig instance vararg void M1() cil managed { ret } .method public hidebysig instance vararg void M2(int32 x) cil managed { ret } .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } } // end of class A "; var comp = CreateCompilationWithILAndMscorlib40(csharp, il); var type = comp.GlobalNamespace.GetMember<NamedTypeSymbol>("A"); var m1 = type.GetMember<MethodSymbol>("M1"); Assert.Equal(0, m1.ParameterCount); Assert.Equal(0, m1.Parameters.Length); var m2 = type.GetMember<MethodSymbol>("M2"); Assert.Equal(1, m2.ParameterCount); Assert.Equal(1, m2.Parameters.Length); } [WorkItem(545055, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545055")] [WorkItem(545056, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545056")] [Fact] public void OperatorArgListParameterCount() { var text = @" class A { public int operator +(__arglist) { return 0; } //illegal, but shouldn't break public int operator -(A a, __arglist) { return 0; } //illegal, but shouldn't break public int operator *(__arglist, A a) { return 0; } //illegal, but shouldn't break public int operator /(__arglist, A a, __arglist) { return 0; } //illegal, but shouldn't break } "; var comp = CreateCompilation(text); var type = comp.GlobalNamespace.GetMember<NamedTypeSymbol>("A"); var m1 = type.GetMember<MethodSymbol>(WellKnownMemberNames.UnaryPlusOperatorName); Assert.Equal(0, m1.ParameterCount); Assert.Equal(0, m1.Parameters.Length); var m2 = type.GetMember<MethodSymbol>(WellKnownMemberNames.SubtractionOperatorName); Assert.Equal(1, m2.ParameterCount); Assert.Equal(1, m2.Parameters.Length); var m3 = type.GetMember<MethodSymbol>(WellKnownMemberNames.MultiplyOperatorName); Assert.Equal(1, m3.ParameterCount); Assert.Equal(1, m3.Parameters.Length); var m4 = type.GetMember<MethodSymbol>(WellKnownMemberNames.DivisionOperatorName); Assert.Equal(1, m4.ParameterCount); Assert.Equal(1, m4.Parameters.Length); } [WorkItem(545055, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545055")] [WorkItem(545056, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545056")] [Fact] public void ConversionArgListParameterCount1() { var text = @" class A { public explicit operator A(__arglist) { return null; } //illegal, but shouldn't break } "; var comp = CreateCompilation(text); var type = comp.GlobalNamespace.GetMember<NamedTypeSymbol>("A"); var conversion = type.GetMember<MethodSymbol>(WellKnownMemberNames.ExplicitConversionName); Assert.Equal(0, conversion.ParameterCount); Assert.Equal(0, conversion.Parameters.Length); } [WorkItem(545055, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545055")] [WorkItem(545056, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545056")] [Fact] public void ConversionArgListParameterCount2() { var text = @" class A { public explicit operator A(int x, __arglist) { return null; } //illegal, but shouldn't break } "; var comp = CreateCompilation(text); var type = comp.GlobalNamespace.GetMember<NamedTypeSymbol>("A"); var conversion = type.GetMember<MethodSymbol>(WellKnownMemberNames.ExplicitConversionName); Assert.Equal(1, conversion.ParameterCount); Assert.Equal(1, conversion.Parameters.Length); } [WorkItem(545055, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545055")] [WorkItem(545056, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545056")] [Fact] public void ConversionArgListParameterCount3() { var text = @" class A { public explicit operator A(__arglist, A a) { return null; } //illegal, but shouldn't break } "; var comp = CreateCompilation(text); var type = comp.GlobalNamespace.GetMember<NamedTypeSymbol>("A"); var conversion = type.GetMember<MethodSymbol>(WellKnownMemberNames.ExplicitConversionName); Assert.Equal(1, conversion.ParameterCount); Assert.Equal(1, conversion.Parameters.Length); } [WorkItem(545055, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545055")] [WorkItem(545056, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545056")] [Fact] public void ConversionArgListParameterCount4() { var text = @" class A { public explicit operator A(__arglist, A a, __arglist) { return null; } //illegal, but shouldn't break } "; var comp = CreateCompilation(text); var type = comp.GlobalNamespace.GetMember<NamedTypeSymbol>("A"); var conversion = type.GetMember<MethodSymbol>(WellKnownMemberNames.ExplicitConversionName); Assert.Equal(1, conversion.ParameterCount); Assert.Equal(1, conversion.Parameters.Length); } [WorkItem(545055, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545055")] [WorkItem(545056, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545056")] [Fact] public void ConstructorArgListParameterCount1() { var text = @" class A { public A(__arglist) { } } "; var comp = CreateCompilation(text); var constructor = comp.GlobalNamespace.GetMember<NamedTypeSymbol>("A").GetMember<MethodSymbol>(WellKnownMemberNames.InstanceConstructorName); Assert.Equal(0, constructor.ParameterCount); //doesn't use syntax Assert.Equal(0, constructor.Parameters.Length); } [WorkItem(545055, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545055")] [WorkItem(545056, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545056")] [Fact] public void ConstructorArgListParameterCount2() { var text = @" class A { public A(int x, __arglist) { } } "; var comp = CreateCompilation(text); var constructor = comp.GlobalNamespace.GetMember<NamedTypeSymbol>("A").GetMember<MethodSymbol>(WellKnownMemberNames.InstanceConstructorName); Assert.Equal(1, constructor.ParameterCount); //doesn't use syntax Assert.Equal(1, constructor.Parameters.Length); } [WorkItem(545055, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545055")] [WorkItem(545056, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545056")] [Fact] public void ConstructorArgListParameterCount3() { var text = @" class A { public A(__arglist, int x) { } //illegal, but shouldn't break } "; var comp = CreateCompilation(text); var constructor = comp.GlobalNamespace.GetMember<NamedTypeSymbol>("A").GetMember<MethodSymbol>(WellKnownMemberNames.InstanceConstructorName); Assert.Equal(1, constructor.ParameterCount); //doesn't use syntax Assert.Equal(1, constructor.Parameters.Length); } [WorkItem(545055, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545055")] [WorkItem(545056, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545056")] [Fact] public void ConstructorArgListParameterCount4() { var text = @" class A { public A(__arglist, int x, __arglist) { } //illegal, but shouldn't break } "; var comp = CreateCompilation(text); var constructor = comp.GlobalNamespace.GetMember<NamedTypeSymbol>("A").GetMember<MethodSymbol>(WellKnownMemberNames.InstanceConstructorName); Assert.Equal(1, constructor.ParameterCount); //doesn't use syntax Assert.Equal(1, constructor.Parameters.Length); } [WorkItem(545055, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545055")] [WorkItem(545056, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545056")] [Fact] public void IndexerArgListParameterCount1() { var text = @" class A { public int this[__arglist] { get { return 0; } set { } } //illegal, but shouldn't break } "; var comp = CreateCompilation(text); var indexer = comp.GlobalNamespace.GetMember<NamedTypeSymbol>("A").GetMember<PropertySymbol>(WellKnownMemberNames.Indexer); Assert.Equal(0, indexer.ParameterCount); //doesn't use syntax Assert.Equal(0, indexer.Parameters.Length); var getter = indexer.GetMethod; Assert.Equal(0, getter.ParameterCount); Assert.Equal(0, getter.Parameters.Length); var setter = indexer.SetMethod; Assert.Equal(1, setter.ParameterCount); Assert.Equal(1, setter.Parameters.Length); } [WorkItem(545055, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545055")] [WorkItem(545056, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545056")] [Fact] public void IndexerArgListParameterCount2() { var text = @" class A { public int this[int x, __arglist] { get { return 0; } set { } } //illegal, but shouldn't break } "; var comp = CreateCompilation(text); var indexer = comp.GlobalNamespace.GetMember<NamedTypeSymbol>("A").GetMember<PropertySymbol>(WellKnownMemberNames.Indexer); Assert.Equal(1, indexer.ParameterCount); //doesn't use syntax Assert.Equal(1, indexer.Parameters.Length); var getter = indexer.GetMethod; Assert.Equal(1, getter.ParameterCount); Assert.Equal(1, getter.Parameters.Length); var setter = indexer.SetMethod; Assert.Equal(2, setter.ParameterCount); Assert.Equal(2, setter.Parameters.Length); } [WorkItem(545055, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545055")] [WorkItem(545056, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545056")] [Fact] public void IndexerArgListParameterCount3() { var text = @" class A { public int this[__arglist, int x] { get { return 0; } set { } } //illegal, but shouldn't break } "; var comp = CreateCompilation(text); var indexer = comp.GlobalNamespace.GetMember<NamedTypeSymbol>("A").GetMember<PropertySymbol>(WellKnownMemberNames.Indexer); Assert.Equal(1, indexer.ParameterCount); //doesn't use syntax Assert.Equal(1, indexer.Parameters.Length); var getter = indexer.GetMethod; Assert.Equal(1, getter.ParameterCount); Assert.Equal(1, getter.Parameters.Length); var setter = indexer.SetMethod; Assert.Equal(2, setter.ParameterCount); Assert.Equal(2, setter.Parameters.Length); } [WorkItem(545055, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545055")] [WorkItem(545056, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545056")] [Fact] public void IndexerArgListParameterCount4() { var text = @" class A { public int this[__arglist, int x, __arglist] { get { return 0; } set { } } //illegal, but shouldn't break } "; var comp = CreateCompilation(text); var indexer = comp.GlobalNamespace.GetMember<NamedTypeSymbol>("A").GetMember<PropertySymbol>(WellKnownMemberNames.Indexer); Assert.Equal(1, indexer.ParameterCount); //doesn't use syntax Assert.Equal(1, indexer.Parameters.Length); var getter = indexer.GetMethod; Assert.Equal(1, getter.ParameterCount); Assert.Equal(1, getter.Parameters.Length); var setter = indexer.SetMethod; Assert.Equal(2, setter.ParameterCount); Assert.Equal(2, setter.Parameters.Length); } [WorkItem(545086, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545086")] [ConditionalFact(typeof(DesktopOnly), Reason = ConditionalSkipReason.RestrictedTypesNeedDesktop)] public void BoxReceiverTest() { var text = @" using System; class C { static void Goo() { RuntimeArgumentHandle rah = default(RuntimeArgumentHandle); ArgIterator ai = default(ArgIterator); TypedReference tr = default(TypedReference); rah.GetType(); // not virtual ai.GetType(); // not virtual tr.GetType(); // not virtual rah.ToString(); // virtual, overridden on ValueType ai.ToString(); // virtual, overridden on ValueType tr.ToString(); // virtual, overridden on ValueType rah.GetHashCode(); // virtual, overridden on ValueType ai.GetHashCode(); // no error: virtual, overridden on ArgIterator tr.GetHashCode(); // no error: virtual, overridden on TypedReference } }"; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (11,9): error CS0029: Cannot implicitly convert type 'System.RuntimeArgumentHandle' to 'object' // rah.GetType(); // not virtual Diagnostic(ErrorCode.ERR_NoImplicitConv, "rah").WithArguments("System.RuntimeArgumentHandle", "object"), // (12,9): error CS0029: Cannot implicitly convert type 'System.ArgIterator' to 'object' // ai.GetType(); // not virtual Diagnostic(ErrorCode.ERR_NoImplicitConv, "ai").WithArguments("System.ArgIterator", "object"), // (13,9): error CS0029: Cannot implicitly convert type 'System.TypedReference' to 'object' // tr.GetType(); // not virtual Diagnostic(ErrorCode.ERR_NoImplicitConv, "tr").WithArguments("System.TypedReference", "object"), // (14,9): error CS0029: Cannot implicitly convert type 'System.RuntimeArgumentHandle' to 'System.ValueType' // rah.ToString(); // virtual, overridden on ValueType Diagnostic(ErrorCode.ERR_NoImplicitConv, "rah").WithArguments("System.RuntimeArgumentHandle", "System.ValueType"), // (15,9): error CS0029: Cannot implicitly convert type 'System.ArgIterator' to 'System.ValueType' // ai.ToString(); // virtual, overridden on ValueType Diagnostic(ErrorCode.ERR_NoImplicitConv, "ai").WithArguments("System.ArgIterator", "System.ValueType"), // (16,9): error CS0029: Cannot implicitly convert type 'System.TypedReference' to 'System.ValueType' // tr.ToString(); // virtual, overridden on ValueType Diagnostic(ErrorCode.ERR_NoImplicitConv, "tr").WithArguments("System.TypedReference", "System.ValueType"), // (17,9): error CS0029: Cannot implicitly convert type 'System.RuntimeArgumentHandle' to 'System.ValueType' // rah.GetHashCode(); // virtual, overridden on ValueType Diagnostic(ErrorCode.ERR_NoImplicitConv, "rah").WithArguments("System.RuntimeArgumentHandle", "System.ValueType") ); } [WorkItem(649808, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/649808")] [Fact] public void MissingArgumentsAndOptionalParameters_1() { var source = @"class A { internal A(object x, __arglist) { } internal static void M(object x, __arglist) { } } class B { internal B(object x = null, __arglist) { } internal static void M(object x = null, __arglist) { } } class C { internal C(object x, object y = null, __arglist) { } internal static void M(object x, object y = null, __arglist) { } } class D { internal D(object x = null, object y = null, __arglist) { } internal static void M(object x = null, object y = null, __arglist) { } } class E { static void M() { // No optional arguments. new A(__arglist()); new A(null, __arglist()); A.M(__arglist()); A.M(null, __arglist()); // One optional argument. new B(__arglist()); new B(null, __arglist()); B.M(__arglist()); B.M(null, __arglist()); // One required, one optional argument. new C(__arglist()); new C(null, __arglist()); new C(null, null, __arglist()); C.M(__arglist()); C.M(null, __arglist()); C.M(null, null, __arglist()); // Two optional arguments. new D(__arglist()); new D(null, __arglist()); new D(null, null, __arglist()); D.M(__arglist()); D.M(null, __arglist()); D.M(null, null, __arglist()); } }"; CreateCompilation(source).VerifyDiagnostics( // (26,13): error CS7036: There is no argument given that corresponds to the required formal parameter '__arglist' of 'A.A(object, __arglist)' // new A(__arglist()); Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "A").WithArguments("__arglist", "A.A(object, __arglist)").WithLocation(26, 13), // (28,9): error CS7036: There is no argument given that corresponds to the required formal parameter '__arglist' of 'A.M(object, __arglist)' // A.M(__arglist()); Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "M").WithArguments("__arglist", "A.M(object, __arglist)").WithLocation(28, 11), // (31,13): error CS7036: There is no argument given that corresponds to the required formal parameter '__arglist' of 'B.B(object, __arglist)' // new B(__arglist()); Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "B").WithArguments("__arglist", "B.B(object, __arglist)").WithLocation(31, 13), // (33,9): error CS7036: There is no argument given that corresponds to the required formal parameter '__arglist' of 'B.M(object, __arglist)' // B.M(__arglist()); Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "M").WithArguments("__arglist", "B.M(object, __arglist)").WithLocation(33, 11), // (36,13): error CS7036: There is no argument given that corresponds to the required formal parameter '__arglist' of 'C.C(object, object, __arglist)' // new C(__arglist()); Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "C").WithArguments("__arglist", "C.C(object, object, __arglist)").WithLocation(36, 13), // (37,13): error CS7036: There is no argument given that corresponds to the required formal parameter '__arglist' of 'C.C(object, object, __arglist)' // new C(null, __arglist()); Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "C").WithArguments("__arglist", "C.C(object, object, __arglist)").WithLocation(37, 13), // (39,9): error CS7036: There is no argument given that corresponds to the required formal parameter '__arglist' of 'C.M(object, object, __arglist)' // C.M(__arglist()); Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "M").WithArguments("__arglist", "C.M(object, object, __arglist)").WithLocation(39, 11), // (40,9): error CS7036: There is no argument given that corresponds to the required formal parameter '__arglist' of 'C.M(object, object, __arglist)' // C.M(null, __arglist()); Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "M").WithArguments("__arglist", "C.M(object, object, __arglist)").WithLocation(40, 11), // (43,13): error CS7036: There is no argument given that corresponds to the required formal parameter '__arglist' of 'D.D(object, object, __arglist)' // new D(__arglist()); Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "D").WithArguments("__arglist", "D.D(object, object, __arglist)").WithLocation(43, 13), // (44,13): error CS7036: There is no argument given that corresponds to the required formal parameter '__arglist' of 'D.D(object, object, __arglist)' // new D(null, __arglist()); Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "D").WithArguments("__arglist", "D.D(object, object, __arglist)").WithLocation(44, 13), // (46,9): error CS7036: There is no argument given that corresponds to the required formal parameter '__arglist' of 'D.M(object, object, __arglist)' // D.M(__arglist()); Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "M").WithArguments("__arglist", "D.M(object, object, __arglist)").WithLocation(46, 11), // (47,9): error CS7036: There is no argument given that corresponds to the required formal parameter '__arglist' of 'D.M(object, object, __arglist)' // D.M(null, __arglist()); Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "M").WithArguments("__arglist", "D.M(object, object, __arglist)").WithLocation(47, 11)); } [WorkItem(649808, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/649808")] [Fact] public void MissingArgumentsAndOptionalParameters_2() { var ilSource = @".class public sealed D extends [mscorlib]System.MulticastDelegate { .method public hidebysig specialname rtspecialname instance void .ctor(object o, native int m) runtime { } .method public hidebysig instance vararg void Invoke([opt] object o) runtime { } .method public hidebysig instance class [mscorlib]System.IAsyncResult BeginInvoke(class [mscorlib]System.AsyncCallback c, object o) runtime { } .method public hidebysig instance void EndInvoke(class [mscorlib]System.IAsyncResult r) runtime { } }"; var source = @"class C { static void M(D d) { d(null, __arglist()); d(__arglist()); } }"; var compilation = CreateCompilationWithILAndMscorlib40(source, ilSource); compilation.VerifyDiagnostics( // (6,9): error CS7036: There is no argument given that corresponds to the required formal parameter '__arglist' of 'D' // d(__arglist()); Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "d").WithArguments("__arglist", "D").WithLocation(6, 9)); } [Fact, WorkItem(1253, "https://github.com/dotnet/roslyn/issues/1253")] public void LambdaWithUnsafeParameter() { var source = @" using System; using System.Threading; namespace ConsoleApplication21 { public unsafe class GooBar : IDisposable { public void Dispose() { NativeOverlapped* overlapped = AllocateNativeOverlapped(() => { }); } private unsafe static NativeOverlapped* AllocateNativeOverlapped(IOCompletionCallback callback, object context, byte[] pinData) { return null; } } } "; CreateCompilation(source, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (12,44): error CS7036: There is no argument given that corresponds to the required formal parameter 'context' of 'GooBar.AllocateNativeOverlapped(IOCompletionCallback, object, byte[])' // NativeOverlapped* overlapped = AllocateNativeOverlapped(() => { }); Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "AllocateNativeOverlapped").WithArguments("context", "ConsoleApplication21.GooBar.AllocateNativeOverlapped(System.Threading.IOCompletionCallback, object, byte[])").WithLocation(12, 44) ); } [Fact, WorkItem(8152, "https://github.com/dotnet/roslyn/issues/8152")] public void DuplicateDeclaration() { var source = @" public class SpecialCases { public void ArgListMethod(__arglist) { ArgListMethod(__arglist("""")); } public void ArgListMethod(__arglist) { ArgListMethod(__arglist("""")); } } "; CreateCompilation(source, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (8,17): error CS0111: Type 'SpecialCases' already defines a member called 'ArgListMethod' with the same parameter types // public void ArgListMethod(__arglist) Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "ArgListMethod").WithArguments("ArgListMethod", "SpecialCases").WithLocation(8, 17), // (6,9): error CS0121: The call is ambiguous between the following methods or properties: 'SpecialCases.ArgListMethod(__arglist)' and 'SpecialCases.ArgListMethod(__arglist)' // ArgListMethod(__arglist("")); Diagnostic(ErrorCode.ERR_AmbigCall, "ArgListMethod").WithArguments("SpecialCases.ArgListMethod(__arglist)", "SpecialCases.ArgListMethod(__arglist)").WithLocation(6, 9), // (10,9): error CS0121: The call is ambiguous between the following methods or properties: 'SpecialCases.ArgListMethod(__arglist)' and 'SpecialCases.ArgListMethod(__arglist)' // ArgListMethod(__arglist("")); Diagnostic(ErrorCode.ERR_AmbigCall, "ArgListMethod").WithArguments("SpecialCases.ArgListMethod(__arglist)", "SpecialCases.ArgListMethod(__arglist)").WithLocation(10, 9) ); } [ConditionalFact(typeof(DesktopOnly), Reason = ConditionalSkipReason.RestrictedTypesNeedDesktop)] public void ArgListMayNotHaveAnOutArgument() { CreateCompilation(@" class Program { static void Test(__arglist) { var a = 1; Test(__arglist(out a)); } } ").VerifyDiagnostics( // (7,25): error CS8378: __arglist cannot have an argument passed by 'in' or 'out' // Test(__arglist(out a)); Diagnostic(ErrorCode.ERR_CantUseInOrOutInArglist, "a").WithLocation(7, 25)); } [Fact] public void ArgListMayNotHaveAnInArgument() { CreateCompilation(@" class Program { static void Test(__arglist) { var a = 1; Test(__arglist(in a)); } } ").VerifyDiagnostics( // (7,24): error CS8378: __arglist cannot have an argument passed by 'in' or 'out' // Test(__arglist(in a)); Diagnostic(ErrorCode.ERR_CantUseInOrOutInArglist, "a").WithLocation(7, 24)); } [ConditionalFact(typeof(WindowsDesktopOnly), Reason = ConditionalSkipReason.RestrictedTypesNeedDesktop)] public void ArgListMayHaveARefArgument() { CompileAndVerify(@" using System; class Program { static void Test(__arglist) { var args = new ArgIterator(__arglist); ref int a = ref __refvalue(args.GetNextArg(), int); a = 5; } static void Main() { int a = 0; Test(__arglist(ref a)); Console.WriteLine(a); } }", options: TestOptions.DebugExe, expectedOutput: "5"); } [ConditionalFact(typeof(DesktopOnly), Reason = ConditionalSkipReason.RestrictedTypesNeedDesktop)] public void ArgListMayHaveAByValArgument() { CompileAndVerify(@" using System; class Program { static void Test(__arglist) { var args = new ArgIterator(__arglist); int a = __refvalue(args.GetNextArg(), int); Console.WriteLine(a); } static void Main() { int a = 5; Test(__arglist(a)); } }", options: TestOptions.DebugExe, expectedOutput: "5"); } } }
-1
dotnet/roslyn
55,262
Fix LSP completions when all items have default commit characters
Fixes an exception stack trace seen in https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1362284 Also fixes behavior of promotion of commit characters to the list to include default commit characters
dibarbet
2021-07-30T02:43:35Z
2021-07-30T21:21:47Z
2f7dffa534aceb92e9767568e88535c926588d12
65ee073bf6cea571a68193793420ecee60752711
Fix LSP completions when all items have default commit characters. Fixes an exception stack trace seen in https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1362284 Also fixes behavior of promotion of commit characters to the list to include default commit characters
./src/EditorFeatures/TestUtilities/Structure/AbstractSyntaxTriviaStructureProviderTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Shared.Collections; using Microsoft.CodeAnalysis.Structure; namespace Microsoft.CodeAnalysis.Editor.UnitTests.Structure { public abstract class AbstractSyntaxTriviaStructureProviderTests : AbstractSyntaxStructureProviderTests { internal abstract AbstractSyntaxStructureProvider CreateProvider(); internal sealed override async Task<ImmutableArray<BlockSpan>> GetBlockSpansWorkerAsync(Document document, int position) { var root = await document.GetSyntaxRootAsync(); var trivia = root.FindTrivia(position, findInsideTrivia: true); var outliner = CreateProvider(); using var actualRegions = TemporaryArray<BlockSpan>.Empty; var optionProvider = new BlockStructureOptionProvider( document.Project.Solution.Options, isMetadataAsSource: document.Project.Solution.Workspace.Kind == CodeAnalysis.WorkspaceKind.MetadataAsSource); outliner.CollectBlockSpans(trivia, ref actualRegions.AsRef(), optionProvider, CancellationToken.None); // TODO: Determine why we get null outlining spans. return actualRegions.ToImmutableAndClear(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Shared.Collections; using Microsoft.CodeAnalysis.Structure; namespace Microsoft.CodeAnalysis.Editor.UnitTests.Structure { public abstract class AbstractSyntaxTriviaStructureProviderTests : AbstractSyntaxStructureProviderTests { internal abstract AbstractSyntaxStructureProvider CreateProvider(); internal sealed override async Task<ImmutableArray<BlockSpan>> GetBlockSpansWorkerAsync(Document document, int position) { var root = await document.GetSyntaxRootAsync(); var trivia = root.FindTrivia(position, findInsideTrivia: true); var outliner = CreateProvider(); using var actualRegions = TemporaryArray<BlockSpan>.Empty; var optionProvider = new BlockStructureOptionProvider( document.Project.Solution.Options, isMetadataAsSource: document.Project.Solution.Workspace.Kind == CodeAnalysis.WorkspaceKind.MetadataAsSource); outliner.CollectBlockSpans(trivia, ref actualRegions.AsRef(), optionProvider, CancellationToken.None); // TODO: Determine why we get null outlining spans. return actualRegions.ToImmutableAndClear(); } } }
-1
dotnet/roslyn
55,262
Fix LSP completions when all items have default commit characters
Fixes an exception stack trace seen in https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1362284 Also fixes behavior of promotion of commit characters to the list to include default commit characters
dibarbet
2021-07-30T02:43:35Z
2021-07-30T21:21:47Z
2f7dffa534aceb92e9767568e88535c926588d12
65ee073bf6cea571a68193793420ecee60752711
Fix LSP completions when all items have default commit characters. Fixes an exception stack trace seen in https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1362284 Also fixes behavior of promotion of commit characters to the list to include default commit characters
./src/Compilers/CSharp/Portable/BoundTree/NullabilityRewriter.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Diagnostics; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { internal sealed partial class NullabilityRewriter : BoundTreeRewriter { protected override BoundExpression? VisitExpressionWithoutStackGuard(BoundExpression node) { return (BoundExpression)Visit(node); } public override BoundNode? VisitBinaryOperator(BoundBinaryOperator node) { return VisitBinaryOperatorBase(node); } public override BoundNode? VisitUserDefinedConditionalLogicalOperator(BoundUserDefinedConditionalLogicalOperator node) { return VisitBinaryOperatorBase(node); } private BoundNode VisitBinaryOperatorBase(BoundBinaryOperatorBase binaryOperator) { // Use an explicit stack to avoid blowing the managed stack when visiting deeply-recursive // binary nodes var stack = ArrayBuilder<BoundBinaryOperatorBase>.GetInstance(); BoundBinaryOperatorBase? currentBinary = binaryOperator; do { stack.Push(currentBinary); currentBinary = currentBinary.Left as BoundBinaryOperatorBase; } while (currentBinary is not null); Debug.Assert(stack.Count > 0); var leftChild = (BoundExpression)Visit(stack.Peek().Left); do { currentBinary = stack.Pop(); bool foundInfo = _updatedNullabilities.TryGetValue(currentBinary, out (NullabilityInfo Info, TypeSymbol? Type) infoAndType); var right = (BoundExpression)Visit(currentBinary.Right); var type = foundInfo ? infoAndType.Type : currentBinary.Type; currentBinary = currentBinary switch { BoundBinaryOperator binary => binary.Update( binary.OperatorKind, binary.Data?.WithUpdatedMethod(GetUpdatedSymbol(binary, binary.Method)), binary.ResultKind, leftChild, right, type!), // https://github.com/dotnet/roslyn/issues/35031: We'll need to update logical.LogicalOperator BoundUserDefinedConditionalLogicalOperator logical => logical.Update(logical.OperatorKind, logical.LogicalOperator, logical.TrueOperator, logical.FalseOperator, logical.ConstrainedToTypeOpt, logical.ResultKind, logical.OriginalUserDefinedOperatorsOpt, leftChild, right, type!), _ => throw ExceptionUtilities.UnexpectedValue(currentBinary.Kind), }; if (foundInfo) { currentBinary.TopLevelNullability = infoAndType.Info; } leftChild = currentBinary; } while (stack.Count > 0); Debug.Assert(currentBinary != null); return currentBinary!; } private T GetUpdatedSymbol<T>(BoundNode expr, T sym) where T : Symbol? { if (sym is null) return sym; Symbol? updatedSymbol = null; if (_snapshotManager?.TryGetUpdatedSymbol(expr, sym, out updatedSymbol) != true) { updatedSymbol = sym; } RoslynDebug.Assert(updatedSymbol is object); switch (updatedSymbol) { case LambdaSymbol lambda: return (T)remapLambda((BoundLambda)expr, lambda); case SourceLocalSymbol local: return (T)remapLocal(local); case ParameterSymbol param: if (_remappedSymbols.TryGetValue(param, out var updatedParam)) { return (T)updatedParam; } break; } return (T)updatedSymbol; Symbol remapLambda(BoundLambda boundLambda, LambdaSymbol lambda) { var updatedDelegateType = _snapshotManager?.GetUpdatedDelegateTypeForLambda(lambda); if (!_remappedSymbols.TryGetValue(lambda.ContainingSymbol, out Symbol? updatedContaining) && updatedDelegateType is null) { return lambda; } LambdaSymbol updatedLambda; if (updatedDelegateType is null) { Debug.Assert(updatedContaining is object); updatedLambda = boundLambda.CreateLambdaSymbol(updatedContaining, lambda.ReturnTypeWithAnnotations, lambda.ParameterTypesWithAnnotations, lambda.ParameterRefKinds, lambda.RefKind); } else { Debug.Assert(updatedDelegateType is object); updatedLambda = boundLambda.CreateLambdaSymbol(updatedDelegateType, updatedContaining ?? lambda.ContainingSymbol); } _remappedSymbols.Add(lambda, updatedLambda); Debug.Assert(lambda.ParameterCount == updatedLambda.ParameterCount); for (int i = 0; i < lambda.ParameterCount; i++) { _remappedSymbols.Add(lambda.Parameters[i], updatedLambda.Parameters[i]); } return updatedLambda; } Symbol remapLocal(SourceLocalSymbol local) { if (_remappedSymbols.TryGetValue(local, out var updatedLocal)) { return updatedLocal; } var updatedType = _snapshotManager?.GetUpdatedTypeForLocalSymbol(local); if (!_remappedSymbols.TryGetValue(local.ContainingSymbol, out Symbol? updatedContaining) && !updatedType.HasValue) { // Map the local to itself so we don't have to search again in the future _remappedSymbols.Add(local, local); return local; } updatedLocal = new UpdatedContainingSymbolAndNullableAnnotationLocal(local, updatedContaining ?? local.ContainingSymbol, updatedType ?? local.TypeWithAnnotations); _remappedSymbols.Add(local, updatedLocal); return updatedLocal; } } private ImmutableArray<T> GetUpdatedArray<T>(BoundNode expr, ImmutableArray<T> symbols) where T : Symbol? { if (symbols.IsDefaultOrEmpty) { return symbols; } var builder = ArrayBuilder<T>.GetInstance(symbols.Length); bool foundUpdate = false; foreach (var originalSymbol in symbols) { T updatedSymbol = null!; if (originalSymbol is object) { updatedSymbol = GetUpdatedSymbol(expr, originalSymbol); Debug.Assert(updatedSymbol is object); if ((object)originalSymbol != updatedSymbol) { foundUpdate = true; } } builder.Add(updatedSymbol); } if (foundUpdate) { return builder.ToImmutableAndFree(); } else { builder.Free(); return symbols; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Diagnostics; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { internal sealed partial class NullabilityRewriter : BoundTreeRewriter { protected override BoundExpression? VisitExpressionWithoutStackGuard(BoundExpression node) { return (BoundExpression)Visit(node); } public override BoundNode? VisitBinaryOperator(BoundBinaryOperator node) { return VisitBinaryOperatorBase(node); } public override BoundNode? VisitUserDefinedConditionalLogicalOperator(BoundUserDefinedConditionalLogicalOperator node) { return VisitBinaryOperatorBase(node); } private BoundNode VisitBinaryOperatorBase(BoundBinaryOperatorBase binaryOperator) { // Use an explicit stack to avoid blowing the managed stack when visiting deeply-recursive // binary nodes var stack = ArrayBuilder<BoundBinaryOperatorBase>.GetInstance(); BoundBinaryOperatorBase? currentBinary = binaryOperator; do { stack.Push(currentBinary); currentBinary = currentBinary.Left as BoundBinaryOperatorBase; } while (currentBinary is not null); Debug.Assert(stack.Count > 0); var leftChild = (BoundExpression)Visit(stack.Peek().Left); do { currentBinary = stack.Pop(); bool foundInfo = _updatedNullabilities.TryGetValue(currentBinary, out (NullabilityInfo Info, TypeSymbol? Type) infoAndType); var right = (BoundExpression)Visit(currentBinary.Right); var type = foundInfo ? infoAndType.Type : currentBinary.Type; currentBinary = currentBinary switch { BoundBinaryOperator binary => binary.Update( binary.OperatorKind, binary.Data?.WithUpdatedMethod(GetUpdatedSymbol(binary, binary.Method)), binary.ResultKind, leftChild, right, type!), // https://github.com/dotnet/roslyn/issues/35031: We'll need to update logical.LogicalOperator BoundUserDefinedConditionalLogicalOperator logical => logical.Update(logical.OperatorKind, logical.LogicalOperator, logical.TrueOperator, logical.FalseOperator, logical.ConstrainedToTypeOpt, logical.ResultKind, logical.OriginalUserDefinedOperatorsOpt, leftChild, right, type!), _ => throw ExceptionUtilities.UnexpectedValue(currentBinary.Kind), }; if (foundInfo) { currentBinary.TopLevelNullability = infoAndType.Info; } leftChild = currentBinary; } while (stack.Count > 0); Debug.Assert(currentBinary != null); return currentBinary!; } private T GetUpdatedSymbol<T>(BoundNode expr, T sym) where T : Symbol? { if (sym is null) return sym; Symbol? updatedSymbol = null; if (_snapshotManager?.TryGetUpdatedSymbol(expr, sym, out updatedSymbol) != true) { updatedSymbol = sym; } RoslynDebug.Assert(updatedSymbol is object); switch (updatedSymbol) { case LambdaSymbol lambda: return (T)remapLambda((BoundLambda)expr, lambda); case SourceLocalSymbol local: return (T)remapLocal(local); case ParameterSymbol param: if (_remappedSymbols.TryGetValue(param, out var updatedParam)) { return (T)updatedParam; } break; } return (T)updatedSymbol; Symbol remapLambda(BoundLambda boundLambda, LambdaSymbol lambda) { var updatedDelegateType = _snapshotManager?.GetUpdatedDelegateTypeForLambda(lambda); if (!_remappedSymbols.TryGetValue(lambda.ContainingSymbol, out Symbol? updatedContaining) && updatedDelegateType is null) { return lambda; } LambdaSymbol updatedLambda; if (updatedDelegateType is null) { Debug.Assert(updatedContaining is object); updatedLambda = boundLambda.CreateLambdaSymbol(updatedContaining, lambda.ReturnTypeWithAnnotations, lambda.ParameterTypesWithAnnotations, lambda.ParameterRefKinds, lambda.RefKind); } else { Debug.Assert(updatedDelegateType is object); updatedLambda = boundLambda.CreateLambdaSymbol(updatedDelegateType, updatedContaining ?? lambda.ContainingSymbol); } _remappedSymbols.Add(lambda, updatedLambda); Debug.Assert(lambda.ParameterCount == updatedLambda.ParameterCount); for (int i = 0; i < lambda.ParameterCount; i++) { _remappedSymbols.Add(lambda.Parameters[i], updatedLambda.Parameters[i]); } return updatedLambda; } Symbol remapLocal(SourceLocalSymbol local) { if (_remappedSymbols.TryGetValue(local, out var updatedLocal)) { return updatedLocal; } var updatedType = _snapshotManager?.GetUpdatedTypeForLocalSymbol(local); if (!_remappedSymbols.TryGetValue(local.ContainingSymbol, out Symbol? updatedContaining) && !updatedType.HasValue) { // Map the local to itself so we don't have to search again in the future _remappedSymbols.Add(local, local); return local; } updatedLocal = new UpdatedContainingSymbolAndNullableAnnotationLocal(local, updatedContaining ?? local.ContainingSymbol, updatedType ?? local.TypeWithAnnotations); _remappedSymbols.Add(local, updatedLocal); return updatedLocal; } } private ImmutableArray<T> GetUpdatedArray<T>(BoundNode expr, ImmutableArray<T> symbols) where T : Symbol? { if (symbols.IsDefaultOrEmpty) { return symbols; } var builder = ArrayBuilder<T>.GetInstance(symbols.Length); bool foundUpdate = false; foreach (var originalSymbol in symbols) { T updatedSymbol = null!; if (originalSymbol is object) { updatedSymbol = GetUpdatedSymbol(expr, originalSymbol); Debug.Assert(updatedSymbol is object); if ((object)originalSymbol != updatedSymbol) { foundUpdate = true; } } builder.Add(updatedSymbol); } if (foundUpdate) { return builder.ToImmutableAndFree(); } else { builder.Free(); return symbols; } } } }
-1
dotnet/roslyn
55,262
Fix LSP completions when all items have default commit characters
Fixes an exception stack trace seen in https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1362284 Also fixes behavior of promotion of commit characters to the list to include default commit characters
dibarbet
2021-07-30T02:43:35Z
2021-07-30T21:21:47Z
2f7dffa534aceb92e9767568e88535c926588d12
65ee073bf6cea571a68193793420ecee60752711
Fix LSP completions when all items have default commit characters. Fixes an exception stack trace seen in https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1362284 Also fixes behavior of promotion of commit characters to the list to include default commit characters
./src/Compilers/CSharp/Portable/Symbols/Synthesized/Records/SynthesizedRecordEqualityContractProperty.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using Microsoft.CodeAnalysis.CSharp.Syntax; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols { internal sealed class SynthesizedRecordEqualityContractProperty : SourcePropertySymbolBase { internal const string PropertyName = "EqualityContract"; public SynthesizedRecordEqualityContractProperty(SourceMemberContainerTypeSymbol containingType, BindingDiagnosticBag diagnostics) : base( containingType, syntax: (CSharpSyntaxNode)containingType.SyntaxReferences[0].GetSyntax(), hasGetAccessor: true, hasSetAccessor: false, isExplicitInterfaceImplementation: false, explicitInterfaceType: null, aliasQualifierOpt: null, modifiers: (containingType.IsSealed, containingType.BaseTypeNoUseSiteDiagnostics.IsObjectType()) switch { (true, true) => DeclarationModifiers.Private, (false, true) => DeclarationModifiers.Protected | DeclarationModifiers.Virtual, (_, false) => DeclarationModifiers.Protected | DeclarationModifiers.Override }, hasInitializer: false, isAutoProperty: false, isExpressionBodied: false, isInitOnly: false, RefKind.None, PropertyName, indexerNameAttributeLists: new SyntaxList<AttributeListSyntax>(), containingType.Locations[0], diagnostics) { } public override bool IsImplicitlyDeclared => true; public override ImmutableArray<SyntaxReference> DeclaringSyntaxReferences => ImmutableArray<SyntaxReference>.Empty; public override SyntaxList<AttributeListSyntax> AttributeDeclarationSyntaxList => new SyntaxList<AttributeListSyntax>(); public override IAttributeTargetSymbol AttributesOwner => this; protected override Location TypeLocation => ContainingType.Locations[0]; protected override SourcePropertyAccessorSymbol CreateGetAccessorSymbol(bool isAutoPropertyAccessor, BindingDiagnosticBag diagnostics) { return SourcePropertyAccessorSymbol.CreateAccessorSymbol( ContainingType, this, _modifiers, ContainingType.Locations[0], (CSharpSyntaxNode)((SourceMemberContainerTypeSymbol)ContainingType).SyntaxReferences[0].GetSyntax(), diagnostics); } protected override SourcePropertyAccessorSymbol CreateSetAccessorSymbol(bool isAutoPropertyAccessor, BindingDiagnosticBag diagnostics) { throw ExceptionUtilities.Unreachable; } protected override (TypeWithAnnotations Type, ImmutableArray<ParameterSymbol> Parameters) MakeParametersAndBindType(BindingDiagnosticBag diagnostics) { return (TypeWithAnnotations.Create(Binder.GetWellKnownType(DeclaringCompilation, WellKnownType.System_Type, diagnostics, Location), NullableAnnotation.NotAnnotated), ImmutableArray<ParameterSymbol>.Empty); } protected override bool HasPointerTypeSyntactically => false; protected override void ValidatePropertyType(BindingDiagnosticBag diagnostics) { base.ValidatePropertyType(diagnostics); VerifyOverridesEqualityContractFromBase(this, diagnostics); } internal static void VerifyOverridesEqualityContractFromBase(PropertySymbol overriding, BindingDiagnosticBag diagnostics) { if (overriding.ContainingType.BaseTypeNoUseSiteDiagnostics.IsObjectType()) { return; } bool reportAnError = false; if (!overriding.IsOverride) { reportAnError = true; } else { var overridden = overriding.OverriddenProperty; if (overridden is object && !overridden.ContainingType.Equals(overriding.ContainingType.BaseTypeNoUseSiteDiagnostics, TypeCompareKind.AllIgnoreOptions)) { reportAnError = true; } } if (reportAnError) { diagnostics.Add(ErrorCode.ERR_DoesNotOverrideBaseEqualityContract, overriding.Locations[0], overriding, overriding.ContainingType.BaseTypeNoUseSiteDiagnostics); } } internal sealed class GetAccessorSymbol : SourcePropertyAccessorSymbol { internal GetAccessorSymbol( NamedTypeSymbol containingType, SourcePropertySymbolBase property, DeclarationModifiers propertyModifiers, Location location, CSharpSyntaxNode syntax, BindingDiagnosticBag diagnostics) : base( containingType, property, propertyModifiers, location, syntax, hasBody: false, hasExpressionBody: false, isIterator: false, modifiers: new SyntaxTokenList(), MethodKind.PropertyGet, usesInit: false, isAutoPropertyAccessor: true, isNullableAnalysisEnabled: false, diagnostics) { } public override ImmutableArray<SyntaxReference> DeclaringSyntaxReferences => ImmutableArray<SyntaxReference>.Empty; internal override bool SynthesizesLoweredBoundBody => true; internal override void GenerateMethodBody(TypeCompilationState compilationState, BindingDiagnosticBag diagnostics) { var F = new SyntheticBoundNodeFactory(this, this.GetNonNullSyntaxNode(), compilationState, diagnostics); try { F.CurrentFunction = this; F.CloseMethod(F.Block(F.Return(F.Typeof(ContainingType)))); } catch (SyntheticBoundNodeFactory.MissingPredefinedMember ex) { diagnostics.Add(ex.Diagnostic); F.CloseMethod(F.ThrowNull()); } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using Microsoft.CodeAnalysis.CSharp.Syntax; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols { internal sealed class SynthesizedRecordEqualityContractProperty : SourcePropertySymbolBase { internal const string PropertyName = "EqualityContract"; public SynthesizedRecordEqualityContractProperty(SourceMemberContainerTypeSymbol containingType, BindingDiagnosticBag diagnostics) : base( containingType, syntax: (CSharpSyntaxNode)containingType.SyntaxReferences[0].GetSyntax(), hasGetAccessor: true, hasSetAccessor: false, isExplicitInterfaceImplementation: false, explicitInterfaceType: null, aliasQualifierOpt: null, modifiers: (containingType.IsSealed, containingType.BaseTypeNoUseSiteDiagnostics.IsObjectType()) switch { (true, true) => DeclarationModifiers.Private, (false, true) => DeclarationModifiers.Protected | DeclarationModifiers.Virtual, (_, false) => DeclarationModifiers.Protected | DeclarationModifiers.Override }, hasInitializer: false, isAutoProperty: false, isExpressionBodied: false, isInitOnly: false, RefKind.None, PropertyName, indexerNameAttributeLists: new SyntaxList<AttributeListSyntax>(), containingType.Locations[0], diagnostics) { } public override bool IsImplicitlyDeclared => true; public override ImmutableArray<SyntaxReference> DeclaringSyntaxReferences => ImmutableArray<SyntaxReference>.Empty; public override SyntaxList<AttributeListSyntax> AttributeDeclarationSyntaxList => new SyntaxList<AttributeListSyntax>(); public override IAttributeTargetSymbol AttributesOwner => this; protected override Location TypeLocation => ContainingType.Locations[0]; protected override SourcePropertyAccessorSymbol CreateGetAccessorSymbol(bool isAutoPropertyAccessor, BindingDiagnosticBag diagnostics) { return SourcePropertyAccessorSymbol.CreateAccessorSymbol( ContainingType, this, _modifiers, ContainingType.Locations[0], (CSharpSyntaxNode)((SourceMemberContainerTypeSymbol)ContainingType).SyntaxReferences[0].GetSyntax(), diagnostics); } protected override SourcePropertyAccessorSymbol CreateSetAccessorSymbol(bool isAutoPropertyAccessor, BindingDiagnosticBag diagnostics) { throw ExceptionUtilities.Unreachable; } protected override (TypeWithAnnotations Type, ImmutableArray<ParameterSymbol> Parameters) MakeParametersAndBindType(BindingDiagnosticBag diagnostics) { return (TypeWithAnnotations.Create(Binder.GetWellKnownType(DeclaringCompilation, WellKnownType.System_Type, diagnostics, Location), NullableAnnotation.NotAnnotated), ImmutableArray<ParameterSymbol>.Empty); } protected override bool HasPointerTypeSyntactically => false; protected override void ValidatePropertyType(BindingDiagnosticBag diagnostics) { base.ValidatePropertyType(diagnostics); VerifyOverridesEqualityContractFromBase(this, diagnostics); } internal static void VerifyOverridesEqualityContractFromBase(PropertySymbol overriding, BindingDiagnosticBag diagnostics) { if (overriding.ContainingType.BaseTypeNoUseSiteDiagnostics.IsObjectType()) { return; } bool reportAnError = false; if (!overriding.IsOverride) { reportAnError = true; } else { var overridden = overriding.OverriddenProperty; if (overridden is object && !overridden.ContainingType.Equals(overriding.ContainingType.BaseTypeNoUseSiteDiagnostics, TypeCompareKind.AllIgnoreOptions)) { reportAnError = true; } } if (reportAnError) { diagnostics.Add(ErrorCode.ERR_DoesNotOverrideBaseEqualityContract, overriding.Locations[0], overriding, overriding.ContainingType.BaseTypeNoUseSiteDiagnostics); } } internal sealed class GetAccessorSymbol : SourcePropertyAccessorSymbol { internal GetAccessorSymbol( NamedTypeSymbol containingType, SourcePropertySymbolBase property, DeclarationModifiers propertyModifiers, Location location, CSharpSyntaxNode syntax, BindingDiagnosticBag diagnostics) : base( containingType, property, propertyModifiers, location, syntax, hasBody: false, hasExpressionBody: false, isIterator: false, modifiers: new SyntaxTokenList(), MethodKind.PropertyGet, usesInit: false, isAutoPropertyAccessor: true, isNullableAnalysisEnabled: false, diagnostics) { } public override ImmutableArray<SyntaxReference> DeclaringSyntaxReferences => ImmutableArray<SyntaxReference>.Empty; internal override bool SynthesizesLoweredBoundBody => true; internal override void GenerateMethodBody(TypeCompilationState compilationState, BindingDiagnosticBag diagnostics) { var F = new SyntheticBoundNodeFactory(this, this.GetNonNullSyntaxNode(), compilationState, diagnostics); try { F.CurrentFunction = this; F.CloseMethod(F.Block(F.Return(F.Typeof(ContainingType)))); } catch (SyntheticBoundNodeFactory.MissingPredefinedMember ex) { diagnostics.Add(ex.Diagnostic); F.CloseMethod(F.ThrowNull()); } } } } }
-1
dotnet/roslyn
55,262
Fix LSP completions when all items have default commit characters
Fixes an exception stack trace seen in https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1362284 Also fixes behavior of promotion of commit characters to the list to include default commit characters
dibarbet
2021-07-30T02:43:35Z
2021-07-30T21:21:47Z
2f7dffa534aceb92e9767568e88535c926588d12
65ee073bf6cea571a68193793420ecee60752711
Fix LSP completions when all items have default commit characters. Fixes an exception stack trace seen in https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1362284 Also fixes behavior of promotion of commit characters to the list to include default commit characters
./src/Tools/AnalyzerRunner/PerformanceTracker.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Diagnostics; namespace AnalyzerRunner { internal sealed class PerformanceTracker { private readonly Stopwatch _stopwatch; #if NETCOREAPP private readonly long _initialTotalAllocatedBytes; #endif public PerformanceTracker(Stopwatch stopwatch, long initialTotalAllocatedBytes) { #if NETCOREAPP _initialTotalAllocatedBytes = initialTotalAllocatedBytes; #endif _stopwatch = stopwatch; } public static PerformanceTracker StartNew(bool preciseMemory = true) { #if NETCOREAPP var initialTotalAllocatedBytes = GC.GetTotalAllocatedBytes(preciseMemory); #else var initialTotalAllocatedBytes = 0L; #endif return new PerformanceTracker(Stopwatch.StartNew(), initialTotalAllocatedBytes); } public TimeSpan Elapsed => _stopwatch.Elapsed; #if NETCOREAPP public long AllocatedBytes => GC.GetTotalAllocatedBytes(true) - _initialTotalAllocatedBytes; #else public long AllocatedBytes => 0; #endif public string GetSummary(bool preciseMemory = true) { #if NETCOREAPP var elapsedTime = Elapsed; var allocatedBytes = GC.GetTotalAllocatedBytes(preciseMemory) - _initialTotalAllocatedBytes; return $"{elapsedTime.TotalMilliseconds:0}ms ({allocatedBytes} bytes allocated)"; #else return $"{Elapsed.TotalMilliseconds:0}ms"; #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 using System; using System.Diagnostics; namespace AnalyzerRunner { internal sealed class PerformanceTracker { private readonly Stopwatch _stopwatch; #if NETCOREAPP private readonly long _initialTotalAllocatedBytes; #endif public PerformanceTracker(Stopwatch stopwatch, long initialTotalAllocatedBytes) { #if NETCOREAPP _initialTotalAllocatedBytes = initialTotalAllocatedBytes; #endif _stopwatch = stopwatch; } public static PerformanceTracker StartNew(bool preciseMemory = true) { #if NETCOREAPP var initialTotalAllocatedBytes = GC.GetTotalAllocatedBytes(preciseMemory); #else var initialTotalAllocatedBytes = 0L; #endif return new PerformanceTracker(Stopwatch.StartNew(), initialTotalAllocatedBytes); } public TimeSpan Elapsed => _stopwatch.Elapsed; #if NETCOREAPP public long AllocatedBytes => GC.GetTotalAllocatedBytes(true) - _initialTotalAllocatedBytes; #else public long AllocatedBytes => 0; #endif public string GetSummary(bool preciseMemory = true) { #if NETCOREAPP var elapsedTime = Elapsed; var allocatedBytes = GC.GetTotalAllocatedBytes(preciseMemory) - _initialTotalAllocatedBytes; return $"{elapsedTime.TotalMilliseconds:0}ms ({allocatedBytes} bytes allocated)"; #else return $"{Elapsed.TotalMilliseconds:0}ms"; #endif } } }
-1
dotnet/roslyn
55,262
Fix LSP completions when all items have default commit characters
Fixes an exception stack trace seen in https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1362284 Also fixes behavior of promotion of commit characters to the list to include default commit characters
dibarbet
2021-07-30T02:43:35Z
2021-07-30T21:21:47Z
2f7dffa534aceb92e9767568e88535c926588d12
65ee073bf6cea571a68193793420ecee60752711
Fix LSP completions when all items have default commit characters. Fixes an exception stack trace seen in https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1362284 Also fixes behavior of promotion of commit characters to the list to include default commit characters
./src/Test/PdbUtilities/Reader/PdbValidation.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.IO; using System.Linq; using System.Reflection.Metadata; using System.Reflection.Metadata.Ecma335; using System.Reflection.PortableExecutable; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Security.Cryptography; using System.Text; using System.Xml; using System.Xml.Linq; using Microsoft.Cci; using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.Emit; using Microsoft.DiaSymReader; using Microsoft.DiaSymReader.Tools; using Microsoft.Metadata.Tools; using Roslyn.Test.PdbUtilities; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Test.Utilities { public static class PdbValidation { public static CompilationVerifier VerifyPdb( this CompilationVerifier verifier, XElement expectedPdb, IEnumerable<EmbeddedText> embeddedTexts = null, IMethodSymbol debugEntryPoint = null, DebugInformationFormat format = 0, PdbValidationOptions options = PdbValidationOptions.Default, [CallerLineNumber] int expectedValueSourceLine = 0, [CallerFilePath] string expectedValueSourcePath = null) { verifier.Compilation.VerifyPdb(expectedPdb, embeddedTexts, debugEntryPoint, format, options, expectedValueSourceLine, expectedValueSourcePath); return verifier; } public static CompilationVerifier VerifyPdb( this CompilationVerifier verifier, string expectedPdb, IEnumerable<EmbeddedText> embeddedTexts = null, IMethodSymbol debugEntryPoint = null, DebugInformationFormat format = 0, PdbValidationOptions options = PdbValidationOptions.Default, [CallerLineNumber] int expectedValueSourceLine = 0, [CallerFilePath] string expectedValueSourcePath = null) { verifier.Compilation.VerifyPdb(expectedPdb, embeddedTexts, debugEntryPoint, format, options, expectedValueSourceLine, expectedValueSourcePath); return verifier; } public static CompilationVerifier VerifyPdb( this CompilationVerifier verifier, string qualifiedMethodName, string expectedPdb, IEnumerable<EmbeddedText> embeddedTexts = null, IMethodSymbol debugEntryPoint = null, DebugInformationFormat format = 0, PdbValidationOptions options = PdbValidationOptions.Default, [CallerLineNumber] int expectedValueSourceLine = 0, [CallerFilePath] string expectedValueSourcePath = null) { verifier.Compilation.VerifyPdb(qualifiedMethodName, expectedPdb, embeddedTexts, debugEntryPoint, format, options, expectedValueSourceLine, expectedValueSourcePath); return verifier; } public static CompilationVerifier VerifyPdb( this CompilationVerifier verifier, string qualifiedMethodName, XElement expectedPdb, IEnumerable<EmbeddedText> embeddedTexts = null, IMethodSymbol debugEntryPoint = null, DebugInformationFormat format = 0, PdbValidationOptions options = PdbValidationOptions.Default, [CallerLineNumber] int expectedValueSourceLine = 0, [CallerFilePath] string expectedValueSourcePath = null) { verifier.Compilation.VerifyPdb(qualifiedMethodName, expectedPdb, embeddedTexts, debugEntryPoint, format, options, expectedValueSourceLine, expectedValueSourcePath); return verifier; } public static void VerifyPdb(this CompilationDifference diff, IEnumerable<MethodDefinitionHandle> methodHandles, string expectedPdb) { VerifyPdb(diff, methodHandles.Select(h => MetadataTokens.GetToken(h)), expectedPdb); } public static void VerifyPdb(this CompilationDifference diff, IEnumerable<MethodDefinitionHandle> methodHandles, XElement expectedPdb) { VerifyPdb(diff, methodHandles.Select(h => MetadataTokens.GetToken(h)), expectedPdb); } public static void VerifyPdb( this CompilationDifference diff, IEnumerable<int> methodTokens, string expectedPdb, DebugInformationFormat format = DebugInformationFormat.Pdb, [CallerLineNumber] int expectedValueSourceLine = 0, [CallerFilePath] string expectedValueSourcePath = null) { VerifyPdb(diff, methodTokens, expectedPdb, format, expectedValueSourceLine, expectedValueSourcePath, expectedIsXmlLiteral: false); } public static void VerifyPdb( this CompilationDifference diff, IEnumerable<int> methodTokens, XElement expectedPdb, DebugInformationFormat format = DebugInformationFormat.Pdb, [CallerLineNumber] int expectedValueSourceLine = 0, [CallerFilePath] string expectedValueSourcePath = null) { VerifyPdb(diff, methodTokens, expectedPdb.ToString(), format, expectedValueSourceLine, expectedValueSourcePath, expectedIsXmlLiteral: true); } private static void VerifyPdb( this CompilationDifference diff, IEnumerable<int> methodTokens, string expectedPdb, DebugInformationFormat format, int expectedValueSourceLine, string expectedValueSourcePath, bool expectedIsXmlLiteral) { Assert.NotEqual(default(DebugInformationFormat), format); Assert.NotEqual(DebugInformationFormat.Embedded, format); string actualPdb = PdbToXmlConverter.DeltaPdbToXml(new ImmutableMemoryStream(diff.PdbDelta), methodTokens); var (actual, expected) = AdjustToPdbFormat(actualPdb, expectedPdb, actualIsPortable: diff.NextGeneration.InitialBaseline.HasPortablePdb, actualIsConverted: false); AssertEx.AssertLinesEqual( expected, actual, $"PDB format: {format}{Environment.NewLine}", expectedValueSourcePath, expectedValueSourceLine, escapeQuotes: !expectedIsXmlLiteral); } public static void VerifyPdb( this Compilation compilation, string expectedPdb, IEnumerable<EmbeddedText> embeddedTexts = null, IMethodSymbol debugEntryPoint = null, DebugInformationFormat format = 0, PdbValidationOptions options = PdbValidationOptions.Default, [CallerLineNumber] int expectedValueSourceLine = 0, [CallerFilePath] string expectedValueSourcePath = null) { VerifyPdb(compilation, "", expectedPdb, embeddedTexts, debugEntryPoint, format, options, expectedValueSourceLine, expectedValueSourcePath); } public static void VerifyPdb( this Compilation compilation, string qualifiedMethodName, string expectedPdb, IEnumerable<EmbeddedText> embeddedTexts = null, IMethodSymbol debugEntryPoint = null, DebugInformationFormat format = 0, PdbValidationOptions options = PdbValidationOptions.Default, [CallerLineNumber] int expectedValueSourceLine = 0, [CallerFilePath] string expectedValueSourcePath = null) { VerifyPdbImpl( compilation, embeddedTexts, debugEntryPoint, qualifiedMethodName, string.IsNullOrWhiteSpace(expectedPdb) ? "<symbols></symbols>" : expectedPdb, format, options, expectedValueSourceLine, expectedValueSourcePath, expectedIsXmlLiteral: false); } public static void VerifyPdb( this Compilation compilation, XElement expectedPdb, IEnumerable<EmbeddedText> embeddedTexts = null, IMethodSymbol debugEntryPoint = null, DebugInformationFormat format = 0, PdbValidationOptions options = PdbValidationOptions.Default, [CallerLineNumber] int expectedValueSourceLine = 0, [CallerFilePath] string expectedValueSourcePath = null) { VerifyPdb(compilation, "", expectedPdb, embeddedTexts, debugEntryPoint, format, options, expectedValueSourceLine, expectedValueSourcePath); } public static void VerifyPdb( this Compilation compilation, string qualifiedMethodName, XElement expectedPdb, IEnumerable<EmbeddedText> embeddedTexts = null, IMethodSymbol debugEntryPoint = null, DebugInformationFormat format = 0, PdbValidationOptions options = PdbValidationOptions.Default, [CallerLineNumber] int expectedValueSourceLine = 0, [CallerFilePath] string expectedValueSourcePath = null) { VerifyPdbImpl( compilation, embeddedTexts, debugEntryPoint, qualifiedMethodName, expectedPdb.ToString(), format, options, expectedValueSourceLine, expectedValueSourcePath, expectedIsXmlLiteral: true); } private static void VerifyPdbImpl( this Compilation compilation, IEnumerable<EmbeddedText> embeddedTexts, IMethodSymbol debugEntryPoint, string qualifiedMethodName, string expectedPdb, DebugInformationFormat format, PdbValidationOptions options, int expectedValueSourceLine, string expectedValueSourcePath, bool expectedIsXmlLiteral) { Assert.NotEqual(DebugInformationFormat.Embedded, format); bool testWindowsPdb = (format == 0 || format == DebugInformationFormat.Pdb) && ExecutionConditionUtil.IsWindows; bool testPortablePdb = format == 0 || format == DebugInformationFormat.PortablePdb; bool testConversion = (options & PdbValidationOptions.SkipConversionValidation) == 0; var pdbToXmlOptions = options.ToPdbToXmlOptions(); if (testWindowsPdb) { Verify(isPortable: false, testOtherFormat: testPortablePdb); } if (testPortablePdb) { Verify(isPortable: true, testOtherFormat: testWindowsPdb); } void Verify(bool isPortable, bool testOtherFormat) { var peStream = new MemoryStream(); var pdbStream = new MemoryStream(); EmitWithPdb(peStream, pdbStream, compilation, debugEntryPoint, embeddedTexts, isPortable); VerifyPdbMatchesExpectedXml(peStream, pdbStream, qualifiedMethodName, pdbToXmlOptions, expectedPdb, expectedValueSourceLine, expectedValueSourcePath, expectedIsXmlLiteral, isPortable); if (testConversion && testOtherFormat) { VerifyConvertedPdbMatchesExpectedXml(peStream, pdbStream, qualifiedMethodName, expectedPdb, pdbToXmlOptions, expectedIsXmlLiteral, isPortable); } } } private static void VerifyPdbMatchesExpectedXml( Stream peStream, Stream pdbStream, string qualifiedMethodName, PdbToXmlOptions pdbToXmlOptions, string expectedPdb, int expectedValueSourceLine, string expectedValueSourcePath, bool expectedIsXmlLiteral, bool isPortable) { peStream.Position = 0; pdbStream.Position = 0; var actualPdb = XElement.Parse(PdbToXmlConverter.ToXml(pdbStream, peStream, pdbToXmlOptions, methodName: qualifiedMethodName)).ToString(); var (actual, expected) = AdjustToPdbFormat(actualPdb, expectedPdb, actualIsPortable: isPortable, actualIsConverted: false); AssertEx.AssertLinesEqual( expected, actual, $"PDB format: {(isPortable ? "Portable" : "Windows")}{Environment.NewLine}", expectedValueSourcePath, expectedValueSourceLine, escapeQuotes: !expectedIsXmlLiteral); } private static void VerifyConvertedPdbMatchesExpectedXml( Stream peStreamOriginal, Stream pdbStreamOriginal, string qualifiedMethodName, string expectedPdb, PdbToXmlOptions pdbToXmlOptions, bool expectedIsXmlLiteral, bool originalIsPortable) { var pdbStreamConverted = new MemoryStream(); var converter = new PdbConverter(diagnostic => Assert.True(false, diagnostic.ToString())); peStreamOriginal.Position = 0; pdbStreamOriginal.Position = 0; if (originalIsPortable) { converter.ConvertPortableToWindows(peStreamOriginal, pdbStreamOriginal, pdbStreamConverted); } else { converter.ConvertWindowsToPortable(peStreamOriginal, pdbStreamOriginal, pdbStreamConverted); } pdbStreamConverted.Position = 0; peStreamOriginal.Position = 0; var actualConverted = AdjustForConversionArtifacts(XElement.Parse(PdbToXmlConverter.ToXml(pdbStreamConverted, peStreamOriginal, pdbToXmlOptions, methodName: qualifiedMethodName)).ToString()); var adjustedExpected = AdjustForConversionArtifacts(expectedPdb); var (actual, expected) = AdjustToPdbFormat(actualConverted, adjustedExpected, actualIsPortable: !originalIsPortable, actualIsConverted: true); AssertEx.AssertLinesEqual( expected, actual, $"PDB format: {(originalIsPortable ? "Windows" : "Portable")} converted from {(originalIsPortable ? "Portable" : "Windows")}{Environment.NewLine}", expectedValueSourcePath: null, expectedValueSourceLine: 0, escapeQuotes: !expectedIsXmlLiteral); } private static string AdjustForConversionArtifacts(string pdb) { var xml = XElement.Parse(pdb); var pendingRemoval = new List<XElement>(); foreach (var e in xml.DescendantsAndSelf()) { if (e.Name == "constant") { // only compare constant names; values and signatures might differ: var name = e.Attribute("name"); e.RemoveAttributes(); e.Add(name); } else if (e.Name == "bucket" && e.Parent.Name == "dynamicLocals") { // dynamic flags might be 0-padded differently var flags = e.Attribute("flags"); flags.SetValue(flags.Value.TrimEnd('0')); } else if (e.Name == "defunct") { pendingRemoval.Add(e); } } foreach (var e in pendingRemoval) { e.Remove(); } RemoveEmptyScopes(xml); return xml.ToString(); } internal static (string Actual, string Expected) AdjustToPdbFormat(string actualPdb, string expectedPdb, bool actualIsPortable, bool actualIsConverted) { var actualXml = XElement.Parse(actualPdb); var expectedXml = XElement.Parse(expectedPdb); if (actualIsPortable) { // Windows SymWriter doesn't serialize empty scopes. // In Portable PDB each method with a body (even with no locals) has a scope that points to the imports. Such scope appears as empty // in the current XML representation. RemoveEmptyScopes(actualXml); // Remove elements that are never present in Portable PDB. RemoveNonPortableElements(expectedXml); } if (actualIsPortable) { RemoveElementsWithSpecifiedFormat(expectedXml, "windows"); } else { RemoveElementsWithSpecifiedFormat(expectedXml, "portable"); } RemoveEmptySequencePoints(expectedXml); RemoveEmptyScopes(expectedXml); RemoveEmptyCustomDebugInfo(expectedXml); RemoveEmptyMethods(expectedXml); RemoveFormatAttributes(expectedXml); return (actualXml.ToString(), expectedXml.ToString()); } private static bool RemoveElements(IEnumerable<XElement> elements) { var array = elements.ToArray(); foreach (var e in array) { e.Remove(); } return array.Length > 0; } private static void RemoveEmptyCustomDebugInfo(XElement pdb) { RemoveElements(from e in pdb.DescendantsAndSelf() where e.Name == "customDebugInfo" && !e.HasElements select e); } private static void RemoveEmptyScopes(XElement pdb) { while (RemoveElements(from e in pdb.DescendantsAndSelf() where e.Name == "scope" && !e.HasElements select e)) ; } private static void RemoveEmptySequencePoints(XElement pdb) { RemoveElements(from e in pdb.DescendantsAndSelf() where e.Name == "sequencePoints" && !e.HasElements select e); } private static void RemoveEmptyMethods(XElement pdb) { RemoveElements(from e in pdb.DescendantsAndSelf() where e.Name == "method" && !e.HasElements select e); } private static void RemoveNonPortableElements(XElement expectedNativePdb) { // The following elements are never present in Portable PDB. RemoveElements(from e in expectedNativePdb.DescendantsAndSelf() where e.Name == "forwardIterator" || e.Name == "forwardToModule" || e.Name == "forward" || e.Name == "tupleElementNames" || e.Name == "dynamicLocals" || e.Name == "using" || e.Name == "currentnamespace" || e.Name == "defaultnamespace" || e.Name == "importsforward" || e.Name == "xmlnamespace" || e.Name == "alias" || e.Name == "namespace" || e.Name == "type" || e.Name == "extern" || e.Name == "externinfo" || e.Name == "defunct" || e.Name == "local" && e.Attributes().Any(a => a.Name.LocalName == "name" && a.Value.StartsWith("$VB$ResumableLocal_")) select e); } private static void RemoveElementsWithSpecifiedFormat(XElement expectedNativePdb, string format) { RemoveElements(from e in expectedNativePdb.DescendantsAndSelf() where e.Attributes().Any(a => a.Name.LocalName == "format" && a.Value == format) select e); } private static void RemoveFormatAttributes(XElement pdb) { foreach (var element in pdb.DescendantsAndSelf()) { element.Attributes().FirstOrDefault(a => a.Name.LocalName == "format")?.Remove(); } } internal static string GetPdbXml( Compilation compilation, IEnumerable<EmbeddedText> embeddedTexts = null, IMethodSymbol debugEntryPoint = null, PdbValidationOptions options = PdbValidationOptions.Default, string qualifiedMethodName = "", bool portable = true) { var peStream = new MemoryStream(); var pdbStream = new MemoryStream(); EmitWithPdb(peStream, pdbStream, compilation, debugEntryPoint, embeddedTexts, portable); pdbStream.Position = 0; peStream.Position = 0; return PdbToXmlConverter.ToXml(pdbStream, peStream, options.ToPdbToXmlOptions(), methodName: qualifiedMethodName); } private static void EmitWithPdb(MemoryStream peStream, MemoryStream pdbStream, Compilation compilation, IMethodSymbol debugEntryPoint, IEnumerable<EmbeddedText> embeddedTexts, bool portable) { var emitOptions = EmitOptions.Default.WithDebugInformationFormat(portable ? DebugInformationFormat.PortablePdb : DebugInformationFormat.Pdb); var result = compilation.Emit( peStream, pdbStream, debugEntryPoint: debugEntryPoint, options: emitOptions, embeddedTexts: embeddedTexts); result.Diagnostics.Where(d => d.Severity == DiagnosticSeverity.Error).Verify(); ValidateDebugDirectory(peStream, portable ? pdbStream : null, compilation.AssemblyName + ".pdb", emitOptions.PdbChecksumAlgorithm, hasEmbeddedPdb: false, isDeterministic: compilation.IsEmitDeterministic); } public static unsafe byte[] GetSourceLinkData(Stream pdbStream) { pdbStream.Position = 0; var symReader = SymReaderFactory.CreateReader(pdbStream); try { Marshal.ThrowExceptionForHR(symReader.GetSourceServerData(out byte* data, out int size)); if (size == 0) { return Array.Empty<byte>(); } var result = new byte[size]; Marshal.Copy((IntPtr)data, result, 0, result.Length); return result; } finally { symReader.Dispose(); } } public static void ValidateDebugDirectory(Stream peStream, Stream portablePdbStreamOpt, string pdbPath, HashAlgorithmName hashAlgorithm, bool hasEmbeddedPdb, bool isDeterministic) { peStream.Position = 0; var peReader = new PEReader(peStream); var entries = peReader.ReadDebugDirectory(); int entryIndex = 0; var codeViewEntry = entries[entryIndex++]; Assert.Equal((portablePdbStreamOpt != null) ? 0x0100 : 0, codeViewEntry.MajorVersion); Assert.Equal((portablePdbStreamOpt != null) ? 0x504d : 0, codeViewEntry.MinorVersion); var codeViewData = peReader.ReadCodeViewDebugDirectoryData(codeViewEntry); Assert.Equal(1, codeViewData.Age); Assert.Equal(pdbPath, codeViewData.Path); // CodeView data: // 4B "RSDS" // 16B Guid // 4B Age // NUL-terminated path int paddedPathLength = codeViewEntry.DataSize - 24; if (isDeterministic) { Assert.Equal(Encoding.UTF8.GetByteCount(pdbPath) + 1, paddedPathLength); } else { Assert.True(paddedPathLength >= 260, "Path should be at least MAX_PATH long"); } if (portablePdbStreamOpt != null) { portablePdbStreamOpt.Position = 0; using (var provider = MetadataReaderProvider.FromPortablePdbStream(portablePdbStreamOpt, MetadataStreamOptions.LeaveOpen)) { var pdbReader = provider.GetMetadataReader(); ValidatePortablePdbId(pdbReader, codeViewEntry.Stamp, codeViewData.Guid); } } if ((portablePdbStreamOpt != null || hasEmbeddedPdb) && hashAlgorithm.Name != null) { var entry = entries[entryIndex++]; var pdbChecksumData = peReader.ReadPdbChecksumDebugDirectoryData(entry); Assert.Equal(hashAlgorithm.Name, pdbChecksumData.AlgorithmName); // TODO: validate hash } if (isDeterministic) { var entry = entries[entryIndex++]; Assert.Equal(0, entry.MinorVersion); Assert.Equal(0, entry.MajorVersion); Assert.Equal(0U, entry.Stamp); Assert.Equal(DebugDirectoryEntryType.Reproducible, entry.Type); Assert.Equal(0, entry.DataPointer); Assert.Equal(0, entry.DataRelativeVirtualAddress); Assert.Equal(0, entry.DataSize); } if (hasEmbeddedPdb) { var entry = entries[entryIndex++]; using (var provider = peReader.ReadEmbeddedPortablePdbDebugDirectoryData(entry)) { ValidatePortablePdbId(provider.GetMetadataReader(), codeViewEntry.Stamp, codeViewData.Guid); } } Assert.Equal(entries.Length, entryIndex); } private static unsafe void ValidatePortablePdbId(MetadataReader pdbReader, uint stampInDebugDirectory, Guid guidInDebugDirectory) { var expectedId = new BlobContentId(guidInDebugDirectory, stampInDebugDirectory); var actualId = new BlobContentId(pdbReader.DebugMetadataHeader.Id); Assert.Equal(expectedId, actualId); } internal static void VerifyPdbLambdasAndClosures(this Compilation compilation, SourceWithMarkedNodes source) { var pdb = GetPdbXml(compilation); var pdbXml = XElement.Parse(pdb); // We need to get the method start index from the input source, as its not in the PDB var methodStartTags = source.MarkedSpans.WhereAsArray(s => s.TagName == "M"); Assert.True(methodStartTags.Length == 1, "There must be one and only one method start tag per test input."); var methodStart = methodStartTags[0].MatchedSpan.Start; // Calculate the expected tags for closures var expectedTags = pdbXml.DescendantsAndSelf("closure").Select((c, i) => new { Tag = $"<C:{i}>", StartIndex = methodStart + int.Parse(c.Attribute("offset").Value) }).ToList(); // Add the expected tags for lambdas expectedTags.AddRange(pdbXml.DescendantsAndSelf("lambda").Select((c, i) => new { Tag = $"<L:{i}.{int.Parse(c.Attribute("closure").Value)}>", StartIndex = methodStart + int.Parse(c.Attribute("offset").Value) })); // Order by start index so they line up nicely expectedTags.Sort((x, y) => x.StartIndex.CompareTo(y.StartIndex)); // Ensure the tag for the method start is the first element expectedTags.Insert(0, new { Tag = "<M>", StartIndex = methodStart }); // Now reverse the list so we can insert without worrying about offsets expectedTags.Reverse(); var expected = source.Source; foreach (var tag in expectedTags) { expected = expected.Insert(tag.StartIndex, tag.Tag); } AssertEx.EqualOrDiff(expected, source.Input); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.IO; using System.Linq; using System.Reflection.Metadata; using System.Reflection.Metadata.Ecma335; using System.Reflection.PortableExecutable; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Security.Cryptography; using System.Text; using System.Xml; using System.Xml.Linq; using Microsoft.Cci; using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.Emit; using Microsoft.DiaSymReader; using Microsoft.DiaSymReader.Tools; using Microsoft.Metadata.Tools; using Roslyn.Test.PdbUtilities; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Test.Utilities { public static class PdbValidation { public static CompilationVerifier VerifyPdb( this CompilationVerifier verifier, XElement expectedPdb, IEnumerable<EmbeddedText> embeddedTexts = null, IMethodSymbol debugEntryPoint = null, DebugInformationFormat format = 0, PdbValidationOptions options = PdbValidationOptions.Default, [CallerLineNumber] int expectedValueSourceLine = 0, [CallerFilePath] string expectedValueSourcePath = null) { verifier.Compilation.VerifyPdb(expectedPdb, embeddedTexts, debugEntryPoint, format, options, expectedValueSourceLine, expectedValueSourcePath); return verifier; } public static CompilationVerifier VerifyPdb( this CompilationVerifier verifier, string expectedPdb, IEnumerable<EmbeddedText> embeddedTexts = null, IMethodSymbol debugEntryPoint = null, DebugInformationFormat format = 0, PdbValidationOptions options = PdbValidationOptions.Default, [CallerLineNumber] int expectedValueSourceLine = 0, [CallerFilePath] string expectedValueSourcePath = null) { verifier.Compilation.VerifyPdb(expectedPdb, embeddedTexts, debugEntryPoint, format, options, expectedValueSourceLine, expectedValueSourcePath); return verifier; } public static CompilationVerifier VerifyPdb( this CompilationVerifier verifier, string qualifiedMethodName, string expectedPdb, IEnumerable<EmbeddedText> embeddedTexts = null, IMethodSymbol debugEntryPoint = null, DebugInformationFormat format = 0, PdbValidationOptions options = PdbValidationOptions.Default, [CallerLineNumber] int expectedValueSourceLine = 0, [CallerFilePath] string expectedValueSourcePath = null) { verifier.Compilation.VerifyPdb(qualifiedMethodName, expectedPdb, embeddedTexts, debugEntryPoint, format, options, expectedValueSourceLine, expectedValueSourcePath); return verifier; } public static CompilationVerifier VerifyPdb( this CompilationVerifier verifier, string qualifiedMethodName, XElement expectedPdb, IEnumerable<EmbeddedText> embeddedTexts = null, IMethodSymbol debugEntryPoint = null, DebugInformationFormat format = 0, PdbValidationOptions options = PdbValidationOptions.Default, [CallerLineNumber] int expectedValueSourceLine = 0, [CallerFilePath] string expectedValueSourcePath = null) { verifier.Compilation.VerifyPdb(qualifiedMethodName, expectedPdb, embeddedTexts, debugEntryPoint, format, options, expectedValueSourceLine, expectedValueSourcePath); return verifier; } public static void VerifyPdb(this CompilationDifference diff, IEnumerable<MethodDefinitionHandle> methodHandles, string expectedPdb) { VerifyPdb(diff, methodHandles.Select(h => MetadataTokens.GetToken(h)), expectedPdb); } public static void VerifyPdb(this CompilationDifference diff, IEnumerable<MethodDefinitionHandle> methodHandles, XElement expectedPdb) { VerifyPdb(diff, methodHandles.Select(h => MetadataTokens.GetToken(h)), expectedPdb); } public static void VerifyPdb( this CompilationDifference diff, IEnumerable<int> methodTokens, string expectedPdb, DebugInformationFormat format = DebugInformationFormat.Pdb, [CallerLineNumber] int expectedValueSourceLine = 0, [CallerFilePath] string expectedValueSourcePath = null) { VerifyPdb(diff, methodTokens, expectedPdb, format, expectedValueSourceLine, expectedValueSourcePath, expectedIsXmlLiteral: false); } public static void VerifyPdb( this CompilationDifference diff, IEnumerable<int> methodTokens, XElement expectedPdb, DebugInformationFormat format = DebugInformationFormat.Pdb, [CallerLineNumber] int expectedValueSourceLine = 0, [CallerFilePath] string expectedValueSourcePath = null) { VerifyPdb(diff, methodTokens, expectedPdb.ToString(), format, expectedValueSourceLine, expectedValueSourcePath, expectedIsXmlLiteral: true); } private static void VerifyPdb( this CompilationDifference diff, IEnumerable<int> methodTokens, string expectedPdb, DebugInformationFormat format, int expectedValueSourceLine, string expectedValueSourcePath, bool expectedIsXmlLiteral) { Assert.NotEqual(default(DebugInformationFormat), format); Assert.NotEqual(DebugInformationFormat.Embedded, format); string actualPdb = PdbToXmlConverter.DeltaPdbToXml(new ImmutableMemoryStream(diff.PdbDelta), methodTokens); var (actual, expected) = AdjustToPdbFormat(actualPdb, expectedPdb, actualIsPortable: diff.NextGeneration.InitialBaseline.HasPortablePdb, actualIsConverted: false); AssertEx.AssertLinesEqual( expected, actual, $"PDB format: {format}{Environment.NewLine}", expectedValueSourcePath, expectedValueSourceLine, escapeQuotes: !expectedIsXmlLiteral); } public static void VerifyPdb( this Compilation compilation, string expectedPdb, IEnumerable<EmbeddedText> embeddedTexts = null, IMethodSymbol debugEntryPoint = null, DebugInformationFormat format = 0, PdbValidationOptions options = PdbValidationOptions.Default, [CallerLineNumber] int expectedValueSourceLine = 0, [CallerFilePath] string expectedValueSourcePath = null) { VerifyPdb(compilation, "", expectedPdb, embeddedTexts, debugEntryPoint, format, options, expectedValueSourceLine, expectedValueSourcePath); } public static void VerifyPdb( this Compilation compilation, string qualifiedMethodName, string expectedPdb, IEnumerable<EmbeddedText> embeddedTexts = null, IMethodSymbol debugEntryPoint = null, DebugInformationFormat format = 0, PdbValidationOptions options = PdbValidationOptions.Default, [CallerLineNumber] int expectedValueSourceLine = 0, [CallerFilePath] string expectedValueSourcePath = null) { VerifyPdbImpl( compilation, embeddedTexts, debugEntryPoint, qualifiedMethodName, string.IsNullOrWhiteSpace(expectedPdb) ? "<symbols></symbols>" : expectedPdb, format, options, expectedValueSourceLine, expectedValueSourcePath, expectedIsXmlLiteral: false); } public static void VerifyPdb( this Compilation compilation, XElement expectedPdb, IEnumerable<EmbeddedText> embeddedTexts = null, IMethodSymbol debugEntryPoint = null, DebugInformationFormat format = 0, PdbValidationOptions options = PdbValidationOptions.Default, [CallerLineNumber] int expectedValueSourceLine = 0, [CallerFilePath] string expectedValueSourcePath = null) { VerifyPdb(compilation, "", expectedPdb, embeddedTexts, debugEntryPoint, format, options, expectedValueSourceLine, expectedValueSourcePath); } public static void VerifyPdb( this Compilation compilation, string qualifiedMethodName, XElement expectedPdb, IEnumerable<EmbeddedText> embeddedTexts = null, IMethodSymbol debugEntryPoint = null, DebugInformationFormat format = 0, PdbValidationOptions options = PdbValidationOptions.Default, [CallerLineNumber] int expectedValueSourceLine = 0, [CallerFilePath] string expectedValueSourcePath = null) { VerifyPdbImpl( compilation, embeddedTexts, debugEntryPoint, qualifiedMethodName, expectedPdb.ToString(), format, options, expectedValueSourceLine, expectedValueSourcePath, expectedIsXmlLiteral: true); } private static void VerifyPdbImpl( this Compilation compilation, IEnumerable<EmbeddedText> embeddedTexts, IMethodSymbol debugEntryPoint, string qualifiedMethodName, string expectedPdb, DebugInformationFormat format, PdbValidationOptions options, int expectedValueSourceLine, string expectedValueSourcePath, bool expectedIsXmlLiteral) { Assert.NotEqual(DebugInformationFormat.Embedded, format); bool testWindowsPdb = (format == 0 || format == DebugInformationFormat.Pdb) && ExecutionConditionUtil.IsWindows; bool testPortablePdb = format == 0 || format == DebugInformationFormat.PortablePdb; bool testConversion = (options & PdbValidationOptions.SkipConversionValidation) == 0; var pdbToXmlOptions = options.ToPdbToXmlOptions(); if (testWindowsPdb) { Verify(isPortable: false, testOtherFormat: testPortablePdb); } if (testPortablePdb) { Verify(isPortable: true, testOtherFormat: testWindowsPdb); } void Verify(bool isPortable, bool testOtherFormat) { var peStream = new MemoryStream(); var pdbStream = new MemoryStream(); EmitWithPdb(peStream, pdbStream, compilation, debugEntryPoint, embeddedTexts, isPortable); VerifyPdbMatchesExpectedXml(peStream, pdbStream, qualifiedMethodName, pdbToXmlOptions, expectedPdb, expectedValueSourceLine, expectedValueSourcePath, expectedIsXmlLiteral, isPortable); if (testConversion && testOtherFormat) { VerifyConvertedPdbMatchesExpectedXml(peStream, pdbStream, qualifiedMethodName, expectedPdb, pdbToXmlOptions, expectedIsXmlLiteral, isPortable); } } } private static void VerifyPdbMatchesExpectedXml( Stream peStream, Stream pdbStream, string qualifiedMethodName, PdbToXmlOptions pdbToXmlOptions, string expectedPdb, int expectedValueSourceLine, string expectedValueSourcePath, bool expectedIsXmlLiteral, bool isPortable) { peStream.Position = 0; pdbStream.Position = 0; var actualPdb = XElement.Parse(PdbToXmlConverter.ToXml(pdbStream, peStream, pdbToXmlOptions, methodName: qualifiedMethodName)).ToString(); var (actual, expected) = AdjustToPdbFormat(actualPdb, expectedPdb, actualIsPortable: isPortable, actualIsConverted: false); AssertEx.AssertLinesEqual( expected, actual, $"PDB format: {(isPortable ? "Portable" : "Windows")}{Environment.NewLine}", expectedValueSourcePath, expectedValueSourceLine, escapeQuotes: !expectedIsXmlLiteral); } private static void VerifyConvertedPdbMatchesExpectedXml( Stream peStreamOriginal, Stream pdbStreamOriginal, string qualifiedMethodName, string expectedPdb, PdbToXmlOptions pdbToXmlOptions, bool expectedIsXmlLiteral, bool originalIsPortable) { var pdbStreamConverted = new MemoryStream(); var converter = new PdbConverter(diagnostic => Assert.True(false, diagnostic.ToString())); peStreamOriginal.Position = 0; pdbStreamOriginal.Position = 0; if (originalIsPortable) { converter.ConvertPortableToWindows(peStreamOriginal, pdbStreamOriginal, pdbStreamConverted); } else { converter.ConvertWindowsToPortable(peStreamOriginal, pdbStreamOriginal, pdbStreamConverted); } pdbStreamConverted.Position = 0; peStreamOriginal.Position = 0; var actualConverted = AdjustForConversionArtifacts(XElement.Parse(PdbToXmlConverter.ToXml(pdbStreamConverted, peStreamOriginal, pdbToXmlOptions, methodName: qualifiedMethodName)).ToString()); var adjustedExpected = AdjustForConversionArtifacts(expectedPdb); var (actual, expected) = AdjustToPdbFormat(actualConverted, adjustedExpected, actualIsPortable: !originalIsPortable, actualIsConverted: true); AssertEx.AssertLinesEqual( expected, actual, $"PDB format: {(originalIsPortable ? "Windows" : "Portable")} converted from {(originalIsPortable ? "Portable" : "Windows")}{Environment.NewLine}", expectedValueSourcePath: null, expectedValueSourceLine: 0, escapeQuotes: !expectedIsXmlLiteral); } private static string AdjustForConversionArtifacts(string pdb) { var xml = XElement.Parse(pdb); var pendingRemoval = new List<XElement>(); foreach (var e in xml.DescendantsAndSelf()) { if (e.Name == "constant") { // only compare constant names; values and signatures might differ: var name = e.Attribute("name"); e.RemoveAttributes(); e.Add(name); } else if (e.Name == "bucket" && e.Parent.Name == "dynamicLocals") { // dynamic flags might be 0-padded differently var flags = e.Attribute("flags"); flags.SetValue(flags.Value.TrimEnd('0')); } else if (e.Name == "defunct") { pendingRemoval.Add(e); } } foreach (var e in pendingRemoval) { e.Remove(); } RemoveEmptyScopes(xml); return xml.ToString(); } internal static (string Actual, string Expected) AdjustToPdbFormat(string actualPdb, string expectedPdb, bool actualIsPortable, bool actualIsConverted) { var actualXml = XElement.Parse(actualPdb); var expectedXml = XElement.Parse(expectedPdb); if (actualIsPortable) { // Windows SymWriter doesn't serialize empty scopes. // In Portable PDB each method with a body (even with no locals) has a scope that points to the imports. Such scope appears as empty // in the current XML representation. RemoveEmptyScopes(actualXml); // Remove elements that are never present in Portable PDB. RemoveNonPortableElements(expectedXml); } if (actualIsPortable) { RemoveElementsWithSpecifiedFormat(expectedXml, "windows"); } else { RemoveElementsWithSpecifiedFormat(expectedXml, "portable"); } RemoveEmptySequencePoints(expectedXml); RemoveEmptyScopes(expectedXml); RemoveEmptyCustomDebugInfo(expectedXml); RemoveEmptyMethods(expectedXml); RemoveFormatAttributes(expectedXml); return (actualXml.ToString(), expectedXml.ToString()); } private static bool RemoveElements(IEnumerable<XElement> elements) { var array = elements.ToArray(); foreach (var e in array) { e.Remove(); } return array.Length > 0; } private static void RemoveEmptyCustomDebugInfo(XElement pdb) { RemoveElements(from e in pdb.DescendantsAndSelf() where e.Name == "customDebugInfo" && !e.HasElements select e); } private static void RemoveEmptyScopes(XElement pdb) { while (RemoveElements(from e in pdb.DescendantsAndSelf() where e.Name == "scope" && !e.HasElements select e)) ; } private static void RemoveEmptySequencePoints(XElement pdb) { RemoveElements(from e in pdb.DescendantsAndSelf() where e.Name == "sequencePoints" && !e.HasElements select e); } private static void RemoveEmptyMethods(XElement pdb) { RemoveElements(from e in pdb.DescendantsAndSelf() where e.Name == "method" && !e.HasElements select e); } private static void RemoveNonPortableElements(XElement expectedNativePdb) { // The following elements are never present in Portable PDB. RemoveElements(from e in expectedNativePdb.DescendantsAndSelf() where e.Name == "forwardIterator" || e.Name == "forwardToModule" || e.Name == "forward" || e.Name == "tupleElementNames" || e.Name == "dynamicLocals" || e.Name == "using" || e.Name == "currentnamespace" || e.Name == "defaultnamespace" || e.Name == "importsforward" || e.Name == "xmlnamespace" || e.Name == "alias" || e.Name == "namespace" || e.Name == "type" || e.Name == "extern" || e.Name == "externinfo" || e.Name == "defunct" || e.Name == "local" && e.Attributes().Any(a => a.Name.LocalName == "name" && a.Value.StartsWith("$VB$ResumableLocal_")) select e); } private static void RemoveElementsWithSpecifiedFormat(XElement expectedNativePdb, string format) { RemoveElements(from e in expectedNativePdb.DescendantsAndSelf() where e.Attributes().Any(a => a.Name.LocalName == "format" && a.Value == format) select e); } private static void RemoveFormatAttributes(XElement pdb) { foreach (var element in pdb.DescendantsAndSelf()) { element.Attributes().FirstOrDefault(a => a.Name.LocalName == "format")?.Remove(); } } internal static string GetPdbXml( Compilation compilation, IEnumerable<EmbeddedText> embeddedTexts = null, IMethodSymbol debugEntryPoint = null, PdbValidationOptions options = PdbValidationOptions.Default, string qualifiedMethodName = "", bool portable = true) { var peStream = new MemoryStream(); var pdbStream = new MemoryStream(); EmitWithPdb(peStream, pdbStream, compilation, debugEntryPoint, embeddedTexts, portable); pdbStream.Position = 0; peStream.Position = 0; return PdbToXmlConverter.ToXml(pdbStream, peStream, options.ToPdbToXmlOptions(), methodName: qualifiedMethodName); } private static void EmitWithPdb(MemoryStream peStream, MemoryStream pdbStream, Compilation compilation, IMethodSymbol debugEntryPoint, IEnumerable<EmbeddedText> embeddedTexts, bool portable) { var emitOptions = EmitOptions.Default.WithDebugInformationFormat(portable ? DebugInformationFormat.PortablePdb : DebugInformationFormat.Pdb); var result = compilation.Emit( peStream, pdbStream, debugEntryPoint: debugEntryPoint, options: emitOptions, embeddedTexts: embeddedTexts); result.Diagnostics.Where(d => d.Severity == DiagnosticSeverity.Error).Verify(); ValidateDebugDirectory(peStream, portable ? pdbStream : null, compilation.AssemblyName + ".pdb", emitOptions.PdbChecksumAlgorithm, hasEmbeddedPdb: false, isDeterministic: compilation.IsEmitDeterministic); } public static unsafe byte[] GetSourceLinkData(Stream pdbStream) { pdbStream.Position = 0; var symReader = SymReaderFactory.CreateReader(pdbStream); try { Marshal.ThrowExceptionForHR(symReader.GetSourceServerData(out byte* data, out int size)); if (size == 0) { return Array.Empty<byte>(); } var result = new byte[size]; Marshal.Copy((IntPtr)data, result, 0, result.Length); return result; } finally { symReader.Dispose(); } } public static void ValidateDebugDirectory(Stream peStream, Stream portablePdbStreamOpt, string pdbPath, HashAlgorithmName hashAlgorithm, bool hasEmbeddedPdb, bool isDeterministic) { peStream.Position = 0; var peReader = new PEReader(peStream); var entries = peReader.ReadDebugDirectory(); int entryIndex = 0; var codeViewEntry = entries[entryIndex++]; Assert.Equal((portablePdbStreamOpt != null) ? 0x0100 : 0, codeViewEntry.MajorVersion); Assert.Equal((portablePdbStreamOpt != null) ? 0x504d : 0, codeViewEntry.MinorVersion); var codeViewData = peReader.ReadCodeViewDebugDirectoryData(codeViewEntry); Assert.Equal(1, codeViewData.Age); Assert.Equal(pdbPath, codeViewData.Path); // CodeView data: // 4B "RSDS" // 16B Guid // 4B Age // NUL-terminated path int paddedPathLength = codeViewEntry.DataSize - 24; if (isDeterministic) { Assert.Equal(Encoding.UTF8.GetByteCount(pdbPath) + 1, paddedPathLength); } else { Assert.True(paddedPathLength >= 260, "Path should be at least MAX_PATH long"); } if (portablePdbStreamOpt != null) { portablePdbStreamOpt.Position = 0; using (var provider = MetadataReaderProvider.FromPortablePdbStream(portablePdbStreamOpt, MetadataStreamOptions.LeaveOpen)) { var pdbReader = provider.GetMetadataReader(); ValidatePortablePdbId(pdbReader, codeViewEntry.Stamp, codeViewData.Guid); } } if ((portablePdbStreamOpt != null || hasEmbeddedPdb) && hashAlgorithm.Name != null) { var entry = entries[entryIndex++]; var pdbChecksumData = peReader.ReadPdbChecksumDebugDirectoryData(entry); Assert.Equal(hashAlgorithm.Name, pdbChecksumData.AlgorithmName); // TODO: validate hash } if (isDeterministic) { var entry = entries[entryIndex++]; Assert.Equal(0, entry.MinorVersion); Assert.Equal(0, entry.MajorVersion); Assert.Equal(0U, entry.Stamp); Assert.Equal(DebugDirectoryEntryType.Reproducible, entry.Type); Assert.Equal(0, entry.DataPointer); Assert.Equal(0, entry.DataRelativeVirtualAddress); Assert.Equal(0, entry.DataSize); } if (hasEmbeddedPdb) { var entry = entries[entryIndex++]; using (var provider = peReader.ReadEmbeddedPortablePdbDebugDirectoryData(entry)) { ValidatePortablePdbId(provider.GetMetadataReader(), codeViewEntry.Stamp, codeViewData.Guid); } } Assert.Equal(entries.Length, entryIndex); } private static unsafe void ValidatePortablePdbId(MetadataReader pdbReader, uint stampInDebugDirectory, Guid guidInDebugDirectory) { var expectedId = new BlobContentId(guidInDebugDirectory, stampInDebugDirectory); var actualId = new BlobContentId(pdbReader.DebugMetadataHeader.Id); Assert.Equal(expectedId, actualId); } internal static void VerifyPdbLambdasAndClosures(this Compilation compilation, SourceWithMarkedNodes source) { var pdb = GetPdbXml(compilation); var pdbXml = XElement.Parse(pdb); // We need to get the method start index from the input source, as its not in the PDB var methodStartTags = source.MarkedSpans.WhereAsArray(s => s.TagName == "M"); Assert.True(methodStartTags.Length == 1, "There must be one and only one method start tag per test input."); var methodStart = methodStartTags[0].MatchedSpan.Start; // Calculate the expected tags for closures var expectedTags = pdbXml.DescendantsAndSelf("closure").Select((c, i) => new { Tag = $"<C:{i}>", StartIndex = methodStart + int.Parse(c.Attribute("offset").Value) }).ToList(); // Add the expected tags for lambdas expectedTags.AddRange(pdbXml.DescendantsAndSelf("lambda").Select((c, i) => new { Tag = $"<L:{i}.{int.Parse(c.Attribute("closure").Value)}>", StartIndex = methodStart + int.Parse(c.Attribute("offset").Value) })); // Order by start index so they line up nicely expectedTags.Sort((x, y) => x.StartIndex.CompareTo(y.StartIndex)); // Ensure the tag for the method start is the first element expectedTags.Insert(0, new { Tag = "<M>", StartIndex = methodStart }); // Now reverse the list so we can insert without worrying about offsets expectedTags.Reverse(); var expected = source.Source; foreach (var tag in expectedTags) { expected = expected.Insert(tag.StartIndex, tag.Tag); } AssertEx.EqualOrDiff(expected, source.Input); } } }
-1
dotnet/roslyn
55,262
Fix LSP completions when all items have default commit characters
Fixes an exception stack trace seen in https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1362284 Also fixes behavior of promotion of commit characters to the list to include default commit characters
dibarbet
2021-07-30T02:43:35Z
2021-07-30T21:21:47Z
2f7dffa534aceb92e9767568e88535c926588d12
65ee073bf6cea571a68193793420ecee60752711
Fix LSP completions when all items have default commit characters. Fixes an exception stack trace seen in https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1362284 Also fixes behavior of promotion of commit characters to the list to include default commit characters
./src/Compilers/CSharp/Portable/Lowering/LocalRewriter/LocalRewriter_FunctionPointerInvocation.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Diagnostics; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.PooledObjects; namespace Microsoft.CodeAnalysis.CSharp { internal sealed partial class LocalRewriter { public override BoundNode? VisitFunctionPointerInvocation(BoundFunctionPointerInvocation node) { var rewrittenExpression = VisitExpression(node.InvokedExpression); // There are target types so we can have handler conversions, but there are no attributes so contexts cannot // be involved. AssertNoImplicitInterpolatedStringHandlerConversions(node.Arguments, allowConversionsWithNoContext: true); MethodSymbol functionPointer = node.FunctionPointer.Signature; var argumentRefKindsOpt = node.ArgumentRefKindsOpt; BoundExpression? discardedReceiver = null; var rewrittenArgs = VisitArguments( node.Arguments, functionPointer, argsToParamsOpt: default, argumentRefKindsOpt: argumentRefKindsOpt, rewrittenReceiver: ref discardedReceiver, temps: out ArrayBuilder<LocalSymbol>? temps); rewrittenArgs = MakeArguments( node.Syntax, rewrittenArgs, functionPointer, expanded: false, argsToParamsOpt: default, ref argumentRefKindsOpt, ref temps, invokedAsExtensionMethod: false, enableCallerInfo: ThreeState.False); Debug.Assert(rewrittenExpression != null); node = node.Update(rewrittenExpression, rewrittenArgs, argumentRefKindsOpt, node.ResultKind, node.Type); if (temps.Count == 0) { temps.Free(); return node; } return new BoundSequence(node.Syntax, temps.ToImmutableAndFree(), sideEffects: ImmutableArray<BoundExpression>.Empty, node, node.Type); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Diagnostics; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.PooledObjects; namespace Microsoft.CodeAnalysis.CSharp { internal sealed partial class LocalRewriter { public override BoundNode? VisitFunctionPointerInvocation(BoundFunctionPointerInvocation node) { var rewrittenExpression = VisitExpression(node.InvokedExpression); // There are target types so we can have handler conversions, but there are no attributes so contexts cannot // be involved. AssertNoImplicitInterpolatedStringHandlerConversions(node.Arguments, allowConversionsWithNoContext: true); MethodSymbol functionPointer = node.FunctionPointer.Signature; var argumentRefKindsOpt = node.ArgumentRefKindsOpt; BoundExpression? discardedReceiver = null; var rewrittenArgs = VisitArguments( node.Arguments, functionPointer, argsToParamsOpt: default, argumentRefKindsOpt: argumentRefKindsOpt, rewrittenReceiver: ref discardedReceiver, temps: out ArrayBuilder<LocalSymbol>? temps); rewrittenArgs = MakeArguments( node.Syntax, rewrittenArgs, functionPointer, expanded: false, argsToParamsOpt: default, ref argumentRefKindsOpt, ref temps, invokedAsExtensionMethod: false, enableCallerInfo: ThreeState.False); Debug.Assert(rewrittenExpression != null); node = node.Update(rewrittenExpression, rewrittenArgs, argumentRefKindsOpt, node.ResultKind, node.Type); if (temps.Count == 0) { temps.Free(); return node; } return new BoundSequence(node.Syntax, temps.ToImmutableAndFree(), sideEffects: ImmutableArray<BoundExpression>.Empty, node, node.Type); } } }
-1
dotnet/roslyn
55,262
Fix LSP completions when all items have default commit characters
Fixes an exception stack trace seen in https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1362284 Also fixes behavior of promotion of commit characters to the list to include default commit characters
dibarbet
2021-07-30T02:43:35Z
2021-07-30T21:21:47Z
2f7dffa534aceb92e9767568e88535c926588d12
65ee073bf6cea571a68193793420ecee60752711
Fix LSP completions when all items have default commit characters. Fixes an exception stack trace seen in https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1362284 Also fixes behavior of promotion of commit characters to the list to include default commit characters
./src/Analyzers/Core/CodeFixes/UseIsNullCheck/AbstractUseIsNullForReferenceEqualsCodeFixProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.CodeFixes; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.UseIsNullCheck { internal abstract class AbstractUseIsNullCheckForReferenceEqualsCodeFixProvider<TExpressionSyntax> : SyntaxEditorBasedCodeFixProvider where TExpressionSyntax : SyntaxNode { public override ImmutableArray<string> FixableDiagnosticIds => ImmutableArray.Create(IDEDiagnosticIds.UseIsNullCheckDiagnosticId); internal sealed override CodeFixCategory CodeFixCategory => CodeFixCategory.CodeStyle; protected abstract string GetIsNullTitle(); protected abstract string GetIsNotNullTitle(); protected abstract SyntaxNode CreateNullCheck(TExpressionSyntax argument, bool isUnconstrainedGeneric); protected abstract SyntaxNode CreateNotNullCheck(TExpressionSyntax argument); private static bool IsSupportedDiagnostic(Diagnostic diagnostic) => diagnostic.Properties[UseIsNullConstants.Kind] == UseIsNullConstants.ReferenceEqualsKey; public override Task RegisterCodeFixesAsync(CodeFixContext context) { var diagnostic = context.Diagnostics.First(); if (IsSupportedDiagnostic(diagnostic)) { var negated = diagnostic.Properties.ContainsKey(UseIsNullConstants.Negated); var title = negated ? GetIsNotNullTitle() : GetIsNullTitle(); context.RegisterCodeFix( new MyCodeAction(title, c => FixAsync(context.Document, diagnostic, c)), context.Diagnostics); } return Task.CompletedTask; } protected override Task FixAllAsync( Document document, ImmutableArray<Diagnostic> diagnostics, SyntaxEditor editor, CancellationToken cancellationToken) { var syntaxFacts = document.GetLanguageService<ISyntaxFactsService>(); // Order in reverse so we process inner diagnostics before outer diagnostics. // Otherwise, we won't be able to find the nodes we want to replace if they're // not there once their parent has been replaced. foreach (var diagnostic in diagnostics.OrderByDescending(d => d.Location.SourceSpan.Start)) { if (!IsSupportedDiagnostic(diagnostic)) { continue; } var invocation = diagnostic.AdditionalLocations[0].FindNode(getInnermostNodeForTie: true, cancellationToken: cancellationToken); var negate = diagnostic.Properties.ContainsKey(UseIsNullConstants.Negated); var isUnconstrainedGeneric = diagnostic.Properties.ContainsKey(UseIsNullConstants.UnconstrainedGeneric); var arguments = syntaxFacts.GetArgumentsOfInvocationExpression(invocation); var argument = syntaxFacts.IsNullLiteralExpression(syntaxFacts.GetExpressionOfArgument(arguments[0])) ? (TExpressionSyntax)syntaxFacts.GetExpressionOfArgument(arguments[1]) : (TExpressionSyntax)syntaxFacts.GetExpressionOfArgument(arguments[0]); var toReplace = negate ? invocation.Parent : invocation; var replacement = negate ? CreateNotNullCheck(argument) : CreateNullCheck(argument, isUnconstrainedGeneric); editor.ReplaceNode( toReplace, replacement.WithTriviaFrom(toReplace)); } return Task.CompletedTask; } private class MyCodeAction : CustomCodeActions.DocumentChangeAction { public MyCodeAction(string title, Func<CancellationToken, Task<Document>> createChangedDocument) : base(title, createChangedDocument, title) { } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.UseIsNullCheck { internal abstract class AbstractUseIsNullCheckForReferenceEqualsCodeFixProvider<TExpressionSyntax> : SyntaxEditorBasedCodeFixProvider where TExpressionSyntax : SyntaxNode { public override ImmutableArray<string> FixableDiagnosticIds => ImmutableArray.Create(IDEDiagnosticIds.UseIsNullCheckDiagnosticId); internal sealed override CodeFixCategory CodeFixCategory => CodeFixCategory.CodeStyle; protected abstract string GetIsNullTitle(); protected abstract string GetIsNotNullTitle(); protected abstract SyntaxNode CreateNullCheck(TExpressionSyntax argument, bool isUnconstrainedGeneric); protected abstract SyntaxNode CreateNotNullCheck(TExpressionSyntax argument); private static bool IsSupportedDiagnostic(Diagnostic diagnostic) => diagnostic.Properties[UseIsNullConstants.Kind] == UseIsNullConstants.ReferenceEqualsKey; public override Task RegisterCodeFixesAsync(CodeFixContext context) { var diagnostic = context.Diagnostics.First(); if (IsSupportedDiagnostic(diagnostic)) { var negated = diagnostic.Properties.ContainsKey(UseIsNullConstants.Negated); var title = negated ? GetIsNotNullTitle() : GetIsNullTitle(); context.RegisterCodeFix( new MyCodeAction(title, c => FixAsync(context.Document, diagnostic, c)), context.Diagnostics); } return Task.CompletedTask; } protected override Task FixAllAsync( Document document, ImmutableArray<Diagnostic> diagnostics, SyntaxEditor editor, CancellationToken cancellationToken) { var syntaxFacts = document.GetLanguageService<ISyntaxFactsService>(); // Order in reverse so we process inner diagnostics before outer diagnostics. // Otherwise, we won't be able to find the nodes we want to replace if they're // not there once their parent has been replaced. foreach (var diagnostic in diagnostics.OrderByDescending(d => d.Location.SourceSpan.Start)) { if (!IsSupportedDiagnostic(diagnostic)) { continue; } var invocation = diagnostic.AdditionalLocations[0].FindNode(getInnermostNodeForTie: true, cancellationToken: cancellationToken); var negate = diagnostic.Properties.ContainsKey(UseIsNullConstants.Negated); var isUnconstrainedGeneric = diagnostic.Properties.ContainsKey(UseIsNullConstants.UnconstrainedGeneric); var arguments = syntaxFacts.GetArgumentsOfInvocationExpression(invocation); var argument = syntaxFacts.IsNullLiteralExpression(syntaxFacts.GetExpressionOfArgument(arguments[0])) ? (TExpressionSyntax)syntaxFacts.GetExpressionOfArgument(arguments[1]) : (TExpressionSyntax)syntaxFacts.GetExpressionOfArgument(arguments[0]); var toReplace = negate ? invocation.Parent : invocation; var replacement = negate ? CreateNotNullCheck(argument) : CreateNullCheck(argument, isUnconstrainedGeneric); editor.ReplaceNode( toReplace, replacement.WithTriviaFrom(toReplace)); } return Task.CompletedTask; } private class MyCodeAction : CustomCodeActions.DocumentChangeAction { public MyCodeAction(string title, Func<CancellationToken, Task<Document>> createChangedDocument) : base(title, createChangedDocument, title) { } } } }
-1
dotnet/roslyn
55,262
Fix LSP completions when all items have default commit characters
Fixes an exception stack trace seen in https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1362284 Also fixes behavior of promotion of commit characters to the list to include default commit characters
dibarbet
2021-07-30T02:43:35Z
2021-07-30T21:21:47Z
2f7dffa534aceb92e9767568e88535c926588d12
65ee073bf6cea571a68193793420ecee60752711
Fix LSP completions when all items have default commit characters. Fixes an exception stack trace seen in https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1362284 Also fixes behavior of promotion of commit characters to the list to include default commit characters
./src/VisualStudio/IntegrationTest/IntegrationTests/CSharp/CSharpSquigglesNetCore.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET 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.Test.Utilities; using Microsoft.VisualStudio.IntegrationTest.Utilities; using Roslyn.Test.Utilities; using Xunit; using Xunit.Abstractions; namespace Roslyn.VisualStudio.IntegrationTests.CSharp { [Collection(nameof(SharedIntegrationHostFixture))] public class CSharpSquigglesNetCore : CSharpSquigglesCommon { public CSharpSquigglesNetCore(VisualStudioInstanceFactory instanceFactory) : base(instanceFactory, WellKnownProjectTemplates.CSharpNetCoreClassLibrary) { } [WpfFact] [Trait(Traits.Feature, Traits.Features.ErrorSquiggles)] [Trait(Traits.Feature, Traits.Features.NetCore)] public override void VerifySyntaxErrorSquiggles() { base.VerifySyntaxErrorSquiggles(); } [WpfFact] [Trait(Traits.Feature, Traits.Features.ErrorSquiggles)] [Trait(Traits.Feature, Traits.Features.NetCore)] public override void VerifySemanticErrorSquiggles() { base.VerifySemanticErrorSquiggles(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET 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.Test.Utilities; using Microsoft.VisualStudio.IntegrationTest.Utilities; using Roslyn.Test.Utilities; using Xunit; using Xunit.Abstractions; namespace Roslyn.VisualStudio.IntegrationTests.CSharp { [Collection(nameof(SharedIntegrationHostFixture))] public class CSharpSquigglesNetCore : CSharpSquigglesCommon { public CSharpSquigglesNetCore(VisualStudioInstanceFactory instanceFactory) : base(instanceFactory, WellKnownProjectTemplates.CSharpNetCoreClassLibrary) { } [WpfFact] [Trait(Traits.Feature, Traits.Features.ErrorSquiggles)] [Trait(Traits.Feature, Traits.Features.NetCore)] public override void VerifySyntaxErrorSquiggles() { base.VerifySyntaxErrorSquiggles(); } [WpfFact] [Trait(Traits.Feature, Traits.Features.ErrorSquiggles)] [Trait(Traits.Feature, Traits.Features.NetCore)] public override void VerifySemanticErrorSquiggles() { base.VerifySemanticErrorSquiggles(); } } }
-1
dotnet/roslyn
55,262
Fix LSP completions when all items have default commit characters
Fixes an exception stack trace seen in https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1362284 Also fixes behavior of promotion of commit characters to the list to include default commit characters
dibarbet
2021-07-30T02:43:35Z
2021-07-30T21:21:47Z
2f7dffa534aceb92e9767568e88535c926588d12
65ee073bf6cea571a68193793420ecee60752711
Fix LSP completions when all items have default commit characters. Fixes an exception stack trace seen in https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1362284 Also fixes behavior of promotion of commit characters to the list to include default commit characters
./src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/LanguageServices/MoveDeclarationNearReference/AbstractMoveDeclarationNearReferenceService.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.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.FindSymbols; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.MoveDeclarationNearReference { internal partial class AbstractMoveDeclarationNearReferenceService< TService, TStatementSyntax, TLocalDeclarationStatementSyntax, TVariableDeclaratorSyntax> { private class State { public TLocalDeclarationStatementSyntax DeclarationStatement { get; private set; } public TVariableDeclaratorSyntax VariableDeclarator { get; private set; } public ILocalSymbol LocalSymbol { get; private set; } public SyntaxNode OutermostBlock { get; private set; } public SyntaxNode InnermostBlock { get; private set; } public IReadOnlyList<SyntaxNode> OutermostBlockStatements { get; private set; } public IReadOnlyList<SyntaxNode> InnermostBlockStatements { get; private set; } public TStatementSyntax FirstStatementAffectedInInnermostBlock { get; private set; } public int IndexOfDeclarationStatementInInnermostBlock { get; private set; } public int IndexOfFirstStatementAffectedInInnermostBlock { get; private set; } internal static async Task<State> GenerateAsync( TService service, Document document, TLocalDeclarationStatementSyntax statement, CancellationToken cancellationToken) { var state = new State(); if (!await state.TryInitializeAsync(service, document, statement, cancellationToken).ConfigureAwait(false)) { return null; } return state; } private async Task<bool> TryInitializeAsync( TService service, Document document, TLocalDeclarationStatementSyntax node, CancellationToken cancellationToken) { var syntaxFacts = document.GetLanguageService<ISyntaxFactsService>(); DeclarationStatement = node; var variables = syntaxFacts.GetVariablesOfLocalDeclarationStatement(DeclarationStatement); if (variables.Count != 1) { return false; } VariableDeclarator = (TVariableDeclaratorSyntax)variables[0]; if (!service.IsValidVariableDeclarator(VariableDeclarator)) { return false; } OutermostBlock = syntaxFacts.GetStatementContainer(DeclarationStatement); if (!syntaxFacts.IsExecutableBlock(OutermostBlock)) { return false; } var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); LocalSymbol = (ILocalSymbol)semanticModel.GetDeclaredSymbol( service.GetVariableDeclaratorSymbolNode(VariableDeclarator), cancellationToken); if (LocalSymbol == null) { // This can happen in broken code, for example: "{ object x; object }" return false; } var findReferencesResult = await SymbolFinder.FindReferencesAsync(LocalSymbol, document.Project.Solution, cancellationToken).ConfigureAwait(false); var findReferencesList = findReferencesResult.ToList(); if (findReferencesList.Count != 1) { return false; } var references = findReferencesList[0].Locations.ToList(); if (references.Count == 0) { return false; } var syntaxRoot = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var referencingStatements = (from r in references let token = syntaxRoot.FindToken(r.Location.SourceSpan.Start) let statement = token.GetAncestor<TStatementSyntax>() where statement != null select statement).ToSet(); if (referencingStatements.Count == 0) { return false; } InnermostBlock = syntaxFacts.FindInnermostCommonExecutableBlock(referencingStatements); if (InnermostBlock == null) { return false; } InnermostBlockStatements = syntaxFacts.GetExecutableBlockStatements(InnermostBlock); OutermostBlockStatements = syntaxFacts.GetExecutableBlockStatements(OutermostBlock); var allAffectedStatements = new HashSet<TStatementSyntax>(referencingStatements.SelectMany( expr => expr.GetAncestorsOrThis<TStatementSyntax>())); FirstStatementAffectedInInnermostBlock = InnermostBlockStatements.Cast<TStatementSyntax>().FirstOrDefault(allAffectedStatements.Contains); if (FirstStatementAffectedInInnermostBlock == null) { return false; } if (FirstStatementAffectedInInnermostBlock == DeclarationStatement) { return false; } IndexOfDeclarationStatementInInnermostBlock = InnermostBlockStatements.IndexOf(DeclarationStatement); IndexOfFirstStatementAffectedInInnermostBlock = InnermostBlockStatements.IndexOf(FirstStatementAffectedInInnermostBlock); if (IndexOfDeclarationStatementInInnermostBlock >= 0 && IndexOfDeclarationStatementInInnermostBlock < IndexOfFirstStatementAffectedInInnermostBlock) { // Don't want to move a decl with initializer past other decls in order to move it to the first // affected statement. If we do we can end up in the following situation: #if false int x = 0; int y = 0; Console.WriteLine(x + y); #endif // Each of these declarations will want to 'move' down to the WriteLine // statement and we don't want to keep offering the refactoring. Note: this // solution is overly aggressive. Technically if 'y' weren't referenced in // Console.Writeline, then it might be a good idea to move the 'x'. But this // gives good enough behavior most of the time. // Note that if the variable declaration has no initializer, then we still want to offer // the move as the closest reference will be an assignment to the variable // and we should be able to merge the declaration and assignment into a single // statement. // So, we also check if the variable declaration has an initializer below. if (syntaxFacts.GetInitializerOfVariableDeclarator(VariableDeclarator) != null && InDeclarationStatementGroup(IndexOfDeclarationStatementInInnermostBlock, IndexOfFirstStatementAffectedInInnermostBlock)) { return false; } } var previousToken = FirstStatementAffectedInInnermostBlock.GetFirstToken().GetPreviousToken(); var affectedSpan = TextSpan.FromBounds(previousToken.SpanStart, FirstStatementAffectedInInnermostBlock.Span.End); if (semanticModel.SyntaxTree.OverlapsHiddenPosition(affectedSpan, cancellationToken)) { return false; } return true; } private bool InDeclarationStatementGroup( int originalIndexInBlock, int firstStatementIndexAffectedInBlock) { for (var i = originalIndexInBlock; i < firstStatementIndexAffectedInBlock; i++) { if (!(InnermostBlockStatements[i] is TLocalDeclarationStatementSyntax)) { return false; } } return true; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.FindSymbols; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.MoveDeclarationNearReference { internal partial class AbstractMoveDeclarationNearReferenceService< TService, TStatementSyntax, TLocalDeclarationStatementSyntax, TVariableDeclaratorSyntax> { private class State { public TLocalDeclarationStatementSyntax DeclarationStatement { get; private set; } public TVariableDeclaratorSyntax VariableDeclarator { get; private set; } public ILocalSymbol LocalSymbol { get; private set; } public SyntaxNode OutermostBlock { get; private set; } public SyntaxNode InnermostBlock { get; private set; } public IReadOnlyList<SyntaxNode> OutermostBlockStatements { get; private set; } public IReadOnlyList<SyntaxNode> InnermostBlockStatements { get; private set; } public TStatementSyntax FirstStatementAffectedInInnermostBlock { get; private set; } public int IndexOfDeclarationStatementInInnermostBlock { get; private set; } public int IndexOfFirstStatementAffectedInInnermostBlock { get; private set; } internal static async Task<State> GenerateAsync( TService service, Document document, TLocalDeclarationStatementSyntax statement, CancellationToken cancellationToken) { var state = new State(); if (!await state.TryInitializeAsync(service, document, statement, cancellationToken).ConfigureAwait(false)) { return null; } return state; } private async Task<bool> TryInitializeAsync( TService service, Document document, TLocalDeclarationStatementSyntax node, CancellationToken cancellationToken) { var syntaxFacts = document.GetLanguageService<ISyntaxFactsService>(); DeclarationStatement = node; var variables = syntaxFacts.GetVariablesOfLocalDeclarationStatement(DeclarationStatement); if (variables.Count != 1) { return false; } VariableDeclarator = (TVariableDeclaratorSyntax)variables[0]; if (!service.IsValidVariableDeclarator(VariableDeclarator)) { return false; } OutermostBlock = syntaxFacts.GetStatementContainer(DeclarationStatement); if (!syntaxFacts.IsExecutableBlock(OutermostBlock)) { return false; } var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); LocalSymbol = (ILocalSymbol)semanticModel.GetDeclaredSymbol( service.GetVariableDeclaratorSymbolNode(VariableDeclarator), cancellationToken); if (LocalSymbol == null) { // This can happen in broken code, for example: "{ object x; object }" return false; } var findReferencesResult = await SymbolFinder.FindReferencesAsync(LocalSymbol, document.Project.Solution, cancellationToken).ConfigureAwait(false); var findReferencesList = findReferencesResult.ToList(); if (findReferencesList.Count != 1) { return false; } var references = findReferencesList[0].Locations.ToList(); if (references.Count == 0) { return false; } var syntaxRoot = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var referencingStatements = (from r in references let token = syntaxRoot.FindToken(r.Location.SourceSpan.Start) let statement = token.GetAncestor<TStatementSyntax>() where statement != null select statement).ToSet(); if (referencingStatements.Count == 0) { return false; } InnermostBlock = syntaxFacts.FindInnermostCommonExecutableBlock(referencingStatements); if (InnermostBlock == null) { return false; } InnermostBlockStatements = syntaxFacts.GetExecutableBlockStatements(InnermostBlock); OutermostBlockStatements = syntaxFacts.GetExecutableBlockStatements(OutermostBlock); var allAffectedStatements = new HashSet<TStatementSyntax>(referencingStatements.SelectMany( expr => expr.GetAncestorsOrThis<TStatementSyntax>())); FirstStatementAffectedInInnermostBlock = InnermostBlockStatements.Cast<TStatementSyntax>().FirstOrDefault(allAffectedStatements.Contains); if (FirstStatementAffectedInInnermostBlock == null) { return false; } if (FirstStatementAffectedInInnermostBlock == DeclarationStatement) { return false; } IndexOfDeclarationStatementInInnermostBlock = InnermostBlockStatements.IndexOf(DeclarationStatement); IndexOfFirstStatementAffectedInInnermostBlock = InnermostBlockStatements.IndexOf(FirstStatementAffectedInInnermostBlock); if (IndexOfDeclarationStatementInInnermostBlock >= 0 && IndexOfDeclarationStatementInInnermostBlock < IndexOfFirstStatementAffectedInInnermostBlock) { // Don't want to move a decl with initializer past other decls in order to move it to the first // affected statement. If we do we can end up in the following situation: #if false int x = 0; int y = 0; Console.WriteLine(x + y); #endif // Each of these declarations will want to 'move' down to the WriteLine // statement and we don't want to keep offering the refactoring. Note: this // solution is overly aggressive. Technically if 'y' weren't referenced in // Console.Writeline, then it might be a good idea to move the 'x'. But this // gives good enough behavior most of the time. // Note that if the variable declaration has no initializer, then we still want to offer // the move as the closest reference will be an assignment to the variable // and we should be able to merge the declaration and assignment into a single // statement. // So, we also check if the variable declaration has an initializer below. if (syntaxFacts.GetInitializerOfVariableDeclarator(VariableDeclarator) != null && InDeclarationStatementGroup(IndexOfDeclarationStatementInInnermostBlock, IndexOfFirstStatementAffectedInInnermostBlock)) { return false; } } var previousToken = FirstStatementAffectedInInnermostBlock.GetFirstToken().GetPreviousToken(); var affectedSpan = TextSpan.FromBounds(previousToken.SpanStart, FirstStatementAffectedInInnermostBlock.Span.End); if (semanticModel.SyntaxTree.OverlapsHiddenPosition(affectedSpan, cancellationToken)) { return false; } return true; } private bool InDeclarationStatementGroup( int originalIndexInBlock, int firstStatementIndexAffectedInBlock) { for (var i = originalIndexInBlock; i < firstStatementIndexAffectedInBlock; i++) { if (!(InnermostBlockStatements[i] is TLocalDeclarationStatementSyntax)) { return false; } } return true; } } } }
-1
dotnet/roslyn
55,262
Fix LSP completions when all items have default commit characters
Fixes an exception stack trace seen in https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1362284 Also fixes behavior of promotion of commit characters to the list to include default commit characters
dibarbet
2021-07-30T02:43:35Z
2021-07-30T21:21:47Z
2f7dffa534aceb92e9767568e88535c926588d12
65ee073bf6cea571a68193793420ecee60752711
Fix LSP completions when all items have default commit characters. Fixes an exception stack trace seen in https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1362284 Also fixes behavior of promotion of commit characters to the list to include default commit characters
./src/EditorFeatures/CSharpTest/UnsealClass/UnsealClassTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CSharp.UnsealClass; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; using Xunit.Abstractions; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.UnsealClass { [Trait(Traits.Feature, Traits.Features.CodeActionsUnsealClass)] public sealed class UnsealClassTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest { public UnsealClassTests(ITestOutputHelper logger) : base(logger) { } internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace) => (null, new CSharpUnsealClassCodeFixProvider()); [Fact] public async Task RemovedFromSealedClass() { await TestInRegularAndScriptAsync(@" sealed class C { } class D : [|C|] { }", @" class C { } class D : C { }"); } [Fact] public async Task RemovedFromSealedClassWithOtherModifiersPreserved() { await TestInRegularAndScriptAsync(@" public sealed unsafe class C { } class D : [|C|] { }", @" public unsafe class C { } class D : C { }"); } [Fact] public async Task RemovedFromSealedClassWithConstructedGeneric() { await TestInRegularAndScriptAsync(@" sealed class C<T> { } class D : [|C<int>|] { }", @" class C<T> { } class D : C<int> { }"); } [Fact] public async Task NotOfferedForNonSealedClass() { await TestMissingInRegularAndScriptAsync(@" class C { } class D : [|C|] { }"); } [Fact] public async Task NotOfferedForStaticClass() { await TestMissingInRegularAndScriptAsync(@" static class C { } class D : [|C|] { }"); } [Fact] public async Task NotOfferedForStruct() { await TestMissingInRegularAndScriptAsync(@" struct S { } class D : [|S|] { }"); } [Fact] public async Task NotOfferedForDelegate() { await TestMissingInRegularAndScriptAsync(@" delegate void F(); { } class D : [|F|] { }"); } [Fact] public async Task NotOfferedForSealedClassFromMetadata1() { await TestMissingInRegularAndScriptAsync(@" class D : [|string|] { }"); } [Fact] public async Task NotOfferedForSealedClassFromMetadata2() { await TestMissingInRegularAndScriptAsync(@" class D : [|System.ApplicationId|] { }"); } [Fact] public async Task RemovedFromAllPartialClassDeclarationsInSameFile() { await TestInRegularAndScriptAsync(@" public sealed partial class C { } partial class C { } sealed partial class C { } class D : [|C|] { }", @" public partial class C { } partial class C { } partial class C { } class D : C { }"); } [Fact] public async Task RemovedFromAllPartialClassDeclarationsAcrossFiles() { await TestInRegularAndScriptAsync(@" <Workspace> <Project Language=""C#""> <Document> public sealed partial class C { } </Document> <Document> partial class C { } sealed partial class C { } </Document> <Document> class D : [|C|] { } </Document> </Project> </Workspace>", @" <Workspace> <Project Language=""C#""> <Document> public partial class C { } </Document> <Document> partial class C { } partial class C { } </Document> <Document> class D : C { } </Document> </Project> </Workspace>"); } [Fact] public async Task RemovedFromClassInVisualBasicProject() { await TestInRegularAndScriptAsync(@" <Workspace> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Project1""> <ProjectReference>Project2</ProjectReference> <Document> class D : [|C|] { } </Document> </Project> <Project Language=""Visual Basic"" CommonReferences=""true"" AssemblyName=""Project2""> <Document> public notinheritable class C end class </Document> </Project> </Workspace>", @" <Workspace> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Project1""> <ProjectReference>Project2</ProjectReference> <Document> class D : C { } </Document> </Project> <Project Language=""Visual Basic"" CommonReferences=""true"" AssemblyName=""Project2""> <Document> public class C end class </Document> </Project> </Workspace>"); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CSharp.UnsealClass; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; using Xunit.Abstractions; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.UnsealClass { [Trait(Traits.Feature, Traits.Features.CodeActionsUnsealClass)] public sealed class UnsealClassTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest { public UnsealClassTests(ITestOutputHelper logger) : base(logger) { } internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace) => (null, new CSharpUnsealClassCodeFixProvider()); [Fact] public async Task RemovedFromSealedClass() { await TestInRegularAndScriptAsync(@" sealed class C { } class D : [|C|] { }", @" class C { } class D : C { }"); } [Fact] public async Task RemovedFromSealedClassWithOtherModifiersPreserved() { await TestInRegularAndScriptAsync(@" public sealed unsafe class C { } class D : [|C|] { }", @" public unsafe class C { } class D : C { }"); } [Fact] public async Task RemovedFromSealedClassWithConstructedGeneric() { await TestInRegularAndScriptAsync(@" sealed class C<T> { } class D : [|C<int>|] { }", @" class C<T> { } class D : C<int> { }"); } [Fact] public async Task NotOfferedForNonSealedClass() { await TestMissingInRegularAndScriptAsync(@" class C { } class D : [|C|] { }"); } [Fact] public async Task NotOfferedForStaticClass() { await TestMissingInRegularAndScriptAsync(@" static class C { } class D : [|C|] { }"); } [Fact] public async Task NotOfferedForStruct() { await TestMissingInRegularAndScriptAsync(@" struct S { } class D : [|S|] { }"); } [Fact] public async Task NotOfferedForDelegate() { await TestMissingInRegularAndScriptAsync(@" delegate void F(); { } class D : [|F|] { }"); } [Fact] public async Task NotOfferedForSealedClassFromMetadata1() { await TestMissingInRegularAndScriptAsync(@" class D : [|string|] { }"); } [Fact] public async Task NotOfferedForSealedClassFromMetadata2() { await TestMissingInRegularAndScriptAsync(@" class D : [|System.ApplicationId|] { }"); } [Fact] public async Task RemovedFromAllPartialClassDeclarationsInSameFile() { await TestInRegularAndScriptAsync(@" public sealed partial class C { } partial class C { } sealed partial class C { } class D : [|C|] { }", @" public partial class C { } partial class C { } partial class C { } class D : C { }"); } [Fact] public async Task RemovedFromAllPartialClassDeclarationsAcrossFiles() { await TestInRegularAndScriptAsync(@" <Workspace> <Project Language=""C#""> <Document> public sealed partial class C { } </Document> <Document> partial class C { } sealed partial class C { } </Document> <Document> class D : [|C|] { } </Document> </Project> </Workspace>", @" <Workspace> <Project Language=""C#""> <Document> public partial class C { } </Document> <Document> partial class C { } partial class C { } </Document> <Document> class D : C { } </Document> </Project> </Workspace>"); } [Fact] public async Task RemovedFromClassInVisualBasicProject() { await TestInRegularAndScriptAsync(@" <Workspace> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Project1""> <ProjectReference>Project2</ProjectReference> <Document> class D : [|C|] { } </Document> </Project> <Project Language=""Visual Basic"" CommonReferences=""true"" AssemblyName=""Project2""> <Document> public notinheritable class C end class </Document> </Project> </Workspace>", @" <Workspace> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Project1""> <ProjectReference>Project2</ProjectReference> <Document> class D : C { } </Document> </Project> <Project Language=""Visual Basic"" CommonReferences=""true"" AssemblyName=""Project2""> <Document> public class C end class </Document> </Project> </Workspace>"); } } }
-1
dotnet/roslyn
55,262
Fix LSP completions when all items have default commit characters
Fixes an exception stack trace seen in https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1362284 Also fixes behavior of promotion of commit characters to the list to include default commit characters
dibarbet
2021-07-30T02:43:35Z
2021-07-30T21:21:47Z
2f7dffa534aceb92e9767568e88535c926588d12
65ee073bf6cea571a68193793420ecee60752711
Fix LSP completions when all items have default commit characters. Fixes an exception stack trace seen in https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1362284 Also fixes behavior of promotion of commit characters to the list to include default commit characters
./src/Compilers/CSharp/Portable/Symbols/NamespaceSymbol.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Symbols; namespace Microsoft.CodeAnalysis.CSharp.Symbols { /// <summary> /// Represents a namespace. /// </summary> internal abstract partial class NamespaceSymbol : NamespaceOrTypeSymbol, INamespaceSymbolInternal { // PERF: initialization of the following fields will allocate, so we make them lazy private ImmutableArray<NamedTypeSymbol> _lazyTypesMightContainExtensionMethods; private string _lazyQualifiedName; // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! // Changes to the public interface of this class should remain synchronized with the VB version. // Do not make any changes to the public interface without making the corresponding change // to the VB version. // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! /// <summary> /// Get all the members of this symbol that are namespaces. /// </summary> /// <returns>An IEnumerable containing all the namespaces that are members of this symbol. /// If this symbol has no namespace members, returns an empty IEnumerable. Never returns /// null.</returns> public IEnumerable<NamespaceSymbol> GetNamespaceMembers() { return this.GetMembers().OfType<NamespaceSymbol>(); } /// <summary> /// Returns whether this namespace is the unnamed, global namespace that is /// at the root of all namespaces. /// </summary> public virtual bool IsGlobalNamespace { get { return (object)ContainingNamespace == null; } } internal abstract NamespaceExtent Extent { get; } /// <summary> /// The kind of namespace: Module, Assembly or Compilation. /// Module namespaces contain only members from the containing module that share the same namespace name. /// Assembly namespaces contain members for all modules in the containing assembly that share the same namespace name. /// Compilation namespaces contain all members, from source or referenced metadata (assemblies and modules) that share the same namespace name. /// </summary> public NamespaceKind NamespaceKind { get { return this.Extent.Kind; } } /// <summary> /// The containing compilation for compilation namespaces. /// </summary> public CSharpCompilation ContainingCompilation { get { return this.NamespaceKind == NamespaceKind.Compilation ? this.Extent.Compilation : null; } } /// <summary> /// If a namespace has Assembly or Compilation extent, it may be composed of multiple /// namespaces that are merged together. If so, ConstituentNamespaces returns /// all the namespaces that were merged. If this namespace was not merged, returns /// an array containing only this namespace. /// </summary> public virtual ImmutableArray<NamespaceSymbol> ConstituentNamespaces { get { return ImmutableArray.Create(this); } } public sealed override NamedTypeSymbol ContainingType { get { return null; } } /// <summary> /// Containing assembly. /// </summary> public abstract override AssemblySymbol ContainingAssembly { get; } internal override ModuleSymbol ContainingModule { get { var extent = this.Extent; if (extent.Kind == NamespaceKind.Module) { return extent.Module; } return null; } } /// <summary> /// Gets the kind of this symbol. /// </summary> public sealed override SymbolKind Kind { get { return SymbolKind.Namespace; } } public sealed override bool IsImplicitlyDeclared { get { return this.IsGlobalNamespace; } } /// <summary> /// Implements visitor pattern. /// </summary> internal override TResult Accept<TArgument, TResult>(CSharpSymbolVisitor<TArgument, TResult> visitor, TArgument argument) { return visitor.VisitNamespace(this, argument); } public override void Accept(CSharpSymbolVisitor visitor) { visitor.VisitNamespace(this); } public override TResult Accept<TResult>(CSharpSymbolVisitor<TResult> visitor) { return visitor.VisitNamespace(this); } // Only the compiler can create namespace symbols. internal NamespaceSymbol() { } /// <summary> /// Get this accessibility that was declared on this symbol. For symbols that do not have /// accessibility declared on them, returns NotApplicable. /// </summary> public sealed override Accessibility DeclaredAccessibility { // C# spec 3.5.1: Namespaces implicitly have public declared accessibility. get { return Accessibility.Public; } } /// <summary> /// Returns true if this symbol is "static"; i.e., declared with the "static" modifier or /// implicitly static. /// </summary> public sealed override bool IsStatic { get { return true; } } /// <summary> /// Returns true if this symbol was declared as requiring an override; i.e., declared with /// the "abstract" modifier. Also returns true on a type declared as "abstract", all /// interface types, and members of interface types. /// </summary> public sealed override bool IsAbstract { get { return false; } } /// <summary> /// Returns true if this symbol was declared to override a base class member and was also /// sealed from further overriding; i.e., declared with the "sealed" modifier. Also set for /// types that do not allow a derived class (declared with "sealed" or "static" or "struct" /// or "enum" or "delegate"). /// </summary> public sealed override bool IsSealed { get { return false; } } /// <summary> /// Returns data decoded from Obsolete attribute or null if there is no Obsolete attribute. /// This property returns ObsoleteAttributeData.Uninitialized if attribute arguments haven't been decoded yet. /// </summary> internal sealed override ObsoleteAttributeData ObsoleteAttributeData { get { return null; } } /// <summary> /// Returns an implicit type symbol for this namespace or null if there is none. This type /// wraps misplaced global code. /// </summary> internal NamedTypeSymbol ImplicitType { get { var types = this.GetTypeMembers(TypeSymbol.ImplicitTypeName); if (types.Length == 0) { return null; } Debug.Assert(types.Length == 1); return types[0]; } } /// <summary> /// Lookup a nested namespace. /// </summary> /// <param name="names"> /// Sequence of names for nested child namespaces. /// </param> /// <returns> /// Symbol for the most nested namespace, if found. Nothing /// if namespace or any part of it can not be found. /// </returns> internal NamespaceSymbol LookupNestedNamespace(ImmutableArray<string> names) { NamespaceSymbol scope = this; foreach (string name in names) { NamespaceSymbol nextScope = null; foreach (NamespaceOrTypeSymbol symbol in scope.GetMembers(name)) { var ns = symbol as NamespaceSymbol; if ((object)ns != null) { if ((object)nextScope != null) { Debug.Assert((object)nextScope == null, "Why did we run into an unmerged namespace?"); nextScope = null; break; } nextScope = ns; } } scope = nextScope; if ((object)scope == null) { break; } } return scope; } internal NamespaceSymbol GetNestedNamespace(string name) { foreach (var sym in this.GetMembers(name)) { if (sym.Kind == SymbolKind.Namespace) { return (NamespaceSymbol)sym; } } return null; } internal NamespaceSymbol GetNestedNamespace(NameSyntax name) { switch (name.Kind()) { case SyntaxKind.GenericName: // DeclarationTreeBuilder.VisitNamespace uses the PlainName, even for generic names case SyntaxKind.IdentifierName: return this.GetNestedNamespace(((SimpleNameSyntax)name).Identifier.ValueText); case SyntaxKind.QualifiedName: var qn = (QualifiedNameSyntax)name; var leftNs = this.GetNestedNamespace(qn.Left); if ((object)leftNs != null) { return leftNs.GetNestedNamespace(qn.Right); } break; case SyntaxKind.AliasQualifiedName: // This is an error scenario, but we should still handle it. // We recover in the same way as DeclarationTreeBuilder.VisitNamespaceDeclaration. return this.GetNestedNamespace(name.GetUnqualifiedName().Identifier.ValueText); } return null; } private ImmutableArray<NamedTypeSymbol> TypesMightContainExtensionMethods { get { var typesWithExtensionMethods = this._lazyTypesMightContainExtensionMethods; if (typesWithExtensionMethods.IsDefault) { this._lazyTypesMightContainExtensionMethods = this.GetTypeMembersUnordered().WhereAsArray(t => t.MightContainExtensionMethods); typesWithExtensionMethods = this._lazyTypesMightContainExtensionMethods; } return typesWithExtensionMethods; } } /// <summary> /// Add all extension methods in this namespace to the given list. If name or arity /// or both are provided, only those extension methods that match are included. /// </summary> /// <param name="methods">Methods list</param> /// <param name="nameOpt">Optional method name</param> /// <param name="arity">Method arity</param> /// <param name="options">Lookup options</param> internal virtual void GetExtensionMethods(ArrayBuilder<MethodSymbol> methods, string nameOpt, int arity, LookupOptions options) { var assembly = this.ContainingAssembly; // Only MergedAssemblySymbol should have a null ContainingAssembly // and MergedAssemblySymbol overrides GetExtensionMethods. Debug.Assert((object)assembly != null); if (!assembly.MightContainExtensionMethods) { return; } var typesWithExtensionMethods = this.TypesMightContainExtensionMethods; foreach (var type in typesWithExtensionMethods) { type.DoGetExtensionMethods(methods, nameOpt, arity, options); } } internal string QualifiedName { get { return _lazyQualifiedName ?? (_lazyQualifiedName = this.ToDisplayString(SymbolDisplayFormat.QualifiedNameOnlyFormat)); } } protected sealed override ISymbol CreateISymbol() { return new PublicModel.NamespaceSymbol(this); } bool INamespaceSymbolInternal.IsGlobalNamespace => this.IsGlobalNamespace; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Symbols; namespace Microsoft.CodeAnalysis.CSharp.Symbols { /// <summary> /// Represents a namespace. /// </summary> internal abstract partial class NamespaceSymbol : NamespaceOrTypeSymbol, INamespaceSymbolInternal { // PERF: initialization of the following fields will allocate, so we make them lazy private ImmutableArray<NamedTypeSymbol> _lazyTypesMightContainExtensionMethods; private string _lazyQualifiedName; // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! // Changes to the public interface of this class should remain synchronized with the VB version. // Do not make any changes to the public interface without making the corresponding change // to the VB version. // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! /// <summary> /// Get all the members of this symbol that are namespaces. /// </summary> /// <returns>An IEnumerable containing all the namespaces that are members of this symbol. /// If this symbol has no namespace members, returns an empty IEnumerable. Never returns /// null.</returns> public IEnumerable<NamespaceSymbol> GetNamespaceMembers() { return this.GetMembers().OfType<NamespaceSymbol>(); } /// <summary> /// Returns whether this namespace is the unnamed, global namespace that is /// at the root of all namespaces. /// </summary> public virtual bool IsGlobalNamespace { get { return (object)ContainingNamespace == null; } } internal abstract NamespaceExtent Extent { get; } /// <summary> /// The kind of namespace: Module, Assembly or Compilation. /// Module namespaces contain only members from the containing module that share the same namespace name. /// Assembly namespaces contain members for all modules in the containing assembly that share the same namespace name. /// Compilation namespaces contain all members, from source or referenced metadata (assemblies and modules) that share the same namespace name. /// </summary> public NamespaceKind NamespaceKind { get { return this.Extent.Kind; } } /// <summary> /// The containing compilation for compilation namespaces. /// </summary> public CSharpCompilation ContainingCompilation { get { return this.NamespaceKind == NamespaceKind.Compilation ? this.Extent.Compilation : null; } } /// <summary> /// If a namespace has Assembly or Compilation extent, it may be composed of multiple /// namespaces that are merged together. If so, ConstituentNamespaces returns /// all the namespaces that were merged. If this namespace was not merged, returns /// an array containing only this namespace. /// </summary> public virtual ImmutableArray<NamespaceSymbol> ConstituentNamespaces { get { return ImmutableArray.Create(this); } } public sealed override NamedTypeSymbol ContainingType { get { return null; } } /// <summary> /// Containing assembly. /// </summary> public abstract override AssemblySymbol ContainingAssembly { get; } internal override ModuleSymbol ContainingModule { get { var extent = this.Extent; if (extent.Kind == NamespaceKind.Module) { return extent.Module; } return null; } } /// <summary> /// Gets the kind of this symbol. /// </summary> public sealed override SymbolKind Kind { get { return SymbolKind.Namespace; } } public sealed override bool IsImplicitlyDeclared { get { return this.IsGlobalNamespace; } } /// <summary> /// Implements visitor pattern. /// </summary> internal override TResult Accept<TArgument, TResult>(CSharpSymbolVisitor<TArgument, TResult> visitor, TArgument argument) { return visitor.VisitNamespace(this, argument); } public override void Accept(CSharpSymbolVisitor visitor) { visitor.VisitNamespace(this); } public override TResult Accept<TResult>(CSharpSymbolVisitor<TResult> visitor) { return visitor.VisitNamespace(this); } // Only the compiler can create namespace symbols. internal NamespaceSymbol() { } /// <summary> /// Get this accessibility that was declared on this symbol. For symbols that do not have /// accessibility declared on them, returns NotApplicable. /// </summary> public sealed override Accessibility DeclaredAccessibility { // C# spec 3.5.1: Namespaces implicitly have public declared accessibility. get { return Accessibility.Public; } } /// <summary> /// Returns true if this symbol is "static"; i.e., declared with the "static" modifier or /// implicitly static. /// </summary> public sealed override bool IsStatic { get { return true; } } /// <summary> /// Returns true if this symbol was declared as requiring an override; i.e., declared with /// the "abstract" modifier. Also returns true on a type declared as "abstract", all /// interface types, and members of interface types. /// </summary> public sealed override bool IsAbstract { get { return false; } } /// <summary> /// Returns true if this symbol was declared to override a base class member and was also /// sealed from further overriding; i.e., declared with the "sealed" modifier. Also set for /// types that do not allow a derived class (declared with "sealed" or "static" or "struct" /// or "enum" or "delegate"). /// </summary> public sealed override bool IsSealed { get { return false; } } /// <summary> /// Returns data decoded from Obsolete attribute or null if there is no Obsolete attribute. /// This property returns ObsoleteAttributeData.Uninitialized if attribute arguments haven't been decoded yet. /// </summary> internal sealed override ObsoleteAttributeData ObsoleteAttributeData { get { return null; } } /// <summary> /// Returns an implicit type symbol for this namespace or null if there is none. This type /// wraps misplaced global code. /// </summary> internal NamedTypeSymbol ImplicitType { get { var types = this.GetTypeMembers(TypeSymbol.ImplicitTypeName); if (types.Length == 0) { return null; } Debug.Assert(types.Length == 1); return types[0]; } } /// <summary> /// Lookup a nested namespace. /// </summary> /// <param name="names"> /// Sequence of names for nested child namespaces. /// </param> /// <returns> /// Symbol for the most nested namespace, if found. Nothing /// if namespace or any part of it can not be found. /// </returns> internal NamespaceSymbol LookupNestedNamespace(ImmutableArray<string> names) { NamespaceSymbol scope = this; foreach (string name in names) { NamespaceSymbol nextScope = null; foreach (NamespaceOrTypeSymbol symbol in scope.GetMembers(name)) { var ns = symbol as NamespaceSymbol; if ((object)ns != null) { if ((object)nextScope != null) { Debug.Assert((object)nextScope == null, "Why did we run into an unmerged namespace?"); nextScope = null; break; } nextScope = ns; } } scope = nextScope; if ((object)scope == null) { break; } } return scope; } internal NamespaceSymbol GetNestedNamespace(string name) { foreach (var sym in this.GetMembers(name)) { if (sym.Kind == SymbolKind.Namespace) { return (NamespaceSymbol)sym; } } return null; } internal NamespaceSymbol GetNestedNamespace(NameSyntax name) { switch (name.Kind()) { case SyntaxKind.GenericName: // DeclarationTreeBuilder.VisitNamespace uses the PlainName, even for generic names case SyntaxKind.IdentifierName: return this.GetNestedNamespace(((SimpleNameSyntax)name).Identifier.ValueText); case SyntaxKind.QualifiedName: var qn = (QualifiedNameSyntax)name; var leftNs = this.GetNestedNamespace(qn.Left); if ((object)leftNs != null) { return leftNs.GetNestedNamespace(qn.Right); } break; case SyntaxKind.AliasQualifiedName: // This is an error scenario, but we should still handle it. // We recover in the same way as DeclarationTreeBuilder.VisitNamespaceDeclaration. return this.GetNestedNamespace(name.GetUnqualifiedName().Identifier.ValueText); } return null; } private ImmutableArray<NamedTypeSymbol> TypesMightContainExtensionMethods { get { var typesWithExtensionMethods = this._lazyTypesMightContainExtensionMethods; if (typesWithExtensionMethods.IsDefault) { this._lazyTypesMightContainExtensionMethods = this.GetTypeMembersUnordered().WhereAsArray(t => t.MightContainExtensionMethods); typesWithExtensionMethods = this._lazyTypesMightContainExtensionMethods; } return typesWithExtensionMethods; } } /// <summary> /// Add all extension methods in this namespace to the given list. If name or arity /// or both are provided, only those extension methods that match are included. /// </summary> /// <param name="methods">Methods list</param> /// <param name="nameOpt">Optional method name</param> /// <param name="arity">Method arity</param> /// <param name="options">Lookup options</param> internal virtual void GetExtensionMethods(ArrayBuilder<MethodSymbol> methods, string nameOpt, int arity, LookupOptions options) { var assembly = this.ContainingAssembly; // Only MergedAssemblySymbol should have a null ContainingAssembly // and MergedAssemblySymbol overrides GetExtensionMethods. Debug.Assert((object)assembly != null); if (!assembly.MightContainExtensionMethods) { return; } var typesWithExtensionMethods = this.TypesMightContainExtensionMethods; foreach (var type in typesWithExtensionMethods) { type.DoGetExtensionMethods(methods, nameOpt, arity, options); } } internal string QualifiedName { get { return _lazyQualifiedName ?? (_lazyQualifiedName = this.ToDisplayString(SymbolDisplayFormat.QualifiedNameOnlyFormat)); } } protected sealed override ISymbol CreateISymbol() { return new PublicModel.NamespaceSymbol(this); } bool INamespaceSymbolInternal.IsGlobalNamespace => this.IsGlobalNamespace; } }
-1
dotnet/roslyn
55,262
Fix LSP completions when all items have default commit characters
Fixes an exception stack trace seen in https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1362284 Also fixes behavior of promotion of commit characters to the list to include default commit characters
dibarbet
2021-07-30T02:43:35Z
2021-07-30T21:21:47Z
2f7dffa534aceb92e9767568e88535c926588d12
65ee073bf6cea571a68193793420ecee60752711
Fix LSP completions when all items have default commit characters. Fixes an exception stack trace seen in https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1362284 Also fixes behavior of promotion of commit characters to the list to include default commit characters
./src/Workspaces/Remote/ServiceHub/Services/SymbolSearchUpdate/RemoteSymbolSearchUpdateService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.IO; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.SymbolSearch; namespace Microsoft.CodeAnalysis.Remote { internal sealed class RemoteSymbolSearchUpdateService : BrokeredServiceBase, IRemoteSymbolSearchUpdateService { internal sealed class Factory : FactoryBase<IRemoteSymbolSearchUpdateService, IRemoteSymbolSearchUpdateService.ICallback> { protected override IRemoteSymbolSearchUpdateService CreateService(in ServiceConstructionArguments arguments, RemoteCallback<IRemoteSymbolSearchUpdateService.ICallback> callback) => new RemoteSymbolSearchUpdateService(arguments, callback); } private sealed class LogService : ISymbolSearchLogService { private readonly RemoteCallback<IRemoteSymbolSearchUpdateService.ICallback> _callback; private readonly RemoteServiceCallbackId _callbackId; public LogService(RemoteCallback<IRemoteSymbolSearchUpdateService.ICallback> callback, RemoteServiceCallbackId callbackId) { _callback = callback; _callbackId = callbackId; } public ValueTask LogExceptionAsync(string exception, string text, CancellationToken cancellationToken) => _callback.InvokeAsync((callback, cancellationToken) => callback.LogExceptionAsync(_callbackId, exception, text, cancellationToken), cancellationToken); public ValueTask LogInfoAsync(string text, CancellationToken cancellationToken) => _callback.InvokeAsync((callback, cancellationToken) => callback.LogInfoAsync(_callbackId, text, cancellationToken), cancellationToken); } private readonly ISymbolSearchUpdateEngine _updateEngine; private readonly RemoteCallback<IRemoteSymbolSearchUpdateService.ICallback> _callback; public RemoteSymbolSearchUpdateService(in ServiceConstructionArguments arguments, RemoteCallback<IRemoteSymbolSearchUpdateService.ICallback> callback) : base(arguments) { _updateEngine = SymbolSearchUpdateEngineFactory.CreateEngineInProcess(); _callback = callback; } public ValueTask UpdateContinuouslyAsync(RemoteServiceCallbackId callbackId, string sourceName, string localSettingsDirectory, CancellationToken cancellationToken) { return RunServiceAsync(cancellationToken => _updateEngine.UpdateContinuouslyAsync(sourceName, localSettingsDirectory, new LogService(_callback, callbackId), cancellationToken), cancellationToken); } public ValueTask<ImmutableArray<PackageWithTypeResult>> FindPackagesWithTypeAsync(string source, string name, int arity, CancellationToken cancellationToken) { return RunServiceAsync(cancellationToken => _updateEngine.FindPackagesWithTypeAsync(source, name, arity, cancellationToken), cancellationToken); } public ValueTask<ImmutableArray<PackageWithAssemblyResult>> FindPackagesWithAssemblyAsync(string source, string assemblyName, CancellationToken cancellationToken) { return RunServiceAsync(cancallationToken => _updateEngine.FindPackagesWithAssemblyAsync(source, assemblyName, cancellationToken), cancellationToken); } public ValueTask<ImmutableArray<ReferenceAssemblyWithTypeResult>> FindReferenceAssembliesWithTypeAsync(string name, int arity, CancellationToken cancellationToken) { return RunServiceAsync(cancallationToken => _updateEngine.FindReferenceAssembliesWithTypeAsync(name, arity, cancellationToken), cancellationToken); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.IO; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.SymbolSearch; namespace Microsoft.CodeAnalysis.Remote { internal sealed class RemoteSymbolSearchUpdateService : BrokeredServiceBase, IRemoteSymbolSearchUpdateService { internal sealed class Factory : FactoryBase<IRemoteSymbolSearchUpdateService, IRemoteSymbolSearchUpdateService.ICallback> { protected override IRemoteSymbolSearchUpdateService CreateService(in ServiceConstructionArguments arguments, RemoteCallback<IRemoteSymbolSearchUpdateService.ICallback> callback) => new RemoteSymbolSearchUpdateService(arguments, callback); } private sealed class LogService : ISymbolSearchLogService { private readonly RemoteCallback<IRemoteSymbolSearchUpdateService.ICallback> _callback; private readonly RemoteServiceCallbackId _callbackId; public LogService(RemoteCallback<IRemoteSymbolSearchUpdateService.ICallback> callback, RemoteServiceCallbackId callbackId) { _callback = callback; _callbackId = callbackId; } public ValueTask LogExceptionAsync(string exception, string text, CancellationToken cancellationToken) => _callback.InvokeAsync((callback, cancellationToken) => callback.LogExceptionAsync(_callbackId, exception, text, cancellationToken), cancellationToken); public ValueTask LogInfoAsync(string text, CancellationToken cancellationToken) => _callback.InvokeAsync((callback, cancellationToken) => callback.LogInfoAsync(_callbackId, text, cancellationToken), cancellationToken); } private readonly ISymbolSearchUpdateEngine _updateEngine; private readonly RemoteCallback<IRemoteSymbolSearchUpdateService.ICallback> _callback; public RemoteSymbolSearchUpdateService(in ServiceConstructionArguments arguments, RemoteCallback<IRemoteSymbolSearchUpdateService.ICallback> callback) : base(arguments) { _updateEngine = SymbolSearchUpdateEngineFactory.CreateEngineInProcess(); _callback = callback; } public ValueTask UpdateContinuouslyAsync(RemoteServiceCallbackId callbackId, string sourceName, string localSettingsDirectory, CancellationToken cancellationToken) { return RunServiceAsync(cancellationToken => _updateEngine.UpdateContinuouslyAsync(sourceName, localSettingsDirectory, new LogService(_callback, callbackId), cancellationToken), cancellationToken); } public ValueTask<ImmutableArray<PackageWithTypeResult>> FindPackagesWithTypeAsync(string source, string name, int arity, CancellationToken cancellationToken) { return RunServiceAsync(cancellationToken => _updateEngine.FindPackagesWithTypeAsync(source, name, arity, cancellationToken), cancellationToken); } public ValueTask<ImmutableArray<PackageWithAssemblyResult>> FindPackagesWithAssemblyAsync(string source, string assemblyName, CancellationToken cancellationToken) { return RunServiceAsync(cancallationToken => _updateEngine.FindPackagesWithAssemblyAsync(source, assemblyName, cancellationToken), cancellationToken); } public ValueTask<ImmutableArray<ReferenceAssemblyWithTypeResult>> FindReferenceAssembliesWithTypeAsync(string name, int arity, CancellationToken cancellationToken) { return RunServiceAsync(cancallationToken => _updateEngine.FindReferenceAssembliesWithTypeAsync(name, arity, cancellationToken), cancellationToken); } } }
-1
dotnet/roslyn
55,262
Fix LSP completions when all items have default commit characters
Fixes an exception stack trace seen in https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1362284 Also fixes behavior of promotion of commit characters to the list to include default commit characters
dibarbet
2021-07-30T02:43:35Z
2021-07-30T21:21:47Z
2f7dffa534aceb92e9767568e88535c926588d12
65ee073bf6cea571a68193793420ecee60752711
Fix LSP completions when all items have default commit characters. Fixes an exception stack trace seen in https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1362284 Also fixes behavior of promotion of commit characters to the list to include default commit characters
./src/ExpressionEvaluator/Core/Source/FunctionResolver/VisualBasic/MemberSignatureParser.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET 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.ExpressionEvaluator; using System; using System.Collections.Immutable; using System.Diagnostics; namespace Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator { internal sealed partial class MemberSignatureParser { internal static readonly StringComparer StringComparer = StringComparer.OrdinalIgnoreCase; internal static readonly ImmutableHashSet<string> Keywords = GetKeywords(StringComparer); internal static readonly ImmutableDictionary<string, SyntaxKind> KeywordKinds = GetKeywordKinds(StringComparer); internal static RequestSignature Parse(string signature) { var scanner = new Scanner(signature); var builder = ImmutableArray.CreateBuilder<Token>(); Token token; do { scanner.MoveNext(); token = scanner.CurrentToken; builder.Add(token); } while (token.Kind != TokenKind.End); var parser = new MemberSignatureParser(builder.ToImmutable()); try { return parser.Parse(); } catch (InvalidSignatureException) { return null; } } private readonly ImmutableArray<Token> _tokens; private int _tokenIndex; private MemberSignatureParser(ImmutableArray<Token> tokens) { _tokens = tokens; _tokenIndex = 0; } private Token CurrentToken => _tokens[_tokenIndex]; private Token PeekToken(int offset) { return _tokens[_tokenIndex + offset]; } private Token EatToken() { var token = CurrentToken; Debug.Assert(token.Kind != TokenKind.End); _tokenIndex++; return token; } private RequestSignature Parse() { var methodName = ParseName(); var parameters = default(ImmutableArray<ParameterSignature>); if (CurrentToken.Kind == TokenKind.OpenParen) { parameters = ParseParameters(); } if (CurrentToken.Kind != TokenKind.End) { throw InvalidSignature(); } return new RequestSignature(methodName, parameters); } private Name ParseName() { Name signature = null; while (true) { switch (CurrentToken.Kind) { case TokenKind.Identifier: break; case TokenKind.Keyword: if (signature == null) { throw InvalidSignature(); } break; default: throw InvalidSignature(); } var name = EatToken().Text; signature = new QualifiedName(signature, name); if (IsStartOfTypeArguments()) { var typeParameters = ParseTypeParameters(); signature = new GenericName((QualifiedName)signature, typeParameters); } if (CurrentToken.Kind != TokenKind.Dot) { return signature; } EatToken(); } } private ImmutableArray<string> ParseTypeParameters() { Debug.Assert(IsStartOfTypeArguments()); EatToken(); EatToken(); var builder = ImmutableArray.CreateBuilder<string>(); while (true) { if (CurrentToken.Kind != TokenKind.Identifier) { throw InvalidSignature(); } var name = EatToken().Text; builder.Add(name); switch (CurrentToken.Kind) { case TokenKind.CloseParen: EatToken(); return builder.ToImmutable(); case TokenKind.Comma: EatToken(); break; default: throw InvalidSignature(); } } } private TypeSignature ParseTypeName() { TypeSignature signature = null; while (true) { switch (CurrentToken.Kind) { case TokenKind.Identifier: { var token = EatToken(); var name = token.Text; signature = new QualifiedTypeSignature(signature, name); } break; case TokenKind.Keyword: if (signature == null) { // Expand special type keywords (Object, Integer, etc.) to qualified names. // This is only done for the first identifier in a qualified name. var specialType = GetSpecialType(CurrentToken.KeywordKind); if (specialType != SpecialType.None) { EatToken(); signature = specialType.GetTypeSignature(); Debug.Assert(signature != null); } if (signature == null) { throw InvalidSignature(); } } else { var token = EatToken(); var name = token.Text; signature = new QualifiedTypeSignature(signature, name); } break; default: throw InvalidSignature(); } if (IsStartOfTypeArguments()) { var typeArguments = ParseTypeArguments(); signature = new GenericTypeSignature((QualifiedTypeSignature)signature, typeArguments); } if (CurrentToken.Kind != TokenKind.Dot) { return signature; } EatToken(); } } private ImmutableArray<TypeSignature> ParseTypeArguments() { Debug.Assert(IsStartOfTypeArguments()); EatToken(); EatToken(); var builder = ImmutableArray.CreateBuilder<TypeSignature>(); while (true) { var name = ParseType(); builder.Add(name); switch (CurrentToken.Kind) { case TokenKind.CloseParen: EatToken(); return builder.ToImmutable(); case TokenKind.Comma: EatToken(); break; default: throw InvalidSignature(); } } } private TypeSignature ParseType() { TypeSignature type = ParseTypeName(); while (true) { switch (CurrentToken.Kind) { case TokenKind.OpenParen: EatToken(); int rank = 1; while (CurrentToken.Kind == TokenKind.Comma) { EatToken(); rank++; } if (CurrentToken.Kind != TokenKind.CloseParen) { throw InvalidSignature(); } EatToken(); type = new ArrayTypeSignature(type, rank); break; case TokenKind.QuestionMark: EatToken(); type = new GenericTypeSignature( SpecialType.System_Nullable_T.GetTypeSignature(), ImmutableArray.Create(type)); break; default: return type; } } } private bool IsStartOfTypeArguments() { return CurrentToken.Kind == TokenKind.OpenParen && PeekToken(1).KeywordKind == SyntaxKind.OfKeyword; } private enum ParameterModifier { None, ByVal, ByRef, } private ParameterModifier ParseParameterModifier() { var modifier = ParameterModifier.None; while (true) { var m = ParameterModifier.None; switch (CurrentToken.KeywordKind) { case SyntaxKind.ByValKeyword: m = ParameterModifier.ByVal; break; case SyntaxKind.ByRefKeyword: m = ParameterModifier.ByRef; break; default: return modifier; } if (modifier != ParameterModifier.None) { // Duplicate modifiers. throw InvalidSignature(); } modifier = m; EatToken(); } } private ImmutableArray<ParameterSignature> ParseParameters() { Debug.Assert(CurrentToken.Kind == TokenKind.OpenParen); EatToken(); if (CurrentToken.Kind == TokenKind.CloseParen) { EatToken(); return ImmutableArray<ParameterSignature>.Empty; } var builder = ImmutableArray.CreateBuilder<ParameterSignature>(); while (true) { var modifier = ParseParameterModifier(); var parameterType = ParseType(); builder.Add(new ParameterSignature(parameterType, isByRef: modifier == ParameterModifier.ByRef)); switch (CurrentToken.Kind) { case TokenKind.CloseParen: EatToken(); return builder.ToImmutable(); case TokenKind.Comma: EatToken(); break; default: throw InvalidSignature(); } } } private static SpecialType GetSpecialType(SyntaxKind kind) { switch (kind) { case SyntaxKind.BooleanKeyword: return SpecialType.System_Boolean; case SyntaxKind.CharKeyword: return SpecialType.System_Char; case SyntaxKind.SByteKeyword: return SpecialType.System_SByte; case SyntaxKind.ByteKeyword: return SpecialType.System_Byte; case SyntaxKind.ShortKeyword: return SpecialType.System_Int16; case SyntaxKind.UShortKeyword: return SpecialType.System_UInt16; case SyntaxKind.IntegerKeyword: return SpecialType.System_Int32; case SyntaxKind.UIntegerKeyword: return SpecialType.System_UInt32; case SyntaxKind.LongKeyword: return SpecialType.System_Int64; case SyntaxKind.ULongKeyword: return SpecialType.System_UInt64; case SyntaxKind.SingleKeyword: return SpecialType.System_Single; case SyntaxKind.DoubleKeyword: return SpecialType.System_Double; case SyntaxKind.StringKeyword: return SpecialType.System_String; case SyntaxKind.ObjectKeyword: return SpecialType.System_Object; case SyntaxKind.DecimalKeyword: return SpecialType.System_Decimal; case SyntaxKind.DateKeyword: return SpecialType.System_DateTime; default: return SpecialType.None; } } private static Exception InvalidSignature() { return new InvalidSignatureException(); } private sealed class InvalidSignatureException : Exception { } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET 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.ExpressionEvaluator; using System; using System.Collections.Immutable; using System.Diagnostics; namespace Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator { internal sealed partial class MemberSignatureParser { internal static readonly StringComparer StringComparer = StringComparer.OrdinalIgnoreCase; internal static readonly ImmutableHashSet<string> Keywords = GetKeywords(StringComparer); internal static readonly ImmutableDictionary<string, SyntaxKind> KeywordKinds = GetKeywordKinds(StringComparer); internal static RequestSignature Parse(string signature) { var scanner = new Scanner(signature); var builder = ImmutableArray.CreateBuilder<Token>(); Token token; do { scanner.MoveNext(); token = scanner.CurrentToken; builder.Add(token); } while (token.Kind != TokenKind.End); var parser = new MemberSignatureParser(builder.ToImmutable()); try { return parser.Parse(); } catch (InvalidSignatureException) { return null; } } private readonly ImmutableArray<Token> _tokens; private int _tokenIndex; private MemberSignatureParser(ImmutableArray<Token> tokens) { _tokens = tokens; _tokenIndex = 0; } private Token CurrentToken => _tokens[_tokenIndex]; private Token PeekToken(int offset) { return _tokens[_tokenIndex + offset]; } private Token EatToken() { var token = CurrentToken; Debug.Assert(token.Kind != TokenKind.End); _tokenIndex++; return token; } private RequestSignature Parse() { var methodName = ParseName(); var parameters = default(ImmutableArray<ParameterSignature>); if (CurrentToken.Kind == TokenKind.OpenParen) { parameters = ParseParameters(); } if (CurrentToken.Kind != TokenKind.End) { throw InvalidSignature(); } return new RequestSignature(methodName, parameters); } private Name ParseName() { Name signature = null; while (true) { switch (CurrentToken.Kind) { case TokenKind.Identifier: break; case TokenKind.Keyword: if (signature == null) { throw InvalidSignature(); } break; default: throw InvalidSignature(); } var name = EatToken().Text; signature = new QualifiedName(signature, name); if (IsStartOfTypeArguments()) { var typeParameters = ParseTypeParameters(); signature = new GenericName((QualifiedName)signature, typeParameters); } if (CurrentToken.Kind != TokenKind.Dot) { return signature; } EatToken(); } } private ImmutableArray<string> ParseTypeParameters() { Debug.Assert(IsStartOfTypeArguments()); EatToken(); EatToken(); var builder = ImmutableArray.CreateBuilder<string>(); while (true) { if (CurrentToken.Kind != TokenKind.Identifier) { throw InvalidSignature(); } var name = EatToken().Text; builder.Add(name); switch (CurrentToken.Kind) { case TokenKind.CloseParen: EatToken(); return builder.ToImmutable(); case TokenKind.Comma: EatToken(); break; default: throw InvalidSignature(); } } } private TypeSignature ParseTypeName() { TypeSignature signature = null; while (true) { switch (CurrentToken.Kind) { case TokenKind.Identifier: { var token = EatToken(); var name = token.Text; signature = new QualifiedTypeSignature(signature, name); } break; case TokenKind.Keyword: if (signature == null) { // Expand special type keywords (Object, Integer, etc.) to qualified names. // This is only done for the first identifier in a qualified name. var specialType = GetSpecialType(CurrentToken.KeywordKind); if (specialType != SpecialType.None) { EatToken(); signature = specialType.GetTypeSignature(); Debug.Assert(signature != null); } if (signature == null) { throw InvalidSignature(); } } else { var token = EatToken(); var name = token.Text; signature = new QualifiedTypeSignature(signature, name); } break; default: throw InvalidSignature(); } if (IsStartOfTypeArguments()) { var typeArguments = ParseTypeArguments(); signature = new GenericTypeSignature((QualifiedTypeSignature)signature, typeArguments); } if (CurrentToken.Kind != TokenKind.Dot) { return signature; } EatToken(); } } private ImmutableArray<TypeSignature> ParseTypeArguments() { Debug.Assert(IsStartOfTypeArguments()); EatToken(); EatToken(); var builder = ImmutableArray.CreateBuilder<TypeSignature>(); while (true) { var name = ParseType(); builder.Add(name); switch (CurrentToken.Kind) { case TokenKind.CloseParen: EatToken(); return builder.ToImmutable(); case TokenKind.Comma: EatToken(); break; default: throw InvalidSignature(); } } } private TypeSignature ParseType() { TypeSignature type = ParseTypeName(); while (true) { switch (CurrentToken.Kind) { case TokenKind.OpenParen: EatToken(); int rank = 1; while (CurrentToken.Kind == TokenKind.Comma) { EatToken(); rank++; } if (CurrentToken.Kind != TokenKind.CloseParen) { throw InvalidSignature(); } EatToken(); type = new ArrayTypeSignature(type, rank); break; case TokenKind.QuestionMark: EatToken(); type = new GenericTypeSignature( SpecialType.System_Nullable_T.GetTypeSignature(), ImmutableArray.Create(type)); break; default: return type; } } } private bool IsStartOfTypeArguments() { return CurrentToken.Kind == TokenKind.OpenParen && PeekToken(1).KeywordKind == SyntaxKind.OfKeyword; } private enum ParameterModifier { None, ByVal, ByRef, } private ParameterModifier ParseParameterModifier() { var modifier = ParameterModifier.None; while (true) { var m = ParameterModifier.None; switch (CurrentToken.KeywordKind) { case SyntaxKind.ByValKeyword: m = ParameterModifier.ByVal; break; case SyntaxKind.ByRefKeyword: m = ParameterModifier.ByRef; break; default: return modifier; } if (modifier != ParameterModifier.None) { // Duplicate modifiers. throw InvalidSignature(); } modifier = m; EatToken(); } } private ImmutableArray<ParameterSignature> ParseParameters() { Debug.Assert(CurrentToken.Kind == TokenKind.OpenParen); EatToken(); if (CurrentToken.Kind == TokenKind.CloseParen) { EatToken(); return ImmutableArray<ParameterSignature>.Empty; } var builder = ImmutableArray.CreateBuilder<ParameterSignature>(); while (true) { var modifier = ParseParameterModifier(); var parameterType = ParseType(); builder.Add(new ParameterSignature(parameterType, isByRef: modifier == ParameterModifier.ByRef)); switch (CurrentToken.Kind) { case TokenKind.CloseParen: EatToken(); return builder.ToImmutable(); case TokenKind.Comma: EatToken(); break; default: throw InvalidSignature(); } } } private static SpecialType GetSpecialType(SyntaxKind kind) { switch (kind) { case SyntaxKind.BooleanKeyword: return SpecialType.System_Boolean; case SyntaxKind.CharKeyword: return SpecialType.System_Char; case SyntaxKind.SByteKeyword: return SpecialType.System_SByte; case SyntaxKind.ByteKeyword: return SpecialType.System_Byte; case SyntaxKind.ShortKeyword: return SpecialType.System_Int16; case SyntaxKind.UShortKeyword: return SpecialType.System_UInt16; case SyntaxKind.IntegerKeyword: return SpecialType.System_Int32; case SyntaxKind.UIntegerKeyword: return SpecialType.System_UInt32; case SyntaxKind.LongKeyword: return SpecialType.System_Int64; case SyntaxKind.ULongKeyword: return SpecialType.System_UInt64; case SyntaxKind.SingleKeyword: return SpecialType.System_Single; case SyntaxKind.DoubleKeyword: return SpecialType.System_Double; case SyntaxKind.StringKeyword: return SpecialType.System_String; case SyntaxKind.ObjectKeyword: return SpecialType.System_Object; case SyntaxKind.DecimalKeyword: return SpecialType.System_Decimal; case SyntaxKind.DateKeyword: return SpecialType.System_DateTime; default: return SpecialType.None; } } private static Exception InvalidSignature() { return new InvalidSignatureException(); } private sealed class InvalidSignatureException : Exception { } } }
-1
dotnet/roslyn
55,262
Fix LSP completions when all items have default commit characters
Fixes an exception stack trace seen in https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1362284 Also fixes behavior of promotion of commit characters to the list to include default commit characters
dibarbet
2021-07-30T02:43:35Z
2021-07-30T21:21:47Z
2f7dffa534aceb92e9767568e88535c926588d12
65ee073bf6cea571a68193793420ecee60752711
Fix LSP completions when all items have default commit characters. Fixes an exception stack trace seen in https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1362284 Also fixes behavior of promotion of commit characters to the list to include default commit characters
./src/Features/Core/Portable/SolutionCrawler/InternalSolutionCrawlerOptions.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using Microsoft.CodeAnalysis.Options; namespace Microsoft.CodeAnalysis.SolutionCrawler { internal static class InternalSolutionCrawlerOptions { private const string LocalRegistryPath = @"Roslyn\Internal\SolutionCrawler\"; public static readonly Option2<bool> SolutionCrawler = new(nameof(InternalSolutionCrawlerOptions), "Solution Crawler", defaultValue: true, storageLocations: new LocalUserProfileStorageLocation(LocalRegistryPath + "Solution Crawler")); public static readonly Option2<bool> DirectDependencyPropagationOnly = new(nameof(InternalSolutionCrawlerOptions), "Project propagation only on direct dependency", defaultValue: true, storageLocations: new LocalUserProfileStorageLocation(LocalRegistryPath + "Project propagation only on direct dependency")); public static readonly TimeSpan ActiveFileWorkerBackOffTimeSpan = TimeSpan.FromMilliseconds(100); public static readonly TimeSpan AllFilesWorkerBackOffTimeSpan = TimeSpan.FromMilliseconds(1500); public static readonly TimeSpan EntireProjectWorkerBackOffTimeSpan = TimeSpan.FromMilliseconds(5000); public static readonly TimeSpan SemanticChangeBackOffTimeSpan = TimeSpan.FromMilliseconds(100); public static readonly TimeSpan ProjectPropagationBackOffTimeSpan = TimeSpan.FromMilliseconds(500); public static readonly TimeSpan PreviewBackOffTimeSpan = TimeSpan.FromMilliseconds(500); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using Microsoft.CodeAnalysis.Options; namespace Microsoft.CodeAnalysis.SolutionCrawler { internal static class InternalSolutionCrawlerOptions { private const string LocalRegistryPath = @"Roslyn\Internal\SolutionCrawler\"; public static readonly Option2<bool> SolutionCrawler = new(nameof(InternalSolutionCrawlerOptions), "Solution Crawler", defaultValue: true, storageLocations: new LocalUserProfileStorageLocation(LocalRegistryPath + "Solution Crawler")); public static readonly Option2<bool> DirectDependencyPropagationOnly = new(nameof(InternalSolutionCrawlerOptions), "Project propagation only on direct dependency", defaultValue: true, storageLocations: new LocalUserProfileStorageLocation(LocalRegistryPath + "Project propagation only on direct dependency")); public static readonly TimeSpan ActiveFileWorkerBackOffTimeSpan = TimeSpan.FromMilliseconds(100); public static readonly TimeSpan AllFilesWorkerBackOffTimeSpan = TimeSpan.FromMilliseconds(1500); public static readonly TimeSpan EntireProjectWorkerBackOffTimeSpan = TimeSpan.FromMilliseconds(5000); public static readonly TimeSpan SemanticChangeBackOffTimeSpan = TimeSpan.FromMilliseconds(100); public static readonly TimeSpan ProjectPropagationBackOffTimeSpan = TimeSpan.FromMilliseconds(500); public static readonly TimeSpan PreviewBackOffTimeSpan = TimeSpan.FromMilliseconds(500); } }
-1
dotnet/roslyn
55,262
Fix LSP completions when all items have default commit characters
Fixes an exception stack trace seen in https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1362284 Also fixes behavior of promotion of commit characters to the list to include default commit characters
dibarbet
2021-07-30T02:43:35Z
2021-07-30T21:21:47Z
2f7dffa534aceb92e9767568e88535c926588d12
65ee073bf6cea571a68193793420ecee60752711
Fix LSP completions when all items have default commit characters. Fixes an exception stack trace seen in https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1362284 Also fixes behavior of promotion of commit characters to the list to include default commit characters
./src/VisualStudio/Core/Def/Implementation/ProjectSystem/RuleSets/VisualStudioRuleSetManager.RuleSetFile.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Shared.TestHooks; namespace Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem { internal sealed partial class VisualStudioRuleSetManager { private sealed class RuleSetFile : IRuleSetFile, IDisposable { private readonly VisualStudioRuleSetManager _ruleSetManager; private readonly object _gate = new(); private readonly CancellationTokenSource _disposalCancellationSource; private readonly CancellationToken _disposalToken; private FileChangeWatcher.IContext _fileChangeContext; private ReportDiagnostic _generalDiagnosticOption; private ImmutableDictionary<string, ReportDiagnostic> _specificDiagnosticOptions; private bool _subscribed = false; private bool _optionsRead = false; private bool _removedFromRuleSetManager = false; private Exception _exception; public RuleSetFile(string filePath, VisualStudioRuleSetManager ruleSetManager) { FilePath = filePath; _ruleSetManager = ruleSetManager; _disposalCancellationSource = new(); _disposalToken = _disposalCancellationSource.Token; } public void InitializeFileTracking(FileChangeWatcher fileChangeWatcher) { lock (_gate) { if (_fileChangeContext == null) { ImmutableArray<string> includes; try { includes = RuleSet.GetEffectiveIncludesFromFile(FilePath); } catch (Exception e) { // We couldn't read the rule set for whatever reason. Capture the exception // so we can surface the error later, and subscribe to file change notifications // so that we'll automatically reload the file if the user can fix the issue. _optionsRead = true; _specificDiagnosticOptions = ImmutableDictionary<string, ReportDiagnostic>.Empty; _exception = e; includes = ImmutableArray.Create(FilePath); } _fileChangeContext = fileChangeWatcher.CreateContext(); _fileChangeContext.FileChanged += IncludeUpdated; foreach (var include in includes) { _fileChangeContext.EnqueueWatchingFile(include); } } } } public event EventHandler UpdatedOnDisk; public string FilePath { get; } public Exception GetException() { EnsureSubscriptions(); EnsureDiagnosticOptionsRead(); return _exception; } public ReportDiagnostic GetGeneralDiagnosticOption() { EnsureSubscriptions(); EnsureDiagnosticOptionsRead(); return _generalDiagnosticOption; } public ImmutableDictionary<string, ReportDiagnostic> GetSpecificDiagnosticOptions() { EnsureSubscriptions(); EnsureDiagnosticOptionsRead(); return _specificDiagnosticOptions; } private void EnsureSubscriptions() { lock (_gate) { if (!_subscribed) { // TODO: ensure subscriptions now _subscribed = true; } } } private void EnsureDiagnosticOptionsRead() { lock (_gate) { if (!_optionsRead) { _optionsRead = true; var specificDiagnosticOptions = new Dictionary<string, ReportDiagnostic>(); try { var effectiveRuleset = RuleSet.LoadEffectiveRuleSetFromFile(FilePath); _generalDiagnosticOption = effectiveRuleset.GeneralDiagnosticOption; foreach (var rule in effectiveRuleset.SpecificDiagnosticOptions) { specificDiagnosticOptions.Add(rule.Key, rule.Value); } _specificDiagnosticOptions = specificDiagnosticOptions.ToImmutableDictionary(); } catch (Exception e) { _exception = e; } } } } public void Dispose() { RemoveFromRuleSetManagerAndDisconnectFileTrackers(); _disposalCancellationSource.Cancel(); _disposalCancellationSource.Dispose(); } private void RemoveFromRuleSetManagerAndDisconnectFileTrackers() { lock (_gate) { _fileChangeContext.Dispose(); if (_removedFromRuleSetManager) { return; } _removedFromRuleSetManager = true; } // Call outside of lock to avoid general surprises; we skip this with the return above inside the lock. _ruleSetManager.StopTrackingRuleSetFile(this); } private void IncludeUpdated(object sender, string fileChanged) { // The file change service is going to notify us of updates on the foreground thread. // This is going to cause us to drop our existing subscriptions and create new ones. // However, the FileChangeTracker signs up for subscriptions in a Task on a background thread. // We can easily end up with the foreground thread waiting on the Task, which is blocked // waiting for the foreground thread to release its lock on the file change service. // To avoid this, just queue up a Task to do the work on the foreground thread later, after // the lock on the file change service has been released. _ruleSetManager._threadingContext.JoinableTaskFactory.RunAsync(async () => { using var _ = _ruleSetManager._listener.BeginAsyncOperation("IncludeUpdated"); await _ruleSetManager._threadingContext.JoinableTaskFactory.SwitchToMainThreadAsync(alwaysYield: true, _disposalToken); IncludeUpdateCore(); }); } private void IncludeUpdateCore() { // It's critical that RemoveFromRuleSetManagerAndDisconnectFileTrackers() is called first prior to raising the event // -- this way any callers who call the RuleSetManager asking for the new file are guaranteed to get the new snapshot first. // idempotent. RemoveFromRuleSetManagerAndDisconnectFileTrackers(); UpdatedOnDisk?.Invoke(this, EventArgs.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; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Shared.TestHooks; namespace Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem { internal sealed partial class VisualStudioRuleSetManager { private sealed class RuleSetFile : IRuleSetFile, IDisposable { private readonly VisualStudioRuleSetManager _ruleSetManager; private readonly object _gate = new(); private readonly CancellationTokenSource _disposalCancellationSource; private readonly CancellationToken _disposalToken; private FileChangeWatcher.IContext _fileChangeContext; private ReportDiagnostic _generalDiagnosticOption; private ImmutableDictionary<string, ReportDiagnostic> _specificDiagnosticOptions; private bool _subscribed = false; private bool _optionsRead = false; private bool _removedFromRuleSetManager = false; private Exception _exception; public RuleSetFile(string filePath, VisualStudioRuleSetManager ruleSetManager) { FilePath = filePath; _ruleSetManager = ruleSetManager; _disposalCancellationSource = new(); _disposalToken = _disposalCancellationSource.Token; } public void InitializeFileTracking(FileChangeWatcher fileChangeWatcher) { lock (_gate) { if (_fileChangeContext == null) { ImmutableArray<string> includes; try { includes = RuleSet.GetEffectiveIncludesFromFile(FilePath); } catch (Exception e) { // We couldn't read the rule set for whatever reason. Capture the exception // so we can surface the error later, and subscribe to file change notifications // so that we'll automatically reload the file if the user can fix the issue. _optionsRead = true; _specificDiagnosticOptions = ImmutableDictionary<string, ReportDiagnostic>.Empty; _exception = e; includes = ImmutableArray.Create(FilePath); } _fileChangeContext = fileChangeWatcher.CreateContext(); _fileChangeContext.FileChanged += IncludeUpdated; foreach (var include in includes) { _fileChangeContext.EnqueueWatchingFile(include); } } } } public event EventHandler UpdatedOnDisk; public string FilePath { get; } public Exception GetException() { EnsureSubscriptions(); EnsureDiagnosticOptionsRead(); return _exception; } public ReportDiagnostic GetGeneralDiagnosticOption() { EnsureSubscriptions(); EnsureDiagnosticOptionsRead(); return _generalDiagnosticOption; } public ImmutableDictionary<string, ReportDiagnostic> GetSpecificDiagnosticOptions() { EnsureSubscriptions(); EnsureDiagnosticOptionsRead(); return _specificDiagnosticOptions; } private void EnsureSubscriptions() { lock (_gate) { if (!_subscribed) { // TODO: ensure subscriptions now _subscribed = true; } } } private void EnsureDiagnosticOptionsRead() { lock (_gate) { if (!_optionsRead) { _optionsRead = true; var specificDiagnosticOptions = new Dictionary<string, ReportDiagnostic>(); try { var effectiveRuleset = RuleSet.LoadEffectiveRuleSetFromFile(FilePath); _generalDiagnosticOption = effectiveRuleset.GeneralDiagnosticOption; foreach (var rule in effectiveRuleset.SpecificDiagnosticOptions) { specificDiagnosticOptions.Add(rule.Key, rule.Value); } _specificDiagnosticOptions = specificDiagnosticOptions.ToImmutableDictionary(); } catch (Exception e) { _exception = e; } } } } public void Dispose() { RemoveFromRuleSetManagerAndDisconnectFileTrackers(); _disposalCancellationSource.Cancel(); _disposalCancellationSource.Dispose(); } private void RemoveFromRuleSetManagerAndDisconnectFileTrackers() { lock (_gate) { _fileChangeContext.Dispose(); if (_removedFromRuleSetManager) { return; } _removedFromRuleSetManager = true; } // Call outside of lock to avoid general surprises; we skip this with the return above inside the lock. _ruleSetManager.StopTrackingRuleSetFile(this); } private void IncludeUpdated(object sender, string fileChanged) { // The file change service is going to notify us of updates on the foreground thread. // This is going to cause us to drop our existing subscriptions and create new ones. // However, the FileChangeTracker signs up for subscriptions in a Task on a background thread. // We can easily end up with the foreground thread waiting on the Task, which is blocked // waiting for the foreground thread to release its lock on the file change service. // To avoid this, just queue up a Task to do the work on the foreground thread later, after // the lock on the file change service has been released. _ruleSetManager._threadingContext.JoinableTaskFactory.RunAsync(async () => { using var _ = _ruleSetManager._listener.BeginAsyncOperation("IncludeUpdated"); await _ruleSetManager._threadingContext.JoinableTaskFactory.SwitchToMainThreadAsync(alwaysYield: true, _disposalToken); IncludeUpdateCore(); }); } private void IncludeUpdateCore() { // It's critical that RemoveFromRuleSetManagerAndDisconnectFileTrackers() is called first prior to raising the event // -- this way any callers who call the RuleSetManager asking for the new file are guaranteed to get the new snapshot first. // idempotent. RemoveFromRuleSetManagerAndDisconnectFileTrackers(); UpdatedOnDisk?.Invoke(this, EventArgs.Empty); } } } }
-1
dotnet/roslyn
55,262
Fix LSP completions when all items have default commit characters
Fixes an exception stack trace seen in https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1362284 Also fixes behavior of promotion of commit characters to the list to include default commit characters
dibarbet
2021-07-30T02:43:35Z
2021-07-30T21:21:47Z
2f7dffa534aceb92e9767568e88535c926588d12
65ee073bf6cea571a68193793420ecee60752711
Fix LSP completions when all items have default commit characters. Fixes an exception stack trace seen in https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1362284 Also fixes behavior of promotion of commit characters to the list to include default commit characters
./src/Compilers/CSharp/Portable/Binder/Binder_Symbols.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Runtime.CompilerServices; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.RuntimeMembers; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { internal partial class Binder { /// <summary> /// Binds the type for the syntax taking into account possibility of "var" type. /// </summary> /// <param name="syntax">Type syntax to bind.</param> /// <param name="diagnostics">Diagnostics.</param> /// <param name="isVar"> /// Set to false if syntax binds to a type in the current context and true if /// syntax is "var" and it binds to "var" keyword in the current context. /// </param> /// <returns> /// Bound type if syntax binds to a type in the current context and /// null if syntax binds to "var" keyword in the current context. /// </returns> internal TypeWithAnnotations BindTypeOrVarKeyword(TypeSyntax syntax, BindingDiagnosticBag diagnostics, out bool isVar) { var symbol = BindTypeOrAliasOrVarKeyword(syntax, diagnostics, out isVar); Debug.Assert(isVar == symbol.IsDefault); return isVar ? default : UnwrapAlias(symbol, diagnostics, syntax).TypeWithAnnotations; } /// <summary> /// Binds the type for the syntax taking into account possibility of "unmanaged" type. /// </summary> /// <param name="syntax">Type syntax to bind.</param> /// <param name="diagnostics">Diagnostics.</param> /// <param name="keyword"> /// Set to <see cref="ConstraintContextualKeyword.None"/> if syntax binds to a type in the current context, otherwise /// syntax binds to the corresponding keyword in the current context. /// </param> /// <returns> /// Bound type if syntax binds to a type in the current context and /// null if syntax binds to a contextual constraint keyword. /// </returns> private TypeWithAnnotations BindTypeOrConstraintKeyword(TypeSyntax syntax, BindingDiagnosticBag diagnostics, out ConstraintContextualKeyword keyword) { var symbol = BindTypeOrAliasOrConstraintKeyword(syntax, diagnostics, out keyword); Debug.Assert((keyword != ConstraintContextualKeyword.None) == symbol.IsDefault); return (keyword != ConstraintContextualKeyword.None) ? default : UnwrapAlias(symbol, diagnostics, syntax).TypeWithAnnotations; } /// <summary> /// Binds the type for the syntax taking into account possibility of "var" type. /// </summary> /// <param name="syntax">Type syntax to bind.</param> /// <param name="diagnostics">Diagnostics.</param> /// <param name="isVar"> /// Set to false if syntax binds to a type in the current context and true if /// syntax is "var" and it binds to "var" keyword in the current context. /// </param> /// <param name="alias">Alias symbol if syntax binds to an alias.</param> /// <returns> /// Bound type if syntax binds to a type in the current context and /// null if syntax binds to "var" keyword in the current context. /// </returns> internal TypeWithAnnotations BindTypeOrVarKeyword(TypeSyntax syntax, BindingDiagnosticBag diagnostics, out bool isVar, out AliasSymbol alias) { var symbol = BindTypeOrAliasOrVarKeyword(syntax, diagnostics, out isVar); Debug.Assert(isVar == symbol.IsDefault); if (isVar) { alias = null; return default; } else { return UnwrapAlias(symbol, out alias, diagnostics, syntax).TypeWithAnnotations; } } /// <summary> /// Binds the type for the syntax taking into account possibility of "var" type. /// If the syntax binds to an alias symbol to a type, it returns the alias symbol. /// </summary> /// <param name="syntax">Type syntax to bind.</param> /// <param name="diagnostics">Diagnostics.</param> /// <param name="isVar"> /// Set to false if syntax binds to a type or alias to a type in the current context and true if /// syntax is "var" and it binds to "var" keyword in the current context. /// </param> /// <returns> /// Bound type or alias if syntax binds to a type or alias to a type in the current context and /// null if syntax binds to "var" keyword in the current context. /// </returns> private NamespaceOrTypeOrAliasSymbolWithAnnotations BindTypeOrAliasOrVarKeyword(TypeSyntax syntax, BindingDiagnosticBag diagnostics, out bool isVar) { if (syntax.IsVar) { var symbol = BindTypeOrAliasOrKeyword((IdentifierNameSyntax)syntax, diagnostics, out isVar); if (isVar) { CheckFeatureAvailability(syntax, MessageID.IDS_FeatureImplicitLocal, diagnostics); } return symbol; } else { isVar = false; return BindTypeOrAlias(syntax, diagnostics, basesBeingResolved: null); } } private enum ConstraintContextualKeyword { None, Unmanaged, NotNull, } private NamespaceOrTypeOrAliasSymbolWithAnnotations BindTypeOrAliasOrConstraintKeyword(TypeSyntax syntax, BindingDiagnosticBag diagnostics, out ConstraintContextualKeyword keyword) { if (syntax.IsUnmanaged) { keyword = ConstraintContextualKeyword.Unmanaged; } else if (syntax.IsNotNull) { keyword = ConstraintContextualKeyword.NotNull; } else { keyword = ConstraintContextualKeyword.None; } if (keyword != ConstraintContextualKeyword.None) { var identifierSyntax = (IdentifierNameSyntax)syntax; var symbol = BindTypeOrAliasOrKeyword(identifierSyntax, diagnostics, out bool isKeyword); if (isKeyword) { switch (keyword) { case ConstraintContextualKeyword.Unmanaged: CheckFeatureAvailability(syntax, MessageID.IDS_FeatureUnmanagedGenericTypeConstraint, diagnostics); break; case ConstraintContextualKeyword.NotNull: CheckFeatureAvailability(identifierSyntax, MessageID.IDS_FeatureNotNullGenericTypeConstraint, diagnostics); break; default: throw ExceptionUtilities.UnexpectedValue(keyword); } } else { keyword = ConstraintContextualKeyword.None; } return symbol; } else { return BindTypeOrAlias(syntax, diagnostics, basesBeingResolved: null); } } /// <summary> /// Binds the type for the syntax taking into account possibility of the type being a keyword. /// If the syntax binds to an alias symbol to a type, it returns the alias symbol. /// PREREQUISITE: syntax should be checked to match the keyword, like <see cref="TypeSyntax.IsVar"/> or <see cref="TypeSyntax.IsUnmanaged"/>. /// Otherwise, call <see cref="Binder.BindTypeOrAlias(ExpressionSyntax, BindingDiagnosticBag, ConsList{TypeSymbol}, bool)"/> instead. /// </summary> private NamespaceOrTypeOrAliasSymbolWithAnnotations BindTypeOrAliasOrKeyword(IdentifierNameSyntax syntax, BindingDiagnosticBag diagnostics, out bool isKeyword) { return BindTypeOrAliasOrKeyword(((IdentifierNameSyntax)syntax).Identifier, syntax, diagnostics, out isKeyword); } private NamespaceOrTypeOrAliasSymbolWithAnnotations BindTypeOrAliasOrKeyword(SyntaxToken identifier, SyntaxNode syntax, BindingDiagnosticBag diagnostics, out bool isKeyword) { // Keywords can only be IdentifierNameSyntax var identifierValueText = identifier.ValueText; Symbol symbol = null; // Perform name lookup without generating diagnostics as it could possibly be a keyword in the current context. var lookupResult = LookupResult.GetInstance(); var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; this.LookupSymbolsInternal(lookupResult, identifierValueText, arity: 0, useSiteInfo: ref discardedUseSiteInfo, basesBeingResolved: null, options: LookupOptions.NamespacesOrTypesOnly, diagnose: false); // We have following possible cases for lookup: // 1) LookupResultKind.Empty: must be a keyword // 2) LookupResultKind.Viable: // a) Single viable result that corresponds to 1) a non-error type: cannot be a keyword // 2) an error type: must be a keyword // b) Single viable result that corresponds to namespace: must be a keyword // c) Multi viable result (ambiguous result), we must return an error type: cannot be a keyword // 3) Non viable, non empty lookup result: must be a keyword // BREAKING CHANGE: Case (2)(c) is a breaking change from the native compiler. // BREAKING CHANGE: Native compiler interprets lookup with ambiguous result to correspond to bind // BREAKING CHANGE: to "var" keyword (isVar = true), rather than reporting an error. // BREAKING CHANGE: See test SemanticErrorTests.ErrorMeansSuccess_var() for an example. switch (lookupResult.Kind) { case LookupResultKind.Empty: // Case (1) isKeyword = true; symbol = null; break; case LookupResultKind.Viable: // Case (2) var resultDiagnostics = new BindingDiagnosticBag(DiagnosticBag.GetInstance(), diagnostics.DependenciesBag); bool wasError; symbol = ResultSymbol( lookupResult, identifierValueText, arity: 0, where: syntax, diagnostics: resultDiagnostics, suppressUseSiteDiagnostics: false, wasError: out wasError, qualifierOpt: null); // Here, we're mimicking behavior of dev10. If the identifier fails to bind // as a type, even if the reason is (e.g.) a type/alias conflict, then treat // it as the contextual keyword. if (wasError && lookupResult.IsSingleViable) { // NOTE: don't report diagnostics - we're not going to use the lookup result. resultDiagnostics.DiagnosticBag.Free(); // Case (2)(a)(2) goto default; } diagnostics.AddRange(resultDiagnostics.DiagnosticBag); resultDiagnostics.DiagnosticBag.Free(); if (lookupResult.IsSingleViable) { var type = UnwrapAlias(symbol, diagnostics, syntax) as TypeSymbol; if ((object)type != null) { // Case (2)(a)(1) isKeyword = false; } else { // Case (2)(b) Debug.Assert(UnwrapAliasNoDiagnostics(symbol) is NamespaceSymbol); isKeyword = true; symbol = null; } } else { // Case (2)(c) isKeyword = false; } break; default: // Case (3) isKeyword = true; symbol = null; break; } lookupResult.Free(); return NamespaceOrTypeOrAliasSymbolWithAnnotations.CreateUnannotated(AreNullableAnnotationsEnabled(identifier), symbol); } // Binds the given expression syntax as Type. // If the resulting symbol is an Alias to a Type, it unwraps the alias // and returns it's target type. internal TypeWithAnnotations BindType(ExpressionSyntax syntax, BindingDiagnosticBag diagnostics, ConsList<TypeSymbol> basesBeingResolved = null, bool suppressUseSiteDiagnostics = false) { var symbol = BindTypeOrAlias(syntax, diagnostics, basesBeingResolved, suppressUseSiteDiagnostics); return UnwrapAlias(symbol, diagnostics, syntax, basesBeingResolved).TypeWithAnnotations; } // Binds the given expression syntax as Type. // If the resulting symbol is an Alias to a Type, it stores the AliasSymbol in // the alias parameter, unwraps the alias and returns it's target type. internal TypeWithAnnotations BindType(ExpressionSyntax syntax, BindingDiagnosticBag diagnostics, out AliasSymbol alias, ConsList<TypeSymbol> basesBeingResolved = null) { var symbol = BindTypeOrAlias(syntax, diagnostics, basesBeingResolved); return UnwrapAlias(symbol, out alias, diagnostics, syntax, basesBeingResolved).TypeWithAnnotations; } // Binds the given expression syntax as Type or an Alias to Type // and returns the resultant symbol. // NOTE: This method doesn't unwrap aliases. internal NamespaceOrTypeOrAliasSymbolWithAnnotations BindTypeOrAlias(ExpressionSyntax syntax, BindingDiagnosticBag diagnostics, ConsList<TypeSymbol> basesBeingResolved = null, bool suppressUseSiteDiagnostics = false) { Debug.Assert(diagnostics != null); var symbol = BindNamespaceOrTypeOrAliasSymbol(syntax, diagnostics, basesBeingResolved, basesBeingResolved != null || suppressUseSiteDiagnostics); // symbol must be a TypeSymbol or an Alias to a TypeSymbol if (symbol.IsType || (symbol.IsAlias && UnwrapAliasNoDiagnostics(symbol.Symbol, basesBeingResolved) is TypeSymbol)) { if (symbol.IsType) { // Obsolete alias targets are reported in UnwrapAlias, but if it was a type (not an // alias to a type) we report the obsolete type here. symbol.TypeWithAnnotations.ReportDiagnosticsIfObsolete(this, syntax, diagnostics); } return symbol; } var diagnosticInfo = diagnostics.Add(ErrorCode.ERR_BadSKknown, syntax.Location, syntax, symbol.Symbol.GetKindText(), MessageID.IDS_SK_TYPE.Localize()); return TypeWithAnnotations.Create(new ExtendedErrorTypeSymbol(GetContainingNamespaceOrType(symbol.Symbol), symbol.Symbol, LookupResultKind.NotATypeOrNamespace, diagnosticInfo)); } /// <summary> /// The immediately containing namespace or named type, or the global /// namespace if containing symbol is neither a namespace or named type. /// </summary> private NamespaceOrTypeSymbol GetContainingNamespaceOrType(Symbol symbol) { return symbol.ContainingNamespaceOrType() ?? this.Compilation.Assembly.GlobalNamespace; } internal Symbol BindNamespaceAliasSymbol(IdentifierNameSyntax node, BindingDiagnosticBag diagnostics) { if (node.Identifier.Kind() == SyntaxKind.GlobalKeyword) { return this.Compilation.GlobalNamespaceAlias; } else { bool wasError; var plainName = node.Identifier.ValueText; var result = LookupResult.GetInstance(); CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); this.LookupSymbolsWithFallback(result, plainName, 0, ref useSiteInfo, null, LookupOptions.NamespaceAliasesOnly); diagnostics.Add(node, useSiteInfo); Symbol bindingResult = ResultSymbol(result, plainName, 0, node, diagnostics, false, out wasError, qualifierOpt: null, options: LookupOptions.NamespaceAliasesOnly); result.Free(); return bindingResult; } } internal NamespaceOrTypeOrAliasSymbolWithAnnotations BindNamespaceOrTypeSymbol(ExpressionSyntax syntax, BindingDiagnosticBag diagnostics, ConsList<TypeSymbol> basesBeingResolved = null) { return BindNamespaceOrTypeSymbol(syntax, diagnostics, basesBeingResolved, basesBeingResolved != null); } /// <summary> /// This method is used in deeply recursive parts of the compiler and requires a non-trivial amount of stack /// space to execute. Preventing inlining here to keep recursive frames small. /// </summary> [MethodImpl(MethodImplOptions.NoInlining)] internal NamespaceOrTypeOrAliasSymbolWithAnnotations BindNamespaceOrTypeSymbol(ExpressionSyntax syntax, BindingDiagnosticBag diagnostics, ConsList<TypeSymbol> basesBeingResolved, bool suppressUseSiteDiagnostics) { var result = BindNamespaceOrTypeOrAliasSymbol(syntax, diagnostics, basesBeingResolved, suppressUseSiteDiagnostics); Debug.Assert(!result.IsDefault); return UnwrapAlias(result, diagnostics, syntax, basesBeingResolved); } #nullable enable /// <summary> /// Bind the syntax into a namespace, type or alias symbol. /// </summary> /// <remarks> /// This method is used in deeply recursive parts of the compiler. Specifically this and /// <see cref="BindQualifiedName(ExpressionSyntax, SimpleNameSyntax, BindingDiagnosticBag, ConsList{TypeSymbol}, bool)"/> /// are mutually recursive. The non-recursive parts of this method tend to reserve significantly large /// stack frames due to their use of large struct like <see cref="TypeWithAnnotations"/>. /// /// To keep the stack frame size on recursive paths small the non-recursive parts are factored into local /// functions. This means we pay their stack penalty only when they are used. They are themselves big /// enough they should be disqualified from inlining. In the future when attributes are allowed on /// local functions we should explicitly mark them as <see cref="MethodImplOptions.NoInlining"/> /// </remarks> internal NamespaceOrTypeOrAliasSymbolWithAnnotations BindNamespaceOrTypeOrAliasSymbol(ExpressionSyntax syntax, BindingDiagnosticBag diagnostics, ConsList<TypeSymbol> basesBeingResolved, bool suppressUseSiteDiagnostics) { switch (syntax.Kind()) { case SyntaxKind.NullableType: return bindNullable(); case SyntaxKind.PredefinedType: return bindPredefined(); case SyntaxKind.IdentifierName: return BindNonGenericSimpleNamespaceOrTypeOrAliasSymbol((IdentifierNameSyntax)syntax, diagnostics, basesBeingResolved, suppressUseSiteDiagnostics, qualifierOpt: null); case SyntaxKind.GenericName: return BindGenericSimpleNamespaceOrTypeOrAliasSymbol((GenericNameSyntax)syntax, diagnostics, basesBeingResolved, qualifierOpt: null); case SyntaxKind.AliasQualifiedName: return bindAlias(); case SyntaxKind.QualifiedName: { var node = (QualifiedNameSyntax)syntax; return BindQualifiedName(node.Left, node.Right, diagnostics, basesBeingResolved, suppressUseSiteDiagnostics); } case SyntaxKind.SimpleMemberAccessExpression: { var node = (MemberAccessExpressionSyntax)syntax; return BindQualifiedName(node.Expression, node.Name, diagnostics, basesBeingResolved, suppressUseSiteDiagnostics); } case SyntaxKind.ArrayType: { return BindArrayType((ArrayTypeSyntax)syntax, diagnostics, permitDimensions: false, basesBeingResolved, disallowRestrictedTypes: true); } case SyntaxKind.PointerType: return bindPointer(); case SyntaxKind.FunctionPointerType: var functionPointerTypeSyntax = (FunctionPointerTypeSyntax)syntax; if (GetUnsafeDiagnosticInfo(sizeOfTypeOpt: null) is CSDiagnosticInfo info) { var @delegate = functionPointerTypeSyntax.DelegateKeyword; var asterisk = functionPointerTypeSyntax.AsteriskToken; RoslynDebug.Assert(@delegate.SyntaxTree is object); diagnostics.Add(info, Location.Create(@delegate.SyntaxTree, TextSpan.FromBounds(@delegate.SpanStart, asterisk.Span.End))); } return TypeWithAnnotations.Create( FunctionPointerTypeSymbol.CreateFromSource( functionPointerTypeSyntax, this, diagnostics, basesBeingResolved, suppressUseSiteDiagnostics)); case SyntaxKind.OmittedTypeArgument: { return BindTypeArgument((TypeSyntax)syntax, diagnostics, basesBeingResolved); } case SyntaxKind.TupleType: { var tupleTypeSyntax = (TupleTypeSyntax)syntax; return TypeWithAnnotations.Create(AreNullableAnnotationsEnabled(tupleTypeSyntax.CloseParenToken), BindTupleType(tupleTypeSyntax, diagnostics, basesBeingResolved)); } case SyntaxKind.RefType: { // ref needs to be handled by the caller var refTypeSyntax = (RefTypeSyntax)syntax; var refToken = refTypeSyntax.RefKeyword; if (!syntax.HasErrors) { diagnostics.Add(ErrorCode.ERR_UnexpectedToken, refToken.GetLocation(), refToken.ToString()); } return BindNamespaceOrTypeOrAliasSymbol(refTypeSyntax.Type, diagnostics, basesBeingResolved, suppressUseSiteDiagnostics); } default: { // This is invalid syntax for a type. This arises when a constant pattern that fails to bind // is attempted to be bound as a type pattern. return createErrorType(); } } void reportNullableReferenceTypesIfNeeded(SyntaxToken questionToken, TypeWithAnnotations typeArgument = default) { bool isNullableEnabled = AreNullableAnnotationsEnabled(questionToken); bool isGeneratedCode = IsGeneratedCode(questionToken); var location = questionToken.GetLocation(); if (diagnostics.DiagnosticBag is DiagnosticBag diagnosticBag) { // Inside a method body or other executable code, we can question IsValueType without causing cycles. if (typeArgument.HasType && !ShouldCheckConstraints) { LazyMissingNonNullTypesContextDiagnosticInfo.AddAll( isNullableEnabled, isGeneratedCode, typeArgument, location, diagnosticBag); } else { LazyMissingNonNullTypesContextDiagnosticInfo.ReportNullableReferenceTypesIfNeeded( isNullableEnabled, isGeneratedCode, typeArgument, location, diagnosticBag); } } } NamespaceOrTypeOrAliasSymbolWithAnnotations bindNullable() { var nullableSyntax = (NullableTypeSyntax)syntax; TypeSyntax typeArgumentSyntax = nullableSyntax.ElementType; TypeWithAnnotations typeArgument = BindType(typeArgumentSyntax, diagnostics, basesBeingResolved); TypeWithAnnotations constructedType = typeArgument.SetIsAnnotated(Compilation); reportNullableReferenceTypesIfNeeded(nullableSyntax.QuestionToken, typeArgument); if (!ShouldCheckConstraints) { diagnostics.Add(new LazyUseSiteDiagnosticsInfoForNullableType(Compilation.LanguageVersion, constructedType), syntax.GetLocation()); } else if (constructedType.IsNullableType()) { ReportUseSite(constructedType.Type.OriginalDefinition, diagnostics, syntax); var type = (NamedTypeSymbol)constructedType.Type; var location = syntax.Location; type.CheckConstraints(new ConstraintsHelper.CheckConstraintsArgs(this.Compilation, this.Conversions, includeNullability: true, location, diagnostics)); } else if (GetNullableUnconstrainedTypeParameterDiagnosticIfNecessary(Compilation.LanguageVersion, constructedType) is { } diagnosticInfo) { diagnostics.Add(diagnosticInfo, syntax.Location); } return constructedType; } NamespaceOrTypeOrAliasSymbolWithAnnotations bindPredefined() { var predefinedType = (PredefinedTypeSyntax)syntax; var type = BindPredefinedTypeSymbol(predefinedType, diagnostics); return TypeWithAnnotations.Create(AreNullableAnnotationsEnabled(predefinedType.Keyword), type); } NamespaceOrTypeOrAliasSymbolWithAnnotations bindAlias() { var node = (AliasQualifiedNameSyntax)syntax; var bindingResult = BindNamespaceAliasSymbol(node.Alias, diagnostics); var alias = bindingResult as AliasSymbol; NamespaceOrTypeSymbol left = (alias is object) ? alias.Target : (NamespaceOrTypeSymbol)bindingResult; if (left.Kind == SymbolKind.NamedType) { return TypeWithAnnotations.Create(new ExtendedErrorTypeSymbol(left, LookupResultKind.NotATypeOrNamespace, diagnostics.Add(ErrorCode.ERR_ColColWithTypeAlias, node.Alias.Location, node.Alias.Identifier.Text))); } return this.BindSimpleNamespaceOrTypeOrAliasSymbol(node.Name, diagnostics, basesBeingResolved, suppressUseSiteDiagnostics, left); } NamespaceOrTypeOrAliasSymbolWithAnnotations bindPointer() { var node = (PointerTypeSyntax)syntax; var elementType = BindType(node.ElementType, diagnostics, basesBeingResolved); ReportUnsafeIfNotAllowed(node, diagnostics); if (!Flags.HasFlag(BinderFlags.SuppressConstraintChecks)) { CheckManagedAddr(Compilation, elementType.Type, node.Location, diagnostics); } return TypeWithAnnotations.Create(new PointerTypeSymbol(elementType)); } NamespaceOrTypeOrAliasSymbolWithAnnotations createErrorType() { diagnostics.Add(ErrorCode.ERR_TypeExpected, syntax.GetLocation()); return TypeWithAnnotations.Create(CreateErrorType()); } } internal static CSDiagnosticInfo? GetNullableUnconstrainedTypeParameterDiagnosticIfNecessary(LanguageVersion languageVersion, in TypeWithAnnotations type) { if (type.Type.IsTypeParameterDisallowingAnnotationInCSharp8()) { // 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(); if (requiredVersion > languageVersion) { return new CSDiagnosticInfo(ErrorCode.ERR_NullableUnconstrainedTypeParameter, new CSharpRequiredLanguageVersion(requiredVersion)); } } return null; } #nullable disable private TypeWithAnnotations BindArrayType( ArrayTypeSyntax node, BindingDiagnosticBag diagnostics, bool permitDimensions, ConsList<TypeSymbol> basesBeingResolved, bool disallowRestrictedTypes) { TypeWithAnnotations type = BindType(node.ElementType, diagnostics, basesBeingResolved); if (type.IsStatic) { // CS0719: '{0}': array elements cannot be of static type Error(diagnostics, ErrorCode.ERR_ArrayOfStaticClass, node.ElementType, type.Type); } if (disallowRestrictedTypes) { // Restricted types cannot be on the heap, but they can be on the stack, so are allowed in a stackalloc if (ShouldCheckConstraints) { if (type.IsRestrictedType()) { // CS0611: Array elements cannot be of type '{0}' Error(diagnostics, ErrorCode.ERR_ArrayElementCantBeRefAny, node.ElementType, type.Type); } } else { diagnostics.Add(new LazyArrayElementCantBeRefAnyDiagnosticInfo(type), node.ElementType.GetLocation()); } } for (int i = node.RankSpecifiers.Count - 1; i >= 0; i--) { var rankSpecifier = node.RankSpecifiers[i]; var dimension = rankSpecifier.Sizes; if (!permitDimensions && dimension.Count != 0 && dimension[0].Kind() != SyntaxKind.OmittedArraySizeExpression) { // https://github.com/dotnet/roslyn/issues/32464 // Should capture invalid dimensions for use in `SemanticModel` and `IOperation`. Error(diagnostics, ErrorCode.ERR_ArraySizeInDeclaration, rankSpecifier); } var array = ArrayTypeSymbol.CreateCSharpArray(this.Compilation.Assembly, type, rankSpecifier.Rank); type = TypeWithAnnotations.Create(AreNullableAnnotationsEnabled(rankSpecifier.CloseBracketToken), array); } return type; } private TypeSymbol BindTupleType(TupleTypeSyntax syntax, BindingDiagnosticBag diagnostics, ConsList<TypeSymbol> basesBeingResolved) { int numElements = syntax.Elements.Count; var types = ArrayBuilder<TypeWithAnnotations>.GetInstance(numElements); var locations = ArrayBuilder<Location>.GetInstance(numElements); ArrayBuilder<string> elementNames = null; // set of names already used var uniqueFieldNames = PooledHashSet<string>.GetInstance(); bool hasExplicitNames = false; for (int i = 0; i < numElements; i++) { var argumentSyntax = syntax.Elements[i]; var argumentType = BindType(argumentSyntax.Type, diagnostics, basesBeingResolved); types.Add(argumentType); string name = null; SyntaxToken nameToken = argumentSyntax.Identifier; if (nameToken.Kind() == SyntaxKind.IdentifierToken) { name = nameToken.ValueText; // validate name if we have one hasExplicitNames = true; CheckTupleMemberName(name, i, nameToken, diagnostics, uniqueFieldNames); locations.Add(nameToken.GetLocation()); } else { locations.Add(argumentSyntax.Location); } CollectTupleFieldMemberName(name, i, numElements, ref elementNames); } uniqueFieldNames.Free(); if (hasExplicitNames) { // If the tuple type with names is bound we must have the TupleElementNamesAttribute to emit // it is typically there though, if we have ValueTuple at all ReportMissingTupleElementNamesAttributesIfNeeded(Compilation, syntax.GetLocation(), diagnostics); } var typesArray = types.ToImmutableAndFree(); var locationsArray = locations.ToImmutableAndFree(); if (typesArray.Length < 2) { throw ExceptionUtilities.UnexpectedValue(typesArray.Length); } bool includeNullability = Compilation.IsFeatureEnabled(MessageID.IDS_FeatureNullableReferenceTypes); return NamedTypeSymbol.CreateTuple(syntax.Location, typesArray, locationsArray, elementNames == null ? default(ImmutableArray<string>) : elementNames.ToImmutableAndFree(), this.Compilation, this.ShouldCheckConstraints, includeNullability: this.ShouldCheckConstraints && includeNullability, errorPositions: default(ImmutableArray<bool>), syntax: syntax, diagnostics: diagnostics); } internal static void ReportMissingTupleElementNamesAttributesIfNeeded(CSharpCompilation compilation, Location location, BindingDiagnosticBag diagnostics) { var bag = BindingDiagnosticBag.GetInstance(diagnostics); if (!compilation.HasTupleNamesAttributes(bag, location)) { var info = new CSDiagnosticInfo(ErrorCode.ERR_TupleElementNamesAttributeMissing, AttributeDescription.TupleElementNamesAttribute.FullName); Error(diagnostics, info, location); } else { diagnostics.AddRange(bag); } bag.Free(); } private static void CollectTupleFieldMemberName(string name, int elementIndex, int tupleSize, ref ArrayBuilder<string> elementNames) { // add the name to the list // names would typically all be there or none at all // but in case we need to handle this in error cases if (elementNames != null) { elementNames.Add(name); } else { if (name != null) { elementNames = ArrayBuilder<string>.GetInstance(tupleSize); for (int j = 0; j < elementIndex; j++) { elementNames.Add(null); } elementNames.Add(name); } } } private static bool CheckTupleMemberName(string name, int index, SyntaxNodeOrToken syntax, BindingDiagnosticBag diagnostics, PooledHashSet<string> uniqueFieldNames) { int reserved = NamedTypeSymbol.IsTupleElementNameReserved(name); if (reserved == 0) { Error(diagnostics, ErrorCode.ERR_TupleReservedElementNameAnyPosition, syntax, name); return false; } else if (reserved > 0 && reserved != index + 1) { Error(diagnostics, ErrorCode.ERR_TupleReservedElementName, syntax, name, reserved); return false; } else if (!uniqueFieldNames.Add(name)) { Error(diagnostics, ErrorCode.ERR_TupleDuplicateElementName, syntax); return false; } return true; } private NamedTypeSymbol BindPredefinedTypeSymbol(PredefinedTypeSyntax node, BindingDiagnosticBag diagnostics) { return GetSpecialType(node.Keyword.Kind().GetSpecialType(), diagnostics, node); } /// <summary> /// Binds a simple name or the simple name portion of a qualified name. /// </summary> private NamespaceOrTypeOrAliasSymbolWithAnnotations BindSimpleNamespaceOrTypeOrAliasSymbol( SimpleNameSyntax syntax, BindingDiagnosticBag diagnostics, ConsList<TypeSymbol> basesBeingResolved, bool suppressUseSiteDiagnostics, NamespaceOrTypeSymbol qualifierOpt = null) { // Note that the comment above is a small lie; there is no such thing as the "simple name portion" of // a qualified alias member expression. A qualified alias member expression has the form // "identifier :: identifier optional-type-arguments" -- the right hand side of which // happens to match the syntactic form of a simple name. As a convenience, we analyze the // right hand side of the "::" here because it is so similar to a simple name; the left hand // side is in qualifierOpt. switch (syntax.Kind()) { default: return TypeWithAnnotations.Create(new ExtendedErrorTypeSymbol(qualifierOpt ?? this.Compilation.Assembly.GlobalNamespace, string.Empty, arity: 0, errorInfo: null)); case SyntaxKind.IdentifierName: return BindNonGenericSimpleNamespaceOrTypeOrAliasSymbol((IdentifierNameSyntax)syntax, diagnostics, basesBeingResolved, suppressUseSiteDiagnostics, qualifierOpt); case SyntaxKind.GenericName: return BindGenericSimpleNamespaceOrTypeOrAliasSymbol((GenericNameSyntax)syntax, diagnostics, basesBeingResolved, qualifierOpt); } } private static bool IsViableType(LookupResult result) { if (!result.IsMultiViable) { return false; } foreach (var s in result.Symbols) { switch (s.Kind) { case SymbolKind.Alias: if (((AliasSymbol)s).Target.Kind == SymbolKind.NamedType) return true; break; case SymbolKind.NamedType: case SymbolKind.TypeParameter: return true; } } return false; } protected NamespaceOrTypeOrAliasSymbolWithAnnotations BindNonGenericSimpleNamespaceOrTypeOrAliasSymbol( IdentifierNameSyntax node, BindingDiagnosticBag diagnostics, ConsList<TypeSymbol> basesBeingResolved, bool suppressUseSiteDiagnostics, NamespaceOrTypeSymbol qualifierOpt) { var identifierValueText = node.Identifier.ValueText; // If we are here in an error-recovery scenario, say, "goo<int, >(123);" then // we might have an 'empty' simple name. In that case do not report an // 'unable to find ""' error; we've already reported an error in the parser so // just bail out with an error symbol. if (string.IsNullOrWhiteSpace(identifierValueText)) { return TypeWithAnnotations.Create(new ExtendedErrorTypeSymbol( Compilation.Assembly.GlobalNamespace, identifierValueText, 0, new CSDiagnosticInfo(ErrorCode.ERR_SingleTypeNameNotFound))); } var errorResult = CreateErrorIfLookupOnTypeParameter(node.Parent, qualifierOpt, identifierValueText, 0, diagnostics); if ((object)errorResult != null) { return TypeWithAnnotations.Create(errorResult); } var result = LookupResult.GetInstance(); LookupOptions options = GetSimpleNameLookupOptions(node, node.Identifier.IsVerbatimIdentifier()); CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); this.LookupSymbolsSimpleName(result, qualifierOpt, identifierValueText, 0, basesBeingResolved, options, diagnose: true, useSiteInfo: ref useSiteInfo); diagnostics.Add(node, useSiteInfo); Symbol bindingResult = null; // If we were looking up "dynamic" or "nint" at the topmost level and didn't find anything good, // use that particular type (assuming the /langversion is supported). if ((object)qualifierOpt == null && !IsViableType(result)) { if (node.Identifier.ValueText == "dynamic") { if ((node.Parent == null || node.Parent.Kind() != SyntaxKind.Attribute && // dynamic not allowed as attribute type SyntaxFacts.IsInTypeOnlyContext(node)) && Compilation.LanguageVersion >= MessageID.IDS_FeatureDynamic.RequiredVersion()) { bindingResult = Compilation.DynamicType; ReportUseSiteDiagnosticForDynamic(diagnostics, node); } } else { bindingResult = BindNativeIntegerSymbolIfAny(node, diagnostics); } } if (bindingResult is null) { bool wasError; bindingResult = ResultSymbol(result, identifierValueText, 0, node, diagnostics, suppressUseSiteDiagnostics, out wasError, qualifierOpt, options); if (bindingResult.Kind == SymbolKind.Alias) { var aliasTarget = ((AliasSymbol)bindingResult).GetAliasTarget(basesBeingResolved); if (aliasTarget.Kind == SymbolKind.NamedType && ((NamedTypeSymbol)aliasTarget).ContainsDynamic()) { ReportUseSiteDiagnosticForDynamic(diagnostics, node); } } } result.Free(); return NamespaceOrTypeOrAliasSymbolWithAnnotations.CreateUnannotated(AreNullableAnnotationsEnabled(node.Identifier), bindingResult); } /// <summary> /// If the node is "nint" or "nuint" and not alone inside nameof, return the corresponding native integer symbol. /// Otherwise return null. /// </summary> private NamedTypeSymbol BindNativeIntegerSymbolIfAny(IdentifierNameSyntax node, BindingDiagnosticBag diagnostics) { SpecialType specialType; switch (node.Identifier.Text) { case "nint": specialType = SpecialType.System_IntPtr; break; case "nuint": specialType = SpecialType.System_UIntPtr; break; default: return null; } switch (node.Parent) { case AttributeSyntax parent when parent.Name == node: // [nint] return null; case UsingDirectiveSyntax parent when parent.Name == node: // using nint; using A = nuint; return null; case ArgumentSyntax parent when // nameof(nint) (IsInsideNameof && parent.Parent?.Parent is InvocationExpressionSyntax invocation && (invocation.Expression as IdentifierNameSyntax)?.Identifier.ContextualKind() == SyntaxKind.NameOfKeyword): // Don't bind nameof(nint) or nameof(nuint) so that ERR_NameNotInContext is reported. return null; } CheckFeatureAvailability(node, MessageID.IDS_FeatureNativeInt, diagnostics); return this.GetSpecialType(specialType, diagnostics, node).AsNativeInteger(); } private void ReportUseSiteDiagnosticForDynamic(BindingDiagnosticBag diagnostics, IdentifierNameSyntax node) { // Dynamic type might be bound in a declaration context where we need to synthesize the DynamicAttribute. // Here we report the use site error (ERR_DynamicAttributeMissing) for missing DynamicAttribute type or it's constructors. // // BREAKING CHANGE: Native compiler reports ERR_DynamicAttributeMissing at emit time when synthesizing DynamicAttribute. // Currently, in Roslyn we don't support reporting diagnostics while synthesizing attributes, these diagnostics are reported at bind time. // Hence, we report this diagnostic here. Note that DynamicAttribute has two constructors, and either of them may be used while // synthesizing the DynamicAttribute (see DynamicAttributeEncoder.Encode method for details). // However, unlike the native compiler which reports use site diagnostic only for the specific DynamicAttribute constructor which is going to be used, // we report it for both the constructors and also for boolean type (used by the second constructor). // This is a breaking change for the case where only one of the two constructor of DynamicAttribute is missing, but we never use it for any of the synthesized DynamicAttributes. // However, this seems like a very unlikely scenario and an acceptable break. if (node.IsTypeInContextWhichNeedsDynamicAttribute()) { var bag = BindingDiagnosticBag.GetInstance(diagnostics); if (!Compilation.HasDynamicEmitAttributes(bag, node.Location)) { // CONSIDER: Native compiler reports error CS1980 for each syntax node which binds to dynamic type, we do the same by reporting a diagnostic here. // However, this means we generate multiple duplicate diagnostics, when a single one would suffice. // We may want to consider adding an "Unreported" flag to the DynamicTypeSymbol to suppress duplicate CS1980. // CS1980: Cannot define a class or member that utilizes 'dynamic' because the compiler required type '{0}' cannot be found. Are you missing a reference? var info = new CSDiagnosticInfo(ErrorCode.ERR_DynamicAttributeMissing, AttributeDescription.DynamicAttribute.FullName); Symbol.ReportUseSiteDiagnostic(info, diagnostics, node.Location); } else { diagnostics.AddRange(bag); } bag.Free(); this.GetSpecialType(SpecialType.System_Boolean, diagnostics, node); } } // Gets the name lookup options for simple generic or non-generic name. private static LookupOptions GetSimpleNameLookupOptions(NameSyntax node, bool isVerbatimIdentifier) { if (SyntaxFacts.IsAttributeName(node)) { // SPEC: By convention, attribute classes are named with a suffix of Attribute. // SPEC: An attribute-name of the form type-name may either include or omit this suffix. // SPEC: If an attribute class is found both with and without this suffix, an ambiguity // SPEC: is present, and a compile-time error results. If the attribute-name is spelled // SPEC: such that its right-most identifier is a verbatim identifier (§2.4.2), then only // SPEC: an attribute without a suffix is matched, thus enabling such an ambiguity to be resolved. return isVerbatimIdentifier ? LookupOptions.VerbatimNameAttributeTypeOnly : LookupOptions.AttributeTypeOnly; } else { return LookupOptions.NamespacesOrTypesOnly; } } private static Symbol UnwrapAliasNoDiagnostics(Symbol symbol, ConsList<TypeSymbol> basesBeingResolved = null) { if (symbol.Kind == SymbolKind.Alias) { return ((AliasSymbol)symbol).GetAliasTarget(basesBeingResolved); } return symbol; } private NamespaceOrTypeOrAliasSymbolWithAnnotations UnwrapAlias(in NamespaceOrTypeOrAliasSymbolWithAnnotations symbol, BindingDiagnosticBag diagnostics, SyntaxNode syntax, ConsList<TypeSymbol> basesBeingResolved = null) { if (symbol.IsAlias) { AliasSymbol discarded; return NamespaceOrTypeOrAliasSymbolWithAnnotations.CreateUnannotated(symbol.IsNullableEnabled, (NamespaceOrTypeSymbol)UnwrapAlias(symbol.Symbol, out discarded, diagnostics, syntax, basesBeingResolved)); } return symbol; } private NamespaceOrTypeOrAliasSymbolWithAnnotations UnwrapAlias(in NamespaceOrTypeOrAliasSymbolWithAnnotations symbol, out AliasSymbol alias, BindingDiagnosticBag diagnostics, SyntaxNode syntax, ConsList<TypeSymbol> basesBeingResolved = null) { if (symbol.IsAlias) { return NamespaceOrTypeOrAliasSymbolWithAnnotations.CreateUnannotated(symbol.IsNullableEnabled, (NamespaceOrTypeSymbol)UnwrapAlias(symbol.Symbol, out alias, diagnostics, syntax, basesBeingResolved)); } alias = null; return symbol; } private Symbol UnwrapAlias(Symbol symbol, BindingDiagnosticBag diagnostics, SyntaxNode syntax, ConsList<TypeSymbol> basesBeingResolved = null) { AliasSymbol discarded; return UnwrapAlias(symbol, out discarded, diagnostics, syntax, basesBeingResolved); } private Symbol UnwrapAlias(Symbol symbol, out AliasSymbol alias, BindingDiagnosticBag diagnostics, SyntaxNode syntax, ConsList<TypeSymbol> basesBeingResolved = null) { Debug.Assert(syntax != null); Debug.Assert(diagnostics != null); if (symbol.Kind == SymbolKind.Alias) { alias = (AliasSymbol)symbol; var result = alias.GetAliasTarget(basesBeingResolved); var type = result as TypeSymbol; if ((object)type != null) { // pass args in a value tuple to avoid allocating a closure var args = (this, diagnostics, syntax); type.VisitType((typePart, argTuple, isNested) => { argTuple.Item1.ReportDiagnosticsIfObsolete(argTuple.diagnostics, typePart, argTuple.syntax, hasBaseReceiver: false); return false; }, args); } return result; } alias = null; return symbol; } private TypeWithAnnotations BindGenericSimpleNamespaceOrTypeOrAliasSymbol( GenericNameSyntax node, BindingDiagnosticBag diagnostics, ConsList<TypeSymbol> basesBeingResolved, NamespaceOrTypeSymbol qualifierOpt) { // We are looking for a namespace, alias or type name and the user has given // us an identifier followed by a type argument list. Therefore they // must expect the result to be a generic type, and not a namespace or alias. // The result of this method will therefore always be a type symbol of the // correct arity, though it might have to be an error type. // We might be asked to bind a generic simple name of the form "T<,,,>", // which is only legal in the context of "typeof(T<,,,>)". If we are given // no type arguments and we are not in such a context, we'll give an error. // If we do have type arguments, then the result of this method will always // be a generic type symbol constructed with the given type arguments. // There are a number of possible error conditions. First, errors involving lookup: // // * Lookup could fail to find anything at all. // * Lookup could find a type of the wrong arity // * Lookup could find something but it is not a type. // // Second, we could be asked to resolve an unbound type T<,,,> when // not in a context where it is legal to do so. Note that this is // intended an improvement over the analysis performed by the // native compiler; in the native compiler we catch bad uses of unbound // types at parse time, not at semantic analysis time. That means that // we end up giving confusing "unexpected comma" or "expected type" // errors when it would be more informative to the user to simply // tell them that an unbound type is not legal in this position. // // This also means that we can get semantic analysis of the open // type in the IDE even in what would have been a syntax error case // in the native compiler. // // We need a heuristic to deal with the situation where both kinds of errors // are potentially in play: what if someone says "typeof(Bogus<>.Blah<int>)"? // There are two errors there: first, that Bogus is not found, not a type, // or not of the appropriate arity, and second, that it is illegal to make // a partially unbound type. // // The heuristic we will use is that the former kind of error takes priority // over the latter; if the meaning of "Bogus<>" cannot be successfully // determined then there is no point telling the user that in addition, // it is syntactically wrong. Moreover, at this point we do not know what they // mean by the remainder ".Blah<int>" of the expression and so it seems wrong to // deduce more errors from it. var plainName = node.Identifier.ValueText; SeparatedSyntaxList<TypeSyntax> typeArguments = node.TypeArgumentList.Arguments; bool isUnboundTypeExpr = node.IsUnboundGenericName; LookupOptions options = GetSimpleNameLookupOptions(node, isVerbatimIdentifier: false); NamedTypeSymbol unconstructedType = LookupGenericTypeName( diagnostics, basesBeingResolved, qualifierOpt, node, plainName, node.Arity, options); NamedTypeSymbol resultType; if (isUnboundTypeExpr) { if (!IsUnboundTypeAllowed(node)) { // If we already have an error type then skip reporting that the unbound type is illegal. if (!unconstructedType.IsErrorType()) { // error CS7003: Unexpected use of an unbound generic name diagnostics.Add(ErrorCode.ERR_UnexpectedUnboundGenericName, node.Location); } resultType = unconstructedType.Construct( UnboundArgumentErrorTypeSymbol.CreateTypeArguments( unconstructedType.TypeParameters, node.Arity, errorInfo: null), unbound: false); } else { resultType = unconstructedType.AsUnboundGenericType(); } } else if ((Flags & BinderFlags.SuppressTypeArgumentBinding) != 0) { resultType = unconstructedType.Construct(PlaceholderTypeArgumentSymbol.CreateTypeArguments(unconstructedType.TypeParameters)); } else { // It's not an unbound type expression, so we must have type arguments, and we have a // generic type of the correct arity in hand (possibly an error type). Bind the type // arguments and construct the final result. resultType = ConstructNamedType( unconstructedType, node, typeArguments, BindTypeArguments(typeArguments, diagnostics, basesBeingResolved), basesBeingResolved, diagnostics); } if (options.IsAttributeTypeLookup()) { // Generic type cannot be an attribute type. // Parser error has already been reported, just wrap the result type with error type symbol. Debug.Assert(unconstructedType.IsErrorType()); Debug.Assert(resultType.IsErrorType()); resultType = new ExtendedErrorTypeSymbol(GetContainingNamespaceOrType(resultType), resultType, LookupResultKind.NotAnAttributeType, errorInfo: null); } return TypeWithAnnotations.Create(AreNullableAnnotationsEnabled(node.TypeArgumentList.GreaterThanToken), resultType); } private NamedTypeSymbol LookupGenericTypeName( BindingDiagnosticBag diagnostics, ConsList<TypeSymbol> basesBeingResolved, NamespaceOrTypeSymbol qualifierOpt, GenericNameSyntax node, string plainName, int arity, LookupOptions options) { var errorResult = CreateErrorIfLookupOnTypeParameter(node.Parent, qualifierOpt, plainName, arity, diagnostics); if ((object)errorResult != null) { return errorResult; } var lookupResult = LookupResult.GetInstance(); CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); this.LookupSymbolsSimpleName(lookupResult, qualifierOpt, plainName, arity, basesBeingResolved, options, diagnose: true, useSiteInfo: ref useSiteInfo); diagnostics.Add(node, useSiteInfo); bool wasError; Symbol lookupResultSymbol = ResultSymbol(lookupResult, plainName, arity, node, diagnostics, (basesBeingResolved != null), out wasError, qualifierOpt, options); // As we said in the method above, there are three cases here: // // * Lookup could fail to find anything at all. // * Lookup could find a type of the wrong arity // * Lookup could find something but it is not a type. // // In the first two cases we will be given back an error type symbol of the appropriate arity. // In the third case we will be given back the symbol -- say, a local variable symbol. // // In all three cases the appropriate error has already been reported. (That the // type was not found, that the generic type found does not have that arity, that // the non-generic type found cannot be used with a type argument list, or that // the symbol found is not something that takes type arguments. ) // The first thing to do is to make sure that we have some sort of generic type in hand. // (Note that an error type symbol is always a generic type.) NamedTypeSymbol type = lookupResultSymbol as NamedTypeSymbol; if ((object)type == null) { // We did a lookup with a generic arity, filtered to types and namespaces. If // we got back something other than a type, there had better be an error info // for us. Debug.Assert(lookupResult.Error != null); type = new ExtendedErrorTypeSymbol( GetContainingNamespaceOrType(lookupResultSymbol), ImmutableArray.Create<Symbol>(lookupResultSymbol), lookupResult.Kind, lookupResult.Error, arity); } lookupResult.Free(); return type; } private ExtendedErrorTypeSymbol CreateErrorIfLookupOnTypeParameter( CSharpSyntaxNode node, NamespaceOrTypeSymbol qualifierOpt, string name, int arity, BindingDiagnosticBag diagnostics) { if (((object)qualifierOpt != null) && (qualifierOpt.Kind == SymbolKind.TypeParameter)) { var diagnosticInfo = new CSDiagnosticInfo(ErrorCode.ERR_LookupInTypeVariable, qualifierOpt); diagnostics.Add(diagnosticInfo, node.Location); return new ExtendedErrorTypeSymbol(this.Compilation, name, arity, diagnosticInfo, unreported: false); } return null; } private ImmutableArray<TypeWithAnnotations> BindTypeArguments(SeparatedSyntaxList<TypeSyntax> typeArguments, BindingDiagnosticBag diagnostics, ConsList<TypeSymbol> basesBeingResolved = null) { Debug.Assert(typeArguments.Count > 0); var args = ArrayBuilder<TypeWithAnnotations>.GetInstance(); foreach (var argSyntax in typeArguments) { args.Add(BindTypeArgument(argSyntax, diagnostics, basesBeingResolved)); } return args.ToImmutableAndFree(); } private TypeWithAnnotations BindTypeArgument(TypeSyntax typeArgument, BindingDiagnosticBag diagnostics, ConsList<TypeSymbol> basesBeingResolved = null) { // Unsafe types can never be type arguments, but there's a special error code for that. var binder = this.WithAdditionalFlags(BinderFlags.SuppressUnsafeDiagnostics); var arg = typeArgument.Kind() == SyntaxKind.OmittedTypeArgument ? TypeWithAnnotations.Create(UnboundArgumentErrorTypeSymbol.Instance) : binder.BindType(typeArgument, diagnostics, basesBeingResolved); return arg; } /// <remarks> /// Keep check and error in sync with ConstructBoundMethodGroupAndReportOmittedTypeArguments. /// </remarks> private NamedTypeSymbol ConstructNamedTypeUnlessTypeArgumentOmitted(SyntaxNode typeSyntax, NamedTypeSymbol type, SeparatedSyntaxList<TypeSyntax> typeArgumentsSyntax, ImmutableArray<TypeWithAnnotations> typeArguments, BindingDiagnosticBag diagnostics) { if (typeArgumentsSyntax.Any(SyntaxKind.OmittedTypeArgument)) { // Note: lookup won't have reported this, since the arity was correct. // CONSIDER: the text of this error message makes sense, but we might want to add a separate code. Error(diagnostics, ErrorCode.ERR_BadArity, typeSyntax, type, MessageID.IDS_SK_TYPE.Localize(), typeArgumentsSyntax.Count); // If the syntax looks like an unbound generic type, then they probably wanted the definition. // Give an error indicating that the syntax is incorrect and then use the definition. // CONSIDER: we could construct an unbound generic type symbol, but that would probably be confusing // outside a typeof. return type; } else { // we pass an empty basesBeingResolved here because this invocation is not on any possible path of // infinite recursion in binding base clauses. return ConstructNamedType(type, typeSyntax, typeArgumentsSyntax, typeArguments, basesBeingResolved: null, diagnostics: diagnostics); } } /// <remarks> /// Keep check and error in sync with ConstructNamedTypeUnlessTypeArgumentOmitted. /// </remarks> private static BoundMethodOrPropertyGroup ConstructBoundMemberGroupAndReportOmittedTypeArguments( SyntaxNode syntax, SeparatedSyntaxList<TypeSyntax> typeArgumentsSyntax, ImmutableArray<TypeWithAnnotations> typeArguments, BoundExpression receiver, string plainName, ArrayBuilder<Symbol> members, LookupResult lookupResult, BoundMethodGroupFlags methodGroupFlags, bool hasErrors, BindingDiagnosticBag diagnostics) { if (!hasErrors && lookupResult.IsMultiViable && typeArgumentsSyntax.Any(SyntaxKind.OmittedTypeArgument)) { // Note: lookup won't have reported this, since the arity was correct. // CONSIDER: the text of this error message makes sense, but we might want to add a separate code. Error(diagnostics, ErrorCode.ERR_BadArity, syntax, plainName, MessageID.IDS_MethodGroup.Localize(), typeArgumentsSyntax.Count); hasErrors = true; } Debug.Assert(members.Count > 0); switch (members[0].Kind) { case SymbolKind.Method: return new BoundMethodGroup( syntax, typeArguments, receiver, plainName, members.SelectAsArray(s_toMethodSymbolFunc), lookupResult, methodGroupFlags, hasErrors); case SymbolKind.Property: return new BoundPropertyGroup( syntax, members.SelectAsArray(s_toPropertySymbolFunc), receiver, lookupResult.Kind, hasErrors); default: throw ExceptionUtilities.UnexpectedValue(members[0].Kind); } } private static readonly Func<Symbol, MethodSymbol> s_toMethodSymbolFunc = s => (MethodSymbol)s; private static readonly Func<Symbol, PropertySymbol> s_toPropertySymbolFunc = s => (PropertySymbol)s; private NamedTypeSymbol ConstructNamedType( NamedTypeSymbol type, SyntaxNode typeSyntax, SeparatedSyntaxList<TypeSyntax> typeArgumentsSyntax, ImmutableArray<TypeWithAnnotations> typeArguments, ConsList<TypeSymbol> basesBeingResolved, BindingDiagnosticBag diagnostics) { Debug.Assert(!typeArguments.IsEmpty); type = type.Construct(typeArguments); if (ShouldCheckConstraints && ConstraintsHelper.RequiresChecking(type)) { bool includeNullability = Compilation.IsFeatureEnabled(MessageID.IDS_FeatureNullableReferenceTypes); type.CheckConstraintsForNamedType(new ConstraintsHelper.CheckConstraintsArgs(this.Compilation, this.Conversions, includeNullability, typeSyntax.Location, diagnostics), typeSyntax, typeArgumentsSyntax, basesBeingResolved); } return type; } /// <summary> /// Check generic type constraints unless the type is used as part of a type or method /// declaration. In those cases, constraints checking is handled by the caller. /// </summary> private bool ShouldCheckConstraints { get { return !this.Flags.Includes(BinderFlags.SuppressConstraintChecks); } } private NamespaceOrTypeOrAliasSymbolWithAnnotations BindQualifiedName( ExpressionSyntax leftName, SimpleNameSyntax rightName, BindingDiagnosticBag diagnostics, ConsList<TypeSymbol> basesBeingResolved, bool suppressUseSiteDiagnostics) { var left = BindNamespaceOrTypeSymbol(leftName, diagnostics, basesBeingResolved, suppressUseSiteDiagnostics: false).NamespaceOrTypeSymbol; ReportDiagnosticsIfObsolete(diagnostics, left, leftName, hasBaseReceiver: false); bool isLeftUnboundGenericType = left.Kind == SymbolKind.NamedType && ((NamedTypeSymbol)left).IsUnboundGenericType; if (isLeftUnboundGenericType) { // If left name bound to an unbound generic type, // we want to perform right name lookup within // left's original named type definition. left = ((NamedTypeSymbol)left).OriginalDefinition; } // since the name is qualified, it cannot result in a using alias symbol, only a type or namespace var right = this.BindSimpleNamespaceOrTypeOrAliasSymbol(rightName, diagnostics, basesBeingResolved, suppressUseSiteDiagnostics, left); // If left name bound to an unbound generic type // and right name bound to a generic type, we must // convert right to an unbound generic type. if (isLeftUnboundGenericType) { return convertToUnboundGenericType(); } return right; // This part is moved into a local function to reduce the method's stack frame size NamespaceOrTypeOrAliasSymbolWithAnnotations convertToUnboundGenericType() { var namedTypeRight = right.Symbol as NamedTypeSymbol; if ((object)namedTypeRight != null && namedTypeRight.IsGenericType) { TypeWithAnnotations type = right.TypeWithAnnotations; return type.WithTypeAndModifiers(namedTypeRight.AsUnboundGenericType(), type.CustomModifiers); } return right; } } internal NamedTypeSymbol GetSpecialType(SpecialType typeId, BindingDiagnosticBag diagnostics, SyntaxNode node) { return GetSpecialType(this.Compilation, typeId, node, diagnostics); } internal static NamedTypeSymbol GetSpecialType(CSharpCompilation compilation, SpecialType typeId, SyntaxNode node, BindingDiagnosticBag diagnostics) { NamedTypeSymbol typeSymbol = compilation.GetSpecialType(typeId); Debug.Assert((object)typeSymbol != null, "Expect an error type if special type isn't found"); ReportUseSite(typeSymbol, diagnostics, node); return typeSymbol; } internal static NamedTypeSymbol GetSpecialType(CSharpCompilation compilation, SpecialType typeId, Location location, BindingDiagnosticBag diagnostics) { NamedTypeSymbol typeSymbol = compilation.GetSpecialType(typeId); Debug.Assert((object)typeSymbol != null, "Expect an error type if special type isn't found"); ReportUseSite(typeSymbol, diagnostics, location); return typeSymbol; } /// <summary> /// This is a layer on top of the Compilation version that generates a diagnostic if the special /// member isn't found. /// </summary> internal Symbol GetSpecialTypeMember(SpecialMember member, BindingDiagnosticBag diagnostics, SyntaxNode syntax) { Symbol memberSymbol; return TryGetSpecialTypeMember(this.Compilation, member, syntax, diagnostics, out memberSymbol) ? memberSymbol : null; } internal static bool TryGetSpecialTypeMember<TSymbol>(CSharpCompilation compilation, SpecialMember specialMember, SyntaxNode syntax, BindingDiagnosticBag diagnostics, out TSymbol symbol) where TSymbol : Symbol { symbol = (TSymbol)compilation.GetSpecialTypeMember(specialMember); if ((object)symbol == null) { MemberDescriptor descriptor = SpecialMembers.GetDescriptor(specialMember); diagnostics.Add(ErrorCode.ERR_MissingPredefinedMember, syntax.Location, descriptor.DeclaringTypeMetadataName, descriptor.Name); return false; } var useSiteInfo = GetUseSiteInfoForWellKnownMemberOrContainingType(symbol); if (useSiteInfo.DiagnosticInfo != null) { diagnostics.ReportUseSiteDiagnostic(useSiteInfo.DiagnosticInfo, new SourceLocation(syntax)); } // No need to track assemblies used by special members or types. They are coming from core library, which // doesn't have any dependencies. return true; } private static UseSiteInfo<AssemblySymbol> GetUseSiteInfoForWellKnownMemberOrContainingType(Symbol symbol) { Debug.Assert(symbol.IsDefinition); UseSiteInfo<AssemblySymbol> info = symbol.GetUseSiteInfo(); symbol.MergeUseSiteInfo(ref info, symbol.ContainingType.GetUseSiteInfo()); return info; } /// <summary> /// Reports use-site diagnostics and dependencies for the specified symbol. /// </summary> /// <returns> /// True if there was an error among the reported diagnostics /// </returns> internal static bool ReportUseSite(Symbol symbol, BindingDiagnosticBag diagnostics, SyntaxNode node) { return diagnostics.ReportUseSite(symbol, node); } internal static bool ReportUseSite(Symbol symbol, BindingDiagnosticBag diagnostics, SyntaxToken token) { return diagnostics.ReportUseSite(symbol, token); } /// <summary> /// Reports use-site diagnostics and dependencies for the specified symbol. /// </summary> /// <returns> /// True if there was an error among the reported diagnostics /// </returns> internal static bool ReportUseSite(Symbol symbol, BindingDiagnosticBag diagnostics, Location location) { return diagnostics.ReportUseSite(symbol, location); } /// <summary> /// This is a layer on top of the Compilation version that generates a diagnostic if the well-known /// type isn't found. /// </summary> internal NamedTypeSymbol GetWellKnownType(WellKnownType type, BindingDiagnosticBag diagnostics, SyntaxNode node) { return GetWellKnownType(type, diagnostics, node.Location); } /// <summary> /// This is a layer on top of the Compilation version that generates a diagnostic if the well-known /// type isn't found. /// </summary> internal NamedTypeSymbol GetWellKnownType(WellKnownType type, BindingDiagnosticBag diagnostics, Location location) { return GetWellKnownType(this.Compilation, type, diagnostics, location); } /// <summary> /// This is a layer on top of the Compilation version that generates a diagnostic if the well-known /// type isn't found. /// </summary> internal static NamedTypeSymbol GetWellKnownType(CSharpCompilation compilation, WellKnownType type, BindingDiagnosticBag diagnostics, SyntaxNode node) { return GetWellKnownType(compilation, type, diagnostics, node.Location); } internal static NamedTypeSymbol GetWellKnownType(CSharpCompilation compilation, WellKnownType type, BindingDiagnosticBag diagnostics, Location location) { NamedTypeSymbol typeSymbol = compilation.GetWellKnownType(type); Debug.Assert((object)typeSymbol != null, "Expect an error type if well-known type isn't found"); ReportUseSite(typeSymbol, diagnostics, location); return typeSymbol; } /// <summary> /// This is a layer on top of the Compilation version that generates a diagnostic if the well-known /// type isn't found. /// </summary> internal NamedTypeSymbol GetWellKnownType(WellKnownType type, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { NamedTypeSymbol typeSymbol = this.Compilation.GetWellKnownType(type); Debug.Assert((object)typeSymbol != null, "Expect an error type if well-known type isn't found"); typeSymbol.AddUseSiteInfo(ref useSiteInfo); return typeSymbol; } internal Symbol GetWellKnownTypeMember(WellKnownMember member, BindingDiagnosticBag diagnostics, Location location = null, SyntaxNode syntax = null, bool isOptional = false) { return GetWellKnownTypeMember(Compilation, member, diagnostics, location, syntax, isOptional); } /// <summary> /// Retrieves a well-known type member and reports diagnostics. /// </summary> /// <returns>Null if the symbol is missing.</returns> internal static Symbol GetWellKnownTypeMember(CSharpCompilation compilation, WellKnownMember member, BindingDiagnosticBag diagnostics, Location location = null, SyntaxNode syntax = null, bool isOptional = false) { Debug.Assert((syntax != null) ^ (location != null)); UseSiteInfo<AssemblySymbol> useSiteInfo; Symbol memberSymbol = GetWellKnownTypeMember(compilation, member, out useSiteInfo, isOptional); diagnostics.Add(useSiteInfo, location ?? syntax.Location); return memberSymbol; } internal static Symbol GetWellKnownTypeMember(CSharpCompilation compilation, WellKnownMember member, out UseSiteInfo<AssemblySymbol> useSiteInfo, bool isOptional = false) { Symbol memberSymbol = compilation.GetWellKnownTypeMember(member); if ((object)memberSymbol != null) { useSiteInfo = GetUseSiteInfoForWellKnownMemberOrContainingType(memberSymbol); if (useSiteInfo.DiagnosticInfo != null) { // Dev11 reports use-site diagnostics even for optional symbols that are found. // We decided to silently ignore bad optional symbols. // Report errors only for non-optional members: if (isOptional) { var severity = useSiteInfo.DiagnosticInfo.Severity; // if the member is optional and bad for whatever reason ignore it: if (severity == DiagnosticSeverity.Error) { useSiteInfo = default; return null; } // ignore warnings: useSiteInfo = new UseSiteInfo<AssemblySymbol>(diagnosticInfo: null, useSiteInfo.PrimaryDependency, useSiteInfo.SecondaryDependencies); } } } else if (!isOptional) { // member is missing MemberDescriptor memberDescriptor = WellKnownMembers.GetDescriptor(member); useSiteInfo = new UseSiteInfo<AssemblySymbol>(new CSDiagnosticInfo(ErrorCode.ERR_MissingPredefinedMember, memberDescriptor.DeclaringTypeMetadataName, memberDescriptor.Name)); } else { useSiteInfo = default; } return memberSymbol; } private class ConsistentSymbolOrder : IComparer<Symbol> { public static readonly ConsistentSymbolOrder Instance = new ConsistentSymbolOrder(); public int Compare(Symbol fst, Symbol snd) { if (snd == fst) return 0; if ((object)fst == null) return -1; if ((object)snd == null) return 1; if (snd.Name != fst.Name) return string.CompareOrdinal(fst.Name, snd.Name); if (snd.Kind != fst.Kind) return (int)fst.Kind - (int)snd.Kind; int aLocationsCount = !snd.Locations.IsDefault ? snd.Locations.Length : 0; int bLocationsCount = fst.Locations.Length; if (aLocationsCount != bLocationsCount) return aLocationsCount - bLocationsCount; if (aLocationsCount == 0 && bLocationsCount == 0) return Compare(fst.ContainingSymbol, snd.ContainingSymbol); Location la = snd.Locations[0]; Location lb = fst.Locations[0]; if (la.IsInSource != lb.IsInSource) return la.IsInSource ? 1 : -1; int containerResult = Compare(fst.ContainingSymbol, snd.ContainingSymbol); if (!la.IsInSource) return containerResult; if (containerResult == 0 && la.SourceTree == lb.SourceTree) return lb.SourceSpan.Start - la.SourceSpan.Start; return containerResult; } } // return the type or namespace symbol in a lookup result, or report an error. internal Symbol ResultSymbol( LookupResult result, string simpleName, int arity, SyntaxNode where, BindingDiagnosticBag diagnostics, bool suppressUseSiteDiagnostics, out bool wasError, NamespaceOrTypeSymbol qualifierOpt, LookupOptions options = default(LookupOptions)) { Symbol symbol = resultSymbol(result, simpleName, arity, where, diagnostics, suppressUseSiteDiagnostics, out wasError, qualifierOpt, options); if (symbol.Kind == SymbolKind.NamedType) { CheckReceiverAndRuntimeSupportForSymbolAccess(where, receiverOpt: null, symbol, diagnostics); if (suppressUseSiteDiagnostics && diagnostics.DependenciesBag is object) { AssemblySymbol container = symbol.ContainingAssembly; if (container is object && container != Compilation.Assembly && container != Compilation.Assembly.CorLibrary) { diagnostics.AddDependency(container); } } } return symbol; Symbol resultSymbol( LookupResult result, string simpleName, int arity, SyntaxNode where, BindingDiagnosticBag diagnostics, bool suppressUseSiteDiagnostics, out bool wasError, NamespaceOrTypeSymbol qualifierOpt, LookupOptions options) { Debug.Assert(where != null); Debug.Assert(diagnostics != null); var symbols = result.Symbols; wasError = false; if (result.IsMultiViable) { if (symbols.Count > 1) { // gracefully handle symbols.Count > 2 symbols.Sort(ConsistentSymbolOrder.Instance); var originalSymbols = symbols.ToImmutable(); for (int i = 0; i < symbols.Count; i++) { symbols[i] = UnwrapAlias(symbols[i], diagnostics, where); } BestSymbolInfo secondBest; BestSymbolInfo best = GetBestSymbolInfo(symbols, out secondBest); Debug.Assert(!best.IsNone); Debug.Assert(!secondBest.IsNone); if (best.IsFromCompilation && !secondBest.IsFromCompilation) { var srcSymbol = symbols[best.Index]; var mdSymbol = symbols[secondBest.Index]; object arg0; if (best.IsFromSourceModule) { arg0 = srcSymbol.Locations.First().SourceTree.FilePath; } else { Debug.Assert(best.IsFromAddedModule); arg0 = srcSymbol.ContainingModule; } //if names match, arities match, and containing symbols match (recursively), ... if (NameAndArityMatchRecursively(srcSymbol, mdSymbol)) { if (srcSymbol.Kind == SymbolKind.Namespace && mdSymbol.Kind == SymbolKind.NamedType) { // ErrorCode.WRN_SameFullNameThisNsAgg: The namespace '{1}' in '{0}' conflicts with the imported type '{3}' in '{2}'. Using the namespace defined in '{0}'. diagnostics.Add(ErrorCode.WRN_SameFullNameThisNsAgg, where.Location, originalSymbols, arg0, srcSymbol, mdSymbol.ContainingAssembly, mdSymbol); return originalSymbols[best.Index]; } else if (srcSymbol.Kind == SymbolKind.NamedType && mdSymbol.Kind == SymbolKind.Namespace) { // ErrorCode.WRN_SameFullNameThisAggNs: The type '{1}' in '{0}' conflicts with the imported namespace '{3}' in '{2}'. Using the type defined in '{0}'. diagnostics.Add(ErrorCode.WRN_SameFullNameThisAggNs, where.Location, originalSymbols, arg0, srcSymbol, GetContainingAssembly(mdSymbol), mdSymbol); return originalSymbols[best.Index]; } else if (srcSymbol.Kind == SymbolKind.NamedType && mdSymbol.Kind == SymbolKind.NamedType) { // WRN_SameFullNameThisAggAgg: The type '{1}' in '{0}' conflicts with the imported type '{3}' in '{2}'. Using the type defined in '{0}'. diagnostics.Add(ErrorCode.WRN_SameFullNameThisAggAgg, where.Location, originalSymbols, arg0, srcSymbol, mdSymbol.ContainingAssembly, mdSymbol); return originalSymbols[best.Index]; } else { // namespace would be merged with the source namespace: Debug.Assert(!(srcSymbol.Kind == SymbolKind.Namespace && mdSymbol.Kind == SymbolKind.Namespace)); } } } var first = symbols[best.Index]; var second = symbols[secondBest.Index]; Debug.Assert(!Symbol.Equals(originalSymbols[best.Index], originalSymbols[secondBest.Index], TypeCompareKind.ConsiderEverything) || options.IsAttributeTypeLookup(), "This kind of ambiguity is only possible for attributes."); Debug.Assert(!Symbol.Equals(first, second, TypeCompareKind.ConsiderEverything) || !Symbol.Equals(originalSymbols[best.Index], originalSymbols[secondBest.Index], TypeCompareKind.ConsiderEverything), "Why does the LookupResult contain the same symbol twice?"); CSDiagnosticInfo info; bool reportError; //if names match, arities match, and containing symbols match (recursively), ... if (first != second && NameAndArityMatchRecursively(first, second)) { // suppress reporting the error if we found multiple symbols from source module // since an error has already been reported from the declaration reportError = !(best.IsFromSourceModule && secondBest.IsFromSourceModule); if (first.Kind == SymbolKind.NamedType && second.Kind == SymbolKind.NamedType) { if (first.OriginalDefinition == second.OriginalDefinition) { // We imported different generic instantiations of the same generic type // and have an ambiguous reference to a type nested in it reportError = true; // '{0}' is an ambiguous reference between '{1}' and '{2}' info = new CSDiagnosticInfo(ErrorCode.ERR_AmbigContext, originalSymbols, new object[] { (where as NameSyntax)?.ErrorDisplayName() ?? simpleName, new FormattedSymbol(first, SymbolDisplayFormat.CSharpErrorMessageFormat), new FormattedSymbol(second, SymbolDisplayFormat.CSharpErrorMessageFormat) }); } else { Debug.Assert(!best.IsFromCorLibrary); // ErrorCode.ERR_SameFullNameAggAgg: The type '{1}' exists in both '{0}' and '{2}' info = new CSDiagnosticInfo(ErrorCode.ERR_SameFullNameAggAgg, originalSymbols, new object[] { first.ContainingAssembly, first, second.ContainingAssembly }); // Do not report this error if the first is declared in source and the second is declared in added module, // we already reported declaration error about this name collision. // Do not report this error if both are declared in added modules, // we will report assembly level declaration error about this name collision. if (secondBest.IsFromAddedModule) { Debug.Assert(best.IsFromCompilation); reportError = false; } else if (this.Flags.Includes(BinderFlags.IgnoreCorLibraryDuplicatedTypes) && secondBest.IsFromCorLibrary) { // Ignore duplicate types from the cor library if necessary. // (Specifically the framework assemblies loaded at runtime in // the EE may contain types also available from mscorlib.dll.) return first; } } } else if (first.Kind == SymbolKind.Namespace && second.Kind == SymbolKind.NamedType) { // ErrorCode.ERR_SameFullNameNsAgg: The namespace '{1}' in '{0}' conflicts with the type '{3}' in '{2}' info = new CSDiagnosticInfo(ErrorCode.ERR_SameFullNameNsAgg, originalSymbols, new object[] { GetContainingAssembly(first), first, second.ContainingAssembly, second }); // Do not report this error if namespace is declared in source and the type is declared in added module, // we already reported declaration error about this name collision. if (best.IsFromSourceModule && secondBest.IsFromAddedModule) { reportError = false; } } else if (first.Kind == SymbolKind.NamedType && second.Kind == SymbolKind.Namespace) { if (!secondBest.IsFromCompilation || secondBest.IsFromSourceModule) { // ErrorCode.ERR_SameFullNameNsAgg: The namespace '{1}' in '{0}' conflicts with the type '{3}' in '{2}' info = new CSDiagnosticInfo(ErrorCode.ERR_SameFullNameNsAgg, originalSymbols, new object[] { GetContainingAssembly(second), second, first.ContainingAssembly, first }); } else { Debug.Assert(secondBest.IsFromAddedModule); // ErrorCode.ERR_SameFullNameThisAggThisNs: The type '{1}' in '{0}' conflicts with the namespace '{3}' in '{2}' object arg0; if (best.IsFromSourceModule) { arg0 = first.Locations.First().SourceTree.FilePath; } else { Debug.Assert(best.IsFromAddedModule); arg0 = first.ContainingModule; } ModuleSymbol arg2 = second.ContainingModule; // Merged namespaces that span multiple modules don't have a containing module, // so just use module with the smallest ordinal from the containing assembly. if ((object)arg2 == null) { foreach (NamespaceSymbol ns in ((NamespaceSymbol)second).ConstituentNamespaces) { if (ns.ContainingAssembly == Compilation.Assembly) { ModuleSymbol module = ns.ContainingModule; if ((object)arg2 == null || arg2.Ordinal > module.Ordinal) { arg2 = module; } } } } Debug.Assert(arg2.ContainingAssembly == Compilation.Assembly); info = new CSDiagnosticInfo(ErrorCode.ERR_SameFullNameThisAggThisNs, originalSymbols, new object[] { arg0, first, arg2, second }); } } else if (first.Kind == SymbolKind.RangeVariable && second.Kind == SymbolKind.RangeVariable) { // We will already have reported a conflicting range variable declaration. info = new CSDiagnosticInfo(ErrorCode.ERR_AmbigMember, originalSymbols, new object[] { first, second }); } else { // TODO: this is not an appropriate error message here, but used as a fallback until the // appropriate diagnostics are implemented. // '{0}' is an ambiguous reference between '{1}' and '{2}' //info = diagnostics.Add(ErrorCode.ERR_AmbigContext, location, readOnlySymbols, // whereText, // first, // second); // CS0229: Ambiguity between '{0}' and '{1}' info = new CSDiagnosticInfo(ErrorCode.ERR_AmbigMember, originalSymbols, new object[] { first, second }); reportError = true; } } else { Debug.Assert(originalSymbols[best.Index].Name != originalSymbols[secondBest.Index].Name || !Symbol.Equals(originalSymbols[best.Index], originalSymbols[secondBest.Index], TypeCompareKind.ConsiderEverything), "Why was the lookup result viable if it contained non-equal symbols with the same name?"); reportError = true; if (first is NamespaceOrTypeSymbol && second is NamespaceOrTypeSymbol) { if (options.IsAttributeTypeLookup() && first.Kind == SymbolKind.NamedType && second.Kind == SymbolKind.NamedType && originalSymbols[best.Index].Name != originalSymbols[secondBest.Index].Name && // Use alias names, if available. Compilation.IsAttributeType((NamedTypeSymbol)first) && Compilation.IsAttributeType((NamedTypeSymbol)second)) { // SPEC: If an attribute class is found both with and without Attribute suffix, an ambiguity // SPEC: is present, and a compile-time error results. info = new CSDiagnosticInfo(ErrorCode.ERR_AmbiguousAttribute, originalSymbols, new object[] { (where as NameSyntax)?.ErrorDisplayName() ?? simpleName, first, second }); } else { // '{0}' is an ambiguous reference between '{1}' and '{2}' info = new CSDiagnosticInfo(ErrorCode.ERR_AmbigContext, originalSymbols, new object[] { (where as NameSyntax)?.ErrorDisplayName() ?? simpleName, new FormattedSymbol(first, SymbolDisplayFormat.CSharpErrorMessageFormat), new FormattedSymbol(second, SymbolDisplayFormat.CSharpErrorMessageFormat) }); } } else { // CS0229: Ambiguity between '{0}' and '{1}' info = new CSDiagnosticInfo(ErrorCode.ERR_AmbigMember, originalSymbols, new object[] { first, second }); } } wasError = true; if (reportError) { diagnostics.Add(info, where.Location); } return new ExtendedErrorTypeSymbol( GetContainingNamespaceOrType(originalSymbols[0]), originalSymbols, LookupResultKind.Ambiguous, info, arity); } else { // Single viable result. var singleResult = symbols[0]; // Cannot reference System.Void directly. var singleType = singleResult as TypeSymbol; if ((object)singleType != null && singleType.PrimitiveTypeCode == Cci.PrimitiveTypeCode.Void && simpleName == "Void") { wasError = true; var errorInfo = new CSDiagnosticInfo(ErrorCode.ERR_SystemVoid); diagnostics.Add(errorInfo, where.Location); singleResult = new ExtendedErrorTypeSymbol(GetContainingNamespaceOrType(singleResult), singleResult, LookupResultKind.NotReferencable, errorInfo); // UNDONE: Review resultkind. } // Check for bad symbol. else { if (singleResult.Kind == SymbolKind.NamedType && ((SourceModuleSymbol)this.Compilation.SourceModule).AnyReferencedAssembliesAreLinked) { // Complain about unembeddable types from linked assemblies. if (diagnostics.DiagnosticBag is object) { Emit.NoPia.EmbeddedTypesManager.IsValidEmbeddableType((NamedTypeSymbol)singleResult, where, diagnostics.DiagnosticBag); } } if (!suppressUseSiteDiagnostics) { wasError = ReportUseSite(singleResult, diagnostics, where); } else if (singleResult.Kind == SymbolKind.ErrorType) { // We want to report ERR_CircularBase error on the spot to make sure // that the right location is used for it. var errorType = (ErrorTypeSymbol)singleResult; if (errorType.Unreported) { DiagnosticInfo errorInfo = errorType.ErrorInfo; if (errorInfo != null && errorInfo.Code == (int)ErrorCode.ERR_CircularBase) { wasError = true; diagnostics.Add(errorInfo, where.Location); singleResult = new ExtendedErrorTypeSymbol(GetContainingNamespaceOrType(errorType), errorType.Name, errorType.Arity, errorInfo, unreported: false); } } } } return singleResult; } } // Below here is the error case; no viable symbols found (but maybe one or more non-viable.) wasError = true; if (result.Kind == LookupResultKind.Empty) { string aliasOpt = null; SyntaxNode node = where; while (node is ExpressionSyntax) { if (node.Kind() == SyntaxKind.AliasQualifiedName) { aliasOpt = ((AliasQualifiedNameSyntax)node).Alias.Identifier.ValueText; break; } node = node.Parent; } CSDiagnosticInfo info = NotFound(where, simpleName, arity, (where as NameSyntax)?.ErrorDisplayName() ?? simpleName, diagnostics, aliasOpt, qualifierOpt, options); return new ExtendedErrorTypeSymbol(qualifierOpt ?? Compilation.Assembly.GlobalNamespace, simpleName, arity, info); } Debug.Assert(symbols.Count > 0); // Report any errors we encountered with the symbol we looked up. if (!suppressUseSiteDiagnostics) { for (int i = 0; i < symbols.Count; i++) { ReportUseSite(symbols[i], diagnostics, where); } } // result.Error might be null if we have already generated parser errors, // e.g. when generic name is used for attribute name. if (result.Error != null && ((object)qualifierOpt == null || qualifierOpt.Kind != SymbolKind.ErrorType)) // Suppress cascading. { diagnostics.Add(new CSDiagnostic(result.Error, where.Location)); } if ((symbols.Count > 1) || (symbols[0] is NamespaceOrTypeSymbol || symbols[0] is AliasSymbol) || result.Kind == LookupResultKind.NotATypeOrNamespace || result.Kind == LookupResultKind.NotAnAttributeType) { // Bad type or namespace (or things expected as types/namespaces) are packaged up as error types, preserving the symbols and the result kind. // We do this if there are multiple symbols too, because just returning one would be losing important information, and they might // be of different kinds. return new ExtendedErrorTypeSymbol(GetContainingNamespaceOrType(symbols[0]), symbols.ToImmutable(), result.Kind, result.Error, arity); } else { // It's a single non-type-or-namespace; error was already reported, so just return it. return symbols[0]; } } } private static AssemblySymbol GetContainingAssembly(Symbol symbol) { // Merged namespaces that span multiple assemblies don't have a containing assembly, // so just use the containing assembly of the first constituent. return symbol.ContainingAssembly ?? ((NamespaceSymbol)symbol).ConstituentNamespaces.First().ContainingAssembly; } [Flags] private enum BestSymbolLocation { None, FromSourceModule, FromAddedModule, FromReferencedAssembly, FromCorLibrary, } [DebuggerDisplay("Location = {_location}, Index = {_index}")] private struct BestSymbolInfo { private readonly BestSymbolLocation _location; private readonly int _index; /// <summary> /// Returns -1 if None. /// </summary> public int Index { get { return IsNone ? -1 : _index; } } public bool IsFromSourceModule { get { return _location == BestSymbolLocation.FromSourceModule; } } public bool IsFromAddedModule { get { return _location == BestSymbolLocation.FromAddedModule; } } public bool IsFromCompilation { get { return (_location == BestSymbolLocation.FromSourceModule) || (_location == BestSymbolLocation.FromAddedModule); } } public bool IsNone { get { return _location == BestSymbolLocation.None; } } public bool IsFromCorLibrary { get { return _location == BestSymbolLocation.FromCorLibrary; } } public BestSymbolInfo(BestSymbolLocation location, int index) { Debug.Assert(location != BestSymbolLocation.None); _location = location; _index = index; } /// <summary> /// Prefers symbols from source module, then from added modules, then from referenced assemblies. /// Returns true if values were swapped. /// </summary> public static bool Sort(ref BestSymbolInfo first, ref BestSymbolInfo second) { if (IsSecondLocationBetter(first._location, second._location)) { BestSymbolInfo temp = first; first = second; second = temp; return true; } return false; } /// <summary> /// Returns true if the second is a better location than the first. /// </summary> public static bool IsSecondLocationBetter(BestSymbolLocation firstLocation, BestSymbolLocation secondLocation) { Debug.Assert(secondLocation != 0); return (firstLocation == BestSymbolLocation.None) || (firstLocation > secondLocation); } } /// <summary> /// Prefer symbols from source module, then from added modules, then from referenced assemblies. /// </summary> private BestSymbolInfo GetBestSymbolInfo(ArrayBuilder<Symbol> symbols, out BestSymbolInfo secondBest) { BestSymbolInfo first = default(BestSymbolInfo); BestSymbolInfo second = default(BestSymbolInfo); var compilation = this.Compilation; for (int i = 0; i < symbols.Count; i++) { var symbol = symbols[i]; BestSymbolLocation location; if (symbol.Kind == SymbolKind.Namespace) { location = BestSymbolLocation.None; foreach (var ns in ((NamespaceSymbol)symbol).ConstituentNamespaces) { var current = GetLocation(compilation, ns); if (BestSymbolInfo.IsSecondLocationBetter(location, current)) { location = current; if (location == BestSymbolLocation.FromSourceModule) { break; } } } } else { location = GetLocation(compilation, symbol); } var third = new BestSymbolInfo(location, i); if (BestSymbolInfo.Sort(ref second, ref third)) { BestSymbolInfo.Sort(ref first, ref second); } } Debug.Assert(!first.IsNone); Debug.Assert(!second.IsNone); secondBest = second; return first; } private static BestSymbolLocation GetLocation(CSharpCompilation compilation, Symbol symbol) { var containingAssembly = symbol.ContainingAssembly; if (containingAssembly == compilation.SourceAssembly) { return (symbol.ContainingModule == compilation.SourceModule) ? BestSymbolLocation.FromSourceModule : BestSymbolLocation.FromAddedModule; } else { return (containingAssembly == containingAssembly.CorLibrary) ? BestSymbolLocation.FromCorLibrary : BestSymbolLocation.FromReferencedAssembly; } } /// <remarks> /// This is only intended to be called when the type isn't found (i.e. not when it is found but is inaccessible, has the wrong arity, etc). /// </remarks> private CSDiagnosticInfo NotFound(SyntaxNode where, string simpleName, int arity, string whereText, BindingDiagnosticBag diagnostics, string aliasOpt, NamespaceOrTypeSymbol qualifierOpt, LookupOptions options) { var location = where.Location; // Lookup totally ignores type forwarders, but we want the type lookup diagnostics // to distinguish between a type that can't be found and a type that is only present // as a type forwarder. We'll look for type forwarders in the containing and // referenced assemblies and report more specific diagnostics if they are found. AssemblySymbol forwardedToAssembly; // for attributes, suggest both, but not for verbatim name if (options.IsAttributeTypeLookup() && !options.IsVerbatimNameAttributeTypeLookup()) { // just recurse one level, so cheat and OR verbatim name option :) NotFound(where, simpleName, arity, whereText + "Attribute", diagnostics, aliasOpt, qualifierOpt, options | LookupOptions.VerbatimNameAttributeTypeOnly); } if ((object)qualifierOpt != null) { if (qualifierOpt.IsType) { var errorQualifier = qualifierOpt as ErrorTypeSymbol; if ((object)errorQualifier != null && errorQualifier.ErrorInfo != null) { return (CSDiagnosticInfo)errorQualifier.ErrorInfo; } return diagnostics.Add(ErrorCode.ERR_DottedTypeNameNotFoundInAgg, location, whereText, qualifierOpt); } else { Debug.Assert(qualifierOpt.IsNamespace); forwardedToAssembly = GetForwardedToAssembly(simpleName, arity, ref qualifierOpt, diagnostics, location); if (ReferenceEquals(qualifierOpt, Compilation.GlobalNamespace)) { Debug.Assert(aliasOpt == null || aliasOpt == SyntaxFacts.GetText(SyntaxKind.GlobalKeyword)); return (object)forwardedToAssembly == null ? diagnostics.Add(ErrorCode.ERR_GlobalSingleTypeNameNotFound, location, whereText, qualifierOpt) : diagnostics.Add(ErrorCode.ERR_GlobalSingleTypeNameNotFoundFwd, location, whereText, forwardedToAssembly); } else { object container = qualifierOpt; // If there was an alias (e.g. A::C) and the given qualifier is the global namespace of the alias, // then use the alias name in the error message, since it's more helpful than "<global namespace>". if (aliasOpt != null && qualifierOpt.IsNamespace && ((NamespaceSymbol)qualifierOpt).IsGlobalNamespace) { container = aliasOpt; } return (object)forwardedToAssembly == null ? diagnostics.Add(ErrorCode.ERR_DottedTypeNameNotFoundInNS, location, whereText, container) : diagnostics.Add(ErrorCode.ERR_DottedTypeNameNotFoundInNSFwd, location, whereText, container, forwardedToAssembly); } } } if (options == LookupOptions.NamespaceAliasesOnly) { return diagnostics.Add(ErrorCode.ERR_AliasNotFound, location, whereText); } if ((where as IdentifierNameSyntax)?.Identifier.Text == "var" && !options.IsAttributeTypeLookup()) { var code = (where.Parent is QueryClauseSyntax) ? ErrorCode.ERR_TypeVarNotFoundRangeVariable : ErrorCode.ERR_TypeVarNotFound; return diagnostics.Add(code, location); } forwardedToAssembly = GetForwardedToAssembly(simpleName, arity, ref qualifierOpt, diagnostics, location); if ((object)forwardedToAssembly != null) { return qualifierOpt == null ? diagnostics.Add(ErrorCode.ERR_SingleTypeNameNotFoundFwd, location, whereText, forwardedToAssembly) : diagnostics.Add(ErrorCode.ERR_DottedTypeNameNotFoundInNSFwd, location, whereText, qualifierOpt, forwardedToAssembly); } return diagnostics.Add(ErrorCode.ERR_SingleTypeNameNotFound, location, whereText); } protected virtual AssemblySymbol GetForwardedToAssemblyInUsingNamespaces(string metadataName, ref NamespaceOrTypeSymbol qualifierOpt, BindingDiagnosticBag diagnostics, Location location) { return Next?.GetForwardedToAssemblyInUsingNamespaces(metadataName, ref qualifierOpt, diagnostics, location); } protected AssemblySymbol GetForwardedToAssembly(string fullName, BindingDiagnosticBag diagnostics, Location location) { var metadataName = MetadataTypeName.FromFullName(fullName); foreach (var referencedAssembly in Compilation.Assembly.Modules[0].GetReferencedAssemblySymbols()) { var forwardedType = referencedAssembly.TryLookupForwardedMetadataType(ref metadataName); if ((object)forwardedType != null) { if (forwardedType.Kind == SymbolKind.ErrorType) { DiagnosticInfo diagInfo = ((ErrorTypeSymbol)forwardedType).ErrorInfo; if (diagInfo.Code == (int)ErrorCode.ERR_CycleInTypeForwarder) { Debug.Assert((object)forwardedType.ContainingAssembly != null, "How did we find a cycle if there was no forwarding?"); diagnostics.Add(ErrorCode.ERR_CycleInTypeForwarder, location, fullName, forwardedType.ContainingAssembly.Name); } else if (diagInfo.Code == (int)ErrorCode.ERR_TypeForwardedToMultipleAssemblies) { diagnostics.Add(diagInfo, location); return null; // Cannot determine a suitable forwarding assembly } } return forwardedType.ContainingAssembly; } } return null; } /// <summary> /// Look for a type forwarder for the given type in the containing assembly and any referenced assemblies. /// </summary> /// <param name="name">The name of the (potentially) forwarded type.</param> /// <param name="arity">The arity of the forwarded type.</param> /// <param name="qualifierOpt">The namespace of the potentially forwarded type. If none is provided, will /// try Usings of the current import for eligible namespaces and return the namespace of the found forwarder, /// if any.</param> /// <param name="diagnostics">Will be used to report non-fatal errors during look up.</param> /// <param name="location">Location to report errors on.</param> /// <returns>Returns the Assembly to which the type is forwarded, or null if none is found.</returns> /// <remarks> /// Since this method is intended to be used for error reporting, it stops as soon as it finds /// any type forwarder (or an error to report). It does not check other assemblies for consistency or better results. /// </remarks> protected AssemblySymbol GetForwardedToAssembly(string name, int arity, ref NamespaceOrTypeSymbol qualifierOpt, BindingDiagnosticBag diagnostics, Location location) { // If we are in the process of binding assembly level attributes, we might get into an infinite cycle // if any of the referenced assemblies forwards type to this assembly. Since forwarded types // are specified through assembly level attributes, an attempt to resolve the forwarded type // might require us to examine types forwarded by this assembly, thus binding assembly level // attributes again. And the cycle continues. // So, we won't do the analysis in this case, at the expense of better diagnostics. if ((this.Flags & BinderFlags.InContextualAttributeBinder) != 0) { var current = this; do { var contextualAttributeBinder = current as ContextualAttributeBinder; if (contextualAttributeBinder != null) { if ((object)contextualAttributeBinder.AttributeTarget != null && contextualAttributeBinder.AttributeTarget.Kind == SymbolKind.Assembly) { return null; } break; } current = current.Next; } while (current != null); } // NOTE: This won't work if the type isn't using CLS-style generic naming (i.e. `arity), but this code is // only intended to improve diagnostic messages, so false negatives in corner cases aren't a big deal. var metadataName = MetadataHelpers.ComposeAritySuffixedMetadataName(name, arity); var fullMetadataName = MetadataHelpers.BuildQualifiedName(qualifierOpt?.ToDisplayString(SymbolDisplayFormat.QualifiedNameOnlyFormat), metadataName); var result = GetForwardedToAssembly(fullMetadataName, diagnostics, location); if ((object)result != null) { return result; } if ((object)qualifierOpt == null) { return GetForwardedToAssemblyInUsingNamespaces(metadataName, ref qualifierOpt, diagnostics, location); } return null; } #nullable enable internal static bool CheckFeatureAvailability(SyntaxNode syntax, MessageID feature, BindingDiagnosticBag diagnostics, Location? location = null) { return CheckFeatureAvailability(syntax, feature, diagnostics.DiagnosticBag, location); } internal static bool CheckFeatureAvailability(SyntaxNode syntax, MessageID feature, DiagnosticBag? diagnostics, Location? location = null) { return CheckFeatureAvailability(syntax.SyntaxTree, feature, diagnostics, location ?? syntax.GetLocation()); } internal static bool CheckFeatureAvailability(SyntaxTree tree, MessageID feature, BindingDiagnosticBag diagnostics, Location location) { return CheckFeatureAvailability(tree, feature, diagnostics.DiagnosticBag, location); } internal static bool CheckFeatureAvailability(SyntaxTree tree, MessageID feature, DiagnosticBag? diagnostics, Location location) { if (feature.GetFeatureAvailabilityDiagnosticInfo((CSharpParseOptions)tree.Options) is { } diagInfo) { diagnostics?.Add(diagInfo, location); return false; } return true; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Runtime.CompilerServices; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.RuntimeMembers; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { internal partial class Binder { /// <summary> /// Binds the type for the syntax taking into account possibility of "var" type. /// </summary> /// <param name="syntax">Type syntax to bind.</param> /// <param name="diagnostics">Diagnostics.</param> /// <param name="isVar"> /// Set to false if syntax binds to a type in the current context and true if /// syntax is "var" and it binds to "var" keyword in the current context. /// </param> /// <returns> /// Bound type if syntax binds to a type in the current context and /// null if syntax binds to "var" keyword in the current context. /// </returns> internal TypeWithAnnotations BindTypeOrVarKeyword(TypeSyntax syntax, BindingDiagnosticBag diagnostics, out bool isVar) { var symbol = BindTypeOrAliasOrVarKeyword(syntax, diagnostics, out isVar); Debug.Assert(isVar == symbol.IsDefault); return isVar ? default : UnwrapAlias(symbol, diagnostics, syntax).TypeWithAnnotations; } /// <summary> /// Binds the type for the syntax taking into account possibility of "unmanaged" type. /// </summary> /// <param name="syntax">Type syntax to bind.</param> /// <param name="diagnostics">Diagnostics.</param> /// <param name="keyword"> /// Set to <see cref="ConstraintContextualKeyword.None"/> if syntax binds to a type in the current context, otherwise /// syntax binds to the corresponding keyword in the current context. /// </param> /// <returns> /// Bound type if syntax binds to a type in the current context and /// null if syntax binds to a contextual constraint keyword. /// </returns> private TypeWithAnnotations BindTypeOrConstraintKeyword(TypeSyntax syntax, BindingDiagnosticBag diagnostics, out ConstraintContextualKeyword keyword) { var symbol = BindTypeOrAliasOrConstraintKeyword(syntax, diagnostics, out keyword); Debug.Assert((keyword != ConstraintContextualKeyword.None) == symbol.IsDefault); return (keyword != ConstraintContextualKeyword.None) ? default : UnwrapAlias(symbol, diagnostics, syntax).TypeWithAnnotations; } /// <summary> /// Binds the type for the syntax taking into account possibility of "var" type. /// </summary> /// <param name="syntax">Type syntax to bind.</param> /// <param name="diagnostics">Diagnostics.</param> /// <param name="isVar"> /// Set to false if syntax binds to a type in the current context and true if /// syntax is "var" and it binds to "var" keyword in the current context. /// </param> /// <param name="alias">Alias symbol if syntax binds to an alias.</param> /// <returns> /// Bound type if syntax binds to a type in the current context and /// null if syntax binds to "var" keyword in the current context. /// </returns> internal TypeWithAnnotations BindTypeOrVarKeyword(TypeSyntax syntax, BindingDiagnosticBag diagnostics, out bool isVar, out AliasSymbol alias) { var symbol = BindTypeOrAliasOrVarKeyword(syntax, diagnostics, out isVar); Debug.Assert(isVar == symbol.IsDefault); if (isVar) { alias = null; return default; } else { return UnwrapAlias(symbol, out alias, diagnostics, syntax).TypeWithAnnotations; } } /// <summary> /// Binds the type for the syntax taking into account possibility of "var" type. /// If the syntax binds to an alias symbol to a type, it returns the alias symbol. /// </summary> /// <param name="syntax">Type syntax to bind.</param> /// <param name="diagnostics">Diagnostics.</param> /// <param name="isVar"> /// Set to false if syntax binds to a type or alias to a type in the current context and true if /// syntax is "var" and it binds to "var" keyword in the current context. /// </param> /// <returns> /// Bound type or alias if syntax binds to a type or alias to a type in the current context and /// null if syntax binds to "var" keyword in the current context. /// </returns> private NamespaceOrTypeOrAliasSymbolWithAnnotations BindTypeOrAliasOrVarKeyword(TypeSyntax syntax, BindingDiagnosticBag diagnostics, out bool isVar) { if (syntax.IsVar) { var symbol = BindTypeOrAliasOrKeyword((IdentifierNameSyntax)syntax, diagnostics, out isVar); if (isVar) { CheckFeatureAvailability(syntax, MessageID.IDS_FeatureImplicitLocal, diagnostics); } return symbol; } else { isVar = false; return BindTypeOrAlias(syntax, diagnostics, basesBeingResolved: null); } } private enum ConstraintContextualKeyword { None, Unmanaged, NotNull, } private NamespaceOrTypeOrAliasSymbolWithAnnotations BindTypeOrAliasOrConstraintKeyword(TypeSyntax syntax, BindingDiagnosticBag diagnostics, out ConstraintContextualKeyword keyword) { if (syntax.IsUnmanaged) { keyword = ConstraintContextualKeyword.Unmanaged; } else if (syntax.IsNotNull) { keyword = ConstraintContextualKeyword.NotNull; } else { keyword = ConstraintContextualKeyword.None; } if (keyword != ConstraintContextualKeyword.None) { var identifierSyntax = (IdentifierNameSyntax)syntax; var symbol = BindTypeOrAliasOrKeyword(identifierSyntax, diagnostics, out bool isKeyword); if (isKeyword) { switch (keyword) { case ConstraintContextualKeyword.Unmanaged: CheckFeatureAvailability(syntax, MessageID.IDS_FeatureUnmanagedGenericTypeConstraint, diagnostics); break; case ConstraintContextualKeyword.NotNull: CheckFeatureAvailability(identifierSyntax, MessageID.IDS_FeatureNotNullGenericTypeConstraint, diagnostics); break; default: throw ExceptionUtilities.UnexpectedValue(keyword); } } else { keyword = ConstraintContextualKeyword.None; } return symbol; } else { return BindTypeOrAlias(syntax, diagnostics, basesBeingResolved: null); } } /// <summary> /// Binds the type for the syntax taking into account possibility of the type being a keyword. /// If the syntax binds to an alias symbol to a type, it returns the alias symbol. /// PREREQUISITE: syntax should be checked to match the keyword, like <see cref="TypeSyntax.IsVar"/> or <see cref="TypeSyntax.IsUnmanaged"/>. /// Otherwise, call <see cref="Binder.BindTypeOrAlias(ExpressionSyntax, BindingDiagnosticBag, ConsList{TypeSymbol}, bool)"/> instead. /// </summary> private NamespaceOrTypeOrAliasSymbolWithAnnotations BindTypeOrAliasOrKeyword(IdentifierNameSyntax syntax, BindingDiagnosticBag diagnostics, out bool isKeyword) { return BindTypeOrAliasOrKeyword(((IdentifierNameSyntax)syntax).Identifier, syntax, diagnostics, out isKeyword); } private NamespaceOrTypeOrAliasSymbolWithAnnotations BindTypeOrAliasOrKeyword(SyntaxToken identifier, SyntaxNode syntax, BindingDiagnosticBag diagnostics, out bool isKeyword) { // Keywords can only be IdentifierNameSyntax var identifierValueText = identifier.ValueText; Symbol symbol = null; // Perform name lookup without generating diagnostics as it could possibly be a keyword in the current context. var lookupResult = LookupResult.GetInstance(); var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; this.LookupSymbolsInternal(lookupResult, identifierValueText, arity: 0, useSiteInfo: ref discardedUseSiteInfo, basesBeingResolved: null, options: LookupOptions.NamespacesOrTypesOnly, diagnose: false); // We have following possible cases for lookup: // 1) LookupResultKind.Empty: must be a keyword // 2) LookupResultKind.Viable: // a) Single viable result that corresponds to 1) a non-error type: cannot be a keyword // 2) an error type: must be a keyword // b) Single viable result that corresponds to namespace: must be a keyword // c) Multi viable result (ambiguous result), we must return an error type: cannot be a keyword // 3) Non viable, non empty lookup result: must be a keyword // BREAKING CHANGE: Case (2)(c) is a breaking change from the native compiler. // BREAKING CHANGE: Native compiler interprets lookup with ambiguous result to correspond to bind // BREAKING CHANGE: to "var" keyword (isVar = true), rather than reporting an error. // BREAKING CHANGE: See test SemanticErrorTests.ErrorMeansSuccess_var() for an example. switch (lookupResult.Kind) { case LookupResultKind.Empty: // Case (1) isKeyword = true; symbol = null; break; case LookupResultKind.Viable: // Case (2) var resultDiagnostics = new BindingDiagnosticBag(DiagnosticBag.GetInstance(), diagnostics.DependenciesBag); bool wasError; symbol = ResultSymbol( lookupResult, identifierValueText, arity: 0, where: syntax, diagnostics: resultDiagnostics, suppressUseSiteDiagnostics: false, wasError: out wasError, qualifierOpt: null); // Here, we're mimicking behavior of dev10. If the identifier fails to bind // as a type, even if the reason is (e.g.) a type/alias conflict, then treat // it as the contextual keyword. if (wasError && lookupResult.IsSingleViable) { // NOTE: don't report diagnostics - we're not going to use the lookup result. resultDiagnostics.DiagnosticBag.Free(); // Case (2)(a)(2) goto default; } diagnostics.AddRange(resultDiagnostics.DiagnosticBag); resultDiagnostics.DiagnosticBag.Free(); if (lookupResult.IsSingleViable) { var type = UnwrapAlias(symbol, diagnostics, syntax) as TypeSymbol; if ((object)type != null) { // Case (2)(a)(1) isKeyword = false; } else { // Case (2)(b) Debug.Assert(UnwrapAliasNoDiagnostics(symbol) is NamespaceSymbol); isKeyword = true; symbol = null; } } else { // Case (2)(c) isKeyword = false; } break; default: // Case (3) isKeyword = true; symbol = null; break; } lookupResult.Free(); return NamespaceOrTypeOrAliasSymbolWithAnnotations.CreateUnannotated(AreNullableAnnotationsEnabled(identifier), symbol); } // Binds the given expression syntax as Type. // If the resulting symbol is an Alias to a Type, it unwraps the alias // and returns it's target type. internal TypeWithAnnotations BindType(ExpressionSyntax syntax, BindingDiagnosticBag diagnostics, ConsList<TypeSymbol> basesBeingResolved = null, bool suppressUseSiteDiagnostics = false) { var symbol = BindTypeOrAlias(syntax, diagnostics, basesBeingResolved, suppressUseSiteDiagnostics); return UnwrapAlias(symbol, diagnostics, syntax, basesBeingResolved).TypeWithAnnotations; } // Binds the given expression syntax as Type. // If the resulting symbol is an Alias to a Type, it stores the AliasSymbol in // the alias parameter, unwraps the alias and returns it's target type. internal TypeWithAnnotations BindType(ExpressionSyntax syntax, BindingDiagnosticBag diagnostics, out AliasSymbol alias, ConsList<TypeSymbol> basesBeingResolved = null) { var symbol = BindTypeOrAlias(syntax, diagnostics, basesBeingResolved); return UnwrapAlias(symbol, out alias, diagnostics, syntax, basesBeingResolved).TypeWithAnnotations; } // Binds the given expression syntax as Type or an Alias to Type // and returns the resultant symbol. // NOTE: This method doesn't unwrap aliases. internal NamespaceOrTypeOrAliasSymbolWithAnnotations BindTypeOrAlias(ExpressionSyntax syntax, BindingDiagnosticBag diagnostics, ConsList<TypeSymbol> basesBeingResolved = null, bool suppressUseSiteDiagnostics = false) { Debug.Assert(diagnostics != null); var symbol = BindNamespaceOrTypeOrAliasSymbol(syntax, diagnostics, basesBeingResolved, basesBeingResolved != null || suppressUseSiteDiagnostics); // symbol must be a TypeSymbol or an Alias to a TypeSymbol if (symbol.IsType || (symbol.IsAlias && UnwrapAliasNoDiagnostics(symbol.Symbol, basesBeingResolved) is TypeSymbol)) { if (symbol.IsType) { // Obsolete alias targets are reported in UnwrapAlias, but if it was a type (not an // alias to a type) we report the obsolete type here. symbol.TypeWithAnnotations.ReportDiagnosticsIfObsolete(this, syntax, diagnostics); } return symbol; } var diagnosticInfo = diagnostics.Add(ErrorCode.ERR_BadSKknown, syntax.Location, syntax, symbol.Symbol.GetKindText(), MessageID.IDS_SK_TYPE.Localize()); return TypeWithAnnotations.Create(new ExtendedErrorTypeSymbol(GetContainingNamespaceOrType(symbol.Symbol), symbol.Symbol, LookupResultKind.NotATypeOrNamespace, diagnosticInfo)); } /// <summary> /// The immediately containing namespace or named type, or the global /// namespace if containing symbol is neither a namespace or named type. /// </summary> private NamespaceOrTypeSymbol GetContainingNamespaceOrType(Symbol symbol) { return symbol.ContainingNamespaceOrType() ?? this.Compilation.Assembly.GlobalNamespace; } internal Symbol BindNamespaceAliasSymbol(IdentifierNameSyntax node, BindingDiagnosticBag diagnostics) { if (node.Identifier.Kind() == SyntaxKind.GlobalKeyword) { return this.Compilation.GlobalNamespaceAlias; } else { bool wasError; var plainName = node.Identifier.ValueText; var result = LookupResult.GetInstance(); CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); this.LookupSymbolsWithFallback(result, plainName, 0, ref useSiteInfo, null, LookupOptions.NamespaceAliasesOnly); diagnostics.Add(node, useSiteInfo); Symbol bindingResult = ResultSymbol(result, plainName, 0, node, diagnostics, false, out wasError, qualifierOpt: null, options: LookupOptions.NamespaceAliasesOnly); result.Free(); return bindingResult; } } internal NamespaceOrTypeOrAliasSymbolWithAnnotations BindNamespaceOrTypeSymbol(ExpressionSyntax syntax, BindingDiagnosticBag diagnostics, ConsList<TypeSymbol> basesBeingResolved = null) { return BindNamespaceOrTypeSymbol(syntax, diagnostics, basesBeingResolved, basesBeingResolved != null); } /// <summary> /// This method is used in deeply recursive parts of the compiler and requires a non-trivial amount of stack /// space to execute. Preventing inlining here to keep recursive frames small. /// </summary> [MethodImpl(MethodImplOptions.NoInlining)] internal NamespaceOrTypeOrAliasSymbolWithAnnotations BindNamespaceOrTypeSymbol(ExpressionSyntax syntax, BindingDiagnosticBag diagnostics, ConsList<TypeSymbol> basesBeingResolved, bool suppressUseSiteDiagnostics) { var result = BindNamespaceOrTypeOrAliasSymbol(syntax, diagnostics, basesBeingResolved, suppressUseSiteDiagnostics); Debug.Assert(!result.IsDefault); return UnwrapAlias(result, diagnostics, syntax, basesBeingResolved); } #nullable enable /// <summary> /// Bind the syntax into a namespace, type or alias symbol. /// </summary> /// <remarks> /// This method is used in deeply recursive parts of the compiler. Specifically this and /// <see cref="BindQualifiedName(ExpressionSyntax, SimpleNameSyntax, BindingDiagnosticBag, ConsList{TypeSymbol}, bool)"/> /// are mutually recursive. The non-recursive parts of this method tend to reserve significantly large /// stack frames due to their use of large struct like <see cref="TypeWithAnnotations"/>. /// /// To keep the stack frame size on recursive paths small the non-recursive parts are factored into local /// functions. This means we pay their stack penalty only when they are used. They are themselves big /// enough they should be disqualified from inlining. In the future when attributes are allowed on /// local functions we should explicitly mark them as <see cref="MethodImplOptions.NoInlining"/> /// </remarks> internal NamespaceOrTypeOrAliasSymbolWithAnnotations BindNamespaceOrTypeOrAliasSymbol(ExpressionSyntax syntax, BindingDiagnosticBag diagnostics, ConsList<TypeSymbol> basesBeingResolved, bool suppressUseSiteDiagnostics) { switch (syntax.Kind()) { case SyntaxKind.NullableType: return bindNullable(); case SyntaxKind.PredefinedType: return bindPredefined(); case SyntaxKind.IdentifierName: return BindNonGenericSimpleNamespaceOrTypeOrAliasSymbol((IdentifierNameSyntax)syntax, diagnostics, basesBeingResolved, suppressUseSiteDiagnostics, qualifierOpt: null); case SyntaxKind.GenericName: return BindGenericSimpleNamespaceOrTypeOrAliasSymbol((GenericNameSyntax)syntax, diagnostics, basesBeingResolved, qualifierOpt: null); case SyntaxKind.AliasQualifiedName: return bindAlias(); case SyntaxKind.QualifiedName: { var node = (QualifiedNameSyntax)syntax; return BindQualifiedName(node.Left, node.Right, diagnostics, basesBeingResolved, suppressUseSiteDiagnostics); } case SyntaxKind.SimpleMemberAccessExpression: { var node = (MemberAccessExpressionSyntax)syntax; return BindQualifiedName(node.Expression, node.Name, diagnostics, basesBeingResolved, suppressUseSiteDiagnostics); } case SyntaxKind.ArrayType: { return BindArrayType((ArrayTypeSyntax)syntax, diagnostics, permitDimensions: false, basesBeingResolved, disallowRestrictedTypes: true); } case SyntaxKind.PointerType: return bindPointer(); case SyntaxKind.FunctionPointerType: var functionPointerTypeSyntax = (FunctionPointerTypeSyntax)syntax; if (GetUnsafeDiagnosticInfo(sizeOfTypeOpt: null) is CSDiagnosticInfo info) { var @delegate = functionPointerTypeSyntax.DelegateKeyword; var asterisk = functionPointerTypeSyntax.AsteriskToken; RoslynDebug.Assert(@delegate.SyntaxTree is object); diagnostics.Add(info, Location.Create(@delegate.SyntaxTree, TextSpan.FromBounds(@delegate.SpanStart, asterisk.Span.End))); } return TypeWithAnnotations.Create( FunctionPointerTypeSymbol.CreateFromSource( functionPointerTypeSyntax, this, diagnostics, basesBeingResolved, suppressUseSiteDiagnostics)); case SyntaxKind.OmittedTypeArgument: { return BindTypeArgument((TypeSyntax)syntax, diagnostics, basesBeingResolved); } case SyntaxKind.TupleType: { var tupleTypeSyntax = (TupleTypeSyntax)syntax; return TypeWithAnnotations.Create(AreNullableAnnotationsEnabled(tupleTypeSyntax.CloseParenToken), BindTupleType(tupleTypeSyntax, diagnostics, basesBeingResolved)); } case SyntaxKind.RefType: { // ref needs to be handled by the caller var refTypeSyntax = (RefTypeSyntax)syntax; var refToken = refTypeSyntax.RefKeyword; if (!syntax.HasErrors) { diagnostics.Add(ErrorCode.ERR_UnexpectedToken, refToken.GetLocation(), refToken.ToString()); } return BindNamespaceOrTypeOrAliasSymbol(refTypeSyntax.Type, diagnostics, basesBeingResolved, suppressUseSiteDiagnostics); } default: { // This is invalid syntax for a type. This arises when a constant pattern that fails to bind // is attempted to be bound as a type pattern. return createErrorType(); } } void reportNullableReferenceTypesIfNeeded(SyntaxToken questionToken, TypeWithAnnotations typeArgument = default) { bool isNullableEnabled = AreNullableAnnotationsEnabled(questionToken); bool isGeneratedCode = IsGeneratedCode(questionToken); var location = questionToken.GetLocation(); if (diagnostics.DiagnosticBag is DiagnosticBag diagnosticBag) { // Inside a method body or other executable code, we can question IsValueType without causing cycles. if (typeArgument.HasType && !ShouldCheckConstraints) { LazyMissingNonNullTypesContextDiagnosticInfo.AddAll( isNullableEnabled, isGeneratedCode, typeArgument, location, diagnosticBag); } else { LazyMissingNonNullTypesContextDiagnosticInfo.ReportNullableReferenceTypesIfNeeded( isNullableEnabled, isGeneratedCode, typeArgument, location, diagnosticBag); } } } NamespaceOrTypeOrAliasSymbolWithAnnotations bindNullable() { var nullableSyntax = (NullableTypeSyntax)syntax; TypeSyntax typeArgumentSyntax = nullableSyntax.ElementType; TypeWithAnnotations typeArgument = BindType(typeArgumentSyntax, diagnostics, basesBeingResolved); TypeWithAnnotations constructedType = typeArgument.SetIsAnnotated(Compilation); reportNullableReferenceTypesIfNeeded(nullableSyntax.QuestionToken, typeArgument); if (!ShouldCheckConstraints) { diagnostics.Add(new LazyUseSiteDiagnosticsInfoForNullableType(Compilation.LanguageVersion, constructedType), syntax.GetLocation()); } else if (constructedType.IsNullableType()) { ReportUseSite(constructedType.Type.OriginalDefinition, diagnostics, syntax); var type = (NamedTypeSymbol)constructedType.Type; var location = syntax.Location; type.CheckConstraints(new ConstraintsHelper.CheckConstraintsArgs(this.Compilation, this.Conversions, includeNullability: true, location, diagnostics)); } else if (GetNullableUnconstrainedTypeParameterDiagnosticIfNecessary(Compilation.LanguageVersion, constructedType) is { } diagnosticInfo) { diagnostics.Add(diagnosticInfo, syntax.Location); } return constructedType; } NamespaceOrTypeOrAliasSymbolWithAnnotations bindPredefined() { var predefinedType = (PredefinedTypeSyntax)syntax; var type = BindPredefinedTypeSymbol(predefinedType, diagnostics); return TypeWithAnnotations.Create(AreNullableAnnotationsEnabled(predefinedType.Keyword), type); } NamespaceOrTypeOrAliasSymbolWithAnnotations bindAlias() { var node = (AliasQualifiedNameSyntax)syntax; var bindingResult = BindNamespaceAliasSymbol(node.Alias, diagnostics); var alias = bindingResult as AliasSymbol; NamespaceOrTypeSymbol left = (alias is object) ? alias.Target : (NamespaceOrTypeSymbol)bindingResult; if (left.Kind == SymbolKind.NamedType) { return TypeWithAnnotations.Create(new ExtendedErrorTypeSymbol(left, LookupResultKind.NotATypeOrNamespace, diagnostics.Add(ErrorCode.ERR_ColColWithTypeAlias, node.Alias.Location, node.Alias.Identifier.Text))); } return this.BindSimpleNamespaceOrTypeOrAliasSymbol(node.Name, diagnostics, basesBeingResolved, suppressUseSiteDiagnostics, left); } NamespaceOrTypeOrAliasSymbolWithAnnotations bindPointer() { var node = (PointerTypeSyntax)syntax; var elementType = BindType(node.ElementType, diagnostics, basesBeingResolved); ReportUnsafeIfNotAllowed(node, diagnostics); if (!Flags.HasFlag(BinderFlags.SuppressConstraintChecks)) { CheckManagedAddr(Compilation, elementType.Type, node.Location, diagnostics); } return TypeWithAnnotations.Create(new PointerTypeSymbol(elementType)); } NamespaceOrTypeOrAliasSymbolWithAnnotations createErrorType() { diagnostics.Add(ErrorCode.ERR_TypeExpected, syntax.GetLocation()); return TypeWithAnnotations.Create(CreateErrorType()); } } internal static CSDiagnosticInfo? GetNullableUnconstrainedTypeParameterDiagnosticIfNecessary(LanguageVersion languageVersion, in TypeWithAnnotations type) { if (type.Type.IsTypeParameterDisallowingAnnotationInCSharp8()) { // 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(); if (requiredVersion > languageVersion) { return new CSDiagnosticInfo(ErrorCode.ERR_NullableUnconstrainedTypeParameter, new CSharpRequiredLanguageVersion(requiredVersion)); } } return null; } #nullable disable private TypeWithAnnotations BindArrayType( ArrayTypeSyntax node, BindingDiagnosticBag diagnostics, bool permitDimensions, ConsList<TypeSymbol> basesBeingResolved, bool disallowRestrictedTypes) { TypeWithAnnotations type = BindType(node.ElementType, diagnostics, basesBeingResolved); if (type.IsStatic) { // CS0719: '{0}': array elements cannot be of static type Error(diagnostics, ErrorCode.ERR_ArrayOfStaticClass, node.ElementType, type.Type); } if (disallowRestrictedTypes) { // Restricted types cannot be on the heap, but they can be on the stack, so are allowed in a stackalloc if (ShouldCheckConstraints) { if (type.IsRestrictedType()) { // CS0611: Array elements cannot be of type '{0}' Error(diagnostics, ErrorCode.ERR_ArrayElementCantBeRefAny, node.ElementType, type.Type); } } else { diagnostics.Add(new LazyArrayElementCantBeRefAnyDiagnosticInfo(type), node.ElementType.GetLocation()); } } for (int i = node.RankSpecifiers.Count - 1; i >= 0; i--) { var rankSpecifier = node.RankSpecifiers[i]; var dimension = rankSpecifier.Sizes; if (!permitDimensions && dimension.Count != 0 && dimension[0].Kind() != SyntaxKind.OmittedArraySizeExpression) { // https://github.com/dotnet/roslyn/issues/32464 // Should capture invalid dimensions for use in `SemanticModel` and `IOperation`. Error(diagnostics, ErrorCode.ERR_ArraySizeInDeclaration, rankSpecifier); } var array = ArrayTypeSymbol.CreateCSharpArray(this.Compilation.Assembly, type, rankSpecifier.Rank); type = TypeWithAnnotations.Create(AreNullableAnnotationsEnabled(rankSpecifier.CloseBracketToken), array); } return type; } private TypeSymbol BindTupleType(TupleTypeSyntax syntax, BindingDiagnosticBag diagnostics, ConsList<TypeSymbol> basesBeingResolved) { int numElements = syntax.Elements.Count; var types = ArrayBuilder<TypeWithAnnotations>.GetInstance(numElements); var locations = ArrayBuilder<Location>.GetInstance(numElements); ArrayBuilder<string> elementNames = null; // set of names already used var uniqueFieldNames = PooledHashSet<string>.GetInstance(); bool hasExplicitNames = false; for (int i = 0; i < numElements; i++) { var argumentSyntax = syntax.Elements[i]; var argumentType = BindType(argumentSyntax.Type, diagnostics, basesBeingResolved); types.Add(argumentType); string name = null; SyntaxToken nameToken = argumentSyntax.Identifier; if (nameToken.Kind() == SyntaxKind.IdentifierToken) { name = nameToken.ValueText; // validate name if we have one hasExplicitNames = true; CheckTupleMemberName(name, i, nameToken, diagnostics, uniqueFieldNames); locations.Add(nameToken.GetLocation()); } else { locations.Add(argumentSyntax.Location); } CollectTupleFieldMemberName(name, i, numElements, ref elementNames); } uniqueFieldNames.Free(); if (hasExplicitNames) { // If the tuple type with names is bound we must have the TupleElementNamesAttribute to emit // it is typically there though, if we have ValueTuple at all ReportMissingTupleElementNamesAttributesIfNeeded(Compilation, syntax.GetLocation(), diagnostics); } var typesArray = types.ToImmutableAndFree(); var locationsArray = locations.ToImmutableAndFree(); if (typesArray.Length < 2) { throw ExceptionUtilities.UnexpectedValue(typesArray.Length); } bool includeNullability = Compilation.IsFeatureEnabled(MessageID.IDS_FeatureNullableReferenceTypes); return NamedTypeSymbol.CreateTuple(syntax.Location, typesArray, locationsArray, elementNames == null ? default(ImmutableArray<string>) : elementNames.ToImmutableAndFree(), this.Compilation, this.ShouldCheckConstraints, includeNullability: this.ShouldCheckConstraints && includeNullability, errorPositions: default(ImmutableArray<bool>), syntax: syntax, diagnostics: diagnostics); } internal static void ReportMissingTupleElementNamesAttributesIfNeeded(CSharpCompilation compilation, Location location, BindingDiagnosticBag diagnostics) { var bag = BindingDiagnosticBag.GetInstance(diagnostics); if (!compilation.HasTupleNamesAttributes(bag, location)) { var info = new CSDiagnosticInfo(ErrorCode.ERR_TupleElementNamesAttributeMissing, AttributeDescription.TupleElementNamesAttribute.FullName); Error(diagnostics, info, location); } else { diagnostics.AddRange(bag); } bag.Free(); } private static void CollectTupleFieldMemberName(string name, int elementIndex, int tupleSize, ref ArrayBuilder<string> elementNames) { // add the name to the list // names would typically all be there or none at all // but in case we need to handle this in error cases if (elementNames != null) { elementNames.Add(name); } else { if (name != null) { elementNames = ArrayBuilder<string>.GetInstance(tupleSize); for (int j = 0; j < elementIndex; j++) { elementNames.Add(null); } elementNames.Add(name); } } } private static bool CheckTupleMemberName(string name, int index, SyntaxNodeOrToken syntax, BindingDiagnosticBag diagnostics, PooledHashSet<string> uniqueFieldNames) { int reserved = NamedTypeSymbol.IsTupleElementNameReserved(name); if (reserved == 0) { Error(diagnostics, ErrorCode.ERR_TupleReservedElementNameAnyPosition, syntax, name); return false; } else if (reserved > 0 && reserved != index + 1) { Error(diagnostics, ErrorCode.ERR_TupleReservedElementName, syntax, name, reserved); return false; } else if (!uniqueFieldNames.Add(name)) { Error(diagnostics, ErrorCode.ERR_TupleDuplicateElementName, syntax); return false; } return true; } private NamedTypeSymbol BindPredefinedTypeSymbol(PredefinedTypeSyntax node, BindingDiagnosticBag diagnostics) { return GetSpecialType(node.Keyword.Kind().GetSpecialType(), diagnostics, node); } /// <summary> /// Binds a simple name or the simple name portion of a qualified name. /// </summary> private NamespaceOrTypeOrAliasSymbolWithAnnotations BindSimpleNamespaceOrTypeOrAliasSymbol( SimpleNameSyntax syntax, BindingDiagnosticBag diagnostics, ConsList<TypeSymbol> basesBeingResolved, bool suppressUseSiteDiagnostics, NamespaceOrTypeSymbol qualifierOpt = null) { // Note that the comment above is a small lie; there is no such thing as the "simple name portion" of // a qualified alias member expression. A qualified alias member expression has the form // "identifier :: identifier optional-type-arguments" -- the right hand side of which // happens to match the syntactic form of a simple name. As a convenience, we analyze the // right hand side of the "::" here because it is so similar to a simple name; the left hand // side is in qualifierOpt. switch (syntax.Kind()) { default: return TypeWithAnnotations.Create(new ExtendedErrorTypeSymbol(qualifierOpt ?? this.Compilation.Assembly.GlobalNamespace, string.Empty, arity: 0, errorInfo: null)); case SyntaxKind.IdentifierName: return BindNonGenericSimpleNamespaceOrTypeOrAliasSymbol((IdentifierNameSyntax)syntax, diagnostics, basesBeingResolved, suppressUseSiteDiagnostics, qualifierOpt); case SyntaxKind.GenericName: return BindGenericSimpleNamespaceOrTypeOrAliasSymbol((GenericNameSyntax)syntax, diagnostics, basesBeingResolved, qualifierOpt); } } private static bool IsViableType(LookupResult result) { if (!result.IsMultiViable) { return false; } foreach (var s in result.Symbols) { switch (s.Kind) { case SymbolKind.Alias: if (((AliasSymbol)s).Target.Kind == SymbolKind.NamedType) return true; break; case SymbolKind.NamedType: case SymbolKind.TypeParameter: return true; } } return false; } protected NamespaceOrTypeOrAliasSymbolWithAnnotations BindNonGenericSimpleNamespaceOrTypeOrAliasSymbol( IdentifierNameSyntax node, BindingDiagnosticBag diagnostics, ConsList<TypeSymbol> basesBeingResolved, bool suppressUseSiteDiagnostics, NamespaceOrTypeSymbol qualifierOpt) { var identifierValueText = node.Identifier.ValueText; // If we are here in an error-recovery scenario, say, "goo<int, >(123);" then // we might have an 'empty' simple name. In that case do not report an // 'unable to find ""' error; we've already reported an error in the parser so // just bail out with an error symbol. if (string.IsNullOrWhiteSpace(identifierValueText)) { return TypeWithAnnotations.Create(new ExtendedErrorTypeSymbol( Compilation.Assembly.GlobalNamespace, identifierValueText, 0, new CSDiagnosticInfo(ErrorCode.ERR_SingleTypeNameNotFound))); } var errorResult = CreateErrorIfLookupOnTypeParameter(node.Parent, qualifierOpt, identifierValueText, 0, diagnostics); if ((object)errorResult != null) { return TypeWithAnnotations.Create(errorResult); } var result = LookupResult.GetInstance(); LookupOptions options = GetSimpleNameLookupOptions(node, node.Identifier.IsVerbatimIdentifier()); CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); this.LookupSymbolsSimpleName(result, qualifierOpt, identifierValueText, 0, basesBeingResolved, options, diagnose: true, useSiteInfo: ref useSiteInfo); diagnostics.Add(node, useSiteInfo); Symbol bindingResult = null; // If we were looking up "dynamic" or "nint" at the topmost level and didn't find anything good, // use that particular type (assuming the /langversion is supported). if ((object)qualifierOpt == null && !IsViableType(result)) { if (node.Identifier.ValueText == "dynamic") { if ((node.Parent == null || node.Parent.Kind() != SyntaxKind.Attribute && // dynamic not allowed as attribute type SyntaxFacts.IsInTypeOnlyContext(node)) && Compilation.LanguageVersion >= MessageID.IDS_FeatureDynamic.RequiredVersion()) { bindingResult = Compilation.DynamicType; ReportUseSiteDiagnosticForDynamic(diagnostics, node); } } else { bindingResult = BindNativeIntegerSymbolIfAny(node, diagnostics); } } if (bindingResult is null) { bool wasError; bindingResult = ResultSymbol(result, identifierValueText, 0, node, diagnostics, suppressUseSiteDiagnostics, out wasError, qualifierOpt, options); if (bindingResult.Kind == SymbolKind.Alias) { var aliasTarget = ((AliasSymbol)bindingResult).GetAliasTarget(basesBeingResolved); if (aliasTarget.Kind == SymbolKind.NamedType && ((NamedTypeSymbol)aliasTarget).ContainsDynamic()) { ReportUseSiteDiagnosticForDynamic(diagnostics, node); } } } result.Free(); return NamespaceOrTypeOrAliasSymbolWithAnnotations.CreateUnannotated(AreNullableAnnotationsEnabled(node.Identifier), bindingResult); } /// <summary> /// If the node is "nint" or "nuint" and not alone inside nameof, return the corresponding native integer symbol. /// Otherwise return null. /// </summary> private NamedTypeSymbol BindNativeIntegerSymbolIfAny(IdentifierNameSyntax node, BindingDiagnosticBag diagnostics) { SpecialType specialType; switch (node.Identifier.Text) { case "nint": specialType = SpecialType.System_IntPtr; break; case "nuint": specialType = SpecialType.System_UIntPtr; break; default: return null; } switch (node.Parent) { case AttributeSyntax parent when parent.Name == node: // [nint] return null; case UsingDirectiveSyntax parent when parent.Name == node: // using nint; using A = nuint; return null; case ArgumentSyntax parent when // nameof(nint) (IsInsideNameof && parent.Parent?.Parent is InvocationExpressionSyntax invocation && (invocation.Expression as IdentifierNameSyntax)?.Identifier.ContextualKind() == SyntaxKind.NameOfKeyword): // Don't bind nameof(nint) or nameof(nuint) so that ERR_NameNotInContext is reported. return null; } CheckFeatureAvailability(node, MessageID.IDS_FeatureNativeInt, diagnostics); return this.GetSpecialType(specialType, diagnostics, node).AsNativeInteger(); } private void ReportUseSiteDiagnosticForDynamic(BindingDiagnosticBag diagnostics, IdentifierNameSyntax node) { // Dynamic type might be bound in a declaration context where we need to synthesize the DynamicAttribute. // Here we report the use site error (ERR_DynamicAttributeMissing) for missing DynamicAttribute type or it's constructors. // // BREAKING CHANGE: Native compiler reports ERR_DynamicAttributeMissing at emit time when synthesizing DynamicAttribute. // Currently, in Roslyn we don't support reporting diagnostics while synthesizing attributes, these diagnostics are reported at bind time. // Hence, we report this diagnostic here. Note that DynamicAttribute has two constructors, and either of them may be used while // synthesizing the DynamicAttribute (see DynamicAttributeEncoder.Encode method for details). // However, unlike the native compiler which reports use site diagnostic only for the specific DynamicAttribute constructor which is going to be used, // we report it for both the constructors and also for boolean type (used by the second constructor). // This is a breaking change for the case where only one of the two constructor of DynamicAttribute is missing, but we never use it for any of the synthesized DynamicAttributes. // However, this seems like a very unlikely scenario and an acceptable break. if (node.IsTypeInContextWhichNeedsDynamicAttribute()) { var bag = BindingDiagnosticBag.GetInstance(diagnostics); if (!Compilation.HasDynamicEmitAttributes(bag, node.Location)) { // CONSIDER: Native compiler reports error CS1980 for each syntax node which binds to dynamic type, we do the same by reporting a diagnostic here. // However, this means we generate multiple duplicate diagnostics, when a single one would suffice. // We may want to consider adding an "Unreported" flag to the DynamicTypeSymbol to suppress duplicate CS1980. // CS1980: Cannot define a class or member that utilizes 'dynamic' because the compiler required type '{0}' cannot be found. Are you missing a reference? var info = new CSDiagnosticInfo(ErrorCode.ERR_DynamicAttributeMissing, AttributeDescription.DynamicAttribute.FullName); Symbol.ReportUseSiteDiagnostic(info, diagnostics, node.Location); } else { diagnostics.AddRange(bag); } bag.Free(); this.GetSpecialType(SpecialType.System_Boolean, diagnostics, node); } } // Gets the name lookup options for simple generic or non-generic name. private static LookupOptions GetSimpleNameLookupOptions(NameSyntax node, bool isVerbatimIdentifier) { if (SyntaxFacts.IsAttributeName(node)) { // SPEC: By convention, attribute classes are named with a suffix of Attribute. // SPEC: An attribute-name of the form type-name may either include or omit this suffix. // SPEC: If an attribute class is found both with and without this suffix, an ambiguity // SPEC: is present, and a compile-time error results. If the attribute-name is spelled // SPEC: such that its right-most identifier is a verbatim identifier (§2.4.2), then only // SPEC: an attribute without a suffix is matched, thus enabling such an ambiguity to be resolved. return isVerbatimIdentifier ? LookupOptions.VerbatimNameAttributeTypeOnly : LookupOptions.AttributeTypeOnly; } else { return LookupOptions.NamespacesOrTypesOnly; } } private static Symbol UnwrapAliasNoDiagnostics(Symbol symbol, ConsList<TypeSymbol> basesBeingResolved = null) { if (symbol.Kind == SymbolKind.Alias) { return ((AliasSymbol)symbol).GetAliasTarget(basesBeingResolved); } return symbol; } private NamespaceOrTypeOrAliasSymbolWithAnnotations UnwrapAlias(in NamespaceOrTypeOrAliasSymbolWithAnnotations symbol, BindingDiagnosticBag diagnostics, SyntaxNode syntax, ConsList<TypeSymbol> basesBeingResolved = null) { if (symbol.IsAlias) { AliasSymbol discarded; return NamespaceOrTypeOrAliasSymbolWithAnnotations.CreateUnannotated(symbol.IsNullableEnabled, (NamespaceOrTypeSymbol)UnwrapAlias(symbol.Symbol, out discarded, diagnostics, syntax, basesBeingResolved)); } return symbol; } private NamespaceOrTypeOrAliasSymbolWithAnnotations UnwrapAlias(in NamespaceOrTypeOrAliasSymbolWithAnnotations symbol, out AliasSymbol alias, BindingDiagnosticBag diagnostics, SyntaxNode syntax, ConsList<TypeSymbol> basesBeingResolved = null) { if (symbol.IsAlias) { return NamespaceOrTypeOrAliasSymbolWithAnnotations.CreateUnannotated(symbol.IsNullableEnabled, (NamespaceOrTypeSymbol)UnwrapAlias(symbol.Symbol, out alias, diagnostics, syntax, basesBeingResolved)); } alias = null; return symbol; } private Symbol UnwrapAlias(Symbol symbol, BindingDiagnosticBag diagnostics, SyntaxNode syntax, ConsList<TypeSymbol> basesBeingResolved = null) { AliasSymbol discarded; return UnwrapAlias(symbol, out discarded, diagnostics, syntax, basesBeingResolved); } private Symbol UnwrapAlias(Symbol symbol, out AliasSymbol alias, BindingDiagnosticBag diagnostics, SyntaxNode syntax, ConsList<TypeSymbol> basesBeingResolved = null) { Debug.Assert(syntax != null); Debug.Assert(diagnostics != null); if (symbol.Kind == SymbolKind.Alias) { alias = (AliasSymbol)symbol; var result = alias.GetAliasTarget(basesBeingResolved); var type = result as TypeSymbol; if ((object)type != null) { // pass args in a value tuple to avoid allocating a closure var args = (this, diagnostics, syntax); type.VisitType((typePart, argTuple, isNested) => { argTuple.Item1.ReportDiagnosticsIfObsolete(argTuple.diagnostics, typePart, argTuple.syntax, hasBaseReceiver: false); return false; }, args); } return result; } alias = null; return symbol; } private TypeWithAnnotations BindGenericSimpleNamespaceOrTypeOrAliasSymbol( GenericNameSyntax node, BindingDiagnosticBag diagnostics, ConsList<TypeSymbol> basesBeingResolved, NamespaceOrTypeSymbol qualifierOpt) { // We are looking for a namespace, alias or type name and the user has given // us an identifier followed by a type argument list. Therefore they // must expect the result to be a generic type, and not a namespace or alias. // The result of this method will therefore always be a type symbol of the // correct arity, though it might have to be an error type. // We might be asked to bind a generic simple name of the form "T<,,,>", // which is only legal in the context of "typeof(T<,,,>)". If we are given // no type arguments and we are not in such a context, we'll give an error. // If we do have type arguments, then the result of this method will always // be a generic type symbol constructed with the given type arguments. // There are a number of possible error conditions. First, errors involving lookup: // // * Lookup could fail to find anything at all. // * Lookup could find a type of the wrong arity // * Lookup could find something but it is not a type. // // Second, we could be asked to resolve an unbound type T<,,,> when // not in a context where it is legal to do so. Note that this is // intended an improvement over the analysis performed by the // native compiler; in the native compiler we catch bad uses of unbound // types at parse time, not at semantic analysis time. That means that // we end up giving confusing "unexpected comma" or "expected type" // errors when it would be more informative to the user to simply // tell them that an unbound type is not legal in this position. // // This also means that we can get semantic analysis of the open // type in the IDE even in what would have been a syntax error case // in the native compiler. // // We need a heuristic to deal with the situation where both kinds of errors // are potentially in play: what if someone says "typeof(Bogus<>.Blah<int>)"? // There are two errors there: first, that Bogus is not found, not a type, // or not of the appropriate arity, and second, that it is illegal to make // a partially unbound type. // // The heuristic we will use is that the former kind of error takes priority // over the latter; if the meaning of "Bogus<>" cannot be successfully // determined then there is no point telling the user that in addition, // it is syntactically wrong. Moreover, at this point we do not know what they // mean by the remainder ".Blah<int>" of the expression and so it seems wrong to // deduce more errors from it. var plainName = node.Identifier.ValueText; SeparatedSyntaxList<TypeSyntax> typeArguments = node.TypeArgumentList.Arguments; bool isUnboundTypeExpr = node.IsUnboundGenericName; LookupOptions options = GetSimpleNameLookupOptions(node, isVerbatimIdentifier: false); NamedTypeSymbol unconstructedType = LookupGenericTypeName( diagnostics, basesBeingResolved, qualifierOpt, node, plainName, node.Arity, options); NamedTypeSymbol resultType; if (isUnboundTypeExpr) { if (!IsUnboundTypeAllowed(node)) { // If we already have an error type then skip reporting that the unbound type is illegal. if (!unconstructedType.IsErrorType()) { // error CS7003: Unexpected use of an unbound generic name diagnostics.Add(ErrorCode.ERR_UnexpectedUnboundGenericName, node.Location); } resultType = unconstructedType.Construct( UnboundArgumentErrorTypeSymbol.CreateTypeArguments( unconstructedType.TypeParameters, node.Arity, errorInfo: null), unbound: false); } else { resultType = unconstructedType.AsUnboundGenericType(); } } else if ((Flags & BinderFlags.SuppressTypeArgumentBinding) != 0) { resultType = unconstructedType.Construct(PlaceholderTypeArgumentSymbol.CreateTypeArguments(unconstructedType.TypeParameters)); } else { // It's not an unbound type expression, so we must have type arguments, and we have a // generic type of the correct arity in hand (possibly an error type). Bind the type // arguments and construct the final result. resultType = ConstructNamedType( unconstructedType, node, typeArguments, BindTypeArguments(typeArguments, diagnostics, basesBeingResolved), basesBeingResolved, diagnostics); } if (options.IsAttributeTypeLookup()) { // Generic type cannot be an attribute type. // Parser error has already been reported, just wrap the result type with error type symbol. Debug.Assert(unconstructedType.IsErrorType()); Debug.Assert(resultType.IsErrorType()); resultType = new ExtendedErrorTypeSymbol(GetContainingNamespaceOrType(resultType), resultType, LookupResultKind.NotAnAttributeType, errorInfo: null); } return TypeWithAnnotations.Create(AreNullableAnnotationsEnabled(node.TypeArgumentList.GreaterThanToken), resultType); } private NamedTypeSymbol LookupGenericTypeName( BindingDiagnosticBag diagnostics, ConsList<TypeSymbol> basesBeingResolved, NamespaceOrTypeSymbol qualifierOpt, GenericNameSyntax node, string plainName, int arity, LookupOptions options) { var errorResult = CreateErrorIfLookupOnTypeParameter(node.Parent, qualifierOpt, plainName, arity, diagnostics); if ((object)errorResult != null) { return errorResult; } var lookupResult = LookupResult.GetInstance(); CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); this.LookupSymbolsSimpleName(lookupResult, qualifierOpt, plainName, arity, basesBeingResolved, options, diagnose: true, useSiteInfo: ref useSiteInfo); diagnostics.Add(node, useSiteInfo); bool wasError; Symbol lookupResultSymbol = ResultSymbol(lookupResult, plainName, arity, node, diagnostics, (basesBeingResolved != null), out wasError, qualifierOpt, options); // As we said in the method above, there are three cases here: // // * Lookup could fail to find anything at all. // * Lookup could find a type of the wrong arity // * Lookup could find something but it is not a type. // // In the first two cases we will be given back an error type symbol of the appropriate arity. // In the third case we will be given back the symbol -- say, a local variable symbol. // // In all three cases the appropriate error has already been reported. (That the // type was not found, that the generic type found does not have that arity, that // the non-generic type found cannot be used with a type argument list, or that // the symbol found is not something that takes type arguments. ) // The first thing to do is to make sure that we have some sort of generic type in hand. // (Note that an error type symbol is always a generic type.) NamedTypeSymbol type = lookupResultSymbol as NamedTypeSymbol; if ((object)type == null) { // We did a lookup with a generic arity, filtered to types and namespaces. If // we got back something other than a type, there had better be an error info // for us. Debug.Assert(lookupResult.Error != null); type = new ExtendedErrorTypeSymbol( GetContainingNamespaceOrType(lookupResultSymbol), ImmutableArray.Create<Symbol>(lookupResultSymbol), lookupResult.Kind, lookupResult.Error, arity); } lookupResult.Free(); return type; } private ExtendedErrorTypeSymbol CreateErrorIfLookupOnTypeParameter( CSharpSyntaxNode node, NamespaceOrTypeSymbol qualifierOpt, string name, int arity, BindingDiagnosticBag diagnostics) { if (((object)qualifierOpt != null) && (qualifierOpt.Kind == SymbolKind.TypeParameter)) { var diagnosticInfo = new CSDiagnosticInfo(ErrorCode.ERR_LookupInTypeVariable, qualifierOpt); diagnostics.Add(diagnosticInfo, node.Location); return new ExtendedErrorTypeSymbol(this.Compilation, name, arity, diagnosticInfo, unreported: false); } return null; } private ImmutableArray<TypeWithAnnotations> BindTypeArguments(SeparatedSyntaxList<TypeSyntax> typeArguments, BindingDiagnosticBag diagnostics, ConsList<TypeSymbol> basesBeingResolved = null) { Debug.Assert(typeArguments.Count > 0); var args = ArrayBuilder<TypeWithAnnotations>.GetInstance(); foreach (var argSyntax in typeArguments) { args.Add(BindTypeArgument(argSyntax, diagnostics, basesBeingResolved)); } return args.ToImmutableAndFree(); } private TypeWithAnnotations BindTypeArgument(TypeSyntax typeArgument, BindingDiagnosticBag diagnostics, ConsList<TypeSymbol> basesBeingResolved = null) { // Unsafe types can never be type arguments, but there's a special error code for that. var binder = this.WithAdditionalFlags(BinderFlags.SuppressUnsafeDiagnostics); var arg = typeArgument.Kind() == SyntaxKind.OmittedTypeArgument ? TypeWithAnnotations.Create(UnboundArgumentErrorTypeSymbol.Instance) : binder.BindType(typeArgument, diagnostics, basesBeingResolved); return arg; } /// <remarks> /// Keep check and error in sync with ConstructBoundMethodGroupAndReportOmittedTypeArguments. /// </remarks> private NamedTypeSymbol ConstructNamedTypeUnlessTypeArgumentOmitted(SyntaxNode typeSyntax, NamedTypeSymbol type, SeparatedSyntaxList<TypeSyntax> typeArgumentsSyntax, ImmutableArray<TypeWithAnnotations> typeArguments, BindingDiagnosticBag diagnostics) { if (typeArgumentsSyntax.Any(SyntaxKind.OmittedTypeArgument)) { // Note: lookup won't have reported this, since the arity was correct. // CONSIDER: the text of this error message makes sense, but we might want to add a separate code. Error(diagnostics, ErrorCode.ERR_BadArity, typeSyntax, type, MessageID.IDS_SK_TYPE.Localize(), typeArgumentsSyntax.Count); // If the syntax looks like an unbound generic type, then they probably wanted the definition. // Give an error indicating that the syntax is incorrect and then use the definition. // CONSIDER: we could construct an unbound generic type symbol, but that would probably be confusing // outside a typeof. return type; } else { // we pass an empty basesBeingResolved here because this invocation is not on any possible path of // infinite recursion in binding base clauses. return ConstructNamedType(type, typeSyntax, typeArgumentsSyntax, typeArguments, basesBeingResolved: null, diagnostics: diagnostics); } } /// <remarks> /// Keep check and error in sync with ConstructNamedTypeUnlessTypeArgumentOmitted. /// </remarks> private static BoundMethodOrPropertyGroup ConstructBoundMemberGroupAndReportOmittedTypeArguments( SyntaxNode syntax, SeparatedSyntaxList<TypeSyntax> typeArgumentsSyntax, ImmutableArray<TypeWithAnnotations> typeArguments, BoundExpression receiver, string plainName, ArrayBuilder<Symbol> members, LookupResult lookupResult, BoundMethodGroupFlags methodGroupFlags, bool hasErrors, BindingDiagnosticBag diagnostics) { if (!hasErrors && lookupResult.IsMultiViable && typeArgumentsSyntax.Any(SyntaxKind.OmittedTypeArgument)) { // Note: lookup won't have reported this, since the arity was correct. // CONSIDER: the text of this error message makes sense, but we might want to add a separate code. Error(diagnostics, ErrorCode.ERR_BadArity, syntax, plainName, MessageID.IDS_MethodGroup.Localize(), typeArgumentsSyntax.Count); hasErrors = true; } Debug.Assert(members.Count > 0); switch (members[0].Kind) { case SymbolKind.Method: return new BoundMethodGroup( syntax, typeArguments, receiver, plainName, members.SelectAsArray(s_toMethodSymbolFunc), lookupResult, methodGroupFlags, hasErrors); case SymbolKind.Property: return new BoundPropertyGroup( syntax, members.SelectAsArray(s_toPropertySymbolFunc), receiver, lookupResult.Kind, hasErrors); default: throw ExceptionUtilities.UnexpectedValue(members[0].Kind); } } private static readonly Func<Symbol, MethodSymbol> s_toMethodSymbolFunc = s => (MethodSymbol)s; private static readonly Func<Symbol, PropertySymbol> s_toPropertySymbolFunc = s => (PropertySymbol)s; private NamedTypeSymbol ConstructNamedType( NamedTypeSymbol type, SyntaxNode typeSyntax, SeparatedSyntaxList<TypeSyntax> typeArgumentsSyntax, ImmutableArray<TypeWithAnnotations> typeArguments, ConsList<TypeSymbol> basesBeingResolved, BindingDiagnosticBag diagnostics) { Debug.Assert(!typeArguments.IsEmpty); type = type.Construct(typeArguments); if (ShouldCheckConstraints && ConstraintsHelper.RequiresChecking(type)) { bool includeNullability = Compilation.IsFeatureEnabled(MessageID.IDS_FeatureNullableReferenceTypes); type.CheckConstraintsForNamedType(new ConstraintsHelper.CheckConstraintsArgs(this.Compilation, this.Conversions, includeNullability, typeSyntax.Location, diagnostics), typeSyntax, typeArgumentsSyntax, basesBeingResolved); } return type; } /// <summary> /// Check generic type constraints unless the type is used as part of a type or method /// declaration. In those cases, constraints checking is handled by the caller. /// </summary> private bool ShouldCheckConstraints { get { return !this.Flags.Includes(BinderFlags.SuppressConstraintChecks); } } private NamespaceOrTypeOrAliasSymbolWithAnnotations BindQualifiedName( ExpressionSyntax leftName, SimpleNameSyntax rightName, BindingDiagnosticBag diagnostics, ConsList<TypeSymbol> basesBeingResolved, bool suppressUseSiteDiagnostics) { var left = BindNamespaceOrTypeSymbol(leftName, diagnostics, basesBeingResolved, suppressUseSiteDiagnostics: false).NamespaceOrTypeSymbol; ReportDiagnosticsIfObsolete(diagnostics, left, leftName, hasBaseReceiver: false); bool isLeftUnboundGenericType = left.Kind == SymbolKind.NamedType && ((NamedTypeSymbol)left).IsUnboundGenericType; if (isLeftUnboundGenericType) { // If left name bound to an unbound generic type, // we want to perform right name lookup within // left's original named type definition. left = ((NamedTypeSymbol)left).OriginalDefinition; } // since the name is qualified, it cannot result in a using alias symbol, only a type or namespace var right = this.BindSimpleNamespaceOrTypeOrAliasSymbol(rightName, diagnostics, basesBeingResolved, suppressUseSiteDiagnostics, left); // If left name bound to an unbound generic type // and right name bound to a generic type, we must // convert right to an unbound generic type. if (isLeftUnboundGenericType) { return convertToUnboundGenericType(); } return right; // This part is moved into a local function to reduce the method's stack frame size NamespaceOrTypeOrAliasSymbolWithAnnotations convertToUnboundGenericType() { var namedTypeRight = right.Symbol as NamedTypeSymbol; if ((object)namedTypeRight != null && namedTypeRight.IsGenericType) { TypeWithAnnotations type = right.TypeWithAnnotations; return type.WithTypeAndModifiers(namedTypeRight.AsUnboundGenericType(), type.CustomModifiers); } return right; } } internal NamedTypeSymbol GetSpecialType(SpecialType typeId, BindingDiagnosticBag diagnostics, SyntaxNode node) { return GetSpecialType(this.Compilation, typeId, node, diagnostics); } internal static NamedTypeSymbol GetSpecialType(CSharpCompilation compilation, SpecialType typeId, SyntaxNode node, BindingDiagnosticBag diagnostics) { NamedTypeSymbol typeSymbol = compilation.GetSpecialType(typeId); Debug.Assert((object)typeSymbol != null, "Expect an error type if special type isn't found"); ReportUseSite(typeSymbol, diagnostics, node); return typeSymbol; } internal static NamedTypeSymbol GetSpecialType(CSharpCompilation compilation, SpecialType typeId, Location location, BindingDiagnosticBag diagnostics) { NamedTypeSymbol typeSymbol = compilation.GetSpecialType(typeId); Debug.Assert((object)typeSymbol != null, "Expect an error type if special type isn't found"); ReportUseSite(typeSymbol, diagnostics, location); return typeSymbol; } /// <summary> /// This is a layer on top of the Compilation version that generates a diagnostic if the special /// member isn't found. /// </summary> internal Symbol GetSpecialTypeMember(SpecialMember member, BindingDiagnosticBag diagnostics, SyntaxNode syntax) { Symbol memberSymbol; return TryGetSpecialTypeMember(this.Compilation, member, syntax, diagnostics, out memberSymbol) ? memberSymbol : null; } internal static bool TryGetSpecialTypeMember<TSymbol>(CSharpCompilation compilation, SpecialMember specialMember, SyntaxNode syntax, BindingDiagnosticBag diagnostics, out TSymbol symbol) where TSymbol : Symbol { symbol = (TSymbol)compilation.GetSpecialTypeMember(specialMember); if ((object)symbol == null) { MemberDescriptor descriptor = SpecialMembers.GetDescriptor(specialMember); diagnostics.Add(ErrorCode.ERR_MissingPredefinedMember, syntax.Location, descriptor.DeclaringTypeMetadataName, descriptor.Name); return false; } var useSiteInfo = GetUseSiteInfoForWellKnownMemberOrContainingType(symbol); if (useSiteInfo.DiagnosticInfo != null) { diagnostics.ReportUseSiteDiagnostic(useSiteInfo.DiagnosticInfo, new SourceLocation(syntax)); } // No need to track assemblies used by special members or types. They are coming from core library, which // doesn't have any dependencies. return true; } private static UseSiteInfo<AssemblySymbol> GetUseSiteInfoForWellKnownMemberOrContainingType(Symbol symbol) { Debug.Assert(symbol.IsDefinition); UseSiteInfo<AssemblySymbol> info = symbol.GetUseSiteInfo(); symbol.MergeUseSiteInfo(ref info, symbol.ContainingType.GetUseSiteInfo()); return info; } /// <summary> /// Reports use-site diagnostics and dependencies for the specified symbol. /// </summary> /// <returns> /// True if there was an error among the reported diagnostics /// </returns> internal static bool ReportUseSite(Symbol symbol, BindingDiagnosticBag diagnostics, SyntaxNode node) { return diagnostics.ReportUseSite(symbol, node); } internal static bool ReportUseSite(Symbol symbol, BindingDiagnosticBag diagnostics, SyntaxToken token) { return diagnostics.ReportUseSite(symbol, token); } /// <summary> /// Reports use-site diagnostics and dependencies for the specified symbol. /// </summary> /// <returns> /// True if there was an error among the reported diagnostics /// </returns> internal static bool ReportUseSite(Symbol symbol, BindingDiagnosticBag diagnostics, Location location) { return diagnostics.ReportUseSite(symbol, location); } /// <summary> /// This is a layer on top of the Compilation version that generates a diagnostic if the well-known /// type isn't found. /// </summary> internal NamedTypeSymbol GetWellKnownType(WellKnownType type, BindingDiagnosticBag diagnostics, SyntaxNode node) { return GetWellKnownType(type, diagnostics, node.Location); } /// <summary> /// This is a layer on top of the Compilation version that generates a diagnostic if the well-known /// type isn't found. /// </summary> internal NamedTypeSymbol GetWellKnownType(WellKnownType type, BindingDiagnosticBag diagnostics, Location location) { return GetWellKnownType(this.Compilation, type, diagnostics, location); } /// <summary> /// This is a layer on top of the Compilation version that generates a diagnostic if the well-known /// type isn't found. /// </summary> internal static NamedTypeSymbol GetWellKnownType(CSharpCompilation compilation, WellKnownType type, BindingDiagnosticBag diagnostics, SyntaxNode node) { return GetWellKnownType(compilation, type, diagnostics, node.Location); } internal static NamedTypeSymbol GetWellKnownType(CSharpCompilation compilation, WellKnownType type, BindingDiagnosticBag diagnostics, Location location) { NamedTypeSymbol typeSymbol = compilation.GetWellKnownType(type); Debug.Assert((object)typeSymbol != null, "Expect an error type if well-known type isn't found"); ReportUseSite(typeSymbol, diagnostics, location); return typeSymbol; } /// <summary> /// This is a layer on top of the Compilation version that generates a diagnostic if the well-known /// type isn't found. /// </summary> internal NamedTypeSymbol GetWellKnownType(WellKnownType type, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { NamedTypeSymbol typeSymbol = this.Compilation.GetWellKnownType(type); Debug.Assert((object)typeSymbol != null, "Expect an error type if well-known type isn't found"); typeSymbol.AddUseSiteInfo(ref useSiteInfo); return typeSymbol; } internal Symbol GetWellKnownTypeMember(WellKnownMember member, BindingDiagnosticBag diagnostics, Location location = null, SyntaxNode syntax = null, bool isOptional = false) { return GetWellKnownTypeMember(Compilation, member, diagnostics, location, syntax, isOptional); } /// <summary> /// Retrieves a well-known type member and reports diagnostics. /// </summary> /// <returns>Null if the symbol is missing.</returns> internal static Symbol GetWellKnownTypeMember(CSharpCompilation compilation, WellKnownMember member, BindingDiagnosticBag diagnostics, Location location = null, SyntaxNode syntax = null, bool isOptional = false) { Debug.Assert((syntax != null) ^ (location != null)); UseSiteInfo<AssemblySymbol> useSiteInfo; Symbol memberSymbol = GetWellKnownTypeMember(compilation, member, out useSiteInfo, isOptional); diagnostics.Add(useSiteInfo, location ?? syntax.Location); return memberSymbol; } internal static Symbol GetWellKnownTypeMember(CSharpCompilation compilation, WellKnownMember member, out UseSiteInfo<AssemblySymbol> useSiteInfo, bool isOptional = false) { Symbol memberSymbol = compilation.GetWellKnownTypeMember(member); if ((object)memberSymbol != null) { useSiteInfo = GetUseSiteInfoForWellKnownMemberOrContainingType(memberSymbol); if (useSiteInfo.DiagnosticInfo != null) { // Dev11 reports use-site diagnostics even for optional symbols that are found. // We decided to silently ignore bad optional symbols. // Report errors only for non-optional members: if (isOptional) { var severity = useSiteInfo.DiagnosticInfo.Severity; // if the member is optional and bad for whatever reason ignore it: if (severity == DiagnosticSeverity.Error) { useSiteInfo = default; return null; } // ignore warnings: useSiteInfo = new UseSiteInfo<AssemblySymbol>(diagnosticInfo: null, useSiteInfo.PrimaryDependency, useSiteInfo.SecondaryDependencies); } } } else if (!isOptional) { // member is missing MemberDescriptor memberDescriptor = WellKnownMembers.GetDescriptor(member); useSiteInfo = new UseSiteInfo<AssemblySymbol>(new CSDiagnosticInfo(ErrorCode.ERR_MissingPredefinedMember, memberDescriptor.DeclaringTypeMetadataName, memberDescriptor.Name)); } else { useSiteInfo = default; } return memberSymbol; } private class ConsistentSymbolOrder : IComparer<Symbol> { public static readonly ConsistentSymbolOrder Instance = new ConsistentSymbolOrder(); public int Compare(Symbol fst, Symbol snd) { if (snd == fst) return 0; if ((object)fst == null) return -1; if ((object)snd == null) return 1; if (snd.Name != fst.Name) return string.CompareOrdinal(fst.Name, snd.Name); if (snd.Kind != fst.Kind) return (int)fst.Kind - (int)snd.Kind; int aLocationsCount = !snd.Locations.IsDefault ? snd.Locations.Length : 0; int bLocationsCount = fst.Locations.Length; if (aLocationsCount != bLocationsCount) return aLocationsCount - bLocationsCount; if (aLocationsCount == 0 && bLocationsCount == 0) return Compare(fst.ContainingSymbol, snd.ContainingSymbol); Location la = snd.Locations[0]; Location lb = fst.Locations[0]; if (la.IsInSource != lb.IsInSource) return la.IsInSource ? 1 : -1; int containerResult = Compare(fst.ContainingSymbol, snd.ContainingSymbol); if (!la.IsInSource) return containerResult; if (containerResult == 0 && la.SourceTree == lb.SourceTree) return lb.SourceSpan.Start - la.SourceSpan.Start; return containerResult; } } // return the type or namespace symbol in a lookup result, or report an error. internal Symbol ResultSymbol( LookupResult result, string simpleName, int arity, SyntaxNode where, BindingDiagnosticBag diagnostics, bool suppressUseSiteDiagnostics, out bool wasError, NamespaceOrTypeSymbol qualifierOpt, LookupOptions options = default(LookupOptions)) { Symbol symbol = resultSymbol(result, simpleName, arity, where, diagnostics, suppressUseSiteDiagnostics, out wasError, qualifierOpt, options); if (symbol.Kind == SymbolKind.NamedType) { CheckReceiverAndRuntimeSupportForSymbolAccess(where, receiverOpt: null, symbol, diagnostics); if (suppressUseSiteDiagnostics && diagnostics.DependenciesBag is object) { AssemblySymbol container = symbol.ContainingAssembly; if (container is object && container != Compilation.Assembly && container != Compilation.Assembly.CorLibrary) { diagnostics.AddDependency(container); } } } return symbol; Symbol resultSymbol( LookupResult result, string simpleName, int arity, SyntaxNode where, BindingDiagnosticBag diagnostics, bool suppressUseSiteDiagnostics, out bool wasError, NamespaceOrTypeSymbol qualifierOpt, LookupOptions options) { Debug.Assert(where != null); Debug.Assert(diagnostics != null); var symbols = result.Symbols; wasError = false; if (result.IsMultiViable) { if (symbols.Count > 1) { // gracefully handle symbols.Count > 2 symbols.Sort(ConsistentSymbolOrder.Instance); var originalSymbols = symbols.ToImmutable(); for (int i = 0; i < symbols.Count; i++) { symbols[i] = UnwrapAlias(symbols[i], diagnostics, where); } BestSymbolInfo secondBest; BestSymbolInfo best = GetBestSymbolInfo(symbols, out secondBest); Debug.Assert(!best.IsNone); Debug.Assert(!secondBest.IsNone); if (best.IsFromCompilation && !secondBest.IsFromCompilation) { var srcSymbol = symbols[best.Index]; var mdSymbol = symbols[secondBest.Index]; object arg0; if (best.IsFromSourceModule) { arg0 = srcSymbol.Locations.First().SourceTree.FilePath; } else { Debug.Assert(best.IsFromAddedModule); arg0 = srcSymbol.ContainingModule; } //if names match, arities match, and containing symbols match (recursively), ... if (NameAndArityMatchRecursively(srcSymbol, mdSymbol)) { if (srcSymbol.Kind == SymbolKind.Namespace && mdSymbol.Kind == SymbolKind.NamedType) { // ErrorCode.WRN_SameFullNameThisNsAgg: The namespace '{1}' in '{0}' conflicts with the imported type '{3}' in '{2}'. Using the namespace defined in '{0}'. diagnostics.Add(ErrorCode.WRN_SameFullNameThisNsAgg, where.Location, originalSymbols, arg0, srcSymbol, mdSymbol.ContainingAssembly, mdSymbol); return originalSymbols[best.Index]; } else if (srcSymbol.Kind == SymbolKind.NamedType && mdSymbol.Kind == SymbolKind.Namespace) { // ErrorCode.WRN_SameFullNameThisAggNs: The type '{1}' in '{0}' conflicts with the imported namespace '{3}' in '{2}'. Using the type defined in '{0}'. diagnostics.Add(ErrorCode.WRN_SameFullNameThisAggNs, where.Location, originalSymbols, arg0, srcSymbol, GetContainingAssembly(mdSymbol), mdSymbol); return originalSymbols[best.Index]; } else if (srcSymbol.Kind == SymbolKind.NamedType && mdSymbol.Kind == SymbolKind.NamedType) { // WRN_SameFullNameThisAggAgg: The type '{1}' in '{0}' conflicts with the imported type '{3}' in '{2}'. Using the type defined in '{0}'. diagnostics.Add(ErrorCode.WRN_SameFullNameThisAggAgg, where.Location, originalSymbols, arg0, srcSymbol, mdSymbol.ContainingAssembly, mdSymbol); return originalSymbols[best.Index]; } else { // namespace would be merged with the source namespace: Debug.Assert(!(srcSymbol.Kind == SymbolKind.Namespace && mdSymbol.Kind == SymbolKind.Namespace)); } } } var first = symbols[best.Index]; var second = symbols[secondBest.Index]; Debug.Assert(!Symbol.Equals(originalSymbols[best.Index], originalSymbols[secondBest.Index], TypeCompareKind.ConsiderEverything) || options.IsAttributeTypeLookup(), "This kind of ambiguity is only possible for attributes."); Debug.Assert(!Symbol.Equals(first, second, TypeCompareKind.ConsiderEverything) || !Symbol.Equals(originalSymbols[best.Index], originalSymbols[secondBest.Index], TypeCompareKind.ConsiderEverything), "Why does the LookupResult contain the same symbol twice?"); CSDiagnosticInfo info; bool reportError; //if names match, arities match, and containing symbols match (recursively), ... if (first != second && NameAndArityMatchRecursively(first, second)) { // suppress reporting the error if we found multiple symbols from source module // since an error has already been reported from the declaration reportError = !(best.IsFromSourceModule && secondBest.IsFromSourceModule); if (first.Kind == SymbolKind.NamedType && second.Kind == SymbolKind.NamedType) { if (first.OriginalDefinition == second.OriginalDefinition) { // We imported different generic instantiations of the same generic type // and have an ambiguous reference to a type nested in it reportError = true; // '{0}' is an ambiguous reference between '{1}' and '{2}' info = new CSDiagnosticInfo(ErrorCode.ERR_AmbigContext, originalSymbols, new object[] { (where as NameSyntax)?.ErrorDisplayName() ?? simpleName, new FormattedSymbol(first, SymbolDisplayFormat.CSharpErrorMessageFormat), new FormattedSymbol(second, SymbolDisplayFormat.CSharpErrorMessageFormat) }); } else { Debug.Assert(!best.IsFromCorLibrary); // ErrorCode.ERR_SameFullNameAggAgg: The type '{1}' exists in both '{0}' and '{2}' info = new CSDiagnosticInfo(ErrorCode.ERR_SameFullNameAggAgg, originalSymbols, new object[] { first.ContainingAssembly, first, second.ContainingAssembly }); // Do not report this error if the first is declared in source and the second is declared in added module, // we already reported declaration error about this name collision. // Do not report this error if both are declared in added modules, // we will report assembly level declaration error about this name collision. if (secondBest.IsFromAddedModule) { Debug.Assert(best.IsFromCompilation); reportError = false; } else if (this.Flags.Includes(BinderFlags.IgnoreCorLibraryDuplicatedTypes) && secondBest.IsFromCorLibrary) { // Ignore duplicate types from the cor library if necessary. // (Specifically the framework assemblies loaded at runtime in // the EE may contain types also available from mscorlib.dll.) return first; } } } else if (first.Kind == SymbolKind.Namespace && second.Kind == SymbolKind.NamedType) { // ErrorCode.ERR_SameFullNameNsAgg: The namespace '{1}' in '{0}' conflicts with the type '{3}' in '{2}' info = new CSDiagnosticInfo(ErrorCode.ERR_SameFullNameNsAgg, originalSymbols, new object[] { GetContainingAssembly(first), first, second.ContainingAssembly, second }); // Do not report this error if namespace is declared in source and the type is declared in added module, // we already reported declaration error about this name collision. if (best.IsFromSourceModule && secondBest.IsFromAddedModule) { reportError = false; } } else if (first.Kind == SymbolKind.NamedType && second.Kind == SymbolKind.Namespace) { if (!secondBest.IsFromCompilation || secondBest.IsFromSourceModule) { // ErrorCode.ERR_SameFullNameNsAgg: The namespace '{1}' in '{0}' conflicts with the type '{3}' in '{2}' info = new CSDiagnosticInfo(ErrorCode.ERR_SameFullNameNsAgg, originalSymbols, new object[] { GetContainingAssembly(second), second, first.ContainingAssembly, first }); } else { Debug.Assert(secondBest.IsFromAddedModule); // ErrorCode.ERR_SameFullNameThisAggThisNs: The type '{1}' in '{0}' conflicts with the namespace '{3}' in '{2}' object arg0; if (best.IsFromSourceModule) { arg0 = first.Locations.First().SourceTree.FilePath; } else { Debug.Assert(best.IsFromAddedModule); arg0 = first.ContainingModule; } ModuleSymbol arg2 = second.ContainingModule; // Merged namespaces that span multiple modules don't have a containing module, // so just use module with the smallest ordinal from the containing assembly. if ((object)arg2 == null) { foreach (NamespaceSymbol ns in ((NamespaceSymbol)second).ConstituentNamespaces) { if (ns.ContainingAssembly == Compilation.Assembly) { ModuleSymbol module = ns.ContainingModule; if ((object)arg2 == null || arg2.Ordinal > module.Ordinal) { arg2 = module; } } } } Debug.Assert(arg2.ContainingAssembly == Compilation.Assembly); info = new CSDiagnosticInfo(ErrorCode.ERR_SameFullNameThisAggThisNs, originalSymbols, new object[] { arg0, first, arg2, second }); } } else if (first.Kind == SymbolKind.RangeVariable && second.Kind == SymbolKind.RangeVariable) { // We will already have reported a conflicting range variable declaration. info = new CSDiagnosticInfo(ErrorCode.ERR_AmbigMember, originalSymbols, new object[] { first, second }); } else { // TODO: this is not an appropriate error message here, but used as a fallback until the // appropriate diagnostics are implemented. // '{0}' is an ambiguous reference between '{1}' and '{2}' //info = diagnostics.Add(ErrorCode.ERR_AmbigContext, location, readOnlySymbols, // whereText, // first, // second); // CS0229: Ambiguity between '{0}' and '{1}' info = new CSDiagnosticInfo(ErrorCode.ERR_AmbigMember, originalSymbols, new object[] { first, second }); reportError = true; } } else { Debug.Assert(originalSymbols[best.Index].Name != originalSymbols[secondBest.Index].Name || !Symbol.Equals(originalSymbols[best.Index], originalSymbols[secondBest.Index], TypeCompareKind.ConsiderEverything), "Why was the lookup result viable if it contained non-equal symbols with the same name?"); reportError = true; if (first is NamespaceOrTypeSymbol && second is NamespaceOrTypeSymbol) { if (options.IsAttributeTypeLookup() && first.Kind == SymbolKind.NamedType && second.Kind == SymbolKind.NamedType && originalSymbols[best.Index].Name != originalSymbols[secondBest.Index].Name && // Use alias names, if available. Compilation.IsAttributeType((NamedTypeSymbol)first) && Compilation.IsAttributeType((NamedTypeSymbol)second)) { // SPEC: If an attribute class is found both with and without Attribute suffix, an ambiguity // SPEC: is present, and a compile-time error results. info = new CSDiagnosticInfo(ErrorCode.ERR_AmbiguousAttribute, originalSymbols, new object[] { (where as NameSyntax)?.ErrorDisplayName() ?? simpleName, first, second }); } else { // '{0}' is an ambiguous reference between '{1}' and '{2}' info = new CSDiagnosticInfo(ErrorCode.ERR_AmbigContext, originalSymbols, new object[] { (where as NameSyntax)?.ErrorDisplayName() ?? simpleName, new FormattedSymbol(first, SymbolDisplayFormat.CSharpErrorMessageFormat), new FormattedSymbol(second, SymbolDisplayFormat.CSharpErrorMessageFormat) }); } } else { // CS0229: Ambiguity between '{0}' and '{1}' info = new CSDiagnosticInfo(ErrorCode.ERR_AmbigMember, originalSymbols, new object[] { first, second }); } } wasError = true; if (reportError) { diagnostics.Add(info, where.Location); } return new ExtendedErrorTypeSymbol( GetContainingNamespaceOrType(originalSymbols[0]), originalSymbols, LookupResultKind.Ambiguous, info, arity); } else { // Single viable result. var singleResult = symbols[0]; // Cannot reference System.Void directly. var singleType = singleResult as TypeSymbol; if ((object)singleType != null && singleType.PrimitiveTypeCode == Cci.PrimitiveTypeCode.Void && simpleName == "Void") { wasError = true; var errorInfo = new CSDiagnosticInfo(ErrorCode.ERR_SystemVoid); diagnostics.Add(errorInfo, where.Location); singleResult = new ExtendedErrorTypeSymbol(GetContainingNamespaceOrType(singleResult), singleResult, LookupResultKind.NotReferencable, errorInfo); // UNDONE: Review resultkind. } // Check for bad symbol. else { if (singleResult.Kind == SymbolKind.NamedType && ((SourceModuleSymbol)this.Compilation.SourceModule).AnyReferencedAssembliesAreLinked) { // Complain about unembeddable types from linked assemblies. if (diagnostics.DiagnosticBag is object) { Emit.NoPia.EmbeddedTypesManager.IsValidEmbeddableType((NamedTypeSymbol)singleResult, where, diagnostics.DiagnosticBag); } } if (!suppressUseSiteDiagnostics) { wasError = ReportUseSite(singleResult, diagnostics, where); } else if (singleResult.Kind == SymbolKind.ErrorType) { // We want to report ERR_CircularBase error on the spot to make sure // that the right location is used for it. var errorType = (ErrorTypeSymbol)singleResult; if (errorType.Unreported) { DiagnosticInfo errorInfo = errorType.ErrorInfo; if (errorInfo != null && errorInfo.Code == (int)ErrorCode.ERR_CircularBase) { wasError = true; diagnostics.Add(errorInfo, where.Location); singleResult = new ExtendedErrorTypeSymbol(GetContainingNamespaceOrType(errorType), errorType.Name, errorType.Arity, errorInfo, unreported: false); } } } } return singleResult; } } // Below here is the error case; no viable symbols found (but maybe one or more non-viable.) wasError = true; if (result.Kind == LookupResultKind.Empty) { string aliasOpt = null; SyntaxNode node = where; while (node is ExpressionSyntax) { if (node.Kind() == SyntaxKind.AliasQualifiedName) { aliasOpt = ((AliasQualifiedNameSyntax)node).Alias.Identifier.ValueText; break; } node = node.Parent; } CSDiagnosticInfo info = NotFound(where, simpleName, arity, (where as NameSyntax)?.ErrorDisplayName() ?? simpleName, diagnostics, aliasOpt, qualifierOpt, options); return new ExtendedErrorTypeSymbol(qualifierOpt ?? Compilation.Assembly.GlobalNamespace, simpleName, arity, info); } Debug.Assert(symbols.Count > 0); // Report any errors we encountered with the symbol we looked up. if (!suppressUseSiteDiagnostics) { for (int i = 0; i < symbols.Count; i++) { ReportUseSite(symbols[i], diagnostics, where); } } // result.Error might be null if we have already generated parser errors, // e.g. when generic name is used for attribute name. if (result.Error != null && ((object)qualifierOpt == null || qualifierOpt.Kind != SymbolKind.ErrorType)) // Suppress cascading. { diagnostics.Add(new CSDiagnostic(result.Error, where.Location)); } if ((symbols.Count > 1) || (symbols[0] is NamespaceOrTypeSymbol || symbols[0] is AliasSymbol) || result.Kind == LookupResultKind.NotATypeOrNamespace || result.Kind == LookupResultKind.NotAnAttributeType) { // Bad type or namespace (or things expected as types/namespaces) are packaged up as error types, preserving the symbols and the result kind. // We do this if there are multiple symbols too, because just returning one would be losing important information, and they might // be of different kinds. return new ExtendedErrorTypeSymbol(GetContainingNamespaceOrType(symbols[0]), symbols.ToImmutable(), result.Kind, result.Error, arity); } else { // It's a single non-type-or-namespace; error was already reported, so just return it. return symbols[0]; } } } private static AssemblySymbol GetContainingAssembly(Symbol symbol) { // Merged namespaces that span multiple assemblies don't have a containing assembly, // so just use the containing assembly of the first constituent. return symbol.ContainingAssembly ?? ((NamespaceSymbol)symbol).ConstituentNamespaces.First().ContainingAssembly; } [Flags] private enum BestSymbolLocation { None, FromSourceModule, FromAddedModule, FromReferencedAssembly, FromCorLibrary, } [DebuggerDisplay("Location = {_location}, Index = {_index}")] private struct BestSymbolInfo { private readonly BestSymbolLocation _location; private readonly int _index; /// <summary> /// Returns -1 if None. /// </summary> public int Index { get { return IsNone ? -1 : _index; } } public bool IsFromSourceModule { get { return _location == BestSymbolLocation.FromSourceModule; } } public bool IsFromAddedModule { get { return _location == BestSymbolLocation.FromAddedModule; } } public bool IsFromCompilation { get { return (_location == BestSymbolLocation.FromSourceModule) || (_location == BestSymbolLocation.FromAddedModule); } } public bool IsNone { get { return _location == BestSymbolLocation.None; } } public bool IsFromCorLibrary { get { return _location == BestSymbolLocation.FromCorLibrary; } } public BestSymbolInfo(BestSymbolLocation location, int index) { Debug.Assert(location != BestSymbolLocation.None); _location = location; _index = index; } /// <summary> /// Prefers symbols from source module, then from added modules, then from referenced assemblies. /// Returns true if values were swapped. /// </summary> public static bool Sort(ref BestSymbolInfo first, ref BestSymbolInfo second) { if (IsSecondLocationBetter(first._location, second._location)) { BestSymbolInfo temp = first; first = second; second = temp; return true; } return false; } /// <summary> /// Returns true if the second is a better location than the first. /// </summary> public static bool IsSecondLocationBetter(BestSymbolLocation firstLocation, BestSymbolLocation secondLocation) { Debug.Assert(secondLocation != 0); return (firstLocation == BestSymbolLocation.None) || (firstLocation > secondLocation); } } /// <summary> /// Prefer symbols from source module, then from added modules, then from referenced assemblies. /// </summary> private BestSymbolInfo GetBestSymbolInfo(ArrayBuilder<Symbol> symbols, out BestSymbolInfo secondBest) { BestSymbolInfo first = default(BestSymbolInfo); BestSymbolInfo second = default(BestSymbolInfo); var compilation = this.Compilation; for (int i = 0; i < symbols.Count; i++) { var symbol = symbols[i]; BestSymbolLocation location; if (symbol.Kind == SymbolKind.Namespace) { location = BestSymbolLocation.None; foreach (var ns in ((NamespaceSymbol)symbol).ConstituentNamespaces) { var current = GetLocation(compilation, ns); if (BestSymbolInfo.IsSecondLocationBetter(location, current)) { location = current; if (location == BestSymbolLocation.FromSourceModule) { break; } } } } else { location = GetLocation(compilation, symbol); } var third = new BestSymbolInfo(location, i); if (BestSymbolInfo.Sort(ref second, ref third)) { BestSymbolInfo.Sort(ref first, ref second); } } Debug.Assert(!first.IsNone); Debug.Assert(!second.IsNone); secondBest = second; return first; } private static BestSymbolLocation GetLocation(CSharpCompilation compilation, Symbol symbol) { var containingAssembly = symbol.ContainingAssembly; if (containingAssembly == compilation.SourceAssembly) { return (symbol.ContainingModule == compilation.SourceModule) ? BestSymbolLocation.FromSourceModule : BestSymbolLocation.FromAddedModule; } else { return (containingAssembly == containingAssembly.CorLibrary) ? BestSymbolLocation.FromCorLibrary : BestSymbolLocation.FromReferencedAssembly; } } /// <remarks> /// This is only intended to be called when the type isn't found (i.e. not when it is found but is inaccessible, has the wrong arity, etc). /// </remarks> private CSDiagnosticInfo NotFound(SyntaxNode where, string simpleName, int arity, string whereText, BindingDiagnosticBag diagnostics, string aliasOpt, NamespaceOrTypeSymbol qualifierOpt, LookupOptions options) { var location = where.Location; // Lookup totally ignores type forwarders, but we want the type lookup diagnostics // to distinguish between a type that can't be found and a type that is only present // as a type forwarder. We'll look for type forwarders in the containing and // referenced assemblies and report more specific diagnostics if they are found. AssemblySymbol forwardedToAssembly; // for attributes, suggest both, but not for verbatim name if (options.IsAttributeTypeLookup() && !options.IsVerbatimNameAttributeTypeLookup()) { // just recurse one level, so cheat and OR verbatim name option :) NotFound(where, simpleName, arity, whereText + "Attribute", diagnostics, aliasOpt, qualifierOpt, options | LookupOptions.VerbatimNameAttributeTypeOnly); } if ((object)qualifierOpt != null) { if (qualifierOpt.IsType) { var errorQualifier = qualifierOpt as ErrorTypeSymbol; if ((object)errorQualifier != null && errorQualifier.ErrorInfo != null) { return (CSDiagnosticInfo)errorQualifier.ErrorInfo; } return diagnostics.Add(ErrorCode.ERR_DottedTypeNameNotFoundInAgg, location, whereText, qualifierOpt); } else { Debug.Assert(qualifierOpt.IsNamespace); forwardedToAssembly = GetForwardedToAssembly(simpleName, arity, ref qualifierOpt, diagnostics, location); if (ReferenceEquals(qualifierOpt, Compilation.GlobalNamespace)) { Debug.Assert(aliasOpt == null || aliasOpt == SyntaxFacts.GetText(SyntaxKind.GlobalKeyword)); return (object)forwardedToAssembly == null ? diagnostics.Add(ErrorCode.ERR_GlobalSingleTypeNameNotFound, location, whereText, qualifierOpt) : diagnostics.Add(ErrorCode.ERR_GlobalSingleTypeNameNotFoundFwd, location, whereText, forwardedToAssembly); } else { object container = qualifierOpt; // If there was an alias (e.g. A::C) and the given qualifier is the global namespace of the alias, // then use the alias name in the error message, since it's more helpful than "<global namespace>". if (aliasOpt != null && qualifierOpt.IsNamespace && ((NamespaceSymbol)qualifierOpt).IsGlobalNamespace) { container = aliasOpt; } return (object)forwardedToAssembly == null ? diagnostics.Add(ErrorCode.ERR_DottedTypeNameNotFoundInNS, location, whereText, container) : diagnostics.Add(ErrorCode.ERR_DottedTypeNameNotFoundInNSFwd, location, whereText, container, forwardedToAssembly); } } } if (options == LookupOptions.NamespaceAliasesOnly) { return diagnostics.Add(ErrorCode.ERR_AliasNotFound, location, whereText); } if ((where as IdentifierNameSyntax)?.Identifier.Text == "var" && !options.IsAttributeTypeLookup()) { var code = (where.Parent is QueryClauseSyntax) ? ErrorCode.ERR_TypeVarNotFoundRangeVariable : ErrorCode.ERR_TypeVarNotFound; return diagnostics.Add(code, location); } forwardedToAssembly = GetForwardedToAssembly(simpleName, arity, ref qualifierOpt, diagnostics, location); if ((object)forwardedToAssembly != null) { return qualifierOpt == null ? diagnostics.Add(ErrorCode.ERR_SingleTypeNameNotFoundFwd, location, whereText, forwardedToAssembly) : diagnostics.Add(ErrorCode.ERR_DottedTypeNameNotFoundInNSFwd, location, whereText, qualifierOpt, forwardedToAssembly); } return diagnostics.Add(ErrorCode.ERR_SingleTypeNameNotFound, location, whereText); } protected virtual AssemblySymbol GetForwardedToAssemblyInUsingNamespaces(string metadataName, ref NamespaceOrTypeSymbol qualifierOpt, BindingDiagnosticBag diagnostics, Location location) { return Next?.GetForwardedToAssemblyInUsingNamespaces(metadataName, ref qualifierOpt, diagnostics, location); } protected AssemblySymbol GetForwardedToAssembly(string fullName, BindingDiagnosticBag diagnostics, Location location) { var metadataName = MetadataTypeName.FromFullName(fullName); foreach (var referencedAssembly in Compilation.Assembly.Modules[0].GetReferencedAssemblySymbols()) { var forwardedType = referencedAssembly.TryLookupForwardedMetadataType(ref metadataName); if ((object)forwardedType != null) { if (forwardedType.Kind == SymbolKind.ErrorType) { DiagnosticInfo diagInfo = ((ErrorTypeSymbol)forwardedType).ErrorInfo; if (diagInfo.Code == (int)ErrorCode.ERR_CycleInTypeForwarder) { Debug.Assert((object)forwardedType.ContainingAssembly != null, "How did we find a cycle if there was no forwarding?"); diagnostics.Add(ErrorCode.ERR_CycleInTypeForwarder, location, fullName, forwardedType.ContainingAssembly.Name); } else if (diagInfo.Code == (int)ErrorCode.ERR_TypeForwardedToMultipleAssemblies) { diagnostics.Add(diagInfo, location); return null; // Cannot determine a suitable forwarding assembly } } return forwardedType.ContainingAssembly; } } return null; } /// <summary> /// Look for a type forwarder for the given type in the containing assembly and any referenced assemblies. /// </summary> /// <param name="name">The name of the (potentially) forwarded type.</param> /// <param name="arity">The arity of the forwarded type.</param> /// <param name="qualifierOpt">The namespace of the potentially forwarded type. If none is provided, will /// try Usings of the current import for eligible namespaces and return the namespace of the found forwarder, /// if any.</param> /// <param name="diagnostics">Will be used to report non-fatal errors during look up.</param> /// <param name="location">Location to report errors on.</param> /// <returns>Returns the Assembly to which the type is forwarded, or null if none is found.</returns> /// <remarks> /// Since this method is intended to be used for error reporting, it stops as soon as it finds /// any type forwarder (or an error to report). It does not check other assemblies for consistency or better results. /// </remarks> protected AssemblySymbol GetForwardedToAssembly(string name, int arity, ref NamespaceOrTypeSymbol qualifierOpt, BindingDiagnosticBag diagnostics, Location location) { // If we are in the process of binding assembly level attributes, we might get into an infinite cycle // if any of the referenced assemblies forwards type to this assembly. Since forwarded types // are specified through assembly level attributes, an attempt to resolve the forwarded type // might require us to examine types forwarded by this assembly, thus binding assembly level // attributes again. And the cycle continues. // So, we won't do the analysis in this case, at the expense of better diagnostics. if ((this.Flags & BinderFlags.InContextualAttributeBinder) != 0) { var current = this; do { var contextualAttributeBinder = current as ContextualAttributeBinder; if (contextualAttributeBinder != null) { if ((object)contextualAttributeBinder.AttributeTarget != null && contextualAttributeBinder.AttributeTarget.Kind == SymbolKind.Assembly) { return null; } break; } current = current.Next; } while (current != null); } // NOTE: This won't work if the type isn't using CLS-style generic naming (i.e. `arity), but this code is // only intended to improve diagnostic messages, so false negatives in corner cases aren't a big deal. var metadataName = MetadataHelpers.ComposeAritySuffixedMetadataName(name, arity); var fullMetadataName = MetadataHelpers.BuildQualifiedName(qualifierOpt?.ToDisplayString(SymbolDisplayFormat.QualifiedNameOnlyFormat), metadataName); var result = GetForwardedToAssembly(fullMetadataName, diagnostics, location); if ((object)result != null) { return result; } if ((object)qualifierOpt == null) { return GetForwardedToAssemblyInUsingNamespaces(metadataName, ref qualifierOpt, diagnostics, location); } return null; } #nullable enable internal static bool CheckFeatureAvailability(SyntaxNode syntax, MessageID feature, BindingDiagnosticBag diagnostics, Location? location = null) { return CheckFeatureAvailability(syntax, feature, diagnostics.DiagnosticBag, location); } internal static bool CheckFeatureAvailability(SyntaxNode syntax, MessageID feature, DiagnosticBag? diagnostics, Location? location = null) { return CheckFeatureAvailability(syntax.SyntaxTree, feature, diagnostics, location ?? syntax.GetLocation()); } internal static bool CheckFeatureAvailability(SyntaxTree tree, MessageID feature, BindingDiagnosticBag diagnostics, Location location) { return CheckFeatureAvailability(tree, feature, diagnostics.DiagnosticBag, location); } internal static bool CheckFeatureAvailability(SyntaxTree tree, MessageID feature, DiagnosticBag? diagnostics, Location location) { if (feature.GetFeatureAvailabilityDiagnosticInfo((CSharpParseOptions)tree.Options) is { } diagInfo) { diagnostics?.Add(diagInfo, location); return false; } return true; } } }
-1
dotnet/roslyn
55,262
Fix LSP completions when all items have default commit characters
Fixes an exception stack trace seen in https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1362284 Also fixes behavior of promotion of commit characters to the list to include default commit characters
dibarbet
2021-07-30T02:43:35Z
2021-07-30T21:21:47Z
2f7dffa534aceb92e9767568e88535c926588d12
65ee073bf6cea571a68193793420ecee60752711
Fix LSP completions when all items have default commit characters. Fixes an exception stack trace seen in https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1362284 Also fixes behavior of promotion of commit characters to the list to include default commit characters
./src/Compilers/CSharp/Portable/Symbols/Metadata/PE/NativeIntegerTypeDecoder.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Diagnostics; using System.Reflection.Metadata; using Microsoft.CodeAnalysis.PooledObjects; namespace Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE { internal struct NativeIntegerTypeDecoder { private sealed class ErrorTypeException : Exception { } internal static TypeSymbol TransformType(TypeSymbol type, EntityHandle handle, PEModuleSymbol containingModule) { return containingModule.Module.HasNativeIntegerAttribute(handle, out var transformFlags) ? TransformType(type, transformFlags) : type; } internal static TypeSymbol TransformType(TypeSymbol type, ImmutableArray<bool> transformFlags) { var decoder = new NativeIntegerTypeDecoder(transformFlags); try { var result = decoder.TransformType(type); if (decoder._index == transformFlags.Length) { return result; } else { return new UnsupportedMetadataTypeSymbol(); } } catch (UnsupportedSignatureContent) { return new UnsupportedMetadataTypeSymbol(); } catch (ErrorTypeException) { // If we failed to decode because there was an error type involved, marking the // metadata as unsupported means that we'll cover up the error that would otherwise // be reported for the type. This would likely lead to a worse error message as we // would just report a BindToBogus, so return the type unchanged. Debug.Assert(type.ContainsErrorType()); return type; } } private readonly ImmutableArray<bool> _transformFlags; private int _index; private NativeIntegerTypeDecoder(ImmutableArray<bool> transformFlags) { _transformFlags = transformFlags; _index = 0; } private TypeWithAnnotations TransformTypeWithAnnotations(TypeWithAnnotations type) { return type.WithTypeAndModifiers(TransformType(type.Type), type.CustomModifiers); } private TypeSymbol TransformType(TypeSymbol type) { switch (type.TypeKind) { case TypeKind.Array: return TransformArrayType((ArrayTypeSymbol)type); case TypeKind.Pointer: return TransformPointerType((PointerTypeSymbol)type); case TypeKind.FunctionPointer: return TransformFunctionPointerType((FunctionPointerTypeSymbol)type); case TypeKind.TypeParameter: case TypeKind.Dynamic: return type; case TypeKind.Class: case TypeKind.Struct: case TypeKind.Interface: case TypeKind.Delegate: case TypeKind.Enum: return TransformNamedType((NamedTypeSymbol)type); default: Debug.Assert(type.TypeKind == TypeKind.Error); throw new ErrorTypeException(); } } private NamedTypeSymbol TransformNamedType(NamedTypeSymbol type) { if (!type.IsGenericType) { switch (type.SpecialType) { case SpecialType.System_IntPtr: case SpecialType.System_UIntPtr: if (_index >= _transformFlags.Length) { throw new UnsupportedSignatureContent(); } return (_transformFlags[_index++], type.IsNativeIntegerType) switch { (false, true) => type.NativeIntegerUnderlyingType, (true, false) => type.AsNativeInteger(), _ => type, }; } } var allTypeArguments = ArrayBuilder<TypeWithAnnotations>.GetInstance(); type.GetAllTypeArgumentsNoUseSiteDiagnostics(allTypeArguments); bool haveChanges = false; for (int i = 0; i < allTypeArguments.Count; i++) { TypeWithAnnotations oldTypeArgument = allTypeArguments[i]; TypeWithAnnotations newTypeArgument = TransformTypeWithAnnotations(oldTypeArgument); if (!oldTypeArgument.IsSameAs(newTypeArgument)) { allTypeArguments[i] = newTypeArgument; haveChanges = true; } } NamedTypeSymbol result = haveChanges ? type.WithTypeArguments(allTypeArguments.ToImmutable()) : type; allTypeArguments.Free(); return result; } private ArrayTypeSymbol TransformArrayType(ArrayTypeSymbol type) { return type.WithElementType(TransformTypeWithAnnotations(type.ElementTypeWithAnnotations)); } private PointerTypeSymbol TransformPointerType(PointerTypeSymbol type) { return type.WithPointedAtType(TransformTypeWithAnnotations(type.PointedAtTypeWithAnnotations)); } private FunctionPointerTypeSymbol TransformFunctionPointerType(FunctionPointerTypeSymbol type) { var transformedReturnType = TransformTypeWithAnnotations(type.Signature.ReturnTypeWithAnnotations); var transformedParameterTypes = ImmutableArray<TypeWithAnnotations>.Empty; var paramsModified = false; if (type.Signature.ParameterCount > 0) { var builder = ArrayBuilder<TypeWithAnnotations>.GetInstance(type.Signature.ParameterCount); foreach (var param in type.Signature.Parameters) { var transformedParam = TransformTypeWithAnnotations(param.TypeWithAnnotations); paramsModified = paramsModified || !transformedParam.IsSameAs(param.TypeWithAnnotations); builder.Add(transformedParam); } if (paramsModified) { transformedParameterTypes = builder.ToImmutableAndFree(); } else { transformedParameterTypes = type.Signature.ParameterTypesWithAnnotations; builder.Free(); } } if (paramsModified || !transformedReturnType.IsSameAs(type.Signature.ReturnTypeWithAnnotations)) { return type.SubstituteTypeSymbol(transformedReturnType, transformedParameterTypes, refCustomModifiers: default, paramRefCustomModifiers: default); } else { return type; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Diagnostics; using System.Reflection.Metadata; using Microsoft.CodeAnalysis.PooledObjects; namespace Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE { internal struct NativeIntegerTypeDecoder { private sealed class ErrorTypeException : Exception { } internal static TypeSymbol TransformType(TypeSymbol type, EntityHandle handle, PEModuleSymbol containingModule) { return containingModule.Module.HasNativeIntegerAttribute(handle, out var transformFlags) ? TransformType(type, transformFlags) : type; } internal static TypeSymbol TransformType(TypeSymbol type, ImmutableArray<bool> transformFlags) { var decoder = new NativeIntegerTypeDecoder(transformFlags); try { var result = decoder.TransformType(type); if (decoder._index == transformFlags.Length) { return result; } else { return new UnsupportedMetadataTypeSymbol(); } } catch (UnsupportedSignatureContent) { return new UnsupportedMetadataTypeSymbol(); } catch (ErrorTypeException) { // If we failed to decode because there was an error type involved, marking the // metadata as unsupported means that we'll cover up the error that would otherwise // be reported for the type. This would likely lead to a worse error message as we // would just report a BindToBogus, so return the type unchanged. Debug.Assert(type.ContainsErrorType()); return type; } } private readonly ImmutableArray<bool> _transformFlags; private int _index; private NativeIntegerTypeDecoder(ImmutableArray<bool> transformFlags) { _transformFlags = transformFlags; _index = 0; } private TypeWithAnnotations TransformTypeWithAnnotations(TypeWithAnnotations type) { return type.WithTypeAndModifiers(TransformType(type.Type), type.CustomModifiers); } private TypeSymbol TransformType(TypeSymbol type) { switch (type.TypeKind) { case TypeKind.Array: return TransformArrayType((ArrayTypeSymbol)type); case TypeKind.Pointer: return TransformPointerType((PointerTypeSymbol)type); case TypeKind.FunctionPointer: return TransformFunctionPointerType((FunctionPointerTypeSymbol)type); case TypeKind.TypeParameter: case TypeKind.Dynamic: return type; case TypeKind.Class: case TypeKind.Struct: case TypeKind.Interface: case TypeKind.Delegate: case TypeKind.Enum: return TransformNamedType((NamedTypeSymbol)type); default: Debug.Assert(type.TypeKind == TypeKind.Error); throw new ErrorTypeException(); } } private NamedTypeSymbol TransformNamedType(NamedTypeSymbol type) { if (!type.IsGenericType) { switch (type.SpecialType) { case SpecialType.System_IntPtr: case SpecialType.System_UIntPtr: if (_index >= _transformFlags.Length) { throw new UnsupportedSignatureContent(); } return (_transformFlags[_index++], type.IsNativeIntegerType) switch { (false, true) => type.NativeIntegerUnderlyingType, (true, false) => type.AsNativeInteger(), _ => type, }; } } var allTypeArguments = ArrayBuilder<TypeWithAnnotations>.GetInstance(); type.GetAllTypeArgumentsNoUseSiteDiagnostics(allTypeArguments); bool haveChanges = false; for (int i = 0; i < allTypeArguments.Count; i++) { TypeWithAnnotations oldTypeArgument = allTypeArguments[i]; TypeWithAnnotations newTypeArgument = TransformTypeWithAnnotations(oldTypeArgument); if (!oldTypeArgument.IsSameAs(newTypeArgument)) { allTypeArguments[i] = newTypeArgument; haveChanges = true; } } NamedTypeSymbol result = haveChanges ? type.WithTypeArguments(allTypeArguments.ToImmutable()) : type; allTypeArguments.Free(); return result; } private ArrayTypeSymbol TransformArrayType(ArrayTypeSymbol type) { return type.WithElementType(TransformTypeWithAnnotations(type.ElementTypeWithAnnotations)); } private PointerTypeSymbol TransformPointerType(PointerTypeSymbol type) { return type.WithPointedAtType(TransformTypeWithAnnotations(type.PointedAtTypeWithAnnotations)); } private FunctionPointerTypeSymbol TransformFunctionPointerType(FunctionPointerTypeSymbol type) { var transformedReturnType = TransformTypeWithAnnotations(type.Signature.ReturnTypeWithAnnotations); var transformedParameterTypes = ImmutableArray<TypeWithAnnotations>.Empty; var paramsModified = false; if (type.Signature.ParameterCount > 0) { var builder = ArrayBuilder<TypeWithAnnotations>.GetInstance(type.Signature.ParameterCount); foreach (var param in type.Signature.Parameters) { var transformedParam = TransformTypeWithAnnotations(param.TypeWithAnnotations); paramsModified = paramsModified || !transformedParam.IsSameAs(param.TypeWithAnnotations); builder.Add(transformedParam); } if (paramsModified) { transformedParameterTypes = builder.ToImmutableAndFree(); } else { transformedParameterTypes = type.Signature.ParameterTypesWithAnnotations; builder.Free(); } } if (paramsModified || !transformedReturnType.IsSameAs(type.Signature.ReturnTypeWithAnnotations)) { return type.SubstituteTypeSymbol(transformedReturnType, transformedParameterTypes, refCustomModifiers: default, paramRefCustomModifiers: default); } else { return type; } } } }
-1
dotnet/roslyn
55,262
Fix LSP completions when all items have default commit characters
Fixes an exception stack trace seen in https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1362284 Also fixes behavior of promotion of commit characters to the list to include default commit characters
dibarbet
2021-07-30T02:43:35Z
2021-07-30T21:21:47Z
2f7dffa534aceb92e9767568e88535c926588d12
65ee073bf6cea571a68193793420ecee60752711
Fix LSP completions when all items have default commit characters. Fixes an exception stack trace seen in https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1362284 Also fixes behavior of promotion of commit characters to the list to include default commit characters
./.gitattributes
############################################################################### # Set default behavior to automatically normalize line endings. ############################################################################### * text=auto encoding=UTF-8 *.sh text eol=lf ############################################################################### # Set default behavior for command prompt diff. # # This is need for earlier builds of msysgit that does not have it on by # default for csharp files. # Note: This is only used by command line ############################################################################### *.cs diff=csharp text *.vb text ############################################################################### # Set the merge driver for project and solution files # # Merging from the command prompt will add diff markers to the files if there # are conflicts (Merging from VS is not affected by the settings below, in VS # the diff markers are never inserted). Diff markers may cause the following # file extensions to fail to load in VS. An alternative would be to treat # these files as binary and thus will always conflict and require user # intervention with every merge. To do so, just uncomment the entries below ############################################################################### #*.sln merge=binary #*.csproj merge=binary #*.vbproj merge=binary #*.vcxproj merge=binary #*.vcproj merge=binary #*.dbproj merge=binary #*.fsproj merge=binary #*.lsproj merge=binary #*.wixproj merge=binary #*.modelproj merge=binary #*.sqlproj merge=binary #*.wwaproj merge=binary ############################################################################### # behavior for image files # # image files are treated as binary by default. ############################################################################### #*.jpg binary #*.png binary #*.gif binary ############################################################################### # diff behavior for common document formats # # Convert binary document formats to text before diffing them. This feature # is only available from the command line. Turn it on by uncommenting the # entries below. ############################################################################### #*.doc diff=astextplain #*.DOC diff=astextplain #*.docx diff=astextplain #*.DOCX diff=astextplain #*.dot diff=astextplain #*.DOT diff=astextplain #*.pdf diff=astextplain #*.PDF diff=astextplain #*.rtf diff=astextplain #*.RTF diff=astextplain # Generated files src/Compilers/CSharp/Portable/Generated/* linguist-generated=true src/Compilers/CSharp/Portable/CSharpResources.Designer.cs linguist-generated=true src/Compilers/VisualBasic/Portable/Generated/* linguist-generated=true src/Compilers/VisualBasic/Portable/VBResources.Designer.vb linguist-generated=true *.xlf linguist-generated=true
############################################################################### # Set default behavior to automatically normalize line endings. ############################################################################### * text=auto encoding=UTF-8 *.sh text eol=lf ############################################################################### # Set default behavior for command prompt diff. # # This is need for earlier builds of msysgit that does not have it on by # default for csharp files. # Note: This is only used by command line ############################################################################### *.cs diff=csharp text *.vb text ############################################################################### # Set the merge driver for project and solution files # # Merging from the command prompt will add diff markers to the files if there # are conflicts (Merging from VS is not affected by the settings below, in VS # the diff markers are never inserted). Diff markers may cause the following # file extensions to fail to load in VS. An alternative would be to treat # these files as binary and thus will always conflict and require user # intervention with every merge. To do so, just uncomment the entries below ############################################################################### #*.sln merge=binary #*.csproj merge=binary #*.vbproj merge=binary #*.vcxproj merge=binary #*.vcproj merge=binary #*.dbproj merge=binary #*.fsproj merge=binary #*.lsproj merge=binary #*.wixproj merge=binary #*.modelproj merge=binary #*.sqlproj merge=binary #*.wwaproj merge=binary ############################################################################### # behavior for image files # # image files are treated as binary by default. ############################################################################### #*.jpg binary #*.png binary #*.gif binary ############################################################################### # diff behavior for common document formats # # Convert binary document formats to text before diffing them. This feature # is only available from the command line. Turn it on by uncommenting the # entries below. ############################################################################### #*.doc diff=astextplain #*.DOC diff=astextplain #*.docx diff=astextplain #*.DOCX diff=astextplain #*.dot diff=astextplain #*.DOT diff=astextplain #*.pdf diff=astextplain #*.PDF diff=astextplain #*.rtf diff=astextplain #*.RTF diff=astextplain # Generated files src/Compilers/CSharp/Portable/Generated/* linguist-generated=true src/Compilers/CSharp/Portable/CSharpResources.Designer.cs linguist-generated=true src/Compilers/VisualBasic/Portable/Generated/* linguist-generated=true src/Compilers/VisualBasic/Portable/VBResources.Designer.vb linguist-generated=true *.xlf linguist-generated=true
-1
dotnet/roslyn
55,262
Fix LSP completions when all items have default commit characters
Fixes an exception stack trace seen in https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1362284 Also fixes behavior of promotion of commit characters to the list to include default commit characters
dibarbet
2021-07-30T02:43:35Z
2021-07-30T21:21:47Z
2f7dffa534aceb92e9767568e88535c926588d12
65ee073bf6cea571a68193793420ecee60752711
Fix LSP completions when all items have default commit characters. Fixes an exception stack trace seen in https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1362284 Also fixes behavior of promotion of commit characters to the list to include default commit characters
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/CodeStyle/CodeStyleOption2`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.Xml.Linq; using Microsoft.CodeAnalysis.Diagnostics; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CodeStyle { internal interface ICodeStyleOption : IObjectWritable { XElement ToXElement(); object? Value { get; } NotificationOption2 Notification { get; } ICodeStyleOption WithValue(object value); ICodeStyleOption WithNotification(NotificationOption2 notification); ICodeStyleOption AsCodeStyleOption<TCodeStyleOption>(); #if !CODE_STYLE ICodeStyleOption AsPublicCodeStyleOption(); #endif } /// <summary> /// Represents a code style option and an associated notification option. Supports /// being instantiated with T as a <see cref="bool"/> or an <c>enum type</c>. /// /// CodeStyleOption also has some basic support for migration a <see cref="bool"/> option /// forward to an <c>enum type</c> option. Specifically, if a previously serialized /// bool-CodeStyleOption is then deserialized into an enum-CodeStyleOption then 'false' /// values will be migrated to have the 0-value of the enum, and 'true' values will be /// migrated to have the 1-value of the enum. /// /// Similarly, enum-type code options will serialize out in a way that is compatible with /// hosts that expect the value to be a boolean. Specifically, if the enum value is 0 or 1 /// then those values will write back as false/true. /// </summary> internal sealed partial class CodeStyleOption2<T> : ICodeStyleOption, IEquatable<CodeStyleOption2<T>?> { static CodeStyleOption2() { ObjectBinder.RegisterTypeReader(typeof(CodeStyleOption2<T>), ReadFrom); } public static CodeStyleOption2<T> Default => new(default!, NotificationOption2.Silent); private const int SerializationVersion = 1; private readonly NotificationOption2 _notification; public CodeStyleOption2(T value, NotificationOption2 notification) { Value = value; _notification = notification ?? throw new ArgumentNullException(nameof(notification)); } public T Value { get; } object? ICodeStyleOption.Value => this.Value; ICodeStyleOption ICodeStyleOption.WithValue(object value) => new CodeStyleOption2<T>((T)value, Notification); ICodeStyleOption ICodeStyleOption.WithNotification(NotificationOption2 notification) => new CodeStyleOption2<T>(Value, notification); #if CODE_STYLE ICodeStyleOption ICodeStyleOption.AsCodeStyleOption<TCodeStyleOption>() => this; #else ICodeStyleOption ICodeStyleOption.AsCodeStyleOption<TCodeStyleOption>() => this is TCodeStyleOption ? this : (ICodeStyleOption)new CodeStyleOption<T>(this); ICodeStyleOption ICodeStyleOption.AsPublicCodeStyleOption() => new CodeStyleOption<T>(this); #endif private int EnumValueAsInt32 => (int)(object)Value!; public NotificationOption2 Notification { get => _notification; } public XElement ToXElement() => new("CodeStyleOption", // Ensure that we use "CodeStyleOption" as the name for back compat. new XAttribute(nameof(SerializationVersion), SerializationVersion), new XAttribute("Type", GetTypeNameForSerialization()), new XAttribute(nameof(Value), GetValueForSerialization()), new XAttribute(nameof(DiagnosticSeverity), Notification.Severity.ToDiagnosticSeverity() ?? DiagnosticSeverity.Hidden)); private object GetValueForSerialization() { if (typeof(T) == typeof(string)) { return Value!; } else if (typeof(T) == typeof(bool)) { return Value!; } else if (IsZeroOrOneValueOfEnum()) { return EnumValueAsInt32 == 1; } else { return EnumValueAsInt32; } } private string GetTypeNameForSerialization() { if (typeof(T) == typeof(string)) { return nameof(String); } if (typeof(T) == typeof(bool) || IsZeroOrOneValueOfEnum()) { return nameof(Boolean); } else { return nameof(Int32); } } private bool IsZeroOrOneValueOfEnum() { var intVal = EnumValueAsInt32; return intVal == 0 || intVal == 1; } public static CodeStyleOption2<T> FromXElement(XElement element) { var typeAttribute = element.Attribute("Type"); var valueAttribute = element.Attribute(nameof(Value)); var severityAttribute = element.Attribute(nameof(DiagnosticSeverity)); var version = (int?)element.Attribute(nameof(SerializationVersion)); if (typeAttribute == null || valueAttribute == null || severityAttribute == null) { // data from storage is corrupt, or nothing has been stored yet. return Default; } if (version != SerializationVersion) { return Default; } var parser = GetParser(typeAttribute.Value); var value = parser(valueAttribute.Value); var severity = (DiagnosticSeverity)Enum.Parse(typeof(DiagnosticSeverity), severityAttribute.Value); return new CodeStyleOption2<T>(value, severity switch { DiagnosticSeverity.Hidden => NotificationOption2.Silent, DiagnosticSeverity.Info => NotificationOption2.Suggestion, DiagnosticSeverity.Warning => NotificationOption2.Warning, DiagnosticSeverity.Error => NotificationOption2.Error, _ => throw new ArgumentException(nameof(element)), }); } public bool ShouldReuseInSerialization => false; public void WriteTo(ObjectWriter writer) { writer.WriteValue(GetValueForSerialization()); writer.WriteInt32((int)(Notification.Severity.ToDiagnosticSeverity() ?? DiagnosticSeverity.Hidden)); } public static CodeStyleOption2<object> ReadFrom(ObjectReader reader) { return new CodeStyleOption2<object>( reader.ReadValue(), (DiagnosticSeverity)reader.ReadInt32() switch { DiagnosticSeverity.Hidden => NotificationOption2.Silent, DiagnosticSeverity.Info => NotificationOption2.Suggestion, DiagnosticSeverity.Warning => NotificationOption2.Warning, DiagnosticSeverity.Error => NotificationOption2.Error, var v => throw ExceptionUtilities.UnexpectedValue(v), }); } private static Func<string, T> GetParser(string type) => type switch { nameof(Boolean) => // Try to map a boolean value. Either map it to true/false if we're a // CodeStyleOption<bool> or map it to the 0 or 1 value for an enum if we're // a CodeStyleOption<SomeEnumType>. (Func<string, T>)(v => Convert(bool.Parse(v))), nameof(Int32) => v => Convert(int.Parse(v)), nameof(String) => v => (T)(object)v, _ => throw new ArgumentException(nameof(type)), }; private static T Convert(bool b) { // If we had a bool and we wanted a bool, then just return this value. if (typeof(T) == typeof(bool)) { return (T)(object)b; } // Map booleans to the 1/0 value of the enum. return b ? (T)(object)1 : (T)(object)0; } private static T Convert(int i) { // We got an int, but we wanted a bool. Map 0 to false, 1 to true, and anything else to default. if (typeof(T) == typeof(bool)) { return (T)(object)(i == 1); } // If had an int and we wanted an enum, then just return this value. return (T)(object)(i); } public bool Equals(CodeStyleOption2<T>? other) { return other is not null && EqualityComparer<T>.Default.Equals(Value, other.Value) && Notification == other.Notification; } public override bool Equals(object? obj) => obj is CodeStyleOption2<T> option && Equals(option); public override int GetHashCode() => unchecked((Notification.GetHashCode() * (int)0xA5555529) + EqualityComparer<T>.Default.GetHashCode(Value!)); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Xml.Linq; using Microsoft.CodeAnalysis.Diagnostics; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CodeStyle { internal interface ICodeStyleOption : IObjectWritable { XElement ToXElement(); object? Value { get; } NotificationOption2 Notification { get; } ICodeStyleOption WithValue(object value); ICodeStyleOption WithNotification(NotificationOption2 notification); ICodeStyleOption AsCodeStyleOption<TCodeStyleOption>(); #if !CODE_STYLE ICodeStyleOption AsPublicCodeStyleOption(); #endif } /// <summary> /// Represents a code style option and an associated notification option. Supports /// being instantiated with T as a <see cref="bool"/> or an <c>enum type</c>. /// /// CodeStyleOption also has some basic support for migration a <see cref="bool"/> option /// forward to an <c>enum type</c> option. Specifically, if a previously serialized /// bool-CodeStyleOption is then deserialized into an enum-CodeStyleOption then 'false' /// values will be migrated to have the 0-value of the enum, and 'true' values will be /// migrated to have the 1-value of the enum. /// /// Similarly, enum-type code options will serialize out in a way that is compatible with /// hosts that expect the value to be a boolean. Specifically, if the enum value is 0 or 1 /// then those values will write back as false/true. /// </summary> internal sealed partial class CodeStyleOption2<T> : ICodeStyleOption, IEquatable<CodeStyleOption2<T>?> { static CodeStyleOption2() { ObjectBinder.RegisterTypeReader(typeof(CodeStyleOption2<T>), ReadFrom); } public static CodeStyleOption2<T> Default => new(default!, NotificationOption2.Silent); private const int SerializationVersion = 1; private readonly NotificationOption2 _notification; public CodeStyleOption2(T value, NotificationOption2 notification) { Value = value; _notification = notification ?? throw new ArgumentNullException(nameof(notification)); } public T Value { get; } object? ICodeStyleOption.Value => this.Value; ICodeStyleOption ICodeStyleOption.WithValue(object value) => new CodeStyleOption2<T>((T)value, Notification); ICodeStyleOption ICodeStyleOption.WithNotification(NotificationOption2 notification) => new CodeStyleOption2<T>(Value, notification); #if CODE_STYLE ICodeStyleOption ICodeStyleOption.AsCodeStyleOption<TCodeStyleOption>() => this; #else ICodeStyleOption ICodeStyleOption.AsCodeStyleOption<TCodeStyleOption>() => this is TCodeStyleOption ? this : (ICodeStyleOption)new CodeStyleOption<T>(this); ICodeStyleOption ICodeStyleOption.AsPublicCodeStyleOption() => new CodeStyleOption<T>(this); #endif private int EnumValueAsInt32 => (int)(object)Value!; public NotificationOption2 Notification { get => _notification; } public XElement ToXElement() => new("CodeStyleOption", // Ensure that we use "CodeStyleOption" as the name for back compat. new XAttribute(nameof(SerializationVersion), SerializationVersion), new XAttribute("Type", GetTypeNameForSerialization()), new XAttribute(nameof(Value), GetValueForSerialization()), new XAttribute(nameof(DiagnosticSeverity), Notification.Severity.ToDiagnosticSeverity() ?? DiagnosticSeverity.Hidden)); private object GetValueForSerialization() { if (typeof(T) == typeof(string)) { return Value!; } else if (typeof(T) == typeof(bool)) { return Value!; } else if (IsZeroOrOneValueOfEnum()) { return EnumValueAsInt32 == 1; } else { return EnumValueAsInt32; } } private string GetTypeNameForSerialization() { if (typeof(T) == typeof(string)) { return nameof(String); } if (typeof(T) == typeof(bool) || IsZeroOrOneValueOfEnum()) { return nameof(Boolean); } else { return nameof(Int32); } } private bool IsZeroOrOneValueOfEnum() { var intVal = EnumValueAsInt32; return intVal == 0 || intVal == 1; } public static CodeStyleOption2<T> FromXElement(XElement element) { var typeAttribute = element.Attribute("Type"); var valueAttribute = element.Attribute(nameof(Value)); var severityAttribute = element.Attribute(nameof(DiagnosticSeverity)); var version = (int?)element.Attribute(nameof(SerializationVersion)); if (typeAttribute == null || valueAttribute == null || severityAttribute == null) { // data from storage is corrupt, or nothing has been stored yet. return Default; } if (version != SerializationVersion) { return Default; } var parser = GetParser(typeAttribute.Value); var value = parser(valueAttribute.Value); var severity = (DiagnosticSeverity)Enum.Parse(typeof(DiagnosticSeverity), severityAttribute.Value); return new CodeStyleOption2<T>(value, severity switch { DiagnosticSeverity.Hidden => NotificationOption2.Silent, DiagnosticSeverity.Info => NotificationOption2.Suggestion, DiagnosticSeverity.Warning => NotificationOption2.Warning, DiagnosticSeverity.Error => NotificationOption2.Error, _ => throw new ArgumentException(nameof(element)), }); } public bool ShouldReuseInSerialization => false; public void WriteTo(ObjectWriter writer) { writer.WriteValue(GetValueForSerialization()); writer.WriteInt32((int)(Notification.Severity.ToDiagnosticSeverity() ?? DiagnosticSeverity.Hidden)); } public static CodeStyleOption2<object> ReadFrom(ObjectReader reader) { return new CodeStyleOption2<object>( reader.ReadValue(), (DiagnosticSeverity)reader.ReadInt32() switch { DiagnosticSeverity.Hidden => NotificationOption2.Silent, DiagnosticSeverity.Info => NotificationOption2.Suggestion, DiagnosticSeverity.Warning => NotificationOption2.Warning, DiagnosticSeverity.Error => NotificationOption2.Error, var v => throw ExceptionUtilities.UnexpectedValue(v), }); } private static Func<string, T> GetParser(string type) => type switch { nameof(Boolean) => // Try to map a boolean value. Either map it to true/false if we're a // CodeStyleOption<bool> or map it to the 0 or 1 value for an enum if we're // a CodeStyleOption<SomeEnumType>. (Func<string, T>)(v => Convert(bool.Parse(v))), nameof(Int32) => v => Convert(int.Parse(v)), nameof(String) => v => (T)(object)v, _ => throw new ArgumentException(nameof(type)), }; private static T Convert(bool b) { // If we had a bool and we wanted a bool, then just return this value. if (typeof(T) == typeof(bool)) { return (T)(object)b; } // Map booleans to the 1/0 value of the enum. return b ? (T)(object)1 : (T)(object)0; } private static T Convert(int i) { // We got an int, but we wanted a bool. Map 0 to false, 1 to true, and anything else to default. if (typeof(T) == typeof(bool)) { return (T)(object)(i == 1); } // If had an int and we wanted an enum, then just return this value. return (T)(object)(i); } public bool Equals(CodeStyleOption2<T>? other) { return other is not null && EqualityComparer<T>.Default.Equals(Value, other.Value) && Notification == other.Notification; } public override bool Equals(object? obj) => obj is CodeStyleOption2<T> option && Equals(option); public override int GetHashCode() => unchecked((Notification.GetHashCode() * (int)0xA5555529) + EqualityComparer<T>.Default.GetHashCode(Value!)); } }
-1
dotnet/roslyn
55,262
Fix LSP completions when all items have default commit characters
Fixes an exception stack trace seen in https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1362284 Also fixes behavior of promotion of commit characters to the list to include default commit characters
dibarbet
2021-07-30T02:43:35Z
2021-07-30T21:21:47Z
2f7dffa534aceb92e9767568e88535c926588d12
65ee073bf6cea571a68193793420ecee60752711
Fix LSP completions when all items have default commit characters. Fixes an exception stack trace seen in https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1362284 Also fixes behavior of promotion of commit characters to the list to include default commit characters
./src/EditorFeatures/Core/Shared/Utilities/CaretPreservingEditTransaction.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Text.Operations; namespace Microsoft.CodeAnalysis.Editor.Shared.Utilities { internal class CaretPreservingEditTransaction : IDisposable { private readonly IEditorOperations _editorOperations; private readonly ITextUndoHistory? _undoHistory; private ITextUndoTransaction? _transaction; private bool _active; public CaretPreservingEditTransaction( string description, ITextView textView, ITextUndoHistoryRegistry undoHistoryRegistry, IEditorOperationsFactoryService editorOperationsFactoryService) : this(description, undoHistoryRegistry.GetHistory(textView.TextBuffer), editorOperationsFactoryService.GetEditorOperations(textView)) { } public CaretPreservingEditTransaction(string description, ITextUndoHistory? undoHistory, IEditorOperations editorOperations) { _editorOperations = editorOperations; _undoHistory = undoHistory; _active = true; if (_undoHistory != null) { _transaction = new HACK_TextUndoTransactionThatRollsBackProperly(_undoHistory.CreateTransaction(description)); _editorOperations.AddBeforeTextBufferChangePrimitive(); } } public static CaretPreservingEditTransaction? TryCreate(string description, ITextView textView, ITextUndoHistoryRegistry undoHistoryRegistry, IEditorOperationsFactoryService editorOperationsFactoryService) { if (undoHistoryRegistry.TryGetHistory(textView.TextBuffer, out _)) { return new CaretPreservingEditTransaction(description, textView, undoHistoryRegistry, editorOperationsFactoryService); } return null; } public void Complete() { if (!_active) { throw new InvalidOperationException(EditorFeaturesResources.The_transaction_is_already_complete); } _editorOperations.AddAfterTextBufferChangePrimitive(); if (_transaction != null) { _transaction.Complete(); } EndTransaction(); } public void Cancel() { if (!_active) { throw new InvalidOperationException(EditorFeaturesResources.The_transaction_is_already_complete); } if (_transaction != null) { _transaction.Cancel(); } EndTransaction(); } public void Dispose() { if (_transaction != null) { // If the transaction is still pending, we'll cancel it Cancel(); } } public IMergeTextUndoTransactionPolicy? MergePolicy { get { return _transaction?.MergePolicy; } set { if (_transaction != null) { _transaction.MergePolicy = value; } } } private void EndTransaction() { if (_transaction != null) { _transaction.Dispose(); _transaction = null; } _active = 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 Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Text.Operations; namespace Microsoft.CodeAnalysis.Editor.Shared.Utilities { internal class CaretPreservingEditTransaction : IDisposable { private readonly IEditorOperations _editorOperations; private readonly ITextUndoHistory? _undoHistory; private ITextUndoTransaction? _transaction; private bool _active; public CaretPreservingEditTransaction( string description, ITextView textView, ITextUndoHistoryRegistry undoHistoryRegistry, IEditorOperationsFactoryService editorOperationsFactoryService) : this(description, undoHistoryRegistry.GetHistory(textView.TextBuffer), editorOperationsFactoryService.GetEditorOperations(textView)) { } public CaretPreservingEditTransaction(string description, ITextUndoHistory? undoHistory, IEditorOperations editorOperations) { _editorOperations = editorOperations; _undoHistory = undoHistory; _active = true; if (_undoHistory != null) { _transaction = new HACK_TextUndoTransactionThatRollsBackProperly(_undoHistory.CreateTransaction(description)); _editorOperations.AddBeforeTextBufferChangePrimitive(); } } public static CaretPreservingEditTransaction? TryCreate(string description, ITextView textView, ITextUndoHistoryRegistry undoHistoryRegistry, IEditorOperationsFactoryService editorOperationsFactoryService) { if (undoHistoryRegistry.TryGetHistory(textView.TextBuffer, out _)) { return new CaretPreservingEditTransaction(description, textView, undoHistoryRegistry, editorOperationsFactoryService); } return null; } public void Complete() { if (!_active) { throw new InvalidOperationException(EditorFeaturesResources.The_transaction_is_already_complete); } _editorOperations.AddAfterTextBufferChangePrimitive(); if (_transaction != null) { _transaction.Complete(); } EndTransaction(); } public void Cancel() { if (!_active) { throw new InvalidOperationException(EditorFeaturesResources.The_transaction_is_already_complete); } if (_transaction != null) { _transaction.Cancel(); } EndTransaction(); } public void Dispose() { if (_transaction != null) { // If the transaction is still pending, we'll cancel it Cancel(); } } public IMergeTextUndoTransactionPolicy? MergePolicy { get { return _transaction?.MergePolicy; } set { if (_transaction != null) { _transaction.MergePolicy = value; } } } private void EndTransaction() { if (_transaction != null) { _transaction.Dispose(); _transaction = null; } _active = false; } } }
-1
dotnet/roslyn
55,262
Fix LSP completions when all items have default commit characters
Fixes an exception stack trace seen in https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1362284 Also fixes behavior of promotion of commit characters to the list to include default commit characters
dibarbet
2021-07-30T02:43:35Z
2021-07-30T21:21:47Z
2f7dffa534aceb92e9767568e88535c926588d12
65ee073bf6cea571a68193793420ecee60752711
Fix LSP completions when all items have default commit characters. Fixes an exception stack trace seen in https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1362284 Also fixes behavior of promotion of commit characters to the list to include default commit characters
./src/Analyzers/CSharp/CodeFixes/xlf/CSharpCodeFixesResources.ru.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="ru" original="../CSharpCodeFixesResources.resx"> <body> <trans-unit id="Add_this"> <source>Add 'this.'</source> <target state="translated">Добавьте "this".</target> <note /> </trans-unit> <trans-unit id="Convert_typeof_to_nameof"> <source>Convert 'typeof' to 'nameof'</source> <target state="translated">Преобразовать "typeof" в "nameof"</target> <note /> </trans-unit> <trans-unit id="Pass_in_captured_variables_as_arguments"> <source>Pass in captured variables as arguments</source> <target state="translated">Передача зафиксированных переменных в качестве аргументов</target> <note /> </trans-unit> <trans-unit id="Place_colon_on_following_line"> <source>Place colon on following line</source> <target state="translated">Поместите двоеточие на следующей строке.</target> <note /> </trans-unit> <trans-unit id="Place_statement_on_following_line"> <source>Place statement on following line</source> <target state="translated">Размещайте оператор на отдельной строке</target> <note /> </trans-unit> <trans-unit id="Remove_Unnecessary_Usings"> <source>Remove Unnecessary Usings</source> <target state="translated">Удалить ненужные директивы using</target> <note /> </trans-unit> <trans-unit id="Remove_blank_lines_between_braces"> <source>Remove blank line between braces</source> <target state="translated">Удалить пустую строку между скобками</target> <note /> </trans-unit> <trans-unit id="Remove_unreachable_code"> <source>Remove unreachable code</source> <target state="translated">Удалить недостижимый код</target> <note /> </trans-unit> <trans-unit id="Warning_colon_Adding_parameters_to_local_function_declaration_may_produce_invalid_code"> <source>Warning: Adding parameters to local function declaration may produce invalid code.</source> <target state="translated">Предупреждение! Добавление параметров в объявление локальной функции может привести к недопустимому коду.</target> <note /> </trans-unit> </body> </file> </xliff>
<?xml version="1.0" encoding="utf-8"?> <xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd"> <file datatype="xml" source-language="en" target-language="ru" original="../CSharpCodeFixesResources.resx"> <body> <trans-unit id="Add_this"> <source>Add 'this.'</source> <target state="translated">Добавьте "this".</target> <note /> </trans-unit> <trans-unit id="Convert_typeof_to_nameof"> <source>Convert 'typeof' to 'nameof'</source> <target state="translated">Преобразовать "typeof" в "nameof"</target> <note /> </trans-unit> <trans-unit id="Pass_in_captured_variables_as_arguments"> <source>Pass in captured variables as arguments</source> <target state="translated">Передача зафиксированных переменных в качестве аргументов</target> <note /> </trans-unit> <trans-unit id="Place_colon_on_following_line"> <source>Place colon on following line</source> <target state="translated">Поместите двоеточие на следующей строке.</target> <note /> </trans-unit> <trans-unit id="Place_statement_on_following_line"> <source>Place statement on following line</source> <target state="translated">Размещайте оператор на отдельной строке</target> <note /> </trans-unit> <trans-unit id="Remove_Unnecessary_Usings"> <source>Remove Unnecessary Usings</source> <target state="translated">Удалить ненужные директивы using</target> <note /> </trans-unit> <trans-unit id="Remove_blank_lines_between_braces"> <source>Remove blank line between braces</source> <target state="translated">Удалить пустую строку между скобками</target> <note /> </trans-unit> <trans-unit id="Remove_unreachable_code"> <source>Remove unreachable code</source> <target state="translated">Удалить недостижимый код</target> <note /> </trans-unit> <trans-unit id="Warning_colon_Adding_parameters_to_local_function_declaration_may_produce_invalid_code"> <source>Warning: Adding parameters to local function declaration may produce invalid code.</source> <target state="translated">Предупреждение! Добавление параметров в объявление локальной функции может привести к недопустимому коду.</target> <note /> </trans-unit> </body> </file> </xliff>
-1
dotnet/roslyn
55,262
Fix LSP completions when all items have default commit characters
Fixes an exception stack trace seen in https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1362284 Also fixes behavior of promotion of commit characters to the list to include default commit characters
dibarbet
2021-07-30T02:43:35Z
2021-07-30T21:21:47Z
2f7dffa534aceb92e9767568e88535c926588d12
65ee073bf6cea571a68193793420ecee60752711
Fix LSP completions when all items have default commit characters. Fixes an exception stack trace seen in https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1362284 Also fixes behavior of promotion of commit characters to the list to include default commit characters
./src/EditorFeatures/CSharpTest2/Recommendations/AsKeywordRecommenderTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading.Tasks; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations { public class AsKeywordRecommenderTests : KeywordRecommenderTests { [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAtRoot_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterClass_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"class C { } $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterGlobalStatement_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"System.Console.WriteLine(); $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterGlobalVariableDeclaration_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"int i = 0; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInUsingAlias() { await VerifyAbsenceAsync( @"using Goo = $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInGlobalUsingAlias() { await VerifyAbsenceAsync( @"global using Goo = $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInEmptyStatement() { await VerifyAbsenceAsync(AddInsideMethod( @"$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterExpr() { await VerifyKeywordAsync(AddInsideMethod( @"var q = goo $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterDottedName() { await VerifyKeywordAsync(AddInsideMethod( @"var q = goo.Current $$")); } [WorkItem(543041, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543041")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterVarInForLoop() { await VerifyAbsenceAsync(AddInsideMethod( @"for (var $$")); } [WorkItem(1064811, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064811")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotBeforeFirstStringHole() { await VerifyAbsenceAsync(AddInsideMethod( @"var x = ""\{0}$$\{1}\{2}""")); } [WorkItem(1064811, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064811")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotBetweenStringHoles() { await VerifyAbsenceAsync(AddInsideMethod( @"var x = ""\{0}\{1}$$\{2}""")); } [WorkItem(1064811, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064811")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterStringHoles() { await VerifyAbsenceAsync(AddInsideMethod( @"var x = ""\{0}\{1}\{2}$$""")); } [WorkItem(1064811, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064811")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterLastStringHole() { await VerifyKeywordAsync(AddInsideMethod( @"var x = ""\{0}\{1}\{2}"" $$")); } [WorkItem(1736, "https://github.com/dotnet/roslyn/issues/1736")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotWithinNumericLiteral() { await VerifyAbsenceAsync(AddInsideMethod( @"var x = .$$0;")); } [WorkItem(28586, "https://github.com/dotnet/roslyn/issues/28586")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterAsync() { await VerifyAbsenceAsync( @" using System; class C { void Goo() { Bar(async $$ } void Bar(Func<int, string> f) { } }"); } [WorkItem(8319, "https://github.com/dotnet/roslyn/issues/8319")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterMethodReference() { await VerifyAbsenceAsync( @" using System; class C { void M() { var v = Console.WriteLine $$"); } [WorkItem(8319, "https://github.com/dotnet/roslyn/issues/8319")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterAnonymousMethod() { await VerifyAbsenceAsync( @" using System; class C { void M() { Action a = delegate { } $$"); } [WorkItem(8319, "https://github.com/dotnet/roslyn/issues/8319")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterLambda1() { await VerifyAbsenceAsync( @" using System; class C { void M() { Action b = (() => 0) $$"); } [WorkItem(8319, "https://github.com/dotnet/roslyn/issues/8319")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterLambda2() { await VerifyAbsenceAsync( @" using System; class C { void M() { Action b = () => {} $$"); } [WorkItem(48573, "https://github.com/dotnet/roslyn/issues/48573")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestMissingAfterNumericLiteral() { await VerifyAbsenceAsync( @" class C { void M() { var x = 1$$ } }"); } [WorkItem(48573, "https://github.com/dotnet/roslyn/issues/48573")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestMissingAfterNumericLiteralAndDot() { await VerifyAbsenceAsync( @" class C { void M() { var x = 1.$$ } }"); } [WorkItem(48573, "https://github.com/dotnet/roslyn/issues/48573")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestMissingAfterNumericLiteralDotAndSpace() { await VerifyAbsenceAsync( @" class C { void M() { var x = 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.Threading.Tasks; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations { public class AsKeywordRecommenderTests : KeywordRecommenderTests { [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAtRoot_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterClass_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"class C { } $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterGlobalStatement_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"System.Console.WriteLine(); $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterGlobalVariableDeclaration_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"int i = 0; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInUsingAlias() { await VerifyAbsenceAsync( @"using Goo = $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInGlobalUsingAlias() { await VerifyAbsenceAsync( @"global using Goo = $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInEmptyStatement() { await VerifyAbsenceAsync(AddInsideMethod( @"$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterExpr() { await VerifyKeywordAsync(AddInsideMethod( @"var q = goo $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterDottedName() { await VerifyKeywordAsync(AddInsideMethod( @"var q = goo.Current $$")); } [WorkItem(543041, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543041")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterVarInForLoop() { await VerifyAbsenceAsync(AddInsideMethod( @"for (var $$")); } [WorkItem(1064811, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064811")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotBeforeFirstStringHole() { await VerifyAbsenceAsync(AddInsideMethod( @"var x = ""\{0}$$\{1}\{2}""")); } [WorkItem(1064811, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064811")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotBetweenStringHoles() { await VerifyAbsenceAsync(AddInsideMethod( @"var x = ""\{0}\{1}$$\{2}""")); } [WorkItem(1064811, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064811")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterStringHoles() { await VerifyAbsenceAsync(AddInsideMethod( @"var x = ""\{0}\{1}\{2}$$""")); } [WorkItem(1064811, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064811")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterLastStringHole() { await VerifyKeywordAsync(AddInsideMethod( @"var x = ""\{0}\{1}\{2}"" $$")); } [WorkItem(1736, "https://github.com/dotnet/roslyn/issues/1736")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotWithinNumericLiteral() { await VerifyAbsenceAsync(AddInsideMethod( @"var x = .$$0;")); } [WorkItem(28586, "https://github.com/dotnet/roslyn/issues/28586")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterAsync() { await VerifyAbsenceAsync( @" using System; class C { void Goo() { Bar(async $$ } void Bar(Func<int, string> f) { } }"); } [WorkItem(8319, "https://github.com/dotnet/roslyn/issues/8319")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterMethodReference() { await VerifyAbsenceAsync( @" using System; class C { void M() { var v = Console.WriteLine $$"); } [WorkItem(8319, "https://github.com/dotnet/roslyn/issues/8319")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterAnonymousMethod() { await VerifyAbsenceAsync( @" using System; class C { void M() { Action a = delegate { } $$"); } [WorkItem(8319, "https://github.com/dotnet/roslyn/issues/8319")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterLambda1() { await VerifyAbsenceAsync( @" using System; class C { void M() { Action b = (() => 0) $$"); } [WorkItem(8319, "https://github.com/dotnet/roslyn/issues/8319")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterLambda2() { await VerifyAbsenceAsync( @" using System; class C { void M() { Action b = () => {} $$"); } [WorkItem(48573, "https://github.com/dotnet/roslyn/issues/48573")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestMissingAfterNumericLiteral() { await VerifyAbsenceAsync( @" class C { void M() { var x = 1$$ } }"); } [WorkItem(48573, "https://github.com/dotnet/roslyn/issues/48573")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestMissingAfterNumericLiteralAndDot() { await VerifyAbsenceAsync( @" class C { void M() { var x = 1.$$ } }"); } [WorkItem(48573, "https://github.com/dotnet/roslyn/issues/48573")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestMissingAfterNumericLiteralDotAndSpace() { await VerifyAbsenceAsync( @" class C { void M() { var x = 1. $$ } }"); } } }
-1
dotnet/roslyn
55,262
Fix LSP completions when all items have default commit characters
Fixes an exception stack trace seen in https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1362284 Also fixes behavior of promotion of commit characters to the list to include default commit characters
dibarbet
2021-07-30T02:43:35Z
2021-07-30T21:21:47Z
2f7dffa534aceb92e9767568e88535c926588d12
65ee073bf6cea571a68193793420ecee60752711
Fix LSP completions when all items have default commit characters. Fixes an exception stack trace seen in https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1362284 Also fixes behavior of promotion of commit characters to the list to include default commit characters
./src/Features/CSharp/Portable/xlf/CSharpFeaturesResources.fr.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="fr" original="../CSharpFeaturesResources.resx"> <body> <trans-unit id="Add_await"> <source>Add 'await'</source> <target state="translated">Ajouter 'await'</target> <note>{Locked="await"} "await" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Add_await_and_ConfigureAwaitFalse"> <source>Add 'await' and 'ConfigureAwait(false)'</source> <target state="translated">Ajouter 'await' et 'ConfigureAwait(false)'</target> <note>{Locked="await"} "await" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Add_missing_usings"> <source>Add missing usings</source> <target state="translated">Ajouter les instructions using manquantes</target> <note>{Locked="using"} "using" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Add_remove_braces_for_single_line_control_statements"> <source>Add/remove braces for single-line control statements</source> <target state="translated">Ajouter/supprimer des accolades pour les instructions de contrôle sur une seule ligne</target> <note /> </trans-unit> <trans-unit id="Allow_unsafe_code_in_this_project"> <source>Allow unsafe code in this project</source> <target state="translated">Autoriser du code unsafe dans ce projet</target> <note /> </trans-unit> <trans-unit id="Apply_expression_block_body_preferences"> <source>Apply expression/block body preferences</source> <target state="translated">Appliquer les préférences de corps d'expression/de bloc</target> <note /> </trans-unit> <trans-unit id="Apply_implicit_explicit_type_preferences"> <source>Apply implicit/explicit type preferences</source> <target state="translated">Appliquer les préférences de type implicite/explicite</target> <note /> </trans-unit> <trans-unit id="Apply_inline_out_variable_preferences"> <source>Apply inline 'out' variables preferences</source> <target state="translated">Appliquer les préférences des variables 'out' inline</target> <note /> </trans-unit> <trans-unit id="Apply_language_framework_type_preferences"> <source>Apply language/framework type preferences</source> <target state="translated">Appliquer les préférences de type de langage/framework</target> <note /> </trans-unit> <trans-unit id="Apply_this_qualification_preferences"> <source>Apply 'this.' qualification preferences</source> <target state="translated">Appliquer les préférences de qualification 'this.'</target> <note /> </trans-unit> <trans-unit id="Apply_using_directive_placement_preferences"> <source>Apply preferred 'using' placement preferences</source> <target state="translated">Appliquer les préférences de placement de 'using' par défaut</target> <note>'using' is a C# keyword and should not be localized</note> </trans-unit> <trans-unit id="Assign_out_parameters"> <source>Assign 'out' parameters</source> <target state="translated">Assigner des paramètres 'out'</target> <note>{Locked="out"} "out" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Assign_out_parameters_at_start"> <source>Assign 'out' parameters (at start)</source> <target state="translated">Assigner des paramètres 'out' (au début)</target> <note>{Locked="out"} "out" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Assign_to_0"> <source>Assign to '{0}'</source> <target state="translated">Affecter à '{0}'</target> <note /> </trans-unit> <trans-unit id="Autoselect_disabled_due_to_potential_pattern_variable_declaration"> <source>Autoselect disabled due to potential pattern variable declaration.</source> <target state="translated">Sélection automatique désactivée en raison d'une déclaration de variable de modèle éventuelle.</target> <note /> </trans-unit> <trans-unit id="Change_to_as_expression"> <source>Change to 'as' expression</source> <target state="translated">Changer en expression 'as'</target> <note /> </trans-unit> <trans-unit id="Change_to_cast"> <source>Change to cast</source> <target state="translated">Changer en cast</target> <note /> </trans-unit> <trans-unit id="Compare_to_0"> <source>Compare to '{0}'</source> <target state="translated">Comparer à '{0}'</target> <note /> </trans-unit> <trans-unit id="Convert_to_method"> <source>Convert to method</source> <target state="translated">Convertir en méthode</target> <note /> </trans-unit> <trans-unit id="Convert_to_regular_string"> <source>Convert to regular string</source> <target state="translated">Convertir en chaîne classique</target> <note /> </trans-unit> <trans-unit id="Convert_to_switch_expression"> <source>Convert to 'switch' expression</source> <target state="translated">Convertir en expression 'switch'</target> <note /> </trans-unit> <trans-unit id="Convert_to_switch_statement"> <source>Convert to 'switch' statement</source> <target state="translated">Convertir en instruction « switch »</target> <note /> </trans-unit> <trans-unit id="Convert_to_verbatim_string"> <source>Convert to verbatim string</source> <target state="translated">Convertir en chaîne verbatim</target> <note /> </trans-unit> <trans-unit id="Declare_as_nullable"> <source>Declare as nullable</source> <target state="translated">Déclarer comme nullable</target> <note /> </trans-unit> <trans-unit id="Fix_return_type"> <source>Fix return type</source> <target state="translated">Corriger le type de retour</target> <note /> </trans-unit> <trans-unit id="Inline_temporary_variable"> <source>Inline temporary variable</source> <target state="translated">Variable temporaire inline</target> <note /> </trans-unit> <trans-unit id="Conflict_s_detected"> <source>Conflict(s) detected.</source> <target state="translated">Conflit(s) détecté(s).</target> <note /> </trans-unit> <trans-unit id="Make_private_field_readonly_when_possible"> <source>Make private fields readonly when possible</source> <target state="translated">Configurer les champs privés en lecture seule quand cela est possible</target> <note /> </trans-unit> <trans-unit id="Make_ref_struct"> <source>Make 'ref struct'</source> <target state="translated">Définir 'ref struct'</target> <note>{Locked="ref"}{Locked="struct"} "ref" and "struct" are C# keywords and should not be localized.</note> </trans-unit> <trans-unit id="Remove_in_keyword"> <source>Remove 'in' keyword</source> <target state="translated">Supprimer le mot clé 'in'</target> <note>{Locked="in"} "in" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Remove_new_modifier"> <source>Remove 'new' modifier</source> <target state="translated">Supprimer le modificateur 'new'</target> <note /> </trans-unit> <trans-unit id="Reverse_for_statement"> <source>Reverse 'for' statement</source> <target state="translated">Inverser l'instruction 'for'</target> <note>{Locked="for"} "for" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Simplify_lambda_expression"> <source>Simplify lambda expression</source> <target state="translated">Simplifier l'expression lambda</target> <note /> </trans-unit> <trans-unit id="Simplify_all_occurrences"> <source>Simplify all occurrences</source> <target state="translated">Simplifier toutes les occurrences</target> <note /> </trans-unit> <trans-unit id="Sort_accessibility_modifiers"> <source>Sort accessibility modifiers</source> <target state="translated">Trier les modificateurs d'accessibilité</target> <note /> </trans-unit> <trans-unit id="Unseal_class_0"> <source>Unseal class '{0}'</source> <target state="translated">Classe unsealed '{0}'</target> <note /> </trans-unit> <trans-unit id="Warning_Inlining_temporary_into_conditional_method_call"> <source>Warning: Inlining temporary into conditional method call.</source> <target state="translated">Avertissement : Inlining temporaire dans un appel de méthode conditionnel.</target> <note /> </trans-unit> <trans-unit id="Warning_Inlining_temporary_variable_may_change_code_meaning"> <source>Warning: Inlining temporary variable may change code meaning.</source> <target state="translated">Avertissement : L'inlining sur une variable temporaire peut changer la signification du code.</target> <note /> </trans-unit> <trans-unit id="asynchronous_foreach_statement"> <source>asynchronous foreach statement</source> <target state="translated">instruction foreach asynchrone</target> <note>{Locked="foreach"} "foreach" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="asynchronous_using_declaration"> <source>asynchronous using declaration</source> <target state="translated">déclaration using asynchrone</target> <note>{Locked="using"} "using" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="extern_alias"> <source>extern alias</source> <target state="translated">alias externe</target> <note /> </trans-unit> <trans-unit id="lambda_expression"> <source>&lt;lambda expression&gt;</source> <target state="translated">&lt;expression lambda&gt;</target> <note /> </trans-unit> <trans-unit id="Autoselect_disabled_due_to_potential_lambda_declaration"> <source>Autoselect disabled due to potential lambda declaration.</source> <target state="translated">Sélection automatique désactivée en raison d'une déclaration lambda éventuelle.</target> <note /> </trans-unit> <trans-unit id="local_variable_declaration"> <source>local variable declaration</source> <target state="translated">déclaration de variable locale</target> <note /> </trans-unit> <trans-unit id="member_name"> <source>&lt;member name&gt; = </source> <target state="translated">&lt;nom de membre&gt; =</target> <note /> </trans-unit> <trans-unit id="Autoselect_disabled_due_to_possible_explicitly_named_anonymous_type_member_creation"> <source>Autoselect disabled due to possible explicitly named anonymous type member creation.</source> <target state="translated">Sélection automatique désactivée en raison de la création éventuelle d'un membre de type anonyme nommé explicitement.</target> <note /> </trans-unit> <trans-unit id="element_name"> <source>&lt;element name&gt; : </source> <target state="translated">&lt;nom d'élément&gt; :</target> <note /> </trans-unit> <trans-unit id="Autoselect_disabled_due_to_possible_tuple_type_element_creation"> <source>Autoselect disabled due to possible tuple type element creation.</source> <target state="translated">Sélection automatique désactivée en raison de la création possible d'un élément de type tuple.</target> <note /> </trans-unit> <trans-unit id="pattern_variable"> <source>&lt;pattern variable&gt;</source> <target state="translated">&lt;variable de modèle&gt;</target> <note /> </trans-unit> <trans-unit id="range_variable"> <source>&lt;range variable&gt;</source> <target state="translated">&lt;variable de plage&gt;</target> <note /> </trans-unit> <trans-unit id="Autoselect_disabled_due_to_potential_range_variable_declaration"> <source>Autoselect disabled due to potential range variable declaration.</source> <target state="translated">Sélection automatique désactivée en raison d'une déclaration de variable de plage éventuelle.</target> <note /> </trans-unit> <trans-unit id="Simplify_name_0"> <source>Simplify name '{0}'</source> <target state="translated">Simplifier le nom '{0}'</target> <note /> </trans-unit> <trans-unit id="Simplify_member_access_0"> <source>Simplify member access '{0}'</source> <target state="translated">Simplifier l'accès au membre '{0}'</target> <note /> </trans-unit> <trans-unit id="Remove_this_qualification"> <source>Remove 'this' qualification</source> <target state="translated">Supprimer la qualification 'this'</target> <note /> </trans-unit> <trans-unit id="Name_can_be_simplified"> <source>Name can be simplified</source> <target state="translated">Le nom peut être simplifié</target> <note /> </trans-unit> <trans-unit id="Can_t_determine_valid_range_of_statements_to_extract"> <source>Can't determine valid range of statements to extract</source> <target state="translated">Impossible de déterminer la plage valide d'instructions à extraire</target> <note /> </trans-unit> <trans-unit id="Not_all_code_paths_return"> <source>Not all code paths return</source> <target state="translated">Tous les chemins du code n'ont pas été retournés</target> <note /> </trans-unit> <trans-unit id="Selection_does_not_contain_a_valid_node"> <source>Selection does not contain a valid node</source> <target state="translated">La sélection ne contient pas un nœud valide</target> <note /> </trans-unit> <trans-unit id="Invalid_selection"> <source>Invalid selection.</source> <target state="translated">Sélection incorrecte.</target> <note /> </trans-unit> <trans-unit id="Contains_invalid_selection"> <source>Contains invalid selection.</source> <target state="translated">Contient une sélection incorrecte.</target> <note /> </trans-unit> <trans-unit id="The_selection_contains_syntactic_errors"> <source>The selection contains syntactic errors</source> <target state="translated">La sélection contient des erreurs syntaxiques</target> <note /> </trans-unit> <trans-unit id="Selection_can_not_cross_over_preprocessor_directives"> <source>Selection can not cross over preprocessor directives.</source> <target state="translated">La sélection ne peut pas traverser plusieurs directives de préprocesseur.</target> <note /> </trans-unit> <trans-unit id="Selection_can_not_contain_a_yield_statement"> <source>Selection can not contain a yield statement.</source> <target state="translated">La sélection ne contient pas d'instruction yield.</target> <note /> </trans-unit> <trans-unit id="Selection_can_not_contain_throw_statement"> <source>Selection can not contain throw statement.</source> <target state="translated">La sélection ne contient pas d'instruction throw.</target> <note /> </trans-unit> <trans-unit id="Selection_can_not_be_part_of_constant_initializer_expression"> <source>Selection can not be part of constant initializer expression.</source> <target state="translated">La sélection ne peut pas faire partie d'une expression d'initialiseur de constante.</target> <note /> </trans-unit> <trans-unit id="Selection_can_not_contain_a_pattern_expression"> <source>Selection can not contain a pattern expression.</source> <target state="translated">La sélection ne peut pas contenir une expression de modèle.</target> <note /> </trans-unit> <trans-unit id="The_selected_code_is_inside_an_unsafe_context"> <source>The selected code is inside an unsafe context.</source> <target state="translated">Le code sélectionné se trouve dans un contexte unsafe.</target> <note /> </trans-unit> <trans-unit id="No_valid_statement_range_to_extract"> <source>No valid statement range to extract</source> <target state="translated">Aucune plage valide d'instructions à extraire</target> <note /> </trans-unit> <trans-unit id="deprecated"> <source>deprecated</source> <target state="translated">déconseillé</target> <note /> </trans-unit> <trans-unit id="extension"> <source>extension</source> <target state="translated">Extension</target> <note /> </trans-unit> <trans-unit id="awaitable"> <source>awaitable</source> <target state="translated">pouvant être attendu(e)</target> <note /> </trans-unit> <trans-unit id="awaitable_extension"> <source>awaitable, extension</source> <target state="translated">awaitable, extension</target> <note /> </trans-unit> <trans-unit id="Organize_Usings"> <source>Organize Usings</source> <target state="translated">Organiser les instructions Using</target> <note /> </trans-unit> <trans-unit id="Insert_await"> <source>Insert 'await'.</source> <target state="translated">Insérez 'await'.</target> <note /> </trans-unit> <trans-unit id="Make_0_return_Task_instead_of_void"> <source>Make {0} return Task instead of void.</source> <target state="translated">{0} doit retourner Task au lieu de void.</target> <note /> </trans-unit> <trans-unit id="Change_return_type_from_0_to_1"> <source>Change return type from {0} to {1}</source> <target state="translated">Changer le type de retour de {0} en {1}</target> <note /> </trans-unit> <trans-unit id="Replace_return_with_yield_return"> <source>Replace return with yield return</source> <target state="translated">Remplacer return par yield return</target> <note /> </trans-unit> <trans-unit id="Generate_explicit_conversion_operator_in_0"> <source>Generate explicit conversion operator in '{0}'</source> <target state="translated">Générer l’opérateur de conversion explicite dans « {0} »</target> <note /> </trans-unit> <trans-unit id="Generate_implicit_conversion_operator_in_0"> <source>Generate implicit conversion operator in '{0}'</source> <target state="translated">Générer l’opérateur de conversion implicite dans « {0} »</target> <note /> </trans-unit> <trans-unit id="record_"> <source>record</source> <target state="translated">enregistrement</target> <note /> </trans-unit> <trans-unit id="record_struct"> <source>record struct</source> <target state="new">record struct</target> <note /> </trans-unit> <trans-unit id="switch_statement"> <source>switch statement</source> <target state="translated">instruction switch</target> <note>{Locked="switch"} "switch" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="switch_statement_case_clause"> <source>switch statement case clause</source> <target state="translated">clause case d'une instruction switch</target> <note>{Locked="switch"}{Locked="case"} "switch" and "case" are a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="try_block"> <source>try block</source> <target state="translated">bloc try</target> <note>{Locked="try"} "try" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="catch_clause"> <source>catch clause</source> <target state="translated">clause catch</target> <note>{Locked="catch"} "catch" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="filter_clause"> <source>filter clause</source> <target state="translated">clause filter</target> <note /> </trans-unit> <trans-unit id="finally_clause"> <source>finally clause</source> <target state="translated">clause finally</target> <note>{Locked="finally"} "finally" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="fixed_statement"> <source>fixed statement</source> <target state="translated">instruction fixed</target> <note>{Locked="fixed"} "fixed" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="using_declaration"> <source>using declaration</source> <target state="translated">déclaration using</target> <note>{Locked="using"} "using" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="using_statement"> <source>using statement</source> <target state="translated">instruction using</target> <note>{Locked="using"} "using" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="lock_statement"> <source>lock statement</source> <target state="translated">instruction lock</target> <note>{Locked="lock"} "lock" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="foreach_statement"> <source>foreach statement</source> <target state="translated">instruction foreach</target> <note>{Locked="foreach"} "foreach" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="checked_statement"> <source>checked statement</source> <target state="translated">instruction checked</target> <note>{Locked="checked"} "checked" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="unchecked_statement"> <source>unchecked statement</source> <target state="translated">instruction unchecked</target> <note>{Locked="unchecked"} "unchecked" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="await_expression"> <source>await expression</source> <target state="translated">expression await</target> <note>{Locked="await"} "await" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="lambda"> <source>lambda</source> <target state="translated">lambda</target> <note /> </trans-unit> <trans-unit id="anonymous_method"> <source>anonymous method</source> <target state="translated">méthode anonyme</target> <note /> </trans-unit> <trans-unit id="from_clause"> <source>from clause</source> <target state="translated">clause from</target> <note /> </trans-unit> <trans-unit id="join_clause"> <source>join clause</source> <target state="translated">clause join</target> <note>{Locked="join"} "join" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="let_clause"> <source>let clause</source> <target state="translated">clause let</target> <note>{Locked="let"} "let" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="where_clause"> <source>where clause</source> <target state="translated">clause where</target> <note>{Locked="where"} "where" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="orderby_clause"> <source>orderby clause</source> <target state="translated">clause orderby</target> <note>{Locked="orderby"} "orderby" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="select_clause"> <source>select clause</source> <target state="translated">clause select</target> <note>{Locked="select"} "select" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="groupby_clause"> <source>groupby clause</source> <target state="translated">clause groupby</target> <note>{Locked="groupby"} "groupby" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="query_body"> <source>query body</source> <target state="translated">corps de la requête</target> <note /> </trans-unit> <trans-unit id="into_clause"> <source>into clause</source> <target state="translated">clause into</target> <note>{Locked="into"} "into" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="is_pattern"> <source>is pattern</source> <target state="translated">modèle is</target> <note>{Locked="is"} "is" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="deconstruction"> <source>deconstruction</source> <target state="translated">déconstruction</target> <note /> </trans-unit> <trans-unit id="tuple"> <source>tuple</source> <target state="translated">tuple</target> <note /> </trans-unit> <trans-unit id="local_function"> <source>local function</source> <target state="translated">fonction locale</target> <note /> </trans-unit> <trans-unit id="out_var"> <source>out variable</source> <target state="translated">variable out</target> <note>{Locked="out"} "out" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="ref_local_or_expression"> <source>ref local or expression</source> <target state="translated">variable locale ou expression ref</target> <note>{Locked="ref"} "ref" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="global_statement"> <source>global statement</source> <target state="translated">instruction global</target> <note>{Locked="global"} "global" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="using_directive"> <source>using directive</source> <target state="translated">directive using</target> <note /> </trans-unit> <trans-unit id="event_field"> <source>event field</source> <target state="translated">champ d'événement</target> <note /> </trans-unit> <trans-unit id="conversion_operator"> <source>conversion operator</source> <target state="translated">opérateur de conversion</target> <note /> </trans-unit> <trans-unit id="destructor"> <source>destructor</source> <target state="translated">destructeur</target> <note /> </trans-unit> <trans-unit id="indexer"> <source>indexer</source> <target state="translated">indexeur</target> <note /> </trans-unit> <trans-unit id="property_getter"> <source>property getter</source> <target state="translated">méthode getter de propriété</target> <note /> </trans-unit> <trans-unit id="indexer_getter"> <source>indexer getter</source> <target state="translated">méthode getter d'indexeur</target> <note /> </trans-unit> <trans-unit id="property_setter"> <source>property setter</source> <target state="translated">méthode setter de propriété</target> <note /> </trans-unit> <trans-unit id="indexer_setter"> <source>indexer setter</source> <target state="translated">méthode setter d'indexeur</target> <note /> </trans-unit> <trans-unit id="attribute_target"> <source>attribute target</source> <target state="translated">cible d'attribut</target> <note /> </trans-unit> <trans-unit id="_0_does_not_contain_a_constructor_that_takes_that_many_arguments"> <source>'{0}' does not contain a constructor that takes that many arguments.</source> <target state="translated">'{0}' ne contient pas de constructeur prenant en charge autant d'arguments.</target> <note /> </trans-unit> <trans-unit id="The_name_0_does_not_exist_in_the_current_context"> <source>The name '{0}' does not exist in the current context.</source> <target state="translated">Le nom '{0}' n'existe pas dans le contexte actuel.</target> <note /> </trans-unit> <trans-unit id="Hide_base_member"> <source>Hide base member</source> <target state="translated">Masquer le membre de base</target> <note /> </trans-unit> <trans-unit id="Properties"> <source>Properties</source> <target state="translated">Propriétés</target> <note /> </trans-unit> <trans-unit id="Autoselect_disabled_due_to_namespace_declaration"> <source>Autoselect disabled due to namespace declaration.</source> <target state="translated">Sélection automatique désactivée en raison d'une déclaration d'espace de noms.</target> <note /> </trans-unit> <trans-unit id="namespace_name"> <source>&lt;namespace name&gt;</source> <target state="translated">&lt;nom d'espace de noms&gt;</target> <note /> </trans-unit> <trans-unit id="Autoselect_disabled_due_to_type_declaration"> <source>Autoselect disabled due to type declaration.</source> <target state="translated">Sélection automatique désactivée en raison d'une déclaration de type.</target> <note /> </trans-unit> <trans-unit id="Autoselect_disabled_due_to_possible_deconstruction_declaration"> <source>Autoselect disabled due to possible deconstruction declaration.</source> <target state="translated">Sélection automatique désactivée en raison d'une déclaration de déconstruction possible.</target> <note /> </trans-unit> <trans-unit id="Upgrade_this_project_to_csharp_language_version_0"> <source>Upgrade this project to C# language version '{0}'</source> <target state="translated">Mettre à niveau ce projet vers la version de langage C# '{0}'</target> <note /> </trans-unit> <trans-unit id="Upgrade_all_csharp_projects_to_language_version_0"> <source>Upgrade all C# projects to language version '{0}'</source> <target state="translated">Mettre à niveau tous les projets C# vers la version de langage '{0}'</target> <note /> </trans-unit> <trans-unit id="class_name"> <source>&lt;class name&gt;</source> <target state="translated">&lt;nom de la classe&gt;</target> <note /> </trans-unit> <trans-unit id="interface_name"> <source>&lt;interface name&gt;</source> <target state="translated">&lt;nom de l'interface&gt;</target> <note /> </trans-unit> <trans-unit id="designation_name"> <source>&lt;designation name&gt;</source> <target state="translated">&lt;nom de la désignation&gt;</target> <note /> </trans-unit> <trans-unit id="struct_name"> <source>&lt;struct name&gt;</source> <target state="translated">&lt;nom du struct&gt;</target> <note /> </trans-unit> <trans-unit id="Make_method_async"> <source>Make method async</source> <target state="translated">Rendre la méthode async</target> <note /> </trans-unit> <trans-unit id="Make_method_async_remain_void"> <source>Make method async (stay void)</source> <target state="translated">Rendre la méthode asynchrone (rester void)</target> <note /> </trans-unit> <trans-unit id="Name"> <source>&lt;Name&gt;</source> <target state="translated">&lt;Nom&gt;</target> <note /> </trans-unit> <trans-unit id="Autoselect_disabled_due_to_member_declaration"> <source>Autoselect disabled due to member declaration</source> <target state="translated">Sélection automatique désactivée en raison d'une déclaration de membre</target> <note /> </trans-unit> <trans-unit id="Suggested_name"> <source>(Suggested name)</source> <target state="translated">(Nom suggéré)</target> <note /> </trans-unit> <trans-unit id="Remove_unused_function"> <source>Remove unused function</source> <target state="translated">Supprimer la fonction inutilisée</target> <note /> </trans-unit> <trans-unit id="Add_parentheses_around_conditional_expression_in_interpolated_string"> <source>Add parentheses</source> <target state="translated">Ajouter des parenthèses</target> <note /> </trans-unit> <trans-unit id="Convert_to_foreach"> <source>Convert to 'foreach'</source> <target state="translated">Convertir en 'foreach'</target> <note /> </trans-unit> <trans-unit id="Convert_to_for"> <source>Convert to 'for'</source> <target state="translated">Convertir en 'for'</target> <note /> </trans-unit> <trans-unit id="Invert_if"> <source>Invert if</source> <target state="translated">Inverser si</target> <note /> </trans-unit> <trans-unit id="Add_Obsolete"> <source>Add [Obsolete]</source> <target state="translated">Ajouter [obsolète]</target> <note /> </trans-unit> <trans-unit id="Use_0"> <source>Use '{0}'</source> <target state="translated">Utiliser '{0}'</target> <note /> </trans-unit> <trans-unit id="Introduce_using_statement"> <source>Introduce 'using' statement</source> <target state="translated">Introduire l’instruction 'using'</target> <note>{Locked="using"} "using" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="yield_break_statement"> <source>yield break statement</source> <target state="translated">instruction yield break</target> <note>{Locked="yield break"} "yield break" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="yield_return_statement"> <source>yield return statement</source> <target state="translated">instruction yield return</target> <note>{Locked="yield return"} "yield return" is a C# keyword and should not be localized.</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="fr" original="../CSharpFeaturesResources.resx"> <body> <trans-unit id="Add_await"> <source>Add 'await'</source> <target state="translated">Ajouter 'await'</target> <note>{Locked="await"} "await" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Add_await_and_ConfigureAwaitFalse"> <source>Add 'await' and 'ConfigureAwait(false)'</source> <target state="translated">Ajouter 'await' et 'ConfigureAwait(false)'</target> <note>{Locked="await"} "await" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Add_missing_usings"> <source>Add missing usings</source> <target state="translated">Ajouter les instructions using manquantes</target> <note>{Locked="using"} "using" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Add_remove_braces_for_single_line_control_statements"> <source>Add/remove braces for single-line control statements</source> <target state="translated">Ajouter/supprimer des accolades pour les instructions de contrôle sur une seule ligne</target> <note /> </trans-unit> <trans-unit id="Allow_unsafe_code_in_this_project"> <source>Allow unsafe code in this project</source> <target state="translated">Autoriser du code unsafe dans ce projet</target> <note /> </trans-unit> <trans-unit id="Apply_expression_block_body_preferences"> <source>Apply expression/block body preferences</source> <target state="translated">Appliquer les préférences de corps d'expression/de bloc</target> <note /> </trans-unit> <trans-unit id="Apply_implicit_explicit_type_preferences"> <source>Apply implicit/explicit type preferences</source> <target state="translated">Appliquer les préférences de type implicite/explicite</target> <note /> </trans-unit> <trans-unit id="Apply_inline_out_variable_preferences"> <source>Apply inline 'out' variables preferences</source> <target state="translated">Appliquer les préférences des variables 'out' inline</target> <note /> </trans-unit> <trans-unit id="Apply_language_framework_type_preferences"> <source>Apply language/framework type preferences</source> <target state="translated">Appliquer les préférences de type de langage/framework</target> <note /> </trans-unit> <trans-unit id="Apply_this_qualification_preferences"> <source>Apply 'this.' qualification preferences</source> <target state="translated">Appliquer les préférences de qualification 'this.'</target> <note /> </trans-unit> <trans-unit id="Apply_using_directive_placement_preferences"> <source>Apply preferred 'using' placement preferences</source> <target state="translated">Appliquer les préférences de placement de 'using' par défaut</target> <note>'using' is a C# keyword and should not be localized</note> </trans-unit> <trans-unit id="Assign_out_parameters"> <source>Assign 'out' parameters</source> <target state="translated">Assigner des paramètres 'out'</target> <note>{Locked="out"} "out" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Assign_out_parameters_at_start"> <source>Assign 'out' parameters (at start)</source> <target state="translated">Assigner des paramètres 'out' (au début)</target> <note>{Locked="out"} "out" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Assign_to_0"> <source>Assign to '{0}'</source> <target state="translated">Affecter à '{0}'</target> <note /> </trans-unit> <trans-unit id="Autoselect_disabled_due_to_potential_pattern_variable_declaration"> <source>Autoselect disabled due to potential pattern variable declaration.</source> <target state="translated">Sélection automatique désactivée en raison d'une déclaration de variable de modèle éventuelle.</target> <note /> </trans-unit> <trans-unit id="Change_to_as_expression"> <source>Change to 'as' expression</source> <target state="translated">Changer en expression 'as'</target> <note /> </trans-unit> <trans-unit id="Change_to_cast"> <source>Change to cast</source> <target state="translated">Changer en cast</target> <note /> </trans-unit> <trans-unit id="Compare_to_0"> <source>Compare to '{0}'</source> <target state="translated">Comparer à '{0}'</target> <note /> </trans-unit> <trans-unit id="Convert_to_method"> <source>Convert to method</source> <target state="translated">Convertir en méthode</target> <note /> </trans-unit> <trans-unit id="Convert_to_regular_string"> <source>Convert to regular string</source> <target state="translated">Convertir en chaîne classique</target> <note /> </trans-unit> <trans-unit id="Convert_to_switch_expression"> <source>Convert to 'switch' expression</source> <target state="translated">Convertir en expression 'switch'</target> <note /> </trans-unit> <trans-unit id="Convert_to_switch_statement"> <source>Convert to 'switch' statement</source> <target state="translated">Convertir en instruction « switch »</target> <note /> </trans-unit> <trans-unit id="Convert_to_verbatim_string"> <source>Convert to verbatim string</source> <target state="translated">Convertir en chaîne verbatim</target> <note /> </trans-unit> <trans-unit id="Declare_as_nullable"> <source>Declare as nullable</source> <target state="translated">Déclarer comme nullable</target> <note /> </trans-unit> <trans-unit id="Fix_return_type"> <source>Fix return type</source> <target state="translated">Corriger le type de retour</target> <note /> </trans-unit> <trans-unit id="Inline_temporary_variable"> <source>Inline temporary variable</source> <target state="translated">Variable temporaire inline</target> <note /> </trans-unit> <trans-unit id="Conflict_s_detected"> <source>Conflict(s) detected.</source> <target state="translated">Conflit(s) détecté(s).</target> <note /> </trans-unit> <trans-unit id="Make_private_field_readonly_when_possible"> <source>Make private fields readonly when possible</source> <target state="translated">Configurer les champs privés en lecture seule quand cela est possible</target> <note /> </trans-unit> <trans-unit id="Make_ref_struct"> <source>Make 'ref struct'</source> <target state="translated">Définir 'ref struct'</target> <note>{Locked="ref"}{Locked="struct"} "ref" and "struct" are C# keywords and should not be localized.</note> </trans-unit> <trans-unit id="Remove_in_keyword"> <source>Remove 'in' keyword</source> <target state="translated">Supprimer le mot clé 'in'</target> <note>{Locked="in"} "in" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Remove_new_modifier"> <source>Remove 'new' modifier</source> <target state="translated">Supprimer le modificateur 'new'</target> <note /> </trans-unit> <trans-unit id="Reverse_for_statement"> <source>Reverse 'for' statement</source> <target state="translated">Inverser l'instruction 'for'</target> <note>{Locked="for"} "for" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Simplify_lambda_expression"> <source>Simplify lambda expression</source> <target state="translated">Simplifier l'expression lambda</target> <note /> </trans-unit> <trans-unit id="Simplify_all_occurrences"> <source>Simplify all occurrences</source> <target state="translated">Simplifier toutes les occurrences</target> <note /> </trans-unit> <trans-unit id="Sort_accessibility_modifiers"> <source>Sort accessibility modifiers</source> <target state="translated">Trier les modificateurs d'accessibilité</target> <note /> </trans-unit> <trans-unit id="Unseal_class_0"> <source>Unseal class '{0}'</source> <target state="translated">Classe unsealed '{0}'</target> <note /> </trans-unit> <trans-unit id="Warning_Inlining_temporary_into_conditional_method_call"> <source>Warning: Inlining temporary into conditional method call.</source> <target state="translated">Avertissement : Inlining temporaire dans un appel de méthode conditionnel.</target> <note /> </trans-unit> <trans-unit id="Warning_Inlining_temporary_variable_may_change_code_meaning"> <source>Warning: Inlining temporary variable may change code meaning.</source> <target state="translated">Avertissement : L'inlining sur une variable temporaire peut changer la signification du code.</target> <note /> </trans-unit> <trans-unit id="asynchronous_foreach_statement"> <source>asynchronous foreach statement</source> <target state="translated">instruction foreach asynchrone</target> <note>{Locked="foreach"} "foreach" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="asynchronous_using_declaration"> <source>asynchronous using declaration</source> <target state="translated">déclaration using asynchrone</target> <note>{Locked="using"} "using" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="extern_alias"> <source>extern alias</source> <target state="translated">alias externe</target> <note /> </trans-unit> <trans-unit id="lambda_expression"> <source>&lt;lambda expression&gt;</source> <target state="translated">&lt;expression lambda&gt;</target> <note /> </trans-unit> <trans-unit id="Autoselect_disabled_due_to_potential_lambda_declaration"> <source>Autoselect disabled due to potential lambda declaration.</source> <target state="translated">Sélection automatique désactivée en raison d'une déclaration lambda éventuelle.</target> <note /> </trans-unit> <trans-unit id="local_variable_declaration"> <source>local variable declaration</source> <target state="translated">déclaration de variable locale</target> <note /> </trans-unit> <trans-unit id="member_name"> <source>&lt;member name&gt; = </source> <target state="translated">&lt;nom de membre&gt; =</target> <note /> </trans-unit> <trans-unit id="Autoselect_disabled_due_to_possible_explicitly_named_anonymous_type_member_creation"> <source>Autoselect disabled due to possible explicitly named anonymous type member creation.</source> <target state="translated">Sélection automatique désactivée en raison de la création éventuelle d'un membre de type anonyme nommé explicitement.</target> <note /> </trans-unit> <trans-unit id="element_name"> <source>&lt;element name&gt; : </source> <target state="translated">&lt;nom d'élément&gt; :</target> <note /> </trans-unit> <trans-unit id="Autoselect_disabled_due_to_possible_tuple_type_element_creation"> <source>Autoselect disabled due to possible tuple type element creation.</source> <target state="translated">Sélection automatique désactivée en raison de la création possible d'un élément de type tuple.</target> <note /> </trans-unit> <trans-unit id="pattern_variable"> <source>&lt;pattern variable&gt;</source> <target state="translated">&lt;variable de modèle&gt;</target> <note /> </trans-unit> <trans-unit id="range_variable"> <source>&lt;range variable&gt;</source> <target state="translated">&lt;variable de plage&gt;</target> <note /> </trans-unit> <trans-unit id="Autoselect_disabled_due_to_potential_range_variable_declaration"> <source>Autoselect disabled due to potential range variable declaration.</source> <target state="translated">Sélection automatique désactivée en raison d'une déclaration de variable de plage éventuelle.</target> <note /> </trans-unit> <trans-unit id="Simplify_name_0"> <source>Simplify name '{0}'</source> <target state="translated">Simplifier le nom '{0}'</target> <note /> </trans-unit> <trans-unit id="Simplify_member_access_0"> <source>Simplify member access '{0}'</source> <target state="translated">Simplifier l'accès au membre '{0}'</target> <note /> </trans-unit> <trans-unit id="Remove_this_qualification"> <source>Remove 'this' qualification</source> <target state="translated">Supprimer la qualification 'this'</target> <note /> </trans-unit> <trans-unit id="Name_can_be_simplified"> <source>Name can be simplified</source> <target state="translated">Le nom peut être simplifié</target> <note /> </trans-unit> <trans-unit id="Can_t_determine_valid_range_of_statements_to_extract"> <source>Can't determine valid range of statements to extract</source> <target state="translated">Impossible de déterminer la plage valide d'instructions à extraire</target> <note /> </trans-unit> <trans-unit id="Not_all_code_paths_return"> <source>Not all code paths return</source> <target state="translated">Tous les chemins du code n'ont pas été retournés</target> <note /> </trans-unit> <trans-unit id="Selection_does_not_contain_a_valid_node"> <source>Selection does not contain a valid node</source> <target state="translated">La sélection ne contient pas un nœud valide</target> <note /> </trans-unit> <trans-unit id="Invalid_selection"> <source>Invalid selection.</source> <target state="translated">Sélection incorrecte.</target> <note /> </trans-unit> <trans-unit id="Contains_invalid_selection"> <source>Contains invalid selection.</source> <target state="translated">Contient une sélection incorrecte.</target> <note /> </trans-unit> <trans-unit id="The_selection_contains_syntactic_errors"> <source>The selection contains syntactic errors</source> <target state="translated">La sélection contient des erreurs syntaxiques</target> <note /> </trans-unit> <trans-unit id="Selection_can_not_cross_over_preprocessor_directives"> <source>Selection can not cross over preprocessor directives.</source> <target state="translated">La sélection ne peut pas traverser plusieurs directives de préprocesseur.</target> <note /> </trans-unit> <trans-unit id="Selection_can_not_contain_a_yield_statement"> <source>Selection can not contain a yield statement.</source> <target state="translated">La sélection ne contient pas d'instruction yield.</target> <note /> </trans-unit> <trans-unit id="Selection_can_not_contain_throw_statement"> <source>Selection can not contain throw statement.</source> <target state="translated">La sélection ne contient pas d'instruction throw.</target> <note /> </trans-unit> <trans-unit id="Selection_can_not_be_part_of_constant_initializer_expression"> <source>Selection can not be part of constant initializer expression.</source> <target state="translated">La sélection ne peut pas faire partie d'une expression d'initialiseur de constante.</target> <note /> </trans-unit> <trans-unit id="Selection_can_not_contain_a_pattern_expression"> <source>Selection can not contain a pattern expression.</source> <target state="translated">La sélection ne peut pas contenir une expression de modèle.</target> <note /> </trans-unit> <trans-unit id="The_selected_code_is_inside_an_unsafe_context"> <source>The selected code is inside an unsafe context.</source> <target state="translated">Le code sélectionné se trouve dans un contexte unsafe.</target> <note /> </trans-unit> <trans-unit id="No_valid_statement_range_to_extract"> <source>No valid statement range to extract</source> <target state="translated">Aucune plage valide d'instructions à extraire</target> <note /> </trans-unit> <trans-unit id="deprecated"> <source>deprecated</source> <target state="translated">déconseillé</target> <note /> </trans-unit> <trans-unit id="extension"> <source>extension</source> <target state="translated">Extension</target> <note /> </trans-unit> <trans-unit id="awaitable"> <source>awaitable</source> <target state="translated">pouvant être attendu(e)</target> <note /> </trans-unit> <trans-unit id="awaitable_extension"> <source>awaitable, extension</source> <target state="translated">awaitable, extension</target> <note /> </trans-unit> <trans-unit id="Organize_Usings"> <source>Organize Usings</source> <target state="translated">Organiser les instructions Using</target> <note /> </trans-unit> <trans-unit id="Insert_await"> <source>Insert 'await'.</source> <target state="translated">Insérez 'await'.</target> <note /> </trans-unit> <trans-unit id="Make_0_return_Task_instead_of_void"> <source>Make {0} return Task instead of void.</source> <target state="translated">{0} doit retourner Task au lieu de void.</target> <note /> </trans-unit> <trans-unit id="Change_return_type_from_0_to_1"> <source>Change return type from {0} to {1}</source> <target state="translated">Changer le type de retour de {0} en {1}</target> <note /> </trans-unit> <trans-unit id="Replace_return_with_yield_return"> <source>Replace return with yield return</source> <target state="translated">Remplacer return par yield return</target> <note /> </trans-unit> <trans-unit id="Generate_explicit_conversion_operator_in_0"> <source>Generate explicit conversion operator in '{0}'</source> <target state="translated">Générer l’opérateur de conversion explicite dans « {0} »</target> <note /> </trans-unit> <trans-unit id="Generate_implicit_conversion_operator_in_0"> <source>Generate implicit conversion operator in '{0}'</source> <target state="translated">Générer l’opérateur de conversion implicite dans « {0} »</target> <note /> </trans-unit> <trans-unit id="record_"> <source>record</source> <target state="translated">enregistrement</target> <note /> </trans-unit> <trans-unit id="record_struct"> <source>record struct</source> <target state="new">record struct</target> <note /> </trans-unit> <trans-unit id="switch_statement"> <source>switch statement</source> <target state="translated">instruction switch</target> <note>{Locked="switch"} "switch" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="switch_statement_case_clause"> <source>switch statement case clause</source> <target state="translated">clause case d'une instruction switch</target> <note>{Locked="switch"}{Locked="case"} "switch" and "case" are a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="try_block"> <source>try block</source> <target state="translated">bloc try</target> <note>{Locked="try"} "try" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="catch_clause"> <source>catch clause</source> <target state="translated">clause catch</target> <note>{Locked="catch"} "catch" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="filter_clause"> <source>filter clause</source> <target state="translated">clause filter</target> <note /> </trans-unit> <trans-unit id="finally_clause"> <source>finally clause</source> <target state="translated">clause finally</target> <note>{Locked="finally"} "finally" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="fixed_statement"> <source>fixed statement</source> <target state="translated">instruction fixed</target> <note>{Locked="fixed"} "fixed" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="using_declaration"> <source>using declaration</source> <target state="translated">déclaration using</target> <note>{Locked="using"} "using" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="using_statement"> <source>using statement</source> <target state="translated">instruction using</target> <note>{Locked="using"} "using" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="lock_statement"> <source>lock statement</source> <target state="translated">instruction lock</target> <note>{Locked="lock"} "lock" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="foreach_statement"> <source>foreach statement</source> <target state="translated">instruction foreach</target> <note>{Locked="foreach"} "foreach" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="checked_statement"> <source>checked statement</source> <target state="translated">instruction checked</target> <note>{Locked="checked"} "checked" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="unchecked_statement"> <source>unchecked statement</source> <target state="translated">instruction unchecked</target> <note>{Locked="unchecked"} "unchecked" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="await_expression"> <source>await expression</source> <target state="translated">expression await</target> <note>{Locked="await"} "await" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="lambda"> <source>lambda</source> <target state="translated">lambda</target> <note /> </trans-unit> <trans-unit id="anonymous_method"> <source>anonymous method</source> <target state="translated">méthode anonyme</target> <note /> </trans-unit> <trans-unit id="from_clause"> <source>from clause</source> <target state="translated">clause from</target> <note /> </trans-unit> <trans-unit id="join_clause"> <source>join clause</source> <target state="translated">clause join</target> <note>{Locked="join"} "join" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="let_clause"> <source>let clause</source> <target state="translated">clause let</target> <note>{Locked="let"} "let" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="where_clause"> <source>where clause</source> <target state="translated">clause where</target> <note>{Locked="where"} "where" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="orderby_clause"> <source>orderby clause</source> <target state="translated">clause orderby</target> <note>{Locked="orderby"} "orderby" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="select_clause"> <source>select clause</source> <target state="translated">clause select</target> <note>{Locked="select"} "select" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="groupby_clause"> <source>groupby clause</source> <target state="translated">clause groupby</target> <note>{Locked="groupby"} "groupby" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="query_body"> <source>query body</source> <target state="translated">corps de la requête</target> <note /> </trans-unit> <trans-unit id="into_clause"> <source>into clause</source> <target state="translated">clause into</target> <note>{Locked="into"} "into" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="is_pattern"> <source>is pattern</source> <target state="translated">modèle is</target> <note>{Locked="is"} "is" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="deconstruction"> <source>deconstruction</source> <target state="translated">déconstruction</target> <note /> </trans-unit> <trans-unit id="tuple"> <source>tuple</source> <target state="translated">tuple</target> <note /> </trans-unit> <trans-unit id="local_function"> <source>local function</source> <target state="translated">fonction locale</target> <note /> </trans-unit> <trans-unit id="out_var"> <source>out variable</source> <target state="translated">variable out</target> <note>{Locked="out"} "out" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="ref_local_or_expression"> <source>ref local or expression</source> <target state="translated">variable locale ou expression ref</target> <note>{Locked="ref"} "ref" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="global_statement"> <source>global statement</source> <target state="translated">instruction global</target> <note>{Locked="global"} "global" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="using_directive"> <source>using directive</source> <target state="translated">directive using</target> <note /> </trans-unit> <trans-unit id="event_field"> <source>event field</source> <target state="translated">champ d'événement</target> <note /> </trans-unit> <trans-unit id="conversion_operator"> <source>conversion operator</source> <target state="translated">opérateur de conversion</target> <note /> </trans-unit> <trans-unit id="destructor"> <source>destructor</source> <target state="translated">destructeur</target> <note /> </trans-unit> <trans-unit id="indexer"> <source>indexer</source> <target state="translated">indexeur</target> <note /> </trans-unit> <trans-unit id="property_getter"> <source>property getter</source> <target state="translated">méthode getter de propriété</target> <note /> </trans-unit> <trans-unit id="indexer_getter"> <source>indexer getter</source> <target state="translated">méthode getter d'indexeur</target> <note /> </trans-unit> <trans-unit id="property_setter"> <source>property setter</source> <target state="translated">méthode setter de propriété</target> <note /> </trans-unit> <trans-unit id="indexer_setter"> <source>indexer setter</source> <target state="translated">méthode setter d'indexeur</target> <note /> </trans-unit> <trans-unit id="attribute_target"> <source>attribute target</source> <target state="translated">cible d'attribut</target> <note /> </trans-unit> <trans-unit id="_0_does_not_contain_a_constructor_that_takes_that_many_arguments"> <source>'{0}' does not contain a constructor that takes that many arguments.</source> <target state="translated">'{0}' ne contient pas de constructeur prenant en charge autant d'arguments.</target> <note /> </trans-unit> <trans-unit id="The_name_0_does_not_exist_in_the_current_context"> <source>The name '{0}' does not exist in the current context.</source> <target state="translated">Le nom '{0}' n'existe pas dans le contexte actuel.</target> <note /> </trans-unit> <trans-unit id="Hide_base_member"> <source>Hide base member</source> <target state="translated">Masquer le membre de base</target> <note /> </trans-unit> <trans-unit id="Properties"> <source>Properties</source> <target state="translated">Propriétés</target> <note /> </trans-unit> <trans-unit id="Autoselect_disabled_due_to_namespace_declaration"> <source>Autoselect disabled due to namespace declaration.</source> <target state="translated">Sélection automatique désactivée en raison d'une déclaration d'espace de noms.</target> <note /> </trans-unit> <trans-unit id="namespace_name"> <source>&lt;namespace name&gt;</source> <target state="translated">&lt;nom d'espace de noms&gt;</target> <note /> </trans-unit> <trans-unit id="Autoselect_disabled_due_to_type_declaration"> <source>Autoselect disabled due to type declaration.</source> <target state="translated">Sélection automatique désactivée en raison d'une déclaration de type.</target> <note /> </trans-unit> <trans-unit id="Autoselect_disabled_due_to_possible_deconstruction_declaration"> <source>Autoselect disabled due to possible deconstruction declaration.</source> <target state="translated">Sélection automatique désactivée en raison d'une déclaration de déconstruction possible.</target> <note /> </trans-unit> <trans-unit id="Upgrade_this_project_to_csharp_language_version_0"> <source>Upgrade this project to C# language version '{0}'</source> <target state="translated">Mettre à niveau ce projet vers la version de langage C# '{0}'</target> <note /> </trans-unit> <trans-unit id="Upgrade_all_csharp_projects_to_language_version_0"> <source>Upgrade all C# projects to language version '{0}'</source> <target state="translated">Mettre à niveau tous les projets C# vers la version de langage '{0}'</target> <note /> </trans-unit> <trans-unit id="class_name"> <source>&lt;class name&gt;</source> <target state="translated">&lt;nom de la classe&gt;</target> <note /> </trans-unit> <trans-unit id="interface_name"> <source>&lt;interface name&gt;</source> <target state="translated">&lt;nom de l'interface&gt;</target> <note /> </trans-unit> <trans-unit id="designation_name"> <source>&lt;designation name&gt;</source> <target state="translated">&lt;nom de la désignation&gt;</target> <note /> </trans-unit> <trans-unit id="struct_name"> <source>&lt;struct name&gt;</source> <target state="translated">&lt;nom du struct&gt;</target> <note /> </trans-unit> <trans-unit id="Make_method_async"> <source>Make method async</source> <target state="translated">Rendre la méthode async</target> <note /> </trans-unit> <trans-unit id="Make_method_async_remain_void"> <source>Make method async (stay void)</source> <target state="translated">Rendre la méthode asynchrone (rester void)</target> <note /> </trans-unit> <trans-unit id="Name"> <source>&lt;Name&gt;</source> <target state="translated">&lt;Nom&gt;</target> <note /> </trans-unit> <trans-unit id="Autoselect_disabled_due_to_member_declaration"> <source>Autoselect disabled due to member declaration</source> <target state="translated">Sélection automatique désactivée en raison d'une déclaration de membre</target> <note /> </trans-unit> <trans-unit id="Suggested_name"> <source>(Suggested name)</source> <target state="translated">(Nom suggéré)</target> <note /> </trans-unit> <trans-unit id="Remove_unused_function"> <source>Remove unused function</source> <target state="translated">Supprimer la fonction inutilisée</target> <note /> </trans-unit> <trans-unit id="Add_parentheses_around_conditional_expression_in_interpolated_string"> <source>Add parentheses</source> <target state="translated">Ajouter des parenthèses</target> <note /> </trans-unit> <trans-unit id="Convert_to_foreach"> <source>Convert to 'foreach'</source> <target state="translated">Convertir en 'foreach'</target> <note /> </trans-unit> <trans-unit id="Convert_to_for"> <source>Convert to 'for'</source> <target state="translated">Convertir en 'for'</target> <note /> </trans-unit> <trans-unit id="Invert_if"> <source>Invert if</source> <target state="translated">Inverser si</target> <note /> </trans-unit> <trans-unit id="Add_Obsolete"> <source>Add [Obsolete]</source> <target state="translated">Ajouter [obsolète]</target> <note /> </trans-unit> <trans-unit id="Use_0"> <source>Use '{0}'</source> <target state="translated">Utiliser '{0}'</target> <note /> </trans-unit> <trans-unit id="Introduce_using_statement"> <source>Introduce 'using' statement</source> <target state="translated">Introduire l’instruction 'using'</target> <note>{Locked="using"} "using" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="yield_break_statement"> <source>yield break statement</source> <target state="translated">instruction yield break</target> <note>{Locked="yield break"} "yield break" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="yield_return_statement"> <source>yield return statement</source> <target state="translated">instruction yield return</target> <note>{Locked="yield return"} "yield return" is a C# keyword and should not be localized.</note> </trans-unit> </body> </file> </xliff>
-1
dotnet/roslyn
55,262
Fix LSP completions when all items have default commit characters
Fixes an exception stack trace seen in https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1362284 Also fixes behavior of promotion of commit characters to the list to include default commit characters
dibarbet
2021-07-30T02:43:35Z
2021-07-30T21:21:47Z
2f7dffa534aceb92e9767568e88535c926588d12
65ee073bf6cea571a68193793420ecee60752711
Fix LSP completions when all items have default commit characters. Fixes an exception stack trace seen in https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1362284 Also fixes behavior of promotion of commit characters to the list to include default commit characters
./src/Compilers/Server/VBCSCompiler/VisualBasicCompilerServer.cs
// Licensed to the .NET Foundation under one or more agreements. // 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.Globalization; using System.IO; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.VisualBasic; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CompilerServer { internal sealed class VisualBasicCompilerServer : VisualBasicCompiler { private readonly Func<string, MetadataReferenceProperties, PortableExecutableReference> _metadataProvider; internal VisualBasicCompilerServer(Func<string, MetadataReferenceProperties, PortableExecutableReference> metadataProvider, string[] args, BuildPaths buildPaths, string? libDirectory, IAnalyzerAssemblyLoader analyzerLoader) : this(metadataProvider, Path.Combine(buildPaths.ClientDirectory, ResponseFileName), args, buildPaths, libDirectory, analyzerLoader) { } internal VisualBasicCompilerServer(Func<string, MetadataReferenceProperties, PortableExecutableReference> metadataProvider, string? responseFile, string[] args, BuildPaths buildPaths, string? libDirectory, IAnalyzerAssemblyLoader analyzerLoader) : base(VisualBasicCommandLineParser.Default, responseFile, args, buildPaths, libDirectory, analyzerLoader) { _metadataProvider = metadataProvider; } internal override Func<string, MetadataReferenceProperties, PortableExecutableReference> GetMetadataProvider() { return _metadataProvider; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Globalization; using System.IO; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.VisualBasic; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CompilerServer { internal sealed class VisualBasicCompilerServer : VisualBasicCompiler { private readonly Func<string, MetadataReferenceProperties, PortableExecutableReference> _metadataProvider; internal VisualBasicCompilerServer(Func<string, MetadataReferenceProperties, PortableExecutableReference> metadataProvider, string[] args, BuildPaths buildPaths, string? libDirectory, IAnalyzerAssemblyLoader analyzerLoader) : this(metadataProvider, Path.Combine(buildPaths.ClientDirectory, ResponseFileName), args, buildPaths, libDirectory, analyzerLoader) { } internal VisualBasicCompilerServer(Func<string, MetadataReferenceProperties, PortableExecutableReference> metadataProvider, string? responseFile, string[] args, BuildPaths buildPaths, string? libDirectory, IAnalyzerAssemblyLoader analyzerLoader) : base(VisualBasicCommandLineParser.Default, responseFile, args, buildPaths, libDirectory, analyzerLoader) { _metadataProvider = metadataProvider; } internal override Func<string, MetadataReferenceProperties, PortableExecutableReference> GetMetadataProvider() { return _metadataProvider; } } }
-1
dotnet/roslyn
55,256
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-30T00:02:02Z
2021-07-30T09:17:54Z
6ce9c0048d37026337701fac035ac0745f6fe49f
88b59775dc6375635957ef229116460f290072aa
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Compilers/CSharp/Portable/Binder/Binder_Conversions.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { internal partial class Binder { internal BoundExpression CreateConversion( BoundExpression source, TypeSymbol destination, BindingDiagnosticBag diagnostics) { CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); var conversion = Conversions.ClassifyConversionFromExpression(source, destination, ref useSiteInfo); diagnostics.Add(source.Syntax, useSiteInfo); return CreateConversion(source.Syntax, source, conversion, isCast: false, conversionGroupOpt: null, destination: destination, diagnostics: diagnostics); } internal BoundExpression CreateConversion( BoundExpression source, Conversion conversion, TypeSymbol destination, BindingDiagnosticBag diagnostics) { return CreateConversion(source.Syntax, source, conversion, isCast: false, conversionGroupOpt: null, destination: destination, diagnostics: diagnostics); } internal BoundExpression CreateConversion( SyntaxNode syntax, BoundExpression source, Conversion conversion, bool isCast, ConversionGroup? conversionGroupOpt, TypeSymbol destination, BindingDiagnosticBag diagnostics) { return CreateConversion(syntax, source, conversion, isCast: isCast, conversionGroupOpt, source.WasCompilerGenerated, destination, diagnostics); } protected BoundExpression CreateConversion( SyntaxNode syntax, BoundExpression source, Conversion conversion, bool isCast, ConversionGroup? conversionGroupOpt, bool wasCompilerGenerated, TypeSymbol destination, BindingDiagnosticBag diagnostics, bool hasErrors = false) { RoslynDebug.Assert(source != null); RoslynDebug.Assert((object)destination != null); RoslynDebug.Assert(!isCast || conversionGroupOpt != null); if (conversion.IsIdentity) { if (source is BoundTupleLiteral sourceTuple) { NamedTypeSymbol.ReportTupleNamesMismatchesIfAny(destination, sourceTuple, diagnostics); } // identity tuple and switch conversions result in a converted expression // to indicate that such conversions are no longer applicable. source = BindToNaturalType(source, diagnostics); RoslynDebug.Assert(source.Type is object); // We need to preserve any conversion that changes the type (even identity conversions, like object->dynamic), // or that was explicitly written in code (so that GetSemanticInfo can find the syntax in the bound tree). if (!isCast && source.Type.Equals(destination, TypeCompareKind.IgnoreNullableModifiersForReferenceTypes)) { return source; } } if (conversion.IsMethodGroup) { return CreateMethodGroupConversion(syntax, source, conversion, isCast: isCast, conversionGroupOpt, destination, diagnostics); } // Obsolete diagnostics for method group are reported as part of creating the method group conversion. ReportDiagnosticsIfObsolete(diagnostics, conversion, syntax, hasBaseReceiver: false); CheckConstraintLanguageVersionAndRuntimeSupportForConversion(syntax, conversion, diagnostics); if (conversion.IsAnonymousFunction && source.Kind == BoundKind.UnboundLambda) { return CreateAnonymousFunctionConversion(syntax, source, conversion, isCast: isCast, conversionGroupOpt, destination, diagnostics); } if (conversion.IsStackAlloc) { return CreateStackAllocConversion(syntax, source, conversion, isCast, conversionGroupOpt, destination, diagnostics); } if (conversion.IsTupleLiteralConversion || (conversion.IsNullable && conversion.UnderlyingConversions[0].IsTupleLiteralConversion)) { return CreateTupleLiteralConversion(syntax, (BoundTupleLiteral)source, conversion, isCast: isCast, conversionGroupOpt, destination, diagnostics); } if (conversion.Kind == ConversionKind.SwitchExpression) { var convertedSwitch = ConvertSwitchExpression((BoundUnconvertedSwitchExpression)source, destination, conversionIfTargetTyped: conversion, diagnostics); return new BoundConversion( syntax, convertedSwitch, conversion, CheckOverflowAtRuntime, explicitCastInCode: isCast && !wasCompilerGenerated, conversionGroupOpt, convertedSwitch.ConstantValue, destination, hasErrors); } if (conversion.Kind == ConversionKind.ConditionalExpression) { var convertedConditional = ConvertConditionalExpression((BoundUnconvertedConditionalOperator)source, destination, conversionIfTargetTyped: conversion, diagnostics); return new BoundConversion( syntax, convertedConditional, conversion, CheckOverflowAtRuntime, explicitCastInCode: isCast && !wasCompilerGenerated, conversionGroupOpt, convertedConditional.ConstantValue, destination, hasErrors); } if (conversion.Kind == ConversionKind.InterpolatedString) { var unconvertedSource = (BoundUnconvertedInterpolatedString)source; source = new BoundInterpolatedString( unconvertedSource.Syntax, interpolationData: null, BindInterpolatedStringParts(unconvertedSource, diagnostics), unconvertedSource.ConstantValue, unconvertedSource.Type, unconvertedSource.HasErrors); } if (conversion.Kind == ConversionKind.InterpolatedStringHandler) { var unconvertedSource = (BoundUnconvertedInterpolatedString)source; return new BoundConversion( syntax, BindUnconvertedInterpolatedStringToHandlerType(unconvertedSource, (NamedTypeSymbol)destination, diagnostics, isHandlerConversion: true), conversion, @checked: CheckOverflowAtRuntime, explicitCastInCode: isCast && !wasCompilerGenerated, conversionGroupOpt, constantValueOpt: null, destination); } if (source.Kind == BoundKind.UnconvertedSwitchExpression) { TypeSymbol? type = source.Type; if (type is null) { Debug.Assert(!conversion.Exists); type = CreateErrorType(); hasErrors = true; } source = ConvertSwitchExpression((BoundUnconvertedSwitchExpression)source, type, conversionIfTargetTyped: null, diagnostics, hasErrors); if (destination.Equals(type, TypeCompareKind.ConsiderEverything) && wasCompilerGenerated) { return source; } } if (conversion.IsObjectCreation) { return ConvertObjectCreationExpression(syntax, (BoundUnconvertedObjectCreationExpression)source, isCast, destination, diagnostics); } if (source.Kind == BoundKind.UnconvertedConditionalOperator) { TypeSymbol? type = source.Type; if (type is null) { Debug.Assert(!conversion.Exists); type = CreateErrorType(); hasErrors = true; } source = ConvertConditionalExpression((BoundUnconvertedConditionalOperator)source, type, conversionIfTargetTyped: null, diagnostics, hasErrors); if (destination.Equals(type, TypeCompareKind.ConsiderEverything) && wasCompilerGenerated) { return source; } } if (conversion.IsUserDefined) { // User-defined conversions are likely to be represented as multiple // BoundConversion instances so a ConversionGroup is necessary. return CreateUserDefinedConversion(syntax, source, conversion, isCast: isCast, conversionGroupOpt ?? new ConversionGroup(conversion), destination, diagnostics, hasErrors); } ConstantValue? constantValue = this.FoldConstantConversion(syntax, source, conversion, destination, diagnostics); if (conversion.Kind == ConversionKind.DefaultLiteral) { source = new BoundDefaultExpression(source.Syntax, targetType: null, constantValue, type: destination) .WithSuppression(source.IsSuppressed); } return new BoundConversion( syntax, BindToNaturalType(source, diagnostics), conversion, @checked: CheckOverflowAtRuntime, explicitCastInCode: isCast && !wasCompilerGenerated, conversionGroupOpt, constantValueOpt: constantValue, type: destination, hasErrors: hasErrors) { WasCompilerGenerated = wasCompilerGenerated }; } internal void CheckConstraintLanguageVersionAndRuntimeSupportForConversion(SyntaxNodeOrToken syntax, Conversion conversion, BindingDiagnosticBag diagnostics) { if (conversion.IsUserDefined && conversion.Method is MethodSymbol method && method.IsStatic && method.IsAbstract) { Debug.Assert(conversion.ConstrainedToTypeOpt is TypeParameterSymbol); if (Compilation.SourceModule != method.ContainingModule) { Debug.Assert(syntax.SyntaxTree is object); CheckFeatureAvailability(syntax.SyntaxTree, MessageID.IDS_FeatureStaticAbstractMembersInInterfaces, diagnostics, syntax.GetLocation()!); if (!Compilation.Assembly.RuntimeSupportsStaticAbstractMembersInInterfaces) { Error(diagnostics, ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, syntax); } } } } private BoundExpression ConvertObjectCreationExpression(SyntaxNode syntax, BoundUnconvertedObjectCreationExpression node, bool isCast, TypeSymbol destination, BindingDiagnosticBag diagnostics) { var arguments = AnalyzedArguments.GetInstance(node.Arguments, node.ArgumentRefKindsOpt, node.ArgumentNamesOpt); BoundExpression expr = BindObjectCreationExpression(node, destination.StrippedType(), arguments, diagnostics); if (destination.IsNullableType()) { // We manually create an ImplicitNullable conversion // if the destination is nullable, in which case we // target the underlying type e.g. `S? x = new();` // is actually identical to `S? x = new S();`. CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); var conversion = Conversions.ClassifyStandardConversion(null, expr.Type, destination, ref useSiteInfo); expr = new BoundConversion( node.Syntax, operand: expr, conversion: conversion, @checked: false, explicitCastInCode: isCast, conversionGroupOpt: new ConversionGroup(conversion), constantValueOpt: expr.ConstantValue, type: destination); diagnostics.Add(syntax, useSiteInfo); } arguments.Free(); return expr; } private BoundExpression BindObjectCreationExpression(BoundUnconvertedObjectCreationExpression node, TypeSymbol type, AnalyzedArguments arguments, BindingDiagnosticBag diagnostics) { var syntax = node.Syntax; switch (type.TypeKind) { case TypeKind.Enum: case TypeKind.Struct: case TypeKind.Class when !type.IsAnonymousType: // We don't want to enable object creation with unspeakable types return BindClassCreationExpression(syntax, type.Name, typeNode: syntax, (NamedTypeSymbol)type, arguments, diagnostics, node.InitializerOpt, wasTargetTyped: true); case TypeKind.TypeParameter: return BindTypeParameterCreationExpression(syntax, (TypeParameterSymbol)type, arguments, node.InitializerOpt, typeSyntax: syntax, diagnostics); case TypeKind.Delegate: return BindDelegateCreationExpression(syntax, (NamedTypeSymbol)type, arguments, node.InitializerOpt, diagnostics); case TypeKind.Interface: return BindInterfaceCreationExpression(syntax, (NamedTypeSymbol)type, diagnostics, typeNode: syntax, arguments, node.InitializerOpt, wasTargetTyped: true); case TypeKind.Array: case TypeKind.Class: case TypeKind.Dynamic: Error(diagnostics, ErrorCode.ERR_ImplicitObjectCreationIllegalTargetType, syntax, type); goto case TypeKind.Error; case TypeKind.Pointer: case TypeKind.FunctionPointer: Error(diagnostics, ErrorCode.ERR_UnsafeTypeInObjectCreation, syntax, type); goto case TypeKind.Error; case TypeKind.Error: return MakeBadExpressionForObjectCreation(syntax, type, arguments, node.InitializerOpt, typeSyntax: syntax, diagnostics); case var v: throw ExceptionUtilities.UnexpectedValue(v); } } /// <summary> /// Rewrite the subexpressions in a conditional expression to convert the whole thing to the destination type. /// </summary> private BoundExpression ConvertConditionalExpression( BoundUnconvertedConditionalOperator source, TypeSymbol destination, Conversion? conversionIfTargetTyped, BindingDiagnosticBag diagnostics, bool hasErrors = false) { bool targetTyped = conversionIfTargetTyped is { }; Debug.Assert(targetTyped || destination.IsErrorType() || destination.Equals(source.Type, TypeCompareKind.ConsiderEverything)); ImmutableArray<Conversion> underlyingConversions = conversionIfTargetTyped.GetValueOrDefault().UnderlyingConversions; var condition = source.Condition; hasErrors |= source.HasErrors || destination.IsErrorType(); var trueExpr = targetTyped ? CreateConversion(source.Consequence.Syntax, source.Consequence, underlyingConversions[0], isCast: false, conversionGroupOpt: null, destination, diagnostics) : GenerateConversionForAssignment(destination, source.Consequence, diagnostics); var falseExpr = targetTyped ? CreateConversion(source.Alternative.Syntax, source.Alternative, underlyingConversions[1], isCast: false, conversionGroupOpt: null, destination, diagnostics) : GenerateConversionForAssignment(destination, source.Alternative, diagnostics); var constantValue = FoldConditionalOperator(condition, trueExpr, falseExpr); hasErrors |= constantValue?.IsBad == true; if (targetTyped && !destination.IsErrorType() && !Compilation.IsFeatureEnabled(MessageID.IDS_FeatureTargetTypedConditional)) { diagnostics.Add( ErrorCode.ERR_NoImplicitConvTargetTypedConditional, source.Syntax.Location, Compilation.LanguageVersion.ToDisplayString(), source.Consequence.Display, source.Alternative.Display, new CSharpRequiredLanguageVersion(MessageID.IDS_FeatureTargetTypedConditional.RequiredVersion())); } return new BoundConditionalOperator(source.Syntax, isRef: false, condition, trueExpr, falseExpr, constantValue, source.Type, wasTargetTyped: targetTyped, destination, hasErrors) .WithSuppression(source.IsSuppressed); } /// <summary> /// Rewrite the expressions in the switch expression arms to add a conversion to the destination type. /// </summary> private BoundExpression ConvertSwitchExpression(BoundUnconvertedSwitchExpression source, TypeSymbol destination, Conversion? conversionIfTargetTyped, BindingDiagnosticBag diagnostics, bool hasErrors = false) { bool targetTyped = conversionIfTargetTyped is { }; Conversion conversion = conversionIfTargetTyped ?? Conversion.Identity; Debug.Assert(targetTyped || destination.IsErrorType() || destination.Equals(source.Type, TypeCompareKind.ConsiderEverything)); ImmutableArray<Conversion> underlyingConversions = conversion.UnderlyingConversions; var builder = ArrayBuilder<BoundSwitchExpressionArm>.GetInstance(source.SwitchArms.Length); for (int i = 0, n = source.SwitchArms.Length; i < n; i++) { var oldCase = source.SwitchArms[i]; Debug.Assert(oldCase.Syntax is SwitchExpressionArmSyntax); var binder = GetRequiredBinder(oldCase.Syntax); var oldValue = oldCase.Value; var newValue = targetTyped ? binder.CreateConversion(oldValue.Syntax, oldValue, underlyingConversions[i], isCast: false, conversionGroupOpt: null, destination, diagnostics) : binder.GenerateConversionForAssignment(destination, oldValue, diagnostics); var newCase = (oldValue == newValue) ? oldCase : new BoundSwitchExpressionArm(oldCase.Syntax, oldCase.Locals, oldCase.Pattern, oldCase.WhenClause, newValue, oldCase.Label, oldCase.HasErrors); builder.Add(newCase); } var newSwitchArms = builder.ToImmutableAndFree(); return new BoundConvertedSwitchExpression( source.Syntax, source.Type, targetTyped, conversion, source.Expression, newSwitchArms, source.DecisionDag, source.DefaultLabel, source.ReportedNotExhaustive, destination, hasErrors || source.HasErrors); } private BoundExpression CreateUserDefinedConversion( SyntaxNode syntax, BoundExpression source, Conversion conversion, bool isCast, ConversionGroup conversionGroup, TypeSymbol destination, BindingDiagnosticBag diagnostics, bool hasErrors) { Debug.Assert(conversionGroup != null); Debug.Assert(conversion.IsUserDefined); if (!conversion.IsValid) { if (!hasErrors) GenerateImplicitConversionError(diagnostics, syntax, conversion, source, destination); return new BoundConversion( syntax, source, conversion, CheckOverflowAtRuntime, explicitCastInCode: isCast, conversionGroup, constantValueOpt: ConstantValue.NotAvailable, type: destination, hasErrors: true) { WasCompilerGenerated = source.WasCompilerGenerated }; } // Due to an oddity in the way we create a non-lifted user-defined conversion from A to D? // (required backwards compatibility with the native compiler) we can end up in a situation // where we have: // a standard conversion from A to B? // then a standard conversion from B? to B // then a user-defined conversion from B to C // then a standard conversion from C to C? // then a standard conversion from C? to D? // // In that scenario, the "from type" of the conversion will be B? and the "from conversion" will be // from A to B?. Similarly the "to type" of the conversion will be C? and the "to conversion" // of the conversion will be from C? to D?. // // Therefore, we might need to introduce an extra conversion on the source side, from B? to B. // Now, you might think we should also introduce an extra conversion on the destination side, // from C to C?. But that then gives us the following bad situation: If we in fact bind this as // // (D?)(C?)(C)(B)(B?)(A)x // // then what we are in effect doing is saying "convert C? to D? by checking for null, unwrapping, // converting C to D, and then wrapping". But we know that the C? will never be null. In this case // we should actually generate // // (D?)(C)(B)(B?)(A)x // // And thereby skip the unnecessary nullable conversion. Debug.Assert(conversion.BestUserDefinedConversionAnalysis is object); // All valid user-defined conversions have this populated // Original expression --> conversion's "from" type BoundExpression convertedOperand = CreateConversion( syntax: source.Syntax, source: source, conversion: conversion.UserDefinedFromConversion, isCast: false, conversionGroupOpt: conversionGroup, wasCompilerGenerated: false, destination: conversion.BestUserDefinedConversionAnalysis.FromType, diagnostics: diagnostics); TypeSymbol conversionParameterType = conversion.BestUserDefinedConversionAnalysis.Operator.GetParameterType(0); CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); if (conversion.BestUserDefinedConversionAnalysis.Kind == UserDefinedConversionAnalysisKind.ApplicableInNormalForm && !TypeSymbol.Equals(conversion.BestUserDefinedConversionAnalysis.FromType, conversionParameterType, TypeCompareKind.ConsiderEverything2)) { // Conversion's "from" type --> conversion method's parameter type. convertedOperand = CreateConversion( syntax: syntax, source: convertedOperand, conversion: Conversions.ClassifyStandardConversion(null, convertedOperand.Type, conversionParameterType, ref useSiteInfo), isCast: false, conversionGroupOpt: conversionGroup, wasCompilerGenerated: true, destination: conversionParameterType, diagnostics: diagnostics); } BoundExpression userDefinedConversion; TypeSymbol conversionReturnType = conversion.BestUserDefinedConversionAnalysis.Operator.ReturnType; TypeSymbol conversionToType = conversion.BestUserDefinedConversionAnalysis.ToType; Conversion toConversion = conversion.UserDefinedToConversion; if (conversion.BestUserDefinedConversionAnalysis.Kind == UserDefinedConversionAnalysisKind.ApplicableInNormalForm && !TypeSymbol.Equals(conversionToType, conversionReturnType, TypeCompareKind.ConsiderEverything2)) { // Conversion method's parameter type --> conversion method's return type // NB: not calling CreateConversion here because this is the recursive base case. userDefinedConversion = new BoundConversion( syntax, convertedOperand, conversion, @checked: false, // There are no checked user-defined conversions, but the conversions on either side might be checked. explicitCastInCode: isCast, conversionGroup, constantValueOpt: ConstantValue.NotAvailable, type: conversionReturnType) { WasCompilerGenerated = true }; if (conversionToType.IsNullableType() && TypeSymbol.Equals(conversionToType.GetNullableUnderlyingType(), conversionReturnType, TypeCompareKind.ConsiderEverything2)) { // Skip introducing the conversion from C to C?. The "to" conversion is now wrong though, // because it will still assume converting C? to D?. toConversion = Conversions.ClassifyConversionFromType(conversionReturnType, destination, ref useSiteInfo); Debug.Assert(toConversion.Exists); } else { // Conversion method's return type --> conversion's "to" type userDefinedConversion = CreateConversion( syntax: syntax, source: userDefinedConversion, conversion: Conversions.ClassifyStandardConversion(null, conversionReturnType, conversionToType, ref useSiteInfo), isCast: false, conversionGroupOpt: conversionGroup, wasCompilerGenerated: true, destination: conversionToType, diagnostics: diagnostics); } } else { // Conversion method's parameter type --> conversion method's "to" type // NB: not calling CreateConversion here because this is the recursive base case. userDefinedConversion = new BoundConversion( syntax, convertedOperand, conversion, @checked: false, explicitCastInCode: isCast, conversionGroup, constantValueOpt: ConstantValue.NotAvailable, type: conversionToType) { WasCompilerGenerated = true }; } diagnostics.Add(syntax, useSiteInfo); // Conversion's "to" type --> final type BoundExpression finalConversion = CreateConversion( syntax: syntax, source: userDefinedConversion, conversion: toConversion, isCast: false, conversionGroupOpt: conversionGroup, wasCompilerGenerated: true, // NOTE: doesn't necessarily set flag on resulting bound expression. destination: destination, diagnostics: diagnostics); finalConversion.ResetCompilerGenerated(source.WasCompilerGenerated); return finalConversion; } private BoundExpression CreateAnonymousFunctionConversion(SyntaxNode syntax, BoundExpression source, Conversion conversion, bool isCast, ConversionGroup? conversionGroup, TypeSymbol destination, BindingDiagnosticBag diagnostics) { // We have a successful anonymous function conversion; rather than producing a node // which is a conversion on top of an unbound lambda, replace it with the bound // lambda. // UNDONE: Figure out what to do about the error case, where a lambda // UNDONE: is converted to a delegate that does not match. What to surface then? var unboundLambda = (UnboundLambda)source; if (destination.SpecialType == SpecialType.System_Delegate || destination.IsNonGenericExpressionType()) { CheckFeatureAvailability(syntax, MessageID.IDS_FeatureInferredDelegateType, diagnostics); CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); var delegateType = unboundLambda.InferDelegateType(ref useSiteInfo); BoundLambda boundLambda; if (delegateType is { }) { bool isExpressionTree = destination.IsNonGenericExpressionType(); if (isExpressionTree) { delegateType = Compilation.GetWellKnownType(WellKnownType.System_Linq_Expressions_Expression_T).Construct(delegateType); delegateType.AddUseSiteInfo(ref useSiteInfo); } boundLambda = unboundLambda.Bind(delegateType, isExpressionTree); } else { diagnostics.Add(ErrorCode.ERR_CannotInferDelegateType, syntax.GetLocation()); delegateType = CreateErrorType(); boundLambda = unboundLambda.BindForErrorRecovery(); } diagnostics.AddRange(boundLambda.Diagnostics); var expr = createAnonymousFunctionConversion(syntax, source, boundLambda, conversion, isCast, conversionGroup, delegateType); conversion = Conversions.ClassifyConversionFromExpression(expr, destination, ref useSiteInfo); diagnostics.Add(syntax, useSiteInfo); return CreateConversion(syntax, expr, conversion, isCast, conversionGroup, destination, diagnostics); } else { #if DEBUG // Test inferring a delegate type for all callers. var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; _ = unboundLambda.InferDelegateType(ref discardedUseSiteInfo); #endif var boundLambda = unboundLambda.Bind((NamedTypeSymbol)destination, isExpressionTree: destination.IsGenericOrNonGenericExpressionType(out _)); diagnostics.AddRange(boundLambda.Diagnostics); return createAnonymousFunctionConversion(syntax, source, boundLambda, conversion, isCast, conversionGroup, destination); } static BoundConversion createAnonymousFunctionConversion(SyntaxNode syntax, BoundExpression source, BoundLambda boundLambda, Conversion conversion, bool isCast, ConversionGroup? conversionGroup, TypeSymbol destination) { return new BoundConversion( syntax, boundLambda, conversion, @checked: false, explicitCastInCode: isCast, conversionGroup, constantValueOpt: ConstantValue.NotAvailable, type: destination) { WasCompilerGenerated = source.WasCompilerGenerated }; } } private BoundExpression CreateMethodGroupConversion(SyntaxNode syntax, BoundExpression source, Conversion conversion, bool isCast, ConversionGroup? conversionGroup, TypeSymbol destination, BindingDiagnosticBag diagnostics) { var (originalGroup, isAddressOf) = source switch { BoundMethodGroup m => (m, false), BoundUnconvertedAddressOfOperator { Operand: { } m } => (m, true), _ => throw ExceptionUtilities.UnexpectedValue(source), }; BoundMethodGroup group = FixMethodGroupWithTypeOrValue(originalGroup, conversion, diagnostics); bool hasErrors = false; if (MethodGroupConversionHasErrors(syntax, conversion, group.ReceiverOpt, conversion.IsExtensionMethod, isAddressOf, destination, diagnostics)) { hasErrors = true; } if (destination.SpecialType == SpecialType.System_Delegate) { CheckFeatureAvailability(syntax, MessageID.IDS_FeatureInferredDelegateType, diagnostics); // https://github.com/dotnet/roslyn/issues/52869: Avoid calculating the delegate type multiple times during conversion. CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); var delegateType = GetMethodGroupDelegateType(group, ref useSiteInfo); var expr = createMethodGroupConversion(syntax, group, conversion, isCast, conversionGroup, delegateType!, hasErrors); conversion = Conversions.ClassifyConversionFromExpression(expr, destination, ref useSiteInfo); diagnostics.Add(syntax, useSiteInfo); return CreateConversion(syntax, expr, conversion, isCast, conversionGroup, destination, diagnostics); } #if DEBUG // Test inferring a delegate type for all callers. var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; _ = GetMethodGroupDelegateType(group, ref discardedUseSiteInfo); #endif return createMethodGroupConversion(syntax, group, conversion, isCast, conversionGroup, destination, hasErrors); static BoundConversion createMethodGroupConversion(SyntaxNode syntax, BoundMethodGroup group, Conversion conversion, bool isCast, ConversionGroup? conversionGroup, TypeSymbol destination, bool hasErrors) { return new BoundConversion(syntax, group, conversion, @checked: false, explicitCastInCode: isCast, conversionGroup, constantValueOpt: ConstantValue.NotAvailable, type: destination, hasErrors: hasErrors) { WasCompilerGenerated = group.WasCompilerGenerated }; } } private BoundExpression CreateStackAllocConversion(SyntaxNode syntax, BoundExpression source, Conversion conversion, bool isCast, ConversionGroup? conversionGroup, TypeSymbol destination, BindingDiagnosticBag diagnostics) { Debug.Assert(conversion.IsStackAlloc); var boundStackAlloc = (BoundStackAllocArrayCreation)source; var elementType = boundStackAlloc.ElementType; TypeSymbol stackAllocType; switch (conversion.Kind) { case ConversionKind.StackAllocToPointerType: ReportUnsafeIfNotAllowed(syntax.Location, diagnostics); stackAllocType = new PointerTypeSymbol(TypeWithAnnotations.Create(elementType)); break; case ConversionKind.StackAllocToSpanType: CheckFeatureAvailability(syntax, MessageID.IDS_FeatureRefStructs, diagnostics); stackAllocType = Compilation.GetWellKnownType(WellKnownType.System_Span_T).Construct(elementType); break; default: throw ExceptionUtilities.UnexpectedValue(conversion.Kind); } var convertedNode = new BoundConvertedStackAllocExpression(syntax, elementType, boundStackAlloc.Count, boundStackAlloc.InitializerOpt, stackAllocType, boundStackAlloc.HasErrors); var underlyingConversion = conversion.UnderlyingConversions.Single(); return CreateConversion(syntax, convertedNode, underlyingConversion, isCast: isCast, conversionGroup, destination, diagnostics); } private BoundExpression CreateTupleLiteralConversion(SyntaxNode syntax, BoundTupleLiteral sourceTuple, Conversion conversion, bool isCast, ConversionGroup? conversionGroup, TypeSymbol destination, BindingDiagnosticBag diagnostics) { // We have a successful tuple conversion; rather than producing a separate conversion node // which is a conversion on top of a tuple literal, tuple conversion is an element-wise conversion of arguments. Debug.Assert(conversion.IsNullable == destination.IsNullableType()); var destinationWithoutNullable = destination; var conversionWithoutNullable = conversion; if (conversion.IsNullable) { destinationWithoutNullable = destination.GetNullableUnderlyingType(); conversionWithoutNullable = conversion.UnderlyingConversions[0]; } Debug.Assert(conversionWithoutNullable.IsTupleLiteralConversion); NamedTypeSymbol targetType = (NamedTypeSymbol)destinationWithoutNullable; if (targetType.IsTupleType) { NamedTypeSymbol.ReportTupleNamesMismatchesIfAny(targetType, sourceTuple, diagnostics); // do not lose the original element names and locations in the literal if different from names in the target // // the tuple has changed the type of elements due to target-typing, // but element names has not changed and locations of their declarations // should not be confused with element locations on the target type. if (sourceTuple.Type is NamedTypeSymbol { IsTupleType: true } sourceType) { targetType = targetType.WithTupleDataFrom(sourceType); } else { var tupleSyntax = (TupleExpressionSyntax)sourceTuple.Syntax; var locationBuilder = ArrayBuilder<Location?>.GetInstance(); foreach (var argument in tupleSyntax.Arguments) { locationBuilder.Add(argument.NameColon?.Name.Location); } targetType = targetType.WithElementNames(sourceTuple.ArgumentNamesOpt!, locationBuilder.ToImmutableAndFree(), errorPositions: default, ImmutableArray.Create(tupleSyntax.Location)); } } var arguments = sourceTuple.Arguments; var convertedArguments = ArrayBuilder<BoundExpression>.GetInstance(arguments.Length); var targetElementTypes = targetType.TupleElementTypesWithAnnotations; Debug.Assert(targetElementTypes.Length == arguments.Length, "converting a tuple literal to incompatible type?"); var underlyingConversions = conversionWithoutNullable.UnderlyingConversions; for (int i = 0; i < arguments.Length; i++) { var argument = arguments[i]; var destType = targetElementTypes[i]; var elementConversion = underlyingConversions[i]; var elementConversionGroup = isCast ? new ConversionGroup(elementConversion, destType) : null; convertedArguments.Add(CreateConversion(argument.Syntax, argument, elementConversion, isCast: isCast, elementConversionGroup, destType.Type, diagnostics)); } BoundExpression result = new BoundConvertedTupleLiteral( sourceTuple.Syntax, sourceTuple, wasTargetTyped: true, convertedArguments.ToImmutableAndFree(), sourceTuple.ArgumentNamesOpt, sourceTuple.InferredNamesOpt, targetType).WithSuppression(sourceTuple.IsSuppressed); if (!TypeSymbol.Equals(sourceTuple.Type, destination, TypeCompareKind.ConsiderEverything2)) { // literal cast is applied to the literal result = new BoundConversion( sourceTuple.Syntax, result, conversion, @checked: false, explicitCastInCode: isCast, conversionGroup, constantValueOpt: ConstantValue.NotAvailable, type: destination); } // If we had a cast in the code, keep conversion in the tree. // even though the literal is already converted to the target type. if (isCast) { result = new BoundConversion( syntax, result, Conversion.Identity, @checked: false, explicitCastInCode: isCast, conversionGroup, constantValueOpt: ConstantValue.NotAvailable, type: destination); } return result; } private static bool IsMethodGroupWithTypeOrValueReceiver(BoundNode node) { if (node.Kind != BoundKind.MethodGroup) { return false; } return Binder.IsTypeOrValueExpression(((BoundMethodGroup)node).ReceiverOpt); } private BoundMethodGroup FixMethodGroupWithTypeOrValue(BoundMethodGroup group, Conversion conversion, BindingDiagnosticBag diagnostics) { if (!IsMethodGroupWithTypeOrValueReceiver(group)) { return group; } BoundExpression? receiverOpt = group.ReceiverOpt; RoslynDebug.Assert(receiverOpt != null); receiverOpt = ReplaceTypeOrValueReceiver(receiverOpt, useType: conversion.Method?.RequiresInstanceReceiver == false && !conversion.IsExtensionMethod, diagnostics); return group.Update( group.TypeArgumentsOpt, group.Name, group.Methods, group.LookupSymbolOpt, group.LookupError, group.Flags, receiverOpt, //only change group.ResultKind); } /// <summary> /// This method implements the algorithm in spec section 7.6.5.1. /// /// For method group conversions, there are situations in which the conversion is /// considered to exist ("Otherwise the algorithm produces a single best method M having /// the same number of parameters as D and the conversion is considered to exist"), but /// application of the conversion fails. These are the "final validation" steps of /// overload resolution. /// </summary> /// <returns> /// True if there is any error, except lack of runtime support errors. /// </returns> private bool MemberGroupFinalValidation(BoundExpression? receiverOpt, MethodSymbol methodSymbol, SyntaxNode node, BindingDiagnosticBag diagnostics, bool invokedAsExtensionMethod) { if (!IsBadBaseAccess(node, receiverOpt, methodSymbol, diagnostics)) { CheckReceiverAndRuntimeSupportForSymbolAccess(node, receiverOpt, methodSymbol, diagnostics); } if (MemberGroupFinalValidationAccessibilityChecks(receiverOpt, methodSymbol, node, diagnostics, invokedAsExtensionMethod)) { return true; } // SPEC: If the best method is a generic method, the type arguments (supplied or inferred) are checked against the constraints // SPEC: declared on the generic method. If any type argument does not satisfy the corresponding constraint(s) on // SPEC: the type parameter, a binding-time error occurs. // The portion of the overload resolution spec quoted above is subtle and somewhat // controversial. The upshot of this is that overload resolution does not consider // constraints to be a part of the signature. Overload resolution matches arguments to // parameter lists; it does not consider things which are outside of the parameter list. // If the best match from the arguments to the formal parameters is not viable then we // give an error rather than falling back to a worse match. // // Consider the following: // // void M<T>(T t) where T : Reptile {} // void M(object x) {} // ... // M(new Giraffe()); // // The correct analysis is to determine that the applicable candidates are // M<Giraffe>(Giraffe) and M(object). Overload resolution then chooses the former // because it is an exact match, over the latter which is an inexact match. Only after // the best method is determined do we check the constraints and discover that the // constraint on T has been violated. // // Note that this is different from the rule that says that during type inference, if an // inference violates a constraint then inference fails. For example: // // class C<T> where T : struct {} // ... // void M<U>(U u, C<U> c){} // void M(object x, object y) {} // ... // M("hello", null); // // Type inference determines that U is string, but since C<string> is not a valid type // because of the constraint, type inference fails. M<string> is never added to the // applicable candidate set, so the applicable candidate set consists solely of // M(object, object) and is therefore the best match. return !methodSymbol.CheckConstraints(new ConstraintsHelper.CheckConstraintsArgs(this.Compilation, this.Conversions, includeNullability: false, node.Location, diagnostics)); } /// <summary> /// Performs the following checks: /// /// Spec 7.6.5: Invocation expressions (definition of Final Validation) /// The method is validated in the context of the method group: If the best method is a static method, /// the method group must have resulted from a simple-name or a member-access through a type. If the best /// method is an instance method, the method group must have resulted from a simple-name, a member-access /// through a variable or value, or a base-access. If neither of these requirements is true, a binding-time /// error occurs. /// (Note that the spec omits to mention, in the case of an instance method invoked through a simple name, that /// the invocation must appear within the body of an instance method) /// /// Spec 7.5.4: Compile-time checking of dynamic overload resolution /// If F is a static method, the method group must have resulted from a simple-name, a member-access through a type, /// or a member-access whose receiver can't be classified as a type or value until after overload resolution (see §7.6.4.1). /// If F is an instance method, the method group must have resulted from a simple-name, a member-access through a variable or value, /// or a member-access whose receiver can't be classified as a type or value until after overload resolution (see §7.6.4.1). /// </summary> /// <returns> /// True if there is any error. /// </returns> private bool MemberGroupFinalValidationAccessibilityChecks(BoundExpression? receiverOpt, Symbol memberSymbol, SyntaxNode node, BindingDiagnosticBag diagnostics, bool invokedAsExtensionMethod) { // Perform final validation of the method to be invoked. Debug.Assert(memberSymbol.Kind != SymbolKind.Method || memberSymbol.CanBeReferencedByName); //note that the same assert does not hold for all properties. Some properties and (all indexers) are not referenceable by name, yet //their binding brings them through here, perhaps needlessly. if (IsTypeOrValueExpression(receiverOpt)) { // TypeOrValue expression isn't replaced only if the invocation is late bound, in which case it can't be extension method. // None of the checks below apply if the receiver can't be classified as a type or value. Debug.Assert(!invokedAsExtensionMethod); } else if (!memberSymbol.RequiresInstanceReceiver()) { Debug.Assert(!invokedAsExtensionMethod || (receiverOpt != null)); if (invokedAsExtensionMethod) { if (IsMemberAccessedThroughType(receiverOpt)) { if (receiverOpt.Kind == BoundKind.QueryClause) { RoslynDebug.Assert(receiverOpt.Type is object); // Could not find an implementation of the query pattern for source type '{0}'. '{1}' not found. diagnostics.Add(ErrorCode.ERR_QueryNoProvider, node.Location, receiverOpt.Type, memberSymbol.Name); } else { // An object reference is required for the non-static field, method, or property '{0}' diagnostics.Add(ErrorCode.ERR_ObjectRequired, node.Location, memberSymbol); } return true; } } else if (!WasImplicitReceiver(receiverOpt) && IsMemberAccessedThroughVariableOrValue(receiverOpt)) { if (this.Flags.Includes(BinderFlags.CollectionInitializerAddMethod)) { diagnostics.Add(ErrorCode.ERR_InitializerAddHasWrongSignature, node.Location, memberSymbol); } else if (node.Kind() == SyntaxKind.AwaitExpression && memberSymbol.Name == WellKnownMemberNames.GetAwaiter) { RoslynDebug.Assert(receiverOpt.Type is object); diagnostics.Add(ErrorCode.ERR_BadAwaitArg, node.Location, receiverOpt.Type); } else { diagnostics.Add(ErrorCode.ERR_ObjectProhibited, node.Location, memberSymbol); } return true; } } else if (IsMemberAccessedThroughType(receiverOpt)) { diagnostics.Add(ErrorCode.ERR_ObjectRequired, node.Location, memberSymbol); return true; } else if (WasImplicitReceiver(receiverOpt)) { if (InFieldInitializer && !ContainingType!.IsScriptClass || InConstructorInitializer || InAttributeArgument) { SyntaxNode errorNode = node; if (node.Parent != null && node.Parent.Kind() == SyntaxKind.InvocationExpression) { errorNode = node.Parent; } ErrorCode code = InFieldInitializer ? ErrorCode.ERR_FieldInitRefNonstatic : ErrorCode.ERR_ObjectRequired; diagnostics.Add(code, errorNode.Location, memberSymbol); return true; } // If we could access the member through implicit "this" the receiver would be a BoundThisReference. // If it is null it means that the instance member is inaccessible. if (receiverOpt == null || ContainingMember().IsStatic) { Error(diagnostics, ErrorCode.ERR_ObjectRequired, node, memberSymbol); return true; } } var containingType = this.ContainingType; if (containingType is object) { CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); bool isAccessible = this.IsSymbolAccessibleConditional(memberSymbol.GetTypeOrReturnType().Type, containingType, ref useSiteInfo); diagnostics.Add(node, useSiteInfo); if (!isAccessible) { // In the presence of non-transitive [InternalsVisibleTo] in source, or obnoxious symbols from metadata, it is possible // to select a method through overload resolution in which the type is not accessible. In this case a method cannot // be called through normal IL, so we give an error. Neither [InternalsVisibleTo] nor the need for this diagnostic is // described by the language specification. // // Dev11 perform different access checks. See bug #530360 and tests AccessCheckTests.InaccessibleReturnType. Error(diagnostics, ErrorCode.ERR_BadAccess, node, memberSymbol); return true; } } return false; } private static bool IsMemberAccessedThroughVariableOrValue(BoundExpression? receiverOpt) { if (receiverOpt == null) { return false; } return !IsMemberAccessedThroughType(receiverOpt); } internal static bool IsMemberAccessedThroughType([NotNullWhen(true)] BoundExpression? receiverOpt) { if (receiverOpt == null) { return false; } while (receiverOpt.Kind == BoundKind.QueryClause) { receiverOpt = ((BoundQueryClause)receiverOpt).Value; } return receiverOpt.Kind == BoundKind.TypeExpression; } /// <summary> /// Was the receiver expression compiler-generated? /// </summary> internal static bool WasImplicitReceiver([NotNullWhen(false)] BoundExpression? receiverOpt) { if (receiverOpt == null) return true; if (!receiverOpt.WasCompilerGenerated) return false; switch (receiverOpt.Kind) { case BoundKind.ThisReference: case BoundKind.HostObjectMemberReference: case BoundKind.PreviousSubmissionReference: return true; default: return false; } } /// <summary> /// This method implements the checks in spec section 15.2. /// </summary> internal bool MethodIsCompatibleWithDelegateOrFunctionPointer(BoundExpression? receiverOpt, bool isExtensionMethod, MethodSymbol method, TypeSymbol delegateType, Location errorLocation, BindingDiagnosticBag diagnostics) { Debug.Assert(delegateType is NamedTypeSymbol { TypeKind: TypeKind.Delegate, DelegateInvokeMethod: { HasUseSiteError: false } } || delegateType.TypeKind == TypeKind.FunctionPointer, "This method should only be called for valid delegate or function pointer types."); MethodSymbol delegateOrFuncPtrMethod = delegateType switch { NamedTypeSymbol { DelegateInvokeMethod: { } invokeMethod } => invokeMethod, FunctionPointerTypeSymbol { Signature: { } signature } => signature, _ => throw ExceptionUtilities.UnexpectedValue(delegateType), }; Debug.Assert(!isExtensionMethod || (receiverOpt != null)); // - Argument types "match", and var delegateOrFuncPtrParameters = delegateOrFuncPtrMethod.Parameters; var methodParameters = method.Parameters; int numParams = delegateOrFuncPtrParameters.Length; if (methodParameters.Length != numParams + (isExtensionMethod ? 1 : 0)) { // This can happen if "method" has optional parameters. Debug.Assert(methodParameters.Length > numParams + (isExtensionMethod ? 1 : 0)); Error(diagnostics, getMethodMismatchErrorCode(delegateType.TypeKind), errorLocation, method, delegateType); return false; } CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); // If this is an extension method delegate, the caller should have verified the // receiver is compatible with the "this" parameter of the extension method. Debug.Assert(!isExtensionMethod || (Conversions.ConvertExtensionMethodThisArg(methodParameters[0].Type, receiverOpt!.Type, ref useSiteInfo).Exists && useSiteInfo.Diagnostics.IsNullOrEmpty())); useSiteInfo = new CompoundUseSiteInfo<AssemblySymbol>(useSiteInfo); for (int i = 0; i < numParams; i++) { var delegateParameter = delegateOrFuncPtrParameters[i]; var methodParameter = methodParameters[isExtensionMethod ? i + 1 : i]; // The delegate compatibility checks are stricter than the checks on applicable functions: it's possible // to get here with a method that, while all the parameters are applicable, is not actually delegate // compatible. This is because the Applicable function member spec requires that: // * Every value parameter (non-ref or similar) from the delegate type has an implicit conversion to the corresponding // target parameter // * Every ref or similar parameter has an identity conversion to the corresponding target parameter // However, the delegate compatibility requirements are stricter: // * Every value parameter (non-ref or similar) from the delegate type has an implicit _reference_ conversion to the // corresponding target parameter. // * Every ref or similar parameter has an identity conversion to the corresponding target parameter // Note the addition of the reference requirement: it means that for delegate type void D(int i), void M(long l) is // _applicable_, but not _compatible_. if (!hasConversion(delegateType.TypeKind, Conversions, delegateParameter.Type, methodParameter.Type, delegateParameter.RefKind, methodParameter.RefKind, ref useSiteInfo)) { // No overload for '{0}' matches delegate '{1}' Error(diagnostics, getMethodMismatchErrorCode(delegateType.TypeKind), errorLocation, method, delegateType); diagnostics.Add(errorLocation, useSiteInfo); return false; } } if (delegateOrFuncPtrMethod.RefKind != method.RefKind) { Error(diagnostics, getRefMismatchErrorCode(delegateType.TypeKind), errorLocation, method, delegateType); diagnostics.Add(errorLocation, useSiteInfo); return false; } var methodReturnType = method.ReturnType; var delegateReturnType = delegateOrFuncPtrMethod.ReturnType; bool returnsMatch = delegateOrFuncPtrMethod switch { { RefKind: RefKind.None, ReturnsVoid: true } => method.ReturnsVoid, { RefKind: var destinationRefKind } => hasConversion(delegateType.TypeKind, Conversions, methodReturnType, delegateReturnType, method.RefKind, destinationRefKind, ref useSiteInfo), }; if (!returnsMatch) { Error(diagnostics, ErrorCode.ERR_BadRetType, errorLocation, method, method.ReturnType); diagnostics.Add(errorLocation, useSiteInfo); return false; } if (delegateType.IsFunctionPointer()) { if (isExtensionMethod) { Error(diagnostics, ErrorCode.ERR_CannotUseReducedExtensionMethodInAddressOf, errorLocation); diagnostics.Add(errorLocation, useSiteInfo); return false; } if (!method.IsStatic) { // This check is here purely for completeness of implementing the spec. It should // never be hit, as static methods should be eliminated as candidates in overload // resolution and should never make it to this point. Debug.Fail("This method should have been eliminated in overload resolution!"); Error(diagnostics, ErrorCode.ERR_FuncPtrMethMustBeStatic, errorLocation, method); diagnostics.Add(errorLocation, useSiteInfo); return false; } } diagnostics.Add(errorLocation, useSiteInfo); return true; static bool hasConversion(TypeKind targetKind, Conversions conversions, TypeSymbol source, TypeSymbol destination, RefKind sourceRefKind, RefKind destinationRefKind, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { if (sourceRefKind != destinationRefKind) { return false; } if (sourceRefKind != RefKind.None) { return ConversionsBase.HasIdentityConversion(source, destination); } if (conversions.HasIdentityOrImplicitReferenceConversion(source, destination, ref useSiteInfo)) { return true; } return targetKind == TypeKind.FunctionPointer && (ConversionsBase.HasImplicitPointerToVoidConversion(source, destination) || conversions.HasImplicitPointerConversion(source, destination, ref useSiteInfo)); } static ErrorCode getMethodMismatchErrorCode(TypeKind type) => type switch { TypeKind.Delegate => ErrorCode.ERR_MethDelegateMismatch, TypeKind.FunctionPointer => ErrorCode.ERR_MethFuncPtrMismatch, _ => throw ExceptionUtilities.UnexpectedValue(type) }; static ErrorCode getRefMismatchErrorCode(TypeKind type) => type switch { TypeKind.Delegate => ErrorCode.ERR_DelegateRefMismatch, TypeKind.FunctionPointer => ErrorCode.ERR_FuncPtrRefMismatch, _ => throw ExceptionUtilities.UnexpectedValue(type) }; } /// <summary> /// This method combines final validation (section 7.6.5.1) and delegate compatibility (section 15.2). /// </summary> /// <param name="syntax">CSharpSyntaxNode of the expression requiring method group conversion.</param> /// <param name="conversion">Conversion to be performed.</param> /// <param name="receiverOpt">Optional receiver.</param> /// <param name="isExtensionMethod">Method invoked as extension method.</param> /// <param name="delegateOrFuncPtrType">Target delegate type.</param> /// <param name="diagnostics">Where diagnostics should be added.</param> /// <returns>True if a diagnostic has been added.</returns> private bool MethodGroupConversionHasErrors( SyntaxNode syntax, Conversion conversion, BoundExpression? receiverOpt, bool isExtensionMethod, bool isAddressOf, TypeSymbol delegateOrFuncPtrType, BindingDiagnosticBag diagnostics) { Debug.Assert(delegateOrFuncPtrType.SpecialType == SpecialType.System_Delegate || delegateOrFuncPtrType.TypeKind == TypeKind.Delegate || delegateOrFuncPtrType.TypeKind == TypeKind.FunctionPointer); Debug.Assert(conversion.Method is object); MethodSymbol selectedMethod = conversion.Method; var location = syntax.Location; if (delegateOrFuncPtrType.SpecialType != SpecialType.System_Delegate) { if (!MethodIsCompatibleWithDelegateOrFunctionPointer(receiverOpt, isExtensionMethod, selectedMethod, delegateOrFuncPtrType, location, diagnostics) || MemberGroupFinalValidation(receiverOpt, selectedMethod, syntax, diagnostics, isExtensionMethod)) { return true; } } if (selectedMethod.IsConditional) { // CS1618: Cannot create delegate with '{0}' because it has a Conditional attribute Error(diagnostics, ErrorCode.ERR_DelegateOnConditional, location, selectedMethod); return true; } var sourceMethod = selectedMethod as SourceOrdinaryMethodSymbol; if (sourceMethod is object && sourceMethod.IsPartialWithoutImplementation) { // CS0762: Cannot create delegate from method '{0}' because it is a partial method without an implementing declaration Error(diagnostics, ErrorCode.ERR_PartialMethodToDelegate, location, selectedMethod); return true; } if ((selectedMethod.HasUnsafeParameter() || selectedMethod.ReturnType.IsUnsafe()) && ReportUnsafeIfNotAllowed(syntax, diagnostics)) { return true; } if (!isAddressOf) { ReportDiagnosticsIfUnmanagedCallersOnly(diagnostics, selectedMethod, location, isDelegateConversion: true); } ReportDiagnosticsIfObsolete(diagnostics, selectedMethod, syntax, hasBaseReceiver: false); // No use site errors, but there could be use site warnings. // If there are use site warnings, they were reported during the overload resolution process // that chose selectedMethod. Debug.Assert(!selectedMethod.HasUseSiteError, "Shouldn't have reached this point if there were use site errors."); return false; } /// <summary> /// This method is a wrapper around MethodGroupConversionHasErrors. As a preliminary step, /// it checks whether a conversion exists. /// </summary> private bool MethodGroupConversionDoesNotExistOrHasErrors( BoundMethodGroup boundMethodGroup, NamedTypeSymbol delegateType, Location delegateMismatchLocation, BindingDiagnosticBag diagnostics, out Conversion conversion) { if (ReportDelegateInvokeUseSiteDiagnostic(diagnostics, delegateType, delegateMismatchLocation)) { conversion = Conversion.NoConversion; return true; } CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); conversion = Conversions.GetMethodGroupDelegateConversion(boundMethodGroup, delegateType, ref useSiteInfo); diagnostics.Add(delegateMismatchLocation, useSiteInfo); if (!conversion.Exists) { if (!Conversions.ReportDelegateOrFunctionPointerMethodGroupDiagnostics(this, boundMethodGroup, delegateType, diagnostics)) { // No overload for '{0}' matches delegate '{1}' diagnostics.Add(ErrorCode.ERR_MethDelegateMismatch, delegateMismatchLocation, boundMethodGroup.Name, delegateType); } return true; } else { Debug.Assert(conversion.IsValid); // i.e. if it exists, then it is valid. // Only cares about nullness and type of receiver, so no need to worry about BoundTypeOrValueExpression. return this.MethodGroupConversionHasErrors(boundMethodGroup.Syntax, conversion, boundMethodGroup.ReceiverOpt, conversion.IsExtensionMethod, isAddressOf: false, delegateType, diagnostics); } } public ConstantValue? FoldConstantConversion( SyntaxNode syntax, BoundExpression source, Conversion conversion, TypeSymbol destination, BindingDiagnosticBag diagnostics) { RoslynDebug.Assert(source != null); RoslynDebug.Assert((object)destination != null); // The diagnostics bag can be null in cases where we know ahead of time that the // conversion will succeed without error or warning. (For example, if we have a valid // implicit numeric conversion on a constant of numeric type.) // SPEC: A constant expression must be the null literal or a value with one of // SPEC: the following types: sbyte, byte, short, ushort, int, uint, long, // SPEC: ulong, char, float, double, decimal, bool, string, or any enumeration type. // SPEC: The following conversions are permitted in constant expressions: // SPEC: Identity conversions // SPEC: Numeric conversions // SPEC: Enumeration conversions // SPEC: Constant expression conversions // SPEC: Implicit and explicit reference conversions, provided that the source of the conversions // SPEC: is a constant expression that evaluates to the null value. // SPEC VIOLATION: C# has always allowed the following, even though this does violate the rule that // SPEC VIOLATION: a constant expression must be either the null literal, or an expression of one // SPEC VIOLATION: of the given types. // SPEC VIOLATION: const C c = (C)null; // TODO: Some conversions can produce errors or warnings depending on checked/unchecked. // TODO: Fold conversions on enums and strings too. var sourceConstantValue = source.ConstantValue; if (sourceConstantValue == null) { if (conversion.Kind == ConversionKind.DefaultLiteral) { return destination.GetDefaultValue(); } else { return sourceConstantValue; } } else if (sourceConstantValue.IsBad) { return sourceConstantValue; } if (source.HasAnyErrors) { return null; } switch (conversion.Kind) { case ConversionKind.Identity: // An identity conversion to a floating-point type (for example from a cast in // source code) changes the internal representation of the constant value // to precisely the required precision. switch (destination.SpecialType) { case SpecialType.System_Single: return ConstantValue.Create(sourceConstantValue.SingleValue); case SpecialType.System_Double: return ConstantValue.Create(sourceConstantValue.DoubleValue); default: return sourceConstantValue; } case ConversionKind.NullLiteral: return sourceConstantValue; case ConversionKind.ImplicitConstant: return FoldConstantNumericConversion(syntax, sourceConstantValue, destination, diagnostics); case ConversionKind.ExplicitNumeric: case ConversionKind.ImplicitNumeric: case ConversionKind.ExplicitEnumeration: case ConversionKind.ImplicitEnumeration: // The C# specification categorizes conversion from literal zero to nullable enum as // an Implicit Enumeration Conversion. Such a thing should not be constant folded // because nullable enums are never constants. if (destination.IsNullableType()) { return null; } return FoldConstantNumericConversion(syntax, sourceConstantValue, destination, diagnostics); case ConversionKind.ExplicitReference: case ConversionKind.ImplicitReference: return sourceConstantValue.IsNull ? sourceConstantValue : null; } return null; } private ConstantValue? FoldConstantNumericConversion( SyntaxNode syntax, ConstantValue sourceValue, TypeSymbol destination, BindingDiagnosticBag diagnostics) { RoslynDebug.Assert(sourceValue != null); Debug.Assert(!sourceValue.IsBad); SpecialType destinationType; if ((object)destination != null && destination.IsEnumType()) { var underlyingType = ((NamedTypeSymbol)destination).EnumUnderlyingType; RoslynDebug.Assert((object)underlyingType != null); Debug.Assert(underlyingType.SpecialType != SpecialType.None); destinationType = underlyingType.SpecialType; } else { destinationType = destination.GetSpecialTypeSafe(); } // In an unchecked context we ignore overflowing conversions on conversions from any // integral type, float and double to any integral type. "unchecked" actually does not // affect conversions from decimal to any integral type; if those are out of bounds then // we always give an error regardless. if (sourceValue.IsDecimal) { if (!CheckConstantBounds(destinationType, sourceValue, out _)) { // NOTE: Dev10 puts a suffix, "M", on the constant value. Error(diagnostics, ErrorCode.ERR_ConstOutOfRange, syntax, sourceValue.Value + "M", destination!); return ConstantValue.Bad; } } else if (destinationType == SpecialType.System_Decimal) { if (!CheckConstantBounds(destinationType, sourceValue, out _)) { Error(diagnostics, ErrorCode.ERR_ConstOutOfRange, syntax, sourceValue.Value!, destination!); return ConstantValue.Bad; } } else if (CheckOverflowAtCompileTime) { if (!CheckConstantBounds(destinationType, sourceValue, out bool maySucceedAtRuntime)) { if (maySucceedAtRuntime) { // Can be calculated at runtime, but is not a compile-time constant. Error(diagnostics, ErrorCode.WRN_ConstOutOfRangeChecked, syntax, sourceValue.Value!, destination!); return null; } else { Error(diagnostics, ErrorCode.ERR_ConstOutOfRangeChecked, syntax, sourceValue.Value!, destination!); return ConstantValue.Bad; } } } else if (destinationType == SpecialType.System_IntPtr || destinationType == SpecialType.System_UIntPtr) { if (!CheckConstantBounds(destinationType, sourceValue, out _)) { // Can be calculated at runtime, but is not a compile-time constant. return null; } } return ConstantValue.Create(DoUncheckedConversion(destinationType, sourceValue), destinationType); } private static object DoUncheckedConversion(SpecialType destinationType, ConstantValue value) { // Note that we keep "single" floats as doubles internally to maintain higher precision. However, // we do not do so in an entirely "lossless" manner. When *converting* to a float, we do lose // the precision lost due to the conversion. But when doing arithmetic, we do the arithmetic on // the double values. // // An example will help. Suppose we have: // // const float cf1 = 1.0f; // const float cf2 = 1.0e-15f; // const double cd3 = cf1 - cf2; // // We first take the double-precision values for 1.0 and 1.0e-15 and round them to floats, // and then turn them back into doubles. Then when we do the subtraction, we do the subtraction // in doubles, not in floats. Had we done the subtraction in floats, we'd get 1.0; but instead we // do it in doubles and get 0.99999999999999. // // Similarly, if we have // // const int i4 = int.MaxValue; // 2147483647 // const float cf5 = int.MaxValue; // 2147483648.0 // const double cd6 = cf5; // 2147483648.0 // // The int is converted to float and stored internally as the double 214783648, even though the // fully precise int would fit into a double. unchecked { switch (value.Discriminator) { case ConstantValueTypeDiscriminator.Byte: byte byteValue = value.ByteValue; switch (destinationType) { case SpecialType.System_Byte: return (byte)byteValue; case SpecialType.System_Char: return (char)byteValue; case SpecialType.System_UInt16: return (ushort)byteValue; case SpecialType.System_UInt32: return (uint)byteValue; case SpecialType.System_UInt64: return (ulong)byteValue; case SpecialType.System_SByte: return (sbyte)byteValue; case SpecialType.System_Int16: return (short)byteValue; case SpecialType.System_Int32: return (int)byteValue; case SpecialType.System_Int64: return (long)byteValue; case SpecialType.System_IntPtr: return (int)byteValue; case SpecialType.System_UIntPtr: return (uint)byteValue; case SpecialType.System_Single: case SpecialType.System_Double: return (double)byteValue; case SpecialType.System_Decimal: return (decimal)byteValue; default: throw ExceptionUtilities.UnexpectedValue(destinationType); } case ConstantValueTypeDiscriminator.Char: char charValue = value.CharValue; switch (destinationType) { case SpecialType.System_Byte: return (byte)charValue; case SpecialType.System_Char: return (char)charValue; case SpecialType.System_UInt16: return (ushort)charValue; case SpecialType.System_UInt32: return (uint)charValue; case SpecialType.System_UInt64: return (ulong)charValue; case SpecialType.System_SByte: return (sbyte)charValue; case SpecialType.System_Int16: return (short)charValue; case SpecialType.System_Int32: return (int)charValue; case SpecialType.System_Int64: return (long)charValue; case SpecialType.System_IntPtr: return (int)charValue; case SpecialType.System_UIntPtr: return (uint)charValue; case SpecialType.System_Single: case SpecialType.System_Double: return (double)charValue; case SpecialType.System_Decimal: return (decimal)charValue; default: throw ExceptionUtilities.UnexpectedValue(destinationType); } case ConstantValueTypeDiscriminator.UInt16: ushort uint16Value = value.UInt16Value; switch (destinationType) { case SpecialType.System_Byte: return (byte)uint16Value; case SpecialType.System_Char: return (char)uint16Value; case SpecialType.System_UInt16: return (ushort)uint16Value; case SpecialType.System_UInt32: return (uint)uint16Value; case SpecialType.System_UInt64: return (ulong)uint16Value; case SpecialType.System_SByte: return (sbyte)uint16Value; case SpecialType.System_Int16: return (short)uint16Value; case SpecialType.System_Int32: return (int)uint16Value; case SpecialType.System_Int64: return (long)uint16Value; case SpecialType.System_IntPtr: return (int)uint16Value; case SpecialType.System_UIntPtr: return (uint)uint16Value; case SpecialType.System_Single: case SpecialType.System_Double: return (double)uint16Value; case SpecialType.System_Decimal: return (decimal)uint16Value; default: throw ExceptionUtilities.UnexpectedValue(destinationType); } case ConstantValueTypeDiscriminator.UInt32: uint uint32Value = value.UInt32Value; switch (destinationType) { case SpecialType.System_Byte: return (byte)uint32Value; case SpecialType.System_Char: return (char)uint32Value; case SpecialType.System_UInt16: return (ushort)uint32Value; case SpecialType.System_UInt32: return (uint)uint32Value; case SpecialType.System_UInt64: return (ulong)uint32Value; case SpecialType.System_SByte: return (sbyte)uint32Value; case SpecialType.System_Int16: return (short)uint32Value; case SpecialType.System_Int32: return (int)uint32Value; case SpecialType.System_Int64: return (long)uint32Value; case SpecialType.System_IntPtr: return (int)uint32Value; case SpecialType.System_UIntPtr: return (uint)uint32Value; case SpecialType.System_Single: return (double)(float)uint32Value; case SpecialType.System_Double: return (double)uint32Value; case SpecialType.System_Decimal: return (decimal)uint32Value; default: throw ExceptionUtilities.UnexpectedValue(destinationType); } case ConstantValueTypeDiscriminator.UInt64: ulong uint64Value = value.UInt64Value; switch (destinationType) { case SpecialType.System_Byte: return (byte)uint64Value; case SpecialType.System_Char: return (char)uint64Value; case SpecialType.System_UInt16: return (ushort)uint64Value; case SpecialType.System_UInt32: return (uint)uint64Value; case SpecialType.System_UInt64: return (ulong)uint64Value; case SpecialType.System_SByte: return (sbyte)uint64Value; case SpecialType.System_Int16: return (short)uint64Value; case SpecialType.System_Int32: return (int)uint64Value; case SpecialType.System_Int64: return (long)uint64Value; case SpecialType.System_IntPtr: return (int)uint64Value; case SpecialType.System_UIntPtr: return (uint)uint64Value; case SpecialType.System_Single: return (double)(float)uint64Value; case SpecialType.System_Double: return (double)uint64Value; case SpecialType.System_Decimal: return (decimal)uint64Value; default: throw ExceptionUtilities.UnexpectedValue(destinationType); } case ConstantValueTypeDiscriminator.NUInt: uint nuintValue = value.UInt32Value; switch (destinationType) { case SpecialType.System_Byte: return (byte)nuintValue; case SpecialType.System_Char: return (char)nuintValue; case SpecialType.System_UInt16: return (ushort)nuintValue; case SpecialType.System_UInt32: return (uint)nuintValue; case SpecialType.System_UInt64: return (ulong)nuintValue; case SpecialType.System_SByte: return (sbyte)nuintValue; case SpecialType.System_Int16: return (short)nuintValue; case SpecialType.System_Int32: return (int)nuintValue; case SpecialType.System_Int64: return (long)nuintValue; case SpecialType.System_IntPtr: return (int)nuintValue; case SpecialType.System_Single: return (double)(float)nuintValue; case SpecialType.System_Double: return (double)nuintValue; case SpecialType.System_Decimal: return (decimal)nuintValue; default: throw ExceptionUtilities.UnexpectedValue(destinationType); } case ConstantValueTypeDiscriminator.SByte: sbyte sbyteValue = value.SByteValue; switch (destinationType) { case SpecialType.System_Byte: return (byte)sbyteValue; case SpecialType.System_Char: return (char)sbyteValue; case SpecialType.System_UInt16: return (ushort)sbyteValue; case SpecialType.System_UInt32: return (uint)sbyteValue; case SpecialType.System_UInt64: return (ulong)sbyteValue; case SpecialType.System_SByte: return (sbyte)sbyteValue; case SpecialType.System_Int16: return (short)sbyteValue; case SpecialType.System_Int32: return (int)sbyteValue; case SpecialType.System_Int64: return (long)sbyteValue; case SpecialType.System_IntPtr: return (int)sbyteValue; case SpecialType.System_UIntPtr: return (uint)sbyteValue; case SpecialType.System_Single: case SpecialType.System_Double: return (double)sbyteValue; case SpecialType.System_Decimal: return (decimal)sbyteValue; default: throw ExceptionUtilities.UnexpectedValue(destinationType); } case ConstantValueTypeDiscriminator.Int16: short int16Value = value.Int16Value; switch (destinationType) { case SpecialType.System_Byte: return (byte)int16Value; case SpecialType.System_Char: return (char)int16Value; case SpecialType.System_UInt16: return (ushort)int16Value; case SpecialType.System_UInt32: return (uint)int16Value; case SpecialType.System_UInt64: return (ulong)int16Value; case SpecialType.System_SByte: return (sbyte)int16Value; case SpecialType.System_Int16: return (short)int16Value; case SpecialType.System_Int32: return (int)int16Value; case SpecialType.System_Int64: return (long)int16Value; case SpecialType.System_IntPtr: return (int)int16Value; case SpecialType.System_UIntPtr: return (uint)int16Value; case SpecialType.System_Single: case SpecialType.System_Double: return (double)int16Value; case SpecialType.System_Decimal: return (decimal)int16Value; default: throw ExceptionUtilities.UnexpectedValue(destinationType); } case ConstantValueTypeDiscriminator.Int32: int int32Value = value.Int32Value; switch (destinationType) { case SpecialType.System_Byte: return (byte)int32Value; case SpecialType.System_Char: return (char)int32Value; case SpecialType.System_UInt16: return (ushort)int32Value; case SpecialType.System_UInt32: return (uint)int32Value; case SpecialType.System_UInt64: return (ulong)int32Value; case SpecialType.System_SByte: return (sbyte)int32Value; case SpecialType.System_Int16: return (short)int32Value; case SpecialType.System_Int32: return (int)int32Value; case SpecialType.System_Int64: return (long)int32Value; case SpecialType.System_IntPtr: return (int)int32Value; case SpecialType.System_UIntPtr: return (uint)int32Value; case SpecialType.System_Single: return (double)(float)int32Value; case SpecialType.System_Double: return (double)int32Value; case SpecialType.System_Decimal: return (decimal)int32Value; default: throw ExceptionUtilities.UnexpectedValue(destinationType); } case ConstantValueTypeDiscriminator.Int64: long int64Value = value.Int64Value; switch (destinationType) { case SpecialType.System_Byte: return (byte)int64Value; case SpecialType.System_Char: return (char)int64Value; case SpecialType.System_UInt16: return (ushort)int64Value; case SpecialType.System_UInt32: return (uint)int64Value; case SpecialType.System_UInt64: return (ulong)int64Value; case SpecialType.System_SByte: return (sbyte)int64Value; case SpecialType.System_Int16: return (short)int64Value; case SpecialType.System_Int32: return (int)int64Value; case SpecialType.System_Int64: return (long)int64Value; case SpecialType.System_IntPtr: return (int)int64Value; case SpecialType.System_UIntPtr: return (uint)int64Value; case SpecialType.System_Single: return (double)(float)int64Value; case SpecialType.System_Double: return (double)int64Value; case SpecialType.System_Decimal: return (decimal)int64Value; default: throw ExceptionUtilities.UnexpectedValue(destinationType); } case ConstantValueTypeDiscriminator.NInt: int nintValue = value.Int32Value; switch (destinationType) { case SpecialType.System_Byte: return (byte)nintValue; case SpecialType.System_Char: return (char)nintValue; case SpecialType.System_UInt16: return (ushort)nintValue; case SpecialType.System_UInt32: return (uint)nintValue; case SpecialType.System_UInt64: return (ulong)nintValue; case SpecialType.System_SByte: return (sbyte)nintValue; case SpecialType.System_Int16: return (short)nintValue; case SpecialType.System_Int32: return (int)nintValue; case SpecialType.System_Int64: return (long)nintValue; case SpecialType.System_IntPtr: return (int)nintValue; case SpecialType.System_UIntPtr: return (uint)nintValue; case SpecialType.System_Single: return (double)(float)nintValue; case SpecialType.System_Double: return (double)nintValue; case SpecialType.System_Decimal: return (decimal)nintValue; default: throw ExceptionUtilities.UnexpectedValue(destinationType); } case ConstantValueTypeDiscriminator.Single: case ConstantValueTypeDiscriminator.Double: // When converting from a floating-point type to an integral type, if the checked conversion would // throw an overflow exception, then the unchecked conversion is undefined. So that we have // identical behavior on every host platform, we yield a result of zero in that case. double doubleValue = CheckConstantBounds(destinationType, value.DoubleValue, out _) ? value.DoubleValue : 0D; switch (destinationType) { case SpecialType.System_Byte: return (byte)doubleValue; case SpecialType.System_Char: return (char)doubleValue; case SpecialType.System_UInt16: return (ushort)doubleValue; case SpecialType.System_UInt32: return (uint)doubleValue; case SpecialType.System_UInt64: return (ulong)doubleValue; case SpecialType.System_SByte: return (sbyte)doubleValue; case SpecialType.System_Int16: return (short)doubleValue; case SpecialType.System_Int32: return (int)doubleValue; case SpecialType.System_Int64: return (long)doubleValue; case SpecialType.System_IntPtr: return (int)doubleValue; case SpecialType.System_UIntPtr: return (uint)doubleValue; case SpecialType.System_Single: return (double)(float)doubleValue; case SpecialType.System_Double: return (double)doubleValue; case SpecialType.System_Decimal: return (value.Discriminator == ConstantValueTypeDiscriminator.Single) ? (decimal)(float)doubleValue : (decimal)doubleValue; default: throw ExceptionUtilities.UnexpectedValue(destinationType); } case ConstantValueTypeDiscriminator.Decimal: decimal decimalValue = CheckConstantBounds(destinationType, value.DecimalValue, out _) ? value.DecimalValue : 0m; switch (destinationType) { case SpecialType.System_Byte: return (byte)decimalValue; case SpecialType.System_Char: return (char)decimalValue; case SpecialType.System_UInt16: return (ushort)decimalValue; case SpecialType.System_UInt32: return (uint)decimalValue; case SpecialType.System_UInt64: return (ulong)decimalValue; case SpecialType.System_SByte: return (sbyte)decimalValue; case SpecialType.System_Int16: return (short)decimalValue; case SpecialType.System_Int32: return (int)decimalValue; case SpecialType.System_Int64: return (long)decimalValue; case SpecialType.System_IntPtr: return (int)decimalValue; case SpecialType.System_UIntPtr: return (uint)decimalValue; case SpecialType.System_Single: return (double)(float)decimalValue; case SpecialType.System_Double: return (double)decimalValue; case SpecialType.System_Decimal: return (decimal)decimalValue; default: throw ExceptionUtilities.UnexpectedValue(destinationType); } default: throw ExceptionUtilities.UnexpectedValue(value.Discriminator); } } // all cases should have been handled in the switch above. // return value.Value; } public static bool CheckConstantBounds(SpecialType destinationType, ConstantValue value, out bool maySucceedAtRuntime) { if (value.IsBad) { //assume that the constant was intended to be in bounds maySucceedAtRuntime = false; return true; } // Compute whether the value fits into the bounds of the given destination type without // error. We know that the constant will fit into either a double or a decimal, so // convert it to one of those and then check the bounds on that. var canonicalValue = CanonicalizeConstant(value); return canonicalValue is decimal ? CheckConstantBounds(destinationType, (decimal)canonicalValue, out maySucceedAtRuntime) : CheckConstantBounds(destinationType, (double)canonicalValue, out maySucceedAtRuntime); } private static bool CheckConstantBounds(SpecialType destinationType, double value, out bool maySucceedAtRuntime) { maySucceedAtRuntime = false; // Dev10 checks (minValue - 1) < value < (maxValue + 1). // See ExpressionBinder::isConstantInRange. switch (destinationType) { case SpecialType.System_Byte: return (byte.MinValue - 1D) < value && value < (byte.MaxValue + 1D); case SpecialType.System_Char: return (char.MinValue - 1D) < value && value < (char.MaxValue + 1D); case SpecialType.System_UInt16: return (ushort.MinValue - 1D) < value && value < (ushort.MaxValue + 1D); case SpecialType.System_UInt32: return (uint.MinValue - 1D) < value && value < (uint.MaxValue + 1D); case SpecialType.System_UInt64: return (ulong.MinValue - 1D) < value && value < (ulong.MaxValue + 1D); case SpecialType.System_SByte: return (sbyte.MinValue - 1D) < value && value < (sbyte.MaxValue + 1D); case SpecialType.System_Int16: return (short.MinValue - 1D) < value && value < (short.MaxValue + 1D); case SpecialType.System_Int32: return (int.MinValue - 1D) < value && value < (int.MaxValue + 1D); // Note: Using <= to compare the min value matches the native compiler. case SpecialType.System_Int64: return (long.MinValue - 1D) <= value && value < (long.MaxValue + 1D); case SpecialType.System_Decimal: return ((double)decimal.MinValue - 1D) < value && value < ((double)decimal.MaxValue + 1D); case SpecialType.System_IntPtr: maySucceedAtRuntime = (long.MinValue - 1D) < value && value < (long.MaxValue + 1D); return (int.MinValue - 1D) < value && value < (int.MaxValue + 1D); case SpecialType.System_UIntPtr: maySucceedAtRuntime = (ulong.MinValue - 1D) < value && value < (ulong.MaxValue + 1D); return (uint.MinValue - 1D) < value && value < (uint.MaxValue + 1D); } return true; } private static bool CheckConstantBounds(SpecialType destinationType, decimal value, out bool maySucceedAtRuntime) { maySucceedAtRuntime = false; // Dev10 checks (minValue - 1) < value < (maxValue + 1). // See ExpressionBinder::isConstantInRange. switch (destinationType) { case SpecialType.System_Byte: return (byte.MinValue - 1M) < value && value < (byte.MaxValue + 1M); case SpecialType.System_Char: return (char.MinValue - 1M) < value && value < (char.MaxValue + 1M); case SpecialType.System_UInt16: return (ushort.MinValue - 1M) < value && value < (ushort.MaxValue + 1M); case SpecialType.System_UInt32: return (uint.MinValue - 1M) < value && value < (uint.MaxValue + 1M); case SpecialType.System_UInt64: return (ulong.MinValue - 1M) < value && value < (ulong.MaxValue + 1M); case SpecialType.System_SByte: return (sbyte.MinValue - 1M) < value && value < (sbyte.MaxValue + 1M); case SpecialType.System_Int16: return (short.MinValue - 1M) < value && value < (short.MaxValue + 1M); case SpecialType.System_Int32: return (int.MinValue - 1M) < value && value < (int.MaxValue + 1M); case SpecialType.System_Int64: return (long.MinValue - 1M) < value && value < (long.MaxValue + 1M); case SpecialType.System_IntPtr: maySucceedAtRuntime = (long.MinValue - 1M) < value && value < (long.MaxValue + 1M); return (int.MinValue - 1M) < value && value < (int.MaxValue + 1M); case SpecialType.System_UIntPtr: maySucceedAtRuntime = (ulong.MinValue - 1M) < value && value < (ulong.MaxValue + 1M); return (uint.MinValue - 1M) < value && value < (uint.MaxValue + 1M); } return true; } // Takes in a constant of any kind and returns the constant as either a double or decimal private static object CanonicalizeConstant(ConstantValue value) { switch (value.Discriminator) { case ConstantValueTypeDiscriminator.SByte: return (decimal)value.SByteValue; case ConstantValueTypeDiscriminator.Int16: return (decimal)value.Int16Value; case ConstantValueTypeDiscriminator.Int32: return (decimal)value.Int32Value; case ConstantValueTypeDiscriminator.Int64: return (decimal)value.Int64Value; case ConstantValueTypeDiscriminator.NInt: return (decimal)value.Int32Value; case ConstantValueTypeDiscriminator.Byte: return (decimal)value.ByteValue; case ConstantValueTypeDiscriminator.Char: return (decimal)value.CharValue; case ConstantValueTypeDiscriminator.UInt16: return (decimal)value.UInt16Value; case ConstantValueTypeDiscriminator.UInt32: return (decimal)value.UInt32Value; case ConstantValueTypeDiscriminator.UInt64: return (decimal)value.UInt64Value; case ConstantValueTypeDiscriminator.NUInt: return (decimal)value.UInt32Value; case ConstantValueTypeDiscriminator.Single: case ConstantValueTypeDiscriminator.Double: return value.DoubleValue; case ConstantValueTypeDiscriminator.Decimal: return value.DecimalValue; default: throw ExceptionUtilities.UnexpectedValue(value.Discriminator); } // all cases handled in the switch, above. } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { internal partial class Binder { internal BoundExpression CreateConversion( BoundExpression source, TypeSymbol destination, BindingDiagnosticBag diagnostics) { CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); var conversion = Conversions.ClassifyConversionFromExpression(source, destination, ref useSiteInfo); diagnostics.Add(source.Syntax, useSiteInfo); return CreateConversion(source.Syntax, source, conversion, isCast: false, conversionGroupOpt: null, destination: destination, diagnostics: diagnostics); } internal BoundExpression CreateConversion( BoundExpression source, Conversion conversion, TypeSymbol destination, BindingDiagnosticBag diagnostics) { return CreateConversion(source.Syntax, source, conversion, isCast: false, conversionGroupOpt: null, destination: destination, diagnostics: diagnostics); } internal BoundExpression CreateConversion( SyntaxNode syntax, BoundExpression source, Conversion conversion, bool isCast, ConversionGroup? conversionGroupOpt, TypeSymbol destination, BindingDiagnosticBag diagnostics) { return CreateConversion(syntax, source, conversion, isCast: isCast, conversionGroupOpt, source.WasCompilerGenerated, destination, diagnostics); } protected BoundExpression CreateConversion( SyntaxNode syntax, BoundExpression source, Conversion conversion, bool isCast, ConversionGroup? conversionGroupOpt, bool wasCompilerGenerated, TypeSymbol destination, BindingDiagnosticBag diagnostics, bool hasErrors = false) { RoslynDebug.Assert(source != null); RoslynDebug.Assert((object)destination != null); RoslynDebug.Assert(!isCast || conversionGroupOpt != null); if (conversion.IsIdentity) { if (source is BoundTupleLiteral sourceTuple) { NamedTypeSymbol.ReportTupleNamesMismatchesIfAny(destination, sourceTuple, diagnostics); } // identity tuple and switch conversions result in a converted expression // to indicate that such conversions are no longer applicable. source = BindToNaturalType(source, diagnostics); RoslynDebug.Assert(source.Type is object); // We need to preserve any conversion that changes the type (even identity conversions, like object->dynamic), // or that was explicitly written in code (so that GetSemanticInfo can find the syntax in the bound tree). if (!isCast && source.Type.Equals(destination, TypeCompareKind.IgnoreNullableModifiersForReferenceTypes)) { return source; } } if (conversion.IsMethodGroup) { return CreateMethodGroupConversion(syntax, source, conversion, isCast: isCast, conversionGroupOpt, destination, diagnostics); } // Obsolete diagnostics for method group are reported as part of creating the method group conversion. ReportDiagnosticsIfObsolete(diagnostics, conversion, syntax, hasBaseReceiver: false); CheckConstraintLanguageVersionAndRuntimeSupportForConversion(syntax, conversion, diagnostics); if (conversion.IsAnonymousFunction && source.Kind == BoundKind.UnboundLambda) { return CreateAnonymousFunctionConversion(syntax, source, conversion, isCast: isCast, conversionGroupOpt, destination, diagnostics); } if (conversion.IsStackAlloc) { return CreateStackAllocConversion(syntax, source, conversion, isCast, conversionGroupOpt, destination, diagnostics); } if (conversion.IsTupleLiteralConversion || (conversion.IsNullable && conversion.UnderlyingConversions[0].IsTupleLiteralConversion)) { return CreateTupleLiteralConversion(syntax, (BoundTupleLiteral)source, conversion, isCast: isCast, conversionGroupOpt, destination, diagnostics); } if (conversion.Kind == ConversionKind.SwitchExpression) { var convertedSwitch = ConvertSwitchExpression((BoundUnconvertedSwitchExpression)source, destination, conversionIfTargetTyped: conversion, diagnostics); return new BoundConversion( syntax, convertedSwitch, conversion, CheckOverflowAtRuntime, explicitCastInCode: isCast && !wasCompilerGenerated, conversionGroupOpt, convertedSwitch.ConstantValue, destination, hasErrors); } if (conversion.Kind == ConversionKind.ConditionalExpression) { var convertedConditional = ConvertConditionalExpression((BoundUnconvertedConditionalOperator)source, destination, conversionIfTargetTyped: conversion, diagnostics); return new BoundConversion( syntax, convertedConditional, conversion, CheckOverflowAtRuntime, explicitCastInCode: isCast && !wasCompilerGenerated, conversionGroupOpt, convertedConditional.ConstantValue, destination, hasErrors); } if (conversion.Kind == ConversionKind.InterpolatedString) { var unconvertedSource = (BoundUnconvertedInterpolatedString)source; source = new BoundInterpolatedString( unconvertedSource.Syntax, interpolationData: null, BindInterpolatedStringParts(unconvertedSource, diagnostics), unconvertedSource.ConstantValue, unconvertedSource.Type, unconvertedSource.HasErrors); } if (conversion.Kind == ConversionKind.InterpolatedStringHandler) { var unconvertedSource = (BoundUnconvertedInterpolatedString)source; return new BoundConversion( syntax, BindUnconvertedInterpolatedStringToHandlerType(unconvertedSource, (NamedTypeSymbol)destination, diagnostics, isHandlerConversion: true), conversion, @checked: CheckOverflowAtRuntime, explicitCastInCode: isCast && !wasCompilerGenerated, conversionGroupOpt, constantValueOpt: null, destination); } if (source.Kind == BoundKind.UnconvertedSwitchExpression) { TypeSymbol? type = source.Type; if (type is null) { Debug.Assert(!conversion.Exists); type = CreateErrorType(); hasErrors = true; } source = ConvertSwitchExpression((BoundUnconvertedSwitchExpression)source, type, conversionIfTargetTyped: null, diagnostics, hasErrors); if (destination.Equals(type, TypeCompareKind.ConsiderEverything) && wasCompilerGenerated) { return source; } } if (conversion.IsObjectCreation) { return ConvertObjectCreationExpression(syntax, (BoundUnconvertedObjectCreationExpression)source, isCast, destination, diagnostics); } if (source.Kind == BoundKind.UnconvertedConditionalOperator) { TypeSymbol? type = source.Type; if (type is null) { Debug.Assert(!conversion.Exists); type = CreateErrorType(); hasErrors = true; } source = ConvertConditionalExpression((BoundUnconvertedConditionalOperator)source, type, conversionIfTargetTyped: null, diagnostics, hasErrors); if (destination.Equals(type, TypeCompareKind.ConsiderEverything) && wasCompilerGenerated) { return source; } } if (conversion.IsUserDefined) { // User-defined conversions are likely to be represented as multiple // BoundConversion instances so a ConversionGroup is necessary. return CreateUserDefinedConversion(syntax, source, conversion, isCast: isCast, conversionGroupOpt ?? new ConversionGroup(conversion), destination, diagnostics, hasErrors); } ConstantValue? constantValue = this.FoldConstantConversion(syntax, source, conversion, destination, diagnostics); if (conversion.Kind == ConversionKind.DefaultLiteral) { source = new BoundDefaultExpression(source.Syntax, targetType: null, constantValue, type: destination) .WithSuppression(source.IsSuppressed); } return new BoundConversion( syntax, BindToNaturalType(source, diagnostics), conversion, @checked: CheckOverflowAtRuntime, explicitCastInCode: isCast && !wasCompilerGenerated, conversionGroupOpt, constantValueOpt: constantValue, type: destination, hasErrors: hasErrors) { WasCompilerGenerated = wasCompilerGenerated }; } internal void CheckConstraintLanguageVersionAndRuntimeSupportForConversion(SyntaxNodeOrToken syntax, Conversion conversion, BindingDiagnosticBag diagnostics) { if (conversion.IsUserDefined && conversion.Method is MethodSymbol method && method.IsStatic && method.IsAbstract) { Debug.Assert(conversion.ConstrainedToTypeOpt is TypeParameterSymbol); if (Compilation.SourceModule != method.ContainingModule) { Debug.Assert(syntax.SyntaxTree is object); CheckFeatureAvailability(syntax.SyntaxTree, MessageID.IDS_FeatureStaticAbstractMembersInInterfaces, diagnostics, syntax.GetLocation()!); if (!Compilation.Assembly.RuntimeSupportsStaticAbstractMembersInInterfaces) { Error(diagnostics, ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, syntax); } } } } private BoundExpression ConvertObjectCreationExpression(SyntaxNode syntax, BoundUnconvertedObjectCreationExpression node, bool isCast, TypeSymbol destination, BindingDiagnosticBag diagnostics) { var arguments = AnalyzedArguments.GetInstance(node.Arguments, node.ArgumentRefKindsOpt, node.ArgumentNamesOpt); BoundExpression expr = BindObjectCreationExpression(node, destination.StrippedType(), arguments, diagnostics); if (destination.IsNullableType()) { // We manually create an ImplicitNullable conversion // if the destination is nullable, in which case we // target the underlying type e.g. `S? x = new();` // is actually identical to `S? x = new S();`. CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); var conversion = Conversions.ClassifyStandardConversion(null, expr.Type, destination, ref useSiteInfo); expr = new BoundConversion( node.Syntax, operand: expr, conversion: conversion, @checked: false, explicitCastInCode: isCast, conversionGroupOpt: new ConversionGroup(conversion), constantValueOpt: expr.ConstantValue, type: destination); diagnostics.Add(syntax, useSiteInfo); } arguments.Free(); return expr; } private BoundExpression BindObjectCreationExpression(BoundUnconvertedObjectCreationExpression node, TypeSymbol type, AnalyzedArguments arguments, BindingDiagnosticBag diagnostics) { var syntax = node.Syntax; switch (type.TypeKind) { case TypeKind.Enum: case TypeKind.Struct: case TypeKind.Class when !type.IsAnonymousType: // We don't want to enable object creation with unspeakable types return BindClassCreationExpression(syntax, type.Name, typeNode: syntax, (NamedTypeSymbol)type, arguments, diagnostics, node.InitializerOpt, wasTargetTyped: true); case TypeKind.TypeParameter: return BindTypeParameterCreationExpression(syntax, (TypeParameterSymbol)type, arguments, node.InitializerOpt, typeSyntax: syntax, diagnostics); case TypeKind.Delegate: return BindDelegateCreationExpression(syntax, (NamedTypeSymbol)type, arguments, node.InitializerOpt, diagnostics); case TypeKind.Interface: return BindInterfaceCreationExpression(syntax, (NamedTypeSymbol)type, diagnostics, typeNode: syntax, arguments, node.InitializerOpt, wasTargetTyped: true); case TypeKind.Array: case TypeKind.Class: case TypeKind.Dynamic: Error(diagnostics, ErrorCode.ERR_ImplicitObjectCreationIllegalTargetType, syntax, type); goto case TypeKind.Error; case TypeKind.Pointer: case TypeKind.FunctionPointer: Error(diagnostics, ErrorCode.ERR_UnsafeTypeInObjectCreation, syntax, type); goto case TypeKind.Error; case TypeKind.Error: return MakeBadExpressionForObjectCreation(syntax, type, arguments, node.InitializerOpt, typeSyntax: syntax, diagnostics); case var v: throw ExceptionUtilities.UnexpectedValue(v); } } /// <summary> /// Rewrite the subexpressions in a conditional expression to convert the whole thing to the destination type. /// </summary> private BoundExpression ConvertConditionalExpression( BoundUnconvertedConditionalOperator source, TypeSymbol destination, Conversion? conversionIfTargetTyped, BindingDiagnosticBag diagnostics, bool hasErrors = false) { bool targetTyped = conversionIfTargetTyped is { }; Debug.Assert(targetTyped || destination.IsErrorType() || destination.Equals(source.Type, TypeCompareKind.ConsiderEverything)); ImmutableArray<Conversion> underlyingConversions = conversionIfTargetTyped.GetValueOrDefault().UnderlyingConversions; var condition = source.Condition; hasErrors |= source.HasErrors || destination.IsErrorType(); var trueExpr = targetTyped ? CreateConversion(source.Consequence.Syntax, source.Consequence, underlyingConversions[0], isCast: false, conversionGroupOpt: null, destination, diagnostics) : GenerateConversionForAssignment(destination, source.Consequence, diagnostics); var falseExpr = targetTyped ? CreateConversion(source.Alternative.Syntax, source.Alternative, underlyingConversions[1], isCast: false, conversionGroupOpt: null, destination, diagnostics) : GenerateConversionForAssignment(destination, source.Alternative, diagnostics); var constantValue = FoldConditionalOperator(condition, trueExpr, falseExpr); hasErrors |= constantValue?.IsBad == true; if (targetTyped && !destination.IsErrorType() && !Compilation.IsFeatureEnabled(MessageID.IDS_FeatureTargetTypedConditional)) { diagnostics.Add( ErrorCode.ERR_NoImplicitConvTargetTypedConditional, source.Syntax.Location, Compilation.LanguageVersion.ToDisplayString(), source.Consequence.Display, source.Alternative.Display, new CSharpRequiredLanguageVersion(MessageID.IDS_FeatureTargetTypedConditional.RequiredVersion())); } return new BoundConditionalOperator(source.Syntax, isRef: false, condition, trueExpr, falseExpr, constantValue, source.Type, wasTargetTyped: targetTyped, destination, hasErrors) .WithSuppression(source.IsSuppressed); } /// <summary> /// Rewrite the expressions in the switch expression arms to add a conversion to the destination type. /// </summary> private BoundExpression ConvertSwitchExpression(BoundUnconvertedSwitchExpression source, TypeSymbol destination, Conversion? conversionIfTargetTyped, BindingDiagnosticBag diagnostics, bool hasErrors = false) { bool targetTyped = conversionIfTargetTyped is { }; Conversion conversion = conversionIfTargetTyped ?? Conversion.Identity; Debug.Assert(targetTyped || destination.IsErrorType() || destination.Equals(source.Type, TypeCompareKind.ConsiderEverything)); ImmutableArray<Conversion> underlyingConversions = conversion.UnderlyingConversions; var builder = ArrayBuilder<BoundSwitchExpressionArm>.GetInstance(source.SwitchArms.Length); for (int i = 0, n = source.SwitchArms.Length; i < n; i++) { var oldCase = source.SwitchArms[i]; Debug.Assert(oldCase.Syntax is SwitchExpressionArmSyntax); var binder = GetRequiredBinder(oldCase.Syntax); var oldValue = oldCase.Value; var newValue = targetTyped ? binder.CreateConversion(oldValue.Syntax, oldValue, underlyingConversions[i], isCast: false, conversionGroupOpt: null, destination, diagnostics) : binder.GenerateConversionForAssignment(destination, oldValue, diagnostics); var newCase = (oldValue == newValue) ? oldCase : new BoundSwitchExpressionArm(oldCase.Syntax, oldCase.Locals, oldCase.Pattern, oldCase.WhenClause, newValue, oldCase.Label, oldCase.HasErrors); builder.Add(newCase); } var newSwitchArms = builder.ToImmutableAndFree(); return new BoundConvertedSwitchExpression( source.Syntax, source.Type, targetTyped, conversion, source.Expression, newSwitchArms, source.DecisionDag, source.DefaultLabel, source.ReportedNotExhaustive, destination, hasErrors || source.HasErrors); } private BoundExpression CreateUserDefinedConversion( SyntaxNode syntax, BoundExpression source, Conversion conversion, bool isCast, ConversionGroup conversionGroup, TypeSymbol destination, BindingDiagnosticBag diagnostics, bool hasErrors) { Debug.Assert(conversionGroup != null); Debug.Assert(conversion.IsUserDefined); if (!conversion.IsValid) { if (!hasErrors) GenerateImplicitConversionError(diagnostics, syntax, conversion, source, destination); return new BoundConversion( syntax, source, conversion, CheckOverflowAtRuntime, explicitCastInCode: isCast, conversionGroup, constantValueOpt: ConstantValue.NotAvailable, type: destination, hasErrors: true) { WasCompilerGenerated = source.WasCompilerGenerated }; } // Due to an oddity in the way we create a non-lifted user-defined conversion from A to D? // (required backwards compatibility with the native compiler) we can end up in a situation // where we have: // a standard conversion from A to B? // then a standard conversion from B? to B // then a user-defined conversion from B to C // then a standard conversion from C to C? // then a standard conversion from C? to D? // // In that scenario, the "from type" of the conversion will be B? and the "from conversion" will be // from A to B?. Similarly the "to type" of the conversion will be C? and the "to conversion" // of the conversion will be from C? to D?. // // Therefore, we might need to introduce an extra conversion on the source side, from B? to B. // Now, you might think we should also introduce an extra conversion on the destination side, // from C to C?. But that then gives us the following bad situation: If we in fact bind this as // // (D?)(C?)(C)(B)(B?)(A)x // // then what we are in effect doing is saying "convert C? to D? by checking for null, unwrapping, // converting C to D, and then wrapping". But we know that the C? will never be null. In this case // we should actually generate // // (D?)(C)(B)(B?)(A)x // // And thereby skip the unnecessary nullable conversion. Debug.Assert(conversion.BestUserDefinedConversionAnalysis is object); // All valid user-defined conversions have this populated // Original expression --> conversion's "from" type BoundExpression convertedOperand = CreateConversion( syntax: source.Syntax, source: source, conversion: conversion.UserDefinedFromConversion, isCast: false, conversionGroupOpt: conversionGroup, wasCompilerGenerated: false, destination: conversion.BestUserDefinedConversionAnalysis.FromType, diagnostics: diagnostics); TypeSymbol conversionParameterType = conversion.BestUserDefinedConversionAnalysis.Operator.GetParameterType(0); CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); if (conversion.BestUserDefinedConversionAnalysis.Kind == UserDefinedConversionAnalysisKind.ApplicableInNormalForm && !TypeSymbol.Equals(conversion.BestUserDefinedConversionAnalysis.FromType, conversionParameterType, TypeCompareKind.ConsiderEverything2)) { // Conversion's "from" type --> conversion method's parameter type. convertedOperand = CreateConversion( syntax: syntax, source: convertedOperand, conversion: Conversions.ClassifyStandardConversion(null, convertedOperand.Type, conversionParameterType, ref useSiteInfo), isCast: false, conversionGroupOpt: conversionGroup, wasCompilerGenerated: true, destination: conversionParameterType, diagnostics: diagnostics); } BoundExpression userDefinedConversion; TypeSymbol conversionReturnType = conversion.BestUserDefinedConversionAnalysis.Operator.ReturnType; TypeSymbol conversionToType = conversion.BestUserDefinedConversionAnalysis.ToType; Conversion toConversion = conversion.UserDefinedToConversion; if (conversion.BestUserDefinedConversionAnalysis.Kind == UserDefinedConversionAnalysisKind.ApplicableInNormalForm && !TypeSymbol.Equals(conversionToType, conversionReturnType, TypeCompareKind.ConsiderEverything2)) { // Conversion method's parameter type --> conversion method's return type // NB: not calling CreateConversion here because this is the recursive base case. userDefinedConversion = new BoundConversion( syntax, convertedOperand, conversion, @checked: false, // There are no checked user-defined conversions, but the conversions on either side might be checked. explicitCastInCode: isCast, conversionGroup, constantValueOpt: ConstantValue.NotAvailable, type: conversionReturnType) { WasCompilerGenerated = true }; if (conversionToType.IsNullableType() && TypeSymbol.Equals(conversionToType.GetNullableUnderlyingType(), conversionReturnType, TypeCompareKind.ConsiderEverything2)) { // Skip introducing the conversion from C to C?. The "to" conversion is now wrong though, // because it will still assume converting C? to D?. toConversion = Conversions.ClassifyConversionFromType(conversionReturnType, destination, ref useSiteInfo); Debug.Assert(toConversion.Exists); } else { // Conversion method's return type --> conversion's "to" type userDefinedConversion = CreateConversion( syntax: syntax, source: userDefinedConversion, conversion: Conversions.ClassifyStandardConversion(null, conversionReturnType, conversionToType, ref useSiteInfo), isCast: false, conversionGroupOpt: conversionGroup, wasCompilerGenerated: true, destination: conversionToType, diagnostics: diagnostics); } } else { // Conversion method's parameter type --> conversion method's "to" type // NB: not calling CreateConversion here because this is the recursive base case. userDefinedConversion = new BoundConversion( syntax, convertedOperand, conversion, @checked: false, explicitCastInCode: isCast, conversionGroup, constantValueOpt: ConstantValue.NotAvailable, type: conversionToType) { WasCompilerGenerated = true }; } diagnostics.Add(syntax, useSiteInfo); // Conversion's "to" type --> final type BoundExpression finalConversion = CreateConversion( syntax: syntax, source: userDefinedConversion, conversion: toConversion, isCast: false, conversionGroupOpt: conversionGroup, wasCompilerGenerated: true, // NOTE: doesn't necessarily set flag on resulting bound expression. destination: destination, diagnostics: diagnostics); finalConversion.ResetCompilerGenerated(source.WasCompilerGenerated); return finalConversion; } private BoundExpression CreateAnonymousFunctionConversion(SyntaxNode syntax, BoundExpression source, Conversion conversion, bool isCast, ConversionGroup? conversionGroup, TypeSymbol destination, BindingDiagnosticBag diagnostics) { // We have a successful anonymous function conversion; rather than producing a node // which is a conversion on top of an unbound lambda, replace it with the bound // lambda. // UNDONE: Figure out what to do about the error case, where a lambda // UNDONE: is converted to a delegate that does not match. What to surface then? var unboundLambda = (UnboundLambda)source; if ((destination.SpecialType == SpecialType.System_Delegate || destination.IsNonGenericExpressionType()) && syntax.IsFeatureEnabled(MessageID.IDS_FeatureInferredDelegateType)) { CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); var delegateType = unboundLambda.InferDelegateType(ref useSiteInfo); BoundLambda boundLambda; if (delegateType is { }) { bool isExpressionTree = destination.IsNonGenericExpressionType(); if (isExpressionTree) { delegateType = Compilation.GetWellKnownType(WellKnownType.System_Linq_Expressions_Expression_T).Construct(delegateType); delegateType.AddUseSiteInfo(ref useSiteInfo); } boundLambda = unboundLambda.Bind(delegateType, isExpressionTree); } else { diagnostics.Add(ErrorCode.ERR_CannotInferDelegateType, syntax.GetLocation()); delegateType = CreateErrorType(); boundLambda = unboundLambda.BindForErrorRecovery(); } diagnostics.AddRange(boundLambda.Diagnostics); var expr = createAnonymousFunctionConversion(syntax, source, boundLambda, conversion, isCast, conversionGroup, delegateType); conversion = Conversions.ClassifyConversionFromExpression(expr, destination, ref useSiteInfo); diagnostics.Add(syntax, useSiteInfo); return CreateConversion(syntax, expr, conversion, isCast, conversionGroup, destination, diagnostics); } else { #if DEBUG // Test inferring a delegate type for all callers. var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; _ = unboundLambda.InferDelegateType(ref discardedUseSiteInfo); #endif var boundLambda = unboundLambda.Bind((NamedTypeSymbol)destination, isExpressionTree: destination.IsGenericOrNonGenericExpressionType(out _)); diagnostics.AddRange(boundLambda.Diagnostics); return createAnonymousFunctionConversion(syntax, source, boundLambda, conversion, isCast, conversionGroup, destination); } static BoundConversion createAnonymousFunctionConversion(SyntaxNode syntax, BoundExpression source, BoundLambda boundLambda, Conversion conversion, bool isCast, ConversionGroup? conversionGroup, TypeSymbol destination) { return new BoundConversion( syntax, boundLambda, conversion, @checked: false, explicitCastInCode: isCast, conversionGroup, constantValueOpt: ConstantValue.NotAvailable, type: destination) { WasCompilerGenerated = source.WasCompilerGenerated }; } } private BoundExpression CreateMethodGroupConversion(SyntaxNode syntax, BoundExpression source, Conversion conversion, bool isCast, ConversionGroup? conversionGroup, TypeSymbol destination, BindingDiagnosticBag diagnostics) { var (originalGroup, isAddressOf) = source switch { BoundMethodGroup m => (m, false), BoundUnconvertedAddressOfOperator { Operand: { } m } => (m, true), _ => throw ExceptionUtilities.UnexpectedValue(source), }; BoundMethodGroup group = FixMethodGroupWithTypeOrValue(originalGroup, conversion, diagnostics); bool hasErrors = false; if (MethodGroupConversionHasErrors(syntax, conversion, group.ReceiverOpt, conversion.IsExtensionMethod, isAddressOf, destination, diagnostics)) { hasErrors = true; } if (destination.SpecialType == SpecialType.System_Delegate && syntax.IsFeatureEnabled(MessageID.IDS_FeatureInferredDelegateType)) { // https://github.com/dotnet/roslyn/issues/52869: Avoid calculating the delegate type multiple times during conversion. CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); var delegateType = GetMethodGroupDelegateType(group, ref useSiteInfo); var expr = createMethodGroupConversion(syntax, group, conversion, isCast, conversionGroup, delegateType!, hasErrors); conversion = Conversions.ClassifyConversionFromExpression(expr, destination, ref useSiteInfo); diagnostics.Add(syntax, useSiteInfo); return CreateConversion(syntax, expr, conversion, isCast, conversionGroup, destination, diagnostics); } #if DEBUG // Test inferring a delegate type for all callers. var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; _ = GetMethodGroupDelegateType(group, ref discardedUseSiteInfo); #endif return createMethodGroupConversion(syntax, group, conversion, isCast, conversionGroup, destination, hasErrors); static BoundConversion createMethodGroupConversion(SyntaxNode syntax, BoundMethodGroup group, Conversion conversion, bool isCast, ConversionGroup? conversionGroup, TypeSymbol destination, bool hasErrors) { return new BoundConversion(syntax, group, conversion, @checked: false, explicitCastInCode: isCast, conversionGroup, constantValueOpt: ConstantValue.NotAvailable, type: destination, hasErrors: hasErrors) { WasCompilerGenerated = group.WasCompilerGenerated }; } } private BoundExpression CreateStackAllocConversion(SyntaxNode syntax, BoundExpression source, Conversion conversion, bool isCast, ConversionGroup? conversionGroup, TypeSymbol destination, BindingDiagnosticBag diagnostics) { Debug.Assert(conversion.IsStackAlloc); var boundStackAlloc = (BoundStackAllocArrayCreation)source; var elementType = boundStackAlloc.ElementType; TypeSymbol stackAllocType; switch (conversion.Kind) { case ConversionKind.StackAllocToPointerType: ReportUnsafeIfNotAllowed(syntax.Location, diagnostics); stackAllocType = new PointerTypeSymbol(TypeWithAnnotations.Create(elementType)); break; case ConversionKind.StackAllocToSpanType: CheckFeatureAvailability(syntax, MessageID.IDS_FeatureRefStructs, diagnostics); stackAllocType = Compilation.GetWellKnownType(WellKnownType.System_Span_T).Construct(elementType); break; default: throw ExceptionUtilities.UnexpectedValue(conversion.Kind); } var convertedNode = new BoundConvertedStackAllocExpression(syntax, elementType, boundStackAlloc.Count, boundStackAlloc.InitializerOpt, stackAllocType, boundStackAlloc.HasErrors); var underlyingConversion = conversion.UnderlyingConversions.Single(); return CreateConversion(syntax, convertedNode, underlyingConversion, isCast: isCast, conversionGroup, destination, diagnostics); } private BoundExpression CreateTupleLiteralConversion(SyntaxNode syntax, BoundTupleLiteral sourceTuple, Conversion conversion, bool isCast, ConversionGroup? conversionGroup, TypeSymbol destination, BindingDiagnosticBag diagnostics) { // We have a successful tuple conversion; rather than producing a separate conversion node // which is a conversion on top of a tuple literal, tuple conversion is an element-wise conversion of arguments. Debug.Assert(conversion.IsNullable == destination.IsNullableType()); var destinationWithoutNullable = destination; var conversionWithoutNullable = conversion; if (conversion.IsNullable) { destinationWithoutNullable = destination.GetNullableUnderlyingType(); conversionWithoutNullable = conversion.UnderlyingConversions[0]; } Debug.Assert(conversionWithoutNullable.IsTupleLiteralConversion); NamedTypeSymbol targetType = (NamedTypeSymbol)destinationWithoutNullable; if (targetType.IsTupleType) { NamedTypeSymbol.ReportTupleNamesMismatchesIfAny(targetType, sourceTuple, diagnostics); // do not lose the original element names and locations in the literal if different from names in the target // // the tuple has changed the type of elements due to target-typing, // but element names has not changed and locations of their declarations // should not be confused with element locations on the target type. if (sourceTuple.Type is NamedTypeSymbol { IsTupleType: true } sourceType) { targetType = targetType.WithTupleDataFrom(sourceType); } else { var tupleSyntax = (TupleExpressionSyntax)sourceTuple.Syntax; var locationBuilder = ArrayBuilder<Location?>.GetInstance(); foreach (var argument in tupleSyntax.Arguments) { locationBuilder.Add(argument.NameColon?.Name.Location); } targetType = targetType.WithElementNames(sourceTuple.ArgumentNamesOpt!, locationBuilder.ToImmutableAndFree(), errorPositions: default, ImmutableArray.Create(tupleSyntax.Location)); } } var arguments = sourceTuple.Arguments; var convertedArguments = ArrayBuilder<BoundExpression>.GetInstance(arguments.Length); var targetElementTypes = targetType.TupleElementTypesWithAnnotations; Debug.Assert(targetElementTypes.Length == arguments.Length, "converting a tuple literal to incompatible type?"); var underlyingConversions = conversionWithoutNullable.UnderlyingConversions; for (int i = 0; i < arguments.Length; i++) { var argument = arguments[i]; var destType = targetElementTypes[i]; var elementConversion = underlyingConversions[i]; var elementConversionGroup = isCast ? new ConversionGroup(elementConversion, destType) : null; convertedArguments.Add(CreateConversion(argument.Syntax, argument, elementConversion, isCast: isCast, elementConversionGroup, destType.Type, diagnostics)); } BoundExpression result = new BoundConvertedTupleLiteral( sourceTuple.Syntax, sourceTuple, wasTargetTyped: true, convertedArguments.ToImmutableAndFree(), sourceTuple.ArgumentNamesOpt, sourceTuple.InferredNamesOpt, targetType).WithSuppression(sourceTuple.IsSuppressed); if (!TypeSymbol.Equals(sourceTuple.Type, destination, TypeCompareKind.ConsiderEverything2)) { // literal cast is applied to the literal result = new BoundConversion( sourceTuple.Syntax, result, conversion, @checked: false, explicitCastInCode: isCast, conversionGroup, constantValueOpt: ConstantValue.NotAvailable, type: destination); } // If we had a cast in the code, keep conversion in the tree. // even though the literal is already converted to the target type. if (isCast) { result = new BoundConversion( syntax, result, Conversion.Identity, @checked: false, explicitCastInCode: isCast, conversionGroup, constantValueOpt: ConstantValue.NotAvailable, type: destination); } return result; } private static bool IsMethodGroupWithTypeOrValueReceiver(BoundNode node) { if (node.Kind != BoundKind.MethodGroup) { return false; } return Binder.IsTypeOrValueExpression(((BoundMethodGroup)node).ReceiverOpt); } private BoundMethodGroup FixMethodGroupWithTypeOrValue(BoundMethodGroup group, Conversion conversion, BindingDiagnosticBag diagnostics) { if (!IsMethodGroupWithTypeOrValueReceiver(group)) { return group; } BoundExpression? receiverOpt = group.ReceiverOpt; RoslynDebug.Assert(receiverOpt != null); receiverOpt = ReplaceTypeOrValueReceiver(receiverOpt, useType: conversion.Method?.RequiresInstanceReceiver == false && !conversion.IsExtensionMethod, diagnostics); return group.Update( group.TypeArgumentsOpt, group.Name, group.Methods, group.LookupSymbolOpt, group.LookupError, group.Flags, receiverOpt, //only change group.ResultKind); } /// <summary> /// This method implements the algorithm in spec section 7.6.5.1. /// /// For method group conversions, there are situations in which the conversion is /// considered to exist ("Otherwise the algorithm produces a single best method M having /// the same number of parameters as D and the conversion is considered to exist"), but /// application of the conversion fails. These are the "final validation" steps of /// overload resolution. /// </summary> /// <returns> /// True if there is any error, except lack of runtime support errors. /// </returns> private bool MemberGroupFinalValidation(BoundExpression? receiverOpt, MethodSymbol methodSymbol, SyntaxNode node, BindingDiagnosticBag diagnostics, bool invokedAsExtensionMethod) { if (!IsBadBaseAccess(node, receiverOpt, methodSymbol, diagnostics)) { CheckReceiverAndRuntimeSupportForSymbolAccess(node, receiverOpt, methodSymbol, diagnostics); } if (MemberGroupFinalValidationAccessibilityChecks(receiverOpt, methodSymbol, node, diagnostics, invokedAsExtensionMethod)) { return true; } // SPEC: If the best method is a generic method, the type arguments (supplied or inferred) are checked against the constraints // SPEC: declared on the generic method. If any type argument does not satisfy the corresponding constraint(s) on // SPEC: the type parameter, a binding-time error occurs. // The portion of the overload resolution spec quoted above is subtle and somewhat // controversial. The upshot of this is that overload resolution does not consider // constraints to be a part of the signature. Overload resolution matches arguments to // parameter lists; it does not consider things which are outside of the parameter list. // If the best match from the arguments to the formal parameters is not viable then we // give an error rather than falling back to a worse match. // // Consider the following: // // void M<T>(T t) where T : Reptile {} // void M(object x) {} // ... // M(new Giraffe()); // // The correct analysis is to determine that the applicable candidates are // M<Giraffe>(Giraffe) and M(object). Overload resolution then chooses the former // because it is an exact match, over the latter which is an inexact match. Only after // the best method is determined do we check the constraints and discover that the // constraint on T has been violated. // // Note that this is different from the rule that says that during type inference, if an // inference violates a constraint then inference fails. For example: // // class C<T> where T : struct {} // ... // void M<U>(U u, C<U> c){} // void M(object x, object y) {} // ... // M("hello", null); // // Type inference determines that U is string, but since C<string> is not a valid type // because of the constraint, type inference fails. M<string> is never added to the // applicable candidate set, so the applicable candidate set consists solely of // M(object, object) and is therefore the best match. return !methodSymbol.CheckConstraints(new ConstraintsHelper.CheckConstraintsArgs(this.Compilation, this.Conversions, includeNullability: false, node.Location, diagnostics)); } /// <summary> /// Performs the following checks: /// /// Spec 7.6.5: Invocation expressions (definition of Final Validation) /// The method is validated in the context of the method group: If the best method is a static method, /// the method group must have resulted from a simple-name or a member-access through a type. If the best /// method is an instance method, the method group must have resulted from a simple-name, a member-access /// through a variable or value, or a base-access. If neither of these requirements is true, a binding-time /// error occurs. /// (Note that the spec omits to mention, in the case of an instance method invoked through a simple name, that /// the invocation must appear within the body of an instance method) /// /// Spec 7.5.4: Compile-time checking of dynamic overload resolution /// If F is a static method, the method group must have resulted from a simple-name, a member-access through a type, /// or a member-access whose receiver can't be classified as a type or value until after overload resolution (see §7.6.4.1). /// If F is an instance method, the method group must have resulted from a simple-name, a member-access through a variable or value, /// or a member-access whose receiver can't be classified as a type or value until after overload resolution (see §7.6.4.1). /// </summary> /// <returns> /// True if there is any error. /// </returns> private bool MemberGroupFinalValidationAccessibilityChecks(BoundExpression? receiverOpt, Symbol memberSymbol, SyntaxNode node, BindingDiagnosticBag diagnostics, bool invokedAsExtensionMethod) { // Perform final validation of the method to be invoked. Debug.Assert(memberSymbol.Kind != SymbolKind.Method || memberSymbol.CanBeReferencedByName); //note that the same assert does not hold for all properties. Some properties and (all indexers) are not referenceable by name, yet //their binding brings them through here, perhaps needlessly. if (IsTypeOrValueExpression(receiverOpt)) { // TypeOrValue expression isn't replaced only if the invocation is late bound, in which case it can't be extension method. // None of the checks below apply if the receiver can't be classified as a type or value. Debug.Assert(!invokedAsExtensionMethod); } else if (!memberSymbol.RequiresInstanceReceiver()) { Debug.Assert(!invokedAsExtensionMethod || (receiverOpt != null)); if (invokedAsExtensionMethod) { if (IsMemberAccessedThroughType(receiverOpt)) { if (receiverOpt.Kind == BoundKind.QueryClause) { RoslynDebug.Assert(receiverOpt.Type is object); // Could not find an implementation of the query pattern for source type '{0}'. '{1}' not found. diagnostics.Add(ErrorCode.ERR_QueryNoProvider, node.Location, receiverOpt.Type, memberSymbol.Name); } else { // An object reference is required for the non-static field, method, or property '{0}' diagnostics.Add(ErrorCode.ERR_ObjectRequired, node.Location, memberSymbol); } return true; } } else if (!WasImplicitReceiver(receiverOpt) && IsMemberAccessedThroughVariableOrValue(receiverOpt)) { if (this.Flags.Includes(BinderFlags.CollectionInitializerAddMethod)) { diagnostics.Add(ErrorCode.ERR_InitializerAddHasWrongSignature, node.Location, memberSymbol); } else if (node.Kind() == SyntaxKind.AwaitExpression && memberSymbol.Name == WellKnownMemberNames.GetAwaiter) { RoslynDebug.Assert(receiverOpt.Type is object); diagnostics.Add(ErrorCode.ERR_BadAwaitArg, node.Location, receiverOpt.Type); } else { diagnostics.Add(ErrorCode.ERR_ObjectProhibited, node.Location, memberSymbol); } return true; } } else if (IsMemberAccessedThroughType(receiverOpt)) { diagnostics.Add(ErrorCode.ERR_ObjectRequired, node.Location, memberSymbol); return true; } else if (WasImplicitReceiver(receiverOpt)) { if (InFieldInitializer && !ContainingType!.IsScriptClass || InConstructorInitializer || InAttributeArgument) { SyntaxNode errorNode = node; if (node.Parent != null && node.Parent.Kind() == SyntaxKind.InvocationExpression) { errorNode = node.Parent; } ErrorCode code = InFieldInitializer ? ErrorCode.ERR_FieldInitRefNonstatic : ErrorCode.ERR_ObjectRequired; diagnostics.Add(code, errorNode.Location, memberSymbol); return true; } // If we could access the member through implicit "this" the receiver would be a BoundThisReference. // If it is null it means that the instance member is inaccessible. if (receiverOpt == null || ContainingMember().IsStatic) { Error(diagnostics, ErrorCode.ERR_ObjectRequired, node, memberSymbol); return true; } } var containingType = this.ContainingType; if (containingType is object) { CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); bool isAccessible = this.IsSymbolAccessibleConditional(memberSymbol.GetTypeOrReturnType().Type, containingType, ref useSiteInfo); diagnostics.Add(node, useSiteInfo); if (!isAccessible) { // In the presence of non-transitive [InternalsVisibleTo] in source, or obnoxious symbols from metadata, it is possible // to select a method through overload resolution in which the type is not accessible. In this case a method cannot // be called through normal IL, so we give an error. Neither [InternalsVisibleTo] nor the need for this diagnostic is // described by the language specification. // // Dev11 perform different access checks. See bug #530360 and tests AccessCheckTests.InaccessibleReturnType. Error(diagnostics, ErrorCode.ERR_BadAccess, node, memberSymbol); return true; } } return false; } private static bool IsMemberAccessedThroughVariableOrValue(BoundExpression? receiverOpt) { if (receiverOpt == null) { return false; } return !IsMemberAccessedThroughType(receiverOpt); } internal static bool IsMemberAccessedThroughType([NotNullWhen(true)] BoundExpression? receiverOpt) { if (receiverOpt == null) { return false; } while (receiverOpt.Kind == BoundKind.QueryClause) { receiverOpt = ((BoundQueryClause)receiverOpt).Value; } return receiverOpt.Kind == BoundKind.TypeExpression; } /// <summary> /// Was the receiver expression compiler-generated? /// </summary> internal static bool WasImplicitReceiver([NotNullWhen(false)] BoundExpression? receiverOpt) { if (receiverOpt == null) return true; if (!receiverOpt.WasCompilerGenerated) return false; switch (receiverOpt.Kind) { case BoundKind.ThisReference: case BoundKind.HostObjectMemberReference: case BoundKind.PreviousSubmissionReference: return true; default: return false; } } /// <summary> /// This method implements the checks in spec section 15.2. /// </summary> internal bool MethodIsCompatibleWithDelegateOrFunctionPointer(BoundExpression? receiverOpt, bool isExtensionMethod, MethodSymbol method, TypeSymbol delegateType, Location errorLocation, BindingDiagnosticBag diagnostics) { Debug.Assert(delegateType is NamedTypeSymbol { TypeKind: TypeKind.Delegate, DelegateInvokeMethod: { HasUseSiteError: false } } || delegateType.TypeKind == TypeKind.FunctionPointer, "This method should only be called for valid delegate or function pointer types."); MethodSymbol delegateOrFuncPtrMethod = delegateType switch { NamedTypeSymbol { DelegateInvokeMethod: { } invokeMethod } => invokeMethod, FunctionPointerTypeSymbol { Signature: { } signature } => signature, _ => throw ExceptionUtilities.UnexpectedValue(delegateType), }; Debug.Assert(!isExtensionMethod || (receiverOpt != null)); // - Argument types "match", and var delegateOrFuncPtrParameters = delegateOrFuncPtrMethod.Parameters; var methodParameters = method.Parameters; int numParams = delegateOrFuncPtrParameters.Length; if (methodParameters.Length != numParams + (isExtensionMethod ? 1 : 0)) { // This can happen if "method" has optional parameters. Debug.Assert(methodParameters.Length > numParams + (isExtensionMethod ? 1 : 0)); Error(diagnostics, getMethodMismatchErrorCode(delegateType.TypeKind), errorLocation, method, delegateType); return false; } CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); // If this is an extension method delegate, the caller should have verified the // receiver is compatible with the "this" parameter of the extension method. Debug.Assert(!isExtensionMethod || (Conversions.ConvertExtensionMethodThisArg(methodParameters[0].Type, receiverOpt!.Type, ref useSiteInfo).Exists && useSiteInfo.Diagnostics.IsNullOrEmpty())); useSiteInfo = new CompoundUseSiteInfo<AssemblySymbol>(useSiteInfo); for (int i = 0; i < numParams; i++) { var delegateParameter = delegateOrFuncPtrParameters[i]; var methodParameter = methodParameters[isExtensionMethod ? i + 1 : i]; // The delegate compatibility checks are stricter than the checks on applicable functions: it's possible // to get here with a method that, while all the parameters are applicable, is not actually delegate // compatible. This is because the Applicable function member spec requires that: // * Every value parameter (non-ref or similar) from the delegate type has an implicit conversion to the corresponding // target parameter // * Every ref or similar parameter has an identity conversion to the corresponding target parameter // However, the delegate compatibility requirements are stricter: // * Every value parameter (non-ref or similar) from the delegate type has an implicit _reference_ conversion to the // corresponding target parameter. // * Every ref or similar parameter has an identity conversion to the corresponding target parameter // Note the addition of the reference requirement: it means that for delegate type void D(int i), void M(long l) is // _applicable_, but not _compatible_. if (!hasConversion(delegateType.TypeKind, Conversions, delegateParameter.Type, methodParameter.Type, delegateParameter.RefKind, methodParameter.RefKind, ref useSiteInfo)) { // No overload for '{0}' matches delegate '{1}' Error(diagnostics, getMethodMismatchErrorCode(delegateType.TypeKind), errorLocation, method, delegateType); diagnostics.Add(errorLocation, useSiteInfo); return false; } } if (delegateOrFuncPtrMethod.RefKind != method.RefKind) { Error(diagnostics, getRefMismatchErrorCode(delegateType.TypeKind), errorLocation, method, delegateType); diagnostics.Add(errorLocation, useSiteInfo); return false; } var methodReturnType = method.ReturnType; var delegateReturnType = delegateOrFuncPtrMethod.ReturnType; bool returnsMatch = delegateOrFuncPtrMethod switch { { RefKind: RefKind.None, ReturnsVoid: true } => method.ReturnsVoid, { RefKind: var destinationRefKind } => hasConversion(delegateType.TypeKind, Conversions, methodReturnType, delegateReturnType, method.RefKind, destinationRefKind, ref useSiteInfo), }; if (!returnsMatch) { Error(diagnostics, ErrorCode.ERR_BadRetType, errorLocation, method, method.ReturnType); diagnostics.Add(errorLocation, useSiteInfo); return false; } if (delegateType.IsFunctionPointer()) { if (isExtensionMethod) { Error(diagnostics, ErrorCode.ERR_CannotUseReducedExtensionMethodInAddressOf, errorLocation); diagnostics.Add(errorLocation, useSiteInfo); return false; } if (!method.IsStatic) { // This check is here purely for completeness of implementing the spec. It should // never be hit, as static methods should be eliminated as candidates in overload // resolution and should never make it to this point. Debug.Fail("This method should have been eliminated in overload resolution!"); Error(diagnostics, ErrorCode.ERR_FuncPtrMethMustBeStatic, errorLocation, method); diagnostics.Add(errorLocation, useSiteInfo); return false; } } diagnostics.Add(errorLocation, useSiteInfo); return true; static bool hasConversion(TypeKind targetKind, Conversions conversions, TypeSymbol source, TypeSymbol destination, RefKind sourceRefKind, RefKind destinationRefKind, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { if (sourceRefKind != destinationRefKind) { return false; } if (sourceRefKind != RefKind.None) { return ConversionsBase.HasIdentityConversion(source, destination); } if (conversions.HasIdentityOrImplicitReferenceConversion(source, destination, ref useSiteInfo)) { return true; } return targetKind == TypeKind.FunctionPointer && (ConversionsBase.HasImplicitPointerToVoidConversion(source, destination) || conversions.HasImplicitPointerConversion(source, destination, ref useSiteInfo)); } static ErrorCode getMethodMismatchErrorCode(TypeKind type) => type switch { TypeKind.Delegate => ErrorCode.ERR_MethDelegateMismatch, TypeKind.FunctionPointer => ErrorCode.ERR_MethFuncPtrMismatch, _ => throw ExceptionUtilities.UnexpectedValue(type) }; static ErrorCode getRefMismatchErrorCode(TypeKind type) => type switch { TypeKind.Delegate => ErrorCode.ERR_DelegateRefMismatch, TypeKind.FunctionPointer => ErrorCode.ERR_FuncPtrRefMismatch, _ => throw ExceptionUtilities.UnexpectedValue(type) }; } /// <summary> /// This method combines final validation (section 7.6.5.1) and delegate compatibility (section 15.2). /// </summary> /// <param name="syntax">CSharpSyntaxNode of the expression requiring method group conversion.</param> /// <param name="conversion">Conversion to be performed.</param> /// <param name="receiverOpt">Optional receiver.</param> /// <param name="isExtensionMethod">Method invoked as extension method.</param> /// <param name="delegateOrFuncPtrType">Target delegate type.</param> /// <param name="diagnostics">Where diagnostics should be added.</param> /// <returns>True if a diagnostic has been added.</returns> private bool MethodGroupConversionHasErrors( SyntaxNode syntax, Conversion conversion, BoundExpression? receiverOpt, bool isExtensionMethod, bool isAddressOf, TypeSymbol delegateOrFuncPtrType, BindingDiagnosticBag diagnostics) { Debug.Assert(delegateOrFuncPtrType.SpecialType == SpecialType.System_Delegate || delegateOrFuncPtrType.TypeKind == TypeKind.Delegate || delegateOrFuncPtrType.TypeKind == TypeKind.FunctionPointer); Debug.Assert(conversion.Method is object); MethodSymbol selectedMethod = conversion.Method; var location = syntax.Location; if (delegateOrFuncPtrType.SpecialType != SpecialType.System_Delegate) { if (!MethodIsCompatibleWithDelegateOrFunctionPointer(receiverOpt, isExtensionMethod, selectedMethod, delegateOrFuncPtrType, location, diagnostics) || MemberGroupFinalValidation(receiverOpt, selectedMethod, syntax, diagnostics, isExtensionMethod)) { return true; } } if (selectedMethod.IsConditional) { // CS1618: Cannot create delegate with '{0}' because it has a Conditional attribute Error(diagnostics, ErrorCode.ERR_DelegateOnConditional, location, selectedMethod); return true; } var sourceMethod = selectedMethod as SourceOrdinaryMethodSymbol; if (sourceMethod is object && sourceMethod.IsPartialWithoutImplementation) { // CS0762: Cannot create delegate from method '{0}' because it is a partial method without an implementing declaration Error(diagnostics, ErrorCode.ERR_PartialMethodToDelegate, location, selectedMethod); return true; } if ((selectedMethod.HasUnsafeParameter() || selectedMethod.ReturnType.IsUnsafe()) && ReportUnsafeIfNotAllowed(syntax, diagnostics)) { return true; } if (!isAddressOf) { ReportDiagnosticsIfUnmanagedCallersOnly(diagnostics, selectedMethod, location, isDelegateConversion: true); } ReportDiagnosticsIfObsolete(diagnostics, selectedMethod, syntax, hasBaseReceiver: false); // No use site errors, but there could be use site warnings. // If there are use site warnings, they were reported during the overload resolution process // that chose selectedMethod. Debug.Assert(!selectedMethod.HasUseSiteError, "Shouldn't have reached this point if there were use site errors."); return false; } /// <summary> /// This method is a wrapper around MethodGroupConversionHasErrors. As a preliminary step, /// it checks whether a conversion exists. /// </summary> private bool MethodGroupConversionDoesNotExistOrHasErrors( BoundMethodGroup boundMethodGroup, NamedTypeSymbol delegateType, Location delegateMismatchLocation, BindingDiagnosticBag diagnostics, out Conversion conversion) { if (ReportDelegateInvokeUseSiteDiagnostic(diagnostics, delegateType, delegateMismatchLocation)) { conversion = Conversion.NoConversion; return true; } CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); conversion = Conversions.GetMethodGroupDelegateConversion(boundMethodGroup, delegateType, ref useSiteInfo); diagnostics.Add(delegateMismatchLocation, useSiteInfo); if (!conversion.Exists) { if (!Conversions.ReportDelegateOrFunctionPointerMethodGroupDiagnostics(this, boundMethodGroup, delegateType, diagnostics)) { // No overload for '{0}' matches delegate '{1}' diagnostics.Add(ErrorCode.ERR_MethDelegateMismatch, delegateMismatchLocation, boundMethodGroup.Name, delegateType); } return true; } else { Debug.Assert(conversion.IsValid); // i.e. if it exists, then it is valid. // Only cares about nullness and type of receiver, so no need to worry about BoundTypeOrValueExpression. return this.MethodGroupConversionHasErrors(boundMethodGroup.Syntax, conversion, boundMethodGroup.ReceiverOpt, conversion.IsExtensionMethod, isAddressOf: false, delegateType, diagnostics); } } public ConstantValue? FoldConstantConversion( SyntaxNode syntax, BoundExpression source, Conversion conversion, TypeSymbol destination, BindingDiagnosticBag diagnostics) { RoslynDebug.Assert(source != null); RoslynDebug.Assert((object)destination != null); // The diagnostics bag can be null in cases where we know ahead of time that the // conversion will succeed without error or warning. (For example, if we have a valid // implicit numeric conversion on a constant of numeric type.) // SPEC: A constant expression must be the null literal or a value with one of // SPEC: the following types: sbyte, byte, short, ushort, int, uint, long, // SPEC: ulong, char, float, double, decimal, bool, string, or any enumeration type. // SPEC: The following conversions are permitted in constant expressions: // SPEC: Identity conversions // SPEC: Numeric conversions // SPEC: Enumeration conversions // SPEC: Constant expression conversions // SPEC: Implicit and explicit reference conversions, provided that the source of the conversions // SPEC: is a constant expression that evaluates to the null value. // SPEC VIOLATION: C# has always allowed the following, even though this does violate the rule that // SPEC VIOLATION: a constant expression must be either the null literal, or an expression of one // SPEC VIOLATION: of the given types. // SPEC VIOLATION: const C c = (C)null; // TODO: Some conversions can produce errors or warnings depending on checked/unchecked. // TODO: Fold conversions on enums and strings too. var sourceConstantValue = source.ConstantValue; if (sourceConstantValue == null) { if (conversion.Kind == ConversionKind.DefaultLiteral) { return destination.GetDefaultValue(); } else { return sourceConstantValue; } } else if (sourceConstantValue.IsBad) { return sourceConstantValue; } if (source.HasAnyErrors) { return null; } switch (conversion.Kind) { case ConversionKind.Identity: // An identity conversion to a floating-point type (for example from a cast in // source code) changes the internal representation of the constant value // to precisely the required precision. switch (destination.SpecialType) { case SpecialType.System_Single: return ConstantValue.Create(sourceConstantValue.SingleValue); case SpecialType.System_Double: return ConstantValue.Create(sourceConstantValue.DoubleValue); default: return sourceConstantValue; } case ConversionKind.NullLiteral: return sourceConstantValue; case ConversionKind.ImplicitConstant: return FoldConstantNumericConversion(syntax, sourceConstantValue, destination, diagnostics); case ConversionKind.ExplicitNumeric: case ConversionKind.ImplicitNumeric: case ConversionKind.ExplicitEnumeration: case ConversionKind.ImplicitEnumeration: // The C# specification categorizes conversion from literal zero to nullable enum as // an Implicit Enumeration Conversion. Such a thing should not be constant folded // because nullable enums are never constants. if (destination.IsNullableType()) { return null; } return FoldConstantNumericConversion(syntax, sourceConstantValue, destination, diagnostics); case ConversionKind.ExplicitReference: case ConversionKind.ImplicitReference: return sourceConstantValue.IsNull ? sourceConstantValue : null; } return null; } private ConstantValue? FoldConstantNumericConversion( SyntaxNode syntax, ConstantValue sourceValue, TypeSymbol destination, BindingDiagnosticBag diagnostics) { RoslynDebug.Assert(sourceValue != null); Debug.Assert(!sourceValue.IsBad); SpecialType destinationType; if ((object)destination != null && destination.IsEnumType()) { var underlyingType = ((NamedTypeSymbol)destination).EnumUnderlyingType; RoslynDebug.Assert((object)underlyingType != null); Debug.Assert(underlyingType.SpecialType != SpecialType.None); destinationType = underlyingType.SpecialType; } else { destinationType = destination.GetSpecialTypeSafe(); } // In an unchecked context we ignore overflowing conversions on conversions from any // integral type, float and double to any integral type. "unchecked" actually does not // affect conversions from decimal to any integral type; if those are out of bounds then // we always give an error regardless. if (sourceValue.IsDecimal) { if (!CheckConstantBounds(destinationType, sourceValue, out _)) { // NOTE: Dev10 puts a suffix, "M", on the constant value. Error(diagnostics, ErrorCode.ERR_ConstOutOfRange, syntax, sourceValue.Value + "M", destination!); return ConstantValue.Bad; } } else if (destinationType == SpecialType.System_Decimal) { if (!CheckConstantBounds(destinationType, sourceValue, out _)) { Error(diagnostics, ErrorCode.ERR_ConstOutOfRange, syntax, sourceValue.Value!, destination!); return ConstantValue.Bad; } } else if (CheckOverflowAtCompileTime) { if (!CheckConstantBounds(destinationType, sourceValue, out bool maySucceedAtRuntime)) { if (maySucceedAtRuntime) { // Can be calculated at runtime, but is not a compile-time constant. Error(diagnostics, ErrorCode.WRN_ConstOutOfRangeChecked, syntax, sourceValue.Value!, destination!); return null; } else { Error(diagnostics, ErrorCode.ERR_ConstOutOfRangeChecked, syntax, sourceValue.Value!, destination!); return ConstantValue.Bad; } } } else if (destinationType == SpecialType.System_IntPtr || destinationType == SpecialType.System_UIntPtr) { if (!CheckConstantBounds(destinationType, sourceValue, out _)) { // Can be calculated at runtime, but is not a compile-time constant. return null; } } return ConstantValue.Create(DoUncheckedConversion(destinationType, sourceValue), destinationType); } private static object DoUncheckedConversion(SpecialType destinationType, ConstantValue value) { // Note that we keep "single" floats as doubles internally to maintain higher precision. However, // we do not do so in an entirely "lossless" manner. When *converting* to a float, we do lose // the precision lost due to the conversion. But when doing arithmetic, we do the arithmetic on // the double values. // // An example will help. Suppose we have: // // const float cf1 = 1.0f; // const float cf2 = 1.0e-15f; // const double cd3 = cf1 - cf2; // // We first take the double-precision values for 1.0 and 1.0e-15 and round them to floats, // and then turn them back into doubles. Then when we do the subtraction, we do the subtraction // in doubles, not in floats. Had we done the subtraction in floats, we'd get 1.0; but instead we // do it in doubles and get 0.99999999999999. // // Similarly, if we have // // const int i4 = int.MaxValue; // 2147483647 // const float cf5 = int.MaxValue; // 2147483648.0 // const double cd6 = cf5; // 2147483648.0 // // The int is converted to float and stored internally as the double 214783648, even though the // fully precise int would fit into a double. unchecked { switch (value.Discriminator) { case ConstantValueTypeDiscriminator.Byte: byte byteValue = value.ByteValue; switch (destinationType) { case SpecialType.System_Byte: return (byte)byteValue; case SpecialType.System_Char: return (char)byteValue; case SpecialType.System_UInt16: return (ushort)byteValue; case SpecialType.System_UInt32: return (uint)byteValue; case SpecialType.System_UInt64: return (ulong)byteValue; case SpecialType.System_SByte: return (sbyte)byteValue; case SpecialType.System_Int16: return (short)byteValue; case SpecialType.System_Int32: return (int)byteValue; case SpecialType.System_Int64: return (long)byteValue; case SpecialType.System_IntPtr: return (int)byteValue; case SpecialType.System_UIntPtr: return (uint)byteValue; case SpecialType.System_Single: case SpecialType.System_Double: return (double)byteValue; case SpecialType.System_Decimal: return (decimal)byteValue; default: throw ExceptionUtilities.UnexpectedValue(destinationType); } case ConstantValueTypeDiscriminator.Char: char charValue = value.CharValue; switch (destinationType) { case SpecialType.System_Byte: return (byte)charValue; case SpecialType.System_Char: return (char)charValue; case SpecialType.System_UInt16: return (ushort)charValue; case SpecialType.System_UInt32: return (uint)charValue; case SpecialType.System_UInt64: return (ulong)charValue; case SpecialType.System_SByte: return (sbyte)charValue; case SpecialType.System_Int16: return (short)charValue; case SpecialType.System_Int32: return (int)charValue; case SpecialType.System_Int64: return (long)charValue; case SpecialType.System_IntPtr: return (int)charValue; case SpecialType.System_UIntPtr: return (uint)charValue; case SpecialType.System_Single: case SpecialType.System_Double: return (double)charValue; case SpecialType.System_Decimal: return (decimal)charValue; default: throw ExceptionUtilities.UnexpectedValue(destinationType); } case ConstantValueTypeDiscriminator.UInt16: ushort uint16Value = value.UInt16Value; switch (destinationType) { case SpecialType.System_Byte: return (byte)uint16Value; case SpecialType.System_Char: return (char)uint16Value; case SpecialType.System_UInt16: return (ushort)uint16Value; case SpecialType.System_UInt32: return (uint)uint16Value; case SpecialType.System_UInt64: return (ulong)uint16Value; case SpecialType.System_SByte: return (sbyte)uint16Value; case SpecialType.System_Int16: return (short)uint16Value; case SpecialType.System_Int32: return (int)uint16Value; case SpecialType.System_Int64: return (long)uint16Value; case SpecialType.System_IntPtr: return (int)uint16Value; case SpecialType.System_UIntPtr: return (uint)uint16Value; case SpecialType.System_Single: case SpecialType.System_Double: return (double)uint16Value; case SpecialType.System_Decimal: return (decimal)uint16Value; default: throw ExceptionUtilities.UnexpectedValue(destinationType); } case ConstantValueTypeDiscriminator.UInt32: uint uint32Value = value.UInt32Value; switch (destinationType) { case SpecialType.System_Byte: return (byte)uint32Value; case SpecialType.System_Char: return (char)uint32Value; case SpecialType.System_UInt16: return (ushort)uint32Value; case SpecialType.System_UInt32: return (uint)uint32Value; case SpecialType.System_UInt64: return (ulong)uint32Value; case SpecialType.System_SByte: return (sbyte)uint32Value; case SpecialType.System_Int16: return (short)uint32Value; case SpecialType.System_Int32: return (int)uint32Value; case SpecialType.System_Int64: return (long)uint32Value; case SpecialType.System_IntPtr: return (int)uint32Value; case SpecialType.System_UIntPtr: return (uint)uint32Value; case SpecialType.System_Single: return (double)(float)uint32Value; case SpecialType.System_Double: return (double)uint32Value; case SpecialType.System_Decimal: return (decimal)uint32Value; default: throw ExceptionUtilities.UnexpectedValue(destinationType); } case ConstantValueTypeDiscriminator.UInt64: ulong uint64Value = value.UInt64Value; switch (destinationType) { case SpecialType.System_Byte: return (byte)uint64Value; case SpecialType.System_Char: return (char)uint64Value; case SpecialType.System_UInt16: return (ushort)uint64Value; case SpecialType.System_UInt32: return (uint)uint64Value; case SpecialType.System_UInt64: return (ulong)uint64Value; case SpecialType.System_SByte: return (sbyte)uint64Value; case SpecialType.System_Int16: return (short)uint64Value; case SpecialType.System_Int32: return (int)uint64Value; case SpecialType.System_Int64: return (long)uint64Value; case SpecialType.System_IntPtr: return (int)uint64Value; case SpecialType.System_UIntPtr: return (uint)uint64Value; case SpecialType.System_Single: return (double)(float)uint64Value; case SpecialType.System_Double: return (double)uint64Value; case SpecialType.System_Decimal: return (decimal)uint64Value; default: throw ExceptionUtilities.UnexpectedValue(destinationType); } case ConstantValueTypeDiscriminator.NUInt: uint nuintValue = value.UInt32Value; switch (destinationType) { case SpecialType.System_Byte: return (byte)nuintValue; case SpecialType.System_Char: return (char)nuintValue; case SpecialType.System_UInt16: return (ushort)nuintValue; case SpecialType.System_UInt32: return (uint)nuintValue; case SpecialType.System_UInt64: return (ulong)nuintValue; case SpecialType.System_SByte: return (sbyte)nuintValue; case SpecialType.System_Int16: return (short)nuintValue; case SpecialType.System_Int32: return (int)nuintValue; case SpecialType.System_Int64: return (long)nuintValue; case SpecialType.System_IntPtr: return (int)nuintValue; case SpecialType.System_Single: return (double)(float)nuintValue; case SpecialType.System_Double: return (double)nuintValue; case SpecialType.System_Decimal: return (decimal)nuintValue; default: throw ExceptionUtilities.UnexpectedValue(destinationType); } case ConstantValueTypeDiscriminator.SByte: sbyte sbyteValue = value.SByteValue; switch (destinationType) { case SpecialType.System_Byte: return (byte)sbyteValue; case SpecialType.System_Char: return (char)sbyteValue; case SpecialType.System_UInt16: return (ushort)sbyteValue; case SpecialType.System_UInt32: return (uint)sbyteValue; case SpecialType.System_UInt64: return (ulong)sbyteValue; case SpecialType.System_SByte: return (sbyte)sbyteValue; case SpecialType.System_Int16: return (short)sbyteValue; case SpecialType.System_Int32: return (int)sbyteValue; case SpecialType.System_Int64: return (long)sbyteValue; case SpecialType.System_IntPtr: return (int)sbyteValue; case SpecialType.System_UIntPtr: return (uint)sbyteValue; case SpecialType.System_Single: case SpecialType.System_Double: return (double)sbyteValue; case SpecialType.System_Decimal: return (decimal)sbyteValue; default: throw ExceptionUtilities.UnexpectedValue(destinationType); } case ConstantValueTypeDiscriminator.Int16: short int16Value = value.Int16Value; switch (destinationType) { case SpecialType.System_Byte: return (byte)int16Value; case SpecialType.System_Char: return (char)int16Value; case SpecialType.System_UInt16: return (ushort)int16Value; case SpecialType.System_UInt32: return (uint)int16Value; case SpecialType.System_UInt64: return (ulong)int16Value; case SpecialType.System_SByte: return (sbyte)int16Value; case SpecialType.System_Int16: return (short)int16Value; case SpecialType.System_Int32: return (int)int16Value; case SpecialType.System_Int64: return (long)int16Value; case SpecialType.System_IntPtr: return (int)int16Value; case SpecialType.System_UIntPtr: return (uint)int16Value; case SpecialType.System_Single: case SpecialType.System_Double: return (double)int16Value; case SpecialType.System_Decimal: return (decimal)int16Value; default: throw ExceptionUtilities.UnexpectedValue(destinationType); } case ConstantValueTypeDiscriminator.Int32: int int32Value = value.Int32Value; switch (destinationType) { case SpecialType.System_Byte: return (byte)int32Value; case SpecialType.System_Char: return (char)int32Value; case SpecialType.System_UInt16: return (ushort)int32Value; case SpecialType.System_UInt32: return (uint)int32Value; case SpecialType.System_UInt64: return (ulong)int32Value; case SpecialType.System_SByte: return (sbyte)int32Value; case SpecialType.System_Int16: return (short)int32Value; case SpecialType.System_Int32: return (int)int32Value; case SpecialType.System_Int64: return (long)int32Value; case SpecialType.System_IntPtr: return (int)int32Value; case SpecialType.System_UIntPtr: return (uint)int32Value; case SpecialType.System_Single: return (double)(float)int32Value; case SpecialType.System_Double: return (double)int32Value; case SpecialType.System_Decimal: return (decimal)int32Value; default: throw ExceptionUtilities.UnexpectedValue(destinationType); } case ConstantValueTypeDiscriminator.Int64: long int64Value = value.Int64Value; switch (destinationType) { case SpecialType.System_Byte: return (byte)int64Value; case SpecialType.System_Char: return (char)int64Value; case SpecialType.System_UInt16: return (ushort)int64Value; case SpecialType.System_UInt32: return (uint)int64Value; case SpecialType.System_UInt64: return (ulong)int64Value; case SpecialType.System_SByte: return (sbyte)int64Value; case SpecialType.System_Int16: return (short)int64Value; case SpecialType.System_Int32: return (int)int64Value; case SpecialType.System_Int64: return (long)int64Value; case SpecialType.System_IntPtr: return (int)int64Value; case SpecialType.System_UIntPtr: return (uint)int64Value; case SpecialType.System_Single: return (double)(float)int64Value; case SpecialType.System_Double: return (double)int64Value; case SpecialType.System_Decimal: return (decimal)int64Value; default: throw ExceptionUtilities.UnexpectedValue(destinationType); } case ConstantValueTypeDiscriminator.NInt: int nintValue = value.Int32Value; switch (destinationType) { case SpecialType.System_Byte: return (byte)nintValue; case SpecialType.System_Char: return (char)nintValue; case SpecialType.System_UInt16: return (ushort)nintValue; case SpecialType.System_UInt32: return (uint)nintValue; case SpecialType.System_UInt64: return (ulong)nintValue; case SpecialType.System_SByte: return (sbyte)nintValue; case SpecialType.System_Int16: return (short)nintValue; case SpecialType.System_Int32: return (int)nintValue; case SpecialType.System_Int64: return (long)nintValue; case SpecialType.System_IntPtr: return (int)nintValue; case SpecialType.System_UIntPtr: return (uint)nintValue; case SpecialType.System_Single: return (double)(float)nintValue; case SpecialType.System_Double: return (double)nintValue; case SpecialType.System_Decimal: return (decimal)nintValue; default: throw ExceptionUtilities.UnexpectedValue(destinationType); } case ConstantValueTypeDiscriminator.Single: case ConstantValueTypeDiscriminator.Double: // When converting from a floating-point type to an integral type, if the checked conversion would // throw an overflow exception, then the unchecked conversion is undefined. So that we have // identical behavior on every host platform, we yield a result of zero in that case. double doubleValue = CheckConstantBounds(destinationType, value.DoubleValue, out _) ? value.DoubleValue : 0D; switch (destinationType) { case SpecialType.System_Byte: return (byte)doubleValue; case SpecialType.System_Char: return (char)doubleValue; case SpecialType.System_UInt16: return (ushort)doubleValue; case SpecialType.System_UInt32: return (uint)doubleValue; case SpecialType.System_UInt64: return (ulong)doubleValue; case SpecialType.System_SByte: return (sbyte)doubleValue; case SpecialType.System_Int16: return (short)doubleValue; case SpecialType.System_Int32: return (int)doubleValue; case SpecialType.System_Int64: return (long)doubleValue; case SpecialType.System_IntPtr: return (int)doubleValue; case SpecialType.System_UIntPtr: return (uint)doubleValue; case SpecialType.System_Single: return (double)(float)doubleValue; case SpecialType.System_Double: return (double)doubleValue; case SpecialType.System_Decimal: return (value.Discriminator == ConstantValueTypeDiscriminator.Single) ? (decimal)(float)doubleValue : (decimal)doubleValue; default: throw ExceptionUtilities.UnexpectedValue(destinationType); } case ConstantValueTypeDiscriminator.Decimal: decimal decimalValue = CheckConstantBounds(destinationType, value.DecimalValue, out _) ? value.DecimalValue : 0m; switch (destinationType) { case SpecialType.System_Byte: return (byte)decimalValue; case SpecialType.System_Char: return (char)decimalValue; case SpecialType.System_UInt16: return (ushort)decimalValue; case SpecialType.System_UInt32: return (uint)decimalValue; case SpecialType.System_UInt64: return (ulong)decimalValue; case SpecialType.System_SByte: return (sbyte)decimalValue; case SpecialType.System_Int16: return (short)decimalValue; case SpecialType.System_Int32: return (int)decimalValue; case SpecialType.System_Int64: return (long)decimalValue; case SpecialType.System_IntPtr: return (int)decimalValue; case SpecialType.System_UIntPtr: return (uint)decimalValue; case SpecialType.System_Single: return (double)(float)decimalValue; case SpecialType.System_Double: return (double)decimalValue; case SpecialType.System_Decimal: return (decimal)decimalValue; default: throw ExceptionUtilities.UnexpectedValue(destinationType); } default: throw ExceptionUtilities.UnexpectedValue(value.Discriminator); } } // all cases should have been handled in the switch above. // return value.Value; } public static bool CheckConstantBounds(SpecialType destinationType, ConstantValue value, out bool maySucceedAtRuntime) { if (value.IsBad) { //assume that the constant was intended to be in bounds maySucceedAtRuntime = false; return true; } // Compute whether the value fits into the bounds of the given destination type without // error. We know that the constant will fit into either a double or a decimal, so // convert it to one of those and then check the bounds on that. var canonicalValue = CanonicalizeConstant(value); return canonicalValue is decimal ? CheckConstantBounds(destinationType, (decimal)canonicalValue, out maySucceedAtRuntime) : CheckConstantBounds(destinationType, (double)canonicalValue, out maySucceedAtRuntime); } private static bool CheckConstantBounds(SpecialType destinationType, double value, out bool maySucceedAtRuntime) { maySucceedAtRuntime = false; // Dev10 checks (minValue - 1) < value < (maxValue + 1). // See ExpressionBinder::isConstantInRange. switch (destinationType) { case SpecialType.System_Byte: return (byte.MinValue - 1D) < value && value < (byte.MaxValue + 1D); case SpecialType.System_Char: return (char.MinValue - 1D) < value && value < (char.MaxValue + 1D); case SpecialType.System_UInt16: return (ushort.MinValue - 1D) < value && value < (ushort.MaxValue + 1D); case SpecialType.System_UInt32: return (uint.MinValue - 1D) < value && value < (uint.MaxValue + 1D); case SpecialType.System_UInt64: return (ulong.MinValue - 1D) < value && value < (ulong.MaxValue + 1D); case SpecialType.System_SByte: return (sbyte.MinValue - 1D) < value && value < (sbyte.MaxValue + 1D); case SpecialType.System_Int16: return (short.MinValue - 1D) < value && value < (short.MaxValue + 1D); case SpecialType.System_Int32: return (int.MinValue - 1D) < value && value < (int.MaxValue + 1D); // Note: Using <= to compare the min value matches the native compiler. case SpecialType.System_Int64: return (long.MinValue - 1D) <= value && value < (long.MaxValue + 1D); case SpecialType.System_Decimal: return ((double)decimal.MinValue - 1D) < value && value < ((double)decimal.MaxValue + 1D); case SpecialType.System_IntPtr: maySucceedAtRuntime = (long.MinValue - 1D) < value && value < (long.MaxValue + 1D); return (int.MinValue - 1D) < value && value < (int.MaxValue + 1D); case SpecialType.System_UIntPtr: maySucceedAtRuntime = (ulong.MinValue - 1D) < value && value < (ulong.MaxValue + 1D); return (uint.MinValue - 1D) < value && value < (uint.MaxValue + 1D); } return true; } private static bool CheckConstantBounds(SpecialType destinationType, decimal value, out bool maySucceedAtRuntime) { maySucceedAtRuntime = false; // Dev10 checks (minValue - 1) < value < (maxValue + 1). // See ExpressionBinder::isConstantInRange. switch (destinationType) { case SpecialType.System_Byte: return (byte.MinValue - 1M) < value && value < (byte.MaxValue + 1M); case SpecialType.System_Char: return (char.MinValue - 1M) < value && value < (char.MaxValue + 1M); case SpecialType.System_UInt16: return (ushort.MinValue - 1M) < value && value < (ushort.MaxValue + 1M); case SpecialType.System_UInt32: return (uint.MinValue - 1M) < value && value < (uint.MaxValue + 1M); case SpecialType.System_UInt64: return (ulong.MinValue - 1M) < value && value < (ulong.MaxValue + 1M); case SpecialType.System_SByte: return (sbyte.MinValue - 1M) < value && value < (sbyte.MaxValue + 1M); case SpecialType.System_Int16: return (short.MinValue - 1M) < value && value < (short.MaxValue + 1M); case SpecialType.System_Int32: return (int.MinValue - 1M) < value && value < (int.MaxValue + 1M); case SpecialType.System_Int64: return (long.MinValue - 1M) < value && value < (long.MaxValue + 1M); case SpecialType.System_IntPtr: maySucceedAtRuntime = (long.MinValue - 1M) < value && value < (long.MaxValue + 1M); return (int.MinValue - 1M) < value && value < (int.MaxValue + 1M); case SpecialType.System_UIntPtr: maySucceedAtRuntime = (ulong.MinValue - 1M) < value && value < (ulong.MaxValue + 1M); return (uint.MinValue - 1M) < value && value < (uint.MaxValue + 1M); } return true; } // Takes in a constant of any kind and returns the constant as either a double or decimal private static object CanonicalizeConstant(ConstantValue value) { switch (value.Discriminator) { case ConstantValueTypeDiscriminator.SByte: return (decimal)value.SByteValue; case ConstantValueTypeDiscriminator.Int16: return (decimal)value.Int16Value; case ConstantValueTypeDiscriminator.Int32: return (decimal)value.Int32Value; case ConstantValueTypeDiscriminator.Int64: return (decimal)value.Int64Value; case ConstantValueTypeDiscriminator.NInt: return (decimal)value.Int32Value; case ConstantValueTypeDiscriminator.Byte: return (decimal)value.ByteValue; case ConstantValueTypeDiscriminator.Char: return (decimal)value.CharValue; case ConstantValueTypeDiscriminator.UInt16: return (decimal)value.UInt16Value; case ConstantValueTypeDiscriminator.UInt32: return (decimal)value.UInt32Value; case ConstantValueTypeDiscriminator.UInt64: return (decimal)value.UInt64Value; case ConstantValueTypeDiscriminator.NUInt: return (decimal)value.UInt32Value; case ConstantValueTypeDiscriminator.Single: case ConstantValueTypeDiscriminator.Double: return value.DoubleValue; case ConstantValueTypeDiscriminator.Decimal: return value.DecimalValue; default: throw ExceptionUtilities.UnexpectedValue(value.Discriminator); } // all cases handled in the switch, above. } } }
1
dotnet/roslyn
55,256
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-30T00:02:02Z
2021-07-30T09:17:54Z
6ce9c0048d37026337701fac035ac0745f6fe49f
88b59775dc6375635957ef229116460f290072aa
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Compilers/CSharp/Portable/Binder/Binder_Statements.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { /// <summary> /// This portion of the binder converts StatementSyntax nodes into BoundStatements /// </summary> internal partial class Binder { /// <summary> /// This is the set of parameters and local variables that were used as arguments to /// lock or using statements in enclosing scopes. /// </summary> /// <remarks> /// using (x) { } // x counts /// using (IDisposable y = null) { } // y does not count /// </remarks> internal virtual ImmutableHashSet<Symbol> LockedOrDisposedVariables { get { return Next.LockedOrDisposedVariables; } } /// <remarks> /// Noteworthy override is in MemberSemanticModel.IncrementalBinder (used for caching). /// </remarks> public virtual BoundStatement BindStatement(StatementSyntax node, BindingDiagnosticBag diagnostics) { if (node.AttributeLists.Count > 0) { var attributeList = node.AttributeLists[0]; // Currently, attributes are only allowed on local-functions. if (node.Kind() == SyntaxKind.LocalFunctionStatement) { CheckFeatureAvailability(attributeList, MessageID.IDS_FeatureLocalFunctionAttributes, diagnostics); } else if (node.Kind() != SyntaxKind.Block) { // Don't explicitly error here for blocks. Some codepaths bypass BindStatement // to directly call BindBlock. Error(diagnostics, ErrorCode.ERR_AttributesNotAllowed, attributeList); } } Debug.Assert(node != null); BoundStatement result; switch (node.Kind()) { case SyntaxKind.Block: result = BindBlock((BlockSyntax)node, diagnostics); break; case SyntaxKind.LocalDeclarationStatement: result = BindLocalDeclarationStatement((LocalDeclarationStatementSyntax)node, diagnostics); break; case SyntaxKind.LocalFunctionStatement: result = BindLocalFunctionStatement((LocalFunctionStatementSyntax)node, diagnostics); break; case SyntaxKind.ExpressionStatement: result = BindExpressionStatement((ExpressionStatementSyntax)node, diagnostics); break; case SyntaxKind.IfStatement: result = BindIfStatement((IfStatementSyntax)node, diagnostics); break; case SyntaxKind.SwitchStatement: result = BindSwitchStatement((SwitchStatementSyntax)node, diagnostics); break; case SyntaxKind.DoStatement: result = BindDo((DoStatementSyntax)node, diagnostics); break; case SyntaxKind.WhileStatement: result = BindWhile((WhileStatementSyntax)node, diagnostics); break; case SyntaxKind.ForStatement: result = BindFor((ForStatementSyntax)node, diagnostics); break; case SyntaxKind.ForEachStatement: case SyntaxKind.ForEachVariableStatement: result = BindForEach((CommonForEachStatementSyntax)node, diagnostics); break; case SyntaxKind.BreakStatement: result = BindBreak((BreakStatementSyntax)node, diagnostics); break; case SyntaxKind.ContinueStatement: result = BindContinue((ContinueStatementSyntax)node, diagnostics); break; case SyntaxKind.ReturnStatement: result = BindReturn((ReturnStatementSyntax)node, diagnostics); break; case SyntaxKind.FixedStatement: result = BindFixedStatement((FixedStatementSyntax)node, diagnostics); break; case SyntaxKind.LabeledStatement: result = BindLabeled((LabeledStatementSyntax)node, diagnostics); break; case SyntaxKind.GotoStatement: case SyntaxKind.GotoCaseStatement: case SyntaxKind.GotoDefaultStatement: result = BindGoto((GotoStatementSyntax)node, diagnostics); break; case SyntaxKind.TryStatement: result = BindTryStatement((TryStatementSyntax)node, diagnostics); break; case SyntaxKind.EmptyStatement: result = BindEmpty((EmptyStatementSyntax)node); break; case SyntaxKind.ThrowStatement: result = BindThrow((ThrowStatementSyntax)node, diagnostics); break; case SyntaxKind.UnsafeStatement: result = BindUnsafeStatement((UnsafeStatementSyntax)node, diagnostics); break; case SyntaxKind.UncheckedStatement: case SyntaxKind.CheckedStatement: result = BindCheckedStatement((CheckedStatementSyntax)node, diagnostics); break; case SyntaxKind.UsingStatement: result = BindUsingStatement((UsingStatementSyntax)node, diagnostics); break; case SyntaxKind.YieldBreakStatement: result = BindYieldBreakStatement((YieldStatementSyntax)node, diagnostics); break; case SyntaxKind.YieldReturnStatement: result = BindYieldReturnStatement((YieldStatementSyntax)node, diagnostics); break; case SyntaxKind.LockStatement: result = BindLockStatement((LockStatementSyntax)node, diagnostics); break; default: // NOTE: We could probably throw an exception here, but it's conceivable // that a non-parser syntax tree could reach this point with an unexpected // SyntaxKind and we don't want to throw if that occurs. result = new BoundBadStatement(node, ImmutableArray<BoundNode>.Empty, hasErrors: true); break; } BoundBlock block; Debug.Assert(result.WasCompilerGenerated == false || (result.Kind == BoundKind.Block && (block = (BoundBlock)result).Statements.Length == 1 && block.Statements.Single().WasCompilerGenerated == false), "Synthetic node would not get cached"); Debug.Assert(result.Syntax is StatementSyntax, "BoundStatement should be associated with a statement syntax."); Debug.Assert(System.Linq.Enumerable.Contains(result.Syntax.AncestorsAndSelf(), node), @"Bound statement (or one of its parents) should have same syntax as the given syntax node. Otherwise it may be confusing to the binder cache that uses syntax node as keys."); return result; } private BoundStatement BindCheckedStatement(CheckedStatementSyntax node, BindingDiagnosticBag diagnostics) { return BindEmbeddedBlock(node.Block, diagnostics); } private BoundStatement BindUnsafeStatement(UnsafeStatementSyntax node, BindingDiagnosticBag diagnostics) { var unsafeBinder = this.GetBinder(node); if (!this.Compilation.Options.AllowUnsafe) { Error(diagnostics, ErrorCode.ERR_IllegalUnsafe, node.UnsafeKeyword); } else if (this.IsIndirectlyInIterator) // called *after* we know the binder map has been created. { // Spec 8.2: "An iterator block always defines a safe context, even when its declaration // is nested in an unsafe context." Error(diagnostics, ErrorCode.ERR_IllegalInnerUnsafe, node.UnsafeKeyword); } return BindEmbeddedBlock(node.Block, diagnostics); } private BoundStatement BindFixedStatement(FixedStatementSyntax node, BindingDiagnosticBag diagnostics) { var fixedBinder = this.GetBinder(node); Debug.Assert(fixedBinder != null); fixedBinder.ReportUnsafeIfNotAllowed(node, diagnostics); return fixedBinder.BindFixedStatementParts(node, diagnostics); } private BoundStatement BindFixedStatementParts(FixedStatementSyntax node, BindingDiagnosticBag diagnostics) { VariableDeclarationSyntax declarationSyntax = node.Declaration; ImmutableArray<BoundLocalDeclaration> declarations; BindForOrUsingOrFixedDeclarations(declarationSyntax, LocalDeclarationKind.FixedVariable, diagnostics, out declarations); Debug.Assert(!declarations.IsEmpty); BoundMultipleLocalDeclarations boundMultipleDeclarations = new BoundMultipleLocalDeclarations(declarationSyntax, declarations); BoundStatement boundBody = BindPossibleEmbeddedStatement(node.Statement, diagnostics); return new BoundFixedStatement(node, GetDeclaredLocalsForScope(node), boundMultipleDeclarations, boundBody); } private void CheckRequiredLangVersionForAsyncIteratorMethods(BindingDiagnosticBag diagnostics) { var method = (MethodSymbol)this.ContainingMemberOrLambda; if (method.IsAsync) { MessageID.IDS_FeatureAsyncStreams.CheckFeatureAvailability( diagnostics, method.DeclaringCompilation, method.Locations[0]); } } protected virtual void ValidateYield(YieldStatementSyntax node, BindingDiagnosticBag diagnostics) { Next?.ValidateYield(node, diagnostics); } private BoundStatement BindYieldReturnStatement(YieldStatementSyntax node, BindingDiagnosticBag diagnostics) { ValidateYield(node, diagnostics); TypeSymbol elementType = GetIteratorElementType().Type; BoundExpression argument = (node.Expression == null) ? BadExpression(node).MakeCompilerGenerated() : BindValue(node.Expression, diagnostics, BindValueKind.RValue); argument = ValidateEscape(argument, ExternalScope, isByRef: false, diagnostics: diagnostics); if (!argument.HasAnyErrors) { argument = GenerateConversionForAssignment(elementType, argument, diagnostics); } else { argument = BindToTypeForErrorRecovery(argument); } // NOTE: it's possible that more than one of these conditions is satisfied and that // we won't report the syntactically innermost. However, dev11 appears to check // them in this order, regardless of syntactic nesting (StatementBinder::bindYield). if (this.Flags.Includes(BinderFlags.InFinallyBlock)) { Error(diagnostics, ErrorCode.ERR_BadYieldInFinally, node.YieldKeyword); } else if (this.Flags.Includes(BinderFlags.InTryBlockOfTryCatch)) { Error(diagnostics, ErrorCode.ERR_BadYieldInTryOfCatch, node.YieldKeyword); } else if (this.Flags.Includes(BinderFlags.InCatchBlock)) { Error(diagnostics, ErrorCode.ERR_BadYieldInCatch, node.YieldKeyword); } else if (BindingTopLevelScriptCode) { Error(diagnostics, ErrorCode.ERR_YieldNotAllowedInScript, node.YieldKeyword); } CheckRequiredLangVersionForAsyncIteratorMethods(diagnostics); return new BoundYieldReturnStatement(node, argument); } private BoundStatement BindYieldBreakStatement(YieldStatementSyntax node, BindingDiagnosticBag diagnostics) { if (this.Flags.Includes(BinderFlags.InFinallyBlock)) { Error(diagnostics, ErrorCode.ERR_BadYieldInFinally, node.YieldKeyword); } else if (BindingTopLevelScriptCode) { Error(diagnostics, ErrorCode.ERR_YieldNotAllowedInScript, node.YieldKeyword); } ValidateYield(node, diagnostics); CheckRequiredLangVersionForAsyncIteratorMethods(diagnostics); return new BoundYieldBreakStatement(node); } private BoundStatement BindLockStatement(LockStatementSyntax node, BindingDiagnosticBag diagnostics) { var lockBinder = this.GetBinder(node); Debug.Assert(lockBinder != null); return lockBinder.BindLockStatementParts(diagnostics, lockBinder); } internal virtual BoundStatement BindLockStatementParts(BindingDiagnosticBag diagnostics, Binder originalBinder) { return this.Next.BindLockStatementParts(diagnostics, originalBinder); } private BoundStatement BindUsingStatement(UsingStatementSyntax node, BindingDiagnosticBag diagnostics) { var usingBinder = this.GetBinder(node); Debug.Assert(usingBinder != null); return usingBinder.BindUsingStatementParts(diagnostics, usingBinder); } internal virtual BoundStatement BindUsingStatementParts(BindingDiagnosticBag diagnostics, Binder originalBinder) { return this.Next.BindUsingStatementParts(diagnostics, originalBinder); } internal BoundStatement BindPossibleEmbeddedStatement(StatementSyntax node, BindingDiagnosticBag diagnostics) { Binder binder; switch (node.Kind()) { case SyntaxKind.LocalDeclarationStatement: // Local declarations are not legal in contexts where we need embedded statements. diagnostics.Add(ErrorCode.ERR_BadEmbeddedStmt, node.GetLocation()); // fall through goto case SyntaxKind.ExpressionStatement; case SyntaxKind.ExpressionStatement: case SyntaxKind.LockStatement: case SyntaxKind.IfStatement: case SyntaxKind.YieldReturnStatement: case SyntaxKind.ReturnStatement: case SyntaxKind.ThrowStatement: binder = this.GetBinder(node); Debug.Assert(binder != null); return binder.WrapWithVariablesIfAny(node, binder.BindStatement(node, diagnostics)); case SyntaxKind.LabeledStatement: case SyntaxKind.LocalFunctionStatement: // Labeled statements and local function statements are not legal in contexts where we need embedded statements. diagnostics.Add(ErrorCode.ERR_BadEmbeddedStmt, node.GetLocation()); binder = this.GetBinder(node); Debug.Assert(binder != null); return binder.WrapWithVariablesAndLocalFunctionsIfAny(node, binder.BindStatement(node, diagnostics)); case SyntaxKind.SwitchStatement: var switchStatement = (SwitchStatementSyntax)node; binder = this.GetBinder(switchStatement.Expression); Debug.Assert(binder != null); return binder.WrapWithVariablesIfAny(switchStatement.Expression, binder.BindStatement(node, diagnostics)); case SyntaxKind.EmptyStatement: var emptyStatement = (EmptyStatementSyntax)node; if (!emptyStatement.SemicolonToken.IsMissing) { switch (node.Parent.Kind()) { case SyntaxKind.ForStatement: case SyntaxKind.ForEachStatement: case SyntaxKind.ForEachVariableStatement: case SyntaxKind.WhileStatement: // For loop constructs, only warn if we see a block following the statement. // That indicates code like: "while (x) ; { }" // which is most likely a bug. if (emptyStatement.SemicolonToken.GetNextToken().Kind() != SyntaxKind.OpenBraceToken) { break; } goto default; default: // For non-loop constructs, always warn. This is for code like: // "if (x) ;" which is almost certainly a bug. diagnostics.Add(ErrorCode.WRN_PossibleMistakenNullStatement, node.GetLocation()); break; } } // fall through goto default; default: return BindStatement(node, diagnostics); } } private BoundExpression BindThrownExpression(ExpressionSyntax exprSyntax, BindingDiagnosticBag diagnostics, ref bool hasErrors) { var boundExpr = BindValue(exprSyntax, diagnostics, BindValueKind.RValue); if (Compilation.LanguageVersion < MessageID.IDS_FeatureSwitchExpression.RequiredVersion()) { // This is the pre-C# 8 algorithm for binding a thrown expression. // SPEC VIOLATION: The spec requires the thrown exception to have a type, and that the type // be System.Exception or derived from System.Exception. (Or, if a type parameter, to have // an effective base class that meets that criterion.) However, we allow the literal null // to be thrown, even though it does not meet that criterion and will at runtime always // produce a null reference exception. if (!boundExpr.IsLiteralNull()) { boundExpr = BindToNaturalType(boundExpr, diagnostics); var type = boundExpr.Type; // If the expression is a lambda, anonymous method, or method group then it will // have no compile-time type; give the same error as if the type was wrong. CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); if ((object)type == null || !type.IsErrorType() && !Compilation.IsExceptionType(type.EffectiveType(ref useSiteInfo), ref useSiteInfo)) { diagnostics.Add(ErrorCode.ERR_BadExceptionType, exprSyntax.Location); hasErrors = true; diagnostics.Add(exprSyntax, useSiteInfo); } else { diagnostics.AddDependencies(useSiteInfo); } } } else { // In C# 8 and later we follow the ECMA specification, which neatly handles null and expressions of exception type. boundExpr = GenerateConversionForAssignment(GetWellKnownType(WellKnownType.System_Exception, diagnostics, exprSyntax), boundExpr, diagnostics); } return boundExpr; } private BoundStatement BindThrow(ThrowStatementSyntax node, BindingDiagnosticBag diagnostics) { BoundExpression boundExpr = null; bool hasErrors = false; ExpressionSyntax exprSyntax = node.Expression; if (exprSyntax != null) { boundExpr = BindThrownExpression(exprSyntax, diagnostics, ref hasErrors); } else if (!this.Flags.Includes(BinderFlags.InCatchBlock)) { diagnostics.Add(ErrorCode.ERR_BadEmptyThrow, node.ThrowKeyword.GetLocation()); hasErrors = true; } else if (this.Flags.Includes(BinderFlags.InNestedFinallyBlock)) { // There's a special error code for a rethrow in a finally clause in a catch clause. // Best guess interpretation: if an exception occurs within the nested try block // (i.e. the one in the catch clause, to which the finally clause is attached), // then it's not clear whether the runtime will try to rethrow the "inner" exception // or the "outer" exception. For this reason, the case is disallowed. diagnostics.Add(ErrorCode.ERR_BadEmptyThrowInFinally, node.ThrowKeyword.GetLocation()); hasErrors = true; } return new BoundThrowStatement(node, boundExpr, hasErrors); } private static BoundStatement BindEmpty(EmptyStatementSyntax node) { return new BoundNoOpStatement(node, NoOpStatementFlavor.Default); } private BoundLabeledStatement BindLabeled(LabeledStatementSyntax node, BindingDiagnosticBag diagnostics) { // TODO: verify that goto label lookup was valid (e.g. error checking of symbol resolution for labels) bool hasError = false; var result = LookupResult.GetInstance(); CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); var binder = this.LookupSymbolsWithFallback(result, node.Identifier.ValueText, arity: 0, useSiteInfo: ref useSiteInfo, options: LookupOptions.LabelsOnly); // result.Symbols can be empty in some malformed code, e.g. when a labeled statement is used an embedded statement in an if or foreach statement // In this case we create new label symbol on the fly, and an error is reported by parser var symbol = result.Symbols.Count > 0 && result.IsMultiViable ? (LabelSymbol)result.Symbols.First() : new SourceLabelSymbol((MethodSymbol)ContainingMemberOrLambda, node.Identifier); if (!symbol.IdentifierNodeOrToken.IsToken || symbol.IdentifierNodeOrToken.AsToken() != node.Identifier) { Error(diagnostics, ErrorCode.ERR_DuplicateLabel, node.Identifier, node.Identifier.ValueText); hasError = true; } // check to see if this label (illegally) hides a label from an enclosing scope if (binder != null) { result.Clear(); binder.Next.LookupSymbolsWithFallback(result, node.Identifier.ValueText, arity: 0, useSiteInfo: ref useSiteInfo, options: LookupOptions.LabelsOnly); if (result.IsMultiViable) { // The label '{0}' shadows another label by the same name in a contained scope Error(diagnostics, ErrorCode.ERR_LabelShadow, node.Identifier, node.Identifier.ValueText); hasError = true; } } diagnostics.Add(node, useSiteInfo); result.Free(); var body = BindStatement(node.Statement, diagnostics); return new BoundLabeledStatement(node, symbol, body, hasError); } private BoundStatement BindGoto(GotoStatementSyntax node, BindingDiagnosticBag diagnostics) { switch (node.Kind()) { case SyntaxKind.GotoStatement: var expression = BindLabel(node.Expression, diagnostics); var boundLabel = expression as BoundLabel; if (boundLabel == null) { // diagnostics already reported return new BoundBadStatement(node, ImmutableArray.Create<BoundNode>(expression), true); } var symbol = boundLabel.Label; return new BoundGotoStatement(node, symbol, null, boundLabel); case SyntaxKind.GotoCaseStatement: case SyntaxKind.GotoDefaultStatement: // SPEC: If the goto case statement is not enclosed by a switch statement, a compile-time error occurs. // SPEC: If the goto default statement is not enclosed by a switch statement, a compile-time error occurs. SwitchBinder binder = GetSwitchBinder(this); if (binder == null) { Error(diagnostics, ErrorCode.ERR_InvalidGotoCase, node); ImmutableArray<BoundNode> childNodes; if (node.Expression != null) { var value = BindRValueWithoutTargetType(node.Expression, BindingDiagnosticBag.Discarded); childNodes = ImmutableArray.Create<BoundNode>(value); } else { childNodes = ImmutableArray<BoundNode>.Empty; } return new BoundBadStatement(node, childNodes, true); } return binder.BindGotoCaseOrDefault(node, this, diagnostics); default: throw ExceptionUtilities.UnexpectedValue(node.Kind()); } } private BoundStatement BindLocalFunctionStatement(LocalFunctionStatementSyntax node, BindingDiagnosticBag diagnostics) { // already defined symbol in containing block var localSymbol = this.LookupLocalFunction(node.Identifier); var hasErrors = localSymbol.ScopeBinder .ValidateDeclarationNameConflictsInScope(localSymbol, diagnostics); BoundBlock blockBody = null; BoundBlock expressionBody = null; if (node.Body != null) { blockBody = runAnalysis(BindEmbeddedBlock(node.Body, diagnostics), diagnostics); if (node.ExpressionBody != null) { expressionBody = runAnalysis(BindExpressionBodyAsBlock(node.ExpressionBody, BindingDiagnosticBag.Discarded), BindingDiagnosticBag.Discarded); } } else if (node.ExpressionBody != null) { expressionBody = runAnalysis(BindExpressionBodyAsBlock(node.ExpressionBody, diagnostics), diagnostics); } else if (!hasErrors && (!localSymbol.IsExtern || !localSymbol.IsStatic)) { hasErrors = true; diagnostics.Add(ErrorCode.ERR_LocalFunctionMissingBody, localSymbol.Locations[0], localSymbol); } if (!hasErrors && (blockBody != null || expressionBody != null) && localSymbol.IsExtern) { hasErrors = true; diagnostics.Add(ErrorCode.ERR_ExternHasBody, localSymbol.Locations[0], localSymbol); } Debug.Assert(blockBody != null || expressionBody != null || (localSymbol.IsExtern && localSymbol.IsStatic) || hasErrors); localSymbol.GetDeclarationDiagnostics(diagnostics); Symbol.CheckForBlockAndExpressionBody( node.Body, node.ExpressionBody, node, diagnostics); return new BoundLocalFunctionStatement(node, localSymbol, blockBody, expressionBody, hasErrors); BoundBlock runAnalysis(BoundBlock block, BindingDiagnosticBag blockDiagnostics) { if (block != null) { // Have to do ControlFlowPass here because in MethodCompiler, we don't call this for synthed methods // rather we go directly to LowerBodyOrInitializer, which skips over flow analysis (which is in CompileMethod) // (the same thing - calling ControlFlowPass.Analyze in the lowering - is done for lambdas) // It's a bit of code duplication, but refactoring would make things worse. // However, we don't need to report diagnostics here. They will be reported when analyzing the parent method. var ignored = DiagnosticBag.GetInstance(); var endIsReachable = ControlFlowPass.Analyze(localSymbol.DeclaringCompilation, localSymbol, block, ignored); ignored.Free(); if (endIsReachable) { if (ImplicitReturnIsOkay(localSymbol)) { block = FlowAnalysisPass.AppendImplicitReturn(block, localSymbol); } else { blockDiagnostics.Add(ErrorCode.ERR_ReturnExpected, localSymbol.Locations[0], localSymbol); } } } return block; } } private bool ImplicitReturnIsOkay(MethodSymbol method) { return method.ReturnsVoid || method.IsIterator || method.IsAsyncEffectivelyReturningTask(this.Compilation); } public BoundStatement BindExpressionStatement(ExpressionStatementSyntax node, BindingDiagnosticBag diagnostics) { return BindExpressionStatement(node, node.Expression, node.AllowsAnyExpression, diagnostics); } private BoundExpressionStatement BindExpressionStatement(CSharpSyntaxNode node, ExpressionSyntax syntax, bool allowsAnyExpression, BindingDiagnosticBag diagnostics) { BoundExpressionStatement expressionStatement; var expression = BindRValueWithoutTargetType(syntax, diagnostics); ReportSuppressionIfNeeded(expression, diagnostics); if (!allowsAnyExpression && !IsValidStatementExpression(syntax, expression)) { if (!node.HasErrors) { Error(diagnostics, ErrorCode.ERR_IllegalStatement, syntax); } expressionStatement = new BoundExpressionStatement(node, expression, hasErrors: true); } else { expressionStatement = new BoundExpressionStatement(node, expression); } CheckForUnobservedAwaitable(expression, diagnostics); return expressionStatement; } /// <summary> /// Report an error if this is an awaitable async method invocation that is not being awaited. /// </summary> /// <remarks> /// The checks here are equivalent to StatementBinder::CheckForUnobservedAwaitable() in the native compiler. /// </remarks> private void CheckForUnobservedAwaitable(BoundExpression expression, BindingDiagnosticBag diagnostics) { if (CouldBeAwaited(expression)) { Error(diagnostics, ErrorCode.WRN_UnobservedAwaitableExpression, expression.Syntax); } } internal BoundStatement BindLocalDeclarationStatement(LocalDeclarationStatementSyntax node, BindingDiagnosticBag diagnostics) { if (node.UsingKeyword != default) { return BindUsingDeclarationStatementParts(node, diagnostics); } else { return BindDeclarationStatementParts(node, diagnostics); } } private BoundStatement BindUsingDeclarationStatementParts(LocalDeclarationStatementSyntax node, BindingDiagnosticBag diagnostics) { var usingDeclaration = UsingStatementBinder.BindUsingStatementOrDeclarationFromParts(node, node.UsingKeyword, node.AwaitKeyword, originalBinder: this, usingBinderOpt: null, diagnostics); Debug.Assert(usingDeclaration is BoundUsingLocalDeclarations); return usingDeclaration; } private BoundStatement BindDeclarationStatementParts(LocalDeclarationStatementSyntax node, BindingDiagnosticBag diagnostics) { var typeSyntax = node.Declaration.Type.SkipRef(out _); bool isConst = node.IsConst; bool isVar; AliasSymbol alias; TypeWithAnnotations declType = BindVariableTypeWithAnnotations(node.Declaration, diagnostics, typeSyntax, ref isConst, isVar: out isVar, alias: out alias); var kind = isConst ? LocalDeclarationKind.Constant : LocalDeclarationKind.RegularVariable; var variableList = node.Declaration.Variables; int variableCount = variableList.Count; if (variableCount == 1) { return BindVariableDeclaration(kind, isVar, variableList[0], typeSyntax, declType, alias, diagnostics, includeBoundType: true, associatedSyntaxNode: node); } else { BoundLocalDeclaration[] boundDeclarations = new BoundLocalDeclaration[variableCount]; int i = 0; foreach (var variableDeclarationSyntax in variableList) { bool includeBoundType = i == 0; //To avoid duplicated expressions, only the first declaration should contain the bound type. boundDeclarations[i++] = BindVariableDeclaration(kind, isVar, variableDeclarationSyntax, typeSyntax, declType, alias, diagnostics, includeBoundType); } return new BoundMultipleLocalDeclarations(node, boundDeclarations.AsImmutableOrNull()); } } /// <summary> /// Checks for a Dispose method on <paramref name="expr"/> and returns its <see cref="MethodSymbol"/> if found. /// </summary> /// <param name="expr">Expression on which to perform lookup</param> /// <param name="syntaxNode">The syntax node to perform lookup on</param> /// <param name="diagnostics">Populated with invocation errors, and warnings of near misses</param> /// <returns>The <see cref="MethodSymbol"/> of the Dispose method if one is found, otherwise null.</returns> internal MethodSymbol TryFindDisposePatternMethod(BoundExpression expr, SyntaxNode syntaxNode, bool hasAwait, BindingDiagnosticBag diagnostics) { Debug.Assert(expr is object); Debug.Assert(expr.Type is object); Debug.Assert(expr.Type.IsRefLikeType || hasAwait); // pattern dispose lookup is only valid on ref structs or asynchronous usings var result = PerformPatternMethodLookup(expr, hasAwait ? WellKnownMemberNames.DisposeAsyncMethodName : WellKnownMemberNames.DisposeMethodName, syntaxNode, diagnostics, out var disposeMethod); if (disposeMethod?.IsExtensionMethod == true) { // Extension methods should just be ignored, rather than rejected after-the-fact // Tracked by https://github.com/dotnet/roslyn/issues/32767 // extension methods do not contribute to pattern-based disposal disposeMethod = null; } else if ((!hasAwait && disposeMethod?.ReturnsVoid == false) || result == PatternLookupResult.NotAMethod) { CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); if (this.IsAccessible(disposeMethod, ref useSiteInfo)) { diagnostics.Add(ErrorCode.WRN_PatternBadSignature, syntaxNode.Location, expr.Type, MessageID.IDS_Disposable.Localize(), disposeMethod); } diagnostics.Add(syntaxNode, useSiteInfo); disposeMethod = null; } return disposeMethod; } private TypeWithAnnotations BindVariableTypeWithAnnotations(CSharpSyntaxNode declarationNode, BindingDiagnosticBag diagnostics, TypeSyntax typeSyntax, ref bool isConst, out bool isVar, out AliasSymbol alias) { Debug.Assert( declarationNode is VariableDesignationSyntax || declarationNode.Kind() == SyntaxKind.VariableDeclaration || declarationNode.Kind() == SyntaxKind.DeclarationExpression || declarationNode.Kind() == SyntaxKind.DiscardDesignation); // If the type is "var" then suppress errors when binding it. "var" might be a legal type // or it might not; if it is not then we do not want to report an error. If it is, then // we want to treat the declaration as an explicitly typed declaration. TypeWithAnnotations declType = BindTypeOrVarKeyword(typeSyntax.SkipRef(out _), diagnostics, out isVar, out alias); Debug.Assert(declType.HasType || isVar); if (isVar) { // There are a number of ways in which a var decl can be illegal, but in these // cases we should report an error and then keep right on going with the inference. if (isConst) { Error(diagnostics, ErrorCode.ERR_ImplicitlyTypedVariableCannotBeConst, declarationNode); // Keep processing it as a non-const local. isConst = false; } // In the dev10 compiler the error recovery semantics for the illegal case // "var x = 10, y = 123.4;" are somewhat undesirable. // // First off, this is an error because a straw poll of language designers and // users showed that there was no consensus on whether the above should mean // "double x = 10, y = 123.4;", taking the best type available and substituting // that for "var", or treating it as "var x = 10; var y = 123.4;" -- since there // was no consensus we decided to simply make it illegal. // // In dev10 for error recovery in the IDE we do an odd thing -- we simply take // the type of the first variable and use it. So that is "int x = 10, y = 123.4;". // // This seems less than ideal. In the error recovery scenario it probably makes // more sense to treat that as "var x = 10; var y = 123.4;" and do each inference // separately. if (declarationNode.Parent.Kind() == SyntaxKind.LocalDeclarationStatement && ((VariableDeclarationSyntax)declarationNode).Variables.Count > 1 && !declarationNode.HasErrors) { Error(diagnostics, ErrorCode.ERR_ImplicitlyTypedVariableMultipleDeclarator, declarationNode); } } else { // In the native compiler when given a situation like // // D[] x; // // where D is a static type we report both that D cannot be an element type // of an array, and that D[] is not a valid type for a local variable. // This seems silly; the first error is entirely sufficient. We no longer // produce additional errors for local variables of arrays of static types. if (declType.IsStatic) { Error(diagnostics, ErrorCode.ERR_VarDeclIsStaticClass, typeSyntax, declType.Type); } if (isConst && !declType.Type.CanBeConst()) { Error(diagnostics, ErrorCode.ERR_BadConstType, typeSyntax, declType.Type); // Keep processing it as a non-const local. isConst = false; } } return declType; } internal BoundExpression BindInferredVariableInitializer(BindingDiagnosticBag diagnostics, RefKind refKind, EqualsValueClauseSyntax initializer, CSharpSyntaxNode errorSyntax) { BindValueKind valueKind; ExpressionSyntax value; IsInitializerRefKindValid(initializer, initializer, refKind, diagnostics, out valueKind, out value); // The return value isn't important here; we just want the diagnostics and the BindValueKind return BindInferredVariableInitializer(diagnostics, value, valueKind, errorSyntax); } // The location where the error is reported might not be the initializer. protected BoundExpression BindInferredVariableInitializer(BindingDiagnosticBag diagnostics, ExpressionSyntax initializer, BindValueKind valueKind, CSharpSyntaxNode errorSyntax) { if (initializer == null) { if (!errorSyntax.HasErrors) { Error(diagnostics, ErrorCode.ERR_ImplicitlyTypedVariableWithNoInitializer, errorSyntax); } return null; } if (initializer.Kind() == SyntaxKind.ArrayInitializerExpression) { var result = BindUnexpectedArrayInitializer((InitializerExpressionSyntax)initializer, diagnostics, ErrorCode.ERR_ImplicitlyTypedVariableAssignedArrayInitializer, errorSyntax); return CheckValue(result, valueKind, diagnostics); } BoundExpression value = BindValue(initializer, diagnostics, valueKind); BoundExpression expression = value.Kind is BoundKind.UnboundLambda or BoundKind.MethodGroup ? BindToInferredDelegateType(value, diagnostics) : BindToNaturalType(value, diagnostics); // Certain expressions (null literals, method groups and anonymous functions) have no type of // their own and therefore cannot be the initializer of an implicitly typed local. if (!expression.HasAnyErrors && !expression.HasExpressionType()) { // Cannot assign {0} to an implicitly-typed local variable Error(diagnostics, ErrorCode.ERR_ImplicitlyTypedVariableAssignedBadValue, errorSyntax, expression.Display); } return expression; } private static bool IsInitializerRefKindValid( EqualsValueClauseSyntax initializer, CSharpSyntaxNode node, RefKind variableRefKind, BindingDiagnosticBag diagnostics, out BindValueKind valueKind, out ExpressionSyntax value) { RefKind expressionRefKind = RefKind.None; value = initializer?.Value.CheckAndUnwrapRefExpression(diagnostics, out expressionRefKind); if (variableRefKind == RefKind.None) { valueKind = BindValueKind.RValue; if (expressionRefKind == RefKind.Ref) { Error(diagnostics, ErrorCode.ERR_InitializeByValueVariableWithReference, node); return false; } } else { valueKind = variableRefKind == RefKind.RefReadOnly ? BindValueKind.ReadonlyRef : BindValueKind.RefOrOut; if (initializer == null) { Error(diagnostics, ErrorCode.ERR_ByReferenceVariableMustBeInitialized, node); return false; } else if (expressionRefKind != RefKind.Ref) { Error(diagnostics, ErrorCode.ERR_InitializeByReferenceVariableWithValue, node); return false; } } return true; } protected BoundLocalDeclaration BindVariableDeclaration( LocalDeclarationKind kind, bool isVar, VariableDeclaratorSyntax declarator, TypeSyntax typeSyntax, TypeWithAnnotations declTypeOpt, AliasSymbol aliasOpt, BindingDiagnosticBag diagnostics, bool includeBoundType, CSharpSyntaxNode associatedSyntaxNode = null) { Debug.Assert(declarator != null); return BindVariableDeclaration(LocateDeclaredVariableSymbol(declarator, typeSyntax, kind), kind, isVar, declarator, typeSyntax, declTypeOpt, aliasOpt, diagnostics, includeBoundType, associatedSyntaxNode); } protected BoundLocalDeclaration BindVariableDeclaration( SourceLocalSymbol localSymbol, LocalDeclarationKind kind, bool isVar, VariableDeclaratorSyntax declarator, TypeSyntax typeSyntax, TypeWithAnnotations declTypeOpt, AliasSymbol aliasOpt, BindingDiagnosticBag diagnostics, bool includeBoundType, CSharpSyntaxNode associatedSyntaxNode = null) { Debug.Assert(declarator != null); Debug.Assert(declTypeOpt.HasType || isVar); Debug.Assert(typeSyntax != null); var localDiagnostics = BindingDiagnosticBag.GetInstance(withDiagnostics: true, diagnostics.AccumulatesDependencies); // if we are not given desired syntax, we use declarator associatedSyntaxNode = associatedSyntaxNode ?? declarator; // Check for variable declaration errors. // Use the binder that owns the scope for the local because this (the current) binder // might own nested scope. bool nameConflict = localSymbol.ScopeBinder.ValidateDeclarationNameConflictsInScope(localSymbol, diagnostics); bool hasErrors = false; if (localSymbol.RefKind != RefKind.None) { CheckRefLocalInAsyncOrIteratorMethod(localSymbol.IdentifierToken, diagnostics); } EqualsValueClauseSyntax equalsClauseSyntax = declarator.Initializer; BindValueKind valueKind; ExpressionSyntax value; if (!IsInitializerRefKindValid(equalsClauseSyntax, declarator, localSymbol.RefKind, diagnostics, out valueKind, out value)) { hasErrors = true; } BoundExpression initializerOpt; if (isVar) { aliasOpt = null; initializerOpt = BindInferredVariableInitializer(diagnostics, value, valueKind, declarator); // If we got a good result then swap the inferred type for the "var" TypeSymbol initializerType = initializerOpt?.Type; if ((object)initializerType != null) { declTypeOpt = TypeWithAnnotations.Create(initializerType); if (declTypeOpt.IsVoidType()) { Error(localDiagnostics, ErrorCode.ERR_ImplicitlyTypedVariableAssignedBadValue, declarator, declTypeOpt.Type); declTypeOpt = TypeWithAnnotations.Create(CreateErrorType("var")); hasErrors = true; } if (!declTypeOpt.Type.IsErrorType()) { if (declTypeOpt.IsStatic) { Error(localDiagnostics, ErrorCode.ERR_VarDeclIsStaticClass, typeSyntax, initializerType); hasErrors = true; } } } else { declTypeOpt = TypeWithAnnotations.Create(CreateErrorType("var")); hasErrors = true; } } else { if (ReferenceEquals(equalsClauseSyntax, null)) { initializerOpt = null; } else { // Basically inlined BindVariableInitializer, but with conversion optional. initializerOpt = BindPossibleArrayInitializer(value, declTypeOpt.Type, valueKind, diagnostics); if (kind != LocalDeclarationKind.FixedVariable) { // If this is for a fixed statement, we'll do our own conversion since there are some special cases. initializerOpt = GenerateConversionForAssignment( declTypeOpt.Type, initializerOpt, localDiagnostics, isRefAssignment: localSymbol.RefKind != RefKind.None); } } } Debug.Assert(declTypeOpt.HasType); if (kind == LocalDeclarationKind.FixedVariable) { // NOTE: this is an error, but it won't prevent further binding. if (isVar) { if (!hasErrors) { Error(localDiagnostics, ErrorCode.ERR_ImplicitlyTypedLocalCannotBeFixed, declarator); hasErrors = true; } } if (!declTypeOpt.Type.IsPointerType()) { if (!hasErrors) { Error(localDiagnostics, declTypeOpt.Type.IsFunctionPointer() ? ErrorCode.ERR_CannotUseFunctionPointerAsFixedLocal : ErrorCode.ERR_BadFixedInitType, declarator); hasErrors = true; } } else if (!IsValidFixedVariableInitializer(declTypeOpt.Type, localSymbol, ref initializerOpt, localDiagnostics)) { hasErrors = true; } } if (CheckRestrictedTypeInAsyncMethod(this.ContainingMemberOrLambda, declTypeOpt.Type, localDiagnostics, typeSyntax)) { hasErrors = true; } localSymbol.SetTypeWithAnnotations(declTypeOpt); if (initializerOpt != null) { var currentScope = LocalScopeDepth; localSymbol.SetValEscape(GetValEscape(initializerOpt, currentScope)); if (localSymbol.RefKind != RefKind.None) { localSymbol.SetRefEscape(GetRefEscape(initializerOpt, currentScope)); } } ImmutableArray<BoundExpression> arguments = BindDeclaratorArguments(declarator, localDiagnostics); if (kind == LocalDeclarationKind.FixedVariable || kind == LocalDeclarationKind.UsingVariable) { // CONSIDER: The error message is "you must provide an initializer in a fixed // CONSIDER: or using declaration". The error message could be targeted to // CONSIDER: the actual situation. "you must provide an initializer in a // CONSIDER: 'fixed' declaration." if (initializerOpt == null) { Error(localDiagnostics, ErrorCode.ERR_FixedMustInit, declarator); hasErrors = true; } } else if (kind == LocalDeclarationKind.Constant && initializerOpt != null && !localDiagnostics.HasAnyResolvedErrors()) { var constantValueDiagnostics = localSymbol.GetConstantValueDiagnostics(initializerOpt); diagnostics.AddRange(constantValueDiagnostics, allowMismatchInDependencyAccumulation: true); hasErrors = constantValueDiagnostics.Diagnostics.HasAnyErrors(); } diagnostics.AddRangeAndFree(localDiagnostics); BoundTypeExpression boundDeclType = null; if (includeBoundType) { var invalidDimensions = ArrayBuilder<BoundExpression>.GetInstance(); typeSyntax.VisitRankSpecifiers((rankSpecifier, args) => { bool _ = false; foreach (var expressionSyntax in rankSpecifier.Sizes) { var size = args.binder.BindArrayDimension(expressionSyntax, args.diagnostics, ref _); if (size != null) { args.invalidDimensions.Add(size); } } }, (binder: this, invalidDimensions: invalidDimensions, diagnostics: diagnostics)); boundDeclType = new BoundTypeExpression(typeSyntax, aliasOpt, dimensionsOpt: invalidDimensions.ToImmutableAndFree(), typeWithAnnotations: declTypeOpt); } return new BoundLocalDeclaration( syntax: associatedSyntaxNode, localSymbol: localSymbol, declaredTypeOpt: boundDeclType, initializerOpt: hasErrors ? BindToTypeForErrorRecovery(initializerOpt)?.WithHasErrors() : initializerOpt, argumentsOpt: arguments, inferredType: isVar, hasErrors: hasErrors | nameConflict); } protected bool CheckRefLocalInAsyncOrIteratorMethod(SyntaxToken identifierToken, BindingDiagnosticBag diagnostics) { if (IsInAsyncMethod()) { Error(diagnostics, ErrorCode.ERR_BadAsyncLocalType, identifierToken); return true; } else if (IsDirectlyInIterator) { Error(diagnostics, ErrorCode.ERR_BadIteratorLocalType, identifierToken); return true; } return false; } internal ImmutableArray<BoundExpression> BindDeclaratorArguments(VariableDeclaratorSyntax declarator, BindingDiagnosticBag diagnostics) { // It is possible that we have a bracketed argument list, like "int x[];" or "int x[123];" // in a non-fixed-size-array declaration . This is a common error made by C++ programmers. // We have already given a good error at parse time telling the user to either make it "fixed" // or to move the brackets to the type. However, we should still do semantic analysis of // the arguments, so that errors in them are discovered, hovering over them in the IDE // gives good results, and so on. var arguments = default(ImmutableArray<BoundExpression>); if (declarator.ArgumentList != null) { AnalyzedArguments analyzedArguments = AnalyzedArguments.GetInstance(); BindArgumentsAndNames(declarator.ArgumentList, diagnostics, analyzedArguments); arguments = BuildArgumentsForErrorRecovery(analyzedArguments); analyzedArguments.Free(); } return arguments; } private SourceLocalSymbol LocateDeclaredVariableSymbol(VariableDeclaratorSyntax declarator, TypeSyntax typeSyntax, LocalDeclarationKind outerKind) { LocalDeclarationKind kind = outerKind == LocalDeclarationKind.UsingVariable ? LocalDeclarationKind.UsingVariable : LocalDeclarationKind.RegularVariable; return LocateDeclaredVariableSymbol(declarator.Identifier, typeSyntax, declarator.Initializer, kind); } private SourceLocalSymbol LocateDeclaredVariableSymbol(SyntaxToken identifier, TypeSyntax typeSyntax, EqualsValueClauseSyntax equalsValue, LocalDeclarationKind kind) { SourceLocalSymbol localSymbol = this.LookupLocal(identifier); // In error scenarios with misplaced code, it is possible we can't bind the local declaration. // This occurs through the semantic model. In that case concoct a plausible result. if ((object)localSymbol == null) { localSymbol = SourceLocalSymbol.MakeLocal( ContainingMemberOrLambda, this, false, // do not allow ref typeSyntax, identifier, kind, equalsValue); } return localSymbol; } private bool IsValidFixedVariableInitializer(TypeSymbol declType, SourceLocalSymbol localSymbol, ref BoundExpression initializerOpt, BindingDiagnosticBag diagnostics) { Debug.Assert(!ReferenceEquals(declType, null)); Debug.Assert(declType.IsPointerType()); if (initializerOpt?.HasAnyErrors != false) { return false; } TypeSymbol initializerType = initializerOpt.Type; SyntaxNode initializerSyntax = initializerOpt.Syntax; if ((object)initializerType == null) { Error(diagnostics, ErrorCode.ERR_ExprCannotBeFixed, initializerSyntax); return false; } TypeSymbol elementType; bool hasErrors = false; MethodSymbol fixedPatternMethod = null; switch (initializerOpt.Kind) { case BoundKind.AddressOfOperator: elementType = ((BoundAddressOfOperator)initializerOpt).Operand.Type; break; case BoundKind.FieldAccess: var fa = (BoundFieldAccess)initializerOpt; if (fa.FieldSymbol.IsFixedSizeBuffer) { elementType = ((PointerTypeSymbol)fa.Type).PointedAtType; break; } goto default; default: // fixed (T* variable = <expr>) ... // check for arrays if (initializerType.IsArray()) { // See ExpressionBinder::BindPtrToArray (though most of that functionality is now in LocalRewriter). elementType = ((ArrayTypeSymbol)initializerType).ElementType; break; } // check for a special ref-returning method var additionalDiagnostics = BindingDiagnosticBag.GetInstance(diagnostics); fixedPatternMethod = GetFixedPatternMethodOpt(initializerOpt, additionalDiagnostics); // check for String // NOTE: We will allow the pattern method to take precedence, but only if it is an instance member of System.String if (initializerType.SpecialType == SpecialType.System_String && ((object)fixedPatternMethod == null || fixedPatternMethod.ContainingType.SpecialType != SpecialType.System_String)) { fixedPatternMethod = null; elementType = this.GetSpecialType(SpecialType.System_Char, diagnostics, initializerSyntax); additionalDiagnostics.Free(); break; } // if the feature was enabled, but something went wrong with the method, report that, otherwise don't. // If feature is not enabled, additional errors would be just noise. bool extensibleFixedEnabled = ((CSharpParseOptions)initializerOpt.SyntaxTree.Options)?.IsFeatureEnabled(MessageID.IDS_FeatureExtensibleFixedStatement) != false; if (extensibleFixedEnabled) { diagnostics.AddRange(additionalDiagnostics); } additionalDiagnostics.Free(); if ((object)fixedPatternMethod != null) { elementType = fixedPatternMethod.ReturnType; CheckFeatureAvailability(initializerOpt.Syntax, MessageID.IDS_FeatureExtensibleFixedStatement, diagnostics); break; } else { Error(diagnostics, ErrorCode.ERR_ExprCannotBeFixed, initializerSyntax); return false; } } if (CheckManagedAddr(Compilation, elementType, initializerSyntax.Location, diagnostics)) { hasErrors = true; } initializerOpt = BindToNaturalType(initializerOpt, diagnostics, reportNoTargetType: false); initializerOpt = GetFixedLocalCollectionInitializer(initializerOpt, elementType, declType, fixedPatternMethod, hasErrors, diagnostics); return true; } private MethodSymbol GetFixedPatternMethodOpt(BoundExpression initializer, BindingDiagnosticBag additionalDiagnostics) { if (initializer.Type.IsVoidType()) { return null; } const string methodName = "GetPinnableReference"; var result = PerformPatternMethodLookup(initializer, methodName, initializer.Syntax, additionalDiagnostics, out var patternMethodSymbol); if (patternMethodSymbol is null) { return null; } if (HasOptionalOrVariableParameters(patternMethodSymbol) || patternMethodSymbol.ReturnsVoid || !patternMethodSymbol.RefKind.IsManagedReference() || !(patternMethodSymbol.ParameterCount == 0 || patternMethodSymbol.IsStatic && patternMethodSymbol.ParameterCount == 1)) { // the method does not fit the pattern additionalDiagnostics.Add(ErrorCode.WRN_PatternBadSignature, initializer.Syntax.Location, initializer.Type, "fixed", patternMethodSymbol); return null; } return patternMethodSymbol; } /// <summary> /// Wrap the initializer in a BoundFixedLocalCollectionInitializer so that the rewriter will have the /// information it needs (e.g. conversions, helper methods). /// </summary> private BoundExpression GetFixedLocalCollectionInitializer( BoundExpression initializer, TypeSymbol elementType, TypeSymbol declType, MethodSymbol patternMethodOpt, bool hasErrors, BindingDiagnosticBag diagnostics) { Debug.Assert(initializer != null); SyntaxNode initializerSyntax = initializer.Syntax; TypeSymbol pointerType = new PointerTypeSymbol(TypeWithAnnotations.Create(elementType)); CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); Conversion elementConversion = this.Conversions.ClassifyConversionFromType(pointerType, declType, ref useSiteInfo); diagnostics.Add(initializerSyntax, useSiteInfo); if (!elementConversion.IsValid || !elementConversion.IsImplicit) { GenerateImplicitConversionError(diagnostics, this.Compilation, initializerSyntax, elementConversion, pointerType, declType); hasErrors = true; } return new BoundFixedLocalCollectionInitializer( initializerSyntax, pointerType, elementConversion, initializer, patternMethodOpt, declType, hasErrors); } private BoundExpression BindAssignment(AssignmentExpressionSyntax node, BindingDiagnosticBag diagnostics) { Debug.Assert(node != null); Debug.Assert(node.Left != null); Debug.Assert(node.Right != null); node.Left.CheckDeconstructionCompatibleArgument(diagnostics); if (node.Left.Kind() == SyntaxKind.TupleExpression || node.Left.Kind() == SyntaxKind.DeclarationExpression) { return BindDeconstruction(node, diagnostics); } BindValueKind lhsKind; BindValueKind rhsKind; ExpressionSyntax rhsExpr; bool isRef = false; if (node.Right.Kind() == SyntaxKind.RefExpression) { isRef = true; lhsKind = BindValueKind.RefAssignable; rhsKind = BindValueKind.RefersToLocation; rhsExpr = ((RefExpressionSyntax)node.Right).Expression; } else { lhsKind = BindValueKind.Assignable; rhsKind = BindValueKind.RValue; rhsExpr = node.Right; } var op1 = BindValue(node.Left, diagnostics, lhsKind); ReportSuppressionIfNeeded(op1, diagnostics); var lhsRefKind = RefKind.None; // If the LHS is a ref (not ref-readonly), the rhs // must also be value-assignable if (lhsKind == BindValueKind.RefAssignable && !op1.HasErrors) { // We should now know that op1 is a valid lvalue lhsRefKind = op1.GetRefKind(); if (lhsRefKind == RefKind.Ref || lhsRefKind == RefKind.Out) { rhsKind |= BindValueKind.Assignable; } } var op2 = BindValue(rhsExpr, diagnostics, rhsKind); if (op1.Kind == BoundKind.DiscardExpression) { op2 = BindToNaturalType(op2, diagnostics); op1 = InferTypeForDiscardAssignment((BoundDiscardExpression)op1, op2, diagnostics); } return BindAssignment(node, op1, op2, isRef, diagnostics); } private BoundExpression InferTypeForDiscardAssignment(BoundDiscardExpression op1, BoundExpression op2, BindingDiagnosticBag diagnostics) { var inferredType = op2.Type; if ((object)inferredType == null) { return op1.FailInference(this, diagnostics); } if (inferredType.IsVoidType()) { diagnostics.Add(ErrorCode.ERR_VoidAssignment, op1.Syntax.Location); } return op1.SetInferredTypeWithAnnotations(TypeWithAnnotations.Create(inferredType)); } private BoundAssignmentOperator BindAssignment( SyntaxNode node, BoundExpression op1, BoundExpression op2, bool isRef, BindingDiagnosticBag diagnostics) { Debug.Assert(op1 != null); Debug.Assert(op2 != null); bool hasErrors = op1.HasAnyErrors || op2.HasAnyErrors; if (!op1.HasAnyErrors) { // Build bound conversion. The node might not be used if this is a dynamic conversion // but diagnostics should be reported anyways. var conversion = GenerateConversionForAssignment(op1.Type, op2, diagnostics, isRefAssignment: isRef); // If the result is a dynamic assignment operation (SetMember or SetIndex), // don't generate the boxing conversion to the dynamic type. // Leave the values as they are, and deal with the conversions at runtime. if (op1.Kind != BoundKind.DynamicIndexerAccess && op1.Kind != BoundKind.DynamicMemberAccess && op1.Kind != BoundKind.DynamicObjectInitializerMember) { op2 = conversion; } else { op2 = BindToNaturalType(op2, diagnostics); } if (isRef) { var leftEscape = GetRefEscape(op1, LocalScopeDepth); var rightEscape = GetRefEscape(op2, LocalScopeDepth); if (leftEscape < rightEscape) { Error(diagnostics, ErrorCode.ERR_RefAssignNarrower, node, op1.ExpressionSymbol.Name, op2.Syntax); op2 = ToBadExpression(op2); } } if (op1.Type.IsRefLikeType) { var leftEscape = GetValEscape(op1, LocalScopeDepth); op2 = ValidateEscape(op2, leftEscape, isByRef: false, diagnostics); } } else { op2 = BindToTypeForErrorRecovery(op2); } TypeSymbol type; if ((op1.Kind == BoundKind.EventAccess) && ((BoundEventAccess)op1).EventSymbol.IsWindowsRuntimeEvent) { // Event assignment is a call to void WindowsRuntimeMarshal.AddEventHandler<T>(). type = this.GetSpecialType(SpecialType.System_Void, diagnostics, node); } else { type = op1.Type; } return new BoundAssignmentOperator(node, op1, op2, isRef, type, hasErrors); } private static PropertySymbol GetPropertySymbol(BoundExpression expr, out BoundExpression receiver, out SyntaxNode propertySyntax) { PropertySymbol propertySymbol; switch (expr.Kind) { case BoundKind.PropertyAccess: { var propertyAccess = (BoundPropertyAccess)expr; receiver = propertyAccess.ReceiverOpt; propertySymbol = propertyAccess.PropertySymbol; } break; case BoundKind.IndexerAccess: { var indexerAccess = (BoundIndexerAccess)expr; receiver = indexerAccess.ReceiverOpt; propertySymbol = indexerAccess.Indexer; } break; case BoundKind.IndexOrRangePatternIndexerAccess: { var patternIndexer = (BoundIndexOrRangePatternIndexerAccess)expr; receiver = patternIndexer.Receiver; propertySymbol = (PropertySymbol)patternIndexer.PatternSymbol; } break; default: receiver = null; propertySymbol = null; propertySyntax = null; return null; } var syntax = expr.Syntax; switch (syntax.Kind()) { case SyntaxKind.SimpleMemberAccessExpression: case SyntaxKind.PointerMemberAccessExpression: propertySyntax = ((MemberAccessExpressionSyntax)syntax).Name; break; case SyntaxKind.IdentifierName: propertySyntax = syntax; break; case SyntaxKind.ElementAccessExpression: propertySyntax = ((ElementAccessExpressionSyntax)syntax).ArgumentList; break; default: // Other syntax types, such as QualifiedName, // might occur in invalid code. propertySyntax = syntax; break; } return propertySymbol; } private static SyntaxNode GetEventName(BoundEventAccess expr) { SyntaxNode syntax = expr.Syntax; switch (syntax.Kind()) { case SyntaxKind.SimpleMemberAccessExpression: case SyntaxKind.PointerMemberAccessExpression: return ((MemberAccessExpressionSyntax)syntax).Name; case SyntaxKind.QualifiedName: // This case is reachable only through SemanticModel return ((QualifiedNameSyntax)syntax).Right; case SyntaxKind.IdentifierName: return syntax; case SyntaxKind.MemberBindingExpression: return ((MemberBindingExpressionSyntax)syntax).Name; default: throw ExceptionUtilities.UnexpectedValue(syntax.Kind()); } } /// <summary> /// There are two BadEventUsage error codes and this method decides which one should /// be used for a given event. /// </summary> private DiagnosticInfo GetBadEventUsageDiagnosticInfo(EventSymbol eventSymbol) { var leastOverridden = (EventSymbol)eventSymbol.GetLeastOverriddenMember(this.ContainingType); return leastOverridden.HasAssociatedField ? new CSDiagnosticInfo(ErrorCode.ERR_BadEventUsage, leastOverridden, leastOverridden.ContainingType) : new CSDiagnosticInfo(ErrorCode.ERR_BadEventUsageNoField, leastOverridden); } internal static bool AccessingAutoPropertyFromConstructor(BoundPropertyAccess propertyAccess, Symbol fromMember) { return AccessingAutoPropertyFromConstructor(propertyAccess.ReceiverOpt, propertyAccess.PropertySymbol, fromMember); } private static bool AccessingAutoPropertyFromConstructor(BoundExpression receiver, PropertySymbol propertySymbol, Symbol fromMember) { if (!propertySymbol.IsDefinition && propertySymbol.ContainingType.Equals(propertySymbol.ContainingType.OriginalDefinition, TypeCompareKind.IgnoreNullableModifiersForReferenceTypes)) { propertySymbol = propertySymbol.OriginalDefinition; } var sourceProperty = propertySymbol as SourcePropertySymbolBase; var propertyIsStatic = propertySymbol.IsStatic; return (object)sourceProperty != null && sourceProperty.IsAutoPropertyWithGetAccessor && TypeSymbol.Equals(sourceProperty.ContainingType, fromMember.ContainingType, TypeCompareKind.ConsiderEverything2) && IsConstructorOrField(fromMember, isStatic: propertyIsStatic) && (propertyIsStatic || receiver.Kind == BoundKind.ThisReference); } private static bool IsConstructorOrField(Symbol member, bool isStatic) { return (member as MethodSymbol)?.MethodKind == (isStatic ? MethodKind.StaticConstructor : MethodKind.Constructor) || (member as FieldSymbol)?.IsStatic == isStatic; } private TypeSymbol GetAccessThroughType(BoundExpression receiver) { if (receiver == null) { return this.ContainingType; } else if (receiver.Kind == BoundKind.BaseReference) { // Allow protected access to members defined // in base classes. See spec section 3.5.3. return null; } else { Debug.Assert((object)receiver.Type != null); return receiver.Type; } } private BoundExpression BindPossibleArrayInitializer( ExpressionSyntax node, TypeSymbol destinationType, BindValueKind valueKind, BindingDiagnosticBag diagnostics) { Debug.Assert(node != null); if (node.Kind() != SyntaxKind.ArrayInitializerExpression) { return BindValue(node, diagnostics, valueKind); } BoundExpression result; if (destinationType.Kind == SymbolKind.ArrayType) { result = BindArrayCreationWithInitializer(diagnostics, null, (InitializerExpressionSyntax)node, (ArrayTypeSymbol)destinationType, ImmutableArray<BoundExpression>.Empty); } else { result = BindUnexpectedArrayInitializer((InitializerExpressionSyntax)node, diagnostics, ErrorCode.ERR_ArrayInitToNonArrayType); } return CheckValue(result, valueKind, diagnostics); } protected virtual SourceLocalSymbol LookupLocal(SyntaxToken nameToken) { return Next.LookupLocal(nameToken); } protected virtual LocalFunctionSymbol LookupLocalFunction(SyntaxToken nameToken) { return Next.LookupLocalFunction(nameToken); } /// <summary> /// Returns a value that tells how many local scopes are visible, including the current. /// I.E. outside of any method will be 0 /// immediately inside a method - 1 /// </summary> internal virtual uint LocalScopeDepth => Next.LocalScopeDepth; internal virtual BoundBlock BindEmbeddedBlock(BlockSyntax node, BindingDiagnosticBag diagnostics) { return BindBlock(node, diagnostics); } private BoundBlock BindBlock(BlockSyntax node, BindingDiagnosticBag diagnostics) { if (node.AttributeLists.Count > 0) { Error(diagnostics, ErrorCode.ERR_AttributesNotAllowed, node.AttributeLists[0]); } var binder = GetBinder(node); Debug.Assert(binder != null); return binder.BindBlockParts(node, diagnostics); } private BoundBlock BindBlockParts(BlockSyntax node, BindingDiagnosticBag diagnostics) { var syntaxStatements = node.Statements; int nStatements = syntaxStatements.Count; ArrayBuilder<BoundStatement> boundStatements = ArrayBuilder<BoundStatement>.GetInstance(nStatements); for (int i = 0; i < nStatements; i++) { var boundStatement = BindStatement(syntaxStatements[i], diagnostics); boundStatements.Add(boundStatement); } return FinishBindBlockParts(node, boundStatements.ToImmutableAndFree(), diagnostics); } private BoundBlock FinishBindBlockParts(CSharpSyntaxNode node, ImmutableArray<BoundStatement> boundStatements, BindingDiagnosticBag diagnostics) { ImmutableArray<LocalSymbol> locals = GetDeclaredLocalsForScope(node); if (IsDirectlyInIterator) { var method = ContainingMemberOrLambda as MethodSymbol; if ((object)method != null) { method.IteratorElementTypeWithAnnotations = GetIteratorElementType(); } else { Debug.Assert(diagnostics.DiagnosticBag is null || !diagnostics.DiagnosticBag.IsEmptyWithoutResolution); } } return new BoundBlock( node, locals, GetDeclaredLocalFunctionsForScope(node), boundStatements); } internal BoundExpression GenerateConversionForAssignment(TypeSymbol targetType, BoundExpression expression, BindingDiagnosticBag diagnostics, bool isDefaultParameter = false, bool isRefAssignment = false) { Debug.Assert((object)targetType != null); Debug.Assert(expression != null); // We wish to avoid "cascading" errors, so if the expression we are // attempting to convert to a type had errors, suppress additional // diagnostics. However, if the expression // with errors is an unbound lambda then the errors are almost certainly // syntax errors. For error recovery analysis purposes we wish to bind // error lambdas like "Action<int> f = x=>{ x. };" because IntelliSense // needs to know that x is of type int. if (expression.HasAnyErrors && expression.Kind != BoundKind.UnboundLambda) { diagnostics = BindingDiagnosticBag.Discarded; } CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); var conversion = this.Conversions.ClassifyConversionFromExpression(expression, targetType, ref useSiteInfo); diagnostics.Add(expression.Syntax, useSiteInfo); if (isRefAssignment) { if (conversion.Kind != ConversionKind.Identity) { Error(diagnostics, ErrorCode.ERR_RefAssignmentMustHaveIdentityConversion, expression.Syntax, targetType); } else { return expression; } } else if (!conversion.IsImplicit || !conversion.IsValid) { // We suppress conversion errors on default parameters; eg, // if someone says "void M(string s = 123) {}". We will report // a special error in the default parameter binder. if (!isDefaultParameter) { GenerateImplicitConversionError(diagnostics, expression.Syntax, conversion, expression, targetType); } // Suppress any additional diagnostics diagnostics = BindingDiagnosticBag.Discarded; } return CreateConversion(expression.Syntax, expression, conversion, isCast: false, conversionGroupOpt: null, targetType, diagnostics); } #nullable enable internal void GenerateAnonymousFunctionConversionError(BindingDiagnosticBag diagnostics, SyntaxNode syntax, UnboundLambda anonymousFunction, TypeSymbol targetType) { Debug.Assert((object)targetType != null); Debug.Assert(anonymousFunction != null); // Is the target type simply bad? // If the target type is an error then we've already reported a diagnostic. Don't bother // reporting the conversion error. if (targetType.IsErrorType()) { return; } // CONSIDER: Instead of computing this again, cache the reason why the conversion failed in // CONSIDER: the Conversion result, and simply report that. var reason = Conversions.IsAnonymousFunctionCompatibleWithType(anonymousFunction, targetType); // It is possible that the conversion from lambda to delegate is just fine, and // that we ended up here because the target type, though itself is not an error // type, contains a type argument which is an error type. For example, converting // (Goo goo)=>{} to Action<Goo> is a perfectly legal conversion even if Goo is undefined! // In that case we have already reported an error that Goo is undefined, so just bail out. if (reason == LambdaConversionResult.Success) { return; } var id = anonymousFunction.MessageID.Localize(); if (reason == LambdaConversionResult.BadTargetType) { if (ReportDelegateInvokeUseSiteDiagnostic(diagnostics, targetType, node: syntax)) { return; } // Cannot convert {0} to type '{1}' because it is not a delegate type Error(diagnostics, ErrorCode.ERR_AnonMethToNonDel, syntax, id, targetType); return; } if (reason == LambdaConversionResult.ExpressionTreeMustHaveDelegateTypeArgument) { Debug.Assert(targetType.IsExpressionTree()); Error(diagnostics, ErrorCode.ERR_ExpressionTreeMustHaveDelegate, syntax, ((NamedTypeSymbol)targetType).TypeArgumentsWithAnnotationsNoUseSiteDiagnostics[0].Type); return; } if (reason == LambdaConversionResult.ExpressionTreeFromAnonymousMethod) { Debug.Assert(targetType.IsGenericOrNonGenericExpressionType(out _)); Error(diagnostics, ErrorCode.ERR_AnonymousMethodToExpressionTree, syntax); return; } if (reason == LambdaConversionResult.MismatchedReturnType) { Error(diagnostics, ErrorCode.ERR_CantConvAnonMethReturnType, syntax, id, targetType); return; } // At this point we know that we have either a delegate type or an expression type for the target. // The target type is a valid delegate or expression tree type. Is there something wrong with the // parameter list? // First off, is there a parameter list at all? if (reason == LambdaConversionResult.MissingSignatureWithOutParameter) { // COMPATIBILITY: The C# 4 compiler produces two errors for: // // delegate void D (out int x); // ... // D d = delegate {}; // // error CS1676: Parameter 1 must be declared with the 'out' keyword // error CS1688: Cannot convert anonymous method block without a parameter list // to delegate type 'D' because it has one or more out parameters // // This seems redundant, (because there is no "parameter 1" in the source code) // and unnecessary. I propose that we eliminate the first error. Error(diagnostics, ErrorCode.ERR_CantConvAnonMethNoParams, syntax, targetType); return; } var delegateType = targetType.GetDelegateType(); Debug.Assert(delegateType is not null); // There is a parameter list. Does it have the right number of elements? if (reason == LambdaConversionResult.BadParameterCount) { // Delegate '{0}' does not take {1} arguments Error(diagnostics, ErrorCode.ERR_BadDelArgCount, syntax, delegateType, anonymousFunction.ParameterCount); return; } // The parameter list exists and had the right number of parameters. Were any of its types bad? // If any parameter type of the lambda is an error type then suppress // further errors. We've already reported errors on the bad type. if (anonymousFunction.HasExplicitlyTypedParameterList) { for (int i = 0; i < anonymousFunction.ParameterCount; ++i) { if (anonymousFunction.ParameterType(i).IsErrorType()) { return; } } } // The parameter list exists and had the right number of parameters. Were any of its types // mismatched with the delegate parameter types? // The simplest possible case is (x, y, z)=>whatever where the target type has a ref or out parameter. var delegateParameters = delegateType.DelegateParameters(); if (reason == LambdaConversionResult.RefInImplicitlyTypedLambda) { for (int i = 0; i < anonymousFunction.ParameterCount; ++i) { var delegateRefKind = delegateParameters[i].RefKind; if (delegateRefKind != RefKind.None) { // Parameter {0} must be declared with the '{1}' keyword Error(diagnostics, ErrorCode.ERR_BadParamRef, anonymousFunction.ParameterLocation(i), i + 1, delegateRefKind.ToParameterDisplayString()); } } return; } // See the comments in IsAnonymousFunctionCompatibleWithDelegate for an explanation of this one. if (reason == LambdaConversionResult.StaticTypeInImplicitlyTypedLambda) { for (int i = 0; i < anonymousFunction.ParameterCount; ++i) { if (delegateParameters[i].TypeWithAnnotations.IsStatic) { // {0}: Static types cannot be used as parameter Error(diagnostics, ErrorFacts.GetStaticClassParameterCode(useWarning: false), anonymousFunction.ParameterLocation(i), delegateParameters[i].Type); } } return; } // Otherwise, there might be a more complex reason why the parameter types are mismatched. if (reason == LambdaConversionResult.MismatchedParameterType) { // Cannot convert {0} to type '{1}' because the parameter types do not match the delegate parameter types Error(diagnostics, ErrorCode.ERR_CantConvAnonMethParams, syntax, id, targetType); Debug.Assert(anonymousFunction.ParameterCount == delegateParameters.Length); for (int i = 0; i < anonymousFunction.ParameterCount; ++i) { var lambdaParameterType = anonymousFunction.ParameterType(i); if (lambdaParameterType.IsErrorType()) { continue; } var lambdaParameterLocation = anonymousFunction.ParameterLocation(i); var lambdaRefKind = anonymousFunction.RefKind(i); var delegateParameterType = delegateParameters[i].Type; var delegateRefKind = delegateParameters[i].RefKind; if (!lambdaParameterType.Equals(delegateParameterType, TypeCompareKind.AllIgnoreOptions)) { SymbolDistinguisher distinguisher = new SymbolDistinguisher(this.Compilation, lambdaParameterType, delegateParameterType); // Parameter {0} is declared as type '{1}{2}' but should be '{3}{4}' Error(diagnostics, ErrorCode.ERR_BadParamType, lambdaParameterLocation, i + 1, lambdaRefKind.ToParameterPrefix(), distinguisher.First, delegateRefKind.ToParameterPrefix(), distinguisher.Second); } else if (lambdaRefKind != delegateRefKind) { if (delegateRefKind == RefKind.None) { // Parameter {0} should not be declared with the '{1}' keyword Error(diagnostics, ErrorCode.ERR_BadParamExtraRef, lambdaParameterLocation, i + 1, lambdaRefKind.ToParameterDisplayString()); } else { // Parameter {0} must be declared with the '{1}' keyword Error(diagnostics, ErrorCode.ERR_BadParamRef, lambdaParameterLocation, i + 1, delegateRefKind.ToParameterDisplayString()); } } } return; } if (reason == LambdaConversionResult.BindingFailed) { var bindingResult = anonymousFunction.Bind(delegateType, isExpressionTree: false); Debug.Assert(ErrorFacts.PreventsSuccessfulDelegateConversion(bindingResult.Diagnostics.Diagnostics)); diagnostics.AddRange(bindingResult.Diagnostics); return; } // UNDONE: LambdaConversionResult.VoidExpressionLambdaMustBeStatementExpression: Debug.Assert(false, "Missing case in lambda conversion error reporting"); diagnostics.Add(ErrorCode.ERR_InternalError, syntax.Location); } #nullable disable protected static void GenerateImplicitConversionError(BindingDiagnosticBag diagnostics, CSharpCompilation compilation, SyntaxNode syntax, Conversion conversion, TypeSymbol sourceType, TypeSymbol targetType, ConstantValue sourceConstantValueOpt = null) { Debug.Assert(!conversion.IsImplicit || !conversion.IsValid); // If the either type is an error then an error has already been reported // for some aspect of the analysis of this expression. (For example, something like // "garbage g = null; short s = g;" -- we don't want to report that g is not // convertible to short because we've already reported that g does not have a good type. if (!sourceType.IsErrorType() && !targetType.IsErrorType()) { if (conversion.IsExplicit) { if (sourceType.SpecialType == SpecialType.System_Double && syntax.Kind() == SyntaxKind.NumericLiteralExpression && (targetType.SpecialType == SpecialType.System_Single || targetType.SpecialType == SpecialType.System_Decimal)) { Error(diagnostics, ErrorCode.ERR_LiteralDoubleCast, syntax, (targetType.SpecialType == SpecialType.System_Single) ? "F" : "M", targetType); } else if (conversion.Kind == ConversionKind.ExplicitNumeric && sourceConstantValueOpt != null && sourceConstantValueOpt != ConstantValue.Bad && ConversionsBase.HasImplicitConstantExpressionConversion(new BoundLiteral(syntax, ConstantValue.Bad, sourceType), targetType)) { // CLEVERNESS: By passing ConstantValue.Bad, we tell HasImplicitConstantExpressionConversion to ignore the constant // value and only consider the types. // If there would be an implicit constant conversion for a different constant of the same type // (i.e. one that's not out of range), then it's more helpful to report the range check failure // than to suggest inserting a cast. Error(diagnostics, ErrorCode.ERR_ConstOutOfRange, syntax, sourceConstantValueOpt.Value, targetType); } else { SymbolDistinguisher distinguisher = new SymbolDistinguisher(compilation, sourceType, targetType); Error(diagnostics, ErrorCode.ERR_NoImplicitConvCast, syntax, distinguisher.First, distinguisher.Second); } } else if (conversion.ResultKind == LookupResultKind.OverloadResolutionFailure) { Debug.Assert(conversion.IsUserDefined); ImmutableArray<MethodSymbol> originalUserDefinedConversions = conversion.OriginalUserDefinedConversions; if (originalUserDefinedConversions.Length > 1) { Error(diagnostics, ErrorCode.ERR_AmbigUDConv, syntax, originalUserDefinedConversions[0], originalUserDefinedConversions[1], sourceType, targetType); } else { Debug.Assert(originalUserDefinedConversions.Length == 0, "How can there be exactly one applicable user-defined conversion if the conversion doesn't exist?"); SymbolDistinguisher distinguisher = new SymbolDistinguisher(compilation, sourceType, targetType); Error(diagnostics, ErrorCode.ERR_NoImplicitConv, syntax, distinguisher.First, distinguisher.Second); } } else if (TypeSymbol.Equals(sourceType, targetType, TypeCompareKind.ConsiderEverything2)) { // This occurs for `void`, which cannot even convert to itself. Since SymbolDistinguisher // requires two distinct types, we preempt its use here. The diagnostic is strange, but correct. // Though this diagnostic tends to be a cascaded one, we cannot suppress it until // we have proven that it is always so. Error(diagnostics, ErrorCode.ERR_NoImplicitConv, syntax, sourceType, targetType); } else { SymbolDistinguisher distinguisher = new SymbolDistinguisher(compilation, sourceType, targetType); Error(diagnostics, ErrorCode.ERR_NoImplicitConv, syntax, distinguisher.First, distinguisher.Second); } } } protected void GenerateImplicitConversionError( BindingDiagnosticBag diagnostics, SyntaxNode syntax, Conversion conversion, BoundExpression operand, TypeSymbol targetType) { Debug.Assert(operand != null); Debug.Assert((object)targetType != null); if (targetType.TypeKind == TypeKind.Error) { return; } if (targetType.IsVoidType()) { Error(diagnostics, ErrorCode.ERR_NoImplicitConv, syntax, operand.Display, targetType); return; } switch (operand.Kind) { case BoundKind.BadExpression: { return; } case BoundKind.UnboundLambda: { GenerateAnonymousFunctionConversionError(diagnostics, syntax, (UnboundLambda)operand, targetType); return; } case BoundKind.TupleLiteral: { var tuple = (BoundTupleLiteral)operand; var targetElementTypes = default(ImmutableArray<TypeWithAnnotations>); // If target is a tuple or compatible type with the same number of elements, // report errors for tuple arguments that failed to convert, which would be more useful. if (targetType.TryGetElementTypesWithAnnotationsIfTupleType(out targetElementTypes) && targetElementTypes.Length == tuple.Arguments.Length) { GenerateImplicitConversionErrorsForTupleLiteralArguments(diagnostics, tuple.Arguments, targetElementTypes); return; } // target is not compatible with source and source does not have a type if ((object)tuple.Type == null) { Error(diagnostics, ErrorCode.ERR_ConversionNotTupleCompatible, syntax, tuple.Arguments.Length, targetType); return; } // Otherwise it is just a regular conversion failure from T1 to T2. break; } case BoundKind.MethodGroup: { reportMethodGroupErrors((BoundMethodGroup)operand, fromAddressOf: false); return; } case BoundKind.UnconvertedAddressOfOperator: { reportMethodGroupErrors(((BoundUnconvertedAddressOfOperator)operand).Operand, fromAddressOf: true); return; } case BoundKind.Literal: { if (operand.IsLiteralNull()) { if (targetType.TypeKind == TypeKind.TypeParameter) { Error(diagnostics, ErrorCode.ERR_TypeVarCantBeNull, syntax, targetType); return; } if (targetType.IsValueType) { Error(diagnostics, ErrorCode.ERR_ValueCantBeNull, syntax, targetType); return; } } break; } case BoundKind.StackAllocArrayCreation: { var stackAllocExpression = (BoundStackAllocArrayCreation)operand; Error(diagnostics, ErrorCode.ERR_StackAllocConversionNotPossible, syntax, stackAllocExpression.ElementType, targetType); return; } case BoundKind.UnconvertedSwitchExpression: { var switchExpression = (BoundUnconvertedSwitchExpression)operand; var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; bool reportedError = false; foreach (var arm in switchExpression.SwitchArms) { tryConversion(arm.Value, ref reportedError, ref discardedUseSiteInfo); } Debug.Assert(reportedError); return; } case BoundKind.AddressOfOperator when targetType.IsFunctionPointer(): { Error(diagnostics, ErrorCode.ERR_InvalidAddrOp, ((BoundAddressOfOperator)operand).Operand.Syntax); return; } case BoundKind.UnconvertedConditionalOperator: { var conditionalOperator = (BoundUnconvertedConditionalOperator)operand; var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; bool reportedError = false; tryConversion(conditionalOperator.Consequence, ref reportedError, ref discardedUseSiteInfo); tryConversion(conditionalOperator.Alternative, ref reportedError, ref discardedUseSiteInfo); Debug.Assert(reportedError); return; } void tryConversion(BoundExpression expr, ref bool reportedError, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { var conversion = this.Conversions.ClassifyImplicitConversionFromExpression(expr, targetType, ref useSiteInfo); if (!conversion.IsImplicit || !conversion.IsValid) { GenerateImplicitConversionError(diagnostics, expr.Syntax, conversion, expr, targetType); reportedError = true; } } } var sourceType = operand.Type; if ((object)sourceType != null) { GenerateImplicitConversionError(diagnostics, this.Compilation, syntax, conversion, sourceType, targetType, operand.ConstantValue); return; } Debug.Assert(operand.HasAnyErrors && operand.Kind != BoundKind.UnboundLambda, "Missing a case in implicit conversion error reporting"); void reportMethodGroupErrors(BoundMethodGroup methodGroup, bool fromAddressOf) { if (!Conversions.ReportDelegateOrFunctionPointerMethodGroupDiagnostics(this, methodGroup, targetType, diagnostics)) { var nodeForError = syntax; while (nodeForError.Kind() == SyntaxKind.ParenthesizedExpression) { nodeForError = ((ParenthesizedExpressionSyntax)nodeForError).Expression; } if (nodeForError.Kind() == SyntaxKind.SimpleMemberAccessExpression || nodeForError.Kind() == SyntaxKind.PointerMemberAccessExpression) { nodeForError = ((MemberAccessExpressionSyntax)nodeForError).Name; } var location = nodeForError.Location; if (ReportDelegateInvokeUseSiteDiagnostic(diagnostics, targetType, location)) { return; } ErrorCode errorCode; switch (targetType.TypeKind) { case TypeKind.FunctionPointer when fromAddressOf: errorCode = ErrorCode.ERR_MethFuncPtrMismatch; break; case TypeKind.FunctionPointer: Error(diagnostics, ErrorCode.ERR_MissingAddressOf, location); return; case TypeKind.Delegate when fromAddressOf: errorCode = ErrorCode.ERR_CannotConvertAddressOfToDelegate; break; case TypeKind.Delegate: errorCode = ErrorCode.ERR_MethDelegateMismatch; break; default: if (fromAddressOf) { errorCode = ErrorCode.ERR_AddressOfToNonFunctionPointer; } else if (targetType.SpecialType == SpecialType.System_Delegate) { Error(diagnostics, ErrorCode.ERR_CannotInferDelegateType, location); return; } else { errorCode = ErrorCode.ERR_MethGrpToNonDel; } break; } Error(diagnostics, errorCode, location, methodGroup.Name, targetType); } } } private void GenerateImplicitConversionErrorsForTupleLiteralArguments( BindingDiagnosticBag diagnostics, ImmutableArray<BoundExpression> tupleArguments, ImmutableArray<TypeWithAnnotations> targetElementTypes) { var argLength = tupleArguments.Length; // report all leaf elements of the tuple literal that failed to convert // NOTE: we are not responsible for reporting use site errors here, just the failed leaf conversions. // By the time we get here we have done analysis and know we have failed the cast in general, and diagnostics collected in the process is already in the bag. // The only thing left is to form a diagnostics about the actually failing conversion(s). // This whole method does not itself collect any usesite diagnostics. Its only purpose is to produce an error better than "conversion failed here" var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; for (int i = 0; i < targetElementTypes.Length; i++) { var argument = tupleArguments[i]; var targetElementType = targetElementTypes[i].Type; var elementConversion = Conversions.ClassifyImplicitConversionFromExpression(argument, targetElementType, ref discardedUseSiteInfo); if (!elementConversion.IsValid) { GenerateImplicitConversionError(diagnostics, argument.Syntax, elementConversion, argument, targetElementType); } } } private BoundStatement BindIfStatement(IfStatementSyntax node, BindingDiagnosticBag diagnostics) { var condition = BindBooleanExpression(node.Condition, diagnostics); var consequence = BindPossibleEmbeddedStatement(node.Statement, diagnostics); BoundStatement alternative = (node.Else == null) ? null : BindPossibleEmbeddedStatement(node.Else.Statement, diagnostics); BoundStatement result = new BoundIfStatement(node, condition, consequence, alternative); return result; } internal BoundExpression BindBooleanExpression(ExpressionSyntax node, BindingDiagnosticBag diagnostics) { // SPEC: // A boolean-expression is an expression that yields a result of type bool; // either directly or through application of operator true in certain // contexts as specified in the following. // // The controlling conditional expression of an if-statement, while-statement, // do-statement, or for-statement is a boolean-expression. The controlling // conditional expression of the ?: operator follows the same rules as a // boolean-expression, but for reasons of operator precedence is classified // as a conditional-or-expression. // // A boolean-expression is required to be implicitly convertible to bool // or of a type that implements operator true. If neither requirement // is satisfied, a binding-time error occurs. // // When a boolean expression cannot be implicitly converted to bool but does // implement operator true, then following evaluation of the expression, // the operator true implementation provided by that type is invoked // to produce a bool value. // // SPEC ERROR: The third paragraph above is obviously not correct; we need // SPEC ERROR: to do more than just check to see whether the type implements // SPEC ERROR: operator true. First off, the type could implement the operator // SPEC ERROR: several times: if it is a struct then it could implement it // SPEC ERROR: twice, to take both nullable and non-nullable arguments, and // SPEC ERROR: if it is a class or type parameter then it could have several // SPEC ERROR: implementations on its base classes or effective base classes. // SPEC ERROR: Second, the type of the argument could be S? where S implements // SPEC ERROR: operator true(S?); we want to look at S, not S?, when looking // SPEC ERROR: for applicable candidates. // // SPEC ERROR: Basically, the spec should say "use unary operator overload resolution // SPEC ERROR: to find the candidate set and choose a unique best operator true". var expr = BindValue(node, diagnostics, BindValueKind.RValue); var boolean = GetSpecialType(SpecialType.System_Boolean, diagnostics, node); if (expr.HasAnyErrors) { // The expression could not be bound. Insert a fake conversion // around it to bool and keep on going. // NOTE: no user-defined conversion candidates. return BoundConversion.Synthesized(node, BindToTypeForErrorRecovery(expr), Conversion.NoConversion, false, explicitCastInCode: false, conversionGroupOpt: null, ConstantValue.NotAvailable, boolean, hasErrors: true); } // Oddly enough, "if(dyn)" is bound not as a dynamic conversion to bool, but as a dynamic // invocation of operator true. if (expr.HasDynamicType()) { return new BoundUnaryOperator( node, UnaryOperatorKind.DynamicTrue, BindToNaturalType(expr, diagnostics), ConstantValue.NotAvailable, methodOpt: null, constrainedToTypeOpt: null, LookupResultKind.Viable, boolean) { WasCompilerGenerated = true }; } // Is the operand implicitly convertible to bool? CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); var conversion = this.Conversions.ClassifyConversionFromExpression(expr, boolean, ref useSiteInfo); diagnostics.Add(expr.Syntax, useSiteInfo); if (conversion.IsImplicit) { if (conversion.Kind == ConversionKind.Identity) { // Check to see if we're assigning a boolean literal in a place where an // equality check would be more conventional. // NOTE: Don't do this check unless the expression will be returned // without being wrapped in another bound node (i.e. identity conversion). if (expr.Kind == BoundKind.AssignmentOperator) { var assignment = (BoundAssignmentOperator)expr; if (assignment.Right.Kind == BoundKind.Literal && assignment.Right.ConstantValue.Discriminator == ConstantValueTypeDiscriminator.Boolean) { Error(diagnostics, ErrorCode.WRN_IncorrectBooleanAssg, assignment.Syntax); } } } return CreateConversion( syntax: expr.Syntax, source: expr, conversion: conversion, isCast: false, conversionGroupOpt: null, wasCompilerGenerated: true, destination: boolean, diagnostics: diagnostics); } // It was not. Does it implement operator true? expr = BindToNaturalType(expr, diagnostics); var best = this.UnaryOperatorOverloadResolution(UnaryOperatorKind.True, expr, node, diagnostics, out LookupResultKind resultKind, out ImmutableArray<MethodSymbol> originalUserDefinedOperators); if (!best.HasValue) { // No. Give a "not convertible to bool" error. Debug.Assert(resultKind == LookupResultKind.Empty, "How could overload resolution fail if a user-defined true operator was found?"); Debug.Assert(originalUserDefinedOperators.IsEmpty, "How could overload resolution fail if a user-defined true operator was found?"); GenerateImplicitConversionError(diagnostics, node, conversion, expr, boolean); return BoundConversion.Synthesized(node, expr, Conversion.NoConversion, false, explicitCastInCode: false, conversionGroupOpt: null, ConstantValue.NotAvailable, boolean, hasErrors: true); } UnaryOperatorSignature signature = best.Signature; BoundExpression resultOperand = CreateConversion( node, expr, best.Conversion, isCast: false, conversionGroupOpt: null, destination: best.Signature.OperandType, diagnostics: diagnostics); CheckConstraintLanguageVersionAndRuntimeSupportForOperator(node, signature.Method, signature.ConstrainedToTypeOpt, diagnostics); // Consider op_true to be compiler-generated so that it doesn't appear in the semantic model. // UNDONE: If we decide to expose the operator in the semantic model, we'll have to remove the // WasCompilerGenerated flag (and possibly suppress the symbol in specific APIs). return new BoundUnaryOperator(node, signature.Kind, resultOperand, ConstantValue.NotAvailable, signature.Method, signature.ConstrainedToTypeOpt, resultKind, originalUserDefinedOperators, signature.ReturnType) { WasCompilerGenerated = true }; } private BoundStatement BindSwitchStatement(SwitchStatementSyntax node, BindingDiagnosticBag diagnostics) { Debug.Assert(node != null); Binder switchBinder = this.GetBinder(node); return switchBinder.BindSwitchStatementCore(node, switchBinder, diagnostics); } internal virtual BoundStatement BindSwitchStatementCore(SwitchStatementSyntax node, Binder originalBinder, BindingDiagnosticBag diagnostics) { return this.Next.BindSwitchStatementCore(node, originalBinder, diagnostics); } internal virtual void BindPatternSwitchLabelForInference(CasePatternSwitchLabelSyntax node, BindingDiagnosticBag diagnostics) { this.Next.BindPatternSwitchLabelForInference(node, diagnostics); } private BoundStatement BindWhile(WhileStatementSyntax node, BindingDiagnosticBag diagnostics) { Debug.Assert(node != null); var loopBinder = this.GetBinder(node); Debug.Assert(loopBinder != null); return loopBinder.BindWhileParts(diagnostics, loopBinder); } internal virtual BoundWhileStatement BindWhileParts(BindingDiagnosticBag diagnostics, Binder originalBinder) { return this.Next.BindWhileParts(diagnostics, originalBinder); } private BoundStatement BindDo(DoStatementSyntax node, BindingDiagnosticBag diagnostics) { var loopBinder = this.GetBinder(node); Debug.Assert(loopBinder != null); return loopBinder.BindDoParts(diagnostics, loopBinder); } internal virtual BoundDoStatement BindDoParts(BindingDiagnosticBag diagnostics, Binder originalBinder) { return this.Next.BindDoParts(diagnostics, originalBinder); } internal BoundForStatement BindFor(ForStatementSyntax node, BindingDiagnosticBag diagnostics) { var loopBinder = this.GetBinder(node); Debug.Assert(loopBinder != null); return loopBinder.BindForParts(diagnostics, loopBinder); } internal virtual BoundForStatement BindForParts(BindingDiagnosticBag diagnostics, Binder originalBinder) { return this.Next.BindForParts(diagnostics, originalBinder); } internal BoundStatement BindForOrUsingOrFixedDeclarations(VariableDeclarationSyntax nodeOpt, LocalDeclarationKind localKind, BindingDiagnosticBag diagnostics, out ImmutableArray<BoundLocalDeclaration> declarations) { if (nodeOpt == null) { declarations = ImmutableArray<BoundLocalDeclaration>.Empty; return null; } var typeSyntax = nodeOpt.Type; // Fixed and using variables are not allowed to be ref-like, but regular variables are if (localKind == LocalDeclarationKind.RegularVariable) { typeSyntax = typeSyntax.SkipRef(out _); } AliasSymbol alias; bool isVar; TypeWithAnnotations declType = BindTypeOrVarKeyword(typeSyntax, diagnostics, out isVar, out alias); Debug.Assert(declType.HasType || isVar); var variables = nodeOpt.Variables; int count = variables.Count; Debug.Assert(count > 0); if (isVar && count > 1) { // There are a number of ways in which a var decl can be illegal, but in these // cases we should report an error and then keep right on going with the inference. Error(diagnostics, ErrorCode.ERR_ImplicitlyTypedVariableMultipleDeclarator, nodeOpt); } var declarationArray = new BoundLocalDeclaration[count]; for (int i = 0; i < count; i++) { var variableDeclarator = variables[i]; bool includeBoundType = i == 0; //To avoid duplicated expressions, only the first declaration should contain the bound type. var declaration = BindVariableDeclaration(localKind, isVar, variableDeclarator, typeSyntax, declType, alias, diagnostics, includeBoundType); declarationArray[i] = declaration; } declarations = declarationArray.AsImmutableOrNull(); return (count == 1) ? (BoundStatement)declarations[0] : new BoundMultipleLocalDeclarations(nodeOpt, declarations); } internal BoundStatement BindStatementExpressionList(SeparatedSyntaxList<ExpressionSyntax> statements, BindingDiagnosticBag diagnostics) { int count = statements.Count; if (count == 0) { return null; } else if (count == 1) { var syntax = statements[0]; return BindExpressionStatement(syntax, syntax, false, diagnostics); } else { var statementBuilder = ArrayBuilder<BoundStatement>.GetInstance(); for (int i = 0; i < count; i++) { var syntax = statements[i]; var statement = BindExpressionStatement(syntax, syntax, false, diagnostics); statementBuilder.Add(statement); } return BoundStatementList.Synthesized(statements.Node, statementBuilder.ToImmutableAndFree()); } } private BoundStatement BindForEach(CommonForEachStatementSyntax node, BindingDiagnosticBag diagnostics) { Binder loopBinder = this.GetBinder(node); return this.GetBinder(node.Expression).WrapWithVariablesIfAny(node.Expression, loopBinder.BindForEachParts(diagnostics, loopBinder)); } internal virtual BoundStatement BindForEachParts(BindingDiagnosticBag diagnostics, Binder originalBinder) { return this.Next.BindForEachParts(diagnostics, originalBinder); } /// <summary> /// Like BindForEachParts, but only bind the deconstruction part of the foreach, for purpose of inferring the types of the declared locals. /// </summary> internal virtual BoundStatement BindForEachDeconstruction(BindingDiagnosticBag diagnostics, Binder originalBinder) { return this.Next.BindForEachDeconstruction(diagnostics, originalBinder); } private BoundStatement BindBreak(BreakStatementSyntax node, BindingDiagnosticBag diagnostics) { var target = this.BreakLabel; if ((object)target == null) { Error(diagnostics, ErrorCode.ERR_NoBreakOrCont, node); return new BoundBadStatement(node, ImmutableArray<BoundNode>.Empty, hasErrors: true); } return new BoundBreakStatement(node, target); } private BoundStatement BindContinue(ContinueStatementSyntax node, BindingDiagnosticBag diagnostics) { var target = this.ContinueLabel; if ((object)target == null) { Error(diagnostics, ErrorCode.ERR_NoBreakOrCont, node); return new BoundBadStatement(node, ImmutableArray<BoundNode>.Empty, hasErrors: true); } return new BoundContinueStatement(node, target); } private static SwitchBinder GetSwitchBinder(Binder binder) { SwitchBinder switchBinder = binder as SwitchBinder; while (binder != null && switchBinder == null) { binder = binder.Next; switchBinder = binder as SwitchBinder; } return switchBinder; } protected static bool IsInAsyncMethod(MethodSymbol method) { return (object)method != null && method.IsAsync; } protected bool IsInAsyncMethod() { return IsInAsyncMethod(this.ContainingMemberOrLambda as MethodSymbol); } protected bool IsEffectivelyTaskReturningAsyncMethod() { var symbol = this.ContainingMemberOrLambda; return symbol?.Kind == SymbolKind.Method && ((MethodSymbol)symbol).IsAsyncEffectivelyReturningTask(this.Compilation); } protected bool IsEffectivelyGenericTaskReturningAsyncMethod() { var symbol = this.ContainingMemberOrLambda; return symbol?.Kind == SymbolKind.Method && ((MethodSymbol)symbol).IsAsyncEffectivelyReturningGenericTask(this.Compilation); } protected bool IsIAsyncEnumerableOrIAsyncEnumeratorReturningAsyncMethod() { var symbol = this.ContainingMemberOrLambda; if (symbol?.Kind == SymbolKind.Method) { var method = (MethodSymbol)symbol; return method.IsAsyncReturningIAsyncEnumerable(this.Compilation) || method.IsAsyncReturningIAsyncEnumerator(this.Compilation); } return false; } protected virtual TypeSymbol GetCurrentReturnType(out RefKind refKind) { var symbol = this.ContainingMemberOrLambda as MethodSymbol; if ((object)symbol != null) { refKind = symbol.RefKind; TypeSymbol returnType = symbol.ReturnType; if ((object)returnType == LambdaSymbol.ReturnTypeIsBeingInferred) { return null; } return returnType; } refKind = RefKind.None; return null; } private BoundStatement BindReturn(ReturnStatementSyntax syntax, BindingDiagnosticBag diagnostics) { var refKind = RefKind.None; var expressionSyntax = syntax.Expression?.CheckAndUnwrapRefExpression(diagnostics, out refKind); BoundExpression arg = null; if (expressionSyntax != null) { BindValueKind requiredValueKind = GetRequiredReturnValueKind(refKind); arg = BindValue(expressionSyntax, diagnostics, requiredValueKind); } else { // If this is a void return statement in a script, return default(T). var interactiveInitializerMethod = this.ContainingMemberOrLambda as SynthesizedInteractiveInitializerMethod; if (interactiveInitializerMethod != null) { arg = new BoundDefaultExpression(interactiveInitializerMethod.GetNonNullSyntaxNode(), interactiveInitializerMethod.ResultType); } } RefKind sigRefKind; TypeSymbol retType = GetCurrentReturnType(out sigRefKind); bool hasErrors = false; if (IsDirectlyInIterator) { diagnostics.Add(ErrorCode.ERR_ReturnInIterator, syntax.ReturnKeyword.GetLocation()); hasErrors = true; } else if (IsInAsyncMethod()) { if (refKind != RefKind.None) { // This can happen if we are binding an async anonymous method to a delegate type. diagnostics.Add(ErrorCode.ERR_MustNotHaveRefReturn, syntax.ReturnKeyword.GetLocation()); hasErrors = true; } else if (IsIAsyncEnumerableOrIAsyncEnumeratorReturningAsyncMethod()) { diagnostics.Add(ErrorCode.ERR_ReturnInIterator, syntax.ReturnKeyword.GetLocation()); hasErrors = true; } } else if ((object)retType != null && (refKind != RefKind.None) != (sigRefKind != RefKind.None)) { var errorCode = refKind != RefKind.None ? ErrorCode.ERR_MustNotHaveRefReturn : ErrorCode.ERR_MustHaveRefReturn; diagnostics.Add(errorCode, syntax.ReturnKeyword.GetLocation()); hasErrors = true; } if (arg != null) { hasErrors |= arg.HasErrors || ((object)arg.Type != null && arg.Type.IsErrorType()); } if (hasErrors) { return new BoundReturnStatement(syntax, refKind, BindToTypeForErrorRecovery(arg), hasErrors: true); } // The return type could be null; we might be attempting to infer the return type either // because of method type inference, or because we are attempting to do error analysis // on a lambda expression of unknown return type. if ((object)retType != null) { if (retType.IsVoidType() || IsEffectivelyTaskReturningAsyncMethod()) { if (arg != null) { var container = this.ContainingMemberOrLambda; var lambda = container as LambdaSymbol; if ((object)lambda != null) { // Error case: void-returning or async task-returning method or lambda with "return x;" var errorCode = retType.IsVoidType() ? ErrorCode.ERR_RetNoObjectRequiredLambda : ErrorCode.ERR_TaskRetNoObjectRequiredLambda; // Anonymous function converted to a void returning delegate cannot return a value Error(diagnostics, errorCode, syntax.ReturnKeyword); hasErrors = true; // COMPATIBILITY: The native compiler also produced an error // COMPATIBILITY: "Cannot convert lambda expression to delegate type 'Action' because some of the // COMPATIBILITY: return types in the block are not implicitly convertible to the delegate return type" // COMPATIBILITY: This error doesn't make sense in the "void" case because the whole idea of // COMPATIBILITY: "conversion to void" is a bit unusual, and we've already given a good error. } else { // Error case: void-returning or async task-returning method or lambda with "return x;" var errorCode = retType.IsVoidType() ? ErrorCode.ERR_RetNoObjectRequired : ErrorCode.ERR_TaskRetNoObjectRequired; Error(diagnostics, errorCode, syntax.ReturnKeyword, container); hasErrors = true; } } } else { if (arg == null) { // Error case: non-void-returning or Task<T>-returning method or lambda but just have "return;" var requiredType = IsEffectivelyGenericTaskReturningAsyncMethod() ? retType.GetMemberTypeArgumentsNoUseSiteDiagnostics().Single() : retType; Error(diagnostics, ErrorCode.ERR_RetObjectRequired, syntax.ReturnKeyword, requiredType); hasErrors = true; } else { arg = CreateReturnConversion(syntax, diagnostics, arg, sigRefKind, retType); arg = ValidateEscape(arg, Binder.ExternalScope, refKind != RefKind.None, diagnostics); } } } else { // Check that the returned expression is not void. if ((object)arg?.Type != null && arg.Type.IsVoidType()) { Error(diagnostics, ErrorCode.ERR_CantReturnVoid, expressionSyntax); hasErrors = true; } } return new BoundReturnStatement(syntax, refKind, hasErrors ? BindToTypeForErrorRecovery(arg) : arg, hasErrors); } internal BoundExpression CreateReturnConversion( SyntaxNode syntax, BindingDiagnosticBag diagnostics, BoundExpression argument, RefKind returnRefKind, TypeSymbol returnType) { // If the return type is not void then the expression must be implicitly convertible. Conversion conversion; bool badAsyncReturnAlreadyReported = false; CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); if (IsInAsyncMethod()) { Debug.Assert(returnRefKind == RefKind.None); if (!IsEffectivelyGenericTaskReturningAsyncMethod()) { conversion = Conversion.NoConversion; badAsyncReturnAlreadyReported = true; } else { returnType = returnType.GetMemberTypeArgumentsNoUseSiteDiagnostics().Single(); conversion = this.Conversions.ClassifyConversionFromExpression(argument, returnType, ref useSiteInfo); } } else { conversion = this.Conversions.ClassifyConversionFromExpression(argument, returnType, ref useSiteInfo); } diagnostics.Add(syntax, useSiteInfo); if (!argument.HasAnyErrors) { if (returnRefKind != RefKind.None) { if (conversion.Kind != ConversionKind.Identity) { Error(diagnostics, ErrorCode.ERR_RefReturnMustHaveIdentityConversion, argument.Syntax, returnType); argument = argument.WithHasErrors(); } else { return BindToNaturalType(argument, diagnostics); } } else if (!conversion.IsImplicit || !conversion.IsValid) { if (!badAsyncReturnAlreadyReported) { RefKind unusedRefKind; if (IsEffectivelyGenericTaskReturningAsyncMethod() && TypeSymbol.Equals(argument.Type, this.GetCurrentReturnType(out unusedRefKind), TypeCompareKind.ConsiderEverything2)) { // Since this is an async method, the return expression must be of type '{0}' rather than 'Task<{0}>' Error(diagnostics, ErrorCode.ERR_BadAsyncReturnExpression, argument.Syntax, returnType); } else { GenerateImplicitConversionError(diagnostics, argument.Syntax, conversion, argument, returnType); if (this.ContainingMemberOrLambda is LambdaSymbol) { ReportCantConvertLambdaReturn(argument.Syntax, diagnostics); } } } } } return CreateConversion(argument.Syntax, argument, conversion, isCast: false, conversionGroupOpt: null, returnType, diagnostics); } private BoundTryStatement BindTryStatement(TryStatementSyntax node, BindingDiagnosticBag diagnostics) { Debug.Assert(node != null); var tryBlock = BindEmbeddedBlock(node.Block, diagnostics); var catchBlocks = BindCatchBlocks(node.Catches, diagnostics); var finallyBlockOpt = (node.Finally != null) ? BindEmbeddedBlock(node.Finally.Block, diagnostics) : null; return new BoundTryStatement(node, tryBlock, catchBlocks, finallyBlockOpt); } private ImmutableArray<BoundCatchBlock> BindCatchBlocks(SyntaxList<CatchClauseSyntax> catchClauses, BindingDiagnosticBag diagnostics) { int n = catchClauses.Count; if (n == 0) { return ImmutableArray<BoundCatchBlock>.Empty; } var catchBlocks = ArrayBuilder<BoundCatchBlock>.GetInstance(n); var hasCatchAll = false; foreach (var catchSyntax in catchClauses) { if (hasCatchAll) { diagnostics.Add(ErrorCode.ERR_TooManyCatches, catchSyntax.CatchKeyword.GetLocation()); } var catchBinder = this.GetBinder(catchSyntax); var catchBlock = catchBinder.BindCatchBlock(catchSyntax, catchBlocks, diagnostics); catchBlocks.Add(catchBlock); hasCatchAll |= catchSyntax.Declaration == null && catchSyntax.Filter == null; } return catchBlocks.ToImmutableAndFree(); } private BoundCatchBlock BindCatchBlock(CatchClauseSyntax node, ArrayBuilder<BoundCatchBlock> previousBlocks, BindingDiagnosticBag diagnostics) { bool hasError = false; TypeSymbol type = null; BoundExpression boundFilter = null; var declaration = node.Declaration; if (declaration != null) { // Note: The type is being bound twice: here and in LocalSymbol.Type. Currently, // LocalSymbol.Type ignores diagnostics so it seems cleaner to bind the type here // as well. However, if LocalSymbol.Type is changed to report diagnostics, we'll // need to avoid binding here since that will result in duplicate diagnostics. type = this.BindType(declaration.Type, diagnostics).Type; Debug.Assert((object)type != null); if (type.IsErrorType()) { hasError = true; } else { CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); TypeSymbol effectiveType = type.EffectiveType(ref useSiteInfo); if (!Compilation.IsExceptionType(effectiveType, ref useSiteInfo)) { // "The type caught or thrown must be derived from System.Exception" Error(diagnostics, ErrorCode.ERR_BadExceptionType, declaration.Type); hasError = true; diagnostics.Add(declaration.Type, useSiteInfo); } else { diagnostics.AddDependencies(useSiteInfo); } } } var filter = node.Filter; if (filter != null) { var filterBinder = this.GetBinder(filter); boundFilter = filterBinder.BindCatchFilter(filter, diagnostics); hasError |= boundFilter.HasAnyErrors; } if (!hasError) { // TODO: Loop is O(n), caller is O(n^2). Perhaps we could iterate in reverse order (since it's easier to find // base types than to find derived types). Debug.Assert(((object)type == null) || !type.IsErrorType()); foreach (var previousBlock in previousBlocks) { var previousType = previousBlock.ExceptionTypeOpt; // If the previous type is a generic parameter we don't know what exception types it's gonna catch exactly. // If it is a class-type we know it's gonna catch all exception types of its type and types that are derived from it. // So if the current type is a class-type (or an effective base type of a generic parameter) // that derives from the previous type the current catch is unreachable. if (previousBlock.ExceptionFilterOpt == null && (object)previousType != null && !previousType.IsErrorType()) { if ((object)type != null) { CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); if (Conversions.HasIdentityOrImplicitReferenceConversion(type, previousType, ref useSiteInfo)) { // "A previous catch clause already catches all exceptions of this or of a super type ('{0}')" Error(diagnostics, ErrorCode.ERR_UnreachableCatch, declaration.Type, previousType); diagnostics.Add(declaration.Type, useSiteInfo); hasError = true; break; } diagnostics.Add(declaration.Type, useSiteInfo); } else if (TypeSymbol.Equals(previousType, Compilation.GetWellKnownType(WellKnownType.System_Exception), TypeCompareKind.ConsiderEverything2) && Compilation.SourceAssembly.RuntimeCompatibilityWrapNonExceptionThrows) { // If the RuntimeCompatibility(WrapNonExceptionThrows = false) is applied on the source assembly or any referenced netmodule. // an empty catch may catch exceptions that don't derive from System.Exception. // "A previous catch clause already catches all exceptions..." Error(diagnostics, ErrorCode.WRN_UnreachableGeneralCatch, node.CatchKeyword); break; } } } } var binder = GetBinder(node); Debug.Assert(binder != null); ImmutableArray<LocalSymbol> locals = binder.GetDeclaredLocalsForScope(node); BoundExpression exceptionSource = null; LocalSymbol local = locals.FirstOrDefault(); if (local?.DeclarationKind == LocalDeclarationKind.CatchVariable) { Debug.Assert(local.Type.IsErrorType() || (TypeSymbol.Equals(local.Type, type, TypeCompareKind.ConsiderEverything2))); // Check for local variable conflicts in the *enclosing* binder, not the *current* binder; // obviously we will find a local of the given name in the current binder. hasError |= this.ValidateDeclarationNameConflictsInScope(local, diagnostics); exceptionSource = new BoundLocal(declaration, local, ConstantValue.NotAvailable, local.Type); } var block = BindEmbeddedBlock(node.Block, diagnostics); return new BoundCatchBlock(node, locals, exceptionSource, type, exceptionFilterPrologueOpt: null, boundFilter, block, hasError); } private BoundExpression BindCatchFilter(CatchFilterClauseSyntax filter, BindingDiagnosticBag diagnostics) { BoundExpression boundFilter = this.BindBooleanExpression(filter.FilterExpression, diagnostics); if (boundFilter.ConstantValue != ConstantValue.NotAvailable) { // Depending on whether the filter constant is true or false, and whether there are other catch clauses, // we suggest different actions var errorCode = boundFilter.ConstantValue.BooleanValue ? ErrorCode.WRN_FilterIsConstantTrue : (filter.Parent.Parent is TryStatementSyntax s && s.Catches.Count == 1 && s.Finally == null) ? ErrorCode.WRN_FilterIsConstantFalseRedundantTryCatch : ErrorCode.WRN_FilterIsConstantFalse; // Since the expression is a constant, the name can be retrieved from the first token Error(diagnostics, errorCode, filter.FilterExpression); } return boundFilter; } // Report an extra error on the return if we are in a lambda conversion. private void ReportCantConvertLambdaReturn(SyntaxNode syntax, BindingDiagnosticBag diagnostics) { // Suppress this error if the lambda is a result of a query rewrite. if (syntax.Parent is QueryClauseSyntax || syntax.Parent is SelectOrGroupClauseSyntax) return; var lambda = this.ContainingMemberOrLambda as LambdaSymbol; if ((object)lambda != null) { Location location = GetLocationForDiagnostics(syntax); if (IsInAsyncMethod()) { // Cannot convert async {0} to intended delegate type. An async {0} may return void, Task or Task<T>, none of which are convertible to '{1}'. Error(diagnostics, ErrorCode.ERR_CantConvAsyncAnonFuncReturns, location, lambda.MessageID.Localize(), lambda.ReturnType); } else { // Cannot convert {0} to intended delegate type because some of the return types in the block are not implicitly convertible to the delegate return type Error(diagnostics, ErrorCode.ERR_CantConvAnonMethReturns, location, lambda.MessageID.Localize()); } } } private static Location GetLocationForDiagnostics(SyntaxNode node) { switch (node) { case LambdaExpressionSyntax lambdaSyntax: return Location.Create(lambdaSyntax.SyntaxTree, Text.TextSpan.FromBounds(lambdaSyntax.SpanStart, lambdaSyntax.ArrowToken.Span.End)); case AnonymousMethodExpressionSyntax anonymousMethodSyntax: return Location.Create(anonymousMethodSyntax.SyntaxTree, Text.TextSpan.FromBounds(anonymousMethodSyntax.SpanStart, anonymousMethodSyntax.ParameterList?.Span.End ?? anonymousMethodSyntax.DelegateKeyword.Span.End)); } return node.Location; } private static bool IsValidStatementExpression(SyntaxNode syntax, BoundExpression expression) { bool syntacticallyValid = SyntaxFacts.IsStatementExpression(syntax); if (!syntacticallyValid) { return false; } if (expression.IsSuppressed) { return false; } // It is possible that an expression is syntactically valid but semantic analysis // reveals it to be illegal in a statement expression: "new MyDelegate(M)" for example // is not legal because it is a delegate-creation-expression and not an // object-creation-expression, but of course we don't know that syntactically. if (expression.Kind == BoundKind.DelegateCreationExpression || expression.Kind == BoundKind.NameOfOperator) { return false; } return true; } /// <summary> /// Wrap a given expression e into a block as either { e; } or { return e; } /// Shared between lambda and expression-bodied method binding. /// </summary> internal BoundBlock CreateBlockFromExpression(CSharpSyntaxNode node, ImmutableArray<LocalSymbol> locals, RefKind refKind, BoundExpression expression, ExpressionSyntax expressionSyntax, BindingDiagnosticBag diagnostics) { RefKind returnRefKind; var returnType = GetCurrentReturnType(out returnRefKind); var syntax = expressionSyntax ?? expression.Syntax; BoundStatement statement; if (IsInAsyncMethod() && refKind != RefKind.None) { // This can happen if we are binding an async anonymous method to a delegate type. Error(diagnostics, ErrorCode.ERR_MustNotHaveRefReturn, syntax); expression = BindToTypeForErrorRecovery(expression); statement = new BoundReturnStatement(syntax, refKind, expression) { WasCompilerGenerated = true }; } else if ((object)returnType != null) { if ((refKind != RefKind.None) != (returnRefKind != RefKind.None) && expression.Kind != BoundKind.ThrowExpression) { var errorCode = refKind != RefKind.None ? ErrorCode.ERR_MustNotHaveRefReturn : ErrorCode.ERR_MustHaveRefReturn; Error(diagnostics, errorCode, syntax); expression = BindToTypeForErrorRecovery(expression); statement = new BoundReturnStatement(syntax, RefKind.None, expression) { WasCompilerGenerated = true }; } else if (returnType.IsVoidType() || IsEffectivelyTaskReturningAsyncMethod()) { // If the return type is void then the expression is required to be a legal // statement expression. Debug.Assert(expressionSyntax != null || !IsValidExpressionBody(expressionSyntax, expression)); bool errors = false; if (expressionSyntax == null || !IsValidExpressionBody(expressionSyntax, expression)) { expression = BindToTypeForErrorRecovery(expression); Error(diagnostics, ErrorCode.ERR_IllegalStatement, syntax); errors = true; } else { expression = BindToNaturalType(expression, diagnostics); } // Don't mark compiler generated so that the rewriter generates sequence points var expressionStatement = new BoundExpressionStatement(syntax, expression, errors); CheckForUnobservedAwaitable(expression, diagnostics); statement = expressionStatement; } else if (IsIAsyncEnumerableOrIAsyncEnumeratorReturningAsyncMethod()) { Error(diagnostics, ErrorCode.ERR_ReturnInIterator, syntax); expression = BindToTypeForErrorRecovery(expression); statement = new BoundReturnStatement(syntax, returnRefKind, expression) { WasCompilerGenerated = true }; } else { expression = returnType.IsErrorType() ? BindToTypeForErrorRecovery(expression) : CreateReturnConversion(syntax, diagnostics, expression, refKind, returnType); statement = new BoundReturnStatement(syntax, returnRefKind, expression) { WasCompilerGenerated = true }; } } else if (expression.Type?.SpecialType == SpecialType.System_Void) { expression = BindToNaturalType(expression, diagnostics); statement = new BoundExpressionStatement(syntax, expression) { WasCompilerGenerated = true }; } else { // When binding for purpose of inferring the return type of a lambda, we do not require returned expressions (such as `default` or switch expressions) to have a natural type var inferringLambda = this.ContainingMemberOrLambda is MethodSymbol method && (object)method.ReturnType == LambdaSymbol.ReturnTypeIsBeingInferred; if (!inferringLambda) { expression = BindToNaturalType(expression, diagnostics); } statement = new BoundReturnStatement(syntax, refKind, expression) { WasCompilerGenerated = true }; } // Need to attach the tree for when we generate sequence points. return new BoundBlock(node, locals, ImmutableArray.Create(statement)) { WasCompilerGenerated = node.Kind() != SyntaxKind.ArrowExpressionClause }; } private static bool IsValidExpressionBody(SyntaxNode expressionSyntax, BoundExpression expression) { return IsValidStatementExpression(expressionSyntax, expression) || expressionSyntax.Kind() == SyntaxKind.ThrowExpression; } /// <summary> /// Binds an expression-bodied member with expression e as either { return e; } or { e; }. /// </summary> internal virtual BoundBlock BindExpressionBodyAsBlock(ArrowExpressionClauseSyntax expressionBody, BindingDiagnosticBag diagnostics) { Binder bodyBinder = this.GetBinder(expressionBody); Debug.Assert(bodyBinder != null); return bindExpressionBodyAsBlockInternal(expressionBody, bodyBinder, diagnostics); // Use static local function to prevent accidentally calling instance methods on `this` instead of `bodyBinder` static BoundBlock bindExpressionBodyAsBlockInternal(ArrowExpressionClauseSyntax expressionBody, Binder bodyBinder, BindingDiagnosticBag diagnostics) { RefKind refKind; ExpressionSyntax expressionSyntax = expressionBody.Expression.CheckAndUnwrapRefExpression(diagnostics, out refKind); BindValueKind requiredValueKind = bodyBinder.GetRequiredReturnValueKind(refKind); BoundExpression expression = bodyBinder.BindValue(expressionSyntax, diagnostics, requiredValueKind); expression = bodyBinder.ValidateEscape(expression, Binder.ExternalScope, refKind != RefKind.None, diagnostics); return bodyBinder.CreateBlockFromExpression(expressionBody, bodyBinder.GetDeclaredLocalsForScope(expressionBody), refKind, expression, expressionSyntax, diagnostics); } } /// <summary> /// Binds a lambda with expression e as either { return e; } or { e; }. /// </summary> public BoundBlock BindLambdaExpressionAsBlock(ExpressionSyntax body, BindingDiagnosticBag diagnostics) { Binder bodyBinder = this.GetBinder(body); Debug.Assert(bodyBinder != null); RefKind refKind; var expressionSyntax = body.CheckAndUnwrapRefExpression(diagnostics, out refKind); BindValueKind requiredValueKind = GetRequiredReturnValueKind(refKind); BoundExpression expression = bodyBinder.BindValue(expressionSyntax, diagnostics, requiredValueKind); expression = ValidateEscape(expression, Binder.ExternalScope, refKind != RefKind.None, diagnostics); return bodyBinder.CreateBlockFromExpression(body, bodyBinder.GetDeclaredLocalsForScope(body), refKind, expression, expressionSyntax, diagnostics); } public BoundBlock CreateBlockFromExpression(ExpressionSyntax body, BoundExpression expression, BindingDiagnosticBag diagnostics) { Binder bodyBinder = this.GetBinder(body); Debug.Assert(bodyBinder != null); Debug.Assert(body.Kind() != SyntaxKind.RefExpression); return bodyBinder.CreateBlockFromExpression(body, bodyBinder.GetDeclaredLocalsForScope(body), RefKind.None, expression, body, diagnostics); } private BindValueKind GetRequiredReturnValueKind(RefKind refKind) { BindValueKind requiredValueKind = BindValueKind.RValue; if (refKind != RefKind.None) { GetCurrentReturnType(out var sigRefKind); requiredValueKind = sigRefKind == RefKind.Ref ? BindValueKind.RefReturn : BindValueKind.ReadonlyRef; } return requiredValueKind; } public virtual BoundNode BindMethodBody(CSharpSyntaxNode syntax, BindingDiagnosticBag diagnostics, bool includesFieldInitializers = false) { switch (syntax) { case RecordDeclarationSyntax recordDecl: return BindRecordConstructorBody(recordDecl, diagnostics); case BaseMethodDeclarationSyntax method: if (method.Kind() == SyntaxKind.ConstructorDeclaration) { return BindConstructorBody((ConstructorDeclarationSyntax)method, diagnostics, includesFieldInitializers); } return BindMethodBody(method, method.Body, method.ExpressionBody, diagnostics); case AccessorDeclarationSyntax accessor: return BindMethodBody(accessor, accessor.Body, accessor.ExpressionBody, diagnostics); case ArrowExpressionClauseSyntax arrowExpression: return BindExpressionBodyAsBlock(arrowExpression, diagnostics); case CompilationUnitSyntax compilationUnit: return BindSimpleProgram(compilationUnit, diagnostics); default: throw ExceptionUtilities.UnexpectedValue(syntax.Kind()); } } private BoundNode BindSimpleProgram(CompilationUnitSyntax compilationUnit, BindingDiagnosticBag diagnostics) { var simpleProgram = (SynthesizedSimpleProgramEntryPointSymbol)ContainingMemberOrLambda; return GetBinder(compilationUnit).BindSimpleProgramCompilationUnit(compilationUnit, simpleProgram, diagnostics); } private BoundNode BindSimpleProgramCompilationUnit(CompilationUnitSyntax compilationUnit, SynthesizedSimpleProgramEntryPointSymbol simpleProgram, BindingDiagnosticBag diagnostics) { ArrayBuilder<BoundStatement> boundStatements = ArrayBuilder<BoundStatement>.GetInstance(); foreach (var statement in compilationUnit.Members) { if (statement is GlobalStatementSyntax topLevelStatement) { var boundStatement = BindStatement(topLevelStatement.Statement, diagnostics); boundStatements.Add(boundStatement); } } return new BoundNonConstructorMethodBody(compilationUnit, FinishBindBlockParts(compilationUnit, boundStatements.ToImmutableAndFree(), diagnostics).MakeCompilerGenerated(), expressionBody: null); } private BoundNode BindRecordConstructorBody(RecordDeclarationSyntax recordDecl, BindingDiagnosticBag diagnostics) { Debug.Assert(recordDecl.ParameterList is object); Debug.Assert(recordDecl.IsKind(SyntaxKind.RecordDeclaration)); Binder bodyBinder = this.GetBinder(recordDecl); Debug.Assert(bodyBinder != null); BoundExpressionStatement initializer = null; if (recordDecl.PrimaryConstructorBaseTypeIfClass is PrimaryConstructorBaseTypeSyntax baseWithArguments) { initializer = bodyBinder.BindConstructorInitializer(baseWithArguments, diagnostics); } return new BoundConstructorMethodBody(recordDecl, bodyBinder.GetDeclaredLocalsForScope(recordDecl), initializer, blockBody: new BoundBlock(recordDecl, ImmutableArray<LocalSymbol>.Empty, ImmutableArray<BoundStatement>.Empty).MakeCompilerGenerated(), expressionBody: null); } internal virtual BoundExpressionStatement BindConstructorInitializer(PrimaryConstructorBaseTypeSyntax initializer, BindingDiagnosticBag diagnostics) { BoundExpression initializerInvocation = GetBinder(initializer).BindConstructorInitializer(initializer.ArgumentList, (MethodSymbol)this.ContainingMember(), diagnostics); var constructorInitializer = new BoundExpressionStatement(initializer, initializerInvocation); Debug.Assert(initializerInvocation.HasAnyErrors || constructorInitializer.IsConstructorInitializer(), "Please keep this bound node in sync with BoundNodeExtensions.IsConstructorInitializer."); return constructorInitializer; } private BoundNode BindConstructorBody(ConstructorDeclarationSyntax constructor, BindingDiagnosticBag diagnostics, bool includesFieldInitializers) { ConstructorInitializerSyntax initializer = constructor.Initializer; if (initializer == null && constructor.Body == null && constructor.ExpressionBody == null) { return null; } Binder bodyBinder = this.GetBinder(constructor); Debug.Assert(bodyBinder != null); bool thisInitializer = initializer?.IsKind(SyntaxKind.ThisConstructorInitializer) == true; if (!thisInitializer && ContainingType.GetMembersUnordered().OfType<SynthesizedRecordConstructor>().Any()) { var constructorSymbol = (MethodSymbol)this.ContainingMember(); if (!constructorSymbol.IsStatic && !SynthesizedRecordCopyCtor.IsCopyConstructor(constructorSymbol)) { // Note: we check the constructor initializer of copy constructors elsewhere Error(diagnostics, ErrorCode.ERR_UnexpectedOrMissingConstructorInitializerInRecord, initializer?.ThisOrBaseKeyword ?? constructor.Identifier); } } // The `: this()` initializer is ignored when it is a default value type constructor // and we need to include field initializers into the constructor. bool skipInitializer = includesFieldInitializers && thisInitializer && ContainingType.IsDefaultValueTypeConstructor(initializer); // Using BindStatement to bind block to make sure we are reusing results of partial binding in SemanticModel return new BoundConstructorMethodBody(constructor, bodyBinder.GetDeclaredLocalsForScope(constructor), skipInitializer ? new BoundNoOpStatement(constructor, NoOpStatementFlavor.Default) : initializer == null ? null : bodyBinder.BindConstructorInitializer(initializer, diagnostics), constructor.Body == null ? null : (BoundBlock)bodyBinder.BindStatement(constructor.Body, diagnostics), constructor.ExpressionBody == null ? null : bodyBinder.BindExpressionBodyAsBlock(constructor.ExpressionBody, constructor.Body == null ? diagnostics : BindingDiagnosticBag.Discarded)); } internal virtual BoundExpressionStatement BindConstructorInitializer(ConstructorInitializerSyntax initializer, BindingDiagnosticBag diagnostics) { BoundExpression initializerInvocation = GetBinder(initializer).BindConstructorInitializer(initializer.ArgumentList, (MethodSymbol)this.ContainingMember(), diagnostics); // Base WasCompilerGenerated state off of whether constructor is implicitly declared, this will ensure proper instrumentation. Debug.Assert(!this.ContainingMember().IsImplicitlyDeclared); var constructorInitializer = new BoundExpressionStatement(initializer, initializerInvocation); Debug.Assert(initializerInvocation.HasAnyErrors || constructorInitializer.IsConstructorInitializer(), "Please keep this bound node in sync with BoundNodeExtensions.IsConstructorInitializer."); return constructorInitializer; } private BoundNode BindMethodBody(CSharpSyntaxNode declaration, BlockSyntax blockBody, ArrowExpressionClauseSyntax expressionBody, BindingDiagnosticBag diagnostics) { if (blockBody == null && expressionBody == null) { return null; } // Using BindStatement to bind block to make sure we are reusing results of partial binding in SemanticModel return new BoundNonConstructorMethodBody(declaration, blockBody == null ? null : (BoundBlock)BindStatement(blockBody, diagnostics), expressionBody == null ? null : BindExpressionBodyAsBlock(expressionBody, blockBody == null ? diagnostics : BindingDiagnosticBag.Discarded)); } internal virtual ImmutableArray<LocalSymbol> Locals { get { return ImmutableArray<LocalSymbol>.Empty; } } internal virtual ImmutableArray<LocalFunctionSymbol> LocalFunctions { get { return ImmutableArray<LocalFunctionSymbol>.Empty; } } internal virtual ImmutableArray<LabelSymbol> Labels { get { return ImmutableArray<LabelSymbol>.Empty; } } /// <summary> /// If this binder owns the scope that can declare extern aliases, a set of declared aliases should be returned (even if empty). /// Otherwise, a default instance should be returned. /// </summary> internal virtual ImmutableArray<AliasAndExternAliasDirective> ExternAliases { get { return default; } } /// <summary> /// If this binder owns the scope that can declare using aliases, a set of declared aliases should be returned (even if empty). /// Otherwise, a default instance should be returned. /// Note, only aliases syntactically declared within the enclosing declaration are included. For example, global aliases /// declared in a different compilation units are not included. /// </summary> internal virtual ImmutableArray<AliasAndUsingDirective> UsingAliases { get { return default; } } /// <summary> /// Perform a lookup for the specified method on the specified expression by attempting to invoke it /// </summary> /// <param name="receiver">The expression to perform pattern lookup on</param> /// <param name="methodName">Method to search for.</param> /// <param name="syntaxNode">The expression for which lookup is being performed</param> /// <param name="diagnostics">Populated with binding diagnostics.</param> /// <param name="result">The method symbol that was looked up, or null</param> /// <returns>A <see cref="PatternLookupResult"/> value with the outcome of the lookup</returns> internal PatternLookupResult PerformPatternMethodLookup(BoundExpression receiver, string methodName, SyntaxNode syntaxNode, BindingDiagnosticBag diagnostics, out MethodSymbol result) { var bindingDiagnostics = BindingDiagnosticBag.GetInstance(diagnostics); try { result = null; var boundAccess = BindInstanceMemberAccess( syntaxNode, syntaxNode, receiver, methodName, rightArity: 0, typeArgumentsSyntax: default, typeArgumentsWithAnnotations: default, invoked: true, indexed: false, bindingDiagnostics); if (boundAccess.Kind != BoundKind.MethodGroup) { // the thing is not a method return PatternLookupResult.NotAMethod; } // NOTE: Because we're calling this method with no arguments and we // explicitly ignore default values for params parameters // (see ParameterSymbol.IsOptional) we know that no ParameterArray // containing method can be invoked in normal form which allows // us to skip some work during the lookup. var analyzedArguments = AnalyzedArguments.GetInstance(); var patternMethodCall = BindMethodGroupInvocation( syntaxNode, syntaxNode, methodName, (BoundMethodGroup)boundAccess, analyzedArguments, bindingDiagnostics, queryClause: null, allowUnexpandedForm: false, anyApplicableCandidates: out _); analyzedArguments.Free(); if (patternMethodCall.Kind != BoundKind.Call) { return PatternLookupResult.NotCallable; } var call = (BoundCall)patternMethodCall; if (call.ResultKind == LookupResultKind.Empty) { return PatternLookupResult.NoResults; } // we have succeeded or almost succeeded to bind the method // report additional binding diagnostics that we have seen so far diagnostics.AddRange(bindingDiagnostics); var patternMethodSymbol = call.Method; if (patternMethodSymbol is ErrorMethodSymbol || patternMethodCall.HasAnyErrors) { return PatternLookupResult.ResultHasErrors; } // Success! result = patternMethodSymbol; return PatternLookupResult.Success; } finally { bindingDiagnostics.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. #nullable disable using System; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { /// <summary> /// This portion of the binder converts StatementSyntax nodes into BoundStatements /// </summary> internal partial class Binder { /// <summary> /// This is the set of parameters and local variables that were used as arguments to /// lock or using statements in enclosing scopes. /// </summary> /// <remarks> /// using (x) { } // x counts /// using (IDisposable y = null) { } // y does not count /// </remarks> internal virtual ImmutableHashSet<Symbol> LockedOrDisposedVariables { get { return Next.LockedOrDisposedVariables; } } /// <remarks> /// Noteworthy override is in MemberSemanticModel.IncrementalBinder (used for caching). /// </remarks> public virtual BoundStatement BindStatement(StatementSyntax node, BindingDiagnosticBag diagnostics) { if (node.AttributeLists.Count > 0) { var attributeList = node.AttributeLists[0]; // Currently, attributes are only allowed on local-functions. if (node.Kind() == SyntaxKind.LocalFunctionStatement) { CheckFeatureAvailability(attributeList, MessageID.IDS_FeatureLocalFunctionAttributes, diagnostics); } else if (node.Kind() != SyntaxKind.Block) { // Don't explicitly error here for blocks. Some codepaths bypass BindStatement // to directly call BindBlock. Error(diagnostics, ErrorCode.ERR_AttributesNotAllowed, attributeList); } } Debug.Assert(node != null); BoundStatement result; switch (node.Kind()) { case SyntaxKind.Block: result = BindBlock((BlockSyntax)node, diagnostics); break; case SyntaxKind.LocalDeclarationStatement: result = BindLocalDeclarationStatement((LocalDeclarationStatementSyntax)node, diagnostics); break; case SyntaxKind.LocalFunctionStatement: result = BindLocalFunctionStatement((LocalFunctionStatementSyntax)node, diagnostics); break; case SyntaxKind.ExpressionStatement: result = BindExpressionStatement((ExpressionStatementSyntax)node, diagnostics); break; case SyntaxKind.IfStatement: result = BindIfStatement((IfStatementSyntax)node, diagnostics); break; case SyntaxKind.SwitchStatement: result = BindSwitchStatement((SwitchStatementSyntax)node, diagnostics); break; case SyntaxKind.DoStatement: result = BindDo((DoStatementSyntax)node, diagnostics); break; case SyntaxKind.WhileStatement: result = BindWhile((WhileStatementSyntax)node, diagnostics); break; case SyntaxKind.ForStatement: result = BindFor((ForStatementSyntax)node, diagnostics); break; case SyntaxKind.ForEachStatement: case SyntaxKind.ForEachVariableStatement: result = BindForEach((CommonForEachStatementSyntax)node, diagnostics); break; case SyntaxKind.BreakStatement: result = BindBreak((BreakStatementSyntax)node, diagnostics); break; case SyntaxKind.ContinueStatement: result = BindContinue((ContinueStatementSyntax)node, diagnostics); break; case SyntaxKind.ReturnStatement: result = BindReturn((ReturnStatementSyntax)node, diagnostics); break; case SyntaxKind.FixedStatement: result = BindFixedStatement((FixedStatementSyntax)node, diagnostics); break; case SyntaxKind.LabeledStatement: result = BindLabeled((LabeledStatementSyntax)node, diagnostics); break; case SyntaxKind.GotoStatement: case SyntaxKind.GotoCaseStatement: case SyntaxKind.GotoDefaultStatement: result = BindGoto((GotoStatementSyntax)node, diagnostics); break; case SyntaxKind.TryStatement: result = BindTryStatement((TryStatementSyntax)node, diagnostics); break; case SyntaxKind.EmptyStatement: result = BindEmpty((EmptyStatementSyntax)node); break; case SyntaxKind.ThrowStatement: result = BindThrow((ThrowStatementSyntax)node, diagnostics); break; case SyntaxKind.UnsafeStatement: result = BindUnsafeStatement((UnsafeStatementSyntax)node, diagnostics); break; case SyntaxKind.UncheckedStatement: case SyntaxKind.CheckedStatement: result = BindCheckedStatement((CheckedStatementSyntax)node, diagnostics); break; case SyntaxKind.UsingStatement: result = BindUsingStatement((UsingStatementSyntax)node, diagnostics); break; case SyntaxKind.YieldBreakStatement: result = BindYieldBreakStatement((YieldStatementSyntax)node, diagnostics); break; case SyntaxKind.YieldReturnStatement: result = BindYieldReturnStatement((YieldStatementSyntax)node, diagnostics); break; case SyntaxKind.LockStatement: result = BindLockStatement((LockStatementSyntax)node, diagnostics); break; default: // NOTE: We could probably throw an exception here, but it's conceivable // that a non-parser syntax tree could reach this point with an unexpected // SyntaxKind and we don't want to throw if that occurs. result = new BoundBadStatement(node, ImmutableArray<BoundNode>.Empty, hasErrors: true); break; } BoundBlock block; Debug.Assert(result.WasCompilerGenerated == false || (result.Kind == BoundKind.Block && (block = (BoundBlock)result).Statements.Length == 1 && block.Statements.Single().WasCompilerGenerated == false), "Synthetic node would not get cached"); Debug.Assert(result.Syntax is StatementSyntax, "BoundStatement should be associated with a statement syntax."); Debug.Assert(System.Linq.Enumerable.Contains(result.Syntax.AncestorsAndSelf(), node), @"Bound statement (or one of its parents) should have same syntax as the given syntax node. Otherwise it may be confusing to the binder cache that uses syntax node as keys."); return result; } private BoundStatement BindCheckedStatement(CheckedStatementSyntax node, BindingDiagnosticBag diagnostics) { return BindEmbeddedBlock(node.Block, diagnostics); } private BoundStatement BindUnsafeStatement(UnsafeStatementSyntax node, BindingDiagnosticBag diagnostics) { var unsafeBinder = this.GetBinder(node); if (!this.Compilation.Options.AllowUnsafe) { Error(diagnostics, ErrorCode.ERR_IllegalUnsafe, node.UnsafeKeyword); } else if (this.IsIndirectlyInIterator) // called *after* we know the binder map has been created. { // Spec 8.2: "An iterator block always defines a safe context, even when its declaration // is nested in an unsafe context." Error(diagnostics, ErrorCode.ERR_IllegalInnerUnsafe, node.UnsafeKeyword); } return BindEmbeddedBlock(node.Block, diagnostics); } private BoundStatement BindFixedStatement(FixedStatementSyntax node, BindingDiagnosticBag diagnostics) { var fixedBinder = this.GetBinder(node); Debug.Assert(fixedBinder != null); fixedBinder.ReportUnsafeIfNotAllowed(node, diagnostics); return fixedBinder.BindFixedStatementParts(node, diagnostics); } private BoundStatement BindFixedStatementParts(FixedStatementSyntax node, BindingDiagnosticBag diagnostics) { VariableDeclarationSyntax declarationSyntax = node.Declaration; ImmutableArray<BoundLocalDeclaration> declarations; BindForOrUsingOrFixedDeclarations(declarationSyntax, LocalDeclarationKind.FixedVariable, diagnostics, out declarations); Debug.Assert(!declarations.IsEmpty); BoundMultipleLocalDeclarations boundMultipleDeclarations = new BoundMultipleLocalDeclarations(declarationSyntax, declarations); BoundStatement boundBody = BindPossibleEmbeddedStatement(node.Statement, diagnostics); return new BoundFixedStatement(node, GetDeclaredLocalsForScope(node), boundMultipleDeclarations, boundBody); } private void CheckRequiredLangVersionForAsyncIteratorMethods(BindingDiagnosticBag diagnostics) { var method = (MethodSymbol)this.ContainingMemberOrLambda; if (method.IsAsync) { MessageID.IDS_FeatureAsyncStreams.CheckFeatureAvailability( diagnostics, method.DeclaringCompilation, method.Locations[0]); } } protected virtual void ValidateYield(YieldStatementSyntax node, BindingDiagnosticBag diagnostics) { Next?.ValidateYield(node, diagnostics); } private BoundStatement BindYieldReturnStatement(YieldStatementSyntax node, BindingDiagnosticBag diagnostics) { ValidateYield(node, diagnostics); TypeSymbol elementType = GetIteratorElementType().Type; BoundExpression argument = (node.Expression == null) ? BadExpression(node).MakeCompilerGenerated() : BindValue(node.Expression, diagnostics, BindValueKind.RValue); argument = ValidateEscape(argument, ExternalScope, isByRef: false, diagnostics: diagnostics); if (!argument.HasAnyErrors) { argument = GenerateConversionForAssignment(elementType, argument, diagnostics); } else { argument = BindToTypeForErrorRecovery(argument); } // NOTE: it's possible that more than one of these conditions is satisfied and that // we won't report the syntactically innermost. However, dev11 appears to check // them in this order, regardless of syntactic nesting (StatementBinder::bindYield). if (this.Flags.Includes(BinderFlags.InFinallyBlock)) { Error(diagnostics, ErrorCode.ERR_BadYieldInFinally, node.YieldKeyword); } else if (this.Flags.Includes(BinderFlags.InTryBlockOfTryCatch)) { Error(diagnostics, ErrorCode.ERR_BadYieldInTryOfCatch, node.YieldKeyword); } else if (this.Flags.Includes(BinderFlags.InCatchBlock)) { Error(diagnostics, ErrorCode.ERR_BadYieldInCatch, node.YieldKeyword); } else if (BindingTopLevelScriptCode) { Error(diagnostics, ErrorCode.ERR_YieldNotAllowedInScript, node.YieldKeyword); } CheckRequiredLangVersionForAsyncIteratorMethods(diagnostics); return new BoundYieldReturnStatement(node, argument); } private BoundStatement BindYieldBreakStatement(YieldStatementSyntax node, BindingDiagnosticBag diagnostics) { if (this.Flags.Includes(BinderFlags.InFinallyBlock)) { Error(diagnostics, ErrorCode.ERR_BadYieldInFinally, node.YieldKeyword); } else if (BindingTopLevelScriptCode) { Error(diagnostics, ErrorCode.ERR_YieldNotAllowedInScript, node.YieldKeyword); } ValidateYield(node, diagnostics); CheckRequiredLangVersionForAsyncIteratorMethods(diagnostics); return new BoundYieldBreakStatement(node); } private BoundStatement BindLockStatement(LockStatementSyntax node, BindingDiagnosticBag diagnostics) { var lockBinder = this.GetBinder(node); Debug.Assert(lockBinder != null); return lockBinder.BindLockStatementParts(diagnostics, lockBinder); } internal virtual BoundStatement BindLockStatementParts(BindingDiagnosticBag diagnostics, Binder originalBinder) { return this.Next.BindLockStatementParts(diagnostics, originalBinder); } private BoundStatement BindUsingStatement(UsingStatementSyntax node, BindingDiagnosticBag diagnostics) { var usingBinder = this.GetBinder(node); Debug.Assert(usingBinder != null); return usingBinder.BindUsingStatementParts(diagnostics, usingBinder); } internal virtual BoundStatement BindUsingStatementParts(BindingDiagnosticBag diagnostics, Binder originalBinder) { return this.Next.BindUsingStatementParts(diagnostics, originalBinder); } internal BoundStatement BindPossibleEmbeddedStatement(StatementSyntax node, BindingDiagnosticBag diagnostics) { Binder binder; switch (node.Kind()) { case SyntaxKind.LocalDeclarationStatement: // Local declarations are not legal in contexts where we need embedded statements. diagnostics.Add(ErrorCode.ERR_BadEmbeddedStmt, node.GetLocation()); // fall through goto case SyntaxKind.ExpressionStatement; case SyntaxKind.ExpressionStatement: case SyntaxKind.LockStatement: case SyntaxKind.IfStatement: case SyntaxKind.YieldReturnStatement: case SyntaxKind.ReturnStatement: case SyntaxKind.ThrowStatement: binder = this.GetBinder(node); Debug.Assert(binder != null); return binder.WrapWithVariablesIfAny(node, binder.BindStatement(node, diagnostics)); case SyntaxKind.LabeledStatement: case SyntaxKind.LocalFunctionStatement: // Labeled statements and local function statements are not legal in contexts where we need embedded statements. diagnostics.Add(ErrorCode.ERR_BadEmbeddedStmt, node.GetLocation()); binder = this.GetBinder(node); Debug.Assert(binder != null); return binder.WrapWithVariablesAndLocalFunctionsIfAny(node, binder.BindStatement(node, diagnostics)); case SyntaxKind.SwitchStatement: var switchStatement = (SwitchStatementSyntax)node; binder = this.GetBinder(switchStatement.Expression); Debug.Assert(binder != null); return binder.WrapWithVariablesIfAny(switchStatement.Expression, binder.BindStatement(node, diagnostics)); case SyntaxKind.EmptyStatement: var emptyStatement = (EmptyStatementSyntax)node; if (!emptyStatement.SemicolonToken.IsMissing) { switch (node.Parent.Kind()) { case SyntaxKind.ForStatement: case SyntaxKind.ForEachStatement: case SyntaxKind.ForEachVariableStatement: case SyntaxKind.WhileStatement: // For loop constructs, only warn if we see a block following the statement. // That indicates code like: "while (x) ; { }" // which is most likely a bug. if (emptyStatement.SemicolonToken.GetNextToken().Kind() != SyntaxKind.OpenBraceToken) { break; } goto default; default: // For non-loop constructs, always warn. This is for code like: // "if (x) ;" which is almost certainly a bug. diagnostics.Add(ErrorCode.WRN_PossibleMistakenNullStatement, node.GetLocation()); break; } } // fall through goto default; default: return BindStatement(node, diagnostics); } } private BoundExpression BindThrownExpression(ExpressionSyntax exprSyntax, BindingDiagnosticBag diagnostics, ref bool hasErrors) { var boundExpr = BindValue(exprSyntax, diagnostics, BindValueKind.RValue); if (Compilation.LanguageVersion < MessageID.IDS_FeatureSwitchExpression.RequiredVersion()) { // This is the pre-C# 8 algorithm for binding a thrown expression. // SPEC VIOLATION: The spec requires the thrown exception to have a type, and that the type // be System.Exception or derived from System.Exception. (Or, if a type parameter, to have // an effective base class that meets that criterion.) However, we allow the literal null // to be thrown, even though it does not meet that criterion and will at runtime always // produce a null reference exception. if (!boundExpr.IsLiteralNull()) { boundExpr = BindToNaturalType(boundExpr, diagnostics); var type = boundExpr.Type; // If the expression is a lambda, anonymous method, or method group then it will // have no compile-time type; give the same error as if the type was wrong. CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); if ((object)type == null || !type.IsErrorType() && !Compilation.IsExceptionType(type.EffectiveType(ref useSiteInfo), ref useSiteInfo)) { diagnostics.Add(ErrorCode.ERR_BadExceptionType, exprSyntax.Location); hasErrors = true; diagnostics.Add(exprSyntax, useSiteInfo); } else { diagnostics.AddDependencies(useSiteInfo); } } } else { // In C# 8 and later we follow the ECMA specification, which neatly handles null and expressions of exception type. boundExpr = GenerateConversionForAssignment(GetWellKnownType(WellKnownType.System_Exception, diagnostics, exprSyntax), boundExpr, diagnostics); } return boundExpr; } private BoundStatement BindThrow(ThrowStatementSyntax node, BindingDiagnosticBag diagnostics) { BoundExpression boundExpr = null; bool hasErrors = false; ExpressionSyntax exprSyntax = node.Expression; if (exprSyntax != null) { boundExpr = BindThrownExpression(exprSyntax, diagnostics, ref hasErrors); } else if (!this.Flags.Includes(BinderFlags.InCatchBlock)) { diagnostics.Add(ErrorCode.ERR_BadEmptyThrow, node.ThrowKeyword.GetLocation()); hasErrors = true; } else if (this.Flags.Includes(BinderFlags.InNestedFinallyBlock)) { // There's a special error code for a rethrow in a finally clause in a catch clause. // Best guess interpretation: if an exception occurs within the nested try block // (i.e. the one in the catch clause, to which the finally clause is attached), // then it's not clear whether the runtime will try to rethrow the "inner" exception // or the "outer" exception. For this reason, the case is disallowed. diagnostics.Add(ErrorCode.ERR_BadEmptyThrowInFinally, node.ThrowKeyword.GetLocation()); hasErrors = true; } return new BoundThrowStatement(node, boundExpr, hasErrors); } private static BoundStatement BindEmpty(EmptyStatementSyntax node) { return new BoundNoOpStatement(node, NoOpStatementFlavor.Default); } private BoundLabeledStatement BindLabeled(LabeledStatementSyntax node, BindingDiagnosticBag diagnostics) { // TODO: verify that goto label lookup was valid (e.g. error checking of symbol resolution for labels) bool hasError = false; var result = LookupResult.GetInstance(); CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); var binder = this.LookupSymbolsWithFallback(result, node.Identifier.ValueText, arity: 0, useSiteInfo: ref useSiteInfo, options: LookupOptions.LabelsOnly); // result.Symbols can be empty in some malformed code, e.g. when a labeled statement is used an embedded statement in an if or foreach statement // In this case we create new label symbol on the fly, and an error is reported by parser var symbol = result.Symbols.Count > 0 && result.IsMultiViable ? (LabelSymbol)result.Symbols.First() : new SourceLabelSymbol((MethodSymbol)ContainingMemberOrLambda, node.Identifier); if (!symbol.IdentifierNodeOrToken.IsToken || symbol.IdentifierNodeOrToken.AsToken() != node.Identifier) { Error(diagnostics, ErrorCode.ERR_DuplicateLabel, node.Identifier, node.Identifier.ValueText); hasError = true; } // check to see if this label (illegally) hides a label from an enclosing scope if (binder != null) { result.Clear(); binder.Next.LookupSymbolsWithFallback(result, node.Identifier.ValueText, arity: 0, useSiteInfo: ref useSiteInfo, options: LookupOptions.LabelsOnly); if (result.IsMultiViable) { // The label '{0}' shadows another label by the same name in a contained scope Error(diagnostics, ErrorCode.ERR_LabelShadow, node.Identifier, node.Identifier.ValueText); hasError = true; } } diagnostics.Add(node, useSiteInfo); result.Free(); var body = BindStatement(node.Statement, diagnostics); return new BoundLabeledStatement(node, symbol, body, hasError); } private BoundStatement BindGoto(GotoStatementSyntax node, BindingDiagnosticBag diagnostics) { switch (node.Kind()) { case SyntaxKind.GotoStatement: var expression = BindLabel(node.Expression, diagnostics); var boundLabel = expression as BoundLabel; if (boundLabel == null) { // diagnostics already reported return new BoundBadStatement(node, ImmutableArray.Create<BoundNode>(expression), true); } var symbol = boundLabel.Label; return new BoundGotoStatement(node, symbol, null, boundLabel); case SyntaxKind.GotoCaseStatement: case SyntaxKind.GotoDefaultStatement: // SPEC: If the goto case statement is not enclosed by a switch statement, a compile-time error occurs. // SPEC: If the goto default statement is not enclosed by a switch statement, a compile-time error occurs. SwitchBinder binder = GetSwitchBinder(this); if (binder == null) { Error(diagnostics, ErrorCode.ERR_InvalidGotoCase, node); ImmutableArray<BoundNode> childNodes; if (node.Expression != null) { var value = BindRValueWithoutTargetType(node.Expression, BindingDiagnosticBag.Discarded); childNodes = ImmutableArray.Create<BoundNode>(value); } else { childNodes = ImmutableArray<BoundNode>.Empty; } return new BoundBadStatement(node, childNodes, true); } return binder.BindGotoCaseOrDefault(node, this, diagnostics); default: throw ExceptionUtilities.UnexpectedValue(node.Kind()); } } private BoundStatement BindLocalFunctionStatement(LocalFunctionStatementSyntax node, BindingDiagnosticBag diagnostics) { // already defined symbol in containing block var localSymbol = this.LookupLocalFunction(node.Identifier); var hasErrors = localSymbol.ScopeBinder .ValidateDeclarationNameConflictsInScope(localSymbol, diagnostics); BoundBlock blockBody = null; BoundBlock expressionBody = null; if (node.Body != null) { blockBody = runAnalysis(BindEmbeddedBlock(node.Body, diagnostics), diagnostics); if (node.ExpressionBody != null) { expressionBody = runAnalysis(BindExpressionBodyAsBlock(node.ExpressionBody, BindingDiagnosticBag.Discarded), BindingDiagnosticBag.Discarded); } } else if (node.ExpressionBody != null) { expressionBody = runAnalysis(BindExpressionBodyAsBlock(node.ExpressionBody, diagnostics), diagnostics); } else if (!hasErrors && (!localSymbol.IsExtern || !localSymbol.IsStatic)) { hasErrors = true; diagnostics.Add(ErrorCode.ERR_LocalFunctionMissingBody, localSymbol.Locations[0], localSymbol); } if (!hasErrors && (blockBody != null || expressionBody != null) && localSymbol.IsExtern) { hasErrors = true; diagnostics.Add(ErrorCode.ERR_ExternHasBody, localSymbol.Locations[0], localSymbol); } Debug.Assert(blockBody != null || expressionBody != null || (localSymbol.IsExtern && localSymbol.IsStatic) || hasErrors); localSymbol.GetDeclarationDiagnostics(diagnostics); Symbol.CheckForBlockAndExpressionBody( node.Body, node.ExpressionBody, node, diagnostics); return new BoundLocalFunctionStatement(node, localSymbol, blockBody, expressionBody, hasErrors); BoundBlock runAnalysis(BoundBlock block, BindingDiagnosticBag blockDiagnostics) { if (block != null) { // Have to do ControlFlowPass here because in MethodCompiler, we don't call this for synthed methods // rather we go directly to LowerBodyOrInitializer, which skips over flow analysis (which is in CompileMethod) // (the same thing - calling ControlFlowPass.Analyze in the lowering - is done for lambdas) // It's a bit of code duplication, but refactoring would make things worse. // However, we don't need to report diagnostics here. They will be reported when analyzing the parent method. var ignored = DiagnosticBag.GetInstance(); var endIsReachable = ControlFlowPass.Analyze(localSymbol.DeclaringCompilation, localSymbol, block, ignored); ignored.Free(); if (endIsReachable) { if (ImplicitReturnIsOkay(localSymbol)) { block = FlowAnalysisPass.AppendImplicitReturn(block, localSymbol); } else { blockDiagnostics.Add(ErrorCode.ERR_ReturnExpected, localSymbol.Locations[0], localSymbol); } } } return block; } } private bool ImplicitReturnIsOkay(MethodSymbol method) { return method.ReturnsVoid || method.IsIterator || method.IsAsyncEffectivelyReturningTask(this.Compilation); } public BoundStatement BindExpressionStatement(ExpressionStatementSyntax node, BindingDiagnosticBag diagnostics) { return BindExpressionStatement(node, node.Expression, node.AllowsAnyExpression, diagnostics); } private BoundExpressionStatement BindExpressionStatement(CSharpSyntaxNode node, ExpressionSyntax syntax, bool allowsAnyExpression, BindingDiagnosticBag diagnostics) { BoundExpressionStatement expressionStatement; var expression = BindRValueWithoutTargetType(syntax, diagnostics); ReportSuppressionIfNeeded(expression, diagnostics); if (!allowsAnyExpression && !IsValidStatementExpression(syntax, expression)) { if (!node.HasErrors) { Error(diagnostics, ErrorCode.ERR_IllegalStatement, syntax); } expressionStatement = new BoundExpressionStatement(node, expression, hasErrors: true); } else { expressionStatement = new BoundExpressionStatement(node, expression); } CheckForUnobservedAwaitable(expression, diagnostics); return expressionStatement; } /// <summary> /// Report an error if this is an awaitable async method invocation that is not being awaited. /// </summary> /// <remarks> /// The checks here are equivalent to StatementBinder::CheckForUnobservedAwaitable() in the native compiler. /// </remarks> private void CheckForUnobservedAwaitable(BoundExpression expression, BindingDiagnosticBag diagnostics) { if (CouldBeAwaited(expression)) { Error(diagnostics, ErrorCode.WRN_UnobservedAwaitableExpression, expression.Syntax); } } internal BoundStatement BindLocalDeclarationStatement(LocalDeclarationStatementSyntax node, BindingDiagnosticBag diagnostics) { if (node.UsingKeyword != default) { return BindUsingDeclarationStatementParts(node, diagnostics); } else { return BindDeclarationStatementParts(node, diagnostics); } } private BoundStatement BindUsingDeclarationStatementParts(LocalDeclarationStatementSyntax node, BindingDiagnosticBag diagnostics) { var usingDeclaration = UsingStatementBinder.BindUsingStatementOrDeclarationFromParts(node, node.UsingKeyword, node.AwaitKeyword, originalBinder: this, usingBinderOpt: null, diagnostics); Debug.Assert(usingDeclaration is BoundUsingLocalDeclarations); return usingDeclaration; } private BoundStatement BindDeclarationStatementParts(LocalDeclarationStatementSyntax node, BindingDiagnosticBag diagnostics) { var typeSyntax = node.Declaration.Type.SkipRef(out _); bool isConst = node.IsConst; bool isVar; AliasSymbol alias; TypeWithAnnotations declType = BindVariableTypeWithAnnotations(node.Declaration, diagnostics, typeSyntax, ref isConst, isVar: out isVar, alias: out alias); var kind = isConst ? LocalDeclarationKind.Constant : LocalDeclarationKind.RegularVariable; var variableList = node.Declaration.Variables; int variableCount = variableList.Count; if (variableCount == 1) { return BindVariableDeclaration(kind, isVar, variableList[0], typeSyntax, declType, alias, diagnostics, includeBoundType: true, associatedSyntaxNode: node); } else { BoundLocalDeclaration[] boundDeclarations = new BoundLocalDeclaration[variableCount]; int i = 0; foreach (var variableDeclarationSyntax in variableList) { bool includeBoundType = i == 0; //To avoid duplicated expressions, only the first declaration should contain the bound type. boundDeclarations[i++] = BindVariableDeclaration(kind, isVar, variableDeclarationSyntax, typeSyntax, declType, alias, diagnostics, includeBoundType); } return new BoundMultipleLocalDeclarations(node, boundDeclarations.AsImmutableOrNull()); } } /// <summary> /// Checks for a Dispose method on <paramref name="expr"/> and returns its <see cref="MethodSymbol"/> if found. /// </summary> /// <param name="expr">Expression on which to perform lookup</param> /// <param name="syntaxNode">The syntax node to perform lookup on</param> /// <param name="diagnostics">Populated with invocation errors, and warnings of near misses</param> /// <returns>The <see cref="MethodSymbol"/> of the Dispose method if one is found, otherwise null.</returns> internal MethodSymbol TryFindDisposePatternMethod(BoundExpression expr, SyntaxNode syntaxNode, bool hasAwait, BindingDiagnosticBag diagnostics) { Debug.Assert(expr is object); Debug.Assert(expr.Type is object); Debug.Assert(expr.Type.IsRefLikeType || hasAwait); // pattern dispose lookup is only valid on ref structs or asynchronous usings var result = PerformPatternMethodLookup(expr, hasAwait ? WellKnownMemberNames.DisposeAsyncMethodName : WellKnownMemberNames.DisposeMethodName, syntaxNode, diagnostics, out var disposeMethod); if (disposeMethod?.IsExtensionMethod == true) { // Extension methods should just be ignored, rather than rejected after-the-fact // Tracked by https://github.com/dotnet/roslyn/issues/32767 // extension methods do not contribute to pattern-based disposal disposeMethod = null; } else if ((!hasAwait && disposeMethod?.ReturnsVoid == false) || result == PatternLookupResult.NotAMethod) { CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); if (this.IsAccessible(disposeMethod, ref useSiteInfo)) { diagnostics.Add(ErrorCode.WRN_PatternBadSignature, syntaxNode.Location, expr.Type, MessageID.IDS_Disposable.Localize(), disposeMethod); } diagnostics.Add(syntaxNode, useSiteInfo); disposeMethod = null; } return disposeMethod; } private TypeWithAnnotations BindVariableTypeWithAnnotations(CSharpSyntaxNode declarationNode, BindingDiagnosticBag diagnostics, TypeSyntax typeSyntax, ref bool isConst, out bool isVar, out AliasSymbol alias) { Debug.Assert( declarationNode is VariableDesignationSyntax || declarationNode.Kind() == SyntaxKind.VariableDeclaration || declarationNode.Kind() == SyntaxKind.DeclarationExpression || declarationNode.Kind() == SyntaxKind.DiscardDesignation); // If the type is "var" then suppress errors when binding it. "var" might be a legal type // or it might not; if it is not then we do not want to report an error. If it is, then // we want to treat the declaration as an explicitly typed declaration. TypeWithAnnotations declType = BindTypeOrVarKeyword(typeSyntax.SkipRef(out _), diagnostics, out isVar, out alias); Debug.Assert(declType.HasType || isVar); if (isVar) { // There are a number of ways in which a var decl can be illegal, but in these // cases we should report an error and then keep right on going with the inference. if (isConst) { Error(diagnostics, ErrorCode.ERR_ImplicitlyTypedVariableCannotBeConst, declarationNode); // Keep processing it as a non-const local. isConst = false; } // In the dev10 compiler the error recovery semantics for the illegal case // "var x = 10, y = 123.4;" are somewhat undesirable. // // First off, this is an error because a straw poll of language designers and // users showed that there was no consensus on whether the above should mean // "double x = 10, y = 123.4;", taking the best type available and substituting // that for "var", or treating it as "var x = 10; var y = 123.4;" -- since there // was no consensus we decided to simply make it illegal. // // In dev10 for error recovery in the IDE we do an odd thing -- we simply take // the type of the first variable and use it. So that is "int x = 10, y = 123.4;". // // This seems less than ideal. In the error recovery scenario it probably makes // more sense to treat that as "var x = 10; var y = 123.4;" and do each inference // separately. if (declarationNode.Parent.Kind() == SyntaxKind.LocalDeclarationStatement && ((VariableDeclarationSyntax)declarationNode).Variables.Count > 1 && !declarationNode.HasErrors) { Error(diagnostics, ErrorCode.ERR_ImplicitlyTypedVariableMultipleDeclarator, declarationNode); } } else { // In the native compiler when given a situation like // // D[] x; // // where D is a static type we report both that D cannot be an element type // of an array, and that D[] is not a valid type for a local variable. // This seems silly; the first error is entirely sufficient. We no longer // produce additional errors for local variables of arrays of static types. if (declType.IsStatic) { Error(diagnostics, ErrorCode.ERR_VarDeclIsStaticClass, typeSyntax, declType.Type); } if (isConst && !declType.Type.CanBeConst()) { Error(diagnostics, ErrorCode.ERR_BadConstType, typeSyntax, declType.Type); // Keep processing it as a non-const local. isConst = false; } } return declType; } internal BoundExpression BindInferredVariableInitializer(BindingDiagnosticBag diagnostics, RefKind refKind, EqualsValueClauseSyntax initializer, CSharpSyntaxNode errorSyntax) { BindValueKind valueKind; ExpressionSyntax value; IsInitializerRefKindValid(initializer, initializer, refKind, diagnostics, out valueKind, out value); // The return value isn't important here; we just want the diagnostics and the BindValueKind return BindInferredVariableInitializer(diagnostics, value, valueKind, errorSyntax); } // The location where the error is reported might not be the initializer. protected BoundExpression BindInferredVariableInitializer(BindingDiagnosticBag diagnostics, ExpressionSyntax initializer, BindValueKind valueKind, CSharpSyntaxNode errorSyntax) { if (initializer == null) { if (!errorSyntax.HasErrors) { Error(diagnostics, ErrorCode.ERR_ImplicitlyTypedVariableWithNoInitializer, errorSyntax); } return null; } if (initializer.Kind() == SyntaxKind.ArrayInitializerExpression) { var result = BindUnexpectedArrayInitializer((InitializerExpressionSyntax)initializer, diagnostics, ErrorCode.ERR_ImplicitlyTypedVariableAssignedArrayInitializer, errorSyntax); return CheckValue(result, valueKind, diagnostics); } BoundExpression value = BindValue(initializer, diagnostics, valueKind); BoundExpression expression = value.Kind is BoundKind.UnboundLambda or BoundKind.MethodGroup ? BindToInferredDelegateType(value, diagnostics) : BindToNaturalType(value, diagnostics); // Certain expressions (null literals, method groups and anonymous functions) have no type of // their own and therefore cannot be the initializer of an implicitly typed local. if (!expression.HasAnyErrors && !expression.HasExpressionType()) { // Cannot assign {0} to an implicitly-typed local variable Error(diagnostics, ErrorCode.ERR_ImplicitlyTypedVariableAssignedBadValue, errorSyntax, expression.Display); } return expression; } private static bool IsInitializerRefKindValid( EqualsValueClauseSyntax initializer, CSharpSyntaxNode node, RefKind variableRefKind, BindingDiagnosticBag diagnostics, out BindValueKind valueKind, out ExpressionSyntax value) { RefKind expressionRefKind = RefKind.None; value = initializer?.Value.CheckAndUnwrapRefExpression(diagnostics, out expressionRefKind); if (variableRefKind == RefKind.None) { valueKind = BindValueKind.RValue; if (expressionRefKind == RefKind.Ref) { Error(diagnostics, ErrorCode.ERR_InitializeByValueVariableWithReference, node); return false; } } else { valueKind = variableRefKind == RefKind.RefReadOnly ? BindValueKind.ReadonlyRef : BindValueKind.RefOrOut; if (initializer == null) { Error(diagnostics, ErrorCode.ERR_ByReferenceVariableMustBeInitialized, node); return false; } else if (expressionRefKind != RefKind.Ref) { Error(diagnostics, ErrorCode.ERR_InitializeByReferenceVariableWithValue, node); return false; } } return true; } protected BoundLocalDeclaration BindVariableDeclaration( LocalDeclarationKind kind, bool isVar, VariableDeclaratorSyntax declarator, TypeSyntax typeSyntax, TypeWithAnnotations declTypeOpt, AliasSymbol aliasOpt, BindingDiagnosticBag diagnostics, bool includeBoundType, CSharpSyntaxNode associatedSyntaxNode = null) { Debug.Assert(declarator != null); return BindVariableDeclaration(LocateDeclaredVariableSymbol(declarator, typeSyntax, kind), kind, isVar, declarator, typeSyntax, declTypeOpt, aliasOpt, diagnostics, includeBoundType, associatedSyntaxNode); } protected BoundLocalDeclaration BindVariableDeclaration( SourceLocalSymbol localSymbol, LocalDeclarationKind kind, bool isVar, VariableDeclaratorSyntax declarator, TypeSyntax typeSyntax, TypeWithAnnotations declTypeOpt, AliasSymbol aliasOpt, BindingDiagnosticBag diagnostics, bool includeBoundType, CSharpSyntaxNode associatedSyntaxNode = null) { Debug.Assert(declarator != null); Debug.Assert(declTypeOpt.HasType || isVar); Debug.Assert(typeSyntax != null); var localDiagnostics = BindingDiagnosticBag.GetInstance(withDiagnostics: true, diagnostics.AccumulatesDependencies); // if we are not given desired syntax, we use declarator associatedSyntaxNode = associatedSyntaxNode ?? declarator; // Check for variable declaration errors. // Use the binder that owns the scope for the local because this (the current) binder // might own nested scope. bool nameConflict = localSymbol.ScopeBinder.ValidateDeclarationNameConflictsInScope(localSymbol, diagnostics); bool hasErrors = false; if (localSymbol.RefKind != RefKind.None) { CheckRefLocalInAsyncOrIteratorMethod(localSymbol.IdentifierToken, diagnostics); } EqualsValueClauseSyntax equalsClauseSyntax = declarator.Initializer; BindValueKind valueKind; ExpressionSyntax value; if (!IsInitializerRefKindValid(equalsClauseSyntax, declarator, localSymbol.RefKind, diagnostics, out valueKind, out value)) { hasErrors = true; } BoundExpression initializerOpt; if (isVar) { aliasOpt = null; initializerOpt = BindInferredVariableInitializer(diagnostics, value, valueKind, declarator); // If we got a good result then swap the inferred type for the "var" TypeSymbol initializerType = initializerOpt?.Type; if ((object)initializerType != null) { declTypeOpt = TypeWithAnnotations.Create(initializerType); if (declTypeOpt.IsVoidType()) { Error(localDiagnostics, ErrorCode.ERR_ImplicitlyTypedVariableAssignedBadValue, declarator, declTypeOpt.Type); declTypeOpt = TypeWithAnnotations.Create(CreateErrorType("var")); hasErrors = true; } if (!declTypeOpt.Type.IsErrorType()) { if (declTypeOpt.IsStatic) { Error(localDiagnostics, ErrorCode.ERR_VarDeclIsStaticClass, typeSyntax, initializerType); hasErrors = true; } } } else { declTypeOpt = TypeWithAnnotations.Create(CreateErrorType("var")); hasErrors = true; } } else { if (ReferenceEquals(equalsClauseSyntax, null)) { initializerOpt = null; } else { // Basically inlined BindVariableInitializer, but with conversion optional. initializerOpt = BindPossibleArrayInitializer(value, declTypeOpt.Type, valueKind, diagnostics); if (kind != LocalDeclarationKind.FixedVariable) { // If this is for a fixed statement, we'll do our own conversion since there are some special cases. initializerOpt = GenerateConversionForAssignment( declTypeOpt.Type, initializerOpt, localDiagnostics, isRefAssignment: localSymbol.RefKind != RefKind.None); } } } Debug.Assert(declTypeOpt.HasType); if (kind == LocalDeclarationKind.FixedVariable) { // NOTE: this is an error, but it won't prevent further binding. if (isVar) { if (!hasErrors) { Error(localDiagnostics, ErrorCode.ERR_ImplicitlyTypedLocalCannotBeFixed, declarator); hasErrors = true; } } if (!declTypeOpt.Type.IsPointerType()) { if (!hasErrors) { Error(localDiagnostics, declTypeOpt.Type.IsFunctionPointer() ? ErrorCode.ERR_CannotUseFunctionPointerAsFixedLocal : ErrorCode.ERR_BadFixedInitType, declarator); hasErrors = true; } } else if (!IsValidFixedVariableInitializer(declTypeOpt.Type, localSymbol, ref initializerOpt, localDiagnostics)) { hasErrors = true; } } if (CheckRestrictedTypeInAsyncMethod(this.ContainingMemberOrLambda, declTypeOpt.Type, localDiagnostics, typeSyntax)) { hasErrors = true; } localSymbol.SetTypeWithAnnotations(declTypeOpt); if (initializerOpt != null) { var currentScope = LocalScopeDepth; localSymbol.SetValEscape(GetValEscape(initializerOpt, currentScope)); if (localSymbol.RefKind != RefKind.None) { localSymbol.SetRefEscape(GetRefEscape(initializerOpt, currentScope)); } } ImmutableArray<BoundExpression> arguments = BindDeclaratorArguments(declarator, localDiagnostics); if (kind == LocalDeclarationKind.FixedVariable || kind == LocalDeclarationKind.UsingVariable) { // CONSIDER: The error message is "you must provide an initializer in a fixed // CONSIDER: or using declaration". The error message could be targeted to // CONSIDER: the actual situation. "you must provide an initializer in a // CONSIDER: 'fixed' declaration." if (initializerOpt == null) { Error(localDiagnostics, ErrorCode.ERR_FixedMustInit, declarator); hasErrors = true; } } else if (kind == LocalDeclarationKind.Constant && initializerOpt != null && !localDiagnostics.HasAnyResolvedErrors()) { var constantValueDiagnostics = localSymbol.GetConstantValueDiagnostics(initializerOpt); diagnostics.AddRange(constantValueDiagnostics, allowMismatchInDependencyAccumulation: true); hasErrors = constantValueDiagnostics.Diagnostics.HasAnyErrors(); } diagnostics.AddRangeAndFree(localDiagnostics); BoundTypeExpression boundDeclType = null; if (includeBoundType) { var invalidDimensions = ArrayBuilder<BoundExpression>.GetInstance(); typeSyntax.VisitRankSpecifiers((rankSpecifier, args) => { bool _ = false; foreach (var expressionSyntax in rankSpecifier.Sizes) { var size = args.binder.BindArrayDimension(expressionSyntax, args.diagnostics, ref _); if (size != null) { args.invalidDimensions.Add(size); } } }, (binder: this, invalidDimensions: invalidDimensions, diagnostics: diagnostics)); boundDeclType = new BoundTypeExpression(typeSyntax, aliasOpt, dimensionsOpt: invalidDimensions.ToImmutableAndFree(), typeWithAnnotations: declTypeOpt); } return new BoundLocalDeclaration( syntax: associatedSyntaxNode, localSymbol: localSymbol, declaredTypeOpt: boundDeclType, initializerOpt: hasErrors ? BindToTypeForErrorRecovery(initializerOpt)?.WithHasErrors() : initializerOpt, argumentsOpt: arguments, inferredType: isVar, hasErrors: hasErrors | nameConflict); } protected bool CheckRefLocalInAsyncOrIteratorMethod(SyntaxToken identifierToken, BindingDiagnosticBag diagnostics) { if (IsInAsyncMethod()) { Error(diagnostics, ErrorCode.ERR_BadAsyncLocalType, identifierToken); return true; } else if (IsDirectlyInIterator) { Error(diagnostics, ErrorCode.ERR_BadIteratorLocalType, identifierToken); return true; } return false; } internal ImmutableArray<BoundExpression> BindDeclaratorArguments(VariableDeclaratorSyntax declarator, BindingDiagnosticBag diagnostics) { // It is possible that we have a bracketed argument list, like "int x[];" or "int x[123];" // in a non-fixed-size-array declaration . This is a common error made by C++ programmers. // We have already given a good error at parse time telling the user to either make it "fixed" // or to move the brackets to the type. However, we should still do semantic analysis of // the arguments, so that errors in them are discovered, hovering over them in the IDE // gives good results, and so on. var arguments = default(ImmutableArray<BoundExpression>); if (declarator.ArgumentList != null) { AnalyzedArguments analyzedArguments = AnalyzedArguments.GetInstance(); BindArgumentsAndNames(declarator.ArgumentList, diagnostics, analyzedArguments); arguments = BuildArgumentsForErrorRecovery(analyzedArguments); analyzedArguments.Free(); } return arguments; } private SourceLocalSymbol LocateDeclaredVariableSymbol(VariableDeclaratorSyntax declarator, TypeSyntax typeSyntax, LocalDeclarationKind outerKind) { LocalDeclarationKind kind = outerKind == LocalDeclarationKind.UsingVariable ? LocalDeclarationKind.UsingVariable : LocalDeclarationKind.RegularVariable; return LocateDeclaredVariableSymbol(declarator.Identifier, typeSyntax, declarator.Initializer, kind); } private SourceLocalSymbol LocateDeclaredVariableSymbol(SyntaxToken identifier, TypeSyntax typeSyntax, EqualsValueClauseSyntax equalsValue, LocalDeclarationKind kind) { SourceLocalSymbol localSymbol = this.LookupLocal(identifier); // In error scenarios with misplaced code, it is possible we can't bind the local declaration. // This occurs through the semantic model. In that case concoct a plausible result. if ((object)localSymbol == null) { localSymbol = SourceLocalSymbol.MakeLocal( ContainingMemberOrLambda, this, false, // do not allow ref typeSyntax, identifier, kind, equalsValue); } return localSymbol; } private bool IsValidFixedVariableInitializer(TypeSymbol declType, SourceLocalSymbol localSymbol, ref BoundExpression initializerOpt, BindingDiagnosticBag diagnostics) { Debug.Assert(!ReferenceEquals(declType, null)); Debug.Assert(declType.IsPointerType()); if (initializerOpt?.HasAnyErrors != false) { return false; } TypeSymbol initializerType = initializerOpt.Type; SyntaxNode initializerSyntax = initializerOpt.Syntax; if ((object)initializerType == null) { Error(diagnostics, ErrorCode.ERR_ExprCannotBeFixed, initializerSyntax); return false; } TypeSymbol elementType; bool hasErrors = false; MethodSymbol fixedPatternMethod = null; switch (initializerOpt.Kind) { case BoundKind.AddressOfOperator: elementType = ((BoundAddressOfOperator)initializerOpt).Operand.Type; break; case BoundKind.FieldAccess: var fa = (BoundFieldAccess)initializerOpt; if (fa.FieldSymbol.IsFixedSizeBuffer) { elementType = ((PointerTypeSymbol)fa.Type).PointedAtType; break; } goto default; default: // fixed (T* variable = <expr>) ... // check for arrays if (initializerType.IsArray()) { // See ExpressionBinder::BindPtrToArray (though most of that functionality is now in LocalRewriter). elementType = ((ArrayTypeSymbol)initializerType).ElementType; break; } // check for a special ref-returning method var additionalDiagnostics = BindingDiagnosticBag.GetInstance(diagnostics); fixedPatternMethod = GetFixedPatternMethodOpt(initializerOpt, additionalDiagnostics); // check for String // NOTE: We will allow the pattern method to take precedence, but only if it is an instance member of System.String if (initializerType.SpecialType == SpecialType.System_String && ((object)fixedPatternMethod == null || fixedPatternMethod.ContainingType.SpecialType != SpecialType.System_String)) { fixedPatternMethod = null; elementType = this.GetSpecialType(SpecialType.System_Char, diagnostics, initializerSyntax); additionalDiagnostics.Free(); break; } // if the feature was enabled, but something went wrong with the method, report that, otherwise don't. // If feature is not enabled, additional errors would be just noise. bool extensibleFixedEnabled = ((CSharpParseOptions)initializerOpt.SyntaxTree.Options)?.IsFeatureEnabled(MessageID.IDS_FeatureExtensibleFixedStatement) != false; if (extensibleFixedEnabled) { diagnostics.AddRange(additionalDiagnostics); } additionalDiagnostics.Free(); if ((object)fixedPatternMethod != null) { elementType = fixedPatternMethod.ReturnType; CheckFeatureAvailability(initializerOpt.Syntax, MessageID.IDS_FeatureExtensibleFixedStatement, diagnostics); break; } else { Error(diagnostics, ErrorCode.ERR_ExprCannotBeFixed, initializerSyntax); return false; } } if (CheckManagedAddr(Compilation, elementType, initializerSyntax.Location, diagnostics)) { hasErrors = true; } initializerOpt = BindToNaturalType(initializerOpt, diagnostics, reportNoTargetType: false); initializerOpt = GetFixedLocalCollectionInitializer(initializerOpt, elementType, declType, fixedPatternMethod, hasErrors, diagnostics); return true; } private MethodSymbol GetFixedPatternMethodOpt(BoundExpression initializer, BindingDiagnosticBag additionalDiagnostics) { if (initializer.Type.IsVoidType()) { return null; } const string methodName = "GetPinnableReference"; var result = PerformPatternMethodLookup(initializer, methodName, initializer.Syntax, additionalDiagnostics, out var patternMethodSymbol); if (patternMethodSymbol is null) { return null; } if (HasOptionalOrVariableParameters(patternMethodSymbol) || patternMethodSymbol.ReturnsVoid || !patternMethodSymbol.RefKind.IsManagedReference() || !(patternMethodSymbol.ParameterCount == 0 || patternMethodSymbol.IsStatic && patternMethodSymbol.ParameterCount == 1)) { // the method does not fit the pattern additionalDiagnostics.Add(ErrorCode.WRN_PatternBadSignature, initializer.Syntax.Location, initializer.Type, "fixed", patternMethodSymbol); return null; } return patternMethodSymbol; } /// <summary> /// Wrap the initializer in a BoundFixedLocalCollectionInitializer so that the rewriter will have the /// information it needs (e.g. conversions, helper methods). /// </summary> private BoundExpression GetFixedLocalCollectionInitializer( BoundExpression initializer, TypeSymbol elementType, TypeSymbol declType, MethodSymbol patternMethodOpt, bool hasErrors, BindingDiagnosticBag diagnostics) { Debug.Assert(initializer != null); SyntaxNode initializerSyntax = initializer.Syntax; TypeSymbol pointerType = new PointerTypeSymbol(TypeWithAnnotations.Create(elementType)); CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); Conversion elementConversion = this.Conversions.ClassifyConversionFromType(pointerType, declType, ref useSiteInfo); diagnostics.Add(initializerSyntax, useSiteInfo); if (!elementConversion.IsValid || !elementConversion.IsImplicit) { GenerateImplicitConversionError(diagnostics, this.Compilation, initializerSyntax, elementConversion, pointerType, declType); hasErrors = true; } return new BoundFixedLocalCollectionInitializer( initializerSyntax, pointerType, elementConversion, initializer, patternMethodOpt, declType, hasErrors); } private BoundExpression BindAssignment(AssignmentExpressionSyntax node, BindingDiagnosticBag diagnostics) { Debug.Assert(node != null); Debug.Assert(node.Left != null); Debug.Assert(node.Right != null); node.Left.CheckDeconstructionCompatibleArgument(diagnostics); if (node.Left.Kind() == SyntaxKind.TupleExpression || node.Left.Kind() == SyntaxKind.DeclarationExpression) { return BindDeconstruction(node, diagnostics); } BindValueKind lhsKind; BindValueKind rhsKind; ExpressionSyntax rhsExpr; bool isRef = false; if (node.Right.Kind() == SyntaxKind.RefExpression) { isRef = true; lhsKind = BindValueKind.RefAssignable; rhsKind = BindValueKind.RefersToLocation; rhsExpr = ((RefExpressionSyntax)node.Right).Expression; } else { lhsKind = BindValueKind.Assignable; rhsKind = BindValueKind.RValue; rhsExpr = node.Right; } var op1 = BindValue(node.Left, diagnostics, lhsKind); ReportSuppressionIfNeeded(op1, diagnostics); var lhsRefKind = RefKind.None; // If the LHS is a ref (not ref-readonly), the rhs // must also be value-assignable if (lhsKind == BindValueKind.RefAssignable && !op1.HasErrors) { // We should now know that op1 is a valid lvalue lhsRefKind = op1.GetRefKind(); if (lhsRefKind == RefKind.Ref || lhsRefKind == RefKind.Out) { rhsKind |= BindValueKind.Assignable; } } var op2 = BindValue(rhsExpr, diagnostics, rhsKind); if (op1.Kind == BoundKind.DiscardExpression) { op2 = BindToNaturalType(op2, diagnostics); op1 = InferTypeForDiscardAssignment((BoundDiscardExpression)op1, op2, diagnostics); } return BindAssignment(node, op1, op2, isRef, diagnostics); } private BoundExpression InferTypeForDiscardAssignment(BoundDiscardExpression op1, BoundExpression op2, BindingDiagnosticBag diagnostics) { var inferredType = op2.Type; if ((object)inferredType == null) { return op1.FailInference(this, diagnostics); } if (inferredType.IsVoidType()) { diagnostics.Add(ErrorCode.ERR_VoidAssignment, op1.Syntax.Location); } return op1.SetInferredTypeWithAnnotations(TypeWithAnnotations.Create(inferredType)); } private BoundAssignmentOperator BindAssignment( SyntaxNode node, BoundExpression op1, BoundExpression op2, bool isRef, BindingDiagnosticBag diagnostics) { Debug.Assert(op1 != null); Debug.Assert(op2 != null); bool hasErrors = op1.HasAnyErrors || op2.HasAnyErrors; if (!op1.HasAnyErrors) { // Build bound conversion. The node might not be used if this is a dynamic conversion // but diagnostics should be reported anyways. var conversion = GenerateConversionForAssignment(op1.Type, op2, diagnostics, isRefAssignment: isRef); // If the result is a dynamic assignment operation (SetMember or SetIndex), // don't generate the boxing conversion to the dynamic type. // Leave the values as they are, and deal with the conversions at runtime. if (op1.Kind != BoundKind.DynamicIndexerAccess && op1.Kind != BoundKind.DynamicMemberAccess && op1.Kind != BoundKind.DynamicObjectInitializerMember) { op2 = conversion; } else { op2 = BindToNaturalType(op2, diagnostics); } if (isRef) { var leftEscape = GetRefEscape(op1, LocalScopeDepth); var rightEscape = GetRefEscape(op2, LocalScopeDepth); if (leftEscape < rightEscape) { Error(diagnostics, ErrorCode.ERR_RefAssignNarrower, node, op1.ExpressionSymbol.Name, op2.Syntax); op2 = ToBadExpression(op2); } } if (op1.Type.IsRefLikeType) { var leftEscape = GetValEscape(op1, LocalScopeDepth); op2 = ValidateEscape(op2, leftEscape, isByRef: false, diagnostics); } } else { op2 = BindToTypeForErrorRecovery(op2); } TypeSymbol type; if ((op1.Kind == BoundKind.EventAccess) && ((BoundEventAccess)op1).EventSymbol.IsWindowsRuntimeEvent) { // Event assignment is a call to void WindowsRuntimeMarshal.AddEventHandler<T>(). type = this.GetSpecialType(SpecialType.System_Void, diagnostics, node); } else { type = op1.Type; } return new BoundAssignmentOperator(node, op1, op2, isRef, type, hasErrors); } private static PropertySymbol GetPropertySymbol(BoundExpression expr, out BoundExpression receiver, out SyntaxNode propertySyntax) { PropertySymbol propertySymbol; switch (expr.Kind) { case BoundKind.PropertyAccess: { var propertyAccess = (BoundPropertyAccess)expr; receiver = propertyAccess.ReceiverOpt; propertySymbol = propertyAccess.PropertySymbol; } break; case BoundKind.IndexerAccess: { var indexerAccess = (BoundIndexerAccess)expr; receiver = indexerAccess.ReceiverOpt; propertySymbol = indexerAccess.Indexer; } break; case BoundKind.IndexOrRangePatternIndexerAccess: { var patternIndexer = (BoundIndexOrRangePatternIndexerAccess)expr; receiver = patternIndexer.Receiver; propertySymbol = (PropertySymbol)patternIndexer.PatternSymbol; } break; default: receiver = null; propertySymbol = null; propertySyntax = null; return null; } var syntax = expr.Syntax; switch (syntax.Kind()) { case SyntaxKind.SimpleMemberAccessExpression: case SyntaxKind.PointerMemberAccessExpression: propertySyntax = ((MemberAccessExpressionSyntax)syntax).Name; break; case SyntaxKind.IdentifierName: propertySyntax = syntax; break; case SyntaxKind.ElementAccessExpression: propertySyntax = ((ElementAccessExpressionSyntax)syntax).ArgumentList; break; default: // Other syntax types, such as QualifiedName, // might occur in invalid code. propertySyntax = syntax; break; } return propertySymbol; } private static SyntaxNode GetEventName(BoundEventAccess expr) { SyntaxNode syntax = expr.Syntax; switch (syntax.Kind()) { case SyntaxKind.SimpleMemberAccessExpression: case SyntaxKind.PointerMemberAccessExpression: return ((MemberAccessExpressionSyntax)syntax).Name; case SyntaxKind.QualifiedName: // This case is reachable only through SemanticModel return ((QualifiedNameSyntax)syntax).Right; case SyntaxKind.IdentifierName: return syntax; case SyntaxKind.MemberBindingExpression: return ((MemberBindingExpressionSyntax)syntax).Name; default: throw ExceptionUtilities.UnexpectedValue(syntax.Kind()); } } /// <summary> /// There are two BadEventUsage error codes and this method decides which one should /// be used for a given event. /// </summary> private DiagnosticInfo GetBadEventUsageDiagnosticInfo(EventSymbol eventSymbol) { var leastOverridden = (EventSymbol)eventSymbol.GetLeastOverriddenMember(this.ContainingType); return leastOverridden.HasAssociatedField ? new CSDiagnosticInfo(ErrorCode.ERR_BadEventUsage, leastOverridden, leastOverridden.ContainingType) : new CSDiagnosticInfo(ErrorCode.ERR_BadEventUsageNoField, leastOverridden); } internal static bool AccessingAutoPropertyFromConstructor(BoundPropertyAccess propertyAccess, Symbol fromMember) { return AccessingAutoPropertyFromConstructor(propertyAccess.ReceiverOpt, propertyAccess.PropertySymbol, fromMember); } private static bool AccessingAutoPropertyFromConstructor(BoundExpression receiver, PropertySymbol propertySymbol, Symbol fromMember) { if (!propertySymbol.IsDefinition && propertySymbol.ContainingType.Equals(propertySymbol.ContainingType.OriginalDefinition, TypeCompareKind.IgnoreNullableModifiersForReferenceTypes)) { propertySymbol = propertySymbol.OriginalDefinition; } var sourceProperty = propertySymbol as SourcePropertySymbolBase; var propertyIsStatic = propertySymbol.IsStatic; return (object)sourceProperty != null && sourceProperty.IsAutoPropertyWithGetAccessor && TypeSymbol.Equals(sourceProperty.ContainingType, fromMember.ContainingType, TypeCompareKind.ConsiderEverything2) && IsConstructorOrField(fromMember, isStatic: propertyIsStatic) && (propertyIsStatic || receiver.Kind == BoundKind.ThisReference); } private static bool IsConstructorOrField(Symbol member, bool isStatic) { return (member as MethodSymbol)?.MethodKind == (isStatic ? MethodKind.StaticConstructor : MethodKind.Constructor) || (member as FieldSymbol)?.IsStatic == isStatic; } private TypeSymbol GetAccessThroughType(BoundExpression receiver) { if (receiver == null) { return this.ContainingType; } else if (receiver.Kind == BoundKind.BaseReference) { // Allow protected access to members defined // in base classes. See spec section 3.5.3. return null; } else { Debug.Assert((object)receiver.Type != null); return receiver.Type; } } private BoundExpression BindPossibleArrayInitializer( ExpressionSyntax node, TypeSymbol destinationType, BindValueKind valueKind, BindingDiagnosticBag diagnostics) { Debug.Assert(node != null); if (node.Kind() != SyntaxKind.ArrayInitializerExpression) { return BindValue(node, diagnostics, valueKind); } BoundExpression result; if (destinationType.Kind == SymbolKind.ArrayType) { result = BindArrayCreationWithInitializer(diagnostics, null, (InitializerExpressionSyntax)node, (ArrayTypeSymbol)destinationType, ImmutableArray<BoundExpression>.Empty); } else { result = BindUnexpectedArrayInitializer((InitializerExpressionSyntax)node, diagnostics, ErrorCode.ERR_ArrayInitToNonArrayType); } return CheckValue(result, valueKind, diagnostics); } protected virtual SourceLocalSymbol LookupLocal(SyntaxToken nameToken) { return Next.LookupLocal(nameToken); } protected virtual LocalFunctionSymbol LookupLocalFunction(SyntaxToken nameToken) { return Next.LookupLocalFunction(nameToken); } /// <summary> /// Returns a value that tells how many local scopes are visible, including the current. /// I.E. outside of any method will be 0 /// immediately inside a method - 1 /// </summary> internal virtual uint LocalScopeDepth => Next.LocalScopeDepth; internal virtual BoundBlock BindEmbeddedBlock(BlockSyntax node, BindingDiagnosticBag diagnostics) { return BindBlock(node, diagnostics); } private BoundBlock BindBlock(BlockSyntax node, BindingDiagnosticBag diagnostics) { if (node.AttributeLists.Count > 0) { Error(diagnostics, ErrorCode.ERR_AttributesNotAllowed, node.AttributeLists[0]); } var binder = GetBinder(node); Debug.Assert(binder != null); return binder.BindBlockParts(node, diagnostics); } private BoundBlock BindBlockParts(BlockSyntax node, BindingDiagnosticBag diagnostics) { var syntaxStatements = node.Statements; int nStatements = syntaxStatements.Count; ArrayBuilder<BoundStatement> boundStatements = ArrayBuilder<BoundStatement>.GetInstance(nStatements); for (int i = 0; i < nStatements; i++) { var boundStatement = BindStatement(syntaxStatements[i], diagnostics); boundStatements.Add(boundStatement); } return FinishBindBlockParts(node, boundStatements.ToImmutableAndFree(), diagnostics); } private BoundBlock FinishBindBlockParts(CSharpSyntaxNode node, ImmutableArray<BoundStatement> boundStatements, BindingDiagnosticBag diagnostics) { ImmutableArray<LocalSymbol> locals = GetDeclaredLocalsForScope(node); if (IsDirectlyInIterator) { var method = ContainingMemberOrLambda as MethodSymbol; if ((object)method != null) { method.IteratorElementTypeWithAnnotations = GetIteratorElementType(); } else { Debug.Assert(diagnostics.DiagnosticBag is null || !diagnostics.DiagnosticBag.IsEmptyWithoutResolution); } } return new BoundBlock( node, locals, GetDeclaredLocalFunctionsForScope(node), boundStatements); } internal BoundExpression GenerateConversionForAssignment(TypeSymbol targetType, BoundExpression expression, BindingDiagnosticBag diagnostics, bool isDefaultParameter = false, bool isRefAssignment = false) { Debug.Assert((object)targetType != null); Debug.Assert(expression != null); // We wish to avoid "cascading" errors, so if the expression we are // attempting to convert to a type had errors, suppress additional // diagnostics. However, if the expression // with errors is an unbound lambda then the errors are almost certainly // syntax errors. For error recovery analysis purposes we wish to bind // error lambdas like "Action<int> f = x=>{ x. };" because IntelliSense // needs to know that x is of type int. if (expression.HasAnyErrors && expression.Kind != BoundKind.UnboundLambda) { diagnostics = BindingDiagnosticBag.Discarded; } CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); var conversion = this.Conversions.ClassifyConversionFromExpression(expression, targetType, ref useSiteInfo); diagnostics.Add(expression.Syntax, useSiteInfo); if (isRefAssignment) { if (conversion.Kind != ConversionKind.Identity) { Error(diagnostics, ErrorCode.ERR_RefAssignmentMustHaveIdentityConversion, expression.Syntax, targetType); } else { return expression; } } else if (!conversion.IsImplicit || !conversion.IsValid) { // We suppress conversion errors on default parameters; eg, // if someone says "void M(string s = 123) {}". We will report // a special error in the default parameter binder. if (!isDefaultParameter) { GenerateImplicitConversionError(diagnostics, expression.Syntax, conversion, expression, targetType); } // Suppress any additional diagnostics diagnostics = BindingDiagnosticBag.Discarded; } return CreateConversion(expression.Syntax, expression, conversion, isCast: false, conversionGroupOpt: null, targetType, diagnostics); } #nullable enable internal void GenerateAnonymousFunctionConversionError(BindingDiagnosticBag diagnostics, SyntaxNode syntax, UnboundLambda anonymousFunction, TypeSymbol targetType) { Debug.Assert((object)targetType != null); Debug.Assert(anonymousFunction != null); // Is the target type simply bad? // If the target type is an error then we've already reported a diagnostic. Don't bother // reporting the conversion error. if (targetType.IsErrorType()) { return; } // CONSIDER: Instead of computing this again, cache the reason why the conversion failed in // CONSIDER: the Conversion result, and simply report that. var reason = Conversions.IsAnonymousFunctionCompatibleWithType(anonymousFunction, targetType); // It is possible that the conversion from lambda to delegate is just fine, and // that we ended up here because the target type, though itself is not an error // type, contains a type argument which is an error type. For example, converting // (Goo goo)=>{} to Action<Goo> is a perfectly legal conversion even if Goo is undefined! // In that case we have already reported an error that Goo is undefined, so just bail out. if (reason == LambdaConversionResult.Success) { return; } var id = anonymousFunction.MessageID.Localize(); if (reason == LambdaConversionResult.BadTargetType) { if (ReportDelegateInvokeUseSiteDiagnostic(diagnostics, targetType, node: syntax)) { return; } // Cannot convert {0} to type '{1}' because it is not a delegate type Error(diagnostics, ErrorCode.ERR_AnonMethToNonDel, syntax, id, targetType); return; } if (reason == LambdaConversionResult.ExpressionTreeMustHaveDelegateTypeArgument) { Debug.Assert(targetType.IsExpressionTree()); Error(diagnostics, ErrorCode.ERR_ExpressionTreeMustHaveDelegate, syntax, ((NamedTypeSymbol)targetType).TypeArgumentsWithAnnotationsNoUseSiteDiagnostics[0].Type); return; } if (reason == LambdaConversionResult.ExpressionTreeFromAnonymousMethod) { Debug.Assert(targetType.IsGenericOrNonGenericExpressionType(out _)); Error(diagnostics, ErrorCode.ERR_AnonymousMethodToExpressionTree, syntax); return; } if (reason == LambdaConversionResult.MismatchedReturnType) { Error(diagnostics, ErrorCode.ERR_CantConvAnonMethReturnType, syntax, id, targetType); return; } // At this point we know that we have either a delegate type or an expression type for the target. // The target type is a valid delegate or expression tree type. Is there something wrong with the // parameter list? // First off, is there a parameter list at all? if (reason == LambdaConversionResult.MissingSignatureWithOutParameter) { // COMPATIBILITY: The C# 4 compiler produces two errors for: // // delegate void D (out int x); // ... // D d = delegate {}; // // error CS1676: Parameter 1 must be declared with the 'out' keyword // error CS1688: Cannot convert anonymous method block without a parameter list // to delegate type 'D' because it has one or more out parameters // // This seems redundant, (because there is no "parameter 1" in the source code) // and unnecessary. I propose that we eliminate the first error. Error(diagnostics, ErrorCode.ERR_CantConvAnonMethNoParams, syntax, targetType); return; } var delegateType = targetType.GetDelegateType(); Debug.Assert(delegateType is not null); // There is a parameter list. Does it have the right number of elements? if (reason == LambdaConversionResult.BadParameterCount) { // Delegate '{0}' does not take {1} arguments Error(diagnostics, ErrorCode.ERR_BadDelArgCount, syntax, delegateType, anonymousFunction.ParameterCount); return; } // The parameter list exists and had the right number of parameters. Were any of its types bad? // If any parameter type of the lambda is an error type then suppress // further errors. We've already reported errors on the bad type. if (anonymousFunction.HasExplicitlyTypedParameterList) { for (int i = 0; i < anonymousFunction.ParameterCount; ++i) { if (anonymousFunction.ParameterType(i).IsErrorType()) { return; } } } // The parameter list exists and had the right number of parameters. Were any of its types // mismatched with the delegate parameter types? // The simplest possible case is (x, y, z)=>whatever where the target type has a ref or out parameter. var delegateParameters = delegateType.DelegateParameters(); if (reason == LambdaConversionResult.RefInImplicitlyTypedLambda) { for (int i = 0; i < anonymousFunction.ParameterCount; ++i) { var delegateRefKind = delegateParameters[i].RefKind; if (delegateRefKind != RefKind.None) { // Parameter {0} must be declared with the '{1}' keyword Error(diagnostics, ErrorCode.ERR_BadParamRef, anonymousFunction.ParameterLocation(i), i + 1, delegateRefKind.ToParameterDisplayString()); } } return; } // See the comments in IsAnonymousFunctionCompatibleWithDelegate for an explanation of this one. if (reason == LambdaConversionResult.StaticTypeInImplicitlyTypedLambda) { for (int i = 0; i < anonymousFunction.ParameterCount; ++i) { if (delegateParameters[i].TypeWithAnnotations.IsStatic) { // {0}: Static types cannot be used as parameter Error(diagnostics, ErrorFacts.GetStaticClassParameterCode(useWarning: false), anonymousFunction.ParameterLocation(i), delegateParameters[i].Type); } } return; } // Otherwise, there might be a more complex reason why the parameter types are mismatched. if (reason == LambdaConversionResult.MismatchedParameterType) { // Cannot convert {0} to type '{1}' because the parameter types do not match the delegate parameter types Error(diagnostics, ErrorCode.ERR_CantConvAnonMethParams, syntax, id, targetType); Debug.Assert(anonymousFunction.ParameterCount == delegateParameters.Length); for (int i = 0; i < anonymousFunction.ParameterCount; ++i) { var lambdaParameterType = anonymousFunction.ParameterType(i); if (lambdaParameterType.IsErrorType()) { continue; } var lambdaParameterLocation = anonymousFunction.ParameterLocation(i); var lambdaRefKind = anonymousFunction.RefKind(i); var delegateParameterType = delegateParameters[i].Type; var delegateRefKind = delegateParameters[i].RefKind; if (!lambdaParameterType.Equals(delegateParameterType, TypeCompareKind.AllIgnoreOptions)) { SymbolDistinguisher distinguisher = new SymbolDistinguisher(this.Compilation, lambdaParameterType, delegateParameterType); // Parameter {0} is declared as type '{1}{2}' but should be '{3}{4}' Error(diagnostics, ErrorCode.ERR_BadParamType, lambdaParameterLocation, i + 1, lambdaRefKind.ToParameterPrefix(), distinguisher.First, delegateRefKind.ToParameterPrefix(), distinguisher.Second); } else if (lambdaRefKind != delegateRefKind) { if (delegateRefKind == RefKind.None) { // Parameter {0} should not be declared with the '{1}' keyword Error(diagnostics, ErrorCode.ERR_BadParamExtraRef, lambdaParameterLocation, i + 1, lambdaRefKind.ToParameterDisplayString()); } else { // Parameter {0} must be declared with the '{1}' keyword Error(diagnostics, ErrorCode.ERR_BadParamRef, lambdaParameterLocation, i + 1, delegateRefKind.ToParameterDisplayString()); } } } return; } if (reason == LambdaConversionResult.BindingFailed) { var bindingResult = anonymousFunction.Bind(delegateType, isExpressionTree: false); Debug.Assert(ErrorFacts.PreventsSuccessfulDelegateConversion(bindingResult.Diagnostics.Diagnostics)); diagnostics.AddRange(bindingResult.Diagnostics); return; } // UNDONE: LambdaConversionResult.VoidExpressionLambdaMustBeStatementExpression: Debug.Assert(false, "Missing case in lambda conversion error reporting"); diagnostics.Add(ErrorCode.ERR_InternalError, syntax.Location); } #nullable disable protected static void GenerateImplicitConversionError(BindingDiagnosticBag diagnostics, CSharpCompilation compilation, SyntaxNode syntax, Conversion conversion, TypeSymbol sourceType, TypeSymbol targetType, ConstantValue sourceConstantValueOpt = null) { Debug.Assert(!conversion.IsImplicit || !conversion.IsValid); // If the either type is an error then an error has already been reported // for some aspect of the analysis of this expression. (For example, something like // "garbage g = null; short s = g;" -- we don't want to report that g is not // convertible to short because we've already reported that g does not have a good type. if (!sourceType.IsErrorType() && !targetType.IsErrorType()) { if (conversion.IsExplicit) { if (sourceType.SpecialType == SpecialType.System_Double && syntax.Kind() == SyntaxKind.NumericLiteralExpression && (targetType.SpecialType == SpecialType.System_Single || targetType.SpecialType == SpecialType.System_Decimal)) { Error(diagnostics, ErrorCode.ERR_LiteralDoubleCast, syntax, (targetType.SpecialType == SpecialType.System_Single) ? "F" : "M", targetType); } else if (conversion.Kind == ConversionKind.ExplicitNumeric && sourceConstantValueOpt != null && sourceConstantValueOpt != ConstantValue.Bad && ConversionsBase.HasImplicitConstantExpressionConversion(new BoundLiteral(syntax, ConstantValue.Bad, sourceType), targetType)) { // CLEVERNESS: By passing ConstantValue.Bad, we tell HasImplicitConstantExpressionConversion to ignore the constant // value and only consider the types. // If there would be an implicit constant conversion for a different constant of the same type // (i.e. one that's not out of range), then it's more helpful to report the range check failure // than to suggest inserting a cast. Error(diagnostics, ErrorCode.ERR_ConstOutOfRange, syntax, sourceConstantValueOpt.Value, targetType); } else { SymbolDistinguisher distinguisher = new SymbolDistinguisher(compilation, sourceType, targetType); Error(diagnostics, ErrorCode.ERR_NoImplicitConvCast, syntax, distinguisher.First, distinguisher.Second); } } else if (conversion.ResultKind == LookupResultKind.OverloadResolutionFailure) { Debug.Assert(conversion.IsUserDefined); ImmutableArray<MethodSymbol> originalUserDefinedConversions = conversion.OriginalUserDefinedConversions; if (originalUserDefinedConversions.Length > 1) { Error(diagnostics, ErrorCode.ERR_AmbigUDConv, syntax, originalUserDefinedConversions[0], originalUserDefinedConversions[1], sourceType, targetType); } else { Debug.Assert(originalUserDefinedConversions.Length == 0, "How can there be exactly one applicable user-defined conversion if the conversion doesn't exist?"); SymbolDistinguisher distinguisher = new SymbolDistinguisher(compilation, sourceType, targetType); Error(diagnostics, ErrorCode.ERR_NoImplicitConv, syntax, distinguisher.First, distinguisher.Second); } } else if (TypeSymbol.Equals(sourceType, targetType, TypeCompareKind.ConsiderEverything2)) { // This occurs for `void`, which cannot even convert to itself. Since SymbolDistinguisher // requires two distinct types, we preempt its use here. The diagnostic is strange, but correct. // Though this diagnostic tends to be a cascaded one, we cannot suppress it until // we have proven that it is always so. Error(diagnostics, ErrorCode.ERR_NoImplicitConv, syntax, sourceType, targetType); } else { SymbolDistinguisher distinguisher = new SymbolDistinguisher(compilation, sourceType, targetType); Error(diagnostics, ErrorCode.ERR_NoImplicitConv, syntax, distinguisher.First, distinguisher.Second); } } } protected void GenerateImplicitConversionError( BindingDiagnosticBag diagnostics, SyntaxNode syntax, Conversion conversion, BoundExpression operand, TypeSymbol targetType) { Debug.Assert(operand != null); Debug.Assert((object)targetType != null); if (targetType.TypeKind == TypeKind.Error) { return; } if (targetType.IsVoidType()) { Error(diagnostics, ErrorCode.ERR_NoImplicitConv, syntax, operand.Display, targetType); return; } switch (operand.Kind) { case BoundKind.BadExpression: { return; } case BoundKind.UnboundLambda: { GenerateAnonymousFunctionConversionError(diagnostics, syntax, (UnboundLambda)operand, targetType); return; } case BoundKind.TupleLiteral: { var tuple = (BoundTupleLiteral)operand; var targetElementTypes = default(ImmutableArray<TypeWithAnnotations>); // If target is a tuple or compatible type with the same number of elements, // report errors for tuple arguments that failed to convert, which would be more useful. if (targetType.TryGetElementTypesWithAnnotationsIfTupleType(out targetElementTypes) && targetElementTypes.Length == tuple.Arguments.Length) { GenerateImplicitConversionErrorsForTupleLiteralArguments(diagnostics, tuple.Arguments, targetElementTypes); return; } // target is not compatible with source and source does not have a type if ((object)tuple.Type == null) { Error(diagnostics, ErrorCode.ERR_ConversionNotTupleCompatible, syntax, tuple.Arguments.Length, targetType); return; } // Otherwise it is just a regular conversion failure from T1 to T2. break; } case BoundKind.MethodGroup: { reportMethodGroupErrors((BoundMethodGroup)operand, fromAddressOf: false); return; } case BoundKind.UnconvertedAddressOfOperator: { reportMethodGroupErrors(((BoundUnconvertedAddressOfOperator)operand).Operand, fromAddressOf: true); return; } case BoundKind.Literal: { if (operand.IsLiteralNull()) { if (targetType.TypeKind == TypeKind.TypeParameter) { Error(diagnostics, ErrorCode.ERR_TypeVarCantBeNull, syntax, targetType); return; } if (targetType.IsValueType) { Error(diagnostics, ErrorCode.ERR_ValueCantBeNull, syntax, targetType); return; } } break; } case BoundKind.StackAllocArrayCreation: { var stackAllocExpression = (BoundStackAllocArrayCreation)operand; Error(diagnostics, ErrorCode.ERR_StackAllocConversionNotPossible, syntax, stackAllocExpression.ElementType, targetType); return; } case BoundKind.UnconvertedSwitchExpression: { var switchExpression = (BoundUnconvertedSwitchExpression)operand; var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; bool reportedError = false; foreach (var arm in switchExpression.SwitchArms) { tryConversion(arm.Value, ref reportedError, ref discardedUseSiteInfo); } Debug.Assert(reportedError); return; } case BoundKind.AddressOfOperator when targetType.IsFunctionPointer(): { Error(diagnostics, ErrorCode.ERR_InvalidAddrOp, ((BoundAddressOfOperator)operand).Operand.Syntax); return; } case BoundKind.UnconvertedConditionalOperator: { var conditionalOperator = (BoundUnconvertedConditionalOperator)operand; var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; bool reportedError = false; tryConversion(conditionalOperator.Consequence, ref reportedError, ref discardedUseSiteInfo); tryConversion(conditionalOperator.Alternative, ref reportedError, ref discardedUseSiteInfo); Debug.Assert(reportedError); return; } void tryConversion(BoundExpression expr, ref bool reportedError, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { var conversion = this.Conversions.ClassifyImplicitConversionFromExpression(expr, targetType, ref useSiteInfo); if (!conversion.IsImplicit || !conversion.IsValid) { GenerateImplicitConversionError(diagnostics, expr.Syntax, conversion, expr, targetType); reportedError = true; } } } var sourceType = operand.Type; if ((object)sourceType != null) { GenerateImplicitConversionError(diagnostics, this.Compilation, syntax, conversion, sourceType, targetType, operand.ConstantValue); return; } Debug.Assert(operand.HasAnyErrors && operand.Kind != BoundKind.UnboundLambda, "Missing a case in implicit conversion error reporting"); void reportMethodGroupErrors(BoundMethodGroup methodGroup, bool fromAddressOf) { if (!Conversions.ReportDelegateOrFunctionPointerMethodGroupDiagnostics(this, methodGroup, targetType, diagnostics)) { var nodeForError = syntax; while (nodeForError.Kind() == SyntaxKind.ParenthesizedExpression) { nodeForError = ((ParenthesizedExpressionSyntax)nodeForError).Expression; } if (nodeForError.Kind() == SyntaxKind.SimpleMemberAccessExpression || nodeForError.Kind() == SyntaxKind.PointerMemberAccessExpression) { nodeForError = ((MemberAccessExpressionSyntax)nodeForError).Name; } var location = nodeForError.Location; if (ReportDelegateInvokeUseSiteDiagnostic(diagnostics, targetType, location)) { return; } ErrorCode errorCode; switch (targetType.TypeKind) { case TypeKind.FunctionPointer when fromAddressOf: errorCode = ErrorCode.ERR_MethFuncPtrMismatch; break; case TypeKind.FunctionPointer: Error(diagnostics, ErrorCode.ERR_MissingAddressOf, location); return; case TypeKind.Delegate when fromAddressOf: errorCode = ErrorCode.ERR_CannotConvertAddressOfToDelegate; break; case TypeKind.Delegate: errorCode = ErrorCode.ERR_MethDelegateMismatch; break; default: if (fromAddressOf) { errorCode = ErrorCode.ERR_AddressOfToNonFunctionPointer; } else if (targetType.SpecialType == SpecialType.System_Delegate && syntax.IsFeatureEnabled(MessageID.IDS_FeatureInferredDelegateType)) { Error(diagnostics, ErrorCode.ERR_CannotInferDelegateType, location); return; } else { errorCode = ErrorCode.ERR_MethGrpToNonDel; } break; } Error(diagnostics, errorCode, location, methodGroup.Name, targetType); } } } private void GenerateImplicitConversionErrorsForTupleLiteralArguments( BindingDiagnosticBag diagnostics, ImmutableArray<BoundExpression> tupleArguments, ImmutableArray<TypeWithAnnotations> targetElementTypes) { var argLength = tupleArguments.Length; // report all leaf elements of the tuple literal that failed to convert // NOTE: we are not responsible for reporting use site errors here, just the failed leaf conversions. // By the time we get here we have done analysis and know we have failed the cast in general, and diagnostics collected in the process is already in the bag. // The only thing left is to form a diagnostics about the actually failing conversion(s). // This whole method does not itself collect any usesite diagnostics. Its only purpose is to produce an error better than "conversion failed here" var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; for (int i = 0; i < targetElementTypes.Length; i++) { var argument = tupleArguments[i]; var targetElementType = targetElementTypes[i].Type; var elementConversion = Conversions.ClassifyImplicitConversionFromExpression(argument, targetElementType, ref discardedUseSiteInfo); if (!elementConversion.IsValid) { GenerateImplicitConversionError(diagnostics, argument.Syntax, elementConversion, argument, targetElementType); } } } private BoundStatement BindIfStatement(IfStatementSyntax node, BindingDiagnosticBag diagnostics) { var condition = BindBooleanExpression(node.Condition, diagnostics); var consequence = BindPossibleEmbeddedStatement(node.Statement, diagnostics); BoundStatement alternative = (node.Else == null) ? null : BindPossibleEmbeddedStatement(node.Else.Statement, diagnostics); BoundStatement result = new BoundIfStatement(node, condition, consequence, alternative); return result; } internal BoundExpression BindBooleanExpression(ExpressionSyntax node, BindingDiagnosticBag diagnostics) { // SPEC: // A boolean-expression is an expression that yields a result of type bool; // either directly or through application of operator true in certain // contexts as specified in the following. // // The controlling conditional expression of an if-statement, while-statement, // do-statement, or for-statement is a boolean-expression. The controlling // conditional expression of the ?: operator follows the same rules as a // boolean-expression, but for reasons of operator precedence is classified // as a conditional-or-expression. // // A boolean-expression is required to be implicitly convertible to bool // or of a type that implements operator true. If neither requirement // is satisfied, a binding-time error occurs. // // When a boolean expression cannot be implicitly converted to bool but does // implement operator true, then following evaluation of the expression, // the operator true implementation provided by that type is invoked // to produce a bool value. // // SPEC ERROR: The third paragraph above is obviously not correct; we need // SPEC ERROR: to do more than just check to see whether the type implements // SPEC ERROR: operator true. First off, the type could implement the operator // SPEC ERROR: several times: if it is a struct then it could implement it // SPEC ERROR: twice, to take both nullable and non-nullable arguments, and // SPEC ERROR: if it is a class or type parameter then it could have several // SPEC ERROR: implementations on its base classes or effective base classes. // SPEC ERROR: Second, the type of the argument could be S? where S implements // SPEC ERROR: operator true(S?); we want to look at S, not S?, when looking // SPEC ERROR: for applicable candidates. // // SPEC ERROR: Basically, the spec should say "use unary operator overload resolution // SPEC ERROR: to find the candidate set and choose a unique best operator true". var expr = BindValue(node, diagnostics, BindValueKind.RValue); var boolean = GetSpecialType(SpecialType.System_Boolean, diagnostics, node); if (expr.HasAnyErrors) { // The expression could not be bound. Insert a fake conversion // around it to bool and keep on going. // NOTE: no user-defined conversion candidates. return BoundConversion.Synthesized(node, BindToTypeForErrorRecovery(expr), Conversion.NoConversion, false, explicitCastInCode: false, conversionGroupOpt: null, ConstantValue.NotAvailable, boolean, hasErrors: true); } // Oddly enough, "if(dyn)" is bound not as a dynamic conversion to bool, but as a dynamic // invocation of operator true. if (expr.HasDynamicType()) { return new BoundUnaryOperator( node, UnaryOperatorKind.DynamicTrue, BindToNaturalType(expr, diagnostics), ConstantValue.NotAvailable, methodOpt: null, constrainedToTypeOpt: null, LookupResultKind.Viable, boolean) { WasCompilerGenerated = true }; } // Is the operand implicitly convertible to bool? CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); var conversion = this.Conversions.ClassifyConversionFromExpression(expr, boolean, ref useSiteInfo); diagnostics.Add(expr.Syntax, useSiteInfo); if (conversion.IsImplicit) { if (conversion.Kind == ConversionKind.Identity) { // Check to see if we're assigning a boolean literal in a place where an // equality check would be more conventional. // NOTE: Don't do this check unless the expression will be returned // without being wrapped in another bound node (i.e. identity conversion). if (expr.Kind == BoundKind.AssignmentOperator) { var assignment = (BoundAssignmentOperator)expr; if (assignment.Right.Kind == BoundKind.Literal && assignment.Right.ConstantValue.Discriminator == ConstantValueTypeDiscriminator.Boolean) { Error(diagnostics, ErrorCode.WRN_IncorrectBooleanAssg, assignment.Syntax); } } } return CreateConversion( syntax: expr.Syntax, source: expr, conversion: conversion, isCast: false, conversionGroupOpt: null, wasCompilerGenerated: true, destination: boolean, diagnostics: diagnostics); } // It was not. Does it implement operator true? expr = BindToNaturalType(expr, diagnostics); var best = this.UnaryOperatorOverloadResolution(UnaryOperatorKind.True, expr, node, diagnostics, out LookupResultKind resultKind, out ImmutableArray<MethodSymbol> originalUserDefinedOperators); if (!best.HasValue) { // No. Give a "not convertible to bool" error. Debug.Assert(resultKind == LookupResultKind.Empty, "How could overload resolution fail if a user-defined true operator was found?"); Debug.Assert(originalUserDefinedOperators.IsEmpty, "How could overload resolution fail if a user-defined true operator was found?"); GenerateImplicitConversionError(diagnostics, node, conversion, expr, boolean); return BoundConversion.Synthesized(node, expr, Conversion.NoConversion, false, explicitCastInCode: false, conversionGroupOpt: null, ConstantValue.NotAvailable, boolean, hasErrors: true); } UnaryOperatorSignature signature = best.Signature; BoundExpression resultOperand = CreateConversion( node, expr, best.Conversion, isCast: false, conversionGroupOpt: null, destination: best.Signature.OperandType, diagnostics: diagnostics); CheckConstraintLanguageVersionAndRuntimeSupportForOperator(node, signature.Method, signature.ConstrainedToTypeOpt, diagnostics); // Consider op_true to be compiler-generated so that it doesn't appear in the semantic model. // UNDONE: If we decide to expose the operator in the semantic model, we'll have to remove the // WasCompilerGenerated flag (and possibly suppress the symbol in specific APIs). return new BoundUnaryOperator(node, signature.Kind, resultOperand, ConstantValue.NotAvailable, signature.Method, signature.ConstrainedToTypeOpt, resultKind, originalUserDefinedOperators, signature.ReturnType) { WasCompilerGenerated = true }; } private BoundStatement BindSwitchStatement(SwitchStatementSyntax node, BindingDiagnosticBag diagnostics) { Debug.Assert(node != null); Binder switchBinder = this.GetBinder(node); return switchBinder.BindSwitchStatementCore(node, switchBinder, diagnostics); } internal virtual BoundStatement BindSwitchStatementCore(SwitchStatementSyntax node, Binder originalBinder, BindingDiagnosticBag diagnostics) { return this.Next.BindSwitchStatementCore(node, originalBinder, diagnostics); } internal virtual void BindPatternSwitchLabelForInference(CasePatternSwitchLabelSyntax node, BindingDiagnosticBag diagnostics) { this.Next.BindPatternSwitchLabelForInference(node, diagnostics); } private BoundStatement BindWhile(WhileStatementSyntax node, BindingDiagnosticBag diagnostics) { Debug.Assert(node != null); var loopBinder = this.GetBinder(node); Debug.Assert(loopBinder != null); return loopBinder.BindWhileParts(diagnostics, loopBinder); } internal virtual BoundWhileStatement BindWhileParts(BindingDiagnosticBag diagnostics, Binder originalBinder) { return this.Next.BindWhileParts(diagnostics, originalBinder); } private BoundStatement BindDo(DoStatementSyntax node, BindingDiagnosticBag diagnostics) { var loopBinder = this.GetBinder(node); Debug.Assert(loopBinder != null); return loopBinder.BindDoParts(diagnostics, loopBinder); } internal virtual BoundDoStatement BindDoParts(BindingDiagnosticBag diagnostics, Binder originalBinder) { return this.Next.BindDoParts(diagnostics, originalBinder); } internal BoundForStatement BindFor(ForStatementSyntax node, BindingDiagnosticBag diagnostics) { var loopBinder = this.GetBinder(node); Debug.Assert(loopBinder != null); return loopBinder.BindForParts(diagnostics, loopBinder); } internal virtual BoundForStatement BindForParts(BindingDiagnosticBag diagnostics, Binder originalBinder) { return this.Next.BindForParts(diagnostics, originalBinder); } internal BoundStatement BindForOrUsingOrFixedDeclarations(VariableDeclarationSyntax nodeOpt, LocalDeclarationKind localKind, BindingDiagnosticBag diagnostics, out ImmutableArray<BoundLocalDeclaration> declarations) { if (nodeOpt == null) { declarations = ImmutableArray<BoundLocalDeclaration>.Empty; return null; } var typeSyntax = nodeOpt.Type; // Fixed and using variables are not allowed to be ref-like, but regular variables are if (localKind == LocalDeclarationKind.RegularVariable) { typeSyntax = typeSyntax.SkipRef(out _); } AliasSymbol alias; bool isVar; TypeWithAnnotations declType = BindTypeOrVarKeyword(typeSyntax, diagnostics, out isVar, out alias); Debug.Assert(declType.HasType || isVar); var variables = nodeOpt.Variables; int count = variables.Count; Debug.Assert(count > 0); if (isVar && count > 1) { // There are a number of ways in which a var decl can be illegal, but in these // cases we should report an error and then keep right on going with the inference. Error(diagnostics, ErrorCode.ERR_ImplicitlyTypedVariableMultipleDeclarator, nodeOpt); } var declarationArray = new BoundLocalDeclaration[count]; for (int i = 0; i < count; i++) { var variableDeclarator = variables[i]; bool includeBoundType = i == 0; //To avoid duplicated expressions, only the first declaration should contain the bound type. var declaration = BindVariableDeclaration(localKind, isVar, variableDeclarator, typeSyntax, declType, alias, diagnostics, includeBoundType); declarationArray[i] = declaration; } declarations = declarationArray.AsImmutableOrNull(); return (count == 1) ? (BoundStatement)declarations[0] : new BoundMultipleLocalDeclarations(nodeOpt, declarations); } internal BoundStatement BindStatementExpressionList(SeparatedSyntaxList<ExpressionSyntax> statements, BindingDiagnosticBag diagnostics) { int count = statements.Count; if (count == 0) { return null; } else if (count == 1) { var syntax = statements[0]; return BindExpressionStatement(syntax, syntax, false, diagnostics); } else { var statementBuilder = ArrayBuilder<BoundStatement>.GetInstance(); for (int i = 0; i < count; i++) { var syntax = statements[i]; var statement = BindExpressionStatement(syntax, syntax, false, diagnostics); statementBuilder.Add(statement); } return BoundStatementList.Synthesized(statements.Node, statementBuilder.ToImmutableAndFree()); } } private BoundStatement BindForEach(CommonForEachStatementSyntax node, BindingDiagnosticBag diagnostics) { Binder loopBinder = this.GetBinder(node); return this.GetBinder(node.Expression).WrapWithVariablesIfAny(node.Expression, loopBinder.BindForEachParts(diagnostics, loopBinder)); } internal virtual BoundStatement BindForEachParts(BindingDiagnosticBag diagnostics, Binder originalBinder) { return this.Next.BindForEachParts(diagnostics, originalBinder); } /// <summary> /// Like BindForEachParts, but only bind the deconstruction part of the foreach, for purpose of inferring the types of the declared locals. /// </summary> internal virtual BoundStatement BindForEachDeconstruction(BindingDiagnosticBag diagnostics, Binder originalBinder) { return this.Next.BindForEachDeconstruction(diagnostics, originalBinder); } private BoundStatement BindBreak(BreakStatementSyntax node, BindingDiagnosticBag diagnostics) { var target = this.BreakLabel; if ((object)target == null) { Error(diagnostics, ErrorCode.ERR_NoBreakOrCont, node); return new BoundBadStatement(node, ImmutableArray<BoundNode>.Empty, hasErrors: true); } return new BoundBreakStatement(node, target); } private BoundStatement BindContinue(ContinueStatementSyntax node, BindingDiagnosticBag diagnostics) { var target = this.ContinueLabel; if ((object)target == null) { Error(diagnostics, ErrorCode.ERR_NoBreakOrCont, node); return new BoundBadStatement(node, ImmutableArray<BoundNode>.Empty, hasErrors: true); } return new BoundContinueStatement(node, target); } private static SwitchBinder GetSwitchBinder(Binder binder) { SwitchBinder switchBinder = binder as SwitchBinder; while (binder != null && switchBinder == null) { binder = binder.Next; switchBinder = binder as SwitchBinder; } return switchBinder; } protected static bool IsInAsyncMethod(MethodSymbol method) { return (object)method != null && method.IsAsync; } protected bool IsInAsyncMethod() { return IsInAsyncMethod(this.ContainingMemberOrLambda as MethodSymbol); } protected bool IsEffectivelyTaskReturningAsyncMethod() { var symbol = this.ContainingMemberOrLambda; return symbol?.Kind == SymbolKind.Method && ((MethodSymbol)symbol).IsAsyncEffectivelyReturningTask(this.Compilation); } protected bool IsEffectivelyGenericTaskReturningAsyncMethod() { var symbol = this.ContainingMemberOrLambda; return symbol?.Kind == SymbolKind.Method && ((MethodSymbol)symbol).IsAsyncEffectivelyReturningGenericTask(this.Compilation); } protected bool IsIAsyncEnumerableOrIAsyncEnumeratorReturningAsyncMethod() { var symbol = this.ContainingMemberOrLambda; if (symbol?.Kind == SymbolKind.Method) { var method = (MethodSymbol)symbol; return method.IsAsyncReturningIAsyncEnumerable(this.Compilation) || method.IsAsyncReturningIAsyncEnumerator(this.Compilation); } return false; } protected virtual TypeSymbol GetCurrentReturnType(out RefKind refKind) { var symbol = this.ContainingMemberOrLambda as MethodSymbol; if ((object)symbol != null) { refKind = symbol.RefKind; TypeSymbol returnType = symbol.ReturnType; if ((object)returnType == LambdaSymbol.ReturnTypeIsBeingInferred) { return null; } return returnType; } refKind = RefKind.None; return null; } private BoundStatement BindReturn(ReturnStatementSyntax syntax, BindingDiagnosticBag diagnostics) { var refKind = RefKind.None; var expressionSyntax = syntax.Expression?.CheckAndUnwrapRefExpression(diagnostics, out refKind); BoundExpression arg = null; if (expressionSyntax != null) { BindValueKind requiredValueKind = GetRequiredReturnValueKind(refKind); arg = BindValue(expressionSyntax, diagnostics, requiredValueKind); } else { // If this is a void return statement in a script, return default(T). var interactiveInitializerMethod = this.ContainingMemberOrLambda as SynthesizedInteractiveInitializerMethod; if (interactiveInitializerMethod != null) { arg = new BoundDefaultExpression(interactiveInitializerMethod.GetNonNullSyntaxNode(), interactiveInitializerMethod.ResultType); } } RefKind sigRefKind; TypeSymbol retType = GetCurrentReturnType(out sigRefKind); bool hasErrors = false; if (IsDirectlyInIterator) { diagnostics.Add(ErrorCode.ERR_ReturnInIterator, syntax.ReturnKeyword.GetLocation()); hasErrors = true; } else if (IsInAsyncMethod()) { if (refKind != RefKind.None) { // This can happen if we are binding an async anonymous method to a delegate type. diagnostics.Add(ErrorCode.ERR_MustNotHaveRefReturn, syntax.ReturnKeyword.GetLocation()); hasErrors = true; } else if (IsIAsyncEnumerableOrIAsyncEnumeratorReturningAsyncMethod()) { diagnostics.Add(ErrorCode.ERR_ReturnInIterator, syntax.ReturnKeyword.GetLocation()); hasErrors = true; } } else if ((object)retType != null && (refKind != RefKind.None) != (sigRefKind != RefKind.None)) { var errorCode = refKind != RefKind.None ? ErrorCode.ERR_MustNotHaveRefReturn : ErrorCode.ERR_MustHaveRefReturn; diagnostics.Add(errorCode, syntax.ReturnKeyword.GetLocation()); hasErrors = true; } if (arg != null) { hasErrors |= arg.HasErrors || ((object)arg.Type != null && arg.Type.IsErrorType()); } if (hasErrors) { return new BoundReturnStatement(syntax, refKind, BindToTypeForErrorRecovery(arg), hasErrors: true); } // The return type could be null; we might be attempting to infer the return type either // because of method type inference, or because we are attempting to do error analysis // on a lambda expression of unknown return type. if ((object)retType != null) { if (retType.IsVoidType() || IsEffectivelyTaskReturningAsyncMethod()) { if (arg != null) { var container = this.ContainingMemberOrLambda; var lambda = container as LambdaSymbol; if ((object)lambda != null) { // Error case: void-returning or async task-returning method or lambda with "return x;" var errorCode = retType.IsVoidType() ? ErrorCode.ERR_RetNoObjectRequiredLambda : ErrorCode.ERR_TaskRetNoObjectRequiredLambda; // Anonymous function converted to a void returning delegate cannot return a value Error(diagnostics, errorCode, syntax.ReturnKeyword); hasErrors = true; // COMPATIBILITY: The native compiler also produced an error // COMPATIBILITY: "Cannot convert lambda expression to delegate type 'Action' because some of the // COMPATIBILITY: return types in the block are not implicitly convertible to the delegate return type" // COMPATIBILITY: This error doesn't make sense in the "void" case because the whole idea of // COMPATIBILITY: "conversion to void" is a bit unusual, and we've already given a good error. } else { // Error case: void-returning or async task-returning method or lambda with "return x;" var errorCode = retType.IsVoidType() ? ErrorCode.ERR_RetNoObjectRequired : ErrorCode.ERR_TaskRetNoObjectRequired; Error(diagnostics, errorCode, syntax.ReturnKeyword, container); hasErrors = true; } } } else { if (arg == null) { // Error case: non-void-returning or Task<T>-returning method or lambda but just have "return;" var requiredType = IsEffectivelyGenericTaskReturningAsyncMethod() ? retType.GetMemberTypeArgumentsNoUseSiteDiagnostics().Single() : retType; Error(diagnostics, ErrorCode.ERR_RetObjectRequired, syntax.ReturnKeyword, requiredType); hasErrors = true; } else { arg = CreateReturnConversion(syntax, diagnostics, arg, sigRefKind, retType); arg = ValidateEscape(arg, Binder.ExternalScope, refKind != RefKind.None, diagnostics); } } } else { // Check that the returned expression is not void. if ((object)arg?.Type != null && arg.Type.IsVoidType()) { Error(diagnostics, ErrorCode.ERR_CantReturnVoid, expressionSyntax); hasErrors = true; } } return new BoundReturnStatement(syntax, refKind, hasErrors ? BindToTypeForErrorRecovery(arg) : arg, hasErrors); } internal BoundExpression CreateReturnConversion( SyntaxNode syntax, BindingDiagnosticBag diagnostics, BoundExpression argument, RefKind returnRefKind, TypeSymbol returnType) { // If the return type is not void then the expression must be implicitly convertible. Conversion conversion; bool badAsyncReturnAlreadyReported = false; CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); if (IsInAsyncMethod()) { Debug.Assert(returnRefKind == RefKind.None); if (!IsEffectivelyGenericTaskReturningAsyncMethod()) { conversion = Conversion.NoConversion; badAsyncReturnAlreadyReported = true; } else { returnType = returnType.GetMemberTypeArgumentsNoUseSiteDiagnostics().Single(); conversion = this.Conversions.ClassifyConversionFromExpression(argument, returnType, ref useSiteInfo); } } else { conversion = this.Conversions.ClassifyConversionFromExpression(argument, returnType, ref useSiteInfo); } diagnostics.Add(syntax, useSiteInfo); if (!argument.HasAnyErrors) { if (returnRefKind != RefKind.None) { if (conversion.Kind != ConversionKind.Identity) { Error(diagnostics, ErrorCode.ERR_RefReturnMustHaveIdentityConversion, argument.Syntax, returnType); argument = argument.WithHasErrors(); } else { return BindToNaturalType(argument, diagnostics); } } else if (!conversion.IsImplicit || !conversion.IsValid) { if (!badAsyncReturnAlreadyReported) { RefKind unusedRefKind; if (IsEffectivelyGenericTaskReturningAsyncMethod() && TypeSymbol.Equals(argument.Type, this.GetCurrentReturnType(out unusedRefKind), TypeCompareKind.ConsiderEverything2)) { // Since this is an async method, the return expression must be of type '{0}' rather than 'Task<{0}>' Error(diagnostics, ErrorCode.ERR_BadAsyncReturnExpression, argument.Syntax, returnType); } else { GenerateImplicitConversionError(diagnostics, argument.Syntax, conversion, argument, returnType); if (this.ContainingMemberOrLambda is LambdaSymbol) { ReportCantConvertLambdaReturn(argument.Syntax, diagnostics); } } } } } return CreateConversion(argument.Syntax, argument, conversion, isCast: false, conversionGroupOpt: null, returnType, diagnostics); } private BoundTryStatement BindTryStatement(TryStatementSyntax node, BindingDiagnosticBag diagnostics) { Debug.Assert(node != null); var tryBlock = BindEmbeddedBlock(node.Block, diagnostics); var catchBlocks = BindCatchBlocks(node.Catches, diagnostics); var finallyBlockOpt = (node.Finally != null) ? BindEmbeddedBlock(node.Finally.Block, diagnostics) : null; return new BoundTryStatement(node, tryBlock, catchBlocks, finallyBlockOpt); } private ImmutableArray<BoundCatchBlock> BindCatchBlocks(SyntaxList<CatchClauseSyntax> catchClauses, BindingDiagnosticBag diagnostics) { int n = catchClauses.Count; if (n == 0) { return ImmutableArray<BoundCatchBlock>.Empty; } var catchBlocks = ArrayBuilder<BoundCatchBlock>.GetInstance(n); var hasCatchAll = false; foreach (var catchSyntax in catchClauses) { if (hasCatchAll) { diagnostics.Add(ErrorCode.ERR_TooManyCatches, catchSyntax.CatchKeyword.GetLocation()); } var catchBinder = this.GetBinder(catchSyntax); var catchBlock = catchBinder.BindCatchBlock(catchSyntax, catchBlocks, diagnostics); catchBlocks.Add(catchBlock); hasCatchAll |= catchSyntax.Declaration == null && catchSyntax.Filter == null; } return catchBlocks.ToImmutableAndFree(); } private BoundCatchBlock BindCatchBlock(CatchClauseSyntax node, ArrayBuilder<BoundCatchBlock> previousBlocks, BindingDiagnosticBag diagnostics) { bool hasError = false; TypeSymbol type = null; BoundExpression boundFilter = null; var declaration = node.Declaration; if (declaration != null) { // Note: The type is being bound twice: here and in LocalSymbol.Type. Currently, // LocalSymbol.Type ignores diagnostics so it seems cleaner to bind the type here // as well. However, if LocalSymbol.Type is changed to report diagnostics, we'll // need to avoid binding here since that will result in duplicate diagnostics. type = this.BindType(declaration.Type, diagnostics).Type; Debug.Assert((object)type != null); if (type.IsErrorType()) { hasError = true; } else { CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); TypeSymbol effectiveType = type.EffectiveType(ref useSiteInfo); if (!Compilation.IsExceptionType(effectiveType, ref useSiteInfo)) { // "The type caught or thrown must be derived from System.Exception" Error(diagnostics, ErrorCode.ERR_BadExceptionType, declaration.Type); hasError = true; diagnostics.Add(declaration.Type, useSiteInfo); } else { diagnostics.AddDependencies(useSiteInfo); } } } var filter = node.Filter; if (filter != null) { var filterBinder = this.GetBinder(filter); boundFilter = filterBinder.BindCatchFilter(filter, diagnostics); hasError |= boundFilter.HasAnyErrors; } if (!hasError) { // TODO: Loop is O(n), caller is O(n^2). Perhaps we could iterate in reverse order (since it's easier to find // base types than to find derived types). Debug.Assert(((object)type == null) || !type.IsErrorType()); foreach (var previousBlock in previousBlocks) { var previousType = previousBlock.ExceptionTypeOpt; // If the previous type is a generic parameter we don't know what exception types it's gonna catch exactly. // If it is a class-type we know it's gonna catch all exception types of its type and types that are derived from it. // So if the current type is a class-type (or an effective base type of a generic parameter) // that derives from the previous type the current catch is unreachable. if (previousBlock.ExceptionFilterOpt == null && (object)previousType != null && !previousType.IsErrorType()) { if ((object)type != null) { CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); if (Conversions.HasIdentityOrImplicitReferenceConversion(type, previousType, ref useSiteInfo)) { // "A previous catch clause already catches all exceptions of this or of a super type ('{0}')" Error(diagnostics, ErrorCode.ERR_UnreachableCatch, declaration.Type, previousType); diagnostics.Add(declaration.Type, useSiteInfo); hasError = true; break; } diagnostics.Add(declaration.Type, useSiteInfo); } else if (TypeSymbol.Equals(previousType, Compilation.GetWellKnownType(WellKnownType.System_Exception), TypeCompareKind.ConsiderEverything2) && Compilation.SourceAssembly.RuntimeCompatibilityWrapNonExceptionThrows) { // If the RuntimeCompatibility(WrapNonExceptionThrows = false) is applied on the source assembly or any referenced netmodule. // an empty catch may catch exceptions that don't derive from System.Exception. // "A previous catch clause already catches all exceptions..." Error(diagnostics, ErrorCode.WRN_UnreachableGeneralCatch, node.CatchKeyword); break; } } } } var binder = GetBinder(node); Debug.Assert(binder != null); ImmutableArray<LocalSymbol> locals = binder.GetDeclaredLocalsForScope(node); BoundExpression exceptionSource = null; LocalSymbol local = locals.FirstOrDefault(); if (local?.DeclarationKind == LocalDeclarationKind.CatchVariable) { Debug.Assert(local.Type.IsErrorType() || (TypeSymbol.Equals(local.Type, type, TypeCompareKind.ConsiderEverything2))); // Check for local variable conflicts in the *enclosing* binder, not the *current* binder; // obviously we will find a local of the given name in the current binder. hasError |= this.ValidateDeclarationNameConflictsInScope(local, diagnostics); exceptionSource = new BoundLocal(declaration, local, ConstantValue.NotAvailable, local.Type); } var block = BindEmbeddedBlock(node.Block, diagnostics); return new BoundCatchBlock(node, locals, exceptionSource, type, exceptionFilterPrologueOpt: null, boundFilter, block, hasError); } private BoundExpression BindCatchFilter(CatchFilterClauseSyntax filter, BindingDiagnosticBag diagnostics) { BoundExpression boundFilter = this.BindBooleanExpression(filter.FilterExpression, diagnostics); if (boundFilter.ConstantValue != ConstantValue.NotAvailable) { // Depending on whether the filter constant is true or false, and whether there are other catch clauses, // we suggest different actions var errorCode = boundFilter.ConstantValue.BooleanValue ? ErrorCode.WRN_FilterIsConstantTrue : (filter.Parent.Parent is TryStatementSyntax s && s.Catches.Count == 1 && s.Finally == null) ? ErrorCode.WRN_FilterIsConstantFalseRedundantTryCatch : ErrorCode.WRN_FilterIsConstantFalse; // Since the expression is a constant, the name can be retrieved from the first token Error(diagnostics, errorCode, filter.FilterExpression); } return boundFilter; } // Report an extra error on the return if we are in a lambda conversion. private void ReportCantConvertLambdaReturn(SyntaxNode syntax, BindingDiagnosticBag diagnostics) { // Suppress this error if the lambda is a result of a query rewrite. if (syntax.Parent is QueryClauseSyntax || syntax.Parent is SelectOrGroupClauseSyntax) return; var lambda = this.ContainingMemberOrLambda as LambdaSymbol; if ((object)lambda != null) { Location location = GetLocationForDiagnostics(syntax); if (IsInAsyncMethod()) { // Cannot convert async {0} to intended delegate type. An async {0} may return void, Task or Task<T>, none of which are convertible to '{1}'. Error(diagnostics, ErrorCode.ERR_CantConvAsyncAnonFuncReturns, location, lambda.MessageID.Localize(), lambda.ReturnType); } else { // Cannot convert {0} to intended delegate type because some of the return types in the block are not implicitly convertible to the delegate return type Error(diagnostics, ErrorCode.ERR_CantConvAnonMethReturns, location, lambda.MessageID.Localize()); } } } private static Location GetLocationForDiagnostics(SyntaxNode node) { switch (node) { case LambdaExpressionSyntax lambdaSyntax: return Location.Create(lambdaSyntax.SyntaxTree, Text.TextSpan.FromBounds(lambdaSyntax.SpanStart, lambdaSyntax.ArrowToken.Span.End)); case AnonymousMethodExpressionSyntax anonymousMethodSyntax: return Location.Create(anonymousMethodSyntax.SyntaxTree, Text.TextSpan.FromBounds(anonymousMethodSyntax.SpanStart, anonymousMethodSyntax.ParameterList?.Span.End ?? anonymousMethodSyntax.DelegateKeyword.Span.End)); } return node.Location; } private static bool IsValidStatementExpression(SyntaxNode syntax, BoundExpression expression) { bool syntacticallyValid = SyntaxFacts.IsStatementExpression(syntax); if (!syntacticallyValid) { return false; } if (expression.IsSuppressed) { return false; } // It is possible that an expression is syntactically valid but semantic analysis // reveals it to be illegal in a statement expression: "new MyDelegate(M)" for example // is not legal because it is a delegate-creation-expression and not an // object-creation-expression, but of course we don't know that syntactically. if (expression.Kind == BoundKind.DelegateCreationExpression || expression.Kind == BoundKind.NameOfOperator) { return false; } return true; } /// <summary> /// Wrap a given expression e into a block as either { e; } or { return e; } /// Shared between lambda and expression-bodied method binding. /// </summary> internal BoundBlock CreateBlockFromExpression(CSharpSyntaxNode node, ImmutableArray<LocalSymbol> locals, RefKind refKind, BoundExpression expression, ExpressionSyntax expressionSyntax, BindingDiagnosticBag diagnostics) { RefKind returnRefKind; var returnType = GetCurrentReturnType(out returnRefKind); var syntax = expressionSyntax ?? expression.Syntax; BoundStatement statement; if (IsInAsyncMethod() && refKind != RefKind.None) { // This can happen if we are binding an async anonymous method to a delegate type. Error(diagnostics, ErrorCode.ERR_MustNotHaveRefReturn, syntax); expression = BindToTypeForErrorRecovery(expression); statement = new BoundReturnStatement(syntax, refKind, expression) { WasCompilerGenerated = true }; } else if ((object)returnType != null) { if ((refKind != RefKind.None) != (returnRefKind != RefKind.None) && expression.Kind != BoundKind.ThrowExpression) { var errorCode = refKind != RefKind.None ? ErrorCode.ERR_MustNotHaveRefReturn : ErrorCode.ERR_MustHaveRefReturn; Error(diagnostics, errorCode, syntax); expression = BindToTypeForErrorRecovery(expression); statement = new BoundReturnStatement(syntax, RefKind.None, expression) { WasCompilerGenerated = true }; } else if (returnType.IsVoidType() || IsEffectivelyTaskReturningAsyncMethod()) { // If the return type is void then the expression is required to be a legal // statement expression. Debug.Assert(expressionSyntax != null || !IsValidExpressionBody(expressionSyntax, expression)); bool errors = false; if (expressionSyntax == null || !IsValidExpressionBody(expressionSyntax, expression)) { expression = BindToTypeForErrorRecovery(expression); Error(diagnostics, ErrorCode.ERR_IllegalStatement, syntax); errors = true; } else { expression = BindToNaturalType(expression, diagnostics); } // Don't mark compiler generated so that the rewriter generates sequence points var expressionStatement = new BoundExpressionStatement(syntax, expression, errors); CheckForUnobservedAwaitable(expression, diagnostics); statement = expressionStatement; } else if (IsIAsyncEnumerableOrIAsyncEnumeratorReturningAsyncMethod()) { Error(diagnostics, ErrorCode.ERR_ReturnInIterator, syntax); expression = BindToTypeForErrorRecovery(expression); statement = new BoundReturnStatement(syntax, returnRefKind, expression) { WasCompilerGenerated = true }; } else { expression = returnType.IsErrorType() ? BindToTypeForErrorRecovery(expression) : CreateReturnConversion(syntax, diagnostics, expression, refKind, returnType); statement = new BoundReturnStatement(syntax, returnRefKind, expression) { WasCompilerGenerated = true }; } } else if (expression.Type?.SpecialType == SpecialType.System_Void) { expression = BindToNaturalType(expression, diagnostics); statement = new BoundExpressionStatement(syntax, expression) { WasCompilerGenerated = true }; } else { // When binding for purpose of inferring the return type of a lambda, we do not require returned expressions (such as `default` or switch expressions) to have a natural type var inferringLambda = this.ContainingMemberOrLambda is MethodSymbol method && (object)method.ReturnType == LambdaSymbol.ReturnTypeIsBeingInferred; if (!inferringLambda) { expression = BindToNaturalType(expression, diagnostics); } statement = new BoundReturnStatement(syntax, refKind, expression) { WasCompilerGenerated = true }; } // Need to attach the tree for when we generate sequence points. return new BoundBlock(node, locals, ImmutableArray.Create(statement)) { WasCompilerGenerated = node.Kind() != SyntaxKind.ArrowExpressionClause }; } private static bool IsValidExpressionBody(SyntaxNode expressionSyntax, BoundExpression expression) { return IsValidStatementExpression(expressionSyntax, expression) || expressionSyntax.Kind() == SyntaxKind.ThrowExpression; } /// <summary> /// Binds an expression-bodied member with expression e as either { return e; } or { e; }. /// </summary> internal virtual BoundBlock BindExpressionBodyAsBlock(ArrowExpressionClauseSyntax expressionBody, BindingDiagnosticBag diagnostics) { Binder bodyBinder = this.GetBinder(expressionBody); Debug.Assert(bodyBinder != null); return bindExpressionBodyAsBlockInternal(expressionBody, bodyBinder, diagnostics); // Use static local function to prevent accidentally calling instance methods on `this` instead of `bodyBinder` static BoundBlock bindExpressionBodyAsBlockInternal(ArrowExpressionClauseSyntax expressionBody, Binder bodyBinder, BindingDiagnosticBag diagnostics) { RefKind refKind; ExpressionSyntax expressionSyntax = expressionBody.Expression.CheckAndUnwrapRefExpression(diagnostics, out refKind); BindValueKind requiredValueKind = bodyBinder.GetRequiredReturnValueKind(refKind); BoundExpression expression = bodyBinder.BindValue(expressionSyntax, diagnostics, requiredValueKind); expression = bodyBinder.ValidateEscape(expression, Binder.ExternalScope, refKind != RefKind.None, diagnostics); return bodyBinder.CreateBlockFromExpression(expressionBody, bodyBinder.GetDeclaredLocalsForScope(expressionBody), refKind, expression, expressionSyntax, diagnostics); } } /// <summary> /// Binds a lambda with expression e as either { return e; } or { e; }. /// </summary> public BoundBlock BindLambdaExpressionAsBlock(ExpressionSyntax body, BindingDiagnosticBag diagnostics) { Binder bodyBinder = this.GetBinder(body); Debug.Assert(bodyBinder != null); RefKind refKind; var expressionSyntax = body.CheckAndUnwrapRefExpression(diagnostics, out refKind); BindValueKind requiredValueKind = GetRequiredReturnValueKind(refKind); BoundExpression expression = bodyBinder.BindValue(expressionSyntax, diagnostics, requiredValueKind); expression = ValidateEscape(expression, Binder.ExternalScope, refKind != RefKind.None, diagnostics); return bodyBinder.CreateBlockFromExpression(body, bodyBinder.GetDeclaredLocalsForScope(body), refKind, expression, expressionSyntax, diagnostics); } public BoundBlock CreateBlockFromExpression(ExpressionSyntax body, BoundExpression expression, BindingDiagnosticBag diagnostics) { Binder bodyBinder = this.GetBinder(body); Debug.Assert(bodyBinder != null); Debug.Assert(body.Kind() != SyntaxKind.RefExpression); return bodyBinder.CreateBlockFromExpression(body, bodyBinder.GetDeclaredLocalsForScope(body), RefKind.None, expression, body, diagnostics); } private BindValueKind GetRequiredReturnValueKind(RefKind refKind) { BindValueKind requiredValueKind = BindValueKind.RValue; if (refKind != RefKind.None) { GetCurrentReturnType(out var sigRefKind); requiredValueKind = sigRefKind == RefKind.Ref ? BindValueKind.RefReturn : BindValueKind.ReadonlyRef; } return requiredValueKind; } public virtual BoundNode BindMethodBody(CSharpSyntaxNode syntax, BindingDiagnosticBag diagnostics, bool includesFieldInitializers = false) { switch (syntax) { case RecordDeclarationSyntax recordDecl: return BindRecordConstructorBody(recordDecl, diagnostics); case BaseMethodDeclarationSyntax method: if (method.Kind() == SyntaxKind.ConstructorDeclaration) { return BindConstructorBody((ConstructorDeclarationSyntax)method, diagnostics, includesFieldInitializers); } return BindMethodBody(method, method.Body, method.ExpressionBody, diagnostics); case AccessorDeclarationSyntax accessor: return BindMethodBody(accessor, accessor.Body, accessor.ExpressionBody, diagnostics); case ArrowExpressionClauseSyntax arrowExpression: return BindExpressionBodyAsBlock(arrowExpression, diagnostics); case CompilationUnitSyntax compilationUnit: return BindSimpleProgram(compilationUnit, diagnostics); default: throw ExceptionUtilities.UnexpectedValue(syntax.Kind()); } } private BoundNode BindSimpleProgram(CompilationUnitSyntax compilationUnit, BindingDiagnosticBag diagnostics) { var simpleProgram = (SynthesizedSimpleProgramEntryPointSymbol)ContainingMemberOrLambda; return GetBinder(compilationUnit).BindSimpleProgramCompilationUnit(compilationUnit, simpleProgram, diagnostics); } private BoundNode BindSimpleProgramCompilationUnit(CompilationUnitSyntax compilationUnit, SynthesizedSimpleProgramEntryPointSymbol simpleProgram, BindingDiagnosticBag diagnostics) { ArrayBuilder<BoundStatement> boundStatements = ArrayBuilder<BoundStatement>.GetInstance(); foreach (var statement in compilationUnit.Members) { if (statement is GlobalStatementSyntax topLevelStatement) { var boundStatement = BindStatement(topLevelStatement.Statement, diagnostics); boundStatements.Add(boundStatement); } } return new BoundNonConstructorMethodBody(compilationUnit, FinishBindBlockParts(compilationUnit, boundStatements.ToImmutableAndFree(), diagnostics).MakeCompilerGenerated(), expressionBody: null); } private BoundNode BindRecordConstructorBody(RecordDeclarationSyntax recordDecl, BindingDiagnosticBag diagnostics) { Debug.Assert(recordDecl.ParameterList is object); Debug.Assert(recordDecl.IsKind(SyntaxKind.RecordDeclaration)); Binder bodyBinder = this.GetBinder(recordDecl); Debug.Assert(bodyBinder != null); BoundExpressionStatement initializer = null; if (recordDecl.PrimaryConstructorBaseTypeIfClass is PrimaryConstructorBaseTypeSyntax baseWithArguments) { initializer = bodyBinder.BindConstructorInitializer(baseWithArguments, diagnostics); } return new BoundConstructorMethodBody(recordDecl, bodyBinder.GetDeclaredLocalsForScope(recordDecl), initializer, blockBody: new BoundBlock(recordDecl, ImmutableArray<LocalSymbol>.Empty, ImmutableArray<BoundStatement>.Empty).MakeCompilerGenerated(), expressionBody: null); } internal virtual BoundExpressionStatement BindConstructorInitializer(PrimaryConstructorBaseTypeSyntax initializer, BindingDiagnosticBag diagnostics) { BoundExpression initializerInvocation = GetBinder(initializer).BindConstructorInitializer(initializer.ArgumentList, (MethodSymbol)this.ContainingMember(), diagnostics); var constructorInitializer = new BoundExpressionStatement(initializer, initializerInvocation); Debug.Assert(initializerInvocation.HasAnyErrors || constructorInitializer.IsConstructorInitializer(), "Please keep this bound node in sync with BoundNodeExtensions.IsConstructorInitializer."); return constructorInitializer; } private BoundNode BindConstructorBody(ConstructorDeclarationSyntax constructor, BindingDiagnosticBag diagnostics, bool includesFieldInitializers) { ConstructorInitializerSyntax initializer = constructor.Initializer; if (initializer == null && constructor.Body == null && constructor.ExpressionBody == null) { return null; } Binder bodyBinder = this.GetBinder(constructor); Debug.Assert(bodyBinder != null); bool thisInitializer = initializer?.IsKind(SyntaxKind.ThisConstructorInitializer) == true; if (!thisInitializer && ContainingType.GetMembersUnordered().OfType<SynthesizedRecordConstructor>().Any()) { var constructorSymbol = (MethodSymbol)this.ContainingMember(); if (!constructorSymbol.IsStatic && !SynthesizedRecordCopyCtor.IsCopyConstructor(constructorSymbol)) { // Note: we check the constructor initializer of copy constructors elsewhere Error(diagnostics, ErrorCode.ERR_UnexpectedOrMissingConstructorInitializerInRecord, initializer?.ThisOrBaseKeyword ?? constructor.Identifier); } } // The `: this()` initializer is ignored when it is a default value type constructor // and we need to include field initializers into the constructor. bool skipInitializer = includesFieldInitializers && thisInitializer && ContainingType.IsDefaultValueTypeConstructor(initializer); // Using BindStatement to bind block to make sure we are reusing results of partial binding in SemanticModel return new BoundConstructorMethodBody(constructor, bodyBinder.GetDeclaredLocalsForScope(constructor), skipInitializer ? new BoundNoOpStatement(constructor, NoOpStatementFlavor.Default) : initializer == null ? null : bodyBinder.BindConstructorInitializer(initializer, diagnostics), constructor.Body == null ? null : (BoundBlock)bodyBinder.BindStatement(constructor.Body, diagnostics), constructor.ExpressionBody == null ? null : bodyBinder.BindExpressionBodyAsBlock(constructor.ExpressionBody, constructor.Body == null ? diagnostics : BindingDiagnosticBag.Discarded)); } internal virtual BoundExpressionStatement BindConstructorInitializer(ConstructorInitializerSyntax initializer, BindingDiagnosticBag diagnostics) { BoundExpression initializerInvocation = GetBinder(initializer).BindConstructorInitializer(initializer.ArgumentList, (MethodSymbol)this.ContainingMember(), diagnostics); // Base WasCompilerGenerated state off of whether constructor is implicitly declared, this will ensure proper instrumentation. Debug.Assert(!this.ContainingMember().IsImplicitlyDeclared); var constructorInitializer = new BoundExpressionStatement(initializer, initializerInvocation); Debug.Assert(initializerInvocation.HasAnyErrors || constructorInitializer.IsConstructorInitializer(), "Please keep this bound node in sync with BoundNodeExtensions.IsConstructorInitializer."); return constructorInitializer; } private BoundNode BindMethodBody(CSharpSyntaxNode declaration, BlockSyntax blockBody, ArrowExpressionClauseSyntax expressionBody, BindingDiagnosticBag diagnostics) { if (blockBody == null && expressionBody == null) { return null; } // Using BindStatement to bind block to make sure we are reusing results of partial binding in SemanticModel return new BoundNonConstructorMethodBody(declaration, blockBody == null ? null : (BoundBlock)BindStatement(blockBody, diagnostics), expressionBody == null ? null : BindExpressionBodyAsBlock(expressionBody, blockBody == null ? diagnostics : BindingDiagnosticBag.Discarded)); } internal virtual ImmutableArray<LocalSymbol> Locals { get { return ImmutableArray<LocalSymbol>.Empty; } } internal virtual ImmutableArray<LocalFunctionSymbol> LocalFunctions { get { return ImmutableArray<LocalFunctionSymbol>.Empty; } } internal virtual ImmutableArray<LabelSymbol> Labels { get { return ImmutableArray<LabelSymbol>.Empty; } } /// <summary> /// If this binder owns the scope that can declare extern aliases, a set of declared aliases should be returned (even if empty). /// Otherwise, a default instance should be returned. /// </summary> internal virtual ImmutableArray<AliasAndExternAliasDirective> ExternAliases { get { return default; } } /// <summary> /// If this binder owns the scope that can declare using aliases, a set of declared aliases should be returned (even if empty). /// Otherwise, a default instance should be returned. /// Note, only aliases syntactically declared within the enclosing declaration are included. For example, global aliases /// declared in a different compilation units are not included. /// </summary> internal virtual ImmutableArray<AliasAndUsingDirective> UsingAliases { get { return default; } } /// <summary> /// Perform a lookup for the specified method on the specified expression by attempting to invoke it /// </summary> /// <param name="receiver">The expression to perform pattern lookup on</param> /// <param name="methodName">Method to search for.</param> /// <param name="syntaxNode">The expression for which lookup is being performed</param> /// <param name="diagnostics">Populated with binding diagnostics.</param> /// <param name="result">The method symbol that was looked up, or null</param> /// <returns>A <see cref="PatternLookupResult"/> value with the outcome of the lookup</returns> internal PatternLookupResult PerformPatternMethodLookup(BoundExpression receiver, string methodName, SyntaxNode syntaxNode, BindingDiagnosticBag diagnostics, out MethodSymbol result) { var bindingDiagnostics = BindingDiagnosticBag.GetInstance(diagnostics); try { result = null; var boundAccess = BindInstanceMemberAccess( syntaxNode, syntaxNode, receiver, methodName, rightArity: 0, typeArgumentsSyntax: default, typeArgumentsWithAnnotations: default, invoked: true, indexed: false, bindingDiagnostics); if (boundAccess.Kind != BoundKind.MethodGroup) { // the thing is not a method return PatternLookupResult.NotAMethod; } // NOTE: Because we're calling this method with no arguments and we // explicitly ignore default values for params parameters // (see ParameterSymbol.IsOptional) we know that no ParameterArray // containing method can be invoked in normal form which allows // us to skip some work during the lookup. var analyzedArguments = AnalyzedArguments.GetInstance(); var patternMethodCall = BindMethodGroupInvocation( syntaxNode, syntaxNode, methodName, (BoundMethodGroup)boundAccess, analyzedArguments, bindingDiagnostics, queryClause: null, allowUnexpandedForm: false, anyApplicableCandidates: out _); analyzedArguments.Free(); if (patternMethodCall.Kind != BoundKind.Call) { return PatternLookupResult.NotCallable; } var call = (BoundCall)patternMethodCall; if (call.ResultKind == LookupResultKind.Empty) { return PatternLookupResult.NoResults; } // we have succeeded or almost succeeded to bind the method // report additional binding diagnostics that we have seen so far diagnostics.AddRange(bindingDiagnostics); var patternMethodSymbol = call.Method; if (patternMethodSymbol is ErrorMethodSymbol || patternMethodCall.HasAnyErrors) { return PatternLookupResult.ResultHasErrors; } // Success! result = patternMethodSymbol; return PatternLookupResult.Success; } finally { bindingDiagnostics.Free(); } } } }
1
dotnet/roslyn
55,256
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-30T00:02:02Z
2021-07-30T09:17:54Z
6ce9c0048d37026337701fac035ac0745f6fe49f
88b59775dc6375635957ef229116460f290072aa
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Compilers/CSharp/Portable/Binder/Semantics/Conversions/Conversions.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Immutable; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { internal sealed class Conversions : ConversionsBase { private readonly Binder _binder; public Conversions(Binder binder) : this(binder, currentRecursionDepth: 0, includeNullability: false, otherNullabilityOpt: null) { } private Conversions(Binder binder, int currentRecursionDepth, bool includeNullability, Conversions otherNullabilityOpt) : base(binder.Compilation.Assembly.CorLibrary, currentRecursionDepth, includeNullability, otherNullabilityOpt) { _binder = binder; } protected override ConversionsBase CreateInstance(int currentRecursionDepth) { return new Conversions(_binder, currentRecursionDepth, IncludeNullability, otherNullabilityOpt: null); } private CSharpCompilation Compilation { get { return _binder.Compilation; } } protected override ConversionsBase WithNullabilityCore(bool includeNullability) { Debug.Assert(IncludeNullability != includeNullability); return new Conversions(_binder, currentRecursionDepth, includeNullability, this); } public override Conversion GetMethodGroupDelegateConversion(BoundMethodGroup source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { // Must be a bona fide delegate type, not an expression tree type. if (!(destination.IsDelegateType() || destination.SpecialType == SpecialType.System_Delegate)) { return Conversion.NoConversion; } var (methodSymbol, isFunctionPointer, callingConventionInfo) = GetDelegateInvokeOrFunctionPointerMethodIfAvailable(source, destination, ref useSiteInfo); if ((object)methodSymbol == null) { return Conversion.NoConversion; } Debug.Assert(destination.SpecialType == SpecialType.System_Delegate || methodSymbol == ((NamedTypeSymbol)destination).DelegateInvokeMethod); var resolution = ResolveDelegateOrFunctionPointerMethodGroup(_binder, source, methodSymbol, isFunctionPointer, callingConventionInfo, ref useSiteInfo); var conversion = (resolution.IsEmpty || resolution.HasAnyErrors) ? Conversion.NoConversion : ToConversion(resolution.OverloadResolutionResult, resolution.MethodGroup, methodSymbol.ParameterCount); resolution.Free(); return conversion; } public override Conversion GetMethodGroupFunctionPointerConversion(BoundMethodGroup source, FunctionPointerTypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { var resolution = ResolveDelegateOrFunctionPointerMethodGroup( _binder, source, destination.Signature, isFunctionPointer: true, new CallingConventionInfo(destination.Signature.CallingConvention, destination.Signature.GetCallingConventionModifiers()), ref useSiteInfo); var conversion = (resolution.IsEmpty || resolution.HasAnyErrors) ? Conversion.NoConversion : ToConversion(resolution.OverloadResolutionResult, resolution.MethodGroup, destination.Signature.ParameterCount); resolution.Free(); return conversion; } protected override Conversion GetInterpolatedStringConversion(BoundUnconvertedInterpolatedString source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { if (destination is NamedTypeSymbol { IsInterpolatedStringHandlerType: true }) { return Conversion.InterpolatedStringHandler; } // An interpolated string expression may be converted to the types // System.IFormattable and System.FormattableString return (TypeSymbol.Equals(destination, Compilation.GetWellKnownType(WellKnownType.System_IFormattable), TypeCompareKind.ConsiderEverything) || TypeSymbol.Equals(destination, Compilation.GetWellKnownType(WellKnownType.System_FormattableString), TypeCompareKind.ConsiderEverything)) ? Conversion.InterpolatedString : Conversion.NoConversion; } /// <summary> /// Resolve method group based on the optional delegate invoke method. /// If the invoke method is null, ignore arguments in resolution. /// </summary> private static MethodGroupResolution ResolveDelegateOrFunctionPointerMethodGroup(Binder binder, BoundMethodGroup source, MethodSymbol delegateInvokeMethodOpt, bool isFunctionPointer, in CallingConventionInfo callingConventionInfo, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { if ((object)delegateInvokeMethodOpt != null) { var analyzedArguments = AnalyzedArguments.GetInstance(); GetDelegateOrFunctionPointerArguments(source.Syntax, analyzedArguments, delegateInvokeMethodOpt.Parameters, binder.Compilation); var resolution = binder.ResolveMethodGroup(source, analyzedArguments, useSiteInfo: ref useSiteInfo, inferWithDynamic: true, isMethodGroupConversion: true, returnRefKind: delegateInvokeMethodOpt.RefKind, returnType: delegateInvokeMethodOpt.ReturnType, isFunctionPointerResolution: isFunctionPointer, callingConventionInfo: callingConventionInfo); analyzedArguments.Free(); return resolution; } else { return binder.ResolveMethodGroup(source, analyzedArguments: null, isMethodGroupConversion: true, ref useSiteInfo); } } /// <summary> /// Return the Invoke method symbol if the type is a delegate /// type and the Invoke method is available, otherwise null. /// </summary> private (MethodSymbol, bool isFunctionPointer, CallingConventionInfo callingConventionInfo) GetDelegateInvokeOrFunctionPointerMethodIfAvailable( BoundMethodGroup methodGroup, TypeSymbol type, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { if (type is FunctionPointerTypeSymbol { Signature: { } signature }) { return (signature, true, new CallingConventionInfo(signature.CallingConvention, signature.GetCallingConventionModifiers())); } var delegateType = (type.SpecialType == SpecialType.System_Delegate) ? // https://github.com/dotnet/roslyn/issues/52869: Avoid calculating the delegate type multiple times during conversion. _binder.GetMethodGroupDelegateType(methodGroup, ref useSiteInfo) : type.GetDelegateType(); if ((object)delegateType == null) { return (null, false, default); } MethodSymbol methodSymbol = delegateType.DelegateInvokeMethod; if ((object)methodSymbol == null || methodSymbol.HasUseSiteError) { return (null, false, default); } return (methodSymbol, false, default); } public bool ReportDelegateOrFunctionPointerMethodGroupDiagnostics(Binder binder, BoundMethodGroup expr, TypeSymbol targetType, BindingDiagnosticBag diagnostics) { CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = binder.GetNewCompoundUseSiteInfo(diagnostics); var (invokeMethodOpt, isFunctionPointer, callingConventionInfo) = GetDelegateInvokeOrFunctionPointerMethodIfAvailable(expr, targetType, ref useSiteInfo); var resolution = ResolveDelegateOrFunctionPointerMethodGroup(binder, expr, invokeMethodOpt, isFunctionPointer, callingConventionInfo, ref useSiteInfo); diagnostics.Add(expr.Syntax, useSiteInfo); bool hasErrors = resolution.HasAnyErrors; diagnostics.AddRange(resolution.Diagnostics); // SPEC VIOLATION: Unfortunately, we cannot exactly implement the specification for // the scenario in which an extension method that extends a value type is converted // to a delegate. The code we generate that captures a delegate to a static method // that is "partially evaluated" with the bound-to-the-delegate first argument // requires that the first argument be of reference type. // // SPEC VIOLATION: Similarly, we cannot capture a method of Nullable<T>, because // boxing a Nullable<T> gives a T, not a boxed Nullable<T>. // // We give special error messages in these situations. if (resolution.MethodGroup != null) { var result = resolution.OverloadResolutionResult; if (result != null) { if (result.Succeeded) { var method = result.BestResult.Member; Debug.Assert((object)method != null); if (resolution.MethodGroup.IsExtensionMethodGroup) { Debug.Assert(method.IsExtensionMethod); var thisParameter = method.Parameters[0]; if (!thisParameter.Type.IsReferenceType) { // Extension method '{0}' defined on value type '{1}' cannot be used to create delegates diagnostics.Add( ErrorCode.ERR_ValueTypeExtDelegate, expr.Syntax.Location, method, thisParameter.Type); hasErrors = true; } } else if (method.ContainingType.IsNullableType() && !method.IsOverride) { // CS1728: Cannot bind delegate to '{0}' because it is a member of 'System.Nullable<T>' diagnostics.Add( ErrorCode.ERR_DelegateOnNullable, expr.Syntax.Location, method); hasErrors = true; } } else if (!hasErrors && !resolution.IsEmpty && resolution.ResultKind == LookupResultKind.Viable) { var overloadDiagnostics = BindingDiagnosticBag.GetInstance(withDiagnostics: true, diagnostics.AccumulatesDependencies); result.ReportDiagnostics( binder: binder, location: expr.Syntax.Location, nodeOpt: expr.Syntax, diagnostics: overloadDiagnostics, name: expr.Name, receiver: resolution.MethodGroup.Receiver, invokedExpression: expr.Syntax, arguments: resolution.AnalyzedArguments, memberGroup: resolution.MethodGroup.Methods.ToImmutable(), typeContainingConstructor: null, delegateTypeBeingInvoked: null, isMethodGroupConversion: true, returnRefKind: invokeMethodOpt?.RefKind, delegateOrFunctionPointerType: targetType); hasErrors = overloadDiagnostics.HasAnyErrors(); diagnostics.AddRangeAndFree(overloadDiagnostics); } } } resolution.Free(); return hasErrors; } public Conversion MethodGroupConversion(SyntaxNode syntax, MethodGroup methodGroup, NamedTypeSymbol delegateType, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { var analyzedArguments = AnalyzedArguments.GetInstance(); var result = OverloadResolutionResult<MethodSymbol>.GetInstance(); var delegateInvokeMethod = delegateType.DelegateInvokeMethod; Debug.Assert((object)delegateInvokeMethod != null && !delegateInvokeMethod.HasUseSiteError, "This method should only be called for valid delegate types"); GetDelegateOrFunctionPointerArguments(syntax, analyzedArguments, delegateInvokeMethod.Parameters, Compilation); _binder.OverloadResolution.MethodInvocationOverloadResolution( methods: methodGroup.Methods, typeArguments: methodGroup.TypeArguments, receiver: methodGroup.Receiver, arguments: analyzedArguments, result: result, useSiteInfo: ref useSiteInfo, isMethodGroupConversion: true, returnRefKind: delegateInvokeMethod.RefKind, returnType: delegateInvokeMethod.ReturnType); var conversion = ToConversion(result, methodGroup, delegateType.DelegateInvokeMethod.ParameterCount); analyzedArguments.Free(); result.Free(); return conversion; } public static void GetDelegateOrFunctionPointerArguments(SyntaxNode syntax, AnalyzedArguments analyzedArguments, ImmutableArray<ParameterSymbol> delegateParameters, CSharpCompilation compilation) { foreach (var p in delegateParameters) { ParameterSymbol parameter = p; // In ExpressionBinder::BindGrpConversion, the native compiler substitutes object in place of dynamic. This is // necessary because conversions from expressions of type dynamic always succeed, whereas conversions from the // type generally fail (modulo identity conversions). This is not reflected in the C# 4 spec, but will be // incorporated going forward. See DevDiv #742345 for additional details. // NOTE: Dev11 does a deep substitution (e.g. C<C<C<dynamic>>> -> C<C<C<object>>>), but that seems redundant. if (parameter.Type.IsDynamic()) { // If we don't have System.Object, then we'll get an error type, which will cause overload resolution to fail, // which will cause some error to be reported. That's sufficient (i.e. no need to specifically report its absence here). parameter = new SignatureOnlyParameterSymbol( TypeWithAnnotations.Create(compilation.GetSpecialType(SpecialType.System_Object), customModifiers: parameter.TypeWithAnnotations.CustomModifiers), parameter.RefCustomModifiers, parameter.IsParams, parameter.RefKind); } analyzedArguments.Arguments.Add(new BoundParameter(syntax, parameter) { WasCompilerGenerated = true }); analyzedArguments.RefKinds.Add(parameter.RefKind); } } private static Conversion ToConversion(OverloadResolutionResult<MethodSymbol> result, MethodGroup methodGroup, int parameterCount) { // 6.6 An implicit conversion (6.1) exists from a method group (7.1) to a compatible // delegate type. Given a delegate type D and an expression E that is classified as // a method group, an implicit conversion exists from E to D if E contains at least // one method that is applicable in its normal form (7.5.3.1) to an argument list // constructed by use of the parameter types and modifiers of D... // SPEC VIOLATION: Unfortunately, we cannot exactly implement the specification for // the scenario in which an extension method that extends a value type is converted // to a delegate. The code we generate that captures a delegate to a static method // that is "partially evaluated" with the bound-to-the-delegate first argument // requires that the first argument be of reference type. // SPEC VIOLATION: Similarly, we cannot capture a method of Nullable<T>, because // boxing a Nullable<T> gives a T, not a boxed Nullable<T>. (We can capture methods // of object on a nullable receiver, but not GetValueOrDefault.) if (!result.Succeeded) { return Conversion.NoConversion; } MethodSymbol method = result.BestResult.Member; if (methodGroup.IsExtensionMethodGroup && !method.Parameters[0].Type.IsReferenceType) { return Conversion.NoConversion; } //cannot capture stack-only types. if (method.RequiresInstanceReceiver && methodGroup.Receiver?.Type?.IsRestrictedType() == true) { return Conversion.NoConversion; } if (method.ContainingType.IsNullableType() && !method.IsOverride) { return Conversion.NoConversion; } // NOTE: Section 6.6 will be slightly updated: // // - The candidate methods considered are only those methods that are applicable in their // normal form (§7.5.3.1), and do not omit any optional parameters. Thus, candidate methods // are ignored if they are applicable only in their expanded form, or if one or more of their // optional parameters do not have a corresponding parameter in the targeted delegate type. // // Therefore, we shouldn't get here unless the parameter count matches. // NOTE: Delegate type compatibility is important, but is not part of the existence check. Debug.Assert(method.ParameterCount == parameterCount + (methodGroup.IsExtensionMethodGroup ? 1 : 0)); return new Conversion(ConversionKind.MethodGroup, method, methodGroup.IsExtensionMethodGroup); } public override Conversion GetStackAllocConversion(BoundStackAllocArrayCreation sourceExpression, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { if (sourceExpression.NeedsToBeConverted()) { Debug.Assert((object)sourceExpression.Type == null); Debug.Assert((object)sourceExpression.ElementType != null); var sourceAsPointer = new PointerTypeSymbol(TypeWithAnnotations.Create(sourceExpression.ElementType)); var pointerConversion = ClassifyImplicitConversionFromType(sourceAsPointer, destination, ref useSiteInfo); if (pointerConversion.IsValid) { return Conversion.MakeStackAllocToPointerType(pointerConversion); } else { var spanType = _binder.GetWellKnownType(WellKnownType.System_Span_T, ref useSiteInfo); if (spanType.TypeKind == TypeKind.Struct && spanType.IsRefLikeType) { var spanType_T = spanType.Construct(sourceExpression.ElementType); var spanConversion = ClassifyImplicitConversionFromType(spanType_T, destination, ref useSiteInfo); if (spanConversion.Exists) { return Conversion.MakeStackAllocToSpanType(spanConversion); } } } } return Conversion.NoConversion; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Immutable; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { internal sealed class Conversions : ConversionsBase { private readonly Binder _binder; public Conversions(Binder binder) : this(binder, currentRecursionDepth: 0, includeNullability: false, otherNullabilityOpt: null) { } private Conversions(Binder binder, int currentRecursionDepth, bool includeNullability, Conversions otherNullabilityOpt) : base(binder.Compilation.Assembly.CorLibrary, currentRecursionDepth, includeNullability, otherNullabilityOpt) { _binder = binder; } protected override ConversionsBase CreateInstance(int currentRecursionDepth) { return new Conversions(_binder, currentRecursionDepth, IncludeNullability, otherNullabilityOpt: null); } private CSharpCompilation Compilation { get { return _binder.Compilation; } } protected override ConversionsBase WithNullabilityCore(bool includeNullability) { Debug.Assert(IncludeNullability != includeNullability); return new Conversions(_binder, currentRecursionDepth, includeNullability, this); } public override Conversion GetMethodGroupDelegateConversion(BoundMethodGroup source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { // Must be a bona fide delegate type, not an expression tree type. if (!(destination.IsDelegateType() || (destination.SpecialType == SpecialType.System_Delegate && IsFeatureInferredDelegateTypeEnabled(source)))) { return Conversion.NoConversion; } var (methodSymbol, isFunctionPointer, callingConventionInfo) = GetDelegateInvokeOrFunctionPointerMethodIfAvailable(source, destination, ref useSiteInfo); if ((object)methodSymbol == null) { return Conversion.NoConversion; } Debug.Assert(destination.SpecialType == SpecialType.System_Delegate || methodSymbol == ((NamedTypeSymbol)destination).DelegateInvokeMethod); var resolution = ResolveDelegateOrFunctionPointerMethodGroup(_binder, source, methodSymbol, isFunctionPointer, callingConventionInfo, ref useSiteInfo); var conversion = (resolution.IsEmpty || resolution.HasAnyErrors) ? Conversion.NoConversion : ToConversion(resolution.OverloadResolutionResult, resolution.MethodGroup, methodSymbol.ParameterCount); resolution.Free(); return conversion; } public override Conversion GetMethodGroupFunctionPointerConversion(BoundMethodGroup source, FunctionPointerTypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { var resolution = ResolveDelegateOrFunctionPointerMethodGroup( _binder, source, destination.Signature, isFunctionPointer: true, new CallingConventionInfo(destination.Signature.CallingConvention, destination.Signature.GetCallingConventionModifiers()), ref useSiteInfo); var conversion = (resolution.IsEmpty || resolution.HasAnyErrors) ? Conversion.NoConversion : ToConversion(resolution.OverloadResolutionResult, resolution.MethodGroup, destination.Signature.ParameterCount); resolution.Free(); return conversion; } protected override Conversion GetInterpolatedStringConversion(BoundUnconvertedInterpolatedString source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { if (destination is NamedTypeSymbol { IsInterpolatedStringHandlerType: true }) { return Conversion.InterpolatedStringHandler; } // An interpolated string expression may be converted to the types // System.IFormattable and System.FormattableString return (TypeSymbol.Equals(destination, Compilation.GetWellKnownType(WellKnownType.System_IFormattable), TypeCompareKind.ConsiderEverything) || TypeSymbol.Equals(destination, Compilation.GetWellKnownType(WellKnownType.System_FormattableString), TypeCompareKind.ConsiderEverything)) ? Conversion.InterpolatedString : Conversion.NoConversion; } /// <summary> /// Resolve method group based on the optional delegate invoke method. /// If the invoke method is null, ignore arguments in resolution. /// </summary> private static MethodGroupResolution ResolveDelegateOrFunctionPointerMethodGroup(Binder binder, BoundMethodGroup source, MethodSymbol delegateInvokeMethodOpt, bool isFunctionPointer, in CallingConventionInfo callingConventionInfo, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { if ((object)delegateInvokeMethodOpt != null) { var analyzedArguments = AnalyzedArguments.GetInstance(); GetDelegateOrFunctionPointerArguments(source.Syntax, analyzedArguments, delegateInvokeMethodOpt.Parameters, binder.Compilation); var resolution = binder.ResolveMethodGroup(source, analyzedArguments, useSiteInfo: ref useSiteInfo, inferWithDynamic: true, isMethodGroupConversion: true, returnRefKind: delegateInvokeMethodOpt.RefKind, returnType: delegateInvokeMethodOpt.ReturnType, isFunctionPointerResolution: isFunctionPointer, callingConventionInfo: callingConventionInfo); analyzedArguments.Free(); return resolution; } else { return binder.ResolveMethodGroup(source, analyzedArguments: null, isMethodGroupConversion: true, ref useSiteInfo); } } /// <summary> /// Return the Invoke method symbol if the type is a delegate /// type and the Invoke method is available, otherwise null. /// </summary> private (MethodSymbol, bool isFunctionPointer, CallingConventionInfo callingConventionInfo) GetDelegateInvokeOrFunctionPointerMethodIfAvailable( BoundMethodGroup methodGroup, TypeSymbol type, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { if (type is FunctionPointerTypeSymbol { Signature: { } signature }) { return (signature, true, new CallingConventionInfo(signature.CallingConvention, signature.GetCallingConventionModifiers())); } var delegateType = (type.SpecialType == SpecialType.System_Delegate) && methodGroup.Syntax.IsFeatureEnabled(MessageID.IDS_FeatureNullableReferenceTypes) ? // https://github.com/dotnet/roslyn/issues/52869: Avoid calculating the delegate type multiple times during conversion. _binder.GetMethodGroupDelegateType(methodGroup, ref useSiteInfo) : type.GetDelegateType(); if ((object)delegateType == null) { return (null, false, default); } MethodSymbol methodSymbol = delegateType.DelegateInvokeMethod; if ((object)methodSymbol == null || methodSymbol.HasUseSiteError) { return (null, false, default); } return (methodSymbol, false, default); } public bool ReportDelegateOrFunctionPointerMethodGroupDiagnostics(Binder binder, BoundMethodGroup expr, TypeSymbol targetType, BindingDiagnosticBag diagnostics) { CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = binder.GetNewCompoundUseSiteInfo(diagnostics); var (invokeMethodOpt, isFunctionPointer, callingConventionInfo) = GetDelegateInvokeOrFunctionPointerMethodIfAvailable(expr, targetType, ref useSiteInfo); var resolution = ResolveDelegateOrFunctionPointerMethodGroup(binder, expr, invokeMethodOpt, isFunctionPointer, callingConventionInfo, ref useSiteInfo); diagnostics.Add(expr.Syntax, useSiteInfo); bool hasErrors = resolution.HasAnyErrors; diagnostics.AddRange(resolution.Diagnostics); // SPEC VIOLATION: Unfortunately, we cannot exactly implement the specification for // the scenario in which an extension method that extends a value type is converted // to a delegate. The code we generate that captures a delegate to a static method // that is "partially evaluated" with the bound-to-the-delegate first argument // requires that the first argument be of reference type. // // SPEC VIOLATION: Similarly, we cannot capture a method of Nullable<T>, because // boxing a Nullable<T> gives a T, not a boxed Nullable<T>. // // We give special error messages in these situations. if (resolution.MethodGroup != null) { var result = resolution.OverloadResolutionResult; if (result != null) { if (result.Succeeded) { var method = result.BestResult.Member; Debug.Assert((object)method != null); if (resolution.MethodGroup.IsExtensionMethodGroup) { Debug.Assert(method.IsExtensionMethod); var thisParameter = method.Parameters[0]; if (!thisParameter.Type.IsReferenceType) { // Extension method '{0}' defined on value type '{1}' cannot be used to create delegates diagnostics.Add( ErrorCode.ERR_ValueTypeExtDelegate, expr.Syntax.Location, method, thisParameter.Type); hasErrors = true; } } else if (method.ContainingType.IsNullableType() && !method.IsOverride) { // CS1728: Cannot bind delegate to '{0}' because it is a member of 'System.Nullable<T>' diagnostics.Add( ErrorCode.ERR_DelegateOnNullable, expr.Syntax.Location, method); hasErrors = true; } } else if (!hasErrors && !resolution.IsEmpty && resolution.ResultKind == LookupResultKind.Viable) { var overloadDiagnostics = BindingDiagnosticBag.GetInstance(withDiagnostics: true, diagnostics.AccumulatesDependencies); result.ReportDiagnostics( binder: binder, location: expr.Syntax.Location, nodeOpt: expr.Syntax, diagnostics: overloadDiagnostics, name: expr.Name, receiver: resolution.MethodGroup.Receiver, invokedExpression: expr.Syntax, arguments: resolution.AnalyzedArguments, memberGroup: resolution.MethodGroup.Methods.ToImmutable(), typeContainingConstructor: null, delegateTypeBeingInvoked: null, isMethodGroupConversion: true, returnRefKind: invokeMethodOpt?.RefKind, delegateOrFunctionPointerType: targetType); hasErrors = overloadDiagnostics.HasAnyErrors(); diagnostics.AddRangeAndFree(overloadDiagnostics); } } } resolution.Free(); return hasErrors; } public Conversion MethodGroupConversion(SyntaxNode syntax, MethodGroup methodGroup, NamedTypeSymbol delegateType, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { var analyzedArguments = AnalyzedArguments.GetInstance(); var result = OverloadResolutionResult<MethodSymbol>.GetInstance(); var delegateInvokeMethod = delegateType.DelegateInvokeMethod; Debug.Assert((object)delegateInvokeMethod != null && !delegateInvokeMethod.HasUseSiteError, "This method should only be called for valid delegate types"); GetDelegateOrFunctionPointerArguments(syntax, analyzedArguments, delegateInvokeMethod.Parameters, Compilation); _binder.OverloadResolution.MethodInvocationOverloadResolution( methods: methodGroup.Methods, typeArguments: methodGroup.TypeArguments, receiver: methodGroup.Receiver, arguments: analyzedArguments, result: result, useSiteInfo: ref useSiteInfo, isMethodGroupConversion: true, returnRefKind: delegateInvokeMethod.RefKind, returnType: delegateInvokeMethod.ReturnType); var conversion = ToConversion(result, methodGroup, delegateType.DelegateInvokeMethod.ParameterCount); analyzedArguments.Free(); result.Free(); return conversion; } public static void GetDelegateOrFunctionPointerArguments(SyntaxNode syntax, AnalyzedArguments analyzedArguments, ImmutableArray<ParameterSymbol> delegateParameters, CSharpCompilation compilation) { foreach (var p in delegateParameters) { ParameterSymbol parameter = p; // In ExpressionBinder::BindGrpConversion, the native compiler substitutes object in place of dynamic. This is // necessary because conversions from expressions of type dynamic always succeed, whereas conversions from the // type generally fail (modulo identity conversions). This is not reflected in the C# 4 spec, but will be // incorporated going forward. See DevDiv #742345 for additional details. // NOTE: Dev11 does a deep substitution (e.g. C<C<C<dynamic>>> -> C<C<C<object>>>), but that seems redundant. if (parameter.Type.IsDynamic()) { // If we don't have System.Object, then we'll get an error type, which will cause overload resolution to fail, // which will cause some error to be reported. That's sufficient (i.e. no need to specifically report its absence here). parameter = new SignatureOnlyParameterSymbol( TypeWithAnnotations.Create(compilation.GetSpecialType(SpecialType.System_Object), customModifiers: parameter.TypeWithAnnotations.CustomModifiers), parameter.RefCustomModifiers, parameter.IsParams, parameter.RefKind); } analyzedArguments.Arguments.Add(new BoundParameter(syntax, parameter) { WasCompilerGenerated = true }); analyzedArguments.RefKinds.Add(parameter.RefKind); } } private static Conversion ToConversion(OverloadResolutionResult<MethodSymbol> result, MethodGroup methodGroup, int parameterCount) { // 6.6 An implicit conversion (6.1) exists from a method group (7.1) to a compatible // delegate type. Given a delegate type D and an expression E that is classified as // a method group, an implicit conversion exists from E to D if E contains at least // one method that is applicable in its normal form (7.5.3.1) to an argument list // constructed by use of the parameter types and modifiers of D... // SPEC VIOLATION: Unfortunately, we cannot exactly implement the specification for // the scenario in which an extension method that extends a value type is converted // to a delegate. The code we generate that captures a delegate to a static method // that is "partially evaluated" with the bound-to-the-delegate first argument // requires that the first argument be of reference type. // SPEC VIOLATION: Similarly, we cannot capture a method of Nullable<T>, because // boxing a Nullable<T> gives a T, not a boxed Nullable<T>. (We can capture methods // of object on a nullable receiver, but not GetValueOrDefault.) if (!result.Succeeded) { return Conversion.NoConversion; } MethodSymbol method = result.BestResult.Member; if (methodGroup.IsExtensionMethodGroup && !method.Parameters[0].Type.IsReferenceType) { return Conversion.NoConversion; } //cannot capture stack-only types. if (method.RequiresInstanceReceiver && methodGroup.Receiver?.Type?.IsRestrictedType() == true) { return Conversion.NoConversion; } if (method.ContainingType.IsNullableType() && !method.IsOverride) { return Conversion.NoConversion; } // NOTE: Section 6.6 will be slightly updated: // // - The candidate methods considered are only those methods that are applicable in their // normal form (§7.5.3.1), and do not omit any optional parameters. Thus, candidate methods // are ignored if they are applicable only in their expanded form, or if one or more of their // optional parameters do not have a corresponding parameter in the targeted delegate type. // // Therefore, we shouldn't get here unless the parameter count matches. // NOTE: Delegate type compatibility is important, but is not part of the existence check. Debug.Assert(method.ParameterCount == parameterCount + (methodGroup.IsExtensionMethodGroup ? 1 : 0)); return new Conversion(ConversionKind.MethodGroup, method, methodGroup.IsExtensionMethodGroup); } public override Conversion GetStackAllocConversion(BoundStackAllocArrayCreation sourceExpression, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { if (sourceExpression.NeedsToBeConverted()) { Debug.Assert((object)sourceExpression.Type == null); Debug.Assert((object)sourceExpression.ElementType != null); var sourceAsPointer = new PointerTypeSymbol(TypeWithAnnotations.Create(sourceExpression.ElementType)); var pointerConversion = ClassifyImplicitConversionFromType(sourceAsPointer, destination, ref useSiteInfo); if (pointerConversion.IsValid) { return Conversion.MakeStackAllocToPointerType(pointerConversion); } else { var spanType = _binder.GetWellKnownType(WellKnownType.System_Span_T, ref useSiteInfo); if (spanType.TypeKind == TypeKind.Struct && spanType.IsRefLikeType) { var spanType_T = spanType.Construct(sourceExpression.ElementType); var spanConversion = ClassifyImplicitConversionFromType(spanType_T, destination, ref useSiteInfo); if (spanConversion.Exists) { return Conversion.MakeStackAllocToSpanType(spanConversion); } } } } return Conversion.NoConversion; } } }
1
dotnet/roslyn
55,256
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-30T00:02:02Z
2021-07-30T09:17:54Z
6ce9c0048d37026337701fac035ac0745f6fe49f
88b59775dc6375635957ef229116460f290072aa
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Compilers/CSharp/Portable/Binder/Semantics/Conversions/ConversionsBase.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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 System.Diagnostics.CodeAnalysis; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { internal abstract partial class ConversionsBase { private const int MaximumRecursionDepth = 50; protected readonly AssemblySymbol corLibrary; protected readonly int currentRecursionDepth; internal readonly bool IncludeNullability; /// <summary> /// An optional clone of this instance with distinct IncludeNullability. /// Used to avoid unnecessary allocations when calling WithNullability() repeatedly. /// </summary> private ConversionsBase _lazyOtherNullability; protected ConversionsBase(AssemblySymbol corLibrary, int currentRecursionDepth, bool includeNullability, ConversionsBase otherNullabilityOpt) { Debug.Assert((object)corLibrary != null); Debug.Assert(otherNullabilityOpt == null || includeNullability != otherNullabilityOpt.IncludeNullability); Debug.Assert(otherNullabilityOpt == null || currentRecursionDepth == otherNullabilityOpt.currentRecursionDepth); this.corLibrary = corLibrary; this.currentRecursionDepth = currentRecursionDepth; IncludeNullability = includeNullability; _lazyOtherNullability = otherNullabilityOpt; } /// <summary> /// Returns this instance if includeNullability is correct, and returns a /// cached clone of this instance with distinct IncludeNullability otherwise. /// </summary> internal ConversionsBase WithNullability(bool includeNullability) { if (IncludeNullability == includeNullability) { return this; } if (_lazyOtherNullability == null) { Interlocked.CompareExchange(ref _lazyOtherNullability, WithNullabilityCore(includeNullability), null); } Debug.Assert(_lazyOtherNullability.IncludeNullability == includeNullability); Debug.Assert(_lazyOtherNullability._lazyOtherNullability == this); return _lazyOtherNullability; } protected abstract ConversionsBase WithNullabilityCore(bool includeNullability); public abstract Conversion GetMethodGroupDelegateConversion(BoundMethodGroup source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo); public abstract Conversion GetMethodGroupFunctionPointerConversion(BoundMethodGroup source, FunctionPointerTypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo); public abstract Conversion GetStackAllocConversion(BoundStackAllocArrayCreation sourceExpression, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo); protected abstract ConversionsBase CreateInstance(int currentRecursionDepth); protected abstract Conversion GetInterpolatedStringConversion(BoundUnconvertedInterpolatedString source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo); internal AssemblySymbol CorLibrary { get { return corLibrary; } } /// <summary> /// Determines if the source expression is convertible to the destination type via /// any built-in or user-defined implicit conversion. /// </summary> public Conversion ClassifyImplicitConversionFromExpression(BoundExpression sourceExpression, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(sourceExpression != null); Debug.Assert((object)destination != null); var sourceType = sourceExpression.Type; //PERF: identity conversion is by far the most common implicit conversion, check for that first if ((object)sourceType != null && HasIdentityConversionInternal(sourceType, destination)) { return Conversion.Identity; } Conversion conversion = ClassifyImplicitBuiltInConversionFromExpression(sourceExpression, sourceType, destination, ref useSiteInfo); if (conversion.Exists) { return conversion; } if ((object)sourceType != null) { // Try using the short-circuit "fast-conversion" path. Conversion fastConversion = FastClassifyConversion(sourceType, destination); if (fastConversion.Exists) { if (fastConversion.IsImplicit) { return fastConversion; } } else { conversion = ClassifyImplicitBuiltInConversionSlow(sourceType, destination, ref useSiteInfo); if (conversion.Exists) { return conversion; } } } conversion = GetImplicitUserDefinedConversion(sourceExpression, sourceType, destination, ref useSiteInfo); if (conversion.Exists) { return conversion; } // The switch expression conversion is "lowest priority", so that if there is a conversion from the expression's // type it will be preferred over the switch expression conversion. Technically, we would want the language // specification to say that the switch expression conversion only "exists" if there is no implicit conversion // from the type, and we accomplish that by making it lowest priority. The same is true for the conditional // expression conversion. conversion = GetSwitchExpressionConversion(sourceExpression, destination, ref useSiteInfo); if (conversion.Exists) { return conversion; } return GetConditionalExpressionConversion(sourceExpression, destination, ref useSiteInfo); } /// <summary> /// Determines if the source type is convertible to the destination type via /// any built-in or user-defined implicit conversion. /// </summary> public Conversion ClassifyImplicitConversionFromType(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); //PERF: identity conversions are very common, check for that first. if (HasIdentityConversionInternal(source, destination)) { return Conversion.Identity; } // Try using the short-circuit "fast-conversion" path. Conversion fastConversion = FastClassifyConversion(source, destination); if (fastConversion.Exists) { return fastConversion.IsImplicit ? fastConversion : Conversion.NoConversion; } else { Conversion conversion = ClassifyImplicitBuiltInConversionSlow(source, destination, ref useSiteInfo); if (conversion.Exists) { return conversion; } } return GetImplicitUserDefinedConversion(null, source, destination, ref useSiteInfo); } /// <summary> /// Determines if the source expression of given type is convertible to the destination type via /// any built-in or user-defined conversion. /// /// This helper is used in rare cases involving synthesized expressions where we know the type of an expression, but do not have the actual expression. /// The reason for this helper (as opposed to ClassifyConversionFromType) is that conversions from expressions could be different /// from conversions from type. For example expressions of dynamic type are implicitly convertable to any type, while dynamic type itself is not. /// </summary> public Conversion ClassifyConversionFromExpressionType(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); // since we are converting from expression, we may have implicit dynamic conversion if (HasImplicitDynamicConversionFromExpression(source, destination)) { return Conversion.ImplicitDynamic; } return ClassifyConversionFromType(source, destination, ref useSiteInfo); } private static bool TryGetVoidConversion(TypeSymbol source, TypeSymbol destination, out Conversion conversion) { var sourceIsVoid = source?.SpecialType == SpecialType.System_Void; var destIsVoid = destination.SpecialType == SpecialType.System_Void; // 'void' is not supposed to be able to convert to or from anything, but in practice, // a lot of code depends on checking whether an expression of type 'void' is convertible to 'void'. // (e.g. for an expression lambda which returns void). // Therefore we allow an identity conversion between 'void' and 'void'. if (sourceIsVoid && destIsVoid) { conversion = Conversion.Identity; return true; } // If exactly one of source or destination is of type 'void' then no conversion may exist. if (sourceIsVoid || destIsVoid) { conversion = Conversion.NoConversion; return true; } conversion = default; return false; } /// <summary> /// Determines if the source expression is convertible to the destination type via /// any conversion: implicit, explicit, user-defined or built-in. /// </summary> /// <remarks> /// It is rare but possible for a source expression to be convertible to a destination type /// by both an implicit user-defined conversion and a built-in explicit conversion. /// In that circumstance, this method classifies the conversion as the implicit conversion or explicit depending on "forCast" /// </remarks> public Conversion ClassifyConversionFromExpression(BoundExpression sourceExpression, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, bool forCast = false) { Debug.Assert(sourceExpression != null); Debug.Assert((object)destination != null); if (TryGetVoidConversion(sourceExpression.Type, destination, out var conversion)) { return conversion; } if (forCast) { return ClassifyConversionFromExpressionForCast(sourceExpression, destination, ref useSiteInfo); } var result = ClassifyImplicitConversionFromExpression(sourceExpression, destination, ref useSiteInfo); if (result.Exists) { return result; } return ClassifyExplicitOnlyConversionFromExpression(sourceExpression, destination, ref useSiteInfo, forCast: false); } /// <summary> /// Determines if the source type is convertible to the destination type via /// any conversion: implicit, explicit, user-defined or built-in. /// </summary> /// <remarks> /// It is rare but possible for a source type to be convertible to a destination type /// by both an implicit user-defined conversion and a built-in explicit conversion. /// In that circumstance, this method classifies the conversion as the implicit conversion or explicit depending on "forCast" /// </remarks> public Conversion ClassifyConversionFromType(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, bool forCast = false) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); if (TryGetVoidConversion(source, destination, out var voidConversion)) { return voidConversion; } if (forCast) { return ClassifyConversionFromTypeForCast(source, destination, ref useSiteInfo); } // Try using the short-circuit "fast-conversion" path. Conversion fastConversion = FastClassifyConversion(source, destination); if (fastConversion.Exists) { return fastConversion; } else { Conversion conversion1 = ClassifyImplicitBuiltInConversionSlow(source, destination, ref useSiteInfo); if (conversion1.Exists) { return conversion1; } } Conversion conversion = GetImplicitUserDefinedConversion(null, source, destination, ref useSiteInfo); if (conversion.Exists) { return conversion; } conversion = ClassifyExplicitBuiltInOnlyConversion(source, destination, ref useSiteInfo, forCast: false); if (conversion.Exists) { return conversion; } return GetExplicitUserDefinedConversion(null, source, destination, ref useSiteInfo); } /// <summary> /// Determines if the source expression is convertible to the destination type via /// any conversion: implicit, explicit, user-defined or built-in. /// </summary> /// <remarks> /// It is rare but possible for a source expression to be convertible to a destination type /// by both an implicit user-defined conversion and a built-in explicit conversion. /// In that circumstance, this method classifies the conversion as the built-in conversion. /// /// An implicit conversion exists from an expression of a dynamic type to any type. /// An explicit conversion exists from a dynamic type to any type. /// When casting we prefer the explicit conversion. /// </remarks> private Conversion ClassifyConversionFromExpressionForCast(BoundExpression source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(source != null); Debug.Assert((object)destination != null); Conversion implicitConversion = ClassifyImplicitConversionFromExpression(source, destination, ref useSiteInfo); if (implicitConversion.Exists && !ExplicitConversionMayDifferFromImplicit(implicitConversion)) { return implicitConversion; } Conversion explicitConversion = ClassifyExplicitOnlyConversionFromExpression(source, destination, ref useSiteInfo, forCast: true); if (explicitConversion.Exists) { return explicitConversion; } // It is possible for a user-defined conversion to be unambiguous when considered as // an implicit conversion and ambiguous when considered as an explicit conversion. // The native compiler does not check to see if a cast could be successfully bound as // an unambiguous user-defined implicit conversion; it goes right to the ambiguous // user-defined explicit conversion and produces an error. This means that in // C# 5 it is possible to have: // // Y y = new Y(); // Z z1 = y; // // succeed but // // Z z2 = (Z)y; // // fail. // // However, there is another interesting wrinkle. It is possible for both // an implicit user-defined conversion and an explicit user-defined conversion // to exist and be unambiguous. For example, if there is an implicit conversion // double-->C and an explicit conversion from int-->C, and the user casts a short // to C, then both the implicit and explicit conversions are applicable and // unambiguous. The native compiler in this case prefers the explicit conversion, // and for backwards compatibility, we match it. return implicitConversion; } /// <summary> /// Determines if the source type is convertible to the destination type via /// any conversion: implicit, explicit, user-defined or built-in. /// </summary> /// <remarks> /// It is rare but possible for a source type to be convertible to a destination type /// by both an implicit user-defined conversion and a built-in explicit conversion. /// In that circumstance, this method classifies the conversion as the built-in conversion. /// </remarks> private Conversion ClassifyConversionFromTypeForCast(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); // Try using the short-circuit "fast-conversion" path. Conversion fastConversion = FastClassifyConversion(source, destination); if (fastConversion.Exists) { return fastConversion; } Conversion implicitBuiltInConversion = ClassifyImplicitBuiltInConversionSlow(source, destination, ref useSiteInfo); if (implicitBuiltInConversion.Exists && !ExplicitConversionMayDifferFromImplicit(implicitBuiltInConversion)) { return implicitBuiltInConversion; } Conversion explicitBuiltInConversion = ClassifyExplicitBuiltInOnlyConversion(source, destination, ref useSiteInfo, forCast: true); if (explicitBuiltInConversion.Exists) { return explicitBuiltInConversion; } if (implicitBuiltInConversion.Exists) { return implicitBuiltInConversion; } // It is possible for a user-defined conversion to be unambiguous when considered as // an implicit conversion and ambiguous when considered as an explicit conversion. // The native compiler does not check to see if a cast could be successfully bound as // an unambiguous user-defined implicit conversion; it goes right to the ambiguous // user-defined explicit conversion and produces an error. This means that in // C# 5 it is possible to have: // // Y y = new Y(); // Z z1 = y; // // succeed but // // Z z2 = (Z)y; // // fail. var conversion = GetExplicitUserDefinedConversion(null, source, destination, ref useSiteInfo); if (conversion.Exists) { return conversion; } return GetImplicitUserDefinedConversion(null, source, destination, ref useSiteInfo); } /// <summary> /// Attempt a quick classification of builtin conversions. As result of "no conversion" /// means that there is no built-in conversion, though there still may be a user-defined /// conversion if compiling against a custom mscorlib. /// </summary> public static Conversion FastClassifyConversion(TypeSymbol source, TypeSymbol target) { ConversionKind convKind = ConversionEasyOut.ClassifyConversion(source, target); if (convKind != ConversionKind.ImplicitNullable && convKind != ConversionKind.ExplicitNullable) { return Conversion.GetTrivialConversion(convKind); } return Conversion.MakeNullableConversion(convKind, FastClassifyConversion(source.StrippedType(), target.StrippedType())); } public Conversion ClassifyBuiltInConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); // Try using the short-circuit "fast-conversion" path. Conversion fastConversion = FastClassifyConversion(source, destination); if (fastConversion.Exists) { return fastConversion; } else { Conversion conversion = ClassifyImplicitBuiltInConversionSlow(source, destination, ref useSiteInfo); if (conversion.Exists) { return conversion; } } return ClassifyExplicitBuiltInOnlyConversion(source, destination, ref useSiteInfo, forCast: false); } /// <summary> /// Determines if the source type is convertible to the destination type via /// any standard implicit or standard explicit conversion. /// </summary> /// <remarks> /// Not all built-in explicit conversions are standard explicit conversions. /// </remarks> public Conversion ClassifyStandardConversion(BoundExpression sourceExpression, TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(sourceExpression != null || (object)source != null); Debug.Assert((object)destination != null); // Note that the definition of explicit standard conversion does not include all explicit // reference conversions! There is a standard implicit reference conversion from // Action<Object> to Action<Exception>, thanks to contravariance. There is a standard // implicit reference conversion from Action<Object> to Action<String> for the same reason. // Therefore there is an explicit reference conversion from Action<Exception> to // Action<String>; a given Action<Exception> might be an Action<Object>, and hence // convertible to Action<String>. However, this is not a *standard* explicit conversion. The // standard explicit conversions are all the standard implicit conversions and their // opposites. Therefore Action<Object>-->Action<String> and Action<String>-->Action<Object> // are both standard conversions. But Action<String>-->Action<Exception> is not a standard // explicit conversion because neither it nor its opposite is a standard implicit // conversion. // // Similarly, there is no standard explicit conversion from double to decimal, because // there is no standard implicit conversion between the two types. // SPEC: The standard explicit conversions are all standard implicit conversions plus // SPEC: the subset of the explicit conversions for which an opposite standard implicit // SPEC: conversion exists. In other words, if a standard implicit conversion exists from // SPEC: a type A to a type B, then a standard explicit conversion exists from type A to // SPEC: type B and from type B to type A. Conversion conversion = ClassifyStandardImplicitConversion(sourceExpression, source, destination, ref useSiteInfo); if (conversion.Exists) { return conversion; } if ((object)source != null) { return DeriveStandardExplicitFromOppositeStandardImplicitConversion(source, destination, ref useSiteInfo); } return Conversion.NoConversion; } private Conversion ClassifyStandardImplicitConversion(BoundExpression sourceExpression, TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(sourceExpression != null || (object)source != null); Debug.Assert(sourceExpression == null || (object)sourceExpression.Type == (object)source); Debug.Assert((object)destination != null); // SPEC: The following implicit conversions are classified as standard implicit conversions: // SPEC: Identity conversions // SPEC: Implicit numeric conversions // SPEC: Implicit nullable conversions // SPEC: Implicit reference conversions // SPEC: Boxing conversions // SPEC: Implicit constant expression conversions // SPEC: Implicit conversions involving type parameters // // and in unsafe code: // // SPEC: From any pointer type to void* // // SPEC ERROR: // The specification does not say to take into account the conversion from // the *expression*, only its *type*. But the expression may not have a type // (because it is null, a method group, or a lambda), or the expression might // be convertible to the destination type via a constant numeric conversion. // For example, the native compiler allows "C c = 1;" to work if C is a class which // has an implicit conversion from byte to C, despite the fact that there is // obviously no standard implicit conversion from *int* to *byte*. // Similarly, if a struct S has an implicit conversion from string to S, then // "S s = null;" should be allowed. // // We extend the definition of standard implicit conversions to include // all of the implicit conversions that are allowed based on an expression, // with the exception of the switch expression conversion. Conversion conversion = ClassifyImplicitBuiltInConversionFromExpression(sourceExpression, source, destination, ref useSiteInfo); if (conversion.Exists) { return conversion; } if ((object)source != null) { return ClassifyStandardImplicitConversion(source, destination, ref useSiteInfo); } return Conversion.NoConversion; } private Conversion ClassifyStandardImplicitConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); if (HasIdentityConversionInternal(source, destination)) { return Conversion.Identity; } if (HasImplicitNumericConversion(source, destination)) { return Conversion.ImplicitNumeric; } var nullableConversion = ClassifyImplicitNullableConversion(source, destination, ref useSiteInfo); if (nullableConversion.Exists) { return nullableConversion; } if (HasImplicitReferenceConversion(source, destination, ref useSiteInfo)) { return Conversion.ImplicitReference; } if (HasBoxingConversion(source, destination, ref useSiteInfo)) { return Conversion.Boxing; } if (HasImplicitPointerToVoidConversion(source, destination)) { return Conversion.PointerToVoid; } if (HasImplicitPointerConversion(source, destination, ref useSiteInfo)) { return Conversion.ImplicitPointer; } var tupleConversion = ClassifyImplicitTupleConversion(source, destination, ref useSiteInfo); if (tupleConversion.Exists) { return tupleConversion; } return Conversion.NoConversion; } private Conversion ClassifyImplicitBuiltInConversionSlow(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); if (source.IsVoidType() || destination.IsVoidType()) { return Conversion.NoConversion; } Conversion conversion = ClassifyStandardImplicitConversion(source, destination, ref useSiteInfo); if (conversion.Exists) { return conversion; } return Conversion.NoConversion; } private Conversion GetImplicitUserDefinedConversion(BoundExpression sourceExpression, TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { var conversionResult = AnalyzeImplicitUserDefinedConversions(sourceExpression, source, destination, ref useSiteInfo); return new Conversion(conversionResult, isImplicit: true); } private Conversion ClassifyExplicitBuiltInOnlyConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, bool forCast) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); if (source.IsVoidType() || destination.IsVoidType()) { return Conversion.NoConversion; } // The call to HasExplicitNumericConversion isn't necessary, because it is always tested // already by the "FastConversion" code. Debug.Assert(!HasExplicitNumericConversion(source, destination)); //if (HasExplicitNumericConversion(source, specialTypeSource, destination, specialTypeDest)) //{ // return Conversion.ExplicitNumeric; //} if (HasSpecialIntPtrConversion(source, destination)) { return Conversion.IntPtr; } if (HasExplicitEnumerationConversion(source, destination)) { return Conversion.ExplicitEnumeration; } var nullableConversion = ClassifyExplicitNullableConversion(source, destination, ref useSiteInfo, forCast); if (nullableConversion.Exists) { return nullableConversion; } if (HasExplicitReferenceConversion(source, destination, ref useSiteInfo)) { return (source.Kind == SymbolKind.DynamicType) ? Conversion.ExplicitDynamic : Conversion.ExplicitReference; } if (HasUnboxingConversion(source, destination, ref useSiteInfo)) { return Conversion.Unboxing; } var tupleConversion = ClassifyExplicitTupleConversion(source, destination, ref useSiteInfo, forCast); if (tupleConversion.Exists) { return tupleConversion; } if (HasPointerToPointerConversion(source, destination)) { return Conversion.PointerToPointer; } if (HasPointerToIntegerConversion(source, destination)) { return Conversion.PointerToInteger; } if (HasIntegerToPointerConversion(source, destination)) { return Conversion.IntegerToPointer; } if (HasExplicitDynamicConversion(source, destination)) { return Conversion.ExplicitDynamic; } return Conversion.NoConversion; } private Conversion GetExplicitUserDefinedConversion(BoundExpression sourceExpression, TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { UserDefinedConversionResult conversionResult = AnalyzeExplicitUserDefinedConversions(sourceExpression, source, destination, ref useSiteInfo); return new Conversion(conversionResult, isImplicit: false); } private Conversion DeriveStandardExplicitFromOppositeStandardImplicitConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { var oppositeConversion = ClassifyStandardImplicitConversion(destination, source, ref useSiteInfo); Conversion impliedExplicitConversion; switch (oppositeConversion.Kind) { case ConversionKind.Identity: impliedExplicitConversion = Conversion.Identity; break; case ConversionKind.ImplicitNumeric: impliedExplicitConversion = Conversion.ExplicitNumeric; break; case ConversionKind.ImplicitReference: impliedExplicitConversion = Conversion.ExplicitReference; break; case ConversionKind.Boxing: impliedExplicitConversion = Conversion.Unboxing; break; case ConversionKind.NoConversion: impliedExplicitConversion = Conversion.NoConversion; break; case ConversionKind.ImplicitPointerToVoid: impliedExplicitConversion = Conversion.PointerToPointer; break; case ConversionKind.ImplicitTuple: // only implicit tuple conversions are standard conversions, // having implicit conversion in the other direction does not help here. impliedExplicitConversion = Conversion.NoConversion; break; case ConversionKind.ImplicitNullable: var strippedSource = source.StrippedType(); var strippedDestination = destination.StrippedType(); var underlyingConversion = DeriveStandardExplicitFromOppositeStandardImplicitConversion(strippedSource, strippedDestination, ref useSiteInfo); // the opposite underlying conversion may not exist // for example if underlying conversion is implicit tuple impliedExplicitConversion = underlyingConversion.Exists ? Conversion.MakeNullableConversion(ConversionKind.ExplicitNullable, underlyingConversion) : Conversion.NoConversion; break; default: throw ExceptionUtilities.UnexpectedValue(oppositeConversion.Kind); } return impliedExplicitConversion; } /// <summary> /// IsBaseInterface returns true if baseType is on the base interface list of derivedType or /// any base class of derivedType. It may be on the base interface list either directly or /// indirectly. /// * baseType must be an interface. /// * type parameters do not have base interfaces. (They have an "effective interface list".) /// * an interface is not a base of itself. /// * this does not check for variance conversions; if a type inherits from /// IEnumerable&lt;string> then IEnumerable&lt;object> is not a base interface. /// </summary> public bool IsBaseInterface(TypeSymbol baseType, TypeSymbol derivedType, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)baseType != null); Debug.Assert((object)derivedType != null); if (!baseType.IsInterfaceType()) { return false; } var d = derivedType as NamedTypeSymbol; if ((object)d == null) { return false; } foreach (var iface in d.AllInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteInfo)) { if (HasIdentityConversionInternal(iface, baseType)) { return true; } } return false; } // IsBaseClass returns true if and only if baseType is a base class of derivedType, period. // // * interfaces do not have base classes. (Structs, enums and classes other than object do.) // * a class is not a base class of itself // * type parameters do not have base classes. (They have "effective base classes".) // * all base classes must be classes // * dynamics are removed; if we have class D : B<dynamic> then B<object> is a // base class of D. However, dynamic is never a base class of anything. public bool IsBaseClass(TypeSymbol derivedType, TypeSymbol baseType, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)derivedType != null); Debug.Assert((object)baseType != null); // A base class has got to be a class. The derived type might be a struct, enum, or delegate. if (!baseType.IsClassType()) { return false; } for (TypeSymbol b = derivedType.BaseTypeWithDefinitionUseSiteDiagnostics(ref useSiteInfo); (object)b != null; b = b.BaseTypeWithDefinitionUseSiteDiagnostics(ref useSiteInfo)) { if (HasIdentityConversionInternal(b, baseType)) { return true; } } return false; } /// <summary> /// returns true when implicit conversion is not necessarily the same as explicit conversion /// </summary> private static bool ExplicitConversionMayDifferFromImplicit(Conversion implicitConversion) { switch (implicitConversion.Kind) { case ConversionKind.ImplicitUserDefined: case ConversionKind.ImplicitDynamic: case ConversionKind.ImplicitTuple: case ConversionKind.ImplicitTupleLiteral: case ConversionKind.ImplicitNullable: case ConversionKind.ConditionalExpression: return true; default: return false; } } private Conversion ClassifyImplicitBuiltInConversionFromExpression(BoundExpression sourceExpression, TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(sourceExpression != null || (object)source != null); Debug.Assert(sourceExpression == null || (object)sourceExpression.Type == (object)source); Debug.Assert((object)destination != null); if (HasImplicitDynamicConversionFromExpression(source, destination)) { return Conversion.ImplicitDynamic; } // The following conversions only exist for certain form of expressions, // if we have no expression none if them is applicable. if (sourceExpression == null) { return Conversion.NoConversion; } if (HasImplicitEnumerationConversion(sourceExpression, destination)) { return Conversion.ImplicitEnumeration; } var constantConversion = ClassifyImplicitConstantExpressionConversion(sourceExpression, destination); if (constantConversion.Exists) { return constantConversion; } switch (sourceExpression.Kind) { case BoundKind.Literal: var nullLiteralConversion = ClassifyNullLiteralConversion(sourceExpression, destination); if (nullLiteralConversion.Exists) { return nullLiteralConversion; } break; case BoundKind.DefaultLiteral: return Conversion.DefaultLiteral; case BoundKind.ExpressionWithNullability: { var innerExpression = ((BoundExpressionWithNullability)sourceExpression).Expression; var innerConversion = ClassifyImplicitBuiltInConversionFromExpression(innerExpression, innerExpression.Type, destination, ref useSiteInfo); if (innerConversion.Exists) { return innerConversion; } break; } case BoundKind.TupleLiteral: var tupleConversion = ClassifyImplicitTupleLiteralConversion((BoundTupleLiteral)sourceExpression, destination, ref useSiteInfo); if (tupleConversion.Exists) { return tupleConversion; } break; case BoundKind.UnboundLambda: if (HasAnonymousFunctionConversion(sourceExpression, destination)) { return Conversion.AnonymousFunction; } break; case BoundKind.MethodGroup: Conversion methodGroupConversion = GetMethodGroupDelegateConversion((BoundMethodGroup)sourceExpression, destination, ref useSiteInfo); if (methodGroupConversion.Exists) { return methodGroupConversion; } break; case BoundKind.UnconvertedInterpolatedString: Conversion interpolatedStringConversion = GetInterpolatedStringConversion((BoundUnconvertedInterpolatedString)sourceExpression, destination, ref useSiteInfo); if (interpolatedStringConversion.Exists) { return interpolatedStringConversion; } break; case BoundKind.StackAllocArrayCreation: var stackAllocConversion = GetStackAllocConversion((BoundStackAllocArrayCreation)sourceExpression, destination, ref useSiteInfo); if (stackAllocConversion.Exists) { return stackAllocConversion; } break; case BoundKind.UnconvertedAddressOfOperator when destination is FunctionPointerTypeSymbol funcPtrType: var addressOfConversion = GetMethodGroupFunctionPointerConversion(((BoundUnconvertedAddressOfOperator)sourceExpression).Operand, funcPtrType, ref useSiteInfo); if (addressOfConversion.Exists) { return addressOfConversion; } break; case BoundKind.ThrowExpression: return Conversion.ImplicitThrow; case BoundKind.UnconvertedObjectCreationExpression: return Conversion.ObjectCreation; } return Conversion.NoConversion; } private Conversion GetSwitchExpressionConversion(BoundExpression source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { switch (source) { case BoundConvertedSwitchExpression _: // It has already been subjected to a switch expression conversion. return Conversion.NoConversion; case BoundUnconvertedSwitchExpression switchExpression: var innerConversions = ArrayBuilder<Conversion>.GetInstance(switchExpression.SwitchArms.Length); foreach (var arm in switchExpression.SwitchArms) { var nestedConversion = this.ClassifyImplicitConversionFromExpression(arm.Value, destination, ref useSiteInfo); if (!nestedConversion.Exists) { innerConversions.Free(); return Conversion.NoConversion; } innerConversions.Add(nestedConversion); } return Conversion.MakeSwitchExpression(innerConversions.ToImmutableAndFree()); default: return Conversion.NoConversion; } } private Conversion GetConditionalExpressionConversion(BoundExpression source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { if (!(source is BoundUnconvertedConditionalOperator conditionalOperator)) return Conversion.NoConversion; var trueConversion = this.ClassifyImplicitConversionFromExpression(conditionalOperator.Consequence, destination, ref useSiteInfo); if (!trueConversion.Exists) return Conversion.NoConversion; var falseConversion = this.ClassifyImplicitConversionFromExpression(conditionalOperator.Alternative, destination, ref useSiteInfo); if (!falseConversion.Exists) return Conversion.NoConversion; return Conversion.MakeConditionalExpression(ImmutableArray.Create(trueConversion, falseConversion)); } private static Conversion ClassifyNullLiteralConversion(BoundExpression source, TypeSymbol destination) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); if (!source.IsLiteralNull()) { return Conversion.NoConversion; } // SPEC: An implicit conversion exists from the null literal to any nullable type. if (destination.IsNullableType()) { // The spec defines a "null literal conversion" specifically as a conversion from // null to nullable type. return Conversion.NullLiteral; } // SPEC: An implicit conversion exists from the null literal to any reference type. // SPEC: An implicit conversion exists from the null literal to type parameter T, // SPEC: provided T is known to be a reference type. [...] The conversion [is] classified // SPEC: as implicit reference conversion. if (destination.IsReferenceType) { return Conversion.ImplicitReference; } // SPEC: The set of implicit conversions is extended to include... // SPEC: ... from the null literal to any pointer type. if (destination.IsPointerOrFunctionPointer()) { return Conversion.NullToPointer; } return Conversion.NoConversion; } private static Conversion ClassifyImplicitConstantExpressionConversion(BoundExpression source, TypeSymbol destination) { if (HasImplicitConstantExpressionConversion(source, destination)) { return Conversion.ImplicitConstant; } // strip nullable from the destination // // the following should work and it is an ImplicitNullable conversion // int? x = 1; if (destination.Kind == SymbolKind.NamedType) { var nt = (NamedTypeSymbol)destination; if (nt.OriginalDefinition.GetSpecialTypeSafe() == SpecialType.System_Nullable_T && HasImplicitConstantExpressionConversion(source, nt.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics[0].Type)) { return new Conversion(ConversionKind.ImplicitNullable, Conversion.ImplicitConstantUnderlying); } } return Conversion.NoConversion; } private Conversion ClassifyImplicitTupleLiteralConversion(BoundTupleLiteral source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { var tupleConversion = GetImplicitTupleLiteralConversion(source, destination, ref useSiteInfo); if (tupleConversion.Exists) { return tupleConversion; } // strip nullable from the destination // // the following should work and it is an ImplicitNullable conversion // (int, double)? x = (1,2); if (destination.Kind == SymbolKind.NamedType) { var nt = (NamedTypeSymbol)destination; if (nt.OriginalDefinition.GetSpecialTypeSafe() == SpecialType.System_Nullable_T) { var underlyingTupleConversion = GetImplicitTupleLiteralConversion(source, nt.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics[0].Type, ref useSiteInfo); if (underlyingTupleConversion.Exists) { return new Conversion(ConversionKind.ImplicitNullable, ImmutableArray.Create(underlyingTupleConversion)); } } } return Conversion.NoConversion; } private Conversion ClassifyExplicitTupleLiteralConversion(BoundTupleLiteral source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, bool forCast) { var tupleConversion = GetExplicitTupleLiteralConversion(source, destination, ref useSiteInfo, forCast); if (tupleConversion.Exists) { return tupleConversion; } // strip nullable from the destination // // the following should work and it is an ExplicitNullable conversion // var x = ((byte, string)?)(1,null); if (destination.Kind == SymbolKind.NamedType) { var nt = (NamedTypeSymbol)destination; if (nt.OriginalDefinition.GetSpecialTypeSafe() == SpecialType.System_Nullable_T) { var underlyingTupleConversion = GetExplicitTupleLiteralConversion(source, nt.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics[0].Type, ref useSiteInfo, forCast); if (underlyingTupleConversion.Exists) { return new Conversion(ConversionKind.ExplicitNullable, ImmutableArray.Create(underlyingTupleConversion)); } } } return Conversion.NoConversion; } internal static bool HasImplicitConstantExpressionConversion(BoundExpression source, TypeSymbol destination) { var constantValue = source.ConstantValue; if (constantValue == null || (object)source.Type == null) { return false; } // An implicit constant expression conversion permits the following conversions: // A constant-expression of type int can be converted to type sbyte, byte, short, // ushort, uint, or ulong, provided the value of the constant-expression is within the // range of the destination type. var specialSource = source.Type.GetSpecialTypeSafe(); if (specialSource == SpecialType.System_Int32) { //if the constant value could not be computed, be generous and assume the conversion will work int value = constantValue.IsBad ? 0 : constantValue.Int32Value; switch (destination.GetSpecialTypeSafe()) { case SpecialType.System_Byte: return byte.MinValue <= value && value <= byte.MaxValue; case SpecialType.System_SByte: return sbyte.MinValue <= value && value <= sbyte.MaxValue; case SpecialType.System_Int16: return short.MinValue <= value && value <= short.MaxValue; case SpecialType.System_IntPtr when destination.IsNativeIntegerType: return true; case SpecialType.System_UInt32: case SpecialType.System_UIntPtr when destination.IsNativeIntegerType: return uint.MinValue <= value; case SpecialType.System_UInt64: return (int)ulong.MinValue <= value; case SpecialType.System_UInt16: return ushort.MinValue <= value && value <= ushort.MaxValue; default: return false; } } else if (specialSource == SpecialType.System_Int64 && destination.GetSpecialTypeSafe() == SpecialType.System_UInt64 && (constantValue.IsBad || 0 <= constantValue.Int64Value)) { // A constant-expression of type long can be converted to type ulong, provided the // value of the constant-expression is not negative. return true; } return false; } private Conversion ClassifyExplicitOnlyConversionFromExpression(BoundExpression sourceExpression, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, bool forCast) { Debug.Assert(sourceExpression != null); Debug.Assert((object)destination != null); var sourceType = sourceExpression.Type; // NB: need to check for explicit tuple literal conversion before checking for explicit conversion from type // The same literal may have both explicit tuple conversion and explicit tuple literal conversion to the target type. // They are, however, observably different conversions via the order of argument evaluations and element-wise conversions if (sourceExpression.Kind == BoundKind.TupleLiteral) { Conversion tupleConversion = ClassifyExplicitTupleLiteralConversion((BoundTupleLiteral)sourceExpression, destination, ref useSiteInfo, forCast); if (tupleConversion.Exists) { return tupleConversion; } } if ((object)sourceType != null) { // Try using the short-circuit "fast-conversion" path. Conversion fastConversion = FastClassifyConversion(sourceType, destination); if (fastConversion.Exists) { return fastConversion; } else { var conversion = ClassifyExplicitBuiltInOnlyConversion(sourceType, destination, ref useSiteInfo, forCast); if (conversion.Exists) { return conversion; } } } return GetExplicitUserDefinedConversion(sourceExpression, sourceType, destination, ref useSiteInfo); } #nullable enable private static bool HasImplicitEnumerationConversion(BoundExpression source, TypeSymbol destination) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); // SPEC: An implicit enumeration conversion permits the decimal-integer-literal 0 to be converted to any enum-type // SPEC: and to any nullable-type whose underlying type is an enum-type. // // For historical reasons we actually allow a conversion from any *numeric constant // zero* to be converted to any enum type, not just the literal integer zero. bool validType = destination.IsEnumType() || destination.IsNullableType() && destination.GetNullableUnderlyingType().IsEnumType(); if (!validType) { return false; } var sourceConstantValue = source.ConstantValue; return sourceConstantValue != null && source.Type is object && IsNumericType(source.Type) && IsConstantNumericZero(sourceConstantValue); } private static LambdaConversionResult IsAnonymousFunctionCompatibleWithDelegate(UnboundLambda anonymousFunction, TypeSymbol type, bool isTargetExpressionTree) { Debug.Assert((object)anonymousFunction != null); Debug.Assert((object)type != null); // SPEC: An anonymous-method-expression or lambda-expression is classified as an anonymous function. // SPEC: The expression does not have a type but can be implicitly converted to a compatible delegate // SPEC: type or expression tree type. Specifically, a delegate type D is compatible with an // SPEC: anonymous function F provided: var delegateType = (NamedTypeSymbol)type; var invokeMethod = delegateType.DelegateInvokeMethod; if ((object)invokeMethod == null || invokeMethod.HasUseSiteError) { return LambdaConversionResult.BadTargetType; } if (anonymousFunction.HasExplicitReturnType(out var refKind, out var returnType)) { if (invokeMethod.RefKind != refKind || !invokeMethod.ReturnType.Equals(returnType.Type, TypeCompareKind.AllIgnoreOptions)) { return LambdaConversionResult.MismatchedReturnType; } } var delegateParameters = invokeMethod.Parameters; // SPEC: If F contains an anonymous-function-signature, then D and F have the same number of parameters. // SPEC: If F does not contain an anonymous-function-signature, then D may have zero or more parameters // SPEC: of any type, as long as no parameter of D has the out parameter modifier. if (anonymousFunction.HasSignature) { if (anonymousFunction.ParameterCount != invokeMethod.ParameterCount) { return LambdaConversionResult.BadParameterCount; } // SPEC: If F has an explicitly typed parameter list, each parameter in D has the same type // SPEC: and modifiers as the corresponding parameter in F. // SPEC: If F has an implicitly typed parameter list, D has no ref or out parameters. if (anonymousFunction.HasExplicitlyTypedParameterList) { for (int p = 0; p < delegateParameters.Length; ++p) { if (delegateParameters[p].RefKind != anonymousFunction.RefKind(p) || !delegateParameters[p].Type.Equals(anonymousFunction.ParameterType(p), TypeCompareKind.AllIgnoreOptions)) { return LambdaConversionResult.MismatchedParameterType; } } } else { for (int p = 0; p < delegateParameters.Length; ++p) { if (delegateParameters[p].RefKind != RefKind.None) { return LambdaConversionResult.RefInImplicitlyTypedLambda; } } // In C# it is not possible to make a delegate type // such that one of its parameter types is a static type. But static types are // in metadata just sealed abstract types; there is nothing stopping someone in // another language from creating a delegate with a static type for a parameter, // though the only argument you could pass for that parameter is null. // // In the native compiler we forbid conversion of an anonymous function that has // an implicitly-typed parameter list to a delegate type that has a static type // for a formal parameter type. However, we do *not* forbid it for an explicitly- // typed lambda (because we already require that the explicitly typed parameter not // be static) and we do not forbid it for an anonymous method with the entire // parameter list missing (because the body cannot possibly have a parameter that // is of static type, even though this means that we will be generating a hidden // method with a parameter of static type.) // // We also allow more exotic situations to work in the native compiler. For example, // though it is not possible to convert x=>{} to Action<GC>, it is possible to convert // it to Action<List<GC>> should there be a language that allows you to construct // a variable of that type. // // We might consider beefing up this rule to disallow a conversion of *any* anonymous // function to *any* delegate that has a static type *anywhere* in the parameter list. for (int p = 0; p < delegateParameters.Length; ++p) { if (delegateParameters[p].TypeWithAnnotations.IsStatic) { return LambdaConversionResult.StaticTypeInImplicitlyTypedLambda; } } } } else { for (int p = 0; p < delegateParameters.Length; ++p) { if (delegateParameters[p].RefKind == RefKind.Out) { return LambdaConversionResult.MissingSignatureWithOutParameter; } } } // Ensure the body can be converted to that delegate type var bound = anonymousFunction.Bind(delegateType, isTargetExpressionTree); if (ErrorFacts.PreventsSuccessfulDelegateConversion(bound.Diagnostics.Diagnostics)) { return LambdaConversionResult.BindingFailed; } return LambdaConversionResult.Success; } private static LambdaConversionResult IsAnonymousFunctionCompatibleWithExpressionTree(UnboundLambda anonymousFunction, NamedTypeSymbol type) { Debug.Assert((object)anonymousFunction != null); Debug.Assert((object)type != null); Debug.Assert(type.IsGenericOrNonGenericExpressionType(out _)); // SPEC OMISSION: // // The C# 3 spec said that anonymous methods and statement lambdas are *convertible* to expression tree // types if the anonymous method/statement lambda is convertible to its delegate type; however, actually // *using* such a conversion is an error. However, that is not what we implemented. In C# 3 we implemented // that an anonymous method is *not convertible* to an expression tree type, period. (Statement lambdas // used the rule described in the spec.) // // This appears to be a spec omission; the intention is to make old-style anonymous methods not // convertible to expression trees. var delegateType = type.Arity == 0 ? null : type.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics[0].Type; if (delegateType is { } && !delegateType.IsDelegateType()) { return LambdaConversionResult.ExpressionTreeMustHaveDelegateTypeArgument; } if (anonymousFunction.Syntax.Kind() == SyntaxKind.AnonymousMethodExpression) { return LambdaConversionResult.ExpressionTreeFromAnonymousMethod; } if (delegateType is null) { return LambdaConversionResult.Success; } return IsAnonymousFunctionCompatibleWithDelegate(anonymousFunction, delegateType, isTargetExpressionTree: true); } public static LambdaConversionResult IsAnonymousFunctionCompatibleWithType(UnboundLambda anonymousFunction, TypeSymbol type) { Debug.Assert((object)anonymousFunction != null); Debug.Assert((object)type != null); if (type.SpecialType == SpecialType.System_Delegate) { return LambdaConversionResult.Success; } else if (type.IsDelegateType()) { return IsAnonymousFunctionCompatibleWithDelegate(anonymousFunction, type, isTargetExpressionTree: false); } else if (type.IsGenericOrNonGenericExpressionType(out bool _)) { return IsAnonymousFunctionCompatibleWithExpressionTree(anonymousFunction, (NamedTypeSymbol)type); } return LambdaConversionResult.BadTargetType; } private static bool HasAnonymousFunctionConversion(BoundExpression source, TypeSymbol destination) { Debug.Assert(source != null); Debug.Assert((object)destination != null); if (source.Kind != BoundKind.UnboundLambda) { return false; } return IsAnonymousFunctionCompatibleWithType((UnboundLambda)source, destination) == LambdaConversionResult.Success; } #nullable disable internal Conversion ClassifyImplicitUserDefinedConversionForV6SwitchGoverningType(TypeSymbol sourceType, out TypeSymbol switchGoverningType, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { // SPEC: The governing type of a switch statement is established by the switch expression. // SPEC: 1) If the type of the switch expression is sbyte, byte, short, ushort, int, uint, // SPEC: long, ulong, bool, char, string, or an enum-type, or if it is the nullable type // SPEC: corresponding to one of these types, then that is the governing type of the switch statement. // SPEC: 2) Otherwise, exactly one user-defined implicit conversion (§6.4) must exist from the // SPEC: type of the switch expression to one of the following possible governing types: // SPEC: sbyte, byte, short, ushort, int, uint, long, ulong, char, string, or, a nullable type // SPEC: corresponding to one of those types // NOTE: We should be called only if (1) is false for source type. Debug.Assert((object)sourceType != null); Debug.Assert(!sourceType.IsValidV6SwitchGoverningType()); UserDefinedConversionResult result = AnalyzeImplicitUserDefinedConversionForV6SwitchGoverningType(sourceType, ref useSiteInfo); if (result.Kind == UserDefinedConversionResultKind.Valid) { UserDefinedConversionAnalysis analysis = result.Results[result.Best]; switchGoverningType = analysis.ToType; Debug.Assert(switchGoverningType.IsValidV6SwitchGoverningType(isTargetTypeOfUserDefinedOp: true)); } else { switchGoverningType = null; } return new Conversion(result, isImplicit: true); } internal Conversion GetCallerLineNumberConversion(TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { var greenNode = new Syntax.InternalSyntax.LiteralExpressionSyntax(SyntaxKind.NumericLiteralExpression, new Syntax.InternalSyntax.SyntaxToken(SyntaxKind.NumericLiteralToken)); var syntaxNode = new LiteralExpressionSyntax(greenNode, null, 0); TypeSymbol expectedAttributeType = corLibrary.GetSpecialType(SpecialType.System_Int32); BoundLiteral intMaxValueLiteral = new BoundLiteral(syntaxNode, ConstantValue.Create(int.MaxValue), expectedAttributeType); return ClassifyStandardImplicitConversion(intMaxValueLiteral, expectedAttributeType, destination, ref useSiteInfo); } internal bool HasCallerLineNumberConversion(TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { return GetCallerLineNumberConversion(destination, ref useSiteInfo).Exists; } internal bool HasCallerInfoStringConversion(TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { TypeSymbol expectedAttributeType = corLibrary.GetSpecialType(SpecialType.System_String); Conversion conversion = ClassifyStandardImplicitConversion(expectedAttributeType, destination, ref useSiteInfo); return conversion.Exists; } public static bool HasIdentityConversion(TypeSymbol type1, TypeSymbol type2) { return HasIdentityConversionInternal(type1, type2, includeNullability: false); } private static bool HasIdentityConversionInternal(TypeSymbol type1, TypeSymbol type2, bool includeNullability) { // Spec (6.1.1): // An identity conversion converts from any type to the same type. This conversion exists // such that an entity that already has a required type can be said to be convertible to // that type. // // Because object and dynamic are considered equivalent there is an identity conversion // between object and dynamic, and between constructed types that are the same when replacing // all occurrences of dynamic with object. Debug.Assert((object)type1 != null); Debug.Assert((object)type2 != null); // Note, when we are paying attention to nullability, we ignore oblivious mismatch. // See TypeCompareKind.ObliviousNullableModifierMatchesAny var compareKind = includeNullability ? TypeCompareKind.AllIgnoreOptions & ~TypeCompareKind.IgnoreNullableModifiersForReferenceTypes : TypeCompareKind.AllIgnoreOptions; return type1.Equals(type2, compareKind); } private bool HasIdentityConversionInternal(TypeSymbol type1, TypeSymbol type2) { return HasIdentityConversionInternal(type1, type2, IncludeNullability); } /// <summary> /// Returns true if: /// - Either type has no nullability information (oblivious). /// - Both types cannot have different nullability at the same time, /// including the case of type parameters that by themselves can represent nullable and not nullable reference types. /// </summary> internal bool HasTopLevelNullabilityIdentityConversion(TypeWithAnnotations source, TypeWithAnnotations destination) { if (!IncludeNullability) { return true; } if (source.NullableAnnotation.IsOblivious() || destination.NullableAnnotation.IsOblivious()) { return true; } var sourceIsPossiblyNullableTypeParameter = IsPossiblyNullableTypeTypeParameter(source); var destinationIsPossiblyNullableTypeParameter = IsPossiblyNullableTypeTypeParameter(destination); if (sourceIsPossiblyNullableTypeParameter && !destinationIsPossiblyNullableTypeParameter) { return destination.NullableAnnotation.IsAnnotated(); } if (destinationIsPossiblyNullableTypeParameter && !sourceIsPossiblyNullableTypeParameter) { return source.NullableAnnotation.IsAnnotated(); } return source.NullableAnnotation.IsAnnotated() == destination.NullableAnnotation.IsAnnotated(); } /// <summary> /// Returns false if source type can be nullable at the same time when destination type can be not nullable, /// including the case of type parameters that by themselves can represent nullable and not nullable reference types. /// When either type has no nullability information (oblivious), this method returns true. /// </summary> internal bool HasTopLevelNullabilityImplicitConversion(TypeWithAnnotations source, TypeWithAnnotations destination) { if (!IncludeNullability) { return true; } if (source.NullableAnnotation.IsOblivious() || destination.NullableAnnotation.IsOblivious() || destination.NullableAnnotation.IsAnnotated()) { return true; } if (IsPossiblyNullableTypeTypeParameter(source) && !IsPossiblyNullableTypeTypeParameter(destination)) { return false; } return !source.NullableAnnotation.IsAnnotated(); } private static bool IsPossiblyNullableTypeTypeParameter(in TypeWithAnnotations typeWithAnnotations) { var type = typeWithAnnotations.Type; return type is object && (type.IsPossiblyNullableReferenceTypeTypeParameter() || type.IsNullableTypeOrTypeParameter()); } /// <summary> /// Returns false if the source does not have an implicit conversion to the destination /// because of either incompatible top level or nested nullability. /// </summary> public bool HasAnyNullabilityImplicitConversion(TypeWithAnnotations source, TypeWithAnnotations destination) { Debug.Assert(IncludeNullability); var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; return HasTopLevelNullabilityImplicitConversion(source, destination) && ClassifyImplicitConversionFromType(source.Type, destination.Type, ref discardedUseSiteInfo).Kind != ConversionKind.NoConversion; } public static bool HasIdentityConversionToAny<T>(T type, ArrayBuilder<T> targetTypes) where T : TypeSymbol { foreach (var targetType in targetTypes) { if (HasIdentityConversionInternal(type, targetType, includeNullability: false)) { return true; } } return false; } public Conversion ConvertExtensionMethodThisArg(TypeSymbol parameterType, TypeSymbol thisType, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)thisType != null); var conversion = this.ClassifyImplicitExtensionMethodThisArgConversion(null, thisType, parameterType, ref useSiteInfo); return IsValidExtensionMethodThisArgConversion(conversion) ? conversion : Conversion.NoConversion; } // Spec 7.6.5.2: "An extension method ... is eligible if ... [an] implicit identity, reference, // or boxing conversion exists from expr to the type of the first parameter" public Conversion ClassifyImplicitExtensionMethodThisArgConversion(BoundExpression sourceExpressionOpt, TypeSymbol sourceType, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(sourceExpressionOpt == null || (object)sourceExpressionOpt.Type == sourceType); Debug.Assert((object)destination != null); if ((object)sourceType != null) { if (HasIdentityConversionInternal(sourceType, destination)) { return Conversion.Identity; } if (HasBoxingConversion(sourceType, destination, ref useSiteInfo)) { return Conversion.Boxing; } if (HasImplicitReferenceConversion(sourceType, destination, ref useSiteInfo)) { return Conversion.ImplicitReference; } } if (sourceExpressionOpt?.Kind == BoundKind.TupleLiteral) { // GetTupleLiteralConversion is not used with IncludeNullability currently. // If that changes, the delegate below will need to consider top-level nullability. Debug.Assert(!IncludeNullability); var tupleConversion = GetTupleLiteralConversion( (BoundTupleLiteral)sourceExpressionOpt, destination, ref useSiteInfo, ConversionKind.ImplicitTupleLiteral, (ConversionsBase conversions, BoundExpression s, TypeWithAnnotations d, ref CompoundUseSiteInfo<AssemblySymbol> u, bool a) => conversions.ClassifyImplicitExtensionMethodThisArgConversion(s, s.Type, d.Type, ref u), arg: false); if (tupleConversion.Exists) { return tupleConversion; } } if ((object)sourceType != null) { var tupleConversion = ClassifyTupleConversion( sourceType, destination, ref useSiteInfo, ConversionKind.ImplicitTuple, (ConversionsBase conversions, TypeWithAnnotations s, TypeWithAnnotations d, ref CompoundUseSiteInfo<AssemblySymbol> u, bool a) => { if (!conversions.HasTopLevelNullabilityImplicitConversion(s, d)) { return Conversion.NoConversion; } return conversions.ClassifyImplicitExtensionMethodThisArgConversion(null, s.Type, d.Type, ref u); }, arg: false); if (tupleConversion.Exists) { return tupleConversion; } } return Conversion.NoConversion; } // It should be possible to remove IsValidExtensionMethodThisArgConversion // since ClassifyImplicitExtensionMethodThisArgConversion should only // return valid conversions. https://github.com/dotnet/roslyn/issues/19622 // Spec 7.6.5.2: "An extension method ... is eligible if ... [an] implicit identity, reference, // or boxing conversion exists from expr to the type of the first parameter" public static bool IsValidExtensionMethodThisArgConversion(Conversion conversion) { switch (conversion.Kind) { case ConversionKind.Identity: case ConversionKind.Boxing: case ConversionKind.ImplicitReference: return true; case ConversionKind.ImplicitTuple: case ConversionKind.ImplicitTupleLiteral: // check if all element conversions satisfy the requirement foreach (var elementConversion in conversion.UnderlyingConversions) { if (!IsValidExtensionMethodThisArgConversion(elementConversion)) { return false; } } return true; default: // Caller should have not have calculated another conversion. Debug.Assert(conversion.Kind == ConversionKind.NoConversion); return false; } } private const bool F = false; private const bool T = true; // Notice that there is no implicit numeric conversion from a type to itself. That's an // identity conversion. private static readonly bool[,] s_implicitNumericConversions = { // to sb b s us i ui l ul c f d m // from /* sb */ { F, F, T, F, T, F, T, F, F, T, T, T }, /* b */ { F, F, T, T, T, T, T, T, F, T, T, T }, /* s */ { F, F, F, F, T, F, T, F, F, T, T, T }, /* us */ { F, F, F, F, T, T, T, T, F, T, T, T }, /* i */ { F, F, F, F, F, F, T, F, F, T, T, T }, /* ui */ { F, F, F, F, F, F, T, T, F, T, T, T }, /* l */ { F, F, F, F, F, F, F, F, F, T, T, T }, /* ul */ { F, F, F, F, F, F, F, F, F, T, T, T }, /* c */ { F, F, F, T, T, T, T, T, F, T, T, T }, /* f */ { F, F, F, F, F, F, F, F, F, F, T, F }, /* d */ { F, F, F, F, F, F, F, F, F, F, F, F }, /* m */ { F, F, F, F, F, F, F, F, F, F, F, F } }; private static readonly bool[,] s_explicitNumericConversions = { // to sb b s us i ui l ul c f d m // from /* sb */ { F, T, F, T, F, T, F, T, T, F, F, F }, /* b */ { T, F, F, F, F, F, F, F, T, F, F, F }, /* s */ { T, T, F, T, F, T, F, T, T, F, F, F }, /* us */ { T, T, T, F, F, F, F, F, T, F, F, F }, /* i */ { T, T, T, T, F, T, F, T, T, F, F, F }, /* ui */ { T, T, T, T, T, F, F, F, T, F, F, F }, /* l */ { T, T, T, T, T, T, F, T, T, F, F, F }, /* ul */ { T, T, T, T, T, T, T, F, T, F, F, F }, /* c */ { T, T, T, F, F, F, F, F, F, F, F, F }, /* f */ { T, T, T, T, T, T, T, T, T, F, F, T }, /* d */ { T, T, T, T, T, T, T, T, T, T, F, T }, /* m */ { T, T, T, T, T, T, T, T, T, T, T, F } }; private static int GetNumericTypeIndex(SpecialType specialType) { switch (specialType) { case SpecialType.System_SByte: return 0; case SpecialType.System_Byte: return 1; case SpecialType.System_Int16: return 2; case SpecialType.System_UInt16: return 3; case SpecialType.System_Int32: return 4; case SpecialType.System_UInt32: return 5; case SpecialType.System_Int64: return 6; case SpecialType.System_UInt64: return 7; case SpecialType.System_Char: return 8; case SpecialType.System_Single: return 9; case SpecialType.System_Double: return 10; case SpecialType.System_Decimal: return 11; default: return -1; } } #nullable enable private static bool HasImplicitNumericConversion(TypeSymbol source, TypeSymbol destination) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); int sourceIndex = GetNumericTypeIndex(source.SpecialType); if (sourceIndex < 0) { return false; } int destinationIndex = GetNumericTypeIndex(destination.SpecialType); if (destinationIndex < 0) { return false; } return s_implicitNumericConversions[sourceIndex, destinationIndex]; } private static bool HasExplicitNumericConversion(TypeSymbol source, TypeSymbol destination) { // SPEC: The explicit numeric conversions are the conversions from a numeric-type to another // SPEC: numeric-type for which an implicit numeric conversion does not already exist. Debug.Assert((object)source != null); Debug.Assert((object)destination != null); int sourceIndex = GetNumericTypeIndex(source.SpecialType); if (sourceIndex < 0) { return false; } int destinationIndex = GetNumericTypeIndex(destination.SpecialType); if (destinationIndex < 0) { return false; } return s_explicitNumericConversions[sourceIndex, destinationIndex]; } private static bool IsConstantNumericZero(ConstantValue value) { switch (value.Discriminator) { case ConstantValueTypeDiscriminator.SByte: return value.SByteValue == 0; case ConstantValueTypeDiscriminator.Byte: return value.ByteValue == 0; case ConstantValueTypeDiscriminator.Int16: return value.Int16Value == 0; case ConstantValueTypeDiscriminator.Int32: case ConstantValueTypeDiscriminator.NInt: return value.Int32Value == 0; case ConstantValueTypeDiscriminator.Int64: return value.Int64Value == 0; case ConstantValueTypeDiscriminator.UInt16: return value.UInt16Value == 0; case ConstantValueTypeDiscriminator.UInt32: case ConstantValueTypeDiscriminator.NUInt: return value.UInt32Value == 0; case ConstantValueTypeDiscriminator.UInt64: return value.UInt64Value == 0; case ConstantValueTypeDiscriminator.Single: case ConstantValueTypeDiscriminator.Double: return value.DoubleValue == 0; case ConstantValueTypeDiscriminator.Decimal: return value.DecimalValue == 0; } return false; } private static bool IsNumericType(TypeSymbol type) { switch (type.SpecialType) { case SpecialType.System_Char: case SpecialType.System_SByte: case SpecialType.System_Byte: case SpecialType.System_Int16: case SpecialType.System_UInt16: case SpecialType.System_Int32: case SpecialType.System_UInt32: case SpecialType.System_Int64: case SpecialType.System_UInt64: case SpecialType.System_Single: case SpecialType.System_Double: case SpecialType.System_Decimal: case SpecialType.System_IntPtr when type.IsNativeIntegerType: case SpecialType.System_UIntPtr when type.IsNativeIntegerType: return true; default: return false; } } private static bool HasSpecialIntPtrConversion(TypeSymbol source, TypeSymbol target) { Debug.Assert((object)source != null); Debug.Assert((object)target != null); // There are only a total of twelve user-defined explicit conversions on IntPtr and UIntPtr: // // IntPtr <---> int // IntPtr <---> long // IntPtr <---> void* // UIntPtr <---> uint // UIntPtr <---> ulong // UIntPtr <---> void* // // The specification says that you can put any *standard* implicit or explicit conversion // on "either side" of a user-defined explicit conversion, so the specification allows, say, // UIntPtr --> byte because the conversion UIntPtr --> uint is user-defined and the // conversion uint --> byte is "standard". It is "standard" because the conversion // byte --> uint is an implicit numeric conversion. // This means that certain conversions should be illegal. For example, IntPtr --> ulong // should be illegal because none of int --> ulong, long --> ulong and void* --> ulong // are "standard" conversions. // Similarly, some conversions involving IntPtr should be illegal because they are // ambiguous. byte --> IntPtr?, for example, is ambiguous. (There are four possible // UD operators: int --> IntPtr and long --> IntPtr, and their lifted versions. The // best possible source type is int, the best possible target type is IntPtr?, and // there is an ambiguity between the unlifted int --> IntPtr, and the lifted // int? --> IntPtr? conversions.) // In practice, the native compiler, and hence, the Roslyn compiler, allows all // these conversions. Any conversion from a numeric type to IntPtr, or from an IntPtr // to a numeric type, is allowed. Also, any conversion from a pointer type to IntPtr // or vice versa is allowed. var s0 = source.StrippedType(); var t0 = target.StrippedType(); TypeSymbol otherType; if (isIntPtrOrUIntPtr(s0)) { otherType = t0; } else if (isIntPtrOrUIntPtr(t0)) { otherType = s0; } else { return false; } if (otherType.IsPointerOrFunctionPointer()) { return true; } if (otherType.TypeKind == TypeKind.Enum) { return true; } switch (otherType.SpecialType) { case SpecialType.System_SByte: case SpecialType.System_Byte: case SpecialType.System_Int16: case SpecialType.System_UInt16: case SpecialType.System_Char: case SpecialType.System_Int32: case SpecialType.System_UInt32: case SpecialType.System_Int64: case SpecialType.System_UInt64: case SpecialType.System_Double: case SpecialType.System_Single: case SpecialType.System_Decimal: return true; } return false; static bool isIntPtrOrUIntPtr(TypeSymbol type) => (type.SpecialType == SpecialType.System_IntPtr || type.SpecialType == SpecialType.System_UIntPtr) && !type.IsNativeIntegerType; } private static bool HasExplicitEnumerationConversion(TypeSymbol source, TypeSymbol destination) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); // SPEC: The explicit enumeration conversions are: // SPEC: From sbyte, byte, short, ushort, int, uint, long, ulong, nint, nuint, char, float, double, or decimal to any enum-type. // SPEC: From any enum-type to sbyte, byte, short, ushort, int, uint, long, ulong, nint, nuint, char, float, double, or decimal. // SPEC: From any enum-type to any other enum-type. if (IsNumericType(source) && destination.IsEnumType()) { return true; } if (IsNumericType(destination) && source.IsEnumType()) { return true; } if (source.IsEnumType() && destination.IsEnumType()) { return true; } return false; } #nullable disable private Conversion ClassifyImplicitNullableConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); // SPEC: Predefined implicit conversions that operate on non-nullable value types can also be used with // SPEC: nullable forms of those types. For each of the predefined implicit identity, numeric and tuple conversions // SPEC: that convert from a non-nullable value type S to a non-nullable value type T, the following implicit // SPEC: nullable conversions exist: // SPEC: * An implicit conversion from S? to T?. // SPEC: * An implicit conversion from S to T?. if (!destination.IsNullableType()) { return Conversion.NoConversion; } TypeSymbol unwrappedDestination = destination.GetNullableUnderlyingType(); TypeSymbol unwrappedSource = source.StrippedType(); if (!unwrappedSource.IsValueType) { return Conversion.NoConversion; } if (HasIdentityConversionInternal(unwrappedSource, unwrappedDestination)) { return new Conversion(ConversionKind.ImplicitNullable, Conversion.IdentityUnderlying); } if (HasImplicitNumericConversion(unwrappedSource, unwrappedDestination)) { return new Conversion(ConversionKind.ImplicitNullable, Conversion.ImplicitNumericUnderlying); } var tupleConversion = ClassifyImplicitTupleConversion(unwrappedSource, unwrappedDestination, ref useSiteInfo); if (tupleConversion.Exists) { return new Conversion(ConversionKind.ImplicitNullable, ImmutableArray.Create(tupleConversion)); } return Conversion.NoConversion; } private delegate Conversion ClassifyConversionFromExpressionDelegate(ConversionsBase conversions, BoundExpression sourceExpression, TypeWithAnnotations destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, bool arg); private delegate Conversion ClassifyConversionFromTypeDelegate(ConversionsBase conversions, TypeWithAnnotations source, TypeWithAnnotations destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, bool arg); private Conversion GetImplicitTupleLiteralConversion(BoundTupleLiteral source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { // GetTupleLiteralConversion is not used with IncludeNullability currently. // If that changes, the delegate below will need to consider top-level nullability. Debug.Assert(!IncludeNullability); return GetTupleLiteralConversion( source, destination, ref useSiteInfo, ConversionKind.ImplicitTupleLiteral, (ConversionsBase conversions, BoundExpression s, TypeWithAnnotations d, ref CompoundUseSiteInfo<AssemblySymbol> u, bool a) => conversions.ClassifyImplicitConversionFromExpression(s, d.Type, ref u), arg: false); } private Conversion GetExplicitTupleLiteralConversion(BoundTupleLiteral source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, bool forCast) { // GetTupleLiteralConversion is not used with IncludeNullability currently. // If that changes, the delegate below will need to consider top-level nullability. Debug.Assert(!IncludeNullability); return GetTupleLiteralConversion( source, destination, ref useSiteInfo, ConversionKind.ExplicitTupleLiteral, (ConversionsBase conversions, BoundExpression s, TypeWithAnnotations d, ref CompoundUseSiteInfo<AssemblySymbol> u, bool a) => conversions.ClassifyConversionFromExpression(s, d.Type, ref u, a), forCast); } private Conversion GetTupleLiteralConversion( BoundTupleLiteral source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, ConversionKind kind, ClassifyConversionFromExpressionDelegate classifyConversion, bool arg) { var arguments = source.Arguments; // check if the type is actually compatible type for a tuple of given cardinality if (!destination.IsTupleTypeOfCardinality(arguments.Length)) { return Conversion.NoConversion; } var targetElementTypes = destination.TupleElementTypesWithAnnotations; Debug.Assert(arguments.Length == targetElementTypes.Length); // check arguments against flattened list of target element types var argumentConversions = ArrayBuilder<Conversion>.GetInstance(arguments.Length); for (int i = 0; i < arguments.Length; i++) { var argument = arguments[i]; var result = classifyConversion(this, argument, targetElementTypes[i], ref useSiteInfo, arg); if (!result.Exists) { argumentConversions.Free(); return Conversion.NoConversion; } argumentConversions.Add(result); } return new Conversion(kind, argumentConversions.ToImmutableAndFree()); } private Conversion ClassifyImplicitTupleConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { return ClassifyTupleConversion( source, destination, ref useSiteInfo, ConversionKind.ImplicitTuple, (ConversionsBase conversions, TypeWithAnnotations s, TypeWithAnnotations d, ref CompoundUseSiteInfo<AssemblySymbol> u, bool a) => { if (!conversions.HasTopLevelNullabilityImplicitConversion(s, d)) { return Conversion.NoConversion; } return conversions.ClassifyImplicitConversionFromType(s.Type, d.Type, ref u); }, arg: false); } private Conversion ClassifyExplicitTupleConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, bool forCast) { return ClassifyTupleConversion( source, destination, ref useSiteInfo, ConversionKind.ExplicitTuple, (ConversionsBase conversions, TypeWithAnnotations s, TypeWithAnnotations d, ref CompoundUseSiteInfo<AssemblySymbol> u, bool a) => { if (!conversions.HasTopLevelNullabilityImplicitConversion(s, d)) { return Conversion.NoConversion; } return conversions.ClassifyConversionFromType(s.Type, d.Type, ref u, a); }, forCast); } private Conversion ClassifyTupleConversion( TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, ConversionKind kind, ClassifyConversionFromTypeDelegate classifyConversion, bool arg) { ImmutableArray<TypeWithAnnotations> sourceTypes; ImmutableArray<TypeWithAnnotations> destTypes; if (!source.TryGetElementTypesWithAnnotationsIfTupleType(out sourceTypes) || !destination.TryGetElementTypesWithAnnotationsIfTupleType(out destTypes) || sourceTypes.Length != destTypes.Length) { return Conversion.NoConversion; } var nestedConversions = ArrayBuilder<Conversion>.GetInstance(sourceTypes.Length); for (int i = 0; i < sourceTypes.Length; i++) { var conversion = classifyConversion(this, sourceTypes[i], destTypes[i], ref useSiteInfo, arg); if (!conversion.Exists) { nestedConversions.Free(); return Conversion.NoConversion; } nestedConversions.Add(conversion); } return new Conversion(kind, nestedConversions.ToImmutableAndFree()); } private Conversion ClassifyExplicitNullableConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, bool forCast) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); // SPEC: Explicit nullable conversions permit predefined explicit conversions that operate on // SPEC: non-nullable value types to also be used with nullable forms of those types. For // SPEC: each of the predefined explicit conversions that convert from a non-nullable value type // SPEC: S to a non-nullable value type T, the following nullable conversions exist: // SPEC: An explicit conversion from S? to T?. // SPEC: An explicit conversion from S to T?. // SPEC: An explicit conversion from S? to T. if (!source.IsNullableType() && !destination.IsNullableType()) { return Conversion.NoConversion; } TypeSymbol unwrappedSource = source.StrippedType(); TypeSymbol unwrappedDestination = destination.StrippedType(); if (HasIdentityConversionInternal(unwrappedSource, unwrappedDestination)) { return new Conversion(ConversionKind.ExplicitNullable, Conversion.IdentityUnderlying); } if (HasImplicitNumericConversion(unwrappedSource, unwrappedDestination)) { return new Conversion(ConversionKind.ExplicitNullable, Conversion.ImplicitNumericUnderlying); } if (HasExplicitNumericConversion(unwrappedSource, unwrappedDestination)) { return new Conversion(ConversionKind.ExplicitNullable, Conversion.ExplicitNumericUnderlying); } var tupleConversion = ClassifyExplicitTupleConversion(unwrappedSource, unwrappedDestination, ref useSiteInfo, forCast); if (tupleConversion.Exists) { return new Conversion(ConversionKind.ExplicitNullable, ImmutableArray.Create(tupleConversion)); } if (HasExplicitEnumerationConversion(unwrappedSource, unwrappedDestination)) { return new Conversion(ConversionKind.ExplicitNullable, Conversion.ExplicitEnumerationUnderlying); } if (HasPointerToIntegerConversion(unwrappedSource, unwrappedDestination)) { return new Conversion(ConversionKind.ExplicitNullable, Conversion.PointerToIntegerUnderlying); } return Conversion.NoConversion; } private bool HasCovariantArrayConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); var s = source as ArrayTypeSymbol; var d = destination as ArrayTypeSymbol; if ((object)s == null || (object)d == null) { return false; } // * S and T differ only in element type. In other words, S and T have the same number of dimensions. if (!s.HasSameShapeAs(d)) { return false; } // * Both SE and TE are reference types. // * An implicit reference conversion exists from SE to TE. return HasImplicitReferenceConversion(s.ElementTypeWithAnnotations, d.ElementTypeWithAnnotations, ref useSiteInfo); } public bool HasIdentityOrImplicitReferenceConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); if (HasIdentityConversionInternal(source, destination)) { return true; } return HasImplicitReferenceConversion(source, destination, ref useSiteInfo); } private static bool HasImplicitDynamicConversionFromExpression(TypeSymbol expressionType, TypeSymbol destination) { // Spec (§6.1.8) // An implicit dynamic conversion exists from an expression of type dynamic to any type T. Debug.Assert((object)destination != null); return expressionType?.Kind == SymbolKind.DynamicType && !destination.IsPointerOrFunctionPointer(); } private static bool HasExplicitDynamicConversion(TypeSymbol source, TypeSymbol destination) { // SPEC: An explicit dynamic conversion exists from an expression of [sic] type dynamic to any type T. // ISSUE: The "an expression of" part of the spec is probably an error; see https://github.com/dotnet/csharplang/issues/132 Debug.Assert((object)source != null); Debug.Assert((object)destination != null); return source.Kind == SymbolKind.DynamicType && !destination.IsPointerOrFunctionPointer(); } private bool HasArrayConversionToInterface(ArrayTypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); if (!source.IsSZArray) { return false; } if (!destination.IsInterfaceType()) { return false; } // The specification says that there is a conversion: // * From a single-dimensional array type S[] to IList<T> and its base // interfaces, provided that there is an implicit identity or reference // conversion from S to T. // // Newer versions of the framework also have arrays be convertible to // IReadOnlyList<T> and IReadOnlyCollection<T>; we honor that as well. // // Therefore we must check for: // // IList<T> // ICollection<T> // IEnumerable<T> // IEnumerable // IReadOnlyList<T> // IReadOnlyCollection<T> if (destination.SpecialType == SpecialType.System_Collections_IEnumerable) { return true; } NamedTypeSymbol destinationAgg = (NamedTypeSymbol)destination; if (destinationAgg.AllTypeArgumentCount() != 1) { return false; } if (!destinationAgg.IsPossibleArrayGenericInterface()) { return false; } TypeWithAnnotations elementType = source.ElementTypeWithAnnotations; TypeWithAnnotations argument0 = destinationAgg.TypeArgumentWithDefinitionUseSiteDiagnostics(0, ref useSiteInfo); if (IncludeNullability && !HasTopLevelNullabilityImplicitConversion(elementType, argument0)) { return false; } return HasIdentityOrImplicitReferenceConversion(elementType.Type, argument0.Type, ref useSiteInfo); } private bool HasImplicitReferenceConversion(TypeWithAnnotations source, TypeWithAnnotations destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { if (IncludeNullability) { if (!HasTopLevelNullabilityImplicitConversion(source, destination)) { return false; } // Check for identity conversion of underlying types if the top-level nullability is distinct. // (An identity conversion where nullability matches is not considered an implicit reference conversion.) if (source.NullableAnnotation != destination.NullableAnnotation && HasIdentityConversionInternal(source.Type, destination.Type, includeNullability: true)) { return true; } } return HasImplicitReferenceConversion(source.Type, destination.Type, ref useSiteInfo); } internal bool HasImplicitReferenceConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); if (source.IsErrorType()) { return false; } if (!source.IsReferenceType) { return false; } // SPEC: The implicit reference conversions are: // SPEC: UNDONE: From any reference-type to a reference-type T if it has an implicit identity // SPEC: UNDONE: or reference conversion to a reference-type T0 and T0 has an identity conversion to T. // UNDONE: Is the right thing to do here to strip dynamic off and check for convertibility? // SPEC: From any reference type to object and dynamic. if (destination.SpecialType == SpecialType.System_Object || destination.Kind == SymbolKind.DynamicType) { return true; } switch (source.TypeKind) { case TypeKind.Class: // SPEC: From any class type S to any class type T provided S is derived from T. if (destination.IsClassType() && IsBaseClass(source, destination, ref useSiteInfo)) { return true; } return HasImplicitConversionToInterface(source, destination, ref useSiteInfo); case TypeKind.Interface: // SPEC: From any interface-type S to any interface-type T, provided S is derived from T. // NOTE: This handles variance conversions return HasImplicitConversionToInterface(source, destination, ref useSiteInfo); case TypeKind.Delegate: // SPEC: From any delegate-type to System.Delegate and the interfaces it implements. // NOTE: This handles variance conversions. return HasImplicitConversionFromDelegate(source, destination, ref useSiteInfo); case TypeKind.TypeParameter: return HasImplicitReferenceTypeParameterConversion((TypeParameterSymbol)source, destination, ref useSiteInfo); case TypeKind.Array: // SPEC: From an array-type S ... to an array-type T, provided ... // SPEC: From any array-type to System.Array and the interfaces it implements. // SPEC: From a single-dimensional array type S[] to IList<T>, provided ... return HasImplicitConversionFromArray(source, destination, ref useSiteInfo); } // UNDONE: Implicit conversions involving type parameters that are known to be reference types. return false; } private bool HasImplicitConversionToInterface(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { if (!destination.IsInterfaceType()) { return false; } // * From any class type S to any interface type T provided S implements an interface // convertible to T. if (source.IsClassType()) { return HasAnyBaseInterfaceConversion(source, destination, ref useSiteInfo); } // * From any interface type S to any interface type T provided S implements an interface // convertible to T. // * From any interface type S to any interface type T provided S is not T and S is // an interface convertible to T. if (source.IsInterfaceType()) { if (HasAnyBaseInterfaceConversion(source, destination, ref useSiteInfo)) { return true; } if (!HasIdentityConversionInternal(source, destination) && HasInterfaceVarianceConversion(source, destination, ref useSiteInfo)) { return true; } } return false; } private bool HasImplicitConversionFromArray(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { ArrayTypeSymbol s = source as ArrayTypeSymbol; if ((object)s == null) { return false; } // * From an array type S with an element type SE to an array type T with element type TE // provided that all of the following are true: // * S and T differ only in element type. In other words, S and T have the same number of dimensions. // * Both SE and TE are reference types. // * An implicit reference conversion exists from SE to TE. if (HasCovariantArrayConversion(source, destination, ref useSiteInfo)) { return true; } // * From any array type to System.Array or any interface implemented by System.Array. if (destination.GetSpecialTypeSafe() == SpecialType.System_Array) { return true; } if (IsBaseInterface(destination, this.corLibrary.GetDeclaredSpecialType(SpecialType.System_Array), ref useSiteInfo)) { return true; } // * From a single-dimensional array type S[] to IList<T> and its base // interfaces, provided that there is an implicit identity or reference // conversion from S to T. if (HasArrayConversionToInterface(s, destination, ref useSiteInfo)) { return true; } return false; } private bool HasImplicitConversionFromDelegate(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { if (!source.IsDelegateType()) { return false; } // * From any delegate type to System.Delegate // // SPEC OMISSION: // // The spec should actually say // // * From any delegate type to System.Delegate // * From any delegate type to System.MulticastDelegate // * From any delegate type to any interface implemented by System.MulticastDelegate var specialDestination = destination.GetSpecialTypeSafe(); if (specialDestination == SpecialType.System_MulticastDelegate || specialDestination == SpecialType.System_Delegate || IsBaseInterface(destination, this.corLibrary.GetDeclaredSpecialType(SpecialType.System_MulticastDelegate), ref useSiteInfo)) { return true; } // * From any delegate type S to a delegate type T provided S is not T and // S is a delegate convertible to T if (HasDelegateVarianceConversion(source, destination, ref useSiteInfo)) { return true; } return false; } public bool HasImplicitTypeParameterConversion(TypeParameterSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { if (HasImplicitReferenceTypeParameterConversion(source, destination, ref useSiteInfo)) { return true; } if (HasImplicitBoxingTypeParameterConversion(source, destination, ref useSiteInfo)) { return true; } if ((destination.TypeKind == TypeKind.TypeParameter) && source.DependsOn((TypeParameterSymbol)destination)) { return true; } return false; } private bool HasImplicitReferenceTypeParameterConversion(TypeParameterSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); if (source.IsValueType) { return false; // Not a reference conversion. } // The following implicit conversions exist for a given type parameter T: // // * From T to its effective base class C. // * From T to any base class of C. // * From T to any interface implemented by C (or any interface variance-compatible with such) if (HasImplicitEffectiveBaseConversion(source, destination, ref useSiteInfo)) { return true; } // * From T to any interface type I in T's effective interface set, and // from T to any base interface of I (or any interface variance-compatible with such) if (HasImplicitEffectiveInterfaceSetConversion(source, destination, ref useSiteInfo)) { return true; } // * From T to a type parameter U, provided T depends on U. if ((destination.TypeKind == TypeKind.TypeParameter) && source.DependsOn((TypeParameterSymbol)destination)) { return true; } return false; } // Spec 6.1.10: Implicit conversions involving type parameters private bool HasImplicitEffectiveBaseConversion(TypeParameterSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { // * From T to its effective base class C. var effectiveBaseClass = source.EffectiveBaseClass(ref useSiteInfo); if (HasIdentityConversionInternal(effectiveBaseClass, destination)) { return true; } // * From T to any base class of C. if (IsBaseClass(effectiveBaseClass, destination, ref useSiteInfo)) { return true; } // * From T to any interface implemented by C (or any interface variance-compatible with such) if (HasAnyBaseInterfaceConversion(effectiveBaseClass, destination, ref useSiteInfo)) { return true; } return false; } private bool HasImplicitEffectiveInterfaceSetConversion(TypeParameterSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { if (!destination.IsInterfaceType()) { return false; } // * From T to any interface type I in T's effective interface set, and // from T to any base interface of I (or any interface variance-compatible with such) foreach (var i in source.AllEffectiveInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteInfo)) { if (HasInterfaceVarianceConversion(i, destination, ref useSiteInfo)) { return true; } } return false; } private bool HasAnyBaseInterfaceConversion(TypeSymbol derivedType, TypeSymbol baseType, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)derivedType != null); Debug.Assert((object)baseType != null); if (!baseType.IsInterfaceType()) { return false; } var d = derivedType as NamedTypeSymbol; if ((object)d == null) { return false; } foreach (var i in d.AllInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteInfo)) { if (HasInterfaceVarianceConversion(i, baseType, ref useSiteInfo)) { return true; } } return false; } //////////////////////////////////////////////////////////////////////////////// // The rules for variant interface and delegate conversions are the same: // // An interface/delegate type S is convertible to an interface/delegate type T // if and only if T is U<S1, ... Sn> and T is U<T1, ... Tn> such that for all // parameters of U: // // * if the ith parameter of U is invariant then Si is exactly equal to Ti. // * if the ith parameter of U is covariant then either Si is exactly equal // to Ti, or there is an implicit reference conversion from Si to Ti. // * if the ith parameter of U is contravariant then either Si is exactly // equal to Ti, or there is an implicit reference conversion from Ti to Si. private bool HasInterfaceVarianceConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); NamedTypeSymbol s = source as NamedTypeSymbol; NamedTypeSymbol d = destination as NamedTypeSymbol; if ((object)s == null || (object)d == null) { return false; } if (!s.IsInterfaceType() || !d.IsInterfaceType()) { return false; } return HasVariantConversion(s, d, ref useSiteInfo); } private bool HasDelegateVarianceConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); NamedTypeSymbol s = source as NamedTypeSymbol; NamedTypeSymbol d = destination as NamedTypeSymbol; if ((object)s == null || (object)d == null) { return false; } if (!s.IsDelegateType() || !d.IsDelegateType()) { return false; } return HasVariantConversion(s, d, ref useSiteInfo); } private bool HasVariantConversion(NamedTypeSymbol source, NamedTypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { // We check for overflows in HasVariantConversion, because they are only an issue // in the presence of contravariant type parameters, which are not involved in // most conversions. // See VarianceTests for examples (e.g. TestVarianceConversionCycle, // TestVarianceConversionInfiniteExpansion). // // CONSIDER: A more rigorous solution would mimic the CLI approach, which uses // a combination of requiring finite instantiation closures (see section 9.2 of // the CLI spec) and records previous conversion steps to check for cycles. if (currentRecursionDepth >= MaximumRecursionDepth) { // NOTE: The spec doesn't really address what happens if there's an overflow // in our conversion check. It's sort of implied that the conversion "proof" // should be finite, so we'll just say that no conversion is possible. return false; } // Do a quick check up front to avoid instantiating a new Conversions object, // if possible. var quickResult = HasVariantConversionQuick(source, destination); if (quickResult.HasValue()) { return quickResult.Value(); } return this.CreateInstance(currentRecursionDepth + 1). HasVariantConversionNoCycleCheck(source, destination, ref useSiteInfo); } private ThreeState HasVariantConversionQuick(NamedTypeSymbol source, NamedTypeSymbol destination) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); if (HasIdentityConversionInternal(source, destination)) { return ThreeState.True; } NamedTypeSymbol typeSymbol = source.OriginalDefinition; if (!TypeSymbol.Equals(typeSymbol, destination.OriginalDefinition, TypeCompareKind.ConsiderEverything2)) { return ThreeState.False; } return ThreeState.Unknown; } private bool HasVariantConversionNoCycleCheck(NamedTypeSymbol source, NamedTypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); var typeParameters = ArrayBuilder<TypeWithAnnotations>.GetInstance(); var sourceTypeArguments = ArrayBuilder<TypeWithAnnotations>.GetInstance(); var destinationTypeArguments = ArrayBuilder<TypeWithAnnotations>.GetInstance(); try { source.OriginalDefinition.GetAllTypeArguments(typeParameters, ref useSiteInfo); source.GetAllTypeArguments(sourceTypeArguments, ref useSiteInfo); destination.GetAllTypeArguments(destinationTypeArguments, ref useSiteInfo); Debug.Assert(TypeSymbol.Equals(source.OriginalDefinition, destination.OriginalDefinition, TypeCompareKind.AllIgnoreOptions)); Debug.Assert(typeParameters.Count == sourceTypeArguments.Count); Debug.Assert(typeParameters.Count == destinationTypeArguments.Count); for (int paramIndex = 0; paramIndex < typeParameters.Count; ++paramIndex) { var sourceTypeArgument = sourceTypeArguments[paramIndex]; var destinationTypeArgument = destinationTypeArguments[paramIndex]; // If they're identical then this one is automatically good, so skip it. if (HasIdentityConversionInternal(sourceTypeArgument.Type, destinationTypeArgument.Type) && HasTopLevelNullabilityIdentityConversion(sourceTypeArgument, destinationTypeArgument)) { continue; } TypeParameterSymbol typeParameterSymbol = (TypeParameterSymbol)typeParameters[paramIndex].Type; switch (typeParameterSymbol.Variance) { case VarianceKind.None: // System.IEquatable<T> is invariant for back compat reasons (dynamic type checks could start // to succeed where they previously failed, creating different runtime behavior), but the uses // require treatment specifically of nullability as contravariant, so we special case the // behavior here. Normally we use GetWellKnownType for these kinds of checks, but in this // case we don't want just the canonical IEquatable to be special-cased, we want all definitions // to be treated as contravariant, in case there are other definitions in metadata that were // compiled with that expectation. if (isTypeIEquatable(destination.OriginalDefinition) && TypeSymbol.Equals(destinationTypeArgument.Type, sourceTypeArgument.Type, TypeCompareKind.AllNullableIgnoreOptions) && HasAnyNullabilityImplicitConversion(destinationTypeArgument, sourceTypeArgument)) { return true; } return false; case VarianceKind.Out: if (!HasImplicitReferenceConversion(sourceTypeArgument, destinationTypeArgument, ref useSiteInfo)) { return false; } break; case VarianceKind.In: if (!HasImplicitReferenceConversion(destinationTypeArgument, sourceTypeArgument, ref useSiteInfo)) { return false; } break; default: throw ExceptionUtilities.UnexpectedValue(typeParameterSymbol.Variance); } } } finally { typeParameters.Free(); sourceTypeArguments.Free(); destinationTypeArguments.Free(); } return true; static bool isTypeIEquatable(NamedTypeSymbol type) { return type is { IsInterface: true, Name: "IEquatable", ContainingNamespace: { Name: "System", ContainingNamespace: { IsGlobalNamespace: true } }, ContainingSymbol: { Kind: SymbolKind.Namespace }, TypeParameters: { Length: 1 } }; } } // Spec 6.1.10 private bool HasImplicitBoxingTypeParameterConversion(TypeParameterSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); if (source.IsReferenceType) { return false; // Not a boxing conversion; both source and destination are references. } // The following implicit conversions exist for a given type parameter T: // // * From T to its effective base class C. // * From T to any base class of C. // * From T to any interface implemented by C (or any interface variance-compatible with such) if (HasImplicitEffectiveBaseConversion(source, destination, ref useSiteInfo)) { return true; } // * From T to any interface type I in T's effective interface set, and // from T to any base interface of I (or any interface variance-compatible with such) if (HasImplicitEffectiveInterfaceSetConversion(source, destination, ref useSiteInfo)) { return true; } // SPEC: From T to a type parameter U, provided T depends on U if ((destination.TypeKind == TypeKind.TypeParameter) && source.DependsOn((TypeParameterSymbol)destination)) { return true; } // SPEC: From T to a reference type I if it has an implicit conversion to a reference // SPEC: type S0 and S0 has an identity conversion to S. At run-time the conversion // SPEC: is executed the same way as the conversion to S0. // REVIEW: If T is not known to be a reference type then the only way this clause can // REVIEW: come into effect is if the target type is dynamic. Is that correct? if (destination.Kind == SymbolKind.DynamicType) { return true; } return false; } public bool HasBoxingConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); // Certain type parameter conversions are classified as boxing conversions. if ((source.TypeKind == TypeKind.TypeParameter) && HasImplicitBoxingTypeParameterConversion((TypeParameterSymbol)source, destination, ref useSiteInfo)) { return true; } // The rest of the boxing conversions only operate when going from a value type to a // reference type. if (!source.IsValueType || !destination.IsReferenceType) { return false; } // A boxing conversion exists from a nullable type to a reference type if and only if a // boxing conversion exists from the underlying type. if (source.IsNullableType()) { return HasBoxingConversion(source.GetNullableUnderlyingType(), destination, ref useSiteInfo); } // A boxing conversion exists from any non-nullable value type to object and dynamic, to // System.ValueType, and to any interface type variance-compatible with one implemented // by the non-nullable value type. // Furthermore, an enum type can be converted to the type System.Enum. // We set the base class of the structs to System.ValueType, System.Enum, etc, so we can // just check here. // There are a couple of exceptions. The very special types ArgIterator, ArgumentHandle and // TypedReference are not boxable: if (source.IsRestrictedType()) { return false; } if (destination.Kind == SymbolKind.DynamicType) { return !source.IsPointerOrFunctionPointer(); } if (IsBaseClass(source, destination, ref useSiteInfo)) { return true; } if (HasAnyBaseInterfaceConversion(source, destination, ref useSiteInfo)) { return true; } return false; } internal static bool HasImplicitPointerToVoidConversion(TypeSymbol source, TypeSymbol destination) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); // SPEC: The set of implicit conversions is extended to include... // SPEC: ... from any pointer type to the type void*. return source.IsPointerOrFunctionPointer() && destination is PointerTypeSymbol { PointedAtType: { SpecialType: SpecialType.System_Void } }; } #nullable enable internal bool HasImplicitPointerConversion(TypeSymbol? source, TypeSymbol? destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { if (!(source is FunctionPointerTypeSymbol { Signature: { } sourceSig }) || !(destination is FunctionPointerTypeSymbol { Signature: { } destinationSig })) { return false; } if (sourceSig.ParameterCount != destinationSig.ParameterCount || sourceSig.CallingConvention != destinationSig.CallingConvention) { return false; } if (sourceSig.CallingConvention == Cci.CallingConvention.Unmanaged && !sourceSig.GetCallingConventionModifiers().SetEquals(destinationSig.GetCallingConventionModifiers())) { return false; } for (int i = 0; i < sourceSig.ParameterCount; i++) { var sourceParam = sourceSig.Parameters[i]; var destinationParam = destinationSig.Parameters[i]; if (sourceParam.RefKind != destinationParam.RefKind) { return false; } if (!hasConversion(sourceParam.RefKind, destinationSig.Parameters[i].TypeWithAnnotations, sourceSig.Parameters[i].TypeWithAnnotations, ref useSiteInfo)) { return false; } } return sourceSig.RefKind == destinationSig.RefKind && hasConversion(sourceSig.RefKind, sourceSig.ReturnTypeWithAnnotations, destinationSig.ReturnTypeWithAnnotations, ref useSiteInfo); bool hasConversion(RefKind refKind, TypeWithAnnotations sourceType, TypeWithAnnotations destinationType, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { switch (refKind) { case RefKind.None: return (!IncludeNullability || HasTopLevelNullabilityImplicitConversion(sourceType, destinationType)) && (HasIdentityOrImplicitReferenceConversion(sourceType.Type, destinationType.Type, ref useSiteInfo) || HasImplicitPointerToVoidConversion(sourceType.Type, destinationType.Type) || HasImplicitPointerConversion(sourceType.Type, destinationType.Type, ref useSiteInfo)); default: return (!IncludeNullability || HasTopLevelNullabilityIdentityConversion(sourceType, destinationType)) && HasIdentityConversion(sourceType.Type, destinationType.Type); } } } #nullable disable private bool HasIdentityOrReferenceConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); if (HasIdentityConversionInternal(source, destination)) { return true; } if (HasImplicitReferenceConversion(source, destination, ref useSiteInfo)) { return true; } if (HasExplicitReferenceConversion(source, destination, ref useSiteInfo)) { return true; } return false; } private bool HasExplicitReferenceConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); // SPEC: The explicit reference conversions are: // SPEC: From object and dynamic to any other reference type. if (source.SpecialType == SpecialType.System_Object) { if (destination.IsReferenceType) { return true; } } else if (source.Kind == SymbolKind.DynamicType && destination.IsReferenceType) { return true; } // SPEC: From any class-type S to any class-type T, provided S is a base class of T. if (destination.IsClassType() && IsBaseClass(destination, source, ref useSiteInfo)) { return true; } // SPEC: From any class-type S to any interface-type T, provided S is not sealed and provided S does not implement T. // ISSUE: class C : IEnumerable<Mammal> { } converting this to IEnumerable<Animal> is not an explicit conversion, // ISSUE: it is an implicit conversion. if (source.IsClassType() && destination.IsInterfaceType() && !source.IsSealed && !HasAnyBaseInterfaceConversion(source, destination, ref useSiteInfo)) { return true; } // SPEC: From any interface-type S to any class-type T, provided T is not sealed or provided T implements S. // ISSUE: What if T is sealed and implements an interface variance-convertible to S? // ISSUE: eg, sealed class C : IEnum<Mammal> { ... } you should be able to cast an IEnum<Animal> to C. if (source.IsInterfaceType() && destination.IsClassType() && (!destination.IsSealed || HasAnyBaseInterfaceConversion(destination, source, ref useSiteInfo))) { return true; } // SPEC: From any interface-type S to any interface-type T, provided S is not derived from T. // ISSUE: This does not rule out identity conversions, which ought not to be classified as // ISSUE: explicit reference conversions. // ISSUE: IEnumerable<Mammal> and IEnumerable<Animal> do not derive from each other but this is // ISSUE: not an explicit reference conversion, this is an implicit reference conversion. if (source.IsInterfaceType() && destination.IsInterfaceType() && !HasImplicitConversionToInterface(source, destination, ref useSiteInfo)) { return true; } // SPEC: UNDONE: From a reference type to a reference type T if it has an explicit reference conversion to a reference type T0 and T0 has an identity conversion T. // SPEC: UNDONE: From a reference type to an interface or delegate type T if it has an explicit reference conversion to an interface or delegate type T0 and either T0 is variance-convertible to T or T is variance-convertible to T0 (§13.1.3.2). if (HasExplicitArrayConversion(source, destination, ref useSiteInfo)) { return true; } if (HasExplicitDelegateConversion(source, destination, ref useSiteInfo)) { return true; } if (HasExplicitReferenceTypeParameterConversion(source, destination, ref useSiteInfo)) { return true; } return false; } // Spec 6.2.7 Explicit conversions involving type parameters private bool HasExplicitReferenceTypeParameterConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); TypeParameterSymbol s = source as TypeParameterSymbol; TypeParameterSymbol t = destination as TypeParameterSymbol; // SPEC: The following explicit conversions exist for a given type parameter T: // SPEC: If T is known to be a reference type, the conversions are all classified as explicit reference conversions. // SPEC: If T is not known to be a reference type, the conversions are classified as unboxing conversions. // SPEC: From the effective base class C of T to T and from any base class of C to T. if ((object)t != null && t.IsReferenceType) { for (var type = t.EffectiveBaseClass(ref useSiteInfo); (object)type != null; type = type.BaseTypeWithDefinitionUseSiteDiagnostics(ref useSiteInfo)) { if (HasIdentityConversionInternal(type, source)) { return true; } } } // SPEC: From any interface type to T. if ((object)t != null && source.IsInterfaceType() && t.IsReferenceType) { return true; } // SPEC: From T to any interface-type I provided there is not already an implicit conversion from T to I. if ((object)s != null && s.IsReferenceType && destination.IsInterfaceType() && !HasImplicitReferenceTypeParameterConversion(s, destination, ref useSiteInfo)) { return true; } // SPEC: From a type parameter U to T, provided T depends on U (§10.1.5) if ((object)s != null && (object)t != null && t.IsReferenceType && t.DependsOn(s)) { return true; } return false; } // Spec 6.2.7 Explicit conversions involving type parameters private bool HasUnboxingTypeParameterConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); TypeParameterSymbol s = source as TypeParameterSymbol; TypeParameterSymbol t = destination as TypeParameterSymbol; // SPEC: The following explicit conversions exist for a given type parameter T: // SPEC: If T is known to be a reference type, the conversions are all classified as explicit reference conversions. // SPEC: If T is not known to be a reference type, the conversions are classified as unboxing conversions. // SPEC: From the effective base class C of T to T and from any base class of C to T. if ((object)t != null && !t.IsReferenceType) { for (var type = t.EffectiveBaseClass(ref useSiteInfo); (object)type != null; type = type.BaseTypeWithDefinitionUseSiteDiagnostics(ref useSiteInfo)) { if (TypeSymbol.Equals(type, source, TypeCompareKind.ConsiderEverything2)) { return true; } } } // SPEC: From any interface type to T. if (source.IsInterfaceType() && (object)t != null && !t.IsReferenceType) { return true; } // SPEC: From T to any interface-type I provided there is not already an implicit conversion from T to I. if ((object)s != null && !s.IsReferenceType && destination.IsInterfaceType() && !HasImplicitReferenceTypeParameterConversion(s, destination, ref useSiteInfo)) { return true; } // SPEC: From a type parameter U to T, provided T depends on U (§10.1.5) if ((object)s != null && (object)t != null && !t.IsReferenceType && t.DependsOn(s)) { return true; } return false; } private bool HasExplicitDelegateConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); // SPEC: From System.Delegate and the interfaces it implements to any delegate-type. // We also support System.MulticastDelegate in the implementation, in spite of it not being mentioned in the spec. if (destination.IsDelegateType()) { if (source.SpecialType == SpecialType.System_Delegate || source.SpecialType == SpecialType.System_MulticastDelegate) { return true; } if (HasImplicitConversionToInterface(this.corLibrary.GetDeclaredSpecialType(SpecialType.System_Delegate), source, ref useSiteInfo)) { return true; } } // SPEC: From D<S1...Sn> to a D<T1...Tn> where D<X1...Xn> is a generic delegate type, D<S1...Sn> is not compatible with or identical to D<T1...Tn>, // SPEC: and for each type parameter Xi of D the following holds: // SPEC: If Xi is invariant, then Si is identical to Ti. // SPEC: If Xi is covariant, then there is an implicit or explicit identity or reference conversion from Si to Ti. // SPECL If Xi is contravariant, then Si and Ti are either identical or both reference types. if (!source.IsDelegateType() || !destination.IsDelegateType()) { return false; } if (!TypeSymbol.Equals(source.OriginalDefinition, destination.OriginalDefinition, TypeCompareKind.ConsiderEverything2)) { return false; } var sourceType = (NamedTypeSymbol)source; var destinationType = (NamedTypeSymbol)destination; var original = sourceType.OriginalDefinition; if (HasIdentityConversionInternal(source, destination)) { return false; } if (HasDelegateVarianceConversion(source, destination, ref useSiteInfo)) { return false; } var sourceTypeArguments = sourceType.TypeArgumentsWithDefinitionUseSiteDiagnostics(ref useSiteInfo); var destinationTypeArguments = destinationType.TypeArgumentsWithDefinitionUseSiteDiagnostics(ref useSiteInfo); for (int i = 0; i < sourceTypeArguments.Length; ++i) { var sourceArg = sourceTypeArguments[i].Type; var destinationArg = destinationTypeArguments[i].Type; switch (original.TypeParameters[i].Variance) { case VarianceKind.None: if (!HasIdentityConversionInternal(sourceArg, destinationArg)) { return false; } break; case VarianceKind.Out: if (!HasIdentityOrReferenceConversion(sourceArg, destinationArg, ref useSiteInfo)) { return false; } break; case VarianceKind.In: bool hasIdentityConversion = HasIdentityConversionInternal(sourceArg, destinationArg); bool bothAreReferenceTypes = sourceArg.IsReferenceType && destinationArg.IsReferenceType; if (!(hasIdentityConversion || bothAreReferenceTypes)) { return false; } break; } } return true; } private bool HasExplicitArrayConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); var sourceArray = source as ArrayTypeSymbol; var destinationArray = destination as ArrayTypeSymbol; // SPEC: From an array-type S with an element type SE to an array-type T with an element type TE, provided all of the following are true: // SPEC: S and T differ only in element type. (In other words, S and T have the same number of dimensions.) // SPEC: Both SE and TE are reference-types. // SPEC: An explicit reference conversion exists from SE to TE. if ((object)sourceArray != null && (object)destinationArray != null) { // HasExplicitReferenceConversion checks that SE and TE are reference types so // there's no need for that check here. Moreover, it's not as simple as checking // IsReferenceType, at least not in the case of type parameters, since SE will be // considered a reference type implicitly in the case of "where TE : class, SE" even // though SE.IsReferenceType may be false. Again, HasExplicitReferenceConversion // already handles these cases. return sourceArray.HasSameShapeAs(destinationArray) && HasExplicitReferenceConversion(sourceArray.ElementType, destinationArray.ElementType, ref useSiteInfo); } // SPEC: From System.Array and the interfaces it implements to any array-type. if ((object)destinationArray != null) { if (source.SpecialType == SpecialType.System_Array) { return true; } foreach (var iface in this.corLibrary.GetDeclaredSpecialType(SpecialType.System_Array).AllInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteInfo)) { if (HasIdentityConversionInternal(iface, source)) { return true; } } } // SPEC: From a single-dimensional array type S[] to System.Collections.Generic.IList<T> and its base interfaces // SPEC: provided that there is an explicit reference conversion from S to T. // The framework now also allows arrays to be converted to IReadOnlyList<T> and IReadOnlyCollection<T>; we // honor that as well. if ((object)sourceArray != null && sourceArray.IsSZArray && destination.IsPossibleArrayGenericInterface()) { if (HasExplicitReferenceConversion(sourceArray.ElementType, ((NamedTypeSymbol)destination).TypeArgumentWithDefinitionUseSiteDiagnostics(0, ref useSiteInfo).Type, ref useSiteInfo)) { return true; } } // SPEC: From System.Collections.Generic.IList<S> and its base interfaces to a single-dimensional array type T[], // provided that there is an explicit identity or reference conversion from S to T. // Similarly, we honor IReadOnlyList<S> and IReadOnlyCollection<S> in the same way. if ((object)destinationArray != null && destinationArray.IsSZArray) { var specialDefinition = ((TypeSymbol)source.OriginalDefinition).SpecialType; if (specialDefinition == SpecialType.System_Collections_Generic_IList_T || specialDefinition == SpecialType.System_Collections_Generic_ICollection_T || specialDefinition == SpecialType.System_Collections_Generic_IEnumerable_T || specialDefinition == SpecialType.System_Collections_Generic_IReadOnlyList_T || specialDefinition == SpecialType.System_Collections_Generic_IReadOnlyCollection_T) { var sourceElement = ((NamedTypeSymbol)source).TypeArgumentWithDefinitionUseSiteDiagnostics(0, ref useSiteInfo).Type; var destinationElement = destinationArray.ElementType; if (HasIdentityConversionInternal(sourceElement, destinationElement)) { return true; } if (HasImplicitReferenceConversion(sourceElement, destinationElement, ref useSiteInfo)) { return true; } if (HasExplicitReferenceConversion(sourceElement, destinationElement, ref useSiteInfo)) { return true; } } } return false; } private bool HasUnboxingConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); if (destination.IsPointerOrFunctionPointer()) { return false; } // Ref-like types cannot be boxed or unboxed if (destination.IsRestrictedType()) { return false; } // SPEC: An unboxing conversion permits a reference type to be explicitly converted to a value-type. // SPEC: An unboxing conversion exists from the types object and System.ValueType to any non-nullable-value-type, var specialTypeSource = source.SpecialType; if (specialTypeSource == SpecialType.System_Object || specialTypeSource == SpecialType.System_ValueType) { if (destination.IsValueType && !destination.IsNullableType()) { return true; } } // SPEC: and from any interface-type to any non-nullable-value-type that implements the interface-type. if (source.IsInterfaceType() && destination.IsValueType && !destination.IsNullableType() && HasBoxingConversion(destination, source, ref useSiteInfo)) { return true; } // SPEC: Furthermore type System.Enum can be unboxed to any enum-type. if (source.SpecialType == SpecialType.System_Enum && destination.IsEnumType()) { return true; } // SPEC: An unboxing conversion exists from a reference type to a nullable-type if an unboxing // SPEC: conversion exists from the reference type to the underlying non-nullable-value-type // SPEC: of the nullable-type. if (source.IsReferenceType && destination.IsNullableType() && HasUnboxingConversion(source, destination.GetNullableUnderlyingType(), ref useSiteInfo)) { return true; } // SPEC: UNDONE A value type S has an unboxing conversion from an interface type I if it has an unboxing // SPEC: UNDONE conversion from an interface type I0 and I0 has an identity conversion to I. // SPEC: UNDONE A value type S has an unboxing conversion from an interface type I if it has an unboxing conversion // SPEC: UNDONE from an interface or delegate type I0 and either I0 is variance-convertible to I or I is variance-convertible to I0. if (HasUnboxingTypeParameterConversion(source, destination, ref useSiteInfo)) { return true; } return false; } private static bool HasPointerToPointerConversion(TypeSymbol source, TypeSymbol destination) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); return source.IsPointerOrFunctionPointer() && destination.IsPointerOrFunctionPointer(); } private static bool HasPointerToIntegerConversion(TypeSymbol source, TypeSymbol destination) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); if (!source.IsPointerOrFunctionPointer()) { return false; } // SPEC OMISSION: // // The spec should state that any pointer type is convertible to // sbyte, byte, ... etc, or any corresponding nullable type. return IsIntegerTypeSupportingPointerConversions(destination.StrippedType()); } private static bool HasIntegerToPointerConversion(TypeSymbol source, TypeSymbol destination) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); if (!destination.IsPointerOrFunctionPointer()) { return false; } // Note that void* is convertible to int?, but int? is not convertible to void*. return IsIntegerTypeSupportingPointerConversions(source); } private static bool IsIntegerTypeSupportingPointerConversions(TypeSymbol type) { switch (type.SpecialType) { case SpecialType.System_SByte: case SpecialType.System_Byte: case SpecialType.System_Int16: case SpecialType.System_UInt16: case SpecialType.System_Int32: case SpecialType.System_UInt32: case SpecialType.System_Int64: case SpecialType.System_UInt64: return true; case SpecialType.System_IntPtr: case SpecialType.System_UIntPtr: return type.IsNativeIntegerType; } 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 System.Diagnostics.CodeAnalysis; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { internal abstract partial class ConversionsBase { private const int MaximumRecursionDepth = 50; protected readonly AssemblySymbol corLibrary; protected readonly int currentRecursionDepth; internal readonly bool IncludeNullability; /// <summary> /// An optional clone of this instance with distinct IncludeNullability. /// Used to avoid unnecessary allocations when calling WithNullability() repeatedly. /// </summary> private ConversionsBase _lazyOtherNullability; protected ConversionsBase(AssemblySymbol corLibrary, int currentRecursionDepth, bool includeNullability, ConversionsBase otherNullabilityOpt) { Debug.Assert((object)corLibrary != null); Debug.Assert(otherNullabilityOpt == null || includeNullability != otherNullabilityOpt.IncludeNullability); Debug.Assert(otherNullabilityOpt == null || currentRecursionDepth == otherNullabilityOpt.currentRecursionDepth); this.corLibrary = corLibrary; this.currentRecursionDepth = currentRecursionDepth; IncludeNullability = includeNullability; _lazyOtherNullability = otherNullabilityOpt; } /// <summary> /// Returns this instance if includeNullability is correct, and returns a /// cached clone of this instance with distinct IncludeNullability otherwise. /// </summary> internal ConversionsBase WithNullability(bool includeNullability) { if (IncludeNullability == includeNullability) { return this; } if (_lazyOtherNullability == null) { Interlocked.CompareExchange(ref _lazyOtherNullability, WithNullabilityCore(includeNullability), null); } Debug.Assert(_lazyOtherNullability.IncludeNullability == includeNullability); Debug.Assert(_lazyOtherNullability._lazyOtherNullability == this); return _lazyOtherNullability; } protected abstract ConversionsBase WithNullabilityCore(bool includeNullability); public abstract Conversion GetMethodGroupDelegateConversion(BoundMethodGroup source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo); public abstract Conversion GetMethodGroupFunctionPointerConversion(BoundMethodGroup source, FunctionPointerTypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo); public abstract Conversion GetStackAllocConversion(BoundStackAllocArrayCreation sourceExpression, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo); protected abstract ConversionsBase CreateInstance(int currentRecursionDepth); protected abstract Conversion GetInterpolatedStringConversion(BoundUnconvertedInterpolatedString source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo); internal AssemblySymbol CorLibrary { get { return corLibrary; } } /// <summary> /// Determines if the source expression is convertible to the destination type via /// any built-in or user-defined implicit conversion. /// </summary> public Conversion ClassifyImplicitConversionFromExpression(BoundExpression sourceExpression, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(sourceExpression != null); Debug.Assert((object)destination != null); var sourceType = sourceExpression.Type; //PERF: identity conversion is by far the most common implicit conversion, check for that first if ((object)sourceType != null && HasIdentityConversionInternal(sourceType, destination)) { return Conversion.Identity; } Conversion conversion = ClassifyImplicitBuiltInConversionFromExpression(sourceExpression, sourceType, destination, ref useSiteInfo); if (conversion.Exists) { return conversion; } if ((object)sourceType != null) { // Try using the short-circuit "fast-conversion" path. Conversion fastConversion = FastClassifyConversion(sourceType, destination); if (fastConversion.Exists) { if (fastConversion.IsImplicit) { return fastConversion; } } else { conversion = ClassifyImplicitBuiltInConversionSlow(sourceType, destination, ref useSiteInfo); if (conversion.Exists) { return conversion; } } } conversion = GetImplicitUserDefinedConversion(sourceExpression, sourceType, destination, ref useSiteInfo); if (conversion.Exists) { return conversion; } // The switch expression conversion is "lowest priority", so that if there is a conversion from the expression's // type it will be preferred over the switch expression conversion. Technically, we would want the language // specification to say that the switch expression conversion only "exists" if there is no implicit conversion // from the type, and we accomplish that by making it lowest priority. The same is true for the conditional // expression conversion. conversion = GetSwitchExpressionConversion(sourceExpression, destination, ref useSiteInfo); if (conversion.Exists) { return conversion; } return GetConditionalExpressionConversion(sourceExpression, destination, ref useSiteInfo); } /// <summary> /// Determines if the source type is convertible to the destination type via /// any built-in or user-defined implicit conversion. /// </summary> public Conversion ClassifyImplicitConversionFromType(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); //PERF: identity conversions are very common, check for that first. if (HasIdentityConversionInternal(source, destination)) { return Conversion.Identity; } // Try using the short-circuit "fast-conversion" path. Conversion fastConversion = FastClassifyConversion(source, destination); if (fastConversion.Exists) { return fastConversion.IsImplicit ? fastConversion : Conversion.NoConversion; } else { Conversion conversion = ClassifyImplicitBuiltInConversionSlow(source, destination, ref useSiteInfo); if (conversion.Exists) { return conversion; } } return GetImplicitUserDefinedConversion(null, source, destination, ref useSiteInfo); } /// <summary> /// Determines if the source expression of given type is convertible to the destination type via /// any built-in or user-defined conversion. /// /// This helper is used in rare cases involving synthesized expressions where we know the type of an expression, but do not have the actual expression. /// The reason for this helper (as opposed to ClassifyConversionFromType) is that conversions from expressions could be different /// from conversions from type. For example expressions of dynamic type are implicitly convertable to any type, while dynamic type itself is not. /// </summary> public Conversion ClassifyConversionFromExpressionType(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); // since we are converting from expression, we may have implicit dynamic conversion if (HasImplicitDynamicConversionFromExpression(source, destination)) { return Conversion.ImplicitDynamic; } return ClassifyConversionFromType(source, destination, ref useSiteInfo); } private static bool TryGetVoidConversion(TypeSymbol source, TypeSymbol destination, out Conversion conversion) { var sourceIsVoid = source?.SpecialType == SpecialType.System_Void; var destIsVoid = destination.SpecialType == SpecialType.System_Void; // 'void' is not supposed to be able to convert to or from anything, but in practice, // a lot of code depends on checking whether an expression of type 'void' is convertible to 'void'. // (e.g. for an expression lambda which returns void). // Therefore we allow an identity conversion between 'void' and 'void'. if (sourceIsVoid && destIsVoid) { conversion = Conversion.Identity; return true; } // If exactly one of source or destination is of type 'void' then no conversion may exist. if (sourceIsVoid || destIsVoid) { conversion = Conversion.NoConversion; return true; } conversion = default; return false; } /// <summary> /// Determines if the source expression is convertible to the destination type via /// any conversion: implicit, explicit, user-defined or built-in. /// </summary> /// <remarks> /// It is rare but possible for a source expression to be convertible to a destination type /// by both an implicit user-defined conversion and a built-in explicit conversion. /// In that circumstance, this method classifies the conversion as the implicit conversion or explicit depending on "forCast" /// </remarks> public Conversion ClassifyConversionFromExpression(BoundExpression sourceExpression, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, bool forCast = false) { Debug.Assert(sourceExpression != null); Debug.Assert((object)destination != null); if (TryGetVoidConversion(sourceExpression.Type, destination, out var conversion)) { return conversion; } if (forCast) { return ClassifyConversionFromExpressionForCast(sourceExpression, destination, ref useSiteInfo); } var result = ClassifyImplicitConversionFromExpression(sourceExpression, destination, ref useSiteInfo); if (result.Exists) { return result; } return ClassifyExplicitOnlyConversionFromExpression(sourceExpression, destination, ref useSiteInfo, forCast: false); } /// <summary> /// Determines if the source type is convertible to the destination type via /// any conversion: implicit, explicit, user-defined or built-in. /// </summary> /// <remarks> /// It is rare but possible for a source type to be convertible to a destination type /// by both an implicit user-defined conversion and a built-in explicit conversion. /// In that circumstance, this method classifies the conversion as the implicit conversion or explicit depending on "forCast" /// </remarks> public Conversion ClassifyConversionFromType(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, bool forCast = false) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); if (TryGetVoidConversion(source, destination, out var voidConversion)) { return voidConversion; } if (forCast) { return ClassifyConversionFromTypeForCast(source, destination, ref useSiteInfo); } // Try using the short-circuit "fast-conversion" path. Conversion fastConversion = FastClassifyConversion(source, destination); if (fastConversion.Exists) { return fastConversion; } else { Conversion conversion1 = ClassifyImplicitBuiltInConversionSlow(source, destination, ref useSiteInfo); if (conversion1.Exists) { return conversion1; } } Conversion conversion = GetImplicitUserDefinedConversion(null, source, destination, ref useSiteInfo); if (conversion.Exists) { return conversion; } conversion = ClassifyExplicitBuiltInOnlyConversion(source, destination, ref useSiteInfo, forCast: false); if (conversion.Exists) { return conversion; } return GetExplicitUserDefinedConversion(null, source, destination, ref useSiteInfo); } /// <summary> /// Determines if the source expression is convertible to the destination type via /// any conversion: implicit, explicit, user-defined or built-in. /// </summary> /// <remarks> /// It is rare but possible for a source expression to be convertible to a destination type /// by both an implicit user-defined conversion and a built-in explicit conversion. /// In that circumstance, this method classifies the conversion as the built-in conversion. /// /// An implicit conversion exists from an expression of a dynamic type to any type. /// An explicit conversion exists from a dynamic type to any type. /// When casting we prefer the explicit conversion. /// </remarks> private Conversion ClassifyConversionFromExpressionForCast(BoundExpression source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(source != null); Debug.Assert((object)destination != null); Conversion implicitConversion = ClassifyImplicitConversionFromExpression(source, destination, ref useSiteInfo); if (implicitConversion.Exists && !ExplicitConversionMayDifferFromImplicit(implicitConversion)) { return implicitConversion; } Conversion explicitConversion = ClassifyExplicitOnlyConversionFromExpression(source, destination, ref useSiteInfo, forCast: true); if (explicitConversion.Exists) { return explicitConversion; } // It is possible for a user-defined conversion to be unambiguous when considered as // an implicit conversion and ambiguous when considered as an explicit conversion. // The native compiler does not check to see if a cast could be successfully bound as // an unambiguous user-defined implicit conversion; it goes right to the ambiguous // user-defined explicit conversion and produces an error. This means that in // C# 5 it is possible to have: // // Y y = new Y(); // Z z1 = y; // // succeed but // // Z z2 = (Z)y; // // fail. // // However, there is another interesting wrinkle. It is possible for both // an implicit user-defined conversion and an explicit user-defined conversion // to exist and be unambiguous. For example, if there is an implicit conversion // double-->C and an explicit conversion from int-->C, and the user casts a short // to C, then both the implicit and explicit conversions are applicable and // unambiguous. The native compiler in this case prefers the explicit conversion, // and for backwards compatibility, we match it. return implicitConversion; } /// <summary> /// Determines if the source type is convertible to the destination type via /// any conversion: implicit, explicit, user-defined or built-in. /// </summary> /// <remarks> /// It is rare but possible for a source type to be convertible to a destination type /// by both an implicit user-defined conversion and a built-in explicit conversion. /// In that circumstance, this method classifies the conversion as the built-in conversion. /// </remarks> private Conversion ClassifyConversionFromTypeForCast(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); // Try using the short-circuit "fast-conversion" path. Conversion fastConversion = FastClassifyConversion(source, destination); if (fastConversion.Exists) { return fastConversion; } Conversion implicitBuiltInConversion = ClassifyImplicitBuiltInConversionSlow(source, destination, ref useSiteInfo); if (implicitBuiltInConversion.Exists && !ExplicitConversionMayDifferFromImplicit(implicitBuiltInConversion)) { return implicitBuiltInConversion; } Conversion explicitBuiltInConversion = ClassifyExplicitBuiltInOnlyConversion(source, destination, ref useSiteInfo, forCast: true); if (explicitBuiltInConversion.Exists) { return explicitBuiltInConversion; } if (implicitBuiltInConversion.Exists) { return implicitBuiltInConversion; } // It is possible for a user-defined conversion to be unambiguous when considered as // an implicit conversion and ambiguous when considered as an explicit conversion. // The native compiler does not check to see if a cast could be successfully bound as // an unambiguous user-defined implicit conversion; it goes right to the ambiguous // user-defined explicit conversion and produces an error. This means that in // C# 5 it is possible to have: // // Y y = new Y(); // Z z1 = y; // // succeed but // // Z z2 = (Z)y; // // fail. var conversion = GetExplicitUserDefinedConversion(null, source, destination, ref useSiteInfo); if (conversion.Exists) { return conversion; } return GetImplicitUserDefinedConversion(null, source, destination, ref useSiteInfo); } /// <summary> /// Attempt a quick classification of builtin conversions. As result of "no conversion" /// means that there is no built-in conversion, though there still may be a user-defined /// conversion if compiling against a custom mscorlib. /// </summary> public static Conversion FastClassifyConversion(TypeSymbol source, TypeSymbol target) { ConversionKind convKind = ConversionEasyOut.ClassifyConversion(source, target); if (convKind != ConversionKind.ImplicitNullable && convKind != ConversionKind.ExplicitNullable) { return Conversion.GetTrivialConversion(convKind); } return Conversion.MakeNullableConversion(convKind, FastClassifyConversion(source.StrippedType(), target.StrippedType())); } public Conversion ClassifyBuiltInConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); // Try using the short-circuit "fast-conversion" path. Conversion fastConversion = FastClassifyConversion(source, destination); if (fastConversion.Exists) { return fastConversion; } else { Conversion conversion = ClassifyImplicitBuiltInConversionSlow(source, destination, ref useSiteInfo); if (conversion.Exists) { return conversion; } } return ClassifyExplicitBuiltInOnlyConversion(source, destination, ref useSiteInfo, forCast: false); } /// <summary> /// Determines if the source type is convertible to the destination type via /// any standard implicit or standard explicit conversion. /// </summary> /// <remarks> /// Not all built-in explicit conversions are standard explicit conversions. /// </remarks> public Conversion ClassifyStandardConversion(BoundExpression sourceExpression, TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(sourceExpression != null || (object)source != null); Debug.Assert((object)destination != null); // Note that the definition of explicit standard conversion does not include all explicit // reference conversions! There is a standard implicit reference conversion from // Action<Object> to Action<Exception>, thanks to contravariance. There is a standard // implicit reference conversion from Action<Object> to Action<String> for the same reason. // Therefore there is an explicit reference conversion from Action<Exception> to // Action<String>; a given Action<Exception> might be an Action<Object>, and hence // convertible to Action<String>. However, this is not a *standard* explicit conversion. The // standard explicit conversions are all the standard implicit conversions and their // opposites. Therefore Action<Object>-->Action<String> and Action<String>-->Action<Object> // are both standard conversions. But Action<String>-->Action<Exception> is not a standard // explicit conversion because neither it nor its opposite is a standard implicit // conversion. // // Similarly, there is no standard explicit conversion from double to decimal, because // there is no standard implicit conversion between the two types. // SPEC: The standard explicit conversions are all standard implicit conversions plus // SPEC: the subset of the explicit conversions for which an opposite standard implicit // SPEC: conversion exists. In other words, if a standard implicit conversion exists from // SPEC: a type A to a type B, then a standard explicit conversion exists from type A to // SPEC: type B and from type B to type A. Conversion conversion = ClassifyStandardImplicitConversion(sourceExpression, source, destination, ref useSiteInfo); if (conversion.Exists) { return conversion; } if ((object)source != null) { return DeriveStandardExplicitFromOppositeStandardImplicitConversion(source, destination, ref useSiteInfo); } return Conversion.NoConversion; } private Conversion ClassifyStandardImplicitConversion(BoundExpression sourceExpression, TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(sourceExpression != null || (object)source != null); Debug.Assert(sourceExpression == null || (object)sourceExpression.Type == (object)source); Debug.Assert((object)destination != null); // SPEC: The following implicit conversions are classified as standard implicit conversions: // SPEC: Identity conversions // SPEC: Implicit numeric conversions // SPEC: Implicit nullable conversions // SPEC: Implicit reference conversions // SPEC: Boxing conversions // SPEC: Implicit constant expression conversions // SPEC: Implicit conversions involving type parameters // // and in unsafe code: // // SPEC: From any pointer type to void* // // SPEC ERROR: // The specification does not say to take into account the conversion from // the *expression*, only its *type*. But the expression may not have a type // (because it is null, a method group, or a lambda), or the expression might // be convertible to the destination type via a constant numeric conversion. // For example, the native compiler allows "C c = 1;" to work if C is a class which // has an implicit conversion from byte to C, despite the fact that there is // obviously no standard implicit conversion from *int* to *byte*. // Similarly, if a struct S has an implicit conversion from string to S, then // "S s = null;" should be allowed. // // We extend the definition of standard implicit conversions to include // all of the implicit conversions that are allowed based on an expression, // with the exception of the switch expression conversion. Conversion conversion = ClassifyImplicitBuiltInConversionFromExpression(sourceExpression, source, destination, ref useSiteInfo); if (conversion.Exists) { return conversion; } if ((object)source != null) { return ClassifyStandardImplicitConversion(source, destination, ref useSiteInfo); } return Conversion.NoConversion; } private Conversion ClassifyStandardImplicitConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); if (HasIdentityConversionInternal(source, destination)) { return Conversion.Identity; } if (HasImplicitNumericConversion(source, destination)) { return Conversion.ImplicitNumeric; } var nullableConversion = ClassifyImplicitNullableConversion(source, destination, ref useSiteInfo); if (nullableConversion.Exists) { return nullableConversion; } if (HasImplicitReferenceConversion(source, destination, ref useSiteInfo)) { return Conversion.ImplicitReference; } if (HasBoxingConversion(source, destination, ref useSiteInfo)) { return Conversion.Boxing; } if (HasImplicitPointerToVoidConversion(source, destination)) { return Conversion.PointerToVoid; } if (HasImplicitPointerConversion(source, destination, ref useSiteInfo)) { return Conversion.ImplicitPointer; } var tupleConversion = ClassifyImplicitTupleConversion(source, destination, ref useSiteInfo); if (tupleConversion.Exists) { return tupleConversion; } return Conversion.NoConversion; } private Conversion ClassifyImplicitBuiltInConversionSlow(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); if (source.IsVoidType() || destination.IsVoidType()) { return Conversion.NoConversion; } Conversion conversion = ClassifyStandardImplicitConversion(source, destination, ref useSiteInfo); if (conversion.Exists) { return conversion; } return Conversion.NoConversion; } private Conversion GetImplicitUserDefinedConversion(BoundExpression sourceExpression, TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { var conversionResult = AnalyzeImplicitUserDefinedConversions(sourceExpression, source, destination, ref useSiteInfo); return new Conversion(conversionResult, isImplicit: true); } private Conversion ClassifyExplicitBuiltInOnlyConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, bool forCast) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); if (source.IsVoidType() || destination.IsVoidType()) { return Conversion.NoConversion; } // The call to HasExplicitNumericConversion isn't necessary, because it is always tested // already by the "FastConversion" code. Debug.Assert(!HasExplicitNumericConversion(source, destination)); //if (HasExplicitNumericConversion(source, specialTypeSource, destination, specialTypeDest)) //{ // return Conversion.ExplicitNumeric; //} if (HasSpecialIntPtrConversion(source, destination)) { return Conversion.IntPtr; } if (HasExplicitEnumerationConversion(source, destination)) { return Conversion.ExplicitEnumeration; } var nullableConversion = ClassifyExplicitNullableConversion(source, destination, ref useSiteInfo, forCast); if (nullableConversion.Exists) { return nullableConversion; } if (HasExplicitReferenceConversion(source, destination, ref useSiteInfo)) { return (source.Kind == SymbolKind.DynamicType) ? Conversion.ExplicitDynamic : Conversion.ExplicitReference; } if (HasUnboxingConversion(source, destination, ref useSiteInfo)) { return Conversion.Unboxing; } var tupleConversion = ClassifyExplicitTupleConversion(source, destination, ref useSiteInfo, forCast); if (tupleConversion.Exists) { return tupleConversion; } if (HasPointerToPointerConversion(source, destination)) { return Conversion.PointerToPointer; } if (HasPointerToIntegerConversion(source, destination)) { return Conversion.PointerToInteger; } if (HasIntegerToPointerConversion(source, destination)) { return Conversion.IntegerToPointer; } if (HasExplicitDynamicConversion(source, destination)) { return Conversion.ExplicitDynamic; } return Conversion.NoConversion; } private Conversion GetExplicitUserDefinedConversion(BoundExpression sourceExpression, TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { UserDefinedConversionResult conversionResult = AnalyzeExplicitUserDefinedConversions(sourceExpression, source, destination, ref useSiteInfo); return new Conversion(conversionResult, isImplicit: false); } private Conversion DeriveStandardExplicitFromOppositeStandardImplicitConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { var oppositeConversion = ClassifyStandardImplicitConversion(destination, source, ref useSiteInfo); Conversion impliedExplicitConversion; switch (oppositeConversion.Kind) { case ConversionKind.Identity: impliedExplicitConversion = Conversion.Identity; break; case ConversionKind.ImplicitNumeric: impliedExplicitConversion = Conversion.ExplicitNumeric; break; case ConversionKind.ImplicitReference: impliedExplicitConversion = Conversion.ExplicitReference; break; case ConversionKind.Boxing: impliedExplicitConversion = Conversion.Unboxing; break; case ConversionKind.NoConversion: impliedExplicitConversion = Conversion.NoConversion; break; case ConversionKind.ImplicitPointerToVoid: impliedExplicitConversion = Conversion.PointerToPointer; break; case ConversionKind.ImplicitTuple: // only implicit tuple conversions are standard conversions, // having implicit conversion in the other direction does not help here. impliedExplicitConversion = Conversion.NoConversion; break; case ConversionKind.ImplicitNullable: var strippedSource = source.StrippedType(); var strippedDestination = destination.StrippedType(); var underlyingConversion = DeriveStandardExplicitFromOppositeStandardImplicitConversion(strippedSource, strippedDestination, ref useSiteInfo); // the opposite underlying conversion may not exist // for example if underlying conversion is implicit tuple impliedExplicitConversion = underlyingConversion.Exists ? Conversion.MakeNullableConversion(ConversionKind.ExplicitNullable, underlyingConversion) : Conversion.NoConversion; break; default: throw ExceptionUtilities.UnexpectedValue(oppositeConversion.Kind); } return impliedExplicitConversion; } /// <summary> /// IsBaseInterface returns true if baseType is on the base interface list of derivedType or /// any base class of derivedType. It may be on the base interface list either directly or /// indirectly. /// * baseType must be an interface. /// * type parameters do not have base interfaces. (They have an "effective interface list".) /// * an interface is not a base of itself. /// * this does not check for variance conversions; if a type inherits from /// IEnumerable&lt;string> then IEnumerable&lt;object> is not a base interface. /// </summary> public bool IsBaseInterface(TypeSymbol baseType, TypeSymbol derivedType, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)baseType != null); Debug.Assert((object)derivedType != null); if (!baseType.IsInterfaceType()) { return false; } var d = derivedType as NamedTypeSymbol; if ((object)d == null) { return false; } foreach (var iface in d.AllInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteInfo)) { if (HasIdentityConversionInternal(iface, baseType)) { return true; } } return false; } // IsBaseClass returns true if and only if baseType is a base class of derivedType, period. // // * interfaces do not have base classes. (Structs, enums and classes other than object do.) // * a class is not a base class of itself // * type parameters do not have base classes. (They have "effective base classes".) // * all base classes must be classes // * dynamics are removed; if we have class D : B<dynamic> then B<object> is a // base class of D. However, dynamic is never a base class of anything. public bool IsBaseClass(TypeSymbol derivedType, TypeSymbol baseType, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)derivedType != null); Debug.Assert((object)baseType != null); // A base class has got to be a class. The derived type might be a struct, enum, or delegate. if (!baseType.IsClassType()) { return false; } for (TypeSymbol b = derivedType.BaseTypeWithDefinitionUseSiteDiagnostics(ref useSiteInfo); (object)b != null; b = b.BaseTypeWithDefinitionUseSiteDiagnostics(ref useSiteInfo)) { if (HasIdentityConversionInternal(b, baseType)) { return true; } } return false; } /// <summary> /// returns true when implicit conversion is not necessarily the same as explicit conversion /// </summary> private static bool ExplicitConversionMayDifferFromImplicit(Conversion implicitConversion) { switch (implicitConversion.Kind) { case ConversionKind.ImplicitUserDefined: case ConversionKind.ImplicitDynamic: case ConversionKind.ImplicitTuple: case ConversionKind.ImplicitTupleLiteral: case ConversionKind.ImplicitNullable: case ConversionKind.ConditionalExpression: return true; default: return false; } } private Conversion ClassifyImplicitBuiltInConversionFromExpression(BoundExpression sourceExpression, TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(sourceExpression != null || (object)source != null); Debug.Assert(sourceExpression == null || (object)sourceExpression.Type == (object)source); Debug.Assert((object)destination != null); if (HasImplicitDynamicConversionFromExpression(source, destination)) { return Conversion.ImplicitDynamic; } // The following conversions only exist for certain form of expressions, // if we have no expression none if them is applicable. if (sourceExpression == null) { return Conversion.NoConversion; } if (HasImplicitEnumerationConversion(sourceExpression, destination)) { return Conversion.ImplicitEnumeration; } var constantConversion = ClassifyImplicitConstantExpressionConversion(sourceExpression, destination); if (constantConversion.Exists) { return constantConversion; } switch (sourceExpression.Kind) { case BoundKind.Literal: var nullLiteralConversion = ClassifyNullLiteralConversion(sourceExpression, destination); if (nullLiteralConversion.Exists) { return nullLiteralConversion; } break; case BoundKind.DefaultLiteral: return Conversion.DefaultLiteral; case BoundKind.ExpressionWithNullability: { var innerExpression = ((BoundExpressionWithNullability)sourceExpression).Expression; var innerConversion = ClassifyImplicitBuiltInConversionFromExpression(innerExpression, innerExpression.Type, destination, ref useSiteInfo); if (innerConversion.Exists) { return innerConversion; } break; } case BoundKind.TupleLiteral: var tupleConversion = ClassifyImplicitTupleLiteralConversion((BoundTupleLiteral)sourceExpression, destination, ref useSiteInfo); if (tupleConversion.Exists) { return tupleConversion; } break; case BoundKind.UnboundLambda: if (HasAnonymousFunctionConversion(sourceExpression, destination)) { return Conversion.AnonymousFunction; } break; case BoundKind.MethodGroup: Conversion methodGroupConversion = GetMethodGroupDelegateConversion((BoundMethodGroup)sourceExpression, destination, ref useSiteInfo); if (methodGroupConversion.Exists) { return methodGroupConversion; } break; case BoundKind.UnconvertedInterpolatedString: Conversion interpolatedStringConversion = GetInterpolatedStringConversion((BoundUnconvertedInterpolatedString)sourceExpression, destination, ref useSiteInfo); if (interpolatedStringConversion.Exists) { return interpolatedStringConversion; } break; case BoundKind.StackAllocArrayCreation: var stackAllocConversion = GetStackAllocConversion((BoundStackAllocArrayCreation)sourceExpression, destination, ref useSiteInfo); if (stackAllocConversion.Exists) { return stackAllocConversion; } break; case BoundKind.UnconvertedAddressOfOperator when destination is FunctionPointerTypeSymbol funcPtrType: var addressOfConversion = GetMethodGroupFunctionPointerConversion(((BoundUnconvertedAddressOfOperator)sourceExpression).Operand, funcPtrType, ref useSiteInfo); if (addressOfConversion.Exists) { return addressOfConversion; } break; case BoundKind.ThrowExpression: return Conversion.ImplicitThrow; case BoundKind.UnconvertedObjectCreationExpression: return Conversion.ObjectCreation; } return Conversion.NoConversion; } private Conversion GetSwitchExpressionConversion(BoundExpression source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { switch (source) { case BoundConvertedSwitchExpression _: // It has already been subjected to a switch expression conversion. return Conversion.NoConversion; case BoundUnconvertedSwitchExpression switchExpression: var innerConversions = ArrayBuilder<Conversion>.GetInstance(switchExpression.SwitchArms.Length); foreach (var arm in switchExpression.SwitchArms) { var nestedConversion = this.ClassifyImplicitConversionFromExpression(arm.Value, destination, ref useSiteInfo); if (!nestedConversion.Exists) { innerConversions.Free(); return Conversion.NoConversion; } innerConversions.Add(nestedConversion); } return Conversion.MakeSwitchExpression(innerConversions.ToImmutableAndFree()); default: return Conversion.NoConversion; } } private Conversion GetConditionalExpressionConversion(BoundExpression source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { if (!(source is BoundUnconvertedConditionalOperator conditionalOperator)) return Conversion.NoConversion; var trueConversion = this.ClassifyImplicitConversionFromExpression(conditionalOperator.Consequence, destination, ref useSiteInfo); if (!trueConversion.Exists) return Conversion.NoConversion; var falseConversion = this.ClassifyImplicitConversionFromExpression(conditionalOperator.Alternative, destination, ref useSiteInfo); if (!falseConversion.Exists) return Conversion.NoConversion; return Conversion.MakeConditionalExpression(ImmutableArray.Create(trueConversion, falseConversion)); } private static Conversion ClassifyNullLiteralConversion(BoundExpression source, TypeSymbol destination) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); if (!source.IsLiteralNull()) { return Conversion.NoConversion; } // SPEC: An implicit conversion exists from the null literal to any nullable type. if (destination.IsNullableType()) { // The spec defines a "null literal conversion" specifically as a conversion from // null to nullable type. return Conversion.NullLiteral; } // SPEC: An implicit conversion exists from the null literal to any reference type. // SPEC: An implicit conversion exists from the null literal to type parameter T, // SPEC: provided T is known to be a reference type. [...] The conversion [is] classified // SPEC: as implicit reference conversion. if (destination.IsReferenceType) { return Conversion.ImplicitReference; } // SPEC: The set of implicit conversions is extended to include... // SPEC: ... from the null literal to any pointer type. if (destination.IsPointerOrFunctionPointer()) { return Conversion.NullToPointer; } return Conversion.NoConversion; } private static Conversion ClassifyImplicitConstantExpressionConversion(BoundExpression source, TypeSymbol destination) { if (HasImplicitConstantExpressionConversion(source, destination)) { return Conversion.ImplicitConstant; } // strip nullable from the destination // // the following should work and it is an ImplicitNullable conversion // int? x = 1; if (destination.Kind == SymbolKind.NamedType) { var nt = (NamedTypeSymbol)destination; if (nt.OriginalDefinition.GetSpecialTypeSafe() == SpecialType.System_Nullable_T && HasImplicitConstantExpressionConversion(source, nt.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics[0].Type)) { return new Conversion(ConversionKind.ImplicitNullable, Conversion.ImplicitConstantUnderlying); } } return Conversion.NoConversion; } private Conversion ClassifyImplicitTupleLiteralConversion(BoundTupleLiteral source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { var tupleConversion = GetImplicitTupleLiteralConversion(source, destination, ref useSiteInfo); if (tupleConversion.Exists) { return tupleConversion; } // strip nullable from the destination // // the following should work and it is an ImplicitNullable conversion // (int, double)? x = (1,2); if (destination.Kind == SymbolKind.NamedType) { var nt = (NamedTypeSymbol)destination; if (nt.OriginalDefinition.GetSpecialTypeSafe() == SpecialType.System_Nullable_T) { var underlyingTupleConversion = GetImplicitTupleLiteralConversion(source, nt.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics[0].Type, ref useSiteInfo); if (underlyingTupleConversion.Exists) { return new Conversion(ConversionKind.ImplicitNullable, ImmutableArray.Create(underlyingTupleConversion)); } } } return Conversion.NoConversion; } private Conversion ClassifyExplicitTupleLiteralConversion(BoundTupleLiteral source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, bool forCast) { var tupleConversion = GetExplicitTupleLiteralConversion(source, destination, ref useSiteInfo, forCast); if (tupleConversion.Exists) { return tupleConversion; } // strip nullable from the destination // // the following should work and it is an ExplicitNullable conversion // var x = ((byte, string)?)(1,null); if (destination.Kind == SymbolKind.NamedType) { var nt = (NamedTypeSymbol)destination; if (nt.OriginalDefinition.GetSpecialTypeSafe() == SpecialType.System_Nullable_T) { var underlyingTupleConversion = GetExplicitTupleLiteralConversion(source, nt.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics[0].Type, ref useSiteInfo, forCast); if (underlyingTupleConversion.Exists) { return new Conversion(ConversionKind.ExplicitNullable, ImmutableArray.Create(underlyingTupleConversion)); } } } return Conversion.NoConversion; } internal static bool HasImplicitConstantExpressionConversion(BoundExpression source, TypeSymbol destination) { var constantValue = source.ConstantValue; if (constantValue == null || (object)source.Type == null) { return false; } // An implicit constant expression conversion permits the following conversions: // A constant-expression of type int can be converted to type sbyte, byte, short, // ushort, uint, or ulong, provided the value of the constant-expression is within the // range of the destination type. var specialSource = source.Type.GetSpecialTypeSafe(); if (specialSource == SpecialType.System_Int32) { //if the constant value could not be computed, be generous and assume the conversion will work int value = constantValue.IsBad ? 0 : constantValue.Int32Value; switch (destination.GetSpecialTypeSafe()) { case SpecialType.System_Byte: return byte.MinValue <= value && value <= byte.MaxValue; case SpecialType.System_SByte: return sbyte.MinValue <= value && value <= sbyte.MaxValue; case SpecialType.System_Int16: return short.MinValue <= value && value <= short.MaxValue; case SpecialType.System_IntPtr when destination.IsNativeIntegerType: return true; case SpecialType.System_UInt32: case SpecialType.System_UIntPtr when destination.IsNativeIntegerType: return uint.MinValue <= value; case SpecialType.System_UInt64: return (int)ulong.MinValue <= value; case SpecialType.System_UInt16: return ushort.MinValue <= value && value <= ushort.MaxValue; default: return false; } } else if (specialSource == SpecialType.System_Int64 && destination.GetSpecialTypeSafe() == SpecialType.System_UInt64 && (constantValue.IsBad || 0 <= constantValue.Int64Value)) { // A constant-expression of type long can be converted to type ulong, provided the // value of the constant-expression is not negative. return true; } return false; } private Conversion ClassifyExplicitOnlyConversionFromExpression(BoundExpression sourceExpression, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, bool forCast) { Debug.Assert(sourceExpression != null); Debug.Assert((object)destination != null); var sourceType = sourceExpression.Type; // NB: need to check for explicit tuple literal conversion before checking for explicit conversion from type // The same literal may have both explicit tuple conversion and explicit tuple literal conversion to the target type. // They are, however, observably different conversions via the order of argument evaluations and element-wise conversions if (sourceExpression.Kind == BoundKind.TupleLiteral) { Conversion tupleConversion = ClassifyExplicitTupleLiteralConversion((BoundTupleLiteral)sourceExpression, destination, ref useSiteInfo, forCast); if (tupleConversion.Exists) { return tupleConversion; } } if ((object)sourceType != null) { // Try using the short-circuit "fast-conversion" path. Conversion fastConversion = FastClassifyConversion(sourceType, destination); if (fastConversion.Exists) { return fastConversion; } else { var conversion = ClassifyExplicitBuiltInOnlyConversion(sourceType, destination, ref useSiteInfo, forCast); if (conversion.Exists) { return conversion; } } } return GetExplicitUserDefinedConversion(sourceExpression, sourceType, destination, ref useSiteInfo); } #nullable enable private static bool HasImplicitEnumerationConversion(BoundExpression source, TypeSymbol destination) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); // SPEC: An implicit enumeration conversion permits the decimal-integer-literal 0 to be converted to any enum-type // SPEC: and to any nullable-type whose underlying type is an enum-type. // // For historical reasons we actually allow a conversion from any *numeric constant // zero* to be converted to any enum type, not just the literal integer zero. bool validType = destination.IsEnumType() || destination.IsNullableType() && destination.GetNullableUnderlyingType().IsEnumType(); if (!validType) { return false; } var sourceConstantValue = source.ConstantValue; return sourceConstantValue != null && source.Type is object && IsNumericType(source.Type) && IsConstantNumericZero(sourceConstantValue); } private static LambdaConversionResult IsAnonymousFunctionCompatibleWithDelegate(UnboundLambda anonymousFunction, TypeSymbol type, bool isTargetExpressionTree) { Debug.Assert((object)anonymousFunction != null); Debug.Assert((object)type != null); // SPEC: An anonymous-method-expression or lambda-expression is classified as an anonymous function. // SPEC: The expression does not have a type but can be implicitly converted to a compatible delegate // SPEC: type or expression tree type. Specifically, a delegate type D is compatible with an // SPEC: anonymous function F provided: var delegateType = (NamedTypeSymbol)type; var invokeMethod = delegateType.DelegateInvokeMethod; if ((object)invokeMethod == null || invokeMethod.HasUseSiteError) { return LambdaConversionResult.BadTargetType; } if (anonymousFunction.HasExplicitReturnType(out var refKind, out var returnType)) { if (invokeMethod.RefKind != refKind || !invokeMethod.ReturnType.Equals(returnType.Type, TypeCompareKind.AllIgnoreOptions)) { return LambdaConversionResult.MismatchedReturnType; } } var delegateParameters = invokeMethod.Parameters; // SPEC: If F contains an anonymous-function-signature, then D and F have the same number of parameters. // SPEC: If F does not contain an anonymous-function-signature, then D may have zero or more parameters // SPEC: of any type, as long as no parameter of D has the out parameter modifier. if (anonymousFunction.HasSignature) { if (anonymousFunction.ParameterCount != invokeMethod.ParameterCount) { return LambdaConversionResult.BadParameterCount; } // SPEC: If F has an explicitly typed parameter list, each parameter in D has the same type // SPEC: and modifiers as the corresponding parameter in F. // SPEC: If F has an implicitly typed parameter list, D has no ref or out parameters. if (anonymousFunction.HasExplicitlyTypedParameterList) { for (int p = 0; p < delegateParameters.Length; ++p) { if (delegateParameters[p].RefKind != anonymousFunction.RefKind(p) || !delegateParameters[p].Type.Equals(anonymousFunction.ParameterType(p), TypeCompareKind.AllIgnoreOptions)) { return LambdaConversionResult.MismatchedParameterType; } } } else { for (int p = 0; p < delegateParameters.Length; ++p) { if (delegateParameters[p].RefKind != RefKind.None) { return LambdaConversionResult.RefInImplicitlyTypedLambda; } } // In C# it is not possible to make a delegate type // such that one of its parameter types is a static type. But static types are // in metadata just sealed abstract types; there is nothing stopping someone in // another language from creating a delegate with a static type for a parameter, // though the only argument you could pass for that parameter is null. // // In the native compiler we forbid conversion of an anonymous function that has // an implicitly-typed parameter list to a delegate type that has a static type // for a formal parameter type. However, we do *not* forbid it for an explicitly- // typed lambda (because we already require that the explicitly typed parameter not // be static) and we do not forbid it for an anonymous method with the entire // parameter list missing (because the body cannot possibly have a parameter that // is of static type, even though this means that we will be generating a hidden // method with a parameter of static type.) // // We also allow more exotic situations to work in the native compiler. For example, // though it is not possible to convert x=>{} to Action<GC>, it is possible to convert // it to Action<List<GC>> should there be a language that allows you to construct // a variable of that type. // // We might consider beefing up this rule to disallow a conversion of *any* anonymous // function to *any* delegate that has a static type *anywhere* in the parameter list. for (int p = 0; p < delegateParameters.Length; ++p) { if (delegateParameters[p].TypeWithAnnotations.IsStatic) { return LambdaConversionResult.StaticTypeInImplicitlyTypedLambda; } } } } else { for (int p = 0; p < delegateParameters.Length; ++p) { if (delegateParameters[p].RefKind == RefKind.Out) { return LambdaConversionResult.MissingSignatureWithOutParameter; } } } // Ensure the body can be converted to that delegate type var bound = anonymousFunction.Bind(delegateType, isTargetExpressionTree); if (ErrorFacts.PreventsSuccessfulDelegateConversion(bound.Diagnostics.Diagnostics)) { return LambdaConversionResult.BindingFailed; } return LambdaConversionResult.Success; } private static LambdaConversionResult IsAnonymousFunctionCompatibleWithExpressionTree(UnboundLambda anonymousFunction, NamedTypeSymbol type) { Debug.Assert((object)anonymousFunction != null); Debug.Assert((object)type != null); Debug.Assert(type.IsGenericOrNonGenericExpressionType(out _)); // SPEC OMISSION: // // The C# 3 spec said that anonymous methods and statement lambdas are *convertible* to expression tree // types if the anonymous method/statement lambda is convertible to its delegate type; however, actually // *using* such a conversion is an error. However, that is not what we implemented. In C# 3 we implemented // that an anonymous method is *not convertible* to an expression tree type, period. (Statement lambdas // used the rule described in the spec.) // // This appears to be a spec omission; the intention is to make old-style anonymous methods not // convertible to expression trees. var delegateType = type.Arity == 0 ? null : type.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics[0].Type; if (delegateType is { } && !delegateType.IsDelegateType()) { return LambdaConversionResult.ExpressionTreeMustHaveDelegateTypeArgument; } if (anonymousFunction.Syntax.Kind() == SyntaxKind.AnonymousMethodExpression) { return LambdaConversionResult.ExpressionTreeFromAnonymousMethod; } if (delegateType is null) { return LambdaConversionResult.Success; } return IsAnonymousFunctionCompatibleWithDelegate(anonymousFunction, delegateType, isTargetExpressionTree: true); } public static LambdaConversionResult IsAnonymousFunctionCompatibleWithType(UnboundLambda anonymousFunction, TypeSymbol type) { Debug.Assert((object)anonymousFunction != null); Debug.Assert((object)type != null); if (type.SpecialType == SpecialType.System_Delegate) { if (IsFeatureInferredDelegateTypeEnabled(anonymousFunction)) { return LambdaConversionResult.Success; } } else if (type.IsDelegateType()) { return IsAnonymousFunctionCompatibleWithDelegate(anonymousFunction, type, isTargetExpressionTree: false); } else if (type.IsGenericOrNonGenericExpressionType(out bool isGenericType)) { if (isGenericType || IsFeatureInferredDelegateTypeEnabled(anonymousFunction)) { return IsAnonymousFunctionCompatibleWithExpressionTree(anonymousFunction, (NamedTypeSymbol)type); } } return LambdaConversionResult.BadTargetType; } internal static bool IsFeatureInferredDelegateTypeEnabled(BoundExpression expr) { return expr.Syntax.IsFeatureEnabled(MessageID.IDS_FeatureInferredDelegateType); } private static bool HasAnonymousFunctionConversion(BoundExpression source, TypeSymbol destination) { Debug.Assert(source != null); Debug.Assert((object)destination != null); if (source.Kind != BoundKind.UnboundLambda) { return false; } return IsAnonymousFunctionCompatibleWithType((UnboundLambda)source, destination) == LambdaConversionResult.Success; } #nullable disable internal Conversion ClassifyImplicitUserDefinedConversionForV6SwitchGoverningType(TypeSymbol sourceType, out TypeSymbol switchGoverningType, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { // SPEC: The governing type of a switch statement is established by the switch expression. // SPEC: 1) If the type of the switch expression is sbyte, byte, short, ushort, int, uint, // SPEC: long, ulong, bool, char, string, or an enum-type, or if it is the nullable type // SPEC: corresponding to one of these types, then that is the governing type of the switch statement. // SPEC: 2) Otherwise, exactly one user-defined implicit conversion (§6.4) must exist from the // SPEC: type of the switch expression to one of the following possible governing types: // SPEC: sbyte, byte, short, ushort, int, uint, long, ulong, char, string, or, a nullable type // SPEC: corresponding to one of those types // NOTE: We should be called only if (1) is false for source type. Debug.Assert((object)sourceType != null); Debug.Assert(!sourceType.IsValidV6SwitchGoverningType()); UserDefinedConversionResult result = AnalyzeImplicitUserDefinedConversionForV6SwitchGoverningType(sourceType, ref useSiteInfo); if (result.Kind == UserDefinedConversionResultKind.Valid) { UserDefinedConversionAnalysis analysis = result.Results[result.Best]; switchGoverningType = analysis.ToType; Debug.Assert(switchGoverningType.IsValidV6SwitchGoverningType(isTargetTypeOfUserDefinedOp: true)); } else { switchGoverningType = null; } return new Conversion(result, isImplicit: true); } internal Conversion GetCallerLineNumberConversion(TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { var greenNode = new Syntax.InternalSyntax.LiteralExpressionSyntax(SyntaxKind.NumericLiteralExpression, new Syntax.InternalSyntax.SyntaxToken(SyntaxKind.NumericLiteralToken)); var syntaxNode = new LiteralExpressionSyntax(greenNode, null, 0); TypeSymbol expectedAttributeType = corLibrary.GetSpecialType(SpecialType.System_Int32); BoundLiteral intMaxValueLiteral = new BoundLiteral(syntaxNode, ConstantValue.Create(int.MaxValue), expectedAttributeType); return ClassifyStandardImplicitConversion(intMaxValueLiteral, expectedAttributeType, destination, ref useSiteInfo); } internal bool HasCallerLineNumberConversion(TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { return GetCallerLineNumberConversion(destination, ref useSiteInfo).Exists; } internal bool HasCallerInfoStringConversion(TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { TypeSymbol expectedAttributeType = corLibrary.GetSpecialType(SpecialType.System_String); Conversion conversion = ClassifyStandardImplicitConversion(expectedAttributeType, destination, ref useSiteInfo); return conversion.Exists; } public static bool HasIdentityConversion(TypeSymbol type1, TypeSymbol type2) { return HasIdentityConversionInternal(type1, type2, includeNullability: false); } private static bool HasIdentityConversionInternal(TypeSymbol type1, TypeSymbol type2, bool includeNullability) { // Spec (6.1.1): // An identity conversion converts from any type to the same type. This conversion exists // such that an entity that already has a required type can be said to be convertible to // that type. // // Because object and dynamic are considered equivalent there is an identity conversion // between object and dynamic, and between constructed types that are the same when replacing // all occurrences of dynamic with object. Debug.Assert((object)type1 != null); Debug.Assert((object)type2 != null); // Note, when we are paying attention to nullability, we ignore oblivious mismatch. // See TypeCompareKind.ObliviousNullableModifierMatchesAny var compareKind = includeNullability ? TypeCompareKind.AllIgnoreOptions & ~TypeCompareKind.IgnoreNullableModifiersForReferenceTypes : TypeCompareKind.AllIgnoreOptions; return type1.Equals(type2, compareKind); } private bool HasIdentityConversionInternal(TypeSymbol type1, TypeSymbol type2) { return HasIdentityConversionInternal(type1, type2, IncludeNullability); } /// <summary> /// Returns true if: /// - Either type has no nullability information (oblivious). /// - Both types cannot have different nullability at the same time, /// including the case of type parameters that by themselves can represent nullable and not nullable reference types. /// </summary> internal bool HasTopLevelNullabilityIdentityConversion(TypeWithAnnotations source, TypeWithAnnotations destination) { if (!IncludeNullability) { return true; } if (source.NullableAnnotation.IsOblivious() || destination.NullableAnnotation.IsOblivious()) { return true; } var sourceIsPossiblyNullableTypeParameter = IsPossiblyNullableTypeTypeParameter(source); var destinationIsPossiblyNullableTypeParameter = IsPossiblyNullableTypeTypeParameter(destination); if (sourceIsPossiblyNullableTypeParameter && !destinationIsPossiblyNullableTypeParameter) { return destination.NullableAnnotation.IsAnnotated(); } if (destinationIsPossiblyNullableTypeParameter && !sourceIsPossiblyNullableTypeParameter) { return source.NullableAnnotation.IsAnnotated(); } return source.NullableAnnotation.IsAnnotated() == destination.NullableAnnotation.IsAnnotated(); } /// <summary> /// Returns false if source type can be nullable at the same time when destination type can be not nullable, /// including the case of type parameters that by themselves can represent nullable and not nullable reference types. /// When either type has no nullability information (oblivious), this method returns true. /// </summary> internal bool HasTopLevelNullabilityImplicitConversion(TypeWithAnnotations source, TypeWithAnnotations destination) { if (!IncludeNullability) { return true; } if (source.NullableAnnotation.IsOblivious() || destination.NullableAnnotation.IsOblivious() || destination.NullableAnnotation.IsAnnotated()) { return true; } if (IsPossiblyNullableTypeTypeParameter(source) && !IsPossiblyNullableTypeTypeParameter(destination)) { return false; } return !source.NullableAnnotation.IsAnnotated(); } private static bool IsPossiblyNullableTypeTypeParameter(in TypeWithAnnotations typeWithAnnotations) { var type = typeWithAnnotations.Type; return type is object && (type.IsPossiblyNullableReferenceTypeTypeParameter() || type.IsNullableTypeOrTypeParameter()); } /// <summary> /// Returns false if the source does not have an implicit conversion to the destination /// because of either incompatible top level or nested nullability. /// </summary> public bool HasAnyNullabilityImplicitConversion(TypeWithAnnotations source, TypeWithAnnotations destination) { Debug.Assert(IncludeNullability); var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; return HasTopLevelNullabilityImplicitConversion(source, destination) && ClassifyImplicitConversionFromType(source.Type, destination.Type, ref discardedUseSiteInfo).Kind != ConversionKind.NoConversion; } public static bool HasIdentityConversionToAny<T>(T type, ArrayBuilder<T> targetTypes) where T : TypeSymbol { foreach (var targetType in targetTypes) { if (HasIdentityConversionInternal(type, targetType, includeNullability: false)) { return true; } } return false; } public Conversion ConvertExtensionMethodThisArg(TypeSymbol parameterType, TypeSymbol thisType, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)thisType != null); var conversion = this.ClassifyImplicitExtensionMethodThisArgConversion(null, thisType, parameterType, ref useSiteInfo); return IsValidExtensionMethodThisArgConversion(conversion) ? conversion : Conversion.NoConversion; } // Spec 7.6.5.2: "An extension method ... is eligible if ... [an] implicit identity, reference, // or boxing conversion exists from expr to the type of the first parameter" public Conversion ClassifyImplicitExtensionMethodThisArgConversion(BoundExpression sourceExpressionOpt, TypeSymbol sourceType, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(sourceExpressionOpt == null || (object)sourceExpressionOpt.Type == sourceType); Debug.Assert((object)destination != null); if ((object)sourceType != null) { if (HasIdentityConversionInternal(sourceType, destination)) { return Conversion.Identity; } if (HasBoxingConversion(sourceType, destination, ref useSiteInfo)) { return Conversion.Boxing; } if (HasImplicitReferenceConversion(sourceType, destination, ref useSiteInfo)) { return Conversion.ImplicitReference; } } if (sourceExpressionOpt?.Kind == BoundKind.TupleLiteral) { // GetTupleLiteralConversion is not used with IncludeNullability currently. // If that changes, the delegate below will need to consider top-level nullability. Debug.Assert(!IncludeNullability); var tupleConversion = GetTupleLiteralConversion( (BoundTupleLiteral)sourceExpressionOpt, destination, ref useSiteInfo, ConversionKind.ImplicitTupleLiteral, (ConversionsBase conversions, BoundExpression s, TypeWithAnnotations d, ref CompoundUseSiteInfo<AssemblySymbol> u, bool a) => conversions.ClassifyImplicitExtensionMethodThisArgConversion(s, s.Type, d.Type, ref u), arg: false); if (tupleConversion.Exists) { return tupleConversion; } } if ((object)sourceType != null) { var tupleConversion = ClassifyTupleConversion( sourceType, destination, ref useSiteInfo, ConversionKind.ImplicitTuple, (ConversionsBase conversions, TypeWithAnnotations s, TypeWithAnnotations d, ref CompoundUseSiteInfo<AssemblySymbol> u, bool a) => { if (!conversions.HasTopLevelNullabilityImplicitConversion(s, d)) { return Conversion.NoConversion; } return conversions.ClassifyImplicitExtensionMethodThisArgConversion(null, s.Type, d.Type, ref u); }, arg: false); if (tupleConversion.Exists) { return tupleConversion; } } return Conversion.NoConversion; } // It should be possible to remove IsValidExtensionMethodThisArgConversion // since ClassifyImplicitExtensionMethodThisArgConversion should only // return valid conversions. https://github.com/dotnet/roslyn/issues/19622 // Spec 7.6.5.2: "An extension method ... is eligible if ... [an] implicit identity, reference, // or boxing conversion exists from expr to the type of the first parameter" public static bool IsValidExtensionMethodThisArgConversion(Conversion conversion) { switch (conversion.Kind) { case ConversionKind.Identity: case ConversionKind.Boxing: case ConversionKind.ImplicitReference: return true; case ConversionKind.ImplicitTuple: case ConversionKind.ImplicitTupleLiteral: // check if all element conversions satisfy the requirement foreach (var elementConversion in conversion.UnderlyingConversions) { if (!IsValidExtensionMethodThisArgConversion(elementConversion)) { return false; } } return true; default: // Caller should have not have calculated another conversion. Debug.Assert(conversion.Kind == ConversionKind.NoConversion); return false; } } private const bool F = false; private const bool T = true; // Notice that there is no implicit numeric conversion from a type to itself. That's an // identity conversion. private static readonly bool[,] s_implicitNumericConversions = { // to sb b s us i ui l ul c f d m // from /* sb */ { F, F, T, F, T, F, T, F, F, T, T, T }, /* b */ { F, F, T, T, T, T, T, T, F, T, T, T }, /* s */ { F, F, F, F, T, F, T, F, F, T, T, T }, /* us */ { F, F, F, F, T, T, T, T, F, T, T, T }, /* i */ { F, F, F, F, F, F, T, F, F, T, T, T }, /* ui */ { F, F, F, F, F, F, T, T, F, T, T, T }, /* l */ { F, F, F, F, F, F, F, F, F, T, T, T }, /* ul */ { F, F, F, F, F, F, F, F, F, T, T, T }, /* c */ { F, F, F, T, T, T, T, T, F, T, T, T }, /* f */ { F, F, F, F, F, F, F, F, F, F, T, F }, /* d */ { F, F, F, F, F, F, F, F, F, F, F, F }, /* m */ { F, F, F, F, F, F, F, F, F, F, F, F } }; private static readonly bool[,] s_explicitNumericConversions = { // to sb b s us i ui l ul c f d m // from /* sb */ { F, T, F, T, F, T, F, T, T, F, F, F }, /* b */ { T, F, F, F, F, F, F, F, T, F, F, F }, /* s */ { T, T, F, T, F, T, F, T, T, F, F, F }, /* us */ { T, T, T, F, F, F, F, F, T, F, F, F }, /* i */ { T, T, T, T, F, T, F, T, T, F, F, F }, /* ui */ { T, T, T, T, T, F, F, F, T, F, F, F }, /* l */ { T, T, T, T, T, T, F, T, T, F, F, F }, /* ul */ { T, T, T, T, T, T, T, F, T, F, F, F }, /* c */ { T, T, T, F, F, F, F, F, F, F, F, F }, /* f */ { T, T, T, T, T, T, T, T, T, F, F, T }, /* d */ { T, T, T, T, T, T, T, T, T, T, F, T }, /* m */ { T, T, T, T, T, T, T, T, T, T, T, F } }; private static int GetNumericTypeIndex(SpecialType specialType) { switch (specialType) { case SpecialType.System_SByte: return 0; case SpecialType.System_Byte: return 1; case SpecialType.System_Int16: return 2; case SpecialType.System_UInt16: return 3; case SpecialType.System_Int32: return 4; case SpecialType.System_UInt32: return 5; case SpecialType.System_Int64: return 6; case SpecialType.System_UInt64: return 7; case SpecialType.System_Char: return 8; case SpecialType.System_Single: return 9; case SpecialType.System_Double: return 10; case SpecialType.System_Decimal: return 11; default: return -1; } } #nullable enable private static bool HasImplicitNumericConversion(TypeSymbol source, TypeSymbol destination) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); int sourceIndex = GetNumericTypeIndex(source.SpecialType); if (sourceIndex < 0) { return false; } int destinationIndex = GetNumericTypeIndex(destination.SpecialType); if (destinationIndex < 0) { return false; } return s_implicitNumericConversions[sourceIndex, destinationIndex]; } private static bool HasExplicitNumericConversion(TypeSymbol source, TypeSymbol destination) { // SPEC: The explicit numeric conversions are the conversions from a numeric-type to another // SPEC: numeric-type for which an implicit numeric conversion does not already exist. Debug.Assert((object)source != null); Debug.Assert((object)destination != null); int sourceIndex = GetNumericTypeIndex(source.SpecialType); if (sourceIndex < 0) { return false; } int destinationIndex = GetNumericTypeIndex(destination.SpecialType); if (destinationIndex < 0) { return false; } return s_explicitNumericConversions[sourceIndex, destinationIndex]; } private static bool IsConstantNumericZero(ConstantValue value) { switch (value.Discriminator) { case ConstantValueTypeDiscriminator.SByte: return value.SByteValue == 0; case ConstantValueTypeDiscriminator.Byte: return value.ByteValue == 0; case ConstantValueTypeDiscriminator.Int16: return value.Int16Value == 0; case ConstantValueTypeDiscriminator.Int32: case ConstantValueTypeDiscriminator.NInt: return value.Int32Value == 0; case ConstantValueTypeDiscriminator.Int64: return value.Int64Value == 0; case ConstantValueTypeDiscriminator.UInt16: return value.UInt16Value == 0; case ConstantValueTypeDiscriminator.UInt32: case ConstantValueTypeDiscriminator.NUInt: return value.UInt32Value == 0; case ConstantValueTypeDiscriminator.UInt64: return value.UInt64Value == 0; case ConstantValueTypeDiscriminator.Single: case ConstantValueTypeDiscriminator.Double: return value.DoubleValue == 0; case ConstantValueTypeDiscriminator.Decimal: return value.DecimalValue == 0; } return false; } private static bool IsNumericType(TypeSymbol type) { switch (type.SpecialType) { case SpecialType.System_Char: case SpecialType.System_SByte: case SpecialType.System_Byte: case SpecialType.System_Int16: case SpecialType.System_UInt16: case SpecialType.System_Int32: case SpecialType.System_UInt32: case SpecialType.System_Int64: case SpecialType.System_UInt64: case SpecialType.System_Single: case SpecialType.System_Double: case SpecialType.System_Decimal: case SpecialType.System_IntPtr when type.IsNativeIntegerType: case SpecialType.System_UIntPtr when type.IsNativeIntegerType: return true; default: return false; } } private static bool HasSpecialIntPtrConversion(TypeSymbol source, TypeSymbol target) { Debug.Assert((object)source != null); Debug.Assert((object)target != null); // There are only a total of twelve user-defined explicit conversions on IntPtr and UIntPtr: // // IntPtr <---> int // IntPtr <---> long // IntPtr <---> void* // UIntPtr <---> uint // UIntPtr <---> ulong // UIntPtr <---> void* // // The specification says that you can put any *standard* implicit or explicit conversion // on "either side" of a user-defined explicit conversion, so the specification allows, say, // UIntPtr --> byte because the conversion UIntPtr --> uint is user-defined and the // conversion uint --> byte is "standard". It is "standard" because the conversion // byte --> uint is an implicit numeric conversion. // This means that certain conversions should be illegal. For example, IntPtr --> ulong // should be illegal because none of int --> ulong, long --> ulong and void* --> ulong // are "standard" conversions. // Similarly, some conversions involving IntPtr should be illegal because they are // ambiguous. byte --> IntPtr?, for example, is ambiguous. (There are four possible // UD operators: int --> IntPtr and long --> IntPtr, and their lifted versions. The // best possible source type is int, the best possible target type is IntPtr?, and // there is an ambiguity between the unlifted int --> IntPtr, and the lifted // int? --> IntPtr? conversions.) // In practice, the native compiler, and hence, the Roslyn compiler, allows all // these conversions. Any conversion from a numeric type to IntPtr, or from an IntPtr // to a numeric type, is allowed. Also, any conversion from a pointer type to IntPtr // or vice versa is allowed. var s0 = source.StrippedType(); var t0 = target.StrippedType(); TypeSymbol otherType; if (isIntPtrOrUIntPtr(s0)) { otherType = t0; } else if (isIntPtrOrUIntPtr(t0)) { otherType = s0; } else { return false; } if (otherType.IsPointerOrFunctionPointer()) { return true; } if (otherType.TypeKind == TypeKind.Enum) { return true; } switch (otherType.SpecialType) { case SpecialType.System_SByte: case SpecialType.System_Byte: case SpecialType.System_Int16: case SpecialType.System_UInt16: case SpecialType.System_Char: case SpecialType.System_Int32: case SpecialType.System_UInt32: case SpecialType.System_Int64: case SpecialType.System_UInt64: case SpecialType.System_Double: case SpecialType.System_Single: case SpecialType.System_Decimal: return true; } return false; static bool isIntPtrOrUIntPtr(TypeSymbol type) => (type.SpecialType == SpecialType.System_IntPtr || type.SpecialType == SpecialType.System_UIntPtr) && !type.IsNativeIntegerType; } private static bool HasExplicitEnumerationConversion(TypeSymbol source, TypeSymbol destination) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); // SPEC: The explicit enumeration conversions are: // SPEC: From sbyte, byte, short, ushort, int, uint, long, ulong, nint, nuint, char, float, double, or decimal to any enum-type. // SPEC: From any enum-type to sbyte, byte, short, ushort, int, uint, long, ulong, nint, nuint, char, float, double, or decimal. // SPEC: From any enum-type to any other enum-type. if (IsNumericType(source) && destination.IsEnumType()) { return true; } if (IsNumericType(destination) && source.IsEnumType()) { return true; } if (source.IsEnumType() && destination.IsEnumType()) { return true; } return false; } #nullable disable private Conversion ClassifyImplicitNullableConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); // SPEC: Predefined implicit conversions that operate on non-nullable value types can also be used with // SPEC: nullable forms of those types. For each of the predefined implicit identity, numeric and tuple conversions // SPEC: that convert from a non-nullable value type S to a non-nullable value type T, the following implicit // SPEC: nullable conversions exist: // SPEC: * An implicit conversion from S? to T?. // SPEC: * An implicit conversion from S to T?. if (!destination.IsNullableType()) { return Conversion.NoConversion; } TypeSymbol unwrappedDestination = destination.GetNullableUnderlyingType(); TypeSymbol unwrappedSource = source.StrippedType(); if (!unwrappedSource.IsValueType) { return Conversion.NoConversion; } if (HasIdentityConversionInternal(unwrappedSource, unwrappedDestination)) { return new Conversion(ConversionKind.ImplicitNullable, Conversion.IdentityUnderlying); } if (HasImplicitNumericConversion(unwrappedSource, unwrappedDestination)) { return new Conversion(ConversionKind.ImplicitNullable, Conversion.ImplicitNumericUnderlying); } var tupleConversion = ClassifyImplicitTupleConversion(unwrappedSource, unwrappedDestination, ref useSiteInfo); if (tupleConversion.Exists) { return new Conversion(ConversionKind.ImplicitNullable, ImmutableArray.Create(tupleConversion)); } return Conversion.NoConversion; } private delegate Conversion ClassifyConversionFromExpressionDelegate(ConversionsBase conversions, BoundExpression sourceExpression, TypeWithAnnotations destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, bool arg); private delegate Conversion ClassifyConversionFromTypeDelegate(ConversionsBase conversions, TypeWithAnnotations source, TypeWithAnnotations destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, bool arg); private Conversion GetImplicitTupleLiteralConversion(BoundTupleLiteral source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { // GetTupleLiteralConversion is not used with IncludeNullability currently. // If that changes, the delegate below will need to consider top-level nullability. Debug.Assert(!IncludeNullability); return GetTupleLiteralConversion( source, destination, ref useSiteInfo, ConversionKind.ImplicitTupleLiteral, (ConversionsBase conversions, BoundExpression s, TypeWithAnnotations d, ref CompoundUseSiteInfo<AssemblySymbol> u, bool a) => conversions.ClassifyImplicitConversionFromExpression(s, d.Type, ref u), arg: false); } private Conversion GetExplicitTupleLiteralConversion(BoundTupleLiteral source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, bool forCast) { // GetTupleLiteralConversion is not used with IncludeNullability currently. // If that changes, the delegate below will need to consider top-level nullability. Debug.Assert(!IncludeNullability); return GetTupleLiteralConversion( source, destination, ref useSiteInfo, ConversionKind.ExplicitTupleLiteral, (ConversionsBase conversions, BoundExpression s, TypeWithAnnotations d, ref CompoundUseSiteInfo<AssemblySymbol> u, bool a) => conversions.ClassifyConversionFromExpression(s, d.Type, ref u, a), forCast); } private Conversion GetTupleLiteralConversion( BoundTupleLiteral source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, ConversionKind kind, ClassifyConversionFromExpressionDelegate classifyConversion, bool arg) { var arguments = source.Arguments; // check if the type is actually compatible type for a tuple of given cardinality if (!destination.IsTupleTypeOfCardinality(arguments.Length)) { return Conversion.NoConversion; } var targetElementTypes = destination.TupleElementTypesWithAnnotations; Debug.Assert(arguments.Length == targetElementTypes.Length); // check arguments against flattened list of target element types var argumentConversions = ArrayBuilder<Conversion>.GetInstance(arguments.Length); for (int i = 0; i < arguments.Length; i++) { var argument = arguments[i]; var result = classifyConversion(this, argument, targetElementTypes[i], ref useSiteInfo, arg); if (!result.Exists) { argumentConversions.Free(); return Conversion.NoConversion; } argumentConversions.Add(result); } return new Conversion(kind, argumentConversions.ToImmutableAndFree()); } private Conversion ClassifyImplicitTupleConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { return ClassifyTupleConversion( source, destination, ref useSiteInfo, ConversionKind.ImplicitTuple, (ConversionsBase conversions, TypeWithAnnotations s, TypeWithAnnotations d, ref CompoundUseSiteInfo<AssemblySymbol> u, bool a) => { if (!conversions.HasTopLevelNullabilityImplicitConversion(s, d)) { return Conversion.NoConversion; } return conversions.ClassifyImplicitConversionFromType(s.Type, d.Type, ref u); }, arg: false); } private Conversion ClassifyExplicitTupleConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, bool forCast) { return ClassifyTupleConversion( source, destination, ref useSiteInfo, ConversionKind.ExplicitTuple, (ConversionsBase conversions, TypeWithAnnotations s, TypeWithAnnotations d, ref CompoundUseSiteInfo<AssemblySymbol> u, bool a) => { if (!conversions.HasTopLevelNullabilityImplicitConversion(s, d)) { return Conversion.NoConversion; } return conversions.ClassifyConversionFromType(s.Type, d.Type, ref u, a); }, forCast); } private Conversion ClassifyTupleConversion( TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, ConversionKind kind, ClassifyConversionFromTypeDelegate classifyConversion, bool arg) { ImmutableArray<TypeWithAnnotations> sourceTypes; ImmutableArray<TypeWithAnnotations> destTypes; if (!source.TryGetElementTypesWithAnnotationsIfTupleType(out sourceTypes) || !destination.TryGetElementTypesWithAnnotationsIfTupleType(out destTypes) || sourceTypes.Length != destTypes.Length) { return Conversion.NoConversion; } var nestedConversions = ArrayBuilder<Conversion>.GetInstance(sourceTypes.Length); for (int i = 0; i < sourceTypes.Length; i++) { var conversion = classifyConversion(this, sourceTypes[i], destTypes[i], ref useSiteInfo, arg); if (!conversion.Exists) { nestedConversions.Free(); return Conversion.NoConversion; } nestedConversions.Add(conversion); } return new Conversion(kind, nestedConversions.ToImmutableAndFree()); } private Conversion ClassifyExplicitNullableConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, bool forCast) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); // SPEC: Explicit nullable conversions permit predefined explicit conversions that operate on // SPEC: non-nullable value types to also be used with nullable forms of those types. For // SPEC: each of the predefined explicit conversions that convert from a non-nullable value type // SPEC: S to a non-nullable value type T, the following nullable conversions exist: // SPEC: An explicit conversion from S? to T?. // SPEC: An explicit conversion from S to T?. // SPEC: An explicit conversion from S? to T. if (!source.IsNullableType() && !destination.IsNullableType()) { return Conversion.NoConversion; } TypeSymbol unwrappedSource = source.StrippedType(); TypeSymbol unwrappedDestination = destination.StrippedType(); if (HasIdentityConversionInternal(unwrappedSource, unwrappedDestination)) { return new Conversion(ConversionKind.ExplicitNullable, Conversion.IdentityUnderlying); } if (HasImplicitNumericConversion(unwrappedSource, unwrappedDestination)) { return new Conversion(ConversionKind.ExplicitNullable, Conversion.ImplicitNumericUnderlying); } if (HasExplicitNumericConversion(unwrappedSource, unwrappedDestination)) { return new Conversion(ConversionKind.ExplicitNullable, Conversion.ExplicitNumericUnderlying); } var tupleConversion = ClassifyExplicitTupleConversion(unwrappedSource, unwrappedDestination, ref useSiteInfo, forCast); if (tupleConversion.Exists) { return new Conversion(ConversionKind.ExplicitNullable, ImmutableArray.Create(tupleConversion)); } if (HasExplicitEnumerationConversion(unwrappedSource, unwrappedDestination)) { return new Conversion(ConversionKind.ExplicitNullable, Conversion.ExplicitEnumerationUnderlying); } if (HasPointerToIntegerConversion(unwrappedSource, unwrappedDestination)) { return new Conversion(ConversionKind.ExplicitNullable, Conversion.PointerToIntegerUnderlying); } return Conversion.NoConversion; } private bool HasCovariantArrayConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); var s = source as ArrayTypeSymbol; var d = destination as ArrayTypeSymbol; if ((object)s == null || (object)d == null) { return false; } // * S and T differ only in element type. In other words, S and T have the same number of dimensions. if (!s.HasSameShapeAs(d)) { return false; } // * Both SE and TE are reference types. // * An implicit reference conversion exists from SE to TE. return HasImplicitReferenceConversion(s.ElementTypeWithAnnotations, d.ElementTypeWithAnnotations, ref useSiteInfo); } public bool HasIdentityOrImplicitReferenceConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); if (HasIdentityConversionInternal(source, destination)) { return true; } return HasImplicitReferenceConversion(source, destination, ref useSiteInfo); } private static bool HasImplicitDynamicConversionFromExpression(TypeSymbol expressionType, TypeSymbol destination) { // Spec (§6.1.8) // An implicit dynamic conversion exists from an expression of type dynamic to any type T. Debug.Assert((object)destination != null); return expressionType?.Kind == SymbolKind.DynamicType && !destination.IsPointerOrFunctionPointer(); } private static bool HasExplicitDynamicConversion(TypeSymbol source, TypeSymbol destination) { // SPEC: An explicit dynamic conversion exists from an expression of [sic] type dynamic to any type T. // ISSUE: The "an expression of" part of the spec is probably an error; see https://github.com/dotnet/csharplang/issues/132 Debug.Assert((object)source != null); Debug.Assert((object)destination != null); return source.Kind == SymbolKind.DynamicType && !destination.IsPointerOrFunctionPointer(); } private bool HasArrayConversionToInterface(ArrayTypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); if (!source.IsSZArray) { return false; } if (!destination.IsInterfaceType()) { return false; } // The specification says that there is a conversion: // * From a single-dimensional array type S[] to IList<T> and its base // interfaces, provided that there is an implicit identity or reference // conversion from S to T. // // Newer versions of the framework also have arrays be convertible to // IReadOnlyList<T> and IReadOnlyCollection<T>; we honor that as well. // // Therefore we must check for: // // IList<T> // ICollection<T> // IEnumerable<T> // IEnumerable // IReadOnlyList<T> // IReadOnlyCollection<T> if (destination.SpecialType == SpecialType.System_Collections_IEnumerable) { return true; } NamedTypeSymbol destinationAgg = (NamedTypeSymbol)destination; if (destinationAgg.AllTypeArgumentCount() != 1) { return false; } if (!destinationAgg.IsPossibleArrayGenericInterface()) { return false; } TypeWithAnnotations elementType = source.ElementTypeWithAnnotations; TypeWithAnnotations argument0 = destinationAgg.TypeArgumentWithDefinitionUseSiteDiagnostics(0, ref useSiteInfo); if (IncludeNullability && !HasTopLevelNullabilityImplicitConversion(elementType, argument0)) { return false; } return HasIdentityOrImplicitReferenceConversion(elementType.Type, argument0.Type, ref useSiteInfo); } private bool HasImplicitReferenceConversion(TypeWithAnnotations source, TypeWithAnnotations destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { if (IncludeNullability) { if (!HasTopLevelNullabilityImplicitConversion(source, destination)) { return false; } // Check for identity conversion of underlying types if the top-level nullability is distinct. // (An identity conversion where nullability matches is not considered an implicit reference conversion.) if (source.NullableAnnotation != destination.NullableAnnotation && HasIdentityConversionInternal(source.Type, destination.Type, includeNullability: true)) { return true; } } return HasImplicitReferenceConversion(source.Type, destination.Type, ref useSiteInfo); } internal bool HasImplicitReferenceConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); if (source.IsErrorType()) { return false; } if (!source.IsReferenceType) { return false; } // SPEC: The implicit reference conversions are: // SPEC: UNDONE: From any reference-type to a reference-type T if it has an implicit identity // SPEC: UNDONE: or reference conversion to a reference-type T0 and T0 has an identity conversion to T. // UNDONE: Is the right thing to do here to strip dynamic off and check for convertibility? // SPEC: From any reference type to object and dynamic. if (destination.SpecialType == SpecialType.System_Object || destination.Kind == SymbolKind.DynamicType) { return true; } switch (source.TypeKind) { case TypeKind.Class: // SPEC: From any class type S to any class type T provided S is derived from T. if (destination.IsClassType() && IsBaseClass(source, destination, ref useSiteInfo)) { return true; } return HasImplicitConversionToInterface(source, destination, ref useSiteInfo); case TypeKind.Interface: // SPEC: From any interface-type S to any interface-type T, provided S is derived from T. // NOTE: This handles variance conversions return HasImplicitConversionToInterface(source, destination, ref useSiteInfo); case TypeKind.Delegate: // SPEC: From any delegate-type to System.Delegate and the interfaces it implements. // NOTE: This handles variance conversions. return HasImplicitConversionFromDelegate(source, destination, ref useSiteInfo); case TypeKind.TypeParameter: return HasImplicitReferenceTypeParameterConversion((TypeParameterSymbol)source, destination, ref useSiteInfo); case TypeKind.Array: // SPEC: From an array-type S ... to an array-type T, provided ... // SPEC: From any array-type to System.Array and the interfaces it implements. // SPEC: From a single-dimensional array type S[] to IList<T>, provided ... return HasImplicitConversionFromArray(source, destination, ref useSiteInfo); } // UNDONE: Implicit conversions involving type parameters that are known to be reference types. return false; } private bool HasImplicitConversionToInterface(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { if (!destination.IsInterfaceType()) { return false; } // * From any class type S to any interface type T provided S implements an interface // convertible to T. if (source.IsClassType()) { return HasAnyBaseInterfaceConversion(source, destination, ref useSiteInfo); } // * From any interface type S to any interface type T provided S implements an interface // convertible to T. // * From any interface type S to any interface type T provided S is not T and S is // an interface convertible to T. if (source.IsInterfaceType()) { if (HasAnyBaseInterfaceConversion(source, destination, ref useSiteInfo)) { return true; } if (!HasIdentityConversionInternal(source, destination) && HasInterfaceVarianceConversion(source, destination, ref useSiteInfo)) { return true; } } return false; } private bool HasImplicitConversionFromArray(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { ArrayTypeSymbol s = source as ArrayTypeSymbol; if ((object)s == null) { return false; } // * From an array type S with an element type SE to an array type T with element type TE // provided that all of the following are true: // * S and T differ only in element type. In other words, S and T have the same number of dimensions. // * Both SE and TE are reference types. // * An implicit reference conversion exists from SE to TE. if (HasCovariantArrayConversion(source, destination, ref useSiteInfo)) { return true; } // * From any array type to System.Array or any interface implemented by System.Array. if (destination.GetSpecialTypeSafe() == SpecialType.System_Array) { return true; } if (IsBaseInterface(destination, this.corLibrary.GetDeclaredSpecialType(SpecialType.System_Array), ref useSiteInfo)) { return true; } // * From a single-dimensional array type S[] to IList<T> and its base // interfaces, provided that there is an implicit identity or reference // conversion from S to T. if (HasArrayConversionToInterface(s, destination, ref useSiteInfo)) { return true; } return false; } private bool HasImplicitConversionFromDelegate(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { if (!source.IsDelegateType()) { return false; } // * From any delegate type to System.Delegate // // SPEC OMISSION: // // The spec should actually say // // * From any delegate type to System.Delegate // * From any delegate type to System.MulticastDelegate // * From any delegate type to any interface implemented by System.MulticastDelegate var specialDestination = destination.GetSpecialTypeSafe(); if (specialDestination == SpecialType.System_MulticastDelegate || specialDestination == SpecialType.System_Delegate || IsBaseInterface(destination, this.corLibrary.GetDeclaredSpecialType(SpecialType.System_MulticastDelegate), ref useSiteInfo)) { return true; } // * From any delegate type S to a delegate type T provided S is not T and // S is a delegate convertible to T if (HasDelegateVarianceConversion(source, destination, ref useSiteInfo)) { return true; } return false; } public bool HasImplicitTypeParameterConversion(TypeParameterSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { if (HasImplicitReferenceTypeParameterConversion(source, destination, ref useSiteInfo)) { return true; } if (HasImplicitBoxingTypeParameterConversion(source, destination, ref useSiteInfo)) { return true; } if ((destination.TypeKind == TypeKind.TypeParameter) && source.DependsOn((TypeParameterSymbol)destination)) { return true; } return false; } private bool HasImplicitReferenceTypeParameterConversion(TypeParameterSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); if (source.IsValueType) { return false; // Not a reference conversion. } // The following implicit conversions exist for a given type parameter T: // // * From T to its effective base class C. // * From T to any base class of C. // * From T to any interface implemented by C (or any interface variance-compatible with such) if (HasImplicitEffectiveBaseConversion(source, destination, ref useSiteInfo)) { return true; } // * From T to any interface type I in T's effective interface set, and // from T to any base interface of I (or any interface variance-compatible with such) if (HasImplicitEffectiveInterfaceSetConversion(source, destination, ref useSiteInfo)) { return true; } // * From T to a type parameter U, provided T depends on U. if ((destination.TypeKind == TypeKind.TypeParameter) && source.DependsOn((TypeParameterSymbol)destination)) { return true; } return false; } // Spec 6.1.10: Implicit conversions involving type parameters private bool HasImplicitEffectiveBaseConversion(TypeParameterSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { // * From T to its effective base class C. var effectiveBaseClass = source.EffectiveBaseClass(ref useSiteInfo); if (HasIdentityConversionInternal(effectiveBaseClass, destination)) { return true; } // * From T to any base class of C. if (IsBaseClass(effectiveBaseClass, destination, ref useSiteInfo)) { return true; } // * From T to any interface implemented by C (or any interface variance-compatible with such) if (HasAnyBaseInterfaceConversion(effectiveBaseClass, destination, ref useSiteInfo)) { return true; } return false; } private bool HasImplicitEffectiveInterfaceSetConversion(TypeParameterSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { if (!destination.IsInterfaceType()) { return false; } // * From T to any interface type I in T's effective interface set, and // from T to any base interface of I (or any interface variance-compatible with such) foreach (var i in source.AllEffectiveInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteInfo)) { if (HasInterfaceVarianceConversion(i, destination, ref useSiteInfo)) { return true; } } return false; } private bool HasAnyBaseInterfaceConversion(TypeSymbol derivedType, TypeSymbol baseType, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)derivedType != null); Debug.Assert((object)baseType != null); if (!baseType.IsInterfaceType()) { return false; } var d = derivedType as NamedTypeSymbol; if ((object)d == null) { return false; } foreach (var i in d.AllInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteInfo)) { if (HasInterfaceVarianceConversion(i, baseType, ref useSiteInfo)) { return true; } } return false; } //////////////////////////////////////////////////////////////////////////////// // The rules for variant interface and delegate conversions are the same: // // An interface/delegate type S is convertible to an interface/delegate type T // if and only if T is U<S1, ... Sn> and T is U<T1, ... Tn> such that for all // parameters of U: // // * if the ith parameter of U is invariant then Si is exactly equal to Ti. // * if the ith parameter of U is covariant then either Si is exactly equal // to Ti, or there is an implicit reference conversion from Si to Ti. // * if the ith parameter of U is contravariant then either Si is exactly // equal to Ti, or there is an implicit reference conversion from Ti to Si. private bool HasInterfaceVarianceConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); NamedTypeSymbol s = source as NamedTypeSymbol; NamedTypeSymbol d = destination as NamedTypeSymbol; if ((object)s == null || (object)d == null) { return false; } if (!s.IsInterfaceType() || !d.IsInterfaceType()) { return false; } return HasVariantConversion(s, d, ref useSiteInfo); } private bool HasDelegateVarianceConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); NamedTypeSymbol s = source as NamedTypeSymbol; NamedTypeSymbol d = destination as NamedTypeSymbol; if ((object)s == null || (object)d == null) { return false; } if (!s.IsDelegateType() || !d.IsDelegateType()) { return false; } return HasVariantConversion(s, d, ref useSiteInfo); } private bool HasVariantConversion(NamedTypeSymbol source, NamedTypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { // We check for overflows in HasVariantConversion, because they are only an issue // in the presence of contravariant type parameters, which are not involved in // most conversions. // See VarianceTests for examples (e.g. TestVarianceConversionCycle, // TestVarianceConversionInfiniteExpansion). // // CONSIDER: A more rigorous solution would mimic the CLI approach, which uses // a combination of requiring finite instantiation closures (see section 9.2 of // the CLI spec) and records previous conversion steps to check for cycles. if (currentRecursionDepth >= MaximumRecursionDepth) { // NOTE: The spec doesn't really address what happens if there's an overflow // in our conversion check. It's sort of implied that the conversion "proof" // should be finite, so we'll just say that no conversion is possible. return false; } // Do a quick check up front to avoid instantiating a new Conversions object, // if possible. var quickResult = HasVariantConversionQuick(source, destination); if (quickResult.HasValue()) { return quickResult.Value(); } return this.CreateInstance(currentRecursionDepth + 1). HasVariantConversionNoCycleCheck(source, destination, ref useSiteInfo); } private ThreeState HasVariantConversionQuick(NamedTypeSymbol source, NamedTypeSymbol destination) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); if (HasIdentityConversionInternal(source, destination)) { return ThreeState.True; } NamedTypeSymbol typeSymbol = source.OriginalDefinition; if (!TypeSymbol.Equals(typeSymbol, destination.OriginalDefinition, TypeCompareKind.ConsiderEverything2)) { return ThreeState.False; } return ThreeState.Unknown; } private bool HasVariantConversionNoCycleCheck(NamedTypeSymbol source, NamedTypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); var typeParameters = ArrayBuilder<TypeWithAnnotations>.GetInstance(); var sourceTypeArguments = ArrayBuilder<TypeWithAnnotations>.GetInstance(); var destinationTypeArguments = ArrayBuilder<TypeWithAnnotations>.GetInstance(); try { source.OriginalDefinition.GetAllTypeArguments(typeParameters, ref useSiteInfo); source.GetAllTypeArguments(sourceTypeArguments, ref useSiteInfo); destination.GetAllTypeArguments(destinationTypeArguments, ref useSiteInfo); Debug.Assert(TypeSymbol.Equals(source.OriginalDefinition, destination.OriginalDefinition, TypeCompareKind.AllIgnoreOptions)); Debug.Assert(typeParameters.Count == sourceTypeArguments.Count); Debug.Assert(typeParameters.Count == destinationTypeArguments.Count); for (int paramIndex = 0; paramIndex < typeParameters.Count; ++paramIndex) { var sourceTypeArgument = sourceTypeArguments[paramIndex]; var destinationTypeArgument = destinationTypeArguments[paramIndex]; // If they're identical then this one is automatically good, so skip it. if (HasIdentityConversionInternal(sourceTypeArgument.Type, destinationTypeArgument.Type) && HasTopLevelNullabilityIdentityConversion(sourceTypeArgument, destinationTypeArgument)) { continue; } TypeParameterSymbol typeParameterSymbol = (TypeParameterSymbol)typeParameters[paramIndex].Type; switch (typeParameterSymbol.Variance) { case VarianceKind.None: // System.IEquatable<T> is invariant for back compat reasons (dynamic type checks could start // to succeed where they previously failed, creating different runtime behavior), but the uses // require treatment specifically of nullability as contravariant, so we special case the // behavior here. Normally we use GetWellKnownType for these kinds of checks, but in this // case we don't want just the canonical IEquatable to be special-cased, we want all definitions // to be treated as contravariant, in case there are other definitions in metadata that were // compiled with that expectation. if (isTypeIEquatable(destination.OriginalDefinition) && TypeSymbol.Equals(destinationTypeArgument.Type, sourceTypeArgument.Type, TypeCompareKind.AllNullableIgnoreOptions) && HasAnyNullabilityImplicitConversion(destinationTypeArgument, sourceTypeArgument)) { return true; } return false; case VarianceKind.Out: if (!HasImplicitReferenceConversion(sourceTypeArgument, destinationTypeArgument, ref useSiteInfo)) { return false; } break; case VarianceKind.In: if (!HasImplicitReferenceConversion(destinationTypeArgument, sourceTypeArgument, ref useSiteInfo)) { return false; } break; default: throw ExceptionUtilities.UnexpectedValue(typeParameterSymbol.Variance); } } } finally { typeParameters.Free(); sourceTypeArguments.Free(); destinationTypeArguments.Free(); } return true; static bool isTypeIEquatable(NamedTypeSymbol type) { return type is { IsInterface: true, Name: "IEquatable", ContainingNamespace: { Name: "System", ContainingNamespace: { IsGlobalNamespace: true } }, ContainingSymbol: { Kind: SymbolKind.Namespace }, TypeParameters: { Length: 1 } }; } } // Spec 6.1.10 private bool HasImplicitBoxingTypeParameterConversion(TypeParameterSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); if (source.IsReferenceType) { return false; // Not a boxing conversion; both source and destination are references. } // The following implicit conversions exist for a given type parameter T: // // * From T to its effective base class C. // * From T to any base class of C. // * From T to any interface implemented by C (or any interface variance-compatible with such) if (HasImplicitEffectiveBaseConversion(source, destination, ref useSiteInfo)) { return true; } // * From T to any interface type I in T's effective interface set, and // from T to any base interface of I (or any interface variance-compatible with such) if (HasImplicitEffectiveInterfaceSetConversion(source, destination, ref useSiteInfo)) { return true; } // SPEC: From T to a type parameter U, provided T depends on U if ((destination.TypeKind == TypeKind.TypeParameter) && source.DependsOn((TypeParameterSymbol)destination)) { return true; } // SPEC: From T to a reference type I if it has an implicit conversion to a reference // SPEC: type S0 and S0 has an identity conversion to S. At run-time the conversion // SPEC: is executed the same way as the conversion to S0. // REVIEW: If T is not known to be a reference type then the only way this clause can // REVIEW: come into effect is if the target type is dynamic. Is that correct? if (destination.Kind == SymbolKind.DynamicType) { return true; } return false; } public bool HasBoxingConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); // Certain type parameter conversions are classified as boxing conversions. if ((source.TypeKind == TypeKind.TypeParameter) && HasImplicitBoxingTypeParameterConversion((TypeParameterSymbol)source, destination, ref useSiteInfo)) { return true; } // The rest of the boxing conversions only operate when going from a value type to a // reference type. if (!source.IsValueType || !destination.IsReferenceType) { return false; } // A boxing conversion exists from a nullable type to a reference type if and only if a // boxing conversion exists from the underlying type. if (source.IsNullableType()) { return HasBoxingConversion(source.GetNullableUnderlyingType(), destination, ref useSiteInfo); } // A boxing conversion exists from any non-nullable value type to object and dynamic, to // System.ValueType, and to any interface type variance-compatible with one implemented // by the non-nullable value type. // Furthermore, an enum type can be converted to the type System.Enum. // We set the base class of the structs to System.ValueType, System.Enum, etc, so we can // just check here. // There are a couple of exceptions. The very special types ArgIterator, ArgumentHandle and // TypedReference are not boxable: if (source.IsRestrictedType()) { return false; } if (destination.Kind == SymbolKind.DynamicType) { return !source.IsPointerOrFunctionPointer(); } if (IsBaseClass(source, destination, ref useSiteInfo)) { return true; } if (HasAnyBaseInterfaceConversion(source, destination, ref useSiteInfo)) { return true; } return false; } internal static bool HasImplicitPointerToVoidConversion(TypeSymbol source, TypeSymbol destination) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); // SPEC: The set of implicit conversions is extended to include... // SPEC: ... from any pointer type to the type void*. return source.IsPointerOrFunctionPointer() && destination is PointerTypeSymbol { PointedAtType: { SpecialType: SpecialType.System_Void } }; } #nullable enable internal bool HasImplicitPointerConversion(TypeSymbol? source, TypeSymbol? destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { if (!(source is FunctionPointerTypeSymbol { Signature: { } sourceSig }) || !(destination is FunctionPointerTypeSymbol { Signature: { } destinationSig })) { return false; } if (sourceSig.ParameterCount != destinationSig.ParameterCount || sourceSig.CallingConvention != destinationSig.CallingConvention) { return false; } if (sourceSig.CallingConvention == Cci.CallingConvention.Unmanaged && !sourceSig.GetCallingConventionModifiers().SetEquals(destinationSig.GetCallingConventionModifiers())) { return false; } for (int i = 0; i < sourceSig.ParameterCount; i++) { var sourceParam = sourceSig.Parameters[i]; var destinationParam = destinationSig.Parameters[i]; if (sourceParam.RefKind != destinationParam.RefKind) { return false; } if (!hasConversion(sourceParam.RefKind, destinationSig.Parameters[i].TypeWithAnnotations, sourceSig.Parameters[i].TypeWithAnnotations, ref useSiteInfo)) { return false; } } return sourceSig.RefKind == destinationSig.RefKind && hasConversion(sourceSig.RefKind, sourceSig.ReturnTypeWithAnnotations, destinationSig.ReturnTypeWithAnnotations, ref useSiteInfo); bool hasConversion(RefKind refKind, TypeWithAnnotations sourceType, TypeWithAnnotations destinationType, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { switch (refKind) { case RefKind.None: return (!IncludeNullability || HasTopLevelNullabilityImplicitConversion(sourceType, destinationType)) && (HasIdentityOrImplicitReferenceConversion(sourceType.Type, destinationType.Type, ref useSiteInfo) || HasImplicitPointerToVoidConversion(sourceType.Type, destinationType.Type) || HasImplicitPointerConversion(sourceType.Type, destinationType.Type, ref useSiteInfo)); default: return (!IncludeNullability || HasTopLevelNullabilityIdentityConversion(sourceType, destinationType)) && HasIdentityConversion(sourceType.Type, destinationType.Type); } } } #nullable disable private bool HasIdentityOrReferenceConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); if (HasIdentityConversionInternal(source, destination)) { return true; } if (HasImplicitReferenceConversion(source, destination, ref useSiteInfo)) { return true; } if (HasExplicitReferenceConversion(source, destination, ref useSiteInfo)) { return true; } return false; } private bool HasExplicitReferenceConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); // SPEC: The explicit reference conversions are: // SPEC: From object and dynamic to any other reference type. if (source.SpecialType == SpecialType.System_Object) { if (destination.IsReferenceType) { return true; } } else if (source.Kind == SymbolKind.DynamicType && destination.IsReferenceType) { return true; } // SPEC: From any class-type S to any class-type T, provided S is a base class of T. if (destination.IsClassType() && IsBaseClass(destination, source, ref useSiteInfo)) { return true; } // SPEC: From any class-type S to any interface-type T, provided S is not sealed and provided S does not implement T. // ISSUE: class C : IEnumerable<Mammal> { } converting this to IEnumerable<Animal> is not an explicit conversion, // ISSUE: it is an implicit conversion. if (source.IsClassType() && destination.IsInterfaceType() && !source.IsSealed && !HasAnyBaseInterfaceConversion(source, destination, ref useSiteInfo)) { return true; } // SPEC: From any interface-type S to any class-type T, provided T is not sealed or provided T implements S. // ISSUE: What if T is sealed and implements an interface variance-convertible to S? // ISSUE: eg, sealed class C : IEnum<Mammal> { ... } you should be able to cast an IEnum<Animal> to C. if (source.IsInterfaceType() && destination.IsClassType() && (!destination.IsSealed || HasAnyBaseInterfaceConversion(destination, source, ref useSiteInfo))) { return true; } // SPEC: From any interface-type S to any interface-type T, provided S is not derived from T. // ISSUE: This does not rule out identity conversions, which ought not to be classified as // ISSUE: explicit reference conversions. // ISSUE: IEnumerable<Mammal> and IEnumerable<Animal> do not derive from each other but this is // ISSUE: not an explicit reference conversion, this is an implicit reference conversion. if (source.IsInterfaceType() && destination.IsInterfaceType() && !HasImplicitConversionToInterface(source, destination, ref useSiteInfo)) { return true; } // SPEC: UNDONE: From a reference type to a reference type T if it has an explicit reference conversion to a reference type T0 and T0 has an identity conversion T. // SPEC: UNDONE: From a reference type to an interface or delegate type T if it has an explicit reference conversion to an interface or delegate type T0 and either T0 is variance-convertible to T or T is variance-convertible to T0 (§13.1.3.2). if (HasExplicitArrayConversion(source, destination, ref useSiteInfo)) { return true; } if (HasExplicitDelegateConversion(source, destination, ref useSiteInfo)) { return true; } if (HasExplicitReferenceTypeParameterConversion(source, destination, ref useSiteInfo)) { return true; } return false; } // Spec 6.2.7 Explicit conversions involving type parameters private bool HasExplicitReferenceTypeParameterConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); TypeParameterSymbol s = source as TypeParameterSymbol; TypeParameterSymbol t = destination as TypeParameterSymbol; // SPEC: The following explicit conversions exist for a given type parameter T: // SPEC: If T is known to be a reference type, the conversions are all classified as explicit reference conversions. // SPEC: If T is not known to be a reference type, the conversions are classified as unboxing conversions. // SPEC: From the effective base class C of T to T and from any base class of C to T. if ((object)t != null && t.IsReferenceType) { for (var type = t.EffectiveBaseClass(ref useSiteInfo); (object)type != null; type = type.BaseTypeWithDefinitionUseSiteDiagnostics(ref useSiteInfo)) { if (HasIdentityConversionInternal(type, source)) { return true; } } } // SPEC: From any interface type to T. if ((object)t != null && source.IsInterfaceType() && t.IsReferenceType) { return true; } // SPEC: From T to any interface-type I provided there is not already an implicit conversion from T to I. if ((object)s != null && s.IsReferenceType && destination.IsInterfaceType() && !HasImplicitReferenceTypeParameterConversion(s, destination, ref useSiteInfo)) { return true; } // SPEC: From a type parameter U to T, provided T depends on U (§10.1.5) if ((object)s != null && (object)t != null && t.IsReferenceType && t.DependsOn(s)) { return true; } return false; } // Spec 6.2.7 Explicit conversions involving type parameters private bool HasUnboxingTypeParameterConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); TypeParameterSymbol s = source as TypeParameterSymbol; TypeParameterSymbol t = destination as TypeParameterSymbol; // SPEC: The following explicit conversions exist for a given type parameter T: // SPEC: If T is known to be a reference type, the conversions are all classified as explicit reference conversions. // SPEC: If T is not known to be a reference type, the conversions are classified as unboxing conversions. // SPEC: From the effective base class C of T to T and from any base class of C to T. if ((object)t != null && !t.IsReferenceType) { for (var type = t.EffectiveBaseClass(ref useSiteInfo); (object)type != null; type = type.BaseTypeWithDefinitionUseSiteDiagnostics(ref useSiteInfo)) { if (TypeSymbol.Equals(type, source, TypeCompareKind.ConsiderEverything2)) { return true; } } } // SPEC: From any interface type to T. if (source.IsInterfaceType() && (object)t != null && !t.IsReferenceType) { return true; } // SPEC: From T to any interface-type I provided there is not already an implicit conversion from T to I. if ((object)s != null && !s.IsReferenceType && destination.IsInterfaceType() && !HasImplicitReferenceTypeParameterConversion(s, destination, ref useSiteInfo)) { return true; } // SPEC: From a type parameter U to T, provided T depends on U (§10.1.5) if ((object)s != null && (object)t != null && !t.IsReferenceType && t.DependsOn(s)) { return true; } return false; } private bool HasExplicitDelegateConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); // SPEC: From System.Delegate and the interfaces it implements to any delegate-type. // We also support System.MulticastDelegate in the implementation, in spite of it not being mentioned in the spec. if (destination.IsDelegateType()) { if (source.SpecialType == SpecialType.System_Delegate || source.SpecialType == SpecialType.System_MulticastDelegate) { return true; } if (HasImplicitConversionToInterface(this.corLibrary.GetDeclaredSpecialType(SpecialType.System_Delegate), source, ref useSiteInfo)) { return true; } } // SPEC: From D<S1...Sn> to a D<T1...Tn> where D<X1...Xn> is a generic delegate type, D<S1...Sn> is not compatible with or identical to D<T1...Tn>, // SPEC: and for each type parameter Xi of D the following holds: // SPEC: If Xi is invariant, then Si is identical to Ti. // SPEC: If Xi is covariant, then there is an implicit or explicit identity or reference conversion from Si to Ti. // SPECL If Xi is contravariant, then Si and Ti are either identical or both reference types. if (!source.IsDelegateType() || !destination.IsDelegateType()) { return false; } if (!TypeSymbol.Equals(source.OriginalDefinition, destination.OriginalDefinition, TypeCompareKind.ConsiderEverything2)) { return false; } var sourceType = (NamedTypeSymbol)source; var destinationType = (NamedTypeSymbol)destination; var original = sourceType.OriginalDefinition; if (HasIdentityConversionInternal(source, destination)) { return false; } if (HasDelegateVarianceConversion(source, destination, ref useSiteInfo)) { return false; } var sourceTypeArguments = sourceType.TypeArgumentsWithDefinitionUseSiteDiagnostics(ref useSiteInfo); var destinationTypeArguments = destinationType.TypeArgumentsWithDefinitionUseSiteDiagnostics(ref useSiteInfo); for (int i = 0; i < sourceTypeArguments.Length; ++i) { var sourceArg = sourceTypeArguments[i].Type; var destinationArg = destinationTypeArguments[i].Type; switch (original.TypeParameters[i].Variance) { case VarianceKind.None: if (!HasIdentityConversionInternal(sourceArg, destinationArg)) { return false; } break; case VarianceKind.Out: if (!HasIdentityOrReferenceConversion(sourceArg, destinationArg, ref useSiteInfo)) { return false; } break; case VarianceKind.In: bool hasIdentityConversion = HasIdentityConversionInternal(sourceArg, destinationArg); bool bothAreReferenceTypes = sourceArg.IsReferenceType && destinationArg.IsReferenceType; if (!(hasIdentityConversion || bothAreReferenceTypes)) { return false; } break; } } return true; } private bool HasExplicitArrayConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); var sourceArray = source as ArrayTypeSymbol; var destinationArray = destination as ArrayTypeSymbol; // SPEC: From an array-type S with an element type SE to an array-type T with an element type TE, provided all of the following are true: // SPEC: S and T differ only in element type. (In other words, S and T have the same number of dimensions.) // SPEC: Both SE and TE are reference-types. // SPEC: An explicit reference conversion exists from SE to TE. if ((object)sourceArray != null && (object)destinationArray != null) { // HasExplicitReferenceConversion checks that SE and TE are reference types so // there's no need for that check here. Moreover, it's not as simple as checking // IsReferenceType, at least not in the case of type parameters, since SE will be // considered a reference type implicitly in the case of "where TE : class, SE" even // though SE.IsReferenceType may be false. Again, HasExplicitReferenceConversion // already handles these cases. return sourceArray.HasSameShapeAs(destinationArray) && HasExplicitReferenceConversion(sourceArray.ElementType, destinationArray.ElementType, ref useSiteInfo); } // SPEC: From System.Array and the interfaces it implements to any array-type. if ((object)destinationArray != null) { if (source.SpecialType == SpecialType.System_Array) { return true; } foreach (var iface in this.corLibrary.GetDeclaredSpecialType(SpecialType.System_Array).AllInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteInfo)) { if (HasIdentityConversionInternal(iface, source)) { return true; } } } // SPEC: From a single-dimensional array type S[] to System.Collections.Generic.IList<T> and its base interfaces // SPEC: provided that there is an explicit reference conversion from S to T. // The framework now also allows arrays to be converted to IReadOnlyList<T> and IReadOnlyCollection<T>; we // honor that as well. if ((object)sourceArray != null && sourceArray.IsSZArray && destination.IsPossibleArrayGenericInterface()) { if (HasExplicitReferenceConversion(sourceArray.ElementType, ((NamedTypeSymbol)destination).TypeArgumentWithDefinitionUseSiteDiagnostics(0, ref useSiteInfo).Type, ref useSiteInfo)) { return true; } } // SPEC: From System.Collections.Generic.IList<S> and its base interfaces to a single-dimensional array type T[], // provided that there is an explicit identity or reference conversion from S to T. // Similarly, we honor IReadOnlyList<S> and IReadOnlyCollection<S> in the same way. if ((object)destinationArray != null && destinationArray.IsSZArray) { var specialDefinition = ((TypeSymbol)source.OriginalDefinition).SpecialType; if (specialDefinition == SpecialType.System_Collections_Generic_IList_T || specialDefinition == SpecialType.System_Collections_Generic_ICollection_T || specialDefinition == SpecialType.System_Collections_Generic_IEnumerable_T || specialDefinition == SpecialType.System_Collections_Generic_IReadOnlyList_T || specialDefinition == SpecialType.System_Collections_Generic_IReadOnlyCollection_T) { var sourceElement = ((NamedTypeSymbol)source).TypeArgumentWithDefinitionUseSiteDiagnostics(0, ref useSiteInfo).Type; var destinationElement = destinationArray.ElementType; if (HasIdentityConversionInternal(sourceElement, destinationElement)) { return true; } if (HasImplicitReferenceConversion(sourceElement, destinationElement, ref useSiteInfo)) { return true; } if (HasExplicitReferenceConversion(sourceElement, destinationElement, ref useSiteInfo)) { return true; } } } return false; } private bool HasUnboxingConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); if (destination.IsPointerOrFunctionPointer()) { return false; } // Ref-like types cannot be boxed or unboxed if (destination.IsRestrictedType()) { return false; } // SPEC: An unboxing conversion permits a reference type to be explicitly converted to a value-type. // SPEC: An unboxing conversion exists from the types object and System.ValueType to any non-nullable-value-type, var specialTypeSource = source.SpecialType; if (specialTypeSource == SpecialType.System_Object || specialTypeSource == SpecialType.System_ValueType) { if (destination.IsValueType && !destination.IsNullableType()) { return true; } } // SPEC: and from any interface-type to any non-nullable-value-type that implements the interface-type. if (source.IsInterfaceType() && destination.IsValueType && !destination.IsNullableType() && HasBoxingConversion(destination, source, ref useSiteInfo)) { return true; } // SPEC: Furthermore type System.Enum can be unboxed to any enum-type. if (source.SpecialType == SpecialType.System_Enum && destination.IsEnumType()) { return true; } // SPEC: An unboxing conversion exists from a reference type to a nullable-type if an unboxing // SPEC: conversion exists from the reference type to the underlying non-nullable-value-type // SPEC: of the nullable-type. if (source.IsReferenceType && destination.IsNullableType() && HasUnboxingConversion(source, destination.GetNullableUnderlyingType(), ref useSiteInfo)) { return true; } // SPEC: UNDONE A value type S has an unboxing conversion from an interface type I if it has an unboxing // SPEC: UNDONE conversion from an interface type I0 and I0 has an identity conversion to I. // SPEC: UNDONE A value type S has an unboxing conversion from an interface type I if it has an unboxing conversion // SPEC: UNDONE from an interface or delegate type I0 and either I0 is variance-convertible to I or I is variance-convertible to I0. if (HasUnboxingTypeParameterConversion(source, destination, ref useSiteInfo)) { return true; } return false; } private static bool HasPointerToPointerConversion(TypeSymbol source, TypeSymbol destination) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); return source.IsPointerOrFunctionPointer() && destination.IsPointerOrFunctionPointer(); } private static bool HasPointerToIntegerConversion(TypeSymbol source, TypeSymbol destination) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); if (!source.IsPointerOrFunctionPointer()) { return false; } // SPEC OMISSION: // // The spec should state that any pointer type is convertible to // sbyte, byte, ... etc, or any corresponding nullable type. return IsIntegerTypeSupportingPointerConversions(destination.StrippedType()); } private static bool HasIntegerToPointerConversion(TypeSymbol source, TypeSymbol destination) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); if (!destination.IsPointerOrFunctionPointer()) { return false; } // Note that void* is convertible to int?, but int? is not convertible to void*. return IsIntegerTypeSupportingPointerConversions(source); } private static bool IsIntegerTypeSupportingPointerConversions(TypeSymbol type) { switch (type.SpecialType) { case SpecialType.System_SByte: case SpecialType.System_Byte: case SpecialType.System_Int16: case SpecialType.System_UInt16: case SpecialType.System_Int32: case SpecialType.System_UInt32: case SpecialType.System_Int64: case SpecialType.System_UInt64: return true; case SpecialType.System_IntPtr: case SpecialType.System_UIntPtr: return type.IsNativeIntegerType; } return false; } } }
1
dotnet/roslyn
55,256
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-30T00:02:02Z
2021-07-30T09:17:54Z
6ce9c0048d37026337701fac035ac0745f6fe49f
88b59775dc6375635957ef229116460f290072aa
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Compilers/CSharp/Portable/Compilation/CSharpCompilationExtensions.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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; namespace Microsoft.CodeAnalysis.CSharp { internal static class CSharpCompilationExtensions { internal static bool IsFeatureEnabled(this CSharpCompilation compilation, MessageID feature) { return ((CSharpParseOptions)compilation.SyntaxTrees.FirstOrDefault()?.Options)?.IsFeatureEnabled(feature) == true; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Linq; namespace Microsoft.CodeAnalysis.CSharp { internal static class CSharpCompilationExtensions { internal static bool IsFeatureEnabled(this CSharpCompilation compilation, MessageID feature) { return ((CSharpParseOptions?)compilation.SyntaxTrees.FirstOrDefault()?.Options)?.IsFeatureEnabled(feature) == true; } internal static bool IsFeatureEnabled(this SyntaxNode? syntax, MessageID feature) { return ((CSharpParseOptions?)syntax?.SyntaxTree.Options)?.IsFeatureEnabled(feature) == true; } } }
1
dotnet/roslyn
55,256
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-30T00:02:02Z
2021-07-30T09:17:54Z
6ce9c0048d37026337701fac035ac0745f6fe49f
88b59775dc6375635957ef229116460f290072aa
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Compilers/CSharp/Test/Emit/CodeGen/CodeGenTupleEqualityTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Linq; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.CodeGen { [CompilerTrait(CompilerFeature.TupleEquality)] public class CodeGenTupleEqualityTests : CSharpTestBase { [Fact] public void TestCSharp7_2() { var source = @" class C { static void Main() { var t = (1, 2); System.Console.Write(t == (1, 2)); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular7_2); comp.VerifyDiagnostics( // (7,30): error CS8320: Feature 'tuple equality' is not available in C# 7.2. Please use language version 7.3 or greater. // System.Console.Write(t == (1, 2)); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_2, "t == (1, 2)").WithArguments("tuple equality", "7.3").WithLocation(7, 30) ); } [Theory] [InlineData("(1, 2)", "(1L, 2L)", true)] [InlineData("(1, 2)", "(1, 0)", false)] [InlineData("(1, 2)", "(0, 2)", false)] [InlineData("(1, 2)", "((long, long))(1, 2)", true)] [InlineData("((1, 2L), (3, 4))", "((1L, 2), (3L, 4))", true)] [InlineData("((1, 2L), (3, 4))", "((0L, 2), (3L, 4))", false)] [InlineData("((1, 2L), (3, 4))", "((1L, 0), (3L, 4))", false)] [InlineData("((1, 2L), (3, 4))", "((1L, 0), (0L, 4))", false)] [InlineData("((1, 2L), (3, 4))", "((1L, 0), (3L, 0))", false)] void TestSimple(string change1, string change2, bool expectedMatch) { var sourceTemplate = @" class C { static void Main() { var t1 = CHANGE1; var t2 = CHANGE2; System.Console.Write($""{(t1 == t2) == EXPECTED} {(t1 != t2) != EXPECTED}""); } }"; string source = sourceTemplate .Replace("CHANGE1", change1) .Replace("CHANGE2", change2) .Replace("EXPECTED", expectedMatch ? "true" : "false"); string name = GetUniqueName(); var comp = CreateCompilation(source, options: TestOptions.DebugExe, assemblyName: name); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "True True"); } [Fact] public void TestTupleLiteralsWithDifferentCardinalities() { var source = @" class C { static bool M() { return (1, 1) == (2, 2, 2); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,16): error CS8373: Tuple types used as operands of an == or != operator must have matching cardinalities. But this operator has tuple types of cardinality 2 on the left and 3 on the right. // return (1, 1) == (2, 2, 2); Diagnostic(ErrorCode.ERR_TupleSizesMismatchForBinOps, "(1, 1) == (2, 2, 2)").WithArguments("2", "3").WithLocation(6, 16) ); } [Fact] public void TestTuplesWithDifferentCardinalities() { var source = @" class C { static bool M() { var t1 = (1, 1); var t2 = (2, 2, 2); return t1 == t2; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (8,16): error CS8355: Tuple types used as operands of a binary operator must have matching cardinalities. But this operator has tuple types of cardinality 2 on the left and 3 on the right. // return t1 == t2; Diagnostic(ErrorCode.ERR_TupleSizesMismatchForBinOps, "t1 == t2").WithArguments("2", "3").WithLocation(8, 16) ); } [Fact] public void TestNestedTuplesWithDifferentCardinalities() { var source = @" class C { static bool M() { var t1 = (1, (1, 1)); var t2 = (2, (2, 2, 2)); return t1 == t2; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (8,16): error CS8355: Tuple types used as operands of a binary operator must have matching cardinalities. But this operator has tuple types of cardinality 2 on the left and 3 on the right. // return t1 == t2; Diagnostic(ErrorCode.ERR_TupleSizesMismatchForBinOps, "t1 == t2").WithArguments("2", "3").WithLocation(8, 16) ); } [Fact, WorkItem(25295, "https://github.com/dotnet/roslyn/issues/25295")] public void TestWithoutValueTuple() { var source = @" class C { static bool M() { return (1, 2) == (3, 4); } }"; var comp = CreateCompilationWithMscorlib40(source); // https://github.com/dotnet/roslyn/issues/25295 // Can we relax the requirement on ValueTuple types being found? comp.VerifyDiagnostics( // (6,16): error CS8179: Predefined type 'System.ValueTuple`2' is not defined or imported // return (1, 2) == (3, 4); Diagnostic(ErrorCode.ERR_PredefinedValueTupleTypeNotFound, "(1, 2)").WithArguments("System.ValueTuple`2").WithLocation(6, 16), // (6,26): error CS8179: Predefined type 'System.ValueTuple`2' is not defined or imported // return (1, 2) == (3, 4); Diagnostic(ErrorCode.ERR_PredefinedValueTupleTypeNotFound, "(3, 4)").WithArguments("System.ValueTuple`2").WithLocation(6, 26) ); } [Fact] public void TestNestedNullableTuplesWithDifferentCardinalities() { var source = @" class C { static bool M() { (int, int)? nt = (1, 1); var t1 = (1, nt); var t2 = (2, (2, 2, 2)); return t1 == t2; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (9,16): error CS8373: Tuple types used as operands of a binary operator must have matching cardinalities. But this operator has tuple types of cardinality 2 on the left and 3 on the right. // return t1 == t2; Diagnostic(ErrorCode.ERR_TupleSizesMismatchForBinOps, "t1 == t2").WithArguments("2", "3").WithLocation(9, 16) ); } [Fact] public void TestILForSimpleEqual() { var source = @" class C { static bool M() { var t1 = (1, 1); var t2 = (2, 2); return t1 == t2; } }"; var comp = CompileAndVerify(source); comp.VerifyDiagnostics(); comp.VerifyIL("C.M", @"{ // Code size 50 (0x32) .maxstack 3 .locals init (System.ValueTuple<int, int> V_0, //t1 System.ValueTuple<int, int> V_1, System.ValueTuple<int, int> V_2) IL_0000: ldloca.s V_0 IL_0002: ldc.i4.1 IL_0003: ldc.i4.1 IL_0004: call ""System.ValueTuple<int, int>..ctor(int, int)"" IL_0009: ldc.i4.2 IL_000a: ldc.i4.2 IL_000b: newobj ""System.ValueTuple<int, int>..ctor(int, int)"" IL_0010: ldloc.0 IL_0011: stloc.1 IL_0012: stloc.2 IL_0013: ldloc.1 IL_0014: ldfld ""int System.ValueTuple<int, int>.Item1"" IL_0019: ldloc.2 IL_001a: ldfld ""int System.ValueTuple<int, int>.Item1"" IL_001f: bne.un.s IL_0030 IL_0021: ldloc.1 IL_0022: ldfld ""int System.ValueTuple<int, int>.Item2"" IL_0027: ldloc.2 IL_0028: ldfld ""int System.ValueTuple<int, int>.Item2"" IL_002d: ceq IL_002f: ret IL_0030: ldc.i4.0 IL_0031: ret }"); } [Fact] public void TestILForSimpleNotEqual() { var source = @" class C { static bool M((int, int) t1, (int, int) t2) { return t1 != t2; } }"; var comp = CompileAndVerify(source); comp.VerifyDiagnostics(); comp.VerifyIL("C.M", @"{ // Code size 38 (0x26) .maxstack 2 .locals init (System.ValueTuple<int, int> V_0, System.ValueTuple<int, int> V_1) IL_0000: ldarg.0 IL_0001: stloc.0 IL_0002: ldarg.1 IL_0003: stloc.1 IL_0004: ldloc.0 IL_0005: ldfld ""int System.ValueTuple<int, int>.Item1"" IL_000a: ldloc.1 IL_000b: ldfld ""int System.ValueTuple<int, int>.Item1"" IL_0010: bne.un.s IL_0024 IL_0012: ldloc.0 IL_0013: ldfld ""int System.ValueTuple<int, int>.Item2"" IL_0018: ldloc.1 IL_0019: ldfld ""int System.ValueTuple<int, int>.Item2"" IL_001e: ceq IL_0020: ldc.i4.0 IL_0021: ceq IL_0023: ret IL_0024: ldc.i4.1 IL_0025: ret }"); } [Fact] public void TestILForSimpleEqualOnInTuple() { var source = @" class C { static bool M(in (int, int) t1, in (int, int) t2) { return t1 == t2; } }"; var comp = CompileAndVerify(source); comp.VerifyDiagnostics(); // note: the logic to save variables and side-effects results in copying the inputs comp.VerifyIL("C.M", @"{ // Code size 45 (0x2d) .maxstack 2 .locals init (System.ValueTuple<int, int> V_0, System.ValueTuple<int, int> V_1) IL_0000: ldarg.0 IL_0001: ldobj ""System.ValueTuple<int, int>"" IL_0006: stloc.0 IL_0007: ldarg.1 IL_0008: ldobj ""System.ValueTuple<int, int>"" IL_000d: stloc.1 IL_000e: ldloc.0 IL_000f: ldfld ""int System.ValueTuple<int, int>.Item1"" IL_0014: ldloc.1 IL_0015: ldfld ""int System.ValueTuple<int, int>.Item1"" IL_001a: bne.un.s IL_002b IL_001c: ldloc.0 IL_001d: ldfld ""int System.ValueTuple<int, int>.Item2"" IL_0022: ldloc.1 IL_0023: ldfld ""int System.ValueTuple<int, int>.Item2"" IL_0028: ceq IL_002a: ret IL_002b: ldc.i4.0 IL_002c: ret }"); } [Fact] public void TestILForSimpleEqualOnTupleLiterals() { var source = @" class C { static void Main() { M(1, 1); M(1, 2); M(2, 1); } static void M(int x, byte y) { System.Console.Write($""{(x, x) == (y, y)} ""); } }"; var comp = CompileAndVerify(source, expectedOutput: "True False False"); comp.VerifyDiagnostics(); comp.VerifyIL("C.M", @"{ // Code size 38 (0x26) .maxstack 3 .locals init (int V_0, byte V_1, byte V_2) IL_0000: ldstr ""{0} "" IL_0005: ldarg.0 IL_0006: ldarg.0 IL_0007: stloc.0 IL_0008: ldarg.1 IL_0009: stloc.1 IL_000a: ldarg.1 IL_000b: stloc.2 IL_000c: ldloc.1 IL_000d: bne.un.s IL_0015 IL_000f: ldloc.0 IL_0010: ldloc.2 IL_0011: ceq IL_0013: br.s IL_0016 IL_0015: ldc.i4.0 IL_0016: box ""bool"" IL_001b: call ""string string.Format(string, object)"" IL_0020: call ""void System.Console.Write(string)"" IL_0025: ret }"); var tree = comp.Compilation.SyntaxTrees.First(); var model = comp.Compilation.GetSemanticModel(tree); // check x var tupleX = tree.GetCompilationUnitRoot().DescendantNodes().OfType<TupleExpressionSyntax>().First(); Assert.Equal("(x, x)", tupleX.ToString()); Assert.Equal(Conversion.Identity, model.GetConversion(tupleX)); Assert.Null(model.GetSymbolInfo(tupleX).Symbol); var lastX = tupleX.Arguments[1].Expression; Assert.Equal("x", lastX.ToString()); Assert.Equal(Conversion.Identity, model.GetConversion(lastX)); Assert.Equal("System.Int32 x", model.GetSymbolInfo(lastX).Symbol.ToTestDisplayString()); var xSymbol = model.GetTypeInfo(lastX); Assert.Equal("System.Int32", xSymbol.Type.ToTestDisplayString()); Assert.Equal("System.Int32", xSymbol.ConvertedType.ToTestDisplayString()); var tupleXSymbol = model.GetTypeInfo(tupleX); Assert.Equal("(System.Int32, System.Int32)", tupleXSymbol.Type.ToTestDisplayString()); Assert.Equal("(System.Int32, System.Int32)", tupleXSymbol.ConvertedType.ToTestDisplayString()); // check y var tupleY = tree.GetCompilationUnitRoot().DescendantNodes().OfType<TupleExpressionSyntax>().Last(); Assert.Equal("(y, y)", tupleY.ToString()); Assert.Equal(ConversionKind.ImplicitTupleLiteral, model.GetConversion(tupleY).Kind); var lastY = tupleY.Arguments[1].Expression; Assert.Equal("y", lastY.ToString()); Assert.Equal(Conversion.ImplicitNumeric, model.GetConversion(lastY)); var ySymbol = model.GetTypeInfo(lastY); Assert.Equal("System.Byte", ySymbol.Type.ToTestDisplayString()); Assert.Equal("System.Int32", ySymbol.ConvertedType.ToTestDisplayString()); var tupleYSymbol = model.GetTypeInfo(tupleY); Assert.Equal("(System.Byte, System.Byte)", tupleYSymbol.Type.ToTestDisplayString()); Assert.Equal("(System.Int32, System.Int32)", tupleYSymbol.ConvertedType.ToTestDisplayString()); } [Fact] public void TestILForAlwaysValuedNullable() { var source = @" class C { static void Main() { System.Console.Write($""{(new int?(Identity(42)), (int?)2) == (new int?(42), new int?(2))} ""); } static int Identity(int x) => x; }"; var comp = CompileAndVerify(source, expectedOutput: "True"); comp.VerifyDiagnostics(); comp.VerifyIL("C.Main", @"{ // Code size 39 (0x27) .maxstack 3 IL_0000: ldstr ""{0} "" IL_0005: ldc.i4.s 42 IL_0007: call ""int C.Identity(int)"" IL_000c: ldc.i4.s 42 IL_000e: bne.un.s IL_0016 IL_0010: ldc.i4.2 IL_0011: ldc.i4.2 IL_0012: ceq IL_0014: br.s IL_0017 IL_0016: ldc.i4.0 IL_0017: box ""bool"" IL_001c: call ""string string.Format(string, object)"" IL_0021: call ""void System.Console.Write(string)"" IL_0026: ret }"); } [Fact] public void TestILForNullableElementsEqualsToNull() { var source = @" class C { static void Main() { System.Console.Write(M(null, null)); System.Console.Write(M(1, true)); } static bool M(int? i1, bool? b1) { var t1 = (i1, b1); return t1 == (null, null); } }"; var comp = CompileAndVerify(source, expectedOutput: "TrueFalse"); comp.VerifyDiagnostics(); comp.VerifyIL("C.M", @"{ // Code size 40 (0x28) .maxstack 2 .locals init (System.ValueTuple<int?, bool?> V_0) IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: newobj ""System.ValueTuple<int?, bool?>..ctor(int?, bool?)"" IL_0007: stloc.0 IL_0008: ldloca.s V_0 IL_000a: ldflda ""int? System.ValueTuple<int?, bool?>.Item1"" IL_000f: call ""bool int?.HasValue.get"" IL_0014: brtrue.s IL_0026 IL_0016: ldloca.s V_0 IL_0018: ldflda ""bool? System.ValueTuple<int?, bool?>.Item2"" IL_001d: call ""bool bool?.HasValue.get"" IL_0022: ldc.i4.0 IL_0023: ceq IL_0025: ret IL_0026: ldc.i4.0 IL_0027: ret }"); } [Fact] public void TestILForNullableElementsNotEqualsToNull() { var source = @" class C { static void Main() { System.Console.Write(M(null, null)); System.Console.Write(M(1, true)); } static bool M(int? i1, bool? b1) { var t1 = (i1, b1); return t1 != (null, null); } }"; var comp = CompileAndVerify(source, expectedOutput: "FalseTrue"); comp.VerifyDiagnostics(); comp.VerifyIL("C.M", @"{ // Code size 37 (0x25) .maxstack 2 .locals init (System.ValueTuple<int?, bool?> V_0) IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: newobj ""System.ValueTuple<int?, bool?>..ctor(int?, bool?)"" IL_0007: stloc.0 IL_0008: ldloca.s V_0 IL_000a: ldflda ""int? System.ValueTuple<int?, bool?>.Item1"" IL_000f: call ""bool int?.HasValue.get"" IL_0014: brtrue.s IL_0023 IL_0016: ldloca.s V_0 IL_0018: ldflda ""bool? System.ValueTuple<int?, bool?>.Item2"" IL_001d: call ""bool bool?.HasValue.get"" IL_0022: ret IL_0023: ldc.i4.1 IL_0024: ret }"); } [Fact] public void TestILForNullableElementsComparedToNonNullValues() { var source = @" class C { static void Main() { System.Console.Write(M((null, null))); System.Console.Write(M((2, true))); } static bool M((int?, bool?) t1) { return t1 == (2, true); } }"; var comp = CompileAndVerify(source, expectedOutput: "FalseTrue"); comp.VerifyDiagnostics(); comp.VerifyIL("C.M", @"{ // Code size 63 (0x3f) .maxstack 2 .locals init (System.ValueTuple<int?, bool?> V_0, int? V_1, int V_2, bool? V_3, bool V_4) IL_0000: ldarg.0 IL_0001: stloc.0 IL_0002: ldloc.0 IL_0003: ldfld ""int? System.ValueTuple<int?, bool?>.Item1"" IL_0008: stloc.1 IL_0009: ldc.i4.2 IL_000a: stloc.2 IL_000b: ldloca.s V_1 IL_000d: call ""int int?.GetValueOrDefault()"" IL_0012: ldloc.2 IL_0013: ceq IL_0015: ldloca.s V_1 IL_0017: call ""bool int?.HasValue.get"" IL_001c: and IL_001d: brfalse.s IL_003d IL_001f: ldloc.0 IL_0020: ldfld ""bool? System.ValueTuple<int?, bool?>.Item2"" IL_0025: stloc.3 IL_0026: ldc.i4.1 IL_0027: stloc.s V_4 IL_0029: ldloca.s V_3 IL_002b: call ""bool bool?.GetValueOrDefault()"" IL_0030: ldloc.s V_4 IL_0032: ceq IL_0034: ldloca.s V_3 IL_0036: call ""bool bool?.HasValue.get"" IL_003b: and IL_003c: ret IL_003d: ldc.i4.0 IL_003e: ret }"); } [Fact] public void TestILForNullableStructEqualsToNull() { var source = @" struct S { static void Main() { S? s = null; _ = s == null; System.Console.Write((s, null) == (null, s)); } }"; var comp = CompileAndVerify(source, expectedOutput: "True"); comp.VerifyDiagnostics(); comp.VerifyIL("S.Main", @"{ // Code size 48 (0x30) .maxstack 2 .locals init (S? V_0, //s S? V_1, S? V_2) IL_0000: ldloca.s V_0 IL_0002: initobj ""S?"" IL_0008: ldloca.s V_0 IL_000a: call ""bool S?.HasValue.get"" IL_000f: pop IL_0010: ldloc.0 IL_0011: stloc.1 IL_0012: ldloc.0 IL_0013: stloc.2 IL_0014: ldloca.s V_1 IL_0016: call ""bool S?.HasValue.get"" IL_001b: brtrue.s IL_0029 IL_001d: ldloca.s V_2 IL_001f: call ""bool S?.HasValue.get"" IL_0024: ldc.i4.0 IL_0025: ceq IL_0027: br.s IL_002a IL_0029: ldc.i4.0 IL_002a: call ""void System.Console.Write(bool)"" IL_002f: ret }"); } [Fact, WorkItem(25488, "https://github.com/dotnet/roslyn/issues/25488")] public void TestThisStruct() { var source = @" public struct S { public int I; public static void Main() { S s = new S() { I = 1 }; s.M(); } void M() { System.Console.Write((this, 2) == (1, this.Mutate())); } S Mutate() { I++; return this; } public static implicit operator S(int value) { return new S() { I = value }; } public static bool operator==(S s1, S s2) { System.Console.Write($""{s1.I} == {s2.I}, ""); return s1.I == s2.I; } public static bool operator!=(S s1, S s2) { throw null; } public override bool Equals(object o) { throw null; } public override int GetHashCode() { throw null; } }"; var comp = CompileAndVerify(source, expectedOutput: "1 == 1, 2 == 2, True"); comp.VerifyDiagnostics(); } [Fact] public void TestThisClass() { var source = @" public class C { public int I; public static void Main() { C c = new C() { I = 1 }; c.M(); } void M() { System.Console.Write((this, 2) == (2, this.Mutate())); } C Mutate() { I++; return this; } public static implicit operator C(int value) { return new C() { I = value }; } public static bool operator==(C c1, C c2) { System.Console.Write($""{c1.I} == {c2.I}, ""); return c1.I == c2.I; } public static bool operator!=(C c1, C c2) { throw null; } public override bool Equals(object o) { throw null; } public override int GetHashCode() { throw null; } }"; var comp = CompileAndVerify(source, expectedOutput: "2 == 2, 2 == 2, True"); comp.VerifyDiagnostics(); } [Fact] public void TestSimpleEqualOnTypelessTupleLiteral() { var source = @" class C { static bool M((string, long) t) { return t == (null, 1) && t == (""hello"", 1); } }"; var comp = CompileAndVerify(source); comp.VerifyDiagnostics(); var tree = comp.Compilation.SyntaxTrees.First(); var model = comp.Compilation.GetSemanticModel(tree); var tuple1 = tree.GetCompilationUnitRoot().DescendantNodes().OfType<TupleExpressionSyntax>().ElementAt(0); var symbol1 = model.GetTypeInfo(tuple1); Assert.Null(symbol1.Type); Assert.Equal("(System.String, System.Int64)", symbol1.ConvertedType.ToTestDisplayString()); Assert.Equal("(System.String, System.Int64)", model.GetDeclaredSymbol(tuple1).ToTestDisplayString()); var tuple2 = tree.GetCompilationUnitRoot().DescendantNodes().OfType<TupleExpressionSyntax>().ElementAt(1); var symbol2 = model.GetTypeInfo(tuple2); Assert.Equal("(System.String, System.Int32)", symbol2.Type.ToTestDisplayString()); Assert.Equal("(System.String, System.Int64)", symbol2.ConvertedType.ToTestDisplayString()); Assert.False(model.GetConstantValue(tuple2).HasValue); Assert.Equal(1, model.GetConstantValue(tuple2.Arguments[1].Expression).Value); } [Fact] public void TestConversionOnTupleExpression() { var source = @" class C { static bool M((int, byte) t) { return t == (1L, 2); } }"; var comp = CompileAndVerify(source); comp.VerifyDiagnostics(); var tree = comp.Compilation.SyntaxTrees.First(); var model = comp.Compilation.GetSemanticModel(tree); var equals = tree.GetCompilationUnitRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().Single(); // check t var t = equals.Left; Assert.Equal("t", t.ToString()); Assert.Equal("(System.Int32, System.Byte) t", model.GetSymbolInfo(t).Symbol.ToTestDisplayString()); Assert.Equal(ConversionKind.ImplicitTuple, model.GetConversion(t).Kind); var tTypeInfo = model.GetTypeInfo(t); Assert.Equal("(System.Int32, System.Byte)", tTypeInfo.Type.ToTestDisplayString()); Assert.Equal("(System.Int64, System.Int32)", tTypeInfo.ConvertedType.ToTestDisplayString()); // check tuple var tuple = equals.Right; Assert.Equal("(1L, 2)", tuple.ToString()); Assert.Null(model.GetSymbolInfo(tuple).Symbol); Assert.Equal(Conversion.Identity, model.GetConversion(tuple)); var tupleTypeInfo = model.GetTypeInfo(tuple); Assert.Equal("(System.Int64, System.Int32)", tupleTypeInfo.Type.ToTestDisplayString()); Assert.Equal("(System.Int64, System.Int32)", tupleTypeInfo.ConvertedType.ToTestDisplayString()); } [Fact] public void TestOtherOperatorsOnTuples() { var source = @" class C { void M() { var t1 = (1, 2); _ = t1 + t1; // error 1 _ = t1 > t1; // error 2 _ = t1 >= t1; // error 3 _ = !t1; // error 4 } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (7,13): error CS0019: Operator '+' cannot be applied to operands of type '(int, int)' and '(int, int)' // _ = t1 + t1; // error 1 Diagnostic(ErrorCode.ERR_BadBinaryOps, "t1 + t1").WithArguments("+", "(int, int)", "(int, int)").WithLocation(7, 13), // (8,13): error CS0019: Operator '>' cannot be applied to operands of type '(int, int)' and '(int, int)' // _ = t1 > t1; // error 2 Diagnostic(ErrorCode.ERR_BadBinaryOps, "t1 > t1").WithArguments(">", "(int, int)", "(int, int)").WithLocation(8, 13), // (9,13): error CS0019: Operator '>=' cannot be applied to operands of type '(int, int)' and '(int, int)' // _ = t1 >= t1; // error 3 Diagnostic(ErrorCode.ERR_BadBinaryOps, "t1 >= t1").WithArguments(">=", "(int, int)", "(int, int)").WithLocation(9, 13), // (10,13): error CS0023: Operator '!' cannot be applied to operand of type '(int, int)' // _ = !t1; // error 4 Diagnostic(ErrorCode.ERR_BadUnaryOp, "!t1").WithArguments("!", "(int, int)").WithLocation(10, 13) ); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var tuple = tree.GetCompilationUnitRoot().DescendantNodes().OfType<TupleExpressionSyntax>().Single(); Assert.Equal("(System.Int32, System.Int32)", model.GetDeclaredSymbol(tuple).ToTestDisplayString()); } [Fact] public void TestTypelessTuples() { var source = @" class C { static void Main() { string s = null; System.Console.Write((s, null) == (null, s)); } }"; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "True"); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); // check first tuple and its null var tuple1 = tree.GetCompilationUnitRoot().DescendantNodes().OfType<TupleExpressionSyntax>().ElementAt(0); Assert.Equal("(s, null)", tuple1.ToString()); var tupleType1 = model.GetTypeInfo(tuple1); Assert.Null(tupleType1.Type); Assert.Equal("(System.String s, System.String)", tupleType1.ConvertedType.ToTestDisplayString()); var tuple1Null = tuple1.Arguments[1].Expression; var tuple1NullTypeInfo = model.GetTypeInfo(tuple1Null); Assert.Null(tuple1NullTypeInfo.Type); Assert.Equal("System.String", tuple1NullTypeInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.ImplicitReference, model.GetConversion(tuple1Null).Kind); // check second tuple and its null var tuple2 = tree.GetCompilationUnitRoot().DescendantNodes().OfType<TupleExpressionSyntax>().ElementAt(1); Assert.Equal("(null, s)", tuple2.ToString()); var tupleType2 = model.GetTypeInfo(tuple2); Assert.Null(tupleType2.Type); Assert.Equal("(System.String, System.String s)", tupleType2.ConvertedType.ToTestDisplayString()); var tuple2Null = tuple2.Arguments[0].Expression; var tuple2NullTypeInfo = model.GetTypeInfo(tuple2Null); Assert.Null(tuple2NullTypeInfo.Type); Assert.Equal("System.String", tuple2NullTypeInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.ImplicitReference, model.GetConversion(tuple2Null).Kind); } [Fact] public void TestWithNoSideEffectsOrTemps() { var source = @" class C { static void Main() { System.Console.Write((1, 2) == (1, 3)); } }"; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "False"); } [Fact] public void TestSimpleTupleAndTupleType_01() { var source = @" class C { static void Main() { var t1 = (1, 2L); System.Console.Write(t1 == (1L, 2)); } }"; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "True"); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var equals = tree.GetCompilationUnitRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().Single(); // check t1 var t1 = equals.Left; Assert.Equal("t1", t1.ToString()); var t1TypeInfo = model.GetTypeInfo(t1); Assert.Equal("(System.Int32, System.Int64)", t1TypeInfo.Type.ToTestDisplayString()); Assert.Equal("(System.Int64, System.Int64)", t1TypeInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.ImplicitTuple, model.GetConversion(t1).Kind); // check tuple and its literal 2 var tuple = (TupleExpressionSyntax)equals.Right; Assert.Equal("(1L, 2)", tuple.ToString()); var tupleType = model.GetTypeInfo(tuple); Assert.Equal("(System.Int64, System.Int32)", tupleType.Type.ToTestDisplayString()); Assert.Equal("(System.Int64, System.Int64)", tupleType.ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.ImplicitTupleLiteral, model.GetConversion(tuple).Kind); var two = tuple.Arguments[1].Expression; Assert.Equal("2", two.ToString()); var twoType = model.GetTypeInfo(two); Assert.Equal("System.Int32", twoType.Type.ToTestDisplayString()); Assert.Equal("System.Int64", twoType.ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.ImplicitNumeric, model.GetConversion(two).Kind); } [Fact] public void TestSimpleTupleAndTupleType_02() { var source = @" class C { static void Main() { var t1 = (1, 2UL); System.Console.Write(t1 == (1L, 2)); } }"; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "True"); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var equals = tree.GetCompilationUnitRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().Single(); // check t1 var t1 = equals.Left; Assert.Equal("t1", t1.ToString()); var t1TypeInfo = model.GetTypeInfo(t1); Assert.Equal("(System.Int32, System.UInt64)", t1TypeInfo.Type.ToTestDisplayString()); Assert.Equal("(System.Int64, System.UInt64)", t1TypeInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.ImplicitTuple, model.GetConversion(t1).Kind); // check tuple and its literal 2 var tuple = (TupleExpressionSyntax)equals.Right; Assert.Equal("(1L, 2)", tuple.ToString()); var tupleType = model.GetTypeInfo(tuple); Assert.Equal("(System.Int64, System.Int32)", tupleType.Type.ToTestDisplayString()); Assert.Equal("(System.Int64, System.UInt64)", tupleType.ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.ImplicitTupleLiteral, model.GetConversion(tuple).Kind); var two = tuple.Arguments[1].Expression; Assert.Equal("2", two.ToString()); var twoType = model.GetTypeInfo(two); Assert.Equal("System.Int32", twoType.Type.ToTestDisplayString()); Assert.Equal("System.UInt64", twoType.ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.ImplicitConstant, model.GetConversion(two).Kind); } [Fact] public void TestNestedTupleAndTupleType() { var source = @" class C { static void Main() { var t1 = (1, (2L, ""hello"")); var t2 = (2, ""hello""); System.Console.Write(t1 == (1L, t2)); } }"; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "True"); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var equals = tree.GetCompilationUnitRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().Single(); // check t1 var t1 = equals.Left; Assert.Equal("t1", t1.ToString()); var t1TypeInfo = model.GetTypeInfo(t1); Assert.Equal("(System.Int32, (System.Int64, System.String))", t1TypeInfo.Type.ToTestDisplayString()); Assert.Equal("(System.Int64, (System.Int64, System.String))", t1TypeInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.ImplicitTuple, model.GetConversion(t1).Kind); Assert.Equal("(System.Int32, (System.Int64, System.String)) t1", model.GetSymbolInfo(t1).Symbol.ToTestDisplayString()); // check tuple and its t2 var tuple = (TupleExpressionSyntax)equals.Right; Assert.Equal("(1L, t2)", tuple.ToString()); var tupleType = model.GetTypeInfo(tuple); Assert.Equal("(System.Int64, (System.Int32, System.String) t2)", tupleType.Type.ToTestDisplayString()); Assert.Equal("(System.Int64, (System.Int64, System.String) t2)", tupleType.ConvertedType.ToTestDisplayString()); var t2 = tuple.Arguments[1].Expression; Assert.Equal("t2", t2.ToString()); var t2TypeInfo = model.GetTypeInfo(t2); Assert.Equal("(System.Int32, System.String)", t2TypeInfo.Type.ToTestDisplayString()); Assert.Equal("(System.Int64, System.String)", t2TypeInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.ImplicitTuple, model.GetConversion(t2).Kind); Assert.Equal("(System.Int32, System.String) t2", model.GetSymbolInfo(t2).Symbol.ToTestDisplayString()); } [Fact] public void TestTypelessTupleAndTupleType() { var source = @" class C { static void Main() { (string, string) t = (null, null); System.Console.Write(t == (null, null)); System.Console.Write(t != (null, null)); System.Console.Write((1, t) == (1, (null, null))); } }"; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "TrueFalseTrue"); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var tuple = tree.GetCompilationUnitRoot().DescendantNodes().OfType<TupleExpressionSyntax>().ElementAt(1); Assert.Equal("(null, null)", tuple.ToString()); var tupleType = model.GetTypeInfo(tuple); Assert.Null(tupleType.Type); Assert.Equal("(System.String, System.String)", tupleType.ConvertedType.ToTestDisplayString()); // check last tuple ... var lastEquals = tree.GetCompilationUnitRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().Last(); var lastTuple = (TupleExpressionSyntax)lastEquals.Right; Assert.Equal("(1, (null, null))", lastTuple.ToString()); TypeInfo lastTupleTypeInfo = model.GetTypeInfo(lastTuple); Assert.Null(lastTupleTypeInfo.Type); Assert.Equal("(System.Int32, (System.String, System.String))", lastTupleTypeInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.ImplicitTupleLiteral, model.GetConversion(lastTuple).Kind); // ... and its nested (null, null) tuple ... var nullNull = (TupleExpressionSyntax)lastTuple.Arguments[1].Expression; TypeInfo nullNullTypeInfo = model.GetTypeInfo(nullNull); Assert.Null(nullNullTypeInfo.Type); Assert.Equal("(System.String, System.String)", nullNullTypeInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.ImplicitTupleLiteral, model.GetConversion(nullNull).Kind); // ... and its last null. var lastNull = nullNull.Arguments[1].Expression; TypeInfo lastNullTypeInfo = model.GetTypeInfo(lastNull); Assert.Null(lastNullTypeInfo.Type); Assert.Equal("System.String", lastNullTypeInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.ImplicitReference, model.GetConversion(lastNull).Kind); } [Fact] public void TestTypedTupleAndDefault() { var source = @" class C { static void Main() { (string, string) t = (null, null); System.Console.Write(t == default); System.Console.Write(t != default); (string, string) t2 = (null, ""hello""); System.Console.Write(t2 == default); System.Console.Write(t2 != default); } }"; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "TrueFalseFalseTrue"); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var defaultLiterals = tree.GetCompilationUnitRoot().DescendantNodes().OfType<LiteralExpressionSyntax>() .Where(e => e.Kind() == SyntaxKind.DefaultLiteralExpression); foreach (var literal in defaultLiterals) { Assert.Equal("default", literal.ToString()); var info = model.GetTypeInfo(literal); Assert.Equal("(System.String, System.String)", info.Type.ToTestDisplayString()); Assert.Equal("(System.String, System.String)", info.ConvertedType.ToTestDisplayString()); } } [Fact] public void TestNullableTupleAndDefault() { var source = @" class C { static void Main() { (string, string)? t = (null, null); System.Console.Write(t == default); System.Console.Write(t != default); System.Console.Write(default == t); System.Console.Write(default != t); } }"; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "FalseTrueFalseTrue"); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var defaultLiterals = tree.GetCompilationUnitRoot().DescendantNodes().OfType<LiteralExpressionSyntax>() .Where(e => e.Kind() == SyntaxKind.DefaultLiteralExpression); foreach (var literal in defaultLiterals) { Assert.Equal("default", literal.ToString()); var info = model.GetTypeInfo(literal); Assert.Equal("(System.String, System.String)?", info.Type.ToTestDisplayString()); Assert.Equal("(System.String, System.String)?", info.ConvertedType.ToTestDisplayString()); } } [Fact] public void TestNullableTupleAndDefault_Nested() { var source = @" class C { static void Main() { (string, string)? t = (null, null); System.Console.Write((null, t) == (null, default)); System.Console.Write((t, null) != (default, null)); } }"; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "FalseTrue"); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var defaultLiterals = tree.GetCompilationUnitRoot().DescendantNodes().OfType<LiteralExpressionSyntax>() .Where(e => e.Kind() == SyntaxKind.DefaultLiteralExpression); foreach (var literal in defaultLiterals) { Assert.Equal("default", literal.ToString()); var info = model.GetTypeInfo(literal); Assert.Equal("(System.String, System.String)?", info.Type.ToTestDisplayString()); Assert.Equal("(System.String, System.String)?", info.ConvertedType.ToTestDisplayString()); } } [Fact] public void TestNestedDefaultWithNonTupleType() { var source = @" class C { static void Main() { System.Console.Write((null, 1) == (null, default)); System.Console.Write((0, null) != (default, null)); } }"; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "FalseFalse"); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var defaultLiterals = tree.GetCompilationUnitRoot().DescendantNodes().OfType<LiteralExpressionSyntax>() .Where(e => e.Kind() == SyntaxKind.DefaultLiteralExpression); foreach (var literal in defaultLiterals) { Assert.Equal("default", literal.ToString()); var info = model.GetTypeInfo(literal); Assert.Equal("System.Int32", info.Type.ToTestDisplayString()); Assert.Equal("System.Int32", info.ConvertedType.ToTestDisplayString()); } } [Fact] public void TestNestedDefaultWithNullableNonTupleType() { var source = @" struct S { static void Main() { S? ns = null; _ = (null, ns) == (null, default); _ = (ns, null) != (default, null); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (7,13): error CS0019: Operator '==' cannot be applied to operands of type 'S?' and 'default' // _ = (null, ns) == (null, default); Diagnostic(ErrorCode.ERR_BadBinaryOps, "(null, ns) == (null, default)").WithArguments("==", "S?", "default").WithLocation(7, 13), // (8,13): error CS0019: Operator '!=' cannot be applied to operands of type 'S?' and 'default' // _ = (ns, null) != (default, null); Diagnostic(ErrorCode.ERR_BadBinaryOps, "(ns, null) != (default, null)").WithArguments("!=", "S?", "default").WithLocation(8, 13) ); } [Fact] public void TestNestedDefaultWithNullableNonTupleType_WithComparisonOperator() { var source = @" public struct S { public static void Main() { S? ns = new S(); System.Console.Write((null, ns) == (null, default)); System.Console.Write((ns, null) != (default, null)); } public static bool operator==(S s1, S s2) => throw null; public static bool operator!=(S s1, S s2) => throw null; public override int GetHashCode() => throw null; public override bool Equals(object o) => throw null; }"; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "FalseTrue"); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var defaults = tree.GetCompilationUnitRoot().DescendantNodes().OfType<LiteralExpressionSyntax>() .Where(e => e.Kind() == SyntaxKind.DefaultLiteralExpression); foreach (var literal in defaults) { var type = model.GetTypeInfo(literal); Assert.Equal("S?", type.Type.ToTestDisplayString()); Assert.Equal("S?", type.ConvertedType.ToTestDisplayString()); } } [Fact] public void TestAllDefaults() { var source = @" class C { static void Main() { System.Console.Write((default, default) == (default, default)); System.Console.Write(default == (default, default)); } }"; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics( // (6,30): error CS8315: Operator '==' is ambiguous on operands 'default' and 'default' // System.Console.Write((default, default) == (default, default)); Diagnostic(ErrorCode.ERR_AmbigBinaryOpsOnDefault, "(default, default) == (default, default)").WithArguments("==", "default", "default").WithLocation(6, 30), // (6,30): error CS8315: Operator '==' is ambiguous on operands 'default' and 'default' // System.Console.Write((default, default) == (default, default)); Diagnostic(ErrorCode.ERR_AmbigBinaryOpsOnDefault, "(default, default) == (default, default)").WithArguments("==", "default", "default").WithLocation(6, 30), // (7,30): error CS0034: Operator '==' is ambiguous on operands of type 'default' and '(default, default)' // System.Console.Write(default == (default, default)); Diagnostic(ErrorCode.ERR_AmbigBinaryOps, "default == (default, default)").WithArguments("==", "default", "(default, default)").WithLocation(7, 30) ); } [Fact] public void TestNullsAndDefaults() { var source = @" class C { static void Main() { _ = (null, default) != (default, null); } }"; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics( // (6,13): error CS0034: Operator '!=' is ambiguous on operands of type '<null>' and 'default' // _ = (null, default) != (default, null); Diagnostic(ErrorCode.ERR_AmbigBinaryOps, "(null, default) != (default, null)").WithArguments("!=", "<null>", "default").WithLocation(6, 13), // (6,13): error CS0034: Operator '!=' is ambiguous on operands of type 'default' and '<null>' // _ = (null, default) != (default, null); Diagnostic(ErrorCode.ERR_AmbigBinaryOps, "(null, default) != (default, null)").WithArguments("!=", "default", "<null>").WithLocation(6, 13) ); } [Fact] public void TestAllDefaults_Nested() { var source = @" class C { static void Main() { System.Console.Write((null, (default, default)) == (null, (default, default))); } }"; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics( // (6,30): error CS8315: Operator '==' is ambiguous on operands 'default' and 'default' // System.Console.Write((null, (default, default)) == (null, (default, default))); Diagnostic(ErrorCode.ERR_AmbigBinaryOpsOnDefault, "(null, (default, default)) == (null, (default, default))").WithArguments("==", "default", "default").WithLocation(6, 30), // (6,30): error CS8315: Operator '==' is ambiguous on operands 'default' and 'default' // System.Console.Write((null, (default, default)) == (null, (default, default))); Diagnostic(ErrorCode.ERR_AmbigBinaryOpsOnDefault, "(null, (default, default)) == (null, (default, default))").WithArguments("==", "default", "default").WithLocation(6, 30) ); } [Fact] public void TestTypedTupleAndTupleOfDefaults() { var source = @" class C { static void Main() { (string, string)? t = (null, null); System.Console.Write(t == (default, default)); System.Console.Write(t != (default, default)); } }"; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "TrueFalse"); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var lastTuple = tree.GetCompilationUnitRoot().DescendantNodes().OfType<TupleExpressionSyntax>().Last(); Assert.Equal("(default, default)", lastTuple.ToString()); Assert.Null(model.GetTypeInfo(lastTuple).Type); Assert.Equal("(System.String, System.String)?", model.GetTypeInfo(lastTuple).ConvertedType.ToTestDisplayString()); var lastDefault = lastTuple.Arguments[1].Expression; Assert.Equal("default", lastDefault.ToString()); Assert.Equal("System.String", model.GetTypeInfo(lastDefault).Type.ToTestDisplayString()); Assert.Equal("System.String", model.GetTypeInfo(lastDefault).ConvertedType.ToTestDisplayString()); } [Fact] public void TestTypelessTupleAndTupleOfDefaults() { var source = @" class C { static void Main() { System.Console.Write((null, () => 1) == (default, default)); System.Console.Write((null, () => 2) == default); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (6,30): error CS0034: Operator '==' is ambiguous on operands of type '<null>' and 'default' // System.Console.Write((null, () => 1) == (default, default)); Diagnostic(ErrorCode.ERR_AmbigBinaryOps, "(null, () => 1) == (default, default)").WithArguments("==", "<null>", "default").WithLocation(6, 30), // (6,37): error CS8773: Feature 'inferred delegate type' is not available in C# 9.0. Please use language version 10.0 or greater. // System.Console.Write((null, () => 1) == (default, default)); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "() => 1").WithArguments("inferred delegate type", "10.0").WithLocation(6, 37), // (6,37): error CS8773: Feature 'inferred delegate type' is not available in C# 9.0. Please use language version 10.0 or greater. // System.Console.Write((null, () => 1) == (default, default)); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "() => 1").WithArguments("inferred delegate type", "10.0").WithLocation(6, 37), // (7,30): error CS0034: Operator '==' is ambiguous on operands of type '(<null>, lambda expression)' and 'default' // System.Console.Write((null, () => 2) == default); Diagnostic(ErrorCode.ERR_AmbigBinaryOps, "(null, () => 2) == default").WithArguments("==", "(<null>, lambda expression)", "default").WithLocation(7, 30) ); comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,30): error CS0034: Operator '==' is ambiguous on operands of type '<null>' and 'default' // System.Console.Write((null, () => 1) == (default, default)); Diagnostic(ErrorCode.ERR_AmbigBinaryOps, "(null, () => 1) == (default, default)").WithArguments("==", "<null>", "default").WithLocation(6, 30), // (7,30): error CS0034: Operator '==' is ambiguous on operands of type '(<null>, lambda expression)' and 'default' // System.Console.Write((null, () => 2) == default); Diagnostic(ErrorCode.ERR_AmbigBinaryOps, "(null, () => 2) == default").WithArguments("==", "(<null>, lambda expression)", "default").WithLocation(7, 30) ); } [Fact] public void TestNullableStructAndDefault() { var source = @" struct S { static void M(string s) { S? ns = new S(); _ = ns == null; _ = s == null; _ = ns == default; // error 1 _ = (ns, ns) == (null, null); _ = (ns, ns) == (default, default); // errors 2 and 3 _ = (ns, ns) == default; // error 4 } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (9,13): error CS0019: Operator '==' cannot be applied to operands of type 'S?' and 'default' // _ = ns == default; // error 1 Diagnostic(ErrorCode.ERR_BadBinaryOps, "ns == default").WithArguments("==", "S?", "default").WithLocation(9, 13), // (11,13): error CS0019: Operator '==' cannot be applied to operands of type 'S?' and 'default' // _ = (ns, ns) == (default, default); // errors 2 and 3 Diagnostic(ErrorCode.ERR_BadBinaryOps, "(ns, ns) == (default, default)").WithArguments("==", "S?", "default").WithLocation(11, 13), // (11,13): error CS0019: Operator '==' cannot be applied to operands of type 'S?' and 'default' // _ = (ns, ns) == (default, default); // errors 2 and 3 Diagnostic(ErrorCode.ERR_BadBinaryOps, "(ns, ns) == (default, default)").WithArguments("==", "S?", "default").WithLocation(11, 13), // (12,13): error CS0019: Operator '==' cannot be applied to operands of type 'S?' and 'S?' // _ = (ns, ns) == default; // error 4 Diagnostic(ErrorCode.ERR_BadBinaryOps, "(ns, ns) == default").WithArguments("==", "S?", "S?").WithLocation(12, 13), // (12,13): error CS0019: Operator '==' cannot be applied to operands of type 'S?' and 'S?' // _ = (ns, ns) == default; // error 4 Diagnostic(ErrorCode.ERR_BadBinaryOps, "(ns, ns) == default").WithArguments("==", "S?", "S?").WithLocation(12, 13) ); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var literals = tree.GetCompilationUnitRoot().DescendantNodes().OfType<LiteralExpressionSyntax>(); var nullLiteral = literals.ElementAt(0); Assert.Equal("null", nullLiteral.ToString()); Assert.Null(model.GetTypeInfo(nullLiteral).ConvertedType); var nullLiteral2 = literals.ElementAt(1); Assert.Equal("null", nullLiteral2.ToString()); Assert.Null(model.GetTypeInfo(nullLiteral2).Type); Assert.Equal("System.String", model.GetTypeInfo(nullLiteral2).ConvertedType.ToTestDisplayString()); var defaultLiterals = tree.GetCompilationUnitRoot().DescendantNodes().OfType<LiteralExpressionSyntax>() .Where(e => e.Kind() == SyntaxKind.DelegateDeclaration); foreach (var defaultLiteral in defaultLiterals) { Assert.Equal("default", defaultLiteral.ToString()); Assert.Null(model.GetTypeInfo(defaultLiteral).Type); Assert.Null(model.GetTypeInfo(defaultLiteral).ConvertedType); } } [Fact, WorkItem(25318, "https://github.com/dotnet/roslyn/issues/25318")] public void TestNullableStructAndDefault_WithComparisonOperator() { var source = @" public struct S { static void M(string s) { S? ns = new S(); _ = ns == 1; _ = (ns, ns) == (default, default); _ = (ns, ns) == default; } public static bool operator==(S s, byte b) => throw null; public static bool operator!=(S s, byte b) => throw null; public override bool Equals(object other) => throw null; public override int GetHashCode() => throw null; }"; var comp = CreateCompilation(source); // https://github.com/dotnet/roslyn/issues/25318 // This should be allowed comp.VerifyDiagnostics( // (7,13): error CS0019: Operator '==' cannot be applied to operands of type 'S?' and 'int' // _ = ns == 1; Diagnostic(ErrorCode.ERR_BadBinaryOps, "ns == 1").WithArguments("==", "S?", "int").WithLocation(7, 13), // (8,13): error CS0019: Operator '==' cannot be applied to operands of type 'S?' and 'default' // _ = (ns, ns) == (default, default); Diagnostic(ErrorCode.ERR_BadBinaryOps, "(ns, ns) == (default, default)").WithArguments("==", "S?", "default").WithLocation(8, 13), // (8,13): error CS0019: Operator '==' cannot be applied to operands of type 'S?' and 'default' // _ = (ns, ns) == (default, default); Diagnostic(ErrorCode.ERR_BadBinaryOps, "(ns, ns) == (default, default)").WithArguments("==", "S?", "default").WithLocation(8, 13), // (9,13): error CS0019: Operator '==' cannot be applied to operands of type 'S?' and 'S?' // _ = (ns, ns) == default; Diagnostic(ErrorCode.ERR_BadBinaryOps, "(ns, ns) == default").WithArguments("==", "S?", "S?").WithLocation(9, 13), // (9,13): error CS0019: Operator '==' cannot be applied to operands of type 'S?' and 'S?' // _ = (ns, ns) == default; Diagnostic(ErrorCode.ERR_BadBinaryOps, "(ns, ns) == default").WithArguments("==", "S?", "S?").WithLocation(9, 13) ); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var defaultLiterals = tree.GetCompilationUnitRoot().DescendantNodes().OfType<LiteralExpressionSyntax>() .Where(e => e.Kind() == SyntaxKind.DelegateDeclaration); // Should have types foreach (var defaultLiteral in defaultLiterals) { Assert.Equal("default", defaultLiteral.ToString()); Assert.Null(model.GetTypeInfo(defaultLiteral).Type); Assert.Null(model.GetTypeInfo(defaultLiteral).ConvertedType); // https://github.com/dotnet/roslyn/issues/25318 // default should become int } } [Fact] public void TestMixedTupleLiteralsAndTypes() { var source = @" class C { static void Main() { (string, string) t = (null, null); System.Console.Write((t, (null, null)) == ((null, null), t)); } }"; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "True"); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); // check last tuple ... var tuple = tree.GetCompilationUnitRoot().DescendantNodes().OfType<TupleExpressionSyntax>().ElementAt(3); Assert.Equal("((null, null), t)", tuple.ToString()); var tupleType = model.GetTypeInfo(tuple); Assert.Null(tupleType.Type); Assert.Equal("((System.String, System.String), (System.String, System.String) t)", tupleType.ConvertedType.ToTestDisplayString()); // ... its t ... var t = tuple.Arguments[1].Expression; Assert.Equal("t", t.ToString()); var tType = model.GetTypeInfo(t); Assert.Equal("(System.String, System.String)", tType.Type.ToTestDisplayString()); Assert.Equal("(System.String, System.String)", tType.ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.Identity, model.GetConversion(t).Kind); Assert.Equal("(System.String, System.String) t", model.GetSymbolInfo(t).Symbol.ToTestDisplayString()); Assert.Null(model.GetDeclaredSymbol(t)); // ... its nested tuple ... var nestedTuple = (TupleExpressionSyntax)tuple.Arguments[0].Expression; Assert.Equal("(null, null)", nestedTuple.ToString()); var nestedTupleType = model.GetTypeInfo(nestedTuple); Assert.Null(nestedTupleType.Type); Assert.Equal("(System.String, System.String)", nestedTupleType.ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.ImplicitTupleLiteral, model.GetConversion(nestedTuple).Kind); Assert.Null(model.GetSymbolInfo(nestedTuple).Symbol); Assert.Equal("(System.String, System.String)", model.GetDeclaredSymbol(nestedTuple).ToTestDisplayString()); // ... a nested null. var nestedNull = nestedTuple.Arguments[0].Expression; Assert.Equal("null", nestedNull.ToString()); var nestedNullType = model.GetTypeInfo(nestedNull); Assert.Null(nestedNullType.Type); Assert.Equal("System.String", nestedNullType.ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.ImplicitReference, model.GetConversion(nestedNull).Kind); } [Fact] public void TestAllNulls() { var source = @" class C { static void Main() { System.Console.Write(null == null); System.Console.Write((null, null) == (null, null)); System.Console.Write((null, null) != (null, null)); } }"; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "TrueTrueFalse"); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var nulls = tree.GetCompilationUnitRoot().DescendantNodes().OfType<LiteralExpressionSyntax>(); foreach (var literal in nulls) { Assert.Equal("null", literal.ToString()); var symbol = model.GetTypeInfo(literal); Assert.Null(symbol.Type); Assert.Null(symbol.ConvertedType); } var tuples = tree.GetCompilationUnitRoot().DescendantNodes().OfType<TupleExpressionSyntax>(); foreach (var tuple in tuples) { Assert.Equal("(null, null)", tuple.ToString()); var symbol = model.GetTypeInfo(tuple); Assert.Null(symbol.Type); Assert.Null(symbol.ConvertedType); } } [Fact] public void TestConvertedElementInTypelessTuple() { var source = @" class C { static void Main() { System.Console.Write((null, 1L) == (null, 2)); } }"; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "False"); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var lastLiteral = tree.GetCompilationUnitRoot().DescendantNodes().OfType<LiteralExpressionSyntax>().Last(); Assert.Equal("2", lastLiteral.ToString()); var literalInfo = model.GetTypeInfo(lastLiteral); Assert.Equal("System.Int32", literalInfo.Type.ToTestDisplayString()); Assert.Equal("System.Int64", literalInfo.ConvertedType.ToTestDisplayString()); } [Fact] public void TestConvertedElementInTypelessTuple_Nested() { var source = @" class C { static void Main() { System.Console.Write(((null, 1L), null) == ((null, 2), null)); } }"; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "False"); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var rightTuple = tree.GetCompilationUnitRoot().DescendantNodes().OfType<TupleExpressionSyntax>().ElementAt(2); Assert.Equal("((null, 2), null)", rightTuple.ToString()); var literalInfo = model.GetTypeInfo(rightTuple); Assert.Null(literalInfo.Type); Assert.Null(literalInfo.ConvertedType); var nestedTuple = (TupleExpressionSyntax)rightTuple.Arguments[0].Expression; Assert.Equal("(null, 2)", nestedTuple.ToString()); var nestedLiteralInfo = model.GetTypeInfo(rightTuple); Assert.Null(nestedLiteralInfo.Type); Assert.Null(nestedLiteralInfo.ConvertedType); var two = nestedTuple.Arguments[1].Expression; Assert.Equal("2", two.ToString()); var twoInfo = model.GetTypeInfo(two); Assert.Equal("System.Int32", twoInfo.Type.ToTestDisplayString()); Assert.Equal("System.Int64", twoInfo.ConvertedType.ToTestDisplayString()); } [Fact] public void TestFailedInference() { var source = @" class C { static void Main() { System.Console.Write((null, null, null, null) == (null, x => x, Main, (int i) => { int j = 0; return i + j; })); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (6,65): error CS8773: Feature 'inferred delegate type' is not available in C# 9.0. Please use language version 10.0 or greater. // System.Console.Write((null, null, null, null) == (null, x => x, Main, (int i) => { int j = 0; return i + j; })); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "x => x").WithArguments("inferred delegate type", "10.0").WithLocation(6, 65), // (6,65): error CS8917: The delegate type could not be inferred. // System.Console.Write((null, null, null, null) == (null, x => x, Main, (int i) => { int j = 0; return i + j; })); Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "x => x").WithLocation(6, 65), // (6,65): error CS8773: Feature 'inferred delegate type' is not available in C# 9.0. Please use language version 10.0 or greater. // System.Console.Write((null, null, null, null) == (null, x => x, Main, (int i) => { int j = 0; return i + j; })); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "x => x").WithArguments("inferred delegate type", "10.0").WithLocation(6, 65), // (6,65): error CS8917: The delegate type could not be inferred. // System.Console.Write((null, null, null, null) == (null, x => x, Main, (int i) => { int j = 0; return i + j; })); Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "x => x").WithLocation(6, 65), // (6,73): error CS8773: Feature 'inferred delegate type' is not available in C# 9.0. Please use language version 10.0 or greater. // System.Console.Write((null, null, null, null) == (null, x => x, Main, (int i) => { int j = 0; return i + j; })); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "Main").WithArguments("inferred delegate type", "10.0").WithLocation(6, 73), // (6,73): error CS8773: Feature 'inferred delegate type' is not available in C# 9.0. Please use language version 10.0 or greater. // System.Console.Write((null, null, null, null) == (null, x => x, Main, (int i) => { int j = 0; return i + j; })); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "Main").WithArguments("inferred delegate type", "10.0").WithLocation(6, 73), // (6,79): error CS8773: Feature 'inferred delegate type' is not available in C# 9.0. Please use language version 10.0 or greater. // System.Console.Write((null, null, null, null) == (null, x => x, Main, (int i) => { int j = 0; return i + j; })); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "(int i) => { int j = 0; return i + j; }").WithArguments("inferred delegate type", "10.0").WithLocation(6, 79), // (6,79): error CS8773: Feature 'inferred delegate type' is not available in C# 9.0. Please use language version 10.0 or greater. // System.Console.Write((null, null, null, null) == (null, x => x, Main, (int i) => { int j = 0; return i + j; })); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "(int i) => { int j = 0; return i + j; }").WithArguments("inferred delegate type", "10.0").WithLocation(6, 79)); verify(comp); comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (6,65): error CS8917: The delegate type could not be inferred. // System.Console.Write((null, null, null, null) == (null, x => x, Main, (int i) => { int j = 0; return i + j; })); Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "x => x").WithLocation(6, 65), // (6,65): error CS8917: The delegate type could not be inferred. // System.Console.Write((null, null, null, null) == (null, x => x, Main, (int i) => { int j = 0; return i + j; })); Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "x => x").WithLocation(6, 65)); verify(comp); static void verify(CSharpCompilation comp) { var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); // check tuple on the left var tuple1 = tree.GetCompilationUnitRoot().DescendantNodes().OfType<TupleExpressionSyntax>().ElementAt(0); Assert.Equal("(null, null, null, null)", tuple1.ToString()); var tupleType1 = model.GetTypeInfo(tuple1); Assert.Null(tupleType1.Type); Assert.Null(tupleType1.ConvertedType); // check tuple on the right ... var tuple2 = tree.GetCompilationUnitRoot().DescendantNodes().OfType<TupleExpressionSyntax>().ElementAt(1); Assert.Equal("(null, x => x, Main, (int i) => { int j = 0; return i + j; })", tuple2.ToString()); var tupleType2 = model.GetTypeInfo(tuple2); Assert.Null(tupleType2.Type); Assert.Null(tupleType2.ConvertedType); // ... its first lambda ... var firstLambda = tuple2.Arguments[1].Expression; Assert.Null(model.GetTypeInfo(firstLambda).Type); Assert.Equal("System.Delegate", model.GetTypeInfo(firstLambda).ConvertedType.ToTestDisplayString()); // ... its method group ... var methodGroup = tuple2.Arguments[2].Expression; Assert.Null(model.GetTypeInfo(methodGroup).Type); Assert.Equal("System.Delegate", model.GetTypeInfo(methodGroup).ConvertedType.ToTestDisplayString()); Assert.Null(model.GetSymbolInfo(methodGroup).Symbol); Assert.Equal(new[] { "void C.Main()" }, model.GetSymbolInfo(methodGroup).CandidateSymbols.Select(s => s.ToTestDisplayString())); // ... its second lambda and the symbols it uses var secondLambda = tuple2.Arguments[3].Expression; Assert.Equal("System.Func<System.Int32, System.Int32>", model.GetTypeInfo(secondLambda).Type.ToTestDisplayString()); Assert.Equal("System.Delegate", model.GetTypeInfo(secondLambda).ConvertedType.ToTestDisplayString()); var addition = tree.GetCompilationUnitRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().Last(); Assert.Equal("i + j", addition.ToString()); var i = addition.Left; Assert.Equal("System.Int32 i", model.GetSymbolInfo(i).Symbol.ToTestDisplayString()); var j = addition.Right; Assert.Equal("System.Int32 j", model.GetSymbolInfo(j).Symbol.ToTestDisplayString()); } } [Fact] public void TestVoidTypeElement() { var source = @" class C { static void Main() { System.Console.Write((Main(), null) != (null, Main())); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,31): error CS8210: A tuple may not contain a value of type 'void'. // System.Console.Write((Main(), null) != (null, Main())); Diagnostic(ErrorCode.ERR_VoidInTuple, "Main()").WithLocation(6, 31), // (6,55): error CS8210: A tuple may not contain a value of type 'void'. // System.Console.Write((Main(), null) != (null, Main())); Diagnostic(ErrorCode.ERR_VoidInTuple, "Main()").WithLocation(6, 55) ); } [Fact] public void TestFailedConversion() { var source = @" class C { static void M(string s) { System.Console.Write((s, s) == (1, () => { })); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,30): error CS0019: Operator '==' cannot be applied to operands of type 'string' and 'int' // System.Console.Write((s, s) == (1, () => { })); Diagnostic(ErrorCode.ERR_BadBinaryOps, "(s, s) == (1, () => { })").WithArguments("==", "string", "int").WithLocation(6, 30), // (6,30): error CS0019: Operator '==' cannot be applied to operands of type 'string' and 'lambda expression' // System.Console.Write((s, s) == (1, () => { })); Diagnostic(ErrorCode.ERR_BadBinaryOps, "(s, s) == (1, () => { })").WithArguments("==", "string", "lambda expression").WithLocation(6, 30) ); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var tuple1 = tree.GetCompilationUnitRoot().DescendantNodes().OfType<TupleExpressionSyntax>().ElementAt(0); Assert.Equal("(s, s)", tuple1.ToString()); var tupleType1 = model.GetTypeInfo(tuple1); Assert.Equal("(System.String, System.String)", tupleType1.Type.ToTestDisplayString()); Assert.Equal("(System.String, System.String)", tupleType1.ConvertedType.ToTestDisplayString()); var tuple2 = tree.GetCompilationUnitRoot().DescendantNodes().OfType<TupleExpressionSyntax>().ElementAt(1); Assert.Equal("(1, () => { })", tuple2.ToString()); var tupleType2 = model.GetTypeInfo(tuple2); Assert.Null(tupleType2.Type); Assert.Null(tupleType2.ConvertedType); } [Fact] public void TestDynamic() { var source = @" public class C { public static void Main() { dynamic d1 = 1; dynamic d2 = 2; System.Console.Write($""{(d1, 2) == (1, d2)} ""); System.Console.Write($""{(d1, 2) != (1, d2)} ""); System.Console.Write($""{(d1, 20) == (10, d2)} ""); System.Console.Write($""{(d1, 20) != (10, d2)} ""); } }"; var comp = CreateCompilation(source, targetFramework: TargetFramework.StandardAndCSharp, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "True False False True"); } [Fact] public void TestDynamicWithConstants() { var source = @" public class C { public static void Main() { System.Console.Write($""{((dynamic)true, (dynamic)false) == ((dynamic)true, (dynamic)false)} ""); } }"; var comp = CreateCompilation(source, targetFramework: TargetFramework.StandardAndCSharp, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "True"); } [Fact] public void TestDynamic_WithTypelessExpression() { var source = @" public class C { public static void Main() { dynamic d1 = 1; dynamic d2 = 2; System.Console.Write((d1, 2) == (() => 1, d2)); } }"; var comp = CreateCompilation(source, targetFramework: TargetFramework.StandardAndCSharp, options: TestOptions.DebugExe); comp.VerifyDiagnostics( // (8,30): error CS0019: Operator '==' cannot be applied to operands of type 'dynamic' and 'lambda expression' // System.Console.Write((d1, 2) == (() => 1, d2)); Diagnostic(ErrorCode.ERR_BadBinaryOps, "(d1, 2) == (() => 1, d2)").WithArguments("==", "dynamic", "lambda expression").WithLocation(8, 30) ); } [Fact] public void TestDynamic_WithBooleanConstants() { var source = @" public class C { public static void Main() { System.Console.Write(((dynamic)true, (dynamic)false) == (true, false)); System.Console.Write(((dynamic)true, (dynamic)false) != (true, false)); } }"; var comp = CreateCompilation(source, targetFramework: TargetFramework.StandardAndCSharp, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "TrueFalse"); } [Fact] public void TestDynamic_WithBadType() { var source = @" public class C { public static void Main() { System.Globalization.CultureInfo saveUICulture = System.Threading.Thread.CurrentThread.CurrentUICulture; System.Threading.Thread.CurrentThread.CurrentUICulture = System.Globalization.CultureInfo.InvariantCulture; dynamic d1 = 1; dynamic d2 = 2; try { bool b = ((d1, 2) == (""hello"", d2)); } catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e) { System.Console.Write(e.Message); } finally { System.Threading.Thread.CurrentThread.CurrentUICulture = saveUICulture; } } }"; var comp = CreateCompilation(source, targetFramework: TargetFramework.StandardAndCSharp, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "Operator '==' cannot be applied to operands of type 'int' and 'string'"); } [Fact] public void TestDynamic_WithNull() { var source = @" public class C { public static void Main() { dynamic d1 = null; dynamic d2 = null; System.Console.Write((d1, null) == (null, d2)); } }"; var comp = CreateCompilation(source, targetFramework: TargetFramework.StandardAndCSharp, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "True"); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var tuple1 = tree.GetCompilationUnitRoot().DescendantNodes().OfType<TupleExpressionSyntax>().ElementAt(0); Assert.Equal("(d1, null)", tuple1.ToString()); var tupleType1 = model.GetTypeInfo(tuple1); Assert.Null(tupleType1.Type); Assert.Equal("(dynamic d1, dynamic)", tupleType1.ConvertedType.ToTestDisplayString()); var tuple2 = tree.GetCompilationUnitRoot().DescendantNodes().OfType<TupleExpressionSyntax>().ElementAt(1); Assert.Equal("(null, d2)", tuple2.ToString()); var tupleType2 = model.GetTypeInfo(tuple2); Assert.Null(tupleType2.Type); Assert.Equal("(dynamic, dynamic d2)", tupleType2.ConvertedType.ToTestDisplayString()); } [Fact] public void TestBadConstraintOnTuple() { // https://github.com/dotnet/roslyn/issues/37121 : This test appears to produce a duplicate diagnostic at (6, 35) var source = @" ref struct S { void M(S s1, S s2) { System.Console.Write(("""", s1) == (null, s2)); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,35): error CS0306: The type 'S' may not be used as a type argument // System.Console.Write(("", s1) == (null, s2)); Diagnostic(ErrorCode.ERR_BadTypeArgument, "s1").WithArguments("S").WithLocation(6, 35), // (6,30): error CS0019: Operator '==' cannot be applied to operands of type 'S' and 'S' // System.Console.Write(("", s1) == (null, s2)); Diagnostic(ErrorCode.ERR_BadBinaryOps, @"("""", s1) == (null, s2)").WithArguments("==", "S", "S").WithLocation(6, 30), // (6,35): error CS0306: The type 'S' may not be used as a type argument // System.Console.Write(("", s1) == (null, s2)); Diagnostic(ErrorCode.ERR_BadTypeArgument, "s1").WithArguments("S").WithLocation(6, 35), // (6,49): error CS0306: The type 'S' may not be used as a type argument // System.Console.Write(("", s1) == (null, s2)); Diagnostic(ErrorCode.ERR_BadTypeArgument, "s2").WithArguments("S").WithLocation(6, 49) ); } [Fact] public void TestErrorInTuple() { var source = @" public class C { public void M() { if (error1 == (error2, 3)) { } } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,13): error CS0103: The name 'error1' does not exist in the current context // if (error1 == (error2, 3)) { } Diagnostic(ErrorCode.ERR_NameNotInContext, "error1").WithArguments("error1").WithLocation(6, 13), // (6,24): error CS0103: The name 'error2' does not exist in the current context // if (error1 == (error2, 3)) { } Diagnostic(ErrorCode.ERR_NameNotInContext, "error2").WithArguments("error2").WithLocation(6, 24) ); } [Fact] public void TestWithTypelessTuple() { var source = @" public class C { public void M() { var t = (null, null); if (null == (() => {}) ) {} if ("""" == 1) {} } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,13): error CS0815: Cannot assign (<null>, <null>) to an implicitly-typed variable // var t = (null, null); Diagnostic(ErrorCode.ERR_ImplicitlyTypedVariableAssignedBadValue, "t = (null, null)").WithArguments("(<null>, <null>)").WithLocation(6, 13), // (8,13): error CS0019: Operator '==' cannot be applied to operands of type 'string' and 'int' // if ("" == 1) {} Diagnostic(ErrorCode.ERR_BadBinaryOps, @""""" == 1").WithArguments("==", "string", "int").WithLocation(8, 13) ); } [Fact] public void TestTupleEqualityPreferredOverCustomOperator() { var source = @" 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 static bool operator ==(ValueTuple<T1, T2> t1, ValueTuple<T1, T2> t2) => throw null; public static bool operator !=(ValueTuple<T1, T2> t1, ValueTuple<T1, T2> t2) => throw null; public override bool Equals(object o) => throw null; public override int GetHashCode() => throw null; } } public class C { public static void Main() { var t1 = (1, 1); var t2 = (2, 2); System.Console.Write(t1 == t2); System.Console.Write(t1 != t2); } } "; var comp = CreateCompilationWithMscorlib40(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); // Note: tuple equality picked ahead of custom operator== (small compat break) CompileAndVerify(comp, expectedOutput: "FalseTrue"); } [Fact] public void TestCustomOperatorPlusAllowed() { var source = @" 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 static ValueTuple<T1, T2> operator +(ValueTuple<T1, T2> t1, ValueTuple<T1, T2> t2) => (default(T1), default(T2)); public override string ToString() => $""({Item1}, {Item2})""; } } public class C { public static void Main() { var t1 = (0, 1); var t2 = (2, 3); System.Console.Write(t1 + t2); } } "; var comp = CreateCompilationWithMscorlib40(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "(0, 0)"); } [Fact] void TestTupleEqualityPreferredOverCustomOperator_Nested() { string source = @" public class C { public static void Main() { System.Console.Write( (1, 2, (3, 4)) == (1, 2, (3, 4)) ); } } 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 static bool operator ==(ValueTuple<T1, T2> t1, ValueTuple<T1, T2> t2) => throw null; public static bool operator !=(ValueTuple<T1, T2> t1, ValueTuple<T1, T2> t2) => throw null; public override bool Equals(object o) => throw null; public override int GetHashCode() => throw null; } public struct ValueTuple<T1, T2, T3> { public T1 Item1; public T2 Item2; public T3 Item3; public ValueTuple(T1 item1, T2 item2, T3 item3) { this.Item1 = item1; this.Item2 = item2; this.Item3 = item3; } } } "; var comp = CreateCompilationWithMscorlib40(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); // Note: tuple equality picked ahead of custom operator== CompileAndVerify(comp, expectedOutput: "True"); } [Fact] public void TestNaN() { var source = @" public class C { public static void Main() { var t1 = (System.Double.NaN, 1); var t2 = (System.Double.NaN, 1); System.Console.Write($""{t1 == t2} {t1.Equals(t2)} {t1 != t2} {t1 == (System.Double.NaN, 1)}""); } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "False True True False"); } [Fact] public void TestTopLevelDynamic() { var source = @" public class C { public static void Main() { System.Globalization.CultureInfo saveUICulture = System.Threading.Thread.CurrentThread.CurrentUICulture; System.Threading.Thread.CurrentThread.CurrentUICulture = System.Globalization.CultureInfo.InvariantCulture; dynamic d1 = (1, 1); try { try { _ = d1 == (1, 1); } catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e) { System.Console.WriteLine(e.Message); } try { _ = d1 != (1, 2); } catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e) { System.Console.WriteLine(e.Message); } } finally { System.Threading.Thread.CurrentThread.CurrentUICulture = saveUICulture; } } } "; var comp = CreateCompilation(source, targetFramework: TargetFramework.StandardAndCSharp, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: @"Operator '==' cannot be applied to operands of type 'System.ValueTuple<int,int>' and 'System.ValueTuple<int,int>' Operator '!=' cannot be applied to operands of type 'System.ValueTuple<int,int>' and 'System.ValueTuple<int,int>'"); } [Fact] public void TestNestedDynamic() { var source = @" public class C { public static void Main() { System.Globalization.CultureInfo saveUICulture = System.Threading.Thread.CurrentThread.CurrentUICulture; System.Threading.Thread.CurrentThread.CurrentUICulture = System.Globalization.CultureInfo.InvariantCulture; dynamic d1 = (1, 1, 1); try { try { _ = (2, d1) == (2, (1, 1, 1)); } catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e) { System.Console.WriteLine(e.Message); } try { _ = (3, d1) != (3, (1, 2, 3)); } catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e) { System.Console.WriteLine(e.Message); } } finally { System.Threading.Thread.CurrentThread.CurrentUICulture = saveUICulture; } } } "; var comp = CreateCompilation(source, targetFramework: TargetFramework.StandardAndCSharp, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: @"Operator '==' cannot be applied to operands of type 'System.ValueTuple<int,int,int>' and 'System.ValueTuple<int,int,int>' Operator '!=' cannot be applied to operands of type 'System.ValueTuple<int,int,int>' and 'System.ValueTuple<int,int,int>'"); } [Fact] public void TestComparisonWithDeconstructionResult() { var source = @" public class C { public static void Main() { var b1 = (1, 2) == ((_, _) = new C()); var b2 = (1, 42) != ((_, _) = new C()); var b3 = (1, 42) == ((_, _) = new C()); // false var b4 = ((_, _) = new C()) == (1, 2); var b5 = ((_, _) = new C()) != (1, 42); var b6 = ((_, _) = new C()) == (1, 42); // false System.Console.Write($""{b1} {b2} {b3} {b4} {b5} {b6}""); } public void Deconstruct(out int x, out int y) { x = 1; y = 2; } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: @"True True False True True False"); } [Fact] public void TestComparisonWithDeconstruction() { var source = @" public class C { public static void Main() { var b1 = (1, 2) == new C(); } public void Deconstruct(out int x, out int y) { x = 1; y = 2; } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,18): error CS0019: Operator '==' cannot be applied to operands of type '(int, int)' and 'C' // var b1 = (1, 2) == new C(); Diagnostic(ErrorCode.ERR_BadBinaryOps, "(1, 2) == new C()").WithArguments("==", "(int, int)", "C").WithLocation(6, 18) ); } [Fact] public void TestEvaluationOrderOnTupleLiteral() { var source = @" public class C { public static void Main() { System.Console.Write($""{EXPRESSION}""); } } 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; throw null; } } } public class Base { public int I; public Base(int i) { I = i; } } public class A : Base { public A(int i) : base(i) { System.Console.Write($""A:{i}, ""); } public static bool operator ==(A a, Y y) { System.Console.Write($""A({a.I}) == Y({y.I}), ""); return a.I == y.I; } public static bool operator !=(A a, Y y) { System.Console.Write($""A({a.I}) != Y({y.I}), ""); return a.I != y.I; } public override bool Equals(object o) => throw null; public override int GetHashCode() => throw null; } public class X : Base { public X(int i) : base(i) { System.Console.Write($""X:{i}, ""); } } public class Y : Base { public Y(int i) : base(i) { System.Console.Write($""Y:{i}, ""); } public static implicit operator Y(X x) { System.Console.Write(""X -> ""); return new Y(x.I); } } "; validate("(new A(1), new A(2)) == (new X(1), new Y(2))", "A:1, A:2, X:1, Y:2, X -> Y:1, A(1) == Y(1), A(2) == Y(2), True"); validate("(new A(1), new A(2)) == (new X(30), new Y(40))", "A:1, A:2, X:30, Y:40, X -> Y:30, A(1) == Y(30), False"); validate("(new A(1), new A(2)) == (new X(1), new Y(50))", "A:1, A:2, X:1, Y:50, X -> Y:1, A(1) == Y(1), A(2) == Y(50), False"); validate("(new A(1), new A(2)) != (new X(1), new Y(2))", "A:1, A:2, X:1, Y:2, X -> Y:1, A(1) != Y(1), A(2) != Y(2), False"); validate("(new A(1), new A(2)) != (new Y(1), new X(2))", "A:1, A:2, Y:1, X:2, A(1) != Y(1), X -> Y:2, A(2) != Y(2), False"); validate("(new A(1), new A(2)) != (new X(30), new Y(40))", "A:1, A:2, X:30, Y:40, X -> Y:30, A(1) != Y(30), True"); validate("(new A(1), new A(2)) != (new X(50), new Y(2))", "A:1, A:2, X:50, Y:2, X -> Y:50, A(1) != Y(50), True"); validate("(new A(1), new A(2)) != (new X(1), new Y(60))", "A:1, A:2, X:1, Y:60, X -> Y:1, A(1) != Y(1), A(2) != Y(60), True"); void validate(string expression, string expected) { var comp = CreateCompilation(source.Replace("EXPRESSION", expression), options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: expected); } } [Fact] public void TestEvaluationOrderOnTupleType() { var source = @" namespace System { public struct ValueTuple<T1, T2> { public T1 Item1; public T2 Item2; public ValueTuple(T1 item1, T2 item2) { System.Console.Write(""ValueTuple2, ""); this.Item1 = item1; this.Item2 = item2; } } public struct ValueTuple<T1, T2, T3> { public ValueTuple(T1 item1, T2 item2, T3 item3) { // ValueTuple'3 required (constructed in bound tree), but not emitted throw null; } } } public class Base { public int I; public Base(int i) { I = i; } } public class A : Base { public A(int i) : base(i) { System.Console.Write($""A:{i}, ""); } public static bool operator ==(A a, Y y) { System.Console.Write($""A({a.I}) == Y({y.I}), ""); return true; } public static bool operator !=(A a, Y y) => throw null; public override bool Equals(object o) => throw null; public override int GetHashCode() => throw null; } public class X : Base { public X(int i) : base(i) { System.Console.Write($""X:{i}, ""); } } public class Y : Base { public Y(int i) : base(i) { System.Console.Write($""Y:{i}, ""); } public static implicit operator Y(X x) { System.Console.Write(""X -> ""); return new Y(x.I); } } public class C { public static void Main() { System.Console.Write($""{(new A(1), GetTuple(), new A(4)) == (new X(5), (new X(6), new Y(7)), new Y(8))}""); } public static (A, A) GetTuple() { System.Console.Write($""GetTuple, ""); return (new A(30), new A(40)); } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "A:1, GetTuple, A:30, A:40, ValueTuple2, A:4, X:5, X:6, Y:7, Y:8, X -> Y:5, A(1) == Y(5), X -> Y:6, A(30) == Y(6), A(40) == Y(7), A(4) == Y(8), True"); } [Fact] public void TestConstrainedValueTuple() { var source = @" class C { void M() { _ = (this, this) == (0, 1); // constraint violated by tuple in source _ = (this, this) == (this, this); // constraint violated by converted tuple } public static bool operator ==(C c, int i) => throw null; public static bool operator !=(C c, int i) => throw null; public override bool Equals(object o) => throw null; public override int GetHashCode() => throw null; public static implicit operator int(C c) => throw null; } namespace System { public struct ValueTuple<T1, T2> where T1 : class where T2 : class { public T1 Item1; public T2 Item2; public ValueTuple(T1 item1, T2 item2) { this.Item1 = item1; this.Item2 = item2; throw null; } } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,30): error CS0452: The type 'int' must be a reference type in order to use it as parameter 'T1' in the generic type or method '(T1, T2)' // _ = (this, this) == (0, 1); // constraint violated by tuple in source Diagnostic(ErrorCode.ERR_RefConstraintNotSatisfied, "0").WithArguments("(T1, T2)", "T1", "int").WithLocation(6, 30), // (6,30): error CS0452: The type 'int' must be a reference type in order to use it as parameter 'T1' in the generic type or method '(T1, T2)' // _ = (this, this) == (0, 1); // constraint violated by tuple in source Diagnostic(ErrorCode.ERR_RefConstraintNotSatisfied, "0").WithArguments("(T1, T2)", "T1", "int").WithLocation(6, 30), // (6,33): error CS0452: The type 'int' must be a reference type in order to use it as parameter 'T2' in the generic type or method '(T1, T2)' // _ = (this, this) == (0, 1); // constraint violated by tuple in source Diagnostic(ErrorCode.ERR_RefConstraintNotSatisfied, "1").WithArguments("(T1, T2)", "T2", "int").WithLocation(6, 33), // (6,33): error CS0452: The type 'int' must be a reference type in order to use it as parameter 'T2' in the generic type or method '(T1, T2)' // _ = (this, this) == (0, 1); // constraint violated by tuple in source Diagnostic(ErrorCode.ERR_RefConstraintNotSatisfied, "1").WithArguments("(T1, T2)", "T2", "int").WithLocation(6, 33), // (7,30): error CS0452: The type 'int' must be a reference type in order to use it as parameter 'T1' in the generic type or method '(T1, T2)' // _ = (this, this) == (this, this); // constraint violated by converted tuple Diagnostic(ErrorCode.ERR_RefConstraintNotSatisfied, "this").WithArguments("(T1, T2)", "T1", "int").WithLocation(7, 30), // (7,36): error CS0452: The type 'int' must be a reference type in order to use it as parameter 'T2' in the generic type or method '(T1, T2)' // _ = (this, this) == (this, this); // constraint violated by converted tuple Diagnostic(ErrorCode.ERR_RefConstraintNotSatisfied, "this").WithArguments("(T1, T2)", "T2", "int").WithLocation(7, 36) ); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); // check the int tuple var firstEquals = tree.GetCompilationUnitRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().First(); var intTuple = firstEquals.Right; Assert.Equal("(0, 1)", intTuple.ToString()); var intTupleType = model.GetTypeInfo(intTuple); Assert.Equal("(System.Int32, System.Int32)", intTupleType.Type.ToTestDisplayString()); Assert.Equal("(System.Int32, System.Int32)", intTupleType.ConvertedType.ToTestDisplayString()); // check the last tuple var secondEquals = tree.GetCompilationUnitRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().Last(); var lastTuple = secondEquals.Right; Assert.Equal("(this, this)", lastTuple.ToString()); var lastTupleType = model.GetTypeInfo(lastTuple); Assert.Equal("(C, C)", lastTupleType.Type.ToTestDisplayString()); Assert.Equal("(System.Int32, System.Int32)", lastTupleType.ConvertedType.ToTestDisplayString()); } [Fact] public void TestConstrainedNullable() { var source = @" class C { void M((int, int)? t1, (long, long)? t2) { _ = t1 == t2; } } public interface IInterface { } namespace System { public class Object { } public abstract class ValueType { } public struct Void { } public struct Boolean { } public struct Int32 { } public struct Int64 { } public struct Nullable<T> where T : struct, IInterface { public T GetValueOrDefault() => default(T); } public class Exception { } public struct ValueTuple<T1, T2> { public T1 Item1; public T2 Item2; public ValueTuple(T1 item1, T2 item2) { this.Item1 = item1; this.Item2 = item2; throw null; } } } "; var comp = CreateEmptyCompilation(source); comp.VerifyDiagnostics( // (4,24): error CS0315: The type '(int, int)' cannot be used as type parameter 'T' in the generic type or method 'Nullable<T>'. There is no boxing conversion from '(int, int)' to 'IInterface'. // void M((int, int)? t1, (long, long)? t2) Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedValType, "t1").WithArguments("System.Nullable<T>", "IInterface", "T", "(int, int)").WithLocation(4, 24), // (4,42): error CS0315: The type '(long, long)' cannot be used as type parameter 'T' in the generic type or method 'Nullable<T>'. There is no boxing conversion from '(long, long)' to 'IInterface'. // void M((int, int)? t1, (long, long)? t2) Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedValType, "t2").WithArguments("System.Nullable<T>", "IInterface", "T", "(long, long)").WithLocation(4, 42) ); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); // check t1 var equals = tree.GetCompilationUnitRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().Last(); var t1 = equals.Left; Assert.Equal("t1", t1.ToString()); var t1Type = model.GetTypeInfo(t1); Assert.Equal("(System.Int32, System.Int32)?", t1Type.Type.ToTestDisplayString()); Assert.Equal("(System.Int64, System.Int64)?", t1Type.ConvertedType.ToTestDisplayString()); } [Fact] public void TestEvaluationOrderOnTupleType2() { var source = @" namespace System { public struct ValueTuple<T1, T2> { public T1 Item1; public T2 Item2; public ValueTuple(T1 item1, T2 item2) { System.Console.Write(""ValueTuple2, ""); this.Item1 = item1; this.Item2 = item2; } } public struct ValueTuple<T1, T2, T3> { public ValueTuple(T1 item1, T2 item2, T3 item3) { // ValueTuple'3 required (constructed in bound tree), but not emitted throw null; } } } public class Base { public int I; public Base(int i) { I = i; } } public class A : Base { public A(int i) : base(i) { System.Console.Write($""A:{i}, ""); } public static bool operator ==(A a, Y y) { System.Console.Write($""A({a.I}) == Y({y.I}), ""); return true; } public static bool operator !=(A a, Y y) => throw null; public override bool Equals(object o) => throw null; public override int GetHashCode() => throw null; } public class X : Base { public X(int i) : base(i) { System.Console.Write($""X:{i}, ""); } } public class Y : Base { public Y(int i) : base(i) { System.Console.Write($""Y:{i}, ""); } public static implicit operator Y(X x) { System.Console.Write($""X:{x.I} -> ""); return new Y(x.I); } } public class C { public static void Main() { System.Console.Write($""{(new A(1), (new A(2), new A(3)), new A(4)) == (new X(5), GetTuple(), new Y(8))}""); } public static (X, Y) GetTuple() { System.Console.Write($""GetTuple, ""); return (new X(6), new Y(7)); } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: @"A:1, A:2, A:3, A:4, X:5, GetTuple, X:6, Y:7, ValueTuple2, Y:8, X:5 -> Y:5, A(1) == Y(5), X:6 -> Y:6, A(2) == Y(6), A(3) == Y(7), A(4) == Y(8), True"); } [Fact] public void TestEvaluationOrderOnTupleType3() { var source = @" namespace System { public struct ValueTuple<T1, T2> { public T1 Item1; public T2 Item2; public ValueTuple(T1 item1, T2 item2) { System.Console.Write(""ValueTuple2, ""); this.Item1 = item1; this.Item2 = item2; } } public struct ValueTuple<T1, T2, T3> { public ValueTuple(T1 item1, T2 item2, T3 item3) { // ValueTuple'3 required (constructed in bound tree), but not emitted throw null; } } } public class Base { public int I; public Base(int i) { I = i; } } public class A : Base { public A(int i) : base(i) { System.Console.Write($""A:{i}, ""); } public static bool operator ==(A a, Y y) { System.Console.Write($""A({a.I}) == Y({y.I}), ""); return true; } public static bool operator !=(A a, Y y) => throw null; public override bool Equals(object o) => throw null; public override int GetHashCode() => throw null; } public class X : Base { public X(int i) : base(i) { System.Console.Write($""X:{i}, ""); } } public class Y : Base { public Y(int i) : base(i) { System.Console.Write($""Y:{i}, ""); } public static implicit operator Y(X x) { System.Console.Write(""X -> ""); return new Y(x.I); } } public class C { public static void Main() { System.Console.Write($""{GetTuple() == (new X(6), new Y(7))}""); } public static (A, A) GetTuple() { System.Console.Write($""GetTuple, ""); return (new A(30), new A(40)); } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "GetTuple, A:30, A:40, ValueTuple2, X:6, Y:7, X -> Y:6, A(30) == Y(6), A(40) == Y(7), True"); } [Fact] public void TestObsoleteEqualityOperator() { var source = @" class C { void M() { System.Console.WriteLine($""{(new A(), new A()) == (new X(), new Y())}""); System.Console.WriteLine($""{(new A(), new A()) != (new X(), new Y())}""); } } public class A { [System.Obsolete(""obsolete"", true)] public static bool operator ==(A a, Y y) => throw null; [System.Obsolete(""obsolete too"", true)] public static bool operator !=(A a, Y y) => throw null; public override bool Equals(object o) => throw null; public override int GetHashCode() => throw null; } public class X { } public class Y { public static implicit operator Y(X x) => throw null; } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,37): error CS0619: 'A.operator ==(A, Y)' is obsolete: 'obsolete' // System.Console.WriteLine($"{(new A(), new A()) == (new X(), new Y())}"); Diagnostic(ErrorCode.ERR_DeprecatedSymbolStr, "(new A(), new A()) == (new X(), new Y())").WithArguments("A.operator ==(A, Y)", "obsolete").WithLocation(6, 37), // (6,37): error CS0619: 'A.operator ==(A, Y)' is obsolete: 'obsolete' // System.Console.WriteLine($"{(new A(), new A()) == (new X(), new Y())}"); Diagnostic(ErrorCode.ERR_DeprecatedSymbolStr, "(new A(), new A()) == (new X(), new Y())").WithArguments("A.operator ==(A, Y)", "obsolete").WithLocation(6, 37), // (7,37): error CS0619: 'A.operator !=(A, Y)' is obsolete: 'obsolete too' // System.Console.WriteLine($"{(new A(), new A()) != (new X(), new Y())}"); Diagnostic(ErrorCode.ERR_DeprecatedSymbolStr, "(new A(), new A()) != (new X(), new Y())").WithArguments("A.operator !=(A, Y)", "obsolete too").WithLocation(7, 37), // (7,37): error CS0619: 'A.operator !=(A, Y)' is obsolete: 'obsolete too' // System.Console.WriteLine($"{(new A(), new A()) != (new X(), new Y())}"); Diagnostic(ErrorCode.ERR_DeprecatedSymbolStr, "(new A(), new A()) != (new X(), new Y())").WithArguments("A.operator !=(A, Y)", "obsolete too").WithLocation(7, 37) ); } [Fact] public void TestDefiniteAssignment() { var source = @" class C { void M() { int error1; System.Console.Write((1, 2) == (error1, 2)); int error2; System.Console.Write((1, (error2, 3)) == (1, (2, 3))); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (7,41): error CS0165: Use of unassigned local variable 'error1' // System.Console.Write((1, 2) == (error1, 2)); Diagnostic(ErrorCode.ERR_UseDefViolation, "error1").WithArguments("error1").WithLocation(7, 41), // (10,35): error CS0165: Use of unassigned local variable 'error2' // System.Console.Write((1, (error2, 3)) == (1, (2, 3))); Diagnostic(ErrorCode.ERR_UseDefViolation, "error2").WithArguments("error2").WithLocation(10, 35) ); } [Fact] public void TestDefiniteAssignment2() { var source = @" class C { int M(out int x) { _ = (M(out int y), y) == (1, 2); // ok _ = (z, M(out int z)) == (1, 2); // error x = 1; return 2; } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (7,14): error CS0841: Cannot use local variable 'z' before it is declared // _ = (z, M(out int z)) == (1, 2); // error Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "z").WithArguments("z").WithLocation(7, 14) ); } [Fact] public void TestEqualityOfTypeConvertingToTuple() { var source = @" class C { private int i; void M() { System.Console.Write(this == (1, 1)); System.Console.Write((1, 1) == this); } public static implicit operator (int, int)(C c) { return (c.i, c.i); } C(int i) { this.i = i; } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (7,30): error CS0019: Operator '==' cannot be applied to operands of type 'C' and '(int, int)' // System.Console.Write(this == (1, 1)); Diagnostic(ErrorCode.ERR_BadBinaryOps, "this == (1, 1)").WithArguments("==", "C", "(int, int)").WithLocation(7, 30), // (8,30): error CS0019: Operator '==' cannot be applied to operands of type '(int, int)' and 'C' // System.Console.Write((1, 1) == this); Diagnostic(ErrorCode.ERR_BadBinaryOps, "(1, 1) == this").WithArguments("==", "(int, int)", "C").WithLocation(8, 30) ); } [Fact] public void TestEqualityOfTypeConvertingFromTuple() { var source = @" class C { private int i; public static void Main() { var c = new C(2); System.Console.Write(c == (1, 1)); System.Console.Write((1, 1) == c); } public static implicit operator C((int, int) x) { return new C(x.Item1 + x.Item2); } public static bool operator ==(C c1, C c2) => c1.i == c2.i; public static bool operator !=(C c1, C c2) => throw null; public override int GetHashCode() => throw null; public override bool Equals(object other) => throw null; C(int i) { this.i = i; } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "TrueTrue"); } [Fact] public void TestEqualityOfTypeComparableWithTuple() { var source = @" class C { private static void Main() { System.Console.Write(new C() == (1, 1)); System.Console.Write(new C() != (1, 1)); } public static bool operator ==(C c, (int, int) t) { return t.Item1 + t.Item2 == 2; } public static bool operator !=(C c, (int, int) t) { return t.Item1 + t.Item2 != 2; } public override bool Equals(object o) => throw null; public override int GetHashCode() => throw null; } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "TrueFalse"); } [Fact] public void TestOfTwoUnrelatedTypes() { var source = @" class A { } class C { static void M() { System.Console.Write(new C() == new A()); System.Console.Write((1, new C()) == (1, new A())); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (7,30): error CS0019: Operator '==' cannot be applied to operands of type 'C' and 'A' // System.Console.Write(new C() == new A()); Diagnostic(ErrorCode.ERR_BadBinaryOps, "new C() == new A()").WithArguments("==", "C", "A").WithLocation(7, 30), // (8,30): error CS0019: Operator '==' cannot be applied to operands of type 'C' and 'A' // System.Console.Write((1, new C()) == (1, new A())); Diagnostic(ErrorCode.ERR_BadBinaryOps, "(1, new C()) == (1, new A())").WithArguments("==", "C", "A").WithLocation(8, 30) ); } [Fact] public void TestOfTwoUnrelatedTypes2() { var source = @" class A { } class C { static void M(string s, System.Exception e) { System.Console.Write(s == 3); System.Console.Write((1, s) == (1, e)); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (7,30): error CS0019: Operator '==' cannot be applied to operands of type 'string' and 'int' // System.Console.Write(s == 3); Diagnostic(ErrorCode.ERR_BadBinaryOps, "s == 3").WithArguments("==", "string", "int").WithLocation(7, 30), // (8,30): error CS0019: Operator '==' cannot be applied to operands of type 'string' and 'Exception' // System.Console.Write((1, s) == (1, e)); Diagnostic(ErrorCode.ERR_BadBinaryOps, "(1, s) == (1, e)").WithArguments("==", "string", "System.Exception").WithLocation(8, 30) ); } [Fact] public void TestBadRefCompare() { var source = @" class C { static void M() { string s = ""11""; object o = s + s; (object, object) t = default; bool b = o == s; bool b2 = t == (s, s); // no warning } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (10,18): warning CS0252: Possible unintended reference comparison; to get a value comparison, cast the left hand side to type 'string' // bool b = o == s; Diagnostic(ErrorCode.WRN_BadRefCompareLeft, "o == s").WithArguments("string").WithLocation(10, 18) ); } [Fact, WorkItem(27047, "https://github.com/dotnet/roslyn/issues/27047")] public void TestWithObsoleteImplicitConversion() { var source = @" class C { private static bool TupleEquals((C, int)? nt1, (int, C) nt2) => nt1 == nt2; // warn 1 and 2 private static bool TupleNotEquals((C, int)? nt1, (int, C) nt2) => nt1 != nt2; // warn 3 and 4 [System.Obsolete(""obsolete"", error: true)] public static implicit operator int(C c) => throw null; } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (5,12): error CS0619: 'C.implicit operator int(C)' is obsolete: 'obsolete' // => nt1 == nt2; // warn 1 and 2 Diagnostic(ErrorCode.ERR_DeprecatedSymbolStr, "nt1").WithArguments("C.implicit operator int(C)", "obsolete").WithLocation(5, 12), // (5,19): error CS0619: 'C.implicit operator int(C)' is obsolete: 'obsolete' // => nt1 == nt2; // warn 1 and 2 Diagnostic(ErrorCode.ERR_DeprecatedSymbolStr, "nt2").WithArguments("C.implicit operator int(C)", "obsolete").WithLocation(5, 19), // (8,12): error CS0619: 'C.implicit operator int(C)' is obsolete: 'obsolete' // => nt1 != nt2; // warn 3 and 4 Diagnostic(ErrorCode.ERR_DeprecatedSymbolStr, "nt1").WithArguments("C.implicit operator int(C)", "obsolete").WithLocation(8, 12), // (8,19): error CS0619: 'C.implicit operator int(C)' is obsolete: 'obsolete' // => nt1 != nt2; // warn 3 and 4 Diagnostic(ErrorCode.ERR_DeprecatedSymbolStr, "nt2").WithArguments("C.implicit operator int(C)", "obsolete").WithLocation(8, 19) ); } [Fact, WorkItem(27047, "https://github.com/dotnet/roslyn/issues/27047")] public void TestWithObsoleteBoolConversion() { var source = @" public class A { public static bool TupleEquals((A, A) t) => t == t; // warn 1 and 2 public static bool TupleNotEquals((A, A) t) => t != t; // warn 3 and 4 public static NotBool operator ==(A a1, A a2) => throw null; public static NotBool operator !=(A a1, A a2) => throw null; public override bool Equals(object o) => throw null; public override int GetHashCode() => throw null; } public class NotBool { [System.Obsolete(""obsolete"", error: true)] public static implicit operator bool(NotBool b) => throw null; } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (4,49): error CS0619: 'NotBool.implicit operator bool(NotBool)' is obsolete: 'obsolete' // public static bool TupleEquals((A, A) t) => t == t; // warn 1 and 2 Diagnostic(ErrorCode.ERR_DeprecatedSymbolStr, "t == t").WithArguments("NotBool.implicit operator bool(NotBool)", "obsolete").WithLocation(4, 49), // (4,49): error CS0619: 'NotBool.implicit operator bool(NotBool)' is obsolete: 'obsolete' // public static bool TupleEquals((A, A) t) => t == t; // warn 1 and 2 Diagnostic(ErrorCode.ERR_DeprecatedSymbolStr, "t == t").WithArguments("NotBool.implicit operator bool(NotBool)", "obsolete").WithLocation(4, 49), // (5,52): error CS0619: 'NotBool.implicit operator bool(NotBool)' is obsolete: 'obsolete' // public static bool TupleNotEquals((A, A) t) => t != t; // warn 3 and 4 Diagnostic(ErrorCode.ERR_DeprecatedSymbolStr, "t != t").WithArguments("NotBool.implicit operator bool(NotBool)", "obsolete").WithLocation(5, 52), // (5,52): error CS0619: 'NotBool.implicit operator bool(NotBool)' is obsolete: 'obsolete' // public static bool TupleNotEquals((A, A) t) => t != t; // warn 3 and 4 Diagnostic(ErrorCode.ERR_DeprecatedSymbolStr, "t != t").WithArguments("NotBool.implicit operator bool(NotBool)", "obsolete").WithLocation(5, 52) ); } [Fact, WorkItem(27047, "https://github.com/dotnet/roslyn/issues/27047")] public void TestWithObsoleteComparisonOperators() { var source = @" public class A { public static bool TupleEquals((A, A) t) => t == t; // warn 1 and 2 public static bool TupleNotEquals((A, A) t) => t != t; // warn 3 and 4 [System.Obsolete("""", error: true)] public static bool operator ==(A a1, A a2) => throw null; [System.Obsolete("""", error: true)] public static bool operator !=(A a1, A a2) => throw null; public override bool Equals(object o) => throw null; public override int GetHashCode() => throw null; } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (4,49): error CS0619: 'A.operator ==(A, A)' is obsolete: '' // public static bool TupleEquals((A, A) t) => t == t; // warn 1 and 2 Diagnostic(ErrorCode.ERR_DeprecatedSymbolStr, "t == t").WithArguments("A.operator ==(A, A)", "").WithLocation(4, 49), // (4,49): error CS0619: 'A.operator ==(A, A)' is obsolete: '' // public static bool TupleEquals((A, A) t) => t == t; // warn 1 and 2 Diagnostic(ErrorCode.ERR_DeprecatedSymbolStr, "t == t").WithArguments("A.operator ==(A, A)", "").WithLocation(4, 49), // (5,52): error CS0619: 'A.operator !=(A, A)' is obsolete: '' // public static bool TupleNotEquals((A, A) t) => t != t; // warn 3 and 4 Diagnostic(ErrorCode.ERR_DeprecatedSymbolStr, "t != t").WithArguments("A.operator !=(A, A)", "").WithLocation(5, 52), // (5,52): error CS0619: 'A.operator !=(A, A)' is obsolete: '' // public static bool TupleNotEquals((A, A) t) => t != t; // warn 3 and 4 Diagnostic(ErrorCode.ERR_DeprecatedSymbolStr, "t != t").WithArguments("A.operator !=(A, A)", "").WithLocation(5, 52) ); } [Fact, WorkItem(27047, "https://github.com/dotnet/roslyn/issues/27047")] public void TestWithObsoleteTruthOperators() { var source = @" public class A { public static bool TupleEquals((A, A) t) => t == t; // warn 1 and 2 public static bool TupleNotEquals((A, A) t) => t != t; // warn 3 and 4 public static NotBool operator ==(A a1, A a2) => throw null; public static NotBool operator !=(A a1, A a2) => throw null; public override bool Equals(object o) => throw null; public override int GetHashCode() => throw null; } public class NotBool { [System.Obsolete(""obsolete"", error: true)] public static bool operator true(NotBool b) => throw null; [System.Obsolete(""obsolete"", error: true)] public static bool operator false(NotBool b) => throw null; } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (4,49): error CS0619: 'NotBool.operator false(NotBool)' is obsolete: 'obsolete' // public static bool TupleEquals((A, A) t) => t == t; // warn 1 and 2 Diagnostic(ErrorCode.ERR_DeprecatedSymbolStr, "t == t").WithArguments("NotBool.operator false(NotBool)", "obsolete").WithLocation(4, 49), // (4,49): error CS0619: 'NotBool.operator false(NotBool)' is obsolete: 'obsolete' // public static bool TupleEquals((A, A) t) => t == t; // warn 1 and 2 Diagnostic(ErrorCode.ERR_DeprecatedSymbolStr, "t == t").WithArguments("NotBool.operator false(NotBool)", "obsolete").WithLocation(4, 49), // (5,52): error CS0619: 'NotBool.operator true(NotBool)' is obsolete: 'obsolete' // public static bool TupleNotEquals((A, A) t) => t != t; // warn 3 and 4 Diagnostic(ErrorCode.ERR_DeprecatedSymbolStr, "t != t").WithArguments("NotBool.operator true(NotBool)", "obsolete").WithLocation(5, 52), // (5,52): error CS0619: 'NotBool.operator true(NotBool)' is obsolete: 'obsolete' // public static bool TupleNotEquals((A, A) t) => t != t; // warn 3 and 4 Diagnostic(ErrorCode.ERR_DeprecatedSymbolStr, "t != t").WithArguments("NotBool.operator true(NotBool)", "obsolete").WithLocation(5, 52) ); } [Fact] public void TestEqualOnNullableVsNullableTuples() { var source = @" class C { public static void Main() { Compare(null, null); Compare(null, (1, 2)); Compare((2, 3), null); Compare((4, 4), (4, 4)); Compare((5, 5), (10, 10)); } private static void Compare((int, int)? nt1, (int, int)? nt2) { System.Console.Write($""{nt1 == nt2} ""); } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "True False False True False"); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var comparison = tree.GetCompilationUnitRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().Single(); var nt1 = comparison.Left; var nt1Type = model.GetTypeInfo(nt1); Assert.Equal("nt1", nt1.ToString()); Assert.Equal("(System.Int32, System.Int32)?", nt1Type.Type.ToTestDisplayString()); Assert.Equal("(System.Int32, System.Int32)?", nt1Type.ConvertedType.ToTestDisplayString()); var nt2 = comparison.Right; var nt2Type = model.GetTypeInfo(nt2); Assert.Equal("nt2", nt2.ToString()); Assert.Equal("(System.Int32, System.Int32)?", nt2Type.Type.ToTestDisplayString()); Assert.Equal("(System.Int32, System.Int32)?", nt2Type.ConvertedType.ToTestDisplayString()); verifier.VerifyIL("C.Compare", @"{ // Code size 104 (0x68) .maxstack 3 .locals init (System.ValueTuple<int, int>? V_0, System.ValueTuple<int, int>? V_1, bool V_2, System.ValueTuple<int, int> V_3, System.ValueTuple<int, int> V_4) IL_0000: nop IL_0001: ldstr ""{0} "" IL_0006: ldarg.0 IL_0007: stloc.0 IL_0008: ldarg.1 IL_0009: stloc.1 IL_000a: ldloca.s V_0 IL_000c: call ""bool System.ValueTuple<int, int>?.HasValue.get"" IL_0011: stloc.2 IL_0012: ldloc.2 IL_0013: ldloca.s V_1 IL_0015: call ""bool System.ValueTuple<int, int>?.HasValue.get"" IL_001a: beq.s IL_001f IL_001c: ldc.i4.0 IL_001d: br.s IL_0057 IL_001f: ldloc.2 IL_0020: brtrue.s IL_0025 IL_0022: ldc.i4.1 IL_0023: br.s IL_0057 IL_0025: ldloca.s V_0 IL_0027: call ""System.ValueTuple<int, int> System.ValueTuple<int, int>?.GetValueOrDefault()"" IL_002c: stloc.3 IL_002d: ldloca.s V_1 IL_002f: call ""System.ValueTuple<int, int> System.ValueTuple<int, int>?.GetValueOrDefault()"" IL_0034: stloc.s V_4 IL_0036: ldloc.3 IL_0037: ldfld ""int System.ValueTuple<int, int>.Item1"" IL_003c: ldloc.s V_4 IL_003e: ldfld ""int System.ValueTuple<int, int>.Item1"" IL_0043: bne.un.s IL_0056 IL_0045: ldloc.3 IL_0046: ldfld ""int System.ValueTuple<int, int>.Item2"" IL_004b: ldloc.s V_4 IL_004d: ldfld ""int System.ValueTuple<int, int>.Item2"" IL_0052: ceq IL_0054: br.s IL_0057 IL_0056: ldc.i4.0 IL_0057: box ""bool"" IL_005c: call ""string string.Format(string, object)"" IL_0061: call ""void System.Console.Write(string)"" IL_0066: nop IL_0067: ret }"); } [Fact] public void TestEqualOnNullableVsNullableTuples_NeverNull() { var source = @" class C { public static void Main() { System.Console.Write(((int, int)?) (1, 2) == ((int, int)?) (1, 2)); } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "True"); verifier.VerifyIL("C.Main", @" { // Code size 19 (0x13) .maxstack 2 IL_0000: nop IL_0001: ldc.i4.1 IL_0002: ldc.i4.1 IL_0003: bne.un.s IL_000b IL_0005: ldc.i4.2 IL_0006: ldc.i4.2 IL_0007: ceq IL_0009: br.s IL_000c IL_000b: ldc.i4.0 IL_000c: call ""void System.Console.Write(bool)"" IL_0011: nop IL_0012: ret } "); } [Fact] public void TestEqualOnNullableVsNullableTuples_OneSideNeverNull() { var source = @" class C { public static void Main() { System.Console.Write(((int, int)?) (1, 2) == (1, 2)); } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "True"); verifier.VerifyIL("C.Main", @" { // Code size 19 (0x13) .maxstack 2 IL_0000: nop IL_0001: ldc.i4.1 IL_0002: ldc.i4.1 IL_0003: bne.un.s IL_000b IL_0005: ldc.i4.2 IL_0006: ldc.i4.2 IL_0007: ceq IL_0009: br.s IL_000c IL_000b: ldc.i4.0 IL_000c: call ""void System.Console.Write(bool)"" IL_0011: nop IL_0012: ret } "); } [Fact] public void TestEqualOnNullableVsNullableTuples_Tuple_AlwaysNull_AlwaysNull() { var source = @" class C { public static void Main() { System.Console.Write(((int, int)?)null == ((int, int)?)null); } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "True"); verifier.VerifyIL("C.Main", @"{ // Code size 9 (0x9) .maxstack 1 IL_0000: nop IL_0001: ldc.i4.1 IL_0002: call ""void System.Console.Write(bool)"" IL_0007: nop IL_0008: ret } "); CompileAndVerify(source, options: TestOptions.ReleaseExe).VerifyIL("C.Main", @"{ // Code size 7 (0x7) .maxstack 1 IL_0000: ldc.i4.1 IL_0001: call ""void System.Console.Write(bool)"" IL_0006: ret } "); } [Fact] public void TestEqualOnNullableVsNullableTuples_Tuple_MaybeNull_AlwaysNull() { var source = @" class C { public static void Main() { M(null); M((1, 2)); } public static void M((int, int)? t) { System.Console.Write(t == ((int, int)?)null); } } "; CompileAndVerify(source, expectedOutput: "TrueFalse", options: TestOptions.ReleaseExe).VerifyIL("C.M", @"{ // Code size 18 (0x12) .maxstack 2 .locals init (System.ValueTuple<int, int>? V_0) IL_0000: ldarg.0 IL_0001: stloc.0 IL_0002: ldloca.s V_0 IL_0004: call ""bool System.ValueTuple<int, int>?.HasValue.get"" IL_0009: ldc.i4.0 IL_000a: ceq IL_000c: call ""void System.Console.Write(bool)"" IL_0011: ret } "); } [Fact] public void TestNotEqualOnNullableVsNullableTuples_Tuple_MaybeNull_AlwaysNull() { var source = @" class C { public static void Main() { M(null); M((1, 2)); } public static void M((int, int)? t) { System.Console.Write(t != ((int, int)?)null); } } "; CompileAndVerify(source, expectedOutput: "FalseTrue", options: TestOptions.ReleaseExe).VerifyIL("C.M", @"{ // Code size 15 (0xf) .maxstack 1 .locals init (System.ValueTuple<int, int>? V_0) IL_0000: ldarg.0 IL_0001: stloc.0 IL_0002: ldloca.s V_0 IL_0004: call ""bool System.ValueTuple<int, int>?.HasValue.get"" IL_0009: call ""void System.Console.Write(bool)"" IL_000e: ret } "); } [Fact] public void TestNotEqualOnNullableVsNullableTuples_Tuple_AlwaysNull_MaybeNull() { var source = @" class C { public static void Main() { M(null); M((1, 2)); } public static void M((int, int)? t) { System.Console.Write(((int, int)?)null == t); } } "; CompileAndVerify(source, expectedOutput: "TrueFalse", options: TestOptions.ReleaseExe).VerifyIL("C.M", @"{ // Code size 18 (0x12) .maxstack 2 .locals init (System.ValueTuple<int, int>? V_0) IL_0000: ldarg.0 IL_0001: stloc.0 IL_0002: ldloca.s V_0 IL_0004: call ""bool System.ValueTuple<int, int>?.HasValue.get"" IL_0009: ldc.i4.0 IL_000a: ceq IL_000c: call ""void System.Console.Write(bool)"" IL_0011: ret } "); } [Fact] public void TestEqualOnNullableVsNullableTuples_Tuple_NeverNull_AlwaysNull() { var source = @" class C { public static void Main() { System.Console.Write((1, 2) == ((int, int)?)null); } } "; CompileAndVerify(source, expectedOutput: "False", options: TestOptions.ReleaseExe).VerifyIL("C.Main", @"{ // Code size 7 (0x7) .maxstack 1 IL_0000: ldc.i4.0 IL_0001: call ""void System.Console.Write(bool)"" IL_0006: ret } "); } [Fact] public void TestEqualOnNullableVsNullableTuples_Tuple_AlwaysNull_MaybeNull() { var source = @" class C { public static void Main() { M(null); M((1, 2)); } public static void M((int, int)? t) { System.Console.Write(((int, int)?)null == t); } } "; CompileAndVerify(source, expectedOutput: "TrueFalse", options: TestOptions.ReleaseExe).VerifyIL("C.M", @"{ // Code size 18 (0x12) .maxstack 2 .locals init (System.ValueTuple<int, int>? V_0) IL_0000: ldarg.0 IL_0001: stloc.0 IL_0002: ldloca.s V_0 IL_0004: call ""bool System.ValueTuple<int, int>?.HasValue.get"" IL_0009: ldc.i4.0 IL_000a: ceq IL_000c: call ""void System.Console.Write(bool)"" IL_0011: ret } "); } [Fact] public void TestEqualOnNullableVsNullableTuples_Tuple_AlwaysNull_NeverNull() { var source = @" class C { public static void Main() { System.Console.Write(((int, int)?)null == (1, 2)); } } "; CompileAndVerify(source, expectedOutput: "False", options: TestOptions.ReleaseExe).VerifyIL("C.Main", @"{ // Code size 7 (0x7) .maxstack 1 IL_0000: ldc.i4.0 IL_0001: call ""void System.Console.Write(bool)"" IL_0006: ret } "); } [Fact] public void TestEqualOnNullableVsNullableTuples_ElementAlwaysNull() { var source = @" class C { public static void Main() { System.Console.Write((null, null) == (new int?(), new int?())); } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "True"); verifier.VerifyIL("C.Main", @"{ // Code size 9 (0x9) .maxstack 1 IL_0000: nop IL_0001: ldc.i4.1 IL_0002: call ""void System.Console.Write(bool)"" IL_0007: nop IL_0008: ret } "); } [Fact] public void TestNotEqualOnNullableVsNullableTuples() { var source = @" class C { public static void Main() { Compare(null, null); Compare(null, (1, 2)); Compare((2, 3), null); Compare((4, 4), (4, 4)); Compare((5, 5), (10, 10)); } private static void Compare((int, int)? nt1, (int, int)? nt2) { System.Console.Write($""{nt1 != nt2} ""); } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "False True True False True"); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var comparison = tree.GetCompilationUnitRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().Single(); var nt1 = comparison.Left; var nt1Type = model.GetTypeInfo(nt1); Assert.Equal("nt1", nt1.ToString()); Assert.Equal("(System.Int32, System.Int32)?", nt1Type.Type.ToTestDisplayString()); Assert.Equal("(System.Int32, System.Int32)?", nt1Type.ConvertedType.ToTestDisplayString()); var nt2 = comparison.Right; var nt2Type = model.GetTypeInfo(nt2); Assert.Equal("nt2", nt2.ToString()); Assert.Equal("(System.Int32, System.Int32)?", nt2Type.Type.ToTestDisplayString()); Assert.Equal("(System.Int32, System.Int32)?", nt2Type.ConvertedType.ToTestDisplayString()); verifier.VerifyIL("C.Compare", @"{ // Code size 107 (0x6b) .maxstack 3 .locals init (System.ValueTuple<int, int>? V_0, System.ValueTuple<int, int>? V_1, bool V_2, System.ValueTuple<int, int> V_3, System.ValueTuple<int, int> V_4) IL_0000: nop IL_0001: ldstr ""{0} "" IL_0006: ldarg.0 IL_0007: stloc.0 IL_0008: ldarg.1 IL_0009: stloc.1 IL_000a: ldloca.s V_0 IL_000c: call ""bool System.ValueTuple<int, int>?.HasValue.get"" IL_0011: stloc.2 IL_0012: ldloc.2 IL_0013: ldloca.s V_1 IL_0015: call ""bool System.ValueTuple<int, int>?.HasValue.get"" IL_001a: beq.s IL_001f IL_001c: ldc.i4.1 IL_001d: br.s IL_005a IL_001f: ldloc.2 IL_0020: brtrue.s IL_0025 IL_0022: ldc.i4.0 IL_0023: br.s IL_005a IL_0025: ldloca.s V_0 IL_0027: call ""System.ValueTuple<int, int> System.ValueTuple<int, int>?.GetValueOrDefault()"" IL_002c: stloc.3 IL_002d: ldloca.s V_1 IL_002f: call ""System.ValueTuple<int, int> System.ValueTuple<int, int>?.GetValueOrDefault()"" IL_0034: stloc.s V_4 IL_0036: ldloc.3 IL_0037: ldfld ""int System.ValueTuple<int, int>.Item1"" IL_003c: ldloc.s V_4 IL_003e: ldfld ""int System.ValueTuple<int, int>.Item1"" IL_0043: bne.un.s IL_0059 IL_0045: ldloc.3 IL_0046: ldfld ""int System.ValueTuple<int, int>.Item2"" IL_004b: ldloc.s V_4 IL_004d: ldfld ""int System.ValueTuple<int, int>.Item2"" IL_0052: ceq IL_0054: ldc.i4.0 IL_0055: ceq IL_0057: br.s IL_005a IL_0059: ldc.i4.1 IL_005a: box ""bool"" IL_005f: call ""string string.Format(string, object)"" IL_0064: call ""void System.Console.Write(string)"" IL_0069: nop IL_006a: ret }"); } [Fact] public void TestNotEqualOnNullableVsNullableNestedTuples() { var source = @" class C { public static void Main() { Compare((1, null), (1, null), true); Compare(null, (1, (2, 3)), false); Compare((1, (2, 3)), (1, null), false); Compare((1, (4, 4)), (1, (4, 4)), true); Compare((1, (5, 5)), (1, (10, 10)), false); System.Console.Write(""Success""); } private static void Compare((int, (int, int)?)? nt1, (int, (int, int)?)? nt2, bool expectMatch) { if (expectMatch != (nt1 == nt2) || expectMatch == (nt1 != nt2)) { throw null; } } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "Success"); } [Fact] public void TestEqualOnNullableVsNullableTuples_WithImplicitConversion() { var source = @" class C { public static void Main() { Compare(null, null); Compare(null, (1, 2)); Compare((2, 3), null); Compare((4, 4), (4, 4)); Compare((5, 5), (10, 10)); } private static void Compare((int, int)? nt1, (byte, long)? nt2) { System.Console.Write($""{nt1 == nt2} ""); } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "True False False True False"); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var comparison = tree.GetCompilationUnitRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().Single(); var nt1 = comparison.Left; var nt1Type = model.GetTypeInfo(nt1); Assert.Equal("nt1", nt1.ToString()); Assert.Equal("(System.Int32, System.Int32)?", nt1Type.Type.ToTestDisplayString()); Assert.Equal("(System.Int32, System.Int64)?", nt1Type.ConvertedType.ToTestDisplayString()); var nt2 = comparison.Right; var nt2Type = model.GetTypeInfo(nt2); Assert.Equal("nt2", nt2.ToString()); Assert.Equal("(System.Byte, System.Int64)?", nt2Type.Type.ToTestDisplayString()); Assert.Equal("(System.Int32, System.Int64)?", nt2Type.ConvertedType.ToTestDisplayString()); verifier.VerifyIL("C.Compare", @"{ // Code size 105 (0x69) .maxstack 3 .locals init (System.ValueTuple<int, int>? V_0, System.ValueTuple<byte, long>? V_1, bool V_2, System.ValueTuple<int, int> V_3, System.ValueTuple<byte, long> V_4) IL_0000: nop IL_0001: ldstr ""{0} "" IL_0006: ldarg.0 IL_0007: stloc.0 IL_0008: ldarg.1 IL_0009: stloc.1 IL_000a: ldloca.s V_0 IL_000c: call ""bool System.ValueTuple<int, int>?.HasValue.get"" IL_0011: stloc.2 IL_0012: ldloc.2 IL_0013: ldloca.s V_1 IL_0015: call ""bool System.ValueTuple<byte, long>?.HasValue.get"" IL_001a: beq.s IL_001f IL_001c: ldc.i4.0 IL_001d: br.s IL_0058 IL_001f: ldloc.2 IL_0020: brtrue.s IL_0025 IL_0022: ldc.i4.1 IL_0023: br.s IL_0058 IL_0025: ldloca.s V_0 IL_0027: call ""System.ValueTuple<int, int> System.ValueTuple<int, int>?.GetValueOrDefault()"" IL_002c: stloc.3 IL_002d: ldloca.s V_1 IL_002f: call ""System.ValueTuple<byte, long> System.ValueTuple<byte, long>?.GetValueOrDefault()"" IL_0034: stloc.s V_4 IL_0036: ldloc.3 IL_0037: ldfld ""int System.ValueTuple<int, int>.Item1"" IL_003c: ldloc.s V_4 IL_003e: ldfld ""byte System.ValueTuple<byte, long>.Item1"" IL_0043: bne.un.s IL_0057 IL_0045: ldloc.3 IL_0046: ldfld ""int System.ValueTuple<int, int>.Item2"" IL_004b: conv.i8 IL_004c: ldloc.s V_4 IL_004e: ldfld ""long System.ValueTuple<byte, long>.Item2"" IL_0053: ceq IL_0055: br.s IL_0058 IL_0057: ldc.i4.0 IL_0058: box ""bool"" IL_005d: call ""string string.Format(string, object)"" IL_0062: call ""void System.Console.Write(string)"" IL_0067: nop IL_0068: ret }"); } [Fact] public void TestOnNullableVsNullableTuples_WithImplicitCustomConversion() { var source = @" class C { int _value; public C(int v) { _value = v; } public static void Main() { Compare(null, null); Compare(null, (1, new C(20))); Compare((new C(30), 3), null); Compare((new C(4), 4), (4, new C(4))); Compare((new C(5), 5), (10, new C(10))); Compare((new C(6), 6), (6, new C(20))); } private static void Compare((C, int)? nt1, (int, C)? nt2) { System.Console.Write($""{nt1 == nt2} ""); } public static implicit operator int(C c) { System.Console.Write($""Convert{c._value} ""); return c._value; } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "True False False Convert4 Convert4 True Convert5 False Convert6 Convert20 False "); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var comparison = tree.GetCompilationUnitRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().Single(); var nt1 = comparison.Left; var nt1Type = model.GetTypeInfo(nt1); Assert.Equal("nt1", nt1.ToString()); Assert.Equal("(C, System.Int32)?", nt1Type.Type.ToTestDisplayString()); Assert.Equal("(System.Int32, System.Int32)?", nt1Type.ConvertedType.ToTestDisplayString()); var nt2 = comparison.Right; var nt2Type = model.GetTypeInfo(nt2); Assert.Equal("nt2", nt2.ToString()); Assert.Equal("(System.Int32, C)?", nt2Type.Type.ToTestDisplayString()); Assert.Equal("(System.Int32, System.Int32)?", nt2Type.ConvertedType.ToTestDisplayString()); verifier.VerifyIL("C.Compare", @"{ // Code size 114 (0x72) .maxstack 3 .locals init (System.ValueTuple<C, int>? V_0, System.ValueTuple<int, C>? V_1, bool V_2, System.ValueTuple<C, int> V_3, System.ValueTuple<int, C> V_4) IL_0000: nop IL_0001: ldstr ""{0} "" IL_0006: ldarg.0 IL_0007: stloc.0 IL_0008: ldarg.1 IL_0009: stloc.1 IL_000a: ldloca.s V_0 IL_000c: call ""bool System.ValueTuple<C, int>?.HasValue.get"" IL_0011: stloc.2 IL_0012: ldloc.2 IL_0013: ldloca.s V_1 IL_0015: call ""bool System.ValueTuple<int, C>?.HasValue.get"" IL_001a: beq.s IL_001f IL_001c: ldc.i4.0 IL_001d: br.s IL_0061 IL_001f: ldloc.2 IL_0020: brtrue.s IL_0025 IL_0022: ldc.i4.1 IL_0023: br.s IL_0061 IL_0025: ldloca.s V_0 IL_0027: call ""System.ValueTuple<C, int> System.ValueTuple<C, int>?.GetValueOrDefault()"" IL_002c: stloc.3 IL_002d: ldloca.s V_1 IL_002f: call ""System.ValueTuple<int, C> System.ValueTuple<int, C>?.GetValueOrDefault()"" IL_0034: stloc.s V_4 IL_0036: ldloc.3 IL_0037: ldfld ""C System.ValueTuple<C, int>.Item1"" IL_003c: call ""int C.op_Implicit(C)"" IL_0041: ldloc.s V_4 IL_0043: ldfld ""int System.ValueTuple<int, C>.Item1"" IL_0048: bne.un.s IL_0060 IL_004a: ldloc.3 IL_004b: ldfld ""int System.ValueTuple<C, int>.Item2"" IL_0050: ldloc.s V_4 IL_0052: ldfld ""C System.ValueTuple<int, C>.Item2"" IL_0057: call ""int C.op_Implicit(C)"" IL_005c: ceq IL_005e: br.s IL_0061 IL_0060: ldc.i4.0 IL_0061: box ""bool"" IL_0066: call ""string string.Format(string, object)"" IL_006b: call ""void System.Console.Write(string)"" IL_0070: nop IL_0071: ret }"); } [Fact] public void TestOnNullableVsNonNullableTuples() { var source = @" class C { public static void Main() { M(null); M((1, 2)); M((10, 20)); } private static void M((byte, int)? nt) { System.Console.Write((1, 2) == nt); } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "FalseTrueFalse"); verifier.VerifyIL("C.M", @"{ // Code size 53 (0x35) .maxstack 2 .locals init (System.ValueTuple<byte, int>? V_0, System.ValueTuple<byte, int> V_1) IL_0000: nop IL_0001: ldarg.0 IL_0002: stloc.0 IL_0003: ldloca.s V_0 IL_0005: call ""bool System.ValueTuple<byte, int>?.HasValue.get"" IL_000a: brtrue.s IL_000f IL_000c: ldc.i4.0 IL_000d: br.s IL_002e IL_000f: br.s IL_0011 IL_0011: ldloca.s V_0 IL_0013: call ""System.ValueTuple<byte, int> System.ValueTuple<byte, int>?.GetValueOrDefault()"" IL_0018: stloc.1 IL_0019: ldc.i4.1 IL_001a: ldloc.1 IL_001b: ldfld ""byte System.ValueTuple<byte, int>.Item1"" IL_0020: bne.un.s IL_002d IL_0022: ldc.i4.2 IL_0023: ldloc.1 IL_0024: ldfld ""int System.ValueTuple<byte, int>.Item2"" IL_0029: ceq IL_002b: br.s IL_002e IL_002d: ldc.i4.0 IL_002e: call ""void System.Console.Write(bool)"" IL_0033: nop IL_0034: ret }"); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var comparison = tree.GetCompilationUnitRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().Single(); var tuple = comparison.Left; var tupleType = model.GetTypeInfo(tuple); Assert.Equal("(1, 2)", tuple.ToString()); Assert.Equal("(System.Int32, System.Int32)", tupleType.Type.ToTestDisplayString()); Assert.Equal("(System.Int32, System.Int32)?", tupleType.ConvertedType.ToTestDisplayString()); var nt = comparison.Right; var ntType = model.GetTypeInfo(nt); Assert.Equal("nt", nt.ToString()); Assert.Equal("(System.Byte, System.Int32)?", ntType.Type.ToTestDisplayString()); Assert.Equal("(System.Int32, System.Int32)?", ntType.ConvertedType.ToTestDisplayString()); } [Fact] public void TestOnNullableVsNonNullableTuples_WithCustomConversion() { var source = @" class C { int _value; public C(int v) { _value = v; } public static void Main() { M(null); M((new C(1), 2)); M((new C(10), 20)); } private static void M((C, int)? nt) { System.Console.Write($""{(1, 2) == nt} ""); System.Console.Write($""{nt == (1, 2)} ""); } public static implicit operator int(C c) { System.Console.Write($""Convert{c._value} ""); return c._value; } }"; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "False False Convert1 True Convert1 True Convert10 False Convert10 False"); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var comparison = tree.GetCompilationUnitRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().First(); Assert.Equal("(1, 2) == nt", comparison.ToString()); var tuple = comparison.Left; var tupleType = model.GetTypeInfo(tuple); Assert.Equal("(1, 2)", tuple.ToString()); Assert.Equal("(System.Int32, System.Int32)", tupleType.Type.ToTestDisplayString()); Assert.Equal("(System.Int32, System.Int32)?", tupleType.ConvertedType.ToTestDisplayString()); var nt = comparison.Right; var ntType = model.GetTypeInfo(nt); Assert.Equal("nt", nt.ToString()); Assert.Equal("(C, System.Int32)?", ntType.Type.ToTestDisplayString()); Assert.Equal("(System.Int32, System.Int32)?", ntType.ConvertedType.ToTestDisplayString()); } [Fact] public void TestOnNullableVsNonNullableTuples3() { var source = @" class C { public static void Main() { M(null); M((1, 2)); M((10, 20)); } private static void M((int, int)? nt) { System.Console.Write(nt == (1, 2)); } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "FalseTrueFalse"); verifier.VerifyIL("C.M", @"{ // Code size 59 (0x3b) .maxstack 2 .locals init (System.ValueTuple<int, int>? V_0, bool V_1, System.ValueTuple<int, int> V_2) IL_0000: nop IL_0001: ldarg.0 IL_0002: stloc.0 IL_0003: ldloca.s V_0 IL_0005: call ""bool System.ValueTuple<int, int>?.HasValue.get"" IL_000a: stloc.1 IL_000b: ldloc.1 IL_000c: brtrue.s IL_0011 IL_000e: ldc.i4.0 IL_000f: br.s IL_0034 IL_0011: ldloc.1 IL_0012: brtrue.s IL_0017 IL_0014: ldc.i4.1 IL_0015: br.s IL_0034 IL_0017: ldloca.s V_0 IL_0019: call ""System.ValueTuple<int, int> System.ValueTuple<int, int>?.GetValueOrDefault()"" IL_001e: stloc.2 IL_001f: ldloc.2 IL_0020: ldfld ""int System.ValueTuple<int, int>.Item1"" IL_0025: ldc.i4.1 IL_0026: bne.un.s IL_0033 IL_0028: ldloc.2 IL_0029: ldfld ""int System.ValueTuple<int, int>.Item2"" IL_002e: ldc.i4.2 IL_002f: ceq IL_0031: br.s IL_0034 IL_0033: ldc.i4.0 IL_0034: call ""void System.Console.Write(bool)"" IL_0039: nop IL_003a: ret }"); } [Fact] public void TestOnNullableVsLiteralTuples() { var source = @" class C { public static void Main() { CheckNull(null); CheckNull((1, 2)); } private static void CheckNull((int, int)? nt) { System.Console.Write($""{nt == null} ""); System.Console.Write($""{nt != null} ""); } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "True False False True"); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var lastNull = tree.GetCompilationUnitRoot().DescendantNodes().OfType<LiteralExpressionSyntax>().Last(); Assert.Equal("null", lastNull.ToString()); var nullType = model.GetTypeInfo(lastNull); Assert.Null(nullType.Type); Assert.Null(nullType.ConvertedType); // In nullable-null comparison, the null literal remains typeless } [Fact] public void TestOnLongTuple() { var source = @" class C { public static void Main() { Assert(MakeLongTuple(1) == MakeLongTuple(1)); Assert(!(MakeLongTuple(1) != MakeLongTuple(1))); Assert(MakeLongTuple(1) == (1, 1, 1, 1, 1, 1, 1, 1, 1)); Assert(!(MakeLongTuple(1) != (1, 1, 1, 1, 1, 1, 1, 1, 1))); Assert(MakeLongTuple(1) == MakeLongTuple(1, 1)); Assert(!(MakeLongTuple(1) != MakeLongTuple(1, 1))); Assert(!(MakeLongTuple(1) == MakeLongTuple(1, 2))); Assert(!(MakeLongTuple(1) == MakeLongTuple(2, 1))); Assert(MakeLongTuple(1) != MakeLongTuple(1, 2)); Assert(MakeLongTuple(1) != MakeLongTuple(2, 1)); System.Console.Write(""Success""); } private static (int, int, int, int, int, int, int, int, int) MakeLongTuple(int x) => (x, x, x, x, x, x, x, x, x); private static (int?, int, int?, int, int?, int, int?, int, int?)? MakeLongTuple(int? x, int y) => (x, y, x, y, x, y, x, y, x); private static void Assert(bool test) { if (!test) { throw null; } } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "Success"); } [Fact] public void TestOn1Tuple_FromRest() { var source = @" class C { public static bool M() { var x1 = MakeLongTuple(1).Rest; bool b1 = x1 == x1; bool b2 = x1 != x1; return b1 && b2; } private static (int, int, int, int, int, int, int, int?) MakeLongTuple(int? x) => throw null; public bool Unused((int, int, int, int, int, int, int, int?) t) { return t.Rest == t.Rest; } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (8,19): error CS0019: Operator '==' cannot be applied to operands of type 'ValueTuple<int?>' and 'ValueTuple<int?>' // bool b1 = x1 == x1; Diagnostic(ErrorCode.ERR_BadBinaryOps, "x1 == x1").WithArguments("==", "System.ValueTuple<int?>", "System.ValueTuple<int?>").WithLocation(8, 19), // (9,19): error CS0019: Operator '!=' cannot be applied to operands of type 'ValueTuple<int?>' and 'ValueTuple<int?>' // bool b2 = x1 != x1; Diagnostic(ErrorCode.ERR_BadBinaryOps, "x1 != x1").WithArguments("!=", "System.ValueTuple<int?>", "System.ValueTuple<int?>").WithLocation(9, 19), // (18,16): error CS0019: Operator '==' cannot be applied to operands of type 'ValueTuple<int?>' and 'ValueTuple<int?>' // return t.Rest == t.Rest; Diagnostic(ErrorCode.ERR_BadBinaryOps, "t.Rest == t.Rest").WithArguments("==", "System.ValueTuple<int?>", "System.ValueTuple<int?>").WithLocation(18, 16) ); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var comparison = tree.GetRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().Last(); Assert.Equal("t.Rest == t.Rest", comparison.ToString()); var left = model.GetTypeInfo(comparison.Left); Assert.Equal("System.ValueTuple<System.Int32?>", left.Type.ToTestDisplayString()); Assert.Equal("System.ValueTuple<System.Int32?>", left.ConvertedType.ToTestDisplayString()); Assert.True(left.Type.IsTupleType); } [Fact] public void TestOn1Tuple_FromValueTuple() { var source = @" using System; class C { public static bool M() { var x1 = ValueTuple.Create((int?)1); bool b1 = x1 == x1; bool b2 = x1 != x1; return b1 && b2; } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (9,19): error CS0019: Operator '==' cannot be applied to operands of type 'ValueTuple<int?>' and 'ValueTuple<int?>' // bool b1 = x1 == x1; Diagnostic(ErrorCode.ERR_BadBinaryOps, "x1 == x1").WithArguments("==", "System.ValueTuple<int?>", "System.ValueTuple<int?>").WithLocation(9, 19), // (10,19): error CS0019: Operator '!=' cannot be applied to operands of type 'ValueTuple<int?>' and 'ValueTuple<int?>' // bool b2 = x1 != x1; Diagnostic(ErrorCode.ERR_BadBinaryOps, "x1 != x1").WithArguments("!=", "System.ValueTuple<int?>", "System.ValueTuple<int?>").WithLocation(10, 19) ); } [Fact] public void TestOnTupleOfDecimals() { var source = @" class C { public static void Main() { System.Console.Write(Compare((1, 2), (1, 2))); System.Console.Write(Compare((1, 2), (10, 20))); } public static bool Compare((decimal, decimal) t1, (decimal, decimal) t2) { return t1 == t2; } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "TrueFalse"); verifier.VerifyIL("C.Compare", @"{ // Code size 49 (0x31) .maxstack 2 .locals init (System.ValueTuple<decimal, decimal> V_0, System.ValueTuple<decimal, decimal> V_1, bool V_2) IL_0000: nop IL_0001: ldarg.0 IL_0002: stloc.0 IL_0003: ldarg.1 IL_0004: stloc.1 IL_0005: ldloc.0 IL_0006: ldfld ""decimal System.ValueTuple<decimal, decimal>.Item1"" IL_000b: ldloc.1 IL_000c: ldfld ""decimal System.ValueTuple<decimal, decimal>.Item1"" IL_0011: call ""bool decimal.op_Equality(decimal, decimal)"" IL_0016: brfalse.s IL_002b IL_0018: ldloc.0 IL_0019: ldfld ""decimal System.ValueTuple<decimal, decimal>.Item2"" IL_001e: ldloc.1 IL_001f: ldfld ""decimal System.ValueTuple<decimal, decimal>.Item2"" IL_0024: call ""bool decimal.op_Equality(decimal, decimal)"" IL_0029: br.s IL_002c IL_002b: ldc.i4.0 IL_002c: stloc.2 IL_002d: br.s IL_002f IL_002f: ldloc.2 IL_0030: ret }"); } [Fact] public void TestSideEffectsAreSavedToTemps() { var source = @" class C { public static void Main() { int i = 0; System.Console.Write((i++, i++, i++) == (0, 1, 2)); } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "True"); } [Fact] public void TestNonBoolComparisonResult_WithTrueFalseOperators() { var source = @" using static System.Console; public class C { public static void Main() { Write($""{REPLACE}""); } } public class Base { public int I; public Base(int i) { I = i; } } public class A : Base { public A(int i) : base(i) { Write($""A:{i}, ""); } public static NotBool operator ==(A a, Y y) { Write(""A == Y, ""); return new NotBool(a.I == y.I); } public static NotBool operator !=(A a, Y y) { Write(""A != Y, ""); return new NotBool(a.I != y.I); } public override bool Equals(object o) => throw null; public override int GetHashCode() => throw null; } public class X : Base { public X(int i) : base(i) { Write($""X:{i}, ""); } } public class Y : Base { public Y(int i) : base(i) { Write($""Y:{i}, ""); } public static implicit operator Y(X x) { Write(""X -> ""); return new Y(x.I); } } public class NotBool { public bool B; public NotBool(bool value) { B = value; } public static bool operator true(NotBool b) { Write($""NotBool.true -> {b.B}, ""); return b.B; } public static bool operator false(NotBool b) { Write($""NotBool.false -> {!b.B}, ""); return !b.B; } } "; validate("(new A(1), new A(2)) == (new X(1), new Y(2))", "A:1, A:2, X:1, Y:2, X -> Y:1, A == Y, NotBool.false -> False, A == Y, NotBool.false -> False, True"); validate("(new A(1), new A(2)) == (new X(1), new Y(20))", "A:1, A:2, X:1, Y:20, X -> Y:1, A == Y, NotBool.false -> False, A == Y, NotBool.false -> True, False"); validate("(new A(1), new A(2)) != (new X(1), new Y(2))", "A:1, A:2, X:1, Y:2, X -> Y:1, A != Y, NotBool.true -> False, A != Y, NotBool.true -> False, False"); validate("(new A(1), new A(2)) != (new X(1), new Y(20))", "A:1, A:2, X:1, Y:20, X -> Y:1, A != Y, NotBool.true -> False, A != Y, NotBool.true -> True, True"); validate("((dynamic)new A(1), new A(2)) == (new X(1), (dynamic)new Y(2))", "A:1, A:2, X:1, Y:2, X -> Y:1, A == Y, NotBool.false -> False, A == Y, NotBool.false -> False, True"); validate("((dynamic)new A(1), new A(2)) == (new X(1), (dynamic)new Y(20))", "A:1, A:2, X:1, Y:20, X -> Y:1, A == Y, NotBool.false -> False, A == Y, NotBool.false -> True, False"); validate("((dynamic)new A(1), new A(2)) != (new X(1), (dynamic)new Y(2))", "A:1, A:2, X:1, Y:2, X -> Y:1, A != Y, NotBool.true -> False, A != Y, NotBool.true -> False, False"); validate("((dynamic)new A(1), new A(2)) != (new X(1), (dynamic)new Y(20))", "A:1, A:2, X:1, Y:20, X -> Y:1, A != Y, NotBool.true -> False, A != Y, NotBool.true -> True, True"); void validate(string expression, string expected) { var comp = CreateCompilation(source.Replace("REPLACE", expression), targetFramework: TargetFramework.StandardAndCSharp, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: expected); } } [Fact] public void TestNonBoolComparisonResult_WithTrueFalseOperatorsOnBase() { var source = @" using static System.Console; public class C { public static void Main() { Write($""{REPLACE}""); } } public class Base { public int I; public Base(int i) { I = i; } } public class A : Base { public A(int i) : base(i) { Write($""A:{i}, ""); } public static NotBool operator ==(A a, Y y) { Write(""A == Y, ""); return new NotBool(a.I == y.I); } public static NotBool operator !=(A a, Y y) { Write(""A != Y, ""); return new NotBool(a.I != y.I); } public override bool Equals(object o) => throw null; public override int GetHashCode() => throw null; } public class X : Base { public X(int i) : base(i) { Write($""X:{i}, ""); } } public class Y : Base { public Y(int i) : base(i) { Write($""Y:{i}, ""); } public static implicit operator Y(X x) { Write(""X -> ""); return new Y(x.I); } } public class NotBoolBase { public bool B; public NotBoolBase(bool value) { B = value; } public static bool operator true(NotBoolBase b) { Write($""NotBoolBase.true -> {b.B}, ""); return b.B; } public static bool operator false(NotBoolBase b) { Write($""NotBoolBase.false -> {!b.B}, ""); return !b.B; } } public class NotBool : NotBoolBase { public NotBool(bool value) : base(value) { } } "; // This tests the case where the custom operators false/true need an input conversion that's not just an identity conversion (in this case, it's an implicit reference conversion) validate("(new A(1), new A(2)) == (new X(1), new Y(2))", "A:1, A:2, X:1, Y:2, X -> Y:1, A == Y, NotBoolBase.false -> False, A == Y, NotBoolBase.false -> False, True"); validate("(new A(1), new A(2)) == (new X(1), new Y(20))", "A:1, A:2, X:1, Y:20, X -> Y:1, A == Y, NotBoolBase.false -> False, A == Y, NotBoolBase.false -> True, False"); validate("(new A(1), new A(2)) != (new X(1), new Y(2))", "A:1, A:2, X:1, Y:2, X -> Y:1, A != Y, NotBoolBase.true -> False, A != Y, NotBoolBase.true -> False, False"); validate("(new A(1), new A(2)) != (new X(1), new Y(20))", "A:1, A:2, X:1, Y:20, X -> Y:1, A != Y, NotBoolBase.true -> False, A != Y, NotBoolBase.true -> True, True"); validate("((dynamic)new A(1), new A(2)) == (new X(1), (dynamic)new Y(2))", "A:1, A:2, X:1, Y:2, X -> Y:1, A == Y, NotBoolBase.false -> False, A == Y, NotBoolBase.false -> False, True"); validate("((dynamic)new A(1), new A(2)) == (new X(1), (dynamic)new Y(20))", "A:1, A:2, X:1, Y:20, X -> Y:1, A == Y, NotBoolBase.false -> False, A == Y, NotBoolBase.false -> True, False"); validate("((dynamic)new A(1), new A(2)) != (new X(1), (dynamic)new Y(2))", "A:1, A:2, X:1, Y:2, X -> Y:1, A != Y, NotBoolBase.true -> False, A != Y, NotBoolBase.true -> False, False"); validate("((dynamic)new A(1), new A(2)) != (new X(1), (dynamic)new Y(20))", "A:1, A:2, X:1, Y:20, X -> Y:1, A != Y, NotBoolBase.true -> False, A != Y, NotBoolBase.true -> True, True"); void validate(string expression, string expected) { var comp = CreateCompilation(source.Replace("REPLACE", expression), targetFramework: TargetFramework.StandardAndCSharp, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: expected); } } [Fact] public void TestNonBoolComparisonResult_WithImplicitBoolConversion() { var source = @" using static System.Console; public class C { public static void Main() { Write($""{REPLACE}""); } } public class Base { public int I; public Base(int i) { I = i; } } public class A : Base { public A(int i) : base(i) { Write($""A:{i}, ""); } public static NotBool operator ==(A a, Y y) { Write(""A == Y, ""); return new NotBool(a.I == y.I); } public static NotBool operator !=(A a, Y y) { Write(""A != Y, ""); return new NotBool(a.I != y.I); } public override bool Equals(object o) => throw null; public override int GetHashCode() => throw null; } public class X : Base { public X(int i) : base(i) { Write($""X:{i}, ""); } } public class Y : Base { public Y(int i) : base(i) { Write($""Y:{i}, ""); } public static implicit operator Y(X x) { Write(""X -> ""); return new Y(x.I); } } public class NotBool { public bool B; public NotBool(bool value) { B = value; } public static implicit operator bool(NotBool b) { Write($""NotBool -> bool:{b.B}, ""); return b.B; } } "; validate("(new A(1), new A(2)) == (new X(1), new Y(2))", "A:1, A:2, X:1, Y:2, X -> Y:1, A == Y, NotBool -> bool:True, A == Y, NotBool -> bool:True, True"); validate("(new A(1), new A(2)) == (new X(10), new Y(2))", "A:1, A:2, X:10, Y:2, X -> Y:10, A == Y, NotBool -> bool:False, False"); validate("(new A(1), new A(2)) == (new X(1), new Y(20))", "A:1, A:2, X:1, Y:20, X -> Y:1, A == Y, NotBool -> bool:True, A == Y, NotBool -> bool:False, False"); validate("(new A(1), new A(2)) != (new X(1), new Y(2))", "A:1, A:2, X:1, Y:2, X -> Y:1, A != Y, NotBool -> bool:False, A != Y, NotBool -> bool:False, False"); validate("(new A(1), new A(2)) != (new X(10), new Y(2))", "A:1, A:2, X:10, Y:2, X -> Y:10, A != Y, NotBool -> bool:True, True"); validate("(new A(1), new A(2)) != (new X(1), new Y(20))", "A:1, A:2, X:1, Y:20, X -> Y:1, A != Y, NotBool -> bool:False, A != Y, NotBool -> bool:True, True"); void validate(string expression, string expected) { var comp = CreateCompilation(source.Replace("REPLACE", expression), options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: expected); } } [Fact] public void TestNonBoolComparisonResult_WithoutImplicitBoolConversion() { var source = @" using static System.Console; public class C { public static void Main() { Write($""{REPLACE}""); } } public class Base { public Base(int i) { } } public class A : Base { public A(int i) : base(i) => throw null; public static NotBool operator ==(A a, Y y) => throw null; public static NotBool operator !=(A a, Y y) => throw null; public override bool Equals(object o) => throw null; public override int GetHashCode() => throw null; } public class X : Base { public X(int i) : base(i) => throw null; } public class Y : Base { public Y(int i) : base(i) => throw null; public static implicit operator Y(X x) => throw null; } public class NotBool { } "; validate("(new A(1), new A(2)) == (new X(1), new Y(2))", // (7,18): error CS0029: Cannot implicitly convert type 'NotBool' to 'bool' // Write($"{(new A(1), new A(2)) == (new X(1), new Y(2))}"); Diagnostic(ErrorCode.ERR_NoImplicitConv, "(new A(1), new A(2)) == (new X(1), new Y(2))").WithArguments("NotBool", "bool").WithLocation(7, 18), // (7,18): error CS0029: Cannot implicitly convert type 'NotBool' to 'bool' // Write($"{(new A(1), new A(2)) == (new X(1), new Y(2))}"); Diagnostic(ErrorCode.ERR_NoImplicitConv, "(new A(1), new A(2)) == (new X(1), new Y(2))").WithArguments("NotBool", "bool").WithLocation(7, 18) ); validate("(new A(1), 2) != (new X(1), 2)", // (7,18): error CS0029: Cannot implicitly convert type 'NotBool' to 'bool' // Write($"{(new A(1), 2) != (new X(1), 2)}"); Diagnostic(ErrorCode.ERR_NoImplicitConv, "(new A(1), 2) != (new X(1), 2)").WithArguments("NotBool", "bool").WithLocation(7, 18) ); void validate(string expression, params DiagnosticDescription[] expected) { var comp = CreateCompilation(source.Replace("REPLACE", expression)); comp.VerifyDiagnostics(expected); } } [Fact] public void TestNonBoolComparisonResult_WithExplicitBoolConversion() { var source = @" using static System.Console; public class C { public static void Main() { Write($""{(new A(1), new A(2)) == (new X(1), new Y(2))}""); } } public class Base { public int I; public Base(int i) { I = i; } } public class A : Base { public A(int i) : base(i) => throw null; public static NotBool operator ==(A a, Y y) => throw null; public static NotBool operator !=(A a, Y y) => throw null; public override bool Equals(object o) => throw null; public override int GetHashCode() => throw null; } public class X : Base { public X(int i) : base(i) => throw null; } public class Y : Base { public Y(int i) : base(i) => throw null; public static implicit operator Y(X x) => throw null; } public class NotBool { public NotBool(bool value) => throw null; public static explicit operator bool(NotBool b) => throw null; } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (7,18): error CS0029: Cannot implicitly convert type 'NotBool' to 'bool' // Write($"{(new A(1), new A(2)) == (new X(1), new Y(2))}"); Diagnostic(ErrorCode.ERR_NoImplicitConv, "(new A(1), new A(2)) == (new X(1), new Y(2))").WithArguments("NotBool", "bool").WithLocation(7, 18), // (7,18): error CS0029: Cannot implicitly convert type 'NotBool' to 'bool' // Write($"{(new A(1), new A(2)) == (new X(1), new Y(2))}"); Diagnostic(ErrorCode.ERR_NoImplicitConv, "(new A(1), new A(2)) == (new X(1), new Y(2))").WithArguments("NotBool", "bool").WithLocation(7, 18) ); } [Fact] public void TestNullableBoolComparisonResult_WithTrueFalseOperators() { var source = @" public class C { public static void M(A a) { _ = (a, a) == (a, a); if (a == a) { } } } public class A { public A(int i) => throw null; public static bool? operator ==(A a1, A a2) => throw null; public static bool? operator !=(A a1, A a2) => throw null; public override bool Equals(object o) => throw null; public override int GetHashCode() => throw null; } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,13): error CS0029: Cannot implicitly convert type 'bool?' to 'bool' // _ = (a, a) == (a, a); Diagnostic(ErrorCode.ERR_NoImplicitConv, "(a, a) == (a, a)").WithArguments("bool?", "bool").WithLocation(6, 13), // (6,13): error CS0029: Cannot implicitly convert type 'bool?' to 'bool' // _ = (a, a) == (a, a); Diagnostic(ErrorCode.ERR_NoImplicitConv, "(a, a) == (a, a)").WithArguments("bool?", "bool").WithLocation(6, 13), // (7,13): error CS0266: Cannot implicitly convert type 'bool?' to 'bool'. An explicit conversion exists (are you missing a cast?) // if (a == a) { } Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "a == a").WithArguments("bool?", "bool").WithLocation(7, 13), // (7,13): warning CS1718: Comparison made to same variable; did you mean to compare something else? // if (a == a) { } Diagnostic(ErrorCode.WRN_ComparisonToSelf, "a == a").WithLocation(7, 13) ); } [Fact] public void TestElementNames() { var source = @" #pragma warning disable CS0219 using static System.Console; public class C { public static void Main() { int a = 1; int b = 2; int c = 3; int d = 4; int x = 5; int y = 6; (int x, int y) t1 = (1, 2); (int, int) t2 = (1, 2); Write($""{REPLACE}""); } } "; // tuple expression vs tuple expression validate("t1 == t2"); // tuple expression vs tuple literal validate("t1 == (x: 1, y: 2)"); validate("t1 == (1, 2)"); validate("(1, 2) == t1"); validate("(x: 1, d) == t1"); validate("t2 == (x: 1, y: 2)", // (16,25): warning CS8375: The tuple element name 'x' is ignored because a different name or no name is specified on the other side of the tuple == or != operator. // Write($"{t2 == (x: 1, y: 2)}"); Diagnostic(ErrorCode.WRN_TupleBinopLiteralNameMismatch, "x: 1").WithArguments("x").WithLocation(16, 25), // (16,31): warning CS8375: The tuple element name 'y' is ignored because a different name or no name is specified on the other side of the tuple == or != operator. // Write($"{t2 == (x: 1, y: 2)}"); Diagnostic(ErrorCode.WRN_TupleBinopLiteralNameMismatch, "y: 2").WithArguments("y").WithLocation(16, 31) ); // tuple literal vs tuple literal // - warnings reported on the right when both sides could complain // - no warnings on inferred names validate("((a, b), c: 3) == ((1, x: 2), 3)", // (16,27): warning CS8375: The tuple element name 'c' is ignored because a different name or no name is specified on the other side of the tuple == or != operator. // Write($"{((a, b), c: 3) == ((1, x: 2), 3)}"); Diagnostic(ErrorCode.WRN_TupleBinopLiteralNameMismatch, "c: 3").WithArguments("c").WithLocation(16, 27), // (16,41): warning CS8375: The tuple element name 'x' is ignored because a different name or no name is specified on the other side of the tuple == or != operator. // Write($"{((a, b), c: 3) == ((1, x: 2), 3)}"); Diagnostic(ErrorCode.WRN_TupleBinopLiteralNameMismatch, "x: 2").WithArguments("x").WithLocation(16, 41) ); validate("(a, b) == (a: 1, b: 2)"); validate("(a, b) == (c: 1, d)", // (16,29): warning CS8375: The tuple element name 'c' is ignored because a different name or no name is specified on the other side of the tuple == or != operator. // Write($"{(a, b) == (c: 1, d)}"); Diagnostic(ErrorCode.WRN_TupleBinopLiteralNameMismatch, "c: 1").WithArguments("c").WithLocation(16, 29) ); validate("(a: 1, b: 2) == (c: 1, d)", // (16,35): warning CS8375: The tuple element name 'c' is ignored because a different name or no name is specified on the other side of the tuple == or != operator. // Write($"{(a: 1, b: 2) == (c: 1, d)}"); Diagnostic(ErrorCode.WRN_TupleBinopLiteralNameMismatch, "c: 1").WithArguments("c").WithLocation(16, 35), // (16,25): warning CS8375: The tuple element name 'b' is ignored because a different name or no name is specified on the other side of the tuple == or != operator. // Write($"{(a: 1, b: 2) == (c: 1, d)}"); Diagnostic(ErrorCode.WRN_TupleBinopLiteralNameMismatch, "b: 2").WithArguments("b").WithLocation(16, 25) ); validate("(null, b) == (c: null, d: 2)", // (16,32): warning CS8375: The tuple element name 'c' is ignored because a different name or no name is specified on the other side of the tuple == or != operator. // Write($"{(null, b) == (c: null, d: 2)}"); Diagnostic(ErrorCode.WRN_TupleBinopLiteralNameMismatch, "c: null").WithArguments("c").WithLocation(16, 32), // (16,41): warning CS8375: The tuple element name 'd' is ignored because a different name or no name is specified on the other side of the tuple == or != operator. // Write($"{(null, b) == (c: null, d: 2)}"); Diagnostic(ErrorCode.WRN_TupleBinopLiteralNameMismatch, "d: 2").WithArguments("d").WithLocation(16, 41) ); void validate(string expression, params DiagnosticDescription[] diagnostics) { var comp = CreateCompilation(source.Replace("REPLACE", expression)); comp.VerifyDiagnostics(diagnostics); } } [Fact] void TestValueTupleWithObsoleteEqualityOperator() { string source = @" public class C { public static void Main() { System.Console.Write((1, 2) == (3, 4)); } } 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; } [System.Obsolete] public static bool operator==(ValueTuple<T1, T2> t1, ValueTuple<T1, T2> t2) => throw null; public static bool operator!=(ValueTuple<T1, T2> t1, ValueTuple<T1, T2> t2) => throw null; public override bool Equals(object other) => throw null; public override int GetHashCode() => throw null; } } "; var comp = CreateCompilationWithMscorlib40(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); // Note: tuple equality picked ahead of custom operator== CompileAndVerify(comp, expectedOutput: "False"); } [Fact] public void TestInExpressionTree() { var source = @" using System; using System.Linq.Expressions; public class C { public static void Main() { Expression<Func<int, bool>> expr = i => (i, i) == (i, i); Expression<Func<(int, int), bool>> expr2 = t => t != t; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (8,49): error CS8374: An expression tree may not contain a tuple == or != operator // Expression<Func<int, bool>> expr = i => (i, i) == (i, i); Diagnostic(ErrorCode.ERR_ExpressionTreeContainsTupleBinOp, "(i, i) == (i, i)").WithLocation(8, 49), // (8,49): error CS8143: An expression tree may not contain a tuple literal. // Expression<Func<int, bool>> expr = i => (i, i) == (i, i); Diagnostic(ErrorCode.ERR_ExpressionTreeContainsTupleLiteral, "(i, i)").WithLocation(8, 49), // (8,59): error CS8143: An expression tree may not contain a tuple literal. // Expression<Func<int, bool>> expr = i => (i, i) == (i, i); Diagnostic(ErrorCode.ERR_ExpressionTreeContainsTupleLiteral, "(i, i)").WithLocation(8, 59), // (9,57): error CS8374: An expression tree may not contain a tuple == or != operator // Expression<Func<(int, int), bool>> expr2 = t => t != t; Diagnostic(ErrorCode.ERR_ExpressionTreeContainsTupleBinOp, "t != t").WithLocation(9, 57) ); } [Fact] public void TestComparisonOfDynamicAndTuple() { var source = @" public class C { (long, string) _t; public C(long l, string s) { _t = (l, s); } public static void Main() { dynamic d = new C(1, ""hello""); (long, string) tuple1 = (1, ""hello""); (long, string) tuple2 = (2, ""world""); System.Console.Write($""{d == tuple1} {d != tuple1} {d == tuple2} {d != tuple2}""); } public static bool operator==(C c, (long, string) t) { return c._t.Item1 == t.Item1 && c._t.Item2 == t.Item2; } public static bool operator!=(C c, (long, string) t) { return !(c == t); } public override bool Equals(object o) => throw null; public override int GetHashCode() => throw null; } "; var comp = CreateCompilation(source, targetFramework: TargetFramework.StandardAndCSharp, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "True False False True"); } [Fact] public void TestComparisonOfDynamicTuple() { var source = @" public class C { public static void Main() { dynamic d1 = (1, ""hello""); dynamic d2 = (1, ""hello""); dynamic d3 = ((byte)1, 2); PrintException(() => d1 == d2); PrintException(() => d1 == d3); } public static void PrintException(System.Func<bool> action) { System.Globalization.CultureInfo saveUICulture = System.Threading.Thread.CurrentThread.CurrentUICulture; System.Threading.Thread.CurrentThread.CurrentUICulture = System.Globalization.CultureInfo.InvariantCulture; try { action(); } catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e) { System.Console.WriteLine(e.Message); } finally { System.Threading.Thread.CurrentThread.CurrentUICulture = saveUICulture; } } } "; var comp = CreateCompilation(source, targetFramework: TargetFramework.StandardAndCSharp, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: @"Operator '==' cannot be applied to operands of type 'System.ValueTuple<int,string>' and 'System.ValueTuple<int,string>' Operator '==' cannot be applied to operands of type 'System.ValueTuple<int,string>' and 'System.ValueTuple<byte,int>'"); } [Fact] public void TestComparisonWithTupleElementNames() { var source = @" public class C { public static void Main() { int Bob = 1; System.Console.Write((Alice: 0, (Bob, 2)) == (Bob: 0, (1, Other: 2))); } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics( // (7,55): warning CS8375: The tuple element name 'Bob' is ignored because a different name or no name is specified on the other side of the tuple == or != operator. // System.Console.Write((Alice: 0, (Bob, 2)) == (Bob: 0, (1, Other: 2))); Diagnostic(ErrorCode.WRN_TupleBinopLiteralNameMismatch, "Bob: 0").WithArguments("Bob").WithLocation(7, 55), // (7,67): warning CS8375: The tuple element name 'Other' is ignored because a different name or no name is specified on the other side of the tuple == or != operator. // System.Console.Write((Alice: 0, (Bob, 2)) == (Bob: 0, (1, Other: 2))); Diagnostic(ErrorCode.WRN_TupleBinopLiteralNameMismatch, "Other: 2").WithArguments("Other").WithLocation(7, 67) ); CompileAndVerify(comp, expectedOutput: "True"); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var equals = tree.GetCompilationUnitRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().First(); // check left tuple var leftTuple = equals.Left; var leftInfo = model.GetTypeInfo(leftTuple); Assert.Equal("(System.Int32 Alice, (System.Int32 Bob, System.Int32))", leftInfo.Type.ToTestDisplayString()); Assert.Equal("(System.Int32 Alice, (System.Int32 Bob, System.Int32))", leftInfo.ConvertedType.ToTestDisplayString()); // check right tuple var rightTuple = equals.Right; var rightInfo = model.GetTypeInfo(rightTuple); Assert.Equal("(System.Int32 Bob, (System.Int32, System.Int32 Other))", rightInfo.Type.ToTestDisplayString()); Assert.Equal("(System.Int32 Bob, (System.Int32, System.Int32 Other))", rightInfo.ConvertedType.ToTestDisplayString()); } [Fact] public void TestComparisonWithCastedTuples() { var source = @" public class C { public static void Main() { System.Console.Write( ((string, (byte, long))) (null, (1, 2L)) == ((string, (long, byte))) (null, (1L, 2)) ); } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "True"); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var equals = tree.GetCompilationUnitRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().First(); // check left cast ... var leftCast = (CastExpressionSyntax)equals.Left; Assert.Equal("((string, (byte, long))) (null, (1, 2L))", leftCast.ToString()); var leftCastInfo = model.GetTypeInfo(leftCast); Assert.Equal("(System.String, (System.Byte, System.Int64))", leftCastInfo.Type.ToTestDisplayString()); Assert.Equal("(System.String, (System.Int64, System.Int64))", leftCastInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.ImplicitTuple, model.GetConversion(leftCast).Kind); // ... its tuple ... var leftTuple = (TupleExpressionSyntax)leftCast.Expression; Assert.Equal("(null, (1, 2L))", leftTuple.ToString()); var leftTupleInfo = model.GetTypeInfo(leftTuple); Assert.Null(leftTupleInfo.Type); Assert.Equal("(System.String, (System.Byte, System.Int64))", leftTupleInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.ExplicitTupleLiteral, model.GetConversion(leftTuple).Kind); // ... its null ... var leftNull = leftTuple.Arguments[0].Expression; Assert.Equal("null", leftNull.ToString()); var leftNullInfo = model.GetTypeInfo(leftNull); Assert.Null(leftNullInfo.Type); Assert.Equal("System.String", leftNullInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.ImplicitReference, model.GetConversion(leftNull).Kind); // ... its nested tuple var leftNestedTuple = leftTuple.Arguments[1].Expression; Assert.Equal("(1, 2L)", leftNestedTuple.ToString()); var leftNestedTupleInfo = model.GetTypeInfo(leftNestedTuple); Assert.Equal("(System.Int32, System.Int64)", leftNestedTupleInfo.Type.ToTestDisplayString()); Assert.Equal("(System.Byte, System.Int64)", leftNestedTupleInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.Identity, model.GetConversion(leftNestedTuple).Kind); // check right cast ... var rightCast = (CastExpressionSyntax)equals.Right; var rightCastInfo = model.GetTypeInfo(rightCast); Assert.Equal("(System.String, (System.Int64, System.Byte))", rightCastInfo.Type.ToTestDisplayString()); Assert.Equal("(System.String, (System.Int64, System.Int64))", rightCastInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.ImplicitTuple, model.GetConversion(rightCast).Kind); // ... its tuple var rightTuple = rightCast.Expression; var rightTupleInfo = model.GetTypeInfo(rightTuple); Assert.Null(rightTupleInfo.Type); Assert.Equal("(System.String, (System.Int64, System.Byte))", rightTupleInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.ExplicitTupleLiteral, model.GetConversion(rightTuple).Kind); } [Fact] public void TestGenericElement() { var source = @" public class C { public void M<T>(T t) { _ = (t, t) == (t, t); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,13): error CS0019: Operator '==' cannot be applied to operands of type 'T' and 'T' // _ = (t, t) == (t, t); Diagnostic(ErrorCode.ERR_BadBinaryOps, "(t, t) == (t, t)").WithArguments("==", "T", "T").WithLocation(6, 13), // (6,13): error CS0019: Operator '==' cannot be applied to operands of type 'T' and 'T' // _ = (t, t) == (t, t); Diagnostic(ErrorCode.ERR_BadBinaryOps, "(t, t) == (t, t)").WithArguments("==", "T", "T").WithLocation(6, 13) ); } [Fact] public void TestNameofEquality() { var source = @" public class C { public void M() { _ = nameof((1, 2) == (3, 4)); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,20): error CS8081: Expression does not have a name. // _ = nameof((1, 2) == (3, 4)); Diagnostic(ErrorCode.ERR_ExpressionHasNoName, "(1, 2) == (3, 4)").WithLocation(6, 20) ); } [Fact] public void TestAsRefOrOutArgument() { var source = @" public class C { public void M(ref bool x, out bool y) { x = true; y = true; M(ref (1, 2) == (3, 4), out (1, 2) == (3, 4)); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (8,15): error CS1510: A ref or out value must be an assignable variable // M(ref (1, 2) == (3, 4), out (1, 2) == (3, 4)); Diagnostic(ErrorCode.ERR_RefLvalueExpected, "(1, 2) == (3, 4)").WithLocation(8, 15), // (8,37): error CS1510: A ref or out value must be an assignable variable // M(ref (1, 2) == (3, 4), out (1, 2) == (3, 4)); Diagnostic(ErrorCode.ERR_RefLvalueExpected, "(1, 2) == (3, 4)").WithLocation(8, 37) ); } [Fact] public void TestWithAnonymousTypes() { var source = @" public class C { public static void Main() { var a = new { A = 1 }; var b = new { B = 2 }; var c = new { A = 1 }; var d = new { B = 2 }; System.Console.Write((a, b) == (a, b)); System.Console.Write((a, b) == (c, d)); System.Console.Write((a, b) != (c, d)); } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "TrueFalseTrue"); } [Fact] public void TestWithAnonymousTypes2() { var source = @" public class C { public static void Main() { var a = new { A = 1 }; var b = new { B = 2 }; System.Console.Write((a, b) == (b, a)); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (9,30): error CS0019: Operator '==' cannot be applied to operands of type '<anonymous type: int A>' and '<anonymous type: int B>' // System.Console.Write((a, b) == (b, a)); Diagnostic(ErrorCode.ERR_BadBinaryOps, "(a, b) == (b, a)").WithArguments("==", "<anonymous type: int A>", "<anonymous type: int B>").WithLocation(9, 30), // (9,30): error CS0019: Operator '==' cannot be applied to operands of type '<anonymous type: int B>' and '<anonymous type: int A>' // System.Console.Write((a, b) == (b, a)); Diagnostic(ErrorCode.ERR_BadBinaryOps, "(a, b) == (b, a)").WithArguments("==", "<anonymous type: int B>", "<anonymous type: int A>").WithLocation(9, 30) ); } [Fact] public void TestRefReturningElements() { var source = @" public class C { public static void Main() { System.Console.Write((P, S()) == (1, ""hello"")); } public static int p = 1; public static ref int P => ref p; public static string s = ""hello""; public static ref string S() => ref s; } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "True"); } [Fact] public void TestChecked() { var source = @" public class C { public static void Main() { try { checked { int ten = 10; System.Console.Write((2147483647 + ten, 1) == (0, 1)); } } catch (System.OverflowException) { System.Console.Write(""overflow""); } } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "overflow"); } [Fact] public void TestUnchecked() { var source = @" public class C { public static void Main() { unchecked { int ten = 10; System.Console.Write((2147483647 + ten, 1) == (-2147483639, 1)); } } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "True"); } [Fact] public void TestInQuery() { var source = @" using System.Linq; public class C { public static void Main() { var query = from a in new int[] { 1, 2, 2} where (a, 2) == (2, a) select a; foreach (var i in query) { System.Console.Write(i); } } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "22"); } [Fact] public void TestWithPointer() { var source = @" public class C { public unsafe static void M() { int x = 234; int y = 236; int* p1 = &x; int* p2 = &y; _ = (p1, p2) == (p1, p2); } } "; var comp = CreateCompilation(source, options: TestOptions.UnsafeDebugDll); comp.VerifyDiagnostics( // (10,14): error CS0306: The type 'int*' may not be used as a type argument // _ = (p1, p2) == (p1, p2); Diagnostic(ErrorCode.ERR_BadTypeArgument, "p1").WithArguments("int*").WithLocation(10, 14), // (10,18): error CS0306: The type 'int*' may not be used as a type argument // _ = (p1, p2) == (p1, p2); Diagnostic(ErrorCode.ERR_BadTypeArgument, "p2").WithArguments("int*").WithLocation(10, 18), // (10,26): error CS0306: The type 'int*' may not be used as a type argument // _ = (p1, p2) == (p1, p2); Diagnostic(ErrorCode.ERR_BadTypeArgument, "p1").WithArguments("int*").WithLocation(10, 26), // (10,30): error CS0306: The type 'int*' may not be used as a type argument // _ = (p1, p2) == (p1, p2); Diagnostic(ErrorCode.ERR_BadTypeArgument, "p2").WithArguments("int*").WithLocation(10, 30), // (10,14): error CS0306: The type 'void*' may not be used as a type argument // _ = (p1, p2) == (p1, p2); Diagnostic(ErrorCode.ERR_BadTypeArgument, "p1").WithArguments("void*").WithLocation(10, 14), // (10,18): error CS0306: The type 'void*' may not be used as a type argument // _ = (p1, p2) == (p1, p2); Diagnostic(ErrorCode.ERR_BadTypeArgument, "p2").WithArguments("void*").WithLocation(10, 18), // (10,26): error CS0306: The type 'void*' may not be used as a type argument // _ = (p1, p2) == (p1, p2); Diagnostic(ErrorCode.ERR_BadTypeArgument, "p1").WithArguments("void*").WithLocation(10, 26), // (10,30): error CS0306: The type 'void*' may not be used as a type argument // _ = (p1, p2) == (p1, p2); Diagnostic(ErrorCode.ERR_BadTypeArgument, "p2").WithArguments("void*").WithLocation(10, 30) ); } [Fact] public void TestOrder01() { var source = @" using System; public class C { public static void Main() { X x = new X(); Y y = new Y(); Console.WriteLine((1, ((int, int))x) == (y, (1, 1))); } } class X { public static implicit operator (short, short)(X x) { Console.WriteLine(""X-> (short, short)""); return (1, 1); } } class Y { public static implicit operator int(Y x) { Console.WriteLine(""Y -> int""); return 1; } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: @"X-> (short, short) Y -> int True"); } [Fact] public void TestOrder02() { var source = @" using System; public class C { public static void Main() { var result = (new B(1), new Nullable<B>(new A(2))) == (new A(3), new B(4)); Console.WriteLine(); Console.WriteLine(result); } } struct A { public readonly int N; public A(int n) { this.N = n; Console.Write($""new A({ n }); ""); } } struct B { public readonly int N; public B(int n) { this.N = n; Console.Write($""new B({n}); ""); } public static implicit operator B(A a) { Console.Write($""A({a.N})->""); return new B(a.N); } public static bool operator ==(B b1, B b2) { Console.Write($""B({b1.N})==B({b2.N}); ""); return b1.N == b2.N; } public static bool operator !=(B b1, B b2) { Console.Write($""B({b1.N})!=B({b2.N}); ""); return b1.N != b2.N; } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics( // (22,8): warning CS0660: 'B' defines operator == or operator != but does not override Object.Equals(object o) // struct B Diagnostic(ErrorCode.WRN_EqualityOpWithoutEquals, "B").WithArguments("B").WithLocation(22, 8), // (22,8): warning CS0661: 'B' defines operator == or operator != but does not override Object.GetHashCode() // struct B Diagnostic(ErrorCode.WRN_EqualityOpWithoutGetHashCode, "B").WithArguments("B").WithLocation(22, 8) ); CompileAndVerify(comp, expectedOutput: @"new B(1); new A(2); A(2)->new B(2); new A(3); new B(4); A(3)->new B(3); B(1)==B(3); False "); } [Fact, WorkItem(35958, "https://github.com/dotnet/roslyn/issues/35958")] public void TestMethodGroupConversionInTupleEquality_01() { var source = @" using System; public class C { public static void Main() { Action a = M; Console.WriteLine((a, M) == (M, a)); } static void M() {} }"; var comp = CompileAndVerify(source, expectedOutput: "True"); comp.VerifyDiagnostics(); } [Fact, WorkItem(35958, "https://github.com/dotnet/roslyn/issues/35958")] public void TestMethodGroupConversionInTupleEquality_02() { var source = @" using System; public class C { public static void Main() { Action a = () => {}; Console.WriteLine((a, M) == (M, a)); } static void M() {} }"; var comp = CompileAndVerify(source, expectedOutput: "False"); comp.VerifyDiagnostics(); } [Fact, WorkItem(35958, "https://github.com/dotnet/roslyn/issues/35958")] public void TestMethodGroupConversionInTupleEquality_03() { var source = @" using System; public class C { public static void Main() { K k = null; Console.WriteLine((k, 1) == (M, 1)); } static void M() {} } class K { public static bool operator ==(K k, System.Action a) => true; public static bool operator !=(K k, System.Action a) => false; public override bool Equals(object other) => false; public override int GetHashCode() => 1; } "; var comp = CompileAndVerify(source, expectedOutput: "True"); comp.VerifyDiagnostics(); } [Fact, WorkItem(35958, "https://github.com/dotnet/roslyn/issues/35958")] public void TestInterpolatedStringConversionInTupleEquality_01() { var source = @" using System; public class C { public static void Main() { K k = null; Console.WriteLine((k, 1) == ($""frog"", 1)); } static void M() {} } class K { public static bool operator ==(K k, IFormattable a) => a.ToString() == ""frog""; public static bool operator !=(K k, IFormattable a) => false; public override bool Equals(object other) => false; public override int GetHashCode() => 1; } "; var comp = CompileAndVerify(source, expectedOutput: "True"); comp.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.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 { [CompilerTrait(CompilerFeature.TupleEquality)] public class CodeGenTupleEqualityTests : CSharpTestBase { [Fact] public void TestCSharp7_2() { var source = @" class C { static void Main() { var t = (1, 2); System.Console.Write(t == (1, 2)); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular7_2); comp.VerifyDiagnostics( // (7,30): error CS8320: Feature 'tuple equality' is not available in C# 7.2. Please use language version 7.3 or greater. // System.Console.Write(t == (1, 2)); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_2, "t == (1, 2)").WithArguments("tuple equality", "7.3").WithLocation(7, 30) ); } [Theory] [InlineData("(1, 2)", "(1L, 2L)", true)] [InlineData("(1, 2)", "(1, 0)", false)] [InlineData("(1, 2)", "(0, 2)", false)] [InlineData("(1, 2)", "((long, long))(1, 2)", true)] [InlineData("((1, 2L), (3, 4))", "((1L, 2), (3L, 4))", true)] [InlineData("((1, 2L), (3, 4))", "((0L, 2), (3L, 4))", false)] [InlineData("((1, 2L), (3, 4))", "((1L, 0), (3L, 4))", false)] [InlineData("((1, 2L), (3, 4))", "((1L, 0), (0L, 4))", false)] [InlineData("((1, 2L), (3, 4))", "((1L, 0), (3L, 0))", false)] void TestSimple(string change1, string change2, bool expectedMatch) { var sourceTemplate = @" class C { static void Main() { var t1 = CHANGE1; var t2 = CHANGE2; System.Console.Write($""{(t1 == t2) == EXPECTED} {(t1 != t2) != EXPECTED}""); } }"; string source = sourceTemplate .Replace("CHANGE1", change1) .Replace("CHANGE2", change2) .Replace("EXPECTED", expectedMatch ? "true" : "false"); string name = GetUniqueName(); var comp = CreateCompilation(source, options: TestOptions.DebugExe, assemblyName: name); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "True True"); } [Fact] public void TestTupleLiteralsWithDifferentCardinalities() { var source = @" class C { static bool M() { return (1, 1) == (2, 2, 2); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,16): error CS8373: Tuple types used as operands of an == or != operator must have matching cardinalities. But this operator has tuple types of cardinality 2 on the left and 3 on the right. // return (1, 1) == (2, 2, 2); Diagnostic(ErrorCode.ERR_TupleSizesMismatchForBinOps, "(1, 1) == (2, 2, 2)").WithArguments("2", "3").WithLocation(6, 16) ); } [Fact] public void TestTuplesWithDifferentCardinalities() { var source = @" class C { static bool M() { var t1 = (1, 1); var t2 = (2, 2, 2); return t1 == t2; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (8,16): error CS8355: Tuple types used as operands of a binary operator must have matching cardinalities. But this operator has tuple types of cardinality 2 on the left and 3 on the right. // return t1 == t2; Diagnostic(ErrorCode.ERR_TupleSizesMismatchForBinOps, "t1 == t2").WithArguments("2", "3").WithLocation(8, 16) ); } [Fact] public void TestNestedTuplesWithDifferentCardinalities() { var source = @" class C { static bool M() { var t1 = (1, (1, 1)); var t2 = (2, (2, 2, 2)); return t1 == t2; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (8,16): error CS8355: Tuple types used as operands of a binary operator must have matching cardinalities. But this operator has tuple types of cardinality 2 on the left and 3 on the right. // return t1 == t2; Diagnostic(ErrorCode.ERR_TupleSizesMismatchForBinOps, "t1 == t2").WithArguments("2", "3").WithLocation(8, 16) ); } [Fact, WorkItem(25295, "https://github.com/dotnet/roslyn/issues/25295")] public void TestWithoutValueTuple() { var source = @" class C { static bool M() { return (1, 2) == (3, 4); } }"; var comp = CreateCompilationWithMscorlib40(source); // https://github.com/dotnet/roslyn/issues/25295 // Can we relax the requirement on ValueTuple types being found? comp.VerifyDiagnostics( // (6,16): error CS8179: Predefined type 'System.ValueTuple`2' is not defined or imported // return (1, 2) == (3, 4); Diagnostic(ErrorCode.ERR_PredefinedValueTupleTypeNotFound, "(1, 2)").WithArguments("System.ValueTuple`2").WithLocation(6, 16), // (6,26): error CS8179: Predefined type 'System.ValueTuple`2' is not defined or imported // return (1, 2) == (3, 4); Diagnostic(ErrorCode.ERR_PredefinedValueTupleTypeNotFound, "(3, 4)").WithArguments("System.ValueTuple`2").WithLocation(6, 26) ); } [Fact] public void TestNestedNullableTuplesWithDifferentCardinalities() { var source = @" class C { static bool M() { (int, int)? nt = (1, 1); var t1 = (1, nt); var t2 = (2, (2, 2, 2)); return t1 == t2; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (9,16): error CS8373: Tuple types used as operands of a binary operator must have matching cardinalities. But this operator has tuple types of cardinality 2 on the left and 3 on the right. // return t1 == t2; Diagnostic(ErrorCode.ERR_TupleSizesMismatchForBinOps, "t1 == t2").WithArguments("2", "3").WithLocation(9, 16) ); } [Fact] public void TestILForSimpleEqual() { var source = @" class C { static bool M() { var t1 = (1, 1); var t2 = (2, 2); return t1 == t2; } }"; var comp = CompileAndVerify(source); comp.VerifyDiagnostics(); comp.VerifyIL("C.M", @"{ // Code size 50 (0x32) .maxstack 3 .locals init (System.ValueTuple<int, int> V_0, //t1 System.ValueTuple<int, int> V_1, System.ValueTuple<int, int> V_2) IL_0000: ldloca.s V_0 IL_0002: ldc.i4.1 IL_0003: ldc.i4.1 IL_0004: call ""System.ValueTuple<int, int>..ctor(int, int)"" IL_0009: ldc.i4.2 IL_000a: ldc.i4.2 IL_000b: newobj ""System.ValueTuple<int, int>..ctor(int, int)"" IL_0010: ldloc.0 IL_0011: stloc.1 IL_0012: stloc.2 IL_0013: ldloc.1 IL_0014: ldfld ""int System.ValueTuple<int, int>.Item1"" IL_0019: ldloc.2 IL_001a: ldfld ""int System.ValueTuple<int, int>.Item1"" IL_001f: bne.un.s IL_0030 IL_0021: ldloc.1 IL_0022: ldfld ""int System.ValueTuple<int, int>.Item2"" IL_0027: ldloc.2 IL_0028: ldfld ""int System.ValueTuple<int, int>.Item2"" IL_002d: ceq IL_002f: ret IL_0030: ldc.i4.0 IL_0031: ret }"); } [Fact] public void TestILForSimpleNotEqual() { var source = @" class C { static bool M((int, int) t1, (int, int) t2) { return t1 != t2; } }"; var comp = CompileAndVerify(source); comp.VerifyDiagnostics(); comp.VerifyIL("C.M", @"{ // Code size 38 (0x26) .maxstack 2 .locals init (System.ValueTuple<int, int> V_0, System.ValueTuple<int, int> V_1) IL_0000: ldarg.0 IL_0001: stloc.0 IL_0002: ldarg.1 IL_0003: stloc.1 IL_0004: ldloc.0 IL_0005: ldfld ""int System.ValueTuple<int, int>.Item1"" IL_000a: ldloc.1 IL_000b: ldfld ""int System.ValueTuple<int, int>.Item1"" IL_0010: bne.un.s IL_0024 IL_0012: ldloc.0 IL_0013: ldfld ""int System.ValueTuple<int, int>.Item2"" IL_0018: ldloc.1 IL_0019: ldfld ""int System.ValueTuple<int, int>.Item2"" IL_001e: ceq IL_0020: ldc.i4.0 IL_0021: ceq IL_0023: ret IL_0024: ldc.i4.1 IL_0025: ret }"); } [Fact] public void TestILForSimpleEqualOnInTuple() { var source = @" class C { static bool M(in (int, int) t1, in (int, int) t2) { return t1 == t2; } }"; var comp = CompileAndVerify(source); comp.VerifyDiagnostics(); // note: the logic to save variables and side-effects results in copying the inputs comp.VerifyIL("C.M", @"{ // Code size 45 (0x2d) .maxstack 2 .locals init (System.ValueTuple<int, int> V_0, System.ValueTuple<int, int> V_1) IL_0000: ldarg.0 IL_0001: ldobj ""System.ValueTuple<int, int>"" IL_0006: stloc.0 IL_0007: ldarg.1 IL_0008: ldobj ""System.ValueTuple<int, int>"" IL_000d: stloc.1 IL_000e: ldloc.0 IL_000f: ldfld ""int System.ValueTuple<int, int>.Item1"" IL_0014: ldloc.1 IL_0015: ldfld ""int System.ValueTuple<int, int>.Item1"" IL_001a: bne.un.s IL_002b IL_001c: ldloc.0 IL_001d: ldfld ""int System.ValueTuple<int, int>.Item2"" IL_0022: ldloc.1 IL_0023: ldfld ""int System.ValueTuple<int, int>.Item2"" IL_0028: ceq IL_002a: ret IL_002b: ldc.i4.0 IL_002c: ret }"); } [Fact] public void TestILForSimpleEqualOnTupleLiterals() { var source = @" class C { static void Main() { M(1, 1); M(1, 2); M(2, 1); } static void M(int x, byte y) { System.Console.Write($""{(x, x) == (y, y)} ""); } }"; var comp = CompileAndVerify(source, expectedOutput: "True False False"); comp.VerifyDiagnostics(); comp.VerifyIL("C.M", @"{ // Code size 38 (0x26) .maxstack 3 .locals init (int V_0, byte V_1, byte V_2) IL_0000: ldstr ""{0} "" IL_0005: ldarg.0 IL_0006: ldarg.0 IL_0007: stloc.0 IL_0008: ldarg.1 IL_0009: stloc.1 IL_000a: ldarg.1 IL_000b: stloc.2 IL_000c: ldloc.1 IL_000d: bne.un.s IL_0015 IL_000f: ldloc.0 IL_0010: ldloc.2 IL_0011: ceq IL_0013: br.s IL_0016 IL_0015: ldc.i4.0 IL_0016: box ""bool"" IL_001b: call ""string string.Format(string, object)"" IL_0020: call ""void System.Console.Write(string)"" IL_0025: ret }"); var tree = comp.Compilation.SyntaxTrees.First(); var model = comp.Compilation.GetSemanticModel(tree); // check x var tupleX = tree.GetCompilationUnitRoot().DescendantNodes().OfType<TupleExpressionSyntax>().First(); Assert.Equal("(x, x)", tupleX.ToString()); Assert.Equal(Conversion.Identity, model.GetConversion(tupleX)); Assert.Null(model.GetSymbolInfo(tupleX).Symbol); var lastX = tupleX.Arguments[1].Expression; Assert.Equal("x", lastX.ToString()); Assert.Equal(Conversion.Identity, model.GetConversion(lastX)); Assert.Equal("System.Int32 x", model.GetSymbolInfo(lastX).Symbol.ToTestDisplayString()); var xSymbol = model.GetTypeInfo(lastX); Assert.Equal("System.Int32", xSymbol.Type.ToTestDisplayString()); Assert.Equal("System.Int32", xSymbol.ConvertedType.ToTestDisplayString()); var tupleXSymbol = model.GetTypeInfo(tupleX); Assert.Equal("(System.Int32, System.Int32)", tupleXSymbol.Type.ToTestDisplayString()); Assert.Equal("(System.Int32, System.Int32)", tupleXSymbol.ConvertedType.ToTestDisplayString()); // check y var tupleY = tree.GetCompilationUnitRoot().DescendantNodes().OfType<TupleExpressionSyntax>().Last(); Assert.Equal("(y, y)", tupleY.ToString()); Assert.Equal(ConversionKind.ImplicitTupleLiteral, model.GetConversion(tupleY).Kind); var lastY = tupleY.Arguments[1].Expression; Assert.Equal("y", lastY.ToString()); Assert.Equal(Conversion.ImplicitNumeric, model.GetConversion(lastY)); var ySymbol = model.GetTypeInfo(lastY); Assert.Equal("System.Byte", ySymbol.Type.ToTestDisplayString()); Assert.Equal("System.Int32", ySymbol.ConvertedType.ToTestDisplayString()); var tupleYSymbol = model.GetTypeInfo(tupleY); Assert.Equal("(System.Byte, System.Byte)", tupleYSymbol.Type.ToTestDisplayString()); Assert.Equal("(System.Int32, System.Int32)", tupleYSymbol.ConvertedType.ToTestDisplayString()); } [Fact] public void TestILForAlwaysValuedNullable() { var source = @" class C { static void Main() { System.Console.Write($""{(new int?(Identity(42)), (int?)2) == (new int?(42), new int?(2))} ""); } static int Identity(int x) => x; }"; var comp = CompileAndVerify(source, expectedOutput: "True"); comp.VerifyDiagnostics(); comp.VerifyIL("C.Main", @"{ // Code size 39 (0x27) .maxstack 3 IL_0000: ldstr ""{0} "" IL_0005: ldc.i4.s 42 IL_0007: call ""int C.Identity(int)"" IL_000c: ldc.i4.s 42 IL_000e: bne.un.s IL_0016 IL_0010: ldc.i4.2 IL_0011: ldc.i4.2 IL_0012: ceq IL_0014: br.s IL_0017 IL_0016: ldc.i4.0 IL_0017: box ""bool"" IL_001c: call ""string string.Format(string, object)"" IL_0021: call ""void System.Console.Write(string)"" IL_0026: ret }"); } [Fact] public void TestILForNullableElementsEqualsToNull() { var source = @" class C { static void Main() { System.Console.Write(M(null, null)); System.Console.Write(M(1, true)); } static bool M(int? i1, bool? b1) { var t1 = (i1, b1); return t1 == (null, null); } }"; var comp = CompileAndVerify(source, expectedOutput: "TrueFalse"); comp.VerifyDiagnostics(); comp.VerifyIL("C.M", @"{ // Code size 40 (0x28) .maxstack 2 .locals init (System.ValueTuple<int?, bool?> V_0) IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: newobj ""System.ValueTuple<int?, bool?>..ctor(int?, bool?)"" IL_0007: stloc.0 IL_0008: ldloca.s V_0 IL_000a: ldflda ""int? System.ValueTuple<int?, bool?>.Item1"" IL_000f: call ""bool int?.HasValue.get"" IL_0014: brtrue.s IL_0026 IL_0016: ldloca.s V_0 IL_0018: ldflda ""bool? System.ValueTuple<int?, bool?>.Item2"" IL_001d: call ""bool bool?.HasValue.get"" IL_0022: ldc.i4.0 IL_0023: ceq IL_0025: ret IL_0026: ldc.i4.0 IL_0027: ret }"); } [Fact] public void TestILForNullableElementsNotEqualsToNull() { var source = @" class C { static void Main() { System.Console.Write(M(null, null)); System.Console.Write(M(1, true)); } static bool M(int? i1, bool? b1) { var t1 = (i1, b1); return t1 != (null, null); } }"; var comp = CompileAndVerify(source, expectedOutput: "FalseTrue"); comp.VerifyDiagnostics(); comp.VerifyIL("C.M", @"{ // Code size 37 (0x25) .maxstack 2 .locals init (System.ValueTuple<int?, bool?> V_0) IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: newobj ""System.ValueTuple<int?, bool?>..ctor(int?, bool?)"" IL_0007: stloc.0 IL_0008: ldloca.s V_0 IL_000a: ldflda ""int? System.ValueTuple<int?, bool?>.Item1"" IL_000f: call ""bool int?.HasValue.get"" IL_0014: brtrue.s IL_0023 IL_0016: ldloca.s V_0 IL_0018: ldflda ""bool? System.ValueTuple<int?, bool?>.Item2"" IL_001d: call ""bool bool?.HasValue.get"" IL_0022: ret IL_0023: ldc.i4.1 IL_0024: ret }"); } [Fact] public void TestILForNullableElementsComparedToNonNullValues() { var source = @" class C { static void Main() { System.Console.Write(M((null, null))); System.Console.Write(M((2, true))); } static bool M((int?, bool?) t1) { return t1 == (2, true); } }"; var comp = CompileAndVerify(source, expectedOutput: "FalseTrue"); comp.VerifyDiagnostics(); comp.VerifyIL("C.M", @"{ // Code size 63 (0x3f) .maxstack 2 .locals init (System.ValueTuple<int?, bool?> V_0, int? V_1, int V_2, bool? V_3, bool V_4) IL_0000: ldarg.0 IL_0001: stloc.0 IL_0002: ldloc.0 IL_0003: ldfld ""int? System.ValueTuple<int?, bool?>.Item1"" IL_0008: stloc.1 IL_0009: ldc.i4.2 IL_000a: stloc.2 IL_000b: ldloca.s V_1 IL_000d: call ""int int?.GetValueOrDefault()"" IL_0012: ldloc.2 IL_0013: ceq IL_0015: ldloca.s V_1 IL_0017: call ""bool int?.HasValue.get"" IL_001c: and IL_001d: brfalse.s IL_003d IL_001f: ldloc.0 IL_0020: ldfld ""bool? System.ValueTuple<int?, bool?>.Item2"" IL_0025: stloc.3 IL_0026: ldc.i4.1 IL_0027: stloc.s V_4 IL_0029: ldloca.s V_3 IL_002b: call ""bool bool?.GetValueOrDefault()"" IL_0030: ldloc.s V_4 IL_0032: ceq IL_0034: ldloca.s V_3 IL_0036: call ""bool bool?.HasValue.get"" IL_003b: and IL_003c: ret IL_003d: ldc.i4.0 IL_003e: ret }"); } [Fact] public void TestILForNullableStructEqualsToNull() { var source = @" struct S { static void Main() { S? s = null; _ = s == null; System.Console.Write((s, null) == (null, s)); } }"; var comp = CompileAndVerify(source, expectedOutput: "True"); comp.VerifyDiagnostics(); comp.VerifyIL("S.Main", @"{ // Code size 48 (0x30) .maxstack 2 .locals init (S? V_0, //s S? V_1, S? V_2) IL_0000: ldloca.s V_0 IL_0002: initobj ""S?"" IL_0008: ldloca.s V_0 IL_000a: call ""bool S?.HasValue.get"" IL_000f: pop IL_0010: ldloc.0 IL_0011: stloc.1 IL_0012: ldloc.0 IL_0013: stloc.2 IL_0014: ldloca.s V_1 IL_0016: call ""bool S?.HasValue.get"" IL_001b: brtrue.s IL_0029 IL_001d: ldloca.s V_2 IL_001f: call ""bool S?.HasValue.get"" IL_0024: ldc.i4.0 IL_0025: ceq IL_0027: br.s IL_002a IL_0029: ldc.i4.0 IL_002a: call ""void System.Console.Write(bool)"" IL_002f: ret }"); } [Fact, WorkItem(25488, "https://github.com/dotnet/roslyn/issues/25488")] public void TestThisStruct() { var source = @" public struct S { public int I; public static void Main() { S s = new S() { I = 1 }; s.M(); } void M() { System.Console.Write((this, 2) == (1, this.Mutate())); } S Mutate() { I++; return this; } public static implicit operator S(int value) { return new S() { I = value }; } public static bool operator==(S s1, S s2) { System.Console.Write($""{s1.I} == {s2.I}, ""); return s1.I == s2.I; } public static bool operator!=(S s1, S s2) { throw null; } public override bool Equals(object o) { throw null; } public override int GetHashCode() { throw null; } }"; var comp = CompileAndVerify(source, expectedOutput: "1 == 1, 2 == 2, True"); comp.VerifyDiagnostics(); } [Fact] public void TestThisClass() { var source = @" public class C { public int I; public static void Main() { C c = new C() { I = 1 }; c.M(); } void M() { System.Console.Write((this, 2) == (2, this.Mutate())); } C Mutate() { I++; return this; } public static implicit operator C(int value) { return new C() { I = value }; } public static bool operator==(C c1, C c2) { System.Console.Write($""{c1.I} == {c2.I}, ""); return c1.I == c2.I; } public static bool operator!=(C c1, C c2) { throw null; } public override bool Equals(object o) { throw null; } public override int GetHashCode() { throw null; } }"; var comp = CompileAndVerify(source, expectedOutput: "2 == 2, 2 == 2, True"); comp.VerifyDiagnostics(); } [Fact] public void TestSimpleEqualOnTypelessTupleLiteral() { var source = @" class C { static bool M((string, long) t) { return t == (null, 1) && t == (""hello"", 1); } }"; var comp = CompileAndVerify(source); comp.VerifyDiagnostics(); var tree = comp.Compilation.SyntaxTrees.First(); var model = comp.Compilation.GetSemanticModel(tree); var tuple1 = tree.GetCompilationUnitRoot().DescendantNodes().OfType<TupleExpressionSyntax>().ElementAt(0); var symbol1 = model.GetTypeInfo(tuple1); Assert.Null(symbol1.Type); Assert.Equal("(System.String, System.Int64)", symbol1.ConvertedType.ToTestDisplayString()); Assert.Equal("(System.String, System.Int64)", model.GetDeclaredSymbol(tuple1).ToTestDisplayString()); var tuple2 = tree.GetCompilationUnitRoot().DescendantNodes().OfType<TupleExpressionSyntax>().ElementAt(1); var symbol2 = model.GetTypeInfo(tuple2); Assert.Equal("(System.String, System.Int32)", symbol2.Type.ToTestDisplayString()); Assert.Equal("(System.String, System.Int64)", symbol2.ConvertedType.ToTestDisplayString()); Assert.False(model.GetConstantValue(tuple2).HasValue); Assert.Equal(1, model.GetConstantValue(tuple2.Arguments[1].Expression).Value); } [Fact] public void TestConversionOnTupleExpression() { var source = @" class C { static bool M((int, byte) t) { return t == (1L, 2); } }"; var comp = CompileAndVerify(source); comp.VerifyDiagnostics(); var tree = comp.Compilation.SyntaxTrees.First(); var model = comp.Compilation.GetSemanticModel(tree); var equals = tree.GetCompilationUnitRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().Single(); // check t var t = equals.Left; Assert.Equal("t", t.ToString()); Assert.Equal("(System.Int32, System.Byte) t", model.GetSymbolInfo(t).Symbol.ToTestDisplayString()); Assert.Equal(ConversionKind.ImplicitTuple, model.GetConversion(t).Kind); var tTypeInfo = model.GetTypeInfo(t); Assert.Equal("(System.Int32, System.Byte)", tTypeInfo.Type.ToTestDisplayString()); Assert.Equal("(System.Int64, System.Int32)", tTypeInfo.ConvertedType.ToTestDisplayString()); // check tuple var tuple = equals.Right; Assert.Equal("(1L, 2)", tuple.ToString()); Assert.Null(model.GetSymbolInfo(tuple).Symbol); Assert.Equal(Conversion.Identity, model.GetConversion(tuple)); var tupleTypeInfo = model.GetTypeInfo(tuple); Assert.Equal("(System.Int64, System.Int32)", tupleTypeInfo.Type.ToTestDisplayString()); Assert.Equal("(System.Int64, System.Int32)", tupleTypeInfo.ConvertedType.ToTestDisplayString()); } [Fact] public void TestOtherOperatorsOnTuples() { var source = @" class C { void M() { var t1 = (1, 2); _ = t1 + t1; // error 1 _ = t1 > t1; // error 2 _ = t1 >= t1; // error 3 _ = !t1; // error 4 } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (7,13): error CS0019: Operator '+' cannot be applied to operands of type '(int, int)' and '(int, int)' // _ = t1 + t1; // error 1 Diagnostic(ErrorCode.ERR_BadBinaryOps, "t1 + t1").WithArguments("+", "(int, int)", "(int, int)").WithLocation(7, 13), // (8,13): error CS0019: Operator '>' cannot be applied to operands of type '(int, int)' and '(int, int)' // _ = t1 > t1; // error 2 Diagnostic(ErrorCode.ERR_BadBinaryOps, "t1 > t1").WithArguments(">", "(int, int)", "(int, int)").WithLocation(8, 13), // (9,13): error CS0019: Operator '>=' cannot be applied to operands of type '(int, int)' and '(int, int)' // _ = t1 >= t1; // error 3 Diagnostic(ErrorCode.ERR_BadBinaryOps, "t1 >= t1").WithArguments(">=", "(int, int)", "(int, int)").WithLocation(9, 13), // (10,13): error CS0023: Operator '!' cannot be applied to operand of type '(int, int)' // _ = !t1; // error 4 Diagnostic(ErrorCode.ERR_BadUnaryOp, "!t1").WithArguments("!", "(int, int)").WithLocation(10, 13) ); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var tuple = tree.GetCompilationUnitRoot().DescendantNodes().OfType<TupleExpressionSyntax>().Single(); Assert.Equal("(System.Int32, System.Int32)", model.GetDeclaredSymbol(tuple).ToTestDisplayString()); } [Fact] public void TestTypelessTuples() { var source = @" class C { static void Main() { string s = null; System.Console.Write((s, null) == (null, s)); } }"; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "True"); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); // check first tuple and its null var tuple1 = tree.GetCompilationUnitRoot().DescendantNodes().OfType<TupleExpressionSyntax>().ElementAt(0); Assert.Equal("(s, null)", tuple1.ToString()); var tupleType1 = model.GetTypeInfo(tuple1); Assert.Null(tupleType1.Type); Assert.Equal("(System.String s, System.String)", tupleType1.ConvertedType.ToTestDisplayString()); var tuple1Null = tuple1.Arguments[1].Expression; var tuple1NullTypeInfo = model.GetTypeInfo(tuple1Null); Assert.Null(tuple1NullTypeInfo.Type); Assert.Equal("System.String", tuple1NullTypeInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.ImplicitReference, model.GetConversion(tuple1Null).Kind); // check second tuple and its null var tuple2 = tree.GetCompilationUnitRoot().DescendantNodes().OfType<TupleExpressionSyntax>().ElementAt(1); Assert.Equal("(null, s)", tuple2.ToString()); var tupleType2 = model.GetTypeInfo(tuple2); Assert.Null(tupleType2.Type); Assert.Equal("(System.String, System.String s)", tupleType2.ConvertedType.ToTestDisplayString()); var tuple2Null = tuple2.Arguments[0].Expression; var tuple2NullTypeInfo = model.GetTypeInfo(tuple2Null); Assert.Null(tuple2NullTypeInfo.Type); Assert.Equal("System.String", tuple2NullTypeInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.ImplicitReference, model.GetConversion(tuple2Null).Kind); } [Fact] public void TestWithNoSideEffectsOrTemps() { var source = @" class C { static void Main() { System.Console.Write((1, 2) == (1, 3)); } }"; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "False"); } [Fact] public void TestSimpleTupleAndTupleType_01() { var source = @" class C { static void Main() { var t1 = (1, 2L); System.Console.Write(t1 == (1L, 2)); } }"; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "True"); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var equals = tree.GetCompilationUnitRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().Single(); // check t1 var t1 = equals.Left; Assert.Equal("t1", t1.ToString()); var t1TypeInfo = model.GetTypeInfo(t1); Assert.Equal("(System.Int32, System.Int64)", t1TypeInfo.Type.ToTestDisplayString()); Assert.Equal("(System.Int64, System.Int64)", t1TypeInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.ImplicitTuple, model.GetConversion(t1).Kind); // check tuple and its literal 2 var tuple = (TupleExpressionSyntax)equals.Right; Assert.Equal("(1L, 2)", tuple.ToString()); var tupleType = model.GetTypeInfo(tuple); Assert.Equal("(System.Int64, System.Int32)", tupleType.Type.ToTestDisplayString()); Assert.Equal("(System.Int64, System.Int64)", tupleType.ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.ImplicitTupleLiteral, model.GetConversion(tuple).Kind); var two = tuple.Arguments[1].Expression; Assert.Equal("2", two.ToString()); var twoType = model.GetTypeInfo(two); Assert.Equal("System.Int32", twoType.Type.ToTestDisplayString()); Assert.Equal("System.Int64", twoType.ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.ImplicitNumeric, model.GetConversion(two).Kind); } [Fact] public void TestSimpleTupleAndTupleType_02() { var source = @" class C { static void Main() { var t1 = (1, 2UL); System.Console.Write(t1 == (1L, 2)); } }"; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "True"); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var equals = tree.GetCompilationUnitRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().Single(); // check t1 var t1 = equals.Left; Assert.Equal("t1", t1.ToString()); var t1TypeInfo = model.GetTypeInfo(t1); Assert.Equal("(System.Int32, System.UInt64)", t1TypeInfo.Type.ToTestDisplayString()); Assert.Equal("(System.Int64, System.UInt64)", t1TypeInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.ImplicitTuple, model.GetConversion(t1).Kind); // check tuple and its literal 2 var tuple = (TupleExpressionSyntax)equals.Right; Assert.Equal("(1L, 2)", tuple.ToString()); var tupleType = model.GetTypeInfo(tuple); Assert.Equal("(System.Int64, System.Int32)", tupleType.Type.ToTestDisplayString()); Assert.Equal("(System.Int64, System.UInt64)", tupleType.ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.ImplicitTupleLiteral, model.GetConversion(tuple).Kind); var two = tuple.Arguments[1].Expression; Assert.Equal("2", two.ToString()); var twoType = model.GetTypeInfo(two); Assert.Equal("System.Int32", twoType.Type.ToTestDisplayString()); Assert.Equal("System.UInt64", twoType.ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.ImplicitConstant, model.GetConversion(two).Kind); } [Fact] public void TestNestedTupleAndTupleType() { var source = @" class C { static void Main() { var t1 = (1, (2L, ""hello"")); var t2 = (2, ""hello""); System.Console.Write(t1 == (1L, t2)); } }"; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "True"); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var equals = tree.GetCompilationUnitRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().Single(); // check t1 var t1 = equals.Left; Assert.Equal("t1", t1.ToString()); var t1TypeInfo = model.GetTypeInfo(t1); Assert.Equal("(System.Int32, (System.Int64, System.String))", t1TypeInfo.Type.ToTestDisplayString()); Assert.Equal("(System.Int64, (System.Int64, System.String))", t1TypeInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.ImplicitTuple, model.GetConversion(t1).Kind); Assert.Equal("(System.Int32, (System.Int64, System.String)) t1", model.GetSymbolInfo(t1).Symbol.ToTestDisplayString()); // check tuple and its t2 var tuple = (TupleExpressionSyntax)equals.Right; Assert.Equal("(1L, t2)", tuple.ToString()); var tupleType = model.GetTypeInfo(tuple); Assert.Equal("(System.Int64, (System.Int32, System.String) t2)", tupleType.Type.ToTestDisplayString()); Assert.Equal("(System.Int64, (System.Int64, System.String) t2)", tupleType.ConvertedType.ToTestDisplayString()); var t2 = tuple.Arguments[1].Expression; Assert.Equal("t2", t2.ToString()); var t2TypeInfo = model.GetTypeInfo(t2); Assert.Equal("(System.Int32, System.String)", t2TypeInfo.Type.ToTestDisplayString()); Assert.Equal("(System.Int64, System.String)", t2TypeInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.ImplicitTuple, model.GetConversion(t2).Kind); Assert.Equal("(System.Int32, System.String) t2", model.GetSymbolInfo(t2).Symbol.ToTestDisplayString()); } [Fact] public void TestTypelessTupleAndTupleType() { var source = @" class C { static void Main() { (string, string) t = (null, null); System.Console.Write(t == (null, null)); System.Console.Write(t != (null, null)); System.Console.Write((1, t) == (1, (null, null))); } }"; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "TrueFalseTrue"); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var tuple = tree.GetCompilationUnitRoot().DescendantNodes().OfType<TupleExpressionSyntax>().ElementAt(1); Assert.Equal("(null, null)", tuple.ToString()); var tupleType = model.GetTypeInfo(tuple); Assert.Null(tupleType.Type); Assert.Equal("(System.String, System.String)", tupleType.ConvertedType.ToTestDisplayString()); // check last tuple ... var lastEquals = tree.GetCompilationUnitRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().Last(); var lastTuple = (TupleExpressionSyntax)lastEquals.Right; Assert.Equal("(1, (null, null))", lastTuple.ToString()); TypeInfo lastTupleTypeInfo = model.GetTypeInfo(lastTuple); Assert.Null(lastTupleTypeInfo.Type); Assert.Equal("(System.Int32, (System.String, System.String))", lastTupleTypeInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.ImplicitTupleLiteral, model.GetConversion(lastTuple).Kind); // ... and its nested (null, null) tuple ... var nullNull = (TupleExpressionSyntax)lastTuple.Arguments[1].Expression; TypeInfo nullNullTypeInfo = model.GetTypeInfo(nullNull); Assert.Null(nullNullTypeInfo.Type); Assert.Equal("(System.String, System.String)", nullNullTypeInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.ImplicitTupleLiteral, model.GetConversion(nullNull).Kind); // ... and its last null. var lastNull = nullNull.Arguments[1].Expression; TypeInfo lastNullTypeInfo = model.GetTypeInfo(lastNull); Assert.Null(lastNullTypeInfo.Type); Assert.Equal("System.String", lastNullTypeInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.ImplicitReference, model.GetConversion(lastNull).Kind); } [Fact] public void TestTypedTupleAndDefault() { var source = @" class C { static void Main() { (string, string) t = (null, null); System.Console.Write(t == default); System.Console.Write(t != default); (string, string) t2 = (null, ""hello""); System.Console.Write(t2 == default); System.Console.Write(t2 != default); } }"; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "TrueFalseFalseTrue"); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var defaultLiterals = tree.GetCompilationUnitRoot().DescendantNodes().OfType<LiteralExpressionSyntax>() .Where(e => e.Kind() == SyntaxKind.DefaultLiteralExpression); foreach (var literal in defaultLiterals) { Assert.Equal("default", literal.ToString()); var info = model.GetTypeInfo(literal); Assert.Equal("(System.String, System.String)", info.Type.ToTestDisplayString()); Assert.Equal("(System.String, System.String)", info.ConvertedType.ToTestDisplayString()); } } [Fact] public void TestNullableTupleAndDefault() { var source = @" class C { static void Main() { (string, string)? t = (null, null); System.Console.Write(t == default); System.Console.Write(t != default); System.Console.Write(default == t); System.Console.Write(default != t); } }"; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "FalseTrueFalseTrue"); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var defaultLiterals = tree.GetCompilationUnitRoot().DescendantNodes().OfType<LiteralExpressionSyntax>() .Where(e => e.Kind() == SyntaxKind.DefaultLiteralExpression); foreach (var literal in defaultLiterals) { Assert.Equal("default", literal.ToString()); var info = model.GetTypeInfo(literal); Assert.Equal("(System.String, System.String)?", info.Type.ToTestDisplayString()); Assert.Equal("(System.String, System.String)?", info.ConvertedType.ToTestDisplayString()); } } [Fact] public void TestNullableTupleAndDefault_Nested() { var source = @" class C { static void Main() { (string, string)? t = (null, null); System.Console.Write((null, t) == (null, default)); System.Console.Write((t, null) != (default, null)); } }"; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "FalseTrue"); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var defaultLiterals = tree.GetCompilationUnitRoot().DescendantNodes().OfType<LiteralExpressionSyntax>() .Where(e => e.Kind() == SyntaxKind.DefaultLiteralExpression); foreach (var literal in defaultLiterals) { Assert.Equal("default", literal.ToString()); var info = model.GetTypeInfo(literal); Assert.Equal("(System.String, System.String)?", info.Type.ToTestDisplayString()); Assert.Equal("(System.String, System.String)?", info.ConvertedType.ToTestDisplayString()); } } [Fact] public void TestNestedDefaultWithNonTupleType() { var source = @" class C { static void Main() { System.Console.Write((null, 1) == (null, default)); System.Console.Write((0, null) != (default, null)); } }"; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "FalseFalse"); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var defaultLiterals = tree.GetCompilationUnitRoot().DescendantNodes().OfType<LiteralExpressionSyntax>() .Where(e => e.Kind() == SyntaxKind.DefaultLiteralExpression); foreach (var literal in defaultLiterals) { Assert.Equal("default", literal.ToString()); var info = model.GetTypeInfo(literal); Assert.Equal("System.Int32", info.Type.ToTestDisplayString()); Assert.Equal("System.Int32", info.ConvertedType.ToTestDisplayString()); } } [Fact] public void TestNestedDefaultWithNullableNonTupleType() { var source = @" struct S { static void Main() { S? ns = null; _ = (null, ns) == (null, default); _ = (ns, null) != (default, null); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (7,13): error CS0019: Operator '==' cannot be applied to operands of type 'S?' and 'default' // _ = (null, ns) == (null, default); Diagnostic(ErrorCode.ERR_BadBinaryOps, "(null, ns) == (null, default)").WithArguments("==", "S?", "default").WithLocation(7, 13), // (8,13): error CS0019: Operator '!=' cannot be applied to operands of type 'S?' and 'default' // _ = (ns, null) != (default, null); Diagnostic(ErrorCode.ERR_BadBinaryOps, "(ns, null) != (default, null)").WithArguments("!=", "S?", "default").WithLocation(8, 13) ); } [Fact] public void TestNestedDefaultWithNullableNonTupleType_WithComparisonOperator() { var source = @" public struct S { public static void Main() { S? ns = new S(); System.Console.Write((null, ns) == (null, default)); System.Console.Write((ns, null) != (default, null)); } public static bool operator==(S s1, S s2) => throw null; public static bool operator!=(S s1, S s2) => throw null; public override int GetHashCode() => throw null; public override bool Equals(object o) => throw null; }"; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "FalseTrue"); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var defaults = tree.GetCompilationUnitRoot().DescendantNodes().OfType<LiteralExpressionSyntax>() .Where(e => e.Kind() == SyntaxKind.DefaultLiteralExpression); foreach (var literal in defaults) { var type = model.GetTypeInfo(literal); Assert.Equal("S?", type.Type.ToTestDisplayString()); Assert.Equal("S?", type.ConvertedType.ToTestDisplayString()); } } [Fact] public void TestAllDefaults() { var source = @" class C { static void Main() { System.Console.Write((default, default) == (default, default)); System.Console.Write(default == (default, default)); } }"; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics( // (6,30): error CS8315: Operator '==' is ambiguous on operands 'default' and 'default' // System.Console.Write((default, default) == (default, default)); Diagnostic(ErrorCode.ERR_AmbigBinaryOpsOnDefault, "(default, default) == (default, default)").WithArguments("==", "default", "default").WithLocation(6, 30), // (6,30): error CS8315: Operator '==' is ambiguous on operands 'default' and 'default' // System.Console.Write((default, default) == (default, default)); Diagnostic(ErrorCode.ERR_AmbigBinaryOpsOnDefault, "(default, default) == (default, default)").WithArguments("==", "default", "default").WithLocation(6, 30), // (7,30): error CS0034: Operator '==' is ambiguous on operands of type 'default' and '(default, default)' // System.Console.Write(default == (default, default)); Diagnostic(ErrorCode.ERR_AmbigBinaryOps, "default == (default, default)").WithArguments("==", "default", "(default, default)").WithLocation(7, 30) ); } [Fact] public void TestNullsAndDefaults() { var source = @" class C { static void Main() { _ = (null, default) != (default, null); } }"; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics( // (6,13): error CS0034: Operator '!=' is ambiguous on operands of type '<null>' and 'default' // _ = (null, default) != (default, null); Diagnostic(ErrorCode.ERR_AmbigBinaryOps, "(null, default) != (default, null)").WithArguments("!=", "<null>", "default").WithLocation(6, 13), // (6,13): error CS0034: Operator '!=' is ambiguous on operands of type 'default' and '<null>' // _ = (null, default) != (default, null); Diagnostic(ErrorCode.ERR_AmbigBinaryOps, "(null, default) != (default, null)").WithArguments("!=", "default", "<null>").WithLocation(6, 13) ); } [Fact] public void TestAllDefaults_Nested() { var source = @" class C { static void Main() { System.Console.Write((null, (default, default)) == (null, (default, default))); } }"; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics( // (6,30): error CS8315: Operator '==' is ambiguous on operands 'default' and 'default' // System.Console.Write((null, (default, default)) == (null, (default, default))); Diagnostic(ErrorCode.ERR_AmbigBinaryOpsOnDefault, "(null, (default, default)) == (null, (default, default))").WithArguments("==", "default", "default").WithLocation(6, 30), // (6,30): error CS8315: Operator '==' is ambiguous on operands 'default' and 'default' // System.Console.Write((null, (default, default)) == (null, (default, default))); Diagnostic(ErrorCode.ERR_AmbigBinaryOpsOnDefault, "(null, (default, default)) == (null, (default, default))").WithArguments("==", "default", "default").WithLocation(6, 30) ); } [Fact] public void TestTypedTupleAndTupleOfDefaults() { var source = @" class C { static void Main() { (string, string)? t = (null, null); System.Console.Write(t == (default, default)); System.Console.Write(t != (default, default)); } }"; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "TrueFalse"); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var lastTuple = tree.GetCompilationUnitRoot().DescendantNodes().OfType<TupleExpressionSyntax>().Last(); Assert.Equal("(default, default)", lastTuple.ToString()); Assert.Null(model.GetTypeInfo(lastTuple).Type); Assert.Equal("(System.String, System.String)?", model.GetTypeInfo(lastTuple).ConvertedType.ToTestDisplayString()); var lastDefault = lastTuple.Arguments[1].Expression; Assert.Equal("default", lastDefault.ToString()); Assert.Equal("System.String", model.GetTypeInfo(lastDefault).Type.ToTestDisplayString()); Assert.Equal("System.String", model.GetTypeInfo(lastDefault).ConvertedType.ToTestDisplayString()); } [Fact] public void TestTypelessTupleAndTupleOfDefaults() { var source = @" class C { static void Main() { System.Console.Write((null, () => 1) == (default, default)); System.Console.Write((null, () => 2) == default); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (6,30): error CS0034: Operator '==' is ambiguous on operands of type '<null>' and 'default' // System.Console.Write((null, () => 1) == (default, default)); Diagnostic(ErrorCode.ERR_AmbigBinaryOps, "(null, () => 1) == (default, default)").WithArguments("==", "<null>", "default").WithLocation(6, 30), // (6,30): error CS0019: Operator '==' cannot be applied to operands of type 'lambda expression' and 'default' // System.Console.Write((null, () => 1) == (default, default)); Diagnostic(ErrorCode.ERR_BadBinaryOps, "(null, () => 1) == (default, default)").WithArguments("==", "lambda expression", "default").WithLocation(6, 30), // (7,30): error CS0034: Operator '==' is ambiguous on operands of type '(<null>, lambda expression)' and 'default' // System.Console.Write((null, () => 2) == default); Diagnostic(ErrorCode.ERR_AmbigBinaryOps, "(null, () => 2) == default").WithArguments("==", "(<null>, lambda expression)", "default").WithLocation(7, 30) ); comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,30): error CS0034: Operator '==' is ambiguous on operands of type '<null>' and 'default' // System.Console.Write((null, () => 1) == (default, default)); Diagnostic(ErrorCode.ERR_AmbigBinaryOps, "(null, () => 1) == (default, default)").WithArguments("==", "<null>", "default").WithLocation(6, 30), // (7,30): error CS0034: Operator '==' is ambiguous on operands of type '(<null>, lambda expression)' and 'default' // System.Console.Write((null, () => 2) == default); Diagnostic(ErrorCode.ERR_AmbigBinaryOps, "(null, () => 2) == default").WithArguments("==", "(<null>, lambda expression)", "default").WithLocation(7, 30) ); } [Fact] public void TestNullableStructAndDefault() { var source = @" struct S { static void M(string s) { S? ns = new S(); _ = ns == null; _ = s == null; _ = ns == default; // error 1 _ = (ns, ns) == (null, null); _ = (ns, ns) == (default, default); // errors 2 and 3 _ = (ns, ns) == default; // error 4 } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (9,13): error CS0019: Operator '==' cannot be applied to operands of type 'S?' and 'default' // _ = ns == default; // error 1 Diagnostic(ErrorCode.ERR_BadBinaryOps, "ns == default").WithArguments("==", "S?", "default").WithLocation(9, 13), // (11,13): error CS0019: Operator '==' cannot be applied to operands of type 'S?' and 'default' // _ = (ns, ns) == (default, default); // errors 2 and 3 Diagnostic(ErrorCode.ERR_BadBinaryOps, "(ns, ns) == (default, default)").WithArguments("==", "S?", "default").WithLocation(11, 13), // (11,13): error CS0019: Operator '==' cannot be applied to operands of type 'S?' and 'default' // _ = (ns, ns) == (default, default); // errors 2 and 3 Diagnostic(ErrorCode.ERR_BadBinaryOps, "(ns, ns) == (default, default)").WithArguments("==", "S?", "default").WithLocation(11, 13), // (12,13): error CS0019: Operator '==' cannot be applied to operands of type 'S?' and 'S?' // _ = (ns, ns) == default; // error 4 Diagnostic(ErrorCode.ERR_BadBinaryOps, "(ns, ns) == default").WithArguments("==", "S?", "S?").WithLocation(12, 13), // (12,13): error CS0019: Operator '==' cannot be applied to operands of type 'S?' and 'S?' // _ = (ns, ns) == default; // error 4 Diagnostic(ErrorCode.ERR_BadBinaryOps, "(ns, ns) == default").WithArguments("==", "S?", "S?").WithLocation(12, 13) ); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var literals = tree.GetCompilationUnitRoot().DescendantNodes().OfType<LiteralExpressionSyntax>(); var nullLiteral = literals.ElementAt(0); Assert.Equal("null", nullLiteral.ToString()); Assert.Null(model.GetTypeInfo(nullLiteral).ConvertedType); var nullLiteral2 = literals.ElementAt(1); Assert.Equal("null", nullLiteral2.ToString()); Assert.Null(model.GetTypeInfo(nullLiteral2).Type); Assert.Equal("System.String", model.GetTypeInfo(nullLiteral2).ConvertedType.ToTestDisplayString()); var defaultLiterals = tree.GetCompilationUnitRoot().DescendantNodes().OfType<LiteralExpressionSyntax>() .Where(e => e.Kind() == SyntaxKind.DelegateDeclaration); foreach (var defaultLiteral in defaultLiterals) { Assert.Equal("default", defaultLiteral.ToString()); Assert.Null(model.GetTypeInfo(defaultLiteral).Type); Assert.Null(model.GetTypeInfo(defaultLiteral).ConvertedType); } } [Fact, WorkItem(25318, "https://github.com/dotnet/roslyn/issues/25318")] public void TestNullableStructAndDefault_WithComparisonOperator() { var source = @" public struct S { static void M(string s) { S? ns = new S(); _ = ns == 1; _ = (ns, ns) == (default, default); _ = (ns, ns) == default; } public static bool operator==(S s, byte b) => throw null; public static bool operator!=(S s, byte b) => throw null; public override bool Equals(object other) => throw null; public override int GetHashCode() => throw null; }"; var comp = CreateCompilation(source); // https://github.com/dotnet/roslyn/issues/25318 // This should be allowed comp.VerifyDiagnostics( // (7,13): error CS0019: Operator '==' cannot be applied to operands of type 'S?' and 'int' // _ = ns == 1; Diagnostic(ErrorCode.ERR_BadBinaryOps, "ns == 1").WithArguments("==", "S?", "int").WithLocation(7, 13), // (8,13): error CS0019: Operator '==' cannot be applied to operands of type 'S?' and 'default' // _ = (ns, ns) == (default, default); Diagnostic(ErrorCode.ERR_BadBinaryOps, "(ns, ns) == (default, default)").WithArguments("==", "S?", "default").WithLocation(8, 13), // (8,13): error CS0019: Operator '==' cannot be applied to operands of type 'S?' and 'default' // _ = (ns, ns) == (default, default); Diagnostic(ErrorCode.ERR_BadBinaryOps, "(ns, ns) == (default, default)").WithArguments("==", "S?", "default").WithLocation(8, 13), // (9,13): error CS0019: Operator '==' cannot be applied to operands of type 'S?' and 'S?' // _ = (ns, ns) == default; Diagnostic(ErrorCode.ERR_BadBinaryOps, "(ns, ns) == default").WithArguments("==", "S?", "S?").WithLocation(9, 13), // (9,13): error CS0019: Operator '==' cannot be applied to operands of type 'S?' and 'S?' // _ = (ns, ns) == default; Diagnostic(ErrorCode.ERR_BadBinaryOps, "(ns, ns) == default").WithArguments("==", "S?", "S?").WithLocation(9, 13) ); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var defaultLiterals = tree.GetCompilationUnitRoot().DescendantNodes().OfType<LiteralExpressionSyntax>() .Where(e => e.Kind() == SyntaxKind.DelegateDeclaration); // Should have types foreach (var defaultLiteral in defaultLiterals) { Assert.Equal("default", defaultLiteral.ToString()); Assert.Null(model.GetTypeInfo(defaultLiteral).Type); Assert.Null(model.GetTypeInfo(defaultLiteral).ConvertedType); // https://github.com/dotnet/roslyn/issues/25318 // default should become int } } [Fact] public void TestMixedTupleLiteralsAndTypes() { var source = @" class C { static void Main() { (string, string) t = (null, null); System.Console.Write((t, (null, null)) == ((null, null), t)); } }"; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "True"); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); // check last tuple ... var tuple = tree.GetCompilationUnitRoot().DescendantNodes().OfType<TupleExpressionSyntax>().ElementAt(3); Assert.Equal("((null, null), t)", tuple.ToString()); var tupleType = model.GetTypeInfo(tuple); Assert.Null(tupleType.Type); Assert.Equal("((System.String, System.String), (System.String, System.String) t)", tupleType.ConvertedType.ToTestDisplayString()); // ... its t ... var t = tuple.Arguments[1].Expression; Assert.Equal("t", t.ToString()); var tType = model.GetTypeInfo(t); Assert.Equal("(System.String, System.String)", tType.Type.ToTestDisplayString()); Assert.Equal("(System.String, System.String)", tType.ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.Identity, model.GetConversion(t).Kind); Assert.Equal("(System.String, System.String) t", model.GetSymbolInfo(t).Symbol.ToTestDisplayString()); Assert.Null(model.GetDeclaredSymbol(t)); // ... its nested tuple ... var nestedTuple = (TupleExpressionSyntax)tuple.Arguments[0].Expression; Assert.Equal("(null, null)", nestedTuple.ToString()); var nestedTupleType = model.GetTypeInfo(nestedTuple); Assert.Null(nestedTupleType.Type); Assert.Equal("(System.String, System.String)", nestedTupleType.ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.ImplicitTupleLiteral, model.GetConversion(nestedTuple).Kind); Assert.Null(model.GetSymbolInfo(nestedTuple).Symbol); Assert.Equal("(System.String, System.String)", model.GetDeclaredSymbol(nestedTuple).ToTestDisplayString()); // ... a nested null. var nestedNull = nestedTuple.Arguments[0].Expression; Assert.Equal("null", nestedNull.ToString()); var nestedNullType = model.GetTypeInfo(nestedNull); Assert.Null(nestedNullType.Type); Assert.Equal("System.String", nestedNullType.ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.ImplicitReference, model.GetConversion(nestedNull).Kind); } [Fact] public void TestAllNulls() { var source = @" class C { static void Main() { System.Console.Write(null == null); System.Console.Write((null, null) == (null, null)); System.Console.Write((null, null) != (null, null)); } }"; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "TrueTrueFalse"); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var nulls = tree.GetCompilationUnitRoot().DescendantNodes().OfType<LiteralExpressionSyntax>(); foreach (var literal in nulls) { Assert.Equal("null", literal.ToString()); var symbol = model.GetTypeInfo(literal); Assert.Null(symbol.Type); Assert.Null(symbol.ConvertedType); } var tuples = tree.GetCompilationUnitRoot().DescendantNodes().OfType<TupleExpressionSyntax>(); foreach (var tuple in tuples) { Assert.Equal("(null, null)", tuple.ToString()); var symbol = model.GetTypeInfo(tuple); Assert.Null(symbol.Type); Assert.Null(symbol.ConvertedType); } } [Fact] public void TestConvertedElementInTypelessTuple() { var source = @" class C { static void Main() { System.Console.Write((null, 1L) == (null, 2)); } }"; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "False"); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var lastLiteral = tree.GetCompilationUnitRoot().DescendantNodes().OfType<LiteralExpressionSyntax>().Last(); Assert.Equal("2", lastLiteral.ToString()); var literalInfo = model.GetTypeInfo(lastLiteral); Assert.Equal("System.Int32", literalInfo.Type.ToTestDisplayString()); Assert.Equal("System.Int64", literalInfo.ConvertedType.ToTestDisplayString()); } [Fact] public void TestConvertedElementInTypelessTuple_Nested() { var source = @" class C { static void Main() { System.Console.Write(((null, 1L), null) == ((null, 2), null)); } }"; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "False"); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var rightTuple = tree.GetCompilationUnitRoot().DescendantNodes().OfType<TupleExpressionSyntax>().ElementAt(2); Assert.Equal("((null, 2), null)", rightTuple.ToString()); var literalInfo = model.GetTypeInfo(rightTuple); Assert.Null(literalInfo.Type); Assert.Null(literalInfo.ConvertedType); var nestedTuple = (TupleExpressionSyntax)rightTuple.Arguments[0].Expression; Assert.Equal("(null, 2)", nestedTuple.ToString()); var nestedLiteralInfo = model.GetTypeInfo(rightTuple); Assert.Null(nestedLiteralInfo.Type); Assert.Null(nestedLiteralInfo.ConvertedType); var two = nestedTuple.Arguments[1].Expression; Assert.Equal("2", two.ToString()); var twoInfo = model.GetTypeInfo(two); Assert.Equal("System.Int32", twoInfo.Type.ToTestDisplayString()); Assert.Equal("System.Int64", twoInfo.ConvertedType.ToTestDisplayString()); } [Fact] public void TestFailedInference() { var source = @" class C { static void Main() { System.Console.Write((null, null, null, null) == (null, x => x, Main, (int i) => { int j = 0; return i + j; })); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (6,30): error CS0019: Operator '==' cannot be applied to operands of type '<null>' and 'lambda expression' // System.Console.Write((null, null, null, null) == (null, x => x, Main, (int i) => { int j = 0; return i + j; })); Diagnostic(ErrorCode.ERR_BadBinaryOps, "(null, null, null, null) == (null, x => x, Main, (int i) => { int j = 0; return i + j; })").WithArguments("==", "<null>", "lambda expression").WithLocation(6, 30), // (6,30): error CS0019: Operator '==' cannot be applied to operands of type '<null>' and 'method group' // System.Console.Write((null, null, null, null) == (null, x => x, Main, (int i) => { int j = 0; return i + j; })); Diagnostic(ErrorCode.ERR_BadBinaryOps, "(null, null, null, null) == (null, x => x, Main, (int i) => { int j = 0; return i + j; })").WithArguments("==", "<null>", "method group").WithLocation(6, 30), // (6,30): error CS0019: Operator '==' cannot be applied to operands of type '<null>' and 'lambda expression' // System.Console.Write((null, null, null, null) == (null, x => x, Main, (int i) => { int j = 0; return i + j; })); Diagnostic(ErrorCode.ERR_BadBinaryOps, "(null, null, null, null) == (null, x => x, Main, (int i) => { int j = 0; return i + j; })").WithArguments("==", "<null>", "lambda expression").WithLocation(6, 30)); verify(comp, inferDelegate: false); comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (6,65): error CS8917: The delegate type could not be inferred. // System.Console.Write((null, null, null, null) == (null, x => x, Main, (int i) => { int j = 0; return i + j; })); Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "x => x").WithLocation(6, 65), // (6,65): error CS8917: The delegate type could not be inferred. // System.Console.Write((null, null, null, null) == (null, x => x, Main, (int i) => { int j = 0; return i + j; })); Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "x => x").WithLocation(6, 65)); verify(comp, inferDelegate: true); static void verify(CSharpCompilation comp, bool inferDelegate) { var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); // check tuple on the left var tuple1 = tree.GetCompilationUnitRoot().DescendantNodes().OfType<TupleExpressionSyntax>().ElementAt(0); Assert.Equal("(null, null, null, null)", tuple1.ToString()); var tupleType1 = model.GetTypeInfo(tuple1); Assert.Null(tupleType1.Type); Assert.Null(tupleType1.ConvertedType); // check tuple on the right ... var tuple2 = tree.GetCompilationUnitRoot().DescendantNodes().OfType<TupleExpressionSyntax>().ElementAt(1); Assert.Equal("(null, x => x, Main, (int i) => { int j = 0; return i + j; })", tuple2.ToString()); var tupleType2 = model.GetTypeInfo(tuple2); Assert.Null(tupleType2.Type); Assert.Null(tupleType2.ConvertedType); // ... its first lambda ... var firstLambda = tuple2.Arguments[1].Expression; Assert.Null(model.GetTypeInfo(firstLambda).Type); verifyType("System.Delegate", model.GetTypeInfo(firstLambda).ConvertedType, inferDelegate); // ... its method group ... var methodGroup = tuple2.Arguments[2].Expression; Assert.Null(model.GetTypeInfo(methodGroup).Type); verifyType("System.Delegate", model.GetTypeInfo(methodGroup).ConvertedType, inferDelegate); Assert.Null(model.GetSymbolInfo(methodGroup).Symbol); Assert.Equal(new[] { "void C.Main()" }, model.GetSymbolInfo(methodGroup).CandidateSymbols.Select(s => s.ToTestDisplayString())); // ... its second lambda and the symbols it uses var secondLambda = tuple2.Arguments[3].Expression; verifyType("System.Func<System.Int32, System.Int32>", model.GetTypeInfo(secondLambda).Type, inferDelegate); verifyType("System.Delegate", model.GetTypeInfo(secondLambda).ConvertedType, inferDelegate); var addition = tree.GetCompilationUnitRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().Last(); Assert.Equal("i + j", addition.ToString()); var i = addition.Left; Assert.Equal("System.Int32 i", model.GetSymbolInfo(i).Symbol.ToTestDisplayString()); var j = addition.Right; Assert.Equal("System.Int32 j", model.GetSymbolInfo(j).Symbol.ToTestDisplayString()); } static void verifyType(string expectedType, ITypeSymbol type, bool inferDelegate) { if (inferDelegate) { Assert.Equal(expectedType, type.ToTestDisplayString()); } else { Assert.Null(type); } } } [Fact] public void TestVoidTypeElement() { var source = @" class C { static void Main() { System.Console.Write((Main(), null) != (null, Main())); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,31): error CS8210: A tuple may not contain a value of type 'void'. // System.Console.Write((Main(), null) != (null, Main())); Diagnostic(ErrorCode.ERR_VoidInTuple, "Main()").WithLocation(6, 31), // (6,55): error CS8210: A tuple may not contain a value of type 'void'. // System.Console.Write((Main(), null) != (null, Main())); Diagnostic(ErrorCode.ERR_VoidInTuple, "Main()").WithLocation(6, 55) ); } [Fact] public void TestFailedConversion() { var source = @" class C { static void M(string s) { System.Console.Write((s, s) == (1, () => { })); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,30): error CS0019: Operator '==' cannot be applied to operands of type 'string' and 'int' // System.Console.Write((s, s) == (1, () => { })); Diagnostic(ErrorCode.ERR_BadBinaryOps, "(s, s) == (1, () => { })").WithArguments("==", "string", "int").WithLocation(6, 30), // (6,30): error CS0019: Operator '==' cannot be applied to operands of type 'string' and 'lambda expression' // System.Console.Write((s, s) == (1, () => { })); Diagnostic(ErrorCode.ERR_BadBinaryOps, "(s, s) == (1, () => { })").WithArguments("==", "string", "lambda expression").WithLocation(6, 30) ); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var tuple1 = tree.GetCompilationUnitRoot().DescendantNodes().OfType<TupleExpressionSyntax>().ElementAt(0); Assert.Equal("(s, s)", tuple1.ToString()); var tupleType1 = model.GetTypeInfo(tuple1); Assert.Equal("(System.String, System.String)", tupleType1.Type.ToTestDisplayString()); Assert.Equal("(System.String, System.String)", tupleType1.ConvertedType.ToTestDisplayString()); var tuple2 = tree.GetCompilationUnitRoot().DescendantNodes().OfType<TupleExpressionSyntax>().ElementAt(1); Assert.Equal("(1, () => { })", tuple2.ToString()); var tupleType2 = model.GetTypeInfo(tuple2); Assert.Null(tupleType2.Type); Assert.Null(tupleType2.ConvertedType); } [Fact] public void TestDynamic() { var source = @" public class C { public static void Main() { dynamic d1 = 1; dynamic d2 = 2; System.Console.Write($""{(d1, 2) == (1, d2)} ""); System.Console.Write($""{(d1, 2) != (1, d2)} ""); System.Console.Write($""{(d1, 20) == (10, d2)} ""); System.Console.Write($""{(d1, 20) != (10, d2)} ""); } }"; var comp = CreateCompilation(source, targetFramework: TargetFramework.StandardAndCSharp, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "True False False True"); } [Fact] public void TestDynamicWithConstants() { var source = @" public class C { public static void Main() { System.Console.Write($""{((dynamic)true, (dynamic)false) == ((dynamic)true, (dynamic)false)} ""); } }"; var comp = CreateCompilation(source, targetFramework: TargetFramework.StandardAndCSharp, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "True"); } [Fact] public void TestDynamic_WithTypelessExpression() { var source = @" public class C { public static void Main() { dynamic d1 = 1; dynamic d2 = 2; System.Console.Write((d1, 2) == (() => 1, d2)); } }"; var comp = CreateCompilation(source, targetFramework: TargetFramework.StandardAndCSharp, options: TestOptions.DebugExe); comp.VerifyDiagnostics( // (8,30): error CS0019: Operator '==' cannot be applied to operands of type 'dynamic' and 'lambda expression' // System.Console.Write((d1, 2) == (() => 1, d2)); Diagnostic(ErrorCode.ERR_BadBinaryOps, "(d1, 2) == (() => 1, d2)").WithArguments("==", "dynamic", "lambda expression").WithLocation(8, 30) ); } [Fact] public void TestDynamic_WithBooleanConstants() { var source = @" public class C { public static void Main() { System.Console.Write(((dynamic)true, (dynamic)false) == (true, false)); System.Console.Write(((dynamic)true, (dynamic)false) != (true, false)); } }"; var comp = CreateCompilation(source, targetFramework: TargetFramework.StandardAndCSharp, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "TrueFalse"); } [Fact] public void TestDynamic_WithBadType() { var source = @" public class C { public static void Main() { System.Globalization.CultureInfo saveUICulture = System.Threading.Thread.CurrentThread.CurrentUICulture; System.Threading.Thread.CurrentThread.CurrentUICulture = System.Globalization.CultureInfo.InvariantCulture; dynamic d1 = 1; dynamic d2 = 2; try { bool b = ((d1, 2) == (""hello"", d2)); } catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e) { System.Console.Write(e.Message); } finally { System.Threading.Thread.CurrentThread.CurrentUICulture = saveUICulture; } } }"; var comp = CreateCompilation(source, targetFramework: TargetFramework.StandardAndCSharp, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "Operator '==' cannot be applied to operands of type 'int' and 'string'"); } [Fact] public void TestDynamic_WithNull() { var source = @" public class C { public static void Main() { dynamic d1 = null; dynamic d2 = null; System.Console.Write((d1, null) == (null, d2)); } }"; var comp = CreateCompilation(source, targetFramework: TargetFramework.StandardAndCSharp, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "True"); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var tuple1 = tree.GetCompilationUnitRoot().DescendantNodes().OfType<TupleExpressionSyntax>().ElementAt(0); Assert.Equal("(d1, null)", tuple1.ToString()); var tupleType1 = model.GetTypeInfo(tuple1); Assert.Null(tupleType1.Type); Assert.Equal("(dynamic d1, dynamic)", tupleType1.ConvertedType.ToTestDisplayString()); var tuple2 = tree.GetCompilationUnitRoot().DescendantNodes().OfType<TupleExpressionSyntax>().ElementAt(1); Assert.Equal("(null, d2)", tuple2.ToString()); var tupleType2 = model.GetTypeInfo(tuple2); Assert.Null(tupleType2.Type); Assert.Equal("(dynamic, dynamic d2)", tupleType2.ConvertedType.ToTestDisplayString()); } [Fact] public void TestBadConstraintOnTuple() { // https://github.com/dotnet/roslyn/issues/37121 : This test appears to produce a duplicate diagnostic at (6, 35) var source = @" ref struct S { void M(S s1, S s2) { System.Console.Write(("""", s1) == (null, s2)); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,35): error CS0306: The type 'S' may not be used as a type argument // System.Console.Write(("", s1) == (null, s2)); Diagnostic(ErrorCode.ERR_BadTypeArgument, "s1").WithArguments("S").WithLocation(6, 35), // (6,30): error CS0019: Operator '==' cannot be applied to operands of type 'S' and 'S' // System.Console.Write(("", s1) == (null, s2)); Diagnostic(ErrorCode.ERR_BadBinaryOps, @"("""", s1) == (null, s2)").WithArguments("==", "S", "S").WithLocation(6, 30), // (6,35): error CS0306: The type 'S' may not be used as a type argument // System.Console.Write(("", s1) == (null, s2)); Diagnostic(ErrorCode.ERR_BadTypeArgument, "s1").WithArguments("S").WithLocation(6, 35), // (6,49): error CS0306: The type 'S' may not be used as a type argument // System.Console.Write(("", s1) == (null, s2)); Diagnostic(ErrorCode.ERR_BadTypeArgument, "s2").WithArguments("S").WithLocation(6, 49) ); } [Fact] public void TestErrorInTuple() { var source = @" public class C { public void M() { if (error1 == (error2, 3)) { } } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,13): error CS0103: The name 'error1' does not exist in the current context // if (error1 == (error2, 3)) { } Diagnostic(ErrorCode.ERR_NameNotInContext, "error1").WithArguments("error1").WithLocation(6, 13), // (6,24): error CS0103: The name 'error2' does not exist in the current context // if (error1 == (error2, 3)) { } Diagnostic(ErrorCode.ERR_NameNotInContext, "error2").WithArguments("error2").WithLocation(6, 24) ); } [Fact] public void TestWithTypelessTuple() { var source = @" public class C { public void M() { var t = (null, null); if (null == (() => {}) ) {} if ("""" == 1) {} } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (6,13): error CS0815: Cannot assign (<null>, <null>) to an implicitly-typed variable // var t = (null, null); Diagnostic(ErrorCode.ERR_ImplicitlyTypedVariableAssignedBadValue, "t = (null, null)").WithArguments("(<null>, <null>)").WithLocation(6, 13), // (7,13): error CS0019: Operator '==' cannot be applied to operands of type '<null>' and 'lambda expression' // if (null == (() => {}) ) {} Diagnostic(ErrorCode.ERR_BadBinaryOps, "null == (() => {})").WithArguments("==", "<null>", "lambda expression").WithLocation(7, 13), // (8,13): error CS0019: Operator '==' cannot be applied to operands of type 'string' and 'int' // if ("" == 1) {} Diagnostic(ErrorCode.ERR_BadBinaryOps, @""""" == 1").WithArguments("==", "string", "int").WithLocation(8, 13) ); comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,13): error CS0815: Cannot assign (<null>, <null>) to an implicitly-typed variable // var t = (null, null); Diagnostic(ErrorCode.ERR_ImplicitlyTypedVariableAssignedBadValue, "t = (null, null)").WithArguments("(<null>, <null>)").WithLocation(6, 13), // (8,13): error CS0019: Operator '==' cannot be applied to operands of type 'string' and 'int' // if ("" == 1) {} Diagnostic(ErrorCode.ERR_BadBinaryOps, @""""" == 1").WithArguments("==", "string", "int").WithLocation(8, 13) ); } [Fact] public void TestTupleEqualityPreferredOverCustomOperator() { var source = @" 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 static bool operator ==(ValueTuple<T1, T2> t1, ValueTuple<T1, T2> t2) => throw null; public static bool operator !=(ValueTuple<T1, T2> t1, ValueTuple<T1, T2> t2) => throw null; public override bool Equals(object o) => throw null; public override int GetHashCode() => throw null; } } public class C { public static void Main() { var t1 = (1, 1); var t2 = (2, 2); System.Console.Write(t1 == t2); System.Console.Write(t1 != t2); } } "; var comp = CreateCompilationWithMscorlib40(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); // Note: tuple equality picked ahead of custom operator== (small compat break) CompileAndVerify(comp, expectedOutput: "FalseTrue"); } [Fact] public void TestCustomOperatorPlusAllowed() { var source = @" 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 static ValueTuple<T1, T2> operator +(ValueTuple<T1, T2> t1, ValueTuple<T1, T2> t2) => (default(T1), default(T2)); public override string ToString() => $""({Item1}, {Item2})""; } } public class C { public static void Main() { var t1 = (0, 1); var t2 = (2, 3); System.Console.Write(t1 + t2); } } "; var comp = CreateCompilationWithMscorlib40(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "(0, 0)"); } [Fact] void TestTupleEqualityPreferredOverCustomOperator_Nested() { string source = @" public class C { public static void Main() { System.Console.Write( (1, 2, (3, 4)) == (1, 2, (3, 4)) ); } } 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 static bool operator ==(ValueTuple<T1, T2> t1, ValueTuple<T1, T2> t2) => throw null; public static bool operator !=(ValueTuple<T1, T2> t1, ValueTuple<T1, T2> t2) => throw null; public override bool Equals(object o) => throw null; public override int GetHashCode() => throw null; } public struct ValueTuple<T1, T2, T3> { public T1 Item1; public T2 Item2; public T3 Item3; public ValueTuple(T1 item1, T2 item2, T3 item3) { this.Item1 = item1; this.Item2 = item2; this.Item3 = item3; } } } "; var comp = CreateCompilationWithMscorlib40(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); // Note: tuple equality picked ahead of custom operator== CompileAndVerify(comp, expectedOutput: "True"); } [Fact] public void TestNaN() { var source = @" public class C { public static void Main() { var t1 = (System.Double.NaN, 1); var t2 = (System.Double.NaN, 1); System.Console.Write($""{t1 == t2} {t1.Equals(t2)} {t1 != t2} {t1 == (System.Double.NaN, 1)}""); } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "False True True False"); } [Fact] public void TestTopLevelDynamic() { var source = @" public class C { public static void Main() { System.Globalization.CultureInfo saveUICulture = System.Threading.Thread.CurrentThread.CurrentUICulture; System.Threading.Thread.CurrentThread.CurrentUICulture = System.Globalization.CultureInfo.InvariantCulture; dynamic d1 = (1, 1); try { try { _ = d1 == (1, 1); } catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e) { System.Console.WriteLine(e.Message); } try { _ = d1 != (1, 2); } catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e) { System.Console.WriteLine(e.Message); } } finally { System.Threading.Thread.CurrentThread.CurrentUICulture = saveUICulture; } } } "; var comp = CreateCompilation(source, targetFramework: TargetFramework.StandardAndCSharp, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: @"Operator '==' cannot be applied to operands of type 'System.ValueTuple<int,int>' and 'System.ValueTuple<int,int>' Operator '!=' cannot be applied to operands of type 'System.ValueTuple<int,int>' and 'System.ValueTuple<int,int>'"); } [Fact] public void TestNestedDynamic() { var source = @" public class C { public static void Main() { System.Globalization.CultureInfo saveUICulture = System.Threading.Thread.CurrentThread.CurrentUICulture; System.Threading.Thread.CurrentThread.CurrentUICulture = System.Globalization.CultureInfo.InvariantCulture; dynamic d1 = (1, 1, 1); try { try { _ = (2, d1) == (2, (1, 1, 1)); } catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e) { System.Console.WriteLine(e.Message); } try { _ = (3, d1) != (3, (1, 2, 3)); } catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e) { System.Console.WriteLine(e.Message); } } finally { System.Threading.Thread.CurrentThread.CurrentUICulture = saveUICulture; } } } "; var comp = CreateCompilation(source, targetFramework: TargetFramework.StandardAndCSharp, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: @"Operator '==' cannot be applied to operands of type 'System.ValueTuple<int,int,int>' and 'System.ValueTuple<int,int,int>' Operator '!=' cannot be applied to operands of type 'System.ValueTuple<int,int,int>' and 'System.ValueTuple<int,int,int>'"); } [Fact] public void TestComparisonWithDeconstructionResult() { var source = @" public class C { public static void Main() { var b1 = (1, 2) == ((_, _) = new C()); var b2 = (1, 42) != ((_, _) = new C()); var b3 = (1, 42) == ((_, _) = new C()); // false var b4 = ((_, _) = new C()) == (1, 2); var b5 = ((_, _) = new C()) != (1, 42); var b6 = ((_, _) = new C()) == (1, 42); // false System.Console.Write($""{b1} {b2} {b3} {b4} {b5} {b6}""); } public void Deconstruct(out int x, out int y) { x = 1; y = 2; } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: @"True True False True True False"); } [Fact] public void TestComparisonWithDeconstruction() { var source = @" public class C { public static void Main() { var b1 = (1, 2) == new C(); } public void Deconstruct(out int x, out int y) { x = 1; y = 2; } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,18): error CS0019: Operator '==' cannot be applied to operands of type '(int, int)' and 'C' // var b1 = (1, 2) == new C(); Diagnostic(ErrorCode.ERR_BadBinaryOps, "(1, 2) == new C()").WithArguments("==", "(int, int)", "C").WithLocation(6, 18) ); } [Fact] public void TestEvaluationOrderOnTupleLiteral() { var source = @" public class C { public static void Main() { System.Console.Write($""{EXPRESSION}""); } } 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; throw null; } } } public class Base { public int I; public Base(int i) { I = i; } } public class A : Base { public A(int i) : base(i) { System.Console.Write($""A:{i}, ""); } public static bool operator ==(A a, Y y) { System.Console.Write($""A({a.I}) == Y({y.I}), ""); return a.I == y.I; } public static bool operator !=(A a, Y y) { System.Console.Write($""A({a.I}) != Y({y.I}), ""); return a.I != y.I; } public override bool Equals(object o) => throw null; public override int GetHashCode() => throw null; } public class X : Base { public X(int i) : base(i) { System.Console.Write($""X:{i}, ""); } } public class Y : Base { public Y(int i) : base(i) { System.Console.Write($""Y:{i}, ""); } public static implicit operator Y(X x) { System.Console.Write(""X -> ""); return new Y(x.I); } } "; validate("(new A(1), new A(2)) == (new X(1), new Y(2))", "A:1, A:2, X:1, Y:2, X -> Y:1, A(1) == Y(1), A(2) == Y(2), True"); validate("(new A(1), new A(2)) == (new X(30), new Y(40))", "A:1, A:2, X:30, Y:40, X -> Y:30, A(1) == Y(30), False"); validate("(new A(1), new A(2)) == (new X(1), new Y(50))", "A:1, A:2, X:1, Y:50, X -> Y:1, A(1) == Y(1), A(2) == Y(50), False"); validate("(new A(1), new A(2)) != (new X(1), new Y(2))", "A:1, A:2, X:1, Y:2, X -> Y:1, A(1) != Y(1), A(2) != Y(2), False"); validate("(new A(1), new A(2)) != (new Y(1), new X(2))", "A:1, A:2, Y:1, X:2, A(1) != Y(1), X -> Y:2, A(2) != Y(2), False"); validate("(new A(1), new A(2)) != (new X(30), new Y(40))", "A:1, A:2, X:30, Y:40, X -> Y:30, A(1) != Y(30), True"); validate("(new A(1), new A(2)) != (new X(50), new Y(2))", "A:1, A:2, X:50, Y:2, X -> Y:50, A(1) != Y(50), True"); validate("(new A(1), new A(2)) != (new X(1), new Y(60))", "A:1, A:2, X:1, Y:60, X -> Y:1, A(1) != Y(1), A(2) != Y(60), True"); void validate(string expression, string expected) { var comp = CreateCompilation(source.Replace("EXPRESSION", expression), options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: expected); } } [Fact] public void TestEvaluationOrderOnTupleType() { var source = @" namespace System { public struct ValueTuple<T1, T2> { public T1 Item1; public T2 Item2; public ValueTuple(T1 item1, T2 item2) { System.Console.Write(""ValueTuple2, ""); this.Item1 = item1; this.Item2 = item2; } } public struct ValueTuple<T1, T2, T3> { public ValueTuple(T1 item1, T2 item2, T3 item3) { // ValueTuple'3 required (constructed in bound tree), but not emitted throw null; } } } public class Base { public int I; public Base(int i) { I = i; } } public class A : Base { public A(int i) : base(i) { System.Console.Write($""A:{i}, ""); } public static bool operator ==(A a, Y y) { System.Console.Write($""A({a.I}) == Y({y.I}), ""); return true; } public static bool operator !=(A a, Y y) => throw null; public override bool Equals(object o) => throw null; public override int GetHashCode() => throw null; } public class X : Base { public X(int i) : base(i) { System.Console.Write($""X:{i}, ""); } } public class Y : Base { public Y(int i) : base(i) { System.Console.Write($""Y:{i}, ""); } public static implicit operator Y(X x) { System.Console.Write(""X -> ""); return new Y(x.I); } } public class C { public static void Main() { System.Console.Write($""{(new A(1), GetTuple(), new A(4)) == (new X(5), (new X(6), new Y(7)), new Y(8))}""); } public static (A, A) GetTuple() { System.Console.Write($""GetTuple, ""); return (new A(30), new A(40)); } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "A:1, GetTuple, A:30, A:40, ValueTuple2, A:4, X:5, X:6, Y:7, Y:8, X -> Y:5, A(1) == Y(5), X -> Y:6, A(30) == Y(6), A(40) == Y(7), A(4) == Y(8), True"); } [Fact] public void TestConstrainedValueTuple() { var source = @" class C { void M() { _ = (this, this) == (0, 1); // constraint violated by tuple in source _ = (this, this) == (this, this); // constraint violated by converted tuple } public static bool operator ==(C c, int i) => throw null; public static bool operator !=(C c, int i) => throw null; public override bool Equals(object o) => throw null; public override int GetHashCode() => throw null; public static implicit operator int(C c) => throw null; } namespace System { public struct ValueTuple<T1, T2> where T1 : class where T2 : class { public T1 Item1; public T2 Item2; public ValueTuple(T1 item1, T2 item2) { this.Item1 = item1; this.Item2 = item2; throw null; } } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,30): error CS0452: The type 'int' must be a reference type in order to use it as parameter 'T1' in the generic type or method '(T1, T2)' // _ = (this, this) == (0, 1); // constraint violated by tuple in source Diagnostic(ErrorCode.ERR_RefConstraintNotSatisfied, "0").WithArguments("(T1, T2)", "T1", "int").WithLocation(6, 30), // (6,30): error CS0452: The type 'int' must be a reference type in order to use it as parameter 'T1' in the generic type or method '(T1, T2)' // _ = (this, this) == (0, 1); // constraint violated by tuple in source Diagnostic(ErrorCode.ERR_RefConstraintNotSatisfied, "0").WithArguments("(T1, T2)", "T1", "int").WithLocation(6, 30), // (6,33): error CS0452: The type 'int' must be a reference type in order to use it as parameter 'T2' in the generic type or method '(T1, T2)' // _ = (this, this) == (0, 1); // constraint violated by tuple in source Diagnostic(ErrorCode.ERR_RefConstraintNotSatisfied, "1").WithArguments("(T1, T2)", "T2", "int").WithLocation(6, 33), // (6,33): error CS0452: The type 'int' must be a reference type in order to use it as parameter 'T2' in the generic type or method '(T1, T2)' // _ = (this, this) == (0, 1); // constraint violated by tuple in source Diagnostic(ErrorCode.ERR_RefConstraintNotSatisfied, "1").WithArguments("(T1, T2)", "T2", "int").WithLocation(6, 33), // (7,30): error CS0452: The type 'int' must be a reference type in order to use it as parameter 'T1' in the generic type or method '(T1, T2)' // _ = (this, this) == (this, this); // constraint violated by converted tuple Diagnostic(ErrorCode.ERR_RefConstraintNotSatisfied, "this").WithArguments("(T1, T2)", "T1", "int").WithLocation(7, 30), // (7,36): error CS0452: The type 'int' must be a reference type in order to use it as parameter 'T2' in the generic type or method '(T1, T2)' // _ = (this, this) == (this, this); // constraint violated by converted tuple Diagnostic(ErrorCode.ERR_RefConstraintNotSatisfied, "this").WithArguments("(T1, T2)", "T2", "int").WithLocation(7, 36) ); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); // check the int tuple var firstEquals = tree.GetCompilationUnitRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().First(); var intTuple = firstEquals.Right; Assert.Equal("(0, 1)", intTuple.ToString()); var intTupleType = model.GetTypeInfo(intTuple); Assert.Equal("(System.Int32, System.Int32)", intTupleType.Type.ToTestDisplayString()); Assert.Equal("(System.Int32, System.Int32)", intTupleType.ConvertedType.ToTestDisplayString()); // check the last tuple var secondEquals = tree.GetCompilationUnitRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().Last(); var lastTuple = secondEquals.Right; Assert.Equal("(this, this)", lastTuple.ToString()); var lastTupleType = model.GetTypeInfo(lastTuple); Assert.Equal("(C, C)", lastTupleType.Type.ToTestDisplayString()); Assert.Equal("(System.Int32, System.Int32)", lastTupleType.ConvertedType.ToTestDisplayString()); } [Fact] public void TestConstrainedNullable() { var source = @" class C { void M((int, int)? t1, (long, long)? t2) { _ = t1 == t2; } } public interface IInterface { } namespace System { public class Object { } public abstract class ValueType { } public struct Void { } public struct Boolean { } public struct Int32 { } public struct Int64 { } public struct Nullable<T> where T : struct, IInterface { public T GetValueOrDefault() => default(T); } public class Exception { } public struct ValueTuple<T1, T2> { public T1 Item1; public T2 Item2; public ValueTuple(T1 item1, T2 item2) { this.Item1 = item1; this.Item2 = item2; throw null; } } } "; var comp = CreateEmptyCompilation(source); comp.VerifyDiagnostics( // (4,24): error CS0315: The type '(int, int)' cannot be used as type parameter 'T' in the generic type or method 'Nullable<T>'. There is no boxing conversion from '(int, int)' to 'IInterface'. // void M((int, int)? t1, (long, long)? t2) Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedValType, "t1").WithArguments("System.Nullable<T>", "IInterface", "T", "(int, int)").WithLocation(4, 24), // (4,42): error CS0315: The type '(long, long)' cannot be used as type parameter 'T' in the generic type or method 'Nullable<T>'. There is no boxing conversion from '(long, long)' to 'IInterface'. // void M((int, int)? t1, (long, long)? t2) Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedValType, "t2").WithArguments("System.Nullable<T>", "IInterface", "T", "(long, long)").WithLocation(4, 42) ); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); // check t1 var equals = tree.GetCompilationUnitRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().Last(); var t1 = equals.Left; Assert.Equal("t1", t1.ToString()); var t1Type = model.GetTypeInfo(t1); Assert.Equal("(System.Int32, System.Int32)?", t1Type.Type.ToTestDisplayString()); Assert.Equal("(System.Int64, System.Int64)?", t1Type.ConvertedType.ToTestDisplayString()); } [Fact] public void TestEvaluationOrderOnTupleType2() { var source = @" namespace System { public struct ValueTuple<T1, T2> { public T1 Item1; public T2 Item2; public ValueTuple(T1 item1, T2 item2) { System.Console.Write(""ValueTuple2, ""); this.Item1 = item1; this.Item2 = item2; } } public struct ValueTuple<T1, T2, T3> { public ValueTuple(T1 item1, T2 item2, T3 item3) { // ValueTuple'3 required (constructed in bound tree), but not emitted throw null; } } } public class Base { public int I; public Base(int i) { I = i; } } public class A : Base { public A(int i) : base(i) { System.Console.Write($""A:{i}, ""); } public static bool operator ==(A a, Y y) { System.Console.Write($""A({a.I}) == Y({y.I}), ""); return true; } public static bool operator !=(A a, Y y) => throw null; public override bool Equals(object o) => throw null; public override int GetHashCode() => throw null; } public class X : Base { public X(int i) : base(i) { System.Console.Write($""X:{i}, ""); } } public class Y : Base { public Y(int i) : base(i) { System.Console.Write($""Y:{i}, ""); } public static implicit operator Y(X x) { System.Console.Write($""X:{x.I} -> ""); return new Y(x.I); } } public class C { public static void Main() { System.Console.Write($""{(new A(1), (new A(2), new A(3)), new A(4)) == (new X(5), GetTuple(), new Y(8))}""); } public static (X, Y) GetTuple() { System.Console.Write($""GetTuple, ""); return (new X(6), new Y(7)); } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: @"A:1, A:2, A:3, A:4, X:5, GetTuple, X:6, Y:7, ValueTuple2, Y:8, X:5 -> Y:5, A(1) == Y(5), X:6 -> Y:6, A(2) == Y(6), A(3) == Y(7), A(4) == Y(8), True"); } [Fact] public void TestEvaluationOrderOnTupleType3() { var source = @" namespace System { public struct ValueTuple<T1, T2> { public T1 Item1; public T2 Item2; public ValueTuple(T1 item1, T2 item2) { System.Console.Write(""ValueTuple2, ""); this.Item1 = item1; this.Item2 = item2; } } public struct ValueTuple<T1, T2, T3> { public ValueTuple(T1 item1, T2 item2, T3 item3) { // ValueTuple'3 required (constructed in bound tree), but not emitted throw null; } } } public class Base { public int I; public Base(int i) { I = i; } } public class A : Base { public A(int i) : base(i) { System.Console.Write($""A:{i}, ""); } public static bool operator ==(A a, Y y) { System.Console.Write($""A({a.I}) == Y({y.I}), ""); return true; } public static bool operator !=(A a, Y y) => throw null; public override bool Equals(object o) => throw null; public override int GetHashCode() => throw null; } public class X : Base { public X(int i) : base(i) { System.Console.Write($""X:{i}, ""); } } public class Y : Base { public Y(int i) : base(i) { System.Console.Write($""Y:{i}, ""); } public static implicit operator Y(X x) { System.Console.Write(""X -> ""); return new Y(x.I); } } public class C { public static void Main() { System.Console.Write($""{GetTuple() == (new X(6), new Y(7))}""); } public static (A, A) GetTuple() { System.Console.Write($""GetTuple, ""); return (new A(30), new A(40)); } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "GetTuple, A:30, A:40, ValueTuple2, X:6, Y:7, X -> Y:6, A(30) == Y(6), A(40) == Y(7), True"); } [Fact] public void TestObsoleteEqualityOperator() { var source = @" class C { void M() { System.Console.WriteLine($""{(new A(), new A()) == (new X(), new Y())}""); System.Console.WriteLine($""{(new A(), new A()) != (new X(), new Y())}""); } } public class A { [System.Obsolete(""obsolete"", true)] public static bool operator ==(A a, Y y) => throw null; [System.Obsolete(""obsolete too"", true)] public static bool operator !=(A a, Y y) => throw null; public override bool Equals(object o) => throw null; public override int GetHashCode() => throw null; } public class X { } public class Y { public static implicit operator Y(X x) => throw null; } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,37): error CS0619: 'A.operator ==(A, Y)' is obsolete: 'obsolete' // System.Console.WriteLine($"{(new A(), new A()) == (new X(), new Y())}"); Diagnostic(ErrorCode.ERR_DeprecatedSymbolStr, "(new A(), new A()) == (new X(), new Y())").WithArguments("A.operator ==(A, Y)", "obsolete").WithLocation(6, 37), // (6,37): error CS0619: 'A.operator ==(A, Y)' is obsolete: 'obsolete' // System.Console.WriteLine($"{(new A(), new A()) == (new X(), new Y())}"); Diagnostic(ErrorCode.ERR_DeprecatedSymbolStr, "(new A(), new A()) == (new X(), new Y())").WithArguments("A.operator ==(A, Y)", "obsolete").WithLocation(6, 37), // (7,37): error CS0619: 'A.operator !=(A, Y)' is obsolete: 'obsolete too' // System.Console.WriteLine($"{(new A(), new A()) != (new X(), new Y())}"); Diagnostic(ErrorCode.ERR_DeprecatedSymbolStr, "(new A(), new A()) != (new X(), new Y())").WithArguments("A.operator !=(A, Y)", "obsolete too").WithLocation(7, 37), // (7,37): error CS0619: 'A.operator !=(A, Y)' is obsolete: 'obsolete too' // System.Console.WriteLine($"{(new A(), new A()) != (new X(), new Y())}"); Diagnostic(ErrorCode.ERR_DeprecatedSymbolStr, "(new A(), new A()) != (new X(), new Y())").WithArguments("A.operator !=(A, Y)", "obsolete too").WithLocation(7, 37) ); } [Fact] public void TestDefiniteAssignment() { var source = @" class C { void M() { int error1; System.Console.Write((1, 2) == (error1, 2)); int error2; System.Console.Write((1, (error2, 3)) == (1, (2, 3))); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (7,41): error CS0165: Use of unassigned local variable 'error1' // System.Console.Write((1, 2) == (error1, 2)); Diagnostic(ErrorCode.ERR_UseDefViolation, "error1").WithArguments("error1").WithLocation(7, 41), // (10,35): error CS0165: Use of unassigned local variable 'error2' // System.Console.Write((1, (error2, 3)) == (1, (2, 3))); Diagnostic(ErrorCode.ERR_UseDefViolation, "error2").WithArguments("error2").WithLocation(10, 35) ); } [Fact] public void TestDefiniteAssignment2() { var source = @" class C { int M(out int x) { _ = (M(out int y), y) == (1, 2); // ok _ = (z, M(out int z)) == (1, 2); // error x = 1; return 2; } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (7,14): error CS0841: Cannot use local variable 'z' before it is declared // _ = (z, M(out int z)) == (1, 2); // error Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "z").WithArguments("z").WithLocation(7, 14) ); } [Fact] public void TestEqualityOfTypeConvertingToTuple() { var source = @" class C { private int i; void M() { System.Console.Write(this == (1, 1)); System.Console.Write((1, 1) == this); } public static implicit operator (int, int)(C c) { return (c.i, c.i); } C(int i) { this.i = i; } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (7,30): error CS0019: Operator '==' cannot be applied to operands of type 'C' and '(int, int)' // System.Console.Write(this == (1, 1)); Diagnostic(ErrorCode.ERR_BadBinaryOps, "this == (1, 1)").WithArguments("==", "C", "(int, int)").WithLocation(7, 30), // (8,30): error CS0019: Operator '==' cannot be applied to operands of type '(int, int)' and 'C' // System.Console.Write((1, 1) == this); Diagnostic(ErrorCode.ERR_BadBinaryOps, "(1, 1) == this").WithArguments("==", "(int, int)", "C").WithLocation(8, 30) ); } [Fact] public void TestEqualityOfTypeConvertingFromTuple() { var source = @" class C { private int i; public static void Main() { var c = new C(2); System.Console.Write(c == (1, 1)); System.Console.Write((1, 1) == c); } public static implicit operator C((int, int) x) { return new C(x.Item1 + x.Item2); } public static bool operator ==(C c1, C c2) => c1.i == c2.i; public static bool operator !=(C c1, C c2) => throw null; public override int GetHashCode() => throw null; public override bool Equals(object other) => throw null; C(int i) { this.i = i; } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "TrueTrue"); } [Fact] public void TestEqualityOfTypeComparableWithTuple() { var source = @" class C { private static void Main() { System.Console.Write(new C() == (1, 1)); System.Console.Write(new C() != (1, 1)); } public static bool operator ==(C c, (int, int) t) { return t.Item1 + t.Item2 == 2; } public static bool operator !=(C c, (int, int) t) { return t.Item1 + t.Item2 != 2; } public override bool Equals(object o) => throw null; public override int GetHashCode() => throw null; } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "TrueFalse"); } [Fact] public void TestOfTwoUnrelatedTypes() { var source = @" class A { } class C { static void M() { System.Console.Write(new C() == new A()); System.Console.Write((1, new C()) == (1, new A())); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (7,30): error CS0019: Operator '==' cannot be applied to operands of type 'C' and 'A' // System.Console.Write(new C() == new A()); Diagnostic(ErrorCode.ERR_BadBinaryOps, "new C() == new A()").WithArguments("==", "C", "A").WithLocation(7, 30), // (8,30): error CS0019: Operator '==' cannot be applied to operands of type 'C' and 'A' // System.Console.Write((1, new C()) == (1, new A())); Diagnostic(ErrorCode.ERR_BadBinaryOps, "(1, new C()) == (1, new A())").WithArguments("==", "C", "A").WithLocation(8, 30) ); } [Fact] public void TestOfTwoUnrelatedTypes2() { var source = @" class A { } class C { static void M(string s, System.Exception e) { System.Console.Write(s == 3); System.Console.Write((1, s) == (1, e)); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (7,30): error CS0019: Operator '==' cannot be applied to operands of type 'string' and 'int' // System.Console.Write(s == 3); Diagnostic(ErrorCode.ERR_BadBinaryOps, "s == 3").WithArguments("==", "string", "int").WithLocation(7, 30), // (8,30): error CS0019: Operator '==' cannot be applied to operands of type 'string' and 'Exception' // System.Console.Write((1, s) == (1, e)); Diagnostic(ErrorCode.ERR_BadBinaryOps, "(1, s) == (1, e)").WithArguments("==", "string", "System.Exception").WithLocation(8, 30) ); } [Fact] public void TestBadRefCompare() { var source = @" class C { static void M() { string s = ""11""; object o = s + s; (object, object) t = default; bool b = o == s; bool b2 = t == (s, s); // no warning } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (10,18): warning CS0252: Possible unintended reference comparison; to get a value comparison, cast the left hand side to type 'string' // bool b = o == s; Diagnostic(ErrorCode.WRN_BadRefCompareLeft, "o == s").WithArguments("string").WithLocation(10, 18) ); } [Fact, WorkItem(27047, "https://github.com/dotnet/roslyn/issues/27047")] public void TestWithObsoleteImplicitConversion() { var source = @" class C { private static bool TupleEquals((C, int)? nt1, (int, C) nt2) => nt1 == nt2; // warn 1 and 2 private static bool TupleNotEquals((C, int)? nt1, (int, C) nt2) => nt1 != nt2; // warn 3 and 4 [System.Obsolete(""obsolete"", error: true)] public static implicit operator int(C c) => throw null; } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (5,12): error CS0619: 'C.implicit operator int(C)' is obsolete: 'obsolete' // => nt1 == nt2; // warn 1 and 2 Diagnostic(ErrorCode.ERR_DeprecatedSymbolStr, "nt1").WithArguments("C.implicit operator int(C)", "obsolete").WithLocation(5, 12), // (5,19): error CS0619: 'C.implicit operator int(C)' is obsolete: 'obsolete' // => nt1 == nt2; // warn 1 and 2 Diagnostic(ErrorCode.ERR_DeprecatedSymbolStr, "nt2").WithArguments("C.implicit operator int(C)", "obsolete").WithLocation(5, 19), // (8,12): error CS0619: 'C.implicit operator int(C)' is obsolete: 'obsolete' // => nt1 != nt2; // warn 3 and 4 Diagnostic(ErrorCode.ERR_DeprecatedSymbolStr, "nt1").WithArguments("C.implicit operator int(C)", "obsolete").WithLocation(8, 12), // (8,19): error CS0619: 'C.implicit operator int(C)' is obsolete: 'obsolete' // => nt1 != nt2; // warn 3 and 4 Diagnostic(ErrorCode.ERR_DeprecatedSymbolStr, "nt2").WithArguments("C.implicit operator int(C)", "obsolete").WithLocation(8, 19) ); } [Fact, WorkItem(27047, "https://github.com/dotnet/roslyn/issues/27047")] public void TestWithObsoleteBoolConversion() { var source = @" public class A { public static bool TupleEquals((A, A) t) => t == t; // warn 1 and 2 public static bool TupleNotEquals((A, A) t) => t != t; // warn 3 and 4 public static NotBool operator ==(A a1, A a2) => throw null; public static NotBool operator !=(A a1, A a2) => throw null; public override bool Equals(object o) => throw null; public override int GetHashCode() => throw null; } public class NotBool { [System.Obsolete(""obsolete"", error: true)] public static implicit operator bool(NotBool b) => throw null; } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (4,49): error CS0619: 'NotBool.implicit operator bool(NotBool)' is obsolete: 'obsolete' // public static bool TupleEquals((A, A) t) => t == t; // warn 1 and 2 Diagnostic(ErrorCode.ERR_DeprecatedSymbolStr, "t == t").WithArguments("NotBool.implicit operator bool(NotBool)", "obsolete").WithLocation(4, 49), // (4,49): error CS0619: 'NotBool.implicit operator bool(NotBool)' is obsolete: 'obsolete' // public static bool TupleEquals((A, A) t) => t == t; // warn 1 and 2 Diagnostic(ErrorCode.ERR_DeprecatedSymbolStr, "t == t").WithArguments("NotBool.implicit operator bool(NotBool)", "obsolete").WithLocation(4, 49), // (5,52): error CS0619: 'NotBool.implicit operator bool(NotBool)' is obsolete: 'obsolete' // public static bool TupleNotEquals((A, A) t) => t != t; // warn 3 and 4 Diagnostic(ErrorCode.ERR_DeprecatedSymbolStr, "t != t").WithArguments("NotBool.implicit operator bool(NotBool)", "obsolete").WithLocation(5, 52), // (5,52): error CS0619: 'NotBool.implicit operator bool(NotBool)' is obsolete: 'obsolete' // public static bool TupleNotEquals((A, A) t) => t != t; // warn 3 and 4 Diagnostic(ErrorCode.ERR_DeprecatedSymbolStr, "t != t").WithArguments("NotBool.implicit operator bool(NotBool)", "obsolete").WithLocation(5, 52) ); } [Fact, WorkItem(27047, "https://github.com/dotnet/roslyn/issues/27047")] public void TestWithObsoleteComparisonOperators() { var source = @" public class A { public static bool TupleEquals((A, A) t) => t == t; // warn 1 and 2 public static bool TupleNotEquals((A, A) t) => t != t; // warn 3 and 4 [System.Obsolete("""", error: true)] public static bool operator ==(A a1, A a2) => throw null; [System.Obsolete("""", error: true)] public static bool operator !=(A a1, A a2) => throw null; public override bool Equals(object o) => throw null; public override int GetHashCode() => throw null; } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (4,49): error CS0619: 'A.operator ==(A, A)' is obsolete: '' // public static bool TupleEquals((A, A) t) => t == t; // warn 1 and 2 Diagnostic(ErrorCode.ERR_DeprecatedSymbolStr, "t == t").WithArguments("A.operator ==(A, A)", "").WithLocation(4, 49), // (4,49): error CS0619: 'A.operator ==(A, A)' is obsolete: '' // public static bool TupleEquals((A, A) t) => t == t; // warn 1 and 2 Diagnostic(ErrorCode.ERR_DeprecatedSymbolStr, "t == t").WithArguments("A.operator ==(A, A)", "").WithLocation(4, 49), // (5,52): error CS0619: 'A.operator !=(A, A)' is obsolete: '' // public static bool TupleNotEquals((A, A) t) => t != t; // warn 3 and 4 Diagnostic(ErrorCode.ERR_DeprecatedSymbolStr, "t != t").WithArguments("A.operator !=(A, A)", "").WithLocation(5, 52), // (5,52): error CS0619: 'A.operator !=(A, A)' is obsolete: '' // public static bool TupleNotEquals((A, A) t) => t != t; // warn 3 and 4 Diagnostic(ErrorCode.ERR_DeprecatedSymbolStr, "t != t").WithArguments("A.operator !=(A, A)", "").WithLocation(5, 52) ); } [Fact, WorkItem(27047, "https://github.com/dotnet/roslyn/issues/27047")] public void TestWithObsoleteTruthOperators() { var source = @" public class A { public static bool TupleEquals((A, A) t) => t == t; // warn 1 and 2 public static bool TupleNotEquals((A, A) t) => t != t; // warn 3 and 4 public static NotBool operator ==(A a1, A a2) => throw null; public static NotBool operator !=(A a1, A a2) => throw null; public override bool Equals(object o) => throw null; public override int GetHashCode() => throw null; } public class NotBool { [System.Obsolete(""obsolete"", error: true)] public static bool operator true(NotBool b) => throw null; [System.Obsolete(""obsolete"", error: true)] public static bool operator false(NotBool b) => throw null; } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (4,49): error CS0619: 'NotBool.operator false(NotBool)' is obsolete: 'obsolete' // public static bool TupleEquals((A, A) t) => t == t; // warn 1 and 2 Diagnostic(ErrorCode.ERR_DeprecatedSymbolStr, "t == t").WithArguments("NotBool.operator false(NotBool)", "obsolete").WithLocation(4, 49), // (4,49): error CS0619: 'NotBool.operator false(NotBool)' is obsolete: 'obsolete' // public static bool TupleEquals((A, A) t) => t == t; // warn 1 and 2 Diagnostic(ErrorCode.ERR_DeprecatedSymbolStr, "t == t").WithArguments("NotBool.operator false(NotBool)", "obsolete").WithLocation(4, 49), // (5,52): error CS0619: 'NotBool.operator true(NotBool)' is obsolete: 'obsolete' // public static bool TupleNotEquals((A, A) t) => t != t; // warn 3 and 4 Diagnostic(ErrorCode.ERR_DeprecatedSymbolStr, "t != t").WithArguments("NotBool.operator true(NotBool)", "obsolete").WithLocation(5, 52), // (5,52): error CS0619: 'NotBool.operator true(NotBool)' is obsolete: 'obsolete' // public static bool TupleNotEquals((A, A) t) => t != t; // warn 3 and 4 Diagnostic(ErrorCode.ERR_DeprecatedSymbolStr, "t != t").WithArguments("NotBool.operator true(NotBool)", "obsolete").WithLocation(5, 52) ); } [Fact] public void TestEqualOnNullableVsNullableTuples() { var source = @" class C { public static void Main() { Compare(null, null); Compare(null, (1, 2)); Compare((2, 3), null); Compare((4, 4), (4, 4)); Compare((5, 5), (10, 10)); } private static void Compare((int, int)? nt1, (int, int)? nt2) { System.Console.Write($""{nt1 == nt2} ""); } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "True False False True False"); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var comparison = tree.GetCompilationUnitRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().Single(); var nt1 = comparison.Left; var nt1Type = model.GetTypeInfo(nt1); Assert.Equal("nt1", nt1.ToString()); Assert.Equal("(System.Int32, System.Int32)?", nt1Type.Type.ToTestDisplayString()); Assert.Equal("(System.Int32, System.Int32)?", nt1Type.ConvertedType.ToTestDisplayString()); var nt2 = comparison.Right; var nt2Type = model.GetTypeInfo(nt2); Assert.Equal("nt2", nt2.ToString()); Assert.Equal("(System.Int32, System.Int32)?", nt2Type.Type.ToTestDisplayString()); Assert.Equal("(System.Int32, System.Int32)?", nt2Type.ConvertedType.ToTestDisplayString()); verifier.VerifyIL("C.Compare", @"{ // Code size 104 (0x68) .maxstack 3 .locals init (System.ValueTuple<int, int>? V_0, System.ValueTuple<int, int>? V_1, bool V_2, System.ValueTuple<int, int> V_3, System.ValueTuple<int, int> V_4) IL_0000: nop IL_0001: ldstr ""{0} "" IL_0006: ldarg.0 IL_0007: stloc.0 IL_0008: ldarg.1 IL_0009: stloc.1 IL_000a: ldloca.s V_0 IL_000c: call ""bool System.ValueTuple<int, int>?.HasValue.get"" IL_0011: stloc.2 IL_0012: ldloc.2 IL_0013: ldloca.s V_1 IL_0015: call ""bool System.ValueTuple<int, int>?.HasValue.get"" IL_001a: beq.s IL_001f IL_001c: ldc.i4.0 IL_001d: br.s IL_0057 IL_001f: ldloc.2 IL_0020: brtrue.s IL_0025 IL_0022: ldc.i4.1 IL_0023: br.s IL_0057 IL_0025: ldloca.s V_0 IL_0027: call ""System.ValueTuple<int, int> System.ValueTuple<int, int>?.GetValueOrDefault()"" IL_002c: stloc.3 IL_002d: ldloca.s V_1 IL_002f: call ""System.ValueTuple<int, int> System.ValueTuple<int, int>?.GetValueOrDefault()"" IL_0034: stloc.s V_4 IL_0036: ldloc.3 IL_0037: ldfld ""int System.ValueTuple<int, int>.Item1"" IL_003c: ldloc.s V_4 IL_003e: ldfld ""int System.ValueTuple<int, int>.Item1"" IL_0043: bne.un.s IL_0056 IL_0045: ldloc.3 IL_0046: ldfld ""int System.ValueTuple<int, int>.Item2"" IL_004b: ldloc.s V_4 IL_004d: ldfld ""int System.ValueTuple<int, int>.Item2"" IL_0052: ceq IL_0054: br.s IL_0057 IL_0056: ldc.i4.0 IL_0057: box ""bool"" IL_005c: call ""string string.Format(string, object)"" IL_0061: call ""void System.Console.Write(string)"" IL_0066: nop IL_0067: ret }"); } [Fact] public void TestEqualOnNullableVsNullableTuples_NeverNull() { var source = @" class C { public static void Main() { System.Console.Write(((int, int)?) (1, 2) == ((int, int)?) (1, 2)); } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "True"); verifier.VerifyIL("C.Main", @" { // Code size 19 (0x13) .maxstack 2 IL_0000: nop IL_0001: ldc.i4.1 IL_0002: ldc.i4.1 IL_0003: bne.un.s IL_000b IL_0005: ldc.i4.2 IL_0006: ldc.i4.2 IL_0007: ceq IL_0009: br.s IL_000c IL_000b: ldc.i4.0 IL_000c: call ""void System.Console.Write(bool)"" IL_0011: nop IL_0012: ret } "); } [Fact] public void TestEqualOnNullableVsNullableTuples_OneSideNeverNull() { var source = @" class C { public static void Main() { System.Console.Write(((int, int)?) (1, 2) == (1, 2)); } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "True"); verifier.VerifyIL("C.Main", @" { // Code size 19 (0x13) .maxstack 2 IL_0000: nop IL_0001: ldc.i4.1 IL_0002: ldc.i4.1 IL_0003: bne.un.s IL_000b IL_0005: ldc.i4.2 IL_0006: ldc.i4.2 IL_0007: ceq IL_0009: br.s IL_000c IL_000b: ldc.i4.0 IL_000c: call ""void System.Console.Write(bool)"" IL_0011: nop IL_0012: ret } "); } [Fact] public void TestEqualOnNullableVsNullableTuples_Tuple_AlwaysNull_AlwaysNull() { var source = @" class C { public static void Main() { System.Console.Write(((int, int)?)null == ((int, int)?)null); } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "True"); verifier.VerifyIL("C.Main", @"{ // Code size 9 (0x9) .maxstack 1 IL_0000: nop IL_0001: ldc.i4.1 IL_0002: call ""void System.Console.Write(bool)"" IL_0007: nop IL_0008: ret } "); CompileAndVerify(source, options: TestOptions.ReleaseExe).VerifyIL("C.Main", @"{ // Code size 7 (0x7) .maxstack 1 IL_0000: ldc.i4.1 IL_0001: call ""void System.Console.Write(bool)"" IL_0006: ret } "); } [Fact] public void TestEqualOnNullableVsNullableTuples_Tuple_MaybeNull_AlwaysNull() { var source = @" class C { public static void Main() { M(null); M((1, 2)); } public static void M((int, int)? t) { System.Console.Write(t == ((int, int)?)null); } } "; CompileAndVerify(source, expectedOutput: "TrueFalse", options: TestOptions.ReleaseExe).VerifyIL("C.M", @"{ // Code size 18 (0x12) .maxstack 2 .locals init (System.ValueTuple<int, int>? V_0) IL_0000: ldarg.0 IL_0001: stloc.0 IL_0002: ldloca.s V_0 IL_0004: call ""bool System.ValueTuple<int, int>?.HasValue.get"" IL_0009: ldc.i4.0 IL_000a: ceq IL_000c: call ""void System.Console.Write(bool)"" IL_0011: ret } "); } [Fact] public void TestNotEqualOnNullableVsNullableTuples_Tuple_MaybeNull_AlwaysNull() { var source = @" class C { public static void Main() { M(null); M((1, 2)); } public static void M((int, int)? t) { System.Console.Write(t != ((int, int)?)null); } } "; CompileAndVerify(source, expectedOutput: "FalseTrue", options: TestOptions.ReleaseExe).VerifyIL("C.M", @"{ // Code size 15 (0xf) .maxstack 1 .locals init (System.ValueTuple<int, int>? V_0) IL_0000: ldarg.0 IL_0001: stloc.0 IL_0002: ldloca.s V_0 IL_0004: call ""bool System.ValueTuple<int, int>?.HasValue.get"" IL_0009: call ""void System.Console.Write(bool)"" IL_000e: ret } "); } [Fact] public void TestNotEqualOnNullableVsNullableTuples_Tuple_AlwaysNull_MaybeNull() { var source = @" class C { public static void Main() { M(null); M((1, 2)); } public static void M((int, int)? t) { System.Console.Write(((int, int)?)null == t); } } "; CompileAndVerify(source, expectedOutput: "TrueFalse", options: TestOptions.ReleaseExe).VerifyIL("C.M", @"{ // Code size 18 (0x12) .maxstack 2 .locals init (System.ValueTuple<int, int>? V_0) IL_0000: ldarg.0 IL_0001: stloc.0 IL_0002: ldloca.s V_0 IL_0004: call ""bool System.ValueTuple<int, int>?.HasValue.get"" IL_0009: ldc.i4.0 IL_000a: ceq IL_000c: call ""void System.Console.Write(bool)"" IL_0011: ret } "); } [Fact] public void TestEqualOnNullableVsNullableTuples_Tuple_NeverNull_AlwaysNull() { var source = @" class C { public static void Main() { System.Console.Write((1, 2) == ((int, int)?)null); } } "; CompileAndVerify(source, expectedOutput: "False", options: TestOptions.ReleaseExe).VerifyIL("C.Main", @"{ // Code size 7 (0x7) .maxstack 1 IL_0000: ldc.i4.0 IL_0001: call ""void System.Console.Write(bool)"" IL_0006: ret } "); } [Fact] public void TestEqualOnNullableVsNullableTuples_Tuple_AlwaysNull_MaybeNull() { var source = @" class C { public static void Main() { M(null); M((1, 2)); } public static void M((int, int)? t) { System.Console.Write(((int, int)?)null == t); } } "; CompileAndVerify(source, expectedOutput: "TrueFalse", options: TestOptions.ReleaseExe).VerifyIL("C.M", @"{ // Code size 18 (0x12) .maxstack 2 .locals init (System.ValueTuple<int, int>? V_0) IL_0000: ldarg.0 IL_0001: stloc.0 IL_0002: ldloca.s V_0 IL_0004: call ""bool System.ValueTuple<int, int>?.HasValue.get"" IL_0009: ldc.i4.0 IL_000a: ceq IL_000c: call ""void System.Console.Write(bool)"" IL_0011: ret } "); } [Fact] public void TestEqualOnNullableVsNullableTuples_Tuple_AlwaysNull_NeverNull() { var source = @" class C { public static void Main() { System.Console.Write(((int, int)?)null == (1, 2)); } } "; CompileAndVerify(source, expectedOutput: "False", options: TestOptions.ReleaseExe).VerifyIL("C.Main", @"{ // Code size 7 (0x7) .maxstack 1 IL_0000: ldc.i4.0 IL_0001: call ""void System.Console.Write(bool)"" IL_0006: ret } "); } [Fact] public void TestEqualOnNullableVsNullableTuples_ElementAlwaysNull() { var source = @" class C { public static void Main() { System.Console.Write((null, null) == (new int?(), new int?())); } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "True"); verifier.VerifyIL("C.Main", @"{ // Code size 9 (0x9) .maxstack 1 IL_0000: nop IL_0001: ldc.i4.1 IL_0002: call ""void System.Console.Write(bool)"" IL_0007: nop IL_0008: ret } "); } [Fact] public void TestNotEqualOnNullableVsNullableTuples() { var source = @" class C { public static void Main() { Compare(null, null); Compare(null, (1, 2)); Compare((2, 3), null); Compare((4, 4), (4, 4)); Compare((5, 5), (10, 10)); } private static void Compare((int, int)? nt1, (int, int)? nt2) { System.Console.Write($""{nt1 != nt2} ""); } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "False True True False True"); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var comparison = tree.GetCompilationUnitRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().Single(); var nt1 = comparison.Left; var nt1Type = model.GetTypeInfo(nt1); Assert.Equal("nt1", nt1.ToString()); Assert.Equal("(System.Int32, System.Int32)?", nt1Type.Type.ToTestDisplayString()); Assert.Equal("(System.Int32, System.Int32)?", nt1Type.ConvertedType.ToTestDisplayString()); var nt2 = comparison.Right; var nt2Type = model.GetTypeInfo(nt2); Assert.Equal("nt2", nt2.ToString()); Assert.Equal("(System.Int32, System.Int32)?", nt2Type.Type.ToTestDisplayString()); Assert.Equal("(System.Int32, System.Int32)?", nt2Type.ConvertedType.ToTestDisplayString()); verifier.VerifyIL("C.Compare", @"{ // Code size 107 (0x6b) .maxstack 3 .locals init (System.ValueTuple<int, int>? V_0, System.ValueTuple<int, int>? V_1, bool V_2, System.ValueTuple<int, int> V_3, System.ValueTuple<int, int> V_4) IL_0000: nop IL_0001: ldstr ""{0} "" IL_0006: ldarg.0 IL_0007: stloc.0 IL_0008: ldarg.1 IL_0009: stloc.1 IL_000a: ldloca.s V_0 IL_000c: call ""bool System.ValueTuple<int, int>?.HasValue.get"" IL_0011: stloc.2 IL_0012: ldloc.2 IL_0013: ldloca.s V_1 IL_0015: call ""bool System.ValueTuple<int, int>?.HasValue.get"" IL_001a: beq.s IL_001f IL_001c: ldc.i4.1 IL_001d: br.s IL_005a IL_001f: ldloc.2 IL_0020: brtrue.s IL_0025 IL_0022: ldc.i4.0 IL_0023: br.s IL_005a IL_0025: ldloca.s V_0 IL_0027: call ""System.ValueTuple<int, int> System.ValueTuple<int, int>?.GetValueOrDefault()"" IL_002c: stloc.3 IL_002d: ldloca.s V_1 IL_002f: call ""System.ValueTuple<int, int> System.ValueTuple<int, int>?.GetValueOrDefault()"" IL_0034: stloc.s V_4 IL_0036: ldloc.3 IL_0037: ldfld ""int System.ValueTuple<int, int>.Item1"" IL_003c: ldloc.s V_4 IL_003e: ldfld ""int System.ValueTuple<int, int>.Item1"" IL_0043: bne.un.s IL_0059 IL_0045: ldloc.3 IL_0046: ldfld ""int System.ValueTuple<int, int>.Item2"" IL_004b: ldloc.s V_4 IL_004d: ldfld ""int System.ValueTuple<int, int>.Item2"" IL_0052: ceq IL_0054: ldc.i4.0 IL_0055: ceq IL_0057: br.s IL_005a IL_0059: ldc.i4.1 IL_005a: box ""bool"" IL_005f: call ""string string.Format(string, object)"" IL_0064: call ""void System.Console.Write(string)"" IL_0069: nop IL_006a: ret }"); } [Fact] public void TestNotEqualOnNullableVsNullableNestedTuples() { var source = @" class C { public static void Main() { Compare((1, null), (1, null), true); Compare(null, (1, (2, 3)), false); Compare((1, (2, 3)), (1, null), false); Compare((1, (4, 4)), (1, (4, 4)), true); Compare((1, (5, 5)), (1, (10, 10)), false); System.Console.Write(""Success""); } private static void Compare((int, (int, int)?)? nt1, (int, (int, int)?)? nt2, bool expectMatch) { if (expectMatch != (nt1 == nt2) || expectMatch == (nt1 != nt2)) { throw null; } } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "Success"); } [Fact] public void TestEqualOnNullableVsNullableTuples_WithImplicitConversion() { var source = @" class C { public static void Main() { Compare(null, null); Compare(null, (1, 2)); Compare((2, 3), null); Compare((4, 4), (4, 4)); Compare((5, 5), (10, 10)); } private static void Compare((int, int)? nt1, (byte, long)? nt2) { System.Console.Write($""{nt1 == nt2} ""); } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "True False False True False"); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var comparison = tree.GetCompilationUnitRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().Single(); var nt1 = comparison.Left; var nt1Type = model.GetTypeInfo(nt1); Assert.Equal("nt1", nt1.ToString()); Assert.Equal("(System.Int32, System.Int32)?", nt1Type.Type.ToTestDisplayString()); Assert.Equal("(System.Int32, System.Int64)?", nt1Type.ConvertedType.ToTestDisplayString()); var nt2 = comparison.Right; var nt2Type = model.GetTypeInfo(nt2); Assert.Equal("nt2", nt2.ToString()); Assert.Equal("(System.Byte, System.Int64)?", nt2Type.Type.ToTestDisplayString()); Assert.Equal("(System.Int32, System.Int64)?", nt2Type.ConvertedType.ToTestDisplayString()); verifier.VerifyIL("C.Compare", @"{ // Code size 105 (0x69) .maxstack 3 .locals init (System.ValueTuple<int, int>? V_0, System.ValueTuple<byte, long>? V_1, bool V_2, System.ValueTuple<int, int> V_3, System.ValueTuple<byte, long> V_4) IL_0000: nop IL_0001: ldstr ""{0} "" IL_0006: ldarg.0 IL_0007: stloc.0 IL_0008: ldarg.1 IL_0009: stloc.1 IL_000a: ldloca.s V_0 IL_000c: call ""bool System.ValueTuple<int, int>?.HasValue.get"" IL_0011: stloc.2 IL_0012: ldloc.2 IL_0013: ldloca.s V_1 IL_0015: call ""bool System.ValueTuple<byte, long>?.HasValue.get"" IL_001a: beq.s IL_001f IL_001c: ldc.i4.0 IL_001d: br.s IL_0058 IL_001f: ldloc.2 IL_0020: brtrue.s IL_0025 IL_0022: ldc.i4.1 IL_0023: br.s IL_0058 IL_0025: ldloca.s V_0 IL_0027: call ""System.ValueTuple<int, int> System.ValueTuple<int, int>?.GetValueOrDefault()"" IL_002c: stloc.3 IL_002d: ldloca.s V_1 IL_002f: call ""System.ValueTuple<byte, long> System.ValueTuple<byte, long>?.GetValueOrDefault()"" IL_0034: stloc.s V_4 IL_0036: ldloc.3 IL_0037: ldfld ""int System.ValueTuple<int, int>.Item1"" IL_003c: ldloc.s V_4 IL_003e: ldfld ""byte System.ValueTuple<byte, long>.Item1"" IL_0043: bne.un.s IL_0057 IL_0045: ldloc.3 IL_0046: ldfld ""int System.ValueTuple<int, int>.Item2"" IL_004b: conv.i8 IL_004c: ldloc.s V_4 IL_004e: ldfld ""long System.ValueTuple<byte, long>.Item2"" IL_0053: ceq IL_0055: br.s IL_0058 IL_0057: ldc.i4.0 IL_0058: box ""bool"" IL_005d: call ""string string.Format(string, object)"" IL_0062: call ""void System.Console.Write(string)"" IL_0067: nop IL_0068: ret }"); } [Fact] public void TestOnNullableVsNullableTuples_WithImplicitCustomConversion() { var source = @" class C { int _value; public C(int v) { _value = v; } public static void Main() { Compare(null, null); Compare(null, (1, new C(20))); Compare((new C(30), 3), null); Compare((new C(4), 4), (4, new C(4))); Compare((new C(5), 5), (10, new C(10))); Compare((new C(6), 6), (6, new C(20))); } private static void Compare((C, int)? nt1, (int, C)? nt2) { System.Console.Write($""{nt1 == nt2} ""); } public static implicit operator int(C c) { System.Console.Write($""Convert{c._value} ""); return c._value; } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "True False False Convert4 Convert4 True Convert5 False Convert6 Convert20 False "); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var comparison = tree.GetCompilationUnitRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().Single(); var nt1 = comparison.Left; var nt1Type = model.GetTypeInfo(nt1); Assert.Equal("nt1", nt1.ToString()); Assert.Equal("(C, System.Int32)?", nt1Type.Type.ToTestDisplayString()); Assert.Equal("(System.Int32, System.Int32)?", nt1Type.ConvertedType.ToTestDisplayString()); var nt2 = comparison.Right; var nt2Type = model.GetTypeInfo(nt2); Assert.Equal("nt2", nt2.ToString()); Assert.Equal("(System.Int32, C)?", nt2Type.Type.ToTestDisplayString()); Assert.Equal("(System.Int32, System.Int32)?", nt2Type.ConvertedType.ToTestDisplayString()); verifier.VerifyIL("C.Compare", @"{ // Code size 114 (0x72) .maxstack 3 .locals init (System.ValueTuple<C, int>? V_0, System.ValueTuple<int, C>? V_1, bool V_2, System.ValueTuple<C, int> V_3, System.ValueTuple<int, C> V_4) IL_0000: nop IL_0001: ldstr ""{0} "" IL_0006: ldarg.0 IL_0007: stloc.0 IL_0008: ldarg.1 IL_0009: stloc.1 IL_000a: ldloca.s V_0 IL_000c: call ""bool System.ValueTuple<C, int>?.HasValue.get"" IL_0011: stloc.2 IL_0012: ldloc.2 IL_0013: ldloca.s V_1 IL_0015: call ""bool System.ValueTuple<int, C>?.HasValue.get"" IL_001a: beq.s IL_001f IL_001c: ldc.i4.0 IL_001d: br.s IL_0061 IL_001f: ldloc.2 IL_0020: brtrue.s IL_0025 IL_0022: ldc.i4.1 IL_0023: br.s IL_0061 IL_0025: ldloca.s V_0 IL_0027: call ""System.ValueTuple<C, int> System.ValueTuple<C, int>?.GetValueOrDefault()"" IL_002c: stloc.3 IL_002d: ldloca.s V_1 IL_002f: call ""System.ValueTuple<int, C> System.ValueTuple<int, C>?.GetValueOrDefault()"" IL_0034: stloc.s V_4 IL_0036: ldloc.3 IL_0037: ldfld ""C System.ValueTuple<C, int>.Item1"" IL_003c: call ""int C.op_Implicit(C)"" IL_0041: ldloc.s V_4 IL_0043: ldfld ""int System.ValueTuple<int, C>.Item1"" IL_0048: bne.un.s IL_0060 IL_004a: ldloc.3 IL_004b: ldfld ""int System.ValueTuple<C, int>.Item2"" IL_0050: ldloc.s V_4 IL_0052: ldfld ""C System.ValueTuple<int, C>.Item2"" IL_0057: call ""int C.op_Implicit(C)"" IL_005c: ceq IL_005e: br.s IL_0061 IL_0060: ldc.i4.0 IL_0061: box ""bool"" IL_0066: call ""string string.Format(string, object)"" IL_006b: call ""void System.Console.Write(string)"" IL_0070: nop IL_0071: ret }"); } [Fact] public void TestOnNullableVsNonNullableTuples() { var source = @" class C { public static void Main() { M(null); M((1, 2)); M((10, 20)); } private static void M((byte, int)? nt) { System.Console.Write((1, 2) == nt); } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "FalseTrueFalse"); verifier.VerifyIL("C.M", @"{ // Code size 53 (0x35) .maxstack 2 .locals init (System.ValueTuple<byte, int>? V_0, System.ValueTuple<byte, int> V_1) IL_0000: nop IL_0001: ldarg.0 IL_0002: stloc.0 IL_0003: ldloca.s V_0 IL_0005: call ""bool System.ValueTuple<byte, int>?.HasValue.get"" IL_000a: brtrue.s IL_000f IL_000c: ldc.i4.0 IL_000d: br.s IL_002e IL_000f: br.s IL_0011 IL_0011: ldloca.s V_0 IL_0013: call ""System.ValueTuple<byte, int> System.ValueTuple<byte, int>?.GetValueOrDefault()"" IL_0018: stloc.1 IL_0019: ldc.i4.1 IL_001a: ldloc.1 IL_001b: ldfld ""byte System.ValueTuple<byte, int>.Item1"" IL_0020: bne.un.s IL_002d IL_0022: ldc.i4.2 IL_0023: ldloc.1 IL_0024: ldfld ""int System.ValueTuple<byte, int>.Item2"" IL_0029: ceq IL_002b: br.s IL_002e IL_002d: ldc.i4.0 IL_002e: call ""void System.Console.Write(bool)"" IL_0033: nop IL_0034: ret }"); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var comparison = tree.GetCompilationUnitRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().Single(); var tuple = comparison.Left; var tupleType = model.GetTypeInfo(tuple); Assert.Equal("(1, 2)", tuple.ToString()); Assert.Equal("(System.Int32, System.Int32)", tupleType.Type.ToTestDisplayString()); Assert.Equal("(System.Int32, System.Int32)?", tupleType.ConvertedType.ToTestDisplayString()); var nt = comparison.Right; var ntType = model.GetTypeInfo(nt); Assert.Equal("nt", nt.ToString()); Assert.Equal("(System.Byte, System.Int32)?", ntType.Type.ToTestDisplayString()); Assert.Equal("(System.Int32, System.Int32)?", ntType.ConvertedType.ToTestDisplayString()); } [Fact] public void TestOnNullableVsNonNullableTuples_WithCustomConversion() { var source = @" class C { int _value; public C(int v) { _value = v; } public static void Main() { M(null); M((new C(1), 2)); M((new C(10), 20)); } private static void M((C, int)? nt) { System.Console.Write($""{(1, 2) == nt} ""); System.Console.Write($""{nt == (1, 2)} ""); } public static implicit operator int(C c) { System.Console.Write($""Convert{c._value} ""); return c._value; } }"; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "False False Convert1 True Convert1 True Convert10 False Convert10 False"); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var comparison = tree.GetCompilationUnitRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().First(); Assert.Equal("(1, 2) == nt", comparison.ToString()); var tuple = comparison.Left; var tupleType = model.GetTypeInfo(tuple); Assert.Equal("(1, 2)", tuple.ToString()); Assert.Equal("(System.Int32, System.Int32)", tupleType.Type.ToTestDisplayString()); Assert.Equal("(System.Int32, System.Int32)?", tupleType.ConvertedType.ToTestDisplayString()); var nt = comparison.Right; var ntType = model.GetTypeInfo(nt); Assert.Equal("nt", nt.ToString()); Assert.Equal("(C, System.Int32)?", ntType.Type.ToTestDisplayString()); Assert.Equal("(System.Int32, System.Int32)?", ntType.ConvertedType.ToTestDisplayString()); } [Fact] public void TestOnNullableVsNonNullableTuples3() { var source = @" class C { public static void Main() { M(null); M((1, 2)); M((10, 20)); } private static void M((int, int)? nt) { System.Console.Write(nt == (1, 2)); } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "FalseTrueFalse"); verifier.VerifyIL("C.M", @"{ // Code size 59 (0x3b) .maxstack 2 .locals init (System.ValueTuple<int, int>? V_0, bool V_1, System.ValueTuple<int, int> V_2) IL_0000: nop IL_0001: ldarg.0 IL_0002: stloc.0 IL_0003: ldloca.s V_0 IL_0005: call ""bool System.ValueTuple<int, int>?.HasValue.get"" IL_000a: stloc.1 IL_000b: ldloc.1 IL_000c: brtrue.s IL_0011 IL_000e: ldc.i4.0 IL_000f: br.s IL_0034 IL_0011: ldloc.1 IL_0012: brtrue.s IL_0017 IL_0014: ldc.i4.1 IL_0015: br.s IL_0034 IL_0017: ldloca.s V_0 IL_0019: call ""System.ValueTuple<int, int> System.ValueTuple<int, int>?.GetValueOrDefault()"" IL_001e: stloc.2 IL_001f: ldloc.2 IL_0020: ldfld ""int System.ValueTuple<int, int>.Item1"" IL_0025: ldc.i4.1 IL_0026: bne.un.s IL_0033 IL_0028: ldloc.2 IL_0029: ldfld ""int System.ValueTuple<int, int>.Item2"" IL_002e: ldc.i4.2 IL_002f: ceq IL_0031: br.s IL_0034 IL_0033: ldc.i4.0 IL_0034: call ""void System.Console.Write(bool)"" IL_0039: nop IL_003a: ret }"); } [Fact] public void TestOnNullableVsLiteralTuples() { var source = @" class C { public static void Main() { CheckNull(null); CheckNull((1, 2)); } private static void CheckNull((int, int)? nt) { System.Console.Write($""{nt == null} ""); System.Console.Write($""{nt != null} ""); } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "True False False True"); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var lastNull = tree.GetCompilationUnitRoot().DescendantNodes().OfType<LiteralExpressionSyntax>().Last(); Assert.Equal("null", lastNull.ToString()); var nullType = model.GetTypeInfo(lastNull); Assert.Null(nullType.Type); Assert.Null(nullType.ConvertedType); // In nullable-null comparison, the null literal remains typeless } [Fact] public void TestOnLongTuple() { var source = @" class C { public static void Main() { Assert(MakeLongTuple(1) == MakeLongTuple(1)); Assert(!(MakeLongTuple(1) != MakeLongTuple(1))); Assert(MakeLongTuple(1) == (1, 1, 1, 1, 1, 1, 1, 1, 1)); Assert(!(MakeLongTuple(1) != (1, 1, 1, 1, 1, 1, 1, 1, 1))); Assert(MakeLongTuple(1) == MakeLongTuple(1, 1)); Assert(!(MakeLongTuple(1) != MakeLongTuple(1, 1))); Assert(!(MakeLongTuple(1) == MakeLongTuple(1, 2))); Assert(!(MakeLongTuple(1) == MakeLongTuple(2, 1))); Assert(MakeLongTuple(1) != MakeLongTuple(1, 2)); Assert(MakeLongTuple(1) != MakeLongTuple(2, 1)); System.Console.Write(""Success""); } private static (int, int, int, int, int, int, int, int, int) MakeLongTuple(int x) => (x, x, x, x, x, x, x, x, x); private static (int?, int, int?, int, int?, int, int?, int, int?)? MakeLongTuple(int? x, int y) => (x, y, x, y, x, y, x, y, x); private static void Assert(bool test) { if (!test) { throw null; } } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "Success"); } [Fact] public void TestOn1Tuple_FromRest() { var source = @" class C { public static bool M() { var x1 = MakeLongTuple(1).Rest; bool b1 = x1 == x1; bool b2 = x1 != x1; return b1 && b2; } private static (int, int, int, int, int, int, int, int?) MakeLongTuple(int? x) => throw null; public bool Unused((int, int, int, int, int, int, int, int?) t) { return t.Rest == t.Rest; } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (8,19): error CS0019: Operator '==' cannot be applied to operands of type 'ValueTuple<int?>' and 'ValueTuple<int?>' // bool b1 = x1 == x1; Diagnostic(ErrorCode.ERR_BadBinaryOps, "x1 == x1").WithArguments("==", "System.ValueTuple<int?>", "System.ValueTuple<int?>").WithLocation(8, 19), // (9,19): error CS0019: Operator '!=' cannot be applied to operands of type 'ValueTuple<int?>' and 'ValueTuple<int?>' // bool b2 = x1 != x1; Diagnostic(ErrorCode.ERR_BadBinaryOps, "x1 != x1").WithArguments("!=", "System.ValueTuple<int?>", "System.ValueTuple<int?>").WithLocation(9, 19), // (18,16): error CS0019: Operator '==' cannot be applied to operands of type 'ValueTuple<int?>' and 'ValueTuple<int?>' // return t.Rest == t.Rest; Diagnostic(ErrorCode.ERR_BadBinaryOps, "t.Rest == t.Rest").WithArguments("==", "System.ValueTuple<int?>", "System.ValueTuple<int?>").WithLocation(18, 16) ); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var comparison = tree.GetRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().Last(); Assert.Equal("t.Rest == t.Rest", comparison.ToString()); var left = model.GetTypeInfo(comparison.Left); Assert.Equal("System.ValueTuple<System.Int32?>", left.Type.ToTestDisplayString()); Assert.Equal("System.ValueTuple<System.Int32?>", left.ConvertedType.ToTestDisplayString()); Assert.True(left.Type.IsTupleType); } [Fact] public void TestOn1Tuple_FromValueTuple() { var source = @" using System; class C { public static bool M() { var x1 = ValueTuple.Create((int?)1); bool b1 = x1 == x1; bool b2 = x1 != x1; return b1 && b2; } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (9,19): error CS0019: Operator '==' cannot be applied to operands of type 'ValueTuple<int?>' and 'ValueTuple<int?>' // bool b1 = x1 == x1; Diagnostic(ErrorCode.ERR_BadBinaryOps, "x1 == x1").WithArguments("==", "System.ValueTuple<int?>", "System.ValueTuple<int?>").WithLocation(9, 19), // (10,19): error CS0019: Operator '!=' cannot be applied to operands of type 'ValueTuple<int?>' and 'ValueTuple<int?>' // bool b2 = x1 != x1; Diagnostic(ErrorCode.ERR_BadBinaryOps, "x1 != x1").WithArguments("!=", "System.ValueTuple<int?>", "System.ValueTuple<int?>").WithLocation(10, 19) ); } [Fact] public void TestOnTupleOfDecimals() { var source = @" class C { public static void Main() { System.Console.Write(Compare((1, 2), (1, 2))); System.Console.Write(Compare((1, 2), (10, 20))); } public static bool Compare((decimal, decimal) t1, (decimal, decimal) t2) { return t1 == t2; } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "TrueFalse"); verifier.VerifyIL("C.Compare", @"{ // Code size 49 (0x31) .maxstack 2 .locals init (System.ValueTuple<decimal, decimal> V_0, System.ValueTuple<decimal, decimal> V_1, bool V_2) IL_0000: nop IL_0001: ldarg.0 IL_0002: stloc.0 IL_0003: ldarg.1 IL_0004: stloc.1 IL_0005: ldloc.0 IL_0006: ldfld ""decimal System.ValueTuple<decimal, decimal>.Item1"" IL_000b: ldloc.1 IL_000c: ldfld ""decimal System.ValueTuple<decimal, decimal>.Item1"" IL_0011: call ""bool decimal.op_Equality(decimal, decimal)"" IL_0016: brfalse.s IL_002b IL_0018: ldloc.0 IL_0019: ldfld ""decimal System.ValueTuple<decimal, decimal>.Item2"" IL_001e: ldloc.1 IL_001f: ldfld ""decimal System.ValueTuple<decimal, decimal>.Item2"" IL_0024: call ""bool decimal.op_Equality(decimal, decimal)"" IL_0029: br.s IL_002c IL_002b: ldc.i4.0 IL_002c: stloc.2 IL_002d: br.s IL_002f IL_002f: ldloc.2 IL_0030: ret }"); } [Fact] public void TestSideEffectsAreSavedToTemps() { var source = @" class C { public static void Main() { int i = 0; System.Console.Write((i++, i++, i++) == (0, 1, 2)); } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "True"); } [Fact] public void TestNonBoolComparisonResult_WithTrueFalseOperators() { var source = @" using static System.Console; public class C { public static void Main() { Write($""{REPLACE}""); } } public class Base { public int I; public Base(int i) { I = i; } } public class A : Base { public A(int i) : base(i) { Write($""A:{i}, ""); } public static NotBool operator ==(A a, Y y) { Write(""A == Y, ""); return new NotBool(a.I == y.I); } public static NotBool operator !=(A a, Y y) { Write(""A != Y, ""); return new NotBool(a.I != y.I); } public override bool Equals(object o) => throw null; public override int GetHashCode() => throw null; } public class X : Base { public X(int i) : base(i) { Write($""X:{i}, ""); } } public class Y : Base { public Y(int i) : base(i) { Write($""Y:{i}, ""); } public static implicit operator Y(X x) { Write(""X -> ""); return new Y(x.I); } } public class NotBool { public bool B; public NotBool(bool value) { B = value; } public static bool operator true(NotBool b) { Write($""NotBool.true -> {b.B}, ""); return b.B; } public static bool operator false(NotBool b) { Write($""NotBool.false -> {!b.B}, ""); return !b.B; } } "; validate("(new A(1), new A(2)) == (new X(1), new Y(2))", "A:1, A:2, X:1, Y:2, X -> Y:1, A == Y, NotBool.false -> False, A == Y, NotBool.false -> False, True"); validate("(new A(1), new A(2)) == (new X(1), new Y(20))", "A:1, A:2, X:1, Y:20, X -> Y:1, A == Y, NotBool.false -> False, A == Y, NotBool.false -> True, False"); validate("(new A(1), new A(2)) != (new X(1), new Y(2))", "A:1, A:2, X:1, Y:2, X -> Y:1, A != Y, NotBool.true -> False, A != Y, NotBool.true -> False, False"); validate("(new A(1), new A(2)) != (new X(1), new Y(20))", "A:1, A:2, X:1, Y:20, X -> Y:1, A != Y, NotBool.true -> False, A != Y, NotBool.true -> True, True"); validate("((dynamic)new A(1), new A(2)) == (new X(1), (dynamic)new Y(2))", "A:1, A:2, X:1, Y:2, X -> Y:1, A == Y, NotBool.false -> False, A == Y, NotBool.false -> False, True"); validate("((dynamic)new A(1), new A(2)) == (new X(1), (dynamic)new Y(20))", "A:1, A:2, X:1, Y:20, X -> Y:1, A == Y, NotBool.false -> False, A == Y, NotBool.false -> True, False"); validate("((dynamic)new A(1), new A(2)) != (new X(1), (dynamic)new Y(2))", "A:1, A:2, X:1, Y:2, X -> Y:1, A != Y, NotBool.true -> False, A != Y, NotBool.true -> False, False"); validate("((dynamic)new A(1), new A(2)) != (new X(1), (dynamic)new Y(20))", "A:1, A:2, X:1, Y:20, X -> Y:1, A != Y, NotBool.true -> False, A != Y, NotBool.true -> True, True"); void validate(string expression, string expected) { var comp = CreateCompilation(source.Replace("REPLACE", expression), targetFramework: TargetFramework.StandardAndCSharp, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: expected); } } [Fact] public void TestNonBoolComparisonResult_WithTrueFalseOperatorsOnBase() { var source = @" using static System.Console; public class C { public static void Main() { Write($""{REPLACE}""); } } public class Base { public int I; public Base(int i) { I = i; } } public class A : Base { public A(int i) : base(i) { Write($""A:{i}, ""); } public static NotBool operator ==(A a, Y y) { Write(""A == Y, ""); return new NotBool(a.I == y.I); } public static NotBool operator !=(A a, Y y) { Write(""A != Y, ""); return new NotBool(a.I != y.I); } public override bool Equals(object o) => throw null; public override int GetHashCode() => throw null; } public class X : Base { public X(int i) : base(i) { Write($""X:{i}, ""); } } public class Y : Base { public Y(int i) : base(i) { Write($""Y:{i}, ""); } public static implicit operator Y(X x) { Write(""X -> ""); return new Y(x.I); } } public class NotBoolBase { public bool B; public NotBoolBase(bool value) { B = value; } public static bool operator true(NotBoolBase b) { Write($""NotBoolBase.true -> {b.B}, ""); return b.B; } public static bool operator false(NotBoolBase b) { Write($""NotBoolBase.false -> {!b.B}, ""); return !b.B; } } public class NotBool : NotBoolBase { public NotBool(bool value) : base(value) { } } "; // This tests the case where the custom operators false/true need an input conversion that's not just an identity conversion (in this case, it's an implicit reference conversion) validate("(new A(1), new A(2)) == (new X(1), new Y(2))", "A:1, A:2, X:1, Y:2, X -> Y:1, A == Y, NotBoolBase.false -> False, A == Y, NotBoolBase.false -> False, True"); validate("(new A(1), new A(2)) == (new X(1), new Y(20))", "A:1, A:2, X:1, Y:20, X -> Y:1, A == Y, NotBoolBase.false -> False, A == Y, NotBoolBase.false -> True, False"); validate("(new A(1), new A(2)) != (new X(1), new Y(2))", "A:1, A:2, X:1, Y:2, X -> Y:1, A != Y, NotBoolBase.true -> False, A != Y, NotBoolBase.true -> False, False"); validate("(new A(1), new A(2)) != (new X(1), new Y(20))", "A:1, A:2, X:1, Y:20, X -> Y:1, A != Y, NotBoolBase.true -> False, A != Y, NotBoolBase.true -> True, True"); validate("((dynamic)new A(1), new A(2)) == (new X(1), (dynamic)new Y(2))", "A:1, A:2, X:1, Y:2, X -> Y:1, A == Y, NotBoolBase.false -> False, A == Y, NotBoolBase.false -> False, True"); validate("((dynamic)new A(1), new A(2)) == (new X(1), (dynamic)new Y(20))", "A:1, A:2, X:1, Y:20, X -> Y:1, A == Y, NotBoolBase.false -> False, A == Y, NotBoolBase.false -> True, False"); validate("((dynamic)new A(1), new A(2)) != (new X(1), (dynamic)new Y(2))", "A:1, A:2, X:1, Y:2, X -> Y:1, A != Y, NotBoolBase.true -> False, A != Y, NotBoolBase.true -> False, False"); validate("((dynamic)new A(1), new A(2)) != (new X(1), (dynamic)new Y(20))", "A:1, A:2, X:1, Y:20, X -> Y:1, A != Y, NotBoolBase.true -> False, A != Y, NotBoolBase.true -> True, True"); void validate(string expression, string expected) { var comp = CreateCompilation(source.Replace("REPLACE", expression), targetFramework: TargetFramework.StandardAndCSharp, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: expected); } } [Fact] public void TestNonBoolComparisonResult_WithImplicitBoolConversion() { var source = @" using static System.Console; public class C { public static void Main() { Write($""{REPLACE}""); } } public class Base { public int I; public Base(int i) { I = i; } } public class A : Base { public A(int i) : base(i) { Write($""A:{i}, ""); } public static NotBool operator ==(A a, Y y) { Write(""A == Y, ""); return new NotBool(a.I == y.I); } public static NotBool operator !=(A a, Y y) { Write(""A != Y, ""); return new NotBool(a.I != y.I); } public override bool Equals(object o) => throw null; public override int GetHashCode() => throw null; } public class X : Base { public X(int i) : base(i) { Write($""X:{i}, ""); } } public class Y : Base { public Y(int i) : base(i) { Write($""Y:{i}, ""); } public static implicit operator Y(X x) { Write(""X -> ""); return new Y(x.I); } } public class NotBool { public bool B; public NotBool(bool value) { B = value; } public static implicit operator bool(NotBool b) { Write($""NotBool -> bool:{b.B}, ""); return b.B; } } "; validate("(new A(1), new A(2)) == (new X(1), new Y(2))", "A:1, A:2, X:1, Y:2, X -> Y:1, A == Y, NotBool -> bool:True, A == Y, NotBool -> bool:True, True"); validate("(new A(1), new A(2)) == (new X(10), new Y(2))", "A:1, A:2, X:10, Y:2, X -> Y:10, A == Y, NotBool -> bool:False, False"); validate("(new A(1), new A(2)) == (new X(1), new Y(20))", "A:1, A:2, X:1, Y:20, X -> Y:1, A == Y, NotBool -> bool:True, A == Y, NotBool -> bool:False, False"); validate("(new A(1), new A(2)) != (new X(1), new Y(2))", "A:1, A:2, X:1, Y:2, X -> Y:1, A != Y, NotBool -> bool:False, A != Y, NotBool -> bool:False, False"); validate("(new A(1), new A(2)) != (new X(10), new Y(2))", "A:1, A:2, X:10, Y:2, X -> Y:10, A != Y, NotBool -> bool:True, True"); validate("(new A(1), new A(2)) != (new X(1), new Y(20))", "A:1, A:2, X:1, Y:20, X -> Y:1, A != Y, NotBool -> bool:False, A != Y, NotBool -> bool:True, True"); void validate(string expression, string expected) { var comp = CreateCompilation(source.Replace("REPLACE", expression), options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: expected); } } [Fact] public void TestNonBoolComparisonResult_WithoutImplicitBoolConversion() { var source = @" using static System.Console; public class C { public static void Main() { Write($""{REPLACE}""); } } public class Base { public Base(int i) { } } public class A : Base { public A(int i) : base(i) => throw null; public static NotBool operator ==(A a, Y y) => throw null; public static NotBool operator !=(A a, Y y) => throw null; public override bool Equals(object o) => throw null; public override int GetHashCode() => throw null; } public class X : Base { public X(int i) : base(i) => throw null; } public class Y : Base { public Y(int i) : base(i) => throw null; public static implicit operator Y(X x) => throw null; } public class NotBool { } "; validate("(new A(1), new A(2)) == (new X(1), new Y(2))", // (7,18): error CS0029: Cannot implicitly convert type 'NotBool' to 'bool' // Write($"{(new A(1), new A(2)) == (new X(1), new Y(2))}"); Diagnostic(ErrorCode.ERR_NoImplicitConv, "(new A(1), new A(2)) == (new X(1), new Y(2))").WithArguments("NotBool", "bool").WithLocation(7, 18), // (7,18): error CS0029: Cannot implicitly convert type 'NotBool' to 'bool' // Write($"{(new A(1), new A(2)) == (new X(1), new Y(2))}"); Diagnostic(ErrorCode.ERR_NoImplicitConv, "(new A(1), new A(2)) == (new X(1), new Y(2))").WithArguments("NotBool", "bool").WithLocation(7, 18) ); validate("(new A(1), 2) != (new X(1), 2)", // (7,18): error CS0029: Cannot implicitly convert type 'NotBool' to 'bool' // Write($"{(new A(1), 2) != (new X(1), 2)}"); Diagnostic(ErrorCode.ERR_NoImplicitConv, "(new A(1), 2) != (new X(1), 2)").WithArguments("NotBool", "bool").WithLocation(7, 18) ); void validate(string expression, params DiagnosticDescription[] expected) { var comp = CreateCompilation(source.Replace("REPLACE", expression)); comp.VerifyDiagnostics(expected); } } [Fact] public void TestNonBoolComparisonResult_WithExplicitBoolConversion() { var source = @" using static System.Console; public class C { public static void Main() { Write($""{(new A(1), new A(2)) == (new X(1), new Y(2))}""); } } public class Base { public int I; public Base(int i) { I = i; } } public class A : Base { public A(int i) : base(i) => throw null; public static NotBool operator ==(A a, Y y) => throw null; public static NotBool operator !=(A a, Y y) => throw null; public override bool Equals(object o) => throw null; public override int GetHashCode() => throw null; } public class X : Base { public X(int i) : base(i) => throw null; } public class Y : Base { public Y(int i) : base(i) => throw null; public static implicit operator Y(X x) => throw null; } public class NotBool { public NotBool(bool value) => throw null; public static explicit operator bool(NotBool b) => throw null; } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (7,18): error CS0029: Cannot implicitly convert type 'NotBool' to 'bool' // Write($"{(new A(1), new A(2)) == (new X(1), new Y(2))}"); Diagnostic(ErrorCode.ERR_NoImplicitConv, "(new A(1), new A(2)) == (new X(1), new Y(2))").WithArguments("NotBool", "bool").WithLocation(7, 18), // (7,18): error CS0029: Cannot implicitly convert type 'NotBool' to 'bool' // Write($"{(new A(1), new A(2)) == (new X(1), new Y(2))}"); Diagnostic(ErrorCode.ERR_NoImplicitConv, "(new A(1), new A(2)) == (new X(1), new Y(2))").WithArguments("NotBool", "bool").WithLocation(7, 18) ); } [Fact] public void TestNullableBoolComparisonResult_WithTrueFalseOperators() { var source = @" public class C { public static void M(A a) { _ = (a, a) == (a, a); if (a == a) { } } } public class A { public A(int i) => throw null; public static bool? operator ==(A a1, A a2) => throw null; public static bool? operator !=(A a1, A a2) => throw null; public override bool Equals(object o) => throw null; public override int GetHashCode() => throw null; } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,13): error CS0029: Cannot implicitly convert type 'bool?' to 'bool' // _ = (a, a) == (a, a); Diagnostic(ErrorCode.ERR_NoImplicitConv, "(a, a) == (a, a)").WithArguments("bool?", "bool").WithLocation(6, 13), // (6,13): error CS0029: Cannot implicitly convert type 'bool?' to 'bool' // _ = (a, a) == (a, a); Diagnostic(ErrorCode.ERR_NoImplicitConv, "(a, a) == (a, a)").WithArguments("bool?", "bool").WithLocation(6, 13), // (7,13): error CS0266: Cannot implicitly convert type 'bool?' to 'bool'. An explicit conversion exists (are you missing a cast?) // if (a == a) { } Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "a == a").WithArguments("bool?", "bool").WithLocation(7, 13), // (7,13): warning CS1718: Comparison made to same variable; did you mean to compare something else? // if (a == a) { } Diagnostic(ErrorCode.WRN_ComparisonToSelf, "a == a").WithLocation(7, 13) ); } [Fact] public void TestElementNames() { var source = @" #pragma warning disable CS0219 using static System.Console; public class C { public static void Main() { int a = 1; int b = 2; int c = 3; int d = 4; int x = 5; int y = 6; (int x, int y) t1 = (1, 2); (int, int) t2 = (1, 2); Write($""{REPLACE}""); } } "; // tuple expression vs tuple expression validate("t1 == t2"); // tuple expression vs tuple literal validate("t1 == (x: 1, y: 2)"); validate("t1 == (1, 2)"); validate("(1, 2) == t1"); validate("(x: 1, d) == t1"); validate("t2 == (x: 1, y: 2)", // (16,25): warning CS8375: The tuple element name 'x' is ignored because a different name or no name is specified on the other side of the tuple == or != operator. // Write($"{t2 == (x: 1, y: 2)}"); Diagnostic(ErrorCode.WRN_TupleBinopLiteralNameMismatch, "x: 1").WithArguments("x").WithLocation(16, 25), // (16,31): warning CS8375: The tuple element name 'y' is ignored because a different name or no name is specified on the other side of the tuple == or != operator. // Write($"{t2 == (x: 1, y: 2)}"); Diagnostic(ErrorCode.WRN_TupleBinopLiteralNameMismatch, "y: 2").WithArguments("y").WithLocation(16, 31) ); // tuple literal vs tuple literal // - warnings reported on the right when both sides could complain // - no warnings on inferred names validate("((a, b), c: 3) == ((1, x: 2), 3)", // (16,27): warning CS8375: The tuple element name 'c' is ignored because a different name or no name is specified on the other side of the tuple == or != operator. // Write($"{((a, b), c: 3) == ((1, x: 2), 3)}"); Diagnostic(ErrorCode.WRN_TupleBinopLiteralNameMismatch, "c: 3").WithArguments("c").WithLocation(16, 27), // (16,41): warning CS8375: The tuple element name 'x' is ignored because a different name or no name is specified on the other side of the tuple == or != operator. // Write($"{((a, b), c: 3) == ((1, x: 2), 3)}"); Diagnostic(ErrorCode.WRN_TupleBinopLiteralNameMismatch, "x: 2").WithArguments("x").WithLocation(16, 41) ); validate("(a, b) == (a: 1, b: 2)"); validate("(a, b) == (c: 1, d)", // (16,29): warning CS8375: The tuple element name 'c' is ignored because a different name or no name is specified on the other side of the tuple == or != operator. // Write($"{(a, b) == (c: 1, d)}"); Diagnostic(ErrorCode.WRN_TupleBinopLiteralNameMismatch, "c: 1").WithArguments("c").WithLocation(16, 29) ); validate("(a: 1, b: 2) == (c: 1, d)", // (16,35): warning CS8375: The tuple element name 'c' is ignored because a different name or no name is specified on the other side of the tuple == or != operator. // Write($"{(a: 1, b: 2) == (c: 1, d)}"); Diagnostic(ErrorCode.WRN_TupleBinopLiteralNameMismatch, "c: 1").WithArguments("c").WithLocation(16, 35), // (16,25): warning CS8375: The tuple element name 'b' is ignored because a different name or no name is specified on the other side of the tuple == or != operator. // Write($"{(a: 1, b: 2) == (c: 1, d)}"); Diagnostic(ErrorCode.WRN_TupleBinopLiteralNameMismatch, "b: 2").WithArguments("b").WithLocation(16, 25) ); validate("(null, b) == (c: null, d: 2)", // (16,32): warning CS8375: The tuple element name 'c' is ignored because a different name or no name is specified on the other side of the tuple == or != operator. // Write($"{(null, b) == (c: null, d: 2)}"); Diagnostic(ErrorCode.WRN_TupleBinopLiteralNameMismatch, "c: null").WithArguments("c").WithLocation(16, 32), // (16,41): warning CS8375: The tuple element name 'd' is ignored because a different name or no name is specified on the other side of the tuple == or != operator. // Write($"{(null, b) == (c: null, d: 2)}"); Diagnostic(ErrorCode.WRN_TupleBinopLiteralNameMismatch, "d: 2").WithArguments("d").WithLocation(16, 41) ); void validate(string expression, params DiagnosticDescription[] diagnostics) { var comp = CreateCompilation(source.Replace("REPLACE", expression)); comp.VerifyDiagnostics(diagnostics); } } [Fact] void TestValueTupleWithObsoleteEqualityOperator() { string source = @" public class C { public static void Main() { System.Console.Write((1, 2) == (3, 4)); } } 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; } [System.Obsolete] public static bool operator==(ValueTuple<T1, T2> t1, ValueTuple<T1, T2> t2) => throw null; public static bool operator!=(ValueTuple<T1, T2> t1, ValueTuple<T1, T2> t2) => throw null; public override bool Equals(object other) => throw null; public override int GetHashCode() => throw null; } } "; var comp = CreateCompilationWithMscorlib40(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); // Note: tuple equality picked ahead of custom operator== CompileAndVerify(comp, expectedOutput: "False"); } [Fact] public void TestInExpressionTree() { var source = @" using System; using System.Linq.Expressions; public class C { public static void Main() { Expression<Func<int, bool>> expr = i => (i, i) == (i, i); Expression<Func<(int, int), bool>> expr2 = t => t != t; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (8,49): error CS8374: An expression tree may not contain a tuple == or != operator // Expression<Func<int, bool>> expr = i => (i, i) == (i, i); Diagnostic(ErrorCode.ERR_ExpressionTreeContainsTupleBinOp, "(i, i) == (i, i)").WithLocation(8, 49), // (8,49): error CS8143: An expression tree may not contain a tuple literal. // Expression<Func<int, bool>> expr = i => (i, i) == (i, i); Diagnostic(ErrorCode.ERR_ExpressionTreeContainsTupleLiteral, "(i, i)").WithLocation(8, 49), // (8,59): error CS8143: An expression tree may not contain a tuple literal. // Expression<Func<int, bool>> expr = i => (i, i) == (i, i); Diagnostic(ErrorCode.ERR_ExpressionTreeContainsTupleLiteral, "(i, i)").WithLocation(8, 59), // (9,57): error CS8374: An expression tree may not contain a tuple == or != operator // Expression<Func<(int, int), bool>> expr2 = t => t != t; Diagnostic(ErrorCode.ERR_ExpressionTreeContainsTupleBinOp, "t != t").WithLocation(9, 57) ); } [Fact] public void TestComparisonOfDynamicAndTuple() { var source = @" public class C { (long, string) _t; public C(long l, string s) { _t = (l, s); } public static void Main() { dynamic d = new C(1, ""hello""); (long, string) tuple1 = (1, ""hello""); (long, string) tuple2 = (2, ""world""); System.Console.Write($""{d == tuple1} {d != tuple1} {d == tuple2} {d != tuple2}""); } public static bool operator==(C c, (long, string) t) { return c._t.Item1 == t.Item1 && c._t.Item2 == t.Item2; } public static bool operator!=(C c, (long, string) t) { return !(c == t); } public override bool Equals(object o) => throw null; public override int GetHashCode() => throw null; } "; var comp = CreateCompilation(source, targetFramework: TargetFramework.StandardAndCSharp, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "True False False True"); } [Fact] public void TestComparisonOfDynamicTuple() { var source = @" public class C { public static void Main() { dynamic d1 = (1, ""hello""); dynamic d2 = (1, ""hello""); dynamic d3 = ((byte)1, 2); PrintException(() => d1 == d2); PrintException(() => d1 == d3); } public static void PrintException(System.Func<bool> action) { System.Globalization.CultureInfo saveUICulture = System.Threading.Thread.CurrentThread.CurrentUICulture; System.Threading.Thread.CurrentThread.CurrentUICulture = System.Globalization.CultureInfo.InvariantCulture; try { action(); } catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e) { System.Console.WriteLine(e.Message); } finally { System.Threading.Thread.CurrentThread.CurrentUICulture = saveUICulture; } } } "; var comp = CreateCompilation(source, targetFramework: TargetFramework.StandardAndCSharp, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: @"Operator '==' cannot be applied to operands of type 'System.ValueTuple<int,string>' and 'System.ValueTuple<int,string>' Operator '==' cannot be applied to operands of type 'System.ValueTuple<int,string>' and 'System.ValueTuple<byte,int>'"); } [Fact] public void TestComparisonWithTupleElementNames() { var source = @" public class C { public static void Main() { int Bob = 1; System.Console.Write((Alice: 0, (Bob, 2)) == (Bob: 0, (1, Other: 2))); } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics( // (7,55): warning CS8375: The tuple element name 'Bob' is ignored because a different name or no name is specified on the other side of the tuple == or != operator. // System.Console.Write((Alice: 0, (Bob, 2)) == (Bob: 0, (1, Other: 2))); Diagnostic(ErrorCode.WRN_TupleBinopLiteralNameMismatch, "Bob: 0").WithArguments("Bob").WithLocation(7, 55), // (7,67): warning CS8375: The tuple element name 'Other' is ignored because a different name or no name is specified on the other side of the tuple == or != operator. // System.Console.Write((Alice: 0, (Bob, 2)) == (Bob: 0, (1, Other: 2))); Diagnostic(ErrorCode.WRN_TupleBinopLiteralNameMismatch, "Other: 2").WithArguments("Other").WithLocation(7, 67) ); CompileAndVerify(comp, expectedOutput: "True"); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var equals = tree.GetCompilationUnitRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().First(); // check left tuple var leftTuple = equals.Left; var leftInfo = model.GetTypeInfo(leftTuple); Assert.Equal("(System.Int32 Alice, (System.Int32 Bob, System.Int32))", leftInfo.Type.ToTestDisplayString()); Assert.Equal("(System.Int32 Alice, (System.Int32 Bob, System.Int32))", leftInfo.ConvertedType.ToTestDisplayString()); // check right tuple var rightTuple = equals.Right; var rightInfo = model.GetTypeInfo(rightTuple); Assert.Equal("(System.Int32 Bob, (System.Int32, System.Int32 Other))", rightInfo.Type.ToTestDisplayString()); Assert.Equal("(System.Int32 Bob, (System.Int32, System.Int32 Other))", rightInfo.ConvertedType.ToTestDisplayString()); } [Fact] public void TestComparisonWithCastedTuples() { var source = @" public class C { public static void Main() { System.Console.Write( ((string, (byte, long))) (null, (1, 2L)) == ((string, (long, byte))) (null, (1L, 2)) ); } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "True"); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var equals = tree.GetCompilationUnitRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().First(); // check left cast ... var leftCast = (CastExpressionSyntax)equals.Left; Assert.Equal("((string, (byte, long))) (null, (1, 2L))", leftCast.ToString()); var leftCastInfo = model.GetTypeInfo(leftCast); Assert.Equal("(System.String, (System.Byte, System.Int64))", leftCastInfo.Type.ToTestDisplayString()); Assert.Equal("(System.String, (System.Int64, System.Int64))", leftCastInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.ImplicitTuple, model.GetConversion(leftCast).Kind); // ... its tuple ... var leftTuple = (TupleExpressionSyntax)leftCast.Expression; Assert.Equal("(null, (1, 2L))", leftTuple.ToString()); var leftTupleInfo = model.GetTypeInfo(leftTuple); Assert.Null(leftTupleInfo.Type); Assert.Equal("(System.String, (System.Byte, System.Int64))", leftTupleInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.ExplicitTupleLiteral, model.GetConversion(leftTuple).Kind); // ... its null ... var leftNull = leftTuple.Arguments[0].Expression; Assert.Equal("null", leftNull.ToString()); var leftNullInfo = model.GetTypeInfo(leftNull); Assert.Null(leftNullInfo.Type); Assert.Equal("System.String", leftNullInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.ImplicitReference, model.GetConversion(leftNull).Kind); // ... its nested tuple var leftNestedTuple = leftTuple.Arguments[1].Expression; Assert.Equal("(1, 2L)", leftNestedTuple.ToString()); var leftNestedTupleInfo = model.GetTypeInfo(leftNestedTuple); Assert.Equal("(System.Int32, System.Int64)", leftNestedTupleInfo.Type.ToTestDisplayString()); Assert.Equal("(System.Byte, System.Int64)", leftNestedTupleInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.Identity, model.GetConversion(leftNestedTuple).Kind); // check right cast ... var rightCast = (CastExpressionSyntax)equals.Right; var rightCastInfo = model.GetTypeInfo(rightCast); Assert.Equal("(System.String, (System.Int64, System.Byte))", rightCastInfo.Type.ToTestDisplayString()); Assert.Equal("(System.String, (System.Int64, System.Int64))", rightCastInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.ImplicitTuple, model.GetConversion(rightCast).Kind); // ... its tuple var rightTuple = rightCast.Expression; var rightTupleInfo = model.GetTypeInfo(rightTuple); Assert.Null(rightTupleInfo.Type); Assert.Equal("(System.String, (System.Int64, System.Byte))", rightTupleInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.ExplicitTupleLiteral, model.GetConversion(rightTuple).Kind); } [Fact] public void TestGenericElement() { var source = @" public class C { public void M<T>(T t) { _ = (t, t) == (t, t); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,13): error CS0019: Operator '==' cannot be applied to operands of type 'T' and 'T' // _ = (t, t) == (t, t); Diagnostic(ErrorCode.ERR_BadBinaryOps, "(t, t) == (t, t)").WithArguments("==", "T", "T").WithLocation(6, 13), // (6,13): error CS0019: Operator '==' cannot be applied to operands of type 'T' and 'T' // _ = (t, t) == (t, t); Diagnostic(ErrorCode.ERR_BadBinaryOps, "(t, t) == (t, t)").WithArguments("==", "T", "T").WithLocation(6, 13) ); } [Fact] public void TestNameofEquality() { var source = @" public class C { public void M() { _ = nameof((1, 2) == (3, 4)); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,20): error CS8081: Expression does not have a name. // _ = nameof((1, 2) == (3, 4)); Diagnostic(ErrorCode.ERR_ExpressionHasNoName, "(1, 2) == (3, 4)").WithLocation(6, 20) ); } [Fact] public void TestAsRefOrOutArgument() { var source = @" public class C { public void M(ref bool x, out bool y) { x = true; y = true; M(ref (1, 2) == (3, 4), out (1, 2) == (3, 4)); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (8,15): error CS1510: A ref or out value must be an assignable variable // M(ref (1, 2) == (3, 4), out (1, 2) == (3, 4)); Diagnostic(ErrorCode.ERR_RefLvalueExpected, "(1, 2) == (3, 4)").WithLocation(8, 15), // (8,37): error CS1510: A ref or out value must be an assignable variable // M(ref (1, 2) == (3, 4), out (1, 2) == (3, 4)); Diagnostic(ErrorCode.ERR_RefLvalueExpected, "(1, 2) == (3, 4)").WithLocation(8, 37) ); } [Fact] public void TestWithAnonymousTypes() { var source = @" public class C { public static void Main() { var a = new { A = 1 }; var b = new { B = 2 }; var c = new { A = 1 }; var d = new { B = 2 }; System.Console.Write((a, b) == (a, b)); System.Console.Write((a, b) == (c, d)); System.Console.Write((a, b) != (c, d)); } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "TrueFalseTrue"); } [Fact] public void TestWithAnonymousTypes2() { var source = @" public class C { public static void Main() { var a = new { A = 1 }; var b = new { B = 2 }; System.Console.Write((a, b) == (b, a)); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (9,30): error CS0019: Operator '==' cannot be applied to operands of type '<anonymous type: int A>' and '<anonymous type: int B>' // System.Console.Write((a, b) == (b, a)); Diagnostic(ErrorCode.ERR_BadBinaryOps, "(a, b) == (b, a)").WithArguments("==", "<anonymous type: int A>", "<anonymous type: int B>").WithLocation(9, 30), // (9,30): error CS0019: Operator '==' cannot be applied to operands of type '<anonymous type: int B>' and '<anonymous type: int A>' // System.Console.Write((a, b) == (b, a)); Diagnostic(ErrorCode.ERR_BadBinaryOps, "(a, b) == (b, a)").WithArguments("==", "<anonymous type: int B>", "<anonymous type: int A>").WithLocation(9, 30) ); } [Fact] public void TestRefReturningElements() { var source = @" public class C { public static void Main() { System.Console.Write((P, S()) == (1, ""hello"")); } public static int p = 1; public static ref int P => ref p; public static string s = ""hello""; public static ref string S() => ref s; } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "True"); } [Fact] public void TestChecked() { var source = @" public class C { public static void Main() { try { checked { int ten = 10; System.Console.Write((2147483647 + ten, 1) == (0, 1)); } } catch (System.OverflowException) { System.Console.Write(""overflow""); } } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "overflow"); } [Fact] public void TestUnchecked() { var source = @" public class C { public static void Main() { unchecked { int ten = 10; System.Console.Write((2147483647 + ten, 1) == (-2147483639, 1)); } } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "True"); } [Fact] public void TestInQuery() { var source = @" using System.Linq; public class C { public static void Main() { var query = from a in new int[] { 1, 2, 2} where (a, 2) == (2, a) select a; foreach (var i in query) { System.Console.Write(i); } } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "22"); } [Fact] public void TestWithPointer() { var source = @" public class C { public unsafe static void M() { int x = 234; int y = 236; int* p1 = &x; int* p2 = &y; _ = (p1, p2) == (p1, p2); } } "; var comp = CreateCompilation(source, options: TestOptions.UnsafeDebugDll); comp.VerifyDiagnostics( // (10,14): error CS0306: The type 'int*' may not be used as a type argument // _ = (p1, p2) == (p1, p2); Diagnostic(ErrorCode.ERR_BadTypeArgument, "p1").WithArguments("int*").WithLocation(10, 14), // (10,18): error CS0306: The type 'int*' may not be used as a type argument // _ = (p1, p2) == (p1, p2); Diagnostic(ErrorCode.ERR_BadTypeArgument, "p2").WithArguments("int*").WithLocation(10, 18), // (10,26): error CS0306: The type 'int*' may not be used as a type argument // _ = (p1, p2) == (p1, p2); Diagnostic(ErrorCode.ERR_BadTypeArgument, "p1").WithArguments("int*").WithLocation(10, 26), // (10,30): error CS0306: The type 'int*' may not be used as a type argument // _ = (p1, p2) == (p1, p2); Diagnostic(ErrorCode.ERR_BadTypeArgument, "p2").WithArguments("int*").WithLocation(10, 30), // (10,14): error CS0306: The type 'void*' may not be used as a type argument // _ = (p1, p2) == (p1, p2); Diagnostic(ErrorCode.ERR_BadTypeArgument, "p1").WithArguments("void*").WithLocation(10, 14), // (10,18): error CS0306: The type 'void*' may not be used as a type argument // _ = (p1, p2) == (p1, p2); Diagnostic(ErrorCode.ERR_BadTypeArgument, "p2").WithArguments("void*").WithLocation(10, 18), // (10,26): error CS0306: The type 'void*' may not be used as a type argument // _ = (p1, p2) == (p1, p2); Diagnostic(ErrorCode.ERR_BadTypeArgument, "p1").WithArguments("void*").WithLocation(10, 26), // (10,30): error CS0306: The type 'void*' may not be used as a type argument // _ = (p1, p2) == (p1, p2); Diagnostic(ErrorCode.ERR_BadTypeArgument, "p2").WithArguments("void*").WithLocation(10, 30) ); } [Fact] public void TestOrder01() { var source = @" using System; public class C { public static void Main() { X x = new X(); Y y = new Y(); Console.WriteLine((1, ((int, int))x) == (y, (1, 1))); } } class X { public static implicit operator (short, short)(X x) { Console.WriteLine(""X-> (short, short)""); return (1, 1); } } class Y { public static implicit operator int(Y x) { Console.WriteLine(""Y -> int""); return 1; } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: @"X-> (short, short) Y -> int True"); } [Fact] public void TestOrder02() { var source = @" using System; public class C { public static void Main() { var result = (new B(1), new Nullable<B>(new A(2))) == (new A(3), new B(4)); Console.WriteLine(); Console.WriteLine(result); } } struct A { public readonly int N; public A(int n) { this.N = n; Console.Write($""new A({ n }); ""); } } struct B { public readonly int N; public B(int n) { this.N = n; Console.Write($""new B({n}); ""); } public static implicit operator B(A a) { Console.Write($""A({a.N})->""); return new B(a.N); } public static bool operator ==(B b1, B b2) { Console.Write($""B({b1.N})==B({b2.N}); ""); return b1.N == b2.N; } public static bool operator !=(B b1, B b2) { Console.Write($""B({b1.N})!=B({b2.N}); ""); return b1.N != b2.N; } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics( // (22,8): warning CS0660: 'B' defines operator == or operator != but does not override Object.Equals(object o) // struct B Diagnostic(ErrorCode.WRN_EqualityOpWithoutEquals, "B").WithArguments("B").WithLocation(22, 8), // (22,8): warning CS0661: 'B' defines operator == or operator != but does not override Object.GetHashCode() // struct B Diagnostic(ErrorCode.WRN_EqualityOpWithoutGetHashCode, "B").WithArguments("B").WithLocation(22, 8) ); CompileAndVerify(comp, expectedOutput: @"new B(1); new A(2); A(2)->new B(2); new A(3); new B(4); A(3)->new B(3); B(1)==B(3); False "); } [Fact, WorkItem(35958, "https://github.com/dotnet/roslyn/issues/35958")] public void TestMethodGroupConversionInTupleEquality_01() { var source = @" using System; public class C { public static void Main() { Action a = M; Console.WriteLine((a, M) == (M, a)); } static void M() {} }"; var comp = CompileAndVerify(source, expectedOutput: "True"); comp.VerifyDiagnostics(); } [Fact, WorkItem(35958, "https://github.com/dotnet/roslyn/issues/35958")] public void TestMethodGroupConversionInTupleEquality_02() { var source = @" using System; public class C { public static void Main() { Action a = () => {}; Console.WriteLine((a, M) == (M, a)); } static void M() {} }"; var comp = CompileAndVerify(source, expectedOutput: "False"); comp.VerifyDiagnostics(); } [Fact, WorkItem(35958, "https://github.com/dotnet/roslyn/issues/35958")] public void TestMethodGroupConversionInTupleEquality_03() { var source = @" using System; public class C { public static void Main() { K k = null; Console.WriteLine((k, 1) == (M, 1)); } static void M() {} } class K { public static bool operator ==(K k, System.Action a) => true; public static bool operator !=(K k, System.Action a) => false; public override bool Equals(object other) => false; public override int GetHashCode() => 1; } "; var comp = CompileAndVerify(source, expectedOutput: "True"); comp.VerifyDiagnostics(); } [Fact, WorkItem(35958, "https://github.com/dotnet/roslyn/issues/35958")] public void TestInterpolatedStringConversionInTupleEquality_01() { var source = @" using System; public class C { public static void Main() { K k = null; Console.WriteLine((k, 1) == ($""frog"", 1)); } static void M() {} } class K { public static bool operator ==(K k, IFormattable a) => a.ToString() == ""frog""; public static bool operator !=(K k, IFormattable a) => false; public override bool Equals(object other) => false; public override int GetHashCode() => 1; } "; var comp = CompileAndVerify(source, expectedOutput: "True"); comp.VerifyDiagnostics(); } } }
1
dotnet/roslyn
55,256
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-30T00:02:02Z
2021-07-30T09:17:54Z
6ce9c0048d37026337701fac035ac0745f6fe49f
88b59775dc6375635957ef229116460f290072aa
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Compilers/CSharp/Test/Semantic/Semantics/DelegateTypeTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Linq; using 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 DelegateTypeTests : CSharpTestBase { private const string s_utils = @"using System; using System.Linq; static class Utils { internal static string GetDelegateMethodName(this Delegate d) { var method = d.Method; return Concat(GetTypeName(method.DeclaringType), method.Name); } internal static string GetDelegateTypeName(this Delegate d) { return d.GetType().GetTypeName(); } internal static string GetTypeName(this Type type) { if (type.IsArray) { return GetTypeName(type.GetElementType()) + ""[]""; } string typeName = type.Name; int index = typeName.LastIndexOf('`'); if (index >= 0) { typeName = typeName.Substring(0, index); } typeName = Concat(type.Namespace, typeName); if (!type.IsGenericType) { return typeName; } return $""{typeName}<{string.Join("", "", type.GetGenericArguments().Select(GetTypeName))}>""; } private static string Concat(string container, string name) { return string.IsNullOrEmpty(container) ? name : container + ""."" + name; } }"; [Fact] public void LanguageVersion() { var source = @"class Program { static void Main() { System.Delegate d; d = Main; d = () => { }; d = delegate () { }; System.Linq.Expressions.Expression e = () => 1; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (6,13): error CS8773: Feature 'inferred delegate type' is not available in C# 9.0. Please use language version 10.0 or greater. // d = Main; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "Main").WithArguments("inferred delegate type", "10.0").WithLocation(6, 13), // (7,13): error CS8773: Feature 'inferred delegate type' is not available in C# 9.0. Please use language version 10.0 or greater. // d = () => { }; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "() => { }").WithArguments("inferred delegate type", "10.0").WithLocation(7, 13), // (8,13): error CS8773: Feature 'inferred delegate type' is not available in C# 9.0. Please use language version 10.0 or greater. // d = delegate () { }; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "delegate () { }").WithArguments("inferred delegate type", "10.0").WithLocation(8, 13), // (9,48): error CS8773: Feature 'inferred delegate type' is not available in C# 9.0. Please use language version 10.0 or greater. // System.Linq.Expressions.Expression e = () => 1; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "() => 1").WithArguments("inferred delegate type", "10.0").WithLocation(9, 48)); comp = CreateCompilation(source, parseOptions: TestOptions.Regular10); comp.VerifyDiagnostics(); } [Fact] public void MethodGroupConversions() { var source = @"class Program { static void Main() { object o = Main; System.ICloneable c = Main; System.Delegate d = Main; System.MulticastDelegate m = Main; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (5,20): error CS0428: Cannot convert method group 'Main' to non-delegate type 'object'. Did you intend to invoke the method? // object o = Main; Diagnostic(ErrorCode.ERR_MethGrpToNonDel, "Main").WithArguments("Main", "object").WithLocation(5, 20), // (6,31): error CS0428: Cannot convert method group 'Main' to non-delegate type 'ICloneable'. Did you intend to invoke the method? // System.ICloneable c = Main; Diagnostic(ErrorCode.ERR_MethGrpToNonDel, "Main").WithArguments("Main", "System.ICloneable").WithLocation(6, 31), // (8,38): error CS0428: Cannot convert method group 'Main' to non-delegate type 'MulticastDelegate'. Did you intend to invoke the method? // System.MulticastDelegate m = Main; Diagnostic(ErrorCode.ERR_MethGrpToNonDel, "Main").WithArguments("Main", "System.MulticastDelegate").WithLocation(8, 38)); } [Fact] public void LambdaConversions() { var source = @"class Program { static void Main() { object o = () => { }; System.ICloneable c = () => { }; System.Delegate d = () => { }; System.MulticastDelegate m = () => { }; d = x => x; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (5,20): error CS1660: Cannot convert lambda expression to type 'object' because it is not a delegate type // object o = () => { }; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => { }").WithArguments("lambda expression", "object").WithLocation(5, 20), // (6,31): error CS1660: Cannot convert lambda expression to type 'ICloneable' because it is not a delegate type // System.ICloneable c = () => { }; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => { }").WithArguments("lambda expression", "System.ICloneable").WithLocation(6, 31), // (8,38): error CS1660: Cannot convert lambda expression to type 'MulticastDelegate' because it is not a delegate type // System.MulticastDelegate m = () => { }; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => { }").WithArguments("lambda expression", "System.MulticastDelegate").WithLocation(8, 38), // (9,13): error CS8917: The delegate type could not be inferred. // d = x => x; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "x => x").WithLocation(9, 13)); } private static IEnumerable<object?[]> GetMethodGroupData(Func<string, string, DiagnosticDescription[]> getExpectedDiagnostics) { yield return getData("static int F() => 0;", "Program.F", "F", "System.Func<System.Int32>"); yield return getData("static int F() => 0;", "F", "F", "System.Func<System.Int32>"); yield return getData("int F() => 0;", "(new Program()).F", "F", "System.Func<System.Int32>"); yield return getData("static T F<T>() => default;", "Program.F<int>", "F", "System.Func<System.Int32>"); yield return getData("static void F<T>() where T : class { }", "F<object>", "F", "System.Action"); yield return getData("static void F<T>() where T : struct { }", "F<int>", "F", "System.Action"); yield return getData("T F<T>() => default;", "(new Program()).F<int>", "F", "System.Func<System.Int32>"); yield return getData("T F<T>() => default;", "(new Program()).F", "F", null); yield return getData("void F<T>(T t) { }", "(new Program()).F<string>", "F", "System.Action<System.String>"); yield return getData("void F<T>(T t) { }", "(new Program()).F", "F", null); yield return getData("static ref int F() => throw null;", "F", "F", null); yield return getData("static ref readonly int F() => throw null;", "F", "F", null); yield return getData("static void F() { }", "F", "F", "System.Action"); yield return getData("static void F(int x, int y) { }", "F", "F", "System.Action<System.Int32, System.Int32>"); yield return getData("static void F(out int x, int y) { x = 0; }", "F", "F", null); yield return getData("static void F(int x, ref int y) { }", "F", "F", null); yield return getData("static void F(int x, in int y) { }", "F", "F", null); yield return getData("static void F(int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16) { }", "F", "F", "System.Action<System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object>"); yield return getData("static void F(int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16, int _17) { }", "F", "F", null); yield return getData("static object F(int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16) => null;", "F", "F", "System.Func<System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Object>"); yield return getData("static object F(int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16, int _17) => null;", "F", "F", null); object?[] getData(string methodDeclaration, string methodGroupExpression, string methodGroupOnly, string? expectedType) => new object?[] { methodDeclaration, methodGroupExpression, expectedType is null ? getExpectedDiagnostics(methodGroupExpression, methodGroupOnly) : null, expectedType }; } public static IEnumerable<object?[]> GetMethodGroupImplicitConversionData() { return GetMethodGroupData((methodGroupExpression, methodGroupOnly) => { int offset = methodGroupExpression.Length - methodGroupOnly.Length; return new[] { // (6,29): error CS8917: The delegate type could not be inferred. // System.Delegate d = F; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, methodGroupOnly).WithLocation(6, 29 + offset) }; }); } [Theory] [MemberData(nameof(GetMethodGroupImplicitConversionData))] public void MethodGroup_ImplicitConversion(string methodDeclaration, string methodGroupExpression, DiagnosticDescription[]? expectedDiagnostics, string? expectedType) { var source = $@"class Program {{ {methodDeclaration} static void Main() {{ System.Delegate d = {methodGroupExpression}; System.Console.Write(d.GetDelegateTypeName()); }} }}"; var comp = CreateCompilation(new[] { source, s_utils }, parseOptions: TestOptions.RegularPreview, options: TestOptions.ReleaseExe); if (expectedDiagnostics is null) { CompileAndVerify(comp, expectedOutput: expectedType); } else { comp.VerifyDiagnostics(expectedDiagnostics); } var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var expr = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Single().Initializer!.Value; var typeInfo = model.GetTypeInfo(expr); Assert.Null(typeInfo.Type); Assert.Equal(SpecialType.System_Delegate, typeInfo.ConvertedType!.SpecialType); } public static IEnumerable<object?[]> GetMethodGroupExplicitConversionData() { return GetMethodGroupData((methodGroupExpression, methodGroupOnly) => { int offset = methodGroupExpression.Length - methodGroupOnly.Length; return new[] { // (6,20): error CS0030: Cannot convert type 'method' to 'Delegate' // object o = (System.Delegate)F; Diagnostic(ErrorCode.ERR_NoExplicitConv, $"(System.Delegate){methodGroupExpression}").WithArguments("method", "System.Delegate").WithLocation(6, 20) }; }); } [Theory] [MemberData(nameof(GetMethodGroupExplicitConversionData))] public void MethodGroup_ExplicitConversion(string methodDeclaration, string methodGroupExpression, DiagnosticDescription[]? expectedDiagnostics, string? expectedType) { var source = $@"class Program {{ {methodDeclaration} static void Main() {{ object o = (System.Delegate){methodGroupExpression}; System.Console.Write(o.GetType().GetTypeName()); }} }}"; var comp = CreateCompilation(new[] { source, s_utils }, parseOptions: TestOptions.RegularPreview, options: TestOptions.ReleaseExe); if (expectedDiagnostics is null) { CompileAndVerify(comp, expectedOutput: expectedType); } else { comp.VerifyDiagnostics(expectedDiagnostics); } var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var expr = ((CastExpressionSyntax)tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Single().Initializer!.Value).Expression; var typeInfo = model.GetTypeInfo(expr); // https://github.com/dotnet/roslyn/issues/52874: GetTypeInfo() for method group should return inferred delegate type. Assert.Null(typeInfo.Type); Assert.Null(typeInfo.ConvertedType); } public static IEnumerable<object?[]> GetLambdaData() { yield return getData("x => x", null); yield return getData("x => { return x; }", null); yield return getData("x => ref args[0]", null); yield return getData("(x, y) => { }", null); yield return getData("() => 1", "System.Func<System.Int32>"); yield return getData("() => ref args[0]", null); yield return getData("() => { }", "System.Action"); yield return getData("(int x, int y) => { }", "System.Action<System.Int32, System.Int32>"); yield return getData("(out int x, int y) => { x = 0; }", null); yield return getData("(int x, ref int y) => { x = 0; }", null); yield return getData("(int x, in int y) => { x = 0; }", null); yield return getData("(int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16) => { }", "System.Action<System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object>"); yield return getData("(int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16, int _17) => { }", null); yield return getData("(int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16) => _1", "System.Func<System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32>"); yield return getData("(int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16, int _17) => _1", null); yield return getData("static () => 1", "System.Func<System.Int32>"); yield return getData("async () => { await System.Threading.Tasks.Task.Delay(0); }", "System.Func<System.Threading.Tasks.Task>"); yield return getData("static async () => { await System.Threading.Tasks.Task.Delay(0); return 0; }", "System.Func<System.Threading.Tasks.Task<System.Int32>>"); yield return getData("() => Main", null); yield return getData("(int x) => x switch { _ => null }", null); yield return getData("_ => { }", null); yield return getData("_ => _", null); yield return getData("() => throw null", null); yield return getData("x => throw null", null); yield return getData("(int x) => throw null", null); yield return getData("() => { throw null; }", "System.Action"); yield return getData("(int x) => { throw null; }", "System.Action<System.Int32>"); yield return getData("(string s) => { if (s.Length > 0) return s; return null; }", "System.Func<System.String, System.String>"); yield return getData("(string s) => { if (s.Length > 0) return default; return s; }", "System.Func<System.String, System.String>"); yield return getData("(int i) => { if (i > 0) return i; return default; }", "System.Func<System.Int32, System.Int32>"); yield return getData("(int x, short y) => { if (x > 0) return x; return y; }", "System.Func<System.Int32, System.Int16, System.Int32>"); yield return getData("(int x, short y) => { if (x > 0) return y; return x; }", "System.Func<System.Int32, System.Int16, System.Int32>"); yield return getData("object () => default", "System.Func<System.Object>"); yield return getData("void () => { }", "System.Action"); static object?[] getData(string expr, string? expectedType) => new object?[] { expr, expectedType }; } public static IEnumerable<object?[]> GetAnonymousMethodData() { yield return getData("delegate { }", null); yield return getData("delegate () { return 1; }", "System.Func<System.Int32>"); yield return getData("delegate () { return ref args[0]; }", null); yield return getData("delegate () { }", "System.Action"); yield return getData("delegate (int x, int y) { }", "System.Action<System.Int32, System.Int32>"); yield return getData("delegate (out int x, int y) { x = 0; }", null); yield return getData("delegate (int x, ref int y) { x = 0; }", null); yield return getData("delegate (int x, in int y) { x = 0; }", null); yield return getData("delegate (int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16) { }", "System.Action<System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object>"); yield return getData("delegate (int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16, int _17) { }", null); yield return getData("delegate (int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16) { return _1; }", "System.Func<System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32>"); yield return getData("delegate (int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16, int _17) { return _1; }", null); static object?[] getData(string expr, string? expectedType) => new object?[] { expr, expectedType }; } [Theory] [MemberData(nameof(GetLambdaData))] [MemberData(nameof(GetAnonymousMethodData))] public void AnonymousFunction_ImplicitConversion(string anonymousFunction, string? expectedType) { var source = $@"class Program {{ static void Main(string[] args) {{ System.Delegate d = {anonymousFunction}; System.Console.Write(d.GetDelegateTypeName()); }} }}"; var comp = CreateCompilation(new[] { source, s_utils }, parseOptions: TestOptions.RegularPreview, options: TestOptions.ReleaseExe); if (expectedType is null) { comp.VerifyDiagnostics( // (5,29): error CS8917: The delegate type could not be inferred. // System.Delegate d = x => x; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, anonymousFunction).WithLocation(5, 29)); } else { CompileAndVerify(comp, expectedOutput: expectedType); } var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var expr = tree.GetRoot().DescendantNodes().OfType<AnonymousFunctionExpressionSyntax>().Single(); var typeInfo = model.GetTypeInfo(expr); if (expectedType == null) { Assert.Null(typeInfo.Type); } else { Assert.Equal(expectedType, typeInfo.Type.ToTestDisplayString()); } Assert.Equal(SpecialType.System_Delegate, typeInfo.ConvertedType!.SpecialType); } [Theory] [MemberData(nameof(GetLambdaData))] [MemberData(nameof(GetAnonymousMethodData))] public void AnonymousFunction_ExplicitConversion(string anonymousFunction, string? expectedType) { var source = $@"class Program {{ static void Main(string[] args) {{ object o = (System.Delegate)({anonymousFunction}); System.Console.Write(o.GetType().GetTypeName()); }} }}"; var comp = CreateCompilation(new[] { source, s_utils }, parseOptions: TestOptions.RegularPreview, options: TestOptions.ReleaseExe); if (expectedType is null) { comp.VerifyDiagnostics( // (5,20): error CS8917: The delegate type could not be inferred. // object o = (System.Delegate)(x => x); Diagnostic(ErrorCode.ERR_CannotInferDelegateType, $"(System.Delegate)({anonymousFunction})").WithLocation(5, 20)); } else { CompileAndVerify(comp, expectedOutput: expectedType); } var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var expr = ((CastExpressionSyntax)tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Single().Initializer!.Value).Expression; var typeInfo = model.GetTypeInfo(expr); Assert.Null(typeInfo.Type); Assert.Equal(expectedType, typeInfo.ConvertedType?.ToTestDisplayString()); } public static IEnumerable<object?[]> GetExpressionData() { yield return getData("x => x", null); yield return getData("() => 1", "System.Func<System.Int32>"); yield return getData("(int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16) => _1", "System.Func<System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32>"); yield return getData("(int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16, int _17) => _1", null); yield return getData("static () => 1", "System.Func<System.Int32>"); static object?[] getData(string expr, string? expectedType) => new object?[] { expr, expectedType }; } [Theory] [MemberData(nameof(GetExpressionData))] public void Expression_ImplicitConversion(string anonymousFunction, string? expectedType) { var source = $@"class Program {{ static void Main(string[] args) {{ System.Linq.Expressions.Expression e = {anonymousFunction}; }} }}"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); if (expectedType is null) { comp.VerifyDiagnostics( // (5,48): error CS8917: The delegate type could not be inferred. // System.Linq.Expressions.Expression e = x => x; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, anonymousFunction).WithLocation(5, 48)); } else { comp.VerifyDiagnostics(); } var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var expr = tree.GetRoot().DescendantNodes().OfType<AnonymousFunctionExpressionSyntax>().Single(); var typeInfo = model.GetTypeInfo(expr); if (expectedType == null) { Assert.Null(typeInfo.Type); } else { Assert.Equal($"System.Linq.Expressions.Expression<{expectedType}>", typeInfo.Type.ToTestDisplayString()); } Assert.Equal("System.Linq.Expressions.Expression", typeInfo.ConvertedType!.ToTestDisplayString()); } [Theory] [MemberData(nameof(GetExpressionData))] public void Expression_ExplicitConversion(string anonymousFunction, string? expectedType) { var source = $@"class Program {{ static void Main(string[] args) {{ object o = (System.Linq.Expressions.Expression)({anonymousFunction}); }} }}"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); if (expectedType is null) { comp.VerifyDiagnostics( // (5,20): error CS8917: The delegate type could not be inferred. // object o = (System.Linq.Expressions.Expression)(x => x); Diagnostic(ErrorCode.ERR_CannotInferDelegateType, $"(System.Linq.Expressions.Expression)({anonymousFunction})").WithLocation(5, 20)); } else { comp.VerifyDiagnostics(); } var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var expr = ((CastExpressionSyntax)tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Single().Initializer!.Value).Expression; var typeInfo = model.GetTypeInfo(expr); Assert.Null(typeInfo.Type); if (expectedType is null) { Assert.Null(typeInfo.ConvertedType); } else { Assert.Equal($"System.Linq.Expressions.Expression<{expectedType}>", typeInfo.ConvertedType.ToTestDisplayString()); } } /// <summary> /// Should bind and report diagnostics from anonymous method body /// regardless of whether the delegate type can be inferred. /// </summary> [Fact] public void AnonymousMethodBodyErrors() { var source = @"using System; class Program { static void Main() { Delegate d0 = x0 => { _ = x0.Length; object y0 = 0; _ = y0.Length; }; Delegate d1 = (object x1) => { _ = x1.Length; }; Delegate d2 = (ref object x2) => { _ = x2.Length; }; Delegate d3 = delegate (object x3) { _ = x3.Length; }; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (6,23): error CS8917: The delegate type could not be inferred. // Delegate d0 = x0 => { _ = x0.Length; object y0 = 0; _ = y0.Length; }; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "x0 => { _ = x0.Length; object y0 = 0; _ = y0.Length; }").WithLocation(6, 23), // (6,68): error CS1061: 'object' does not contain a definition for 'Length' and no accessible extension method 'Length' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?) // Delegate d0 = x0 => { _ = x0.Length; object y0 = 0; _ = y0.Length; }; Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "Length").WithArguments("object", "Length").WithLocation(6, 68), // (7,47): error CS1061: 'object' does not contain a definition for 'Length' and no accessible extension method 'Length' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?) // Delegate d1 = (object x1) => { _ = x1.Length; }; Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "Length").WithArguments("object", "Length").WithLocation(7, 47), // (8,23): error CS8917: The delegate type could not be inferred. // Delegate d2 = (ref object x2) => { _ = x2.Length; }; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "(ref object x2) => { _ = x2.Length; }").WithLocation(8, 23), // (8,51): error CS1061: 'object' does not contain a definition for 'Length' and no accessible extension method 'Length' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?) // Delegate d2 = (ref object x2) => { _ = x2.Length; }; Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "Length").WithArguments("object", "Length").WithLocation(8, 51), // (9,53): error CS1061: 'object' does not contain a definition for 'Length' and no accessible extension method 'Length' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?) // Delegate d3 = delegate (object x3) { _ = x3.Length; }; Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "Length").WithArguments("object", "Length").WithLocation(9, 53)); } public static IEnumerable<object?[]> GetBaseAndDerivedTypesData() { yield return getData("internal void F(object x) { }", "internal static new void F(object x) { }", "F", "F", null, "System.Action<System.Object>"); // instance and static // https://github.com/dotnet/roslyn/issues/52701: Assert failure: Unexpected value 'LessDerived' of type 'Microsoft.CodeAnalysis.CSharp.MemberResolutionKind' #if !DEBUG yield return getData("internal void F(object x) { }", "internal static new void F(object x) { }", "this.F", "F", new[] { // (5,29): error CS0176: Member 'B.F(object)' cannot be accessed with an instance reference; qualify it with a type name instead // System.Delegate d = this.F; Diagnostic(ErrorCode.ERR_ObjectProhibited, "this.F").WithArguments("B.F(object)").WithLocation(5, 29) }); // instance and static #endif yield return getData("internal void F(object x) { }", "internal static new void F(object x) { }", "base.F", "F", null, "System.Action<System.Object>"); // instance and static yield return getData("internal static void F(object x) { }", "internal new void F(object x) { }", "F", "F", null, "System.Action<System.Object>"); // static and instance yield return getData("internal static void F(object x) { }", "internal new void F(object x) { }", "this.F", "F", null, "System.Action<System.Object>"); // static and instance yield return getData("internal static void F(object x) { }", "internal new void F(object x) { }", "base.F", "F"); // static and instance yield return getData("internal void F(object x) { }", "internal static void F() { }", "F", "F"); // instance and static, different number of parameters yield return getData("internal void F(object x) { }", "internal static void F() { }", "B.F", "F", null, "System.Action"); // instance and static, different number of parameters yield return getData("internal void F(object x) { }", "internal static void F() { }", "this.F", "F", null, "System.Action<System.Object>"); // instance and static, different number of parameters yield return getData("internal void F(object x) { }", "internal static void F() { }", "base.F", "F", null, "System.Action<System.Object>"); // instance and static, different number of parameters yield return getData("internal static void F() { }", "internal void F(object x) { }", "F", "F"); // static and instance, different number of parameters yield return getData("internal static void F() { }", "internal void F(object x) { }", "B.F", "F", null, "System.Action"); // static and instance, different number of parameters yield return getData("internal static void F() { }", "internal void F(object x) { }", "this.F", "F", null, "System.Action<System.Object>"); // static and instance, different number of parameters yield return getData("internal static void F() { }", "internal void F(object x) { }", "base.F", "F"); // static and instance, different number of parameters yield return getData("internal static void F(object x) { }", "private static void F() { }", "F", "F"); // internal and private yield return getData("private static void F(object x) { }", "internal static void F() { }", "F", "F", null, "System.Action"); // internal and private yield return getData("internal abstract void F(object x);", "internal override void F(object x) { }", "F", "F", null, "System.Action<System.Object>"); // override yield return getData("internal virtual void F(object x) { }", "internal override void F(object x) { }", "F", "F", null, "System.Action<System.Object>"); // override yield return getData("internal void F(object x) { }", "internal void F(object x) { }", "F", "F", null, "System.Action<System.Object>"); // hiding yield return getData("internal void F(object x) { }", "internal new void F(object x) { }", "F", "F", null, "System.Action<System.Object>"); // hiding yield return getData("internal void F(object x) { }", "internal new void F(object y) { }", "F", "F", null, "System.Action<System.Object>"); // different parameter name yield return getData("internal void F(object x) { }", "internal void F(string x) { }", "F", "F"); // different parameter type yield return getData("internal void F(object x) { }", "internal void F(object x, object y) { }", "F", "F"); // different number of parameters yield return getData("internal void F(object x) { }", "internal void F(ref object x) { }", "F", "F"); // different parameter ref kind yield return getData("internal void F(ref object x) { }", "internal void F(object x) { }", "F", "F"); // different parameter ref kind yield return getData("internal abstract object F();", "internal override object F() => throw null;", "F", "F", null, "System.Func<System.Object>"); // override yield return getData("internal virtual object F() => throw null;", "internal override object F() => throw null;", "F", "F", null, "System.Func<System.Object>"); // override yield return getData("internal object F() => throw null;", "internal object F() => throw null;", "F", "F", null, "System.Func<System.Object>"); // hiding yield return getData("internal object F() => throw null;", "internal new object F() => throw null;", "F", "F", null, "System.Func<System.Object>"); // hiding yield return getData("internal string F() => throw null;", "internal new object F() => throw null;", "F", "F"); // different return type yield return getData("internal object F() => throw null;", "internal new ref object F() => throw null;", "F", "F"); // different return ref kind yield return getData("internal ref object F() => throw null;", "internal new object F() => throw null;", "F", "F"); // different return ref kind yield return getData("internal void F(object x) { }", "internal new void F(dynamic x) { }", "F", "F", null, "System.Action<System.Object>"); // object/dynamic yield return getData("internal dynamic F() => throw null;", "internal new object F() => throw null;", "F", "F", null, "System.Func<System.Object>"); // object/dynamic yield return getData("internal void F((object, int) x) { }", "internal new void F((object a, int b) x) { }", "F", "F", null, "System.Action<System.ValueTuple<System.Object, System.Int32>>"); // tuple names yield return getData("internal (object a, int b) F() => throw null;", "internal new (object, int) F() => throw null;", "F", "F", null, "System.Func<System.ValueTuple<System.Object, System.Int32>>"); // tuple names yield return getData("internal void F(System.IntPtr x) { }", "internal new void F(nint x) { }", "F", "F", null, "System.Action<System.IntPtr>"); // System.IntPtr/nint yield return getData("internal nint F() => throw null;", "internal new System.IntPtr F() => throw null;", "F", "F", null, "System.Func<System.IntPtr>"); // System.IntPtr/nint yield return getData("internal void F(object x) { }", @"#nullable enable internal new void F(object? x) { } #nullable disable", "F", "F", null, "System.Action<System.Object>"); // different nullability yield return getData( @"#nullable enable internal object? F() => throw null!; #nullable disable", "internal new object F() => throw null;", "F", "F", null, "System.Func<System.Object>"); // different nullability yield return getData("internal void F() { }", "internal void F<T>() { }", "F", "F"); // different arity yield return getData("internal void F() { }", "internal void F<T>() { }", "F<int>", "F<int>", null, "System.Action"); // different arity yield return getData("internal void F<T>() { }", "internal void F() { }", "F", "F"); // different arity yield return getData("internal void F<T>() { }", "internal void F() { }", "F<int>", "F<int>", null, "System.Action"); // different arity yield return getData("internal void F<T>() { }", "internal void F<T, U>() { }", "F<int>", "F<int>", null, "System.Action"); // different arity yield return getData("internal void F<T>() { }", "internal void F<T, U>() { }", "F<int, object>", "F<int, object>", null, "System.Action"); // different arity yield return getData("internal void F<T>(T t) { }", "internal new void F<U>(U u) { }", "F<int>", "F<int>", null, "System.Action<System.Int32>"); // different type parameter names yield return getData("internal void F<T>(T t) where T : class { }", "internal new void F<T>(T t) { }", "F<object>", "F<object>", null, "System.Action<System.Object>"); // different type parameter constraints yield return getData("internal void F<T>(T t) { }", "internal new void F<T>(T t) where T : class { }", "F<object>", "F<object>", null, "System.Action<System.Object>"); // different type parameter constraints yield return getData("internal void F<T>(T t) { }", "internal new void F<T>(T t) where T : class { }", "base.F<object>", "F<object>", null, "System.Action<System.Object>"); // different type parameter constraints yield return getData("internal void F<T>(T t) where T : class { }", "internal new void F<T>(T t) where T : struct { }", "F<int>", "F<int>", null, "System.Action<System.Int32>"); // different type parameter constraints // https://github.com/dotnet/roslyn/issues/52701: Assert failure: Unexpected value 'LessDerived' of type 'Microsoft.CodeAnalysis.CSharp.MemberResolutionKind' #if !DEBUG yield return getData("internal void F<T>(T t) where T : class { }", "internal new void F<T>(T t) where T : struct { }", "F<object>", "F<object>", new[] { // (5,29): 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.Delegate d = F<object>; Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "F<object>").WithArguments("B.F<T>(T)", "T", "object").WithLocation(5, 29) }); // different type parameter constraints #endif static object?[] getData(string methodA, string methodB, string methodGroupExpression, string methodGroupOnly, DiagnosticDescription[]? expectedDiagnostics = null, string? expectedType = null) { if (expectedDiagnostics is null && expectedType is null) { int offset = methodGroupExpression.Length - methodGroupOnly.Length; expectedDiagnostics = new[] { // (5,29): error CS8917: The delegate type could not be inferred. // System.Delegate d = F; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, methodGroupOnly).WithLocation(5, 29 + offset) }; } return new object?[] { methodA, methodB, methodGroupExpression, expectedDiagnostics, expectedType }; } } [Theory] [MemberData(nameof(GetBaseAndDerivedTypesData))] public void MethodGroup_BaseAndDerivedTypes(string methodA, string methodB, string methodGroupExpression, DiagnosticDescription[]? expectedDiagnostics, string? expectedType) { var source = $@"partial class B {{ void M() {{ System.Delegate d = {methodGroupExpression}; System.Console.Write(d.GetDelegateTypeName()); }} static void Main() {{ new B().M(); }} }} abstract class A {{ {methodA} }} partial class B : A {{ {methodB} }}"; var comp = CreateCompilation(new[] { source, s_utils }, parseOptions: TestOptions.RegularPreview, options: TestOptions.ReleaseExe); if (expectedDiagnostics is null) { CompileAndVerify(comp, expectedOutput: expectedType); } else { comp.VerifyDiagnostics(expectedDiagnostics); } var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var expr = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Single().Initializer!.Value; var typeInfo = model.GetTypeInfo(expr); Assert.Null(typeInfo.Type); Assert.Equal(SpecialType.System_Delegate, typeInfo.ConvertedType!.SpecialType); } public static IEnumerable<object?[]> GetExtensionMethodsSameScopeData() { yield return getData("internal static void F(this object x) { }", "internal static void F(this string x) { }", "string.Empty.F", "F", null, "B.F", "System.Action"); // different parameter type yield return getData("internal static void F(this object x) { }", "internal static void F(this string x) { }", "this.F", "F", null, "A.F", "System.Action"); // different parameter type yield return getData("internal static void F(this object x) { }", "internal static void F(this object x, object y) { }", "this.F", "F"); // different number of parameters yield return getData("internal static void F(this object x, object y) { }", "internal static void F(this object x, ref object y) { }", "this.F", "F"); // different parameter ref kind yield return getData("internal static void F(this object x, ref object y) { }", "internal static void F(this object x, object y) { }", "this.F", "F"); // different parameter ref kind yield return getData("internal static object F(this object x) => throw null;", "internal static ref object F(this object x) => throw null;", "this.F", "F"); // different return ref kind yield return getData("internal static ref object F(this object x) => throw null;", "internal static object F(this object x) => throw null;", "this.F", "F"); // different return ref kind yield return getData("internal static void F(this object x, object y) { }", "internal static void F<T>(this object x, T y) { }", "this.F", "F"); // different arity yield return getData("internal static void F(this object x, object y) { }", "internal static void F<T>(this object x, T y) { }", "this.F<int>", "F<int>", null, "B.F", "System.Action<System.Int32>"); // different arity yield return getData("internal static void F<T>(this object x) { }", "internal static void F(this object x) { }", "this.F", "F"); // different arity yield return getData("internal static void F<T>(this object x) { }", "internal static void F(this object x) { }", "this.F<int>", "F<int>", null, "A.F", "System.Action"); // different arity yield return getData("internal static void F<T>(this T t) where T : class { }", "internal static void F<T>(this T t) { }", "this.F<object>", "F<object>", new[] { // (5,29): error CS0121: The call is ambiguous between the following methods or properties: 'A.F<T>(T)' and 'B.F<T>(T)' // System.Delegate d = this.F<object>; Diagnostic(ErrorCode.ERR_AmbigCall, "this.F<object>").WithArguments("A.F<T>(T)", "B.F<T>(T)").WithLocation(5, 29) }); // different type parameter constraints yield return getData("internal static void F<T>(this T t) { }", "internal static void F<T>(this T t) where T : class { }", "this.F<object>", "F<object>", new[] { // (5,29): error CS0121: The call is ambiguous between the following methods or properties: 'A.F<T>(T)' and 'B.F<T>(T)' // System.Delegate d = this.F<object>; Diagnostic(ErrorCode.ERR_AmbigCall, "this.F<object>").WithArguments("A.F<T>(T)", "B.F<T>(T)").WithLocation(5, 29) }); // different type parameter constraints yield return getData("internal static void F<T>(this T t) where T : class { }", "internal static void F<T>(this T t) where T : struct { }", "this.F<int>", "F<int>"); // different type parameter constraints static object?[] getData(string methodA, string methodB, string methodGroupExpression, string methodGroupOnly, DiagnosticDescription[]? expectedDiagnostics = null, string? expectedMethod = null, string? expectedType = null) { if (expectedDiagnostics is null && expectedType is null) { int offset = methodGroupExpression.Length - methodGroupOnly.Length; expectedDiagnostics = new[] { // (5,29): error CS8917: The delegate type could not be inferred. // System.Delegate d = F; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, methodGroupOnly).WithLocation(5, 29 + offset) }; } return new object?[] { methodA, methodB, methodGroupExpression, expectedDiagnostics, expectedMethod, expectedType }; } } [Theory] [MemberData(nameof(GetExtensionMethodsSameScopeData))] public void MethodGroup_ExtensionMethodsSameScope(string methodA, string methodB, string methodGroupExpression, DiagnosticDescription[]? expectedDiagnostics, string? expectedMethod, string? expectedType) { var source = $@"class Program {{ void M() {{ System.Delegate d = {methodGroupExpression}; System.Console.Write(""{{0}}: {{1}}"", d.GetDelegateMethodName(), d.GetDelegateTypeName()); }} static void Main() {{ new Program().M(); }} }} static class A {{ {methodA} }} static class B {{ {methodB} }}"; var comp = CreateCompilation(new[] { source, s_utils }, parseOptions: TestOptions.RegularPreview, options: TestOptions.ReleaseExe); if (expectedDiagnostics is null) { CompileAndVerify(comp, expectedOutput: $"{expectedMethod}: {expectedType}"); } else { comp.VerifyDiagnostics(expectedDiagnostics); } var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var expr = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Single().Initializer!.Value; var typeInfo = model.GetTypeInfo(expr); Assert.Null(typeInfo.Type); Assert.Equal(SpecialType.System_Delegate, typeInfo.ConvertedType!.SpecialType); var symbolInfo = model.GetSymbolInfo(expr); // https://github.com/dotnet/roslyn/issues/52870: GetSymbolInfo() should return resolved method from method group. Assert.Null(symbolInfo.Symbol); } public static IEnumerable<object?[]> GetExtensionMethodsDifferentScopeData() { yield return getData("internal static void F(this object x) { }", "internal static void F(this object x) { }", "this.F", "F", null, "A.F", "System.Action"); // hiding yield return getData("internal static void F(this object x) { }", "internal static void F(this object y) { }", "this.F", "F", null, "A.F", "System.Action"); // different parameter name yield return getData("internal static void F(this object x) { }", "internal static void F(this string x) { }", "string.Empty.F", "F", null, "A.F", "System.Action"); // different parameter type yield return getData("internal static void F(this object x) { }", "internal static void F(this string x) { }", "this.F", "F", null, "A.F", "System.Action"); // different parameter type yield return getData("internal static void F(this object x) { }", "internal static void F(this object x, object y) { }", "this.F", "F"); // different number of parameters yield return getData("internal static void F(this object x, object y) { }", "internal static void F(this object x, ref object y) { }", "this.F", "F"); // different parameter ref kind yield return getData("internal static void F(this object x, ref object y) { }", "internal static void F(this object x, object y) { }", "this.F", "F"); // different parameter ref kind yield return getData("internal static object F(this object x) => throw null;", "internal static ref object F(this object x) => throw null;", "this.F", "F"); // different return ref kind yield return getData("internal static ref object F(this object x) => throw null;", "internal static object F(this object x) => throw null;", "this.F", "F"); // different return ref kind yield return getData("internal static void F(this object x, System.IntPtr y) { }", "internal static void F(this object x, nint y) { }", "this.F", "F", null, "A.F", "System.Action<System.IntPtr>"); // System.IntPtr/nint yield return getData("internal static nint F(this object x) => throw null;", "internal static System.IntPtr F(this object x) => throw null;", "this.F", "F", null, "A.F", "System.Func<System.IntPtr>"); // System.IntPtr/nint yield return getData("internal static void F(this object x, object y) { }", "internal static void F<T>(this object x, T y) { }", "this.F", "F"); // different arity yield return getData("internal static void F(this object x, object y) { }", "internal static void F<T>(this object x, T y) { }", "this.F<int>", "F<int>", null, "N.B.F", "System.Action<System.Int32>"); // different arity yield return getData("internal static void F<T>(this object x) { }", "internal static void F(this object x) { }", "this.F", "F"); // different arity yield return getData("internal static void F<T>(this object x) { }", "internal static void F(this object x) { }", "this.F<int>", "F<int>", null, "A.F", "System.Action"); // different arity yield return getData("internal static void F<T>(this T t) where T : class { }", "internal static void F<T>(this T t) { }", "this.F<object>", "F<object>", null, "A.F", "System.Action"); // different type parameter constraints yield return getData("internal static void F<T>(this T t) { }", "internal static void F<T>(this T t) where T : class { }", "this.F<object>", "F<object>", null, "A.F", "System.Action"); // different type parameter constraints yield return getData("internal static void F<T>(this T t) where T : class { }", "internal static void F<T>(this T t) where T : struct { }", "this.F<int>", "F<int>"); // different type parameter constraints static object?[] getData(string methodA, string methodB, string methodGroupExpression, string methodGroupOnly, DiagnosticDescription[]? expectedDiagnostics = null, string? expectedMethod = null, string? expectedType = null) { if (expectedDiagnostics is null && expectedType is null) { int offset = methodGroupExpression.Length - methodGroupOnly.Length; expectedDiagnostics = new[] { // (6,29): error CS8917: The delegate type could not be inferred. // System.Delegate d = F; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, methodGroupOnly).WithLocation(6, 29 + offset) }; } return new object?[] { methodA, methodB, methodGroupExpression, expectedDiagnostics, expectedMethod, expectedType }; } } [Theory] [MemberData(nameof(GetExtensionMethodsDifferentScopeData))] public void MethodGroup_ExtensionMethodsDifferentScope(string methodA, string methodB, string methodGroupExpression, DiagnosticDescription[]? expectedDiagnostics, string? expectedMethod, string? expectedType) { var source = $@"using N; class Program {{ void M() {{ System.Delegate d = {methodGroupExpression}; System.Console.Write(""{{0}}: {{1}}"", d.GetDelegateMethodName(), d.GetDelegateTypeName()); }} static void Main() {{ new Program().M(); }} }} static class A {{ {methodA} }} namespace N {{ static class B {{ {methodB} }} }}"; var comp = CreateCompilation(new[] { source, s_utils }, parseOptions: TestOptions.RegularPreview, options: TestOptions.ReleaseExe); if (expectedDiagnostics is null) { CompileAndVerify(comp, expectedOutput: $"{expectedMethod}: {expectedType}"); } else { comp.VerifyDiagnostics(expectedDiagnostics); } var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var expr = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Single().Initializer!.Value; var typeInfo = model.GetTypeInfo(expr); Assert.Null(typeInfo.Type); Assert.Equal(SpecialType.System_Delegate, typeInfo.ConvertedType!.SpecialType); var symbolInfo = model.GetSymbolInfo(expr); // https://github.com/dotnet/roslyn/issues/52870: GetSymbolInfo() should return resolved method from method group. Assert.Null(symbolInfo.Symbol); } [Fact] public void InstanceMethods_01() { var source = @"using System; class Program { object F1() => null; void F2(object x, int y) { } void F() { Delegate d1 = F1; Delegate d2 = this.F2; Console.WriteLine(""{0}, {1}"", d1.GetDelegateTypeName(), d2.GetDelegateTypeName()); } static void Main() { new Program().F(); } }"; CompileAndVerify(new[] { source, s_utils }, parseOptions: TestOptions.RegularPreview, expectedOutput: "System.Func<System.Object>, System.Action<System.Object, System.Int32>"); } [Fact] public void InstanceMethods_02() { var source = @"using System; class A { protected virtual void F() { Console.WriteLine(nameof(A)); } } class B : A { protected override void F() { Console.WriteLine(nameof(B)); } static void Invoke(Delegate d) { d.DynamicInvoke(); } void M() { Invoke(F); Invoke(this.F); Invoke(base.F); } static void Main() { new B().M(); } }"; CompileAndVerify(source, parseOptions: TestOptions.RegularPreview, expectedOutput: @"B B A"); } [Fact] public void InstanceMethods_03() { var source = @"using System; class A { protected void F() { Console.WriteLine(nameof(A)); } } class B : A { protected new void F() { Console.WriteLine(nameof(B)); } static void Invoke(Delegate d) { d.DynamicInvoke(); } void M() { Invoke(F); Invoke(this.F); Invoke(base.F); } static void Main() { new B().M(); } }"; CompileAndVerify(source, parseOptions: TestOptions.RegularPreview, expectedOutput: @"B B A"); } [Fact] public void InstanceMethods_04() { var source = @"class Program { T F<T>() => default; static void Main() { var p = new Program(); System.Delegate d = p.F; object o = (System.Delegate)p.F; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (7,31): error CS8917: The delegate type could not be inferred. // System.Delegate d = p.F; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "F").WithLocation(7, 31), // (8,20): error CS0030: Cannot convert type 'method' to 'Delegate' // object o = (System.Delegate)p.F; Diagnostic(ErrorCode.ERR_NoExplicitConv, "(System.Delegate)p.F").WithArguments("method", "System.Delegate").WithLocation(8, 20)); } [Fact] public void MethodGroup_Inaccessible() { var source = @"using System; class A { private static void F() { } internal static void F(object o) { } } class B { static void Main() { Delegate d = A.F; Console.WriteLine(d.GetDelegateTypeName()); } }"; CompileAndVerify(new[] { source, s_utils }, parseOptions: TestOptions.RegularPreview, expectedOutput: "System.Action<System.Object>"); } [Fact] public void MethodGroup_IncorrectArity() { var source = @"class Program { static void F0(object o) { } static void F0<T>(object o) { } static void F1(object o) { } static void F1<T, U>(object o) { } static void F2<T>(object o) { } static void F2<T, U>(object o) { } static void Main() { System.Delegate d; d = F0<int, object>; d = F1<int>; d = F2; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (12,13): error CS0308: The non-generic method 'Program.F0(object)' cannot be used with type arguments // d = F0<int, object>; Diagnostic(ErrorCode.ERR_HasNoTypeVars, "F0<int, object>").WithArguments("Program.F0(object)", "method").WithLocation(12, 13), // (13,13): error CS0308: The non-generic method 'Program.F1(object)' cannot be used with type arguments // d = F1<int>; Diagnostic(ErrorCode.ERR_HasNoTypeVars, "F1<int>").WithArguments("Program.F1(object)", "method").WithLocation(13, 13), // (14,13): error CS8917: The delegate type could not be inferred. // d = F2; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "F2").WithLocation(14, 13)); } [Fact] public void ExtensionMethods_01() { var source = @"static class E { internal static void F1(this object x, int y) { } internal static void F2(this object x) { } } class Program { void F2(int x) { } static void Main() { System.Delegate d; var p = new Program(); d = p.F1; d = p.F2; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (14,15): error CS8917: The delegate type could not be inferred. // d = p.F2; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "F2").WithLocation(14, 15)); } [Fact] public void ExtensionMethods_02() { var source = @"using System; static class E { internal static void F(this System.Type x, int y) { } internal static void F(this string x) { } } class Program { static void Main() { Delegate d1 = typeof(Program).F; Delegate d2 = """".F; Console.WriteLine(""{0}, {1}"", d1.GetDelegateTypeName(), d2.GetDelegateTypeName()); } }"; var comp = CreateCompilation(new[] { source, s_utils }, parseOptions: TestOptions.RegularPreview, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: "System.Action<System.Int32>, System.Action"); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var exprs = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Select(d => d.Initializer!.Value).ToArray(); Assert.Equal(2, exprs.Length); foreach (var expr in exprs) { var typeInfo = model.GetTypeInfo(expr); Assert.Null(typeInfo.Type); Assert.Equal(SpecialType.System_Delegate, typeInfo.ConvertedType!.SpecialType); } } [Fact] public void ExtensionMethods_03() { var source = @"using N; namespace N { static class E1 { internal static void F1(this object x, int y) { } internal static void F2(this object x, int y) { } internal static void F2(this object x) { } internal static void F3(this object x) { } } } static class E2 { internal static void F1(this object x) { } } class Program { static void Main() { System.Delegate d; var p = new Program(); d = p.F1; d = p.F2; d = p.F3; d = E1.F1; d = E2.F1; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (22,15): error CS8917: The delegate type could not be inferred. // d = p.F1; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "F1").WithLocation(22, 15), // (23,15): error CS8917: The delegate type could not be inferred. // d = p.F2; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "F2").WithLocation(23, 15)); } [Fact] public void ExtensionMethods_04() { var source = @"static class E { internal static void F1(this object x, int y) { } } static class Program { static void F2(this object x) { } static void Main() { System.Delegate d; d = E.F1; d = F2; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics(); } [Fact] public void ExtensionMethods_05() { var source = @"using System; static class E { internal static void F(this A a) { } } class A { } class B : A { static void Invoke(Delegate d) { } void M() { Invoke(F); Invoke(this.F); Invoke(base.F); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (14,16): error CS0103: The name 'F' does not exist in the current context // Invoke(F); Diagnostic(ErrorCode.ERR_NameNotInContext, "F").WithArguments("F").WithLocation(14, 16), // (16,21): error CS0117: 'A' does not contain a definition for 'F' // Invoke(base.F); Diagnostic(ErrorCode.ERR_NoSuchMember, "F").WithArguments("A", "F").WithLocation(16, 21)); } [Fact] public void ExtensionMethods_06() { var source = @"static class E { internal static void F1<T>(this object x, T y) { } internal static void F2<T, U>(this T t) { } } class Program { static void F<T>(T t) where T : class { System.Delegate d; d = t.F1; d = t.F2; d = t.F1<int>; d = t.F1<T>; d = t.F2<T, object>; d = t.F2<object, T>; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (11,15): error CS8917: The delegate type could not be inferred. // d = t.F1; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "F1").WithLocation(11, 15), // (12,15): error CS8917: The delegate type could not be inferred. // d = t.F2; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "F2").WithLocation(12, 15)); } /// <summary> /// Method group with dynamic receiver does not use method group conversion. /// </summary> [Fact] public void DynamicReceiver() { var source = @"using System; class Program { void F() { } static void Main() { dynamic d = new Program(); object obj; try { obj = d.F; } catch (Exception e) { obj = e; } Console.WriteLine(obj.GetType().FullName); } }"; CompileAndVerify(source, parseOptions: TestOptions.RegularPreview, references: new[] { CSharpRef }, expectedOutput: "Microsoft.CSharp.RuntimeBinder.RuntimeBinderException"); } // System.Func<> and System.Action<> cannot be used as the delegate type // when the parameters or return type are not valid type arguments. [Fact] public void InvalidTypeArguments() { var source = @"unsafe class Program { static int* F() => throw null; static void Main() { System.Delegate d; d = F; d = (int x, int* y) => { }; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview, options: TestOptions.UnsafeReleaseExe); comp.VerifyDiagnostics( // (7,13): error CS8917: The delegate type could not be inferred. // d = F; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "F").WithLocation(7, 13), // (8,13): error CS8917: The delegate type could not be inferred. // d = (int x, int* y) => { }; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "(int x, int* y) => { }").WithLocation(8, 13)); } [Fact] public void GenericDelegateType() { var source = @"using System; class Program { static void Main() { Delegate d = F<int>(); Console.WriteLine(d.GetDelegateTypeName()); } unsafe static Delegate F<T>() { return (T t, int* p) => { }; } }"; // When we synthesize delegate types, and infer a synthesized // delegate type, run the program to report the actual delegate type. var comp = CreateCompilation(new[] { source, s_utils }, parseOptions: TestOptions.RegularPreview, options: TestOptions.UnsafeReleaseExe); comp.VerifyDiagnostics( // (11,16): error CS8917: The delegate type could not be inferred. // return (T t, int* p) => { }; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "(T t, int* p) => { }").WithLocation(11, 16)); } /// <summary> /// Custom modifiers should not affect delegate signature. /// </summary> [Fact] public void CustomModifiers_01() { var sourceA = @".class public A { .method public static void F1(object modopt(int32) x) { ldnull throw } .method public static object modopt(int32) F2() { ldnull throw } }"; var refA = CompileIL(sourceA); var sourceB = @"using System; class B { static void Report(Delegate d) { Console.WriteLine(d.GetDelegateTypeName()); } static void Main() { Report(A.F1); Report(A.F2); } }"; var comp = CreateCompilation(new[] { sourceB, s_utils }, new[] { refA }, parseOptions: TestOptions.RegularPreview, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: @"System.Action<System.Object> System.Func<System.Object>"); } /// <summary> /// Custom modifiers should not affect delegate signature. /// </summary> [Fact] public void CustomModifiers_02() { var sourceA = @".class public A { .method public static void F1(object modreq(int32) x) { ldnull throw } .method public static object modreq(int32) F2() { ldnull throw } }"; var refA = CompileIL(sourceA); var sourceB = @"using System; class B { static void Report(Delegate d) { Console.WriteLine(d.GetDelegateTypeName()); } static void Main() { Report(A.F1); Report(A.F2); } }"; var comp = CreateCompilation(new[] { sourceB, s_utils }, new[] { refA }, parseOptions: TestOptions.RegularPreview, options: TestOptions.ReleaseExe); comp.VerifyDiagnostics( // (10,16): error CS1503: Argument 1: cannot convert from 'method group' to 'Delegate' // Report(A.F1); Diagnostic(ErrorCode.ERR_BadArgType, "A.F1").WithArguments("1", "method group", "System.Delegate").WithLocation(10, 16), // (11,16): error CS1503: Argument 1: cannot convert from 'method group' to 'Delegate' // Report(A.F2); Diagnostic(ErrorCode.ERR_BadArgType, "A.F2").WithArguments("1", "method group", "System.Delegate").WithLocation(11, 16)); } [Fact] public void UnmanagedCallersOnlyAttribute_01() { var source = @"using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; class Program { static void Main() { Delegate d = F; } [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] static void F() { } }"; var comp = CreateCompilation(new[] { source, UnmanagedCallersOnlyAttributeDefinition }, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (8,22): error CS8902: 'Program.F()' is attributed with 'UnmanagedCallersOnly' and cannot be converted to a delegate type. Obtain a function pointer to this method. // Delegate d = F; Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyMethodsCannotBeConvertedToDelegate, "F").WithArguments("Program.F()").WithLocation(8, 22)); } [Fact] public void UnmanagedCallersOnlyAttribute_02() { var source = @"using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; class Program { static void Main() { Delegate d = new S().F; } } struct S { } static class E1 { [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] public static void F(this S s) { } } static class E2 { [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvStdcall) })] public static void F(this S s) { } }"; var comp = CreateCompilation(new[] { source, UnmanagedCallersOnlyAttributeDefinition }, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (8,22): error CS0121: The call is ambiguous between the following methods or properties: 'E1.F(S)' and 'E2.F(S)' // Delegate d = new S().F; Diagnostic(ErrorCode.ERR_AmbigCall, "new S().F").WithArguments("E1.F(S)", "E2.F(S)").WithLocation(8, 22)); } [Fact] public void SystemActionAndFunc_Missing() { var sourceA = @".assembly mscorlib { .ver 0:0:0:0 } .class public System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public abstract System.ValueType extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public System.String extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Void extends System.ValueType { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Boolean extends System.ValueType { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Int32 extends System.ValueType { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public abstract System.Delegate extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } }"; var refA = CompileIL(sourceA, prependDefaultHeader: false, autoInherit: false); var sourceB = @"class Program { static void Main() { System.Delegate d; d = Main; d = () => 1; } }"; var comp = CreateEmptyCompilation(sourceB, new[] { refA }, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (6,13): error CS0518: Predefined type 'System.Action' is not defined or imported // d = Main; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "Main").WithArguments("System.Action").WithLocation(6, 13), // (6,13): error CS0518: Predefined type 'System.Action' is not defined or imported // d = Main; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "Main").WithArguments("System.Action").WithLocation(6, 13), // (6,13): error CS8917: The delegate type could not be inferred. // d = Main; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "Main").WithLocation(6, 13), // (7,13): error CS0518: Predefined type 'System.Func`1' is not defined or imported // d = () => 1; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "() => 1").WithArguments("System.Func`1").WithLocation(7, 13)); } private static MetadataReference GetCorlibWithInvalidActionAndFuncOfT() { var sourceA = @".assembly mscorlib { .ver 0:0:0:0 } .class public System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public abstract System.ValueType extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public System.String extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public System.Type extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Void extends System.ValueType { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Boolean extends System.ValueType { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Int32 extends System.ValueType { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public abstract System.Delegate extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public abstract System.Attribute extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Runtime.CompilerServices.RequiredAttributeAttribute extends System.Attribute { .method public hidebysig specialname rtspecialname instance void .ctor(class System.Type t) cil managed { ret } } .class public abstract System.MulticastDelegate extends System.Delegate { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Action`1<T> extends System.MulticastDelegate { .custom instance void System.Runtime.CompilerServices.RequiredAttributeAttribute::.ctor(class System.Type) = ( 01 00 FF 00 00 ) .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } .method public hidebysig instance void Invoke(!T t) { ret } } .class public sealed System.Func`1<T> extends System.MulticastDelegate { .custom instance void System.Runtime.CompilerServices.RequiredAttributeAttribute::.ctor(class System.Type) = ( 01 00 FF 00 00 ) .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } .method public hidebysig instance !T Invoke() { ldnull throw } }"; return CompileIL(sourceA, prependDefaultHeader: false, autoInherit: false); } [Fact] public void SystemActionAndFunc_UseSiteErrors() { var refA = GetCorlibWithInvalidActionAndFuncOfT(); var sourceB = @"class Program { static void F(object o) { } static void Main() { System.Delegate d; d = F; d = () => 1; } }"; var comp = CreateEmptyCompilation(sourceB, new[] { refA }, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (9,13): error CS0648: 'Action<T>' is a type not supported by the language // d = F; Diagnostic(ErrorCode.ERR_BogusType, "F").WithArguments("System.Action<T>").WithLocation(9, 13), // (9,13): error CS0648: 'Action<T>' is a type not supported by the language // d = F; Diagnostic(ErrorCode.ERR_BogusType, "F").WithArguments("System.Action<T>").WithLocation(9, 13), // (10,13): error CS0648: 'Func<T>' is a type not supported by the language // d = () => 1; Diagnostic(ErrorCode.ERR_BogusType, "() => 1").WithArguments("System.Func<T>").WithLocation(10, 13)); } [Fact] public void SystemLinqExpressionsExpression_Missing() { var sourceA = @".assembly mscorlib { .ver 0:0:0:0 } .class public System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public abstract System.ValueType extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public System.String extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public System.Type extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Void extends System.ValueType { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Boolean extends System.ValueType { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Int32 extends System.ValueType { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public abstract System.Delegate extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public abstract System.MulticastDelegate extends System.Delegate { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Func`1<T> extends System.MulticastDelegate { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } .method public hidebysig instance !T Invoke() { ldnull throw } } .class public abstract System.Linq.Expressions.Expression extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } }"; var refA = CompileIL(sourceA, prependDefaultHeader: false, autoInherit: false); var sourceB = @"class Program { static void Main() { System.Linq.Expressions.Expression e = () => 1; } }"; var comp = CreateEmptyCompilation(sourceB, new[] { refA }, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (5,48): error CS0518: Predefined type 'System.Linq.Expressions.Expression`1' is not defined or imported // System.Linq.Expressions.Expression e = () => 1; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "() => 1").WithArguments("System.Linq.Expressions.Expression`1").WithLocation(5, 48)); } [Fact] public void SystemLinqExpressionsExpression_UseSiteErrors() { var sourceA = @".assembly mscorlib { .ver 0:0:0:0 } .class public System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public abstract System.ValueType extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public System.String extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public System.Type extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Void extends System.ValueType { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Boolean extends System.ValueType { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Int32 extends System.ValueType { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public abstract System.Delegate extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public abstract System.Attribute extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Runtime.CompilerServices.RequiredAttributeAttribute extends System.Attribute { .method public hidebysig specialname rtspecialname instance void .ctor(class System.Type t) cil managed { ret } } .class public abstract System.MulticastDelegate extends System.Delegate { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Func`1<T> extends System.MulticastDelegate { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } .method public hidebysig instance !T Invoke() { ldnull throw } } .class public abstract System.Linq.Expressions.Expression extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public abstract System.Linq.Expressions.LambdaExpression extends System.Linq.Expressions.Expression { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Linq.Expressions.Expression`1<T> extends System.Linq.Expressions.LambdaExpression { .custom instance void System.Runtime.CompilerServices.RequiredAttributeAttribute::.ctor(class System.Type) = ( 01 00 FF 00 00 ) .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } }"; var refA = CompileIL(sourceA, prependDefaultHeader: false, autoInherit: false); var sourceB = @"class Program { static void Main() { System.Linq.Expressions.Expression e = () => 1; } }"; var comp = CreateEmptyCompilation(sourceB, new[] { refA }, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (5,48): error CS0648: 'Expression<T>' is a type not supported by the language // System.Linq.Expressions.Expression e = () => 1; Diagnostic(ErrorCode.ERR_BogusType, "() => 1").WithArguments("System.Linq.Expressions.Expression<T>").WithLocation(5, 48)); } [WorkItem(4674, "https://github.com/dotnet/csharplang/issues/4674")] [Fact] public void OverloadResolution_01() { var source = @"using System; class Program { static void M<T>(T t) { Console.WriteLine(""M<T>(T t)""); } static void M(Action<string> a) { Console.WriteLine(""M(Action<string> a)""); } static void F(object o) { } static void Main() { M(F); // C#9: M(Action<string>) } }"; var expectedOutput = @"M(Action<string> a)"; CompileAndVerify(source, parseOptions: TestOptions.Regular9, expectedOutput: expectedOutput); CompileAndVerify(source, parseOptions: TestOptions.RegularPreview, expectedOutput: expectedOutput); } [WorkItem(4674, "https://github.com/dotnet/csharplang/issues/4674")] [Fact] public void OverloadResolution_02() { var source = @"using System; class Program { static void Main() { var c = new C(); c.M(Main); // C#9: E.M(object x, Action y) c.M(() => { }); // C#9: E.M(object x, Action y) } } class C { public void M(object y) { Console.WriteLine(""C.M(object y)""); } } static class E { public static void M(this object x, Action y) { Console.WriteLine(""E.M(object x, Action y)""); } }"; var expectedOutput = @"E.M(object x, Action y) E.M(object x, Action y) "; CompileAndVerify(source, parseOptions: TestOptions.Regular9, expectedOutput: expectedOutput); CompileAndVerify(source, parseOptions: TestOptions.RegularPreview, expectedOutput: expectedOutput); } [WorkItem(4674, "https://github.com/dotnet/csharplang/issues/4674")] [Fact] public void OverloadResolution_03() { var source = @"using System; class Program { static void Main() { var c = new C(); c.M(Main); // C#9: E.M(object x, Action y) c.M(() => { }); // C#9: E.M(object x, Action y) } } class C { public void M(Delegate d) { Console.WriteLine(""C.M""); } } static class E { public static void M(this object o, Action a) { Console.WriteLine(""E.M""); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (7,13): error CS8773: Feature 'inferred delegate type' is not available in C# 9.0. Please use language version 10.0 or greater. // c.M(Main); // C#9: E.M(object x, Action y) Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "Main").WithArguments("inferred delegate type", "10.0").WithLocation(7, 13), // (8,13): error CS8773: Feature 'inferred delegate type' is not available in C# 9.0. Please use language version 10.0 or greater. // c.M(() => { }); // C#9: E.M(object x, Action y) Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "() => { }").WithArguments("inferred delegate type", "10.0").WithLocation(8, 13)); // Breaking change from C#9 which binds to E.M. CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: @"C.M C.M "); } [WorkItem(4674, "https://github.com/dotnet/csharplang/issues/4674")] [Fact] public void OverloadResolution_04() { var source = @"using System; using System.Linq.Expressions; class Program { static void Main() { var c = new C(); c.M(() => 1); } } class C { public void M(Expression e) { Console.WriteLine(""C.M""); } } static class E { public static void M(this object o, Func<int> a) { Console.WriteLine(""E.M""); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (8,13): error CS8773: Feature 'inferred delegate type' is not available in C# 9.0. Please use language version 10.0 or greater. // c.M(() => 1); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "() => 1").WithArguments("inferred delegate type", "10.0").WithLocation(8, 13)); // Breaking change from C#9 which binds to E.M. CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: @"C.M"); } [Fact] public void OverloadResolution_05() { var source = @"using System; class Program { static void Report(string name) { Console.WriteLine(name); } static void FA(Delegate d) { Report(""FA(Delegate)""); } static void FA(Action d) { Report(""FA(Action)""); } static void FB(Delegate d) { Report(""FB(Delegate)""); } static void FB(Func<int> d) { Report(""FB(Func<int>)""); } static void F1() { } static int F2() => 0; static void Main() { FA(F1); FA(F2); FB(F1); FB(F2); FA(() => { }); FA(() => 0); FB(() => { }); FB(() => 0); FA(delegate () { }); FA(delegate () { return 0; }); FB(delegate () { }); FB(delegate () { return 0; }); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (14,12): error CS8773: Feature 'inferred delegate type' is not available in C# 9.0. Please use language version 10.0 or greater. // FA(F2); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "F2").WithArguments("inferred delegate type", "10.0").WithLocation(14, 12), // (15,12): error CS8773: Feature 'inferred delegate type' is not available in C# 9.0. Please use language version 10.0 or greater. // FB(F1); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "F1").WithArguments("inferred delegate type", "10.0").WithLocation(15, 12), // (18,12): error CS8773: Feature 'inferred delegate type' is not available in C# 9.0. Please use language version 10.0 or greater. // FA(() => 0); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "() => 0").WithArguments("inferred delegate type", "10.0").WithLocation(18, 12), // (19,12): error CS8773: Feature 'inferred delegate type' is not available in C# 9.0. Please use language version 10.0 or greater. // FB(() => { }); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "() => { }").WithArguments("inferred delegate type", "10.0").WithLocation(19, 12), // (22,12): error CS8773: Feature 'inferred delegate type' is not available in C# 9.0. Please use language version 10.0 or greater. // FA(delegate () { return 0; }); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "delegate () { return 0; }").WithArguments("inferred delegate type", "10.0").WithLocation(22, 12), // (23,12): error CS8773: Feature 'inferred delegate type' is not available in C# 9.0. Please use language version 10.0 or greater. // FB(delegate () { }); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "delegate () { }").WithArguments("inferred delegate type", "10.0").WithLocation(23, 12)); CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: @"FA(Action) FA(Delegate) FB(Delegate) FB(Func<int>) FA(Action) FA(Delegate) FB(Delegate) FB(Func<int>) FA(Action) FA(Delegate) FB(Delegate) FB(Func<int>) "); } [Fact] public void OverloadResolution_06() { var source = @"using System; using System.Linq.Expressions; class Program { static void Report(string name, Expression e) { Console.WriteLine(""{0}: {1}"", name, e); } static void F(Expression e) { Report(""F(Expression)"", e); } static void F(Expression<Func<int>> e) { Report(""F(Expression<Func<int>>)"", e); } static void Main() { F(() => 0); F(() => string.Empty); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (11,11): error CS8773: Feature 'inferred delegate type' is not available in C# 9.0. Please use language version 10.0 or greater. // F(() => string.Empty); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "() => string.Empty").WithArguments("inferred delegate type", "10.0").WithLocation(11, 11)); CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: @"F(Expression<Func<int>>): () => 0 F(Expression): () => String.Empty "); } [Fact] public void OverloadResolution_07() { var source = @"using System; using System.Linq.Expressions; class Program { static void F(Expression e) { } static void F(Expression<Func<int>> e) { } static void Main() { F(delegate () { return 0; }); F(delegate () { return string.Empty; }); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (9,11): error CS1946: An anonymous method expression cannot be converted to an expression tree // F(delegate () { return 0; }); Diagnostic(ErrorCode.ERR_AnonymousMethodToExpressionTree, "delegate () { return 0; }").WithLocation(9, 11), // (10,11): error CS1946: An anonymous method expression cannot be converted to an expression tree // F(delegate () { return string.Empty; }); Diagnostic(ErrorCode.ERR_AnonymousMethodToExpressionTree, "delegate () { return string.Empty; }").WithLocation(10, 11)); } [Fact] public void ImplicitlyTypedVariables_01() { var source = @"using System; class Program { static void Main() { var d1 = Main; Report(d1); var d2 = () => { }; Report(d2); var d3 = delegate () { }; Report(d3); } static void Report(Delegate d) => Console.WriteLine(d.GetDelegateTypeName()); }"; var comp = CreateCompilation(new[] { source, s_utils }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe); comp.VerifyDiagnostics( // (6,18): error CS8773: Feature 'inferred delegate type' is not available in C# 9.0. Please use language version 10.0 or greater. // var d1 = Main; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "Main").WithArguments("inferred delegate type", "10.0").WithLocation(6, 18), // (8,18): error CS8773: Feature 'inferred delegate type' is not available in C# 9.0. Please use language version 10.0 or greater. // var d2 = () => { }; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "() => { }").WithArguments("inferred delegate type", "10.0").WithLocation(8, 18), // (10,18): error CS8773: Feature 'inferred delegate type' is not available in C# 9.0. Please use language version 10.0 or greater. // var d3 = delegate () { }; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "delegate () { }").WithArguments("inferred delegate type", "10.0").WithLocation(10, 18)); comp = CreateCompilation(new[] { source, s_utils }, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: @"System.Action System.Action System.Action"); verifier.VerifyIL("Program.Main", @"{ // Code size 100 (0x64) .maxstack 2 .locals init (System.Action V_0, //d1 System.Action V_1, //d2 System.Action V_2) //d3 IL_0000: nop IL_0001: ldnull IL_0002: ldftn ""void Program.Main()"" IL_0008: newobj ""System.Action..ctor(object, System.IntPtr)"" IL_000d: stloc.0 IL_000e: ldloc.0 IL_000f: call ""void Program.Report(System.Delegate)"" IL_0014: nop IL_0015: ldsfld ""System.Action Program.<>c.<>9__0_0"" IL_001a: dup IL_001b: brtrue.s IL_0034 IL_001d: pop IL_001e: ldsfld ""Program.<>c Program.<>c.<>9"" IL_0023: ldftn ""void Program.<>c.<Main>b__0_0()"" IL_0029: newobj ""System.Action..ctor(object, System.IntPtr)"" IL_002e: dup IL_002f: stsfld ""System.Action Program.<>c.<>9__0_0"" IL_0034: stloc.1 IL_0035: ldloc.1 IL_0036: call ""void Program.Report(System.Delegate)"" IL_003b: nop IL_003c: ldsfld ""System.Action Program.<>c.<>9__0_1"" IL_0041: dup IL_0042: brtrue.s IL_005b IL_0044: pop IL_0045: ldsfld ""Program.<>c Program.<>c.<>9"" IL_004a: ldftn ""void Program.<>c.<Main>b__0_1()"" IL_0050: newobj ""System.Action..ctor(object, System.IntPtr)"" IL_0055: dup IL_0056: stsfld ""System.Action Program.<>c.<>9__0_1"" IL_005b: stloc.2 IL_005c: ldloc.2 IL_005d: call ""void Program.Report(System.Delegate)"" IL_0062: nop IL_0063: ret }"); } [Fact] public void ImplicitlyTypedVariables_02() { var source = @"var d1 = object.ReferenceEquals; var d2 = () => { }; var d3 = delegate () { }; "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9.WithKind(SourceCodeKind.Script)); comp.VerifyDiagnostics( // (1,10): error CS8773: Feature 'inferred delegate type' is not available in C# 9.0. Please use language version 10.0 or greater. // var d1 = object.ReferenceEquals; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "object.ReferenceEquals").WithArguments("inferred delegate type", "10.0").WithLocation(1, 10), // (2,10): error CS8773: Feature 'inferred delegate type' is not available in C# 9.0. Please use language version 10.0 or greater. // var d2 = () => { }; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "() => { }").WithArguments("inferred delegate type", "10.0").WithLocation(2, 10), // (3,10): error CS8773: Feature 'inferred delegate type' is not available in C# 9.0. Please use language version 10.0 or greater. // var d3 = delegate () { }; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "delegate () { }").WithArguments("inferred delegate type", "10.0").WithLocation(3, 10)); comp = CreateCompilation(source, parseOptions: TestOptions.Regular10.WithKind(SourceCodeKind.Script)); comp.VerifyDiagnostics(); } [Fact] public void ImplicitlyTypedVariables_03() { var source = @"class Program { static void Main() { ref var d1 = Main; ref var d2 = () => { }; ref var d3 = delegate () { }; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (5,17): error CS8172: Cannot initialize a by-reference variable with a value // ref var d1 = Main; Diagnostic(ErrorCode.ERR_InitializeByReferenceVariableWithValue, "d1 = Main").WithLocation(5, 17), // (5,22): error CS1657: Cannot use 'Main' as a ref or out value because it is a 'method group' // ref var d1 = Main; Diagnostic(ErrorCode.ERR_RefReadonlyLocalCause, "Main").WithArguments("Main", "method group").WithLocation(5, 22), // (6,17): error CS8172: Cannot initialize a by-reference variable with a value // ref var d2 = () => { }; Diagnostic(ErrorCode.ERR_InitializeByReferenceVariableWithValue, "d2 = () => { }").WithLocation(6, 17), // (6,22): error CS1510: A ref or out value must be an assignable variable // ref var d2 = () => { }; Diagnostic(ErrorCode.ERR_RefLvalueExpected, "() => { }").WithLocation(6, 22), // (7,17): error CS8172: Cannot initialize a by-reference variable with a value // ref var d3 = delegate () { }; Diagnostic(ErrorCode.ERR_InitializeByReferenceVariableWithValue, "d3 = delegate () { }").WithLocation(7, 17), // (7,22): error CS1510: A ref or out value must be an assignable variable // ref var d3 = delegate () { }; Diagnostic(ErrorCode.ERR_RefLvalueExpected, "delegate () { }").WithLocation(7, 22)); } [Fact] public void ImplicitlyTypedVariables_04() { var source = @"class Program { static void Main() { using var d1 = Main; using var d2 = () => { }; using var d3 = delegate () { }; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (5,9): error CS1674: 'Action': type used in a using statement must be implicitly convertible to 'System.IDisposable'. // using var d1 = Main; Diagnostic(ErrorCode.ERR_NoConvToIDisp, "using var d1 = Main;").WithArguments("System.Action").WithLocation(5, 9), // (6,9): error CS1674: 'Action': type used in a using statement must be implicitly convertible to 'System.IDisposable'. // using var d2 = () => { }; Diagnostic(ErrorCode.ERR_NoConvToIDisp, "using var d2 = () => { };").WithArguments("System.Action").WithLocation(6, 9), // (7,9): error CS1674: 'Action': type used in a using statement must be implicitly convertible to 'System.IDisposable'. // using var d3 = delegate () { }; Diagnostic(ErrorCode.ERR_NoConvToIDisp, "using var d3 = delegate () { };").WithArguments("System.Action").WithLocation(7, 9)); } [Fact] public void ImplicitlyTypedVariables_05() { var source = @"class Program { static void Main() { foreach (var d1 in Main) { } foreach (var d2 in () => { }) { } foreach (var d3 in delegate () { }) { } } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (5,28): error CS0446: Foreach cannot operate on a 'method group'. Did you intend to invoke the 'method group'? // foreach (var d1 in Main) { } Diagnostic(ErrorCode.ERR_AnonMethGrpInForEach, "Main").WithArguments("method group").WithLocation(5, 28), // (6,28): error CS0446: Foreach cannot operate on a 'lambda expression'. Did you intend to invoke the 'lambda expression'? // foreach (var d2 in () => { }) { } Diagnostic(ErrorCode.ERR_AnonMethGrpInForEach, "() => { }").WithArguments("lambda expression").WithLocation(6, 28), // (7,28): error CS0446: Foreach cannot operate on a 'anonymous method'. Did you intend to invoke the 'anonymous method'? // foreach (var d3 in delegate () { }) { } Diagnostic(ErrorCode.ERR_AnonMethGrpInForEach, "delegate () { }").WithArguments("anonymous method").WithLocation(7, 28)); } [Fact] public void ImplicitlyTypedVariables_06() { var source = @"using System; class Program { static void Main() { Func<int> f; var d1 = Main; f = d1; var d2 = object (int x) => x; f = d2; var d3 = delegate () { return string.Empty; }; f = d3; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (8,13): error CS0029: Cannot implicitly convert type 'System.Action' to 'System.Func<int>' // f = d1; Diagnostic(ErrorCode.ERR_NoImplicitConv, "d1").WithArguments("System.Action", "System.Func<int>").WithLocation(8, 13), // (10,13): error CS0029: Cannot implicitly convert type 'System.Func<int, object>' to 'System.Func<int>' // f = d2; Diagnostic(ErrorCode.ERR_NoImplicitConv, "d2").WithArguments("System.Func<int, object>", "System.Func<int>").WithLocation(10, 13), // (12,13): error CS0029: Cannot implicitly convert type 'System.Func<string>' to 'System.Func<int>' // f = d3; Diagnostic(ErrorCode.ERR_NoImplicitConv, "d3").WithArguments("System.Func<string>", "System.Func<int>").WithLocation(12, 13)); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var variables = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Where(v => v.Initializer != null); var expectedInfo = new (string?, string?, string?)[] { ("System.Action d1", null, "System.Action"), ("System.Func<System.Int32, System.Object> d2", null, "System.Func<System.Int32, System.Object>"), ("System.Func<System.String> d3", null, "System.Func<System.String>"), }; AssertEx.Equal(expectedInfo, variables.Select(v => getVariableInfo(model, v))); static (string?, string?, string?) getVariableInfo(SemanticModel model, VariableDeclaratorSyntax variable) { var symbol = model.GetDeclaredSymbol(variable); var typeInfo = model.GetTypeInfo(variable.Initializer!.Value); return (symbol?.ToTestDisplayString(), typeInfo.Type?.ToTestDisplayString(), typeInfo.ConvertedType?.ToTestDisplayString()); } } [Fact] public void ImplicitlyTypedVariables_07() { var source = @"class Program { static void Main() { var t = (Main, () => { }); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (5,13): error CS0815: Cannot assign (method group, lambda expression) to an implicitly-typed variable // var t = (Main, () => { }); Diagnostic(ErrorCode.ERR_ImplicitlyTypedVariableAssignedBadValue, "t = (Main, () => { })").WithArguments("(method group, lambda expression)").WithLocation(5, 13)); } [Fact] public void ImplicitlyTypedVariables_08() { var source = @"class Program { static void Main() { (var x1, var y1) = Main; var (x2, y2) = () => { }; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (5,14): error CS8130: Cannot infer the type of implicitly-typed deconstruction variable 'x1'. // (var x1, var y1) = Main; Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, "x1").WithArguments("x1").WithLocation(5, 14), // (5,22): error CS8130: Cannot infer the type of implicitly-typed deconstruction variable 'y1'. // (var x1, var y1) = Main; Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, "y1").WithArguments("y1").WithLocation(5, 22), // (5,28): error CS8131: Deconstruct assignment requires an expression with a type on the right-hand-side. // (var x1, var y1) = Main; Diagnostic(ErrorCode.ERR_DeconstructRequiresExpression, "Main").WithLocation(5, 28), // (6,14): error CS8130: Cannot infer the type of implicitly-typed deconstruction variable 'x2'. // var (x2, y2) = () => { }; Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, "x2").WithArguments("x2").WithLocation(6, 14), // (6,18): error CS8130: Cannot infer the type of implicitly-typed deconstruction variable 'y2'. // var (x2, y2) = () => { }; Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, "y2").WithArguments("y2").WithLocation(6, 18), // (6,24): error CS8131: Deconstruct assignment requires an expression with a type on the right-hand-side. // var (x2, y2) = () => { }; Diagnostic(ErrorCode.ERR_DeconstructRequiresExpression, "() => { }").WithLocation(6, 24)); } [Fact] public void ImplicitlyTypedVariables_09() { var source = @"class Program { static void Main() { var (x, y) = (Main, () => { }); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (5,14): error CS8130: Cannot infer the type of implicitly-typed deconstruction variable 'x'. // var (x, y) = (Main, () => { }); 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) = (Main, () => { }); Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, "y").WithArguments("y").WithLocation(5, 17)); } [Fact] public void ImplicitlyTypedVariables_10() { var source = @"using System; class Program { static void Main() { (var x1, Action y1) = (Main, null); (Action x2, var y2) = (null, () => { }); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,14): error CS8130: Cannot infer the type of implicitly-typed deconstruction variable 'x1'. // (var x1, Action y1) = (Main, null); Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, "x1").WithArguments("x1").WithLocation(6, 14), // (7,25): error CS8130: Cannot infer the type of implicitly-typed deconstruction variable 'y2'. // (Action x2, var y2) = (null, () => { }); Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, "y2").WithArguments("y2").WithLocation(7, 25)); } [Fact] public void ImplicitlyTypedVariables_11() { var source = @"class Program { static void F(object o) { } static void F(int i) { } static void Main() { var d1 = F; var d2 = x => x; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (7,18): error CS8917: The delegate type could not be inferred. // var d1 = F; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "F").WithLocation(7, 18), // (8,18): error CS8917: The delegate type could not be inferred. // var d2 = x => x; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "x => x").WithLocation(8, 18)); } [Fact] public void ImplicitlyTypedVariables_12() { var source = @"class Program { static void F(ref int i) { } static void Main() { var d1 = F; var d2 = (ref int x) => x; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,18): error CS8917: The delegate type could not be inferred. // var d1 = F; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "F").WithLocation(6, 18), // (7,18): error CS8917: The delegate type could not be inferred. // var d2 = (ref int x) => x; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "(ref int x) => x").WithLocation(7, 18)); } [Fact] public void ImplicitlyTypedVariables_13() { var source = @"using System; class Program { static int F() => 0; static void Main() { var d1 = (F); Report(d1); var d2 = (object (int x) => x); Report(d2); var d3 = (delegate () { return string.Empty; }); Report(d3); } static void Report(Delegate d) => Console.WriteLine(d.GetDelegateTypeName()); }"; CompileAndVerify(new[] { source, s_utils }, options: TestOptions.DebugExe, expectedOutput: @"System.Func<System.Int32> System.Func<System.Int32, System.Object> System.Func<System.String>"); } [Fact] public void ImplicitlyTypedVariables_UseSiteErrors() { var source = @"class Program { static void F(object o) { } static void Main() { var d1 = F; var d2 = () => 1; } }"; var comp = CreateEmptyCompilation(source, new[] { GetCorlibWithInvalidActionAndFuncOfT() }); comp.VerifyDiagnostics( // (6,18): error CS0648: 'Action<T>' is a type not supported by the language // var d1 = F; Diagnostic(ErrorCode.ERR_BogusType, "F").WithArguments("System.Action<T>").WithLocation(6, 18), // (7,18): error CS0648: 'Func<T>' is a type not supported by the language // var d2 = () => 1; Diagnostic(ErrorCode.ERR_BogusType, "() => 1").WithArguments("System.Func<T>").WithLocation(7, 18)); } /// <summary> /// Ensure the conversion group containing the implicit /// conversion is handled correctly in NullableWalker. /// </summary> [Fact] public void NullableAnalysis_01() { var source = @"#nullable enable class Program { static void Main() { System.Delegate d; d = Main; d = () => { }; d = delegate () { }; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics(); } /// <summary> /// Ensure the conversion group containing the explicit /// conversion is handled correctly in NullableWalker. /// </summary> [Fact] public void NullableAnalysis_02() { var source = @"#nullable enable class Program { static void Main() { object o; o = (System.Delegate)Main; o = (System.Delegate)(() => { }); o = (System.Delegate)(delegate () { }); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics(); } [Fact] public void TaskRunArgument() { var source = @"using System.Threading.Tasks; class Program { static async Task F() { await Task.Run(() => { }); } }"; var verifier = CompileAndVerify(source, parseOptions: TestOptions.RegularPreview); var method = (MethodSymbol)verifier.TestData.GetMethodsByName()["Program.<>c.<F>b__0_0()"].Method; Assert.Equal("void Program.<>c.<F>b__0_0()", method.ToTestDisplayString()); verifier.VerifyIL("Program.<>c.<F>b__0_0()", @"{ // Code size 1 (0x1) .maxstack 0 IL_0000: ret }"); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class DelegateTypeTests : CSharpTestBase { private const string s_utils = @"using System; using System.Linq; static class Utils { internal static string GetDelegateMethodName(this Delegate d) { var method = d.Method; return Concat(GetTypeName(method.DeclaringType), method.Name); } internal static string GetDelegateTypeName(this Delegate d) { return d.GetType().GetTypeName(); } internal static string GetTypeName(this Type type) { if (type.IsArray) { return GetTypeName(type.GetElementType()) + ""[]""; } string typeName = type.Name; int index = typeName.LastIndexOf('`'); if (index >= 0) { typeName = typeName.Substring(0, index); } typeName = Concat(type.Namespace, typeName); if (!type.IsGenericType) { return typeName; } return $""{typeName}<{string.Join("", "", type.GetGenericArguments().Select(GetTypeName))}>""; } private static string Concat(string container, string name) { return string.IsNullOrEmpty(container) ? name : container + ""."" + name; } }"; [Fact] public void LanguageVersion() { var source = @"class Program { static void Main() { System.Delegate d; d = Main; d = () => { }; d = delegate () { }; System.Linq.Expressions.Expression e = () => 1; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (6,13): error CS0428: Cannot convert method group 'Main' to non-delegate type 'Delegate'. Did you intend to invoke the method? // d = Main; Diagnostic(ErrorCode.ERR_MethGrpToNonDel, "Main").WithArguments("Main", "System.Delegate").WithLocation(6, 13), // (7,13): error CS1660: Cannot convert lambda expression to type 'Delegate' because it is not a delegate type // d = () => { }; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => { }").WithArguments("lambda expression", "System.Delegate").WithLocation(7, 13), // (8,13): error CS1660: Cannot convert anonymous method to type 'Delegate' because it is not a delegate type // d = delegate () { }; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "delegate () { }").WithArguments("anonymous method", "System.Delegate").WithLocation(8, 13), // (9,48): error CS1660: Cannot convert lambda expression to type 'Expression' because it is not a delegate type // System.Linq.Expressions.Expression e = () => 1; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => 1").WithArguments("lambda expression", "System.Linq.Expressions.Expression").WithLocation(9, 48)); comp = CreateCompilation(source, parseOptions: TestOptions.Regular10); comp.VerifyDiagnostics(); } [Fact] public void MethodGroupConversions() { var source = @"class Program { static void Main() { object o = Main; System.ICloneable c = Main; System.Delegate d = Main; System.MulticastDelegate m = Main; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (5,20): error CS0428: Cannot convert method group 'Main' to non-delegate type 'object'. Did you intend to invoke the method? // object o = Main; Diagnostic(ErrorCode.ERR_MethGrpToNonDel, "Main").WithArguments("Main", "object").WithLocation(5, 20), // (6,31): error CS0428: Cannot convert method group 'Main' to non-delegate type 'ICloneable'. Did you intend to invoke the method? // System.ICloneable c = Main; Diagnostic(ErrorCode.ERR_MethGrpToNonDel, "Main").WithArguments("Main", "System.ICloneable").WithLocation(6, 31), // (8,38): error CS0428: Cannot convert method group 'Main' to non-delegate type 'MulticastDelegate'. Did you intend to invoke the method? // System.MulticastDelegate m = Main; Diagnostic(ErrorCode.ERR_MethGrpToNonDel, "Main").WithArguments("Main", "System.MulticastDelegate").WithLocation(8, 38)); } [Fact] public void LambdaConversions() { var source = @"class Program { static void Main() { object o = () => { }; System.ICloneable c = () => { }; System.Delegate d = () => { }; System.MulticastDelegate m = () => { }; d = x => x; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (5,20): error CS1660: Cannot convert lambda expression to type 'object' because it is not a delegate type // object o = () => { }; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => { }").WithArguments("lambda expression", "object").WithLocation(5, 20), // (6,31): error CS1660: Cannot convert lambda expression to type 'ICloneable' because it is not a delegate type // System.ICloneable c = () => { }; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => { }").WithArguments("lambda expression", "System.ICloneable").WithLocation(6, 31), // (8,38): error CS1660: Cannot convert lambda expression to type 'MulticastDelegate' because it is not a delegate type // System.MulticastDelegate m = () => { }; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => { }").WithArguments("lambda expression", "System.MulticastDelegate").WithLocation(8, 38), // (9,13): error CS8917: The delegate type could not be inferred. // d = x => x; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "x => x").WithLocation(9, 13)); } private static IEnumerable<object?[]> GetMethodGroupData(Func<string, string, DiagnosticDescription[]> getExpectedDiagnostics) { yield return getData("static int F() => 0;", "Program.F", "F", "System.Func<System.Int32>"); yield return getData("static int F() => 0;", "F", "F", "System.Func<System.Int32>"); yield return getData("int F() => 0;", "(new Program()).F", "F", "System.Func<System.Int32>"); yield return getData("static T F<T>() => default;", "Program.F<int>", "F", "System.Func<System.Int32>"); yield return getData("static void F<T>() where T : class { }", "F<object>", "F", "System.Action"); yield return getData("static void F<T>() where T : struct { }", "F<int>", "F", "System.Action"); yield return getData("T F<T>() => default;", "(new Program()).F<int>", "F", "System.Func<System.Int32>"); yield return getData("T F<T>() => default;", "(new Program()).F", "F", null); yield return getData("void F<T>(T t) { }", "(new Program()).F<string>", "F", "System.Action<System.String>"); yield return getData("void F<T>(T t) { }", "(new Program()).F", "F", null); yield return getData("static ref int F() => throw null;", "F", "F", null); yield return getData("static ref readonly int F() => throw null;", "F", "F", null); yield return getData("static void F() { }", "F", "F", "System.Action"); yield return getData("static void F(int x, int y) { }", "F", "F", "System.Action<System.Int32, System.Int32>"); yield return getData("static void F(out int x, int y) { x = 0; }", "F", "F", null); yield return getData("static void F(int x, ref int y) { }", "F", "F", null); yield return getData("static void F(int x, in int y) { }", "F", "F", null); yield return getData("static void F(int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16) { }", "F", "F", "System.Action<System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object>"); yield return getData("static void F(int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16, int _17) { }", "F", "F", null); yield return getData("static object F(int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16) => null;", "F", "F", "System.Func<System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Object>"); yield return getData("static object F(int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16, int _17) => null;", "F", "F", null); object?[] getData(string methodDeclaration, string methodGroupExpression, string methodGroupOnly, string? expectedType) => new object?[] { methodDeclaration, methodGroupExpression, expectedType is null ? getExpectedDiagnostics(methodGroupExpression, methodGroupOnly) : null, expectedType }; } public static IEnumerable<object?[]> GetMethodGroupImplicitConversionData() { return GetMethodGroupData((methodGroupExpression, methodGroupOnly) => { int offset = methodGroupExpression.Length - methodGroupOnly.Length; return new[] { // (6,29): error CS8917: The delegate type could not be inferred. // System.Delegate d = F; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, methodGroupOnly).WithLocation(6, 29 + offset) }; }); } [Theory] [MemberData(nameof(GetMethodGroupImplicitConversionData))] public void MethodGroup_ImplicitConversion(string methodDeclaration, string methodGroupExpression, DiagnosticDescription[]? expectedDiagnostics, string? expectedType) { var source = $@"class Program {{ {methodDeclaration} static void Main() {{ System.Delegate d = {methodGroupExpression}; System.Console.Write(d.GetDelegateTypeName()); }} }}"; var comp = CreateCompilation(new[] { source, s_utils }, parseOptions: TestOptions.RegularPreview, options: TestOptions.ReleaseExe); if (expectedDiagnostics is null) { CompileAndVerify(comp, expectedOutput: expectedType); } else { comp.VerifyDiagnostics(expectedDiagnostics); } var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var expr = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Single().Initializer!.Value; var typeInfo = model.GetTypeInfo(expr); Assert.Null(typeInfo.Type); Assert.Equal(SpecialType.System_Delegate, typeInfo.ConvertedType!.SpecialType); } public static IEnumerable<object?[]> GetMethodGroupExplicitConversionData() { return GetMethodGroupData((methodGroupExpression, methodGroupOnly) => { int offset = methodGroupExpression.Length - methodGroupOnly.Length; return new[] { // (6,20): error CS0030: Cannot convert type 'method' to 'Delegate' // object o = (System.Delegate)F; Diagnostic(ErrorCode.ERR_NoExplicitConv, $"(System.Delegate){methodGroupExpression}").WithArguments("method", "System.Delegate").WithLocation(6, 20) }; }); } [Theory] [MemberData(nameof(GetMethodGroupExplicitConversionData))] public void MethodGroup_ExplicitConversion(string methodDeclaration, string methodGroupExpression, DiagnosticDescription[]? expectedDiagnostics, string? expectedType) { var source = $@"class Program {{ {methodDeclaration} static void Main() {{ object o = (System.Delegate){methodGroupExpression}; System.Console.Write(o.GetType().GetTypeName()); }} }}"; var comp = CreateCompilation(new[] { source, s_utils }, parseOptions: TestOptions.RegularPreview, options: TestOptions.ReleaseExe); if (expectedDiagnostics is null) { CompileAndVerify(comp, expectedOutput: expectedType); } else { comp.VerifyDiagnostics(expectedDiagnostics); } var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var expr = ((CastExpressionSyntax)tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Single().Initializer!.Value).Expression; var typeInfo = model.GetTypeInfo(expr); // https://github.com/dotnet/roslyn/issues/52874: GetTypeInfo() for method group should return inferred delegate type. Assert.Null(typeInfo.Type); Assert.Null(typeInfo.ConvertedType); } public static IEnumerable<object?[]> GetLambdaData() { yield return getData("x => x", null); yield return getData("x => { return x; }", null); yield return getData("x => ref args[0]", null); yield return getData("(x, y) => { }", null); yield return getData("() => 1", "System.Func<System.Int32>"); yield return getData("() => ref args[0]", null); yield return getData("() => { }", "System.Action"); yield return getData("(int x, int y) => { }", "System.Action<System.Int32, System.Int32>"); yield return getData("(out int x, int y) => { x = 0; }", null); yield return getData("(int x, ref int y) => { x = 0; }", null); yield return getData("(int x, in int y) => { x = 0; }", null); yield return getData("(int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16) => { }", "System.Action<System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object>"); yield return getData("(int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16, int _17) => { }", null); yield return getData("(int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16) => _1", "System.Func<System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32>"); yield return getData("(int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16, int _17) => _1", null); yield return getData("static () => 1", "System.Func<System.Int32>"); yield return getData("async () => { await System.Threading.Tasks.Task.Delay(0); }", "System.Func<System.Threading.Tasks.Task>"); yield return getData("static async () => { await System.Threading.Tasks.Task.Delay(0); return 0; }", "System.Func<System.Threading.Tasks.Task<System.Int32>>"); yield return getData("() => Main", null); yield return getData("(int x) => x switch { _ => null }", null); yield return getData("_ => { }", null); yield return getData("_ => _", null); yield return getData("() => throw null", null); yield return getData("x => throw null", null); yield return getData("(int x) => throw null", null); yield return getData("() => { throw null; }", "System.Action"); yield return getData("(int x) => { throw null; }", "System.Action<System.Int32>"); yield return getData("(string s) => { if (s.Length > 0) return s; return null; }", "System.Func<System.String, System.String>"); yield return getData("(string s) => { if (s.Length > 0) return default; return s; }", "System.Func<System.String, System.String>"); yield return getData("(int i) => { if (i > 0) return i; return default; }", "System.Func<System.Int32, System.Int32>"); yield return getData("(int x, short y) => { if (x > 0) return x; return y; }", "System.Func<System.Int32, System.Int16, System.Int32>"); yield return getData("(int x, short y) => { if (x > 0) return y; return x; }", "System.Func<System.Int32, System.Int16, System.Int32>"); yield return getData("object () => default", "System.Func<System.Object>"); yield return getData("void () => { }", "System.Action"); static object?[] getData(string expr, string? expectedType) => new object?[] { expr, expectedType }; } public static IEnumerable<object?[]> GetAnonymousMethodData() { yield return getData("delegate { }", null); yield return getData("delegate () { return 1; }", "System.Func<System.Int32>"); yield return getData("delegate () { return ref args[0]; }", null); yield return getData("delegate () { }", "System.Action"); yield return getData("delegate (int x, int y) { }", "System.Action<System.Int32, System.Int32>"); yield return getData("delegate (out int x, int y) { x = 0; }", null); yield return getData("delegate (int x, ref int y) { x = 0; }", null); yield return getData("delegate (int x, in int y) { x = 0; }", null); yield return getData("delegate (int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16) { }", "System.Action<System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object>"); yield return getData("delegate (int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16, int _17) { }", null); yield return getData("delegate (int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16) { return _1; }", "System.Func<System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32>"); yield return getData("delegate (int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16, int _17) { return _1; }", null); static object?[] getData(string expr, string? expectedType) => new object?[] { expr, expectedType }; } [Theory] [MemberData(nameof(GetLambdaData))] [MemberData(nameof(GetAnonymousMethodData))] public void AnonymousFunction_ImplicitConversion(string anonymousFunction, string? expectedType) { var source = $@"class Program {{ static void Main(string[] args) {{ System.Delegate d = {anonymousFunction}; System.Console.Write(d.GetDelegateTypeName()); }} }}"; var comp = CreateCompilation(new[] { source, s_utils }, parseOptions: TestOptions.RegularPreview, options: TestOptions.ReleaseExe); if (expectedType is null) { comp.VerifyDiagnostics( // (5,29): error CS8917: The delegate type could not be inferred. // System.Delegate d = x => x; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, anonymousFunction).WithLocation(5, 29)); } else { CompileAndVerify(comp, expectedOutput: expectedType); } var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var expr = tree.GetRoot().DescendantNodes().OfType<AnonymousFunctionExpressionSyntax>().Single(); var typeInfo = model.GetTypeInfo(expr); if (expectedType == null) { Assert.Null(typeInfo.Type); } else { Assert.Equal(expectedType, typeInfo.Type.ToTestDisplayString()); } Assert.Equal(SpecialType.System_Delegate, typeInfo.ConvertedType!.SpecialType); } [Theory] [MemberData(nameof(GetLambdaData))] [MemberData(nameof(GetAnonymousMethodData))] public void AnonymousFunction_ExplicitConversion(string anonymousFunction, string? expectedType) { var source = $@"class Program {{ static void Main(string[] args) {{ object o = (System.Delegate)({anonymousFunction}); System.Console.Write(o.GetType().GetTypeName()); }} }}"; var comp = CreateCompilation(new[] { source, s_utils }, parseOptions: TestOptions.RegularPreview, options: TestOptions.ReleaseExe); if (expectedType is null) { comp.VerifyDiagnostics( // (5,20): error CS8917: The delegate type could not be inferred. // object o = (System.Delegate)(x => x); Diagnostic(ErrorCode.ERR_CannotInferDelegateType, $"(System.Delegate)({anonymousFunction})").WithLocation(5, 20)); } else { CompileAndVerify(comp, expectedOutput: expectedType); } var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var expr = ((CastExpressionSyntax)tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Single().Initializer!.Value).Expression; var typeInfo = model.GetTypeInfo(expr); Assert.Null(typeInfo.Type); Assert.Equal(expectedType, typeInfo.ConvertedType?.ToTestDisplayString()); } public static IEnumerable<object?[]> GetExpressionData() { yield return getData("x => x", null); yield return getData("() => 1", "System.Func<System.Int32>"); yield return getData("(int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16) => _1", "System.Func<System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32, System.Object, System.Int32>"); yield return getData("(int _1, object _2, int _3, object _4, int _5, object _6, int _7, object _8, int _9, object _10, int _11, object _12, int _13, object _14, int _15, object _16, int _17) => _1", null); yield return getData("static () => 1", "System.Func<System.Int32>"); static object?[] getData(string expr, string? expectedType) => new object?[] { expr, expectedType }; } [Theory] [MemberData(nameof(GetExpressionData))] public void Expression_ImplicitConversion(string anonymousFunction, string? expectedType) { var source = $@"class Program {{ static void Main(string[] args) {{ System.Linq.Expressions.Expression e = {anonymousFunction}; }} }}"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); if (expectedType is null) { comp.VerifyDiagnostics( // (5,48): error CS8917: The delegate type could not be inferred. // System.Linq.Expressions.Expression e = x => x; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, anonymousFunction).WithLocation(5, 48)); } else { comp.VerifyDiagnostics(); } var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var expr = tree.GetRoot().DescendantNodes().OfType<AnonymousFunctionExpressionSyntax>().Single(); var typeInfo = model.GetTypeInfo(expr); if (expectedType == null) { Assert.Null(typeInfo.Type); } else { Assert.Equal($"System.Linq.Expressions.Expression<{expectedType}>", typeInfo.Type.ToTestDisplayString()); } Assert.Equal("System.Linq.Expressions.Expression", typeInfo.ConvertedType!.ToTestDisplayString()); } [Theory] [MemberData(nameof(GetExpressionData))] public void Expression_ExplicitConversion(string anonymousFunction, string? expectedType) { var source = $@"class Program {{ static void Main(string[] args) {{ object o = (System.Linq.Expressions.Expression)({anonymousFunction}); }} }}"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); if (expectedType is null) { comp.VerifyDiagnostics( // (5,20): error CS8917: The delegate type could not be inferred. // object o = (System.Linq.Expressions.Expression)(x => x); Diagnostic(ErrorCode.ERR_CannotInferDelegateType, $"(System.Linq.Expressions.Expression)({anonymousFunction})").WithLocation(5, 20)); } else { comp.VerifyDiagnostics(); } var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var expr = ((CastExpressionSyntax)tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Single().Initializer!.Value).Expression; var typeInfo = model.GetTypeInfo(expr); Assert.Null(typeInfo.Type); if (expectedType is null) { Assert.Null(typeInfo.ConvertedType); } else { Assert.Equal($"System.Linq.Expressions.Expression<{expectedType}>", typeInfo.ConvertedType.ToTestDisplayString()); } } /// <summary> /// Should bind and report diagnostics from anonymous method body /// regardless of whether the delegate type can be inferred. /// </summary> [Fact] public void AnonymousMethodBodyErrors() { var source = @"using System; class Program { static void Main() { Delegate d0 = x0 => { _ = x0.Length; object y0 = 0; _ = y0.Length; }; Delegate d1 = (object x1) => { _ = x1.Length; }; Delegate d2 = (ref object x2) => { _ = x2.Length; }; Delegate d3 = delegate (object x3) { _ = x3.Length; }; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (6,23): error CS8917: The delegate type could not be inferred. // Delegate d0 = x0 => { _ = x0.Length; object y0 = 0; _ = y0.Length; }; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "x0 => { _ = x0.Length; object y0 = 0; _ = y0.Length; }").WithLocation(6, 23), // (6,68): error CS1061: 'object' does not contain a definition for 'Length' and no accessible extension method 'Length' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?) // Delegate d0 = x0 => { _ = x0.Length; object y0 = 0; _ = y0.Length; }; Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "Length").WithArguments("object", "Length").WithLocation(6, 68), // (7,47): error CS1061: 'object' does not contain a definition for 'Length' and no accessible extension method 'Length' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?) // Delegate d1 = (object x1) => { _ = x1.Length; }; Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "Length").WithArguments("object", "Length").WithLocation(7, 47), // (8,23): error CS8917: The delegate type could not be inferred. // Delegate d2 = (ref object x2) => { _ = x2.Length; }; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "(ref object x2) => { _ = x2.Length; }").WithLocation(8, 23), // (8,51): error CS1061: 'object' does not contain a definition for 'Length' and no accessible extension method 'Length' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?) // Delegate d2 = (ref object x2) => { _ = x2.Length; }; Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "Length").WithArguments("object", "Length").WithLocation(8, 51), // (9,53): error CS1061: 'object' does not contain a definition for 'Length' and no accessible extension method 'Length' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?) // Delegate d3 = delegate (object x3) { _ = x3.Length; }; Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "Length").WithArguments("object", "Length").WithLocation(9, 53)); } public static IEnumerable<object?[]> GetBaseAndDerivedTypesData() { yield return getData("internal void F(object x) { }", "internal static new void F(object x) { }", "F", "F", null, "System.Action<System.Object>"); // instance and static // https://github.com/dotnet/roslyn/issues/52701: Assert failure: Unexpected value 'LessDerived' of type 'Microsoft.CodeAnalysis.CSharp.MemberResolutionKind' #if !DEBUG yield return getData("internal void F(object x) { }", "internal static new void F(object x) { }", "this.F", "F", new[] { // (5,29): error CS0176: Member 'B.F(object)' cannot be accessed with an instance reference; qualify it with a type name instead // System.Delegate d = this.F; Diagnostic(ErrorCode.ERR_ObjectProhibited, "this.F").WithArguments("B.F(object)").WithLocation(5, 29) }); // instance and static #endif yield return getData("internal void F(object x) { }", "internal static new void F(object x) { }", "base.F", "F", null, "System.Action<System.Object>"); // instance and static yield return getData("internal static void F(object x) { }", "internal new void F(object x) { }", "F", "F", null, "System.Action<System.Object>"); // static and instance yield return getData("internal static void F(object x) { }", "internal new void F(object x) { }", "this.F", "F", null, "System.Action<System.Object>"); // static and instance yield return getData("internal static void F(object x) { }", "internal new void F(object x) { }", "base.F", "F"); // static and instance yield return getData("internal void F(object x) { }", "internal static void F() { }", "F", "F"); // instance and static, different number of parameters yield return getData("internal void F(object x) { }", "internal static void F() { }", "B.F", "F", null, "System.Action"); // instance and static, different number of parameters yield return getData("internal void F(object x) { }", "internal static void F() { }", "this.F", "F", null, "System.Action<System.Object>"); // instance and static, different number of parameters yield return getData("internal void F(object x) { }", "internal static void F() { }", "base.F", "F", null, "System.Action<System.Object>"); // instance and static, different number of parameters yield return getData("internal static void F() { }", "internal void F(object x) { }", "F", "F"); // static and instance, different number of parameters yield return getData("internal static void F() { }", "internal void F(object x) { }", "B.F", "F", null, "System.Action"); // static and instance, different number of parameters yield return getData("internal static void F() { }", "internal void F(object x) { }", "this.F", "F", null, "System.Action<System.Object>"); // static and instance, different number of parameters yield return getData("internal static void F() { }", "internal void F(object x) { }", "base.F", "F"); // static and instance, different number of parameters yield return getData("internal static void F(object x) { }", "private static void F() { }", "F", "F"); // internal and private yield return getData("private static void F(object x) { }", "internal static void F() { }", "F", "F", null, "System.Action"); // internal and private yield return getData("internal abstract void F(object x);", "internal override void F(object x) { }", "F", "F", null, "System.Action<System.Object>"); // override yield return getData("internal virtual void F(object x) { }", "internal override void F(object x) { }", "F", "F", null, "System.Action<System.Object>"); // override yield return getData("internal void F(object x) { }", "internal void F(object x) { }", "F", "F", null, "System.Action<System.Object>"); // hiding yield return getData("internal void F(object x) { }", "internal new void F(object x) { }", "F", "F", null, "System.Action<System.Object>"); // hiding yield return getData("internal void F(object x) { }", "internal new void F(object y) { }", "F", "F", null, "System.Action<System.Object>"); // different parameter name yield return getData("internal void F(object x) { }", "internal void F(string x) { }", "F", "F"); // different parameter type yield return getData("internal void F(object x) { }", "internal void F(object x, object y) { }", "F", "F"); // different number of parameters yield return getData("internal void F(object x) { }", "internal void F(ref object x) { }", "F", "F"); // different parameter ref kind yield return getData("internal void F(ref object x) { }", "internal void F(object x) { }", "F", "F"); // different parameter ref kind yield return getData("internal abstract object F();", "internal override object F() => throw null;", "F", "F", null, "System.Func<System.Object>"); // override yield return getData("internal virtual object F() => throw null;", "internal override object F() => throw null;", "F", "F", null, "System.Func<System.Object>"); // override yield return getData("internal object F() => throw null;", "internal object F() => throw null;", "F", "F", null, "System.Func<System.Object>"); // hiding yield return getData("internal object F() => throw null;", "internal new object F() => throw null;", "F", "F", null, "System.Func<System.Object>"); // hiding yield return getData("internal string F() => throw null;", "internal new object F() => throw null;", "F", "F"); // different return type yield return getData("internal object F() => throw null;", "internal new ref object F() => throw null;", "F", "F"); // different return ref kind yield return getData("internal ref object F() => throw null;", "internal new object F() => throw null;", "F", "F"); // different return ref kind yield return getData("internal void F(object x) { }", "internal new void F(dynamic x) { }", "F", "F", null, "System.Action<System.Object>"); // object/dynamic yield return getData("internal dynamic F() => throw null;", "internal new object F() => throw null;", "F", "F", null, "System.Func<System.Object>"); // object/dynamic yield return getData("internal void F((object, int) x) { }", "internal new void F((object a, int b) x) { }", "F", "F", null, "System.Action<System.ValueTuple<System.Object, System.Int32>>"); // tuple names yield return getData("internal (object a, int b) F() => throw null;", "internal new (object, int) F() => throw null;", "F", "F", null, "System.Func<System.ValueTuple<System.Object, System.Int32>>"); // tuple names yield return getData("internal void F(System.IntPtr x) { }", "internal new void F(nint x) { }", "F", "F", null, "System.Action<System.IntPtr>"); // System.IntPtr/nint yield return getData("internal nint F() => throw null;", "internal new System.IntPtr F() => throw null;", "F", "F", null, "System.Func<System.IntPtr>"); // System.IntPtr/nint yield return getData("internal void F(object x) { }", @"#nullable enable internal new void F(object? x) { } #nullable disable", "F", "F", null, "System.Action<System.Object>"); // different nullability yield return getData( @"#nullable enable internal object? F() => throw null!; #nullable disable", "internal new object F() => throw null;", "F", "F", null, "System.Func<System.Object>"); // different nullability yield return getData("internal void F() { }", "internal void F<T>() { }", "F", "F"); // different arity yield return getData("internal void F() { }", "internal void F<T>() { }", "F<int>", "F<int>", null, "System.Action"); // different arity yield return getData("internal void F<T>() { }", "internal void F() { }", "F", "F"); // different arity yield return getData("internal void F<T>() { }", "internal void F() { }", "F<int>", "F<int>", null, "System.Action"); // different arity yield return getData("internal void F<T>() { }", "internal void F<T, U>() { }", "F<int>", "F<int>", null, "System.Action"); // different arity yield return getData("internal void F<T>() { }", "internal void F<T, U>() { }", "F<int, object>", "F<int, object>", null, "System.Action"); // different arity yield return getData("internal void F<T>(T t) { }", "internal new void F<U>(U u) { }", "F<int>", "F<int>", null, "System.Action<System.Int32>"); // different type parameter names yield return getData("internal void F<T>(T t) where T : class { }", "internal new void F<T>(T t) { }", "F<object>", "F<object>", null, "System.Action<System.Object>"); // different type parameter constraints yield return getData("internal void F<T>(T t) { }", "internal new void F<T>(T t) where T : class { }", "F<object>", "F<object>", null, "System.Action<System.Object>"); // different type parameter constraints yield return getData("internal void F<T>(T t) { }", "internal new void F<T>(T t) where T : class { }", "base.F<object>", "F<object>", null, "System.Action<System.Object>"); // different type parameter constraints yield return getData("internal void F<T>(T t) where T : class { }", "internal new void F<T>(T t) where T : struct { }", "F<int>", "F<int>", null, "System.Action<System.Int32>"); // different type parameter constraints // https://github.com/dotnet/roslyn/issues/52701: Assert failure: Unexpected value 'LessDerived' of type 'Microsoft.CodeAnalysis.CSharp.MemberResolutionKind' #if !DEBUG yield return getData("internal void F<T>(T t) where T : class { }", "internal new void F<T>(T t) where T : struct { }", "F<object>", "F<object>", new[] { // (5,29): 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.Delegate d = F<object>; Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "F<object>").WithArguments("B.F<T>(T)", "T", "object").WithLocation(5, 29) }); // different type parameter constraints #endif static object?[] getData(string methodA, string methodB, string methodGroupExpression, string methodGroupOnly, DiagnosticDescription[]? expectedDiagnostics = null, string? expectedType = null) { if (expectedDiagnostics is null && expectedType is null) { int offset = methodGroupExpression.Length - methodGroupOnly.Length; expectedDiagnostics = new[] { // (5,29): error CS8917: The delegate type could not be inferred. // System.Delegate d = F; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, methodGroupOnly).WithLocation(5, 29 + offset) }; } return new object?[] { methodA, methodB, methodGroupExpression, expectedDiagnostics, expectedType }; } } [Theory] [MemberData(nameof(GetBaseAndDerivedTypesData))] public void MethodGroup_BaseAndDerivedTypes(string methodA, string methodB, string methodGroupExpression, DiagnosticDescription[]? expectedDiagnostics, string? expectedType) { var source = $@"partial class B {{ void M() {{ System.Delegate d = {methodGroupExpression}; System.Console.Write(d.GetDelegateTypeName()); }} static void Main() {{ new B().M(); }} }} abstract class A {{ {methodA} }} partial class B : A {{ {methodB} }}"; var comp = CreateCompilation(new[] { source, s_utils }, parseOptions: TestOptions.RegularPreview, options: TestOptions.ReleaseExe); if (expectedDiagnostics is null) { CompileAndVerify(comp, expectedOutput: expectedType); } else { comp.VerifyDiagnostics(expectedDiagnostics); } var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var expr = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Single().Initializer!.Value; var typeInfo = model.GetTypeInfo(expr); Assert.Null(typeInfo.Type); Assert.Equal(SpecialType.System_Delegate, typeInfo.ConvertedType!.SpecialType); } public static IEnumerable<object?[]> GetExtensionMethodsSameScopeData() { yield return getData("internal static void F(this object x) { }", "internal static void F(this string x) { }", "string.Empty.F", "F", null, "B.F", "System.Action"); // different parameter type yield return getData("internal static void F(this object x) { }", "internal static void F(this string x) { }", "this.F", "F", null, "A.F", "System.Action"); // different parameter type yield return getData("internal static void F(this object x) { }", "internal static void F(this object x, object y) { }", "this.F", "F"); // different number of parameters yield return getData("internal static void F(this object x, object y) { }", "internal static void F(this object x, ref object y) { }", "this.F", "F"); // different parameter ref kind yield return getData("internal static void F(this object x, ref object y) { }", "internal static void F(this object x, object y) { }", "this.F", "F"); // different parameter ref kind yield return getData("internal static object F(this object x) => throw null;", "internal static ref object F(this object x) => throw null;", "this.F", "F"); // different return ref kind yield return getData("internal static ref object F(this object x) => throw null;", "internal static object F(this object x) => throw null;", "this.F", "F"); // different return ref kind yield return getData("internal static void F(this object x, object y) { }", "internal static void F<T>(this object x, T y) { }", "this.F", "F"); // different arity yield return getData("internal static void F(this object x, object y) { }", "internal static void F<T>(this object x, T y) { }", "this.F<int>", "F<int>", null, "B.F", "System.Action<System.Int32>"); // different arity yield return getData("internal static void F<T>(this object x) { }", "internal static void F(this object x) { }", "this.F", "F"); // different arity yield return getData("internal static void F<T>(this object x) { }", "internal static void F(this object x) { }", "this.F<int>", "F<int>", null, "A.F", "System.Action"); // different arity yield return getData("internal static void F<T>(this T t) where T : class { }", "internal static void F<T>(this T t) { }", "this.F<object>", "F<object>", new[] { // (5,29): error CS0121: The call is ambiguous between the following methods or properties: 'A.F<T>(T)' and 'B.F<T>(T)' // System.Delegate d = this.F<object>; Diagnostic(ErrorCode.ERR_AmbigCall, "this.F<object>").WithArguments("A.F<T>(T)", "B.F<T>(T)").WithLocation(5, 29) }); // different type parameter constraints yield return getData("internal static void F<T>(this T t) { }", "internal static void F<T>(this T t) where T : class { }", "this.F<object>", "F<object>", new[] { // (5,29): error CS0121: The call is ambiguous between the following methods or properties: 'A.F<T>(T)' and 'B.F<T>(T)' // System.Delegate d = this.F<object>; Diagnostic(ErrorCode.ERR_AmbigCall, "this.F<object>").WithArguments("A.F<T>(T)", "B.F<T>(T)").WithLocation(5, 29) }); // different type parameter constraints yield return getData("internal static void F<T>(this T t) where T : class { }", "internal static void F<T>(this T t) where T : struct { }", "this.F<int>", "F<int>"); // different type parameter constraints static object?[] getData(string methodA, string methodB, string methodGroupExpression, string methodGroupOnly, DiagnosticDescription[]? expectedDiagnostics = null, string? expectedMethod = null, string? expectedType = null) { if (expectedDiagnostics is null && expectedType is null) { int offset = methodGroupExpression.Length - methodGroupOnly.Length; expectedDiagnostics = new[] { // (5,29): error CS8917: The delegate type could not be inferred. // System.Delegate d = F; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, methodGroupOnly).WithLocation(5, 29 + offset) }; } return new object?[] { methodA, methodB, methodGroupExpression, expectedDiagnostics, expectedMethod, expectedType }; } } [Theory] [MemberData(nameof(GetExtensionMethodsSameScopeData))] public void MethodGroup_ExtensionMethodsSameScope(string methodA, string methodB, string methodGroupExpression, DiagnosticDescription[]? expectedDiagnostics, string? expectedMethod, string? expectedType) { var source = $@"class Program {{ void M() {{ System.Delegate d = {methodGroupExpression}; System.Console.Write(""{{0}}: {{1}}"", d.GetDelegateMethodName(), d.GetDelegateTypeName()); }} static void Main() {{ new Program().M(); }} }} static class A {{ {methodA} }} static class B {{ {methodB} }}"; var comp = CreateCompilation(new[] { source, s_utils }, parseOptions: TestOptions.RegularPreview, options: TestOptions.ReleaseExe); if (expectedDiagnostics is null) { CompileAndVerify(comp, expectedOutput: $"{expectedMethod}: {expectedType}"); } else { comp.VerifyDiagnostics(expectedDiagnostics); } var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var expr = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Single().Initializer!.Value; var typeInfo = model.GetTypeInfo(expr); Assert.Null(typeInfo.Type); Assert.Equal(SpecialType.System_Delegate, typeInfo.ConvertedType!.SpecialType); var symbolInfo = model.GetSymbolInfo(expr); // https://github.com/dotnet/roslyn/issues/52870: GetSymbolInfo() should return resolved method from method group. Assert.Null(symbolInfo.Symbol); } public static IEnumerable<object?[]> GetExtensionMethodsDifferentScopeData() { yield return getData("internal static void F(this object x) { }", "internal static void F(this object x) { }", "this.F", "F", null, "A.F", "System.Action"); // hiding yield return getData("internal static void F(this object x) { }", "internal static void F(this object y) { }", "this.F", "F", null, "A.F", "System.Action"); // different parameter name yield return getData("internal static void F(this object x) { }", "internal static void F(this string x) { }", "string.Empty.F", "F", null, "A.F", "System.Action"); // different parameter type yield return getData("internal static void F(this object x) { }", "internal static void F(this string x) { }", "this.F", "F", null, "A.F", "System.Action"); // different parameter type yield return getData("internal static void F(this object x) { }", "internal static void F(this object x, object y) { }", "this.F", "F"); // different number of parameters yield return getData("internal static void F(this object x, object y) { }", "internal static void F(this object x, ref object y) { }", "this.F", "F"); // different parameter ref kind yield return getData("internal static void F(this object x, ref object y) { }", "internal static void F(this object x, object y) { }", "this.F", "F"); // different parameter ref kind yield return getData("internal static object F(this object x) => throw null;", "internal static ref object F(this object x) => throw null;", "this.F", "F"); // different return ref kind yield return getData("internal static ref object F(this object x) => throw null;", "internal static object F(this object x) => throw null;", "this.F", "F"); // different return ref kind yield return getData("internal static void F(this object x, System.IntPtr y) { }", "internal static void F(this object x, nint y) { }", "this.F", "F", null, "A.F", "System.Action<System.IntPtr>"); // System.IntPtr/nint yield return getData("internal static nint F(this object x) => throw null;", "internal static System.IntPtr F(this object x) => throw null;", "this.F", "F", null, "A.F", "System.Func<System.IntPtr>"); // System.IntPtr/nint yield return getData("internal static void F(this object x, object y) { }", "internal static void F<T>(this object x, T y) { }", "this.F", "F"); // different arity yield return getData("internal static void F(this object x, object y) { }", "internal static void F<T>(this object x, T y) { }", "this.F<int>", "F<int>", null, "N.B.F", "System.Action<System.Int32>"); // different arity yield return getData("internal static void F<T>(this object x) { }", "internal static void F(this object x) { }", "this.F", "F"); // different arity yield return getData("internal static void F<T>(this object x) { }", "internal static void F(this object x) { }", "this.F<int>", "F<int>", null, "A.F", "System.Action"); // different arity yield return getData("internal static void F<T>(this T t) where T : class { }", "internal static void F<T>(this T t) { }", "this.F<object>", "F<object>", null, "A.F", "System.Action"); // different type parameter constraints yield return getData("internal static void F<T>(this T t) { }", "internal static void F<T>(this T t) where T : class { }", "this.F<object>", "F<object>", null, "A.F", "System.Action"); // different type parameter constraints yield return getData("internal static void F<T>(this T t) where T : class { }", "internal static void F<T>(this T t) where T : struct { }", "this.F<int>", "F<int>"); // different type parameter constraints static object?[] getData(string methodA, string methodB, string methodGroupExpression, string methodGroupOnly, DiagnosticDescription[]? expectedDiagnostics = null, string? expectedMethod = null, string? expectedType = null) { if (expectedDiagnostics is null && expectedType is null) { int offset = methodGroupExpression.Length - methodGroupOnly.Length; expectedDiagnostics = new[] { // (6,29): error CS8917: The delegate type could not be inferred. // System.Delegate d = F; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, methodGroupOnly).WithLocation(6, 29 + offset) }; } return new object?[] { methodA, methodB, methodGroupExpression, expectedDiagnostics, expectedMethod, expectedType }; } } [Theory] [MemberData(nameof(GetExtensionMethodsDifferentScopeData))] public void MethodGroup_ExtensionMethodsDifferentScope(string methodA, string methodB, string methodGroupExpression, DiagnosticDescription[]? expectedDiagnostics, string? expectedMethod, string? expectedType) { var source = $@"using N; class Program {{ void M() {{ System.Delegate d = {methodGroupExpression}; System.Console.Write(""{{0}}: {{1}}"", d.GetDelegateMethodName(), d.GetDelegateTypeName()); }} static void Main() {{ new Program().M(); }} }} static class A {{ {methodA} }} namespace N {{ static class B {{ {methodB} }} }}"; var comp = CreateCompilation(new[] { source, s_utils }, parseOptions: TestOptions.RegularPreview, options: TestOptions.ReleaseExe); if (expectedDiagnostics is null) { CompileAndVerify(comp, expectedOutput: $"{expectedMethod}: {expectedType}"); } else { comp.VerifyDiagnostics(expectedDiagnostics); } var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var expr = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Single().Initializer!.Value; var typeInfo = model.GetTypeInfo(expr); Assert.Null(typeInfo.Type); Assert.Equal(SpecialType.System_Delegate, typeInfo.ConvertedType!.SpecialType); var symbolInfo = model.GetSymbolInfo(expr); // https://github.com/dotnet/roslyn/issues/52870: GetSymbolInfo() should return resolved method from method group. Assert.Null(symbolInfo.Symbol); } [Fact] public void InstanceMethods_01() { var source = @"using System; class Program { object F1() => null; void F2(object x, int y) { } void F() { Delegate d1 = F1; Delegate d2 = this.F2; Console.WriteLine(""{0}, {1}"", d1.GetDelegateTypeName(), d2.GetDelegateTypeName()); } static void Main() { new Program().F(); } }"; CompileAndVerify(new[] { source, s_utils }, parseOptions: TestOptions.RegularPreview, expectedOutput: "System.Func<System.Object>, System.Action<System.Object, System.Int32>"); } [Fact] public void InstanceMethods_02() { var source = @"using System; class A { protected virtual void F() { Console.WriteLine(nameof(A)); } } class B : A { protected override void F() { Console.WriteLine(nameof(B)); } static void Invoke(Delegate d) { d.DynamicInvoke(); } void M() { Invoke(F); Invoke(this.F); Invoke(base.F); } static void Main() { new B().M(); } }"; CompileAndVerify(source, parseOptions: TestOptions.RegularPreview, expectedOutput: @"B B A"); } [Fact] public void InstanceMethods_03() { var source = @"using System; class A { protected void F() { Console.WriteLine(nameof(A)); } } class B : A { protected new void F() { Console.WriteLine(nameof(B)); } static void Invoke(Delegate d) { d.DynamicInvoke(); } void M() { Invoke(F); Invoke(this.F); Invoke(base.F); } static void Main() { new B().M(); } }"; CompileAndVerify(source, parseOptions: TestOptions.RegularPreview, expectedOutput: @"B B A"); } [Fact] public void InstanceMethods_04() { var source = @"class Program { T F<T>() => default; static void Main() { var p = new Program(); System.Delegate d = p.F; object o = (System.Delegate)p.F; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (7,31): error CS8917: The delegate type could not be inferred. // System.Delegate d = p.F; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "F").WithLocation(7, 31), // (8,20): error CS0030: Cannot convert type 'method' to 'Delegate' // object o = (System.Delegate)p.F; Diagnostic(ErrorCode.ERR_NoExplicitConv, "(System.Delegate)p.F").WithArguments("method", "System.Delegate").WithLocation(8, 20)); } [Fact] public void MethodGroup_Inaccessible() { var source = @"using System; class A { private static void F() { } internal static void F(object o) { } } class B { static void Main() { Delegate d = A.F; Console.WriteLine(d.GetDelegateTypeName()); } }"; CompileAndVerify(new[] { source, s_utils }, parseOptions: TestOptions.RegularPreview, expectedOutput: "System.Action<System.Object>"); } [Fact] public void MethodGroup_IncorrectArity() { var source = @"class Program { static void F0(object o) { } static void F0<T>(object o) { } static void F1(object o) { } static void F1<T, U>(object o) { } static void F2<T>(object o) { } static void F2<T, U>(object o) { } static void Main() { System.Delegate d; d = F0<int, object>; d = F1<int>; d = F2; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (12,13): error CS0308: The non-generic method 'Program.F0(object)' cannot be used with type arguments // d = F0<int, object>; Diagnostic(ErrorCode.ERR_HasNoTypeVars, "F0<int, object>").WithArguments("Program.F0(object)", "method").WithLocation(12, 13), // (13,13): error CS0308: The non-generic method 'Program.F1(object)' cannot be used with type arguments // d = F1<int>; Diagnostic(ErrorCode.ERR_HasNoTypeVars, "F1<int>").WithArguments("Program.F1(object)", "method").WithLocation(13, 13), // (14,13): error CS8917: The delegate type could not be inferred. // d = F2; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "F2").WithLocation(14, 13)); } [Fact] public void ExtensionMethods_01() { var source = @"static class E { internal static void F1(this object x, int y) { } internal static void F2(this object x) { } } class Program { void F2(int x) { } static void Main() { System.Delegate d; var p = new Program(); d = p.F1; d = p.F2; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (14,15): error CS8917: The delegate type could not be inferred. // d = p.F2; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "F2").WithLocation(14, 15)); } [Fact] public void ExtensionMethods_02() { var source = @"using System; static class E { internal static void F(this System.Type x, int y) { } internal static void F(this string x) { } } class Program { static void Main() { Delegate d1 = typeof(Program).F; Delegate d2 = """".F; Console.WriteLine(""{0}, {1}"", d1.GetDelegateTypeName(), d2.GetDelegateTypeName()); } }"; var comp = CreateCompilation(new[] { source, s_utils }, parseOptions: TestOptions.RegularPreview, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: "System.Action<System.Int32>, System.Action"); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var exprs = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Select(d => d.Initializer!.Value).ToArray(); Assert.Equal(2, exprs.Length); foreach (var expr in exprs) { var typeInfo = model.GetTypeInfo(expr); Assert.Null(typeInfo.Type); Assert.Equal(SpecialType.System_Delegate, typeInfo.ConvertedType!.SpecialType); } } [Fact] public void ExtensionMethods_03() { var source = @"using N; namespace N { static class E1 { internal static void F1(this object x, int y) { } internal static void F2(this object x, int y) { } internal static void F2(this object x) { } internal static void F3(this object x) { } } } static class E2 { internal static void F1(this object x) { } } class Program { static void Main() { System.Delegate d; var p = new Program(); d = p.F1; d = p.F2; d = p.F3; d = E1.F1; d = E2.F1; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (22,15): error CS8917: The delegate type could not be inferred. // d = p.F1; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "F1").WithLocation(22, 15), // (23,15): error CS8917: The delegate type could not be inferred. // d = p.F2; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "F2").WithLocation(23, 15)); } [Fact] public void ExtensionMethods_04() { var source = @"static class E { internal static void F1(this object x, int y) { } } static class Program { static void F2(this object x) { } static void Main() { System.Delegate d; d = E.F1; d = F2; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics(); } [Fact] public void ExtensionMethods_05() { var source = @"using System; static class E { internal static void F(this A a) { } } class A { } class B : A { static void Invoke(Delegate d) { } void M() { Invoke(F); Invoke(this.F); Invoke(base.F); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (14,16): error CS0103: The name 'F' does not exist in the current context // Invoke(F); Diagnostic(ErrorCode.ERR_NameNotInContext, "F").WithArguments("F").WithLocation(14, 16), // (16,21): error CS0117: 'A' does not contain a definition for 'F' // Invoke(base.F); Diagnostic(ErrorCode.ERR_NoSuchMember, "F").WithArguments("A", "F").WithLocation(16, 21)); } [Fact] public void ExtensionMethods_06() { var source = @"static class E { internal static void F1<T>(this object x, T y) { } internal static void F2<T, U>(this T t) { } } class Program { static void F<T>(T t) where T : class { System.Delegate d; d = t.F1; d = t.F2; d = t.F1<int>; d = t.F1<T>; d = t.F2<T, object>; d = t.F2<object, T>; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (11,15): error CS8917: The delegate type could not be inferred. // d = t.F1; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "F1").WithLocation(11, 15), // (12,15): error CS8917: The delegate type could not be inferred. // d = t.F2; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "F2").WithLocation(12, 15)); } /// <summary> /// Method group with dynamic receiver does not use method group conversion. /// </summary> [Fact] public void DynamicReceiver() { var source = @"using System; class Program { void F() { } static void Main() { dynamic d = new Program(); object obj; try { obj = d.F; } catch (Exception e) { obj = e; } Console.WriteLine(obj.GetType().FullName); } }"; CompileAndVerify(source, parseOptions: TestOptions.RegularPreview, references: new[] { CSharpRef }, expectedOutput: "Microsoft.CSharp.RuntimeBinder.RuntimeBinderException"); } // System.Func<> and System.Action<> cannot be used as the delegate type // when the parameters or return type are not valid type arguments. [Fact] public void InvalidTypeArguments() { var source = @"unsafe class Program { static int* F() => throw null; static void Main() { System.Delegate d; d = F; d = (int x, int* y) => { }; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview, options: TestOptions.UnsafeReleaseExe); comp.VerifyDiagnostics( // (7,13): error CS8917: The delegate type could not be inferred. // d = F; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "F").WithLocation(7, 13), // (8,13): error CS8917: The delegate type could not be inferred. // d = (int x, int* y) => { }; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "(int x, int* y) => { }").WithLocation(8, 13)); } [Fact] public void GenericDelegateType() { var source = @"using System; class Program { static void Main() { Delegate d = F<int>(); Console.WriteLine(d.GetDelegateTypeName()); } unsafe static Delegate F<T>() { return (T t, int* p) => { }; } }"; // When we synthesize delegate types, and infer a synthesized // delegate type, run the program to report the actual delegate type. var comp = CreateCompilation(new[] { source, s_utils }, parseOptions: TestOptions.RegularPreview, options: TestOptions.UnsafeReleaseExe); comp.VerifyDiagnostics( // (11,16): error CS8917: The delegate type could not be inferred. // return (T t, int* p) => { }; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "(T t, int* p) => { }").WithLocation(11, 16)); } /// <summary> /// Custom modifiers should not affect delegate signature. /// </summary> [Fact] public void CustomModifiers_01() { var sourceA = @".class public A { .method public static void F1(object modopt(int32) x) { ldnull throw } .method public static object modopt(int32) F2() { ldnull throw } }"; var refA = CompileIL(sourceA); var sourceB = @"using System; class B { static void Report(Delegate d) { Console.WriteLine(d.GetDelegateTypeName()); } static void Main() { Report(A.F1); Report(A.F2); } }"; var comp = CreateCompilation(new[] { sourceB, s_utils }, new[] { refA }, parseOptions: TestOptions.RegularPreview, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: @"System.Action<System.Object> System.Func<System.Object>"); } /// <summary> /// Custom modifiers should not affect delegate signature. /// </summary> [Fact] public void CustomModifiers_02() { var sourceA = @".class public A { .method public static void F1(object modreq(int32) x) { ldnull throw } .method public static object modreq(int32) F2() { ldnull throw } }"; var refA = CompileIL(sourceA); var sourceB = @"using System; class B { static void Report(Delegate d) { Console.WriteLine(d.GetDelegateTypeName()); } static void Main() { Report(A.F1); Report(A.F2); } }"; var comp = CreateCompilation(new[] { sourceB, s_utils }, new[] { refA }, parseOptions: TestOptions.RegularPreview, options: TestOptions.ReleaseExe); comp.VerifyDiagnostics( // (10,16): error CS1503: Argument 1: cannot convert from 'method group' to 'Delegate' // Report(A.F1); Diagnostic(ErrorCode.ERR_BadArgType, "A.F1").WithArguments("1", "method group", "System.Delegate").WithLocation(10, 16), // (11,16): error CS1503: Argument 1: cannot convert from 'method group' to 'Delegate' // Report(A.F2); Diagnostic(ErrorCode.ERR_BadArgType, "A.F2").WithArguments("1", "method group", "System.Delegate").WithLocation(11, 16)); } [Fact] public void UnmanagedCallersOnlyAttribute_01() { var source = @"using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; class Program { static void Main() { Delegate d = F; } [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] static void F() { } }"; var comp = CreateCompilation(new[] { source, UnmanagedCallersOnlyAttributeDefinition }, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (8,22): error CS8902: 'Program.F()' is attributed with 'UnmanagedCallersOnly' and cannot be converted to a delegate type. Obtain a function pointer to this method. // Delegate d = F; Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyMethodsCannotBeConvertedToDelegate, "F").WithArguments("Program.F()").WithLocation(8, 22)); } [Fact] public void UnmanagedCallersOnlyAttribute_02() { var source = @"using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; class Program { static void Main() { Delegate d = new S().F; } } struct S { } static class E1 { [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] public static void F(this S s) { } } static class E2 { [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvStdcall) })] public static void F(this S s) { } }"; var comp = CreateCompilation(new[] { source, UnmanagedCallersOnlyAttributeDefinition }, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (8,22): error CS0121: The call is ambiguous between the following methods or properties: 'E1.F(S)' and 'E2.F(S)' // Delegate d = new S().F; Diagnostic(ErrorCode.ERR_AmbigCall, "new S().F").WithArguments("E1.F(S)", "E2.F(S)").WithLocation(8, 22)); } [Fact] public void SystemActionAndFunc_Missing() { var sourceA = @".assembly mscorlib { .ver 0:0:0:0 } .class public System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public abstract System.ValueType extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public System.String extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Void extends System.ValueType { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Boolean extends System.ValueType { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Int32 extends System.ValueType { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public abstract System.Delegate extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } }"; var refA = CompileIL(sourceA, prependDefaultHeader: false, autoInherit: false); var sourceB = @"class Program { static void Main() { System.Delegate d; d = Main; d = () => 1; } }"; var comp = CreateEmptyCompilation(sourceB, new[] { refA }, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (6,13): error CS0518: Predefined type 'System.Action' is not defined or imported // d = Main; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "Main").WithArguments("System.Action").WithLocation(6, 13), // (6,13): error CS0518: Predefined type 'System.Action' is not defined or imported // d = Main; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "Main").WithArguments("System.Action").WithLocation(6, 13), // (6,13): error CS8917: The delegate type could not be inferred. // d = Main; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "Main").WithLocation(6, 13), // (7,13): error CS0518: Predefined type 'System.Func`1' is not defined or imported // d = () => 1; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "() => 1").WithArguments("System.Func`1").WithLocation(7, 13)); } private static MetadataReference GetCorlibWithInvalidActionAndFuncOfT() { var sourceA = @".assembly mscorlib { .ver 0:0:0:0 } .class public System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public abstract System.ValueType extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public System.String extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public System.Type extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Void extends System.ValueType { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Boolean extends System.ValueType { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Int32 extends System.ValueType { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public abstract System.Delegate extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public abstract System.Attribute extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Runtime.CompilerServices.RequiredAttributeAttribute extends System.Attribute { .method public hidebysig specialname rtspecialname instance void .ctor(class System.Type t) cil managed { ret } } .class public abstract System.MulticastDelegate extends System.Delegate { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Action`1<T> extends System.MulticastDelegate { .custom instance void System.Runtime.CompilerServices.RequiredAttributeAttribute::.ctor(class System.Type) = ( 01 00 FF 00 00 ) .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } .method public hidebysig instance void Invoke(!T t) { ret } } .class public sealed System.Func`1<T> extends System.MulticastDelegate { .custom instance void System.Runtime.CompilerServices.RequiredAttributeAttribute::.ctor(class System.Type) = ( 01 00 FF 00 00 ) .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } .method public hidebysig instance !T Invoke() { ldnull throw } }"; return CompileIL(sourceA, prependDefaultHeader: false, autoInherit: false); } [Fact] public void SystemActionAndFunc_UseSiteErrors() { var refA = GetCorlibWithInvalidActionAndFuncOfT(); var sourceB = @"class Program { static void F(object o) { } static void Main() { System.Delegate d; d = F; d = () => 1; } }"; var comp = CreateEmptyCompilation(sourceB, new[] { refA }, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (9,13): error CS0648: 'Action<T>' is a type not supported by the language // d = F; Diagnostic(ErrorCode.ERR_BogusType, "F").WithArguments("System.Action<T>").WithLocation(9, 13), // (9,13): error CS0648: 'Action<T>' is a type not supported by the language // d = F; Diagnostic(ErrorCode.ERR_BogusType, "F").WithArguments("System.Action<T>").WithLocation(9, 13), // (10,13): error CS0648: 'Func<T>' is a type not supported by the language // d = () => 1; Diagnostic(ErrorCode.ERR_BogusType, "() => 1").WithArguments("System.Func<T>").WithLocation(10, 13)); } [Fact] public void SystemLinqExpressionsExpression_Missing() { var sourceA = @".assembly mscorlib { .ver 0:0:0:0 } .class public System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public abstract System.ValueType extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public System.String extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public System.Type extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Void extends System.ValueType { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Boolean extends System.ValueType { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Int32 extends System.ValueType { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public abstract System.Delegate extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public abstract System.MulticastDelegate extends System.Delegate { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Func`1<T> extends System.MulticastDelegate { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } .method public hidebysig instance !T Invoke() { ldnull throw } } .class public abstract System.Linq.Expressions.Expression extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } }"; var refA = CompileIL(sourceA, prependDefaultHeader: false, autoInherit: false); var sourceB = @"class Program { static void Main() { System.Linq.Expressions.Expression e = () => 1; } }"; var comp = CreateEmptyCompilation(sourceB, new[] { refA }, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (5,48): error CS0518: Predefined type 'System.Linq.Expressions.Expression`1' is not defined or imported // System.Linq.Expressions.Expression e = () => 1; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "() => 1").WithArguments("System.Linq.Expressions.Expression`1").WithLocation(5, 48)); } [Fact] public void SystemLinqExpressionsExpression_UseSiteErrors() { var sourceA = @".assembly mscorlib { .ver 0:0:0:0 } .class public System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public abstract System.ValueType extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public System.String extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public System.Type extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Void extends System.ValueType { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Boolean extends System.ValueType { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Int32 extends System.ValueType { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public abstract System.Delegate extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public abstract System.Attribute extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Runtime.CompilerServices.RequiredAttributeAttribute extends System.Attribute { .method public hidebysig specialname rtspecialname instance void .ctor(class System.Type t) cil managed { ret } } .class public abstract System.MulticastDelegate extends System.Delegate { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Func`1<T> extends System.MulticastDelegate { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } .method public hidebysig instance !T Invoke() { ldnull throw } } .class public abstract System.Linq.Expressions.Expression extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public abstract System.Linq.Expressions.LambdaExpression extends System.Linq.Expressions.Expression { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public sealed System.Linq.Expressions.Expression`1<T> extends System.Linq.Expressions.LambdaExpression { .custom instance void System.Runtime.CompilerServices.RequiredAttributeAttribute::.ctor(class System.Type) = ( 01 00 FF 00 00 ) .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } }"; var refA = CompileIL(sourceA, prependDefaultHeader: false, autoInherit: false); var sourceB = @"class Program { static void Main() { System.Linq.Expressions.Expression e = () => 1; } }"; var comp = CreateEmptyCompilation(sourceB, new[] { refA }, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (5,48): error CS0648: 'Expression<T>' is a type not supported by the language // System.Linq.Expressions.Expression e = () => 1; Diagnostic(ErrorCode.ERR_BogusType, "() => 1").WithArguments("System.Linq.Expressions.Expression<T>").WithLocation(5, 48)); } [WorkItem(4674, "https://github.com/dotnet/csharplang/issues/4674")] [Fact] public void OverloadResolution_01() { var source = @"using System; class Program { static void M<T>(T t) { Console.WriteLine(""M<T>(T t)""); } static void M(Action<string> a) { Console.WriteLine(""M(Action<string> a)""); } static void F(object o) { } static void Main() { M(F); // C#9: M(Action<string>) } }"; var expectedOutput = @"M(Action<string> a)"; CompileAndVerify(source, parseOptions: TestOptions.Regular9, expectedOutput: expectedOutput); CompileAndVerify(source, parseOptions: TestOptions.RegularPreview, expectedOutput: expectedOutput); } [WorkItem(4674, "https://github.com/dotnet/csharplang/issues/4674")] [Fact] public void OverloadResolution_02() { var source = @"using System; class Program { static void Main() { var c = new C(); c.M(Main); // C#9: E.M(object x, Action y) c.M(() => { }); // C#9: E.M(object x, Action y) } } class C { public void M(object y) { Console.WriteLine(""C.M(object y)""); } } static class E { public static void M(this object x, Action y) { Console.WriteLine(""E.M(object x, Action y)""); } }"; var expectedOutput = @"E.M(object x, Action y) E.M(object x, Action y) "; CompileAndVerify(source, parseOptions: TestOptions.Regular9, expectedOutput: expectedOutput); CompileAndVerify(source, parseOptions: TestOptions.RegularPreview, expectedOutput: expectedOutput); } [WorkItem(4674, "https://github.com/dotnet/csharplang/issues/4674")] [Fact] public void OverloadResolution_03() { var source = @"using System; class Program { static void Main() { var c = new C(); c.M(Main); // C#9: E.M(object x, Action y) c.M(() => { }); // C#9: E.M(object x, Action y) } } class C { public void M(Delegate d) { Console.WriteLine(""C.M""); } } static class E { public static void M(this object o, Action a) { Console.WriteLine(""E.M""); } }"; CompileAndVerify(source, parseOptions: TestOptions.Regular9, expectedOutput: @"E.M E.M "); // Breaking change from C#9 which binds to E.M. CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: @"C.M C.M "); } [WorkItem(4674, "https://github.com/dotnet/csharplang/issues/4674")] [Fact] public void OverloadResolution_04() { var source = @"using System; using System.Linq.Expressions; class Program { static void Main() { var c = new C(); c.M(() => 1); } } class C { public void M(Expression e) { Console.WriteLine(""C.M""); } } static class E { public static void M(this object o, Func<int> a) { Console.WriteLine(""E.M""); } }"; CompileAndVerify(source, parseOptions: TestOptions.Regular9, expectedOutput: @"E.M"); // Breaking change from C#9 which binds to E.M. CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: @"C.M"); } [Fact] public void OverloadResolution_05() { var source = @"using System; class Program { static void Report(string name) { Console.WriteLine(name); } static void FA(Delegate d) { Report(""FA(Delegate)""); } static void FA(Action d) { Report(""FA(Action)""); } static void FB(Delegate d) { Report(""FB(Delegate)""); } static void FB(Func<int> d) { Report(""FB(Func<int>)""); } static void F1() { } static int F2() => 0; static void Main() { FA(F1); FA(F2); FB(F1); FB(F2); FA(() => { }); FA(() => 0); FB(() => { }); FB(() => 0); FA(delegate () { }); FA(delegate () { return 0; }); FB(delegate () { }); FB(delegate () { return 0; }); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (14,12): error CS1503: Argument 1: cannot convert from 'method group' to 'Delegate' // FA(F2); Diagnostic(ErrorCode.ERR_BadArgType, "F2").WithArguments("1", "method group", "System.Delegate").WithLocation(14, 12), // (15,12): error CS1503: Argument 1: cannot convert from 'method group' to 'Delegate' // FB(F1); Diagnostic(ErrorCode.ERR_BadArgType, "F1").WithArguments("1", "method group", "System.Delegate").WithLocation(15, 12), // (18,18): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement // FA(() => 0); Diagnostic(ErrorCode.ERR_IllegalStatement, "0").WithLocation(18, 18), // (19,15): error CS1643: Not all code paths return a value in lambda expression of type 'Func<int>' // FB(() => { }); Diagnostic(ErrorCode.ERR_AnonymousReturnExpected, "=>").WithArguments("lambda expression", "System.Func<int>").WithLocation(19, 15), // (22,26): error CS8030: Anonymous function converted to a void returning delegate cannot return a value // FA(delegate () { return 0; }); Diagnostic(ErrorCode.ERR_RetNoObjectRequiredLambda, "return").WithLocation(22, 26), // (23,12): error CS1643: Not all code paths return a value in anonymous method of type 'Func<int>' // FB(delegate () { }); Diagnostic(ErrorCode.ERR_AnonymousReturnExpected, "delegate").WithArguments("anonymous method", "System.Func<int>").WithLocation(23, 12)); CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: @"FA(Action) FA(Delegate) FB(Delegate) FB(Func<int>) FA(Action) FA(Delegate) FB(Delegate) FB(Func<int>) FA(Action) FA(Delegate) FB(Delegate) FB(Func<int>) "); } [Fact] public void OverloadResolution_06() { var source = @"using System; using System.Linq.Expressions; class Program { static void Report(string name, Expression e) { Console.WriteLine(""{0}: {1}"", name, e); } static void F(Expression e) { Report(""F(Expression)"", e); } static void F(Expression<Func<int>> e) { Report(""F(Expression<Func<int>>)"", e); } static void Main() { F(() => 0); F(() => string.Empty); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (11,17): error CS0029: Cannot implicitly convert type 'string' to 'int' // F(() => string.Empty); Diagnostic(ErrorCode.ERR_NoImplicitConv, "string.Empty").WithArguments("string", "int").WithLocation(11, 17), // (11,17): error CS1662: Cannot convert lambda expression to intended delegate type because some of the return types in the block are not implicitly convertible to the delegate return type // F(() => string.Empty); Diagnostic(ErrorCode.ERR_CantConvAnonMethReturns, "string.Empty").WithArguments("lambda expression").WithLocation(11, 17)); CompileAndVerify(source, parseOptions: TestOptions.Regular10, expectedOutput: @"F(Expression<Func<int>>): () => 0 F(Expression): () => String.Empty "); } [Fact] public void OverloadResolution_07() { var source = @"using System; using System.Linq.Expressions; class Program { static void F(Expression e) { } static void F(Expression<Func<int>> e) { } static void Main() { F(delegate () { return 0; }); F(delegate () { return string.Empty; }); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (9,11): error CS1946: An anonymous method expression cannot be converted to an expression tree // F(delegate () { return 0; }); Diagnostic(ErrorCode.ERR_AnonymousMethodToExpressionTree, "delegate () { return 0; }").WithLocation(9, 11), // (10,11): error CS1946: An anonymous method expression cannot be converted to an expression tree // F(delegate () { return string.Empty; }); Diagnostic(ErrorCode.ERR_AnonymousMethodToExpressionTree, "delegate () { return string.Empty; }").WithLocation(10, 11)); } [Fact] public void ImplicitlyTypedVariables_01() { var source = @"using System; class Program { static void Main() { var d1 = Main; Report(d1); var d2 = () => { }; Report(d2); var d3 = delegate () { }; Report(d3); } static void Report(Delegate d) => Console.WriteLine(d.GetDelegateTypeName()); }"; var comp = CreateCompilation(new[] { source, s_utils }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe); comp.VerifyDiagnostics( // (6,18): error CS8773: Feature 'inferred delegate type' is not available in C# 9.0. Please use language version 10.0 or greater. // var d1 = Main; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "Main").WithArguments("inferred delegate type", "10.0").WithLocation(6, 18), // (8,18): error CS8773: Feature 'inferred delegate type' is not available in C# 9.0. Please use language version 10.0 or greater. // var d2 = () => { }; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "() => { }").WithArguments("inferred delegate type", "10.0").WithLocation(8, 18), // (10,18): error CS8773: Feature 'inferred delegate type' is not available in C# 9.0. Please use language version 10.0 or greater. // var d3 = delegate () { }; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "delegate () { }").WithArguments("inferred delegate type", "10.0").WithLocation(10, 18)); comp = CreateCompilation(new[] { source, s_utils }, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: @"System.Action System.Action System.Action"); verifier.VerifyIL("Program.Main", @"{ // Code size 100 (0x64) .maxstack 2 .locals init (System.Action V_0, //d1 System.Action V_1, //d2 System.Action V_2) //d3 IL_0000: nop IL_0001: ldnull IL_0002: ldftn ""void Program.Main()"" IL_0008: newobj ""System.Action..ctor(object, System.IntPtr)"" IL_000d: stloc.0 IL_000e: ldloc.0 IL_000f: call ""void Program.Report(System.Delegate)"" IL_0014: nop IL_0015: ldsfld ""System.Action Program.<>c.<>9__0_0"" IL_001a: dup IL_001b: brtrue.s IL_0034 IL_001d: pop IL_001e: ldsfld ""Program.<>c Program.<>c.<>9"" IL_0023: ldftn ""void Program.<>c.<Main>b__0_0()"" IL_0029: newobj ""System.Action..ctor(object, System.IntPtr)"" IL_002e: dup IL_002f: stsfld ""System.Action Program.<>c.<>9__0_0"" IL_0034: stloc.1 IL_0035: ldloc.1 IL_0036: call ""void Program.Report(System.Delegate)"" IL_003b: nop IL_003c: ldsfld ""System.Action Program.<>c.<>9__0_1"" IL_0041: dup IL_0042: brtrue.s IL_005b IL_0044: pop IL_0045: ldsfld ""Program.<>c Program.<>c.<>9"" IL_004a: ldftn ""void Program.<>c.<Main>b__0_1()"" IL_0050: newobj ""System.Action..ctor(object, System.IntPtr)"" IL_0055: dup IL_0056: stsfld ""System.Action Program.<>c.<>9__0_1"" IL_005b: stloc.2 IL_005c: ldloc.2 IL_005d: call ""void Program.Report(System.Delegate)"" IL_0062: nop IL_0063: ret }"); } [Fact] public void ImplicitlyTypedVariables_02() { var source = @"var d1 = object.ReferenceEquals; var d2 = () => { }; var d3 = delegate () { }; "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9.WithKind(SourceCodeKind.Script)); comp.VerifyDiagnostics( // (1,10): error CS8773: Feature 'inferred delegate type' is not available in C# 9.0. Please use language version 10.0 or greater. // var d1 = object.ReferenceEquals; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "object.ReferenceEquals").WithArguments("inferred delegate type", "10.0").WithLocation(1, 10), // (2,10): error CS8773: Feature 'inferred delegate type' is not available in C# 9.0. Please use language version 10.0 or greater. // var d2 = () => { }; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "() => { }").WithArguments("inferred delegate type", "10.0").WithLocation(2, 10), // (3,10): error CS8773: Feature 'inferred delegate type' is not available in C# 9.0. Please use language version 10.0 or greater. // var d3 = delegate () { }; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "delegate () { }").WithArguments("inferred delegate type", "10.0").WithLocation(3, 10)); comp = CreateCompilation(source, parseOptions: TestOptions.Regular10.WithKind(SourceCodeKind.Script)); comp.VerifyDiagnostics(); } [Fact] public void ImplicitlyTypedVariables_03() { var source = @"class Program { static void Main() { ref var d1 = Main; ref var d2 = () => { }; ref var d3 = delegate () { }; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (5,17): error CS8172: Cannot initialize a by-reference variable with a value // ref var d1 = Main; Diagnostic(ErrorCode.ERR_InitializeByReferenceVariableWithValue, "d1 = Main").WithLocation(5, 17), // (5,22): error CS1657: Cannot use 'Main' as a ref or out value because it is a 'method group' // ref var d1 = Main; Diagnostic(ErrorCode.ERR_RefReadonlyLocalCause, "Main").WithArguments("Main", "method group").WithLocation(5, 22), // (6,17): error CS8172: Cannot initialize a by-reference variable with a value // ref var d2 = () => { }; Diagnostic(ErrorCode.ERR_InitializeByReferenceVariableWithValue, "d2 = () => { }").WithLocation(6, 17), // (6,22): error CS1510: A ref or out value must be an assignable variable // ref var d2 = () => { }; Diagnostic(ErrorCode.ERR_RefLvalueExpected, "() => { }").WithLocation(6, 22), // (7,17): error CS8172: Cannot initialize a by-reference variable with a value // ref var d3 = delegate () { }; Diagnostic(ErrorCode.ERR_InitializeByReferenceVariableWithValue, "d3 = delegate () { }").WithLocation(7, 17), // (7,22): error CS1510: A ref or out value must be an assignable variable // ref var d3 = delegate () { }; Diagnostic(ErrorCode.ERR_RefLvalueExpected, "delegate () { }").WithLocation(7, 22)); } [Fact] public void ImplicitlyTypedVariables_04() { var source = @"class Program { static void Main() { using var d1 = Main; using var d2 = () => { }; using var d3 = delegate () { }; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (5,9): error CS1674: 'Action': type used in a using statement must be implicitly convertible to 'System.IDisposable'. // using var d1 = Main; Diagnostic(ErrorCode.ERR_NoConvToIDisp, "using var d1 = Main;").WithArguments("System.Action").WithLocation(5, 9), // (6,9): error CS1674: 'Action': type used in a using statement must be implicitly convertible to 'System.IDisposable'. // using var d2 = () => { }; Diagnostic(ErrorCode.ERR_NoConvToIDisp, "using var d2 = () => { };").WithArguments("System.Action").WithLocation(6, 9), // (7,9): error CS1674: 'Action': type used in a using statement must be implicitly convertible to 'System.IDisposable'. // using var d3 = delegate () { }; Diagnostic(ErrorCode.ERR_NoConvToIDisp, "using var d3 = delegate () { };").WithArguments("System.Action").WithLocation(7, 9)); } [Fact] public void ImplicitlyTypedVariables_05() { var source = @"class Program { static void Main() { foreach (var d1 in Main) { } foreach (var d2 in () => { }) { } foreach (var d3 in delegate () { }) { } } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (5,28): error CS0446: Foreach cannot operate on a 'method group'. Did you intend to invoke the 'method group'? // foreach (var d1 in Main) { } Diagnostic(ErrorCode.ERR_AnonMethGrpInForEach, "Main").WithArguments("method group").WithLocation(5, 28), // (6,28): error CS0446: Foreach cannot operate on a 'lambda expression'. Did you intend to invoke the 'lambda expression'? // foreach (var d2 in () => { }) { } Diagnostic(ErrorCode.ERR_AnonMethGrpInForEach, "() => { }").WithArguments("lambda expression").WithLocation(6, 28), // (7,28): error CS0446: Foreach cannot operate on a 'anonymous method'. Did you intend to invoke the 'anonymous method'? // foreach (var d3 in delegate () { }) { } Diagnostic(ErrorCode.ERR_AnonMethGrpInForEach, "delegate () { }").WithArguments("anonymous method").WithLocation(7, 28)); } [Fact] public void ImplicitlyTypedVariables_06() { var source = @"using System; class Program { static void Main() { Func<int> f; var d1 = Main; f = d1; var d2 = object (int x) => x; f = d2; var d3 = delegate () { return string.Empty; }; f = d3; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (8,13): error CS0029: Cannot implicitly convert type 'System.Action' to 'System.Func<int>' // f = d1; Diagnostic(ErrorCode.ERR_NoImplicitConv, "d1").WithArguments("System.Action", "System.Func<int>").WithLocation(8, 13), // (10,13): error CS0029: Cannot implicitly convert type 'System.Func<int, object>' to 'System.Func<int>' // f = d2; Diagnostic(ErrorCode.ERR_NoImplicitConv, "d2").WithArguments("System.Func<int, object>", "System.Func<int>").WithLocation(10, 13), // (12,13): error CS0029: Cannot implicitly convert type 'System.Func<string>' to 'System.Func<int>' // f = d3; Diagnostic(ErrorCode.ERR_NoImplicitConv, "d3").WithArguments("System.Func<string>", "System.Func<int>").WithLocation(12, 13)); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var variables = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Where(v => v.Initializer != null); var expectedInfo = new (string?, string?, string?)[] { ("System.Action d1", null, "System.Action"), ("System.Func<System.Int32, System.Object> d2", null, "System.Func<System.Int32, System.Object>"), ("System.Func<System.String> d3", null, "System.Func<System.String>"), }; AssertEx.Equal(expectedInfo, variables.Select(v => getVariableInfo(model, v))); static (string?, string?, string?) getVariableInfo(SemanticModel model, VariableDeclaratorSyntax variable) { var symbol = model.GetDeclaredSymbol(variable); var typeInfo = model.GetTypeInfo(variable.Initializer!.Value); return (symbol?.ToTestDisplayString(), typeInfo.Type?.ToTestDisplayString(), typeInfo.ConvertedType?.ToTestDisplayString()); } } [Fact] public void ImplicitlyTypedVariables_07() { var source = @"class Program { static void Main() { var t = (Main, () => { }); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (5,13): error CS0815: Cannot assign (method group, lambda expression) to an implicitly-typed variable // var t = (Main, () => { }); Diagnostic(ErrorCode.ERR_ImplicitlyTypedVariableAssignedBadValue, "t = (Main, () => { })").WithArguments("(method group, lambda expression)").WithLocation(5, 13)); } [Fact] public void ImplicitlyTypedVariables_08() { var source = @"class Program { static void Main() { (var x1, var y1) = Main; var (x2, y2) = () => { }; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (5,14): error CS8130: Cannot infer the type of implicitly-typed deconstruction variable 'x1'. // (var x1, var y1) = Main; Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, "x1").WithArguments("x1").WithLocation(5, 14), // (5,22): error CS8130: Cannot infer the type of implicitly-typed deconstruction variable 'y1'. // (var x1, var y1) = Main; Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, "y1").WithArguments("y1").WithLocation(5, 22), // (5,28): error CS8131: Deconstruct assignment requires an expression with a type on the right-hand-side. // (var x1, var y1) = Main; Diagnostic(ErrorCode.ERR_DeconstructRequiresExpression, "Main").WithLocation(5, 28), // (6,14): error CS8130: Cannot infer the type of implicitly-typed deconstruction variable 'x2'. // var (x2, y2) = () => { }; Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, "x2").WithArguments("x2").WithLocation(6, 14), // (6,18): error CS8130: Cannot infer the type of implicitly-typed deconstruction variable 'y2'. // var (x2, y2) = () => { }; Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, "y2").WithArguments("y2").WithLocation(6, 18), // (6,24): error CS8131: Deconstruct assignment requires an expression with a type on the right-hand-side. // var (x2, y2) = () => { }; Diagnostic(ErrorCode.ERR_DeconstructRequiresExpression, "() => { }").WithLocation(6, 24)); } [Fact] public void ImplicitlyTypedVariables_09() { var source = @"class Program { static void Main() { var (x, y) = (Main, () => { }); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (5,14): error CS8130: Cannot infer the type of implicitly-typed deconstruction variable 'x'. // var (x, y) = (Main, () => { }); 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) = (Main, () => { }); Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, "y").WithArguments("y").WithLocation(5, 17)); } [Fact] public void ImplicitlyTypedVariables_10() { var source = @"using System; class Program { static void Main() { (var x1, Action y1) = (Main, null); (Action x2, var y2) = (null, () => { }); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,14): error CS8130: Cannot infer the type of implicitly-typed deconstruction variable 'x1'. // (var x1, Action y1) = (Main, null); Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, "x1").WithArguments("x1").WithLocation(6, 14), // (7,25): error CS8130: Cannot infer the type of implicitly-typed deconstruction variable 'y2'. // (Action x2, var y2) = (null, () => { }); Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, "y2").WithArguments("y2").WithLocation(7, 25)); } [Fact] public void ImplicitlyTypedVariables_11() { var source = @"class Program { static void F(object o) { } static void F(int i) { } static void Main() { var d1 = F; var d2 = x => x; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (7,18): error CS8917: The delegate type could not be inferred. // var d1 = F; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "F").WithLocation(7, 18), // (8,18): error CS8917: The delegate type could not be inferred. // var d2 = x => x; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "x => x").WithLocation(8, 18)); } [Fact] public void ImplicitlyTypedVariables_12() { var source = @"class Program { static void F(ref int i) { } static void Main() { var d1 = F; var d2 = (ref int x) => x; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,18): error CS8917: The delegate type could not be inferred. // var d1 = F; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "F").WithLocation(6, 18), // (7,18): error CS8917: The delegate type could not be inferred. // var d2 = (ref int x) => x; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "(ref int x) => x").WithLocation(7, 18)); } [Fact] public void ImplicitlyTypedVariables_13() { var source = @"using System; class Program { static int F() => 0; static void Main() { var d1 = (F); Report(d1); var d2 = (object (int x) => x); Report(d2); var d3 = (delegate () { return string.Empty; }); Report(d3); } static void Report(Delegate d) => Console.WriteLine(d.GetDelegateTypeName()); }"; CompileAndVerify(new[] { source, s_utils }, options: TestOptions.DebugExe, expectedOutput: @"System.Func<System.Int32> System.Func<System.Int32, System.Object> System.Func<System.String>"); } [Fact] public void ImplicitlyTypedVariables_UseSiteErrors() { var source = @"class Program { static void F(object o) { } static void Main() { var d1 = F; var d2 = () => 1; } }"; var comp = CreateEmptyCompilation(source, new[] { GetCorlibWithInvalidActionAndFuncOfT() }); comp.VerifyDiagnostics( // (6,18): error CS0648: 'Action<T>' is a type not supported by the language // var d1 = F; Diagnostic(ErrorCode.ERR_BogusType, "F").WithArguments("System.Action<T>").WithLocation(6, 18), // (7,18): error CS0648: 'Func<T>' is a type not supported by the language // var d2 = () => 1; Diagnostic(ErrorCode.ERR_BogusType, "() => 1").WithArguments("System.Func<T>").WithLocation(7, 18)); } /// <summary> /// Ensure the conversion group containing the implicit /// conversion is handled correctly in NullableWalker. /// </summary> [Fact] public void NullableAnalysis_01() { var source = @"#nullable enable class Program { static void Main() { System.Delegate d; d = Main; d = () => { }; d = delegate () { }; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics(); } /// <summary> /// Ensure the conversion group containing the explicit /// conversion is handled correctly in NullableWalker. /// </summary> [Fact] public void NullableAnalysis_02() { var source = @"#nullable enable class Program { static void Main() { object o; o = (System.Delegate)Main; o = (System.Delegate)(() => { }); o = (System.Delegate)(delegate () { }); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics(); } [Fact] public void TaskRunArgument() { var source = @"using System.Threading.Tasks; class Program { static async Task F() { await Task.Run(() => { }); } }"; var verifier = CompileAndVerify(source, parseOptions: TestOptions.RegularPreview); var method = (MethodSymbol)verifier.TestData.GetMethodsByName()["Program.<>c.<F>b__0_0()"].Method; Assert.Equal("void Program.<>c.<F>b__0_0()", method.ToTestDisplayString()); verifier.VerifyIL("Program.<>c.<F>b__0_0()", @"{ // Code size 1 (0x1) .maxstack 0 IL_0000: ret }"); } } }
1
dotnet/roslyn
55,256
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-30T00:02:02Z
2021-07-30T09:17:54Z
6ce9c0048d37026337701fac035ac0745f6fe49f
88b59775dc6375635957ef229116460f290072aa
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Compilers/CSharp/Test/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 CS8773: Feature 'inferred delegate type' is not available in C# 9.0. Please use language version 10.0 or greater. // if (a.E! != null) // 2 Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "a.E").WithArguments("inferred delegate type", "10.0").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 CS8773: Feature 'inferred delegate type' is not available in C# 9.0. Please use language version 10.0 or greater. // if (a.F! != null) // 9 Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "a.F").WithArguments("inferred delegate type", "10.0").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(); CompileAndVerify(comp); } [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' 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' 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 calculcated 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,24): error CS1660: Cannot convert lambda expression to type 'object' because it is not a delegate type // object a = b ? () => s.ToString() : () => s?.ToString(); Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => s.ToString()").WithArguments("lambda expression", "object").WithLocation(7, 24), // (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), // (7,45): error CS1660: Cannot convert lambda expression to type 'object' because it is not a delegate type // object a = b ? () => s.ToString() : () => s?.ToString(); Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => s?.ToString()").WithArguments("lambda expression", "object").WithLocation(7, 45) ); } [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) { CSharpCompilation c = CreateCompilation(new[] { @" #nullable enable string? s = null; M($""{s = """"}{s.ToString()}"", 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, 30) ); } else { c.VerifyDiagnostics(); } } [Theory] [CombinatorialData] public void StringInterpolation_03(bool useBoolReturns, bool validityParameter) { CSharpCompilation c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; using System.Runtime.CompilerServices; #nullable enable string? s = """"; M( #line 1000 ref s, #line 2000 $"""", #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) { CSharpCompilation c = CreateCompilation(new[] { @" using System.Runtime.CompilerServices; #nullable enable string? s = null; M(s, $""""); 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) { CSharpCompilation c = CreateCompilation(new[] { @" using System.Runtime.CompilerServices; #nullable enable string? s = null; M($""{s}""); 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) { CSharpCompilation c = CreateCompilation(new[] { @" using System.Runtime.CompilerServices; #nullable enable string? s = """"; M($""{s = null}{s = """"}""); _ = 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( ); } } [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( // (5,11): error CS1503: Argument 1: cannot convert from 'method group' to 'object' // G(F!); Diagnostic(ErrorCode.ERR_BadArgType, "F").WithArguments("1", "method group", "object").WithLocation(5, 11), // (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( // (5,46): error CS0428: Cannot convert method group 'F' to non-delegate type 'object'. Did you intend to invoke the method? // var a = new object[] { new object(), F! }; Diagnostic(ErrorCode.ERR_MethGrpToNonDel, "F").WithArguments("F", "object").WithLocation(5, 46)); } [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 CS0428: Cannot convert method group 'F' to non-delegate type 'object'. Did you intend to invoke the method? // if (o is F) Diagnostic(ErrorCode.ERR_MethGrpToNonDel, "F").WithArguments("F", "object").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 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(3, 2), // (4,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(4, 2), // (4,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(4, 2), // (6,20): error CS8652: The 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 CS8652: The 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 CS8652: The 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 CS8652: The 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 CS8652: The 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 CS8652: The 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 CS8652: The 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 CS8652: The 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 CS8652: The 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 CS8652: The 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 CS8652: The 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 LambaReturnType_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 LambaReturnType_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 LambaReturnType_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 LambaReturnType_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] 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) ); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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(); CompileAndVerify(comp); } [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' 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' 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 calculcated 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,24): error CS1660: Cannot convert lambda expression to type 'object' because it is not a delegate type // object a = b ? () => s.ToString() : () => s?.ToString(); Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => s.ToString()").WithArguments("lambda expression", "object").WithLocation(7, 24), // (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), // (7,45): error CS1660: Cannot convert lambda expression to type 'object' because it is not a delegate type // object a = b ? () => s.ToString() : () => s?.ToString(); Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => s?.ToString()").WithArguments("lambda expression", "object").WithLocation(7, 45) ); } [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) { CSharpCompilation c = CreateCompilation(new[] { @" #nullable enable string? s = null; M($""{s = """"}{s.ToString()}"", 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, 30) ); } else { c.VerifyDiagnostics(); } } [Theory] [CombinatorialData] public void StringInterpolation_03(bool useBoolReturns, bool validityParameter) { CSharpCompilation c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; using System.Runtime.CompilerServices; #nullable enable string? s = """"; M( #line 1000 ref s, #line 2000 $"""", #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) { CSharpCompilation c = CreateCompilation(new[] { @" using System.Runtime.CompilerServices; #nullable enable string? s = null; M(s, $""""); 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) { CSharpCompilation c = CreateCompilation(new[] { @" using System.Runtime.CompilerServices; #nullable enable string? s = null; M($""{s}""); 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) { CSharpCompilation c = CreateCompilation(new[] { @" using System.Runtime.CompilerServices; #nullable enable string? s = """"; M($""{s = null}{s = """"}""); _ = 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( ); } } [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( // (5,11): error CS1503: Argument 1: cannot convert from 'method group' to 'object' // G(F!); Diagnostic(ErrorCode.ERR_BadArgType, "F").WithArguments("1", "method group", "object").WithLocation(5, 11), // (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( // (5,46): error CS0428: Cannot convert method group 'F' to non-delegate type 'object'. Did you intend to invoke the method? // var a = new object[] { new object(), F! }; Diagnostic(ErrorCode.ERR_MethGrpToNonDel, "F").WithArguments("F", "object").WithLocation(5, 46)); } [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 CS0428: Cannot convert method group 'F' to non-delegate type 'object'. Did you intend to invoke the method? // if (o is F) Diagnostic(ErrorCode.ERR_MethGrpToNonDel, "F").WithArguments("F", "object").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 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(3, 2), // (4,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(4, 2), // (4,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(4, 2), // (6,20): error CS8652: The 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 CS8652: The 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 CS8652: The 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 CS8652: The 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 CS8652: The 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 CS8652: The 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 CS8652: The 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 CS8652: The 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 CS8652: The 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 CS8652: The 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 CS8652: The 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 LambaReturnType_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 LambaReturnType_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 LambaReturnType_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 LambaReturnType_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] 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) ); } } }
1
dotnet/roslyn
55,256
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-30T00:02:02Z
2021-07-30T09:17:54Z
6ce9c0048d37026337701fac035ac0745f6fe49f
88b59775dc6375635957ef229116460f290072aa
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Compilers/CSharp/Test/Symbol/Symbols/ExtensionMethodTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.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 Utils = Microsoft.CodeAnalysis.CSharp.UnitTests.CompilationUtils; using static Roslyn.Test.Utilities.TestMetadata; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Symbols { public class ExtensionMethodTests : CSharpTestBase { [ClrOnlyFact] public void IsExtensionMethod() { var source = @"static class C { internal static void M1(object o) { } internal static void M2(this object o) { } internal static void M3<T, U>(this T t, U u) { } }"; Action<ModuleSymbol> validator = module => { var type = module.GlobalNamespace.GetMember<NamedTypeSymbol>("C"); // Ordinary method. var method = type.GetMember<MethodSymbol>("M1"); Assert.False(method.IsExtensionMethod); var parameter = method.Parameters[0]; Assert.Equal(SpecialType.System_Object, parameter.Type.SpecialType); // Extension method. method = type.GetMember<MethodSymbol>("M2"); Assert.True(method.IsExtensionMethod); parameter = method.Parameters[0]; Assert.Equal(SpecialType.System_Object, parameter.Type.SpecialType); // Extension method with type parameters. method = type.GetMember<MethodSymbol>("M3"); Assert.True(method.IsExtensionMethod); parameter = method.Parameters[0]; Assert.Equal(TypeKind.TypeParameter, parameter.Type.TypeKind); }; CompileAndVerify(source, validator: validator, options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal)); } /// <summary> /// IsExtensionMethod should be false for /// invalid extension methods. /// </summary> [Fact] public void InvalidExtensionMethods() { var ilSource = @".assembly extern mscorlib { .ver 4:0:0:0 .publickeytoken = (B7 7A 5C 56 19 34 E0 89) } .assembly extern System.Core {} .assembly '<<GeneratedFileName>>' { .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) } .class public C { .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) .method public static void M1() { .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) ret } .method public void M2(object o) { .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) ret } } .class public S { .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) .method public static void M1() { .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) ret } .method public static void M2([out] object& o) { .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) ret } .method public static void M3(object[] o) { .param [1] .custom instance void [mscorlib]System.ParamArrayAttribute::.ctor() = ( 01 00 00 00 ) .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) ret } } "; var source = @"class A { internal static C F = null; internal static S G = null; }"; var compilation = CreateCompilationWithILAndMscorlib40(source, ilSource, appendDefaultHeader: false); var refType = compilation.Assembly.GlobalNamespace.GetMember<NamedTypeSymbol>("A"); var type = (NamedTypeSymbol)refType.GetMember<FieldSymbol>("F").Type; // Static method no args. var method = type.GetMember<MethodSymbol>("M1"); Assert.Equal(0, method.Parameters.Length); Assert.True(method.IsStatic); Assert.False(method.IsExtensionMethod); // Instance method. method = type.GetMember<MethodSymbol>("M2"); Assert.Equal(1, method.Parameters.Length); Assert.False(method.IsStatic); Assert.False(method.IsExtensionMethod); type = (NamedTypeSymbol)refType.GetMember<FieldSymbol>("G").Type; // Static method no args. method = type.GetMember<MethodSymbol>("M1"); Assert.Equal(0, method.Parameters.Length); Assert.True(method.IsStatic); Assert.False(method.IsExtensionMethod); // Static method out param. method = type.GetMember<MethodSymbol>("M2"); Assert.Equal(1, method.Parameters.Length); Assert.True(method.IsStatic); Assert.False(method.IsExtensionMethod); // Static method params array. method = type.GetMember<MethodSymbol>("M3"); Assert.Equal(1, method.Parameters.Length); Assert.True(method.IsStatic); Assert.False(method.IsExtensionMethod); } [ClrOnlyFact] public void OverloadResolution() { var source = @"class C { void N() { this.M(3); (new C()).M(0.5); } } static class S { public static void M(this object o, int i) { } public static void M(this C c, int i) { } public static void M(this C c, double x) { } }"; CompileAndVerify(source); } [Fact] public void SameNameAsMember() { var source = @"class C { public object F = null; public object P { get; set; } public class T { } static void A(System.Action a) { } static void B(C c) { c.F(c.F); c.P(c.P); c.T(); A(c.F); A(c.P); A(((object)c).F); A(((object)c).P); } } static class S { public static void F(this object o) { } public static void F(this object x, object y) { } public static void P(this object o) { } public static void P(this object x, object y) { } public static void T(this object o) { } }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (12,11): error CS1503: Argument 1: cannot convert from 'object' to 'System.Action' Diagnostic(ErrorCode.ERR_BadArgType, "c.F").WithArguments("1", "object", "System.Action").WithLocation(12, 11), // (13,11): error CS1503: Argument 1: cannot convert from 'object' to 'System.Action' Diagnostic(ErrorCode.ERR_BadArgType, "c.P").WithArguments("1", "object", "System.Action").WithLocation(13, 11)); } [WorkItem(529063, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529063")] [Fact] public void GetSymbolInfoTest() { var source = @"static class S { static void Goo(this string s) { } static void Main() { string s = null; s.Goo(); } }"; var compilation = CreateCompilation(source); var syntaxTree = compilation.SyntaxTrees.Single(); var gooSymbol = (IMethodSymbol)compilation.GetSemanticModel(syntaxTree).GetSymbolInfo( syntaxTree.GetCompilationUnitRoot().DescendantNodes().OfType<MemberAccessExpressionSyntax>().Single()).Symbol; Assert.True(gooSymbol.IsExtensionMethod); Assert.Equal(MethodKind.ReducedExtension, gooSymbol.MethodKind); var gooOriginal = gooSymbol.ReducedFrom; Assert.True(gooOriginal.IsExtensionMethod); Assert.Equal(MethodKind.Ordinary, gooOriginal.MethodKind); } [Fact] public void InaccessibleExtensionMethodSameNameAsMember() { var source = @"class C { public object F = null; public object P { get; set; } static void A(System.Action a) { } static void B(C c) { c.F(); c.P(); A(c.F); A(c.P); } } static class S { private static void F(this object o) { } private static void P(this object o) { } }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (8,11): error CS1955: Non-invocable member 'C.F' cannot be used like a method. // c.F(); Diagnostic(ErrorCode.ERR_NonInvocableMemberCalled, "F").WithArguments("C.F"), // (9,11): error CS1955: Non-invocable member 'C.P' cannot be used like a method. // c.P(); Diagnostic(ErrorCode.ERR_NonInvocableMemberCalled, "P").WithArguments("C.P"), // (10,11): error CS1503: Argument 1: cannot convert from 'object' to 'System.Action' Diagnostic(ErrorCode.ERR_BadArgType, "c.F").WithArguments("1", "object", "System.Action").WithLocation(10, 11), // (11,11): error CS1503: Argument 1: cannot convert from 'object' to 'System.Action' Diagnostic(ErrorCode.ERR_BadArgType, "c.P").WithArguments("1", "object", "System.Action").WithLocation(11, 11)); } [ClrOnlyFact] public void ExtensionMethodInTheSameClass() { var source = @"using System; static class Program { static void Main() { ""ABC"".Goo(); Action a = ""123"".Goo; a(); a = new Action(a); a(); a = new Action(""xyz"".Goo); a(); } static void Goo(this string x) { Console.WriteLine(x); } }"; CompileAndVerify(source, expectedOutput: @"ABC 123 123 xyz"); } [WorkItem(541143, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541143")] [ClrOnlyFact] public void NumericConversionsAreNotAllowed() { var source = @" using System; static class Program { static void Main() { 0.Goo(); } static void Goo(this long x) { Console.WriteLine(""long""); } static void Goo(this object x) { Console.WriteLine(""object""); } } "; CompileAndVerify(source, expectedOutput: "object"); } [WorkItem(541144, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541144")] [ClrOnlyFact] public void EnumerationConversionsAreNotAllowed() { var source = @" using System; static class Program { static void Main() { 0.Goo(); } static void Goo(this DayOfWeek x) { Console.WriteLine(""DayOfWeek""); } static void Goo(this object x) { Console.WriteLine(""object""); } } "; CompileAndVerify(source, expectedOutput: "object"); } [WorkItem(541145, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541145")] [ClrOnlyFact] public void CannotCreateDelegateToExtensionMethodOnValueType() { var source = @" using System; static class Program { static void Main() { Bar(x => x.Goo); } static void Bar(Func<int, Action> x) { Console.WriteLine(1); } static void Bar(Func<object, Action> x) { Console.WriteLine(2); } static void Goo<T>(this T x) { } } "; CompileAndVerify(source, expectedOutput: "2"); } [WorkItem(528426, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528426")] [ClrOnlyFact] public void TypedReferenceCannotBeUsedAsTypeArgument() { var source = @" using System; static class Program { static void Main() { Bar(y => new TypedReference().Goo(y)); } static void Bar(Action<string> a) { Console.WriteLine(1); } static void Bar(Action<int> a) { Console.WriteLine(2); } static void Goo<T>(this T x, string y) { } static void Goo(this TypedReference x, int y) { } } "; CompileAndVerify(source, expectedOutput: "2"); } [WorkItem(541146, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541146")] [WorkItem(868538, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/868538")] [Fact] public void VariablesUsedInExtensionMethodGroupMustBeDefinitelyAssigned() { var source = @" using System; static class Program { static void Main() { string s; bool x = s.Goo is Action; int i; bool y = i.Goo is Action; } static void Goo(this string x) { } } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (9,18): error CS0837: The first operand of an 'is' or 'as' operator may not be a lambda expression, anonymous method, or method group. // bool x = s.Goo is Action; Diagnostic(ErrorCode.ERR_LambdaInIsAs, "s.Goo is Action").WithLocation(9, 18), // (12,18): error CS0837: The first operand of an 'is' or 'as' operator may not be a lambda expression, anonymous method, or method group. // bool y = i.Goo is Action; Diagnostic(ErrorCode.ERR_LambdaInIsAs, "i.Goo is Action").WithLocation(12, 18), // (9,18): error CS0165: Use of unassigned local variable 's' // bool x = s.Goo is Action; Diagnostic(ErrorCode.ERR_UseDefViolation, "s").WithArguments("s").WithLocation(9, 18), // (12,18): error CS0165: Use of unassigned local variable 'i' // bool y = i.Goo is Action; Diagnostic(ErrorCode.ERR_UseDefViolation, "i").WithArguments("i").WithLocation(12, 18) ); } [WorkItem(541187, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541187")] [Fact] public void ExtensionMethodsCannotBeDeclaredInNamespaces() { var source = @" namespace N { static void Goo(this int x) { } } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (4,17): error CS0116: A namespace does not directly contain members such as fields or methods Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "Goo"), // (4,17): error CS1106: Extension methods must be defined in a non-generic static class Diagnostic(ErrorCode.ERR_BadExtensionAgg, "Goo")); } [WorkItem(541189, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541189")] [ClrOnlyFact] public void ExtensionMethodsDeclaredInEnclosingNamespaceArePreferredOverImported2() { var source = @" using System; using N; static class Program { static void Main() { """".Goo(1); } public static void Goo(this string x, object y) { Console.WriteLine(1); } } namespace N { static class C { public static void Goo(this string x, int y) { Console.WriteLine(2); } } }"; CompileAndVerify(source, expectedOutput: "1"); } [WorkItem(541189, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541189")] [ClrOnlyFact] public void ExtensionMethodsDeclaredInEnclosingNamespaceArePreferredOverImported() { var source = @" using System; using N; static class Program { static void Main() { """".Goo(); } public static void Goo(this string x) { Console.WriteLine(1); } } namespace N { static class C { public static void Goo(this string x) { Console.WriteLine(2); } } } "; CompileAndVerify(source, expectedOutput: "1"); } [ClrOnlyFact] public void CandidateSearchByArgType() { var source = @"static class A { public static void E(this object o, double d) { } } namespace N1 { static class B { public static void E(this object o, bool b) { } } } namespace N1.N2 { static class C { public static void E(this object o, int i) { } static void Main() { 1.E(2.0); } } }"; CompileAndVerify(source); } [ClrOnlyFact] public void CandidateSearchConversion() { var source = @"interface I<T> { } namespace N { class C { static void M() { object o = 1.F1(); o = 2.F2(); o = 3.F3(1, 2, 3); } } static class S1 { internal static void F1<T>(this I<T> t) { } internal static void F2(this double d) { } internal static void F3(this long l, params object[] args) { } } } static class S2 { internal static object F1<T>(this T t) { return null; } internal static object F2(this int i) { return null; } internal static object F3(this int i, params object[] args) { return null; } }"; CompileAndVerify(source); } /// <summary> /// Continue search for extension method candidates in certain /// cases where nearer candidates are not applicable. /// </summary> [Fact] public void CandidateSearch() { var source = @"namespace N1 { namespace N2 { partial class C { // Invalid calls with no extension methods in scope. void M() { this.M1(1, 2, 3); // MethodResolutionKind.NoCorrespondingParameter this.M2(1); // MethodResolutionKind.RequiredParameterMissing this.M3(1, 2.0); // MethodResolutionKind.BadArguments this.M4(null, 2); // MethodResolutionKind.TypeInferenceFailed this.M5<string, string>(null, 2); // Bad arity this.M6(null, null); // Ambiguous } void M1(int x, int y) { } void M2(int x, int y) { } void M3(int x, int y) { } void M3(int x, long y) { } void M4<T>(T x, int y) { } void M4<T>(T x, long y) { } void M5<T>(T x, int y) { } void M5<T>(T x, long y) { } void M6(object x, string y) { } void M6(string x, object y) { } } } } namespace N1 { using N4; namespace N2 { using N3; partial class C { // Same calls as above but with N3.S and N4.S extension methods in scope. void N() { this.M1(1, 2, 3); // MethodResolutionKind.NoCorrespondingParameter this.M2(1); // MethodResolutionKind.RequiredParameterMissing this.M3(1, 2.0); // MethodResolutionKind.BadArguments this.M4(null, 2); // MethodResolutionKind.TypeInferenceFailed this.M5<string, string>(null, 2); // Bad arity this.M6(null, null); // Ambiguous } } } } namespace N3 { static class S { // Same signatures as instance methods above. public static void M1(this N1.N2.C c, int x, int y) { } public static void M2(this N1.N2.C c, int x, int y) { } public static void M3(this N1.N2.C c, int x, int y) { } public static void M3(this N1.N2.C c, int x, long y) { } public static void M4<T>(this N1.N2.C c, T x, int y) { } public static void M4<T>(this N1.N2.C c, T x, long y) { } public static void M5<T>(this N1.N2.C c, T x, int y) { } public static void M5<T>(this N1.N2.C c, T x, long y) { } public static void M6(this N1.N2.C c, object x, string y) { } public static void M6(this N1.N2.C c, string x, object y) { } } } namespace N4 { static class S { // Different signatures but also resulting in errors. public static void M1(this N1.N2.C c, string x, int y, int z) { } public static void M2(this N1.N2.C c, string x) { } public static void M3(this N1.N2.C c, string x) { } public static void M4(this N1.N2.C c, int x, int y) { } public static void M5<T, U>(this N1.N2.C c, T x, T y) { } public static void M6(this N1.N2.C c, int x, int y) { } } }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (10,17): error CS1501: No overload for method 'M1' takes 3 arguments // this.M1(1, 2, 3); // MethodResolutionKind.NoCorrespondingParameter Diagnostic(ErrorCode.ERR_BadArgCount, "M1").WithArguments("M1", "3").WithLocation(10, 22), // (11,17): error CS7036: There is no argument given that corresponds to the required formal parameter 'y' of 'N1.N2.C.M2(int, int)' // this.M2(1); // MethodResolutionKind.RequiredParameterMissing Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "M2").WithArguments("y", "N1.N2.C.M2(int, int)").WithLocation(11, 22), // (12,28): error CS1503: Argument 2: cannot convert from 'double' to 'int' // this.M3(1, 2.0); // MethodResolutionKind.BadArguments Diagnostic(ErrorCode.ERR_BadArgType, "2.0").WithArguments("2", "double", "int").WithLocation(12, 28), // (13,17): error CS0411: The type arguments for method 'N1.N2.C.M4<T>(T, int)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // this.M4(null, 2); // MethodResolutionKind.TypeInferenceFailed Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M4").WithArguments("N1.N2.C.M4<T>(T, int)").WithLocation(13, 22), // (14,22): error CS0305: Using the generic method 'N1.N2.C.M5<T>(T, int)' requires 1 type arguments // this.M5<string, string>(null, 2); // Bad arity Diagnostic(ErrorCode.ERR_BadArity, "M5<string, string>").WithArguments("N1.N2.C.M5<T>(T, int)", "method", "1").WithLocation(14, 22), // (15,17): error CS0121: The call is ambiguous between the following methods or properties: 'N1.N2.C.M6(object, string)' and 'N1.N2.C.M6(string, object)' // this.M6(null, null); // Ambiguous Diagnostic(ErrorCode.ERR_AmbigCall, "M6").WithArguments("N1.N2.C.M6(object, string)", "N1.N2.C.M6(string, object)").WithLocation(15, 22), // (41,17): error CS1501: No overload for method 'M1' takes 3 arguments // this.M1(1, 2, 3); // MethodResolutionKind.NoCorrespondingParameter Diagnostic(ErrorCode.ERR_BadArgCount, "M1").WithArguments("M1", "3").WithLocation(41, 22), // (42,17): error CS7036: There is no argument given that corresponds to the required formal parameter 'y' of 'N1.N2.C.M2(int, int)' // this.M2(1); // MethodResolutionKind.RequiredParameterMissing Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "M2").WithArguments("y", "N1.N2.C.M2(int, int)").WithLocation(42, 22), // (43,28): error CS1503: Argument 2: cannot convert from 'double' to 'int' // this.M3(1, 2.0); // MethodResolutionKind.BadArguments Diagnostic(ErrorCode.ERR_BadArgType, "2.0").WithArguments("2", "double", "int").WithLocation(43, 28), // (44,17): error CS0411: The type arguments for method 'N1.N2.C.M4<T>(T, int)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // this.M4(null, 2); // MethodResolutionKind.TypeInferenceFailed Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M4").WithArguments("N1.N2.C.M4<T>(T, int)").WithLocation(44, 22), // (45,47): error CS1503: Argument 3: cannot convert from 'int' to 'string' // this.M5<string, string>(null, 2); // Bad arity Diagnostic(ErrorCode.ERR_BadArgType, "2").WithArguments("3", "int", "string").WithLocation(45, 47), // (46,17): error CS0121: The call is ambiguous between the following methods or properties: 'N1.N2.C.M6(object, string)' and 'N1.N2.C.M6(string, object)' // this.M6(null, null); // Ambiguous Diagnostic(ErrorCode.ERR_AmbigCall, "M6").WithArguments("N1.N2.C.M6(object, string)", "N1.N2.C.M6(string, object)").WithLocation(46, 22)); } /// <summary> /// End search for extension method candidates /// if current method group is ambiguous. /// </summary> [Fact] public void EndSearchIfAmbiguous() { var source = @"namespace N1 { internal static class S { public static void E(this object o, int x, object y) { } public static void E(this object o, double x, int y) { } public static void E(this object o, A x, B y) { } } class A { } class B { } namespace N2 { internal static class S { public static void E(this object o, double x, A y) { } public static void E(this object o, double x, B y) { } } class C { static void M(object o) { o.E(1, null); // ambiguous o.E(1.0, 2.0); // N2.S.E(object, double, A) o.E(1.0, 2); // N1.S.E(object, double, int) o.E(null, null); // N1.S.E(object, A, B) } } } }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (22,17): error CS0121: The call is ambiguous between the following methods or properties: 'N1.N2.S.E(object, double, N1.A)' and 'N1.N2.S.E(object, double, N1.B)' Diagnostic(ErrorCode.ERR_AmbigCall, "E").WithArguments("N1.N2.S.E(object, double, N1.A)", "N1.N2.S.E(object, double, N1.B)").WithLocation(22, 19), // (23,26): error CS1503: Argument 3: cannot convert from 'double' to 'N1.A' Diagnostic(ErrorCode.ERR_BadArgType, "2.0").WithArguments("3", "double", "N1.A").WithLocation(23, 26)); } [Fact(Skip = "528425")] public void ParenthesizedMethodGroup() { var source = @"static class S { public static void E(this object a, object b) { } public static void E(this object o, int i) { } private static void E(this object o, object x, object y) { } } class C { void E(int i, int j) { } void M() { ((this.E))(null); ((this.E))(null, null); } }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (13, 9): error CS0122: 'S.E(object, object, object)' is inaccessible due to its protection level Diagnostic(ErrorCode.ERR_BadAccess, "((this.E))(null, null)").WithArguments("S.E(object, object, object)").WithLocation(13, 9)); } [ClrOnlyFact] public void DelegateMembers() { var source = @"using System; class C { public Action<int> F = A; public Action<int> P { get { return A; } } static void A(int i) { Console.WriteLine(i); } static void Main() { C c = new C(); c.F(1); c.P(2); } }"; CompileAndVerify(source, expectedOutput: @"1 2"); } [Fact] public void DelegatesAndExtensionMethods() { var source = @"using System; class C { public Action<int> F = A; public Action<int> P { get { return A; } } static void A(int i) { } void M() { this.F(1, 2); this.P(1.0); } } class D { void F(int i) { } void P(int i) { } void M() { this.F(1, 2); this.P(2.0); } } static class S { public static void F(this object o, int x, int y) { } public static void P(this object o, double d) { } }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (9, 9): error CS1593: Delegate 'System.Action<int>' does not take 2 arguments Diagnostic(ErrorCode.ERR_BadDelArgCount, "F").WithArguments("System.Action<int>", "2").WithLocation(9, 14), // (10,16): error CS1503: Argument 1: cannot convert from 'double' to 'int' Diagnostic(ErrorCode.ERR_BadArgType, "1.0").WithArguments("1", "double", "int").WithLocation(10, 16)); } [ClrOnlyFact] public void DelegatesFromOverloads() { var source = @"namespace N { class C { void M(System.Action<object> a) { M(this.F); a = this.F; C c = new C(); M(c.G); a = c.G; } } static class A { internal static void G(this C c) { } } } static class B { internal static void F(this object o) { } internal static void F(this object x, object y) { } internal static void G(this object x, object y) { } }"; var compilation = CompileAndVerify(source); compilation.VerifyIL("N.C.M", @"{ // Code size 71 (0x47) .maxstack 3 .locals init (N.C V_0) //c IL_0000: ldarg.0 IL_0001: ldarg.0 IL_0002: ldftn ""void B.F(object, object)"" IL_0008: newobj ""System.Action<object>..ctor(object, System.IntPtr)"" IL_000d: call ""void N.C.M(System.Action<object>)"" IL_0012: ldarg.0 IL_0013: ldftn ""void B.F(object, object)"" IL_0019: newobj ""System.Action<object>..ctor(object, System.IntPtr)"" IL_001e: starg.s V_1 IL_0020: newobj ""N.C..ctor()"" IL_0025: stloc.0 IL_0026: ldarg.0 IL_0027: ldloc.0 IL_0028: ldftn ""void B.G(object, object)"" IL_002e: newobj ""System.Action<object>..ctor(object, System.IntPtr)"" IL_0033: call ""void N.C.M(System.Action<object>)"" IL_0038: ldloc.0 IL_0039: ldftn ""void B.G(object, object)"" IL_003f: newobj ""System.Action<object>..ctor(object, System.IntPtr)"" IL_0044: starg.s V_1 IL_0046: ret }"); } [ClrOnlyFact] public void DelegatesAsArguments() { var source = @"using System; namespace N { class C { static void M(object o) { o.M1(o.F1); // S1.M1(S1.F1) o.M1(o.F2); // S1.M1(S2.F2) o.M2(o.F3); // S2.M2(S1.F3) o.M2(o.F4); // S2.M2(S2.F4) } } static class S1 { internal static void M1(this object o, Action<object> f) { } internal static void M2(this object o, Action f) { } internal static void F1(this object x, object y) { } internal static void F2(this object x, int y) { } internal static void F3(this object x, object y) { } internal static void F4(this object x, int y) { } } } static class S2 { internal static void M1(this object o, Action f) { } internal static void M2(this object o, Action<object> f) { } internal static void F1(this object x, int y) { } internal static void F2(this object x, object y) { } internal static void F3(this object x, int y) { } internal static void F4(this object x, object y) { } }"; var compilation = CompileAndVerify(source); compilation.VerifyIL("N.C.M", @" { // Code size 73 (0x49) .maxstack 3 IL_0000: ldarg.0 IL_0001: ldarg.0 IL_0002: ldftn ""void N.S1.F1(object, object)"" IL_0008: newobj ""System.Action<object>..ctor(object, System.IntPtr)"" IL_000d: call ""void N.S1.M1(object, System.Action<object>)"" IL_0012: ldarg.0 IL_0013: ldarg.0 IL_0014: ldftn ""void S2.F2(object, object)"" IL_001a: newobj ""System.Action<object>..ctor(object, System.IntPtr)"" IL_001f: call ""void N.S1.M1(object, System.Action<object>)"" IL_0024: ldarg.0 IL_0025: ldarg.0 IL_0026: ldftn ""void N.S1.F3(object, object)"" IL_002c: newobj ""System.Action<object>..ctor(object, System.IntPtr)"" IL_0031: call ""void S2.M2(object, System.Action<object>)"" IL_0036: ldarg.0 IL_0037: ldarg.0 IL_0038: ldftn ""void S2.F4(object, object)"" IL_003e: newobj ""System.Action<object>..ctor(object, System.IntPtr)"" IL_0043: call ""void S2.M2(object, System.Action<object>)"" IL_0048: ret }"); } [Fact] public void DelegatesFromInvalidOverloads() { var source = @"namespace N { class C { static void M1(System.Func<object, object> f) { } static void M2(System.Action<object> f) { } static void M() { C c = new C(); M1(c.F1); // wrong return type M2(c.F1); M1(c.F2); M2(c.F2); // wrong return type M1(c.F3); // ambiguous } } static class S1 { internal static void F1(this C c) { } internal static object F2(this C c) { return null; } } } static class S2 { internal static void F1(this object x, object y) { } internal static object F2(this N.C x, object y) { return null; } internal static object F3(this N.C x, object y) { return null; } } static class S3 { internal static object F3(this N.C x, object y) { return null; } }"; CreateCompilationWithMscorlib40(source, references: new[] { Net40.SystemCore }, parseOptions: TestOptions.WithoutImprovedOverloadCandidates).VerifyDiagnostics( // (10,16): error CS0407: 'void S2.F1(object, object)' has the wrong return type // M1(c.F1); // wrong return type Diagnostic(ErrorCode.ERR_BadRetType, "c.F1").WithArguments("S2.F1(object, object)", "void").WithLocation(10, 16), // (13,16): error CS0407: 'object S2.F2(C, object)' has the wrong return type // M2(c.F2); // wrong return type Diagnostic(ErrorCode.ERR_BadRetType, "c.F2").WithArguments("S2.F2(N.C, object)", "object").WithLocation(13, 16), // (14,16): error CS0121: The call is ambiguous between the following methods or properties: 'S2.F3(C, object)' and 'S3.F3(C, object)' // M1(c.F3); // ambiguous Diagnostic(ErrorCode.ERR_AmbigCall, "c.F3").WithArguments("S2.F3(N.C, object)", "S3.F3(N.C, object)").WithLocation(14, 16)); // NOTE: we have a degradation in the quality of diagnostics for a delegate conversion in this particular failure case. // See https://github.com/dotnet/roslyn/issues/24787 // It is caused by a combination of two shortcomings in the computation of diagnostics. First, in `BindExtensionMethod` // when we fail to find an applicable extension method, we only report a diagnostic for the first extension method group // that failed, even if some other extension method group contains a much better candidate. In the case of this test the first // extension method group contains a method with the wrong number of parameters, while the second one has an extension method // that fails only because of its return type mismatch. Second, in // `OverloadResolutionResult<TMember>.ReportDiagnostics<T>`, we do not report a diagnostic for the failure // `MemberResolutionKind.NoCorrespondingParameter`, leaving it to the caller to notice that we failed to produce a // diagnostic (the caller has to grub through the diagnostic bag to see that there is no error there) and then the caller // has to produce a generic error message, which we see below. It does not appear that all callers have that test, though, // suggesting there may be a latent bug of missing diagnostics. CreateCompilationWithMscorlib40(source, references: new[] { Net40.SystemCore }).VerifyDiagnostics( // (10,16): error CS1503: Argument 1: cannot convert from 'method group' to 'Func<object, object>' // M1(c.F1); // wrong return type Diagnostic(ErrorCode.ERR_BadArgType, "c.F1").WithArguments("1", "method group", "System.Func<object, object>").WithLocation(10, 16), // (13,16): error CS1503: Argument 1: cannot convert from 'method group' to 'Action<object>' // M2(c.F2); // wrong return type Diagnostic(ErrorCode.ERR_BadArgType, "c.F2").WithArguments("1", "method group", "System.Action<object>").WithLocation(13, 16), // (14,16): error CS0121: The call is ambiguous between the following methods or properties: 'S2.F3(C, object)' and 'S3.F3(C, object)' // M1(c.F3); // ambiguous Diagnostic(ErrorCode.ERR_AmbigCall, "c.F3").WithArguments("S2.F3(N.C, object)", "S3.F3(N.C, object)").WithLocation(14, 16)); } [Fact] public void DelegatesAsInvalidArguments() { var source = @"class A { } class B { } delegate A DA(DA a); delegate B DB(DB b); class C { static void M() { M1(F); M2(F); M1(G(F)); M2(G(F)); } static void M1(DA f) { } static void M2(DB f) { } static A F(DA a) { return null; } static B F(DB b) { return null; } static DA G(DA f) { return f; } static DB G(DB f) { return f; } } namespace N { class C { static void M(object o) { o.M1(o.F); o.M2(o.F); o.M1(G(o.F)); o.M2(G(o.F)); } static DA G(DA f) { return f; } static DB G(DB f) { return f; } } static class S1 { internal static void M1(this object o, DA f) { } internal static void M2(this object o, DB f) { } internal static A F(this object o, DA a) { return null; } } } static class S2 { internal static B F(this object o, DB b) { return null; } }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (11,12): error CS0121: The call is ambiguous between the following methods or properties: 'C.G(DA)' and 'C.G(DB)' Diagnostic(ErrorCode.ERR_AmbigCall, "G").WithArguments("C.G(DA)", "C.G(DB)").WithLocation(11, 12), // (12,12): error CS0121: The call is ambiguous between the following methods or properties: 'C.G(DA)' and 'C.G(DB)' Diagnostic(ErrorCode.ERR_AmbigCall, "G").WithArguments("C.G(DA)", "C.G(DB)").WithLocation(12, 12), // (29,18): error CS0121: The call is ambiguous between the following methods or properties: 'N.C.G(DA)' and 'N.C.G(DB)' Diagnostic(ErrorCode.ERR_AmbigCall, "G").WithArguments("N.C.G(DA)", "N.C.G(DB)").WithLocation(29, 18), // (30,18): error CS0121: The call is ambiguous between the following methods or properties: 'N.C.G(DA)' and 'N.C.G(DB)' Diagnostic(ErrorCode.ERR_AmbigCall, "G").WithArguments("N.C.G(DA)", "N.C.G(DB)").WithLocation(30, 18)); } /// <summary> /// Extension methods should be resolved correctly even /// in cases where a method group is not allowed. /// </summary> [Fact] public void InvalidUseOfExtensionMethodGroup() { var source = @"class C { static void M(object o) { o.E += o.E; if (o.E != null) { M(o.E); o.E.ToString(); o = !o.E; } o.F += o.F; if (o.F != null) { M(o.F); o.F.ToString(); o = !o.F; } o.E.F(); } } static class S { internal static object E(this object o) { return null; } private static object F(this object o) { return null; } }"; var compilation = CreateCompilation(source, parseOptions: TestOptions.Regular9); compilation.VerifyDiagnostics( // (5,9): error CS1656: Cannot assign to 'E' because it is a 'method group' // o.E += o.E; Diagnostic(ErrorCode.ERR_AssgReadonlyLocalCause, "o.E").WithArguments("E", "method group").WithLocation(5, 9), // (6,13): error CS8773: Feature 'inferred delegate type' is not available in C# 9.0. Please use language version 10.0 or greater. // if (o.E != null) Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "o.E").WithArguments("inferred delegate type", "10.0").WithLocation(6, 13), // (8,15): error CS1503: Argument 1: cannot convert from 'method group' to 'object' // M(o.E); Diagnostic(ErrorCode.ERR_BadArgType, "o.E").WithArguments("1", "method group", "object").WithLocation(8, 15), // (9,15): error CS0119: 'S.E(object)' is a method, which is not valid in the given context // o.E.ToString(); Diagnostic(ErrorCode.ERR_BadSKunknown, "E").WithArguments("S.E(object)", "method").WithLocation(9, 15), // (10,17): error CS0023: Operator '!' cannot be applied to operand of type 'method group' // o = !o.E; Diagnostic(ErrorCode.ERR_BadUnaryOp, "!o.E").WithArguments("!", "method group").WithLocation(10, 17), // (12,11): error CS1061: 'object' does not contain a definition for 'F' and no accessible extension method 'F' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?) // o.F += o.F; Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "F").WithArguments("object", "F").WithLocation(12, 11), // (12,18): error CS1061: 'object' does not contain a definition for 'F' and no accessible extension method 'F' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?) // o.F += o.F; Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "F").WithArguments("object", "F").WithLocation(12, 18), // (13,15): error CS1061: 'object' does not contain a definition for 'F' and no accessible extension method 'F' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?) // if (o.F != null) Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "F").WithArguments("object", "F").WithLocation(13, 15), // (15,17): error CS1061: 'object' does not contain a definition for 'F' and no accessible extension method 'F' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?) // M(o.F); Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "F").WithArguments("object", "F").WithLocation(15, 17), // (16,15): error CS1061: 'object' does not contain a definition for 'F' and no accessible extension method 'F' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?) // o.F.ToString(); Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "F").WithArguments("object", "F").WithLocation(16, 15), // (17,20): error CS1061: 'object' does not contain a definition for 'F' and no accessible extension method 'F' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?) // o = !o.F; Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "F").WithArguments("object", "F").WithLocation(17, 20), // (19,11): error CS0119: 'S.E(object)' is a method, which is not valid in the given context // o.E.F(); Diagnostic(ErrorCode.ERR_BadSKunknown, "E").WithArguments("S.E(object)", "method").WithLocation(19, 11) ); } [Fact] public void Inaccessible() { var source = @"using System; class C { static void M(object o) { o.F(); M(o.F); Action a = o.F; o = o.F; } static void M(Action a) { } } static class S { static void F(this object o) { } }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (6,11): error CS1061: 'object' does not contain a definition for 'F' and no extension method 'F' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?) // o.F(); Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "F").WithArguments("object", "F").WithLocation(6, 11), // (7,13): error CS1061: 'object' does not contain a definition for 'F' and no extension method 'F' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?) // M(o.F); Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "F").WithArguments("object", "F").WithLocation(7, 13), // (8,22): error CS1061: 'object' does not contain a definition for 'F' and no extension method 'F' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?) // Action a = o.F; Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "F").WithArguments("object", "F").WithLocation(8, 22), // (9,15): error CS1061: 'object' does not contain a definition for 'F' and no extension method 'F' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?) // o = o.F; Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "F").WithArguments("object", "F").WithLocation(9, 15) ); } [Fact(Skip = "528425")] public void InaccessibleAndAccessible() { var source = @"using System; namespace N { class C { static void M(object o) { o.F(null); o.F(); M1(o.F); M2(o.F); Action<object> a = o.F; Action b = o.F; o.G(); // no error } static void M1(Action<object> a) { } static void M2(Action a) { } } static class S1 { static void F(this object o) { } internal static void F(this object x, object y) { } static void G(this object o) { } } } static class S2 { internal static void G(this object o) { } }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (9,9): error CS0122: 'S.F(object)' is inaccessible due to its protection level Diagnostic(ErrorCode.ERR_BadAccess, "F").WithArguments("S.F(object)").WithLocation(9, 9), // (11,9): error CS1503: Argument 1: cannot convert from 'method group' to 'System.Action' Diagnostic(ErrorCode.ERR_BadArgType, "o.F").WithArguments("1", "method group", "System.Action").WithLocation(11, 9), // (13,20): error CS0122: 'S.F(object)' is inaccessible due to its protection level Diagnostic(ErrorCode.ERR_BadAccess, "F").WithArguments("S.F(object)").WithLocation(13, 20)); } /// <summary> /// Inaccessible instance member and /// extension method of same name. /// </summary> [Fact] public void InaccessibleInstanceMember() { var source = @"using System; class A { void F() { } Action G; A H; } namespace N1 { class B { // No extension methods. static void M(A a) { a.F(); a.G(); a.H(); M(a.F); M(a.G); M(a.H); } static void M(Action a) { } } } namespace N2 { class C { // Valid extension methods. static void M(A a) { a.F(); a.G(); a.H(); M(a.F); M(a.G); M(a.H); } static void M(Action a) { } } static class S { internal static void F(this A a) { } internal static void G(this A a) { } internal static void H(this A a) { } } } namespace N3 { class C { // Inaccessible extension methods. static void M(A a) { a.F(); a.G(); a.H(); M(a.F); M(a.G); M(a.H); } static void M(Action a) { } } static class S { static void F(this A a) { } static void G(this A a) { } static void H(this A a) { } } }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (15,15): error CS0122: 'A.F()' is inaccessible due to its protection level // a.F(); Diagnostic(ErrorCode.ERR_BadAccess, "F").WithArguments("A.F()"), // (16,15): error CS0122: 'A.G' is inaccessible due to its protection level // a.G(); Diagnostic(ErrorCode.ERR_BadAccess, "G").WithArguments("A.G"), // (17,15): error CS1955: Non-invocable member 'A.H' cannot be used like a method. // a.H(); Diagnostic(ErrorCode.ERR_NonInvocableMemberCalled, "H").WithArguments("A.H"), // (18,17): error CS0122: 'A.F()' is inaccessible due to its protection level // M(a.F); Diagnostic(ErrorCode.ERR_BadAccess, "F").WithArguments("A.F()"), // (19,17): error CS0122: 'A.G' is inaccessible due to its protection level // M(a.G); Diagnostic(ErrorCode.ERR_BadAccess, "G").WithArguments("A.G"), // (20,17): error CS0122: 'A.H' is inaccessible due to its protection level // M(a.H); Diagnostic(ErrorCode.ERR_BadAccess, "H").WithArguments("A.H"), // (55,15): error CS0122: 'A.F()' is inaccessible due to its protection level // a.F(); Diagnostic(ErrorCode.ERR_BadAccess, "F").WithArguments("A.F()"), // (56,15): error CS0122: 'A.G' is inaccessible due to its protection level // a.G(); Diagnostic(ErrorCode.ERR_BadAccess, "G").WithArguments("A.G"), // (57,15): error CS1955: Non-invocable member 'A.H' cannot be used like a method. // a.H(); Diagnostic(ErrorCode.ERR_NonInvocableMemberCalled, "H").WithArguments("A.H"), // (58,17): error CS0122: 'A.F()' is inaccessible due to its protection level // M(a.F); Diagnostic(ErrorCode.ERR_BadAccess, "F").WithArguments("A.F()"), // (59,17): error CS0122: 'A.G' is inaccessible due to its protection level // M(a.G); Diagnostic(ErrorCode.ERR_BadAccess, "G").WithArguments("A.G"), // (60,17): error CS0122: 'A.H' is inaccessible due to its protection level // M(a.H); Diagnostic(ErrorCode.ERR_BadAccess, "H").WithArguments("A.H"), // (5,12): warning CS0169: The field 'A.G' is never used // Action G; Diagnostic(ErrorCode.WRN_UnreferencedField, "G").WithArguments("A.G"), // (6,7): warning CS0169: The field 'A.H' is never used // A H; Diagnostic(ErrorCode.WRN_UnreferencedField, "H").WithArguments("A.H")); } /// <summary> /// Method arguments should be evaluated, /// even if too many. /// </summary> [Fact] public void InaccessibleTooManyArgs() { var source = @"static class S { static void E(this object o) { } } class A { static void F() { } void G() { } } class B { static void M() { A a = null; M(a.E(), A.F(), a.G()); } }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (15,13): error CS1061: 'A' does not contain a definition for 'E' and no extension method 'E' accepting a first argument of type 'A' could be found (are you missing a using directive or an assembly reference?) // M(a.E(), A.F(), a.G()); Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "E").WithArguments("A", "E").WithLocation(15, 13), // (15,20): error CS0122: 'A.F()' is inaccessible due to its protection level // M(a.E(), A.F(), a.G()); Diagnostic(ErrorCode.ERR_BadAccess, "F").WithArguments("A.F()").WithLocation(15, 20), // (15,27): error CS0122: 'A.G()' is inaccessible due to its protection level // M(a.E(), A.F(), a.G()); Diagnostic(ErrorCode.ERR_BadAccess, "G").WithArguments("A.G()").WithLocation(15, 27) ); } [WorkItem(541330, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541330")] [WorkItem(541335, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541335")] [Fact] public void ReturnDelegateAsObject() { var source = @"class C { static object M(object o) { return o.E; } } static class S { internal static void E(this object o) { } }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (5,18): error CS0428: Cannot convert method group 'E' to non-delegate type 'object'. Did you intend to invoke the method? Diagnostic(ErrorCode.ERR_MethGrpToNonDel, "E").WithArguments("E", "object").WithLocation(5, 18)); } [Fact] public void AllExtensionMethodsInaccessible() { var source = @"namespace N { class A { void F() { } } class C { void M(A a) { a.F(); // instance and extension methods a.G(); // only extension methods } } static class S1 { static void F(this object o) { } static void G(this object o) { } } } static class S2 { static void F(this object o) { } static void G(this object o) { } }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (11,15): error CS0122: 'A.F()' is inaccessible due to its protection level // a.F(); // instance and extension methods Diagnostic(ErrorCode.ERR_BadAccess, "F").WithArguments("N.A.F()").WithLocation(11, 15), // (12,15): error CS1061: 'A' does not contain a definition for 'G' and no extension method 'G' accepting a first argument of type 'A' could be found (are you missing a using directive or an assembly reference?) // a.G(); // only extension methods Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "G").WithArguments("N.A", "G").WithLocation(12, 15) ); } [WorkItem(868538, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/868538")] [Fact] public void IsAndAs() { var source = @"delegate void D(); static class S { internal static void E(this object o) { } } class C { static void M(C c) { if (F is D) { (F as D)(); } if (c.F is D) { (c.F as D)(); } if (G is D) { (G as D)(); } if (c.E is D) { (c.E as D)(); } } void F() { } static void G() { } }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (10,13): error CS0837: The first operand of an 'is' or 'as' operator may not be a lambda expression, anonymous method, or method group. // if (F is D) Diagnostic(ErrorCode.ERR_LambdaInIsAs, "F is D").WithLocation(10, 13), // (12,14): error CS0837: The first operand of an 'is' or 'as' operator may not be a lambda expression, anonymous method, or method group. // (F as D)(); Diagnostic(ErrorCode.ERR_LambdaInIsAs, "F as D").WithLocation(12, 14), // (14,13): error CS0837: The first operand of an 'is' or 'as' operator may not be a lambda expression, anonymous method, or method group. // if (c.F is D) Diagnostic(ErrorCode.ERR_LambdaInIsAs, "c.F is D").WithLocation(14, 13), // (16,14): error CS0837: The first operand of an 'is' or 'as' operator may not be a lambda expression, anonymous method, or method group. // (c.F as D)(); Diagnostic(ErrorCode.ERR_LambdaInIsAs, "c.F as D").WithLocation(16, 14), // (18,13): error CS0837: The first operand of an 'is' or 'as' operator may not be a lambda expression, anonymous method, or method group. // if (G is D) Diagnostic(ErrorCode.ERR_LambdaInIsAs, "G is D").WithLocation(18, 13), // (20,14): error CS0837: The first operand of an 'is' or 'as' operator may not be a lambda expression, anonymous method, or method group. // (G as D)(); Diagnostic(ErrorCode.ERR_LambdaInIsAs, "G as D").WithLocation(20, 14), // (22,13): error CS0837: The first operand of an 'is' or 'as' operator may not be a lambda expression, anonymous method, or method group. // if (c.E is D) Diagnostic(ErrorCode.ERR_LambdaInIsAs, "c.E is D").WithLocation(22, 13), // (24,14): error CS0837: The first operand of an 'is' or 'as' operator may not be a lambda expression, anonymous method, or method group. // (c.E as D)(); Diagnostic(ErrorCode.ERR_LambdaInIsAs, "c.E as D").WithLocation(24, 14)); } [Fact] public void Casts() { var source = @"delegate void D(); static class S { internal static void E(this object o) { } } class C { static void M(C c) { ((D)c.F)(); ((D)G)(); ((D)c.E)(); } void F() { } static void G() { } }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics(); } [Fact] public void NoReceiver() { var source = @"class C { void M() { E(); } } static class S { public static void E(this C c) { } }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( Diagnostic(ErrorCode.ERR_NameNotInContext, "E").WithArguments("E").WithLocation(5, 9)); } [Fact] public void BaseReceiver() { var source = @"class C { } class D : C { void M() { base.E(); } } static class S { public static void E(this C c) { } }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( Diagnostic(ErrorCode.ERR_NoSuchMember, "E").WithArguments("C", "E").WithLocation(8, 14)); } [ClrOnlyFact] public void DefinedInSameClass() { var source = @"static class C { static void M(this string s, int i) { s.M(i + 1); } }"; CompileAndVerify(source); } /// <summary> /// Should not favor method from one class over another in same /// namespace, even if one method is defined in caller's class. /// </summary> [Fact] public void AmbiguousMethodDifferentClassesSameNamespace() { var source = @"static class A { public static void E(this string s, int i) { } } static class B { public static void E(this string s, int i) { } static void M(string s) { s.E(1); } } static class C { static void M(string s) { s.E(2); } } namespace N.S { static class A { public static void E(this string s, int i) { } } } namespace N.S { static class B { public static void E(this string s, int i) { } static void M(string s) { s.E(3); } } static class C { static void M(string s) { s.E(4); } } }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( Diagnostic(ErrorCode.ERR_AmbigCall, "E").WithArgumentsAnyOrder("A.E(string, int)", "B.E(string, int)").WithLocation(10, 11), Diagnostic(ErrorCode.ERR_AmbigCall, "E").WithArgumentsAnyOrder("B.E(string, int)", "A.E(string, int)").WithLocation(17, 11), Diagnostic(ErrorCode.ERR_AmbigCall, "E").WithArguments("N.S.A.E(string, int)", "N.S.B.E(string, int)").WithLocation(34, 15), Diagnostic(ErrorCode.ERR_AmbigCall, "E").WithArguments("N.S.A.E(string, int)", "N.S.B.E(string, int)").WithLocation(41, 15)); } /// <summary> /// Extension method delegates in different scopes make /// consumer (an overloaded method invocation) ambiguous. /// </summary> [Fact] public void AmbiguousConsumerWithExtensionMethodDelegateArg() { var source = @"namespace N { class C { static void M1(object o) { M2(o.F); } static void M2(System.Action a) { } static void M2(System.Action<int> a) { } } static class E { public static void F(this object o) { } } } static class E { public static void F(this object o, int i) { } }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (7,13): error CS0121: The call is ambiguous between the following methods or properties: 'N.C.M2(System.Action)' and 'N.C.M2(System.Action<int>)' Diagnostic(ErrorCode.ERR_AmbigCall, "M2").WithArgumentsAnyOrder("N.C.M2(System.Action)", "N.C.M2(System.Action<int>)").WithLocation(7, 13)); } /// <summary> /// Prefer methods on classes on inner namespaces. /// </summary> [ClrOnlyFact] public void InnerNamespacesBeforeOuter() { var source = @"using System; static class A { public static void E(this string s) { Console.WriteLine(""A.E: {0}"", s); } public static void E(this string s, int i) { Console.WriteLine(""A.E: {0}, {1}"", s, i); } public static void E(this string s, bool b) { Console.WriteLine(""C.E: {0}, {1}"", s, b); } } namespace N1 { static class B { public static void E(this string s) { Console.WriteLine(""B.E: {0}"", s); } public static void E(this string s, bool b) { Console.WriteLine(""B.E: {0}, {1}"", s, b); } } } namespace N1.N2 { static class C { public static void E(this string s) { Console.WriteLine(""C.E: {0}"", s); } } namespace N3 { static class D { public static void E(this string s) { Console.WriteLine(""D.E: {0}"", s); } } } static class E { static void Main() { ""str"".E(); ""int"".E(1); ""bool"".E(true); } } }"; CompileAndVerify(source, expectedOutput: @"C.E: str A.E: int, 1 B.E: bool, True"); } [Fact] public void ExtensionMethodsWithAccessorNames() { var source = @"class C { public object P { get; set; } void M() { this.set_P(this.get_P()); set_P(get_P()); } } class D { static void M(C c) { c.set_P(c.get_P()); } } static class S { internal static object get_P(this C c) { return null; } static void set_P(this C c, object o) { } }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (6,14): error CS0571: 'C.P.set': cannot explicitly call operator or accessor Diagnostic(ErrorCode.ERR_CantCallSpecialMethod, "set_P").WithArguments("C.P.set").WithLocation(6, 14), // (7,9): error CS0571: 'C.P.set': cannot explicitly call operator or accessor Diagnostic(ErrorCode.ERR_CantCallSpecialMethod, "set_P").WithArguments("C.P.set").WithLocation(7, 9), // (7,15): error CS0571: 'C.P.get': cannot explicitly call operator or accessor Diagnostic(ErrorCode.ERR_CantCallSpecialMethod, "get_P").WithArguments("C.P.get").WithLocation(7, 15), // (14,11): error CS0571: 'C.P.set': cannot explicitly call operator or accessor Diagnostic(ErrorCode.ERR_CantCallSpecialMethod, "set_P").WithArguments("C.P.set").WithLocation(14, 11)); } [Fact] public void DelegateExtensionMethodsWithAccessorNames() { var source = @"using System; class C { object P { get; set; } object Q { get; set; } void M() { F(this.get_P); F(this.get_Q); } void F(Func<object> f) { } } static class S { internal static object get_P(this C c) { return null; } static object get_Q(this C c) { return null; } }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (9,16): error CS0571: 'C.Q.get': cannot explicitly call operator or accessor Diagnostic(ErrorCode.ERR_CantCallSpecialMethod, "get_Q").WithArguments("C.Q.get").WithLocation(9, 16)); } [Fact] public void Delegates() { var source = @"static class S { public static void E(this object o) { } public static void F(this System.Action a) { } public static void G(this System.Action<object> a) { } } class C { static void M() { S.F(4.E); S.F(new object().E); S.F(""str"".E); ""str"".E.F(); (""str"".E).F(); System.Action a = ""str"".E; a.F(); S.G(S.E); S.E.G(); System.Action<object> b = S.E; b.G(); } }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (14,15): error CS0119: 'S.E(object)' is a 'method', which is not valid in the given context Diagnostic(ErrorCode.ERR_BadSKunknown, "E").WithArguments("S.E(object)", "method").WithLocation(14, 15), // (15,16): error CS0119: 'S.E(object)' is a 'method', which is not valid in the given context Diagnostic(ErrorCode.ERR_BadSKunknown, "E").WithArguments("S.E(object)", "method").WithLocation(15, 16), // (19,11): error CS0119: 'S.E(object)' is a 'method', which is not valid in the given context Diagnostic(ErrorCode.ERR_BadSKunknown, "E").WithArguments("S.E(object)", "method").WithLocation(19, 11)); } [ClrOnlyFact] public void GenericDelegate() { var source = @"delegate void D<T>(T t); class C { static void Main() { F<int>(new C().M)(2); } static D<T> F<T>(D<T> d) { return d; } public int P { get { return 3; } } } static class S { public static void M(this C c, int i) { System.Console.Write(c.P * i); } }"; CompileAndVerify(source, expectedOutput: "6"); } [Fact] public void InvalidTypeArguments() { var source = @"class C { void M() { this.E<int>(1); this.E<S>(); this.E<A>(null); this.E<int, int>(1); } void E<T>() { } } static class S { public static void E<T>(this C c, T t) { } }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (6,14): error CS0718: 'S': static types cannot be used as type arguments // this.E<S>(); Diagnostic(ErrorCode.ERR_GenericArgIsStaticClass, "E<S>").WithArguments("S").WithLocation(6, 14), // (7,16): error CS0246: The type or namespace name 'A' could not be found (are you missing a using directive or an assembly reference?) // this.E<A>(null); Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "A").WithArguments("A").WithLocation(7, 16), // (8,14): error CS0305: Using the generic method 'C.E<T>()' requires 1 type arguments // this.E<int, int>(1); Diagnostic(ErrorCode.ERR_BadArity, "E<int, int>").WithArguments("C.E<T>()", "method", "1").WithLocation(8, 14) ); } [Fact] public void ThisArgumentConversions() { var source = @"class A { } class B { } struct S { } class C { static void M() { A a = new A(); a.A(); a.B(); a.O(); a.T(); B b = new B(); b.A(); b.B(); b.O(); S s = new S(); s.A(); s.S(); s.O(); s.T(); (1.0).D(); (2.0).O(); 1.A(); 2.O(); 3.T(); } } static class Extensions { internal static void A(this A a) { } internal static void B(this B b) { } internal static void S(this S s) { } internal static void T<U>(this U u) { } internal static void D(this double d) { } internal static void O(this object o) { } }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (10,9): error CS1929: 'A' does not contain a definition for 'B' and the best extension method overload 'Extensions.B(B)' requires a receiver of type 'B' // a.B(); Diagnostic(ErrorCode.ERR_BadInstanceArgType, "a").WithArguments("A", "B", "Extensions.B(B)", "B"), // (14,9): error CS1929: 'B' does not contain a definition for 'A' and the best extension method overload 'Extensions.A(A)' requires a receiver of type 'A' // b.A(); Diagnostic(ErrorCode.ERR_BadInstanceArgType, "b").WithArguments("B", "A", "Extensions.A(A)", "A"), // (18,9): error CS1929: 'S' does not contain a definition for 'A' and the best extension method overload 'Extensions.A(A)' requires a receiver of type 'A' // s.A(); Diagnostic(ErrorCode.ERR_BadInstanceArgType, "s").WithArguments("S", "A", "Extensions.A(A)", "A"), // (24,9): error CS1929: 'int' does not contain a definition for 'A' and the best extension method overload 'Extensions.A(A)' requires a receiver of type 'A' // 1.A(); Diagnostic(ErrorCode.ERR_BadInstanceArgType, "1").WithArguments("int", "A", "Extensions.A(A)", "A") ); } [Fact] public void ThisArgumentImplicitConversions() { var source = @"class C { static void M() { 1.E1(); 2.E2(); 3.E3(); 4.E4(); } } static class S { internal static void E1<T>(this T t) { } internal static void E2(this double d) { } internal static void E3(this long l, params object[] args) { } internal static void E4(this object o) { } }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (6,9): error CS1929: 'int' does not contain a definition for 'E2' and the best extension method overload 'S.E2(double)' requires a receiver of type 'double' // 2.E2(); Diagnostic(ErrorCode.ERR_BadInstanceArgType, "2").WithArguments("int", "E2", "S.E2(double)", "double").WithLocation(6, 9), // (7,9): error CS1929: 'int' does not contain a definition for 'E3' and the best extension method overload 'S.E3(long, params object[])' requires a receiver of type 'long' // 3.E3(); Diagnostic(ErrorCode.ERR_BadInstanceArgType, "3").WithArguments("int", "E3", "S.E3(long, params object[])", "long").WithLocation(7, 9)); } [ClrOnlyFact] public void ParamsArray() { var source = @"delegate void D(params int[] args); class C { void M() { this.E1(0); this.E1(1, null); 1.E2(); 1.E2(2, 3); D d = this.E2; } } static class S { internal static void E1(this C c, int i, params object[] args) { } internal static void E2(this object o, params int[] args) { } }"; CompileAndVerify(source); } [ClrOnlyFact] public void Using() { var source = @"using System; using N1.N2; namespace N1 { internal static class S { public static void E(this object o) { Console.WriteLine(""N1.S.E""); } } namespace N2 { internal static class S { public static void E(this object o) { Console.WriteLine(""N1.N2.S.E""); } } } } namespace N3 { internal static class S { public static void E(this object o) { Console.WriteLine(""N3.S.E""); } } } namespace N4 { using N3; class A { public static void M(object o) { o.E(); } } } namespace N4 { using N1; class B { public static void M(object o) { o.E(); } } } class C { public static void M(object o) { o.E(); } } class D { static void Main() { object o = null; N4.A.M(o); N4.B.M(o); C.M(o); } }"; var compilation = CompileAndVerify(source, expectedOutput: @"N3.S.E N1.S.E N1.N2.S.E"); } [Fact] public void AmbiguousUsing() { var source = @"using N1; using N2; namespace N1 { internal static class S { public static void E(this object o) { } } } namespace N2 { internal static class S { public static void E(this object o) { } } } namespace N3 { internal static class S { public static void F(this object o) { } public static void G(this object o) { } } } namespace N4 { using N3; internal static class S { public static void F(this object o) { } } class C { static void M() { object o = null; o.E(); // ambiguous N1.S.E, N2.S.E o.F(); // choose N4.S.F over N3.S.F o.G(); // N3.S.G } } }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (37,13): error CS0121: The call is ambiguous between the following methods or properties: 'N1.S.E(object)' and 'N2.S.E(object)' Diagnostic(ErrorCode.ERR_AmbigCall, "E").WithArguments("N1.S.E(object)", "N2.S.E(object)").WithLocation(37, 15)); } [Fact] public void VerifyDiagnosticForMissingSystemCoreReference() { var source = @" internal static class C { internal static void M1(this object o) { } private static void Main(string[] args) { } } "; var compilation = CreateEmptyCompilation(source, new[] { Net40.mscorlib }); compilation.VerifyDiagnostics( // (4,29): error CS1110: Cannot define a new extension method because the compiler required type 'System.Runtime.CompilerServices.ExtensionAttribute' cannot be found. Are you missing a reference to System.Core.dll? Diagnostic(ErrorCode.ERR_ExtensionAttrNotFound, "this").WithArguments("System.Runtime.CompilerServices.ExtensionAttribute").WithLocation(4, 29)); } [ClrOnlyFact] public void SystemLinqEnumerable() { var source = @"using System; using System.Linq; class C { static void Main() { string result = F(""banana"", ""orange"", ""lime"", ""apple"", ""kiwi""); Console.Write(result); } static string F(params string[] args) { return args.Skip(1).Where(Filter).Aggregate(Combine); } static string G(params string[] args) { return Enumerable.Aggregate(Enumerable.Where(Enumerable.Skip(args, 1), Filter), Combine); } static bool Filter(string s) { return s.Length > 4; } static string Combine(string s1, string s2) { return s1 + "", "" + s2; } }"; var code = @"{ // Code size 42 (0x2a) .maxstack 3 IL_0000: ldarg.0 IL_0001: ldc.i4.1 IL_0002: call ""System.Collections.Generic.IEnumerable<string> System.Linq.Enumerable.Skip<string>(System.Collections.Generic.IEnumerable<string>, int)"" IL_0007: ldnull IL_0008: ldftn ""bool C.Filter(string)"" IL_000e: newobj ""System.Func<string, bool>..ctor(object, System.IntPtr)"" IL_0013: call ""System.Collections.Generic.IEnumerable<string> System.Linq.Enumerable.Where<string>(System.Collections.Generic.IEnumerable<string>, System.Func<string, bool>)"" IL_0018: ldnull IL_0019: ldftn ""string C.Combine(string, string)"" IL_001f: newobj ""System.Func<string, string, string>..ctor(object, System.IntPtr)"" IL_0024: call ""string System.Linq.Enumerable.Aggregate<string>(System.Collections.Generic.IEnumerable<string>, System.Func<string, string, string>)"" IL_0029: ret }"; var compilation = CompileAndVerify(source, expectedOutput: "orange, apple"); compilation.VerifyIL("C.F", code); compilation.VerifyIL("C.G", code); } /// <summary> /// A value type should be boxed when used as a reference type receiver to an /// extension method. Note: Dev10 reports an error in such cases ("No overload for /// 'C.F(object)' matches delegate 'System.Action'") even though these cases are valid. /// </summary> [ClrOnlyFact] public void BoxingConversionOfDelegateReceiver01() { var source = @"using System; struct S { } static class C { static void Main() { M(1.F); M((new S()).F); M(1.G); M((new S()).G); } static void F(this object o) { Console.WriteLine(""F: {0}"", o.GetType()); } static void G(this ValueType v) { Console.WriteLine(""G: {0}"", v.GetType()); } static void M(Action a) { a(); } }"; var compilation = CompileAndVerify(source, expectedOutput: @"F: System.Int32 F: S G: System.Int32 G: S"); compilation.VerifyIL("C.Main", @"{ // Code size 105 (0x69) .maxstack 2 .locals init (S V_0) IL_0000: ldc.i4.1 IL_0001: box ""int"" IL_0006: ldftn ""void C.F(object)"" IL_000c: newobj ""System.Action..ctor(object, System.IntPtr)"" IL_0011: call ""void C.M(System.Action)"" IL_0016: ldloca.s V_0 IL_0018: initobj ""S"" IL_001e: ldloc.0 IL_001f: box ""S"" IL_0024: ldftn ""void C.F(object)"" IL_002a: newobj ""System.Action..ctor(object, System.IntPtr)"" IL_002f: call ""void C.M(System.Action)"" IL_0034: ldc.i4.1 IL_0035: box ""int"" IL_003a: ldftn ""void C.G(System.ValueType)"" IL_0040: newobj ""System.Action..ctor(object, System.IntPtr)"" IL_0045: call ""void C.M(System.Action)"" IL_004a: ldloca.s V_0 IL_004c: initobj ""S"" IL_0052: ldloc.0 IL_0053: box ""S"" IL_0058: ldftn ""void C.G(System.ValueType)"" IL_005e: newobj ""System.Action..ctor(object, System.IntPtr)"" IL_0063: call ""void C.M(System.Action)"" IL_0068: ret }"); } /// <summary> /// Similar to the test above, but using instances of type /// parameters for the delegate receiver. /// </summary> [ClrOnlyFact] public void BoxingConversionOfDelegateReceiver02() { var source = @"using System; interface I { } class A { } class B : A, I { } class C { static void Main() { M(new object(), new object(), 1, new B(), new B()); } static void M<T1, T2, T3, T4, T5>(T1 t1, T2 t2, T3 t3, T4 t4, T5 t5) where T2 : class where T3 : struct where T4 : I where T5 : A { F(t1.M); F(t2.M); F(t3.M); F(t4.M); F(t5.M); } static void F(Action a) { a(); } } static class E { internal static void M(this object o) { Console.WriteLine(""{0}"", o.GetType()); } }"; var compilation = CompileAndVerify(source, expectedOutput: @"System.Object System.Object System.Int32 B B"); compilation.VerifyIL("C.M<T1, T2, T3, T4, T5>", @"{ // Code size 112 (0x70) .maxstack 2 IL_0000: ldarg.0 IL_0001: box ""T1"" IL_0006: ldftn ""void E.M(object)"" IL_000c: newobj ""System.Action..ctor(object, System.IntPtr)"" IL_0011: call ""void C.F(System.Action)"" IL_0016: ldarg.1 IL_0017: box ""T2"" IL_001c: ldftn ""void E.M(object)"" IL_0022: newobj ""System.Action..ctor(object, System.IntPtr)"" IL_0027: call ""void C.F(System.Action)"" IL_002c: ldarg.2 IL_002d: box ""T3"" IL_0032: ldftn ""void E.M(object)"" IL_0038: newobj ""System.Action..ctor(object, System.IntPtr)"" IL_003d: call ""void C.F(System.Action)"" IL_0042: ldarg.3 IL_0043: box ""T4"" IL_0048: ldftn ""void E.M(object)"" IL_004e: newobj ""System.Action..ctor(object, System.IntPtr)"" IL_0053: call ""void C.F(System.Action)"" IL_0058: ldarg.s V_4 IL_005a: box ""T5"" IL_005f: ldftn ""void E.M(object)"" IL_0065: newobj ""System.Action..ctor(object, System.IntPtr)"" IL_006a: call ""void C.F(System.Action)"" IL_006f: ret }"); } [Fact] public void UsingInScript() { string test = @"using System.Linq; (new string[0]).Take(1)"; var tree = SyntaxFactory.ParseSyntaxTree(test, options: TestOptions.Script.WithLanguageVersion(LanguageVersion.CSharp6)); var compilation = CSharpCompilation.Create( assemblyName: GetUniqueName(), options: TestOptions.DebugExe.WithScriptClassName("Script"), syntaxTrees: new[] { tree }, references: new[] { MscorlibRef, LinqAssemblyRef }); var expr = ((ExpressionStatementSyntax)((GlobalStatementSyntax)tree.GetCompilationUnitRoot().Members[0]).Statement).Expression; var model = compilation.GetSemanticModel(tree); var info = model.GetSymbolInfo(expr); Assert.NotNull(info.Symbol); var symbol = info.Symbol; Utils.CheckSymbol(symbol, "IEnumerable<string> IEnumerable<string>.Take<string>(int count)"); } [ClrOnlyFact] public void AssemblyMightContainExtensionMethods() { var source = @"static class C { internal static int F; internal static System.Linq.Expressions.Expression G; internal static void M(this object o) { } }"; Func<bool, Action<ModuleSymbol>> validator = isFromSource => module => { var type = module.GlobalNamespace.GetMember<NamedTypeSymbol>("C"); // mscorlib.dll var mscorlib = type.GetMember<FieldSymbol>("F").Type.ContainingAssembly; Assert.Equal(RuntimeCorLibName.Name, mscorlib.Name); // We assume every PE assembly may contain extension methods. Assert.True(mscorlib.MightContainExtensionMethods); // TODO: Original references are not included in symbol validator. if (isFromSource) { // System.Core.dll var systemCore = type.GetMember<FieldSymbol>("G").Type.ContainingAssembly; Assert.True(systemCore.MightContainExtensionMethods); } // Local assembly. var assembly = type.ContainingAssembly; Assert.True(assembly.MightContainExtensionMethods); }; CompileAndVerify( source: source, sourceSymbolValidator: validator(true), symbolValidator: validator(false), options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal)); } /// <summary> /// AssemblySymbol.MightContainExtensionMethods should be reset after /// emit, after all types within the assembly have been inspected, if there /// are no types with extension methods. /// </summary> [ClrOnlyFact] public void AssemblyMightContainExtensionMethodsReset() { var source = @"static class C { internal static void M(object o) { } }"; AssemblySymbol sourceAssembly = null; Func<bool, Action<ModuleSymbol>> validator = isFromSource => module => { var assembly = module.ContainingAssembly; var mightContainExtensionMethods = assembly.MightContainExtensionMethods; // Every PE assembly is assumed to be capable of having an extension method. // The source assembly doesn't know (so reports "true") until all methods have been inspected. Assert.True(mightContainExtensionMethods); if (isFromSource) { Assert.Null(sourceAssembly); sourceAssembly = assembly; } }; CompileAndVerify(source, symbolValidator: validator(false), sourceSymbolValidator: validator(true)); Assert.NotNull(sourceAssembly); Assert.False(sourceAssembly.MightContainExtensionMethods); } [ClrOnlyFact] public void ReducedExtensionMethodSymbols() { var source = @"using System.Collections.Generic; static class S { internal static void M1(this object o) { } internal static void M2<T>(this IEnumerable<T> t) { } internal static void M3<T, U>(this U u, IEnumerable<T> t) { } }"; var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal)); Action<ModuleSymbol> validator = module => { var type = module.GlobalNamespace.GetMember<NamedTypeSymbol>("S"); var intType = compilation.GetSpecialType(SpecialType.System_Int32); var stringType = compilation.GetSpecialType(SpecialType.System_String); var arrayType = ArrayTypeSymbol.CreateCSharpArray(compilation.Assembly, TypeWithAnnotations.Create(stringType), 1); // Non-generic method. var method = type.GetMember<MethodSymbol>("M1"); CheckExtensionMethod(method, ImmutableArray.Create<TypeWithAnnotations>(), "void object.M1()", "void S.M1(object o)", "void object.M1()", "void S.M1(object o)"); // Generic method, one type argument. method = type.GetMember<MethodSymbol>("M2"); CheckExtensionMethod(method, ImmutableArray.Create(TypeWithAnnotations.Create(intType)), "void IEnumerable<int>.M2<int>()", "void S.M2<T>(IEnumerable<T> t)", "void IEnumerable<T>.M2<T>()", "void S.M2<T>(IEnumerable<T> t)"); // Generic method, multiple type arguments. method = type.GetMember<MethodSymbol>("M3"); CheckExtensionMethod(method, ImmutableArray.Create(TypeWithAnnotations.Create(intType), TypeWithAnnotations.Create(arrayType)), "void string[].M3<int, string[]>(IEnumerable<int> t)", "void S.M3<T, U>(U u, IEnumerable<T> t)", "void U.M3<T, U>(IEnumerable<T> t)", "void S.M3<T, U>(U u, IEnumerable<T> t)"); }; CompileAndVerify(compilation, sourceSymbolValidator: validator, symbolValidator: validator); } private void CheckExtensionMethod( MethodSymbol method, ImmutableArray<TypeWithAnnotations> typeArgs, string reducedMethodDescription, string reducedFromDescription, string constructedFromDescription, string reducedAndConstructedFromDescription) { // Create instance form from constructed method. var extensionMethod = ReducedExtensionMethodSymbol.Create(method.ConstructIfGeneric(typeArgs)); Utils.CheckReducedExtensionMethod(extensionMethod, reducedMethodDescription, reducedFromDescription, constructedFromDescription, reducedAndConstructedFromDescription); // Construct method from unconstructed instance form. extensionMethod = ReducedExtensionMethodSymbol.Create(method).ConstructIfGeneric(typeArgs); Utils.CheckReducedExtensionMethod(extensionMethod, reducedMethodDescription, reducedFromDescription, constructedFromDescription, reducedAndConstructedFromDescription); } /// <summary> /// Roslyn bug 7782: NullRef in PeWriter.DebuggerShouldHideMethod /// </summary> [Fact] public void ExtensionMethod_ValidateExtensionAttribute() { var comp = CreateCompilation(@" using System; internal static class C { internal static void M1(this object o) { } private static void Main(string[] args) { } } ", options: TestOptions.DebugExe.WithMetadataImportOptions(MetadataImportOptions.All)); CompileAndVerify(comp, symbolValidator: module => { var method = module.GlobalNamespace.GetMember<NamedTypeSymbol>("C").GetMember<PEMethodSymbol>("M1"); Assert.True(method.IsExtensionMethod); Assert.Equal(SpecialType.System_Object, method.Parameters.Single().Type.SpecialType); var attr = ((PEModuleSymbol)module).GetCustomAttributesForToken(method.Handle).Single(); Assert.Equal("System.Runtime.CompilerServices.ExtensionAttribute", attr.AttributeClass.ToTestDisplayString()); }); } [WorkItem(541327, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541327")] [Fact] public void RegressBug7992() { var text = @"using System.Runtime.InteropServices; namespace ConsoleApplication1 { [StructLayout(Pack = A.B)] struct Program { } } "; CreateCompilation(text).GetDiagnostics(); } /// <summary> /// Box value type receiver if passed as reference type. /// </summary> [ClrOnlyFact] public void BoxValueTypeReceiverIfNecessary() { var source = @"struct S { } static class C { static void Main() { ""str"".F(); ""str"".G(); (2.0).F(); (2.0).G(); (new S()).F(); (new S()).G(); } static void F(this object o) { System.Console.WriteLine(""{0}"", o.ToString()); } static void G<T>(this T t) { System.Console.WriteLine(""{0}"", t.ToString()); } }"; var compilation = CompileAndVerify(source, expectedOutput: @"str str 2 2 S S"); compilation.VerifyIL("C.Main", @"{ // Code size 87 (0x57) .maxstack 1 .locals init (S V_0) IL_0000: ldstr ""str"" IL_0005: call ""void C.F(object)"" IL_000a: ldstr ""str"" IL_000f: call ""void C.G<string>(string)"" IL_0014: ldc.r8 2 IL_001d: box ""double"" IL_0022: call ""void C.F(object)"" IL_0027: ldc.r8 2 IL_0030: call ""void C.G<double>(double)"" IL_0035: ldloca.s V_0 IL_0037: initobj ""S"" IL_003d: ldloc.0 IL_003e: box ""S"" IL_0043: call ""void C.F(object)"" IL_0048: ldloca.s V_0 IL_004a: initobj ""S"" IL_0050: ldloc.0 IL_0051: call ""void C.G<S>(S)"" IL_0056: ret }"); } [WorkItem(541652, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541652")] [ClrOnlyFact] public void ReduceExtensionMethodWithNullReceiverType() { var source = @"static class Extensions { public static int NonGeneric(this object o) { return o.GetHashCode(); } public static int Generic<T>(this T o) { return o.GetHashCode(); } } "; CompileAndVerify(source, validator: module => { var type = module.GlobalNamespace.GetMember<NamedTypeSymbol>("Extensions"); var nonGenericExtension = type.GetMember<MethodSymbol>("NonGeneric"); var genericExtension = type.GetMember<MethodSymbol>("Generic"); Assert.True(nonGenericExtension.IsExtensionMethod); Assert.Throws<ArgumentNullException>(() => nonGenericExtension.ReduceExtensionMethod(receiverType: null, compilation: null!)); Assert.True(genericExtension.IsExtensionMethod); Assert.Throws<ArgumentNullException>(() => genericExtension.ReduceExtensionMethod(receiverType: null, compilation: null!)); }); } [WorkItem(528730, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528730")] [Fact] public void ThisParameterCalledOnNonSourceMethodSymbol() { var code = @"using System.Collections.Generic; using System.Linq; class Program { static void Main(string[] args) { int[] numbers = new int[] { 4, 5 }; int i1 = numbers.GetHashCode(); int i2 = numbers.Cast<T1>(); } }"; var compilation = CreateCompilationWithMscorlib40AndSystemCore(code); var tree = compilation.SyntaxTrees[0]; var model = compilation.GetSemanticModel(tree); var node = tree.GetCompilationUnitRoot().FindToken(code.IndexOf("GetHashCode", StringComparison.Ordinal)).Parent; var symbolInfo = model.GetSymbolInfo((SimpleNameSyntax)node); var methodSymbol = symbolInfo.Symbol.GetSymbol<MethodSymbol>(); Assert.False(methodSymbol.IsFromCompilation(compilation)); var parameter = methodSymbol.ThisParameter; Assert.Equal(parameter.Ordinal, -1); Assert.Equal(parameter.ContainingSymbol, methodSymbol); // Get the GenericNameSyntax node Cast<T1> for binding node = tree.GetCompilationUnitRoot().FindToken(code.IndexOf("Cast<T1>", StringComparison.Ordinal)).Parent; symbolInfo = model.GetSymbolInfo((GenericNameSyntax)node); methodSymbol = (MethodSymbol)symbolInfo.Symbol.GetSymbol<MethodSymbol>(); Assert.False(methodSymbol.IsFromCompilation(compilation)); // 9341 is resolved as Won't Fix since ThisParameter property is internal. Assert.Throws<InvalidOperationException>(() => methodSymbol.ThisParameter); } private CompilationVerifier CompileAndVerify(string source, string expectedOutput = null, Action<ModuleSymbol> validator = null, CSharpCompilationOptions options = null) { return CompileAndVerify( source: source, expectedOutput: expectedOutput, sourceSymbolValidator: validator, symbolValidator: validator, options: options); } [WorkItem(528853, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528853")] [Fact] public void NoOverloadTakesNArguments() { var source = @"static class S { static void M(this object x, object y) { x.M(x, y); x.M(); M(x); } }"; CreateCompilationWithMscorlib40AndSystemCore(source).VerifyDiagnostics( // (5,9): error CS1501: No overload for method 'M' takes 2 arguments // x.M(x, y); Diagnostic(ErrorCode.ERR_BadArgCount, "M").WithArguments("M", "2").WithLocation(5, 11), // (6,9): error CS7036: There is no argument given that corresponds to the required formal parameter 'y' of 'S.M(object, object)' // x.M(); Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "M").WithArguments("y", "S.M(object, object)").WithLocation(6, 11), // (7,9): error CS7036: There is no argument given that corresponds to the required formal parameter 'y' of 'S.M(object, object)' // M(x); Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "M").WithArguments("y", "S.M(object, object)").WithLocation(7, 9)); } [WorkItem(543711, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543711")] [Fact] public void ReduceReducedExtensionsMethod() { var source = @"static class C { static void M(this object x) { } }"; var compilation = CreateCompilationWithMscorlib40AndSystemCore(source); compilation.VerifyDiagnostics(); var extensionMethod = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("C").GetMember<MethodSymbol>("M"); Assert.True(extensionMethod.IsExtensionMethod); var reduced = extensionMethod.ReduceExtensionMethod(); Assert.True(reduced.IsExtensionMethod); Assert.Null(reduced.ReduceExtensionMethod()); var int32Type = compilation.GetSpecialType(SpecialType.System_Int32); var reducedWithReceiver = extensionMethod.ReduceExtensionMethod(int32Type, null!); Assert.True(reduced.IsExtensionMethod); Assert.Equal(reduced, reducedWithReceiver); Assert.Null(reducedWithReceiver.ReduceExtensionMethod(int32Type, null!)); } [WorkItem(37780, "https://github.com/dotnet/roslyn/issues/37780")] [Fact] public void ReducedExtensionMethodVsUnmanagedConstraint() { var source1 = @"public static class C { public static void M<T>(this T self) where T : unmanaged { } }"; var compilation1 = CreateCompilation(source1); compilation1.VerifyDiagnostics(); var source2 = @"public class D { static void M(MyStruct<int> s) { s.M(); } } public struct MyStruct<T> { public T field; } "; var compilation2 = CreateCompilation(source2, references: new[] { new CSharpCompilationReference(compilation1) }, parseOptions: TestOptions.Regular8); compilation2.VerifyDiagnostics(); var extensionMethod = compilation2.GlobalNamespace.GetMember<NamedTypeSymbol>("C").GetMember<MethodSymbol>("M"); Assert.True(extensionMethod.IsExtensionMethod); var myStruct = (NamedTypeSymbol)compilation2.GlobalNamespace.GetMember<NamedTypeSymbol>("MyStruct"); var int32Type = compilation2.GetSpecialType(SpecialType.System_Int32); var msi = myStruct.Construct(int32Type); object reducedWithReceiver = extensionMethod.ReduceExtensionMethod(msi, compilation2); Assert.NotNull(reducedWithReceiver); reducedWithReceiver = extensionMethod.ReduceExtensionMethod(msi, null!); Assert.NotNull(reducedWithReceiver); reducedWithReceiver = extensionMethod.GetPublicSymbol().ReduceExtensionMethod(msi.GetPublicSymbol()); Assert.NotNull(reducedWithReceiver); compilation2 = CreateCompilation(source2, references: new[] { new CSharpCompilationReference(compilation1) }, parseOptions: TestOptions.Regular7); compilation2.VerifyDiagnostics( // (5,9): error CS8107: Feature 'unmanaged constructed types' is not available in C# 7.0. Please use language version 8.0 or greater. // s.M(); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "s.M").WithArguments("unmanaged constructed types", "8.0").WithLocation(5, 9) ); extensionMethod = compilation2.GlobalNamespace.GetMember<NamedTypeSymbol>("C").GetMember<MethodSymbol>("M"); Assert.True(extensionMethod.IsExtensionMethod); myStruct = (NamedTypeSymbol)compilation2.GlobalNamespace.GetMember<NamedTypeSymbol>("MyStruct"); int32Type = compilation2.GetSpecialType(SpecialType.System_Int32); msi = myStruct.Construct(int32Type); reducedWithReceiver = extensionMethod.ReduceExtensionMethod(msi, compilation2); Assert.Null(reducedWithReceiver); reducedWithReceiver = extensionMethod.ReduceExtensionMethod(msi, null!); Assert.NotNull(reducedWithReceiver); reducedWithReceiver = extensionMethod.GetPublicSymbol().ReduceExtensionMethod(msi.GetPublicSymbol()); Assert.NotNull(reducedWithReceiver); } /// <summary> /// Dev11 reports error for inaccessible extension method in addition to an /// error for the instance method that was used for binding. The inaccessible /// error may be helpful for the user or for "quick fix" in particular. /// </summary> [WorkItem(529866, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529866")] [Fact] public void InstanceMethodAndInaccessibleExtensionMethod_Diagnostics() { var source = @"class C { static void Main() { C c = new C(); c.Test(1d); } void Test(float f) { } } static class Extensions { static void Test(this C c, double d) { } static void Test<T>(this T t) { } }"; // Dev11 also reports: // (17,17): error CS0122: 'Extensions.Test<T>(T)' is inaccessible due to its protection level CreateCompilationWithMscorlib40AndSystemCore(source).VerifyDiagnostics( // (6,16): error CS1503: Argument 1: cannot convert from 'double' to 'float' Diagnostic(ErrorCode.ERR_BadArgType, "1d").WithArguments("1", "double", "float").WithLocation(6, 16)); } [WorkItem(545322, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545322")] // Bug relates to defunct LookupOptions.IgnoreAccessibility. [Fact] public void InstanceMethodAndInaccessibleExtensionMethod_Symbols() { var source = @"class C { static void Main() { C c = new C(); c.Test(1d); } void Test(float f) { } } static class Extensions { static void Test(this C c, double d) { } static void Test<T>(this T t) { } }"; var compilation = (Compilation)CreateCompilationWithMscorlib40AndSystemCore(source); var globalNamespace = compilation.GlobalNamespace; var type = globalNamespace.GetMember<INamedTypeSymbol>("C"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var memberAccess = tree.GetCompilationUnitRoot().DescendantNodes().OfType<MemberAccessExpressionSyntax>().Single(); var lookupResult = model.LookupSymbols( memberAccess.SpanStart, container: null, name: "Test", includeReducedExtensionMethods: true); Utils.CheckISymbols(lookupResult, "void C.Test(float f)"); lookupResult = model.LookupSymbols( memberAccess.SpanStart, container: type, name: "Test", includeReducedExtensionMethods: true); Utils.CheckISymbols(lookupResult, "void C.Test(float f)"); // Extension methods not found. var memberGroup = model.GetMemberGroup(memberAccess); Utils.CheckISymbols(memberGroup, "void C.Test(float f)"); compilation.VerifyDiagnostics( // (6,16): error CS1503: Argument 1: cannot convert from 'double' to 'float' // c.Test(1d); Diagnostic(ErrorCode.ERR_BadArgType, "1d").WithArguments("1", "double", "float")); } [WorkItem(541890, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541890")] [Fact] public void InstanceMethodAndInaccessibleExtensionMethod_CandidateSymbols() { var source = @"class C { static void Main() { C c = new C(); c.Test(1d); } void Test(float f) { } } static class Extensions { static void Test(this C c, double d) { } static void Test<T>(this T t) { } }"; var compilation = (Compilation)CreateCompilationWithMscorlib40AndSystemCore(source); var globalNamespace = compilation.GlobalNamespace; var type = globalNamespace.GetMember<INamedTypeSymbol>("C"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var memberAccess = tree.GetCompilationUnitRoot().DescendantNodes().OfType<MemberAccessExpressionSyntax>().Single(); var call = (ExpressionSyntax)memberAccess.Parent; Assert.Equal(SyntaxKind.InvocationExpression, call.Kind()); var info = model.GetSymbolInfo(call); Assert.Null(info.Symbol); Assert.Equal(CandidateReason.OverloadResolutionFailure, info.CandidateReason); // Definitely want the extension method here for quick fix. Utils.CheckISymbols(info.CandidateSymbols, "void C.Test(float f)"); } [WorkItem(529596, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529596")] [Fact(Skip = "529596")] public void DelegateFromValueTypeExtensionMethod() { var source = @" public delegate void VoidDelegate(); static class C { public static void Goo(this int x) { VoidDelegate v; v = x.Goo; // CS1113 v = new VoidDelegate(x.Goo); // Roslyn reports CS0123 v += x.Goo; // Roslyn reports CS0019 } } "; // TODO: Dev10 reports CS1113 for all of these. Roslyn reports various other diagnostics // because we detect the condition for CS1113 and then indicate that no conversion exists, // resulting in various cascaded errors. CreateCompilationWithMscorlib40AndSystemCore(source).VerifyDiagnostics( // (9,13): error CS1113: Extension method 'C.Goo(int)' defined on value type 'int' cannot be used to create delegates Diagnostic(ErrorCode.ERR_ValueTypeExtDelegate, "x.Goo").WithArguments("C.Goo(int)", "int").WithLocation(9, 13), // (10,13): error CS1113: Extension method 'C.Goo(int)' defined on value type 'int' cannot be used to create delegates Diagnostic(ErrorCode.ERR_ValueTypeExtDelegate, "new VoidDelegate(x.Goo)").WithArguments("C.Goo(int)", "int").WithLocation(10, 13), // (11,14): error CS1113: Extension method 'C.Goo(int)' defined on value type 'int' cannot be used to create delegates Diagnostic(ErrorCode.ERR_ValueTypeExtDelegate, "x.Goo").WithArguments("'C.Goo(int)", "int").WithLocation(11, 14)); } [Fact] public void DelegateFromGenericExtensionMethod() { var source = @" public delegate void VoidDelegate(); static class DevDivBugs142219 { public static void Goo<T>(this T x) { VoidDelegate f = x.Goo; // CS1113 } public static void Bar<T>(this T x) where T : class { VoidDelegate f = x.Bar; // ok } } "; CreateCompilationWithMscorlib40AndSystemCore(source).VerifyDiagnostics( // (8,26): error CS1113: Extension method 'DevDivBugs142219.Goo<T>(T)' defined on value type 'T' cannot be used to create delegates // VoidDelegate f = x.Goo; // CS1113 Diagnostic(ErrorCode.ERR_ValueTypeExtDelegate, "x.Goo").WithArguments("DevDivBugs142219.Goo<T>(T)", "T")); } [ClrOnlyFact] [WorkItem(545734, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545734")] public void ExtensionMethodWithRefParameterFromMetadata() { var lib = @" public static class Extensions { public static bool TryGetWithoutAttributeSuffix( this string name, out string result) { result = ""42""; return false; } }"; var consumer = @" static class Program { static void Main() { var symbolName = ""test""; string nameWithoutAttributeSuffix; symbolName.TryGetWithoutAttributeSuffix(out nameWithoutAttributeSuffix); } }"; var libCompilation = CreateCompilationWithMscorlib40AndSystemCore(lib, assemblyName: Guid.NewGuid().ToString()); var libReference = new CSharpCompilationReference(libCompilation); CompileAndVerify(consumer, references: new[] { libReference }); } [Fact, WorkItem(545800, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545800")] public void SameExtensionMethodSymbol() { var src1 = @" using System.Collections.Generic; public class MyClass { public void InstanceMethod<T>(T t) { } } public static class Extensions { public static void ExtensionMethod<T>(this MyClass p, T t) { } } class Test { static void Main() { var obj = new MyClass(); obj.InstanceMethod('q'); obj.ExtensionMethod('c'); } } "; var comp = CreateCompilation(src1); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var nodes = tree.GetCompilationUnitRoot().DescendantNodes().OfType<InvocationExpressionSyntax>().ToList(); Assert.Equal(2, nodes.Count); var firstInvocation = nodes[0]; var firstInvocationExpression = firstInvocation.Expression; var firstInvocationSymbol = model.GetSymbolInfo(firstInvocation).Symbol; var firstInvocationExpressionSymbol = model.GetSymbolInfo(firstInvocationExpression).Symbol; var secondInvocation = nodes[1]; var secondInvocationExpression = secondInvocation.Expression; var secondInvocationSymbol = model.GetSymbolInfo(secondInvocation).Symbol; var secondInvocationExpressionSymbol = model.GetSymbolInfo(secondInvocationExpression).Symbol; Assert.Equal("obj.InstanceMethod", firstInvocationExpression.ToString()); Assert.Equal(SyntaxKind.SimpleMemberAccessExpression, firstInvocationExpression.Kind()); Assert.Equal(SymbolKind.Method, firstInvocationSymbol.Kind); Assert.Equal("InstanceMethod", firstInvocationSymbol.Name); Assert.Equal(firstInvocationSymbol, firstInvocationExpressionSymbol); Assert.Equal("obj.ExtensionMethod", secondInvocationExpression.ToString()); Assert.Equal(SyntaxKind.SimpleMemberAccessExpression, secondInvocationExpression.Kind()); Assert.Equal(SymbolKind.Method, secondInvocationSymbol.Kind); Assert.Equal("ExtensionMethod", secondInvocationSymbol.Name); Assert.Equal(secondInvocationSymbol, secondInvocationExpressionSymbol); } /// <summary> /// Dev11 allows referencing extension methods defined on /// non-static classes, generic classes, structs, and delegates. /// </summary> [WorkItem(546093, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546093")] [Fact] public void NonStaticClasses() { var source1 = @".assembly extern mscorlib { .ver 4:0:0:0 .publickeytoken = (B7 7A 5C 56 19 34 E0 89) } .assembly extern System.Core {} .assembly '<<GeneratedFileName>>' { .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) } .class public A { .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) .method public hidebysig specialname rtspecialname instance void .ctor() { ret } // public method .method public static void MA(object o) { .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) ret } // protected method .method family static void MP(object o) { .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) ret } } .class public B<T> { .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) .method public hidebysig specialname rtspecialname instance void .ctor() { ret } // generic type method .method public static void MB(object o) { .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) ret } } .class public sealed S extends [mscorlib]System.ValueType { .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) // struct method .method public static void MS(object o) { .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) ret } } .class public abstract interface I { .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) // interface method .method public static void MI(object o) { .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) ret } } .class public sealed D extends [mscorlib]System.MulticastDelegate { .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) .method public instance void Invoke() { ret } // delegate method .method public static void MD(object o) { .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) ret } }"; var reference1 = CompileIL(source1, prependDefaultHeader: false); var source2 = @"class C : A { static void M(object o) { o.MA(); // A.MA() o.MP(); // A.MP() (protected) o.MB(); // B<T>.MB() o.MS(); // S.MS() o.MI(); // I.MI() o.MD(); // D.MD() } }"; var compilation = CreateCompilation(source2, new[] { reference1 }); compilation.VerifyDiagnostics( // (9,11): error CS1061: 'object' does not contain a definition for 'MI' and no extension method 'MI' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?) Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "MI").WithArguments("object", "MI").WithLocation(9, 11)); } [WorkItem(546093, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546093")] [ClrOnlyFact] public void VBExtensionMethod() { var source1 = @"Imports System.Runtime.CompilerServices Public Module M <Extension()> Public Sub F(o As Object) End Sub End Module"; var reference1 = BasicCompilationUtils.CompileToMetadata(source1, references: new[] { MscorlibRef, SystemCoreRef, MsvbRef }); var source2 = @"class C { static void M(object o) { o.F(); } }"; var compilation2 = CreateCompilation(source2, new[] { reference1 }); compilation2.VerifyDiagnostics(); } [WorkItem(602893, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/602893")] [ClrOnlyFact] public void Bug602893() { var source1 = @"namespace NA { internal static class A { public static void F(this object o) { } } }"; var compilation1 = CreateCompilationWithMscorlib40AndSystemCore(source1, assemblyName: "A"); compilation1.VerifyDiagnostics(); var compilationVerifier = CompileAndVerify(compilation1); var reference1 = MetadataReference.CreateFromImage(compilationVerifier.EmittedAssemblyData); var source2 = @"[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""C"")] namespace NB { internal static class B { public static void F(this object o) { } } }"; var compilation2 = CreateCompilationWithMscorlib40AndSystemCore(source2, assemblyName: "B"); compilation2.VerifyDiagnostics(); compilationVerifier = CompileAndVerify(compilation2); var reference2 = MetadataReference.CreateFromImage(compilationVerifier.EmittedAssemblyData); var source3 = @"using NB; namespace NA.NC { class C { static void Main() { new object().F(); } } }"; var compilation3 = CreateCompilation(source3, assemblyName: "C", references: new[] { reference1, reference2 }); compilation3.VerifyDiagnostics(); } /// <summary> /// As test above but with all classes defined in the same compilation. /// </summary> [WorkItem(602893, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/602893")] [Fact] public void Bug602893_2() { var source = @"using NB; namespace NA { internal static class A { static void F(this object o) { } } } namespace NB { internal static class B { public static void F(this object o) { } } } namespace NA { class C { static void Main() { new object().F(); } } }"; var compilation = CreateCompilationWithMscorlib40AndSystemCore(source); compilation.VerifyDiagnostics(); } /// <summary> /// Ambiguous methods should hide methods in outer scopes. /// </summary> [Fact] public void AmbiguousMethodsHideOuterScope() { var source = @"using NB; namespace NA { internal static class A { public static void F(this object o) { } } internal static class B { public static void F(this object o) { } } class C { static void Main() { new object().F(); } } } namespace NB { internal static class B { public static void F(this object o) { } } }"; var compilation = CreateCompilationWithMscorlib40AndSystemCore(source); compilation.VerifyDiagnostics( // (16,13): error CS0121: The call is ambiguous between the following methods or properties: 'NA.A.F(object)' and 'NA.B.F(object)' Diagnostic(ErrorCode.ERR_AmbigCall, "F").WithArguments("NA.A.F(object)", "NA.B.F(object)").WithLocation(16, 26), // (1,1): info CS8019: Unnecessary using directive. // using NB; Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using NB;")); } [Fact, WorkItem(822125, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/822125")] public void ConsumeFSharpExtensionMethods() { var source = @"using FSharpTestLibrary; namespace CSharpApp { class Program { static void Main() { var question = 42.GetQuestion(); } } }"; var compilation = CreateCompilation(source, references: new[] { FSharpTestLibraryRef }); compilation.VerifyDiagnostics(); } [ClrOnlyFact] public void InternalExtensionAttribute() { var source = @" namespace System.Runtime.CompilerServices { [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)] class ExtensionAttribute : Attribute { } } internal static class Test { public static void M(this int p) { } } "; var compilation = CreateEmptyCompilation(source, new[] { MscorlibRef_v20 }, TestOptions.ReleaseDll); CompileAndVerify(compilation); } [ClrOnlyFact] [WorkItem(1010648, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1010648")] public void ExtensionMethodFromUsingStatic() { const string source = @" using System; using static N.S; class Program { static void Main() { 1.Goo(); } } namespace N { static class S { public static void Goo(this int x) { Console.Write(x); } } }"; CompileAndVerify(source, expectedOutput: "1"); } [Fact, WorkItem(1085744, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1085744")] public void ExtensionMethodsAreNotImportedAsSimpleNames() { const string source = @" using System; using static N.S; class Program { static void Main() { 1.Goo(); Goo(1); } } namespace N { static class S { public static void Goo(this int x) { Console.Write(x); } } }"; var compilation = CreateCompilationWithMscorlib40AndSystemCore(source); compilation.VerifyDiagnostics( // (10,9): error CS0103: The name 'Goo' does not exist in the current context // Goo(1); Diagnostic(ErrorCode.ERR_NameNotInContext, "Goo").WithArguments("Goo").WithLocation(10, 9)); } [ClrOnlyFact] [WorkItem(1010648, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1010648")] public void ExtensionMethodImportedTwiceNoErrors() { const string source = @" using System; using N; using static N.S; class Program { static void Main() { 1.Goo(); } } namespace N { static class S { public static void Goo(this int x) { Console.WriteLine(x); } } }"; CompileAndVerify(source, expectedOutput: "1"); } [Fact, WorkItem(1010648, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1010648")] public void ExtensionMethodIsNotDisambiguatedByUsingStaticAtTheSameLevel() { const string source = @" using N; using static N.S; class Program { static void Main() { 1.Goo(); } } namespace N { static class S { public static void Goo(this int x) { } } static class R { public static void Goo(this int x) { } } }"; var compilation = CreateCompilationWithMscorlib40AndSystemCore(source); compilation.VerifyDiagnostics( // (9,11): error CS0121: The call is ambiguous between the following methods or properties: 'S.Goo(int)' and 'R.Goo(int)' // 1.Goo(); Diagnostic(ErrorCode.ERR_AmbigCall, "Goo").WithArguments("N.S.Goo(int)", "N.R.Goo(int)").WithLocation(9, 11)); } [ClrOnlyFact] [WorkItem(1010648, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1010648")] public void ExtensionMethodIsDisambiguatedByUsingStaticAtDeeperLevel() { const string source = @" using System; using N; namespace K { using static S; class Program { static void Main() { 1.Goo(); } } } namespace N { static class S { public static void Goo(this int x) { Console.WriteLine(""S""); } } static class R { public static void Goo(this int x) { Console.WriteLine(""R""); } } }"; CompileAndVerify(source, expectedOutput: "S"); } [Fact, WorkItem(1010648, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1010648")] public void ExtensionMethodAmbiguousAcrossMultipleUsingStatic() { const string source = @" using System; namespace K { using static N.S; using static N.R; class Program { static void Main() { 1.Goo(); } } } namespace N { static class S { public static void Goo(this int x) { Console.WriteLine(""S""); } } static class R { public static void Goo(this int x) { Console.WriteLine(""R""); } } }"; var compilation = CreateCompilationWithMscorlib40AndSystemCore(source); compilation.VerifyDiagnostics( // (13,15): error CS0121: The call is ambiguous between the following methods or properties: 'S.Goo(int)' and 'R.Goo(int)' // 1.Goo(); Diagnostic(ErrorCode.ERR_AmbigCall, "Goo").WithArguments("N.S.Goo(int)", "N.R.Goo(int)").WithLocation(13, 15)); } [Fact, WorkItem(1010648, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1010648")] public void ExtensionMethodsInTheContainingClassDoNotHaveHigherPrecedence() { const string source = @" namespace N { using static Program; static class Program { static void Main() { 1.Goo(); } public static void Goo(this int x) { } } static class R { public static void Goo(this int x) { } } }"; var compilation = CreateCompilationWithMscorlib40AndSystemCore(source); compilation.VerifyDiagnostics( // (10,15): error CS0121: The call is ambiguous between the following methods or properties: 'Program.Goo(int)' and 'R.Goo(int)' // 1.Goo(); Diagnostic(ErrorCode.ERR_AmbigCall, "Goo").WithArguments("N.Program.Goo(int)", "N.R.Goo(int)").WithLocation(10, 15), // (4,5): hidden CS8019: Unnecessary using directive. // using Program; Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using static Program;").WithLocation(4, 5)); } [Fact, WorkItem(1010648, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1010648")] public void UsingAliasDoesNotImportExtensionMethods() { const string source = @" namespace K { using X = N.S; class Program { static void Main() { 1.Goo(); } } } namespace N { static class S { public static void Goo(this int x) { } } }"; var compilation = CreateCompilationWithMscorlib40AndSystemCore(source); compilation.VerifyDiagnostics( // (9,15): error CS1061: 'int' does not contain a definition for 'Goo' and no extension method 'Goo' accepting a first argument of type 'int' could be found (are you missing a using directive or an assembly reference?) // 1.Goo(); Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "Goo").WithArguments("int", "Goo").WithLocation(9, 15), // (4,5): hidden CS8019: Unnecessary using directive. // using X = N.S; Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using X = N.S;").WithLocation(4, 5)); } [WorkItem(1094849, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1094849"), WorkItem(2288, "https://github.com/dotnet/roslyn/issues/2288")] [Fact] public void LookupSymbolsWithPartialInference() { var source = @" using System.Collections.Generic; namespace ConsoleApplication22 { static class Program { static void Main(string[] args) { } internal static void GetEnumerableDisposable1<T, TEnumerator>(this IEnumerable<T> enumerable) where TEnumerator : struct , IEnumerator<T> { } internal static void GetEnumerableDisposable2<T, TEnumerator>(this IEnumerable<T> enumerable) where TEnumerator : struct { } private static void Overlaps<T, TEnumerator>(IEnumerable<T> other) where TEnumerator : struct, IEnumerator<T> { other.GetEnumerableDisposable1<T, TEnumerator>(); } } }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics(); var syntaxTree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(syntaxTree); var member = (MemberAccessExpressionSyntax)syntaxTree.GetRoot().DescendantNodes().OfType<InvocationExpressionSyntax>().Single().Expression; Assert.Equal("other.GetEnumerableDisposable1<T, TEnumerator>", member.ToString()); var type = model.GetTypeInfo(member.Expression).Type; Assert.Equal("System.Collections.Generic.IEnumerable<T>", type.ToTestDisplayString()); var symbols = model.LookupSymbols(member.Expression.EndPosition, type, includeReducedExtensionMethods: true).Select(s => s.Name).ToArray(); Assert.Contains("GetEnumerableDisposable2", symbols); Assert.Contains("GetEnumerableDisposable1", symbols); } [Fact] public void ScriptExtensionMethods() { var source = @"static object F(this object o) { return null; } class C { void M() { this.F(); } } var o = new object(); o.F();"; var compilation = CreateCompilationWithMscorlib45(source, parseOptions: TestOptions.Script); compilation.VerifyDiagnostics(); } [Fact] public void InteractiveExtensionMethods() { var parseOptions = TestOptions.Script; var references = new[] { MscorlibRef, SystemCoreRef }; var source0 = @"static object F(this object o) { return 0; } var o = new object(); o.F();"; var source1 = @"static object G(this object o) { return 1; } var o = new object(); o.G().F();"; var s0 = CSharpCompilation.CreateScriptCompilation( "s0.dll", syntaxTree: SyntaxFactory.ParseSyntaxTree(source0, options: parseOptions), references: references); s0.VerifyDiagnostics(); var s1 = CSharpCompilation.CreateScriptCompilation( "s1.dll", syntaxTree: SyntaxFactory.ParseSyntaxTree(source1, options: parseOptions), previousScriptCompilation: s0, references: references); s1.VerifyDiagnostics(); } [Fact] [WorkItem(11166, "https://github.com/dotnet/roslyn/issues/11166")] public void SemanticModelLookup_01() { var source = @" public static class TestClass { public static void Test() { var Instance = new BaseClass<int>(); Instance.SetMember(32); } } public static class Extensions { public static BC SetMember<BC, TMember>(this BC This, TMember NewValue) where BC : BaseClass<TMember> { This.Member = NewValue; return This; } } public class BaseClass<TMember> { public TMember Member { get; set; } } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var instance = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(n => n.Identifier.ValueText == "Instance").First(); Assert.Equal("Instance.SetMember", instance.Parent.ToString()); var baseClass = model.GetTypeInfo(instance).Type; Assert.Equal("BaseClass<System.Int32>", baseClass.ToTestDisplayString()); var setMember = model.LookupSymbols(instance.Position, baseClass, "SetMember", includeReducedExtensionMethods: true).Single(); Assert.Equal("BaseClass<System.Int32> BaseClass<System.Int32>.SetMember<BaseClass<System.Int32>, TMember>(TMember NewValue)", setMember.ToTestDisplayString()); Assert.Contains(setMember, model.LookupSymbols(instance.Position, baseClass, includeReducedExtensionMethods: true)); } [Fact] [WorkItem(11166, "https://github.com/dotnet/roslyn/issues/11166")] public void SemanticModelLookup_02() { var source = @" public static class TestClass { public static void Test() { var Instance = new BaseClass<int>(); Instance.SetMember(32); } } public static class Extensions { public static BC SetMember<BC, TMember>(this BC This, TMember NewValue) where BC : BaseClass<long> { return This; } } public class BaseClass<TMember> { public TMember Member { get; set; } } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (7,18): error CS0311: The type 'BaseClass<int>' cannot be used as type parameter 'BC' in the generic type or method 'Extensions.SetMember<BC, TMember>(BC, TMember)'. There is no implicit reference conversion from 'BaseClass<int>' to 'BaseClass<long>'. // Instance.SetMember(32); Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "SetMember").WithArguments("Extensions.SetMember<BC, TMember>(BC, TMember)", "BaseClass<long>", "BC", "BaseClass<int>").WithLocation(7, 18) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var instance = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(n => n.Identifier.ValueText == "Instance").First(); Assert.Equal("Instance.SetMember", instance.Parent.ToString()); var baseClass = model.GetTypeInfo(instance).Type; Assert.Equal("BaseClass<System.Int32>", baseClass.ToTestDisplayString()); Assert.Empty(model.LookupSymbols(instance.Position, baseClass, "SetMember", includeReducedExtensionMethods: true)); Assert.Empty(model.LookupSymbols(instance.Position, baseClass, includeReducedExtensionMethods: true).Where(s => s.Name == "SetMembers")); } [Fact] [WorkItem(11166, "https://github.com/dotnet/roslyn/issues/11166")] public void SemanticModelLookup_03() { var source = @" public static class TestClass { public static void Test() { var Instance = new BaseClass<int>(); Instance.SetMember(32); } } public static class Extensions { public static BC SetMember<BC, TMember>(this BC This, TMember NewValue) where BC : BaseClass<TMember>, I1<TMember> { This.Member = NewValue; return This; } } public interface I1<T>{} public class BaseClass<TMember> : I1<TMember> { public TMember Member { get; set; } } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var instance = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(n => n.Identifier.ValueText == "Instance").First(); Assert.Equal("Instance.SetMember", instance.Parent.ToString()); var baseClass = model.GetTypeInfo(instance).Type; Assert.Equal("BaseClass<System.Int32>", baseClass.ToTestDisplayString()); var setMember = model.LookupSymbols(instance.Position, baseClass, "SetMember", includeReducedExtensionMethods: true).Single(); Assert.Equal("BaseClass<System.Int32> BaseClass<System.Int32>.SetMember<BaseClass<System.Int32>, TMember>(TMember NewValue)", setMember.ToTestDisplayString()); Assert.Contains(setMember, model.LookupSymbols(instance.Position, baseClass, includeReducedExtensionMethods: true)); } [Fact] [WorkItem(11166, "https://github.com/dotnet/roslyn/issues/11166")] public void SemanticModelLookup_04() { var source = @" public static class TestClass { public static void Test() { var Instance = new BaseClass<int>(); Instance.SetMember(32); } } public static class Extensions { public static BC SetMember<BC, TMember>(this BC This, TMember NewValue) where BC : BaseClass<TMember>, I1<long> { This.Member = NewValue; return This; } } public interface I1<T>{} public class BaseClass<TMember> : I1<TMember> { public TMember Member { get; set; } } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (7,18): error CS0311: The type 'BaseClass<int>' cannot be used as type parameter 'BC' in the generic type or method 'Extensions.SetMember<BC, TMember>(BC, TMember)'. There is no implicit reference conversion from 'BaseClass<int>' to 'I1<long>'. // Instance.SetMember(32); Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "SetMember").WithArguments("Extensions.SetMember<BC, TMember>(BC, TMember)", "I1<long>", "BC", "BaseClass<int>").WithLocation(7, 18) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var instance = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(n => n.Identifier.ValueText == "Instance").First(); Assert.Equal("Instance.SetMember", instance.Parent.ToString()); var baseClass = model.GetTypeInfo(instance).Type; Assert.Equal("BaseClass<System.Int32>", baseClass.ToTestDisplayString()); Assert.Empty(model.LookupSymbols(instance.Position, baseClass, "SetMember", includeReducedExtensionMethods: true)); Assert.Empty(model.LookupSymbols(instance.Position, baseClass, includeReducedExtensionMethods: true).Where(s => s.Name == "SetMembers")); } [Fact] public void InExtensionMethods() { var source = @" public static class C { public static void M1(this in int p) { } public static void M2(in this int p) { } }"; void Validator(ModuleSymbol module) { var type = module.GlobalNamespace.GetMember<NamedTypeSymbol>("C"); var method = type.GetMember<MethodSymbol>("M1"); Assert.True(method.IsExtensionMethod); var parameter = method.Parameters[0]; Assert.Equal(SpecialType.System_Int32, parameter.Type.SpecialType); Assert.Equal(RefKind.In, parameter.RefKind); method = type.GetMember<MethodSymbol>("M2"); Assert.True(method.IsExtensionMethod); parameter = method.Parameters[0]; Assert.Equal(SpecialType.System_Int32, parameter.Type.SpecialType); Assert.Equal(RefKind.In, parameter.RefKind); } CompileAndVerify(source, validator: Validator, options: TestOptions.ReleaseDll); } [Fact] public void RefExtensionMethods() { var source = @" public static class C { public static void M1(this ref int p) { } public static void M2(ref this int p) { } }"; void Validator(ModuleSymbol module) { var type = module.GlobalNamespace.GetMember<NamedTypeSymbol>("C"); var method = type.GetMember<MethodSymbol>("M1"); Assert.True(method.IsExtensionMethod); var parameter = method.Parameters[0]; Assert.Equal(SpecialType.System_Int32, parameter.Type.SpecialType); Assert.Equal(RefKind.Ref, parameter.RefKind); method = type.GetMember<MethodSymbol>("M2"); Assert.True(method.IsExtensionMethod); parameter = method.Parameters[0]; Assert.Equal(SpecialType.System_Int32, parameter.Type.SpecialType); Assert.Equal(RefKind.Ref, parameter.RefKind); } CompileAndVerify(source, validator: Validator, options: TestOptions.ReleaseDll); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.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 Utils = Microsoft.CodeAnalysis.CSharp.UnitTests.CompilationUtils; using static Roslyn.Test.Utilities.TestMetadata; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Symbols { public class ExtensionMethodTests : CSharpTestBase { [ClrOnlyFact] public void IsExtensionMethod() { var source = @"static class C { internal static void M1(object o) { } internal static void M2(this object o) { } internal static void M3<T, U>(this T t, U u) { } }"; Action<ModuleSymbol> validator = module => { var type = module.GlobalNamespace.GetMember<NamedTypeSymbol>("C"); // Ordinary method. var method = type.GetMember<MethodSymbol>("M1"); Assert.False(method.IsExtensionMethod); var parameter = method.Parameters[0]; Assert.Equal(SpecialType.System_Object, parameter.Type.SpecialType); // Extension method. method = type.GetMember<MethodSymbol>("M2"); Assert.True(method.IsExtensionMethod); parameter = method.Parameters[0]; Assert.Equal(SpecialType.System_Object, parameter.Type.SpecialType); // Extension method with type parameters. method = type.GetMember<MethodSymbol>("M3"); Assert.True(method.IsExtensionMethod); parameter = method.Parameters[0]; Assert.Equal(TypeKind.TypeParameter, parameter.Type.TypeKind); }; CompileAndVerify(source, validator: validator, options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal)); } /// <summary> /// IsExtensionMethod should be false for /// invalid extension methods. /// </summary> [Fact] public void InvalidExtensionMethods() { var ilSource = @".assembly extern mscorlib { .ver 4:0:0:0 .publickeytoken = (B7 7A 5C 56 19 34 E0 89) } .assembly extern System.Core {} .assembly '<<GeneratedFileName>>' { .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) } .class public C { .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) .method public static void M1() { .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) ret } .method public void M2(object o) { .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) ret } } .class public S { .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) .method public static void M1() { .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) ret } .method public static void M2([out] object& o) { .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) ret } .method public static void M3(object[] o) { .param [1] .custom instance void [mscorlib]System.ParamArrayAttribute::.ctor() = ( 01 00 00 00 ) .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) ret } } "; var source = @"class A { internal static C F = null; internal static S G = null; }"; var compilation = CreateCompilationWithILAndMscorlib40(source, ilSource, appendDefaultHeader: false); var refType = compilation.Assembly.GlobalNamespace.GetMember<NamedTypeSymbol>("A"); var type = (NamedTypeSymbol)refType.GetMember<FieldSymbol>("F").Type; // Static method no args. var method = type.GetMember<MethodSymbol>("M1"); Assert.Equal(0, method.Parameters.Length); Assert.True(method.IsStatic); Assert.False(method.IsExtensionMethod); // Instance method. method = type.GetMember<MethodSymbol>("M2"); Assert.Equal(1, method.Parameters.Length); Assert.False(method.IsStatic); Assert.False(method.IsExtensionMethod); type = (NamedTypeSymbol)refType.GetMember<FieldSymbol>("G").Type; // Static method no args. method = type.GetMember<MethodSymbol>("M1"); Assert.Equal(0, method.Parameters.Length); Assert.True(method.IsStatic); Assert.False(method.IsExtensionMethod); // Static method out param. method = type.GetMember<MethodSymbol>("M2"); Assert.Equal(1, method.Parameters.Length); Assert.True(method.IsStatic); Assert.False(method.IsExtensionMethod); // Static method params array. method = type.GetMember<MethodSymbol>("M3"); Assert.Equal(1, method.Parameters.Length); Assert.True(method.IsStatic); Assert.False(method.IsExtensionMethod); } [ClrOnlyFact] public void OverloadResolution() { var source = @"class C { void N() { this.M(3); (new C()).M(0.5); } } static class S { public static void M(this object o, int i) { } public static void M(this C c, int i) { } public static void M(this C c, double x) { } }"; CompileAndVerify(source); } [Fact] public void SameNameAsMember() { var source = @"class C { public object F = null; public object P { get; set; } public class T { } static void A(System.Action a) { } static void B(C c) { c.F(c.F); c.P(c.P); c.T(); A(c.F); A(c.P); A(((object)c).F); A(((object)c).P); } } static class S { public static void F(this object o) { } public static void F(this object x, object y) { } public static void P(this object o) { } public static void P(this object x, object y) { } public static void T(this object o) { } }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (12,11): error CS1503: Argument 1: cannot convert from 'object' to 'System.Action' Diagnostic(ErrorCode.ERR_BadArgType, "c.F").WithArguments("1", "object", "System.Action").WithLocation(12, 11), // (13,11): error CS1503: Argument 1: cannot convert from 'object' to 'System.Action' Diagnostic(ErrorCode.ERR_BadArgType, "c.P").WithArguments("1", "object", "System.Action").WithLocation(13, 11)); } [WorkItem(529063, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529063")] [Fact] public void GetSymbolInfoTest() { var source = @"static class S { static void Goo(this string s) { } static void Main() { string s = null; s.Goo(); } }"; var compilation = CreateCompilation(source); var syntaxTree = compilation.SyntaxTrees.Single(); var gooSymbol = (IMethodSymbol)compilation.GetSemanticModel(syntaxTree).GetSymbolInfo( syntaxTree.GetCompilationUnitRoot().DescendantNodes().OfType<MemberAccessExpressionSyntax>().Single()).Symbol; Assert.True(gooSymbol.IsExtensionMethod); Assert.Equal(MethodKind.ReducedExtension, gooSymbol.MethodKind); var gooOriginal = gooSymbol.ReducedFrom; Assert.True(gooOriginal.IsExtensionMethod); Assert.Equal(MethodKind.Ordinary, gooOriginal.MethodKind); } [Fact] public void InaccessibleExtensionMethodSameNameAsMember() { var source = @"class C { public object F = null; public object P { get; set; } static void A(System.Action a) { } static void B(C c) { c.F(); c.P(); A(c.F); A(c.P); } } static class S { private static void F(this object o) { } private static void P(this object o) { } }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (8,11): error CS1955: Non-invocable member 'C.F' cannot be used like a method. // c.F(); Diagnostic(ErrorCode.ERR_NonInvocableMemberCalled, "F").WithArguments("C.F"), // (9,11): error CS1955: Non-invocable member 'C.P' cannot be used like a method. // c.P(); Diagnostic(ErrorCode.ERR_NonInvocableMemberCalled, "P").WithArguments("C.P"), // (10,11): error CS1503: Argument 1: cannot convert from 'object' to 'System.Action' Diagnostic(ErrorCode.ERR_BadArgType, "c.F").WithArguments("1", "object", "System.Action").WithLocation(10, 11), // (11,11): error CS1503: Argument 1: cannot convert from 'object' to 'System.Action' Diagnostic(ErrorCode.ERR_BadArgType, "c.P").WithArguments("1", "object", "System.Action").WithLocation(11, 11)); } [ClrOnlyFact] public void ExtensionMethodInTheSameClass() { var source = @"using System; static class Program { static void Main() { ""ABC"".Goo(); Action a = ""123"".Goo; a(); a = new Action(a); a(); a = new Action(""xyz"".Goo); a(); } static void Goo(this string x) { Console.WriteLine(x); } }"; CompileAndVerify(source, expectedOutput: @"ABC 123 123 xyz"); } [WorkItem(541143, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541143")] [ClrOnlyFact] public void NumericConversionsAreNotAllowed() { var source = @" using System; static class Program { static void Main() { 0.Goo(); } static void Goo(this long x) { Console.WriteLine(""long""); } static void Goo(this object x) { Console.WriteLine(""object""); } } "; CompileAndVerify(source, expectedOutput: "object"); } [WorkItem(541144, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541144")] [ClrOnlyFact] public void EnumerationConversionsAreNotAllowed() { var source = @" using System; static class Program { static void Main() { 0.Goo(); } static void Goo(this DayOfWeek x) { Console.WriteLine(""DayOfWeek""); } static void Goo(this object x) { Console.WriteLine(""object""); } } "; CompileAndVerify(source, expectedOutput: "object"); } [WorkItem(541145, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541145")] [ClrOnlyFact] public void CannotCreateDelegateToExtensionMethodOnValueType() { var source = @" using System; static class Program { static void Main() { Bar(x => x.Goo); } static void Bar(Func<int, Action> x) { Console.WriteLine(1); } static void Bar(Func<object, Action> x) { Console.WriteLine(2); } static void Goo<T>(this T x) { } } "; CompileAndVerify(source, expectedOutput: "2"); } [WorkItem(528426, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528426")] [ClrOnlyFact] public void TypedReferenceCannotBeUsedAsTypeArgument() { var source = @" using System; static class Program { static void Main() { Bar(y => new TypedReference().Goo(y)); } static void Bar(Action<string> a) { Console.WriteLine(1); } static void Bar(Action<int> a) { Console.WriteLine(2); } static void Goo<T>(this T x, string y) { } static void Goo(this TypedReference x, int y) { } } "; CompileAndVerify(source, expectedOutput: "2"); } [WorkItem(541146, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541146")] [WorkItem(868538, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/868538")] [Fact] public void VariablesUsedInExtensionMethodGroupMustBeDefinitelyAssigned() { var source = @" using System; static class Program { static void Main() { string s; bool x = s.Goo is Action; int i; bool y = i.Goo is Action; } static void Goo(this string x) { } } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (9,18): error CS0837: The first operand of an 'is' or 'as' operator may not be a lambda expression, anonymous method, or method group. // bool x = s.Goo is Action; Diagnostic(ErrorCode.ERR_LambdaInIsAs, "s.Goo is Action").WithLocation(9, 18), // (12,18): error CS0837: The first operand of an 'is' or 'as' operator may not be a lambda expression, anonymous method, or method group. // bool y = i.Goo is Action; Diagnostic(ErrorCode.ERR_LambdaInIsAs, "i.Goo is Action").WithLocation(12, 18), // (9,18): error CS0165: Use of unassigned local variable 's' // bool x = s.Goo is Action; Diagnostic(ErrorCode.ERR_UseDefViolation, "s").WithArguments("s").WithLocation(9, 18), // (12,18): error CS0165: Use of unassigned local variable 'i' // bool y = i.Goo is Action; Diagnostic(ErrorCode.ERR_UseDefViolation, "i").WithArguments("i").WithLocation(12, 18) ); } [WorkItem(541187, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541187")] [Fact] public void ExtensionMethodsCannotBeDeclaredInNamespaces() { var source = @" namespace N { static void Goo(this int x) { } } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (4,17): error CS0116: A namespace does not directly contain members such as fields or methods Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "Goo"), // (4,17): error CS1106: Extension methods must be defined in a non-generic static class Diagnostic(ErrorCode.ERR_BadExtensionAgg, "Goo")); } [WorkItem(541189, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541189")] [ClrOnlyFact] public void ExtensionMethodsDeclaredInEnclosingNamespaceArePreferredOverImported2() { var source = @" using System; using N; static class Program { static void Main() { """".Goo(1); } public static void Goo(this string x, object y) { Console.WriteLine(1); } } namespace N { static class C { public static void Goo(this string x, int y) { Console.WriteLine(2); } } }"; CompileAndVerify(source, expectedOutput: "1"); } [WorkItem(541189, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541189")] [ClrOnlyFact] public void ExtensionMethodsDeclaredInEnclosingNamespaceArePreferredOverImported() { var source = @" using System; using N; static class Program { static void Main() { """".Goo(); } public static void Goo(this string x) { Console.WriteLine(1); } } namespace N { static class C { public static void Goo(this string x) { Console.WriteLine(2); } } } "; CompileAndVerify(source, expectedOutput: "1"); } [ClrOnlyFact] public void CandidateSearchByArgType() { var source = @"static class A { public static void E(this object o, double d) { } } namespace N1 { static class B { public static void E(this object o, bool b) { } } } namespace N1.N2 { static class C { public static void E(this object o, int i) { } static void Main() { 1.E(2.0); } } }"; CompileAndVerify(source); } [ClrOnlyFact] public void CandidateSearchConversion() { var source = @"interface I<T> { } namespace N { class C { static void M() { object o = 1.F1(); o = 2.F2(); o = 3.F3(1, 2, 3); } } static class S1 { internal static void F1<T>(this I<T> t) { } internal static void F2(this double d) { } internal static void F3(this long l, params object[] args) { } } } static class S2 { internal static object F1<T>(this T t) { return null; } internal static object F2(this int i) { return null; } internal static object F3(this int i, params object[] args) { return null; } }"; CompileAndVerify(source); } /// <summary> /// Continue search for extension method candidates in certain /// cases where nearer candidates are not applicable. /// </summary> [Fact] public void CandidateSearch() { var source = @"namespace N1 { namespace N2 { partial class C { // Invalid calls with no extension methods in scope. void M() { this.M1(1, 2, 3); // MethodResolutionKind.NoCorrespondingParameter this.M2(1); // MethodResolutionKind.RequiredParameterMissing this.M3(1, 2.0); // MethodResolutionKind.BadArguments this.M4(null, 2); // MethodResolutionKind.TypeInferenceFailed this.M5<string, string>(null, 2); // Bad arity this.M6(null, null); // Ambiguous } void M1(int x, int y) { } void M2(int x, int y) { } void M3(int x, int y) { } void M3(int x, long y) { } void M4<T>(T x, int y) { } void M4<T>(T x, long y) { } void M5<T>(T x, int y) { } void M5<T>(T x, long y) { } void M6(object x, string y) { } void M6(string x, object y) { } } } } namespace N1 { using N4; namespace N2 { using N3; partial class C { // Same calls as above but with N3.S and N4.S extension methods in scope. void N() { this.M1(1, 2, 3); // MethodResolutionKind.NoCorrespondingParameter this.M2(1); // MethodResolutionKind.RequiredParameterMissing this.M3(1, 2.0); // MethodResolutionKind.BadArguments this.M4(null, 2); // MethodResolutionKind.TypeInferenceFailed this.M5<string, string>(null, 2); // Bad arity this.M6(null, null); // Ambiguous } } } } namespace N3 { static class S { // Same signatures as instance methods above. public static void M1(this N1.N2.C c, int x, int y) { } public static void M2(this N1.N2.C c, int x, int y) { } public static void M3(this N1.N2.C c, int x, int y) { } public static void M3(this N1.N2.C c, int x, long y) { } public static void M4<T>(this N1.N2.C c, T x, int y) { } public static void M4<T>(this N1.N2.C c, T x, long y) { } public static void M5<T>(this N1.N2.C c, T x, int y) { } public static void M5<T>(this N1.N2.C c, T x, long y) { } public static void M6(this N1.N2.C c, object x, string y) { } public static void M6(this N1.N2.C c, string x, object y) { } } } namespace N4 { static class S { // Different signatures but also resulting in errors. public static void M1(this N1.N2.C c, string x, int y, int z) { } public static void M2(this N1.N2.C c, string x) { } public static void M3(this N1.N2.C c, string x) { } public static void M4(this N1.N2.C c, int x, int y) { } public static void M5<T, U>(this N1.N2.C c, T x, T y) { } public static void M6(this N1.N2.C c, int x, int y) { } } }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (10,17): error CS1501: No overload for method 'M1' takes 3 arguments // this.M1(1, 2, 3); // MethodResolutionKind.NoCorrespondingParameter Diagnostic(ErrorCode.ERR_BadArgCount, "M1").WithArguments("M1", "3").WithLocation(10, 22), // (11,17): error CS7036: There is no argument given that corresponds to the required formal parameter 'y' of 'N1.N2.C.M2(int, int)' // this.M2(1); // MethodResolutionKind.RequiredParameterMissing Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "M2").WithArguments("y", "N1.N2.C.M2(int, int)").WithLocation(11, 22), // (12,28): error CS1503: Argument 2: cannot convert from 'double' to 'int' // this.M3(1, 2.0); // MethodResolutionKind.BadArguments Diagnostic(ErrorCode.ERR_BadArgType, "2.0").WithArguments("2", "double", "int").WithLocation(12, 28), // (13,17): error CS0411: The type arguments for method 'N1.N2.C.M4<T>(T, int)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // this.M4(null, 2); // MethodResolutionKind.TypeInferenceFailed Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M4").WithArguments("N1.N2.C.M4<T>(T, int)").WithLocation(13, 22), // (14,22): error CS0305: Using the generic method 'N1.N2.C.M5<T>(T, int)' requires 1 type arguments // this.M5<string, string>(null, 2); // Bad arity Diagnostic(ErrorCode.ERR_BadArity, "M5<string, string>").WithArguments("N1.N2.C.M5<T>(T, int)", "method", "1").WithLocation(14, 22), // (15,17): error CS0121: The call is ambiguous between the following methods or properties: 'N1.N2.C.M6(object, string)' and 'N1.N2.C.M6(string, object)' // this.M6(null, null); // Ambiguous Diagnostic(ErrorCode.ERR_AmbigCall, "M6").WithArguments("N1.N2.C.M6(object, string)", "N1.N2.C.M6(string, object)").WithLocation(15, 22), // (41,17): error CS1501: No overload for method 'M1' takes 3 arguments // this.M1(1, 2, 3); // MethodResolutionKind.NoCorrespondingParameter Diagnostic(ErrorCode.ERR_BadArgCount, "M1").WithArguments("M1", "3").WithLocation(41, 22), // (42,17): error CS7036: There is no argument given that corresponds to the required formal parameter 'y' of 'N1.N2.C.M2(int, int)' // this.M2(1); // MethodResolutionKind.RequiredParameterMissing Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "M2").WithArguments("y", "N1.N2.C.M2(int, int)").WithLocation(42, 22), // (43,28): error CS1503: Argument 2: cannot convert from 'double' to 'int' // this.M3(1, 2.0); // MethodResolutionKind.BadArguments Diagnostic(ErrorCode.ERR_BadArgType, "2.0").WithArguments("2", "double", "int").WithLocation(43, 28), // (44,17): error CS0411: The type arguments for method 'N1.N2.C.M4<T>(T, int)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // this.M4(null, 2); // MethodResolutionKind.TypeInferenceFailed Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M4").WithArguments("N1.N2.C.M4<T>(T, int)").WithLocation(44, 22), // (45,47): error CS1503: Argument 3: cannot convert from 'int' to 'string' // this.M5<string, string>(null, 2); // Bad arity Diagnostic(ErrorCode.ERR_BadArgType, "2").WithArguments("3", "int", "string").WithLocation(45, 47), // (46,17): error CS0121: The call is ambiguous between the following methods or properties: 'N1.N2.C.M6(object, string)' and 'N1.N2.C.M6(string, object)' // this.M6(null, null); // Ambiguous Diagnostic(ErrorCode.ERR_AmbigCall, "M6").WithArguments("N1.N2.C.M6(object, string)", "N1.N2.C.M6(string, object)").WithLocation(46, 22)); } /// <summary> /// End search for extension method candidates /// if current method group is ambiguous. /// </summary> [Fact] public void EndSearchIfAmbiguous() { var source = @"namespace N1 { internal static class S { public static void E(this object o, int x, object y) { } public static void E(this object o, double x, int y) { } public static void E(this object o, A x, B y) { } } class A { } class B { } namespace N2 { internal static class S { public static void E(this object o, double x, A y) { } public static void E(this object o, double x, B y) { } } class C { static void M(object o) { o.E(1, null); // ambiguous o.E(1.0, 2.0); // N2.S.E(object, double, A) o.E(1.0, 2); // N1.S.E(object, double, int) o.E(null, null); // N1.S.E(object, A, B) } } } }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (22,17): error CS0121: The call is ambiguous between the following methods or properties: 'N1.N2.S.E(object, double, N1.A)' and 'N1.N2.S.E(object, double, N1.B)' Diagnostic(ErrorCode.ERR_AmbigCall, "E").WithArguments("N1.N2.S.E(object, double, N1.A)", "N1.N2.S.E(object, double, N1.B)").WithLocation(22, 19), // (23,26): error CS1503: Argument 3: cannot convert from 'double' to 'N1.A' Diagnostic(ErrorCode.ERR_BadArgType, "2.0").WithArguments("3", "double", "N1.A").WithLocation(23, 26)); } [Fact(Skip = "528425")] public void ParenthesizedMethodGroup() { var source = @"static class S { public static void E(this object a, object b) { } public static void E(this object o, int i) { } private static void E(this object o, object x, object y) { } } class C { void E(int i, int j) { } void M() { ((this.E))(null); ((this.E))(null, null); } }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (13, 9): error CS0122: 'S.E(object, object, object)' is inaccessible due to its protection level Diagnostic(ErrorCode.ERR_BadAccess, "((this.E))(null, null)").WithArguments("S.E(object, object, object)").WithLocation(13, 9)); } [ClrOnlyFact] public void DelegateMembers() { var source = @"using System; class C { public Action<int> F = A; public Action<int> P { get { return A; } } static void A(int i) { Console.WriteLine(i); } static void Main() { C c = new C(); c.F(1); c.P(2); } }"; CompileAndVerify(source, expectedOutput: @"1 2"); } [Fact] public void DelegatesAndExtensionMethods() { var source = @"using System; class C { public Action<int> F = A; public Action<int> P { get { return A; } } static void A(int i) { } void M() { this.F(1, 2); this.P(1.0); } } class D { void F(int i) { } void P(int i) { } void M() { this.F(1, 2); this.P(2.0); } } static class S { public static void F(this object o, int x, int y) { } public static void P(this object o, double d) { } }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (9, 9): error CS1593: Delegate 'System.Action<int>' does not take 2 arguments Diagnostic(ErrorCode.ERR_BadDelArgCount, "F").WithArguments("System.Action<int>", "2").WithLocation(9, 14), // (10,16): error CS1503: Argument 1: cannot convert from 'double' to 'int' Diagnostic(ErrorCode.ERR_BadArgType, "1.0").WithArguments("1", "double", "int").WithLocation(10, 16)); } [ClrOnlyFact] public void DelegatesFromOverloads() { var source = @"namespace N { class C { void M(System.Action<object> a) { M(this.F); a = this.F; C c = new C(); M(c.G); a = c.G; } } static class A { internal static void G(this C c) { } } } static class B { internal static void F(this object o) { } internal static void F(this object x, object y) { } internal static void G(this object x, object y) { } }"; var compilation = CompileAndVerify(source); compilation.VerifyIL("N.C.M", @"{ // Code size 71 (0x47) .maxstack 3 .locals init (N.C V_0) //c IL_0000: ldarg.0 IL_0001: ldarg.0 IL_0002: ldftn ""void B.F(object, object)"" IL_0008: newobj ""System.Action<object>..ctor(object, System.IntPtr)"" IL_000d: call ""void N.C.M(System.Action<object>)"" IL_0012: ldarg.0 IL_0013: ldftn ""void B.F(object, object)"" IL_0019: newobj ""System.Action<object>..ctor(object, System.IntPtr)"" IL_001e: starg.s V_1 IL_0020: newobj ""N.C..ctor()"" IL_0025: stloc.0 IL_0026: ldarg.0 IL_0027: ldloc.0 IL_0028: ldftn ""void B.G(object, object)"" IL_002e: newobj ""System.Action<object>..ctor(object, System.IntPtr)"" IL_0033: call ""void N.C.M(System.Action<object>)"" IL_0038: ldloc.0 IL_0039: ldftn ""void B.G(object, object)"" IL_003f: newobj ""System.Action<object>..ctor(object, System.IntPtr)"" IL_0044: starg.s V_1 IL_0046: ret }"); } [ClrOnlyFact] public void DelegatesAsArguments() { var source = @"using System; namespace N { class C { static void M(object o) { o.M1(o.F1); // S1.M1(S1.F1) o.M1(o.F2); // S1.M1(S2.F2) o.M2(o.F3); // S2.M2(S1.F3) o.M2(o.F4); // S2.M2(S2.F4) } } static class S1 { internal static void M1(this object o, Action<object> f) { } internal static void M2(this object o, Action f) { } internal static void F1(this object x, object y) { } internal static void F2(this object x, int y) { } internal static void F3(this object x, object y) { } internal static void F4(this object x, int y) { } } } static class S2 { internal static void M1(this object o, Action f) { } internal static void M2(this object o, Action<object> f) { } internal static void F1(this object x, int y) { } internal static void F2(this object x, object y) { } internal static void F3(this object x, int y) { } internal static void F4(this object x, object y) { } }"; var compilation = CompileAndVerify(source); compilation.VerifyIL("N.C.M", @" { // Code size 73 (0x49) .maxstack 3 IL_0000: ldarg.0 IL_0001: ldarg.0 IL_0002: ldftn ""void N.S1.F1(object, object)"" IL_0008: newobj ""System.Action<object>..ctor(object, System.IntPtr)"" IL_000d: call ""void N.S1.M1(object, System.Action<object>)"" IL_0012: ldarg.0 IL_0013: ldarg.0 IL_0014: ldftn ""void S2.F2(object, object)"" IL_001a: newobj ""System.Action<object>..ctor(object, System.IntPtr)"" IL_001f: call ""void N.S1.M1(object, System.Action<object>)"" IL_0024: ldarg.0 IL_0025: ldarg.0 IL_0026: ldftn ""void N.S1.F3(object, object)"" IL_002c: newobj ""System.Action<object>..ctor(object, System.IntPtr)"" IL_0031: call ""void S2.M2(object, System.Action<object>)"" IL_0036: ldarg.0 IL_0037: ldarg.0 IL_0038: ldftn ""void S2.F4(object, object)"" IL_003e: newobj ""System.Action<object>..ctor(object, System.IntPtr)"" IL_0043: call ""void S2.M2(object, System.Action<object>)"" IL_0048: ret }"); } [Fact] public void DelegatesFromInvalidOverloads() { var source = @"namespace N { class C { static void M1(System.Func<object, object> f) { } static void M2(System.Action<object> f) { } static void M() { C c = new C(); M1(c.F1); // wrong return type M2(c.F1); M1(c.F2); M2(c.F2); // wrong return type M1(c.F3); // ambiguous } } static class S1 { internal static void F1(this C c) { } internal static object F2(this C c) { return null; } } } static class S2 { internal static void F1(this object x, object y) { } internal static object F2(this N.C x, object y) { return null; } internal static object F3(this N.C x, object y) { return null; } } static class S3 { internal static object F3(this N.C x, object y) { return null; } }"; CreateCompilationWithMscorlib40(source, references: new[] { Net40.SystemCore }, parseOptions: TestOptions.WithoutImprovedOverloadCandidates).VerifyDiagnostics( // (10,16): error CS0407: 'void S2.F1(object, object)' has the wrong return type // M1(c.F1); // wrong return type Diagnostic(ErrorCode.ERR_BadRetType, "c.F1").WithArguments("S2.F1(object, object)", "void").WithLocation(10, 16), // (13,16): error CS0407: 'object S2.F2(C, object)' has the wrong return type // M2(c.F2); // wrong return type Diagnostic(ErrorCode.ERR_BadRetType, "c.F2").WithArguments("S2.F2(N.C, object)", "object").WithLocation(13, 16), // (14,16): error CS0121: The call is ambiguous between the following methods or properties: 'S2.F3(C, object)' and 'S3.F3(C, object)' // M1(c.F3); // ambiguous Diagnostic(ErrorCode.ERR_AmbigCall, "c.F3").WithArguments("S2.F3(N.C, object)", "S3.F3(N.C, object)").WithLocation(14, 16)); // NOTE: we have a degradation in the quality of diagnostics for a delegate conversion in this particular failure case. // See https://github.com/dotnet/roslyn/issues/24787 // It is caused by a combination of two shortcomings in the computation of diagnostics. First, in `BindExtensionMethod` // when we fail to find an applicable extension method, we only report a diagnostic for the first extension method group // that failed, even if some other extension method group contains a much better candidate. In the case of this test the first // extension method group contains a method with the wrong number of parameters, while the second one has an extension method // that fails only because of its return type mismatch. Second, in // `OverloadResolutionResult<TMember>.ReportDiagnostics<T>`, we do not report a diagnostic for the failure // `MemberResolutionKind.NoCorrespondingParameter`, leaving it to the caller to notice that we failed to produce a // diagnostic (the caller has to grub through the diagnostic bag to see that there is no error there) and then the caller // has to produce a generic error message, which we see below. It does not appear that all callers have that test, though, // suggesting there may be a latent bug of missing diagnostics. CreateCompilationWithMscorlib40(source, references: new[] { Net40.SystemCore }).VerifyDiagnostics( // (10,16): error CS1503: Argument 1: cannot convert from 'method group' to 'Func<object, object>' // M1(c.F1); // wrong return type Diagnostic(ErrorCode.ERR_BadArgType, "c.F1").WithArguments("1", "method group", "System.Func<object, object>").WithLocation(10, 16), // (13,16): error CS1503: Argument 1: cannot convert from 'method group' to 'Action<object>' // M2(c.F2); // wrong return type Diagnostic(ErrorCode.ERR_BadArgType, "c.F2").WithArguments("1", "method group", "System.Action<object>").WithLocation(13, 16), // (14,16): error CS0121: The call is ambiguous between the following methods or properties: 'S2.F3(C, object)' and 'S3.F3(C, object)' // M1(c.F3); // ambiguous Diagnostic(ErrorCode.ERR_AmbigCall, "c.F3").WithArguments("S2.F3(N.C, object)", "S3.F3(N.C, object)").WithLocation(14, 16)); } [Fact] public void DelegatesAsInvalidArguments() { var source = @"class A { } class B { } delegate A DA(DA a); delegate B DB(DB b); class C { static void M() { M1(F); M2(F); M1(G(F)); M2(G(F)); } static void M1(DA f) { } static void M2(DB f) { } static A F(DA a) { return null; } static B F(DB b) { return null; } static DA G(DA f) { return f; } static DB G(DB f) { return f; } } namespace N { class C { static void M(object o) { o.M1(o.F); o.M2(o.F); o.M1(G(o.F)); o.M2(G(o.F)); } static DA G(DA f) { return f; } static DB G(DB f) { return f; } } static class S1 { internal static void M1(this object o, DA f) { } internal static void M2(this object o, DB f) { } internal static A F(this object o, DA a) { return null; } } } static class S2 { internal static B F(this object o, DB b) { return null; } }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (11,12): error CS0121: The call is ambiguous between the following methods or properties: 'C.G(DA)' and 'C.G(DB)' Diagnostic(ErrorCode.ERR_AmbigCall, "G").WithArguments("C.G(DA)", "C.G(DB)").WithLocation(11, 12), // (12,12): error CS0121: The call is ambiguous between the following methods or properties: 'C.G(DA)' and 'C.G(DB)' Diagnostic(ErrorCode.ERR_AmbigCall, "G").WithArguments("C.G(DA)", "C.G(DB)").WithLocation(12, 12), // (29,18): error CS0121: The call is ambiguous between the following methods or properties: 'N.C.G(DA)' and 'N.C.G(DB)' Diagnostic(ErrorCode.ERR_AmbigCall, "G").WithArguments("N.C.G(DA)", "N.C.G(DB)").WithLocation(29, 18), // (30,18): error CS0121: The call is ambiguous between the following methods or properties: 'N.C.G(DA)' and 'N.C.G(DB)' Diagnostic(ErrorCode.ERR_AmbigCall, "G").WithArguments("N.C.G(DA)", "N.C.G(DB)").WithLocation(30, 18)); } /// <summary> /// Extension methods should be resolved correctly even /// in cases where a method group is not allowed. /// </summary> [Fact] public void InvalidUseOfExtensionMethodGroup() { var source = @"class C { static void M(object o) { o.E += o.E; if (o.E != null) { M(o.E); o.E.ToString(); o = !o.E; } o.F += o.F; if (o.F != null) { M(o.F); o.F.ToString(); o = !o.F; } o.E.F(); } } static class S { internal static object E(this object o) { return null; } private static object F(this object o) { return null; } }"; var compilation = CreateCompilation(source, parseOptions: TestOptions.Regular9); compilation.VerifyDiagnostics( // (5,9): error CS1656: Cannot assign to 'E' because it is a 'method group' // o.E += o.E; Diagnostic(ErrorCode.ERR_AssgReadonlyLocalCause, "o.E").WithArguments("E", "method group").WithLocation(5, 9), // (6,13): error CS0019: Operator '!=' cannot be applied to operands of type 'method group' and '<null>' // if (o.E != null) Diagnostic(ErrorCode.ERR_BadBinaryOps, "o.E != null").WithArguments("!=", "method group", "<null>").WithLocation(6, 13), // (8,15): error CS1503: Argument 1: cannot convert from 'method group' to 'object' // M(o.E); Diagnostic(ErrorCode.ERR_BadArgType, "o.E").WithArguments("1", "method group", "object").WithLocation(8, 15), // (9,15): error CS0119: 'S.E(object)' is a method, which is not valid in the given context // o.E.ToString(); Diagnostic(ErrorCode.ERR_BadSKunknown, "E").WithArguments("S.E(object)", "method").WithLocation(9, 15), // (10,17): error CS0023: Operator '!' cannot be applied to operand of type 'method group' // o = !o.E; Diagnostic(ErrorCode.ERR_BadUnaryOp, "!o.E").WithArguments("!", "method group").WithLocation(10, 17), // (12,11): error CS1061: 'object' does not contain a definition for 'F' and no accessible extension method 'F' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?) // o.F += o.F; Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "F").WithArguments("object", "F").WithLocation(12, 11), // (12,18): error CS1061: 'object' does not contain a definition for 'F' and no accessible extension method 'F' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?) // o.F += o.F; Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "F").WithArguments("object", "F").WithLocation(12, 18), // (13,15): error CS1061: 'object' does not contain a definition for 'F' and no accessible extension method 'F' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?) // if (o.F != null) Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "F").WithArguments("object", "F").WithLocation(13, 15), // (15,17): error CS1061: 'object' does not contain a definition for 'F' and no accessible extension method 'F' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?) // M(o.F); Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "F").WithArguments("object", "F").WithLocation(15, 17), // (16,15): error CS1061: 'object' does not contain a definition for 'F' and no accessible extension method 'F' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?) // o.F.ToString(); Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "F").WithArguments("object", "F").WithLocation(16, 15), // (17,20): error CS1061: 'object' does not contain a definition for 'F' and no accessible extension method 'F' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?) // o = !o.F; Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "F").WithArguments("object", "F").WithLocation(17, 20), // (19,11): error CS0119: 'S.E(object)' is a method, which is not valid in the given context // o.E.F(); Diagnostic(ErrorCode.ERR_BadSKunknown, "E").WithArguments("S.E(object)", "method").WithLocation(19, 11) ); } [Fact] public void Inaccessible() { var source = @"using System; class C { static void M(object o) { o.F(); M(o.F); Action a = o.F; o = o.F; } static void M(Action a) { } } static class S { static void F(this object o) { } }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (6,11): error CS1061: 'object' does not contain a definition for 'F' and no extension method 'F' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?) // o.F(); Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "F").WithArguments("object", "F").WithLocation(6, 11), // (7,13): error CS1061: 'object' does not contain a definition for 'F' and no extension method 'F' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?) // M(o.F); Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "F").WithArguments("object", "F").WithLocation(7, 13), // (8,22): error CS1061: 'object' does not contain a definition for 'F' and no extension method 'F' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?) // Action a = o.F; Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "F").WithArguments("object", "F").WithLocation(8, 22), // (9,15): error CS1061: 'object' does not contain a definition for 'F' and no extension method 'F' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?) // o = o.F; Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "F").WithArguments("object", "F").WithLocation(9, 15) ); } [Fact(Skip = "528425")] public void InaccessibleAndAccessible() { var source = @"using System; namespace N { class C { static void M(object o) { o.F(null); o.F(); M1(o.F); M2(o.F); Action<object> a = o.F; Action b = o.F; o.G(); // no error } static void M1(Action<object> a) { } static void M2(Action a) { } } static class S1 { static void F(this object o) { } internal static void F(this object x, object y) { } static void G(this object o) { } } } static class S2 { internal static void G(this object o) { } }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (9,9): error CS0122: 'S.F(object)' is inaccessible due to its protection level Diagnostic(ErrorCode.ERR_BadAccess, "F").WithArguments("S.F(object)").WithLocation(9, 9), // (11,9): error CS1503: Argument 1: cannot convert from 'method group' to 'System.Action' Diagnostic(ErrorCode.ERR_BadArgType, "o.F").WithArguments("1", "method group", "System.Action").WithLocation(11, 9), // (13,20): error CS0122: 'S.F(object)' is inaccessible due to its protection level Diagnostic(ErrorCode.ERR_BadAccess, "F").WithArguments("S.F(object)").WithLocation(13, 20)); } /// <summary> /// Inaccessible instance member and /// extension method of same name. /// </summary> [Fact] public void InaccessibleInstanceMember() { var source = @"using System; class A { void F() { } Action G; A H; } namespace N1 { class B { // No extension methods. static void M(A a) { a.F(); a.G(); a.H(); M(a.F); M(a.G); M(a.H); } static void M(Action a) { } } } namespace N2 { class C { // Valid extension methods. static void M(A a) { a.F(); a.G(); a.H(); M(a.F); M(a.G); M(a.H); } static void M(Action a) { } } static class S { internal static void F(this A a) { } internal static void G(this A a) { } internal static void H(this A a) { } } } namespace N3 { class C { // Inaccessible extension methods. static void M(A a) { a.F(); a.G(); a.H(); M(a.F); M(a.G); M(a.H); } static void M(Action a) { } } static class S { static void F(this A a) { } static void G(this A a) { } static void H(this A a) { } } }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (15,15): error CS0122: 'A.F()' is inaccessible due to its protection level // a.F(); Diagnostic(ErrorCode.ERR_BadAccess, "F").WithArguments("A.F()"), // (16,15): error CS0122: 'A.G' is inaccessible due to its protection level // a.G(); Diagnostic(ErrorCode.ERR_BadAccess, "G").WithArguments("A.G"), // (17,15): error CS1955: Non-invocable member 'A.H' cannot be used like a method. // a.H(); Diagnostic(ErrorCode.ERR_NonInvocableMemberCalled, "H").WithArguments("A.H"), // (18,17): error CS0122: 'A.F()' is inaccessible due to its protection level // M(a.F); Diagnostic(ErrorCode.ERR_BadAccess, "F").WithArguments("A.F()"), // (19,17): error CS0122: 'A.G' is inaccessible due to its protection level // M(a.G); Diagnostic(ErrorCode.ERR_BadAccess, "G").WithArguments("A.G"), // (20,17): error CS0122: 'A.H' is inaccessible due to its protection level // M(a.H); Diagnostic(ErrorCode.ERR_BadAccess, "H").WithArguments("A.H"), // (55,15): error CS0122: 'A.F()' is inaccessible due to its protection level // a.F(); Diagnostic(ErrorCode.ERR_BadAccess, "F").WithArguments("A.F()"), // (56,15): error CS0122: 'A.G' is inaccessible due to its protection level // a.G(); Diagnostic(ErrorCode.ERR_BadAccess, "G").WithArguments("A.G"), // (57,15): error CS1955: Non-invocable member 'A.H' cannot be used like a method. // a.H(); Diagnostic(ErrorCode.ERR_NonInvocableMemberCalled, "H").WithArguments("A.H"), // (58,17): error CS0122: 'A.F()' is inaccessible due to its protection level // M(a.F); Diagnostic(ErrorCode.ERR_BadAccess, "F").WithArguments("A.F()"), // (59,17): error CS0122: 'A.G' is inaccessible due to its protection level // M(a.G); Diagnostic(ErrorCode.ERR_BadAccess, "G").WithArguments("A.G"), // (60,17): error CS0122: 'A.H' is inaccessible due to its protection level // M(a.H); Diagnostic(ErrorCode.ERR_BadAccess, "H").WithArguments("A.H"), // (5,12): warning CS0169: The field 'A.G' is never used // Action G; Diagnostic(ErrorCode.WRN_UnreferencedField, "G").WithArguments("A.G"), // (6,7): warning CS0169: The field 'A.H' is never used // A H; Diagnostic(ErrorCode.WRN_UnreferencedField, "H").WithArguments("A.H")); } /// <summary> /// Method arguments should be evaluated, /// even if too many. /// </summary> [Fact] public void InaccessibleTooManyArgs() { var source = @"static class S { static void E(this object o) { } } class A { static void F() { } void G() { } } class B { static void M() { A a = null; M(a.E(), A.F(), a.G()); } }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (15,13): error CS1061: 'A' does not contain a definition for 'E' and no extension method 'E' accepting a first argument of type 'A' could be found (are you missing a using directive or an assembly reference?) // M(a.E(), A.F(), a.G()); Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "E").WithArguments("A", "E").WithLocation(15, 13), // (15,20): error CS0122: 'A.F()' is inaccessible due to its protection level // M(a.E(), A.F(), a.G()); Diagnostic(ErrorCode.ERR_BadAccess, "F").WithArguments("A.F()").WithLocation(15, 20), // (15,27): error CS0122: 'A.G()' is inaccessible due to its protection level // M(a.E(), A.F(), a.G()); Diagnostic(ErrorCode.ERR_BadAccess, "G").WithArguments("A.G()").WithLocation(15, 27) ); } [WorkItem(541330, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541330")] [WorkItem(541335, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541335")] [Fact] public void ReturnDelegateAsObject() { var source = @"class C { static object M(object o) { return o.E; } } static class S { internal static void E(this object o) { } }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (5,18): error CS0428: Cannot convert method group 'E' to non-delegate type 'object'. Did you intend to invoke the method? Diagnostic(ErrorCode.ERR_MethGrpToNonDel, "E").WithArguments("E", "object").WithLocation(5, 18)); } [Fact] public void AllExtensionMethodsInaccessible() { var source = @"namespace N { class A { void F() { } } class C { void M(A a) { a.F(); // instance and extension methods a.G(); // only extension methods } } static class S1 { static void F(this object o) { } static void G(this object o) { } } } static class S2 { static void F(this object o) { } static void G(this object o) { } }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (11,15): error CS0122: 'A.F()' is inaccessible due to its protection level // a.F(); // instance and extension methods Diagnostic(ErrorCode.ERR_BadAccess, "F").WithArguments("N.A.F()").WithLocation(11, 15), // (12,15): error CS1061: 'A' does not contain a definition for 'G' and no extension method 'G' accepting a first argument of type 'A' could be found (are you missing a using directive or an assembly reference?) // a.G(); // only extension methods Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "G").WithArguments("N.A", "G").WithLocation(12, 15) ); } [WorkItem(868538, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/868538")] [Fact] public void IsAndAs() { var source = @"delegate void D(); static class S { internal static void E(this object o) { } } class C { static void M(C c) { if (F is D) { (F as D)(); } if (c.F is D) { (c.F as D)(); } if (G is D) { (G as D)(); } if (c.E is D) { (c.E as D)(); } } void F() { } static void G() { } }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (10,13): error CS0837: The first operand of an 'is' or 'as' operator may not be a lambda expression, anonymous method, or method group. // if (F is D) Diagnostic(ErrorCode.ERR_LambdaInIsAs, "F is D").WithLocation(10, 13), // (12,14): error CS0837: The first operand of an 'is' or 'as' operator may not be a lambda expression, anonymous method, or method group. // (F as D)(); Diagnostic(ErrorCode.ERR_LambdaInIsAs, "F as D").WithLocation(12, 14), // (14,13): error CS0837: The first operand of an 'is' or 'as' operator may not be a lambda expression, anonymous method, or method group. // if (c.F is D) Diagnostic(ErrorCode.ERR_LambdaInIsAs, "c.F is D").WithLocation(14, 13), // (16,14): error CS0837: The first operand of an 'is' or 'as' operator may not be a lambda expression, anonymous method, or method group. // (c.F as D)(); Diagnostic(ErrorCode.ERR_LambdaInIsAs, "c.F as D").WithLocation(16, 14), // (18,13): error CS0837: The first operand of an 'is' or 'as' operator may not be a lambda expression, anonymous method, or method group. // if (G is D) Diagnostic(ErrorCode.ERR_LambdaInIsAs, "G is D").WithLocation(18, 13), // (20,14): error CS0837: The first operand of an 'is' or 'as' operator may not be a lambda expression, anonymous method, or method group. // (G as D)(); Diagnostic(ErrorCode.ERR_LambdaInIsAs, "G as D").WithLocation(20, 14), // (22,13): error CS0837: The first operand of an 'is' or 'as' operator may not be a lambda expression, anonymous method, or method group. // if (c.E is D) Diagnostic(ErrorCode.ERR_LambdaInIsAs, "c.E is D").WithLocation(22, 13), // (24,14): error CS0837: The first operand of an 'is' or 'as' operator may not be a lambda expression, anonymous method, or method group. // (c.E as D)(); Diagnostic(ErrorCode.ERR_LambdaInIsAs, "c.E as D").WithLocation(24, 14)); } [Fact] public void Casts() { var source = @"delegate void D(); static class S { internal static void E(this object o) { } } class C { static void M(C c) { ((D)c.F)(); ((D)G)(); ((D)c.E)(); } void F() { } static void G() { } }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics(); } [Fact] public void NoReceiver() { var source = @"class C { void M() { E(); } } static class S { public static void E(this C c) { } }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( Diagnostic(ErrorCode.ERR_NameNotInContext, "E").WithArguments("E").WithLocation(5, 9)); } [Fact] public void BaseReceiver() { var source = @"class C { } class D : C { void M() { base.E(); } } static class S { public static void E(this C c) { } }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( Diagnostic(ErrorCode.ERR_NoSuchMember, "E").WithArguments("C", "E").WithLocation(8, 14)); } [ClrOnlyFact] public void DefinedInSameClass() { var source = @"static class C { static void M(this string s, int i) { s.M(i + 1); } }"; CompileAndVerify(source); } /// <summary> /// Should not favor method from one class over another in same /// namespace, even if one method is defined in caller's class. /// </summary> [Fact] public void AmbiguousMethodDifferentClassesSameNamespace() { var source = @"static class A { public static void E(this string s, int i) { } } static class B { public static void E(this string s, int i) { } static void M(string s) { s.E(1); } } static class C { static void M(string s) { s.E(2); } } namespace N.S { static class A { public static void E(this string s, int i) { } } } namespace N.S { static class B { public static void E(this string s, int i) { } static void M(string s) { s.E(3); } } static class C { static void M(string s) { s.E(4); } } }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( Diagnostic(ErrorCode.ERR_AmbigCall, "E").WithArgumentsAnyOrder("A.E(string, int)", "B.E(string, int)").WithLocation(10, 11), Diagnostic(ErrorCode.ERR_AmbigCall, "E").WithArgumentsAnyOrder("B.E(string, int)", "A.E(string, int)").WithLocation(17, 11), Diagnostic(ErrorCode.ERR_AmbigCall, "E").WithArguments("N.S.A.E(string, int)", "N.S.B.E(string, int)").WithLocation(34, 15), Diagnostic(ErrorCode.ERR_AmbigCall, "E").WithArguments("N.S.A.E(string, int)", "N.S.B.E(string, int)").WithLocation(41, 15)); } /// <summary> /// Extension method delegates in different scopes make /// consumer (an overloaded method invocation) ambiguous. /// </summary> [Fact] public void AmbiguousConsumerWithExtensionMethodDelegateArg() { var source = @"namespace N { class C { static void M1(object o) { M2(o.F); } static void M2(System.Action a) { } static void M2(System.Action<int> a) { } } static class E { public static void F(this object o) { } } } static class E { public static void F(this object o, int i) { } }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (7,13): error CS0121: The call is ambiguous between the following methods or properties: 'N.C.M2(System.Action)' and 'N.C.M2(System.Action<int>)' Diagnostic(ErrorCode.ERR_AmbigCall, "M2").WithArgumentsAnyOrder("N.C.M2(System.Action)", "N.C.M2(System.Action<int>)").WithLocation(7, 13)); } /// <summary> /// Prefer methods on classes on inner namespaces. /// </summary> [ClrOnlyFact] public void InnerNamespacesBeforeOuter() { var source = @"using System; static class A { public static void E(this string s) { Console.WriteLine(""A.E: {0}"", s); } public static void E(this string s, int i) { Console.WriteLine(""A.E: {0}, {1}"", s, i); } public static void E(this string s, bool b) { Console.WriteLine(""C.E: {0}, {1}"", s, b); } } namespace N1 { static class B { public static void E(this string s) { Console.WriteLine(""B.E: {0}"", s); } public static void E(this string s, bool b) { Console.WriteLine(""B.E: {0}, {1}"", s, b); } } } namespace N1.N2 { static class C { public static void E(this string s) { Console.WriteLine(""C.E: {0}"", s); } } namespace N3 { static class D { public static void E(this string s) { Console.WriteLine(""D.E: {0}"", s); } } } static class E { static void Main() { ""str"".E(); ""int"".E(1); ""bool"".E(true); } } }"; CompileAndVerify(source, expectedOutput: @"C.E: str A.E: int, 1 B.E: bool, True"); } [Fact] public void ExtensionMethodsWithAccessorNames() { var source = @"class C { public object P { get; set; } void M() { this.set_P(this.get_P()); set_P(get_P()); } } class D { static void M(C c) { c.set_P(c.get_P()); } } static class S { internal static object get_P(this C c) { return null; } static void set_P(this C c, object o) { } }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (6,14): error CS0571: 'C.P.set': cannot explicitly call operator or accessor Diagnostic(ErrorCode.ERR_CantCallSpecialMethod, "set_P").WithArguments("C.P.set").WithLocation(6, 14), // (7,9): error CS0571: 'C.P.set': cannot explicitly call operator or accessor Diagnostic(ErrorCode.ERR_CantCallSpecialMethod, "set_P").WithArguments("C.P.set").WithLocation(7, 9), // (7,15): error CS0571: 'C.P.get': cannot explicitly call operator or accessor Diagnostic(ErrorCode.ERR_CantCallSpecialMethod, "get_P").WithArguments("C.P.get").WithLocation(7, 15), // (14,11): error CS0571: 'C.P.set': cannot explicitly call operator or accessor Diagnostic(ErrorCode.ERR_CantCallSpecialMethod, "set_P").WithArguments("C.P.set").WithLocation(14, 11)); } [Fact] public void DelegateExtensionMethodsWithAccessorNames() { var source = @"using System; class C { object P { get; set; } object Q { get; set; } void M() { F(this.get_P); F(this.get_Q); } void F(Func<object> f) { } } static class S { internal static object get_P(this C c) { return null; } static object get_Q(this C c) { return null; } }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (9,16): error CS0571: 'C.Q.get': cannot explicitly call operator or accessor Diagnostic(ErrorCode.ERR_CantCallSpecialMethod, "get_Q").WithArguments("C.Q.get").WithLocation(9, 16)); } [Fact] public void Delegates() { var source = @"static class S { public static void E(this object o) { } public static void F(this System.Action a) { } public static void G(this System.Action<object> a) { } } class C { static void M() { S.F(4.E); S.F(new object().E); S.F(""str"".E); ""str"".E.F(); (""str"".E).F(); System.Action a = ""str"".E; a.F(); S.G(S.E); S.E.G(); System.Action<object> b = S.E; b.G(); } }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (14,15): error CS0119: 'S.E(object)' is a 'method', which is not valid in the given context Diagnostic(ErrorCode.ERR_BadSKunknown, "E").WithArguments("S.E(object)", "method").WithLocation(14, 15), // (15,16): error CS0119: 'S.E(object)' is a 'method', which is not valid in the given context Diagnostic(ErrorCode.ERR_BadSKunknown, "E").WithArguments("S.E(object)", "method").WithLocation(15, 16), // (19,11): error CS0119: 'S.E(object)' is a 'method', which is not valid in the given context Diagnostic(ErrorCode.ERR_BadSKunknown, "E").WithArguments("S.E(object)", "method").WithLocation(19, 11)); } [ClrOnlyFact] public void GenericDelegate() { var source = @"delegate void D<T>(T t); class C { static void Main() { F<int>(new C().M)(2); } static D<T> F<T>(D<T> d) { return d; } public int P { get { return 3; } } } static class S { public static void M(this C c, int i) { System.Console.Write(c.P * i); } }"; CompileAndVerify(source, expectedOutput: "6"); } [Fact] public void InvalidTypeArguments() { var source = @"class C { void M() { this.E<int>(1); this.E<S>(); this.E<A>(null); this.E<int, int>(1); } void E<T>() { } } static class S { public static void E<T>(this C c, T t) { } }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (6,14): error CS0718: 'S': static types cannot be used as type arguments // this.E<S>(); Diagnostic(ErrorCode.ERR_GenericArgIsStaticClass, "E<S>").WithArguments("S").WithLocation(6, 14), // (7,16): error CS0246: The type or namespace name 'A' could not be found (are you missing a using directive or an assembly reference?) // this.E<A>(null); Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "A").WithArguments("A").WithLocation(7, 16), // (8,14): error CS0305: Using the generic method 'C.E<T>()' requires 1 type arguments // this.E<int, int>(1); Diagnostic(ErrorCode.ERR_BadArity, "E<int, int>").WithArguments("C.E<T>()", "method", "1").WithLocation(8, 14) ); } [Fact] public void ThisArgumentConversions() { var source = @"class A { } class B { } struct S { } class C { static void M() { A a = new A(); a.A(); a.B(); a.O(); a.T(); B b = new B(); b.A(); b.B(); b.O(); S s = new S(); s.A(); s.S(); s.O(); s.T(); (1.0).D(); (2.0).O(); 1.A(); 2.O(); 3.T(); } } static class Extensions { internal static void A(this A a) { } internal static void B(this B b) { } internal static void S(this S s) { } internal static void T<U>(this U u) { } internal static void D(this double d) { } internal static void O(this object o) { } }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (10,9): error CS1929: 'A' does not contain a definition for 'B' and the best extension method overload 'Extensions.B(B)' requires a receiver of type 'B' // a.B(); Diagnostic(ErrorCode.ERR_BadInstanceArgType, "a").WithArguments("A", "B", "Extensions.B(B)", "B"), // (14,9): error CS1929: 'B' does not contain a definition for 'A' and the best extension method overload 'Extensions.A(A)' requires a receiver of type 'A' // b.A(); Diagnostic(ErrorCode.ERR_BadInstanceArgType, "b").WithArguments("B", "A", "Extensions.A(A)", "A"), // (18,9): error CS1929: 'S' does not contain a definition for 'A' and the best extension method overload 'Extensions.A(A)' requires a receiver of type 'A' // s.A(); Diagnostic(ErrorCode.ERR_BadInstanceArgType, "s").WithArguments("S", "A", "Extensions.A(A)", "A"), // (24,9): error CS1929: 'int' does not contain a definition for 'A' and the best extension method overload 'Extensions.A(A)' requires a receiver of type 'A' // 1.A(); Diagnostic(ErrorCode.ERR_BadInstanceArgType, "1").WithArguments("int", "A", "Extensions.A(A)", "A") ); } [Fact] public void ThisArgumentImplicitConversions() { var source = @"class C { static void M() { 1.E1(); 2.E2(); 3.E3(); 4.E4(); } } static class S { internal static void E1<T>(this T t) { } internal static void E2(this double d) { } internal static void E3(this long l, params object[] args) { } internal static void E4(this object o) { } }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (6,9): error CS1929: 'int' does not contain a definition for 'E2' and the best extension method overload 'S.E2(double)' requires a receiver of type 'double' // 2.E2(); Diagnostic(ErrorCode.ERR_BadInstanceArgType, "2").WithArguments("int", "E2", "S.E2(double)", "double").WithLocation(6, 9), // (7,9): error CS1929: 'int' does not contain a definition for 'E3' and the best extension method overload 'S.E3(long, params object[])' requires a receiver of type 'long' // 3.E3(); Diagnostic(ErrorCode.ERR_BadInstanceArgType, "3").WithArguments("int", "E3", "S.E3(long, params object[])", "long").WithLocation(7, 9)); } [ClrOnlyFact] public void ParamsArray() { var source = @"delegate void D(params int[] args); class C { void M() { this.E1(0); this.E1(1, null); 1.E2(); 1.E2(2, 3); D d = this.E2; } } static class S { internal static void E1(this C c, int i, params object[] args) { } internal static void E2(this object o, params int[] args) { } }"; CompileAndVerify(source); } [ClrOnlyFact] public void Using() { var source = @"using System; using N1.N2; namespace N1 { internal static class S { public static void E(this object o) { Console.WriteLine(""N1.S.E""); } } namespace N2 { internal static class S { public static void E(this object o) { Console.WriteLine(""N1.N2.S.E""); } } } } namespace N3 { internal static class S { public static void E(this object o) { Console.WriteLine(""N3.S.E""); } } } namespace N4 { using N3; class A { public static void M(object o) { o.E(); } } } namespace N4 { using N1; class B { public static void M(object o) { o.E(); } } } class C { public static void M(object o) { o.E(); } } class D { static void Main() { object o = null; N4.A.M(o); N4.B.M(o); C.M(o); } }"; var compilation = CompileAndVerify(source, expectedOutput: @"N3.S.E N1.S.E N1.N2.S.E"); } [Fact] public void AmbiguousUsing() { var source = @"using N1; using N2; namespace N1 { internal static class S { public static void E(this object o) { } } } namespace N2 { internal static class S { public static void E(this object o) { } } } namespace N3 { internal static class S { public static void F(this object o) { } public static void G(this object o) { } } } namespace N4 { using N3; internal static class S { public static void F(this object o) { } } class C { static void M() { object o = null; o.E(); // ambiguous N1.S.E, N2.S.E o.F(); // choose N4.S.F over N3.S.F o.G(); // N3.S.G } } }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (37,13): error CS0121: The call is ambiguous between the following methods or properties: 'N1.S.E(object)' and 'N2.S.E(object)' Diagnostic(ErrorCode.ERR_AmbigCall, "E").WithArguments("N1.S.E(object)", "N2.S.E(object)").WithLocation(37, 15)); } [Fact] public void VerifyDiagnosticForMissingSystemCoreReference() { var source = @" internal static class C { internal static void M1(this object o) { } private static void Main(string[] args) { } } "; var compilation = CreateEmptyCompilation(source, new[] { Net40.mscorlib }); compilation.VerifyDiagnostics( // (4,29): error CS1110: Cannot define a new extension method because the compiler required type 'System.Runtime.CompilerServices.ExtensionAttribute' cannot be found. Are you missing a reference to System.Core.dll? Diagnostic(ErrorCode.ERR_ExtensionAttrNotFound, "this").WithArguments("System.Runtime.CompilerServices.ExtensionAttribute").WithLocation(4, 29)); } [ClrOnlyFact] public void SystemLinqEnumerable() { var source = @"using System; using System.Linq; class C { static void Main() { string result = F(""banana"", ""orange"", ""lime"", ""apple"", ""kiwi""); Console.Write(result); } static string F(params string[] args) { return args.Skip(1).Where(Filter).Aggregate(Combine); } static string G(params string[] args) { return Enumerable.Aggregate(Enumerable.Where(Enumerable.Skip(args, 1), Filter), Combine); } static bool Filter(string s) { return s.Length > 4; } static string Combine(string s1, string s2) { return s1 + "", "" + s2; } }"; var code = @"{ // Code size 42 (0x2a) .maxstack 3 IL_0000: ldarg.0 IL_0001: ldc.i4.1 IL_0002: call ""System.Collections.Generic.IEnumerable<string> System.Linq.Enumerable.Skip<string>(System.Collections.Generic.IEnumerable<string>, int)"" IL_0007: ldnull IL_0008: ldftn ""bool C.Filter(string)"" IL_000e: newobj ""System.Func<string, bool>..ctor(object, System.IntPtr)"" IL_0013: call ""System.Collections.Generic.IEnumerable<string> System.Linq.Enumerable.Where<string>(System.Collections.Generic.IEnumerable<string>, System.Func<string, bool>)"" IL_0018: ldnull IL_0019: ldftn ""string C.Combine(string, string)"" IL_001f: newobj ""System.Func<string, string, string>..ctor(object, System.IntPtr)"" IL_0024: call ""string System.Linq.Enumerable.Aggregate<string>(System.Collections.Generic.IEnumerable<string>, System.Func<string, string, string>)"" IL_0029: ret }"; var compilation = CompileAndVerify(source, expectedOutput: "orange, apple"); compilation.VerifyIL("C.F", code); compilation.VerifyIL("C.G", code); } /// <summary> /// A value type should be boxed when used as a reference type receiver to an /// extension method. Note: Dev10 reports an error in such cases ("No overload for /// 'C.F(object)' matches delegate 'System.Action'") even though these cases are valid. /// </summary> [ClrOnlyFact] public void BoxingConversionOfDelegateReceiver01() { var source = @"using System; struct S { } static class C { static void Main() { M(1.F); M((new S()).F); M(1.G); M((new S()).G); } static void F(this object o) { Console.WriteLine(""F: {0}"", o.GetType()); } static void G(this ValueType v) { Console.WriteLine(""G: {0}"", v.GetType()); } static void M(Action a) { a(); } }"; var compilation = CompileAndVerify(source, expectedOutput: @"F: System.Int32 F: S G: System.Int32 G: S"); compilation.VerifyIL("C.Main", @"{ // Code size 105 (0x69) .maxstack 2 .locals init (S V_0) IL_0000: ldc.i4.1 IL_0001: box ""int"" IL_0006: ldftn ""void C.F(object)"" IL_000c: newobj ""System.Action..ctor(object, System.IntPtr)"" IL_0011: call ""void C.M(System.Action)"" IL_0016: ldloca.s V_0 IL_0018: initobj ""S"" IL_001e: ldloc.0 IL_001f: box ""S"" IL_0024: ldftn ""void C.F(object)"" IL_002a: newobj ""System.Action..ctor(object, System.IntPtr)"" IL_002f: call ""void C.M(System.Action)"" IL_0034: ldc.i4.1 IL_0035: box ""int"" IL_003a: ldftn ""void C.G(System.ValueType)"" IL_0040: newobj ""System.Action..ctor(object, System.IntPtr)"" IL_0045: call ""void C.M(System.Action)"" IL_004a: ldloca.s V_0 IL_004c: initobj ""S"" IL_0052: ldloc.0 IL_0053: box ""S"" IL_0058: ldftn ""void C.G(System.ValueType)"" IL_005e: newobj ""System.Action..ctor(object, System.IntPtr)"" IL_0063: call ""void C.M(System.Action)"" IL_0068: ret }"); } /// <summary> /// Similar to the test above, but using instances of type /// parameters for the delegate receiver. /// </summary> [ClrOnlyFact] public void BoxingConversionOfDelegateReceiver02() { var source = @"using System; interface I { } class A { } class B : A, I { } class C { static void Main() { M(new object(), new object(), 1, new B(), new B()); } static void M<T1, T2, T3, T4, T5>(T1 t1, T2 t2, T3 t3, T4 t4, T5 t5) where T2 : class where T3 : struct where T4 : I where T5 : A { F(t1.M); F(t2.M); F(t3.M); F(t4.M); F(t5.M); } static void F(Action a) { a(); } } static class E { internal static void M(this object o) { Console.WriteLine(""{0}"", o.GetType()); } }"; var compilation = CompileAndVerify(source, expectedOutput: @"System.Object System.Object System.Int32 B B"); compilation.VerifyIL("C.M<T1, T2, T3, T4, T5>", @"{ // Code size 112 (0x70) .maxstack 2 IL_0000: ldarg.0 IL_0001: box ""T1"" IL_0006: ldftn ""void E.M(object)"" IL_000c: newobj ""System.Action..ctor(object, System.IntPtr)"" IL_0011: call ""void C.F(System.Action)"" IL_0016: ldarg.1 IL_0017: box ""T2"" IL_001c: ldftn ""void E.M(object)"" IL_0022: newobj ""System.Action..ctor(object, System.IntPtr)"" IL_0027: call ""void C.F(System.Action)"" IL_002c: ldarg.2 IL_002d: box ""T3"" IL_0032: ldftn ""void E.M(object)"" IL_0038: newobj ""System.Action..ctor(object, System.IntPtr)"" IL_003d: call ""void C.F(System.Action)"" IL_0042: ldarg.3 IL_0043: box ""T4"" IL_0048: ldftn ""void E.M(object)"" IL_004e: newobj ""System.Action..ctor(object, System.IntPtr)"" IL_0053: call ""void C.F(System.Action)"" IL_0058: ldarg.s V_4 IL_005a: box ""T5"" IL_005f: ldftn ""void E.M(object)"" IL_0065: newobj ""System.Action..ctor(object, System.IntPtr)"" IL_006a: call ""void C.F(System.Action)"" IL_006f: ret }"); } [Fact] public void UsingInScript() { string test = @"using System.Linq; (new string[0]).Take(1)"; var tree = SyntaxFactory.ParseSyntaxTree(test, options: TestOptions.Script.WithLanguageVersion(LanguageVersion.CSharp6)); var compilation = CSharpCompilation.Create( assemblyName: GetUniqueName(), options: TestOptions.DebugExe.WithScriptClassName("Script"), syntaxTrees: new[] { tree }, references: new[] { MscorlibRef, LinqAssemblyRef }); var expr = ((ExpressionStatementSyntax)((GlobalStatementSyntax)tree.GetCompilationUnitRoot().Members[0]).Statement).Expression; var model = compilation.GetSemanticModel(tree); var info = model.GetSymbolInfo(expr); Assert.NotNull(info.Symbol); var symbol = info.Symbol; Utils.CheckSymbol(symbol, "IEnumerable<string> IEnumerable<string>.Take<string>(int count)"); } [ClrOnlyFact] public void AssemblyMightContainExtensionMethods() { var source = @"static class C { internal static int F; internal static System.Linq.Expressions.Expression G; internal static void M(this object o) { } }"; Func<bool, Action<ModuleSymbol>> validator = isFromSource => module => { var type = module.GlobalNamespace.GetMember<NamedTypeSymbol>("C"); // mscorlib.dll var mscorlib = type.GetMember<FieldSymbol>("F").Type.ContainingAssembly; Assert.Equal(RuntimeCorLibName.Name, mscorlib.Name); // We assume every PE assembly may contain extension methods. Assert.True(mscorlib.MightContainExtensionMethods); // TODO: Original references are not included in symbol validator. if (isFromSource) { // System.Core.dll var systemCore = type.GetMember<FieldSymbol>("G").Type.ContainingAssembly; Assert.True(systemCore.MightContainExtensionMethods); } // Local assembly. var assembly = type.ContainingAssembly; Assert.True(assembly.MightContainExtensionMethods); }; CompileAndVerify( source: source, sourceSymbolValidator: validator(true), symbolValidator: validator(false), options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal)); } /// <summary> /// AssemblySymbol.MightContainExtensionMethods should be reset after /// emit, after all types within the assembly have been inspected, if there /// are no types with extension methods. /// </summary> [ClrOnlyFact] public void AssemblyMightContainExtensionMethodsReset() { var source = @"static class C { internal static void M(object o) { } }"; AssemblySymbol sourceAssembly = null; Func<bool, Action<ModuleSymbol>> validator = isFromSource => module => { var assembly = module.ContainingAssembly; var mightContainExtensionMethods = assembly.MightContainExtensionMethods; // Every PE assembly is assumed to be capable of having an extension method. // The source assembly doesn't know (so reports "true") until all methods have been inspected. Assert.True(mightContainExtensionMethods); if (isFromSource) { Assert.Null(sourceAssembly); sourceAssembly = assembly; } }; CompileAndVerify(source, symbolValidator: validator(false), sourceSymbolValidator: validator(true)); Assert.NotNull(sourceAssembly); Assert.False(sourceAssembly.MightContainExtensionMethods); } [ClrOnlyFact] public void ReducedExtensionMethodSymbols() { var source = @"using System.Collections.Generic; static class S { internal static void M1(this object o) { } internal static void M2<T>(this IEnumerable<T> t) { } internal static void M3<T, U>(this U u, IEnumerable<T> t) { } }"; var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal)); Action<ModuleSymbol> validator = module => { var type = module.GlobalNamespace.GetMember<NamedTypeSymbol>("S"); var intType = compilation.GetSpecialType(SpecialType.System_Int32); var stringType = compilation.GetSpecialType(SpecialType.System_String); var arrayType = ArrayTypeSymbol.CreateCSharpArray(compilation.Assembly, TypeWithAnnotations.Create(stringType), 1); // Non-generic method. var method = type.GetMember<MethodSymbol>("M1"); CheckExtensionMethod(method, ImmutableArray.Create<TypeWithAnnotations>(), "void object.M1()", "void S.M1(object o)", "void object.M1()", "void S.M1(object o)"); // Generic method, one type argument. method = type.GetMember<MethodSymbol>("M2"); CheckExtensionMethod(method, ImmutableArray.Create(TypeWithAnnotations.Create(intType)), "void IEnumerable<int>.M2<int>()", "void S.M2<T>(IEnumerable<T> t)", "void IEnumerable<T>.M2<T>()", "void S.M2<T>(IEnumerable<T> t)"); // Generic method, multiple type arguments. method = type.GetMember<MethodSymbol>("M3"); CheckExtensionMethod(method, ImmutableArray.Create(TypeWithAnnotations.Create(intType), TypeWithAnnotations.Create(arrayType)), "void string[].M3<int, string[]>(IEnumerable<int> t)", "void S.M3<T, U>(U u, IEnumerable<T> t)", "void U.M3<T, U>(IEnumerable<T> t)", "void S.M3<T, U>(U u, IEnumerable<T> t)"); }; CompileAndVerify(compilation, sourceSymbolValidator: validator, symbolValidator: validator); } private void CheckExtensionMethod( MethodSymbol method, ImmutableArray<TypeWithAnnotations> typeArgs, string reducedMethodDescription, string reducedFromDescription, string constructedFromDescription, string reducedAndConstructedFromDescription) { // Create instance form from constructed method. var extensionMethod = ReducedExtensionMethodSymbol.Create(method.ConstructIfGeneric(typeArgs)); Utils.CheckReducedExtensionMethod(extensionMethod, reducedMethodDescription, reducedFromDescription, constructedFromDescription, reducedAndConstructedFromDescription); // Construct method from unconstructed instance form. extensionMethod = ReducedExtensionMethodSymbol.Create(method).ConstructIfGeneric(typeArgs); Utils.CheckReducedExtensionMethod(extensionMethod, reducedMethodDescription, reducedFromDescription, constructedFromDescription, reducedAndConstructedFromDescription); } /// <summary> /// Roslyn bug 7782: NullRef in PeWriter.DebuggerShouldHideMethod /// </summary> [Fact] public void ExtensionMethod_ValidateExtensionAttribute() { var comp = CreateCompilation(@" using System; internal static class C { internal static void M1(this object o) { } private static void Main(string[] args) { } } ", options: TestOptions.DebugExe.WithMetadataImportOptions(MetadataImportOptions.All)); CompileAndVerify(comp, symbolValidator: module => { var method = module.GlobalNamespace.GetMember<NamedTypeSymbol>("C").GetMember<PEMethodSymbol>("M1"); Assert.True(method.IsExtensionMethod); Assert.Equal(SpecialType.System_Object, method.Parameters.Single().Type.SpecialType); var attr = ((PEModuleSymbol)module).GetCustomAttributesForToken(method.Handle).Single(); Assert.Equal("System.Runtime.CompilerServices.ExtensionAttribute", attr.AttributeClass.ToTestDisplayString()); }); } [WorkItem(541327, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541327")] [Fact] public void RegressBug7992() { var text = @"using System.Runtime.InteropServices; namespace ConsoleApplication1 { [StructLayout(Pack = A.B)] struct Program { } } "; CreateCompilation(text).GetDiagnostics(); } /// <summary> /// Box value type receiver if passed as reference type. /// </summary> [ClrOnlyFact] public void BoxValueTypeReceiverIfNecessary() { var source = @"struct S { } static class C { static void Main() { ""str"".F(); ""str"".G(); (2.0).F(); (2.0).G(); (new S()).F(); (new S()).G(); } static void F(this object o) { System.Console.WriteLine(""{0}"", o.ToString()); } static void G<T>(this T t) { System.Console.WriteLine(""{0}"", t.ToString()); } }"; var compilation = CompileAndVerify(source, expectedOutput: @"str str 2 2 S S"); compilation.VerifyIL("C.Main", @"{ // Code size 87 (0x57) .maxstack 1 .locals init (S V_0) IL_0000: ldstr ""str"" IL_0005: call ""void C.F(object)"" IL_000a: ldstr ""str"" IL_000f: call ""void C.G<string>(string)"" IL_0014: ldc.r8 2 IL_001d: box ""double"" IL_0022: call ""void C.F(object)"" IL_0027: ldc.r8 2 IL_0030: call ""void C.G<double>(double)"" IL_0035: ldloca.s V_0 IL_0037: initobj ""S"" IL_003d: ldloc.0 IL_003e: box ""S"" IL_0043: call ""void C.F(object)"" IL_0048: ldloca.s V_0 IL_004a: initobj ""S"" IL_0050: ldloc.0 IL_0051: call ""void C.G<S>(S)"" IL_0056: ret }"); } [WorkItem(541652, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541652")] [ClrOnlyFact] public void ReduceExtensionMethodWithNullReceiverType() { var source = @"static class Extensions { public static int NonGeneric(this object o) { return o.GetHashCode(); } public static int Generic<T>(this T o) { return o.GetHashCode(); } } "; CompileAndVerify(source, validator: module => { var type = module.GlobalNamespace.GetMember<NamedTypeSymbol>("Extensions"); var nonGenericExtension = type.GetMember<MethodSymbol>("NonGeneric"); var genericExtension = type.GetMember<MethodSymbol>("Generic"); Assert.True(nonGenericExtension.IsExtensionMethod); Assert.Throws<ArgumentNullException>(() => nonGenericExtension.ReduceExtensionMethod(receiverType: null, compilation: null!)); Assert.True(genericExtension.IsExtensionMethod); Assert.Throws<ArgumentNullException>(() => genericExtension.ReduceExtensionMethod(receiverType: null, compilation: null!)); }); } [WorkItem(528730, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528730")] [Fact] public void ThisParameterCalledOnNonSourceMethodSymbol() { var code = @"using System.Collections.Generic; using System.Linq; class Program { static void Main(string[] args) { int[] numbers = new int[] { 4, 5 }; int i1 = numbers.GetHashCode(); int i2 = numbers.Cast<T1>(); } }"; var compilation = CreateCompilationWithMscorlib40AndSystemCore(code); var tree = compilation.SyntaxTrees[0]; var model = compilation.GetSemanticModel(tree); var node = tree.GetCompilationUnitRoot().FindToken(code.IndexOf("GetHashCode", StringComparison.Ordinal)).Parent; var symbolInfo = model.GetSymbolInfo((SimpleNameSyntax)node); var methodSymbol = symbolInfo.Symbol.GetSymbol<MethodSymbol>(); Assert.False(methodSymbol.IsFromCompilation(compilation)); var parameter = methodSymbol.ThisParameter; Assert.Equal(parameter.Ordinal, -1); Assert.Equal(parameter.ContainingSymbol, methodSymbol); // Get the GenericNameSyntax node Cast<T1> for binding node = tree.GetCompilationUnitRoot().FindToken(code.IndexOf("Cast<T1>", StringComparison.Ordinal)).Parent; symbolInfo = model.GetSymbolInfo((GenericNameSyntax)node); methodSymbol = (MethodSymbol)symbolInfo.Symbol.GetSymbol<MethodSymbol>(); Assert.False(methodSymbol.IsFromCompilation(compilation)); // 9341 is resolved as Won't Fix since ThisParameter property is internal. Assert.Throws<InvalidOperationException>(() => methodSymbol.ThisParameter); } private CompilationVerifier CompileAndVerify(string source, string expectedOutput = null, Action<ModuleSymbol> validator = null, CSharpCompilationOptions options = null) { return CompileAndVerify( source: source, expectedOutput: expectedOutput, sourceSymbolValidator: validator, symbolValidator: validator, options: options); } [WorkItem(528853, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528853")] [Fact] public void NoOverloadTakesNArguments() { var source = @"static class S { static void M(this object x, object y) { x.M(x, y); x.M(); M(x); } }"; CreateCompilationWithMscorlib40AndSystemCore(source).VerifyDiagnostics( // (5,9): error CS1501: No overload for method 'M' takes 2 arguments // x.M(x, y); Diagnostic(ErrorCode.ERR_BadArgCount, "M").WithArguments("M", "2").WithLocation(5, 11), // (6,9): error CS7036: There is no argument given that corresponds to the required formal parameter 'y' of 'S.M(object, object)' // x.M(); Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "M").WithArguments("y", "S.M(object, object)").WithLocation(6, 11), // (7,9): error CS7036: There is no argument given that corresponds to the required formal parameter 'y' of 'S.M(object, object)' // M(x); Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "M").WithArguments("y", "S.M(object, object)").WithLocation(7, 9)); } [WorkItem(543711, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543711")] [Fact] public void ReduceReducedExtensionsMethod() { var source = @"static class C { static void M(this object x) { } }"; var compilation = CreateCompilationWithMscorlib40AndSystemCore(source); compilation.VerifyDiagnostics(); var extensionMethod = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("C").GetMember<MethodSymbol>("M"); Assert.True(extensionMethod.IsExtensionMethod); var reduced = extensionMethod.ReduceExtensionMethod(); Assert.True(reduced.IsExtensionMethod); Assert.Null(reduced.ReduceExtensionMethod()); var int32Type = compilation.GetSpecialType(SpecialType.System_Int32); var reducedWithReceiver = extensionMethod.ReduceExtensionMethod(int32Type, null!); Assert.True(reduced.IsExtensionMethod); Assert.Equal(reduced, reducedWithReceiver); Assert.Null(reducedWithReceiver.ReduceExtensionMethod(int32Type, null!)); } [WorkItem(37780, "https://github.com/dotnet/roslyn/issues/37780")] [Fact] public void ReducedExtensionMethodVsUnmanagedConstraint() { var source1 = @"public static class C { public static void M<T>(this T self) where T : unmanaged { } }"; var compilation1 = CreateCompilation(source1); compilation1.VerifyDiagnostics(); var source2 = @"public class D { static void M(MyStruct<int> s) { s.M(); } } public struct MyStruct<T> { public T field; } "; var compilation2 = CreateCompilation(source2, references: new[] { new CSharpCompilationReference(compilation1) }, parseOptions: TestOptions.Regular8); compilation2.VerifyDiagnostics(); var extensionMethod = compilation2.GlobalNamespace.GetMember<NamedTypeSymbol>("C").GetMember<MethodSymbol>("M"); Assert.True(extensionMethod.IsExtensionMethod); var myStruct = (NamedTypeSymbol)compilation2.GlobalNamespace.GetMember<NamedTypeSymbol>("MyStruct"); var int32Type = compilation2.GetSpecialType(SpecialType.System_Int32); var msi = myStruct.Construct(int32Type); object reducedWithReceiver = extensionMethod.ReduceExtensionMethod(msi, compilation2); Assert.NotNull(reducedWithReceiver); reducedWithReceiver = extensionMethod.ReduceExtensionMethod(msi, null!); Assert.NotNull(reducedWithReceiver); reducedWithReceiver = extensionMethod.GetPublicSymbol().ReduceExtensionMethod(msi.GetPublicSymbol()); Assert.NotNull(reducedWithReceiver); compilation2 = CreateCompilation(source2, references: new[] { new CSharpCompilationReference(compilation1) }, parseOptions: TestOptions.Regular7); compilation2.VerifyDiagnostics( // (5,9): error CS8107: Feature 'unmanaged constructed types' is not available in C# 7.0. Please use language version 8.0 or greater. // s.M(); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "s.M").WithArguments("unmanaged constructed types", "8.0").WithLocation(5, 9) ); extensionMethod = compilation2.GlobalNamespace.GetMember<NamedTypeSymbol>("C").GetMember<MethodSymbol>("M"); Assert.True(extensionMethod.IsExtensionMethod); myStruct = (NamedTypeSymbol)compilation2.GlobalNamespace.GetMember<NamedTypeSymbol>("MyStruct"); int32Type = compilation2.GetSpecialType(SpecialType.System_Int32); msi = myStruct.Construct(int32Type); reducedWithReceiver = extensionMethod.ReduceExtensionMethod(msi, compilation2); Assert.Null(reducedWithReceiver); reducedWithReceiver = extensionMethod.ReduceExtensionMethod(msi, null!); Assert.NotNull(reducedWithReceiver); reducedWithReceiver = extensionMethod.GetPublicSymbol().ReduceExtensionMethod(msi.GetPublicSymbol()); Assert.NotNull(reducedWithReceiver); } /// <summary> /// Dev11 reports error for inaccessible extension method in addition to an /// error for the instance method that was used for binding. The inaccessible /// error may be helpful for the user or for "quick fix" in particular. /// </summary> [WorkItem(529866, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529866")] [Fact] public void InstanceMethodAndInaccessibleExtensionMethod_Diagnostics() { var source = @"class C { static void Main() { C c = new C(); c.Test(1d); } void Test(float f) { } } static class Extensions { static void Test(this C c, double d) { } static void Test<T>(this T t) { } }"; // Dev11 also reports: // (17,17): error CS0122: 'Extensions.Test<T>(T)' is inaccessible due to its protection level CreateCompilationWithMscorlib40AndSystemCore(source).VerifyDiagnostics( // (6,16): error CS1503: Argument 1: cannot convert from 'double' to 'float' Diagnostic(ErrorCode.ERR_BadArgType, "1d").WithArguments("1", "double", "float").WithLocation(6, 16)); } [WorkItem(545322, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545322")] // Bug relates to defunct LookupOptions.IgnoreAccessibility. [Fact] public void InstanceMethodAndInaccessibleExtensionMethod_Symbols() { var source = @"class C { static void Main() { C c = new C(); c.Test(1d); } void Test(float f) { } } static class Extensions { static void Test(this C c, double d) { } static void Test<T>(this T t) { } }"; var compilation = (Compilation)CreateCompilationWithMscorlib40AndSystemCore(source); var globalNamespace = compilation.GlobalNamespace; var type = globalNamespace.GetMember<INamedTypeSymbol>("C"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var memberAccess = tree.GetCompilationUnitRoot().DescendantNodes().OfType<MemberAccessExpressionSyntax>().Single(); var lookupResult = model.LookupSymbols( memberAccess.SpanStart, container: null, name: "Test", includeReducedExtensionMethods: true); Utils.CheckISymbols(lookupResult, "void C.Test(float f)"); lookupResult = model.LookupSymbols( memberAccess.SpanStart, container: type, name: "Test", includeReducedExtensionMethods: true); Utils.CheckISymbols(lookupResult, "void C.Test(float f)"); // Extension methods not found. var memberGroup = model.GetMemberGroup(memberAccess); Utils.CheckISymbols(memberGroup, "void C.Test(float f)"); compilation.VerifyDiagnostics( // (6,16): error CS1503: Argument 1: cannot convert from 'double' to 'float' // c.Test(1d); Diagnostic(ErrorCode.ERR_BadArgType, "1d").WithArguments("1", "double", "float")); } [WorkItem(541890, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541890")] [Fact] public void InstanceMethodAndInaccessibleExtensionMethod_CandidateSymbols() { var source = @"class C { static void Main() { C c = new C(); c.Test(1d); } void Test(float f) { } } static class Extensions { static void Test(this C c, double d) { } static void Test<T>(this T t) { } }"; var compilation = (Compilation)CreateCompilationWithMscorlib40AndSystemCore(source); var globalNamespace = compilation.GlobalNamespace; var type = globalNamespace.GetMember<INamedTypeSymbol>("C"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var memberAccess = tree.GetCompilationUnitRoot().DescendantNodes().OfType<MemberAccessExpressionSyntax>().Single(); var call = (ExpressionSyntax)memberAccess.Parent; Assert.Equal(SyntaxKind.InvocationExpression, call.Kind()); var info = model.GetSymbolInfo(call); Assert.Null(info.Symbol); Assert.Equal(CandidateReason.OverloadResolutionFailure, info.CandidateReason); // Definitely want the extension method here for quick fix. Utils.CheckISymbols(info.CandidateSymbols, "void C.Test(float f)"); } [WorkItem(529596, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529596")] [Fact(Skip = "529596")] public void DelegateFromValueTypeExtensionMethod() { var source = @" public delegate void VoidDelegate(); static class C { public static void Goo(this int x) { VoidDelegate v; v = x.Goo; // CS1113 v = new VoidDelegate(x.Goo); // Roslyn reports CS0123 v += x.Goo; // Roslyn reports CS0019 } } "; // TODO: Dev10 reports CS1113 for all of these. Roslyn reports various other diagnostics // because we detect the condition for CS1113 and then indicate that no conversion exists, // resulting in various cascaded errors. CreateCompilationWithMscorlib40AndSystemCore(source).VerifyDiagnostics( // (9,13): error CS1113: Extension method 'C.Goo(int)' defined on value type 'int' cannot be used to create delegates Diagnostic(ErrorCode.ERR_ValueTypeExtDelegate, "x.Goo").WithArguments("C.Goo(int)", "int").WithLocation(9, 13), // (10,13): error CS1113: Extension method 'C.Goo(int)' defined on value type 'int' cannot be used to create delegates Diagnostic(ErrorCode.ERR_ValueTypeExtDelegate, "new VoidDelegate(x.Goo)").WithArguments("C.Goo(int)", "int").WithLocation(10, 13), // (11,14): error CS1113: Extension method 'C.Goo(int)' defined on value type 'int' cannot be used to create delegates Diagnostic(ErrorCode.ERR_ValueTypeExtDelegate, "x.Goo").WithArguments("'C.Goo(int)", "int").WithLocation(11, 14)); } [Fact] public void DelegateFromGenericExtensionMethod() { var source = @" public delegate void VoidDelegate(); static class DevDivBugs142219 { public static void Goo<T>(this T x) { VoidDelegate f = x.Goo; // CS1113 } public static void Bar<T>(this T x) where T : class { VoidDelegate f = x.Bar; // ok } } "; CreateCompilationWithMscorlib40AndSystemCore(source).VerifyDiagnostics( // (8,26): error CS1113: Extension method 'DevDivBugs142219.Goo<T>(T)' defined on value type 'T' cannot be used to create delegates // VoidDelegate f = x.Goo; // CS1113 Diagnostic(ErrorCode.ERR_ValueTypeExtDelegate, "x.Goo").WithArguments("DevDivBugs142219.Goo<T>(T)", "T")); } [ClrOnlyFact] [WorkItem(545734, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545734")] public void ExtensionMethodWithRefParameterFromMetadata() { var lib = @" public static class Extensions { public static bool TryGetWithoutAttributeSuffix( this string name, out string result) { result = ""42""; return false; } }"; var consumer = @" static class Program { static void Main() { var symbolName = ""test""; string nameWithoutAttributeSuffix; symbolName.TryGetWithoutAttributeSuffix(out nameWithoutAttributeSuffix); } }"; var libCompilation = CreateCompilationWithMscorlib40AndSystemCore(lib, assemblyName: Guid.NewGuid().ToString()); var libReference = new CSharpCompilationReference(libCompilation); CompileAndVerify(consumer, references: new[] { libReference }); } [Fact, WorkItem(545800, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545800")] public void SameExtensionMethodSymbol() { var src1 = @" using System.Collections.Generic; public class MyClass { public void InstanceMethod<T>(T t) { } } public static class Extensions { public static void ExtensionMethod<T>(this MyClass p, T t) { } } class Test { static void Main() { var obj = new MyClass(); obj.InstanceMethod('q'); obj.ExtensionMethod('c'); } } "; var comp = CreateCompilation(src1); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var nodes = tree.GetCompilationUnitRoot().DescendantNodes().OfType<InvocationExpressionSyntax>().ToList(); Assert.Equal(2, nodes.Count); var firstInvocation = nodes[0]; var firstInvocationExpression = firstInvocation.Expression; var firstInvocationSymbol = model.GetSymbolInfo(firstInvocation).Symbol; var firstInvocationExpressionSymbol = model.GetSymbolInfo(firstInvocationExpression).Symbol; var secondInvocation = nodes[1]; var secondInvocationExpression = secondInvocation.Expression; var secondInvocationSymbol = model.GetSymbolInfo(secondInvocation).Symbol; var secondInvocationExpressionSymbol = model.GetSymbolInfo(secondInvocationExpression).Symbol; Assert.Equal("obj.InstanceMethod", firstInvocationExpression.ToString()); Assert.Equal(SyntaxKind.SimpleMemberAccessExpression, firstInvocationExpression.Kind()); Assert.Equal(SymbolKind.Method, firstInvocationSymbol.Kind); Assert.Equal("InstanceMethod", firstInvocationSymbol.Name); Assert.Equal(firstInvocationSymbol, firstInvocationExpressionSymbol); Assert.Equal("obj.ExtensionMethod", secondInvocationExpression.ToString()); Assert.Equal(SyntaxKind.SimpleMemberAccessExpression, secondInvocationExpression.Kind()); Assert.Equal(SymbolKind.Method, secondInvocationSymbol.Kind); Assert.Equal("ExtensionMethod", secondInvocationSymbol.Name); Assert.Equal(secondInvocationSymbol, secondInvocationExpressionSymbol); } /// <summary> /// Dev11 allows referencing extension methods defined on /// non-static classes, generic classes, structs, and delegates. /// </summary> [WorkItem(546093, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546093")] [Fact] public void NonStaticClasses() { var source1 = @".assembly extern mscorlib { .ver 4:0:0:0 .publickeytoken = (B7 7A 5C 56 19 34 E0 89) } .assembly extern System.Core {} .assembly '<<GeneratedFileName>>' { .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) } .class public A { .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) .method public hidebysig specialname rtspecialname instance void .ctor() { ret } // public method .method public static void MA(object o) { .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) ret } // protected method .method family static void MP(object o) { .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) ret } } .class public B<T> { .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) .method public hidebysig specialname rtspecialname instance void .ctor() { ret } // generic type method .method public static void MB(object o) { .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) ret } } .class public sealed S extends [mscorlib]System.ValueType { .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) // struct method .method public static void MS(object o) { .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) ret } } .class public abstract interface I { .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) // interface method .method public static void MI(object o) { .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) ret } } .class public sealed D extends [mscorlib]System.MulticastDelegate { .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) .method public instance void Invoke() { ret } // delegate method .method public static void MD(object o) { .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) ret } }"; var reference1 = CompileIL(source1, prependDefaultHeader: false); var source2 = @"class C : A { static void M(object o) { o.MA(); // A.MA() o.MP(); // A.MP() (protected) o.MB(); // B<T>.MB() o.MS(); // S.MS() o.MI(); // I.MI() o.MD(); // D.MD() } }"; var compilation = CreateCompilation(source2, new[] { reference1 }); compilation.VerifyDiagnostics( // (9,11): error CS1061: 'object' does not contain a definition for 'MI' and no extension method 'MI' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?) Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "MI").WithArguments("object", "MI").WithLocation(9, 11)); } [WorkItem(546093, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546093")] [ClrOnlyFact] public void VBExtensionMethod() { var source1 = @"Imports System.Runtime.CompilerServices Public Module M <Extension()> Public Sub F(o As Object) End Sub End Module"; var reference1 = BasicCompilationUtils.CompileToMetadata(source1, references: new[] { MscorlibRef, SystemCoreRef, MsvbRef }); var source2 = @"class C { static void M(object o) { o.F(); } }"; var compilation2 = CreateCompilation(source2, new[] { reference1 }); compilation2.VerifyDiagnostics(); } [WorkItem(602893, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/602893")] [ClrOnlyFact] public void Bug602893() { var source1 = @"namespace NA { internal static class A { public static void F(this object o) { } } }"; var compilation1 = CreateCompilationWithMscorlib40AndSystemCore(source1, assemblyName: "A"); compilation1.VerifyDiagnostics(); var compilationVerifier = CompileAndVerify(compilation1); var reference1 = MetadataReference.CreateFromImage(compilationVerifier.EmittedAssemblyData); var source2 = @"[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""C"")] namespace NB { internal static class B { public static void F(this object o) { } } }"; var compilation2 = CreateCompilationWithMscorlib40AndSystemCore(source2, assemblyName: "B"); compilation2.VerifyDiagnostics(); compilationVerifier = CompileAndVerify(compilation2); var reference2 = MetadataReference.CreateFromImage(compilationVerifier.EmittedAssemblyData); var source3 = @"using NB; namespace NA.NC { class C { static void Main() { new object().F(); } } }"; var compilation3 = CreateCompilation(source3, assemblyName: "C", references: new[] { reference1, reference2 }); compilation3.VerifyDiagnostics(); } /// <summary> /// As test above but with all classes defined in the same compilation. /// </summary> [WorkItem(602893, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/602893")] [Fact] public void Bug602893_2() { var source = @"using NB; namespace NA { internal static class A { static void F(this object o) { } } } namespace NB { internal static class B { public static void F(this object o) { } } } namespace NA { class C { static void Main() { new object().F(); } } }"; var compilation = CreateCompilationWithMscorlib40AndSystemCore(source); compilation.VerifyDiagnostics(); } /// <summary> /// Ambiguous methods should hide methods in outer scopes. /// </summary> [Fact] public void AmbiguousMethodsHideOuterScope() { var source = @"using NB; namespace NA { internal static class A { public static void F(this object o) { } } internal static class B { public static void F(this object o) { } } class C { static void Main() { new object().F(); } } } namespace NB { internal static class B { public static void F(this object o) { } } }"; var compilation = CreateCompilationWithMscorlib40AndSystemCore(source); compilation.VerifyDiagnostics( // (16,13): error CS0121: The call is ambiguous between the following methods or properties: 'NA.A.F(object)' and 'NA.B.F(object)' Diagnostic(ErrorCode.ERR_AmbigCall, "F").WithArguments("NA.A.F(object)", "NA.B.F(object)").WithLocation(16, 26), // (1,1): info CS8019: Unnecessary using directive. // using NB; Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using NB;")); } [Fact, WorkItem(822125, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/822125")] public void ConsumeFSharpExtensionMethods() { var source = @"using FSharpTestLibrary; namespace CSharpApp { class Program { static void Main() { var question = 42.GetQuestion(); } } }"; var compilation = CreateCompilation(source, references: new[] { FSharpTestLibraryRef }); compilation.VerifyDiagnostics(); } [ClrOnlyFact] public void InternalExtensionAttribute() { var source = @" namespace System.Runtime.CompilerServices { [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)] class ExtensionAttribute : Attribute { } } internal static class Test { public static void M(this int p) { } } "; var compilation = CreateEmptyCompilation(source, new[] { MscorlibRef_v20 }, TestOptions.ReleaseDll); CompileAndVerify(compilation); } [ClrOnlyFact] [WorkItem(1010648, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1010648")] public void ExtensionMethodFromUsingStatic() { const string source = @" using System; using static N.S; class Program { static void Main() { 1.Goo(); } } namespace N { static class S { public static void Goo(this int x) { Console.Write(x); } } }"; CompileAndVerify(source, expectedOutput: "1"); } [Fact, WorkItem(1085744, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1085744")] public void ExtensionMethodsAreNotImportedAsSimpleNames() { const string source = @" using System; using static N.S; class Program { static void Main() { 1.Goo(); Goo(1); } } namespace N { static class S { public static void Goo(this int x) { Console.Write(x); } } }"; var compilation = CreateCompilationWithMscorlib40AndSystemCore(source); compilation.VerifyDiagnostics( // (10,9): error CS0103: The name 'Goo' does not exist in the current context // Goo(1); Diagnostic(ErrorCode.ERR_NameNotInContext, "Goo").WithArguments("Goo").WithLocation(10, 9)); } [ClrOnlyFact] [WorkItem(1010648, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1010648")] public void ExtensionMethodImportedTwiceNoErrors() { const string source = @" using System; using N; using static N.S; class Program { static void Main() { 1.Goo(); } } namespace N { static class S { public static void Goo(this int x) { Console.WriteLine(x); } } }"; CompileAndVerify(source, expectedOutput: "1"); } [Fact, WorkItem(1010648, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1010648")] public void ExtensionMethodIsNotDisambiguatedByUsingStaticAtTheSameLevel() { const string source = @" using N; using static N.S; class Program { static void Main() { 1.Goo(); } } namespace N { static class S { public static void Goo(this int x) { } } static class R { public static void Goo(this int x) { } } }"; var compilation = CreateCompilationWithMscorlib40AndSystemCore(source); compilation.VerifyDiagnostics( // (9,11): error CS0121: The call is ambiguous between the following methods or properties: 'S.Goo(int)' and 'R.Goo(int)' // 1.Goo(); Diagnostic(ErrorCode.ERR_AmbigCall, "Goo").WithArguments("N.S.Goo(int)", "N.R.Goo(int)").WithLocation(9, 11)); } [ClrOnlyFact] [WorkItem(1010648, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1010648")] public void ExtensionMethodIsDisambiguatedByUsingStaticAtDeeperLevel() { const string source = @" using System; using N; namespace K { using static S; class Program { static void Main() { 1.Goo(); } } } namespace N { static class S { public static void Goo(this int x) { Console.WriteLine(""S""); } } static class R { public static void Goo(this int x) { Console.WriteLine(""R""); } } }"; CompileAndVerify(source, expectedOutput: "S"); } [Fact, WorkItem(1010648, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1010648")] public void ExtensionMethodAmbiguousAcrossMultipleUsingStatic() { const string source = @" using System; namespace K { using static N.S; using static N.R; class Program { static void Main() { 1.Goo(); } } } namespace N { static class S { public static void Goo(this int x) { Console.WriteLine(""S""); } } static class R { public static void Goo(this int x) { Console.WriteLine(""R""); } } }"; var compilation = CreateCompilationWithMscorlib40AndSystemCore(source); compilation.VerifyDiagnostics( // (13,15): error CS0121: The call is ambiguous between the following methods or properties: 'S.Goo(int)' and 'R.Goo(int)' // 1.Goo(); Diagnostic(ErrorCode.ERR_AmbigCall, "Goo").WithArguments("N.S.Goo(int)", "N.R.Goo(int)").WithLocation(13, 15)); } [Fact, WorkItem(1010648, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1010648")] public void ExtensionMethodsInTheContainingClassDoNotHaveHigherPrecedence() { const string source = @" namespace N { using static Program; static class Program { static void Main() { 1.Goo(); } public static void Goo(this int x) { } } static class R { public static void Goo(this int x) { } } }"; var compilation = CreateCompilationWithMscorlib40AndSystemCore(source); compilation.VerifyDiagnostics( // (10,15): error CS0121: The call is ambiguous between the following methods or properties: 'Program.Goo(int)' and 'R.Goo(int)' // 1.Goo(); Diagnostic(ErrorCode.ERR_AmbigCall, "Goo").WithArguments("N.Program.Goo(int)", "N.R.Goo(int)").WithLocation(10, 15), // (4,5): hidden CS8019: Unnecessary using directive. // using Program; Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using static Program;").WithLocation(4, 5)); } [Fact, WorkItem(1010648, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1010648")] public void UsingAliasDoesNotImportExtensionMethods() { const string source = @" namespace K { using X = N.S; class Program { static void Main() { 1.Goo(); } } } namespace N { static class S { public static void Goo(this int x) { } } }"; var compilation = CreateCompilationWithMscorlib40AndSystemCore(source); compilation.VerifyDiagnostics( // (9,15): error CS1061: 'int' does not contain a definition for 'Goo' and no extension method 'Goo' accepting a first argument of type 'int' could be found (are you missing a using directive or an assembly reference?) // 1.Goo(); Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "Goo").WithArguments("int", "Goo").WithLocation(9, 15), // (4,5): hidden CS8019: Unnecessary using directive. // using X = N.S; Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using X = N.S;").WithLocation(4, 5)); } [WorkItem(1094849, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1094849"), WorkItem(2288, "https://github.com/dotnet/roslyn/issues/2288")] [Fact] public void LookupSymbolsWithPartialInference() { var source = @" using System.Collections.Generic; namespace ConsoleApplication22 { static class Program { static void Main(string[] args) { } internal static void GetEnumerableDisposable1<T, TEnumerator>(this IEnumerable<T> enumerable) where TEnumerator : struct , IEnumerator<T> { } internal static void GetEnumerableDisposable2<T, TEnumerator>(this IEnumerable<T> enumerable) where TEnumerator : struct { } private static void Overlaps<T, TEnumerator>(IEnumerable<T> other) where TEnumerator : struct, IEnumerator<T> { other.GetEnumerableDisposable1<T, TEnumerator>(); } } }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics(); var syntaxTree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(syntaxTree); var member = (MemberAccessExpressionSyntax)syntaxTree.GetRoot().DescendantNodes().OfType<InvocationExpressionSyntax>().Single().Expression; Assert.Equal("other.GetEnumerableDisposable1<T, TEnumerator>", member.ToString()); var type = model.GetTypeInfo(member.Expression).Type; Assert.Equal("System.Collections.Generic.IEnumerable<T>", type.ToTestDisplayString()); var symbols = model.LookupSymbols(member.Expression.EndPosition, type, includeReducedExtensionMethods: true).Select(s => s.Name).ToArray(); Assert.Contains("GetEnumerableDisposable2", symbols); Assert.Contains("GetEnumerableDisposable1", symbols); } [Fact] public void ScriptExtensionMethods() { var source = @"static object F(this object o) { return null; } class C { void M() { this.F(); } } var o = new object(); o.F();"; var compilation = CreateCompilationWithMscorlib45(source, parseOptions: TestOptions.Script); compilation.VerifyDiagnostics(); } [Fact] public void InteractiveExtensionMethods() { var parseOptions = TestOptions.Script; var references = new[] { MscorlibRef, SystemCoreRef }; var source0 = @"static object F(this object o) { return 0; } var o = new object(); o.F();"; var source1 = @"static object G(this object o) { return 1; } var o = new object(); o.G().F();"; var s0 = CSharpCompilation.CreateScriptCompilation( "s0.dll", syntaxTree: SyntaxFactory.ParseSyntaxTree(source0, options: parseOptions), references: references); s0.VerifyDiagnostics(); var s1 = CSharpCompilation.CreateScriptCompilation( "s1.dll", syntaxTree: SyntaxFactory.ParseSyntaxTree(source1, options: parseOptions), previousScriptCompilation: s0, references: references); s1.VerifyDiagnostics(); } [Fact] [WorkItem(11166, "https://github.com/dotnet/roslyn/issues/11166")] public void SemanticModelLookup_01() { var source = @" public static class TestClass { public static void Test() { var Instance = new BaseClass<int>(); Instance.SetMember(32); } } public static class Extensions { public static BC SetMember<BC, TMember>(this BC This, TMember NewValue) where BC : BaseClass<TMember> { This.Member = NewValue; return This; } } public class BaseClass<TMember> { public TMember Member { get; set; } } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var instance = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(n => n.Identifier.ValueText == "Instance").First(); Assert.Equal("Instance.SetMember", instance.Parent.ToString()); var baseClass = model.GetTypeInfo(instance).Type; Assert.Equal("BaseClass<System.Int32>", baseClass.ToTestDisplayString()); var setMember = model.LookupSymbols(instance.Position, baseClass, "SetMember", includeReducedExtensionMethods: true).Single(); Assert.Equal("BaseClass<System.Int32> BaseClass<System.Int32>.SetMember<BaseClass<System.Int32>, TMember>(TMember NewValue)", setMember.ToTestDisplayString()); Assert.Contains(setMember, model.LookupSymbols(instance.Position, baseClass, includeReducedExtensionMethods: true)); } [Fact] [WorkItem(11166, "https://github.com/dotnet/roslyn/issues/11166")] public void SemanticModelLookup_02() { var source = @" public static class TestClass { public static void Test() { var Instance = new BaseClass<int>(); Instance.SetMember(32); } } public static class Extensions { public static BC SetMember<BC, TMember>(this BC This, TMember NewValue) where BC : BaseClass<long> { return This; } } public class BaseClass<TMember> { public TMember Member { get; set; } } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (7,18): error CS0311: The type 'BaseClass<int>' cannot be used as type parameter 'BC' in the generic type or method 'Extensions.SetMember<BC, TMember>(BC, TMember)'. There is no implicit reference conversion from 'BaseClass<int>' to 'BaseClass<long>'. // Instance.SetMember(32); Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "SetMember").WithArguments("Extensions.SetMember<BC, TMember>(BC, TMember)", "BaseClass<long>", "BC", "BaseClass<int>").WithLocation(7, 18) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var instance = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(n => n.Identifier.ValueText == "Instance").First(); Assert.Equal("Instance.SetMember", instance.Parent.ToString()); var baseClass = model.GetTypeInfo(instance).Type; Assert.Equal("BaseClass<System.Int32>", baseClass.ToTestDisplayString()); Assert.Empty(model.LookupSymbols(instance.Position, baseClass, "SetMember", includeReducedExtensionMethods: true)); Assert.Empty(model.LookupSymbols(instance.Position, baseClass, includeReducedExtensionMethods: true).Where(s => s.Name == "SetMembers")); } [Fact] [WorkItem(11166, "https://github.com/dotnet/roslyn/issues/11166")] public void SemanticModelLookup_03() { var source = @" public static class TestClass { public static void Test() { var Instance = new BaseClass<int>(); Instance.SetMember(32); } } public static class Extensions { public static BC SetMember<BC, TMember>(this BC This, TMember NewValue) where BC : BaseClass<TMember>, I1<TMember> { This.Member = NewValue; return This; } } public interface I1<T>{} public class BaseClass<TMember> : I1<TMember> { public TMember Member { get; set; } } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var instance = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(n => n.Identifier.ValueText == "Instance").First(); Assert.Equal("Instance.SetMember", instance.Parent.ToString()); var baseClass = model.GetTypeInfo(instance).Type; Assert.Equal("BaseClass<System.Int32>", baseClass.ToTestDisplayString()); var setMember = model.LookupSymbols(instance.Position, baseClass, "SetMember", includeReducedExtensionMethods: true).Single(); Assert.Equal("BaseClass<System.Int32> BaseClass<System.Int32>.SetMember<BaseClass<System.Int32>, TMember>(TMember NewValue)", setMember.ToTestDisplayString()); Assert.Contains(setMember, model.LookupSymbols(instance.Position, baseClass, includeReducedExtensionMethods: true)); } [Fact] [WorkItem(11166, "https://github.com/dotnet/roslyn/issues/11166")] public void SemanticModelLookup_04() { var source = @" public static class TestClass { public static void Test() { var Instance = new BaseClass<int>(); Instance.SetMember(32); } } public static class Extensions { public static BC SetMember<BC, TMember>(this BC This, TMember NewValue) where BC : BaseClass<TMember>, I1<long> { This.Member = NewValue; return This; } } public interface I1<T>{} public class BaseClass<TMember> : I1<TMember> { public TMember Member { get; set; } } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (7,18): error CS0311: The type 'BaseClass<int>' cannot be used as type parameter 'BC' in the generic type or method 'Extensions.SetMember<BC, TMember>(BC, TMember)'. There is no implicit reference conversion from 'BaseClass<int>' to 'I1<long>'. // Instance.SetMember(32); Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "SetMember").WithArguments("Extensions.SetMember<BC, TMember>(BC, TMember)", "I1<long>", "BC", "BaseClass<int>").WithLocation(7, 18) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var instance = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(n => n.Identifier.ValueText == "Instance").First(); Assert.Equal("Instance.SetMember", instance.Parent.ToString()); var baseClass = model.GetTypeInfo(instance).Type; Assert.Equal("BaseClass<System.Int32>", baseClass.ToTestDisplayString()); Assert.Empty(model.LookupSymbols(instance.Position, baseClass, "SetMember", includeReducedExtensionMethods: true)); Assert.Empty(model.LookupSymbols(instance.Position, baseClass, includeReducedExtensionMethods: true).Where(s => s.Name == "SetMembers")); } [Fact] public void InExtensionMethods() { var source = @" public static class C { public static void M1(this in int p) { } public static void M2(in this int p) { } }"; void Validator(ModuleSymbol module) { var type = module.GlobalNamespace.GetMember<NamedTypeSymbol>("C"); var method = type.GetMember<MethodSymbol>("M1"); Assert.True(method.IsExtensionMethod); var parameter = method.Parameters[0]; Assert.Equal(SpecialType.System_Int32, parameter.Type.SpecialType); Assert.Equal(RefKind.In, parameter.RefKind); method = type.GetMember<MethodSymbol>("M2"); Assert.True(method.IsExtensionMethod); parameter = method.Parameters[0]; Assert.Equal(SpecialType.System_Int32, parameter.Type.SpecialType); Assert.Equal(RefKind.In, parameter.RefKind); } CompileAndVerify(source, validator: Validator, options: TestOptions.ReleaseDll); } [Fact] public void RefExtensionMethods() { var source = @" public static class C { public static void M1(this ref int p) { } public static void M2(ref this int p) { } }"; void Validator(ModuleSymbol module) { var type = module.GlobalNamespace.GetMember<NamedTypeSymbol>("C"); var method = type.GetMember<MethodSymbol>("M1"); Assert.True(method.IsExtensionMethod); var parameter = method.Parameters[0]; Assert.Equal(SpecialType.System_Int32, parameter.Type.SpecialType); Assert.Equal(RefKind.Ref, parameter.RefKind); method = type.GetMember<MethodSymbol>("M2"); Assert.True(method.IsExtensionMethod); parameter = method.Parameters[0]; Assert.Equal(SpecialType.System_Int32, parameter.Type.SpecialType); Assert.Equal(RefKind.Ref, parameter.RefKind); } CompileAndVerify(source, validator: Validator, options: TestOptions.ReleaseDll); } } }
1
dotnet/roslyn
55,256
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-30T00:02:02Z
2021-07-30T09:17:54Z
6ce9c0048d37026337701fac035ac0745f6fe49f
88b59775dc6375635957ef229116460f290072aa
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Compilers/Core/Portable/FileSystemExtensions.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.IO; using System.Threading; using Microsoft.CodeAnalysis.Emit; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { public static class FileSystemExtensions { /// <summary> /// Emit the IL for the compilation into the specified stream. /// </summary> /// <param name="compilation">Compilation.</param> /// <param name="outputPath">Path of the file to which the compilation will be written.</param> /// <param name="pdbPath">Path of the file to which the compilation's debug info will be written. /// Also embedded in the output file. Null to forego PDB generation. /// </param> /// <param name="xmlDocPath">Path of the file to which the compilation's XML documentation will be written. Null to forego XML generation.</param> /// <param name="win32ResourcesPath">Path of the file from which the compilation's Win32 resources will be read (in RES format). /// Null to indicate that there are none.</param> /// <param name="manifestResources">List of the compilation's managed resources. Null to indicate that there are none.</param> /// <param name="cancellationToken">To cancel the emit process.</param> /// <exception cref="ArgumentNullException">Compilation or path is null.</exception> /// <exception cref="ArgumentException">Path is empty or invalid.</exception> /// <exception cref="IOException">An error occurred while reading or writing a file.</exception> public static EmitResult Emit( this Compilation compilation, string outputPath, string? pdbPath = null, string? xmlDocPath = null, string? win32ResourcesPath = null, IEnumerable<ResourceDescription>? manifestResources = null, CancellationToken cancellationToken = default) { if (compilation == null) { throw new ArgumentNullException(nameof(compilation)); } using (var outputStream = FileUtilities.CreateFileStreamChecked(File.Create, outputPath, nameof(outputPath))) using (var pdbStream = (pdbPath == null ? null : FileUtilities.CreateFileStreamChecked(File.Create, pdbPath, nameof(pdbPath)))) using (var xmlDocStream = (xmlDocPath == null ? null : FileUtilities.CreateFileStreamChecked(File.Create, xmlDocPath, nameof(xmlDocPath)))) using (var win32ResourcesStream = (win32ResourcesPath == null ? null : FileUtilities.CreateFileStreamChecked(File.OpenRead, win32ResourcesPath, nameof(win32ResourcesPath)))) { return compilation.Emit( outputStream, pdbStream: pdbStream, xmlDocumentationStream: xmlDocStream, win32Resources: win32ResourcesStream, manifestResources: manifestResources, options: new EmitOptions(pdbFilePath: pdbPath), 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; using System.Collections.Generic; using System.IO; using System.Threading; using Microsoft.CodeAnalysis.Emit; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { public static class FileSystemExtensions { /// <summary> /// Emit the IL for the compilation into the specified stream. /// </summary> /// <param name="compilation">Compilation.</param> /// <param name="outputPath">Path of the file to which the compilation will be written.</param> /// <param name="pdbPath">Path of the file to which the compilation's debug info will be written. /// Also embedded in the output file. Null to forego PDB generation. /// </param> /// <param name="xmlDocPath">Path of the file to which the compilation's XML documentation will be written. Null to forego XML generation.</param> /// <param name="win32ResourcesPath">Path of the file from which the compilation's Win32 resources will be read (in RES format). /// Null to indicate that there are none.</param> /// <param name="manifestResources">List of the compilation's managed resources. Null to indicate that there are none.</param> /// <param name="cancellationToken">To cancel the emit process.</param> /// <exception cref="ArgumentNullException">Compilation or path is null.</exception> /// <exception cref="ArgumentException">Path is empty or invalid.</exception> /// <exception cref="IOException">An error occurred while reading or writing a file.</exception> public static EmitResult Emit( this Compilation compilation, string outputPath, string? pdbPath = null, string? xmlDocPath = null, string? win32ResourcesPath = null, IEnumerable<ResourceDescription>? manifestResources = null, CancellationToken cancellationToken = default) { if (compilation == null) { throw new ArgumentNullException(nameof(compilation)); } using (var outputStream = FileUtilities.CreateFileStreamChecked(File.Create, outputPath, nameof(outputPath))) using (var pdbStream = (pdbPath == null ? null : FileUtilities.CreateFileStreamChecked(File.Create, pdbPath, nameof(pdbPath)))) using (var xmlDocStream = (xmlDocPath == null ? null : FileUtilities.CreateFileStreamChecked(File.Create, xmlDocPath, nameof(xmlDocPath)))) using (var win32ResourcesStream = (win32ResourcesPath == null ? null : FileUtilities.CreateFileStreamChecked(File.OpenRead, win32ResourcesPath, nameof(win32ResourcesPath)))) { return compilation.Emit( outputStream, pdbStream: pdbStream, xmlDocumentationStream: xmlDocStream, win32Resources: win32ResourcesStream, manifestResources: manifestResources, options: new EmitOptions(pdbFilePath: pdbPath), cancellationToken: cancellationToken); } } } }
-1
dotnet/roslyn
55,256
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-30T00:02:02Z
2021-07-30T09:17:54Z
6ce9c0048d37026337701fac035ac0745f6fe49f
88b59775dc6375635957ef229116460f290072aa
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/VisualStudio/Core/Def/Implementation/Extensions/ITextSnapshotExtensions.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET 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.Text.Shared.Extensions; using Microsoft.VisualStudio.Text; using VsTextSpan = Microsoft.VisualStudio.TextManager.Interop.TextSpan; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Extensions { internal static class ITextSnapshotExtensions { public static SnapshotSpan GetSpan(this ITextSnapshot snapshot, VsTextSpan textSpan) => TryGetSpan(snapshot, textSpan).Value; public static SnapshotSpan? TryGetSpan(this ITextSnapshot snapshot, VsTextSpan textSpan) => snapshot.TryGetSpan(textSpan.iStartLine, textSpan.iStartIndex, textSpan.iEndLine, textSpan.iEndIndex); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET 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.Text.Shared.Extensions; using Microsoft.VisualStudio.Text; using VsTextSpan = Microsoft.VisualStudio.TextManager.Interop.TextSpan; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Extensions { internal static class ITextSnapshotExtensions { public static SnapshotSpan GetSpan(this ITextSnapshot snapshot, VsTextSpan textSpan) => TryGetSpan(snapshot, textSpan).Value; public static SnapshotSpan? TryGetSpan(this ITextSnapshot snapshot, VsTextSpan textSpan) => snapshot.TryGetSpan(textSpan.iStartLine, textSpan.iStartIndex, textSpan.iEndLine, textSpan.iEndIndex); } }
-1
dotnet/roslyn
55,256
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-30T00:02:02Z
2021-07-30T09:17:54Z
6ce9c0048d37026337701fac035ac0745f6fe49f
88b59775dc6375635957ef229116460f290072aa
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Compilers/CSharp/Test/Syntax/Parsing/TypeArgumentListParsingTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET 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; using Xunit.Abstractions; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class TypeArgumentListParsingTests : ParsingTests { public TypeArgumentListParsingTests(ITestOutputHelper output) : base(output) { } protected override SyntaxTree ParseTree(string text, CSharpParseOptions options) { return SyntaxFactory.ParseSyntaxTree(text, options: options); } [Fact, WorkItem(19456, "https://github.com/dotnet/roslyn/issues/19456")] public void TestPredefinedType() { UsingTree(@" class C { void M() { var added = ImmutableDictionary<string, IImmutableDictionary<X, Y>> ProjectChange = projectChange; } } "); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "M"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.LocalDeclarationStatement); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "added"); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken, "ImmutableDictionary"); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.PredefinedType); { N(SyntaxKind.StringKeyword); } N(SyntaxKind.CommaToken); N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken, "IImmutableDictionary"); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "X"); } N(SyntaxKind.CommaToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Y"); } N(SyntaxKind.GreaterThanToken); } } N(SyntaxKind.GreaterThanToken); } } } } } M(SyntaxKind.SemicolonToken); } N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "ProjectChange"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "projectChange"); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact, WorkItem(19456, "https://github.com/dotnet/roslyn/issues/19456")] public void TestArrayType() { UsingTree(@" class C { void M() { var added = ImmutableDictionary<X[], IImmutableDictionary<X, Y>> ProjectChange = projectChange; } } "); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "M"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.LocalDeclarationStatement); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "added"); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken, "ImmutableDictionary"); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.ArrayType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "X"); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } N(SyntaxKind.CommaToken); N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken, "IImmutableDictionary"); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "X"); } N(SyntaxKind.CommaToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Y"); } N(SyntaxKind.GreaterThanToken); } } N(SyntaxKind.GreaterThanToken); } } } } } M(SyntaxKind.SemicolonToken); } N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "ProjectChange"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "projectChange"); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact, WorkItem(19456, "https://github.com/dotnet/roslyn/issues/19456")] public void TestPredefinedPointerType() { UsingTree(@" class C { void M() { var added = ImmutableDictionary<int*, IImmutableDictionary<X, Y>> ProjectChange = projectChange; } } "); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "M"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.LocalDeclarationStatement); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "added"); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken, "ImmutableDictionary"); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.PointerType); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.AsteriskToken); } N(SyntaxKind.CommaToken); N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken, "IImmutableDictionary"); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "X"); } N(SyntaxKind.CommaToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Y"); } N(SyntaxKind.GreaterThanToken); } } N(SyntaxKind.GreaterThanToken); } } } } } M(SyntaxKind.SemicolonToken); } N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "ProjectChange"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "projectChange"); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact, WorkItem(19456, "https://github.com/dotnet/roslyn/issues/19456")] public void TestNonPredefinedPointerType() { UsingTree(@" class C { void M() { var added = ImmutableDictionary<X*, IImmutableDictionary<X, Y>> ProjectChange = projectChange; } } "); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "M"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.LocalDeclarationStatement); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "added"); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.LessThanExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "ImmutableDictionary"); } N(SyntaxKind.LessThanToken); N(SyntaxKind.MultiplyExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "X"); } N(SyntaxKind.AsteriskToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } } } } N(SyntaxKind.CommaToken); N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "IImmutableDictionary"); } } M(SyntaxKind.SemicolonToken); } N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.LessThanExpression); { M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } N(SyntaxKind.LessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "X"); } } M(SyntaxKind.SemicolonToken); } N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.RightShiftExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Y"); } N(SyntaxKind.GreaterThanGreaterThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "ProjectChange"); } } N(SyntaxKind.EqualsToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "projectChange"); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact, WorkItem(19456, "https://github.com/dotnet/roslyn/issues/19456")] public void TestTwoItemTupleType() { UsingTree(@" class C { void M() { var added = ImmutableDictionary<(int, string), IImmutableDictionary<X, Y>> ProjectChange = projectChange; } } "); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "M"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.LocalDeclarationStatement); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "added"); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.LessThanExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "ImmutableDictionary"); } N(SyntaxKind.LessThanToken); N(SyntaxKind.TupleExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } } N(SyntaxKind.CommaToken); N(SyntaxKind.Argument); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.StringKeyword); } } N(SyntaxKind.CloseParenToken); } } } } N(SyntaxKind.CommaToken); N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "IImmutableDictionary"); } } M(SyntaxKind.SemicolonToken); } N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.LessThanExpression); { M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } N(SyntaxKind.LessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "X"); } } M(SyntaxKind.SemicolonToken); } N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.RightShiftExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Y"); } N(SyntaxKind.GreaterThanGreaterThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "ProjectChange"); } } N(SyntaxKind.EqualsToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "projectChange"); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact, WorkItem(19456, "https://github.com/dotnet/roslyn/issues/19456")] public void TestComparisonToTuple() { UsingTree(@" public class C { public static void Main() { XX X = new XX(); int a = 1, b = 2; bool z = X < (a, b), w = false; } } struct XX { public static bool operator <(XX x, (int a, int b) arg) => true; public static bool operator >(XX x, (int a, int b) arg) => false; }"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.PublicKeyword); N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PublicKeyword); N(SyntaxKind.StaticKeyword); N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "Main"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.LocalDeclarationStatement); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "XX"); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "X"); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.ObjectCreationExpression); { N(SyntaxKind.NewKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "XX"); } N(SyntaxKind.ArgumentList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } } } } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.LocalDeclarationStatement); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "a"); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } } N(SyntaxKind.CommaToken); N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "b"); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "2"); } } } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.LocalDeclarationStatement); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.BoolKeyword); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "z"); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.LessThanExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "X"); } N(SyntaxKind.LessThanToken); N(SyntaxKind.TupleExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.Argument); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } } N(SyntaxKind.CloseParenToken); } } } } N(SyntaxKind.CommaToken); N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "w"); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.FalseLiteralExpression); { N(SyntaxKind.FalseKeyword); } } } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.StructDeclaration); { N(SyntaxKind.StructKeyword); N(SyntaxKind.IdentifierToken, "XX"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.OperatorDeclaration); { N(SyntaxKind.PublicKeyword); N(SyntaxKind.StaticKeyword); N(SyntaxKind.PredefinedType); { N(SyntaxKind.BoolKeyword); } N(SyntaxKind.OperatorKeyword); N(SyntaxKind.LessThanToken); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "XX"); } N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.CommaToken); N(SyntaxKind.Parameter); { N(SyntaxKind.TupleType); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.CommaToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "b"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.IdentifierToken, "arg"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrowExpressionClause); { N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.TrueLiteralExpression); { N(SyntaxKind.TrueKeyword); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.OperatorDeclaration); { N(SyntaxKind.PublicKeyword); N(SyntaxKind.StaticKeyword); N(SyntaxKind.PredefinedType); { N(SyntaxKind.BoolKeyword); } N(SyntaxKind.OperatorKeyword); N(SyntaxKind.GreaterThanToken); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "XX"); } N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.CommaToken); N(SyntaxKind.Parameter); { N(SyntaxKind.TupleType); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.CommaToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "b"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.IdentifierToken, "arg"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrowExpressionClause); { N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.FalseLiteralExpression); { N(SyntaxKind.FalseKeyword); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact, WorkItem(19456, "https://github.com/dotnet/roslyn/issues/19456")] public void TestOneItemTupleType() { UsingTree(@" class C { void M() { var added = ImmutableDictionary<(A), IImmutableDictionary<X, Y>> ProjectChange = projectChange; } } "); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "M"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.LocalDeclarationStatement); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "added"); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.LessThanExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "ImmutableDictionary"); } N(SyntaxKind.LessThanToken); N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } N(SyntaxKind.CloseParenToken); } } } } N(SyntaxKind.CommaToken); N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "IImmutableDictionary"); } } M(SyntaxKind.SemicolonToken); } N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.LessThanExpression); { M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } N(SyntaxKind.LessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "X"); } } M(SyntaxKind.SemicolonToken); } N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.RightShiftExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Y"); } N(SyntaxKind.GreaterThanGreaterThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "ProjectChange"); } } N(SyntaxKind.EqualsToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "projectChange"); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact, WorkItem(19456, "https://github.com/dotnet/roslyn/issues/19456")] public void TestQualifiedName() { UsingTree(@" class C { void M() { var added = ImmutableDictionary<A.B, IImmutableDictionary<X, Y>> ProjectChange = projectChange; } } "); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "M"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.LocalDeclarationStatement); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "added"); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.LessThanExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "ImmutableDictionary"); } N(SyntaxKind.LessThanToken); N(SyntaxKind.SimpleMemberAccessExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "B"); } } } } } N(SyntaxKind.CommaToken); N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "IImmutableDictionary"); } } M(SyntaxKind.SemicolonToken); } N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.LessThanExpression); { M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } N(SyntaxKind.LessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "X"); } } M(SyntaxKind.SemicolonToken); } N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.RightShiftExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Y"); } N(SyntaxKind.GreaterThanGreaterThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "ProjectChange"); } } N(SyntaxKind.EqualsToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "projectChange"); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact, WorkItem(19456, "https://github.com/dotnet/roslyn/issues/19456")] public void TestAliasName() { UsingTree(@" class C { void M() { var added = ImmutableDictionary<A::B, IImmutableDictionary<X, Y>> ProjectChange = projectChange; } } "); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "M"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.LocalDeclarationStatement); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "added"); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.LessThanExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "ImmutableDictionary"); } N(SyntaxKind.LessThanToken); N(SyntaxKind.AliasQualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } N(SyntaxKind.ColonColonToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "B"); } } } } } N(SyntaxKind.CommaToken); N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "IImmutableDictionary"); } } M(SyntaxKind.SemicolonToken); } N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.LessThanExpression); { M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } N(SyntaxKind.LessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "X"); } } M(SyntaxKind.SemicolonToken); } N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.RightShiftExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Y"); } N(SyntaxKind.GreaterThanGreaterThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "ProjectChange"); } } N(SyntaxKind.EqualsToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "projectChange"); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact, WorkItem(19456, "https://github.com/dotnet/roslyn/issues/19456")] public void TestNullableTypeWithComma() { UsingTree(@" class C { void M() { var added = ImmutableDictionary<A?, IImmutableDictionary<X, Y>> ProjectChange = projectChange; } } "); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "M"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.LocalDeclarationStatement); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "added"); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken, "ImmutableDictionary"); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.NullableType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } N(SyntaxKind.QuestionToken); } N(SyntaxKind.CommaToken); N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken, "IImmutableDictionary"); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "X"); } N(SyntaxKind.CommaToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Y"); } N(SyntaxKind.GreaterThanToken); } } N(SyntaxKind.GreaterThanToken); } } } } } M(SyntaxKind.SemicolonToken); } N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "ProjectChange"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "projectChange"); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact, WorkItem(19456, "https://github.com/dotnet/roslyn/issues/19456")] public void TestNullableTypeWithGreaterThan() { UsingTree(@" class C { void M() { var added = ImmutableDictionary<A?> ProjectChange = projectChange; } } "); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "M"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.LocalDeclarationStatement); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "added"); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken, "ImmutableDictionary"); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.NullableType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } N(SyntaxKind.QuestionToken); } N(SyntaxKind.GreaterThanToken); } } } } } M(SyntaxKind.SemicolonToken); } N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "ProjectChange"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "projectChange"); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact, WorkItem(19456, "https://github.com/dotnet/roslyn/issues/19456")] public void TestNotNullableType() { UsingTree(@" class C { void M() { var added = ImmutableDictionary<A? ProjectChange = projectChange; } } "); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "M"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.LocalDeclarationStatement); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "added"); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.LessThanExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "ImmutableDictionary"); } N(SyntaxKind.LessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } } N(SyntaxKind.QuestionToken); N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "ProjectChange"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "projectChange"); } } M(SyntaxKind.ColonToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } } } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact, WorkItem(19456, "https://github.com/dotnet/roslyn/issues/19456")] public void TestGenericArgWithComma() { UsingTree(@" class C { void M() { var added = ImmutableDictionary<T<S>, IImmutableDictionary<X, Y>> ProjectChange = projectChange; } } "); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "M"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.LocalDeclarationStatement); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "added"); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken, "ImmutableDictionary"); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken, "T"); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "S"); } N(SyntaxKind.GreaterThanToken); } } N(SyntaxKind.CommaToken); N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken, "IImmutableDictionary"); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "X"); } N(SyntaxKind.CommaToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Y"); } N(SyntaxKind.GreaterThanToken); } } N(SyntaxKind.GreaterThanToken); } } } } } M(SyntaxKind.SemicolonToken); } N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "ProjectChange"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "projectChange"); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact, WorkItem(19456, "https://github.com/dotnet/roslyn/issues/19456")] public void TestGenericArgWithGreaterThan() { UsingTree(@" class C { void M() { var added = ImmutableDictionary<T<S>> ProjectChange = projectChange; } } "); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "M"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.LocalDeclarationStatement); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "added"); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.LessThanExpression); { N(SyntaxKind.LessThanExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "ImmutableDictionary"); } N(SyntaxKind.LessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } } N(SyntaxKind.LessThanToken); N(SyntaxKind.RightShiftExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "S"); } N(SyntaxKind.GreaterThanGreaterThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "ProjectChange"); } } } N(SyntaxKind.EqualsToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "projectChange"); } } } } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Roslyn.Test.Utilities; using Xunit; using Xunit.Abstractions; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class TypeArgumentListParsingTests : ParsingTests { public TypeArgumentListParsingTests(ITestOutputHelper output) : base(output) { } protected override SyntaxTree ParseTree(string text, CSharpParseOptions options) { return SyntaxFactory.ParseSyntaxTree(text, options: options); } [Fact, WorkItem(19456, "https://github.com/dotnet/roslyn/issues/19456")] public void TestPredefinedType() { UsingTree(@" class C { void M() { var added = ImmutableDictionary<string, IImmutableDictionary<X, Y>> ProjectChange = projectChange; } } "); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "M"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.LocalDeclarationStatement); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "added"); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken, "ImmutableDictionary"); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.PredefinedType); { N(SyntaxKind.StringKeyword); } N(SyntaxKind.CommaToken); N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken, "IImmutableDictionary"); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "X"); } N(SyntaxKind.CommaToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Y"); } N(SyntaxKind.GreaterThanToken); } } N(SyntaxKind.GreaterThanToken); } } } } } M(SyntaxKind.SemicolonToken); } N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "ProjectChange"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "projectChange"); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact, WorkItem(19456, "https://github.com/dotnet/roslyn/issues/19456")] public void TestArrayType() { UsingTree(@" class C { void M() { var added = ImmutableDictionary<X[], IImmutableDictionary<X, Y>> ProjectChange = projectChange; } } "); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "M"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.LocalDeclarationStatement); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "added"); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken, "ImmutableDictionary"); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.ArrayType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "X"); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } N(SyntaxKind.CommaToken); N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken, "IImmutableDictionary"); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "X"); } N(SyntaxKind.CommaToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Y"); } N(SyntaxKind.GreaterThanToken); } } N(SyntaxKind.GreaterThanToken); } } } } } M(SyntaxKind.SemicolonToken); } N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "ProjectChange"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "projectChange"); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact, WorkItem(19456, "https://github.com/dotnet/roslyn/issues/19456")] public void TestPredefinedPointerType() { UsingTree(@" class C { void M() { var added = ImmutableDictionary<int*, IImmutableDictionary<X, Y>> ProjectChange = projectChange; } } "); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "M"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.LocalDeclarationStatement); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "added"); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken, "ImmutableDictionary"); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.PointerType); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.AsteriskToken); } N(SyntaxKind.CommaToken); N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken, "IImmutableDictionary"); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "X"); } N(SyntaxKind.CommaToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Y"); } N(SyntaxKind.GreaterThanToken); } } N(SyntaxKind.GreaterThanToken); } } } } } M(SyntaxKind.SemicolonToken); } N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "ProjectChange"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "projectChange"); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact, WorkItem(19456, "https://github.com/dotnet/roslyn/issues/19456")] public void TestNonPredefinedPointerType() { UsingTree(@" class C { void M() { var added = ImmutableDictionary<X*, IImmutableDictionary<X, Y>> ProjectChange = projectChange; } } "); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "M"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.LocalDeclarationStatement); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "added"); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.LessThanExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "ImmutableDictionary"); } N(SyntaxKind.LessThanToken); N(SyntaxKind.MultiplyExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "X"); } N(SyntaxKind.AsteriskToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } } } } N(SyntaxKind.CommaToken); N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "IImmutableDictionary"); } } M(SyntaxKind.SemicolonToken); } N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.LessThanExpression); { M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } N(SyntaxKind.LessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "X"); } } M(SyntaxKind.SemicolonToken); } N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.RightShiftExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Y"); } N(SyntaxKind.GreaterThanGreaterThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "ProjectChange"); } } N(SyntaxKind.EqualsToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "projectChange"); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact, WorkItem(19456, "https://github.com/dotnet/roslyn/issues/19456")] public void TestTwoItemTupleType() { UsingTree(@" class C { void M() { var added = ImmutableDictionary<(int, string), IImmutableDictionary<X, Y>> ProjectChange = projectChange; } } "); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "M"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.LocalDeclarationStatement); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "added"); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.LessThanExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "ImmutableDictionary"); } N(SyntaxKind.LessThanToken); N(SyntaxKind.TupleExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } } N(SyntaxKind.CommaToken); N(SyntaxKind.Argument); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.StringKeyword); } } N(SyntaxKind.CloseParenToken); } } } } N(SyntaxKind.CommaToken); N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "IImmutableDictionary"); } } M(SyntaxKind.SemicolonToken); } N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.LessThanExpression); { M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } N(SyntaxKind.LessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "X"); } } M(SyntaxKind.SemicolonToken); } N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.RightShiftExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Y"); } N(SyntaxKind.GreaterThanGreaterThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "ProjectChange"); } } N(SyntaxKind.EqualsToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "projectChange"); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact, WorkItem(19456, "https://github.com/dotnet/roslyn/issues/19456")] public void TestComparisonToTuple() { UsingTree(@" public class C { public static void Main() { XX X = new XX(); int a = 1, b = 2; bool z = X < (a, b), w = false; } } struct XX { public static bool operator <(XX x, (int a, int b) arg) => true; public static bool operator >(XX x, (int a, int b) arg) => false; }"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.PublicKeyword); N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PublicKeyword); N(SyntaxKind.StaticKeyword); N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "Main"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.LocalDeclarationStatement); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "XX"); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "X"); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.ObjectCreationExpression); { N(SyntaxKind.NewKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "XX"); } N(SyntaxKind.ArgumentList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } } } } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.LocalDeclarationStatement); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "a"); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } } N(SyntaxKind.CommaToken); N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "b"); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "2"); } } } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.LocalDeclarationStatement); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.BoolKeyword); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "z"); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.LessThanExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "X"); } N(SyntaxKind.LessThanToken); N(SyntaxKind.TupleExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.Argument); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } } N(SyntaxKind.CloseParenToken); } } } } N(SyntaxKind.CommaToken); N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "w"); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.FalseLiteralExpression); { N(SyntaxKind.FalseKeyword); } } } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.StructDeclaration); { N(SyntaxKind.StructKeyword); N(SyntaxKind.IdentifierToken, "XX"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.OperatorDeclaration); { N(SyntaxKind.PublicKeyword); N(SyntaxKind.StaticKeyword); N(SyntaxKind.PredefinedType); { N(SyntaxKind.BoolKeyword); } N(SyntaxKind.OperatorKeyword); N(SyntaxKind.LessThanToken); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "XX"); } N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.CommaToken); N(SyntaxKind.Parameter); { N(SyntaxKind.TupleType); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.CommaToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "b"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.IdentifierToken, "arg"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrowExpressionClause); { N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.TrueLiteralExpression); { N(SyntaxKind.TrueKeyword); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.OperatorDeclaration); { N(SyntaxKind.PublicKeyword); N(SyntaxKind.StaticKeyword); N(SyntaxKind.PredefinedType); { N(SyntaxKind.BoolKeyword); } N(SyntaxKind.OperatorKeyword); N(SyntaxKind.GreaterThanToken); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "XX"); } N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.CommaToken); N(SyntaxKind.Parameter); { N(SyntaxKind.TupleType); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.CommaToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "b"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.IdentifierToken, "arg"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrowExpressionClause); { N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.FalseLiteralExpression); { N(SyntaxKind.FalseKeyword); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact, WorkItem(19456, "https://github.com/dotnet/roslyn/issues/19456")] public void TestOneItemTupleType() { UsingTree(@" class C { void M() { var added = ImmutableDictionary<(A), IImmutableDictionary<X, Y>> ProjectChange = projectChange; } } "); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "M"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.LocalDeclarationStatement); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "added"); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.LessThanExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "ImmutableDictionary"); } N(SyntaxKind.LessThanToken); N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } N(SyntaxKind.CloseParenToken); } } } } N(SyntaxKind.CommaToken); N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "IImmutableDictionary"); } } M(SyntaxKind.SemicolonToken); } N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.LessThanExpression); { M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } N(SyntaxKind.LessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "X"); } } M(SyntaxKind.SemicolonToken); } N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.RightShiftExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Y"); } N(SyntaxKind.GreaterThanGreaterThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "ProjectChange"); } } N(SyntaxKind.EqualsToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "projectChange"); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact, WorkItem(19456, "https://github.com/dotnet/roslyn/issues/19456")] public void TestQualifiedName() { UsingTree(@" class C { void M() { var added = ImmutableDictionary<A.B, IImmutableDictionary<X, Y>> ProjectChange = projectChange; } } "); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "M"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.LocalDeclarationStatement); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "added"); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.LessThanExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "ImmutableDictionary"); } N(SyntaxKind.LessThanToken); N(SyntaxKind.SimpleMemberAccessExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "B"); } } } } } N(SyntaxKind.CommaToken); N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "IImmutableDictionary"); } } M(SyntaxKind.SemicolonToken); } N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.LessThanExpression); { M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } N(SyntaxKind.LessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "X"); } } M(SyntaxKind.SemicolonToken); } N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.RightShiftExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Y"); } N(SyntaxKind.GreaterThanGreaterThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "ProjectChange"); } } N(SyntaxKind.EqualsToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "projectChange"); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact, WorkItem(19456, "https://github.com/dotnet/roslyn/issues/19456")] public void TestAliasName() { UsingTree(@" class C { void M() { var added = ImmutableDictionary<A::B, IImmutableDictionary<X, Y>> ProjectChange = projectChange; } } "); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "M"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.LocalDeclarationStatement); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "added"); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.LessThanExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "ImmutableDictionary"); } N(SyntaxKind.LessThanToken); N(SyntaxKind.AliasQualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } N(SyntaxKind.ColonColonToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "B"); } } } } } N(SyntaxKind.CommaToken); N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "IImmutableDictionary"); } } M(SyntaxKind.SemicolonToken); } N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.LessThanExpression); { M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } N(SyntaxKind.LessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "X"); } } M(SyntaxKind.SemicolonToken); } N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.RightShiftExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Y"); } N(SyntaxKind.GreaterThanGreaterThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "ProjectChange"); } } N(SyntaxKind.EqualsToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "projectChange"); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact, WorkItem(19456, "https://github.com/dotnet/roslyn/issues/19456")] public void TestNullableTypeWithComma() { UsingTree(@" class C { void M() { var added = ImmutableDictionary<A?, IImmutableDictionary<X, Y>> ProjectChange = projectChange; } } "); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "M"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.LocalDeclarationStatement); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "added"); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken, "ImmutableDictionary"); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.NullableType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } N(SyntaxKind.QuestionToken); } N(SyntaxKind.CommaToken); N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken, "IImmutableDictionary"); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "X"); } N(SyntaxKind.CommaToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Y"); } N(SyntaxKind.GreaterThanToken); } } N(SyntaxKind.GreaterThanToken); } } } } } M(SyntaxKind.SemicolonToken); } N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "ProjectChange"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "projectChange"); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact, WorkItem(19456, "https://github.com/dotnet/roslyn/issues/19456")] public void TestNullableTypeWithGreaterThan() { UsingTree(@" class C { void M() { var added = ImmutableDictionary<A?> ProjectChange = projectChange; } } "); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "M"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.LocalDeclarationStatement); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "added"); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken, "ImmutableDictionary"); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.NullableType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } N(SyntaxKind.QuestionToken); } N(SyntaxKind.GreaterThanToken); } } } } } M(SyntaxKind.SemicolonToken); } N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "ProjectChange"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "projectChange"); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact, WorkItem(19456, "https://github.com/dotnet/roslyn/issues/19456")] public void TestNotNullableType() { UsingTree(@" class C { void M() { var added = ImmutableDictionary<A? ProjectChange = projectChange; } } "); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "M"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.LocalDeclarationStatement); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "added"); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.LessThanExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "ImmutableDictionary"); } N(SyntaxKind.LessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } } N(SyntaxKind.QuestionToken); N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "ProjectChange"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "projectChange"); } } M(SyntaxKind.ColonToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } } } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact, WorkItem(19456, "https://github.com/dotnet/roslyn/issues/19456")] public void TestGenericArgWithComma() { UsingTree(@" class C { void M() { var added = ImmutableDictionary<T<S>, IImmutableDictionary<X, Y>> ProjectChange = projectChange; } } "); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "M"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.LocalDeclarationStatement); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "added"); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken, "ImmutableDictionary"); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken, "T"); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "S"); } N(SyntaxKind.GreaterThanToken); } } N(SyntaxKind.CommaToken); N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken, "IImmutableDictionary"); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "X"); } N(SyntaxKind.CommaToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Y"); } N(SyntaxKind.GreaterThanToken); } } N(SyntaxKind.GreaterThanToken); } } } } } M(SyntaxKind.SemicolonToken); } N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "ProjectChange"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "projectChange"); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact, WorkItem(19456, "https://github.com/dotnet/roslyn/issues/19456")] public void TestGenericArgWithGreaterThan() { UsingTree(@" class C { void M() { var added = ImmutableDictionary<T<S>> ProjectChange = projectChange; } } "); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "M"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.LocalDeclarationStatement); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "added"); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.LessThanExpression); { N(SyntaxKind.LessThanExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "ImmutableDictionary"); } N(SyntaxKind.LessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } } N(SyntaxKind.LessThanToken); N(SyntaxKind.RightShiftExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "S"); } N(SyntaxKind.GreaterThanGreaterThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "ProjectChange"); } } } N(SyntaxKind.EqualsToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "projectChange"); } } } } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } } }
-1
dotnet/roslyn
55,256
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-30T00:02:02Z
2021-07-30T09:17:54Z
6ce9c0048d37026337701fac035ac0745f6fe49f
88b59775dc6375635957ef229116460f290072aa
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/VisualStudio/Core/Def/Implementation/Options/LanguageSettingsPersisterProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.ComponentModel.Composition; using System.Runtime.InteropServices; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Options; using Microsoft.VisualStudio.TextManager.Interop; using IAsyncServiceProvider = Microsoft.VisualStudio.Shell.IAsyncServiceProvider; using SAsyncServiceProvider = Microsoft.VisualStudio.Shell.Interop.SAsyncServiceProvider; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Options { [Export(typeof(IOptionPersisterProvider))] internal sealed class LanguageSettingsPersisterProvider : IOptionPersisterProvider { private readonly IThreadingContext _threadingContext; private readonly IAsyncServiceProvider _serviceProvider; private readonly IGlobalOptionService _optionService; private LanguageSettingsPersister? _lazyPersister; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public LanguageSettingsPersisterProvider( IThreadingContext threadingContext, [Import(typeof(SAsyncServiceProvider))] IAsyncServiceProvider serviceProvider, IGlobalOptionService optionService) { _threadingContext = threadingContext; _serviceProvider = serviceProvider; _optionService = optionService; } public async ValueTask<IOptionPersister> GetOrCreatePersisterAsync(CancellationToken cancellationToken) { if (_lazyPersister is not null) { return _lazyPersister; } await _threadingContext.JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken); // Asynchronously load dependent package prior to calling synchronous APIs on IVsTextManager4 _ = await _serviceProvider.GetServiceAsync(typeof(SVsManagedFontAndColorInformation)).ConfigureAwait(true); var textManager = (IVsTextManager4?)await _serviceProvider.GetServiceAsync(typeof(SVsTextManager)).ConfigureAwait(true); Assumes.Present(textManager); _lazyPersister ??= new LanguageSettingsPersister(_threadingContext, textManager, _optionService); return _lazyPersister; } /// <summary> /// Shim to allow asynchronous loading of a package prior to calling synchronous (blocking) APIs that use it. /// </summary> [Guid("48d069e8-1993-4752-baf3-232236a3ea4f")] private class SVsManagedFontAndColorInformation { } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.ComponentModel.Composition; using System.Runtime.InteropServices; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Options; using Microsoft.VisualStudio.TextManager.Interop; using IAsyncServiceProvider = Microsoft.VisualStudio.Shell.IAsyncServiceProvider; using SAsyncServiceProvider = Microsoft.VisualStudio.Shell.Interop.SAsyncServiceProvider; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Options { [Export(typeof(IOptionPersisterProvider))] internal sealed class LanguageSettingsPersisterProvider : IOptionPersisterProvider { private readonly IThreadingContext _threadingContext; private readonly IAsyncServiceProvider _serviceProvider; private readonly IGlobalOptionService _optionService; private LanguageSettingsPersister? _lazyPersister; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public LanguageSettingsPersisterProvider( IThreadingContext threadingContext, [Import(typeof(SAsyncServiceProvider))] IAsyncServiceProvider serviceProvider, IGlobalOptionService optionService) { _threadingContext = threadingContext; _serviceProvider = serviceProvider; _optionService = optionService; } public async ValueTask<IOptionPersister> GetOrCreatePersisterAsync(CancellationToken cancellationToken) { if (_lazyPersister is not null) { return _lazyPersister; } await _threadingContext.JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken); // Asynchronously load dependent package prior to calling synchronous APIs on IVsTextManager4 _ = await _serviceProvider.GetServiceAsync(typeof(SVsManagedFontAndColorInformation)).ConfigureAwait(true); var textManager = (IVsTextManager4?)await _serviceProvider.GetServiceAsync(typeof(SVsTextManager)).ConfigureAwait(true); Assumes.Present(textManager); _lazyPersister ??= new LanguageSettingsPersister(_threadingContext, textManager, _optionService); return _lazyPersister; } /// <summary> /// Shim to allow asynchronous loading of a package prior to calling synchronous (blocking) APIs that use it. /// </summary> [Guid("48d069e8-1993-4752-baf3-232236a3ea4f")] private class SVsManagedFontAndColorInformation { } } }
-1
dotnet/roslyn
55,256
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-30T00:02:02Z
2021-07-30T09:17:54Z
6ce9c0048d37026337701fac035ac0745f6fe49f
88b59775dc6375635957ef229116460f290072aa
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/VisualStudio/Xaml/Impl/Implementation/LanguageServer/XamlRequestDispatcherFactory.cs
// Licensed to the .NET Foundation under one or more agreements. // 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.Composition; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Editor.Xaml; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.LanguageServer; using Microsoft.CodeAnalysis.LanguageServer.Handler; using Microsoft.VisualStudio.LanguageServer.Protocol; using Microsoft.VisualStudio.LanguageServices.Xaml.Telemetry; namespace Microsoft.VisualStudio.LanguageServices.Xaml.LanguageServer { /// <summary> /// Implements the Language Server Protocol for XAML /// </summary> [Export(typeof(XamlRequestDispatcherFactory)), Shared] internal sealed class XamlRequestDispatcherFactory : AbstractRequestDispatcherFactory { private readonly XamlProjectService _projectService; private readonly IXamlLanguageServerFeedbackService? _feedbackService; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public XamlRequestDispatcherFactory( [ImportMany] IEnumerable<Lazy<AbstractRequestHandlerProvider, RequestHandlerProviderMetadataView>> requestHandlerProviders, XamlProjectService projectService, [Import(AllowDefault = true)] IXamlLanguageServerFeedbackService? feedbackService) : base(requestHandlerProviders, languageName: StringConstants.XamlLanguageName) { _projectService = projectService; _feedbackService = feedbackService; } public override RequestDispatcher CreateRequestDispatcher() { return new XamlRequestDispatcher(_projectService, _requestHandlerProviders, _feedbackService, _languageName); } private class XamlRequestDispatcher : RequestDispatcher { private readonly XamlProjectService _projectService; private readonly IXamlLanguageServerFeedbackService? _feedbackService; public XamlRequestDispatcher( XamlProjectService projectService, ImmutableArray<Lazy<AbstractRequestHandlerProvider, RequestHandlerProviderMetadataView>> requestHandlerProviders, IXamlLanguageServerFeedbackService? feedbackService, string? languageName = null) : base(requestHandlerProviders, languageName) { _projectService = projectService; _feedbackService = feedbackService; } protected override async Task<ResponseType> ExecuteRequestAsync<RequestType, ResponseType>(RequestExecutionQueue queue, RequestType request, ClientCapabilities clientCapabilities, string? clientName, string methodName, bool mutatesSolutionState, bool requiresLSPSolution, IRequestHandler<RequestType, ResponseType> handler, CancellationToken cancellationToken) { var textDocument = handler.GetTextDocumentIdentifier(request); DocumentId? documentId = null; if (textDocument is { Uri: { IsAbsoluteUri: true } documentUri }) { documentId = _projectService.TrackOpenDocument(documentUri.LocalPath); } using (var requestScope = _feedbackService?.CreateRequestScope(documentId, methodName)) { try { return await base.ExecuteRequestAsync(queue, request, clientCapabilities, clientName, methodName, mutatesSolutionState, requiresLSPSolution, handler, cancellationToken).ConfigureAwait(false); } catch (Exception e) when (e is not OperationCanceledException) { // Inform Xaml language service that the RequestScope failed. // This doesn't send the exception to Telemetry or Watson requestScope?.RecordFailure(e); throw; } } } } } }
// Licensed to the .NET Foundation under one or more agreements. // 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.Composition; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Editor.Xaml; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.LanguageServer; using Microsoft.CodeAnalysis.LanguageServer.Handler; using Microsoft.VisualStudio.LanguageServer.Protocol; using Microsoft.VisualStudio.LanguageServices.Xaml.Telemetry; namespace Microsoft.VisualStudio.LanguageServices.Xaml.LanguageServer { /// <summary> /// Implements the Language Server Protocol for XAML /// </summary> [Export(typeof(XamlRequestDispatcherFactory)), Shared] internal sealed class XamlRequestDispatcherFactory : AbstractRequestDispatcherFactory { private readonly XamlProjectService _projectService; private readonly IXamlLanguageServerFeedbackService? _feedbackService; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public XamlRequestDispatcherFactory( [ImportMany] IEnumerable<Lazy<AbstractRequestHandlerProvider, RequestHandlerProviderMetadataView>> requestHandlerProviders, XamlProjectService projectService, [Import(AllowDefault = true)] IXamlLanguageServerFeedbackService? feedbackService) : base(requestHandlerProviders, languageName: StringConstants.XamlLanguageName) { _projectService = projectService; _feedbackService = feedbackService; } public override RequestDispatcher CreateRequestDispatcher() { return new XamlRequestDispatcher(_projectService, _requestHandlerProviders, _feedbackService, _languageName); } private class XamlRequestDispatcher : RequestDispatcher { private readonly XamlProjectService _projectService; private readonly IXamlLanguageServerFeedbackService? _feedbackService; public XamlRequestDispatcher( XamlProjectService projectService, ImmutableArray<Lazy<AbstractRequestHandlerProvider, RequestHandlerProviderMetadataView>> requestHandlerProviders, IXamlLanguageServerFeedbackService? feedbackService, string? languageName = null) : base(requestHandlerProviders, languageName) { _projectService = projectService; _feedbackService = feedbackService; } protected override async Task<ResponseType> ExecuteRequestAsync<RequestType, ResponseType>(RequestExecutionQueue queue, RequestType request, ClientCapabilities clientCapabilities, string? clientName, string methodName, bool mutatesSolutionState, bool requiresLSPSolution, IRequestHandler<RequestType, ResponseType> handler, CancellationToken cancellationToken) { var textDocument = handler.GetTextDocumentIdentifier(request); DocumentId? documentId = null; if (textDocument is { Uri: { IsAbsoluteUri: true } documentUri }) { documentId = _projectService.TrackOpenDocument(documentUri.LocalPath); } using (var requestScope = _feedbackService?.CreateRequestScope(documentId, methodName)) { try { return await base.ExecuteRequestAsync(queue, request, clientCapabilities, clientName, methodName, mutatesSolutionState, requiresLSPSolution, handler, cancellationToken).ConfigureAwait(false); } catch (Exception e) when (e is not OperationCanceledException) { // Inform Xaml language service that the RequestScope failed. // This doesn't send the exception to Telemetry or Watson requestScope?.RecordFailure(e); throw; } } } } } }
-1
dotnet/roslyn
55,256
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-30T00:02:02Z
2021-07-30T09:17:54Z
6ce9c0048d37026337701fac035ac0745f6fe49f
88b59775dc6375635957ef229116460f290072aa
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/VisualStudio/Core/Impl/SolutionExplorer/AnalyzersCommandHandler.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.ComponentModel.Composition; using System.ComponentModel.Design; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Linq; using EnvDTE; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.Editor; using Microsoft.CodeAnalysis.Editor.Host; using Microsoft.CodeAnalysis.Editor.Implementation; using Microsoft.CodeAnalysis.Notification; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.Internal.VisualStudio.PlatformUI; using Microsoft.VisualStudio.CodeAnalysis; using Microsoft.VisualStudio.ComponentModelHost; using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem; using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; using Microsoft.VisualStudio.Utilities; using Roslyn.Utilities; using VSLangProj140; using Workspace = Microsoft.CodeAnalysis.Workspace; namespace Microsoft.VisualStudio.LanguageServices.Implementation.SolutionExplorer { [Export] internal class AnalyzersCommandHandler : IAnalyzersCommandHandler, IVsUpdateSolutionEvents { private readonly AnalyzerItemsTracker _tracker; private readonly AnalyzerReferenceManager _analyzerReferenceManager; private readonly IServiceProvider _serviceProvider; private ContextMenuController _analyzerFolderContextMenuController; private ContextMenuController _analyzerContextMenuController; private ContextMenuController _diagnosticContextMenuController; // Analyzers folder context menu items private MenuCommand _addMenuItem; // Analyzer context menu items private MenuCommand _removeMenuItem; // Diagnostic context menu items private MenuCommand _setSeverityDefaultMenuItem; private MenuCommand _setSeverityErrorMenuItem; private MenuCommand _setSeverityWarningMenuItem; private MenuCommand _setSeverityInfoMenuItem; private MenuCommand _setSeverityHiddenMenuItem; private MenuCommand _setSeverityNoneMenuItem; private MenuCommand _openHelpLinkMenuItem; // Other menu items private MenuCommand _projectAddMenuItem; private MenuCommand _projectContextAddMenuItem; private MenuCommand _referencesContextAddMenuItem; private MenuCommand _setActiveRuleSetMenuItem; private Workspace _workspace; private bool _allowProjectSystemOperations = true; private bool _initialized; [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] public AnalyzersCommandHandler( AnalyzerItemsTracker tracker, AnalyzerReferenceManager analyzerReferenceManager, [Import(typeof(SVsServiceProvider))] IServiceProvider serviceProvider) { _tracker = tracker; _analyzerReferenceManager = analyzerReferenceManager; _serviceProvider = serviceProvider; } /// <summary> /// Hook up the context menu handlers. /// </summary> public void Initialize(IMenuCommandService menuCommandService) { if (menuCommandService != null) { // Analyzers folder context menu items _addMenuItem = AddCommandHandler(menuCommandService, ID.RoslynCommands.AddAnalyzer, AddAnalyzerHandler); _ = AddCommandHandler(menuCommandService, ID.RoslynCommands.OpenRuleSet, OpenRuleSetHandler); // Analyzer context menu items _removeMenuItem = AddCommandHandler(menuCommandService, ID.RoslynCommands.RemoveAnalyzer, RemoveAnalyzerHandler); // Diagnostic context menu items _setSeverityDefaultMenuItem = AddCommandHandler(menuCommandService, ID.RoslynCommands.SetSeverityDefault, SetSeverityHandler); _setSeverityErrorMenuItem = AddCommandHandler(menuCommandService, ID.RoslynCommands.SetSeverityError, SetSeverityHandler); _setSeverityWarningMenuItem = AddCommandHandler(menuCommandService, ID.RoslynCommands.SetSeverityWarning, SetSeverityHandler); _setSeverityInfoMenuItem = AddCommandHandler(menuCommandService, ID.RoslynCommands.SetSeverityInfo, SetSeverityHandler); _setSeverityHiddenMenuItem = AddCommandHandler(menuCommandService, ID.RoslynCommands.SetSeverityHidden, SetSeverityHandler); _setSeverityNoneMenuItem = AddCommandHandler(menuCommandService, ID.RoslynCommands.SetSeverityNone, SetSeverityHandler); _openHelpLinkMenuItem = AddCommandHandler(menuCommandService, ID.RoslynCommands.OpenDiagnosticHelpLink, OpenDiagnosticHelpLinkHandler); // Other menu items _projectAddMenuItem = AddCommandHandler(menuCommandService, ID.RoslynCommands.ProjectAddAnalyzer, AddAnalyzerHandler); _projectContextAddMenuItem = AddCommandHandler(menuCommandService, ID.RoslynCommands.ProjectContextAddAnalyzer, AddAnalyzerHandler); _referencesContextAddMenuItem = AddCommandHandler(menuCommandService, ID.RoslynCommands.ReferencesContextAddAnalyzer, AddAnalyzerHandler); _setActiveRuleSetMenuItem = AddCommandHandler(menuCommandService, ID.RoslynCommands.SetActiveRuleSet, SetActiveRuleSetHandler); UpdateOtherMenuItemsVisibility(); if (_tracker != null) { _tracker.SelectedHierarchyItemChanged += SelectedHierarchyItemChangedHandler; } var buildManager = (IVsSolutionBuildManager)_serviceProvider.GetService(typeof(SVsSolutionBuildManager)); buildManager.AdviseUpdateSolutionEvents(this, out var cookie); _initialized = true; } } public IContextMenuController AnalyzerFolderContextMenuController { get { if (_analyzerFolderContextMenuController == null) { _analyzerFolderContextMenuController = new ContextMenuController( ID.RoslynCommands.AnalyzerFolderContextMenu, ShouldShowAnalyzerFolderContextMenu, UpdateAnalyzerFolderContextMenu); } return _analyzerFolderContextMenuController; } } private bool ShouldShowAnalyzerFolderContextMenu(IEnumerable<object> items) { return items.Count() == 1; } private void UpdateAnalyzerFolderContextMenu() { if (_addMenuItem != null) { _addMenuItem.Visible = SelectedProjectSupportsAnalyzers(); _addMenuItem.Enabled = _allowProjectSystemOperations; } } public IContextMenuController AnalyzerContextMenuController { get { if (_analyzerContextMenuController == null) { _analyzerContextMenuController = new ContextMenuController( ID.RoslynCommands.AnalyzerContextMenu, ShouldShowAnalyzerContextMenu, UpdateAnalyzerContextMenu); } return _analyzerContextMenuController; } } private bool ShouldShowAnalyzerContextMenu(IEnumerable<object> items) { return items.All(item => item is AnalyzerItem); } private void UpdateAnalyzerContextMenu() { if (_removeMenuItem != null) { _removeMenuItem.Enabled = _allowProjectSystemOperations; } } public IContextMenuController DiagnosticContextMenuController { get { if (_diagnosticContextMenuController == null) { _diagnosticContextMenuController = new ContextMenuController( ID.RoslynCommands.DiagnosticContextMenu, ShouldShowDiagnosticContextMenu, UpdateDiagnosticContextMenu); } return _diagnosticContextMenuController; } } private bool ShouldShowDiagnosticContextMenu(IEnumerable<object> items) { return _initialized && items.All(item => item is DiagnosticItem); } private void UpdateDiagnosticContextMenu() { Debug.Assert(_initialized); UpdateSeverityMenuItemsChecked(); UpdateSeverityMenuItemsEnabled(); UpdateOpenHelpLinkMenuItemVisibility(); } private MenuCommand AddCommandHandler(IMenuCommandService menuCommandService, int roslynCommand, EventHandler handler) { var commandID = new CommandID(Guids.RoslynGroupId, roslynCommand); var menuCommand = new MenuCommand(handler, commandID); menuCommandService.AddCommand(menuCommand); return menuCommand; } private void SelectedHierarchyItemChangedHandler(object sender, EventArgs e) { UpdateOtherMenuItemsVisibility(); } private void UpdateOtherMenuItemsVisibility() { var selectedProjectSupportsAnalyzers = SelectedProjectSupportsAnalyzers(); _projectAddMenuItem.Visible = selectedProjectSupportsAnalyzers; _projectContextAddMenuItem.Visible = selectedProjectSupportsAnalyzers && _tracker.SelectedItemId == VSConstants.VSITEMID_ROOT; _referencesContextAddMenuItem.Visible = selectedProjectSupportsAnalyzers; _setActiveRuleSetMenuItem.Visible = selectedProjectSupportsAnalyzers && _tracker.SelectedHierarchy.TryGetItemName(_tracker.SelectedItemId, out var itemName) && Path.GetExtension(itemName).Equals(".ruleset", StringComparison.OrdinalIgnoreCase); } private void UpdateOtherMenuItemsEnabled() { _projectAddMenuItem.Enabled = _allowProjectSystemOperations; _projectContextAddMenuItem.Enabled = _allowProjectSystemOperations; _referencesContextAddMenuItem.Enabled = _allowProjectSystemOperations; _removeMenuItem.Enabled = _allowProjectSystemOperations; } private void UpdateOpenHelpLinkMenuItemVisibility() { _openHelpLinkMenuItem.Visible = _tracker.SelectedDiagnosticItems.Length == 1 && _tracker.SelectedDiagnosticItems[0].GetHelpLink() != null; } private void UpdateSeverityMenuItemsChecked() { _setSeverityDefaultMenuItem.Checked = false; _setSeverityErrorMenuItem.Checked = false; _setSeverityWarningMenuItem.Checked = false; _setSeverityInfoMenuItem.Checked = false; _setSeverityHiddenMenuItem.Checked = false; _setSeverityNoneMenuItem.Checked = false; var workspace = TryGetWorkspace() as VisualStudioWorkspace; if (workspace == null) { return; } var selectedItemSeverities = new HashSet<ReportDiagnostic>(); var groups = _tracker.SelectedDiagnosticItems.GroupBy(item => item.ProjectId); foreach (var group in groups) { var project = workspace.CurrentSolution.GetProject(group.Key); if (project == null) { continue; } var analyzerConfigOptions = project.GetAnalyzerConfigOptions(); foreach (var diagnosticItem in group) { var severity = diagnosticItem.Descriptor.GetEffectiveSeverity(project.CompilationOptions, analyzerConfigOptions); selectedItemSeverities.Add(severity); } } if (selectedItemSeverities.Count != 1) { return; } switch (selectedItemSeverities.Single()) { case ReportDiagnostic.Default: _setSeverityDefaultMenuItem.Checked = true; break; case ReportDiagnostic.Error: _setSeverityErrorMenuItem.Checked = true; break; case ReportDiagnostic.Warn: _setSeverityWarningMenuItem.Checked = true; break; case ReportDiagnostic.Info: _setSeverityInfoMenuItem.Checked = true; break; case ReportDiagnostic.Hidden: _setSeverityHiddenMenuItem.Checked = true; break; case ReportDiagnostic.Suppress: _setSeverityNoneMenuItem.Checked = true; break; default: break; } } private void UpdateSeverityMenuItemsEnabled() { var configurable = !_tracker.SelectedDiagnosticItems.Any(item => item.Descriptor.CustomTags.Contains(WellKnownDiagnosticTags.NotConfigurable)); _setSeverityDefaultMenuItem.Enabled = configurable; _setSeverityErrorMenuItem.Enabled = configurable; _setSeverityWarningMenuItem.Enabled = configurable; _setSeverityInfoMenuItem.Enabled = configurable; _setSeverityHiddenMenuItem.Enabled = configurable; _setSeverityNoneMenuItem.Enabled = configurable; } private bool SelectedProjectSupportsAnalyzers() { return _tracker != null && _tracker.SelectedHierarchy != null && _tracker.SelectedHierarchy.TryGetProject(out var project) && project.Object is VSProject3; } /// <summary> /// Handler for "Add Analyzer..." context menu on Analyzers folder node. /// </summary> internal void AddAnalyzerHandler(object sender, EventArgs args) { if (_analyzerReferenceManager != null) { _analyzerReferenceManager.ShowDialog(); } } /// <summary> /// Handler for "Remove" context menu on individual Analyzer items. /// </summary> /// <param name="sender"></param> /// <param name="args"></param> internal void RemoveAnalyzerHandler(object sender, EventArgs args) { foreach (var item in _tracker.SelectedAnalyzerItems) { item.Remove(); } } internal void OpenRuleSetHandler(object sender, EventArgs args) { if (_tracker.SelectedFolder != null && _serviceProvider != null) { var workspace = _tracker.SelectedFolder.Workspace as VisualStudioWorkspace; var projectId = _tracker.SelectedFolder.ProjectId; if (workspace != null) { var ruleSetFile = workspace.TryGetRuleSetPathForProject(projectId); if (ruleSetFile == null) { SendUnableToOpenRuleSetNotification(workspace, SolutionExplorerShim.No_rule_set_file_is_specified_or_the_file_does_not_exist); return; } try { var dte = (EnvDTE.DTE)_serviceProvider.GetService(typeof(EnvDTE.DTE)); dte.ItemOperations.OpenFile(ruleSetFile); } catch (Exception e) { SendUnableToOpenRuleSetNotification(workspace, e.Message); } } } } private void SetSeverityHandler(object sender, EventArgs args) { var selectedItem = (MenuCommand)sender; var selectedAction = MapSelectedItemToReportDiagnostic(selectedItem); if (!selectedAction.HasValue) { return; } var workspace = TryGetWorkspace() as VisualStudioWorkspaceImpl; if (workspace == null) { return; } foreach (var selectedDiagnostic in _tracker.SelectedDiagnosticItems) { var projectId = selectedDiagnostic.ProjectId; var pathToRuleSet = workspace.TryGetRuleSetPathForProject(projectId); var project = workspace.CurrentSolution.GetProject(projectId); var pathToAnalyzerConfigDoc = project?.TryGetAnalyzerConfigPathForProjectConfiguration(); if (pathToRuleSet == null && pathToAnalyzerConfigDoc == null) { SendUnableToUpdateRuleSetNotification(workspace, SolutionExplorerShim.No_rule_set_file_is_specified_or_the_file_does_not_exist); continue; } var componentModel = (IComponentModel)_serviceProvider.GetService(typeof(SComponentModel)); var uiThreadOperationExecutor = componentModel.GetService<IUIThreadOperationExecutor>(); var editHandlerService = componentModel.GetService<ICodeActionEditHandlerService>(); try { var envDteProject = workspace.TryGetDTEProject(projectId); if (pathToRuleSet == null || SdkUiUtilities.IsBuiltInRuleSet(pathToRuleSet, _serviceProvider)) { // If project is using the default built-in ruleset or no ruleset, then prefer .editorconfig for severity configuration. if (pathToAnalyzerConfigDoc != null) { uiThreadOperationExecutor.Execute( title: ServicesVSResources.Updating_severity, defaultDescription: "", allowCancellation: true, showProgress: true, action: context => { var scope = context.AddScope(allowCancellation: true, ServicesVSResources.Updating_severity); var newSolution = selectedDiagnostic.GetSolutionWithUpdatedAnalyzerConfigSeverityAsync(selectedAction.Value, project, context.UserCancellationToken).WaitAndGetResult(context.UserCancellationToken); var operations = ImmutableArray.Create<CodeActionOperation>(new ApplyChangesOperation(newSolution)); editHandlerService.Apply( _workspace, fromDocument: null, operations: operations, title: ServicesVSResources.Updating_severity, progressTracker: new UIThreadOperationContextProgressTracker(scope), cancellationToken: context.UserCancellationToken); }); continue; } // Otherwise, fall back to using ruleset. if (pathToRuleSet == null) { SendUnableToUpdateRuleSetNotification(workspace, SolutionExplorerShim.No_rule_set_file_is_specified_or_the_file_does_not_exist); continue; } pathToRuleSet = CreateCopyOfRuleSetForProject(pathToRuleSet, envDteProject); if (pathToRuleSet == null) { SendUnableToUpdateRuleSetNotification(workspace, string.Format(SolutionExplorerShim.Could_not_create_a_rule_set_for_project_0, envDteProject.Name)); continue; } var fileInfo = new FileInfo(pathToRuleSet); fileInfo.IsReadOnly = false; } uiThreadOperationExecutor.Execute( title: SolutionExplorerShim.Rule_Set, defaultDescription: string.Format(SolutionExplorerShim.Checking_out_0_for_editing, Path.GetFileName(pathToRuleSet)), allowCancellation: false, showProgress: false, action: c => { if (envDteProject.DTE.SourceControl.IsItemUnderSCC(pathToRuleSet)) { envDteProject.DTE.SourceControl.CheckOutItem(pathToRuleSet); } }); selectedDiagnostic.SetRuleSetSeverity(selectedAction.Value, pathToRuleSet); } catch (Exception e) { SendUnableToUpdateRuleSetNotification(workspace, e.Message); } } } private void OpenDiagnosticHelpLinkHandler(object sender, EventArgs e) { if (_tracker.SelectedDiagnosticItems.Length != 1) { return; } var uri = _tracker.SelectedDiagnosticItems[0].GetHelpLink(); if (uri != null) { VisualStudioNavigateToLinkService.StartBrowser(uri); } } private void SetActiveRuleSetHandler(object sender, EventArgs e) { if (_tracker.SelectedHierarchy.TryGetProject(out var project) && _tracker.SelectedHierarchy.TryGetCanonicalName(_tracker.SelectedItemId, out var ruleSetFileFullPath)) { var projectDirectoryFullPath = Path.GetDirectoryName(project.FullName); var ruleSetFileRelativePath = PathUtilities.GetRelativePath(projectDirectoryFullPath, ruleSetFileFullPath); UpdateProjectConfigurationsToUseRuleSetFile(project, ruleSetFileRelativePath); } } private string CreateCopyOfRuleSetForProject(string pathToRuleSet, EnvDTE.Project envDteProject) { var fileName = GetNewRuleSetFileNameForProject(envDteProject); var projectDirectory = Path.GetDirectoryName(envDteProject.FullName); var fullFilePath = Path.Combine(projectDirectory, fileName); File.Copy(pathToRuleSet, fullFilePath); UpdateProjectConfigurationsToUseRuleSetFile(envDteProject, fileName); envDteProject.ProjectItems.AddFromFile(fullFilePath); return fullFilePath; } private void UpdateProjectConfigurationsToUseRuleSetFile(EnvDTE.Project envDteProject, string fileName) { foreach (EnvDTE.Configuration config in envDteProject.ConfigurationManager) { var properties = config.Properties; try { var codeAnalysisRuleSetFileProperty = properties?.Item("CodeAnalysisRuleSet"); if (codeAnalysisRuleSetFileProperty != null) { codeAnalysisRuleSetFileProperty.Value = fileName; } } catch (ArgumentException) { // Unfortunately the properties collection sometimes throws an ArgumentException // instead of returning null if the current configuration doesn't support CodeAnalysisRuleSet. // Ignore it and move on. } } } private string GetNewRuleSetFileNameForProject(EnvDTE.Project envDteProject) { var projectName = envDteProject.Name; var projectItemNames = new HashSet<string>(StringComparer.OrdinalIgnoreCase); foreach (ProjectItem item in envDteProject.ProjectItems) { projectItemNames.Add(item.Name); } var ruleSetName = projectName + ".ruleset"; if (!projectItemNames.Contains(ruleSetName)) { return ruleSetName; } for (var i = 1; i < int.MaxValue; i++) { ruleSetName = projectName + i + ".ruleset"; if (!projectItemNames.Contains(ruleSetName)) { return ruleSetName; } } return null; } private static ReportDiagnostic? MapSelectedItemToReportDiagnostic(MenuCommand selectedItem) { ReportDiagnostic? selectedAction = null; if (selectedItem.CommandID.Guid == Guids.RoslynGroupId) { switch (selectedItem.CommandID.ID) { case ID.RoslynCommands.SetSeverityDefault: selectedAction = ReportDiagnostic.Default; break; case ID.RoslynCommands.SetSeverityError: selectedAction = ReportDiagnostic.Error; break; case ID.RoslynCommands.SetSeverityWarning: selectedAction = ReportDiagnostic.Warn; break; case ID.RoslynCommands.SetSeverityInfo: selectedAction = ReportDiagnostic.Info; break; case ID.RoslynCommands.SetSeverityHidden: selectedAction = ReportDiagnostic.Hidden; break; case ID.RoslynCommands.SetSeverityNone: selectedAction = ReportDiagnostic.Suppress; break; default: selectedAction = null; break; } } return selectedAction; } private void SendUnableToOpenRuleSetNotification(Workspace workspace, string message) { SendErrorNotification( workspace, SolutionExplorerShim.The_rule_set_file_could_not_be_opened, message); } private void SendUnableToUpdateRuleSetNotification(Workspace workspace, string message) { SendErrorNotification( workspace, SolutionExplorerShim.The_rule_set_file_could_not_be_updated, message); } private void SendErrorNotification(Workspace workspace, string message1, string message2) { var notificationService = workspace.Services.GetService<INotificationService>(); notificationService.SendNotification(message1 + Environment.NewLine + Environment.NewLine + message2, severity: NotificationSeverity.Error); } int IVsUpdateSolutionEvents.UpdateSolution_Begin(ref int pfCancelUpdate) { _allowProjectSystemOperations = false; UpdateOtherMenuItemsEnabled(); return VSConstants.S_OK; } int IVsUpdateSolutionEvents.UpdateSolution_Done(int fSucceeded, int fModified, int fCancelCommand) { _allowProjectSystemOperations = true; UpdateOtherMenuItemsEnabled(); return VSConstants.S_OK; } int IVsUpdateSolutionEvents.UpdateSolution_StartUpdate(ref int pfCancelUpdate) { return VSConstants.S_OK; } int IVsUpdateSolutionEvents.UpdateSolution_Cancel() { _allowProjectSystemOperations = true; UpdateOtherMenuItemsEnabled(); return VSConstants.S_OK; } int IVsUpdateSolutionEvents.OnActiveProjectCfgChange(IVsHierarchy pIVsHierarchy) { return VSConstants.S_OK; } private Workspace TryGetWorkspace() { if (_workspace == null) { var componentModel = (IComponentModel)_serviceProvider.GetService(typeof(SComponentModel)); _workspace = componentModel.DefaultExportProvider.GetExportedValueOrDefault<VisualStudioWorkspace>(); } return _workspace; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.ComponentModel.Composition; using System.ComponentModel.Design; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Linq; using EnvDTE; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.Editor; using Microsoft.CodeAnalysis.Editor.Host; using Microsoft.CodeAnalysis.Editor.Implementation; using Microsoft.CodeAnalysis.Notification; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.Internal.VisualStudio.PlatformUI; using Microsoft.VisualStudio.CodeAnalysis; using Microsoft.VisualStudio.ComponentModelHost; using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem; using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; using Microsoft.VisualStudio.Utilities; using Roslyn.Utilities; using VSLangProj140; using Workspace = Microsoft.CodeAnalysis.Workspace; namespace Microsoft.VisualStudio.LanguageServices.Implementation.SolutionExplorer { [Export] internal class AnalyzersCommandHandler : IAnalyzersCommandHandler, IVsUpdateSolutionEvents { private readonly AnalyzerItemsTracker _tracker; private readonly AnalyzerReferenceManager _analyzerReferenceManager; private readonly IServiceProvider _serviceProvider; private ContextMenuController _analyzerFolderContextMenuController; private ContextMenuController _analyzerContextMenuController; private ContextMenuController _diagnosticContextMenuController; // Analyzers folder context menu items private MenuCommand _addMenuItem; // Analyzer context menu items private MenuCommand _removeMenuItem; // Diagnostic context menu items private MenuCommand _setSeverityDefaultMenuItem; private MenuCommand _setSeverityErrorMenuItem; private MenuCommand _setSeverityWarningMenuItem; private MenuCommand _setSeverityInfoMenuItem; private MenuCommand _setSeverityHiddenMenuItem; private MenuCommand _setSeverityNoneMenuItem; private MenuCommand _openHelpLinkMenuItem; // Other menu items private MenuCommand _projectAddMenuItem; private MenuCommand _projectContextAddMenuItem; private MenuCommand _referencesContextAddMenuItem; private MenuCommand _setActiveRuleSetMenuItem; private Workspace _workspace; private bool _allowProjectSystemOperations = true; private bool _initialized; [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] public AnalyzersCommandHandler( AnalyzerItemsTracker tracker, AnalyzerReferenceManager analyzerReferenceManager, [Import(typeof(SVsServiceProvider))] IServiceProvider serviceProvider) { _tracker = tracker; _analyzerReferenceManager = analyzerReferenceManager; _serviceProvider = serviceProvider; } /// <summary> /// Hook up the context menu handlers. /// </summary> public void Initialize(IMenuCommandService menuCommandService) { if (menuCommandService != null) { // Analyzers folder context menu items _addMenuItem = AddCommandHandler(menuCommandService, ID.RoslynCommands.AddAnalyzer, AddAnalyzerHandler); _ = AddCommandHandler(menuCommandService, ID.RoslynCommands.OpenRuleSet, OpenRuleSetHandler); // Analyzer context menu items _removeMenuItem = AddCommandHandler(menuCommandService, ID.RoslynCommands.RemoveAnalyzer, RemoveAnalyzerHandler); // Diagnostic context menu items _setSeverityDefaultMenuItem = AddCommandHandler(menuCommandService, ID.RoslynCommands.SetSeverityDefault, SetSeverityHandler); _setSeverityErrorMenuItem = AddCommandHandler(menuCommandService, ID.RoslynCommands.SetSeverityError, SetSeverityHandler); _setSeverityWarningMenuItem = AddCommandHandler(menuCommandService, ID.RoslynCommands.SetSeverityWarning, SetSeverityHandler); _setSeverityInfoMenuItem = AddCommandHandler(menuCommandService, ID.RoslynCommands.SetSeverityInfo, SetSeverityHandler); _setSeverityHiddenMenuItem = AddCommandHandler(menuCommandService, ID.RoslynCommands.SetSeverityHidden, SetSeverityHandler); _setSeverityNoneMenuItem = AddCommandHandler(menuCommandService, ID.RoslynCommands.SetSeverityNone, SetSeverityHandler); _openHelpLinkMenuItem = AddCommandHandler(menuCommandService, ID.RoslynCommands.OpenDiagnosticHelpLink, OpenDiagnosticHelpLinkHandler); // Other menu items _projectAddMenuItem = AddCommandHandler(menuCommandService, ID.RoslynCommands.ProjectAddAnalyzer, AddAnalyzerHandler); _projectContextAddMenuItem = AddCommandHandler(menuCommandService, ID.RoslynCommands.ProjectContextAddAnalyzer, AddAnalyzerHandler); _referencesContextAddMenuItem = AddCommandHandler(menuCommandService, ID.RoslynCommands.ReferencesContextAddAnalyzer, AddAnalyzerHandler); _setActiveRuleSetMenuItem = AddCommandHandler(menuCommandService, ID.RoslynCommands.SetActiveRuleSet, SetActiveRuleSetHandler); UpdateOtherMenuItemsVisibility(); if (_tracker != null) { _tracker.SelectedHierarchyItemChanged += SelectedHierarchyItemChangedHandler; } var buildManager = (IVsSolutionBuildManager)_serviceProvider.GetService(typeof(SVsSolutionBuildManager)); buildManager.AdviseUpdateSolutionEvents(this, out var cookie); _initialized = true; } } public IContextMenuController AnalyzerFolderContextMenuController { get { if (_analyzerFolderContextMenuController == null) { _analyzerFolderContextMenuController = new ContextMenuController( ID.RoslynCommands.AnalyzerFolderContextMenu, ShouldShowAnalyzerFolderContextMenu, UpdateAnalyzerFolderContextMenu); } return _analyzerFolderContextMenuController; } } private bool ShouldShowAnalyzerFolderContextMenu(IEnumerable<object> items) { return items.Count() == 1; } private void UpdateAnalyzerFolderContextMenu() { if (_addMenuItem != null) { _addMenuItem.Visible = SelectedProjectSupportsAnalyzers(); _addMenuItem.Enabled = _allowProjectSystemOperations; } } public IContextMenuController AnalyzerContextMenuController { get { if (_analyzerContextMenuController == null) { _analyzerContextMenuController = new ContextMenuController( ID.RoslynCommands.AnalyzerContextMenu, ShouldShowAnalyzerContextMenu, UpdateAnalyzerContextMenu); } return _analyzerContextMenuController; } } private bool ShouldShowAnalyzerContextMenu(IEnumerable<object> items) { return items.All(item => item is AnalyzerItem); } private void UpdateAnalyzerContextMenu() { if (_removeMenuItem != null) { _removeMenuItem.Enabled = _allowProjectSystemOperations; } } public IContextMenuController DiagnosticContextMenuController { get { if (_diagnosticContextMenuController == null) { _diagnosticContextMenuController = new ContextMenuController( ID.RoslynCommands.DiagnosticContextMenu, ShouldShowDiagnosticContextMenu, UpdateDiagnosticContextMenu); } return _diagnosticContextMenuController; } } private bool ShouldShowDiagnosticContextMenu(IEnumerable<object> items) { return _initialized && items.All(item => item is DiagnosticItem); } private void UpdateDiagnosticContextMenu() { Debug.Assert(_initialized); UpdateSeverityMenuItemsChecked(); UpdateSeverityMenuItemsEnabled(); UpdateOpenHelpLinkMenuItemVisibility(); } private MenuCommand AddCommandHandler(IMenuCommandService menuCommandService, int roslynCommand, EventHandler handler) { var commandID = new CommandID(Guids.RoslynGroupId, roslynCommand); var menuCommand = new MenuCommand(handler, commandID); menuCommandService.AddCommand(menuCommand); return menuCommand; } private void SelectedHierarchyItemChangedHandler(object sender, EventArgs e) { UpdateOtherMenuItemsVisibility(); } private void UpdateOtherMenuItemsVisibility() { var selectedProjectSupportsAnalyzers = SelectedProjectSupportsAnalyzers(); _projectAddMenuItem.Visible = selectedProjectSupportsAnalyzers; _projectContextAddMenuItem.Visible = selectedProjectSupportsAnalyzers && _tracker.SelectedItemId == VSConstants.VSITEMID_ROOT; _referencesContextAddMenuItem.Visible = selectedProjectSupportsAnalyzers; _setActiveRuleSetMenuItem.Visible = selectedProjectSupportsAnalyzers && _tracker.SelectedHierarchy.TryGetItemName(_tracker.SelectedItemId, out var itemName) && Path.GetExtension(itemName).Equals(".ruleset", StringComparison.OrdinalIgnoreCase); } private void UpdateOtherMenuItemsEnabled() { _projectAddMenuItem.Enabled = _allowProjectSystemOperations; _projectContextAddMenuItem.Enabled = _allowProjectSystemOperations; _referencesContextAddMenuItem.Enabled = _allowProjectSystemOperations; _removeMenuItem.Enabled = _allowProjectSystemOperations; } private void UpdateOpenHelpLinkMenuItemVisibility() { _openHelpLinkMenuItem.Visible = _tracker.SelectedDiagnosticItems.Length == 1 && _tracker.SelectedDiagnosticItems[0].GetHelpLink() != null; } private void UpdateSeverityMenuItemsChecked() { _setSeverityDefaultMenuItem.Checked = false; _setSeverityErrorMenuItem.Checked = false; _setSeverityWarningMenuItem.Checked = false; _setSeverityInfoMenuItem.Checked = false; _setSeverityHiddenMenuItem.Checked = false; _setSeverityNoneMenuItem.Checked = false; var workspace = TryGetWorkspace() as VisualStudioWorkspace; if (workspace == null) { return; } var selectedItemSeverities = new HashSet<ReportDiagnostic>(); var groups = _tracker.SelectedDiagnosticItems.GroupBy(item => item.ProjectId); foreach (var group in groups) { var project = workspace.CurrentSolution.GetProject(group.Key); if (project == null) { continue; } var analyzerConfigOptions = project.GetAnalyzerConfigOptions(); foreach (var diagnosticItem in group) { var severity = diagnosticItem.Descriptor.GetEffectiveSeverity(project.CompilationOptions, analyzerConfigOptions); selectedItemSeverities.Add(severity); } } if (selectedItemSeverities.Count != 1) { return; } switch (selectedItemSeverities.Single()) { case ReportDiagnostic.Default: _setSeverityDefaultMenuItem.Checked = true; break; case ReportDiagnostic.Error: _setSeverityErrorMenuItem.Checked = true; break; case ReportDiagnostic.Warn: _setSeverityWarningMenuItem.Checked = true; break; case ReportDiagnostic.Info: _setSeverityInfoMenuItem.Checked = true; break; case ReportDiagnostic.Hidden: _setSeverityHiddenMenuItem.Checked = true; break; case ReportDiagnostic.Suppress: _setSeverityNoneMenuItem.Checked = true; break; default: break; } } private void UpdateSeverityMenuItemsEnabled() { var configurable = !_tracker.SelectedDiagnosticItems.Any(item => item.Descriptor.CustomTags.Contains(WellKnownDiagnosticTags.NotConfigurable)); _setSeverityDefaultMenuItem.Enabled = configurable; _setSeverityErrorMenuItem.Enabled = configurable; _setSeverityWarningMenuItem.Enabled = configurable; _setSeverityInfoMenuItem.Enabled = configurable; _setSeverityHiddenMenuItem.Enabled = configurable; _setSeverityNoneMenuItem.Enabled = configurable; } private bool SelectedProjectSupportsAnalyzers() { return _tracker != null && _tracker.SelectedHierarchy != null && _tracker.SelectedHierarchy.TryGetProject(out var project) && project.Object is VSProject3; } /// <summary> /// Handler for "Add Analyzer..." context menu on Analyzers folder node. /// </summary> internal void AddAnalyzerHandler(object sender, EventArgs args) { if (_analyzerReferenceManager != null) { _analyzerReferenceManager.ShowDialog(); } } /// <summary> /// Handler for "Remove" context menu on individual Analyzer items. /// </summary> /// <param name="sender"></param> /// <param name="args"></param> internal void RemoveAnalyzerHandler(object sender, EventArgs args) { foreach (var item in _tracker.SelectedAnalyzerItems) { item.Remove(); } } internal void OpenRuleSetHandler(object sender, EventArgs args) { if (_tracker.SelectedFolder != null && _serviceProvider != null) { var workspace = _tracker.SelectedFolder.Workspace as VisualStudioWorkspace; var projectId = _tracker.SelectedFolder.ProjectId; if (workspace != null) { var ruleSetFile = workspace.TryGetRuleSetPathForProject(projectId); if (ruleSetFile == null) { SendUnableToOpenRuleSetNotification(workspace, SolutionExplorerShim.No_rule_set_file_is_specified_or_the_file_does_not_exist); return; } try { var dte = (EnvDTE.DTE)_serviceProvider.GetService(typeof(EnvDTE.DTE)); dte.ItemOperations.OpenFile(ruleSetFile); } catch (Exception e) { SendUnableToOpenRuleSetNotification(workspace, e.Message); } } } } private void SetSeverityHandler(object sender, EventArgs args) { var selectedItem = (MenuCommand)sender; var selectedAction = MapSelectedItemToReportDiagnostic(selectedItem); if (!selectedAction.HasValue) { return; } var workspace = TryGetWorkspace() as VisualStudioWorkspaceImpl; if (workspace == null) { return; } foreach (var selectedDiagnostic in _tracker.SelectedDiagnosticItems) { var projectId = selectedDiagnostic.ProjectId; var pathToRuleSet = workspace.TryGetRuleSetPathForProject(projectId); var project = workspace.CurrentSolution.GetProject(projectId); var pathToAnalyzerConfigDoc = project?.TryGetAnalyzerConfigPathForProjectConfiguration(); if (pathToRuleSet == null && pathToAnalyzerConfigDoc == null) { SendUnableToUpdateRuleSetNotification(workspace, SolutionExplorerShim.No_rule_set_file_is_specified_or_the_file_does_not_exist); continue; } var componentModel = (IComponentModel)_serviceProvider.GetService(typeof(SComponentModel)); var uiThreadOperationExecutor = componentModel.GetService<IUIThreadOperationExecutor>(); var editHandlerService = componentModel.GetService<ICodeActionEditHandlerService>(); try { var envDteProject = workspace.TryGetDTEProject(projectId); if (pathToRuleSet == null || SdkUiUtilities.IsBuiltInRuleSet(pathToRuleSet, _serviceProvider)) { // If project is using the default built-in ruleset or no ruleset, then prefer .editorconfig for severity configuration. if (pathToAnalyzerConfigDoc != null) { uiThreadOperationExecutor.Execute( title: ServicesVSResources.Updating_severity, defaultDescription: "", allowCancellation: true, showProgress: true, action: context => { var scope = context.AddScope(allowCancellation: true, ServicesVSResources.Updating_severity); var newSolution = selectedDiagnostic.GetSolutionWithUpdatedAnalyzerConfigSeverityAsync(selectedAction.Value, project, context.UserCancellationToken).WaitAndGetResult(context.UserCancellationToken); var operations = ImmutableArray.Create<CodeActionOperation>(new ApplyChangesOperation(newSolution)); editHandlerService.Apply( _workspace, fromDocument: null, operations: operations, title: ServicesVSResources.Updating_severity, progressTracker: new UIThreadOperationContextProgressTracker(scope), cancellationToken: context.UserCancellationToken); }); continue; } // Otherwise, fall back to using ruleset. if (pathToRuleSet == null) { SendUnableToUpdateRuleSetNotification(workspace, SolutionExplorerShim.No_rule_set_file_is_specified_or_the_file_does_not_exist); continue; } pathToRuleSet = CreateCopyOfRuleSetForProject(pathToRuleSet, envDteProject); if (pathToRuleSet == null) { SendUnableToUpdateRuleSetNotification(workspace, string.Format(SolutionExplorerShim.Could_not_create_a_rule_set_for_project_0, envDteProject.Name)); continue; } var fileInfo = new FileInfo(pathToRuleSet); fileInfo.IsReadOnly = false; } uiThreadOperationExecutor.Execute( title: SolutionExplorerShim.Rule_Set, defaultDescription: string.Format(SolutionExplorerShim.Checking_out_0_for_editing, Path.GetFileName(pathToRuleSet)), allowCancellation: false, showProgress: false, action: c => { if (envDteProject.DTE.SourceControl.IsItemUnderSCC(pathToRuleSet)) { envDteProject.DTE.SourceControl.CheckOutItem(pathToRuleSet); } }); selectedDiagnostic.SetRuleSetSeverity(selectedAction.Value, pathToRuleSet); } catch (Exception e) { SendUnableToUpdateRuleSetNotification(workspace, e.Message); } } } private void OpenDiagnosticHelpLinkHandler(object sender, EventArgs e) { if (_tracker.SelectedDiagnosticItems.Length != 1) { return; } var uri = _tracker.SelectedDiagnosticItems[0].GetHelpLink(); if (uri != null) { VisualStudioNavigateToLinkService.StartBrowser(uri); } } private void SetActiveRuleSetHandler(object sender, EventArgs e) { if (_tracker.SelectedHierarchy.TryGetProject(out var project) && _tracker.SelectedHierarchy.TryGetCanonicalName(_tracker.SelectedItemId, out var ruleSetFileFullPath)) { var projectDirectoryFullPath = Path.GetDirectoryName(project.FullName); var ruleSetFileRelativePath = PathUtilities.GetRelativePath(projectDirectoryFullPath, ruleSetFileFullPath); UpdateProjectConfigurationsToUseRuleSetFile(project, ruleSetFileRelativePath); } } private string CreateCopyOfRuleSetForProject(string pathToRuleSet, EnvDTE.Project envDteProject) { var fileName = GetNewRuleSetFileNameForProject(envDteProject); var projectDirectory = Path.GetDirectoryName(envDteProject.FullName); var fullFilePath = Path.Combine(projectDirectory, fileName); File.Copy(pathToRuleSet, fullFilePath); UpdateProjectConfigurationsToUseRuleSetFile(envDteProject, fileName); envDteProject.ProjectItems.AddFromFile(fullFilePath); return fullFilePath; } private void UpdateProjectConfigurationsToUseRuleSetFile(EnvDTE.Project envDteProject, string fileName) { foreach (EnvDTE.Configuration config in envDteProject.ConfigurationManager) { var properties = config.Properties; try { var codeAnalysisRuleSetFileProperty = properties?.Item("CodeAnalysisRuleSet"); if (codeAnalysisRuleSetFileProperty != null) { codeAnalysisRuleSetFileProperty.Value = fileName; } } catch (ArgumentException) { // Unfortunately the properties collection sometimes throws an ArgumentException // instead of returning null if the current configuration doesn't support CodeAnalysisRuleSet. // Ignore it and move on. } } } private string GetNewRuleSetFileNameForProject(EnvDTE.Project envDteProject) { var projectName = envDteProject.Name; var projectItemNames = new HashSet<string>(StringComparer.OrdinalIgnoreCase); foreach (ProjectItem item in envDteProject.ProjectItems) { projectItemNames.Add(item.Name); } var ruleSetName = projectName + ".ruleset"; if (!projectItemNames.Contains(ruleSetName)) { return ruleSetName; } for (var i = 1; i < int.MaxValue; i++) { ruleSetName = projectName + i + ".ruleset"; if (!projectItemNames.Contains(ruleSetName)) { return ruleSetName; } } return null; } private static ReportDiagnostic? MapSelectedItemToReportDiagnostic(MenuCommand selectedItem) { ReportDiagnostic? selectedAction = null; if (selectedItem.CommandID.Guid == Guids.RoslynGroupId) { switch (selectedItem.CommandID.ID) { case ID.RoslynCommands.SetSeverityDefault: selectedAction = ReportDiagnostic.Default; break; case ID.RoslynCommands.SetSeverityError: selectedAction = ReportDiagnostic.Error; break; case ID.RoslynCommands.SetSeverityWarning: selectedAction = ReportDiagnostic.Warn; break; case ID.RoslynCommands.SetSeverityInfo: selectedAction = ReportDiagnostic.Info; break; case ID.RoslynCommands.SetSeverityHidden: selectedAction = ReportDiagnostic.Hidden; break; case ID.RoslynCommands.SetSeverityNone: selectedAction = ReportDiagnostic.Suppress; break; default: selectedAction = null; break; } } return selectedAction; } private void SendUnableToOpenRuleSetNotification(Workspace workspace, string message) { SendErrorNotification( workspace, SolutionExplorerShim.The_rule_set_file_could_not_be_opened, message); } private void SendUnableToUpdateRuleSetNotification(Workspace workspace, string message) { SendErrorNotification( workspace, SolutionExplorerShim.The_rule_set_file_could_not_be_updated, message); } private void SendErrorNotification(Workspace workspace, string message1, string message2) { var notificationService = workspace.Services.GetService<INotificationService>(); notificationService.SendNotification(message1 + Environment.NewLine + Environment.NewLine + message2, severity: NotificationSeverity.Error); } int IVsUpdateSolutionEvents.UpdateSolution_Begin(ref int pfCancelUpdate) { _allowProjectSystemOperations = false; UpdateOtherMenuItemsEnabled(); return VSConstants.S_OK; } int IVsUpdateSolutionEvents.UpdateSolution_Done(int fSucceeded, int fModified, int fCancelCommand) { _allowProjectSystemOperations = true; UpdateOtherMenuItemsEnabled(); return VSConstants.S_OK; } int IVsUpdateSolutionEvents.UpdateSolution_StartUpdate(ref int pfCancelUpdate) { return VSConstants.S_OK; } int IVsUpdateSolutionEvents.UpdateSolution_Cancel() { _allowProjectSystemOperations = true; UpdateOtherMenuItemsEnabled(); return VSConstants.S_OK; } int IVsUpdateSolutionEvents.OnActiveProjectCfgChange(IVsHierarchy pIVsHierarchy) { return VSConstants.S_OK; } private Workspace TryGetWorkspace() { if (_workspace == null) { var componentModel = (IComponentModel)_serviceProvider.GetService(typeof(SComponentModel)); _workspace = componentModel.DefaultExportProvider.GetExportedValueOrDefault<VisualStudioWorkspace>(); } return _workspace; } } }
-1
dotnet/roslyn
55,256
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-30T00:02:02Z
2021-07-30T09:17:54Z
6ce9c0048d37026337701fac035ac0745f6fe49f
88b59775dc6375635957ef229116460f290072aa
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/EditorFeatures/Core.Wpf/EditAndContinue/ActiveStatementTagFormatDefinition.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.ComponentModel.Composition; using System.Diagnostics.CodeAnalysis; using System.Windows.Media; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.VisualStudio.Text.Classification; using Microsoft.VisualStudio.Utilities; namespace Microsoft.CodeAnalysis.Editor.Implementation.EditAndContinue { [Export(typeof(EditorFormatDefinition))] [Name(ActiveStatementTag.TagId)] [UserVisible(true)] [ExcludeFromCodeCoverage] internal sealed class ActiveStatementTagFormatDefinition : MarkerFormatDefinition { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public ActiveStatementTagFormatDefinition() { // TODO (tomat): bug 777271 // Should we reuse an existing marker for read only regions? // MARKER_READONLY // { L"Read-Only Region", IDS_MDN_READONLY, MV_COLOR_ALWAYS, LI_NONE, CI_BLACK, RGB(255, 255, 255), FALSE, CI_LIGHTGRAY, RGB(238, 239, 230), TRUE, DrawNoGlyph, MB_INHERIT_FOREGROUND, 0} this.BackgroundColor = Colors.Silver; this.DisplayName = EditorFeaturesResources.Active_Statement; this.ZOrder = -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.ComponentModel.Composition; using System.Diagnostics.CodeAnalysis; using System.Windows.Media; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.VisualStudio.Text.Classification; using Microsoft.VisualStudio.Utilities; namespace Microsoft.CodeAnalysis.Editor.Implementation.EditAndContinue { [Export(typeof(EditorFormatDefinition))] [Name(ActiveStatementTag.TagId)] [UserVisible(true)] [ExcludeFromCodeCoverage] internal sealed class ActiveStatementTagFormatDefinition : MarkerFormatDefinition { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public ActiveStatementTagFormatDefinition() { // TODO (tomat): bug 777271 // Should we reuse an existing marker for read only regions? // MARKER_READONLY // { L"Read-Only Region", IDS_MDN_READONLY, MV_COLOR_ALWAYS, LI_NONE, CI_BLACK, RGB(255, 255, 255), FALSE, CI_LIGHTGRAY, RGB(238, 239, 230), TRUE, DrawNoGlyph, MB_INHERIT_FOREGROUND, 0} this.BackgroundColor = Colors.Silver; this.DisplayName = EditorFeaturesResources.Active_Statement; this.ZOrder = -1; } } }
-1
dotnet/roslyn
55,256
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-30T00:02:02Z
2021-07-30T09:17:54Z
6ce9c0048d37026337701fac035ac0745f6fe49f
88b59775dc6375635957ef229116460f290072aa
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Compilers/Core/Portable/InternalUtilities/SpecializedCollections.ReadOnly.Set.cs
// Licensed to the .NET Foundation under one or more agreements. // 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; namespace Roslyn.Utilities { internal partial class SpecializedCollections { private partial class ReadOnly { internal class Set<TUnderlying, T> : Collection<TUnderlying, T>, ISet<T>, IReadOnlySet<T> where TUnderlying : ISet<T> { public Set(TUnderlying underlying) : base(underlying) { } public new bool Add(T item) { throw new NotSupportedException(); } public void ExceptWith(IEnumerable<T> other) { throw new NotSupportedException(); } public void IntersectWith(IEnumerable<T> other) { throw new NotSupportedException(); } public bool IsProperSubsetOf(IEnumerable<T> other) { return Underlying.IsProperSubsetOf(other); } public bool IsProperSupersetOf(IEnumerable<T> other) { return Underlying.IsProperSupersetOf(other); } public bool IsSubsetOf(IEnumerable<T> other) { return Underlying.IsSubsetOf(other); } public bool IsSupersetOf(IEnumerable<T> other) { return Underlying.IsSupersetOf(other); } public bool Overlaps(IEnumerable<T> other) { return Underlying.Overlaps(other); } public bool SetEquals(IEnumerable<T> other) { return Underlying.SetEquals(other); } public void SymmetricExceptWith(IEnumerable<T> other) { throw new NotSupportedException(); } public void UnionWith(IEnumerable<T> other) { throw new NotSupportedException(); } } } } }
// Licensed to the .NET Foundation under one or more agreements. // 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; namespace Roslyn.Utilities { internal partial class SpecializedCollections { private partial class ReadOnly { internal class Set<TUnderlying, T> : Collection<TUnderlying, T>, ISet<T>, IReadOnlySet<T> where TUnderlying : ISet<T> { public Set(TUnderlying underlying) : base(underlying) { } public new bool Add(T item) { throw new NotSupportedException(); } public void ExceptWith(IEnumerable<T> other) { throw new NotSupportedException(); } public void IntersectWith(IEnumerable<T> other) { throw new NotSupportedException(); } public bool IsProperSubsetOf(IEnumerable<T> other) { return Underlying.IsProperSubsetOf(other); } public bool IsProperSupersetOf(IEnumerable<T> other) { return Underlying.IsProperSupersetOf(other); } public bool IsSubsetOf(IEnumerable<T> other) { return Underlying.IsSubsetOf(other); } public bool IsSupersetOf(IEnumerable<T> other) { return Underlying.IsSupersetOf(other); } public bool Overlaps(IEnumerable<T> other) { return Underlying.Overlaps(other); } public bool SetEquals(IEnumerable<T> other) { return Underlying.SetEquals(other); } public void SymmetricExceptWith(IEnumerable<T> other) { throw new NotSupportedException(); } public void UnionWith(IEnumerable<T> other) { throw new NotSupportedException(); } } } } }
-1
dotnet/roslyn
55,256
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-30T00:02:02Z
2021-07-30T09:17:54Z
6ce9c0048d37026337701fac035ac0745f6fe49f
88b59775dc6375635957ef229116460f290072aa
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Features/Core/Portable/Diagnostics/EngineV2/DiagnosticIncrementalAnalyzer_GetDiagnostics.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Diagnostics.EngineV2 { internal partial class DiagnosticIncrementalAnalyzer { public Task<ImmutableArray<DiagnosticData>> GetSpecificCachedDiagnosticsAsync(Solution solution, object id, bool includeSuppressedDiagnostics = false, CancellationToken cancellationToken = default) { if (id is not LiveDiagnosticUpdateArgsId argsId) { return SpecializedTasks.EmptyImmutableArray<DiagnosticData>(); } var (documentId, projectId) = (argsId.ProjectOrDocumentId is DocumentId docId) ? (docId, docId.ProjectId) : (null, (ProjectId)argsId.ProjectOrDocumentId); return new IdeCachedDiagnosticGetter(this, solution, projectId, documentId, includeSuppressedDiagnostics).GetSpecificDiagnosticsAsync(argsId.Analyzer, (AnalysisKind)argsId.Kind, cancellationToken); } public Task<ImmutableArray<DiagnosticData>> GetCachedDiagnosticsAsync(Solution solution, ProjectId? projectId, DocumentId? documentId, bool includeSuppressedDiagnostics = false, CancellationToken cancellationToken = default) => new IdeCachedDiagnosticGetter(this, solution, projectId, documentId, includeSuppressedDiagnostics).GetDiagnosticsAsync(cancellationToken); public Task<ImmutableArray<DiagnosticData>> GetDiagnosticsAsync(Solution solution, ProjectId? projectId, DocumentId? documentId, bool includeSuppressedDiagnostics = false, CancellationToken cancellationToken = default) => new IdeLatestDiagnosticGetter(this, solution, projectId, documentId, diagnosticIds: null, includeSuppressedDiagnostics).GetDiagnosticsAsync(cancellationToken); public Task<ImmutableArray<DiagnosticData>> GetDiagnosticsForIdsAsync(Solution solution, ProjectId? projectId, DocumentId? documentId, ImmutableHashSet<string>? diagnosticIds, bool includeSuppressedDiagnostics = false, CancellationToken cancellationToken = default) => new IdeLatestDiagnosticGetter(this, solution, projectId, documentId, diagnosticIds, includeSuppressedDiagnostics).GetDiagnosticsAsync(cancellationToken); public Task<ImmutableArray<DiagnosticData>> GetProjectDiagnosticsForIdsAsync(Solution solution, ProjectId? projectId, ImmutableHashSet<string>? diagnosticIds, bool includeSuppressedDiagnostics = false, CancellationToken cancellationToken = default) => new IdeLatestDiagnosticGetter(this, solution, projectId, documentId: null, diagnosticIds: diagnosticIds, includeSuppressedDiagnostics).GetProjectDiagnosticsAsync(cancellationToken); private abstract class DiagnosticGetter { protected readonly DiagnosticIncrementalAnalyzer Owner; protected readonly Solution Solution; protected readonly ProjectId? ProjectId; protected readonly DocumentId? DocumentId; protected readonly bool IncludeSuppressedDiagnostics; private ImmutableArray<DiagnosticData>.Builder? _lazyDataBuilder; public DiagnosticGetter( DiagnosticIncrementalAnalyzer owner, Solution solution, ProjectId? projectId, DocumentId? documentId, bool includeSuppressedDiagnostics) { Owner = owner; Solution = solution; DocumentId = documentId; ProjectId = projectId ?? documentId?.ProjectId; IncludeSuppressedDiagnostics = includeSuppressedDiagnostics; } protected StateManager StateManager => Owner._stateManager; protected virtual bool ShouldIncludeDiagnostic(DiagnosticData diagnostic) => true; protected ImmutableArray<DiagnosticData> GetDiagnosticData() => (_lazyDataBuilder != null) ? _lazyDataBuilder.ToImmutableArray() : ImmutableArray<DiagnosticData>.Empty; protected abstract Task AppendDiagnosticsAsync(Project project, IEnumerable<DocumentId> documentIds, bool includeProjectNonLocalResult, CancellationToken cancellationToken); public async Task<ImmutableArray<DiagnosticData>> GetDiagnosticsAsync(CancellationToken cancellationToken) { if (ProjectId != null) { var project = Solution.GetProject(ProjectId); if (project == null) { return GetDiagnosticData(); } var documentIds = (DocumentId != null) ? SpecializedCollections.SingletonEnumerable(DocumentId) : project.DocumentIds; // return diagnostics specific to one project or document var includeProjectNonLocalResult = DocumentId == null; await AppendDiagnosticsAsync(project, documentIds, includeProjectNonLocalResult, cancellationToken).ConfigureAwait(false); return GetDiagnosticData(); } await AppendDiagnosticsAsync(Solution, cancellationToken).ConfigureAwait(false); return GetDiagnosticData(); } protected async Task AppendDiagnosticsAsync(Solution solution, CancellationToken cancellationToken) { // PERF: run projects in parallel rather than running CompilationWithAnalyzer with concurrency == true. // We do this to not get into thread starvation causing hundreds of threads to be spawned. var includeProjectNonLocalResult = true; var tasks = new Task[solution.ProjectIds.Count]; var index = 0; foreach (var project in solution.Projects) { var localProject = project; tasks[index++] = Task.Run( () => AppendDiagnosticsAsync( localProject, localProject.DocumentIds, includeProjectNonLocalResult, cancellationToken), cancellationToken); } await Task.WhenAll(tasks).ConfigureAwait(false); } protected void AppendDiagnostics(ImmutableArray<DiagnosticData> items) { Debug.Assert(!items.IsDefault); if (_lazyDataBuilder == null) { Interlocked.CompareExchange(ref _lazyDataBuilder, ImmutableArray.CreateBuilder<DiagnosticData>(), null); } lock (_lazyDataBuilder) { _lazyDataBuilder.AddRange(items.Where(ShouldIncludeSuppressedDiagnostic).Where(ShouldIncludeDiagnostic)); } } private bool ShouldIncludeSuppressedDiagnostic(DiagnosticData diagnostic) => IncludeSuppressedDiagnostics || !diagnostic.IsSuppressed; } private sealed class IdeCachedDiagnosticGetter : DiagnosticGetter { public IdeCachedDiagnosticGetter(DiagnosticIncrementalAnalyzer owner, Solution solution, ProjectId? projectId, DocumentId? documentId, bool includeSuppressedDiagnostics) : base(owner, solution, projectId, documentId, includeSuppressedDiagnostics) { } protected override async Task AppendDiagnosticsAsync(Project project, IEnumerable<DocumentId> documentIds, bool includeProjectNonLocalResult, CancellationToken cancellationToken) { foreach (var stateSet in StateManager.GetStateSets(project.Id)) { foreach (var documentId in documentIds) { AppendDiagnostics(await GetDiagnosticsAsync(stateSet, project, documentId, AnalysisKind.Syntax, cancellationToken).ConfigureAwait(false)); AppendDiagnostics(await GetDiagnosticsAsync(stateSet, project, documentId, AnalysisKind.Semantic, cancellationToken).ConfigureAwait(false)); AppendDiagnostics(await GetDiagnosticsAsync(stateSet, project, documentId, AnalysisKind.NonLocal, cancellationToken).ConfigureAwait(false)); } if (includeProjectNonLocalResult) { // include project diagnostics if there is no target document AppendDiagnostics(await GetProjectStateDiagnosticsAsync(stateSet, project, documentId: null, AnalysisKind.NonLocal, cancellationToken).ConfigureAwait(false)); } } } public async Task<ImmutableArray<DiagnosticData>> GetSpecificDiagnosticsAsync(DiagnosticAnalyzer analyzer, AnalysisKind analysisKind, CancellationToken cancellationToken) { var project = Solution.GetProject(ProjectId); if (project == null) { // when we return cached result, make sure we at least return something that exist in current solution return ImmutableArray<DiagnosticData>.Empty; } var stateSet = StateManager.GetOrCreateStateSet(project, analyzer); if (stateSet == null) { return ImmutableArray<DiagnosticData>.Empty; } var diagnostics = await GetDiagnosticsAsync(stateSet, project, DocumentId, analysisKind, cancellationToken).ConfigureAwait(false); return IncludeSuppressedDiagnostics ? diagnostics : diagnostics.WhereAsArray(d => !d.IsSuppressed); } private static async Task<ImmutableArray<DiagnosticData>> GetDiagnosticsAsync(StateSet stateSet, Project project, DocumentId? documentId, AnalysisKind kind, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); // active file diagnostics: if (documentId != null && kind != AnalysisKind.NonLocal && stateSet.TryGetActiveFileState(documentId, out var state)) { return state.GetAnalysisData(kind).Items; } // project diagnostics: return await GetProjectStateDiagnosticsAsync(stateSet, project, documentId, kind, cancellationToken).ConfigureAwait(false); } private static async Task<ImmutableArray<DiagnosticData>> GetProjectStateDiagnosticsAsync(StateSet stateSet, Project project, DocumentId? documentId, AnalysisKind kind, CancellationToken cancellationToken) { if (!stateSet.TryGetProjectState(project.Id, out var state)) { // never analyzed this project yet. return ImmutableArray<DiagnosticData>.Empty; } if (documentId != null) { // file doesn't exist in current solution var document = project.Solution.GetDocument(documentId); if (document == null) { return ImmutableArray<DiagnosticData>.Empty; } var result = await state.GetAnalysisDataAsync(document, avoidLoadingData: false, cancellationToken).ConfigureAwait(false); return result.GetDocumentDiagnostics(documentId, kind); } Contract.ThrowIfFalse(kind == AnalysisKind.NonLocal); var nonLocalResult = await state.GetProjectAnalysisDataAsync(project, avoidLoadingData: false, cancellationToken: cancellationToken).ConfigureAwait(false); return nonLocalResult.GetOtherDiagnostics(); } } private sealed class IdeLatestDiagnosticGetter : DiagnosticGetter { private readonly ImmutableHashSet<string>? _diagnosticIds; public IdeLatestDiagnosticGetter(DiagnosticIncrementalAnalyzer owner, Solution solution, ProjectId? projectId, DocumentId? documentId, ImmutableHashSet<string>? diagnosticIds, bool includeSuppressedDiagnostics) : base(owner, solution, projectId, documentId, includeSuppressedDiagnostics) { _diagnosticIds = diagnosticIds; } public async Task<ImmutableArray<DiagnosticData>> GetProjectDiagnosticsAsync(CancellationToken cancellationToken) { if (ProjectId != null) { var project = Solution.GetProject(ProjectId); if (project != null) { await AppendDiagnosticsAsync(project, SpecializedCollections.EmptyEnumerable<DocumentId>(), includeProjectNonLocalResult: true, cancellationToken).ConfigureAwait(false); } return GetDiagnosticData(); } await AppendDiagnosticsAsync(Solution, cancellationToken).ConfigureAwait(false); return GetDiagnosticData(); } protected override bool ShouldIncludeDiagnostic(DiagnosticData diagnostic) => _diagnosticIds == null || _diagnosticIds.Contains(diagnostic.Id); protected override async Task AppendDiagnosticsAsync(Project project, IEnumerable<DocumentId> documentIds, bool includeProjectNonLocalResult, CancellationToken cancellationToken) { // get analyzers that are not suppressed. var stateSets = StateManager.GetOrCreateStateSets(project).Where(s => ShouldIncludeStateSet(project, s)).ToImmutableArrayOrEmpty(); // unlike the suppressed (disabled) analyzer, we will include hidden diagnostic only analyzers here. var compilation = await CreateCompilationWithAnalyzersAsync(project, stateSets, IncludeSuppressedDiagnostics, cancellationToken).ConfigureAwait(false); var result = await Owner.GetProjectAnalysisDataAsync(compilation, project, stateSets, forceAnalyzerRun: true, cancellationToken).ConfigureAwait(false); foreach (var stateSet in stateSets) { var analysisResult = result.GetResult(stateSet.Analyzer); foreach (var documentId in documentIds) { AppendDiagnostics(analysisResult.GetDocumentDiagnostics(documentId, AnalysisKind.Syntax)); AppendDiagnostics(analysisResult.GetDocumentDiagnostics(documentId, AnalysisKind.Semantic)); AppendDiagnostics(analysisResult.GetDocumentDiagnostics(documentId, AnalysisKind.NonLocal)); } if (includeProjectNonLocalResult) { // include project diagnostics if there is no target document AppendDiagnostics(analysisResult.GetOtherDiagnostics()); } } } private bool ShouldIncludeStateSet(Project project, StateSet stateSet) { var infoCache = Owner.DiagnosticAnalyzerInfoCache; if (infoCache.IsAnalyzerSuppressed(stateSet.Analyzer, project)) { return false; } if (_diagnosticIds != null && infoCache.GetDiagnosticDescriptors(stateSet.Analyzer).All(d => !_diagnosticIds.Contains(d.Id))) { return false; } return true; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Diagnostics.EngineV2 { internal partial class DiagnosticIncrementalAnalyzer { public Task<ImmutableArray<DiagnosticData>> GetSpecificCachedDiagnosticsAsync(Solution solution, object id, bool includeSuppressedDiagnostics = false, CancellationToken cancellationToken = default) { if (id is not LiveDiagnosticUpdateArgsId argsId) { return SpecializedTasks.EmptyImmutableArray<DiagnosticData>(); } var (documentId, projectId) = (argsId.ProjectOrDocumentId is DocumentId docId) ? (docId, docId.ProjectId) : (null, (ProjectId)argsId.ProjectOrDocumentId); return new IdeCachedDiagnosticGetter(this, solution, projectId, documentId, includeSuppressedDiagnostics).GetSpecificDiagnosticsAsync(argsId.Analyzer, (AnalysisKind)argsId.Kind, cancellationToken); } public Task<ImmutableArray<DiagnosticData>> GetCachedDiagnosticsAsync(Solution solution, ProjectId? projectId, DocumentId? documentId, bool includeSuppressedDiagnostics = false, CancellationToken cancellationToken = default) => new IdeCachedDiagnosticGetter(this, solution, projectId, documentId, includeSuppressedDiagnostics).GetDiagnosticsAsync(cancellationToken); public Task<ImmutableArray<DiagnosticData>> GetDiagnosticsAsync(Solution solution, ProjectId? projectId, DocumentId? documentId, bool includeSuppressedDiagnostics = false, CancellationToken cancellationToken = default) => new IdeLatestDiagnosticGetter(this, solution, projectId, documentId, diagnosticIds: null, includeSuppressedDiagnostics).GetDiagnosticsAsync(cancellationToken); public Task<ImmutableArray<DiagnosticData>> GetDiagnosticsForIdsAsync(Solution solution, ProjectId? projectId, DocumentId? documentId, ImmutableHashSet<string>? diagnosticIds, bool includeSuppressedDiagnostics = false, CancellationToken cancellationToken = default) => new IdeLatestDiagnosticGetter(this, solution, projectId, documentId, diagnosticIds, includeSuppressedDiagnostics).GetDiagnosticsAsync(cancellationToken); public Task<ImmutableArray<DiagnosticData>> GetProjectDiagnosticsForIdsAsync(Solution solution, ProjectId? projectId, ImmutableHashSet<string>? diagnosticIds, bool includeSuppressedDiagnostics = false, CancellationToken cancellationToken = default) => new IdeLatestDiagnosticGetter(this, solution, projectId, documentId: null, diagnosticIds: diagnosticIds, includeSuppressedDiagnostics).GetProjectDiagnosticsAsync(cancellationToken); private abstract class DiagnosticGetter { protected readonly DiagnosticIncrementalAnalyzer Owner; protected readonly Solution Solution; protected readonly ProjectId? ProjectId; protected readonly DocumentId? DocumentId; protected readonly bool IncludeSuppressedDiagnostics; private ImmutableArray<DiagnosticData>.Builder? _lazyDataBuilder; public DiagnosticGetter( DiagnosticIncrementalAnalyzer owner, Solution solution, ProjectId? projectId, DocumentId? documentId, bool includeSuppressedDiagnostics) { Owner = owner; Solution = solution; DocumentId = documentId; ProjectId = projectId ?? documentId?.ProjectId; IncludeSuppressedDiagnostics = includeSuppressedDiagnostics; } protected StateManager StateManager => Owner._stateManager; protected virtual bool ShouldIncludeDiagnostic(DiagnosticData diagnostic) => true; protected ImmutableArray<DiagnosticData> GetDiagnosticData() => (_lazyDataBuilder != null) ? _lazyDataBuilder.ToImmutableArray() : ImmutableArray<DiagnosticData>.Empty; protected abstract Task AppendDiagnosticsAsync(Project project, IEnumerable<DocumentId> documentIds, bool includeProjectNonLocalResult, CancellationToken cancellationToken); public async Task<ImmutableArray<DiagnosticData>> GetDiagnosticsAsync(CancellationToken cancellationToken) { if (ProjectId != null) { var project = Solution.GetProject(ProjectId); if (project == null) { return GetDiagnosticData(); } var documentIds = (DocumentId != null) ? SpecializedCollections.SingletonEnumerable(DocumentId) : project.DocumentIds; // return diagnostics specific to one project or document var includeProjectNonLocalResult = DocumentId == null; await AppendDiagnosticsAsync(project, documentIds, includeProjectNonLocalResult, cancellationToken).ConfigureAwait(false); return GetDiagnosticData(); } await AppendDiagnosticsAsync(Solution, cancellationToken).ConfigureAwait(false); return GetDiagnosticData(); } protected async Task AppendDiagnosticsAsync(Solution solution, CancellationToken cancellationToken) { // PERF: run projects in parallel rather than running CompilationWithAnalyzer with concurrency == true. // We do this to not get into thread starvation causing hundreds of threads to be spawned. var includeProjectNonLocalResult = true; var tasks = new Task[solution.ProjectIds.Count]; var index = 0; foreach (var project in solution.Projects) { var localProject = project; tasks[index++] = Task.Run( () => AppendDiagnosticsAsync( localProject, localProject.DocumentIds, includeProjectNonLocalResult, cancellationToken), cancellationToken); } await Task.WhenAll(tasks).ConfigureAwait(false); } protected void AppendDiagnostics(ImmutableArray<DiagnosticData> items) { Debug.Assert(!items.IsDefault); if (_lazyDataBuilder == null) { Interlocked.CompareExchange(ref _lazyDataBuilder, ImmutableArray.CreateBuilder<DiagnosticData>(), null); } lock (_lazyDataBuilder) { _lazyDataBuilder.AddRange(items.Where(ShouldIncludeSuppressedDiagnostic).Where(ShouldIncludeDiagnostic)); } } private bool ShouldIncludeSuppressedDiagnostic(DiagnosticData diagnostic) => IncludeSuppressedDiagnostics || !diagnostic.IsSuppressed; } private sealed class IdeCachedDiagnosticGetter : DiagnosticGetter { public IdeCachedDiagnosticGetter(DiagnosticIncrementalAnalyzer owner, Solution solution, ProjectId? projectId, DocumentId? documentId, bool includeSuppressedDiagnostics) : base(owner, solution, projectId, documentId, includeSuppressedDiagnostics) { } protected override async Task AppendDiagnosticsAsync(Project project, IEnumerable<DocumentId> documentIds, bool includeProjectNonLocalResult, CancellationToken cancellationToken) { foreach (var stateSet in StateManager.GetStateSets(project.Id)) { foreach (var documentId in documentIds) { AppendDiagnostics(await GetDiagnosticsAsync(stateSet, project, documentId, AnalysisKind.Syntax, cancellationToken).ConfigureAwait(false)); AppendDiagnostics(await GetDiagnosticsAsync(stateSet, project, documentId, AnalysisKind.Semantic, cancellationToken).ConfigureAwait(false)); AppendDiagnostics(await GetDiagnosticsAsync(stateSet, project, documentId, AnalysisKind.NonLocal, cancellationToken).ConfigureAwait(false)); } if (includeProjectNonLocalResult) { // include project diagnostics if there is no target document AppendDiagnostics(await GetProjectStateDiagnosticsAsync(stateSet, project, documentId: null, AnalysisKind.NonLocal, cancellationToken).ConfigureAwait(false)); } } } public async Task<ImmutableArray<DiagnosticData>> GetSpecificDiagnosticsAsync(DiagnosticAnalyzer analyzer, AnalysisKind analysisKind, CancellationToken cancellationToken) { var project = Solution.GetProject(ProjectId); if (project == null) { // when we return cached result, make sure we at least return something that exist in current solution return ImmutableArray<DiagnosticData>.Empty; } var stateSet = StateManager.GetOrCreateStateSet(project, analyzer); if (stateSet == null) { return ImmutableArray<DiagnosticData>.Empty; } var diagnostics = await GetDiagnosticsAsync(stateSet, project, DocumentId, analysisKind, cancellationToken).ConfigureAwait(false); return IncludeSuppressedDiagnostics ? diagnostics : diagnostics.WhereAsArray(d => !d.IsSuppressed); } private static async Task<ImmutableArray<DiagnosticData>> GetDiagnosticsAsync(StateSet stateSet, Project project, DocumentId? documentId, AnalysisKind kind, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); // active file diagnostics: if (documentId != null && kind != AnalysisKind.NonLocal && stateSet.TryGetActiveFileState(documentId, out var state)) { return state.GetAnalysisData(kind).Items; } // project diagnostics: return await GetProjectStateDiagnosticsAsync(stateSet, project, documentId, kind, cancellationToken).ConfigureAwait(false); } private static async Task<ImmutableArray<DiagnosticData>> GetProjectStateDiagnosticsAsync(StateSet stateSet, Project project, DocumentId? documentId, AnalysisKind kind, CancellationToken cancellationToken) { if (!stateSet.TryGetProjectState(project.Id, out var state)) { // never analyzed this project yet. return ImmutableArray<DiagnosticData>.Empty; } if (documentId != null) { // file doesn't exist in current solution var document = project.Solution.GetDocument(documentId); if (document == null) { return ImmutableArray<DiagnosticData>.Empty; } var result = await state.GetAnalysisDataAsync(document, avoidLoadingData: false, cancellationToken).ConfigureAwait(false); return result.GetDocumentDiagnostics(documentId, kind); } Contract.ThrowIfFalse(kind == AnalysisKind.NonLocal); var nonLocalResult = await state.GetProjectAnalysisDataAsync(project, avoidLoadingData: false, cancellationToken: cancellationToken).ConfigureAwait(false); return nonLocalResult.GetOtherDiagnostics(); } } private sealed class IdeLatestDiagnosticGetter : DiagnosticGetter { private readonly ImmutableHashSet<string>? _diagnosticIds; public IdeLatestDiagnosticGetter(DiagnosticIncrementalAnalyzer owner, Solution solution, ProjectId? projectId, DocumentId? documentId, ImmutableHashSet<string>? diagnosticIds, bool includeSuppressedDiagnostics) : base(owner, solution, projectId, documentId, includeSuppressedDiagnostics) { _diagnosticIds = diagnosticIds; } public async Task<ImmutableArray<DiagnosticData>> GetProjectDiagnosticsAsync(CancellationToken cancellationToken) { if (ProjectId != null) { var project = Solution.GetProject(ProjectId); if (project != null) { await AppendDiagnosticsAsync(project, SpecializedCollections.EmptyEnumerable<DocumentId>(), includeProjectNonLocalResult: true, cancellationToken).ConfigureAwait(false); } return GetDiagnosticData(); } await AppendDiagnosticsAsync(Solution, cancellationToken).ConfigureAwait(false); return GetDiagnosticData(); } protected override bool ShouldIncludeDiagnostic(DiagnosticData diagnostic) => _diagnosticIds == null || _diagnosticIds.Contains(diagnostic.Id); protected override async Task AppendDiagnosticsAsync(Project project, IEnumerable<DocumentId> documentIds, bool includeProjectNonLocalResult, CancellationToken cancellationToken) { // get analyzers that are not suppressed. var stateSets = StateManager.GetOrCreateStateSets(project).Where(s => ShouldIncludeStateSet(project, s)).ToImmutableArrayOrEmpty(); // unlike the suppressed (disabled) analyzer, we will include hidden diagnostic only analyzers here. var compilation = await CreateCompilationWithAnalyzersAsync(project, stateSets, IncludeSuppressedDiagnostics, cancellationToken).ConfigureAwait(false); var result = await Owner.GetProjectAnalysisDataAsync(compilation, project, stateSets, forceAnalyzerRun: true, cancellationToken).ConfigureAwait(false); foreach (var stateSet in stateSets) { var analysisResult = result.GetResult(stateSet.Analyzer); foreach (var documentId in documentIds) { AppendDiagnostics(analysisResult.GetDocumentDiagnostics(documentId, AnalysisKind.Syntax)); AppendDiagnostics(analysisResult.GetDocumentDiagnostics(documentId, AnalysisKind.Semantic)); AppendDiagnostics(analysisResult.GetDocumentDiagnostics(documentId, AnalysisKind.NonLocal)); } if (includeProjectNonLocalResult) { // include project diagnostics if there is no target document AppendDiagnostics(analysisResult.GetOtherDiagnostics()); } } } private bool ShouldIncludeStateSet(Project project, StateSet stateSet) { var infoCache = Owner.DiagnosticAnalyzerInfoCache; if (infoCache.IsAnalyzerSuppressed(stateSet.Analyzer, project)) { return false; } if (_diagnosticIds != null && infoCache.GetDiagnosticDescriptors(stateSet.Analyzer).All(d => !_diagnosticIds.Contains(d.Id))) { return false; } return true; } } } }
-1
dotnet/roslyn
55,256
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-30T00:02:02Z
2021-07-30T09:17:54Z
6ce9c0048d37026337701fac035ac0745f6fe49f
88b59775dc6375635957ef229116460f290072aa
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Tools/IdeCoreBenchmarks/CloudCache/IdeCoreBenchmarksCloudCacheServiceProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // 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; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Storage; using Microsoft.CodeAnalysis.Storage.CloudCache; using Microsoft.CodeAnalysis.UnitTests.WorkspaceServices.Mocks; namespace CloudCache { [ExportWorkspaceService(typeof(ICloudCacheStorageServiceFactory), ServiceLayer.Host), Shared] internal class IdeCoreBenchmarksCloudCacheServiceProvider : ICloudCacheStorageServiceFactory { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public IdeCoreBenchmarksCloudCacheServiceProvider() { Console.WriteLine($"Instantiated {nameof(IdeCoreBenchmarksCloudCacheServiceProvider)}"); } public AbstractPersistentStorageService Create(IPersistentStorageLocationService locationService) { return new MockCloudCachePersistentStorageService( locationService, @"C:\github\roslyn", cs => { if (cs is IAsyncDisposable asyncDisposable) { asyncDisposable.DisposeAsync().AsTask().Wait(); } else if (cs is IDisposable disposable) { disposable.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.Composition; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Storage; using Microsoft.CodeAnalysis.Storage.CloudCache; using Microsoft.CodeAnalysis.UnitTests.WorkspaceServices.Mocks; namespace CloudCache { [ExportWorkspaceService(typeof(ICloudCacheStorageServiceFactory), ServiceLayer.Host), Shared] internal class IdeCoreBenchmarksCloudCacheServiceProvider : ICloudCacheStorageServiceFactory { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public IdeCoreBenchmarksCloudCacheServiceProvider() { Console.WriteLine($"Instantiated {nameof(IdeCoreBenchmarksCloudCacheServiceProvider)}"); } public AbstractPersistentStorageService Create(IPersistentStorageLocationService locationService) { return new MockCloudCachePersistentStorageService( locationService, @"C:\github\roslyn", cs => { if (cs is IAsyncDisposable asyncDisposable) { asyncDisposable.DisposeAsync().AsTask().Wait(); } else if (cs is IDisposable disposable) { disposable.Dispose(); } }); } } }
-1
dotnet/roslyn
55,256
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-30T00:02:02Z
2021-07-30T09:17:54Z
6ce9c0048d37026337701fac035ac0745f6fe49f
88b59775dc6375635957ef229116460f290072aa
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Compilers/Test/Core/Compilation/RuntimeUtilities.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Reflection; using System.Runtime.InteropServices; using System.Text; using Roslyn.Test.Utilities; namespace Microsoft.CodeAnalysis.Test.Utilities { /// <summary> /// Hide all of the runtime specific implementations of types that we need to use when multi-targeting. /// </summary> public static partial class RuntimeUtilities { internal static bool IsDesktopRuntime => #if NET472 true; #elif NETCOREAPP false; #elif NETSTANDARD2_0 throw new PlatformNotSupportedException(); #else #error Unsupported configuration #endif internal static bool IsCoreClrRuntime => !IsDesktopRuntime; internal static BuildPaths CreateBuildPaths(string workingDirectory, string sdkDirectory = null, string tempDirectory = null) { tempDirectory = tempDirectory ?? Path.GetTempPath(); #if NET472 return new BuildPaths( clientDir: Path.GetDirectoryName(typeof(BuildPathsUtil).Assembly.Location), workingDir: workingDirectory, sdkDir: sdkDirectory ?? RuntimeEnvironment.GetRuntimeDirectory(), tempDir: tempDirectory); #else return new BuildPaths( clientDir: AppContext.BaseDirectory, workingDir: workingDirectory, sdkDir: sdkDirectory, tempDir: tempDirectory); #endif } internal static IRuntimeEnvironmentFactory GetRuntimeEnvironmentFactory() { #if NET472 return new Roslyn.Test.Utilities.Desktop.DesktopRuntimeEnvironmentFactory(); #elif NETCOREAPP return new Roslyn.Test.Utilities.CoreClr.CoreCLRRuntimeEnvironmentFactory(); #elif NETSTANDARD2_0 throw new PlatformNotSupportedException(); #else #error Unsupported configuration #endif } /// <summary> /// Get the location of the assembly that contains this type /// </summary> internal static string GetAssemblyLocation(Type type) { return type.GetTypeInfo().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. #nullable disable using System; using System.Collections.Generic; using System.IO; using System.Reflection; using System.Runtime.InteropServices; using System.Text; using Roslyn.Test.Utilities; namespace Microsoft.CodeAnalysis.Test.Utilities { /// <summary> /// Hide all of the runtime specific implementations of types that we need to use when multi-targeting. /// </summary> public static partial class RuntimeUtilities { internal static bool IsDesktopRuntime => #if NET472 true; #elif NETCOREAPP false; #elif NETSTANDARD2_0 throw new PlatformNotSupportedException(); #else #error Unsupported configuration #endif internal static bool IsCoreClrRuntime => !IsDesktopRuntime; internal static BuildPaths CreateBuildPaths(string workingDirectory, string sdkDirectory = null, string tempDirectory = null) { tempDirectory = tempDirectory ?? Path.GetTempPath(); #if NET472 return new BuildPaths( clientDir: Path.GetDirectoryName(typeof(BuildPathsUtil).Assembly.Location), workingDir: workingDirectory, sdkDir: sdkDirectory ?? RuntimeEnvironment.GetRuntimeDirectory(), tempDir: tempDirectory); #else return new BuildPaths( clientDir: AppContext.BaseDirectory, workingDir: workingDirectory, sdkDir: sdkDirectory, tempDir: tempDirectory); #endif } internal static IRuntimeEnvironmentFactory GetRuntimeEnvironmentFactory() { #if NET472 return new Roslyn.Test.Utilities.Desktop.DesktopRuntimeEnvironmentFactory(); #elif NETCOREAPP return new Roslyn.Test.Utilities.CoreClr.CoreCLRRuntimeEnvironmentFactory(); #elif NETSTANDARD2_0 throw new PlatformNotSupportedException(); #else #error Unsupported configuration #endif } /// <summary> /// Get the location of the assembly that contains this type /// </summary> internal static string GetAssemblyLocation(Type type) { return type.GetTypeInfo().Assembly.Location; } } }
-1
dotnet/roslyn
55,256
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-30T00:02:02Z
2021-07-30T09:17:54Z
6ce9c0048d37026337701fac035ac0745f6fe49f
88b59775dc6375635957ef229116460f290072aa
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Compilers/CSharp/Test/Emit/Emit/BinaryCompatibility.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class BinaryCompatibility : EmitMetadataTestBase { [Fact] public void InvokeVirtualBoundToOriginal() { // A method invocation of a virtual method is statically bound by the C# language to // the original declaration of the virtual method, not the most derived override of // that method. The difference between these two choices is visible in the binary // compatibility behavior of the program at runtime (e.g. when executing the program // against a modified library). This test checks that we bind the invocation to the // virtual method, not the override. var lib0 = @" public class Base { public virtual void M() { System.Console.WriteLine(""Base0""); } } public class Derived : Base { public override void M() { System.Console.WriteLine(""Derived0""); } } "; var lib0Image = CreateCompilationWithMscorlib46(lib0, options: TestOptions.ReleaseDll, assemblyName: "lib").EmitToImageReference(); var lib1 = @" public class Base { public virtual void M() { System.Console.WriteLine(""Base1""); } } public class Derived : Base { public new virtual void M() { System.Console.WriteLine(""Derived1""); } } "; var lib1Image = CreateCompilationWithMscorlib46(lib1, options: TestOptions.ReleaseDll, assemblyName: "lib").EmitToImageReference(); var client = @" public class Client { public static void M() { Derived d = new Derived(); d.M(); } } "; var clientImage = CreateCompilationWithMscorlib46(client, references: new[] { lib0Image }, options: TestOptions.ReleaseDll).EmitToImageReference(); var program = @" public class Program { public static void Main() { Client.M(); } } "; var compilation = CreateCompilationWithMscorlib46(program, references: new[] { lib1Image, clientImage }, options: TestOptions.ReleaseExe); CompileAndVerify(compilation, expectedOutput: @"Base1"); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class BinaryCompatibility : EmitMetadataTestBase { [Fact] public void InvokeVirtualBoundToOriginal() { // A method invocation of a virtual method is statically bound by the C# language to // the original declaration of the virtual method, not the most derived override of // that method. The difference between these two choices is visible in the binary // compatibility behavior of the program at runtime (e.g. when executing the program // against a modified library). This test checks that we bind the invocation to the // virtual method, not the override. var lib0 = @" public class Base { public virtual void M() { System.Console.WriteLine(""Base0""); } } public class Derived : Base { public override void M() { System.Console.WriteLine(""Derived0""); } } "; var lib0Image = CreateCompilationWithMscorlib46(lib0, options: TestOptions.ReleaseDll, assemblyName: "lib").EmitToImageReference(); var lib1 = @" public class Base { public virtual void M() { System.Console.WriteLine(""Base1""); } } public class Derived : Base { public new virtual void M() { System.Console.WriteLine(""Derived1""); } } "; var lib1Image = CreateCompilationWithMscorlib46(lib1, options: TestOptions.ReleaseDll, assemblyName: "lib").EmitToImageReference(); var client = @" public class Client { public static void M() { Derived d = new Derived(); d.M(); } } "; var clientImage = CreateCompilationWithMscorlib46(client, references: new[] { lib0Image }, options: TestOptions.ReleaseDll).EmitToImageReference(); var program = @" public class Program { public static void Main() { Client.M(); } } "; var compilation = CreateCompilationWithMscorlib46(program, references: new[] { lib1Image, clientImage }, options: TestOptions.ReleaseExe); CompileAndVerify(compilation, expectedOutput: @"Base1"); } } }
-1
dotnet/roslyn
55,256
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-30T00:02:02Z
2021-07-30T09:17:54Z
6ce9c0048d37026337701fac035ac0745f6fe49f
88b59775dc6375635957ef229116460f290072aa
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Compilers/Test/Core/ThrowingTraceListener.cs
// Licensed to the .NET Foundation under one or more agreements. // 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 { // To enable this for a process, add the following to the app.config for the project: // // <configuration> // <system.diagnostics> // <trace> // <listeners> // <remove name="Default" /> // <add name="ThrowingTraceListener" type="Microsoft.CodeAnalysis.ThrowingTraceListener, Roslyn.Test.Utilities" /> // </listeners> // </trace> // </system.diagnostics> //</configuration> public sealed class ThrowingTraceListener : TraceListener { public override void Fail(string? message, string? detailMessage) { throw new InvalidOperationException( (string.IsNullOrEmpty(message) ? "Assertion failed" : message) + (string.IsNullOrEmpty(detailMessage) ? "" : Environment.NewLine + detailMessage)); } public override void Write(object? o) { } public override void Write(object? o, string? category) { } public override void Write(string? message) { } public override void Write(string? message, string? category) { } public override void WriteLine(object? o) { } public override void WriteLine(object? o, string? category) { } public override void WriteLine(string? message) { } public override void WriteLine(string? message, string? category) { } } }
// Licensed to the .NET Foundation under one or more agreements. // 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 { // To enable this for a process, add the following to the app.config for the project: // // <configuration> // <system.diagnostics> // <trace> // <listeners> // <remove name="Default" /> // <add name="ThrowingTraceListener" type="Microsoft.CodeAnalysis.ThrowingTraceListener, Roslyn.Test.Utilities" /> // </listeners> // </trace> // </system.diagnostics> //</configuration> public sealed class ThrowingTraceListener : TraceListener { public override void Fail(string? message, string? detailMessage) { throw new InvalidOperationException( (string.IsNullOrEmpty(message) ? "Assertion failed" : message) + (string.IsNullOrEmpty(detailMessage) ? "" : Environment.NewLine + detailMessage)); } public override void Write(object? o) { } public override void Write(object? o, string? category) { } public override void Write(string? message) { } public override void Write(string? message, string? category) { } public override void WriteLine(object? o) { } public override void WriteLine(object? o, string? category) { } public override void WriteLine(string? message) { } public override void WriteLine(string? message, string? category) { } } }
-1
dotnet/roslyn
55,256
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-30T00:02:02Z
2021-07-30T09:17:54Z
6ce9c0048d37026337701fac035ac0745f6fe49f
88b59775dc6375635957ef229116460f290072aa
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Compilers/CSharp/Test/Symbol/Symbols/Source/DeclaringSyntaxNodeTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Text; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Symbols.Source { public class DeclaringSyntaxNodeTests : CSharpTestBase { // Check that the given symbol has the expected number of declaring syntax nodes. // and that each declared node goes back to the given symbol. private ImmutableArray<SyntaxReference> CheckDeclaringSyntaxNodes(Compilation compilation, ISymbol symbol, int expectedNumber) { var declaringReferences = symbol.DeclaringSyntaxReferences; Assert.Equal(expectedNumber, declaringReferences.Length); if (expectedNumber == 0) { Assert.True(!symbol.GetSymbol().IsFromCompilation((CSharpCompilation)compilation) || symbol.IsImplicitlyDeclared, "non-implicitly declares source symbol should have declaring location"); } else { Assert.True(symbol.GetSymbol().IsFromCompilation((CSharpCompilation)compilation) || symbol.GetSymbol() is MergedNamespaceSymbol, "symbol with declaration should be in source, except for merged namespaces"); Assert.False(symbol.IsImplicitlyDeclared); foreach (var node in declaringReferences.Select(d => d.GetSyntax())) { // Make sure GetDeclaredSymbol gets back to the symbol for each node. SyntaxTree tree = node.SyntaxTree; SemanticModel model = compilation.GetSemanticModel(tree); Assert.Equal(symbol.OriginalDefinition, model.GetDeclaredSymbol(node)); } } return declaringReferences; } private ImmutableArray<SyntaxReference> CheckDeclaringSyntaxNodesIncludingParameters(Compilation compilation, ISymbol symbol, int expectedNumber) { var nodes = CheckDeclaringSyntaxNodes(compilation, symbol, expectedNumber); var meth = symbol as IMethodSymbol; if (meth != null) { foreach (IParameterSymbol p in meth.Parameters) CheckDeclaringSyntaxNodes(compilation, p, meth.GetSymbol().IsAccessor() ? 0 : expectedNumber); } var prop = symbol as IPropertySymbol; if (prop != null) { foreach (IParameterSymbol p in prop.Parameters) CheckDeclaringSyntaxNodes(compilation, p, expectedNumber); } return nodes; } // Check that the given symbol has the expected number of declaring syntax nodes. // and that the syntax has the expected kind. Does NOT test GetDeclaringSymbol private ImmutableArray<SyntaxReference> CheckDeclaringSyntaxNodesWithoutGetDeclaredSymbol(Compilation compilation, ISymbol symbol, int expectedNumber, SyntaxKind expectedSyntaxKind) { var declaringReferences = symbol.DeclaringSyntaxReferences; Assert.Equal(expectedNumber, declaringReferences.Length); if (expectedNumber == 0) { Assert.True(!symbol.GetSymbol().IsFromCompilation((CSharpCompilation)compilation) || symbol.IsImplicitlyDeclared, "non-implicitly declares source symbol should have declaring location"); } else { Assert.True(symbol.GetSymbol().IsFromCompilation((CSharpCompilation)compilation) || symbol.GetSymbol() is MergedNamespaceSymbol, "symbol with declaration should be in source, except for merged namespaces"); if (symbol.Kind == SymbolKind.Namespace && ((INamespaceSymbol)symbol).IsGlobalNamespace) { Assert.True(symbol.IsImplicitlyDeclared); } else { Assert.False(symbol.IsImplicitlyDeclared); } foreach (var node in declaringReferences.Select(d => d.GetSyntax())) { // Make sure each node is of the expected kind. Assert.Equal(expectedSyntaxKind, node.Kind()); } } return declaringReferences; } private void AssertDeclaringSyntaxNodes(Symbol symbol, CSharpCompilation compilation, params SyntaxNode[] expectedSyntaxNodes) { int expectedNumber = expectedSyntaxNodes.Length; var declaringReferences = symbol.DeclaringSyntaxReferences; Assert.Equal(expectedNumber, declaringReferences.Length); if (expectedNumber == 0) { Assert.True(!symbol.IsFromCompilation(compilation) || symbol.IsImplicitlyDeclared, "non-implicitly declares source symbol should have declaring location"); } else { Assert.True(symbol.IsFromCompilation(compilation) || symbol is MergedNamespaceSymbol, "symbol with declaration should be in source, except for merged namespaces"); Assert.False(symbol.IsImplicitlyDeclared); for (int i = 0; i < expectedNumber; i++) { Assert.Same(expectedSyntaxNodes[i], declaringReferences[i].GetSyntax()); } } } private void CheckDeclaringSyntax<TNode>(CSharpCompilation comp, SyntaxTree tree, string name, SymbolKind kind) where TNode : CSharpSyntaxNode { var model = comp.GetSemanticModel(tree); string code = tree.GetText().ToString(); int position = code.IndexOf(name, StringComparison.Ordinal); var node = tree.GetRoot().FindToken(position).Parent.FirstAncestorOrSelf<TNode>(); var sym = model.GetDeclaredSymbol(node); Assert.Equal(kind, sym.Kind); Assert.Equal(name, sym.Name); CheckDeclaringSyntaxNodes(comp, sym, 1); } private void CheckLambdaDeclaringSyntax<TNode>(CSharpCompilation comp, SyntaxTree tree, string textToSearchFor) where TNode : ExpressionSyntax { var model = comp.GetSemanticModel(tree); string code = tree.GetText().ToString(); int position = code.IndexOf(textToSearchFor, StringComparison.Ordinal); var node = tree.GetCompilationUnitRoot().FindToken(position).Parent.FirstAncestorOrSelf<TNode>(); var sym = model.GetSymbolInfo(node).Symbol as IMethodSymbol; Assert.NotNull(sym); Assert.Equal(MethodKind.AnonymousFunction, sym.MethodKind); var nodes = CheckDeclaringSyntaxNodesWithoutGetDeclaredSymbol(comp, sym, 1, node.Kind()); Assert.Equal(nodes[0].GetSyntax(), node); foreach (IParameterSymbol p in sym.Parameters) { CheckDeclaringSyntaxNodes(comp, p, 1); } } [Theory, MemberData(nameof(FileScopedOrBracedNamespace))] public void SourceNamedTypeDeclaringSyntax(string ob, string cb) { var text = @" namespace N1 " + ob + @" class C1<T> { class Nested<U> {} delegate int NestedDel(string s); } public struct S1 { C1<int> f; } internal interface I1 {} enum E1 { Red } delegate void D1(int i); " + cb + @" "; var comp = (Compilation)CreateCompilation(text); var global = comp.GlobalNamespace; var n1 = global.GetMembers("N1").Single() as INamespaceSymbol; Assert.False(n1.IsImplicitlyDeclared); Assert.True(comp.SourceModule.GlobalNamespace.IsImplicitlyDeclared); var types = n1.GetTypeMembers(); foreach (ISymbol s in types) { CheckDeclaringSyntaxNodes(comp, s, 1); } var c1 = n1.GetTypeMembers("C1").Single() as INamedTypeSymbol; var s1 = n1.GetTypeMembers("S1").Single() as INamedTypeSymbol; var f = s1.GetMembers("f").Single() as IFieldSymbol; CheckDeclaringSyntaxNodes(comp, f.Type, 1); // constructed type C1<int>. // Nested types. foreach (ISymbol s in c1.GetTypeMembers()) { CheckDeclaringSyntaxNodes(comp, s, 1); } } [Fact] public void NonSourceTypeDeclaringSyntax() { var text = @" namespace N1 { class C1 { object o; int i; System.Collections.Generic.List<string> lst; dynamic dyn; C1[] arr; C1[,] arr2d; ErrType err; ConsErrType<object> consErr; } } "; var comp = (Compilation)CreateCompilation(text); var global = comp.GlobalNamespace; var n1 = global.GetMembers("N1").Single() as INamespaceSymbol; var c1 = n1.GetTypeMembers("C1").Single() as INamedTypeSymbol; // Check types of each field in C1; should not have declaring syntax node. foreach (IFieldSymbol f in c1.GetMembers().OfType<IFieldSymbol>()) { CheckDeclaringSyntaxNodes(comp, f.Type, 0); } } [Fact] public void AnonTypeDeclaringSyntax() { var text = @" class C1 { void f() { var a1 = new { a = 5, b = ""hi"" }; var a2 = new {}; } } "; var tree = Parse(text); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var global = comp.GlobalNamespace; int posA1 = text.IndexOf("a1", StringComparison.Ordinal); var declaratorA1 = tree.GetCompilationUnitRoot().FindToken(posA1).Parent.FirstAncestorOrSelf<VariableDeclaratorSyntax>(); var localA1 = (ILocalSymbol)model.GetDeclaredSymbol(declaratorA1); var localA1Type = localA1.Type; Assert.True(localA1Type.IsAnonymousType); // Anonymous types don't support GetDeclaredSymbol. CheckDeclaringSyntaxNodesWithoutGetDeclaredSymbol(comp, localA1Type, 1, SyntaxKind.AnonymousObjectCreationExpression); // Check members of the anonymous type. foreach (ISymbol memb in localA1Type.GetMembers()) { int expectedDeclaringNodes = 0; if (memb is IPropertySymbol) { expectedDeclaringNodes = 1; // declared property } CheckDeclaringSyntaxNodes(comp, memb, expectedDeclaringNodes); } } [WorkItem(543829, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543829")] [Fact] public void AnonymousTypeSymbolWithExplicitNew() { var text = @" class C1 { void f() { var q = new { y = 2 }; var x = new { y = 5 }; var z = x; } } "; var tree = Parse(text); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var global = comp.GlobalNamespace; // check 'q' int posQ = text.IndexOf('q'); var declaratorQ = tree.GetCompilationUnitRoot().FindToken(posQ).Parent.FirstAncestorOrSelf<VariableDeclaratorSyntax>(); CheckAnonymousType(model, (ILocalSymbol)model.GetDeclaredSymbol(declaratorQ), (AnonymousObjectCreationExpressionSyntax)declaratorQ.Initializer.Value); // check 'x' int posX = text.IndexOf('x'); var declaratorX = tree.GetCompilationUnitRoot().FindToken(posX).Parent.FirstAncestorOrSelf<VariableDeclaratorSyntax>(); CheckAnonymousType(model, (ILocalSymbol)model.GetDeclaredSymbol(declaratorX), (AnonymousObjectCreationExpressionSyntax)declaratorX.Initializer.Value); // check 'z' --> 'x' int posZ = text.IndexOf('z'); var declaratorZ = tree.GetCompilationUnitRoot().FindToken(posZ).Parent.FirstAncestorOrSelf<VariableDeclaratorSyntax>(); CheckAnonymousType(model, (ILocalSymbol)model.GetDeclaredSymbol(declaratorZ), (AnonymousObjectCreationExpressionSyntax)declaratorX.Initializer.Value); } private void CheckAnonymousType(SemanticModel model, ILocalSymbol local, AnonymousObjectCreationExpressionSyntax anonObjectCreation) { var localType = local.Type; Assert.True(localType.IsAnonymousType); // IsImplicitlyDeclared: Return false. The new { } clause // serves as the declaration. Assert.False(localType.IsImplicitlyDeclared); // DeclaringSyntaxNodes: Return the AnonymousObjectCreationExpression from the particular // anonymous type definition that flowed to this usage. AssertDeclaringSyntaxNodes(((CSharp.Symbols.PublicModel.Symbol)localType).UnderlyingSymbol, (CSharpCompilation)model.Compilation, anonObjectCreation); // SemanticModel.GetDeclaredSymbol: Return this symbol when applied to the // AnonymousObjectCreationExpression in the new { } declaration. var symbol = model.GetDeclaredSymbol(anonObjectCreation); Assert.NotNull(symbol); Assert.Equal<ISymbol>(localType, symbol); Assert.Same(localType.DeclaringSyntaxReferences[0].GetSyntax(), symbol.DeclaringSyntaxReferences[0].GetSyntax()); // Locations: Return the Span of that particular // AnonymousObjectCreationExpression's NewKeyword. Assert.Equal(1, localType.Locations.Length); Assert.Equal(localType.Locations[0], anonObjectCreation.NewKeyword.GetLocation()); // Members check int propIndex = 0; foreach (var member in localType.GetMembers()) { if (member.Kind == SymbolKind.Property) { // Equals: Return true when comparing same-named members of // structurally-equivalent anonymous type symbols. var members = symbol.GetMembers(member.Name); Assert.Equal(1, members.Length); Assert.Equal(member, members[0]); // IsImplicitlyDeclared: Return false. The goo = bar clause in // the new { } clause serves as the declaration. Assert.False(member.IsImplicitlyDeclared); // DeclaringSyntaxNodes: Return the AnonymousObjectMemberDeclarator from the // particular property definition that flowed to this usage. var propertyInitializer = anonObjectCreation.Initializers[propIndex]; Assert.Equal(1, member.DeclaringSyntaxReferences.Length); Assert.Same(propertyInitializer, member.DeclaringSyntaxReferences[0].GetSyntax()); // SemanticModel.GetDeclaredSymbol: Return this symbol when applied to its new { } // declaration's AnonymousObjectMemberDeclarator. var propSymbol = model.GetDeclaredSymbol(propertyInitializer); Assert.Equal<ISymbol>(member, propSymbol); Assert.Same(propertyInitializer, propSymbol.DeclaringSyntaxReferences[0].GetSyntax()); // Locations: Return the Span of that particular // AnonymousObjectMemberDeclarator's IdentifierToken. Assert.Equal(1, member.Locations.Length); Assert.Equal(member.Locations[0], propertyInitializer.NameEquals.Name.GetLocation()); propIndex++; } } } [Fact] public void NamespaceDeclaringSyntax() { var text = @" namespace N1 { namespace N2 { namespace N3 {} } } namespace N1.N2 { namespace N3 {} } namespace System {} "; var comp = (Compilation)CreateCompilation(text); var global = comp.GlobalNamespace; var system = global.GetMembers("System").Single() as INamespaceSymbol; var n1 = global.GetMembers("N1").Single() as INamespaceSymbol; var n2 = n1.GetMembers("N2").Single() as INamespaceSymbol; var n3 = n2.GetMembers("N3").Single() as INamespaceSymbol; CheckDeclaringSyntaxNodes(comp, n2, 2); CheckDeclaringSyntaxNodes(comp, n3, 2); CheckDeclaringSyntaxNodes(comp, system, 1); // Can't use GetDeclaredSymbol for N1 or global. CheckDeclaringSyntaxNodesWithoutGetDeclaredSymbol(comp, n1, 2, SyntaxKind.NamespaceDeclaration); CheckDeclaringSyntaxNodesWithoutGetDeclaredSymbol(comp, global, 1, SyntaxKind.CompilationUnit); } [Theory, MemberData(nameof(FileScopedOrBracedNamespace))] public void TypeParameterDeclaringSyntax(string ob, string cb) { var text = @" using System; using System.Collections.Generic; namespace N1 " + ob + @" class C1<T, U> { class C2<W> { public C1<int, string>.C2<W> f1; public void m<R, S>(); } class C3<W> { IEnumerable<U> f2; Goo<Bar> f3; } } class M { } " + cb + @" "; var comp = (Compilation)CreateCompilation(text); var global = comp.GlobalNamespace; var n1 = global.GetMembers("N1").Single() as INamespaceSymbol; var c1 = n1.GetTypeMembers("C1").Single() as INamedTypeSymbol; var c2 = c1.GetTypeMembers("C2").Single() as INamedTypeSymbol; var c3 = c1.GetTypeMembers("C3").Single() as INamedTypeSymbol; foreach (ISymbol s in c1.TypeParameters) { CheckDeclaringSyntaxNodes(comp, s, 1); } foreach (IFieldSymbol f in c2.GetMembers().OfType<IFieldSymbol>()) { foreach (ITypeParameterSymbol tp in ((INamedTypeSymbol)f.Type).TypeParameters) { CheckDeclaringSyntaxNodes(comp, tp, 1); } } foreach (IMethodSymbol m in c2.GetMembers().OfType<IMethodSymbol>()) { foreach (ITypeParameterSymbol tp in m.TypeParameters) { CheckDeclaringSyntaxNodes(comp, tp, 1); } } foreach (IFieldSymbol f in c3.GetMembers().OfType<IFieldSymbol>()) { foreach (ITypeParameterSymbol tp in ((INamedTypeSymbol)f.Type).TypeParameters) { CheckDeclaringSyntaxNodes(comp, tp, 0); } } } [Fact] public void MemberDeclaringSyntax() { var text = @" using System; using System.Collections.Generic; namespace N1 { enum E1 {Red, Blue = 5, Green }; class C1<T> { C1<int> t, w, x; const int q = 4, r = 7; C1(int i) {} static C1() {} int m(T t, int y = 3) { return 3; } int P {get { return 0; } set {}} abstract int Prop2 {get; set; } int Prop3 {get; set; } string this[int i] {get { return ""; } set {}} abstract string this[int i, int j] {get; set;} event EventHandler ev1; event EventHandler ev2 { add {} remove {} } } class C2<U> { static int x = 7; } } "; var comp = (Compilation)CreateCompilation(text); var global = comp.GlobalNamespace; var n1 = global.GetMembers("N1").Single() as INamespaceSymbol; var c1 = n1.GetTypeMembers("C1").Single() as INamedTypeSymbol; var c2 = n1.GetTypeMembers("C2").Single() as INamedTypeSymbol; var e1 = n1.GetTypeMembers("E1").Single() as INamedTypeSymbol; foreach (ISymbol memb in e1.GetMembers()) { if (memb.Kind == SymbolKind.Method && ((IMethodSymbol)memb).MethodKind == MethodKind.Constructor) CheckDeclaringSyntaxNodesIncludingParameters(comp, memb, 0); // implicit constructor else CheckDeclaringSyntaxNodesIncludingParameters(comp, memb, 1); } var ev1 = c1.GetMembers("ev1").Single() as IEventSymbol; var prop3 = c1.GetMembers("Prop3").Single() as IPropertySymbol; foreach (ISymbol memb in c1.GetMembers()) { int expectedDeclaringNodes = 1; if (memb is IMethodSymbol) { var meth = (IMethodSymbol)memb; if (meth.AssociatedSymbol != null && meth.AssociatedSymbol.OriginalDefinition.Equals(ev1)) expectedDeclaringNodes = 0; // implicit accessor. } if (memb is IFieldSymbol) { var fld = (IFieldSymbol)memb; if (fld.AssociatedSymbol != null && fld.AssociatedSymbol.OriginalDefinition.Equals(prop3)) expectedDeclaringNodes = 0; // auto-prop backing field. } CheckDeclaringSyntaxNodesIncludingParameters(comp, memb, expectedDeclaringNodes); } var fieldT = c1.GetMembers("t").Single() as IFieldSymbol; var constructedC1 = fieldT.Type; foreach (ISymbol memb in constructedC1.GetMembers()) { int expectedDeclaringNodes = 1; if (memb is IMethodSymbol) { var meth = (IMethodSymbol)memb; if (meth.AssociatedSymbol != null && meth.AssociatedSymbol.OriginalDefinition.Equals(ev1)) expectedDeclaringNodes = 0; // implicit accessor. } if (memb is IFieldSymbol) { var fld = (IFieldSymbol)memb; if (fld.AssociatedSymbol != null && fld.AssociatedSymbol.OriginalDefinition.Equals(prop3)) expectedDeclaringNodes = 0; // auto-prop backing field. } CheckDeclaringSyntaxNodesIncludingParameters(comp, memb, expectedDeclaringNodes); } foreach (ISymbol memb in c2.GetMembers()) { if (memb.Kind == SymbolKind.Method) CheckDeclaringSyntaxNodesIncludingParameters(comp, memb, 0); } } [Fact] public void LocalDeclaringSyntax() { var text = @" using System; using System.Collections.Generic; class C1 { void m() { int loc1, loc2 = 4, loc3; const int loc4 = 6, loc5 = 7; using (IDisposable loc6 = goo()) {} for (int loc7 = 0; loc7 < 10; ++loc7) {} foreach (int loc8 in new int[] {1,3,4}) {} } } "; var tree = Parse(text); var comp = CreateCompilation(tree); CheckDeclaringSyntax<VariableDeclaratorSyntax>(comp, tree, "loc1", SymbolKind.Local); CheckDeclaringSyntax<VariableDeclaratorSyntax>(comp, tree, "loc2", SymbolKind.Local); CheckDeclaringSyntax<VariableDeclaratorSyntax>(comp, tree, "loc3", SymbolKind.Local); CheckDeclaringSyntax<VariableDeclaratorSyntax>(comp, tree, "loc4", SymbolKind.Local); CheckDeclaringSyntax<VariableDeclaratorSyntax>(comp, tree, "loc5", SymbolKind.Local); CheckDeclaringSyntax<VariableDeclaratorSyntax>(comp, tree, "loc6", SymbolKind.Local); CheckDeclaringSyntax<VariableDeclaratorSyntax>(comp, tree, "loc7", SymbolKind.Local); CheckDeclaringSyntax<ForEachStatementSyntax>(comp, tree, "loc8", SymbolKind.Local); } [Fact] public void LabelDeclaringSyntax() { var text = @" using System; using System.Collections.Generic; class C1 { void m(int i) { lab1: ; lab2: lab3: Console.WriteLine(); switch (i) { case 4: case 3: break; default: break; } } } "; var tree = Parse(text); var comp = CreateCompilation(tree); CheckDeclaringSyntax<LabeledStatementSyntax>(comp, tree, "lab1", SymbolKind.Label); CheckDeclaringSyntax<LabeledStatementSyntax>(comp, tree, "lab2", SymbolKind.Label); CheckDeclaringSyntax<LabeledStatementSyntax>(comp, tree, "lab3", SymbolKind.Label); CheckDeclaringSyntax<SwitchLabelSyntax>(comp, tree, "case 4:", SymbolKind.Label); CheckDeclaringSyntax<SwitchLabelSyntax>(comp, tree, "case 3:", SymbolKind.Label); CheckDeclaringSyntax<SwitchLabelSyntax>(comp, tree, "default", SymbolKind.Label); } [Fact] public void AliasDeclaringSyntax() { var text = @" using System; using System.Collections.Generic; using ConsoleAlias=System.Console; using ListOfIntAlias=System.Collections.Generic.List<int>; namespace N1 { using GooAlias=Con; } "; var tree = Parse(text); var comp = CreateCompilation(tree); CheckDeclaringSyntax<UsingDirectiveSyntax>(comp, tree, "ConsoleAlias", SymbolKind.Alias); CheckDeclaringSyntax<UsingDirectiveSyntax>(comp, tree, "ListOfIntAlias", SymbolKind.Alias); CheckDeclaringSyntax<UsingDirectiveSyntax>(comp, tree, "GooAlias", SymbolKind.Alias); } [Fact] public void RangeVariableDeclaringSyntax() { var text = @" using System; using System.Collections.Generic; using System.Linq; class C { void f() { IEnumerable<int> a = null; var y1 = from range1 in a let range2 = a.ToString() select range1 into range3 select range3 + 1; var y2 = from range4 in a join range5 in a on range4.ToString() equals range5.ToString() into range6 select range6; } } "; var tree = Parse(text); var comp = CreateCompilation(tree); CheckDeclaringSyntax<QueryClauseSyntax>(comp, tree, "range1", SymbolKind.RangeVariable); CheckDeclaringSyntax<QueryClauseSyntax>(comp, tree, "range2", SymbolKind.RangeVariable); CheckDeclaringSyntax<QueryContinuationSyntax>(comp, tree, "range3", SymbolKind.RangeVariable); CheckDeclaringSyntax<QueryClauseSyntax>(comp, tree, "range4", SymbolKind.RangeVariable); CheckDeclaringSyntax<QueryClauseSyntax>(comp, tree, "range5", SymbolKind.RangeVariable); CheckDeclaringSyntax<JoinIntoClauseSyntax>(comp, tree, "range6", SymbolKind.RangeVariable); } [Fact] public void LambdaDeclaringSyntax() { var text = @" using System; using System.Collections.Generic; using System.Linq; class C { void f() { Func<int, int, int> f1 = (a,b) => /*1*/ a + b; Func<int, int, int> f1 = a => /*2*/ a + 1; Func<int, int, int> f1 = delegate(int a, int b) /*3*/ { return a + b; }; } } "; var tree = Parse(text); var comp = CreateCompilation(tree); CheckLambdaDeclaringSyntax<ParenthesizedLambdaExpressionSyntax>(comp, tree, "/*1*/"); CheckLambdaDeclaringSyntax<SimpleLambdaExpressionSyntax>(comp, tree, "/*2*/"); CheckLambdaDeclaringSyntax<AnonymousMethodExpressionSyntax>(comp, tree, "/*3*/"); } /// <summary> /// Symbol location order should be preserved when trees /// are replaced in the compilation. /// </summary> [WorkItem(11015, "https://github.com/dotnet/roslyn/issues/11015")] [Fact] public void PreserveLocationOrderOnReplaceSyntaxTree() { var source0 = Parse("namespace N { partial class C { } } namespace N0 { } class C0 { }"); var source1 = Parse("namespace N { partial class C { } } namespace N1 { } class C1 { }"); var source2 = Parse("namespace N { struct S { } }"); var source3 = Parse("namespace N { partial class C { } } namespace N3 { } class C3 { }"); var comp0 = CreateCompilation(new[] { source0, source1, source2, source3 }); comp0.VerifyDiagnostics(); Assert.Equal(new[] { source0, source1, source2, source3 }, comp0.SyntaxTrees); // Location order of partial class should match SyntaxTrees order. var locations = comp0.GetMember<NamedTypeSymbol>("N.C").Locations; Assert.Equal(new[] { source0, source1, source3 }, locations.Select(l => l.SourceTree)); // AddSyntaxTrees will add to the end. var source4 = Parse("namespace N { partial class C { } } namespace N4 { } class C4 { }"); var comp1 = comp0.AddSyntaxTrees(source4); locations = comp1.GetMember<NamedTypeSymbol>("N.C").Locations; Assert.Equal(new[] { source0, source1, source3, source4 }, locations.Select(l => l.SourceTree)); // ReplaceSyntaxTree should preserve location order. var comp2 = comp0.ReplaceSyntaxTree(source1, source4); locations = comp2.GetMember<NamedTypeSymbol>("N.C").Locations; Assert.Equal(new[] { source0, source4, source3 }, locations.Select(l => l.SourceTree)); // NamespaceNames and TypeNames do not match SyntaxTrees order. // This is expected. Assert.Equal(new[] { "", "N3", "N0", "N", "", "N4", "N" }, comp2.Declarations.NamespaceNames.ToArray()); Assert.Equal(new[] { "C3", "C0", "S", "C", "C4", "C" }, comp2.Declarations.TypeNames.ToArray()); // RemoveSyntaxTrees should preserve order of remaining trees. var comp3 = comp2.RemoveSyntaxTrees(source0); locations = comp3.GetMember<NamedTypeSymbol>("N.C").Locations; Assert.Equal(new[] { source4, source3 }, locations.Select(l => l.SourceTree)); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Text; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Symbols.Source { public class DeclaringSyntaxNodeTests : CSharpTestBase { // Check that the given symbol has the expected number of declaring syntax nodes. // and that each declared node goes back to the given symbol. private ImmutableArray<SyntaxReference> CheckDeclaringSyntaxNodes(Compilation compilation, ISymbol symbol, int expectedNumber) { var declaringReferences = symbol.DeclaringSyntaxReferences; Assert.Equal(expectedNumber, declaringReferences.Length); if (expectedNumber == 0) { Assert.True(!symbol.GetSymbol().IsFromCompilation((CSharpCompilation)compilation) || symbol.IsImplicitlyDeclared, "non-implicitly declares source symbol should have declaring location"); } else { Assert.True(symbol.GetSymbol().IsFromCompilation((CSharpCompilation)compilation) || symbol.GetSymbol() is MergedNamespaceSymbol, "symbol with declaration should be in source, except for merged namespaces"); Assert.False(symbol.IsImplicitlyDeclared); foreach (var node in declaringReferences.Select(d => d.GetSyntax())) { // Make sure GetDeclaredSymbol gets back to the symbol for each node. SyntaxTree tree = node.SyntaxTree; SemanticModel model = compilation.GetSemanticModel(tree); Assert.Equal(symbol.OriginalDefinition, model.GetDeclaredSymbol(node)); } } return declaringReferences; } private ImmutableArray<SyntaxReference> CheckDeclaringSyntaxNodesIncludingParameters(Compilation compilation, ISymbol symbol, int expectedNumber) { var nodes = CheckDeclaringSyntaxNodes(compilation, symbol, expectedNumber); var meth = symbol as IMethodSymbol; if (meth != null) { foreach (IParameterSymbol p in meth.Parameters) CheckDeclaringSyntaxNodes(compilation, p, meth.GetSymbol().IsAccessor() ? 0 : expectedNumber); } var prop = symbol as IPropertySymbol; if (prop != null) { foreach (IParameterSymbol p in prop.Parameters) CheckDeclaringSyntaxNodes(compilation, p, expectedNumber); } return nodes; } // Check that the given symbol has the expected number of declaring syntax nodes. // and that the syntax has the expected kind. Does NOT test GetDeclaringSymbol private ImmutableArray<SyntaxReference> CheckDeclaringSyntaxNodesWithoutGetDeclaredSymbol(Compilation compilation, ISymbol symbol, int expectedNumber, SyntaxKind expectedSyntaxKind) { var declaringReferences = symbol.DeclaringSyntaxReferences; Assert.Equal(expectedNumber, declaringReferences.Length); if (expectedNumber == 0) { Assert.True(!symbol.GetSymbol().IsFromCompilation((CSharpCompilation)compilation) || symbol.IsImplicitlyDeclared, "non-implicitly declares source symbol should have declaring location"); } else { Assert.True(symbol.GetSymbol().IsFromCompilation((CSharpCompilation)compilation) || symbol.GetSymbol() is MergedNamespaceSymbol, "symbol with declaration should be in source, except for merged namespaces"); if (symbol.Kind == SymbolKind.Namespace && ((INamespaceSymbol)symbol).IsGlobalNamespace) { Assert.True(symbol.IsImplicitlyDeclared); } else { Assert.False(symbol.IsImplicitlyDeclared); } foreach (var node in declaringReferences.Select(d => d.GetSyntax())) { // Make sure each node is of the expected kind. Assert.Equal(expectedSyntaxKind, node.Kind()); } } return declaringReferences; } private void AssertDeclaringSyntaxNodes(Symbol symbol, CSharpCompilation compilation, params SyntaxNode[] expectedSyntaxNodes) { int expectedNumber = expectedSyntaxNodes.Length; var declaringReferences = symbol.DeclaringSyntaxReferences; Assert.Equal(expectedNumber, declaringReferences.Length); if (expectedNumber == 0) { Assert.True(!symbol.IsFromCompilation(compilation) || symbol.IsImplicitlyDeclared, "non-implicitly declares source symbol should have declaring location"); } else { Assert.True(symbol.IsFromCompilation(compilation) || symbol is MergedNamespaceSymbol, "symbol with declaration should be in source, except for merged namespaces"); Assert.False(symbol.IsImplicitlyDeclared); for (int i = 0; i < expectedNumber; i++) { Assert.Same(expectedSyntaxNodes[i], declaringReferences[i].GetSyntax()); } } } private void CheckDeclaringSyntax<TNode>(CSharpCompilation comp, SyntaxTree tree, string name, SymbolKind kind) where TNode : CSharpSyntaxNode { var model = comp.GetSemanticModel(tree); string code = tree.GetText().ToString(); int position = code.IndexOf(name, StringComparison.Ordinal); var node = tree.GetRoot().FindToken(position).Parent.FirstAncestorOrSelf<TNode>(); var sym = model.GetDeclaredSymbol(node); Assert.Equal(kind, sym.Kind); Assert.Equal(name, sym.Name); CheckDeclaringSyntaxNodes(comp, sym, 1); } private void CheckLambdaDeclaringSyntax<TNode>(CSharpCompilation comp, SyntaxTree tree, string textToSearchFor) where TNode : ExpressionSyntax { var model = comp.GetSemanticModel(tree); string code = tree.GetText().ToString(); int position = code.IndexOf(textToSearchFor, StringComparison.Ordinal); var node = tree.GetCompilationUnitRoot().FindToken(position).Parent.FirstAncestorOrSelf<TNode>(); var sym = model.GetSymbolInfo(node).Symbol as IMethodSymbol; Assert.NotNull(sym); Assert.Equal(MethodKind.AnonymousFunction, sym.MethodKind); var nodes = CheckDeclaringSyntaxNodesWithoutGetDeclaredSymbol(comp, sym, 1, node.Kind()); Assert.Equal(nodes[0].GetSyntax(), node); foreach (IParameterSymbol p in sym.Parameters) { CheckDeclaringSyntaxNodes(comp, p, 1); } } [Theory, MemberData(nameof(FileScopedOrBracedNamespace))] public void SourceNamedTypeDeclaringSyntax(string ob, string cb) { var text = @" namespace N1 " + ob + @" class C1<T> { class Nested<U> {} delegate int NestedDel(string s); } public struct S1 { C1<int> f; } internal interface I1 {} enum E1 { Red } delegate void D1(int i); " + cb + @" "; var comp = (Compilation)CreateCompilation(text); var global = comp.GlobalNamespace; var n1 = global.GetMembers("N1").Single() as INamespaceSymbol; Assert.False(n1.IsImplicitlyDeclared); Assert.True(comp.SourceModule.GlobalNamespace.IsImplicitlyDeclared); var types = n1.GetTypeMembers(); foreach (ISymbol s in types) { CheckDeclaringSyntaxNodes(comp, s, 1); } var c1 = n1.GetTypeMembers("C1").Single() as INamedTypeSymbol; var s1 = n1.GetTypeMembers("S1").Single() as INamedTypeSymbol; var f = s1.GetMembers("f").Single() as IFieldSymbol; CheckDeclaringSyntaxNodes(comp, f.Type, 1); // constructed type C1<int>. // Nested types. foreach (ISymbol s in c1.GetTypeMembers()) { CheckDeclaringSyntaxNodes(comp, s, 1); } } [Fact] public void NonSourceTypeDeclaringSyntax() { var text = @" namespace N1 { class C1 { object o; int i; System.Collections.Generic.List<string> lst; dynamic dyn; C1[] arr; C1[,] arr2d; ErrType err; ConsErrType<object> consErr; } } "; var comp = (Compilation)CreateCompilation(text); var global = comp.GlobalNamespace; var n1 = global.GetMembers("N1").Single() as INamespaceSymbol; var c1 = n1.GetTypeMembers("C1").Single() as INamedTypeSymbol; // Check types of each field in C1; should not have declaring syntax node. foreach (IFieldSymbol f in c1.GetMembers().OfType<IFieldSymbol>()) { CheckDeclaringSyntaxNodes(comp, f.Type, 0); } } [Fact] public void AnonTypeDeclaringSyntax() { var text = @" class C1 { void f() { var a1 = new { a = 5, b = ""hi"" }; var a2 = new {}; } } "; var tree = Parse(text); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var global = comp.GlobalNamespace; int posA1 = text.IndexOf("a1", StringComparison.Ordinal); var declaratorA1 = tree.GetCompilationUnitRoot().FindToken(posA1).Parent.FirstAncestorOrSelf<VariableDeclaratorSyntax>(); var localA1 = (ILocalSymbol)model.GetDeclaredSymbol(declaratorA1); var localA1Type = localA1.Type; Assert.True(localA1Type.IsAnonymousType); // Anonymous types don't support GetDeclaredSymbol. CheckDeclaringSyntaxNodesWithoutGetDeclaredSymbol(comp, localA1Type, 1, SyntaxKind.AnonymousObjectCreationExpression); // Check members of the anonymous type. foreach (ISymbol memb in localA1Type.GetMembers()) { int expectedDeclaringNodes = 0; if (memb is IPropertySymbol) { expectedDeclaringNodes = 1; // declared property } CheckDeclaringSyntaxNodes(comp, memb, expectedDeclaringNodes); } } [WorkItem(543829, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543829")] [Fact] public void AnonymousTypeSymbolWithExplicitNew() { var text = @" class C1 { void f() { var q = new { y = 2 }; var x = new { y = 5 }; var z = x; } } "; var tree = Parse(text); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var global = comp.GlobalNamespace; // check 'q' int posQ = text.IndexOf('q'); var declaratorQ = tree.GetCompilationUnitRoot().FindToken(posQ).Parent.FirstAncestorOrSelf<VariableDeclaratorSyntax>(); CheckAnonymousType(model, (ILocalSymbol)model.GetDeclaredSymbol(declaratorQ), (AnonymousObjectCreationExpressionSyntax)declaratorQ.Initializer.Value); // check 'x' int posX = text.IndexOf('x'); var declaratorX = tree.GetCompilationUnitRoot().FindToken(posX).Parent.FirstAncestorOrSelf<VariableDeclaratorSyntax>(); CheckAnonymousType(model, (ILocalSymbol)model.GetDeclaredSymbol(declaratorX), (AnonymousObjectCreationExpressionSyntax)declaratorX.Initializer.Value); // check 'z' --> 'x' int posZ = text.IndexOf('z'); var declaratorZ = tree.GetCompilationUnitRoot().FindToken(posZ).Parent.FirstAncestorOrSelf<VariableDeclaratorSyntax>(); CheckAnonymousType(model, (ILocalSymbol)model.GetDeclaredSymbol(declaratorZ), (AnonymousObjectCreationExpressionSyntax)declaratorX.Initializer.Value); } private void CheckAnonymousType(SemanticModel model, ILocalSymbol local, AnonymousObjectCreationExpressionSyntax anonObjectCreation) { var localType = local.Type; Assert.True(localType.IsAnonymousType); // IsImplicitlyDeclared: Return false. The new { } clause // serves as the declaration. Assert.False(localType.IsImplicitlyDeclared); // DeclaringSyntaxNodes: Return the AnonymousObjectCreationExpression from the particular // anonymous type definition that flowed to this usage. AssertDeclaringSyntaxNodes(((CSharp.Symbols.PublicModel.Symbol)localType).UnderlyingSymbol, (CSharpCompilation)model.Compilation, anonObjectCreation); // SemanticModel.GetDeclaredSymbol: Return this symbol when applied to the // AnonymousObjectCreationExpression in the new { } declaration. var symbol = model.GetDeclaredSymbol(anonObjectCreation); Assert.NotNull(symbol); Assert.Equal<ISymbol>(localType, symbol); Assert.Same(localType.DeclaringSyntaxReferences[0].GetSyntax(), symbol.DeclaringSyntaxReferences[0].GetSyntax()); // Locations: Return the Span of that particular // AnonymousObjectCreationExpression's NewKeyword. Assert.Equal(1, localType.Locations.Length); Assert.Equal(localType.Locations[0], anonObjectCreation.NewKeyword.GetLocation()); // Members check int propIndex = 0; foreach (var member in localType.GetMembers()) { if (member.Kind == SymbolKind.Property) { // Equals: Return true when comparing same-named members of // structurally-equivalent anonymous type symbols. var members = symbol.GetMembers(member.Name); Assert.Equal(1, members.Length); Assert.Equal(member, members[0]); // IsImplicitlyDeclared: Return false. The goo = bar clause in // the new { } clause serves as the declaration. Assert.False(member.IsImplicitlyDeclared); // DeclaringSyntaxNodes: Return the AnonymousObjectMemberDeclarator from the // particular property definition that flowed to this usage. var propertyInitializer = anonObjectCreation.Initializers[propIndex]; Assert.Equal(1, member.DeclaringSyntaxReferences.Length); Assert.Same(propertyInitializer, member.DeclaringSyntaxReferences[0].GetSyntax()); // SemanticModel.GetDeclaredSymbol: Return this symbol when applied to its new { } // declaration's AnonymousObjectMemberDeclarator. var propSymbol = model.GetDeclaredSymbol(propertyInitializer); Assert.Equal<ISymbol>(member, propSymbol); Assert.Same(propertyInitializer, propSymbol.DeclaringSyntaxReferences[0].GetSyntax()); // Locations: Return the Span of that particular // AnonymousObjectMemberDeclarator's IdentifierToken. Assert.Equal(1, member.Locations.Length); Assert.Equal(member.Locations[0], propertyInitializer.NameEquals.Name.GetLocation()); propIndex++; } } } [Fact] public void NamespaceDeclaringSyntax() { var text = @" namespace N1 { namespace N2 { namespace N3 {} } } namespace N1.N2 { namespace N3 {} } namespace System {} "; var comp = (Compilation)CreateCompilation(text); var global = comp.GlobalNamespace; var system = global.GetMembers("System").Single() as INamespaceSymbol; var n1 = global.GetMembers("N1").Single() as INamespaceSymbol; var n2 = n1.GetMembers("N2").Single() as INamespaceSymbol; var n3 = n2.GetMembers("N3").Single() as INamespaceSymbol; CheckDeclaringSyntaxNodes(comp, n2, 2); CheckDeclaringSyntaxNodes(comp, n3, 2); CheckDeclaringSyntaxNodes(comp, system, 1); // Can't use GetDeclaredSymbol for N1 or global. CheckDeclaringSyntaxNodesWithoutGetDeclaredSymbol(comp, n1, 2, SyntaxKind.NamespaceDeclaration); CheckDeclaringSyntaxNodesWithoutGetDeclaredSymbol(comp, global, 1, SyntaxKind.CompilationUnit); } [Theory, MemberData(nameof(FileScopedOrBracedNamespace))] public void TypeParameterDeclaringSyntax(string ob, string cb) { var text = @" using System; using System.Collections.Generic; namespace N1 " + ob + @" class C1<T, U> { class C2<W> { public C1<int, string>.C2<W> f1; public void m<R, S>(); } class C3<W> { IEnumerable<U> f2; Goo<Bar> f3; } } class M { } " + cb + @" "; var comp = (Compilation)CreateCompilation(text); var global = comp.GlobalNamespace; var n1 = global.GetMembers("N1").Single() as INamespaceSymbol; var c1 = n1.GetTypeMembers("C1").Single() as INamedTypeSymbol; var c2 = c1.GetTypeMembers("C2").Single() as INamedTypeSymbol; var c3 = c1.GetTypeMembers("C3").Single() as INamedTypeSymbol; foreach (ISymbol s in c1.TypeParameters) { CheckDeclaringSyntaxNodes(comp, s, 1); } foreach (IFieldSymbol f in c2.GetMembers().OfType<IFieldSymbol>()) { foreach (ITypeParameterSymbol tp in ((INamedTypeSymbol)f.Type).TypeParameters) { CheckDeclaringSyntaxNodes(comp, tp, 1); } } foreach (IMethodSymbol m in c2.GetMembers().OfType<IMethodSymbol>()) { foreach (ITypeParameterSymbol tp in m.TypeParameters) { CheckDeclaringSyntaxNodes(comp, tp, 1); } } foreach (IFieldSymbol f in c3.GetMembers().OfType<IFieldSymbol>()) { foreach (ITypeParameterSymbol tp in ((INamedTypeSymbol)f.Type).TypeParameters) { CheckDeclaringSyntaxNodes(comp, tp, 0); } } } [Fact] public void MemberDeclaringSyntax() { var text = @" using System; using System.Collections.Generic; namespace N1 { enum E1 {Red, Blue = 5, Green }; class C1<T> { C1<int> t, w, x; const int q = 4, r = 7; C1(int i) {} static C1() {} int m(T t, int y = 3) { return 3; } int P {get { return 0; } set {}} abstract int Prop2 {get; set; } int Prop3 {get; set; } string this[int i] {get { return ""; } set {}} abstract string this[int i, int j] {get; set;} event EventHandler ev1; event EventHandler ev2 { add {} remove {} } } class C2<U> { static int x = 7; } } "; var comp = (Compilation)CreateCompilation(text); var global = comp.GlobalNamespace; var n1 = global.GetMembers("N1").Single() as INamespaceSymbol; var c1 = n1.GetTypeMembers("C1").Single() as INamedTypeSymbol; var c2 = n1.GetTypeMembers("C2").Single() as INamedTypeSymbol; var e1 = n1.GetTypeMembers("E1").Single() as INamedTypeSymbol; foreach (ISymbol memb in e1.GetMembers()) { if (memb.Kind == SymbolKind.Method && ((IMethodSymbol)memb).MethodKind == MethodKind.Constructor) CheckDeclaringSyntaxNodesIncludingParameters(comp, memb, 0); // implicit constructor else CheckDeclaringSyntaxNodesIncludingParameters(comp, memb, 1); } var ev1 = c1.GetMembers("ev1").Single() as IEventSymbol; var prop3 = c1.GetMembers("Prop3").Single() as IPropertySymbol; foreach (ISymbol memb in c1.GetMembers()) { int expectedDeclaringNodes = 1; if (memb is IMethodSymbol) { var meth = (IMethodSymbol)memb; if (meth.AssociatedSymbol != null && meth.AssociatedSymbol.OriginalDefinition.Equals(ev1)) expectedDeclaringNodes = 0; // implicit accessor. } if (memb is IFieldSymbol) { var fld = (IFieldSymbol)memb; if (fld.AssociatedSymbol != null && fld.AssociatedSymbol.OriginalDefinition.Equals(prop3)) expectedDeclaringNodes = 0; // auto-prop backing field. } CheckDeclaringSyntaxNodesIncludingParameters(comp, memb, expectedDeclaringNodes); } var fieldT = c1.GetMembers("t").Single() as IFieldSymbol; var constructedC1 = fieldT.Type; foreach (ISymbol memb in constructedC1.GetMembers()) { int expectedDeclaringNodes = 1; if (memb is IMethodSymbol) { var meth = (IMethodSymbol)memb; if (meth.AssociatedSymbol != null && meth.AssociatedSymbol.OriginalDefinition.Equals(ev1)) expectedDeclaringNodes = 0; // implicit accessor. } if (memb is IFieldSymbol) { var fld = (IFieldSymbol)memb; if (fld.AssociatedSymbol != null && fld.AssociatedSymbol.OriginalDefinition.Equals(prop3)) expectedDeclaringNodes = 0; // auto-prop backing field. } CheckDeclaringSyntaxNodesIncludingParameters(comp, memb, expectedDeclaringNodes); } foreach (ISymbol memb in c2.GetMembers()) { if (memb.Kind == SymbolKind.Method) CheckDeclaringSyntaxNodesIncludingParameters(comp, memb, 0); } } [Fact] public void LocalDeclaringSyntax() { var text = @" using System; using System.Collections.Generic; class C1 { void m() { int loc1, loc2 = 4, loc3; const int loc4 = 6, loc5 = 7; using (IDisposable loc6 = goo()) {} for (int loc7 = 0; loc7 < 10; ++loc7) {} foreach (int loc8 in new int[] {1,3,4}) {} } } "; var tree = Parse(text); var comp = CreateCompilation(tree); CheckDeclaringSyntax<VariableDeclaratorSyntax>(comp, tree, "loc1", SymbolKind.Local); CheckDeclaringSyntax<VariableDeclaratorSyntax>(comp, tree, "loc2", SymbolKind.Local); CheckDeclaringSyntax<VariableDeclaratorSyntax>(comp, tree, "loc3", SymbolKind.Local); CheckDeclaringSyntax<VariableDeclaratorSyntax>(comp, tree, "loc4", SymbolKind.Local); CheckDeclaringSyntax<VariableDeclaratorSyntax>(comp, tree, "loc5", SymbolKind.Local); CheckDeclaringSyntax<VariableDeclaratorSyntax>(comp, tree, "loc6", SymbolKind.Local); CheckDeclaringSyntax<VariableDeclaratorSyntax>(comp, tree, "loc7", SymbolKind.Local); CheckDeclaringSyntax<ForEachStatementSyntax>(comp, tree, "loc8", SymbolKind.Local); } [Fact] public void LabelDeclaringSyntax() { var text = @" using System; using System.Collections.Generic; class C1 { void m(int i) { lab1: ; lab2: lab3: Console.WriteLine(); switch (i) { case 4: case 3: break; default: break; } } } "; var tree = Parse(text); var comp = CreateCompilation(tree); CheckDeclaringSyntax<LabeledStatementSyntax>(comp, tree, "lab1", SymbolKind.Label); CheckDeclaringSyntax<LabeledStatementSyntax>(comp, tree, "lab2", SymbolKind.Label); CheckDeclaringSyntax<LabeledStatementSyntax>(comp, tree, "lab3", SymbolKind.Label); CheckDeclaringSyntax<SwitchLabelSyntax>(comp, tree, "case 4:", SymbolKind.Label); CheckDeclaringSyntax<SwitchLabelSyntax>(comp, tree, "case 3:", SymbolKind.Label); CheckDeclaringSyntax<SwitchLabelSyntax>(comp, tree, "default", SymbolKind.Label); } [Fact] public void AliasDeclaringSyntax() { var text = @" using System; using System.Collections.Generic; using ConsoleAlias=System.Console; using ListOfIntAlias=System.Collections.Generic.List<int>; namespace N1 { using GooAlias=Con; } "; var tree = Parse(text); var comp = CreateCompilation(tree); CheckDeclaringSyntax<UsingDirectiveSyntax>(comp, tree, "ConsoleAlias", SymbolKind.Alias); CheckDeclaringSyntax<UsingDirectiveSyntax>(comp, tree, "ListOfIntAlias", SymbolKind.Alias); CheckDeclaringSyntax<UsingDirectiveSyntax>(comp, tree, "GooAlias", SymbolKind.Alias); } [Fact] public void RangeVariableDeclaringSyntax() { var text = @" using System; using System.Collections.Generic; using System.Linq; class C { void f() { IEnumerable<int> a = null; var y1 = from range1 in a let range2 = a.ToString() select range1 into range3 select range3 + 1; var y2 = from range4 in a join range5 in a on range4.ToString() equals range5.ToString() into range6 select range6; } } "; var tree = Parse(text); var comp = CreateCompilation(tree); CheckDeclaringSyntax<QueryClauseSyntax>(comp, tree, "range1", SymbolKind.RangeVariable); CheckDeclaringSyntax<QueryClauseSyntax>(comp, tree, "range2", SymbolKind.RangeVariable); CheckDeclaringSyntax<QueryContinuationSyntax>(comp, tree, "range3", SymbolKind.RangeVariable); CheckDeclaringSyntax<QueryClauseSyntax>(comp, tree, "range4", SymbolKind.RangeVariable); CheckDeclaringSyntax<QueryClauseSyntax>(comp, tree, "range5", SymbolKind.RangeVariable); CheckDeclaringSyntax<JoinIntoClauseSyntax>(comp, tree, "range6", SymbolKind.RangeVariable); } [Fact] public void LambdaDeclaringSyntax() { var text = @" using System; using System.Collections.Generic; using System.Linq; class C { void f() { Func<int, int, int> f1 = (a,b) => /*1*/ a + b; Func<int, int, int> f1 = a => /*2*/ a + 1; Func<int, int, int> f1 = delegate(int a, int b) /*3*/ { return a + b; }; } } "; var tree = Parse(text); var comp = CreateCompilation(tree); CheckLambdaDeclaringSyntax<ParenthesizedLambdaExpressionSyntax>(comp, tree, "/*1*/"); CheckLambdaDeclaringSyntax<SimpleLambdaExpressionSyntax>(comp, tree, "/*2*/"); CheckLambdaDeclaringSyntax<AnonymousMethodExpressionSyntax>(comp, tree, "/*3*/"); } /// <summary> /// Symbol location order should be preserved when trees /// are replaced in the compilation. /// </summary> [WorkItem(11015, "https://github.com/dotnet/roslyn/issues/11015")] [Fact] public void PreserveLocationOrderOnReplaceSyntaxTree() { var source0 = Parse("namespace N { partial class C { } } namespace N0 { } class C0 { }"); var source1 = Parse("namespace N { partial class C { } } namespace N1 { } class C1 { }"); var source2 = Parse("namespace N { struct S { } }"); var source3 = Parse("namespace N { partial class C { } } namespace N3 { } class C3 { }"); var comp0 = CreateCompilation(new[] { source0, source1, source2, source3 }); comp0.VerifyDiagnostics(); Assert.Equal(new[] { source0, source1, source2, source3 }, comp0.SyntaxTrees); // Location order of partial class should match SyntaxTrees order. var locations = comp0.GetMember<NamedTypeSymbol>("N.C").Locations; Assert.Equal(new[] { source0, source1, source3 }, locations.Select(l => l.SourceTree)); // AddSyntaxTrees will add to the end. var source4 = Parse("namespace N { partial class C { } } namespace N4 { } class C4 { }"); var comp1 = comp0.AddSyntaxTrees(source4); locations = comp1.GetMember<NamedTypeSymbol>("N.C").Locations; Assert.Equal(new[] { source0, source1, source3, source4 }, locations.Select(l => l.SourceTree)); // ReplaceSyntaxTree should preserve location order. var comp2 = comp0.ReplaceSyntaxTree(source1, source4); locations = comp2.GetMember<NamedTypeSymbol>("N.C").Locations; Assert.Equal(new[] { source0, source4, source3 }, locations.Select(l => l.SourceTree)); // NamespaceNames and TypeNames do not match SyntaxTrees order. // This is expected. Assert.Equal(new[] { "", "N3", "N0", "N", "", "N4", "N" }, comp2.Declarations.NamespaceNames.ToArray()); Assert.Equal(new[] { "C3", "C0", "S", "C", "C4", "C" }, comp2.Declarations.TypeNames.ToArray()); // RemoveSyntaxTrees should preserve order of remaining trees. var comp3 = comp2.RemoveSyntaxTrees(source0); locations = comp3.GetMember<NamedTypeSymbol>("N.C").Locations; Assert.Equal(new[] { source4, source3 }, locations.Select(l => l.SourceTree)); } } }
-1
dotnet/roslyn
55,256
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-30T00:02:02Z
2021-07-30T09:17:54Z
6ce9c0048d37026337701fac035ac0745f6fe49f
88b59775dc6375635957ef229116460f290072aa
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/EditorFeatures/TestUtilities/Squiggles/TestDiagnosticTagProducer.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.Implementation.Diagnostics; using Microsoft.CodeAnalysis.Editor.UnitTests.Diagnostics; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.Text.Shared.Extensions; using Microsoft.VisualStudio.Text.Tagging; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.UnitTests.Squiggles { internal sealed class TestDiagnosticTagProducer<TProvider> where TProvider : AbstractDiagnosticsAdornmentTaggerProvider<IErrorTag> { internal static Task<(ImmutableArray<DiagnosticData>, ImmutableArray<ITagSpan<IErrorTag>>)> GetDiagnosticsAndErrorSpans( TestWorkspace workspace, IReadOnlyDictionary<string, ImmutableArray<DiagnosticAnalyzer>> analyzerMap = null) { return SquiggleUtilities.GetDiagnosticsAndErrorSpansAsync<TProvider>(workspace, analyzerMap); } internal static async Task<IList<ITagSpan<IErrorTag>>> GetErrorsFromUpdateSource(TestWorkspace workspace, DiagnosticsUpdatedArgs updateArgs) { var source = new TestDiagnosticUpdateSource(workspace); using (var wrapper = new DiagnosticTaggerWrapper<TProvider, IErrorTag>(workspace, updateSource: source)) { var tagger = wrapper.TaggerProvider.CreateTagger<IErrorTag>(workspace.Documents.First().GetTextBuffer()); using (var disposable = tagger as IDisposable) { source.RaiseDiagnosticsUpdated(updateArgs); await wrapper.WaitForTags(); var snapshot = workspace.Documents.First().GetTextBuffer().CurrentSnapshot; var spans = tagger.GetTags(snapshot.GetSnapshotSpanCollection()).ToImmutableArray(); return spans; } } } internal static DiagnosticData CreateDiagnosticData(TestHostDocument document, TextSpan span) { return new DiagnosticData( id: "test", category: "test", message: "test", enuMessageForBingSearch: "test", severity: DiagnosticSeverity.Error, defaultSeverity: DiagnosticSeverity.Error, isEnabledByDefault: true, warningLevel: 0, projectId: document.Project.Id, customTags: ImmutableArray<string>.Empty, properties: ImmutableDictionary<string, string>.Empty, location: new DiagnosticDataLocation(document.Id, span), language: document.Project.Language); } private class TestDiagnosticUpdateSource : IDiagnosticUpdateSource { private ImmutableArray<DiagnosticData> _diagnostics = ImmutableArray<DiagnosticData>.Empty; private readonly Workspace _workspace; public TestDiagnosticUpdateSource(Workspace workspace) => _workspace = workspace; public void RaiseDiagnosticsUpdated(DiagnosticsUpdatedArgs args) { _diagnostics = args.GetPushDiagnostics(_workspace, InternalDiagnosticsOptions.NormalDiagnosticMode); DiagnosticsUpdated?.Invoke(this, args); } public event EventHandler<DiagnosticsUpdatedArgs> DiagnosticsUpdated; public event EventHandler DiagnosticsCleared { add { } remove { } } public bool SupportGetDiagnostics => false; public ValueTask<ImmutableArray<DiagnosticData>> GetDiagnosticsAsync(Workspace workspace, ProjectId projectId, DocumentId documentId, object id, bool includeSuppressedDiagnostics = false, CancellationToken cancellationToken = default) => new(includeSuppressedDiagnostics ? _diagnostics : _diagnostics.WhereAsArray(d => !d.IsSuppressed)); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.Implementation.Diagnostics; using Microsoft.CodeAnalysis.Editor.UnitTests.Diagnostics; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.Text.Shared.Extensions; using Microsoft.VisualStudio.Text.Tagging; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.UnitTests.Squiggles { internal sealed class TestDiagnosticTagProducer<TProvider> where TProvider : AbstractDiagnosticsAdornmentTaggerProvider<IErrorTag> { internal static Task<(ImmutableArray<DiagnosticData>, ImmutableArray<ITagSpan<IErrorTag>>)> GetDiagnosticsAndErrorSpans( TestWorkspace workspace, IReadOnlyDictionary<string, ImmutableArray<DiagnosticAnalyzer>> analyzerMap = null) { return SquiggleUtilities.GetDiagnosticsAndErrorSpansAsync<TProvider>(workspace, analyzerMap); } internal static async Task<IList<ITagSpan<IErrorTag>>> GetErrorsFromUpdateSource(TestWorkspace workspace, DiagnosticsUpdatedArgs updateArgs) { var source = new TestDiagnosticUpdateSource(workspace); using (var wrapper = new DiagnosticTaggerWrapper<TProvider, IErrorTag>(workspace, updateSource: source)) { var tagger = wrapper.TaggerProvider.CreateTagger<IErrorTag>(workspace.Documents.First().GetTextBuffer()); using (var disposable = tagger as IDisposable) { source.RaiseDiagnosticsUpdated(updateArgs); await wrapper.WaitForTags(); var snapshot = workspace.Documents.First().GetTextBuffer().CurrentSnapshot; var spans = tagger.GetTags(snapshot.GetSnapshotSpanCollection()).ToImmutableArray(); return spans; } } } internal static DiagnosticData CreateDiagnosticData(TestHostDocument document, TextSpan span) { return new DiagnosticData( id: "test", category: "test", message: "test", enuMessageForBingSearch: "test", severity: DiagnosticSeverity.Error, defaultSeverity: DiagnosticSeverity.Error, isEnabledByDefault: true, warningLevel: 0, projectId: document.Project.Id, customTags: ImmutableArray<string>.Empty, properties: ImmutableDictionary<string, string>.Empty, location: new DiagnosticDataLocation(document.Id, span), language: document.Project.Language); } private class TestDiagnosticUpdateSource : IDiagnosticUpdateSource { private ImmutableArray<DiagnosticData> _diagnostics = ImmutableArray<DiagnosticData>.Empty; private readonly Workspace _workspace; public TestDiagnosticUpdateSource(Workspace workspace) => _workspace = workspace; public void RaiseDiagnosticsUpdated(DiagnosticsUpdatedArgs args) { _diagnostics = args.GetPushDiagnostics(_workspace, InternalDiagnosticsOptions.NormalDiagnosticMode); DiagnosticsUpdated?.Invoke(this, args); } public event EventHandler<DiagnosticsUpdatedArgs> DiagnosticsUpdated; public event EventHandler DiagnosticsCleared { add { } remove { } } public bool SupportGetDiagnostics => false; public ValueTask<ImmutableArray<DiagnosticData>> GetDiagnosticsAsync(Workspace workspace, ProjectId projectId, DocumentId documentId, object id, bool includeSuppressedDiagnostics = false, CancellationToken cancellationToken = default) => new(includeSuppressedDiagnostics ? _diagnostics : _diagnostics.WhereAsArray(d => !d.IsSuppressed)); } } }
-1
dotnet/roslyn
55,256
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-30T00:02:02Z
2021-07-30T09:17:54Z
6ce9c0048d37026337701fac035ac0745f6fe49f
88b59775dc6375635957ef229116460f290072aa
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Compilers/Core/Portable/MetadataReference/MetadataReferenceProperties.cs
// Licensed to the .NET Foundation under one or more agreements. // 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.Linq; using System.Collections.Generic; using System.Collections.Immutable; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { /// <summary> /// Information about a metadata reference. /// </summary> public struct MetadataReferenceProperties : IEquatable<MetadataReferenceProperties> { private readonly MetadataImageKind _kind; private readonly ImmutableArray<string> _aliases; private readonly bool _embedInteropTypes; /// <summary> /// Default properties for a module reference. /// </summary> public static MetadataReferenceProperties Module => new MetadataReferenceProperties(MetadataImageKind.Module); /// <summary> /// Default properties for an assembly reference. /// </summary> public static MetadataReferenceProperties Assembly => new MetadataReferenceProperties(MetadataImageKind.Assembly); /// <summary> /// Initializes reference properties. /// </summary> /// <param name="kind">The image kind - assembly or module.</param> /// <param name="aliases">Assembly aliases. Can't be set for a module.</param> /// <param name="embedInteropTypes">True to embed interop types from the referenced assembly to the referencing compilation. Must be false for a module.</param> public MetadataReferenceProperties(MetadataImageKind kind = MetadataImageKind.Assembly, ImmutableArray<string> aliases = default, bool embedInteropTypes = false) { if (!kind.IsValid()) { throw new ArgumentOutOfRangeException(nameof(kind)); } if (kind == MetadataImageKind.Module) { if (embedInteropTypes) { throw new ArgumentException(CodeAnalysisResources.CannotEmbedInteropTypesFromModule, nameof(embedInteropTypes)); } if (!aliases.IsDefaultOrEmpty) { throw new ArgumentException(CodeAnalysisResources.CannotAliasModule, nameof(aliases)); } } if (!aliases.IsDefaultOrEmpty) { foreach (var alias in aliases) { if (!alias.IsValidClrTypeName()) { throw new ArgumentException(CodeAnalysisResources.InvalidAlias, nameof(aliases)); } } } _kind = kind; _aliases = aliases; _embedInteropTypes = embedInteropTypes; HasRecursiveAliases = false; } internal MetadataReferenceProperties(MetadataImageKind kind, ImmutableArray<string> aliases, bool embedInteropTypes, bool hasRecursiveAliases) : this(kind, aliases, embedInteropTypes) { HasRecursiveAliases = hasRecursiveAliases; } /// <summary> /// Returns <see cref="MetadataReferenceProperties"/> with specified aliases. /// </summary> /// <exception cref="ArgumentException"> /// <see cref="Kind"/> is <see cref="MetadataImageKind.Module"/>, as modules can't be aliased. /// </exception> public MetadataReferenceProperties WithAliases(IEnumerable<string> aliases) { return WithAliases(aliases.AsImmutableOrEmpty()); } /// <summary> /// Returns <see cref="MetadataReferenceProperties"/> with specified aliases. /// </summary> /// <exception cref="ArgumentException"> /// <see cref="Kind"/> is <see cref="MetadataImageKind.Module"/>, as modules can't be aliased. /// </exception> public MetadataReferenceProperties WithAliases(ImmutableArray<string> aliases) { return new MetadataReferenceProperties(_kind, aliases, _embedInteropTypes, HasRecursiveAliases); } /// <summary> /// Returns <see cref="MetadataReferenceProperties"/> with <see cref="EmbedInteropTypes"/> set to specified value. /// </summary> /// <exception cref="ArgumentException"><see cref="Kind"/> is <see cref="MetadataImageKind.Module"/>, as interop types can't be embedded from modules.</exception> public MetadataReferenceProperties WithEmbedInteropTypes(bool embedInteropTypes) { return new MetadataReferenceProperties(_kind, _aliases, embedInteropTypes, HasRecursiveAliases); } /// <summary> /// Returns <see cref="MetadataReferenceProperties"/> with <see cref="HasRecursiveAliases"/> set to specified value. /// </summary> internal MetadataReferenceProperties WithRecursiveAliases(bool value) { return new MetadataReferenceProperties(_kind, _aliases, _embedInteropTypes, value); } /// <summary> /// The image kind (assembly or module) the reference refers to. /// </summary> public MetadataImageKind Kind => _kind; /// <summary> /// Alias that represents a global declaration space. /// </summary> /// <remarks> /// Namespaces in references whose <see cref="Aliases"/> contain <see cref="GlobalAlias"/> are available in global declaration space. /// </remarks> public static string GlobalAlias => "global"; /// <summary> /// Aliases for the metadata reference. Empty if the reference has no aliases. /// </summary> /// <remarks> /// In C# these aliases can be used in "extern alias" syntax to disambiguate type names. /// </remarks> public ImmutableArray<string> Aliases { get { // Simplify usage - we can't avoid the _aliases field being null but we can always return empty array here: return _aliases.NullToEmpty(); } } /// <summary> /// True if interop types defined in the referenced metadata should be embedded into the compilation referencing the metadata. /// </summary> public bool EmbedInteropTypes => _embedInteropTypes; /// <summary> /// True to apply <see cref="Aliases"/> recursively on the target assembly and on all its transitive dependencies. /// False to apply <see cref="Aliases"/> only on the target assembly. /// </summary> internal bool HasRecursiveAliases { get; private set; } public override bool Equals(object? obj) { return obj is MetadataReferenceProperties && Equals((MetadataReferenceProperties)obj); } public bool Equals(MetadataReferenceProperties other) { return Aliases.SequenceEqual(other.Aliases) && _embedInteropTypes == other._embedInteropTypes && _kind == other._kind && HasRecursiveAliases == other.HasRecursiveAliases; } public override int GetHashCode() { return Hash.Combine(Hash.CombineValues(Aliases), Hash.Combine(_embedInteropTypes, Hash.Combine(HasRecursiveAliases, _kind.GetHashCode()))); } public static bool operator ==(MetadataReferenceProperties left, MetadataReferenceProperties right) { return left.Equals(right); } public static bool operator !=(MetadataReferenceProperties left, MetadataReferenceProperties right) { return !left.Equals(right); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Linq; using System.Collections.Generic; using System.Collections.Immutable; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { /// <summary> /// Information about a metadata reference. /// </summary> public struct MetadataReferenceProperties : IEquatable<MetadataReferenceProperties> { private readonly MetadataImageKind _kind; private readonly ImmutableArray<string> _aliases; private readonly bool _embedInteropTypes; /// <summary> /// Default properties for a module reference. /// </summary> public static MetadataReferenceProperties Module => new MetadataReferenceProperties(MetadataImageKind.Module); /// <summary> /// Default properties for an assembly reference. /// </summary> public static MetadataReferenceProperties Assembly => new MetadataReferenceProperties(MetadataImageKind.Assembly); /// <summary> /// Initializes reference properties. /// </summary> /// <param name="kind">The image kind - assembly or module.</param> /// <param name="aliases">Assembly aliases. Can't be set for a module.</param> /// <param name="embedInteropTypes">True to embed interop types from the referenced assembly to the referencing compilation. Must be false for a module.</param> public MetadataReferenceProperties(MetadataImageKind kind = MetadataImageKind.Assembly, ImmutableArray<string> aliases = default, bool embedInteropTypes = false) { if (!kind.IsValid()) { throw new ArgumentOutOfRangeException(nameof(kind)); } if (kind == MetadataImageKind.Module) { if (embedInteropTypes) { throw new ArgumentException(CodeAnalysisResources.CannotEmbedInteropTypesFromModule, nameof(embedInteropTypes)); } if (!aliases.IsDefaultOrEmpty) { throw new ArgumentException(CodeAnalysisResources.CannotAliasModule, nameof(aliases)); } } if (!aliases.IsDefaultOrEmpty) { foreach (var alias in aliases) { if (!alias.IsValidClrTypeName()) { throw new ArgumentException(CodeAnalysisResources.InvalidAlias, nameof(aliases)); } } } _kind = kind; _aliases = aliases; _embedInteropTypes = embedInteropTypes; HasRecursiveAliases = false; } internal MetadataReferenceProperties(MetadataImageKind kind, ImmutableArray<string> aliases, bool embedInteropTypes, bool hasRecursiveAliases) : this(kind, aliases, embedInteropTypes) { HasRecursiveAliases = hasRecursiveAliases; } /// <summary> /// Returns <see cref="MetadataReferenceProperties"/> with specified aliases. /// </summary> /// <exception cref="ArgumentException"> /// <see cref="Kind"/> is <see cref="MetadataImageKind.Module"/>, as modules can't be aliased. /// </exception> public MetadataReferenceProperties WithAliases(IEnumerable<string> aliases) { return WithAliases(aliases.AsImmutableOrEmpty()); } /// <summary> /// Returns <see cref="MetadataReferenceProperties"/> with specified aliases. /// </summary> /// <exception cref="ArgumentException"> /// <see cref="Kind"/> is <see cref="MetadataImageKind.Module"/>, as modules can't be aliased. /// </exception> public MetadataReferenceProperties WithAliases(ImmutableArray<string> aliases) { return new MetadataReferenceProperties(_kind, aliases, _embedInteropTypes, HasRecursiveAliases); } /// <summary> /// Returns <see cref="MetadataReferenceProperties"/> with <see cref="EmbedInteropTypes"/> set to specified value. /// </summary> /// <exception cref="ArgumentException"><see cref="Kind"/> is <see cref="MetadataImageKind.Module"/>, as interop types can't be embedded from modules.</exception> public MetadataReferenceProperties WithEmbedInteropTypes(bool embedInteropTypes) { return new MetadataReferenceProperties(_kind, _aliases, embedInteropTypes, HasRecursiveAliases); } /// <summary> /// Returns <see cref="MetadataReferenceProperties"/> with <see cref="HasRecursiveAliases"/> set to specified value. /// </summary> internal MetadataReferenceProperties WithRecursiveAliases(bool value) { return new MetadataReferenceProperties(_kind, _aliases, _embedInteropTypes, value); } /// <summary> /// The image kind (assembly or module) the reference refers to. /// </summary> public MetadataImageKind Kind => _kind; /// <summary> /// Alias that represents a global declaration space. /// </summary> /// <remarks> /// Namespaces in references whose <see cref="Aliases"/> contain <see cref="GlobalAlias"/> are available in global declaration space. /// </remarks> public static string GlobalAlias => "global"; /// <summary> /// Aliases for the metadata reference. Empty if the reference has no aliases. /// </summary> /// <remarks> /// In C# these aliases can be used in "extern alias" syntax to disambiguate type names. /// </remarks> public ImmutableArray<string> Aliases { get { // Simplify usage - we can't avoid the _aliases field being null but we can always return empty array here: return _aliases.NullToEmpty(); } } /// <summary> /// True if interop types defined in the referenced metadata should be embedded into the compilation referencing the metadata. /// </summary> public bool EmbedInteropTypes => _embedInteropTypes; /// <summary> /// True to apply <see cref="Aliases"/> recursively on the target assembly and on all its transitive dependencies. /// False to apply <see cref="Aliases"/> only on the target assembly. /// </summary> internal bool HasRecursiveAliases { get; private set; } public override bool Equals(object? obj) { return obj is MetadataReferenceProperties && Equals((MetadataReferenceProperties)obj); } public bool Equals(MetadataReferenceProperties other) { return Aliases.SequenceEqual(other.Aliases) && _embedInteropTypes == other._embedInteropTypes && _kind == other._kind && HasRecursiveAliases == other.HasRecursiveAliases; } public override int GetHashCode() { return Hash.Combine(Hash.CombineValues(Aliases), Hash.Combine(_embedInteropTypes, Hash.Combine(HasRecursiveAliases, _kind.GetHashCode()))); } public static bool operator ==(MetadataReferenceProperties left, MetadataReferenceProperties right) { return left.Equals(right); } public static bool operator !=(MetadataReferenceProperties left, MetadataReferenceProperties right) { return !left.Equals(right); } } }
-1
dotnet/roslyn
55,256
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-30T00:02:02Z
2021-07-30T09:17:54Z
6ce9c0048d37026337701fac035ac0745f6fe49f
88b59775dc6375635957ef229116460f290072aa
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Compilers/Test/Core/Compilation/DiagnosticBagErrorLogger.cs
// Licensed to the .NET Foundation under one or more agreements. // 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.Diagnostics; namespace Microsoft.CodeAnalysis.Test.Utilities { internal sealed class DiagnosticBagErrorLogger : ErrorLogger { internal readonly DiagnosticBag Diagnostics; internal DiagnosticBagErrorLogger(DiagnosticBag diagnostics) { Diagnostics = diagnostics; } public override void LogDiagnostic(Diagnostic diagnostic, SuppressionInfo? suppressionInfo) { Diagnostics.Add(diagnostic); } } }
// Licensed to the .NET Foundation under one or more agreements. // 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.Diagnostics; namespace Microsoft.CodeAnalysis.Test.Utilities { internal sealed class DiagnosticBagErrorLogger : ErrorLogger { internal readonly DiagnosticBag Diagnostics; internal DiagnosticBagErrorLogger(DiagnosticBag diagnostics) { Diagnostics = diagnostics; } public override void LogDiagnostic(Diagnostic diagnostic, SuppressionInfo? suppressionInfo) { Diagnostics.Add(diagnostic); } } }
-1
dotnet/roslyn
55,256
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-30T00:02:02Z
2021-07-30T09:17:54Z
6ce9c0048d37026337701fac035ac0745f6fe49f
88b59775dc6375635957ef229116460f290072aa
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/ExpressionEvaluator/Core/Source/FunctionResolver/VisualBasic/Keywords.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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; namespace Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator { internal sealed partial class MemberSignatureParser { // From SyntaxFacts.GetReservedKeywordKinds(). (See // VisualBasicParsingTests.Keywords() which verifies the lists are in sync.) private static ImmutableHashSet<string> GetKeywords(StringComparer comparer) { return ImmutableHashSet.CreateRange( comparer, new[] { "AddressOf", "AddHandler", "Alias", "And", "AndAlso", "As", "Boolean", "ByRef", "Byte", "ByVal", "Call", "Case", "Catch", "CBool", "CByte", "CChar", "CDate", "CDec", "CDbl", "Char", "CInt", "Class", "CLng", "CObj", "Const", "Continue", "CSByte", "CShort", "CSng", "CStr", "CType", "CUInt", "CULng", "CUShort", "Date", "Decimal", "Declare", "Default", "Delegate", "Dim", "DirectCast", "Do", "Double", "Each", "Else", "ElseIf", "End", "Enum", "Erase", "Error", "Event", "Exit", "False", "Finally", "For", "Friend", "Function", "Get", "GetType", "GetXmlNamespace", "Global", "GoTo", "Handles", "If", "Implements", "Imports", "In", "Inherits", "Integer", "Interface", "Is", "IsNot", "Let", "Lib", "Like", "Long", "Loop", "Me", "Mod", "Module", "MustInherit", "MustOverride", "MyBase", "MyClass", "NameOf", "Namespace", "Narrowing", "Next", "New", "Not", "Nothing", "NotInheritable", "NotOverridable", "Object", "Of", "On", "Operator", "Option", "Optional", "Or", "OrElse", "Overloads", "Overridable", "Overrides", "ParamArray", "Partial", "Private", "Property", "Protected", "Public", "RaiseEvent", "ReadOnly", "ReDim", "REM", "RemoveHandler", "Resume", "Return", "SByte", "Select", "Set", "Shadows", "Shared", "Short", "Single", "Static", "Step", "Stop", "String", "Structure", "Sub", "SyncLock", "Then", "Throw", "To", "True", "Try", "TryCast", "TypeOf", "UInteger", "ULong", "UShort", "Using", "When", "While", "Widening", "With", "WithEvents", "WriteOnly", "Xor", "EndIf", "Gosub", "Variant", "Wend", }); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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; namespace Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator { internal sealed partial class MemberSignatureParser { // From SyntaxFacts.GetReservedKeywordKinds(). (See // VisualBasicParsingTests.Keywords() which verifies the lists are in sync.) private static ImmutableHashSet<string> GetKeywords(StringComparer comparer) { return ImmutableHashSet.CreateRange( comparer, new[] { "AddressOf", "AddHandler", "Alias", "And", "AndAlso", "As", "Boolean", "ByRef", "Byte", "ByVal", "Call", "Case", "Catch", "CBool", "CByte", "CChar", "CDate", "CDec", "CDbl", "Char", "CInt", "Class", "CLng", "CObj", "Const", "Continue", "CSByte", "CShort", "CSng", "CStr", "CType", "CUInt", "CULng", "CUShort", "Date", "Decimal", "Declare", "Default", "Delegate", "Dim", "DirectCast", "Do", "Double", "Each", "Else", "ElseIf", "End", "Enum", "Erase", "Error", "Event", "Exit", "False", "Finally", "For", "Friend", "Function", "Get", "GetType", "GetXmlNamespace", "Global", "GoTo", "Handles", "If", "Implements", "Imports", "In", "Inherits", "Integer", "Interface", "Is", "IsNot", "Let", "Lib", "Like", "Long", "Loop", "Me", "Mod", "Module", "MustInherit", "MustOverride", "MyBase", "MyClass", "NameOf", "Namespace", "Narrowing", "Next", "New", "Not", "Nothing", "NotInheritable", "NotOverridable", "Object", "Of", "On", "Operator", "Option", "Optional", "Or", "OrElse", "Overloads", "Overridable", "Overrides", "ParamArray", "Partial", "Private", "Property", "Protected", "Public", "RaiseEvent", "ReadOnly", "ReDim", "REM", "RemoveHandler", "Resume", "Return", "SByte", "Select", "Set", "Shadows", "Shared", "Short", "Single", "Static", "Step", "Stop", "String", "Structure", "Sub", "SyncLock", "Then", "Throw", "To", "True", "Try", "TryCast", "TypeOf", "UInteger", "ULong", "UShort", "Using", "When", "While", "Widening", "With", "WithEvents", "WriteOnly", "Xor", "EndIf", "Gosub", "Variant", "Wend", }); } } }
-1
dotnet/roslyn
55,256
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-30T00:02:02Z
2021-07-30T09:17:54Z
6ce9c0048d37026337701fac035ac0745f6fe49f
88b59775dc6375635957ef229116460f290072aa
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/EditorFeatures/CSharpTest/ExtractClass/ExtractClassTests.cs
// Licensed to the .NET Foundation under one or more agreements. // 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.Linq; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.CodeRefactorings.ExtractClass; using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeRefactorings; using Microsoft.CodeAnalysis.ExtractClass; using Microsoft.CodeAnalysis.PullMemberUp; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.ExtractClass { public class ExtractClassTests : AbstractCSharpCodeActionTest { private Task TestExtractClassAsync( string input, string? expected = null, IEnumerable<(string name, bool makeAbstract)>? dialogSelection = null, bool sameFile = false, bool isClassDeclarationSelection = false, TestParameters testParameters = default) { var service = new TestExtractClassOptionsService(dialogSelection, sameFile, isClassDeclarationSelection); var parametersWithOptionsService = testParameters.WithFixProviderData(service); if (expected is null) { return TestMissingAsync(input, parametersWithOptionsService); } return TestInRegularAndScript1Async( input, expected, parameters: parametersWithOptionsService); } protected override CodeRefactoringProvider CreateCodeRefactoringProvider(Workspace workspace, TestParameters parameters) => new CSharpExtractClassCodeRefactoringProvider((IExtractClassOptionsService)parameters.fixProviderData); [Fact] public async Task TestSingleMethod() { var input = @" <Workspace> <Project Language=""C#""> <Document FilePath=""Test.cs""> class Test { int [||]Method() { return 1 + 1; } } </Document> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#""> <Document FilePath=""Test.cs""> class Test : MyBase { } </Document> <Document FilePath=""MyBase.cs"">internal class MyBase { int Method() { return 1 + 1; } }</Document> </Project> </Workspace>"; await TestExtractClassAsync(input, expected); } [Fact] public async Task TestErrorBaseMethod() { var input = @" <Workspace> <Project Language=""C#""> <Document FilePath=""Test.cs""> class Test : ErrorBase { int [||]Method() { return 1 + 1; } } </Document> </Project> </Workspace>"; await TestExtractClassAsync(input); } [Fact] public async Task TestMiscellaneousFiles() { var input = @" <Workspace> <Project Language=""C#""> <Document FilePath=""Test.cs""> class Test { int [||]Method() { return 1 + 1; } } </Document> </Project> </Workspace>"; TestParameters parameters = default; await TestExtractClassAsync(input, testParameters: parameters.WithWorkspaceKind(WorkspaceKind.MiscellaneousFiles)); } [Fact] public async Task TestPartialClass() { var input = @" <Workspace> <Project Language=""C#""> <Document FilePath=""Test.cs""> partial class Test { int [||]Method() { return 1 + 1; } } </Document> <Document FilePath=""Test.Other.cs""> partial class Test { int Method2() { return 5; } } </Document> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#""> <Document FilePath=""Test.cs""> partial class Test : MyBase { } </Document> <Document FilePath=""Test.Other.cs""> partial class Test { } </Document> <Document FilePath=""MyBase.cs"">internal class MyBase { int Method() { return 1 + 1; } int Method2() { return 5; } }</Document> </Project> </Workspace>"; await TestExtractClassAsync( input, expected, dialogSelection: MakeSelection("Method", "Method2")); } [Fact] public async Task TestInNamespace() { var input = @" <Workspace> <Project Language=""C#""> <Document FilePath=""Test.cs""> namespace MyNamespace { class Test { int [||]Method() { return 1 + 1; } } } </Document> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#""> <Document FilePath=""Test.cs""> namespace MyNamespace { class Test : MyBase { } } </Document> <Document FilePath=""MyBase.cs"">namespace MyNamespace { internal class MyBase { int Method() { return 1 + 1; } } }</Document> </Project> </Workspace>"; await TestExtractClassAsync(input, expected); } [Fact] public async Task TestInNamespace_FileScopedNamespace1() { var input = @" <Workspace> <Project Language=""C#"" LanguageVersion=""10""> <Document FilePath=""Test.cs""> namespace MyNamespace { class Test { int [||]Method() { return 1 + 1; } } } </Document> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" LanguageVersion=""10""> <Document FilePath=""Test.cs""> namespace MyNamespace { class Test : MyBase { } } </Document> <Document FilePath=""MyBase.cs"">namespace MyNamespace; internal class MyBase { int Method() { return 1 + 1; } }</Document> </Project> </Workspace>"; await TestAsync( input, expected, CSharpParseOptions.Default, options: Option(CSharpCodeStyleOptions.NamespaceDeclarations, NamespaceDeclarationPreference.FileScoped, NotificationOption2.Silent), fixProviderData: new TestExtractClassOptionsService()); } [Fact] public async Task TestInNamespace_FileScopedNamespace2() { var input = @" <Workspace> <Project Language=""C#"" LanguageVersion=""9""> <Document FilePath=""Test.cs""> namespace MyNamespace { class Test { int [||]Method() { return 1 + 1; } } } </Document> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" LanguageVersion=""9""> <Document FilePath=""Test.cs""> namespace MyNamespace { class Test : MyBase { } } </Document> <Document FilePath=""MyBase.cs"">namespace MyNamespace { internal class MyBase { int Method() { return 1 + 1; } } }</Document> </Project> </Workspace>"; await TestAsync( input, expected, CSharpParseOptions.Default, options: Option(CSharpCodeStyleOptions.NamespaceDeclarations, NamespaceDeclarationPreference.FileScoped, NotificationOption2.Silent), fixProviderData: new TestExtractClassOptionsService()); } [Fact] public async Task TestInNamespace_FileScopedNamespace3() { var input = @" <Workspace> <Project Language=""C#"" LanguageVersion=""10""> <Document FilePath=""Test.cs""> namespace MyNamespace { class Test { int [||]Method() { return 1 + 1; } } } </Document> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" LanguageVersion=""10""> <Document FilePath=""Test.cs""> namespace MyNamespace { class Test : MyBase { } } </Document> <Document FilePath=""MyBase.cs"">namespace MyNamespace { internal class MyBase { int Method() { return 1 + 1; } } }</Document> </Project> </Workspace>"; await TestAsync( input, expected, CSharpParseOptions.Default, options: Option(CSharpCodeStyleOptions.NamespaceDeclarations, NamespaceDeclarationPreference.BlockScoped, NotificationOption2.Silent), fixProviderData: new TestExtractClassOptionsService()); } [Fact] public async Task TestAccessibility() { var input = @" <Workspace> <Project Language=""C#""> <Document FilePath=""Test.cs""> public class Test { int [||]Method() { return 1 + 1; } } </Document> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#""> <Document FilePath=""Test.cs""> public class Test : MyBase { } </Document> <Document FilePath=""MyBase.cs"">public class MyBase { int Method() { return 1 + 1; } }</Document> </Project> </Workspace>"; await TestExtractClassAsync(input, expected); } [Fact] public async Task TestEvent() { var input = @" <Workspace> <Project Language=""C#""> <Document FilePath=""Test.cs""> using System; class Test { private event EventHandler [||]Event1; } </Document> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#""> <Document FilePath=""Test.cs""> using System; class Test : MyBase { } </Document> <Document FilePath=""MyBase.cs"">internal class MyBase { private event EventHandler Event1; }</Document> </Project> </Workspace>"; await TestExtractClassAsync(input, expected); } [Fact] public async Task TestProperty() { var input = @" <Workspace> <Project Language=""C#""> <Document FilePath=""Test.cs""> class Test { int [||]MyProperty { get; set; } } </Document> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#""> <Document FilePath=""Test.cs""> class Test : MyBase { } </Document> <Document FilePath=""MyBase.cs"">internal class MyBase { int MyProperty { get; set; } }</Document> </Project> </Workspace>"; await TestExtractClassAsync(input, expected); } [Fact] public async Task TestField() { var input = @" <Workspace> <Project Language=""C#""> <Document FilePath=""Test.cs""> class Test { int [||]MyField; } </Document> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#""> <Document FilePath=""Test.cs""> class Test : MyBase { } </Document> <Document FilePath=""MyBase.cs"">internal class MyBase { int MyField; }</Document> </Project> </Workspace>"; await TestExtractClassAsync(input, expected); } [Fact] public async Task TestFileHeader() { var input = @" <Workspace> <Project Language=""C#""> <Document FilePath=""Test.cs"">// this is my document header // that should be copied over class Test { int [||]Method() { return 1 + 1; } } </Document> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#""> <Document FilePath=""Test.cs"">// this is my document header // that should be copied over class Test : MyBase { } </Document> <Document FilePath=""MyBase.cs"">// this is my document header // that should be copied over internal class MyBase { int Method() { return 1 + 1; } }</Document> </Project> </Workspace>"; await TestExtractClassAsync(input, expected); } [Fact] public async Task TestWithInterface() { var input = @" <Workspace> <Project Language=""C#""> <Document FilePath=""Test.cs""> interface ITest { int Method(); } class Test : ITest { int [||]Method() { return 1 + 1; } } </Document> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#""> <Document FilePath=""Test.cs""> interface ITest { int Method(); } class Test : MyBase, ITest { } </Document> <Document FilePath=""MyBase.cs"">internal class MyBase { int Method() { return 1 + 1; } }</Document> </Project> </Workspace>"; await TestExtractClassAsync(input, expected); } [ConditionalFact(AlwaysSkip = "https://github.com/dotnet/roslyn/issues/45977")] public async Task TestRegion() { var input = @" <Workspace> <Project Language=""C#""> <Document FilePath=""Test.cs""> class Test { #region MyRegion int [||]Method() { return 1 + 1; } void OtherMethiod() { } #endregion } </Document> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#""> <Document FilePath=""Test.cs""> class Test : MyBase { #region MyRegion void OtherMethiod() { } #endregion } </Document> <Document FilePath=""MyBase.cs"">internal class MyBase { #region MyRegion int Method() { return 1 + 1; } #endregion }</Document> </Project> </Workspace>"; await TestExtractClassAsync( input, expected, dialogSelection: MakeSelection("Method")); } [Fact] public async Task TestMakeAbstract_SingleMethod() { var input = @" <Workspace> <Project Language=""C#""> <Document FilePath=""Test.cs""> class Test { int [||]Method() { return 1 + 1; } } </Document> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#""> <Document FilePath=""Test.cs""> class Test : MyBase { override int Method() { return 1 + 1; } } </Document> <Document FilePath=""MyBase.cs"">internal abstract class MyBase { private abstract global::System.Int32 Method(); }</Document> </Project> </Workspace>"; await TestExtractClassAsync( input, expected, dialogSelection: MakeAbstractSelection("Method")); } [Fact] public async Task TestMakeAbstract_MultipleMethods() { var input = @" <Workspace> <Project Language=""C#""> <Document FilePath=""Test.cs""> class Test { int [||]Method() { return 1 + 1; } int Method2() => 2; int Method3() => 3; } </Document> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#""> <Document FilePath=""Test.cs""> class Test : MyBase { override int Method() { return 1 + 1; } override int Method2() => 2; override int Method3() => 3; } </Document> <Document FilePath=""MyBase.cs"">internal abstract class MyBase { private abstract global::System.Int32 Method(); private abstract global::System.Int32 Method2(); private abstract global::System.Int32 Method3(); }</Document> </Project> </Workspace>"; await TestExtractClassAsync( input, expected, dialogSelection: MakeAbstractSelection("Method", "Method2", "Method3")); } [Fact] public async Task TestMultipleMethods() { var input = @" <Workspace> <Project Language=""C#""> <Document FilePath=""Test.cs""> class Test { int [||]Method() { return Method2() + 1; } int Method2() => 1; } </Document> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#""> <Document FilePath=""Test.cs""> class Test : MyBase { } </Document> <Document FilePath=""MyBase.cs"">internal class MyBase { int Method() { return Method2() + 1; } int Method2() => 1; }</Document> </Project> </Workspace>"; await TestExtractClassAsync( input, expected, dialogSelection: MakeSelection("Method", "Method2")); } [Fact] public async Task TestMultipleMethods_SomeSelected() { var input = @" <Workspace> <Project Language=""C#""> <Document FilePath=""Test.cs""> class Test { int [||]Method() { return Method2() + 1; } int Method2() => 1; } </Document> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#""> <Document FilePath=""Test.cs""> class Test : MyBase { int Method() { return Method2() + 1; } } </Document> <Document FilePath=""MyBase.cs"">internal class MyBase { int Method2() => 1; }</Document> </Project> </Workspace>"; await TestExtractClassAsync( input, expected, dialogSelection: MakeSelection("Method2")); } [Fact] public async Task TestSelection_CompleteMethodAndComments() { var input = @" <Workspace> <Project Language=""C#""> <Document FilePath=""Test.cs""> class Test { [|/// <summary> /// this is a test method /// </summary> int Method() { return 1 + 1; }|] } </Document> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#""> <Document FilePath=""Test.cs""> class Test : MyBase { } </Document> <Document FilePath=""MyBase.cs"">internal class MyBase { /// <summary> /// this is a test method /// </summary> int Method() { return 1 + 1; } }</Document> </Project> </Workspace>"; await TestExtractClassAsync(input, expected); } [Fact] public async Task TestSelection_PartialMethodAndComments() { var input = @" <Workspace> <Project Language=""C#""> <Document FilePath=""Test.cs""> class Test { [|/// <summary> /// this is a test method /// </summary> int Method() {|] return 1 + 1; } } </Document> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#""> <Document FilePath=""Test.cs""> class Test : MyBase { } </Document> <Document FilePath=""MyBase.cs"">internal class MyBase { /// <summary> /// this is a test method /// </summary> int Method() { return 1 + 1; } }</Document> </Project> </Workspace>"; await TestExtractClassAsync(input, expected); } [Fact] public async Task TestSelection_PartialMethodAndComments2() { var input = @" <Workspace> <Project Language=""C#""> <Document FilePath=""Test.cs""> class Test { /// <summary> /// [|this is a test method /// </summary> int Method() {|] return 1 + 1; } } </Document> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#""> <Document FilePath=""Test.cs""> class Test : MyBase { } </Document> <Document FilePath=""MyBase.cs"">internal class MyBase { /// <summary> /// this is a test method /// </summary> int Method() { return 1 + 1; } }</Document> </Project> </Workspace>"; await TestExtractClassAsync(input, expected); } [Fact] public async Task TestSelection_PartialMethodAndComments3() { var input = @" <Workspace> <Project Language=""C#""> <Document FilePath=""Test.cs""> class Test { /// <summary> /// [|this is a test method /// </summary> int Method()|] { return 1 + 1; } } </Document> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#""> <Document FilePath=""Test.cs""> class Test : MyBase { } </Document> <Document FilePath=""MyBase.cs"">internal class MyBase { /// <summary> /// this is a test method /// </summary> int Method() { return 1 + 1; } }</Document> </Project> </Workspace>"; await TestExtractClassAsync(input, expected); } [Fact] public async Task TestAttributes() { var input = @" <Workspace> <Project Language=""C#""> <Document FilePath=""Test.cs""> using System; class TestAttribute : Attribute { } class Test { /// <summary> /// this is a test method /// </summary> [||][TestAttribute] int Method() { return 1 + 1; } } </Document> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#""> <Document FilePath=""Test.cs""> using System; class TestAttribute : Attribute { } class Test : MyBase { } </Document> <Document FilePath=""MyBase.cs"">internal class MyBase { /// <summary> /// this is a test method /// </summary> [TestAttribute] int Method() { return 1 + 1; } }</Document> </Project> </Workspace>"; await TestExtractClassAsync(input, expected); } [Fact] public async Task TestAttributes2() { var input = @" <Workspace> <Project Language=""C#""> <Document FilePath=""Test.cs""> using System; class TestAttribute : Attribute { } class TestAttribute2 : Attribute { } class Test { /// <summary> /// this is a test method /// </summary> [||][TestAttribute] [TestAttribute2] int Method() { return 1 + 1; } } </Document> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#""> <Document FilePath=""Test.cs""> using System; class TestAttribute : Attribute { } class TestAttribute2 : Attribute { } class Test : MyBase { } </Document> <Document FilePath=""MyBase.cs"">internal class MyBase { /// <summary> /// this is a test method /// </summary> [TestAttribute] [TestAttribute2] int Method() { return 1 + 1; } }</Document> </Project> </Workspace>"; await TestExtractClassAsync(input, expected); } [ConditionalFact(AlwaysSkip = "https://github.com/dotnet/roslyn/issues/45987")] public async Task TestAttributes3() { var input = @" <Workspace> <Project Language=""C#""> <Document FilePath=""Test.cs""> using System; class TestAttribute : Attribute { } class TestAttribute2 : Attribute { } class Test { /// <summary> /// this is a test method /// </summary> [TestAttribute] [||][TestAttribute2] int Method() { return 1 + 1; } } </Document> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#""> <Document FilePath=""Test.cs""> using System; class TestAttribute : Attribute { } class Test : MyBase { } </Document> <Document FilePath=""MyBase.cs"">internal class MyBase { /// <summary> /// this is a test method /// </summary> [TestAttribute] [TestAttribute2] int Method() { return 1 + 1; } }</Document> </Project> </Workspace>"; await TestExtractClassAsync(input, expected); } [ConditionalFact(AlwaysSkip = "https://github.com/dotnet/roslyn/issues/45987")] public async Task TestAttributes4() { var input = @" <Workspace> <Project Language=""C#""> <Document FilePath=""Test.cs""> using System; class TestAttribute : Attribute { } class TestAttribute2 : Attribute { } class Test { /// <summary> /// this is a test method /// </summary> [TestAttribute] [TestAttribute2][||] int Method() { return 1 + 1; } } </Document> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#""> <Document FilePath=""Test.cs""> using System; class TestAttribute : Attribute { } class Test : MyBase { } </Document> <Document FilePath=""MyBase.cs"">internal class MyBase { /// <summary> /// this is a test method /// </summary> [TestAttribute] [TestAttribute2] int Method() { return 1 + 1; } }</Document> </Project> </Workspace>"; await TestExtractClassAsync(input, expected); } [Fact] public async Task TestSameFile() { var input = @" <Workspace> <Project Language=""C#""> <Document FilePath=""Test.cs""> class Test { void Method[||]() { } } </Document> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#""> <Document FilePath=""Test.cs""> internal class MyBase { void Method() { } } class Test : MyBase { } </Document> </Project> </Workspace>"; await TestExtractClassAsync(input, expected, sameFile: true); } [Fact] public async Task TestClassDeclaration() { var input = @" <Workspace> <Project Language=""C#""> <Document FilePath=""Test.cs""> class Test[||] { int Method() { return 1 + 1; } } </Document> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#""> <Document FilePath=""Test.cs""> class Test : MyBase { } </Document> <Document FilePath=""MyBase.cs"">internal class MyBase { int Method() { return 1 + 1; } }</Document> </Project> </Workspace>"; await TestExtractClassAsync(input, expected, isClassDeclarationSelection: true); } [Fact] public async Task TestClassDeclaration2() { var input = @" <Workspace> <Project Language=""C#""> <Document FilePath=""Test.cs""> class [||]Test { int Method() { return 1 + 1; } } </Document> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#""> <Document FilePath=""Test.cs""> class Test : MyBase { } </Document> <Document FilePath=""MyBase.cs"">internal class MyBase { int Method() { return 1 + 1; } }</Document> </Project> </Workspace>"; await TestExtractClassAsync(input, expected, isClassDeclarationSelection: true); } [Fact] public async Task TestClassDeclaration3() { var input = @" <Workspace> <Project Language=""C#""> <Document FilePath=""Test.cs""> [||]class Test { int Method() { return 1 + 1; } } </Document> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#""> <Document FilePath=""Test.cs""> class Test : MyBase { } </Document> <Document FilePath=""MyBase.cs"">internal class MyBase { int Method() { return 1 + 1; } }</Document> </Project> </Workspace>"; await TestExtractClassAsync(input, expected, isClassDeclarationSelection: true); } [Fact] public async Task TestClassDeclaration4() { var input = @" <Workspace> <Project Language=""C#""> <Document FilePath=""Test.cs""> class[||] Test { int Method() { return 1 + 1; } } </Document> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#""> <Document FilePath=""Test.cs""> class Test : MyBase { } </Document> <Document FilePath=""MyBase.cs"">internal class MyBase { int Method() { return 1 + 1; } }</Document> </Project> </Workspace>"; await TestExtractClassAsync(input, expected, isClassDeclarationSelection: true); } [Fact] public async Task TestClassDeclaration_Comment() { var input = @" <Workspace> <Project Language=""C#""> <Document FilePath=""Test.cs""> using System; /// <summary> /// [|This is a test class /// </summary> class Test|] { int Method() { return 1 + 1; } } </Document> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#""> <Document FilePath=""Test.cs""> using System; /// <summary> /// This is a test class /// </summary> class Test : MyBase { } </Document> <Document FilePath=""MyBase.cs"">internal class MyBase { int Method() { return 1 + 1; } }</Document> </Project> </Workspace>"; await TestExtractClassAsync(input, expected, isClassDeclarationSelection: true); } [Fact] public async Task TestClassDeclaration_Comment2() { var input = @" <Workspace> <Project Language=""C#""> <Document FilePath=""Test.cs""> using System; /// <summary> /// This is a test class /// [|</summary> class Test|] { int Method() { return 1 + 1; } } </Document> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#""> <Document FilePath=""Test.cs""> using System; /// <summary> /// This is a test class /// </summary> class Test : MyBase { } </Document> <Document FilePath=""MyBase.cs"">internal class MyBase { int Method() { return 1 + 1; } }</Document> </Project> </Workspace>"; await TestExtractClassAsync(input, expected, isClassDeclarationSelection: true); } [Fact] public async Task TestClassDeclaration_Comment3() { var input = @" <Workspace> <Project Language=""C#""> <Document FilePath=""Test.cs""> using System; /// <summary> /// This is a [|test class /// </summary> class|] Test { int Method() { return 1 + 1; } } </Document> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#""> <Document FilePath=""Test.cs""> using System; /// <summary> /// This is a test class /// </summary> class Test : MyBase { } </Document> <Document FilePath=""MyBase.cs"">internal class MyBase { int Method() { return 1 + 1; } }</Document> </Project> </Workspace>"; await TestExtractClassAsync(input, expected, isClassDeclarationSelection: true); } [Fact] public async Task TestClassDeclaration_Attribute() { var input = @" <Workspace> <Project Language=""C#""> <Document FilePath=""Test.cs""> using System; public class MyAttribute : Attribute { } [||][MyAttribute] class Test { int Method() { return 1 + 1; } } </Document> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#""> <Document FilePath=""Test.cs""> using System; public class MyAttribute : Attribute { } [MyAttribute] class Test : MyBase { } </Document> <Document FilePath=""MyBase.cs"">[MyAttribute] internal class MyBase { int Method() { return 1 + 1; } }</Document> </Project> </Workspace>"; await TestExtractClassAsync(input, expected, isClassDeclarationSelection: true); } [Fact] public async Task TestClassDeclaration_SelectWithMembers() { var input = @" <Workspace> <Project Language=""C#""> <Document FilePath=""Test.cs""> [|class Test { int Method() { return 1 + 1; } }|] </Document> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#""> <Document FilePath=""Test.cs""> class Test : MyBase { } </Document> <Document FilePath=""MyBase.cs"">internal class MyBase { int Method() { return 1 + 1; } }</Document> </Project> </Workspace>"; await TestExtractClassAsync(input, expected, isClassDeclarationSelection: true); } [Fact] public async Task TestClassDeclaration_SelectWithMembers2() { var input = @" <Workspace> <Project Language=""C#""> <Document FilePath=""Test.cs""> [|class Test { int Method() { return 1 + 1; }|] } </Document> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#""> <Document FilePath=""Test.cs""> class Test : MyBase { } </Document> <Document FilePath=""MyBase.cs"">internal class MyBase { int Method() { return 1 + 1; } }</Document> </Project> </Workspace>"; await TestExtractClassAsync(input, expected, isClassDeclarationSelection: true); } private static IEnumerable<(string name, bool makeAbstract)> MakeAbstractSelection(params string[] memberNames) => memberNames.Select(m => (m, true)); private static IEnumerable<(string name, bool makeAbstract)> MakeSelection(params string[] memberNames) => memberNames.Select(m => (m, false)); private class TestExtractClassOptionsService : IExtractClassOptionsService { private readonly IEnumerable<(string name, bool makeAbstract)>? _dialogSelection; private readonly bool _sameFile; private readonly bool isClassDeclarationSelection; public TestExtractClassOptionsService(IEnumerable<(string name, bool makeAbstract)>? dialogSelection = null, bool sameFile = false, bool isClassDeclarationSelection = false) { _dialogSelection = dialogSelection; _sameFile = sameFile; this.isClassDeclarationSelection = isClassDeclarationSelection; } public string FileName { get; set; } = "MyBase.cs"; public string BaseName { get; set; } = "MyBase"; public Task<ExtractClassOptions?> GetExtractClassOptionsAsync(Document document, INamedTypeSymbol originalSymbol, ISymbol? selectedMember) { var availableMembers = originalSymbol.GetMembers().Where(member => MemberAndDestinationValidator.IsMemberValid(member)); IEnumerable<(ISymbol member, bool makeAbstract)> selections; if (_dialogSelection == null) { if (selectedMember is null) { Assert.True(isClassDeclarationSelection); selections = availableMembers.Select(member => (member, makeAbstract: false)); } else { Assert.False(isClassDeclarationSelection); selections = new[] { (selectedMember, false) }; } } else { selections = _dialogSelection.Select(selection => (member: availableMembers.Single(symbol => symbol.Name == selection.name), selection.makeAbstract)); } var memberAnalysis = selections.Select(s => new ExtractClassMemberAnalysisResult( s.member, s.makeAbstract)) .ToImmutableArray(); return Task.FromResult<ExtractClassOptions?>(new ExtractClassOptions(FileName, BaseName, _sameFile, memberAnalysis)); } } } }
// Licensed to the .NET Foundation under one or more agreements. // 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.Linq; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.CodeRefactorings.ExtractClass; using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeRefactorings; using Microsoft.CodeAnalysis.ExtractClass; using Microsoft.CodeAnalysis.PullMemberUp; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.ExtractClass { public class ExtractClassTests : AbstractCSharpCodeActionTest { private Task TestExtractClassAsync( string input, string? expected = null, IEnumerable<(string name, bool makeAbstract)>? dialogSelection = null, bool sameFile = false, bool isClassDeclarationSelection = false, TestParameters testParameters = default) { var service = new TestExtractClassOptionsService(dialogSelection, sameFile, isClassDeclarationSelection); var parametersWithOptionsService = testParameters.WithFixProviderData(service); if (expected is null) { return TestMissingAsync(input, parametersWithOptionsService); } return TestInRegularAndScript1Async( input, expected, parameters: parametersWithOptionsService); } protected override CodeRefactoringProvider CreateCodeRefactoringProvider(Workspace workspace, TestParameters parameters) => new CSharpExtractClassCodeRefactoringProvider((IExtractClassOptionsService)parameters.fixProviderData); [Fact] public async Task TestSingleMethod() { var input = @" <Workspace> <Project Language=""C#""> <Document FilePath=""Test.cs""> class Test { int [||]Method() { return 1 + 1; } } </Document> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#""> <Document FilePath=""Test.cs""> class Test : MyBase { } </Document> <Document FilePath=""MyBase.cs"">internal class MyBase { int Method() { return 1 + 1; } }</Document> </Project> </Workspace>"; await TestExtractClassAsync(input, expected); } [Fact] public async Task TestErrorBaseMethod() { var input = @" <Workspace> <Project Language=""C#""> <Document FilePath=""Test.cs""> class Test : ErrorBase { int [||]Method() { return 1 + 1; } } </Document> </Project> </Workspace>"; await TestExtractClassAsync(input); } [Fact] public async Task TestMiscellaneousFiles() { var input = @" <Workspace> <Project Language=""C#""> <Document FilePath=""Test.cs""> class Test { int [||]Method() { return 1 + 1; } } </Document> </Project> </Workspace>"; TestParameters parameters = default; await TestExtractClassAsync(input, testParameters: parameters.WithWorkspaceKind(WorkspaceKind.MiscellaneousFiles)); } [Fact] public async Task TestPartialClass() { var input = @" <Workspace> <Project Language=""C#""> <Document FilePath=""Test.cs""> partial class Test { int [||]Method() { return 1 + 1; } } </Document> <Document FilePath=""Test.Other.cs""> partial class Test { int Method2() { return 5; } } </Document> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#""> <Document FilePath=""Test.cs""> partial class Test : MyBase { } </Document> <Document FilePath=""Test.Other.cs""> partial class Test { } </Document> <Document FilePath=""MyBase.cs"">internal class MyBase { int Method() { return 1 + 1; } int Method2() { return 5; } }</Document> </Project> </Workspace>"; await TestExtractClassAsync( input, expected, dialogSelection: MakeSelection("Method", "Method2")); } [Fact] public async Task TestInNamespace() { var input = @" <Workspace> <Project Language=""C#""> <Document FilePath=""Test.cs""> namespace MyNamespace { class Test { int [||]Method() { return 1 + 1; } } } </Document> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#""> <Document FilePath=""Test.cs""> namespace MyNamespace { class Test : MyBase { } } </Document> <Document FilePath=""MyBase.cs"">namespace MyNamespace { internal class MyBase { int Method() { return 1 + 1; } } }</Document> </Project> </Workspace>"; await TestExtractClassAsync(input, expected); } [Fact] public async Task TestInNamespace_FileScopedNamespace1() { var input = @" <Workspace> <Project Language=""C#"" LanguageVersion=""10""> <Document FilePath=""Test.cs""> namespace MyNamespace { class Test { int [||]Method() { return 1 + 1; } } } </Document> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" LanguageVersion=""10""> <Document FilePath=""Test.cs""> namespace MyNamespace { class Test : MyBase { } } </Document> <Document FilePath=""MyBase.cs"">namespace MyNamespace; internal class MyBase { int Method() { return 1 + 1; } }</Document> </Project> </Workspace>"; await TestAsync( input, expected, CSharpParseOptions.Default, options: Option(CSharpCodeStyleOptions.NamespaceDeclarations, NamespaceDeclarationPreference.FileScoped, NotificationOption2.Silent), fixProviderData: new TestExtractClassOptionsService()); } [Fact] public async Task TestInNamespace_FileScopedNamespace2() { var input = @" <Workspace> <Project Language=""C#"" LanguageVersion=""9""> <Document FilePath=""Test.cs""> namespace MyNamespace { class Test { int [||]Method() { return 1 + 1; } } } </Document> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" LanguageVersion=""9""> <Document FilePath=""Test.cs""> namespace MyNamespace { class Test : MyBase { } } </Document> <Document FilePath=""MyBase.cs"">namespace MyNamespace { internal class MyBase { int Method() { return 1 + 1; } } }</Document> </Project> </Workspace>"; await TestAsync( input, expected, CSharpParseOptions.Default, options: Option(CSharpCodeStyleOptions.NamespaceDeclarations, NamespaceDeclarationPreference.FileScoped, NotificationOption2.Silent), fixProviderData: new TestExtractClassOptionsService()); } [Fact] public async Task TestInNamespace_FileScopedNamespace3() { var input = @" <Workspace> <Project Language=""C#"" LanguageVersion=""10""> <Document FilePath=""Test.cs""> namespace MyNamespace { class Test { int [||]Method() { return 1 + 1; } } } </Document> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" LanguageVersion=""10""> <Document FilePath=""Test.cs""> namespace MyNamespace { class Test : MyBase { } } </Document> <Document FilePath=""MyBase.cs"">namespace MyNamespace { internal class MyBase { int Method() { return 1 + 1; } } }</Document> </Project> </Workspace>"; await TestAsync( input, expected, CSharpParseOptions.Default, options: Option(CSharpCodeStyleOptions.NamespaceDeclarations, NamespaceDeclarationPreference.BlockScoped, NotificationOption2.Silent), fixProviderData: new TestExtractClassOptionsService()); } [Fact] public async Task TestAccessibility() { var input = @" <Workspace> <Project Language=""C#""> <Document FilePath=""Test.cs""> public class Test { int [||]Method() { return 1 + 1; } } </Document> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#""> <Document FilePath=""Test.cs""> public class Test : MyBase { } </Document> <Document FilePath=""MyBase.cs"">public class MyBase { int Method() { return 1 + 1; } }</Document> </Project> </Workspace>"; await TestExtractClassAsync(input, expected); } [Fact] public async Task TestEvent() { var input = @" <Workspace> <Project Language=""C#""> <Document FilePath=""Test.cs""> using System; class Test { private event EventHandler [||]Event1; } </Document> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#""> <Document FilePath=""Test.cs""> using System; class Test : MyBase { } </Document> <Document FilePath=""MyBase.cs"">internal class MyBase { private event EventHandler Event1; }</Document> </Project> </Workspace>"; await TestExtractClassAsync(input, expected); } [Fact] public async Task TestProperty() { var input = @" <Workspace> <Project Language=""C#""> <Document FilePath=""Test.cs""> class Test { int [||]MyProperty { get; set; } } </Document> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#""> <Document FilePath=""Test.cs""> class Test : MyBase { } </Document> <Document FilePath=""MyBase.cs"">internal class MyBase { int MyProperty { get; set; } }</Document> </Project> </Workspace>"; await TestExtractClassAsync(input, expected); } [Fact] public async Task TestField() { var input = @" <Workspace> <Project Language=""C#""> <Document FilePath=""Test.cs""> class Test { int [||]MyField; } </Document> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#""> <Document FilePath=""Test.cs""> class Test : MyBase { } </Document> <Document FilePath=""MyBase.cs"">internal class MyBase { int MyField; }</Document> </Project> </Workspace>"; await TestExtractClassAsync(input, expected); } [Fact] public async Task TestFileHeader() { var input = @" <Workspace> <Project Language=""C#""> <Document FilePath=""Test.cs"">// this is my document header // that should be copied over class Test { int [||]Method() { return 1 + 1; } } </Document> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#""> <Document FilePath=""Test.cs"">// this is my document header // that should be copied over class Test : MyBase { } </Document> <Document FilePath=""MyBase.cs"">// this is my document header // that should be copied over internal class MyBase { int Method() { return 1 + 1; } }</Document> </Project> </Workspace>"; await TestExtractClassAsync(input, expected); } [Fact] public async Task TestWithInterface() { var input = @" <Workspace> <Project Language=""C#""> <Document FilePath=""Test.cs""> interface ITest { int Method(); } class Test : ITest { int [||]Method() { return 1 + 1; } } </Document> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#""> <Document FilePath=""Test.cs""> interface ITest { int Method(); } class Test : MyBase, ITest { } </Document> <Document FilePath=""MyBase.cs"">internal class MyBase { int Method() { return 1 + 1; } }</Document> </Project> </Workspace>"; await TestExtractClassAsync(input, expected); } [ConditionalFact(AlwaysSkip = "https://github.com/dotnet/roslyn/issues/45977")] public async Task TestRegion() { var input = @" <Workspace> <Project Language=""C#""> <Document FilePath=""Test.cs""> class Test { #region MyRegion int [||]Method() { return 1 + 1; } void OtherMethiod() { } #endregion } </Document> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#""> <Document FilePath=""Test.cs""> class Test : MyBase { #region MyRegion void OtherMethiod() { } #endregion } </Document> <Document FilePath=""MyBase.cs"">internal class MyBase { #region MyRegion int Method() { return 1 + 1; } #endregion }</Document> </Project> </Workspace>"; await TestExtractClassAsync( input, expected, dialogSelection: MakeSelection("Method")); } [Fact] public async Task TestMakeAbstract_SingleMethod() { var input = @" <Workspace> <Project Language=""C#""> <Document FilePath=""Test.cs""> class Test { int [||]Method() { return 1 + 1; } } </Document> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#""> <Document FilePath=""Test.cs""> class Test : MyBase { override int Method() { return 1 + 1; } } </Document> <Document FilePath=""MyBase.cs"">internal abstract class MyBase { private abstract global::System.Int32 Method(); }</Document> </Project> </Workspace>"; await TestExtractClassAsync( input, expected, dialogSelection: MakeAbstractSelection("Method")); } [Fact] public async Task TestMakeAbstract_MultipleMethods() { var input = @" <Workspace> <Project Language=""C#""> <Document FilePath=""Test.cs""> class Test { int [||]Method() { return 1 + 1; } int Method2() => 2; int Method3() => 3; } </Document> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#""> <Document FilePath=""Test.cs""> class Test : MyBase { override int Method() { return 1 + 1; } override int Method2() => 2; override int Method3() => 3; } </Document> <Document FilePath=""MyBase.cs"">internal abstract class MyBase { private abstract global::System.Int32 Method(); private abstract global::System.Int32 Method2(); private abstract global::System.Int32 Method3(); }</Document> </Project> </Workspace>"; await TestExtractClassAsync( input, expected, dialogSelection: MakeAbstractSelection("Method", "Method2", "Method3")); } [Fact] public async Task TestMultipleMethods() { var input = @" <Workspace> <Project Language=""C#""> <Document FilePath=""Test.cs""> class Test { int [||]Method() { return Method2() + 1; } int Method2() => 1; } </Document> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#""> <Document FilePath=""Test.cs""> class Test : MyBase { } </Document> <Document FilePath=""MyBase.cs"">internal class MyBase { int Method() { return Method2() + 1; } int Method2() => 1; }</Document> </Project> </Workspace>"; await TestExtractClassAsync( input, expected, dialogSelection: MakeSelection("Method", "Method2")); } [Fact] public async Task TestMultipleMethods_SomeSelected() { var input = @" <Workspace> <Project Language=""C#""> <Document FilePath=""Test.cs""> class Test { int [||]Method() { return Method2() + 1; } int Method2() => 1; } </Document> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#""> <Document FilePath=""Test.cs""> class Test : MyBase { int Method() { return Method2() + 1; } } </Document> <Document FilePath=""MyBase.cs"">internal class MyBase { int Method2() => 1; }</Document> </Project> </Workspace>"; await TestExtractClassAsync( input, expected, dialogSelection: MakeSelection("Method2")); } [Fact] public async Task TestSelection_CompleteMethodAndComments() { var input = @" <Workspace> <Project Language=""C#""> <Document FilePath=""Test.cs""> class Test { [|/// <summary> /// this is a test method /// </summary> int Method() { return 1 + 1; }|] } </Document> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#""> <Document FilePath=""Test.cs""> class Test : MyBase { } </Document> <Document FilePath=""MyBase.cs"">internal class MyBase { /// <summary> /// this is a test method /// </summary> int Method() { return 1 + 1; } }</Document> </Project> </Workspace>"; await TestExtractClassAsync(input, expected); } [Fact] public async Task TestSelection_PartialMethodAndComments() { var input = @" <Workspace> <Project Language=""C#""> <Document FilePath=""Test.cs""> class Test { [|/// <summary> /// this is a test method /// </summary> int Method() {|] return 1 + 1; } } </Document> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#""> <Document FilePath=""Test.cs""> class Test : MyBase { } </Document> <Document FilePath=""MyBase.cs"">internal class MyBase { /// <summary> /// this is a test method /// </summary> int Method() { return 1 + 1; } }</Document> </Project> </Workspace>"; await TestExtractClassAsync(input, expected); } [Fact] public async Task TestSelection_PartialMethodAndComments2() { var input = @" <Workspace> <Project Language=""C#""> <Document FilePath=""Test.cs""> class Test { /// <summary> /// [|this is a test method /// </summary> int Method() {|] return 1 + 1; } } </Document> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#""> <Document FilePath=""Test.cs""> class Test : MyBase { } </Document> <Document FilePath=""MyBase.cs"">internal class MyBase { /// <summary> /// this is a test method /// </summary> int Method() { return 1 + 1; } }</Document> </Project> </Workspace>"; await TestExtractClassAsync(input, expected); } [Fact] public async Task TestSelection_PartialMethodAndComments3() { var input = @" <Workspace> <Project Language=""C#""> <Document FilePath=""Test.cs""> class Test { /// <summary> /// [|this is a test method /// </summary> int Method()|] { return 1 + 1; } } </Document> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#""> <Document FilePath=""Test.cs""> class Test : MyBase { } </Document> <Document FilePath=""MyBase.cs"">internal class MyBase { /// <summary> /// this is a test method /// </summary> int Method() { return 1 + 1; } }</Document> </Project> </Workspace>"; await TestExtractClassAsync(input, expected); } [Fact] public async Task TestAttributes() { var input = @" <Workspace> <Project Language=""C#""> <Document FilePath=""Test.cs""> using System; class TestAttribute : Attribute { } class Test { /// <summary> /// this is a test method /// </summary> [||][TestAttribute] int Method() { return 1 + 1; } } </Document> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#""> <Document FilePath=""Test.cs""> using System; class TestAttribute : Attribute { } class Test : MyBase { } </Document> <Document FilePath=""MyBase.cs"">internal class MyBase { /// <summary> /// this is a test method /// </summary> [TestAttribute] int Method() { return 1 + 1; } }</Document> </Project> </Workspace>"; await TestExtractClassAsync(input, expected); } [Fact] public async Task TestAttributes2() { var input = @" <Workspace> <Project Language=""C#""> <Document FilePath=""Test.cs""> using System; class TestAttribute : Attribute { } class TestAttribute2 : Attribute { } class Test { /// <summary> /// this is a test method /// </summary> [||][TestAttribute] [TestAttribute2] int Method() { return 1 + 1; } } </Document> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#""> <Document FilePath=""Test.cs""> using System; class TestAttribute : Attribute { } class TestAttribute2 : Attribute { } class Test : MyBase { } </Document> <Document FilePath=""MyBase.cs"">internal class MyBase { /// <summary> /// this is a test method /// </summary> [TestAttribute] [TestAttribute2] int Method() { return 1 + 1; } }</Document> </Project> </Workspace>"; await TestExtractClassAsync(input, expected); } [ConditionalFact(AlwaysSkip = "https://github.com/dotnet/roslyn/issues/45987")] public async Task TestAttributes3() { var input = @" <Workspace> <Project Language=""C#""> <Document FilePath=""Test.cs""> using System; class TestAttribute : Attribute { } class TestAttribute2 : Attribute { } class Test { /// <summary> /// this is a test method /// </summary> [TestAttribute] [||][TestAttribute2] int Method() { return 1 + 1; } } </Document> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#""> <Document FilePath=""Test.cs""> using System; class TestAttribute : Attribute { } class Test : MyBase { } </Document> <Document FilePath=""MyBase.cs"">internal class MyBase { /// <summary> /// this is a test method /// </summary> [TestAttribute] [TestAttribute2] int Method() { return 1 + 1; } }</Document> </Project> </Workspace>"; await TestExtractClassAsync(input, expected); } [ConditionalFact(AlwaysSkip = "https://github.com/dotnet/roslyn/issues/45987")] public async Task TestAttributes4() { var input = @" <Workspace> <Project Language=""C#""> <Document FilePath=""Test.cs""> using System; class TestAttribute : Attribute { } class TestAttribute2 : Attribute { } class Test { /// <summary> /// this is a test method /// </summary> [TestAttribute] [TestAttribute2][||] int Method() { return 1 + 1; } } </Document> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#""> <Document FilePath=""Test.cs""> using System; class TestAttribute : Attribute { } class Test : MyBase { } </Document> <Document FilePath=""MyBase.cs"">internal class MyBase { /// <summary> /// this is a test method /// </summary> [TestAttribute] [TestAttribute2] int Method() { return 1 + 1; } }</Document> </Project> </Workspace>"; await TestExtractClassAsync(input, expected); } [Fact] public async Task TestSameFile() { var input = @" <Workspace> <Project Language=""C#""> <Document FilePath=""Test.cs""> class Test { void Method[||]() { } } </Document> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#""> <Document FilePath=""Test.cs""> internal class MyBase { void Method() { } } class Test : MyBase { } </Document> </Project> </Workspace>"; await TestExtractClassAsync(input, expected, sameFile: true); } [Fact] public async Task TestClassDeclaration() { var input = @" <Workspace> <Project Language=""C#""> <Document FilePath=""Test.cs""> class Test[||] { int Method() { return 1 + 1; } } </Document> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#""> <Document FilePath=""Test.cs""> class Test : MyBase { } </Document> <Document FilePath=""MyBase.cs"">internal class MyBase { int Method() { return 1 + 1; } }</Document> </Project> </Workspace>"; await TestExtractClassAsync(input, expected, isClassDeclarationSelection: true); } [Fact] public async Task TestClassDeclaration2() { var input = @" <Workspace> <Project Language=""C#""> <Document FilePath=""Test.cs""> class [||]Test { int Method() { return 1 + 1; } } </Document> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#""> <Document FilePath=""Test.cs""> class Test : MyBase { } </Document> <Document FilePath=""MyBase.cs"">internal class MyBase { int Method() { return 1 + 1; } }</Document> </Project> </Workspace>"; await TestExtractClassAsync(input, expected, isClassDeclarationSelection: true); } [Fact] public async Task TestClassDeclaration3() { var input = @" <Workspace> <Project Language=""C#""> <Document FilePath=""Test.cs""> [||]class Test { int Method() { return 1 + 1; } } </Document> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#""> <Document FilePath=""Test.cs""> class Test : MyBase { } </Document> <Document FilePath=""MyBase.cs"">internal class MyBase { int Method() { return 1 + 1; } }</Document> </Project> </Workspace>"; await TestExtractClassAsync(input, expected, isClassDeclarationSelection: true); } [Fact] public async Task TestClassDeclaration4() { var input = @" <Workspace> <Project Language=""C#""> <Document FilePath=""Test.cs""> class[||] Test { int Method() { return 1 + 1; } } </Document> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#""> <Document FilePath=""Test.cs""> class Test : MyBase { } </Document> <Document FilePath=""MyBase.cs"">internal class MyBase { int Method() { return 1 + 1; } }</Document> </Project> </Workspace>"; await TestExtractClassAsync(input, expected, isClassDeclarationSelection: true); } [Fact] public async Task TestClassDeclaration_Comment() { var input = @" <Workspace> <Project Language=""C#""> <Document FilePath=""Test.cs""> using System; /// <summary> /// [|This is a test class /// </summary> class Test|] { int Method() { return 1 + 1; } } </Document> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#""> <Document FilePath=""Test.cs""> using System; /// <summary> /// This is a test class /// </summary> class Test : MyBase { } </Document> <Document FilePath=""MyBase.cs"">internal class MyBase { int Method() { return 1 + 1; } }</Document> </Project> </Workspace>"; await TestExtractClassAsync(input, expected, isClassDeclarationSelection: true); } [Fact] public async Task TestClassDeclaration_Comment2() { var input = @" <Workspace> <Project Language=""C#""> <Document FilePath=""Test.cs""> using System; /// <summary> /// This is a test class /// [|</summary> class Test|] { int Method() { return 1 + 1; } } </Document> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#""> <Document FilePath=""Test.cs""> using System; /// <summary> /// This is a test class /// </summary> class Test : MyBase { } </Document> <Document FilePath=""MyBase.cs"">internal class MyBase { int Method() { return 1 + 1; } }</Document> </Project> </Workspace>"; await TestExtractClassAsync(input, expected, isClassDeclarationSelection: true); } [Fact] public async Task TestClassDeclaration_Comment3() { var input = @" <Workspace> <Project Language=""C#""> <Document FilePath=""Test.cs""> using System; /// <summary> /// This is a [|test class /// </summary> class|] Test { int Method() { return 1 + 1; } } </Document> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#""> <Document FilePath=""Test.cs""> using System; /// <summary> /// This is a test class /// </summary> class Test : MyBase { } </Document> <Document FilePath=""MyBase.cs"">internal class MyBase { int Method() { return 1 + 1; } }</Document> </Project> </Workspace>"; await TestExtractClassAsync(input, expected, isClassDeclarationSelection: true); } [Fact] public async Task TestClassDeclaration_Attribute() { var input = @" <Workspace> <Project Language=""C#""> <Document FilePath=""Test.cs""> using System; public class MyAttribute : Attribute { } [||][MyAttribute] class Test { int Method() { return 1 + 1; } } </Document> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#""> <Document FilePath=""Test.cs""> using System; public class MyAttribute : Attribute { } [MyAttribute] class Test : MyBase { } </Document> <Document FilePath=""MyBase.cs"">[MyAttribute] internal class MyBase { int Method() { return 1 + 1; } }</Document> </Project> </Workspace>"; await TestExtractClassAsync(input, expected, isClassDeclarationSelection: true); } [Fact] public async Task TestClassDeclaration_SelectWithMembers() { var input = @" <Workspace> <Project Language=""C#""> <Document FilePath=""Test.cs""> [|class Test { int Method() { return 1 + 1; } }|] </Document> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#""> <Document FilePath=""Test.cs""> class Test : MyBase { } </Document> <Document FilePath=""MyBase.cs"">internal class MyBase { int Method() { return 1 + 1; } }</Document> </Project> </Workspace>"; await TestExtractClassAsync(input, expected, isClassDeclarationSelection: true); } [Fact] public async Task TestClassDeclaration_SelectWithMembers2() { var input = @" <Workspace> <Project Language=""C#""> <Document FilePath=""Test.cs""> [|class Test { int Method() { return 1 + 1; }|] } </Document> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#""> <Document FilePath=""Test.cs""> class Test : MyBase { } </Document> <Document FilePath=""MyBase.cs"">internal class MyBase { int Method() { return 1 + 1; } }</Document> </Project> </Workspace>"; await TestExtractClassAsync(input, expected, isClassDeclarationSelection: true); } private static IEnumerable<(string name, bool makeAbstract)> MakeAbstractSelection(params string[] memberNames) => memberNames.Select(m => (m, true)); private static IEnumerable<(string name, bool makeAbstract)> MakeSelection(params string[] memberNames) => memberNames.Select(m => (m, false)); private class TestExtractClassOptionsService : IExtractClassOptionsService { private readonly IEnumerable<(string name, bool makeAbstract)>? _dialogSelection; private readonly bool _sameFile; private readonly bool isClassDeclarationSelection; public TestExtractClassOptionsService(IEnumerable<(string name, bool makeAbstract)>? dialogSelection = null, bool sameFile = false, bool isClassDeclarationSelection = false) { _dialogSelection = dialogSelection; _sameFile = sameFile; this.isClassDeclarationSelection = isClassDeclarationSelection; } public string FileName { get; set; } = "MyBase.cs"; public string BaseName { get; set; } = "MyBase"; public Task<ExtractClassOptions?> GetExtractClassOptionsAsync(Document document, INamedTypeSymbol originalSymbol, ISymbol? selectedMember) { var availableMembers = originalSymbol.GetMembers().Where(member => MemberAndDestinationValidator.IsMemberValid(member)); IEnumerable<(ISymbol member, bool makeAbstract)> selections; if (_dialogSelection == null) { if (selectedMember is null) { Assert.True(isClassDeclarationSelection); selections = availableMembers.Select(member => (member, makeAbstract: false)); } else { Assert.False(isClassDeclarationSelection); selections = new[] { (selectedMember, false) }; } } else { selections = _dialogSelection.Select(selection => (member: availableMembers.Single(symbol => symbol.Name == selection.name), selection.makeAbstract)); } var memberAnalysis = selections.Select(s => new ExtractClassMemberAnalysisResult( s.member, s.makeAbstract)) .ToImmutableArray(); return Task.FromResult<ExtractClassOptions?>(new ExtractClassOptions(FileName, BaseName, _sameFile, memberAnalysis)); } } } }
-1
dotnet/roslyn
55,256
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-30T00:02:02Z
2021-07-30T09:17:54Z
6ce9c0048d37026337701fac035ac0745f6fe49f
88b59775dc6375635957ef229116460f290072aa
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/EmbeddedLanguages/VirtualChars/VirtualCharSequence.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Diagnostics; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.EmbeddedLanguages.VirtualChars { /// <summary> /// Represents the individual characters that raw string token represents (i.e. with escapes collapsed). /// The difference between this and the result from token.ValueText is that for each collapsed character /// returned the original span of text in the original token can be found. i.e. if you had the /// following in C#: /// /// "G\u006fo" /// /// Then you'd get back: /// /// 'G' -> [0, 1) 'o' -> [1, 7) 'o' -> [7, 1) /// /// This allows for embedded language processing that can refer back to the user's original code /// instead of the escaped value we're processing. /// </summary> internal partial struct VirtualCharSequence { public static readonly VirtualCharSequence Empty = Create(ImmutableArray<VirtualChar>.Empty); public static VirtualCharSequence Create(ImmutableArray<VirtualChar> virtualChars) => new(new ImmutableArrayChunk(virtualChars)); public static VirtualCharSequence Create(int firstVirtualCharPosition, string underlyingData) => new(new StringChunk(firstVirtualCharPosition, underlyingData)); /// <summary> /// The actual characters that this <see cref="VirtualCharSequence"/> is a portion of. /// </summary> private readonly Chunk _leafCharacters; /// <summary> /// The portion of <see cref="_leafCharacters"/> that is being exposed. This span /// is `[inclusive, exclusive)`. /// </summary> private readonly TextSpan _span; private VirtualCharSequence(Chunk sequence) : this(sequence, new TextSpan(0, sequence.Length)) { } private VirtualCharSequence(Chunk sequence, TextSpan span) { if (span.Start > sequence.Length) { throw new ArgumentException(); } if (span.End > sequence.Length) { throw new ArgumentException(); } _leafCharacters = sequence; _span = span; } public int Length => _span.Length; public VirtualChar this[int index] => _leafCharacters[_span.Start + index]; public bool IsDefault => _leafCharacters == null; public bool IsEmpty => Length == 0; public bool IsDefaultOrEmpty => IsDefault || IsEmpty; public VirtualCharSequence GetSubSequence(TextSpan span) => new( _leafCharacters, new TextSpan(_span.Start + span.Start, span.Length)); public VirtualChar First() => this[0]; public VirtualChar Last() => this[this.Length - 1]; public Enumerator GetEnumerator() => new(this); public VirtualChar? FirstOrNull(Func<VirtualChar, bool> predicate) { foreach (var ch in this) { if (predicate(ch)) { return ch; } } return null; } public bool Contains(VirtualChar @char) => IndexOf(@char) >= 0; public int IndexOf(VirtualChar @char) { var index = 0; foreach (var ch in this) { if (ch == @char) { return index; } index++; } return -1; } public string CreateString() { using var _ = PooledStringBuilder.GetInstance(out var builder); foreach (var ch in this) ch.AppendTo(builder); return builder.ToString(); } [Conditional("DEBUG")] public void AssertAdjacentTo(VirtualCharSequence virtualChars) { Debug.Assert(_leafCharacters == virtualChars._leafCharacters); Debug.Assert(_span.End == virtualChars._span.Start); } /// <summary> /// Combines two <see cref="VirtualCharSequence"/>s, producing a final /// sequence that points at the same underlying data, but spans from the /// start of <paramref name="chars1"/> to the end of <paramref name="chars2"/>. /// </summary> public static VirtualCharSequence FromBounds( VirtualCharSequence chars1, VirtualCharSequence chars2) { Debug.Assert(chars1._leafCharacters == chars2._leafCharacters); return new VirtualCharSequence( chars1._leafCharacters, TextSpan.FromBounds(chars1._span.Start, chars2._span.End)); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Diagnostics; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.EmbeddedLanguages.VirtualChars { /// <summary> /// Represents the individual characters that raw string token represents (i.e. with escapes collapsed). /// The difference between this and the result from token.ValueText is that for each collapsed character /// returned the original span of text in the original token can be found. i.e. if you had the /// following in C#: /// /// "G\u006fo" /// /// Then you'd get back: /// /// 'G' -> [0, 1) 'o' -> [1, 7) 'o' -> [7, 1) /// /// This allows for embedded language processing that can refer back to the user's original code /// instead of the escaped value we're processing. /// </summary> internal partial struct VirtualCharSequence { public static readonly VirtualCharSequence Empty = Create(ImmutableArray<VirtualChar>.Empty); public static VirtualCharSequence Create(ImmutableArray<VirtualChar> virtualChars) => new(new ImmutableArrayChunk(virtualChars)); public static VirtualCharSequence Create(int firstVirtualCharPosition, string underlyingData) => new(new StringChunk(firstVirtualCharPosition, underlyingData)); /// <summary> /// The actual characters that this <see cref="VirtualCharSequence"/> is a portion of. /// </summary> private readonly Chunk _leafCharacters; /// <summary> /// The portion of <see cref="_leafCharacters"/> that is being exposed. This span /// is `[inclusive, exclusive)`. /// </summary> private readonly TextSpan _span; private VirtualCharSequence(Chunk sequence) : this(sequence, new TextSpan(0, sequence.Length)) { } private VirtualCharSequence(Chunk sequence, TextSpan span) { if (span.Start > sequence.Length) { throw new ArgumentException(); } if (span.End > sequence.Length) { throw new ArgumentException(); } _leafCharacters = sequence; _span = span; } public int Length => _span.Length; public VirtualChar this[int index] => _leafCharacters[_span.Start + index]; public bool IsDefault => _leafCharacters == null; public bool IsEmpty => Length == 0; public bool IsDefaultOrEmpty => IsDefault || IsEmpty; public VirtualCharSequence GetSubSequence(TextSpan span) => new( _leafCharacters, new TextSpan(_span.Start + span.Start, span.Length)); public VirtualChar First() => this[0]; public VirtualChar Last() => this[this.Length - 1]; public Enumerator GetEnumerator() => new(this); public VirtualChar? FirstOrNull(Func<VirtualChar, bool> predicate) { foreach (var ch in this) { if (predicate(ch)) { return ch; } } return null; } public bool Contains(VirtualChar @char) => IndexOf(@char) >= 0; public int IndexOf(VirtualChar @char) { var index = 0; foreach (var ch in this) { if (ch == @char) { return index; } index++; } return -1; } public string CreateString() { using var _ = PooledStringBuilder.GetInstance(out var builder); foreach (var ch in this) ch.AppendTo(builder); return builder.ToString(); } [Conditional("DEBUG")] public void AssertAdjacentTo(VirtualCharSequence virtualChars) { Debug.Assert(_leafCharacters == virtualChars._leafCharacters); Debug.Assert(_span.End == virtualChars._span.Start); } /// <summary> /// Combines two <see cref="VirtualCharSequence"/>s, producing a final /// sequence that points at the same underlying data, but spans from the /// start of <paramref name="chars1"/> to the end of <paramref name="chars2"/>. /// </summary> public static VirtualCharSequence FromBounds( VirtualCharSequence chars1, VirtualCharSequence chars2) { Debug.Assert(chars1._leafCharacters == chars2._leafCharacters); return new VirtualCharSequence( chars1._leafCharacters, TextSpan.FromBounds(chars1._span.Start, chars2._span.End)); } } }
-1
dotnet/roslyn
55,256
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-30T00:02:02Z
2021-07-30T09:17:54Z
6ce9c0048d37026337701fac035ac0745f6fe49f
88b59775dc6375635957ef229116460f290072aa
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/VisualStudio/IntegrationTest/IntegrationTests/CSharp/CSharpExtractInterfaceDialog.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.VisualStudio.IntegrationTest.Utilities; using Microsoft.VisualStudio.IntegrationTest.Utilities.OutOfProcess; using Roslyn.Test.Utilities; using Xunit; using Xunit.Abstractions; using ProjectUtils = Microsoft.VisualStudio.IntegrationTest.Utilities.Common.ProjectUtils; namespace Roslyn.VisualStudio.IntegrationTests.CSharp { [Collection(nameof(SharedIntegrationHostFixture))] public class CSharpExtractInterfaceDialog : AbstractEditorTest { protected override string LanguageName => LanguageNames.CSharp; private ExtractInterfaceDialog_OutOfProc ExtractInterfaceDialog => VisualStudio.ExtractInterfaceDialog; public CSharpExtractInterfaceDialog(VisualStudioInstanceFactory instanceFactory) : base(instanceFactory, nameof(CSharpExtractInterfaceDialog)) { } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractInterface)] public void VerifyCancellation() { SetUpEditor(@"class C$$ { public void M() { } } "); VisualStudio.Editor.InvokeCodeActionList(); VisualStudio.Editor.Verify.CodeAction("Extract interface...", applyFix: true, blockUntilComplete: false); ExtractInterfaceDialog.VerifyOpen(); ExtractInterfaceDialog.ClickCancel(); ExtractInterfaceDialog.VerifyClosed(); VisualStudio.Editor.Verify.TextContains(@"class C { public void M() { } } "); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractInterface)] public void CheckFileName() { SetUpEditor(@"class C$$ { public void M() { } } "); VisualStudio.Editor.InvokeCodeActionList(); VisualStudio.Editor.Verify.CodeAction("Extract interface...", applyFix: true, blockUntilComplete: false); ExtractInterfaceDialog.VerifyOpen(); var targetFileName = ExtractInterfaceDialog.GetTargetFileName(); Assert.Equal(expected: "IC.cs", actual: targetFileName); ExtractInterfaceDialog.ClickCancel(); ExtractInterfaceDialog.VerifyClosed(); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractInterface)] public void VerifySelectAndDeselectAllButtons() { SetUpEditor(@"class C$$ { public void M1() { } public void M2() { } } "); VisualStudio.Editor.InvokeCodeActionList(); VisualStudio.Editor.Verify.CodeAction("Extract interface...", applyFix: true, blockUntilComplete: false); ExtractInterfaceDialog.VerifyOpen(); var selectedItems = ExtractInterfaceDialog.GetSelectedItems(); Assert.Equal( expected: new[] { "M1()", "M2()" }, actual: selectedItems); ExtractInterfaceDialog.ClickDeselectAll(); selectedItems = ExtractInterfaceDialog.GetSelectedItems(); Assert.Empty(selectedItems); ExtractInterfaceDialog.ClickSelectAll(); selectedItems = ExtractInterfaceDialog.GetSelectedItems(); Assert.Equal( expected: new[] { "M1()", "M2()" }, actual: selectedItems); ExtractInterfaceDialog.ClickCancel(); ExtractInterfaceDialog.VerifyClosed(); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractInterface)] public void OnlySelectedItemsAreGenerated() { SetUpEditor(@"class C$$ { public void M1() { } public void M2() { } } "); VisualStudio.Editor.InvokeCodeActionList(); VisualStudio.Editor.Verify.CodeAction("Extract interface...", applyFix: true, blockUntilComplete: false); ExtractInterfaceDialog.VerifyOpen(); ExtractInterfaceDialog.ClickDeselectAll(); ExtractInterfaceDialog.ToggleItem("M2()"); ExtractInterfaceDialog.ClickOK(); ExtractInterfaceDialog.VerifyClosed(); var project = new ProjectUtils.Project(ProjectName); VisualStudio.SolutionExplorer.OpenFile(project, "Class1.cs"); VisualStudio.Editor.Verify.TextContains(@"class C : IC { public void M1() { } public void M2() { } } "); VisualStudio.SolutionExplorer.OpenFile(project, "IC.cs"); VisualStudio.Editor.Verify.TextContains(@"interface IC { void M2(); }"); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractInterface)] public void CheckSameFile() { SetUpEditor(@"class C$$ { public void M() { } } "); VisualStudio.Editor.InvokeCodeActionList(); VisualStudio.Editor.Verify.CodeAction("Extract interface...", applyFix: true, blockUntilComplete: false); ExtractInterfaceDialog.VerifyOpen(); ExtractInterfaceDialog.SelectSameFile(); ExtractInterfaceDialog.ClickOK(); ExtractInterfaceDialog.VerifyClosed(); _ = new ProjectUtils.Project(ProjectName); VisualStudio.Editor.Verify.TextContains(@"interface IC { void M(); } class C : IC { public void M() { } } "); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractInterface)] public void CheckSameFileOnlySelectedItems() { SetUpEditor(@"class C$$ { public void M1() { } public void M2() { } } "); VisualStudio.Editor.InvokeCodeActionList(); VisualStudio.Editor.Verify.CodeAction("Extract interface...", applyFix: true, blockUntilComplete: false); ExtractInterfaceDialog.VerifyOpen(); ExtractInterfaceDialog.ClickDeselectAll(); ExtractInterfaceDialog.ToggleItem("M2()"); ExtractInterfaceDialog.SelectSameFile(); ExtractInterfaceDialog.ClickOK(); ExtractInterfaceDialog.VerifyClosed(); VisualStudio.Editor.Verify.TextContains(@"interface IC { void M2(); } class C : IC { public void M1() { } public void M2() { } } "); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractInterface)] public void CheckSameFileNamespace() { SetUpEditor(@"namespace A { class C$$ { public void M() { } } } "); VisualStudio.Editor.InvokeCodeActionList(); VisualStudio.Editor.Verify.CodeAction("Extract interface...", applyFix: true, blockUntilComplete: false); ExtractInterfaceDialog.VerifyOpen(); ExtractInterfaceDialog.SelectSameFile(); ExtractInterfaceDialog.ClickOK(); ExtractInterfaceDialog.VerifyClosed(); _ = new ProjectUtils.Project(ProjectName); VisualStudio.Editor.Verify.TextContains(@"namespace A { interface IC { void M(); } class C : IC { public void M() { } } } "); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractInterface)] public void CheckSameWithTypes() { SetUpEditor(@"class C$$ { public bool M() => false; } "); VisualStudio.Editor.InvokeCodeActionList(); VisualStudio.Editor.Verify.CodeAction("Extract interface...", applyFix: true, blockUntilComplete: false); ExtractInterfaceDialog.VerifyOpen(); ExtractInterfaceDialog.SelectSameFile(); ExtractInterfaceDialog.ClickOK(); ExtractInterfaceDialog.VerifyClosed(); _ = new ProjectUtils.Project(ProjectName); VisualStudio.Editor.Verify.TextContains(@"interface IC { bool M(); } class C : IC { public bool M() => 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 Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.VisualStudio.IntegrationTest.Utilities; using Microsoft.VisualStudio.IntegrationTest.Utilities.OutOfProcess; using Roslyn.Test.Utilities; using Xunit; using Xunit.Abstractions; using ProjectUtils = Microsoft.VisualStudio.IntegrationTest.Utilities.Common.ProjectUtils; namespace Roslyn.VisualStudio.IntegrationTests.CSharp { [Collection(nameof(SharedIntegrationHostFixture))] public class CSharpExtractInterfaceDialog : AbstractEditorTest { protected override string LanguageName => LanguageNames.CSharp; private ExtractInterfaceDialog_OutOfProc ExtractInterfaceDialog => VisualStudio.ExtractInterfaceDialog; public CSharpExtractInterfaceDialog(VisualStudioInstanceFactory instanceFactory) : base(instanceFactory, nameof(CSharpExtractInterfaceDialog)) { } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractInterface)] public void VerifyCancellation() { SetUpEditor(@"class C$$ { public void M() { } } "); VisualStudio.Editor.InvokeCodeActionList(); VisualStudio.Editor.Verify.CodeAction("Extract interface...", applyFix: true, blockUntilComplete: false); ExtractInterfaceDialog.VerifyOpen(); ExtractInterfaceDialog.ClickCancel(); ExtractInterfaceDialog.VerifyClosed(); VisualStudio.Editor.Verify.TextContains(@"class C { public void M() { } } "); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractInterface)] public void CheckFileName() { SetUpEditor(@"class C$$ { public void M() { } } "); VisualStudio.Editor.InvokeCodeActionList(); VisualStudio.Editor.Verify.CodeAction("Extract interface...", applyFix: true, blockUntilComplete: false); ExtractInterfaceDialog.VerifyOpen(); var targetFileName = ExtractInterfaceDialog.GetTargetFileName(); Assert.Equal(expected: "IC.cs", actual: targetFileName); ExtractInterfaceDialog.ClickCancel(); ExtractInterfaceDialog.VerifyClosed(); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractInterface)] public void VerifySelectAndDeselectAllButtons() { SetUpEditor(@"class C$$ { public void M1() { } public void M2() { } } "); VisualStudio.Editor.InvokeCodeActionList(); VisualStudio.Editor.Verify.CodeAction("Extract interface...", applyFix: true, blockUntilComplete: false); ExtractInterfaceDialog.VerifyOpen(); var selectedItems = ExtractInterfaceDialog.GetSelectedItems(); Assert.Equal( expected: new[] { "M1()", "M2()" }, actual: selectedItems); ExtractInterfaceDialog.ClickDeselectAll(); selectedItems = ExtractInterfaceDialog.GetSelectedItems(); Assert.Empty(selectedItems); ExtractInterfaceDialog.ClickSelectAll(); selectedItems = ExtractInterfaceDialog.GetSelectedItems(); Assert.Equal( expected: new[] { "M1()", "M2()" }, actual: selectedItems); ExtractInterfaceDialog.ClickCancel(); ExtractInterfaceDialog.VerifyClosed(); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractInterface)] public void OnlySelectedItemsAreGenerated() { SetUpEditor(@"class C$$ { public void M1() { } public void M2() { } } "); VisualStudio.Editor.InvokeCodeActionList(); VisualStudio.Editor.Verify.CodeAction("Extract interface...", applyFix: true, blockUntilComplete: false); ExtractInterfaceDialog.VerifyOpen(); ExtractInterfaceDialog.ClickDeselectAll(); ExtractInterfaceDialog.ToggleItem("M2()"); ExtractInterfaceDialog.ClickOK(); ExtractInterfaceDialog.VerifyClosed(); var project = new ProjectUtils.Project(ProjectName); VisualStudio.SolutionExplorer.OpenFile(project, "Class1.cs"); VisualStudio.Editor.Verify.TextContains(@"class C : IC { public void M1() { } public void M2() { } } "); VisualStudio.SolutionExplorer.OpenFile(project, "IC.cs"); VisualStudio.Editor.Verify.TextContains(@"interface IC { void M2(); }"); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractInterface)] public void CheckSameFile() { SetUpEditor(@"class C$$ { public void M() { } } "); VisualStudio.Editor.InvokeCodeActionList(); VisualStudio.Editor.Verify.CodeAction("Extract interface...", applyFix: true, blockUntilComplete: false); ExtractInterfaceDialog.VerifyOpen(); ExtractInterfaceDialog.SelectSameFile(); ExtractInterfaceDialog.ClickOK(); ExtractInterfaceDialog.VerifyClosed(); _ = new ProjectUtils.Project(ProjectName); VisualStudio.Editor.Verify.TextContains(@"interface IC { void M(); } class C : IC { public void M() { } } "); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractInterface)] public void CheckSameFileOnlySelectedItems() { SetUpEditor(@"class C$$ { public void M1() { } public void M2() { } } "); VisualStudio.Editor.InvokeCodeActionList(); VisualStudio.Editor.Verify.CodeAction("Extract interface...", applyFix: true, blockUntilComplete: false); ExtractInterfaceDialog.VerifyOpen(); ExtractInterfaceDialog.ClickDeselectAll(); ExtractInterfaceDialog.ToggleItem("M2()"); ExtractInterfaceDialog.SelectSameFile(); ExtractInterfaceDialog.ClickOK(); ExtractInterfaceDialog.VerifyClosed(); VisualStudio.Editor.Verify.TextContains(@"interface IC { void M2(); } class C : IC { public void M1() { } public void M2() { } } "); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractInterface)] public void CheckSameFileNamespace() { SetUpEditor(@"namespace A { class C$$ { public void M() { } } } "); VisualStudio.Editor.InvokeCodeActionList(); VisualStudio.Editor.Verify.CodeAction("Extract interface...", applyFix: true, blockUntilComplete: false); ExtractInterfaceDialog.VerifyOpen(); ExtractInterfaceDialog.SelectSameFile(); ExtractInterfaceDialog.ClickOK(); ExtractInterfaceDialog.VerifyClosed(); _ = new ProjectUtils.Project(ProjectName); VisualStudio.Editor.Verify.TextContains(@"namespace A { interface IC { void M(); } class C : IC { public void M() { } } } "); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractInterface)] public void CheckSameWithTypes() { SetUpEditor(@"class C$$ { public bool M() => false; } "); VisualStudio.Editor.InvokeCodeActionList(); VisualStudio.Editor.Verify.CodeAction("Extract interface...", applyFix: true, blockUntilComplete: false); ExtractInterfaceDialog.VerifyOpen(); ExtractInterfaceDialog.SelectSameFile(); ExtractInterfaceDialog.ClickOK(); ExtractInterfaceDialog.VerifyClosed(); _ = new ProjectUtils.Project(ProjectName); VisualStudio.Editor.Verify.TextContains(@"interface IC { bool M(); } class C : IC { public bool M() => false; } "); } } }
-1
dotnet/roslyn
55,256
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-30T00:02:02Z
2021-07-30T09:17:54Z
6ce9c0048d37026337701fac035ac0745f6fe49f
88b59775dc6375635957ef229116460f290072aa
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/Extensions/SyntaxGeneratorExtensions_CreateGetHashCodeMethod.cs
// Licensed to the .NET Foundation under one or more agreements. // 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 Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Shared.Extensions { internal static partial class SyntaxGeneratorExtensions { private const string GetHashCodeName = nameof(object.GetHashCode); public static ImmutableArray<SyntaxNode> GetGetHashCodeComponents( this SyntaxGenerator factory, SyntaxGeneratorInternal generatorInternal, Compilation compilation, INamedTypeSymbol? containingType, ImmutableArray<ISymbol> members, bool justMemberReference) { var result = ArrayBuilder<SyntaxNode>.GetInstance(); if (containingType != null && GetBaseGetHashCodeMethod(containingType) != null) { result.Add(factory.InvocationExpression( factory.MemberAccessExpression(factory.BaseExpression(), GetHashCodeName))); } foreach (var member in members) { result.Add(GetMemberForGetHashCode(factory, generatorInternal, compilation, member, justMemberReference)); } return result.ToImmutableAndFree(); } public static ImmutableArray<SyntaxNode> CreateGetHashCodeStatementsUsingSystemHashCode( this SyntaxGenerator factory, SyntaxGeneratorInternal generatorInternal, INamedTypeSymbol hashCodeType, ImmutableArray<SyntaxNode> memberReferences) { if (memberReferences.Length <= 8) { var statement = factory.ReturnStatement( factory.InvocationExpression( factory.MemberAccessExpression(factory.TypeExpression(hashCodeType), "Combine"), memberReferences)); return ImmutableArray.Create(statement); } const string hashName = "hash"; var statements = ArrayBuilder<SyntaxNode>.GetInstance(); statements.Add(factory.SimpleLocalDeclarationStatement(generatorInternal, hashCodeType, hashName, factory.ObjectCreationExpression(hashCodeType))); var localReference = factory.IdentifierName(hashName); foreach (var member in memberReferences) { statements.Add(factory.ExpressionStatement( factory.InvocationExpression( factory.MemberAccessExpression(localReference, "Add"), member))); } statements.Add(factory.ReturnStatement( factory.InvocationExpression( factory.MemberAccessExpression(localReference, "ToHashCode")))); return statements.ToImmutableAndFree(); } /// <summary> /// Generates an override of <see cref="object.GetHashCode()"/> similar to the one /// generated for anonymous types. /// </summary> public static ImmutableArray<SyntaxNode> CreateGetHashCodeMethodStatements( this SyntaxGenerator factory, SyntaxGeneratorInternal generatorInternal, Compilation compilation, INamedTypeSymbol containingType, ImmutableArray<ISymbol> members, bool useInt64) { var components = GetGetHashCodeComponents( factory, generatorInternal, compilation, containingType, members, justMemberReference: false); if (components.Length == 0) { return ImmutableArray.Create(factory.ReturnStatement(factory.LiteralExpression(0))); } const int hashFactor = -1521134295; var initHash = 0; var baseHashCode = GetBaseGetHashCodeMethod(containingType); if (baseHashCode != null) { initHash = initHash * hashFactor + Hash.GetFNVHashCode(baseHashCode.Name); } foreach (var symbol in members) { initHash = initHash * hashFactor + Hash.GetFNVHashCode(symbol.Name); } if (components.Length == 1 && !useInt64) { // If there's just one value to hash, then we can compute and directly // return it. i.e. The full computation is: // // return initHash * hashfactor + ... // // But as we know the values of initHash and hashFactor we can just compute // is here and directly inject the result value, producing: // // return someHash + this.S1.GetHashCode(); // or var multiplyResult = initHash * hashFactor; return ImmutableArray.Create(factory.ReturnStatement( factory.AddExpression( CreateLiteralExpression(factory, multiplyResult), components[0]))); } var statements = ArrayBuilder<SyntaxNode>.GetInstance(); // initialize the initial hashCode: // // var hashCode = initialHashCode; const string HashCodeName = "hashCode"; statements.Add(!useInt64 ? factory.SimpleLocalDeclarationStatement(generatorInternal, compilation.GetSpecialType(SpecialType.System_Int32), HashCodeName, CreateLiteralExpression(factory, initHash)) : factory.LocalDeclarationStatement(compilation.GetSpecialType(SpecialType.System_Int64), HashCodeName, CreateLiteralExpression(factory, initHash))); var hashCodeNameExpression = factory.IdentifierName(HashCodeName); // -1521134295 var permuteValue = CreateLiteralExpression(factory, hashFactor); foreach (var component in components) { // hashCode = hashCode * -1521134295 + this.S.GetHashCode(); var rightSide = factory.AddExpression( factory.MultiplyExpression(hashCodeNameExpression, permuteValue), component); if (useInt64) { rightSide = factory.InvocationExpression( factory.MemberAccessExpression(rightSide, GetHashCodeName)); } statements.Add(factory.ExpressionStatement( factory.AssignmentStatement(hashCodeNameExpression, rightSide))); } // And finally, the "return hashCode;" statement. statements.Add(!useInt64 ? factory.ReturnStatement(hashCodeNameExpression) : factory.ReturnStatement( factory.ConvertExpression( compilation.GetSpecialType(SpecialType.System_Int32), hashCodeNameExpression))); return statements.ToImmutableAndFree(); } /// <summary> /// In VB it's more idiomatic to write things like <c>Dim t = TryCast(obj, SomeType)</c> /// instead of <c>Dim t As SomeType = TryCast(obj, SomeType)</c>, so we just elide the type /// from the decl. For C# we don't want to do this though. We want to always include the /// type and let the simplifier decide if it should be <c>var</c> or not. /// </summary> private static SyntaxNode SimpleLocalDeclarationStatement( this SyntaxGenerator generator, SyntaxGeneratorInternal generatorInternal, INamedTypeSymbol namedTypeSymbol, string name, SyntaxNode initializer) { return generatorInternal.RequiresLocalDeclarationType() ? generator.LocalDeclarationStatement(namedTypeSymbol, name, initializer) : generator.LocalDeclarationStatement(name, initializer); } private static SyntaxNode CreateLiteralExpression(SyntaxGenerator factory, int value) => value < 0 ? factory.NegateExpression(factory.LiteralExpression(-value)) : factory.LiteralExpression(value); public static IMethodSymbol? GetBaseGetHashCodeMethod(INamedTypeSymbol containingType) { if (containingType.IsValueType) { // Don't want to produce base.GetHashCode for a value type. The point with value // types is to produce a good, fast, hash ourselves, avoiding the built in slow // one in System.ValueType. return null; } // Check if any of our base types override GetHashCode. If so, first check with them. var existingMethods = from baseType in containingType.GetBaseTypes() from method in baseType.GetMembers(GetHashCodeName).OfType<IMethodSymbol>() where method.IsOverride && method.DeclaredAccessibility == Accessibility.Public && !method.IsStatic && method.Parameters.Length == 0 && method.ReturnType.SpecialType == SpecialType.System_Int32 && !method.IsAbstract select method; return existingMethods.FirstOrDefault(); } private static SyntaxNode GetMemberForGetHashCode( SyntaxGenerator factory, SyntaxGeneratorInternal generatorInternal, Compilation compilation, ISymbol member, bool justMemberReference) { var getHashCodeNameExpression = factory.IdentifierName(GetHashCodeName); var thisSymbol = factory.MemberAccessExpression(factory.ThisExpression(), factory.IdentifierName(member.Name)).WithAdditionalAnnotations(Simplification.Simplifier.Annotation); // Caller only wanted the reference to the member, nothing else added. if (justMemberReference) { return thisSymbol; } if (member.GetSymbolType()?.IsValueType ?? false) { // There is no reason to generate the bulkier syntax of EqualityComparer<>.Default.GetHashCode for value // types. No null check is necessary, and there's no performance advantage on .NET Core for using // EqualityComparer.GetHashCode instead of calling GetHashCode directly. On .NET Framework, using // EqualityComparer.GetHashCode on value types actually performs more poorly. return factory.InvocationExpression( factory.MemberAccessExpression(thisSymbol, nameof(object.GetHashCode))); } else { return factory.InvocationExpression( factory.MemberAccessExpression( GetDefaultEqualityComparer(factory, generatorInternal, compilation, GetType(compilation, member)), getHashCodeNameExpression), thisSymbol); } } } }
// Licensed to the .NET Foundation under one or more agreements. // 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 Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Shared.Extensions { internal static partial class SyntaxGeneratorExtensions { private const string GetHashCodeName = nameof(object.GetHashCode); public static ImmutableArray<SyntaxNode> GetGetHashCodeComponents( this SyntaxGenerator factory, SyntaxGeneratorInternal generatorInternal, Compilation compilation, INamedTypeSymbol? containingType, ImmutableArray<ISymbol> members, bool justMemberReference) { var result = ArrayBuilder<SyntaxNode>.GetInstance(); if (containingType != null && GetBaseGetHashCodeMethod(containingType) != null) { result.Add(factory.InvocationExpression( factory.MemberAccessExpression(factory.BaseExpression(), GetHashCodeName))); } foreach (var member in members) { result.Add(GetMemberForGetHashCode(factory, generatorInternal, compilation, member, justMemberReference)); } return result.ToImmutableAndFree(); } public static ImmutableArray<SyntaxNode> CreateGetHashCodeStatementsUsingSystemHashCode( this SyntaxGenerator factory, SyntaxGeneratorInternal generatorInternal, INamedTypeSymbol hashCodeType, ImmutableArray<SyntaxNode> memberReferences) { if (memberReferences.Length <= 8) { var statement = factory.ReturnStatement( factory.InvocationExpression( factory.MemberAccessExpression(factory.TypeExpression(hashCodeType), "Combine"), memberReferences)); return ImmutableArray.Create(statement); } const string hashName = "hash"; var statements = ArrayBuilder<SyntaxNode>.GetInstance(); statements.Add(factory.SimpleLocalDeclarationStatement(generatorInternal, hashCodeType, hashName, factory.ObjectCreationExpression(hashCodeType))); var localReference = factory.IdentifierName(hashName); foreach (var member in memberReferences) { statements.Add(factory.ExpressionStatement( factory.InvocationExpression( factory.MemberAccessExpression(localReference, "Add"), member))); } statements.Add(factory.ReturnStatement( factory.InvocationExpression( factory.MemberAccessExpression(localReference, "ToHashCode")))); return statements.ToImmutableAndFree(); } /// <summary> /// Generates an override of <see cref="object.GetHashCode()"/> similar to the one /// generated for anonymous types. /// </summary> public static ImmutableArray<SyntaxNode> CreateGetHashCodeMethodStatements( this SyntaxGenerator factory, SyntaxGeneratorInternal generatorInternal, Compilation compilation, INamedTypeSymbol containingType, ImmutableArray<ISymbol> members, bool useInt64) { var components = GetGetHashCodeComponents( factory, generatorInternal, compilation, containingType, members, justMemberReference: false); if (components.Length == 0) { return ImmutableArray.Create(factory.ReturnStatement(factory.LiteralExpression(0))); } const int hashFactor = -1521134295; var initHash = 0; var baseHashCode = GetBaseGetHashCodeMethod(containingType); if (baseHashCode != null) { initHash = initHash * hashFactor + Hash.GetFNVHashCode(baseHashCode.Name); } foreach (var symbol in members) { initHash = initHash * hashFactor + Hash.GetFNVHashCode(symbol.Name); } if (components.Length == 1 && !useInt64) { // If there's just one value to hash, then we can compute and directly // return it. i.e. The full computation is: // // return initHash * hashfactor + ... // // But as we know the values of initHash and hashFactor we can just compute // is here and directly inject the result value, producing: // // return someHash + this.S1.GetHashCode(); // or var multiplyResult = initHash * hashFactor; return ImmutableArray.Create(factory.ReturnStatement( factory.AddExpression( CreateLiteralExpression(factory, multiplyResult), components[0]))); } var statements = ArrayBuilder<SyntaxNode>.GetInstance(); // initialize the initial hashCode: // // var hashCode = initialHashCode; const string HashCodeName = "hashCode"; statements.Add(!useInt64 ? factory.SimpleLocalDeclarationStatement(generatorInternal, compilation.GetSpecialType(SpecialType.System_Int32), HashCodeName, CreateLiteralExpression(factory, initHash)) : factory.LocalDeclarationStatement(compilation.GetSpecialType(SpecialType.System_Int64), HashCodeName, CreateLiteralExpression(factory, initHash))); var hashCodeNameExpression = factory.IdentifierName(HashCodeName); // -1521134295 var permuteValue = CreateLiteralExpression(factory, hashFactor); foreach (var component in components) { // hashCode = hashCode * -1521134295 + this.S.GetHashCode(); var rightSide = factory.AddExpression( factory.MultiplyExpression(hashCodeNameExpression, permuteValue), component); if (useInt64) { rightSide = factory.InvocationExpression( factory.MemberAccessExpression(rightSide, GetHashCodeName)); } statements.Add(factory.ExpressionStatement( factory.AssignmentStatement(hashCodeNameExpression, rightSide))); } // And finally, the "return hashCode;" statement. statements.Add(!useInt64 ? factory.ReturnStatement(hashCodeNameExpression) : factory.ReturnStatement( factory.ConvertExpression( compilation.GetSpecialType(SpecialType.System_Int32), hashCodeNameExpression))); return statements.ToImmutableAndFree(); } /// <summary> /// In VB it's more idiomatic to write things like <c>Dim t = TryCast(obj, SomeType)</c> /// instead of <c>Dim t As SomeType = TryCast(obj, SomeType)</c>, so we just elide the type /// from the decl. For C# we don't want to do this though. We want to always include the /// type and let the simplifier decide if it should be <c>var</c> or not. /// </summary> private static SyntaxNode SimpleLocalDeclarationStatement( this SyntaxGenerator generator, SyntaxGeneratorInternal generatorInternal, INamedTypeSymbol namedTypeSymbol, string name, SyntaxNode initializer) { return generatorInternal.RequiresLocalDeclarationType() ? generator.LocalDeclarationStatement(namedTypeSymbol, name, initializer) : generator.LocalDeclarationStatement(name, initializer); } private static SyntaxNode CreateLiteralExpression(SyntaxGenerator factory, int value) => value < 0 ? factory.NegateExpression(factory.LiteralExpression(-value)) : factory.LiteralExpression(value); public static IMethodSymbol? GetBaseGetHashCodeMethod(INamedTypeSymbol containingType) { if (containingType.IsValueType) { // Don't want to produce base.GetHashCode for a value type. The point with value // types is to produce a good, fast, hash ourselves, avoiding the built in slow // one in System.ValueType. return null; } // Check if any of our base types override GetHashCode. If so, first check with them. var existingMethods = from baseType in containingType.GetBaseTypes() from method in baseType.GetMembers(GetHashCodeName).OfType<IMethodSymbol>() where method.IsOverride && method.DeclaredAccessibility == Accessibility.Public && !method.IsStatic && method.Parameters.Length == 0 && method.ReturnType.SpecialType == SpecialType.System_Int32 && !method.IsAbstract select method; return existingMethods.FirstOrDefault(); } private static SyntaxNode GetMemberForGetHashCode( SyntaxGenerator factory, SyntaxGeneratorInternal generatorInternal, Compilation compilation, ISymbol member, bool justMemberReference) { var getHashCodeNameExpression = factory.IdentifierName(GetHashCodeName); var thisSymbol = factory.MemberAccessExpression(factory.ThisExpression(), factory.IdentifierName(member.Name)).WithAdditionalAnnotations(Simplification.Simplifier.Annotation); // Caller only wanted the reference to the member, nothing else added. if (justMemberReference) { return thisSymbol; } if (member.GetSymbolType()?.IsValueType ?? false) { // There is no reason to generate the bulkier syntax of EqualityComparer<>.Default.GetHashCode for value // types. No null check is necessary, and there's no performance advantage on .NET Core for using // EqualityComparer.GetHashCode instead of calling GetHashCode directly. On .NET Framework, using // EqualityComparer.GetHashCode on value types actually performs more poorly. return factory.InvocationExpression( factory.MemberAccessExpression(thisSymbol, nameof(object.GetHashCode))); } else { return factory.InvocationExpression( factory.MemberAccessExpression( GetDefaultEqualityComparer(factory, generatorInternal, compilation, GetType(compilation, member)), getHashCodeNameExpression), thisSymbol); } } } }
-1
dotnet/roslyn
55,256
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-30T00:02:02Z
2021-07-30T09:17:54Z
6ce9c0048d37026337701fac035ac0745f6fe49f
88b59775dc6375635957ef229116460f290072aa
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Compilers/Test/Utilities/CSharp/CompilingTestBase.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Emit; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Emit; using Roslyn.Test.Utilities; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { // Some utility functions for compiling and checking errors. public abstract class CompilingTestBase : CSharpTestBase { private const string DefaultTypeName = "C"; private const string DefaultMethodName = "M"; internal static BoundBlock ParseAndBindMethodBody(string program, string typeName = DefaultTypeName, string methodName = DefaultMethodName) { var compilation = CreateCompilation(program); var method = (MethodSymbol)compilation.GlobalNamespace.GetTypeMembers(typeName).Single().GetMembers(methodName).Single(); // Provide an Emit.Module so that the lowering passes will be run var module = new PEAssemblyBuilder( (SourceAssemblySymbol)compilation.Assembly, emitOptions: EmitOptions.Default, outputKind: OutputKind.ConsoleApplication, serializationProperties: GetDefaultModulePropertiesForSerialization(), manifestResources: Enumerable.Empty<ResourceDescription>()); TypeCompilationState compilationState = new TypeCompilationState(method.ContainingType, compilation, module); var diagnostics = DiagnosticBag.GetInstance(); var block = MethodCompiler.BindMethodBody(method, compilationState, new BindingDiagnosticBag(diagnostics)); diagnostics.Free(); return block; } public const string LINQ = #region the string LINQ defines a complete LINQ API called List1<T> (for instance method) and List2<T> (for extension methods) @"using System; using System.Text; public delegate R Func1<in T1, out R>(T1 arg1); public delegate R Func1<in T1, in T2, out R>(T1 arg1, T2 arg2); public class List1<T> { internal T[] data; internal int length; public List1(params T[] args) { this.data = (T[])args.Clone(); this.length = data.Length; } public List1() { this.data = new T[0]; this.length = 0; } public int Length { get { return length; } } //public T this[int index] { get { return this.data[index]; } } public T Get(int index) { return this.data[index]; } public virtual void Add(T t) { if (data.Length == length) Array.Resize(ref data, data.Length * 2 + 1); data[length++] = t; } public override string ToString() { StringBuilder builder = new StringBuilder(); builder.Append('['); for (int i = 0; i < Length; i++) { if (i != 0) builder.Append(',').Append(' '); builder.Append(data[i]); } builder.Append(']'); return builder.ToString(); } public List1<E> Cast<E>() { E[] data = new E[Length]; for (int i = 0; i < Length; i++) data[i] = (E)(object)this.data[i]; return new List1<E>(data); } public List1<T> Where(Func1<T, bool> predicate) { List1<T> result = new List1<T>(); for (int i = 0; i < Length; i++) { T datum = this.data[i]; if (predicate(datum)) result.Add(datum); } return result; } public List1<U> Select<U>(Func1<T, U> selector) { int length = this.Length; U[] data = new U[length]; for (int i = 0; i < length; i++) data[i] = selector(this.data[i]); return new List1<U>(data); } public List1<V> SelectMany<U, V>(Func1<T, List1<U>> selector, Func1<T, U, V> resultSelector) { List1<V> result = new List1<V>(); int length = this.Length; for (int i = 0; i < length; i++) { T t = this.data[i]; List1<U> selected = selector(t); int ulength = selected.Length; for (int j = 0; j < ulength; j++) { U u = selected.data[j]; V v = resultSelector(t, u); result.Add(v); } } return result; } public List1<V> Join<U, K, V>(List1<U> inner, Func1<T, K> outerKeyselector, Func1<U, K> innerKeyselector, Func1<T, U, V> resultSelector) { List1<Joined<K, T, U>> joined = new List1<Joined<K, T, U>>(); for (int i = 0; i < Length; i++) { T t = this.Get(i); K k = outerKeyselector(t); Joined<K, T, U> row = null; for (int j = 0; j < joined.Length; j++) { if (joined.Get(j).k.Equals(k)) { row = joined.Get(j); break; } } if (row == null) joined.Add(row = new Joined<K, T, U>(k)); row.t.Add(t); } for (int i = 0; i < inner.Length; i++) { U u = inner.Get(i); K k = innerKeyselector(u); Joined<K, T, U> row = null; for (int j = 0; j < joined.Length; j++) { if (joined.Get(j).k.Equals(k)) { row = joined.Get(j); break; } } if (row == null) joined.Add(row = new Joined<K, T, U>(k)); row.u.Add(u); } List1<V> result = new List1<V>(); for (int i = 0; i < joined.Length; i++) { Joined<K, T, U> row = joined.Get(i); for (int j = 0; j < row.t.Length; j++) { T t = row.t.Get(j); for (int k = 0; k < row.u.Length; k++) { U u = row.u.Get(k); V v = resultSelector(t, u); result.Add(v); } } } return result; } class Joined<K, T2, U> { public Joined(K k) { this.k = k; this.t = new List1<T2>(); this.u = new List1<U>(); } public readonly K k; public readonly List1<T2> t; public readonly List1<U> u; } public List1<V> GroupJoin<U, K, V>(List1<U> inner, Func1<T, K> outerKeyselector, Func1<U, K> innerKeyselector, Func1<T, List1<U>, V> resultSelector) { List1<Joined<K, T, U>> joined = new List1<Joined<K, T, U>>(); for (int i = 0; i < Length; i++) { T t = this.Get(i); K k = outerKeyselector(t); Joined<K, T, U> row = null; for (int j = 0; j < joined.Length; j++) { if (joined.Get(j).k.Equals(k)) { row = joined.Get(j); break; } } if (row == null) joined.Add(row = new Joined<K, T, U>(k)); row.t.Add(t); } for (int i = 0; i < inner.Length; i++) { U u = inner.Get(i); K k = innerKeyselector(u); Joined<K, T, U> row = null; for (int j = 0; j < joined.Length; j++) { if (joined.Get(j).k.Equals(k)) { row = joined.Get(j); break; } } if (row == null) joined.Add(row = new Joined<K, T, U>(k)); row.u.Add(u); } List1<V> result = new List1<V>(); for (int i = 0; i < joined.Length; i++) { Joined<K, T, U> row = joined.Get(i); for (int j = 0; j < row.t.Length; j++) { T t = row.t.Get(j); V v = resultSelector(t, row.u); result.Add(v); } } return result; } public OrderedList1<T> OrderBy<K>(Func1<T, K> Keyselector) { OrderedList1<T> result = new OrderedList1<T>(this); result.ThenBy(Keyselector); return result; } public OrderedList1<T> OrderByDescending<K>(Func1<T, K> Keyselector) { OrderedList1<T> result = new OrderedList1<T>(this); result.ThenByDescending(Keyselector); return result; } public List1<Group1<K, T>> GroupBy<K>(Func1<T, K> Keyselector) { List1<Group1<K, T>> result = new List1<Group1<K, T>>(); for (int i = 0; i < Length; i++) { T t = this.Get(i); K k = Keyselector(t); Group1<K, T> Group1 = null; for (int j = 0; j < result.Length; j++) { if (result.Get(j).Key.Equals(k)) { Group1 = result.Get(j); break; } } if (Group1 == null) { result.Add(Group1 = new Group1<K, T>(k)); } Group1.Add(t); } return result; } public List1<Group1<K, E>> GroupBy<K, E>(Func1<T, K> Keyselector, Func1<T, E> elementSelector) { List1<Group1<K, E>> result = new List1<Group1<K, E>>(); for (int i = 0; i < Length; i++) { T t = this.Get(i); K k = Keyselector(t); Group1<K, E> Group1 = null; for (int j = 0; j < result.Length; j++) { if (result.Get(j).Key.Equals(k)) { Group1 = result.Get(j); break; } } if (Group1 == null) { result.Add(Group1 = new Group1<K, E>(k)); } Group1.Add(elementSelector(t)); } return result; } } public class OrderedList1<T> : List1<T> { private List1<Keys1> Keys1; public override void Add(T t) { throw new NotSupportedException(); } internal OrderedList1(List1<T> list) { Keys1 = new List1<Keys1>(); for (int i = 0; i < list.Length; i++) { base.Add(list.Get(i)); Keys1.Add(new Keys1()); } } public OrderedList1<T> ThenBy<K>(Func1<T, K> Keyselector) { for (int i = 0; i < Length; i++) { object o = Keyselector(this.Get(i)); // work around bug 8405 Keys1.Get(i).Add((IComparable)o); } Sort(); return this; } class ReverseOrder : IComparable { IComparable c; public ReverseOrder(IComparable c) { this.c = c; } public int CompareTo(object o) { ReverseOrder other = (ReverseOrder)o; return other.c.CompareTo(this.c); } public override string ToString() { return String.Empty + '-' + c; } } public OrderedList1<T> ThenByDescending<K>(Func1<T, K> Keyselector) { for (int i = 0; i < Length; i++) { object o = Keyselector(this.Get(i)); // work around bug 8405 Keys1.Get(i).Add(new ReverseOrder((IComparable)o)); } Sort(); return this; } void Sort() { Array.Sort(this.Keys1.data, this.data, 0, Length); } } class Keys1 : List1<IComparable>, IComparable { public int CompareTo(object o) { Keys1 other = (Keys1)o; for (int i = 0; i < Length; i++) { int c = this.Get(i).CompareTo(other.Get(i)); if (c != 0) return c; } return 0; } } public class Group1<K, T> : List1<T> { public Group1(K k, params T[] data) : base(data) { this.Key = k; } public K Key { get; private set; } public override string ToString() { return Key + String.Empty + ':' + base.ToString(); } } //public delegate R Func2<in T1, out R>(T1 arg1); //public delegate R Func2<in T1, in T2, out R>(T1 arg1, T2 arg2); // //public class List2<T> //{ // internal T[] data; // internal int length; // // public List2(params T[] args) // { // this.data = (T[])args.Clone(); // this.length = data.Length; // } // // public List2() // { // this.data = new T[0]; // this.length = 0; // } // // public int Length { get { return length; } } // // //public T this[int index] { get { return this.data[index]; } } // public T Get(int index) { return this.data[index]; } // // public virtual void Add(T t) // { // if (data.Length == length) Array.Resize(ref data, data.Length * 2 + 1); // data[length++] = t; // } // // public override string ToString() // { // StringBuilder builder = new StringBuilder(); // builder.Append('['); // for (int i = 0; i < Length; i++) // { // if (i != 0) builder.Append(',').Append(' '); // builder.Append(data[i]); // } // builder.Append(']'); // return builder.ToString(); // } // //} // //public class OrderedList2<T> : List2<T> //{ // internal List2<Keys2> Keys2; // // public override void Add(T t) // { // throw new NotSupportedException(); // } // // internal OrderedList2(List2<T> list) // { // Keys2 = new List2<Keys2>(); // for (int i = 0; i < list.Length; i++) // { // base.Add(list.Get(i)); // Keys2.Add(new Keys2()); // } // } // // internal void Sort() // { // Array.Sort(this.Keys2.data, this.data, 0, Length); // } //} // //class Keys2 : List2<IComparable>, IComparable //{ // public int CompareTo(object o) // { // Keys2 other = (Keys2)o; // for (int i = 0; i < Length; i++) // { // int c = this.Get(i).CompareTo(other.Get(i)); // if (c != 0) return c; // } // return 0; // } //} // //public class Group2<K, T> : List2<T> //{ // public Group2(K k, params T[] data) // : base(data) // { // this.Key = k; // } // // public K Key { get; private set; } // // public override string ToString() // { // return Key + String.Empty + ':' + base.ToString(); // } //} // //public static class Extensions2 //{ // // public static List2<E> Cast<T, E>(this List2<T> _this) // { // E[] data = new E[_this.Length]; // for (int i = 0; i < _this.Length; i++) // data[i] = (E)(object)_this.data[i]; // return new List2<E>(data); // } // // public static List2<T> Where<T>(this List2<T> _this, Func2<T, bool> predicate) // { // List2<T> result = new List2<T>(); // for (int i = 0; i < _this.Length; i++) // { // T datum = _this.data[i]; // if (predicate(datum)) result.Add(datum); // } // return result; // } // // public static List2<U> Select<T,U>(this List2<T> _this, Func2<T, U> selector) // { // int length = _this.Length; // U[] data = new U[length]; // for (int i = 0; i < length; i++) data[i] = selector(_this.data[i]); // return new List2<U>(data); // } // // public static List2<V> SelectMany<T, U, V>(this List2<T> _this, Func2<T, List2<U>> selector, Func2<T, U, V> resultSelector) // { // List2<V> result = new List2<V>(); // int length = _this.Length; // for (int i = 0; i < length; i++) // { // T t = _this.data[i]; // List2<U> selected = selector(t); // int ulength = selected.Length; // for (int j = 0; j < ulength; j++) // { // U u = selected.data[j]; // V v = resultSelector(t, u); // result.Add(v); // } // } // // return result; // } // // public static List2<V> Join<T, U, K, V>(this List2<T> _this, List2<U> inner, Func2<T, K> outerKeyselector, // Func2<U, K> innerKeyselector, Func2<T, U, V> resultSelector) // { // List2<Joined<K, T, U>> joined = new List2<Joined<K, T, U>>(); // for (int i = 0; i < _this.Length; i++) // { // T t = _this.Get(i); // K k = outerKeyselector(t); // Joined<K, T, U> row = null; // for (int j = 0; j < joined.Length; j++) // { // if (joined.Get(j).k.Equals(k)) // { // row = joined.Get(j); // break; // } // } // if (row == null) joined.Add(row = new Joined<K, T, U>(k)); // row.t.Add(t); // } // for (int i = 0; i < inner.Length; i++) // { // U u = inner.Get(i); // K k = innerKeyselector(u); // Joined<K, T, U> row = null; // for (int j = 0; j < joined.Length; j++) // { // if (joined.Get(j).k.Equals(k)) // { // row = joined.Get(j); // break; // } // } // if (row == null) joined.Add(row = new Joined<K, T, U>(k)); // row.u.Add(u); // } // List2<V> result = new List2<V>(); // for (int i = 0; i < joined.Length; i++) // { // Joined<K, T, U> row = joined.Get(i); // for (int j = 0; j < row.t.Length; j++) // { // T t = row.t.Get(j); // for (int k = 0; k < row.u.Length; k++) // { // U u = row.u.Get(k); // V v = resultSelector(t, u); // result.Add(v); // } // } // } // return result; // } // // class Joined<K, T2, U> // { // public Joined(K k) // { // this.k = k; // this.t = new List2<T2>(); // this.u = new List2<U>(); // } // public readonly K k; // public readonly List2<T2> t; // public readonly List2<U> u; // } // // public static List2<V> GroupJoin<T, U, K, V>(this List2<T> _this, List2<U> inner, Func2<T, K> outerKeyselector, // Func2<U, K> innerKeyselector, Func2<T, List2<U>, V> resultSelector) // { // List2<Joined<K, T, U>> joined = new List2<Joined<K, T, U>>(); // for (int i = 0; i < _this.Length; i++) // { // T t = _this.Get(i); // K k = outerKeyselector(t); // Joined<K, T, U> row = null; // for (int j = 0; j < joined.Length; j++) // { // if (joined.Get(j).k.Equals(k)) // { // row = joined.Get(j); // break; // } // } // if (row == null) joined.Add(row = new Joined<K, T, U>(k)); // row.t.Add(t); // } // for (int i = 0; i < inner.Length; i++) // { // U u = inner.Get(i); // K k = innerKeyselector(u); // Joined<K, T, U> row = null; // for (int j = 0; j < joined.Length; j++) // { // if (joined.Get(j).k.Equals(k)) // { // row = joined.Get(j); // break; // } // } // if (row == null) joined.Add(row = new Joined<K, T, U>(k)); // row.u.Add(u); // } // List2<V> result = new List2<V>(); // for (int i = 0; i < joined.Length; i++) // { // Joined<K, T, U> row = joined.Get(i); // for (int j = 0; j < row.t.Length; j++) // { // T t = row.t.Get(j); // V v = resultSelector(t, row.u); // result.Add(v); // } // } // return result; // } // // public static OrderedList2<T> OrderBy<T, K>(this List2<T> _this, Func2<T, K> Keyselector) // { // OrderedList2<T> result = new OrderedList2<T>(_this); // result.ThenBy(Keyselector); // return result; // } // // public static OrderedList2<T> OrderByDescending<T, K>(this List2<T> _this, Func2<T, K> Keyselector) // { // OrderedList2<T> result = new OrderedList2<T>(_this); // result.ThenByDescending(Keyselector); // return result; // } // // public static List2<Group2<K, T>> GroupBy<T, K>(this List2<T> _this, Func2<T, K> Keyselector) // { // List2<Group2<K, T>> result = new List2<Group2<K, T>>(); // for (int i = 0; i < _this.Length; i++) // { // T t = _this.Get(i); // K k = Keyselector(t); // Group2<K, T> Group2 = null; // for (int j = 0; j < result.Length; j++) // { // if (result.Get(j).Key.Equals(k)) // { // Group2 = result.Get(j); // break; // } // } // if (Group2 == null) // { // result.Add(Group2 = new Group2<K, T>(k)); // } // Group2.Add(t); // } // return result; // } // // public static List2<Group2<K, E>> GroupBy<T, K, E>(this List2<T> _this, Func2<T, K> Keyselector, // Func2<T, E> elementSelector) // { // List2<Group2<K, E>> result = new List2<Group2<K, E>>(); // for (int i = 0; i < _this.Length; i++) // { // T t = _this.Get(i); // K k = Keyselector(t); // Group2<K, E> Group2 = null; // for (int j = 0; j < result.Length; j++) // { // if (result.Get(j).Key.Equals(k)) // { // Group2 = result.Get(j); // break; // } // } // if (Group2 == null) // { // result.Add(Group2 = new Group2<K, E>(k)); // } // Group2.Add(elementSelector(t)); // } // return result; // } // // public static OrderedList2<T> ThenBy<T, K>(this OrderedList2<T> _this, Func2<T, K> Keyselector) // { // for (int i = 0; i < _this.Length; i++) // { // object o = Keyselector(_this.Get(i)); // work around bug 8405 // _this.Keys2.Get(i).Add((IComparable)o); // } // _this.Sort(); // return _this; // } // // class ReverseOrder : IComparable // { // IComparable c; // public ReverseOrder(IComparable c) // { // this.c = c; // } // public int CompareTo(object o) // { // ReverseOrder other = (ReverseOrder)o; // return other.c.CompareTo(this.c); // } // public override string ToString() // { // return String.Empty + '-' + c; // } // } // // public static OrderedList2<T> ThenByDescending<T, K>(this OrderedList2<T> _this, Func2<T, K> Keyselector) // { // for (int i = 0; i < _this.Length; i++) // { // object o = Keyselector(_this.Get(i)); // work around bug 8405 // _this.Keys2.Get(i).Add(new ReverseOrder((IComparable)o)); // } // _this.Sort(); // return _this; // } // //} " #endregion the string LINQ ; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Emit; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Emit; using Roslyn.Test.Utilities; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { // Some utility functions for compiling and checking errors. public abstract class CompilingTestBase : CSharpTestBase { private const string DefaultTypeName = "C"; private const string DefaultMethodName = "M"; internal static BoundBlock ParseAndBindMethodBody(string program, string typeName = DefaultTypeName, string methodName = DefaultMethodName) { var compilation = CreateCompilation(program); var method = (MethodSymbol)compilation.GlobalNamespace.GetTypeMembers(typeName).Single().GetMembers(methodName).Single(); // Provide an Emit.Module so that the lowering passes will be run var module = new PEAssemblyBuilder( (SourceAssemblySymbol)compilation.Assembly, emitOptions: EmitOptions.Default, outputKind: OutputKind.ConsoleApplication, serializationProperties: GetDefaultModulePropertiesForSerialization(), manifestResources: Enumerable.Empty<ResourceDescription>()); TypeCompilationState compilationState = new TypeCompilationState(method.ContainingType, compilation, module); var diagnostics = DiagnosticBag.GetInstance(); var block = MethodCompiler.BindMethodBody(method, compilationState, new BindingDiagnosticBag(diagnostics)); diagnostics.Free(); return block; } public const string LINQ = #region the string LINQ defines a complete LINQ API called List1<T> (for instance method) and List2<T> (for extension methods) @"using System; using System.Text; public delegate R Func1<in T1, out R>(T1 arg1); public delegate R Func1<in T1, in T2, out R>(T1 arg1, T2 arg2); public class List1<T> { internal T[] data; internal int length; public List1(params T[] args) { this.data = (T[])args.Clone(); this.length = data.Length; } public List1() { this.data = new T[0]; this.length = 0; } public int Length { get { return length; } } //public T this[int index] { get { return this.data[index]; } } public T Get(int index) { return this.data[index]; } public virtual void Add(T t) { if (data.Length == length) Array.Resize(ref data, data.Length * 2 + 1); data[length++] = t; } public override string ToString() { StringBuilder builder = new StringBuilder(); builder.Append('['); for (int i = 0; i < Length; i++) { if (i != 0) builder.Append(',').Append(' '); builder.Append(data[i]); } builder.Append(']'); return builder.ToString(); } public List1<E> Cast<E>() { E[] data = new E[Length]; for (int i = 0; i < Length; i++) data[i] = (E)(object)this.data[i]; return new List1<E>(data); } public List1<T> Where(Func1<T, bool> predicate) { List1<T> result = new List1<T>(); for (int i = 0; i < Length; i++) { T datum = this.data[i]; if (predicate(datum)) result.Add(datum); } return result; } public List1<U> Select<U>(Func1<T, U> selector) { int length = this.Length; U[] data = new U[length]; for (int i = 0; i < length; i++) data[i] = selector(this.data[i]); return new List1<U>(data); } public List1<V> SelectMany<U, V>(Func1<T, List1<U>> selector, Func1<T, U, V> resultSelector) { List1<V> result = new List1<V>(); int length = this.Length; for (int i = 0; i < length; i++) { T t = this.data[i]; List1<U> selected = selector(t); int ulength = selected.Length; for (int j = 0; j < ulength; j++) { U u = selected.data[j]; V v = resultSelector(t, u); result.Add(v); } } return result; } public List1<V> Join<U, K, V>(List1<U> inner, Func1<T, K> outerKeyselector, Func1<U, K> innerKeyselector, Func1<T, U, V> resultSelector) { List1<Joined<K, T, U>> joined = new List1<Joined<K, T, U>>(); for (int i = 0; i < Length; i++) { T t = this.Get(i); K k = outerKeyselector(t); Joined<K, T, U> row = null; for (int j = 0; j < joined.Length; j++) { if (joined.Get(j).k.Equals(k)) { row = joined.Get(j); break; } } if (row == null) joined.Add(row = new Joined<K, T, U>(k)); row.t.Add(t); } for (int i = 0; i < inner.Length; i++) { U u = inner.Get(i); K k = innerKeyselector(u); Joined<K, T, U> row = null; for (int j = 0; j < joined.Length; j++) { if (joined.Get(j).k.Equals(k)) { row = joined.Get(j); break; } } if (row == null) joined.Add(row = new Joined<K, T, U>(k)); row.u.Add(u); } List1<V> result = new List1<V>(); for (int i = 0; i < joined.Length; i++) { Joined<K, T, U> row = joined.Get(i); for (int j = 0; j < row.t.Length; j++) { T t = row.t.Get(j); for (int k = 0; k < row.u.Length; k++) { U u = row.u.Get(k); V v = resultSelector(t, u); result.Add(v); } } } return result; } class Joined<K, T2, U> { public Joined(K k) { this.k = k; this.t = new List1<T2>(); this.u = new List1<U>(); } public readonly K k; public readonly List1<T2> t; public readonly List1<U> u; } public List1<V> GroupJoin<U, K, V>(List1<U> inner, Func1<T, K> outerKeyselector, Func1<U, K> innerKeyselector, Func1<T, List1<U>, V> resultSelector) { List1<Joined<K, T, U>> joined = new List1<Joined<K, T, U>>(); for (int i = 0; i < Length; i++) { T t = this.Get(i); K k = outerKeyselector(t); Joined<K, T, U> row = null; for (int j = 0; j < joined.Length; j++) { if (joined.Get(j).k.Equals(k)) { row = joined.Get(j); break; } } if (row == null) joined.Add(row = new Joined<K, T, U>(k)); row.t.Add(t); } for (int i = 0; i < inner.Length; i++) { U u = inner.Get(i); K k = innerKeyselector(u); Joined<K, T, U> row = null; for (int j = 0; j < joined.Length; j++) { if (joined.Get(j).k.Equals(k)) { row = joined.Get(j); break; } } if (row == null) joined.Add(row = new Joined<K, T, U>(k)); row.u.Add(u); } List1<V> result = new List1<V>(); for (int i = 0; i < joined.Length; i++) { Joined<K, T, U> row = joined.Get(i); for (int j = 0; j < row.t.Length; j++) { T t = row.t.Get(j); V v = resultSelector(t, row.u); result.Add(v); } } return result; } public OrderedList1<T> OrderBy<K>(Func1<T, K> Keyselector) { OrderedList1<T> result = new OrderedList1<T>(this); result.ThenBy(Keyselector); return result; } public OrderedList1<T> OrderByDescending<K>(Func1<T, K> Keyselector) { OrderedList1<T> result = new OrderedList1<T>(this); result.ThenByDescending(Keyselector); return result; } public List1<Group1<K, T>> GroupBy<K>(Func1<T, K> Keyselector) { List1<Group1<K, T>> result = new List1<Group1<K, T>>(); for (int i = 0; i < Length; i++) { T t = this.Get(i); K k = Keyselector(t); Group1<K, T> Group1 = null; for (int j = 0; j < result.Length; j++) { if (result.Get(j).Key.Equals(k)) { Group1 = result.Get(j); break; } } if (Group1 == null) { result.Add(Group1 = new Group1<K, T>(k)); } Group1.Add(t); } return result; } public List1<Group1<K, E>> GroupBy<K, E>(Func1<T, K> Keyselector, Func1<T, E> elementSelector) { List1<Group1<K, E>> result = new List1<Group1<K, E>>(); for (int i = 0; i < Length; i++) { T t = this.Get(i); K k = Keyselector(t); Group1<K, E> Group1 = null; for (int j = 0; j < result.Length; j++) { if (result.Get(j).Key.Equals(k)) { Group1 = result.Get(j); break; } } if (Group1 == null) { result.Add(Group1 = new Group1<K, E>(k)); } Group1.Add(elementSelector(t)); } return result; } } public class OrderedList1<T> : List1<T> { private List1<Keys1> Keys1; public override void Add(T t) { throw new NotSupportedException(); } internal OrderedList1(List1<T> list) { Keys1 = new List1<Keys1>(); for (int i = 0; i < list.Length; i++) { base.Add(list.Get(i)); Keys1.Add(new Keys1()); } } public OrderedList1<T> ThenBy<K>(Func1<T, K> Keyselector) { for (int i = 0; i < Length; i++) { object o = Keyselector(this.Get(i)); // work around bug 8405 Keys1.Get(i).Add((IComparable)o); } Sort(); return this; } class ReverseOrder : IComparable { IComparable c; public ReverseOrder(IComparable c) { this.c = c; } public int CompareTo(object o) { ReverseOrder other = (ReverseOrder)o; return other.c.CompareTo(this.c); } public override string ToString() { return String.Empty + '-' + c; } } public OrderedList1<T> ThenByDescending<K>(Func1<T, K> Keyselector) { for (int i = 0; i < Length; i++) { object o = Keyselector(this.Get(i)); // work around bug 8405 Keys1.Get(i).Add(new ReverseOrder((IComparable)o)); } Sort(); return this; } void Sort() { Array.Sort(this.Keys1.data, this.data, 0, Length); } } class Keys1 : List1<IComparable>, IComparable { public int CompareTo(object o) { Keys1 other = (Keys1)o; for (int i = 0; i < Length; i++) { int c = this.Get(i).CompareTo(other.Get(i)); if (c != 0) return c; } return 0; } } public class Group1<K, T> : List1<T> { public Group1(K k, params T[] data) : base(data) { this.Key = k; } public K Key { get; private set; } public override string ToString() { return Key + String.Empty + ':' + base.ToString(); } } //public delegate R Func2<in T1, out R>(T1 arg1); //public delegate R Func2<in T1, in T2, out R>(T1 arg1, T2 arg2); // //public class List2<T> //{ // internal T[] data; // internal int length; // // public List2(params T[] args) // { // this.data = (T[])args.Clone(); // this.length = data.Length; // } // // public List2() // { // this.data = new T[0]; // this.length = 0; // } // // public int Length { get { return length; } } // // //public T this[int index] { get { return this.data[index]; } } // public T Get(int index) { return this.data[index]; } // // public virtual void Add(T t) // { // if (data.Length == length) Array.Resize(ref data, data.Length * 2 + 1); // data[length++] = t; // } // // public override string ToString() // { // StringBuilder builder = new StringBuilder(); // builder.Append('['); // for (int i = 0; i < Length; i++) // { // if (i != 0) builder.Append(',').Append(' '); // builder.Append(data[i]); // } // builder.Append(']'); // return builder.ToString(); // } // //} // //public class OrderedList2<T> : List2<T> //{ // internal List2<Keys2> Keys2; // // public override void Add(T t) // { // throw new NotSupportedException(); // } // // internal OrderedList2(List2<T> list) // { // Keys2 = new List2<Keys2>(); // for (int i = 0; i < list.Length; i++) // { // base.Add(list.Get(i)); // Keys2.Add(new Keys2()); // } // } // // internal void Sort() // { // Array.Sort(this.Keys2.data, this.data, 0, Length); // } //} // //class Keys2 : List2<IComparable>, IComparable //{ // public int CompareTo(object o) // { // Keys2 other = (Keys2)o; // for (int i = 0; i < Length; i++) // { // int c = this.Get(i).CompareTo(other.Get(i)); // if (c != 0) return c; // } // return 0; // } //} // //public class Group2<K, T> : List2<T> //{ // public Group2(K k, params T[] data) // : base(data) // { // this.Key = k; // } // // public K Key { get; private set; } // // public override string ToString() // { // return Key + String.Empty + ':' + base.ToString(); // } //} // //public static class Extensions2 //{ // // public static List2<E> Cast<T, E>(this List2<T> _this) // { // E[] data = new E[_this.Length]; // for (int i = 0; i < _this.Length; i++) // data[i] = (E)(object)_this.data[i]; // return new List2<E>(data); // } // // public static List2<T> Where<T>(this List2<T> _this, Func2<T, bool> predicate) // { // List2<T> result = new List2<T>(); // for (int i = 0; i < _this.Length; i++) // { // T datum = _this.data[i]; // if (predicate(datum)) result.Add(datum); // } // return result; // } // // public static List2<U> Select<T,U>(this List2<T> _this, Func2<T, U> selector) // { // int length = _this.Length; // U[] data = new U[length]; // for (int i = 0; i < length; i++) data[i] = selector(_this.data[i]); // return new List2<U>(data); // } // // public static List2<V> SelectMany<T, U, V>(this List2<T> _this, Func2<T, List2<U>> selector, Func2<T, U, V> resultSelector) // { // List2<V> result = new List2<V>(); // int length = _this.Length; // for (int i = 0; i < length; i++) // { // T t = _this.data[i]; // List2<U> selected = selector(t); // int ulength = selected.Length; // for (int j = 0; j < ulength; j++) // { // U u = selected.data[j]; // V v = resultSelector(t, u); // result.Add(v); // } // } // // return result; // } // // public static List2<V> Join<T, U, K, V>(this List2<T> _this, List2<U> inner, Func2<T, K> outerKeyselector, // Func2<U, K> innerKeyselector, Func2<T, U, V> resultSelector) // { // List2<Joined<K, T, U>> joined = new List2<Joined<K, T, U>>(); // for (int i = 0; i < _this.Length; i++) // { // T t = _this.Get(i); // K k = outerKeyselector(t); // Joined<K, T, U> row = null; // for (int j = 0; j < joined.Length; j++) // { // if (joined.Get(j).k.Equals(k)) // { // row = joined.Get(j); // break; // } // } // if (row == null) joined.Add(row = new Joined<K, T, U>(k)); // row.t.Add(t); // } // for (int i = 0; i < inner.Length; i++) // { // U u = inner.Get(i); // K k = innerKeyselector(u); // Joined<K, T, U> row = null; // for (int j = 0; j < joined.Length; j++) // { // if (joined.Get(j).k.Equals(k)) // { // row = joined.Get(j); // break; // } // } // if (row == null) joined.Add(row = new Joined<K, T, U>(k)); // row.u.Add(u); // } // List2<V> result = new List2<V>(); // for (int i = 0; i < joined.Length; i++) // { // Joined<K, T, U> row = joined.Get(i); // for (int j = 0; j < row.t.Length; j++) // { // T t = row.t.Get(j); // for (int k = 0; k < row.u.Length; k++) // { // U u = row.u.Get(k); // V v = resultSelector(t, u); // result.Add(v); // } // } // } // return result; // } // // class Joined<K, T2, U> // { // public Joined(K k) // { // this.k = k; // this.t = new List2<T2>(); // this.u = new List2<U>(); // } // public readonly K k; // public readonly List2<T2> t; // public readonly List2<U> u; // } // // public static List2<V> GroupJoin<T, U, K, V>(this List2<T> _this, List2<U> inner, Func2<T, K> outerKeyselector, // Func2<U, K> innerKeyselector, Func2<T, List2<U>, V> resultSelector) // { // List2<Joined<K, T, U>> joined = new List2<Joined<K, T, U>>(); // for (int i = 0; i < _this.Length; i++) // { // T t = _this.Get(i); // K k = outerKeyselector(t); // Joined<K, T, U> row = null; // for (int j = 0; j < joined.Length; j++) // { // if (joined.Get(j).k.Equals(k)) // { // row = joined.Get(j); // break; // } // } // if (row == null) joined.Add(row = new Joined<K, T, U>(k)); // row.t.Add(t); // } // for (int i = 0; i < inner.Length; i++) // { // U u = inner.Get(i); // K k = innerKeyselector(u); // Joined<K, T, U> row = null; // for (int j = 0; j < joined.Length; j++) // { // if (joined.Get(j).k.Equals(k)) // { // row = joined.Get(j); // break; // } // } // if (row == null) joined.Add(row = new Joined<K, T, U>(k)); // row.u.Add(u); // } // List2<V> result = new List2<V>(); // for (int i = 0; i < joined.Length; i++) // { // Joined<K, T, U> row = joined.Get(i); // for (int j = 0; j < row.t.Length; j++) // { // T t = row.t.Get(j); // V v = resultSelector(t, row.u); // result.Add(v); // } // } // return result; // } // // public static OrderedList2<T> OrderBy<T, K>(this List2<T> _this, Func2<T, K> Keyselector) // { // OrderedList2<T> result = new OrderedList2<T>(_this); // result.ThenBy(Keyselector); // return result; // } // // public static OrderedList2<T> OrderByDescending<T, K>(this List2<T> _this, Func2<T, K> Keyselector) // { // OrderedList2<T> result = new OrderedList2<T>(_this); // result.ThenByDescending(Keyselector); // return result; // } // // public static List2<Group2<K, T>> GroupBy<T, K>(this List2<T> _this, Func2<T, K> Keyselector) // { // List2<Group2<K, T>> result = new List2<Group2<K, T>>(); // for (int i = 0; i < _this.Length; i++) // { // T t = _this.Get(i); // K k = Keyselector(t); // Group2<K, T> Group2 = null; // for (int j = 0; j < result.Length; j++) // { // if (result.Get(j).Key.Equals(k)) // { // Group2 = result.Get(j); // break; // } // } // if (Group2 == null) // { // result.Add(Group2 = new Group2<K, T>(k)); // } // Group2.Add(t); // } // return result; // } // // public static List2<Group2<K, E>> GroupBy<T, K, E>(this List2<T> _this, Func2<T, K> Keyselector, // Func2<T, E> elementSelector) // { // List2<Group2<K, E>> result = new List2<Group2<K, E>>(); // for (int i = 0; i < _this.Length; i++) // { // T t = _this.Get(i); // K k = Keyselector(t); // Group2<K, E> Group2 = null; // for (int j = 0; j < result.Length; j++) // { // if (result.Get(j).Key.Equals(k)) // { // Group2 = result.Get(j); // break; // } // } // if (Group2 == null) // { // result.Add(Group2 = new Group2<K, E>(k)); // } // Group2.Add(elementSelector(t)); // } // return result; // } // // public static OrderedList2<T> ThenBy<T, K>(this OrderedList2<T> _this, Func2<T, K> Keyselector) // { // for (int i = 0; i < _this.Length; i++) // { // object o = Keyselector(_this.Get(i)); // work around bug 8405 // _this.Keys2.Get(i).Add((IComparable)o); // } // _this.Sort(); // return _this; // } // // class ReverseOrder : IComparable // { // IComparable c; // public ReverseOrder(IComparable c) // { // this.c = c; // } // public int CompareTo(object o) // { // ReverseOrder other = (ReverseOrder)o; // return other.c.CompareTo(this.c); // } // public override string ToString() // { // return String.Empty + '-' + c; // } // } // // public static OrderedList2<T> ThenByDescending<T, K>(this OrderedList2<T> _this, Func2<T, K> Keyselector) // { // for (int i = 0; i < _this.Length; i++) // { // object o = Keyselector(_this.Get(i)); // work around bug 8405 // _this.Keys2.Get(i).Add(new ReverseOrder((IComparable)o)); // } // _this.Sort(); // return _this; // } // //} " #endregion the string LINQ ; } }
-1
dotnet/roslyn
55,256
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-30T00:02:02Z
2021-07-30T09:17:54Z
6ce9c0048d37026337701fac035ac0745f6fe49f
88b59775dc6375635957ef229116460f290072aa
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/VisualStudio/Core/Impl/CodeModel/FileCodeModel.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Runtime.InteropServices; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Simplification; using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.Collections; using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.InternalElements; using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.Interop; using Microsoft.VisualStudio.LanguageServices.Implementation.Interop; using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem; using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Threading; using Roslyn.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel { /// <summary> /// Implementations of EnvDTE.FileCodeModel for both languages. /// </summary> public sealed partial class FileCodeModel : AbstractCodeModelObject, EnvDTE.FileCodeModel, EnvDTE80.FileCodeModel2, ICodeElementContainer<AbstractCodeElement>, IVBFileCodeModelEvents, ICSCodeModelRefactoring { internal static ComHandle<EnvDTE80.FileCodeModel2, FileCodeModel> Create( CodeModelState state, object parent, DocumentId documentId, ITextManagerAdapter textManagerAdapter) { return new FileCodeModel(state, parent, documentId, textManagerAdapter).GetComHandle<EnvDTE80.FileCodeModel2, FileCodeModel>(); } private readonly ComHandle<object, object> _parentHandle; /// <summary> /// Don't use directly. Instead, call <see cref="GetDocumentId()"/>. /// </summary> private DocumentId _documentId; // Note: these are only valid when the underlying file is being renamed. Do not use. private ProjectId _incomingProjectId; private string _incomingFilePath; private Document _previousDocument; private readonly CleanableWeakComHandleTable<SyntaxNodeKey, EnvDTE.CodeElement> _codeElementTable; // These are used during batching. private bool _batchMode; private List<AbstractKeyedCodeElement> _batchElements; private Document _batchDocument; // track state to make sure we open editor only once private int _editCount; private IInvisibleEditor _invisibleEditor; private SyntaxTree _lastSyntaxTree; private FileCodeModel( CodeModelState state, object parent, DocumentId documentId, ITextManagerAdapter textManagerAdapter) : base(state) { Debug.Assert(documentId != null); Debug.Assert(textManagerAdapter != null); _parentHandle = new ComHandle<object, object>(parent); _documentId = documentId; TextManagerAdapter = textManagerAdapter; _codeElementTable = new CleanableWeakComHandleTable<SyntaxNodeKey, EnvDTE.CodeElement>(state.ThreadingContext); _batchMode = false; _batchDocument = null; _lastSyntaxTree = GetSyntaxTree(); } internal ITextManagerAdapter TextManagerAdapter { get; set; } /// <summary> /// Internally, we store the DocumentId for the document that the FileCodeModel represents. If the underlying file /// is renamed, the DocumentId will become invalid because the Roslyn VS workspace treats file renames as a remove/add pair. /// To work around this, the FileCodeModel is notified when a file rename is about to occur. At that point, the /// <see cref="_documentId"/> field is null'd out and <see cref="_incomingFilePath"/> is set to the name of the new file. /// The next time that a FileCodeModel operation occurs that requires the DocumentId, it will be retrieved from the workspace /// using the <see cref="_incomingFilePath"/>. /// </summary> internal void OnRename(string newFilePath) { Debug.Assert(_editCount == 0, "FileCodeModel have an open edit and the underlying file is being renamed. This is a bug."); if (_documentId != null) { _previousDocument = Workspace.CurrentSolution.GetDocument(_documentId); } _incomingFilePath = newFilePath; _incomingProjectId = _documentId.ProjectId; _documentId = null; } internal override void Shutdown() { if (_invisibleEditor != null) { // we are shutting down, so do not worry about editCount. We will detach our format tracking from the text // buffer now; if anybody else had an invisible editor open to this file, we wouldn't want our format tracking // to trigger. We can safely do that on a background thread since it's just disconnecting a few event handlers. // We have to defer the shutdown of the invisible editor though as that requires talking to the UI thread. // We don't want to block up file removal on the UI thread since we want that path to stay asynchronous. CodeModelService.DetachFormatTrackingToBuffer(_invisibleEditor.TextBuffer); State.ProjectCodeModelFactory.ScheduleDeferredCleanupTask( cancellationToken => { // Ignore cancellationToken: we always need to call Dispose since it triggers the file save. _ = cancellationToken; _invisibleEditor.Dispose(); }); } base.Shutdown(); } private bool TryGetDocumentId(out DocumentId documentId) { if (_documentId != null) { documentId = _documentId; return true; } documentId = null; // We don't have DocumentId, so try to retrieve it from the workspace. if (_incomingProjectId == null || _incomingFilePath == null) { return false; } var project = this.State.Workspace.CurrentSolution.GetProject(_incomingProjectId); if (project == null) { return false; } documentId = project.Solution.GetDocumentIdsWithFilePath(_incomingFilePath).FirstOrDefault(d => d.ProjectId == project.Id); if (documentId == null) { return false; } _documentId = documentId; _incomingProjectId = null; _incomingFilePath = null; _previousDocument = null; return true; } internal DocumentId GetDocumentId() { if (_documentId != null) { return _documentId; } if (TryGetDocumentId(out var documentId)) { return documentId; } throw Exceptions.ThrowEUnexpected(); } internal void UpdateCodeElementNodeKey(AbstractKeyedCodeElement keyedElement, SyntaxNodeKey oldNodeKey, SyntaxNodeKey newNodeKey) { if (!_codeElementTable.TryGetValue(oldNodeKey, out var codeElement)) { throw new InvalidOperationException($"Could not find {oldNodeKey} in Code Model element table."); } _codeElementTable.Remove(oldNodeKey); var managedElement = ComAggregate.GetManagedObject<AbstractKeyedCodeElement>(codeElement); if (!object.Equals(managedElement, keyedElement)) { throw new InvalidOperationException($"Unexpected failure in Code Model while updating node keys {oldNodeKey} -> {newNodeKey}"); } // If we're updating this element with the same node key as an element that's already in the table, // just remove the old element. The old element will continue to function (through its node key), but // the new element will replace it in the cache. if (_codeElementTable.ContainsKey(newNodeKey)) { _codeElementTable.Remove(newNodeKey); } _codeElementTable.Add(newNodeKey, codeElement); } internal void OnCodeElementCreated(SyntaxNodeKey nodeKey, EnvDTE.CodeElement element) { // If we're updating this element with the same node key as an element that's already in the table, // just remove the old element. The old element will continue to function (through its node key), but // the new element will replace it in the cache. if (_codeElementTable.ContainsKey(nodeKey)) { _codeElementTable.Remove(nodeKey); } _codeElementTable.Add(nodeKey, element); } internal void OnCodeElementDeleted(SyntaxNodeKey nodeKey) => _codeElementTable.Remove(nodeKey); internal T GetOrCreateCodeElement<T>(SyntaxNode node) { var nodeKey = CodeModelService.TryGetNodeKey(node); if (!nodeKey.IsEmpty) { // Since the node already has a key, check to see if a code element already // exists for it. If so, return that element it it's still valid; otherwise, // remove it from the table. if (_codeElementTable.TryGetValue(nodeKey, out var codeElement)) { if (codeElement != null) { var element = ComAggregate.TryGetManagedObject<AbstractCodeElement>(codeElement); if (element.IsValidNode()) { if (codeElement is T tcodeElement) { return tcodeElement; } throw new InvalidOperationException($"Found a valid code element for {nodeKey}, but it is not of type, {typeof(T).ToString()}"); } } } // Go ahead and remove the nodeKey from the table. At this point, we'll be creating a new one. _codeElementTable.Remove(nodeKey); } return (T)CodeModelService.CreateInternalCodeElement(this.State, this, node); } private void InitializeEditor() { _editCount++; if (_editCount == 1) { Debug.Assert(_invisibleEditor == null); _invisibleEditor = Workspace.OpenInvisibleEditor(GetDocumentId()); CodeModelService.AttachFormatTrackingToBuffer(_invisibleEditor.TextBuffer); } } private void ReleaseEditor() { Debug.Assert(_editCount >= 1); _editCount--; if (_editCount == 0) { Debug.Assert(_invisibleEditor != null); CodeModelService.DetachFormatTrackingToBuffer(_invisibleEditor.TextBuffer); _invisibleEditor.Dispose(); _invisibleEditor = null; } } internal void EnsureEditor(Action action) { InitializeEditor(); try { action(); } finally { ReleaseEditor(); } } internal T EnsureEditor<T>(Func<T> action) { InitializeEditor(); try { return action(); } finally { ReleaseEditor(); } } internal void PerformEdit(Func<Document, Document> action) { EnsureEditor(() => { Debug.Assert(_invisibleEditor != null); var document = GetDocument(); var workspace = document.Project.Solution.Workspace; var result = action(document); var formatted = State.ThreadingContext.JoinableTaskFactory.Run(async () => { var formatted = await Formatter.FormatAsync(result, Formatter.Annotation).ConfigureAwait(true); formatted = await Formatter.FormatAsync(formatted, SyntaxAnnotation.ElasticAnnotation).ConfigureAwait(true); return formatted; }); ApplyChanges(workspace, formatted); }); } internal T PerformEdit<T>(Func<Document, Tuple<T, Document>> action) where T : SyntaxNode { return EnsureEditor(() => { Debug.Assert(_invisibleEditor != null); var document = GetDocument(); var workspace = document.Project.Solution.Workspace; var result = action(document); ApplyChanges(workspace, result.Item2); return result.Item1; }); } private void ApplyChanges(Workspace workspace, Document document) { if (IsBatchOpen) { _batchDocument = document; } else { workspace.TryApplyChanges(document.Project.Solution); } } internal Document GetDocument() { if (!TryGetDocument(out var document)) { throw Exceptions.ThrowEFail(); } return document; } internal bool TryGetDocument(out Document document) { if (IsBatchOpen && _batchDocument != null) { document = _batchDocument; return true; } if (!TryGetDocumentId(out _) && _previousDocument != null) { document = _previousDocument; } else { // HACK HACK HACK: Ensure we've processed all files being opened before we let designers work further. // In https://devdiv.visualstudio.com/DevDiv/_workitems/edit/728035, a file is opened in an invisible editor and contents are written // to it. The file isn't saved, but it's added to the workspace; we won't have yet hooked up to the open file since that work was deferred. // Since we're on the UI thread here, we can ensure those are all wired up since the analysis of this document may depend on that other file. // We choose to do this here rather than in the project system code when it's added because we don't want to pay the penalty of checking the RDT for // all files being opened on the UI thread if we really don't need it. This uses an 'as' cast, because in unit tests the workspace is a different // derived form of VisualStudioWorkspace, and there we aren't dealing with open files at all so it doesn't matter. (State.Workspace as VisualStudioWorkspaceImpl)?.ProcessQueuedWorkOnUIThread(); document = Workspace.CurrentSolution.GetDocument(GetDocumentId()); } return document != null; } internal SyntaxTree GetSyntaxTree() { return GetDocument().GetSyntaxTreeSynchronously(CancellationToken.None); } internal SyntaxNode GetSyntaxRoot() { return GetDocument().GetSyntaxRootSynchronously(CancellationToken.None); } internal SemanticModel GetSemanticModel() => State.ThreadingContext.JoinableTaskFactory.Run(() => { return GetDocument() .GetSemanticModelAsync(CancellationToken.None); }); internal Compilation GetCompilation() => State.ThreadingContext.JoinableTaskFactory.Run(() => { return GetDocument().Project .GetCompilationAsync(CancellationToken.None); }); internal ProjectId GetProjectId() => GetDocumentId().ProjectId; internal SyntaxNode LookupNode(SyntaxNodeKey nodeKey) => CodeModelService.LookupNode(nodeKey, GetSyntaxTree()); internal TSyntaxNode LookupNode<TSyntaxNode>(SyntaxNodeKey nodeKey) where TSyntaxNode : SyntaxNode { return CodeModelService.LookupNode(nodeKey, GetSyntaxTree()) as TSyntaxNode; } public EnvDTE.CodeAttribute AddAttribute(string name, string value, object position) { return EnsureEditor(() => { return AddAttribute(GetSyntaxRoot(), name, value, position, target: CodeModelService.AssemblyAttributeString); }); } public EnvDTE.CodeClass AddClass(string name, object position, object bases, object implementedInterfaces, EnvDTE.vsCMAccess access) { return EnsureEditor(() => { return AddClass(GetSyntaxRoot(), name, position, bases, implementedInterfaces, access); }); } public EnvDTE.CodeDelegate AddDelegate(string name, object type, object position, EnvDTE.vsCMAccess access) { return EnsureEditor(() => { return AddDelegate(GetSyntaxRoot(), name, type, position, access); }); } public EnvDTE.CodeEnum AddEnum(string name, object position, object bases, EnvDTE.vsCMAccess access) { return EnsureEditor(() => { return AddEnum(GetSyntaxRoot(), name, position, bases, access); }); } public EnvDTE.CodeFunction AddFunction(string name, EnvDTE.vsCMFunction kind, object type, object position, EnvDTE.vsCMAccess access) => throw Exceptions.ThrowEFail(); public EnvDTE80.CodeImport AddImport(string name, object position, string alias) { return EnsureEditor(() => { return AddImport(GetSyntaxRoot(), name, position, alias); }); } public EnvDTE.CodeInterface AddInterface(string name, object position, object bases, EnvDTE.vsCMAccess access) { return EnsureEditor(() => { return AddInterface(GetSyntaxRoot(), name, position, bases, access); }); } public EnvDTE.CodeNamespace AddNamespace(string name, object position) { return EnsureEditor(() => { return AddNamespace(GetSyntaxRoot(), name, position); }); } public EnvDTE.CodeStruct AddStruct(string name, object position, object bases, object implementedInterfaces, EnvDTE.vsCMAccess access) { return EnsureEditor(() => { return AddStruct(GetSyntaxRoot(), name, position, bases, implementedInterfaces, access); }); } public EnvDTE.CodeVariable AddVariable(string name, object type, object position, EnvDTE.vsCMAccess access) => throw Exceptions.ThrowEFail(); public EnvDTE.CodeElement CodeElementFromPoint(EnvDTE.TextPoint point, EnvDTE.vsCMElement scope) { // Can't use point.AbsoluteCharOffset because it's calculated by the native // implementation in GetAbsoluteOffset (in env\msenv\textmgr\autoutil.cpp) // to only count each newline as a single character. We need to ask for line and // column and calculate the right offset ourselves. See DevDiv2 530496 for details. var position = GetPositionFromTextPoint(point); var result = CodeElementFromPosition(position, scope); if (result == null) { throw Exceptions.ThrowEFail(); } return result; } private int GetPositionFromTextPoint(EnvDTE.TextPoint point) { var lineNumber = point.Line - 1; var column = point.LineCharOffset - 1; var line = GetDocument().GetTextSynchronously(CancellationToken.None).Lines[lineNumber]; var position = line.Start + column; return position; } internal EnvDTE.CodeElement CodeElementFromPosition(int position, EnvDTE.vsCMElement scope) { var root = GetSyntaxRoot(); var leftToken = SyntaxFactsService.FindTokenOnLeftOfPosition(root, position); var rightToken = SyntaxFactsService.FindTokenOnRightOfPosition(root, position); // We apply a set of heuristics to determine which member we pick to start searching. var token = leftToken; if (leftToken != rightToken) { if (leftToken.Span.End == position && rightToken.SpanStart == position) { // If both tokens are touching, we prefer identifiers and keywords to // separators. Note that the language doesn't allow both tokens to be a // keyword or identifier. if (SyntaxFactsService.IsReservedOrContextualKeyword(rightToken) || SyntaxFactsService.IsIdentifier(rightToken)) { token = rightToken; } } else if (leftToken.Span.End < position && rightToken.SpanStart <= position) { // If only the right token is touching, we have to use it. token = rightToken; } } // If we ended up using the left token but the position is after that token, // walk up to the first node who's last token is not the leftToken. By doing this, we // ensure that we don't find members when the position is actually between them. // In that case, we should find the enclosing type or namespace. var parent = token.Parent; if (token == leftToken && position > token.Span.End) { while (parent != null) { if (parent.GetLastToken() == token) { parent = parent.Parent; } else { break; } } } var node = parent?.AncestorsAndSelf().FirstOrDefault(n => CodeModelService.MatchesScope(n, scope)); if (node == null) { return null; } if (scope == EnvDTE.vsCMElement.vsCMElementAttribute || scope == EnvDTE.vsCMElement.vsCMElementImportStmt || scope == EnvDTE.vsCMElement.vsCMElementParameter || scope == EnvDTE.vsCMElement.vsCMElementOptionStmt || scope == EnvDTE.vsCMElement.vsCMElementInheritsStmt || scope == EnvDTE.vsCMElement.vsCMElementImplementsStmt || (scope == EnvDTE.vsCMElement.vsCMElementFunction && CodeModelService.IsAccessorNode(node))) { // Attributes, imports, parameters, Option, Inherits and Implements // don't have node keys of their own and won't be included in our // collection of elements. Delegate to the service to create these. return CodeModelService.CreateInternalCodeElement(State, this, node); } return GetOrCreateCodeElement<EnvDTE.CodeElement>(node); } public EnvDTE.CodeElements CodeElements { get { return NamespaceCollection.Create(this.State, this, this, SyntaxNodeKey.Empty); } } public EnvDTE.ProjectItem Parent { get { return _parentHandle.Object as EnvDTE.ProjectItem; } } public void Remove(object element) { var codeElement = ComAggregate.TryGetManagedObject<AbstractCodeElement>(element); if (codeElement == null) { codeElement = ComAggregate.TryGetManagedObject<AbstractCodeElement>(this.CodeElements.Item(element)); } if (codeElement == null) { throw new ArgumentException(ServicesVSResources.Element_is_not_valid, nameof(element)); } codeElement.Delete(); } int IVBFileCodeModelEvents.StartEdit() { try { InitializeEditor(); if (_editCount == 1) { _batchMode = true; _batchElements = new List<AbstractKeyedCodeElement>(); } return VSConstants.S_OK; } catch (Exception ex) { return Marshal.GetHRForException(ex); } } int IVBFileCodeModelEvents.EndEdit() { try { if (_editCount == 1) { List<ValueTuple<AbstractKeyedCodeElement, SyntaxPath>> elementAndPaths = null; if (_batchElements.Count > 0) { foreach (var element in _batchElements) { var node = element.LookupNode(); if (node != null) { elementAndPaths ??= new List<ValueTuple<AbstractKeyedCodeElement, SyntaxPath>>(); elementAndPaths.Add(ValueTuple.Create(element, new SyntaxPath(node))); } } } if (_batchDocument != null) { // perform expensive operations at once var newDocument = State.ThreadingContext.JoinableTaskFactory.Run(() => Simplifier.ReduceAsync(_batchDocument, Simplifier.Annotation, cancellationToken: CancellationToken.None)); _batchDocument.Project.Solution.Workspace.TryApplyChanges(newDocument.Project.Solution); // done using batch document _batchDocument = null; } // Ensure the file is prettylisted, even if we didn't make any edits CodeModelService.EnsureBufferFormatted(_invisibleEditor.TextBuffer); if (elementAndPaths != null) { foreach (var elementAndPath in elementAndPaths) { // make sure the element is there. if (_codeElementTable.TryGetValue(elementAndPath.Item1.NodeKey, out var existingElement)) { elementAndPath.Item1.ReacquireNodeKey(elementAndPath.Item2, CancellationToken.None); } // make sure existing element doesn't go away (weak reference) in the middle of // updating the node key GC.KeepAlive(existingElement); } } _batchMode = false; _batchElements = null; } return VSConstants.S_OK; } catch (Exception ex) { return Marshal.GetHRForException(ex); } finally { ReleaseEditor(); } } public void BeginBatch() { IVBFileCodeModelEvents temp = this; ErrorHandler.ThrowOnFailure(temp.StartEdit()); } public void EndBatch() { IVBFileCodeModelEvents temp = this; ErrorHandler.ThrowOnFailure(temp.EndEdit()); } public bool IsBatchOpen { get { return _batchMode && _editCount > 0; } } public EnvDTE.CodeElement ElementFromID(string id) => throw new NotImplementedException(); public EnvDTE80.vsCMParseStatus ParseStatus { get { var syntaxTree = GetSyntaxTree(); return syntaxTree.GetDiagnostics().Any(d => d.Severity == DiagnosticSeverity.Error) ? EnvDTE80.vsCMParseStatus.vsCMParseStatusError : EnvDTE80.vsCMParseStatus.vsCMParseStatusComplete; } } public void Synchronize() => FireEvents(); EnvDTE.CodeElements ICodeElementContainer<AbstractCodeElement>.GetCollection() => CodeElements; internal List<GlobalNodeKey> GetCurrentNodeKeys() { var currentNodeKeys = new List<GlobalNodeKey>(); foreach (var element in _codeElementTable.Values) { var keyedElement = ComAggregate.TryGetManagedObject<AbstractKeyedCodeElement>(element); if (keyedElement == null) { continue; } if (keyedElement.TryLookupNode(out var node)) { var nodeKey = keyedElement.NodeKey; currentNodeKeys.Add(new GlobalNodeKey(nodeKey, new SyntaxPath(node))); } } return currentNodeKeys; } internal void ResetElementKeys(List<GlobalNodeKey> globalNodeKeys) { foreach (var globalNodeKey in globalNodeKeys) { ResetElementKey(globalNodeKey); } } private void ResetElementKey(GlobalNodeKey globalNodeKey) { // Failure to find the element is not an error -- it just means the code // element didn't exist... if (_codeElementTable.TryGetValue(globalNodeKey.NodeKey, out var element)) { var keyedElement = ComAggregate.GetManagedObject<AbstractKeyedCodeElement>(element); if (keyedElement != null) { keyedElement.ReacquireNodeKey(globalNodeKey.Path, 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.Diagnostics; using System.Linq; using System.Runtime.InteropServices; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Simplification; using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.Collections; using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.InternalElements; using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.Interop; using Microsoft.VisualStudio.LanguageServices.Implementation.Interop; using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem; using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Threading; using Roslyn.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel { /// <summary> /// Implementations of EnvDTE.FileCodeModel for both languages. /// </summary> public sealed partial class FileCodeModel : AbstractCodeModelObject, EnvDTE.FileCodeModel, EnvDTE80.FileCodeModel2, ICodeElementContainer<AbstractCodeElement>, IVBFileCodeModelEvents, ICSCodeModelRefactoring { internal static ComHandle<EnvDTE80.FileCodeModel2, FileCodeModel> Create( CodeModelState state, object parent, DocumentId documentId, ITextManagerAdapter textManagerAdapter) { return new FileCodeModel(state, parent, documentId, textManagerAdapter).GetComHandle<EnvDTE80.FileCodeModel2, FileCodeModel>(); } private readonly ComHandle<object, object> _parentHandle; /// <summary> /// Don't use directly. Instead, call <see cref="GetDocumentId()"/>. /// </summary> private DocumentId _documentId; // Note: these are only valid when the underlying file is being renamed. Do not use. private ProjectId _incomingProjectId; private string _incomingFilePath; private Document _previousDocument; private readonly CleanableWeakComHandleTable<SyntaxNodeKey, EnvDTE.CodeElement> _codeElementTable; // These are used during batching. private bool _batchMode; private List<AbstractKeyedCodeElement> _batchElements; private Document _batchDocument; // track state to make sure we open editor only once private int _editCount; private IInvisibleEditor _invisibleEditor; private SyntaxTree _lastSyntaxTree; private FileCodeModel( CodeModelState state, object parent, DocumentId documentId, ITextManagerAdapter textManagerAdapter) : base(state) { Debug.Assert(documentId != null); Debug.Assert(textManagerAdapter != null); _parentHandle = new ComHandle<object, object>(parent); _documentId = documentId; TextManagerAdapter = textManagerAdapter; _codeElementTable = new CleanableWeakComHandleTable<SyntaxNodeKey, EnvDTE.CodeElement>(state.ThreadingContext); _batchMode = false; _batchDocument = null; _lastSyntaxTree = GetSyntaxTree(); } internal ITextManagerAdapter TextManagerAdapter { get; set; } /// <summary> /// Internally, we store the DocumentId for the document that the FileCodeModel represents. If the underlying file /// is renamed, the DocumentId will become invalid because the Roslyn VS workspace treats file renames as a remove/add pair. /// To work around this, the FileCodeModel is notified when a file rename is about to occur. At that point, the /// <see cref="_documentId"/> field is null'd out and <see cref="_incomingFilePath"/> is set to the name of the new file. /// The next time that a FileCodeModel operation occurs that requires the DocumentId, it will be retrieved from the workspace /// using the <see cref="_incomingFilePath"/>. /// </summary> internal void OnRename(string newFilePath) { Debug.Assert(_editCount == 0, "FileCodeModel have an open edit and the underlying file is being renamed. This is a bug."); if (_documentId != null) { _previousDocument = Workspace.CurrentSolution.GetDocument(_documentId); } _incomingFilePath = newFilePath; _incomingProjectId = _documentId.ProjectId; _documentId = null; } internal override void Shutdown() { if (_invisibleEditor != null) { // we are shutting down, so do not worry about editCount. We will detach our format tracking from the text // buffer now; if anybody else had an invisible editor open to this file, we wouldn't want our format tracking // to trigger. We can safely do that on a background thread since it's just disconnecting a few event handlers. // We have to defer the shutdown of the invisible editor though as that requires talking to the UI thread. // We don't want to block up file removal on the UI thread since we want that path to stay asynchronous. CodeModelService.DetachFormatTrackingToBuffer(_invisibleEditor.TextBuffer); State.ProjectCodeModelFactory.ScheduleDeferredCleanupTask( cancellationToken => { // Ignore cancellationToken: we always need to call Dispose since it triggers the file save. _ = cancellationToken; _invisibleEditor.Dispose(); }); } base.Shutdown(); } private bool TryGetDocumentId(out DocumentId documentId) { if (_documentId != null) { documentId = _documentId; return true; } documentId = null; // We don't have DocumentId, so try to retrieve it from the workspace. if (_incomingProjectId == null || _incomingFilePath == null) { return false; } var project = this.State.Workspace.CurrentSolution.GetProject(_incomingProjectId); if (project == null) { return false; } documentId = project.Solution.GetDocumentIdsWithFilePath(_incomingFilePath).FirstOrDefault(d => d.ProjectId == project.Id); if (documentId == null) { return false; } _documentId = documentId; _incomingProjectId = null; _incomingFilePath = null; _previousDocument = null; return true; } internal DocumentId GetDocumentId() { if (_documentId != null) { return _documentId; } if (TryGetDocumentId(out var documentId)) { return documentId; } throw Exceptions.ThrowEUnexpected(); } internal void UpdateCodeElementNodeKey(AbstractKeyedCodeElement keyedElement, SyntaxNodeKey oldNodeKey, SyntaxNodeKey newNodeKey) { if (!_codeElementTable.TryGetValue(oldNodeKey, out var codeElement)) { throw new InvalidOperationException($"Could not find {oldNodeKey} in Code Model element table."); } _codeElementTable.Remove(oldNodeKey); var managedElement = ComAggregate.GetManagedObject<AbstractKeyedCodeElement>(codeElement); if (!object.Equals(managedElement, keyedElement)) { throw new InvalidOperationException($"Unexpected failure in Code Model while updating node keys {oldNodeKey} -> {newNodeKey}"); } // If we're updating this element with the same node key as an element that's already in the table, // just remove the old element. The old element will continue to function (through its node key), but // the new element will replace it in the cache. if (_codeElementTable.ContainsKey(newNodeKey)) { _codeElementTable.Remove(newNodeKey); } _codeElementTable.Add(newNodeKey, codeElement); } internal void OnCodeElementCreated(SyntaxNodeKey nodeKey, EnvDTE.CodeElement element) { // If we're updating this element with the same node key as an element that's already in the table, // just remove the old element. The old element will continue to function (through its node key), but // the new element will replace it in the cache. if (_codeElementTable.ContainsKey(nodeKey)) { _codeElementTable.Remove(nodeKey); } _codeElementTable.Add(nodeKey, element); } internal void OnCodeElementDeleted(SyntaxNodeKey nodeKey) => _codeElementTable.Remove(nodeKey); internal T GetOrCreateCodeElement<T>(SyntaxNode node) { var nodeKey = CodeModelService.TryGetNodeKey(node); if (!nodeKey.IsEmpty) { // Since the node already has a key, check to see if a code element already // exists for it. If so, return that element it it's still valid; otherwise, // remove it from the table. if (_codeElementTable.TryGetValue(nodeKey, out var codeElement)) { if (codeElement != null) { var element = ComAggregate.TryGetManagedObject<AbstractCodeElement>(codeElement); if (element.IsValidNode()) { if (codeElement is T tcodeElement) { return tcodeElement; } throw new InvalidOperationException($"Found a valid code element for {nodeKey}, but it is not of type, {typeof(T).ToString()}"); } } } // Go ahead and remove the nodeKey from the table. At this point, we'll be creating a new one. _codeElementTable.Remove(nodeKey); } return (T)CodeModelService.CreateInternalCodeElement(this.State, this, node); } private void InitializeEditor() { _editCount++; if (_editCount == 1) { Debug.Assert(_invisibleEditor == null); _invisibleEditor = Workspace.OpenInvisibleEditor(GetDocumentId()); CodeModelService.AttachFormatTrackingToBuffer(_invisibleEditor.TextBuffer); } } private void ReleaseEditor() { Debug.Assert(_editCount >= 1); _editCount--; if (_editCount == 0) { Debug.Assert(_invisibleEditor != null); CodeModelService.DetachFormatTrackingToBuffer(_invisibleEditor.TextBuffer); _invisibleEditor.Dispose(); _invisibleEditor = null; } } internal void EnsureEditor(Action action) { InitializeEditor(); try { action(); } finally { ReleaseEditor(); } } internal T EnsureEditor<T>(Func<T> action) { InitializeEditor(); try { return action(); } finally { ReleaseEditor(); } } internal void PerformEdit(Func<Document, Document> action) { EnsureEditor(() => { Debug.Assert(_invisibleEditor != null); var document = GetDocument(); var workspace = document.Project.Solution.Workspace; var result = action(document); var formatted = State.ThreadingContext.JoinableTaskFactory.Run(async () => { var formatted = await Formatter.FormatAsync(result, Formatter.Annotation).ConfigureAwait(true); formatted = await Formatter.FormatAsync(formatted, SyntaxAnnotation.ElasticAnnotation).ConfigureAwait(true); return formatted; }); ApplyChanges(workspace, formatted); }); } internal T PerformEdit<T>(Func<Document, Tuple<T, Document>> action) where T : SyntaxNode { return EnsureEditor(() => { Debug.Assert(_invisibleEditor != null); var document = GetDocument(); var workspace = document.Project.Solution.Workspace; var result = action(document); ApplyChanges(workspace, result.Item2); return result.Item1; }); } private void ApplyChanges(Workspace workspace, Document document) { if (IsBatchOpen) { _batchDocument = document; } else { workspace.TryApplyChanges(document.Project.Solution); } } internal Document GetDocument() { if (!TryGetDocument(out var document)) { throw Exceptions.ThrowEFail(); } return document; } internal bool TryGetDocument(out Document document) { if (IsBatchOpen && _batchDocument != null) { document = _batchDocument; return true; } if (!TryGetDocumentId(out _) && _previousDocument != null) { document = _previousDocument; } else { // HACK HACK HACK: Ensure we've processed all files being opened before we let designers work further. // In https://devdiv.visualstudio.com/DevDiv/_workitems/edit/728035, a file is opened in an invisible editor and contents are written // to it. The file isn't saved, but it's added to the workspace; we won't have yet hooked up to the open file since that work was deferred. // Since we're on the UI thread here, we can ensure those are all wired up since the analysis of this document may depend on that other file. // We choose to do this here rather than in the project system code when it's added because we don't want to pay the penalty of checking the RDT for // all files being opened on the UI thread if we really don't need it. This uses an 'as' cast, because in unit tests the workspace is a different // derived form of VisualStudioWorkspace, and there we aren't dealing with open files at all so it doesn't matter. (State.Workspace as VisualStudioWorkspaceImpl)?.ProcessQueuedWorkOnUIThread(); document = Workspace.CurrentSolution.GetDocument(GetDocumentId()); } return document != null; } internal SyntaxTree GetSyntaxTree() { return GetDocument().GetSyntaxTreeSynchronously(CancellationToken.None); } internal SyntaxNode GetSyntaxRoot() { return GetDocument().GetSyntaxRootSynchronously(CancellationToken.None); } internal SemanticModel GetSemanticModel() => State.ThreadingContext.JoinableTaskFactory.Run(() => { return GetDocument() .GetSemanticModelAsync(CancellationToken.None); }); internal Compilation GetCompilation() => State.ThreadingContext.JoinableTaskFactory.Run(() => { return GetDocument().Project .GetCompilationAsync(CancellationToken.None); }); internal ProjectId GetProjectId() => GetDocumentId().ProjectId; internal SyntaxNode LookupNode(SyntaxNodeKey nodeKey) => CodeModelService.LookupNode(nodeKey, GetSyntaxTree()); internal TSyntaxNode LookupNode<TSyntaxNode>(SyntaxNodeKey nodeKey) where TSyntaxNode : SyntaxNode { return CodeModelService.LookupNode(nodeKey, GetSyntaxTree()) as TSyntaxNode; } public EnvDTE.CodeAttribute AddAttribute(string name, string value, object position) { return EnsureEditor(() => { return AddAttribute(GetSyntaxRoot(), name, value, position, target: CodeModelService.AssemblyAttributeString); }); } public EnvDTE.CodeClass AddClass(string name, object position, object bases, object implementedInterfaces, EnvDTE.vsCMAccess access) { return EnsureEditor(() => { return AddClass(GetSyntaxRoot(), name, position, bases, implementedInterfaces, access); }); } public EnvDTE.CodeDelegate AddDelegate(string name, object type, object position, EnvDTE.vsCMAccess access) { return EnsureEditor(() => { return AddDelegate(GetSyntaxRoot(), name, type, position, access); }); } public EnvDTE.CodeEnum AddEnum(string name, object position, object bases, EnvDTE.vsCMAccess access) { return EnsureEditor(() => { return AddEnum(GetSyntaxRoot(), name, position, bases, access); }); } public EnvDTE.CodeFunction AddFunction(string name, EnvDTE.vsCMFunction kind, object type, object position, EnvDTE.vsCMAccess access) => throw Exceptions.ThrowEFail(); public EnvDTE80.CodeImport AddImport(string name, object position, string alias) { return EnsureEditor(() => { return AddImport(GetSyntaxRoot(), name, position, alias); }); } public EnvDTE.CodeInterface AddInterface(string name, object position, object bases, EnvDTE.vsCMAccess access) { return EnsureEditor(() => { return AddInterface(GetSyntaxRoot(), name, position, bases, access); }); } public EnvDTE.CodeNamespace AddNamespace(string name, object position) { return EnsureEditor(() => { return AddNamespace(GetSyntaxRoot(), name, position); }); } public EnvDTE.CodeStruct AddStruct(string name, object position, object bases, object implementedInterfaces, EnvDTE.vsCMAccess access) { return EnsureEditor(() => { return AddStruct(GetSyntaxRoot(), name, position, bases, implementedInterfaces, access); }); } public EnvDTE.CodeVariable AddVariable(string name, object type, object position, EnvDTE.vsCMAccess access) => throw Exceptions.ThrowEFail(); public EnvDTE.CodeElement CodeElementFromPoint(EnvDTE.TextPoint point, EnvDTE.vsCMElement scope) { // Can't use point.AbsoluteCharOffset because it's calculated by the native // implementation in GetAbsoluteOffset (in env\msenv\textmgr\autoutil.cpp) // to only count each newline as a single character. We need to ask for line and // column and calculate the right offset ourselves. See DevDiv2 530496 for details. var position = GetPositionFromTextPoint(point); var result = CodeElementFromPosition(position, scope); if (result == null) { throw Exceptions.ThrowEFail(); } return result; } private int GetPositionFromTextPoint(EnvDTE.TextPoint point) { var lineNumber = point.Line - 1; var column = point.LineCharOffset - 1; var line = GetDocument().GetTextSynchronously(CancellationToken.None).Lines[lineNumber]; var position = line.Start + column; return position; } internal EnvDTE.CodeElement CodeElementFromPosition(int position, EnvDTE.vsCMElement scope) { var root = GetSyntaxRoot(); var leftToken = SyntaxFactsService.FindTokenOnLeftOfPosition(root, position); var rightToken = SyntaxFactsService.FindTokenOnRightOfPosition(root, position); // We apply a set of heuristics to determine which member we pick to start searching. var token = leftToken; if (leftToken != rightToken) { if (leftToken.Span.End == position && rightToken.SpanStart == position) { // If both tokens are touching, we prefer identifiers and keywords to // separators. Note that the language doesn't allow both tokens to be a // keyword or identifier. if (SyntaxFactsService.IsReservedOrContextualKeyword(rightToken) || SyntaxFactsService.IsIdentifier(rightToken)) { token = rightToken; } } else if (leftToken.Span.End < position && rightToken.SpanStart <= position) { // If only the right token is touching, we have to use it. token = rightToken; } } // If we ended up using the left token but the position is after that token, // walk up to the first node who's last token is not the leftToken. By doing this, we // ensure that we don't find members when the position is actually between them. // In that case, we should find the enclosing type or namespace. var parent = token.Parent; if (token == leftToken && position > token.Span.End) { while (parent != null) { if (parent.GetLastToken() == token) { parent = parent.Parent; } else { break; } } } var node = parent?.AncestorsAndSelf().FirstOrDefault(n => CodeModelService.MatchesScope(n, scope)); if (node == null) { return null; } if (scope == EnvDTE.vsCMElement.vsCMElementAttribute || scope == EnvDTE.vsCMElement.vsCMElementImportStmt || scope == EnvDTE.vsCMElement.vsCMElementParameter || scope == EnvDTE.vsCMElement.vsCMElementOptionStmt || scope == EnvDTE.vsCMElement.vsCMElementInheritsStmt || scope == EnvDTE.vsCMElement.vsCMElementImplementsStmt || (scope == EnvDTE.vsCMElement.vsCMElementFunction && CodeModelService.IsAccessorNode(node))) { // Attributes, imports, parameters, Option, Inherits and Implements // don't have node keys of their own and won't be included in our // collection of elements. Delegate to the service to create these. return CodeModelService.CreateInternalCodeElement(State, this, node); } return GetOrCreateCodeElement<EnvDTE.CodeElement>(node); } public EnvDTE.CodeElements CodeElements { get { return NamespaceCollection.Create(this.State, this, this, SyntaxNodeKey.Empty); } } public EnvDTE.ProjectItem Parent { get { return _parentHandle.Object as EnvDTE.ProjectItem; } } public void Remove(object element) { var codeElement = ComAggregate.TryGetManagedObject<AbstractCodeElement>(element); if (codeElement == null) { codeElement = ComAggregate.TryGetManagedObject<AbstractCodeElement>(this.CodeElements.Item(element)); } if (codeElement == null) { throw new ArgumentException(ServicesVSResources.Element_is_not_valid, nameof(element)); } codeElement.Delete(); } int IVBFileCodeModelEvents.StartEdit() { try { InitializeEditor(); if (_editCount == 1) { _batchMode = true; _batchElements = new List<AbstractKeyedCodeElement>(); } return VSConstants.S_OK; } catch (Exception ex) { return Marshal.GetHRForException(ex); } } int IVBFileCodeModelEvents.EndEdit() { try { if (_editCount == 1) { List<ValueTuple<AbstractKeyedCodeElement, SyntaxPath>> elementAndPaths = null; if (_batchElements.Count > 0) { foreach (var element in _batchElements) { var node = element.LookupNode(); if (node != null) { elementAndPaths ??= new List<ValueTuple<AbstractKeyedCodeElement, SyntaxPath>>(); elementAndPaths.Add(ValueTuple.Create(element, new SyntaxPath(node))); } } } if (_batchDocument != null) { // perform expensive operations at once var newDocument = State.ThreadingContext.JoinableTaskFactory.Run(() => Simplifier.ReduceAsync(_batchDocument, Simplifier.Annotation, cancellationToken: CancellationToken.None)); _batchDocument.Project.Solution.Workspace.TryApplyChanges(newDocument.Project.Solution); // done using batch document _batchDocument = null; } // Ensure the file is prettylisted, even if we didn't make any edits CodeModelService.EnsureBufferFormatted(_invisibleEditor.TextBuffer); if (elementAndPaths != null) { foreach (var elementAndPath in elementAndPaths) { // make sure the element is there. if (_codeElementTable.TryGetValue(elementAndPath.Item1.NodeKey, out var existingElement)) { elementAndPath.Item1.ReacquireNodeKey(elementAndPath.Item2, CancellationToken.None); } // make sure existing element doesn't go away (weak reference) in the middle of // updating the node key GC.KeepAlive(existingElement); } } _batchMode = false; _batchElements = null; } return VSConstants.S_OK; } catch (Exception ex) { return Marshal.GetHRForException(ex); } finally { ReleaseEditor(); } } public void BeginBatch() { IVBFileCodeModelEvents temp = this; ErrorHandler.ThrowOnFailure(temp.StartEdit()); } public void EndBatch() { IVBFileCodeModelEvents temp = this; ErrorHandler.ThrowOnFailure(temp.EndEdit()); } public bool IsBatchOpen { get { return _batchMode && _editCount > 0; } } public EnvDTE.CodeElement ElementFromID(string id) => throw new NotImplementedException(); public EnvDTE80.vsCMParseStatus ParseStatus { get { var syntaxTree = GetSyntaxTree(); return syntaxTree.GetDiagnostics().Any(d => d.Severity == DiagnosticSeverity.Error) ? EnvDTE80.vsCMParseStatus.vsCMParseStatusError : EnvDTE80.vsCMParseStatus.vsCMParseStatusComplete; } } public void Synchronize() => FireEvents(); EnvDTE.CodeElements ICodeElementContainer<AbstractCodeElement>.GetCollection() => CodeElements; internal List<GlobalNodeKey> GetCurrentNodeKeys() { var currentNodeKeys = new List<GlobalNodeKey>(); foreach (var element in _codeElementTable.Values) { var keyedElement = ComAggregate.TryGetManagedObject<AbstractKeyedCodeElement>(element); if (keyedElement == null) { continue; } if (keyedElement.TryLookupNode(out var node)) { var nodeKey = keyedElement.NodeKey; currentNodeKeys.Add(new GlobalNodeKey(nodeKey, new SyntaxPath(node))); } } return currentNodeKeys; } internal void ResetElementKeys(List<GlobalNodeKey> globalNodeKeys) { foreach (var globalNodeKey in globalNodeKeys) { ResetElementKey(globalNodeKey); } } private void ResetElementKey(GlobalNodeKey globalNodeKey) { // Failure to find the element is not an error -- it just means the code // element didn't exist... if (_codeElementTable.TryGetValue(globalNodeKey.NodeKey, out var element)) { var keyedElement = ComAggregate.GetManagedObject<AbstractKeyedCodeElement>(element); if (keyedElement != null) { keyedElement.ReacquireNodeKey(globalNodeKey.Path, default); } } } } }
-1
dotnet/roslyn
55,256
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-30T00:02:02Z
2021-07-30T09:17:54Z
6ce9c0048d37026337701fac035ac0745f6fe49f
88b59775dc6375635957ef229116460f290072aa
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Features/Core/Portable/Completion/Providers/Scripting/AbstractLoadDirectiveCompletionProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Completion; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Completion.Providers { internal abstract class AbstractLoadDirectiveCompletionProvider : AbstractDirectivePathCompletionProvider { private static readonly CompletionItemRules s_rules = CompletionItemRules.Create( filterCharacterRules: ImmutableArray<CharacterSetModificationRule>.Empty, commitCharacterRules: ImmutableArray.Create(CharacterSetModificationRule.Create(CharacterSetModificationKind.Replace, GetCommitCharacters())), enterKeyRule: EnterKeyRule.Never, selectionBehavior: CompletionItemSelectionBehavior.HardSelection); private static ImmutableArray<char> GetCommitCharacters() { using var builderDisposer = ArrayBuilder<char>.GetInstance(out var builder); builder.Add('"'); if (PathUtilities.IsUnixLikePlatform) { builder.Add('/'); } else { builder.Add('/'); builder.Add('\\'); } return builder.ToImmutable(); } protected override async Task ProvideCompletionsAsync(CompletionContext context, string pathThroughLastSlash) { var helper = GetFileSystemCompletionHelper(context.Document, Glyph.CSharpFile, ImmutableArray.Create(".csx"), s_rules); context.AddItems(await helper.GetItemsAsync(pathThroughLastSlash, context.CancellationToken).ConfigureAwait(false)); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Completion; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Completion.Providers { internal abstract class AbstractLoadDirectiveCompletionProvider : AbstractDirectivePathCompletionProvider { private static readonly CompletionItemRules s_rules = CompletionItemRules.Create( filterCharacterRules: ImmutableArray<CharacterSetModificationRule>.Empty, commitCharacterRules: ImmutableArray.Create(CharacterSetModificationRule.Create(CharacterSetModificationKind.Replace, GetCommitCharacters())), enterKeyRule: EnterKeyRule.Never, selectionBehavior: CompletionItemSelectionBehavior.HardSelection); private static ImmutableArray<char> GetCommitCharacters() { using var builderDisposer = ArrayBuilder<char>.GetInstance(out var builder); builder.Add('"'); if (PathUtilities.IsUnixLikePlatform) { builder.Add('/'); } else { builder.Add('/'); builder.Add('\\'); } return builder.ToImmutable(); } protected override async Task ProvideCompletionsAsync(CompletionContext context, string pathThroughLastSlash) { var helper = GetFileSystemCompletionHelper(context.Document, Glyph.CSharpFile, ImmutableArray.Create(".csx"), s_rules); context.AddItems(await helper.GetItemsAsync(pathThroughLastSlash, context.CancellationToken).ConfigureAwait(false)); } } }
-1
dotnet/roslyn
55,256
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-30T00:02:02Z
2021-07-30T09:17:54Z
6ce9c0048d37026337701fac035ac0745f6fe49f
88b59775dc6375635957ef229116460f290072aa
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Compilers/CSharp/Portable/Binder/Semantics/Operators/BinaryOperatorSignature.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Diagnostics; using Microsoft.CodeAnalysis.CSharp.Symbols; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { internal struct BinaryOperatorSignature : IEquatable<BinaryOperatorSignature> { public static BinaryOperatorSignature Error = default(BinaryOperatorSignature); public readonly TypeSymbol LeftType; public readonly TypeSymbol RightType; public readonly TypeSymbol ReturnType; public readonly MethodSymbol Method; public readonly TypeSymbol ConstrainedToTypeOpt; public readonly BinaryOperatorKind Kind; /// <summary> /// To duplicate native compiler behavior for some scenarios we force a priority among /// operators. If two operators are both applicable and both have a non-null Priority, /// the one with the numerically lower Priority value is preferred. /// </summary> public int? Priority; public BinaryOperatorSignature(BinaryOperatorKind kind, TypeSymbol leftType, TypeSymbol rightType, TypeSymbol returnType) { this.Kind = kind; this.LeftType = leftType; this.RightType = rightType; this.ReturnType = returnType; this.Method = null; this.ConstrainedToTypeOpt = null; this.Priority = null; } public BinaryOperatorSignature(BinaryOperatorKind kind, TypeSymbol leftType, TypeSymbol rightType, TypeSymbol returnType, MethodSymbol method, TypeSymbol constrainedToTypeOpt) { this.Kind = kind; this.LeftType = leftType; this.RightType = rightType; this.ReturnType = returnType; this.Method = method; this.ConstrainedToTypeOpt = constrainedToTypeOpt; this.Priority = null; } public override string ToString() { return $"kind: {this.Kind} leftType: {this.LeftType} leftRefKind: {this.LeftRefKind} rightType: {this.RightType} rightRefKind: {this.RightRefKind} return: {this.ReturnType}"; } public bool Equals(BinaryOperatorSignature other) { return this.Kind == other.Kind && TypeSymbol.Equals(this.LeftType, other.LeftType, TypeCompareKind.ConsiderEverything2) && TypeSymbol.Equals(this.RightType, other.RightType, TypeCompareKind.ConsiderEverything2) && TypeSymbol.Equals(this.ReturnType, other.ReturnType, TypeCompareKind.ConsiderEverything2) && this.Method == other.Method; } public static bool operator ==(BinaryOperatorSignature x, BinaryOperatorSignature y) { return x.Equals(y); } public static bool operator !=(BinaryOperatorSignature x, BinaryOperatorSignature y) { return !x.Equals(y); } public override bool Equals(object obj) { return obj is BinaryOperatorSignature && Equals((BinaryOperatorSignature)obj); } public override int GetHashCode() { return Hash.Combine(ReturnType, Hash.Combine(LeftType, Hash.Combine(RightType, Hash.Combine(Method, (int)Kind)))); } public RefKind LeftRefKind { get { if ((object)Method != null) { Debug.Assert(Method.ParameterCount == 2); if (!Method.ParameterRefKinds.IsDefaultOrEmpty) { Debug.Assert(Method.ParameterRefKinds.Length == 2); return Method.ParameterRefKinds[0]; } } return RefKind.None; } } public RefKind RightRefKind { get { if ((object)Method != null) { Debug.Assert(Method.ParameterCount == 2); if (!Method.ParameterRefKinds.IsDefaultOrEmpty) { Debug.Assert(Method.ParameterRefKinds.Length == 2); return Method.ParameterRefKinds[1]; } } return RefKind.None; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Diagnostics; using Microsoft.CodeAnalysis.CSharp.Symbols; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { internal struct BinaryOperatorSignature : IEquatable<BinaryOperatorSignature> { public static BinaryOperatorSignature Error = default(BinaryOperatorSignature); public readonly TypeSymbol LeftType; public readonly TypeSymbol RightType; public readonly TypeSymbol ReturnType; public readonly MethodSymbol Method; public readonly TypeSymbol ConstrainedToTypeOpt; public readonly BinaryOperatorKind Kind; /// <summary> /// To duplicate native compiler behavior for some scenarios we force a priority among /// operators. If two operators are both applicable and both have a non-null Priority, /// the one with the numerically lower Priority value is preferred. /// </summary> public int? Priority; public BinaryOperatorSignature(BinaryOperatorKind kind, TypeSymbol leftType, TypeSymbol rightType, TypeSymbol returnType) { this.Kind = kind; this.LeftType = leftType; this.RightType = rightType; this.ReturnType = returnType; this.Method = null; this.ConstrainedToTypeOpt = null; this.Priority = null; } public BinaryOperatorSignature(BinaryOperatorKind kind, TypeSymbol leftType, TypeSymbol rightType, TypeSymbol returnType, MethodSymbol method, TypeSymbol constrainedToTypeOpt) { this.Kind = kind; this.LeftType = leftType; this.RightType = rightType; this.ReturnType = returnType; this.Method = method; this.ConstrainedToTypeOpt = constrainedToTypeOpt; this.Priority = null; } public override string ToString() { return $"kind: {this.Kind} leftType: {this.LeftType} leftRefKind: {this.LeftRefKind} rightType: {this.RightType} rightRefKind: {this.RightRefKind} return: {this.ReturnType}"; } public bool Equals(BinaryOperatorSignature other) { return this.Kind == other.Kind && TypeSymbol.Equals(this.LeftType, other.LeftType, TypeCompareKind.ConsiderEverything2) && TypeSymbol.Equals(this.RightType, other.RightType, TypeCompareKind.ConsiderEverything2) && TypeSymbol.Equals(this.ReturnType, other.ReturnType, TypeCompareKind.ConsiderEverything2) && this.Method == other.Method; } public static bool operator ==(BinaryOperatorSignature x, BinaryOperatorSignature y) { return x.Equals(y); } public static bool operator !=(BinaryOperatorSignature x, BinaryOperatorSignature y) { return !x.Equals(y); } public override bool Equals(object obj) { return obj is BinaryOperatorSignature && Equals((BinaryOperatorSignature)obj); } public override int GetHashCode() { return Hash.Combine(ReturnType, Hash.Combine(LeftType, Hash.Combine(RightType, Hash.Combine(Method, (int)Kind)))); } public RefKind LeftRefKind { get { if ((object)Method != null) { Debug.Assert(Method.ParameterCount == 2); if (!Method.ParameterRefKinds.IsDefaultOrEmpty) { Debug.Assert(Method.ParameterRefKinds.Length == 2); return Method.ParameterRefKinds[0]; } } return RefKind.None; } } public RefKind RightRefKind { get { if ((object)Method != null) { Debug.Assert(Method.ParameterCount == 2); if (!Method.ParameterRefKinds.IsDefaultOrEmpty) { Debug.Assert(Method.ParameterRefKinds.Length == 2); return Method.ParameterRefKinds[1]; } } return RefKind.None; } } } }
-1
dotnet/roslyn
55,256
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-30T00:02:02Z
2021-07-30T09:17:54Z
6ce9c0048d37026337701fac035ac0745f6fe49f
88b59775dc6375635957ef229116460f290072aa
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Extensions/OperationExtensions.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using Microsoft.CodeAnalysis.FlowAnalysis; using Microsoft.CodeAnalysis.Operations; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { internal static partial class OperationExtensions { public static bool IsTargetOfObjectMemberInitializer(this IOperation operation) => operation.Parent is IAssignmentOperation assignmentOperation && assignmentOperation.Target == operation && assignmentOperation.Parent?.Kind == OperationKind.ObjectOrCollectionInitializer; /// <summary> /// Returns the <see cref="ValueUsageInfo"/> for the given operation. /// This extension can be removed once https://github.com/dotnet/roslyn/issues/25057 is implemented. /// </summary> public static ValueUsageInfo GetValueUsageInfo(this IOperation operation, ISymbol containingSymbol) { /* | code | Read | Write | ReadableRef | WritableRef | NonReadWriteRef | | x.Prop = 1 | | ✔️ | | | | | x.Prop += 1 | ✔️ | ✔️ | | | | | x.Prop++ | ✔️ | ✔️ | | | | | Foo(x.Prop) | ✔️ | | | | | | Foo(x.Prop), | | | ✔️ | | | where void Foo(in T v) | Foo(out x.Prop) | | | | ✔️ | | | Foo(ref x.Prop) | | | ✔️ | ✔️ | | | nameof(x) | | | | | ✔️ | ️ | sizeof(x) | | | | | ✔️ | ️ | typeof(x) | | | | | ✔️ | ️ | out var x | | ✔️ | | | | ️ | case X x: | | ✔️ | | | | ️ | obj is X x | | ✔️ | | | | | ref var x = | | | ✔️ | ✔️ | | | ref readonly var x = | | | ✔️ | | | */ if (operation is ILocalReferenceOperation localReference && localReference.IsDeclaration && !localReference.IsImplicit) // Workaround for https://github.com/dotnet/roslyn/issues/30753 { // Declaration expression is a definition (write) for the declared local. return ValueUsageInfo.Write; } else if (operation is IDeclarationPatternOperation) { while (operation.Parent is IBinaryPatternOperation || operation.Parent is INegatedPatternOperation || operation.Parent is IRelationalPatternOperation) { operation = operation.Parent; } switch (operation.Parent) { case IPatternCaseClauseOperation _: // A declaration pattern within a pattern case clause is a // write for the declared local. // For example, 'x' is defined and assigned the value from 'obj' below: // switch (obj) // { // case X x: // return ValueUsageInfo.Write; case IRecursivePatternOperation _: // A declaration pattern within a recursive pattern is a // write for the declared local. // For example, 'x' is defined and assigned the value from 'obj' below: // (obj) switch // { // (X x) => ... // }; // return ValueUsageInfo.Write; case ISwitchExpressionArmOperation _: // A declaration pattern within a switch expression arm is a // write for the declared local. // For example, 'x' is defined and assigned the value from 'obj' below: // obj switch // { // X x => ... // return ValueUsageInfo.Write; case IIsPatternOperation _: // A declaration pattern within an is pattern is a // write for the declared local. // For example, 'x' is defined and assigned the value from 'obj' below: // if (obj is X x) // return ValueUsageInfo.Write; case IPropertySubpatternOperation _: // A declaration pattern within a property sub-pattern is a // write for the declared local. // For example, 'x' is defined and assigned the value from 'obj.Property' below: // if (obj is { Property : int x }) // return ValueUsageInfo.Write; default: Debug.Fail("Unhandled declaration pattern context"); // Conservatively assume read/write. return ValueUsageInfo.ReadWrite; } } if (operation.Parent is IAssignmentOperation assignmentOperation && assignmentOperation.Target == operation) { return operation.Parent.IsAnyCompoundAssignment() ? ValueUsageInfo.ReadWrite : ValueUsageInfo.Write; } else if (operation.Parent is IIncrementOrDecrementOperation) { return ValueUsageInfo.ReadWrite; } else if (operation.Parent is IParenthesizedOperation parenthesizedOperation) { // Note: IParenthesizedOperation is specific to VB, where the parens cause a copy, so this cannot be classified as a write. Debug.Assert(parenthesizedOperation.Language == LanguageNames.VisualBasic); return parenthesizedOperation.GetValueUsageInfo(containingSymbol) & ~(ValueUsageInfo.Write | ValueUsageInfo.Reference); } else if (operation.Parent is INameOfOperation || operation.Parent is ITypeOfOperation || operation.Parent is ISizeOfOperation) { return ValueUsageInfo.Name; } else if (operation.Parent is IArgumentOperation argumentOperation) { switch (argumentOperation.Parameter?.RefKind) { case RefKind.RefReadOnly: return ValueUsageInfo.ReadableReference; case RefKind.Out: return ValueUsageInfo.WritableReference; case RefKind.Ref: return ValueUsageInfo.ReadableWritableReference; default: return ValueUsageInfo.Read; } } else if (operation.Parent is IReturnOperation returnOperation) { return returnOperation.GetRefKind(containingSymbol) switch { RefKind.RefReadOnly => ValueUsageInfo.ReadableReference, RefKind.Ref => ValueUsageInfo.ReadableWritableReference, _ => ValueUsageInfo.Read, }; } else if (operation.Parent is IConditionalOperation conditionalOperation) { if (operation == conditionalOperation.WhenTrue || operation == conditionalOperation.WhenFalse) { return GetValueUsageInfo(conditionalOperation, containingSymbol); } else { return ValueUsageInfo.Read; } } else if (operation.Parent is IReDimClauseOperation reDimClauseOperation && reDimClauseOperation.Operand == operation) { return (reDimClauseOperation.Parent as IReDimOperation)?.Preserve == true ? ValueUsageInfo.ReadWrite : ValueUsageInfo.Write; } else if (operation.Parent is IDeclarationExpressionOperation declarationExpression) { return declarationExpression.GetValueUsageInfo(containingSymbol); } else if (operation.IsInLeftOfDeconstructionAssignment(out _)) { return ValueUsageInfo.Write; } else if (operation.Parent is IVariableInitializerOperation variableInitializerOperation) { if (variableInitializerOperation.Parent is IVariableDeclaratorOperation variableDeclaratorOperation) { switch (variableDeclaratorOperation.Symbol.RefKind) { case RefKind.Ref: return ValueUsageInfo.ReadableWritableReference; case RefKind.RefReadOnly: return ValueUsageInfo.ReadableReference; } } } return ValueUsageInfo.Read; } public static RefKind GetRefKind(this IReturnOperation? operation, ISymbol containingSymbol) { var containingMethod = TryGetContainingAnonymousFunctionOrLocalFunction(operation) ?? (containingSymbol as IMethodSymbol); return containingMethod?.RefKind ?? RefKind.None; } public static IMethodSymbol? TryGetContainingAnonymousFunctionOrLocalFunction(this IOperation? operation) { operation = operation?.Parent; while (operation != null) { switch (operation.Kind) { case OperationKind.AnonymousFunction: return ((IAnonymousFunctionOperation)operation).Symbol; case OperationKind.LocalFunction: return ((ILocalFunctionOperation)operation).Symbol; } operation = operation.Parent; } return null; } public static bool IsInLeftOfDeconstructionAssignment(this IOperation operation, [NotNullWhen(true)] out IDeconstructionAssignmentOperation? deconstructionAssignment) { deconstructionAssignment = null; var previousOperation = operation; var current = operation.Parent; while (current != null) { switch (current.Kind) { case OperationKind.DeconstructionAssignment: deconstructionAssignment = (IDeconstructionAssignmentOperation)current; return deconstructionAssignment.Target == previousOperation; case OperationKind.Tuple: case OperationKind.Conversion: case OperationKind.Parenthesized: previousOperation = current; current = current.Parent; continue; default: return false; } } return false; } /// <summary> /// Retursn true if the given operation is a regular compound assignment, /// i.e. <see cref="ICompoundAssignmentOperation"/> such as <code>a += b</code>, /// or a special null coalescing compoud assignment, i.e. <see cref="ICoalesceAssignmentOperation"/> /// such as <code>a ??= b</code>. /// </summary> public static bool IsAnyCompoundAssignment(this IOperation operation) { switch (operation) { case ICompoundAssignmentOperation _: case ICoalesceAssignmentOperation _: return true; default: return false; } } public static bool IsInsideCatchRegion(this IOperation operation, ControlFlowGraph cfg) { foreach (var block in cfg.Blocks) { var isCatchRegionBlock = false; var currentRegion = block.EnclosingRegion; while (currentRegion != null) { switch (currentRegion.Kind) { case ControlFlowRegionKind.Catch: isCatchRegionBlock = true; break; } currentRegion = currentRegion.EnclosingRegion; } if (isCatchRegionBlock) { foreach (var descendant in block.DescendantOperations()) { if (operation == descendant) { return true; } } } } return false; } public static bool HasAnyOperationDescendant(this ImmutableArray<IOperation> operationBlocks, Func<IOperation, bool> predicate) { foreach (var operationBlock in operationBlocks) { if (operationBlock.HasAnyOperationDescendant(predicate)) { return true; } } return false; } public static bool HasAnyOperationDescendant(this IOperation operationBlock, Func<IOperation, bool> predicate) => operationBlock.HasAnyOperationDescendant(predicate, out _); public static bool HasAnyOperationDescendant(this IOperation operationBlock, Func<IOperation, bool> predicate, [NotNullWhen(true)] out IOperation? foundOperation) { RoslynDebug.AssertNotNull(operationBlock); RoslynDebug.AssertNotNull(predicate); foreach (var descendant in operationBlock.DescendantsAndSelf()) { if (predicate(descendant)) { foundOperation = descendant; return true; } } foundOperation = null; return false; } public static bool HasAnyOperationDescendant(this ImmutableArray<IOperation> operationBlocks, OperationKind kind) => operationBlocks.HasAnyOperationDescendant(predicate: operation => operation.Kind == kind); public static bool IsNumericLiteral(this IOperation operation) => operation.Kind == OperationKind.Literal && operation.Type.IsNumericType(); public static bool IsNullLiteral(this IOperation operand) => operand is ILiteralOperation { ConstantValue: { HasValue: true, Value: 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.Diagnostics; using System.Diagnostics.CodeAnalysis; using Microsoft.CodeAnalysis.FlowAnalysis; using Microsoft.CodeAnalysis.Operations; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { internal static partial class OperationExtensions { public static bool IsTargetOfObjectMemberInitializer(this IOperation operation) => operation.Parent is IAssignmentOperation assignmentOperation && assignmentOperation.Target == operation && assignmentOperation.Parent?.Kind == OperationKind.ObjectOrCollectionInitializer; /// <summary> /// Returns the <see cref="ValueUsageInfo"/> for the given operation. /// This extension can be removed once https://github.com/dotnet/roslyn/issues/25057 is implemented. /// </summary> public static ValueUsageInfo GetValueUsageInfo(this IOperation operation, ISymbol containingSymbol) { /* | code | Read | Write | ReadableRef | WritableRef | NonReadWriteRef | | x.Prop = 1 | | ✔️ | | | | | x.Prop += 1 | ✔️ | ✔️ | | | | | x.Prop++ | ✔️ | ✔️ | | | | | Foo(x.Prop) | ✔️ | | | | | | Foo(x.Prop), | | | ✔️ | | | where void Foo(in T v) | Foo(out x.Prop) | | | | ✔️ | | | Foo(ref x.Prop) | | | ✔️ | ✔️ | | | nameof(x) | | | | | ✔️ | ️ | sizeof(x) | | | | | ✔️ | ️ | typeof(x) | | | | | ✔️ | ️ | out var x | | ✔️ | | | | ️ | case X x: | | ✔️ | | | | ️ | obj is X x | | ✔️ | | | | | ref var x = | | | ✔️ | ✔️ | | | ref readonly var x = | | | ✔️ | | | */ if (operation is ILocalReferenceOperation localReference && localReference.IsDeclaration && !localReference.IsImplicit) // Workaround for https://github.com/dotnet/roslyn/issues/30753 { // Declaration expression is a definition (write) for the declared local. return ValueUsageInfo.Write; } else if (operation is IDeclarationPatternOperation) { while (operation.Parent is IBinaryPatternOperation || operation.Parent is INegatedPatternOperation || operation.Parent is IRelationalPatternOperation) { operation = operation.Parent; } switch (operation.Parent) { case IPatternCaseClauseOperation _: // A declaration pattern within a pattern case clause is a // write for the declared local. // For example, 'x' is defined and assigned the value from 'obj' below: // switch (obj) // { // case X x: // return ValueUsageInfo.Write; case IRecursivePatternOperation _: // A declaration pattern within a recursive pattern is a // write for the declared local. // For example, 'x' is defined and assigned the value from 'obj' below: // (obj) switch // { // (X x) => ... // }; // return ValueUsageInfo.Write; case ISwitchExpressionArmOperation _: // A declaration pattern within a switch expression arm is a // write for the declared local. // For example, 'x' is defined and assigned the value from 'obj' below: // obj switch // { // X x => ... // return ValueUsageInfo.Write; case IIsPatternOperation _: // A declaration pattern within an is pattern is a // write for the declared local. // For example, 'x' is defined and assigned the value from 'obj' below: // if (obj is X x) // return ValueUsageInfo.Write; case IPropertySubpatternOperation _: // A declaration pattern within a property sub-pattern is a // write for the declared local. // For example, 'x' is defined and assigned the value from 'obj.Property' below: // if (obj is { Property : int x }) // return ValueUsageInfo.Write; default: Debug.Fail("Unhandled declaration pattern context"); // Conservatively assume read/write. return ValueUsageInfo.ReadWrite; } } if (operation.Parent is IAssignmentOperation assignmentOperation && assignmentOperation.Target == operation) { return operation.Parent.IsAnyCompoundAssignment() ? ValueUsageInfo.ReadWrite : ValueUsageInfo.Write; } else if (operation.Parent is IIncrementOrDecrementOperation) { return ValueUsageInfo.ReadWrite; } else if (operation.Parent is IParenthesizedOperation parenthesizedOperation) { // Note: IParenthesizedOperation is specific to VB, where the parens cause a copy, so this cannot be classified as a write. Debug.Assert(parenthesizedOperation.Language == LanguageNames.VisualBasic); return parenthesizedOperation.GetValueUsageInfo(containingSymbol) & ~(ValueUsageInfo.Write | ValueUsageInfo.Reference); } else if (operation.Parent is INameOfOperation || operation.Parent is ITypeOfOperation || operation.Parent is ISizeOfOperation) { return ValueUsageInfo.Name; } else if (operation.Parent is IArgumentOperation argumentOperation) { switch (argumentOperation.Parameter?.RefKind) { case RefKind.RefReadOnly: return ValueUsageInfo.ReadableReference; case RefKind.Out: return ValueUsageInfo.WritableReference; case RefKind.Ref: return ValueUsageInfo.ReadableWritableReference; default: return ValueUsageInfo.Read; } } else if (operation.Parent is IReturnOperation returnOperation) { return returnOperation.GetRefKind(containingSymbol) switch { RefKind.RefReadOnly => ValueUsageInfo.ReadableReference, RefKind.Ref => ValueUsageInfo.ReadableWritableReference, _ => ValueUsageInfo.Read, }; } else if (operation.Parent is IConditionalOperation conditionalOperation) { if (operation == conditionalOperation.WhenTrue || operation == conditionalOperation.WhenFalse) { return GetValueUsageInfo(conditionalOperation, containingSymbol); } else { return ValueUsageInfo.Read; } } else if (operation.Parent is IReDimClauseOperation reDimClauseOperation && reDimClauseOperation.Operand == operation) { return (reDimClauseOperation.Parent as IReDimOperation)?.Preserve == true ? ValueUsageInfo.ReadWrite : ValueUsageInfo.Write; } else if (operation.Parent is IDeclarationExpressionOperation declarationExpression) { return declarationExpression.GetValueUsageInfo(containingSymbol); } else if (operation.IsInLeftOfDeconstructionAssignment(out _)) { return ValueUsageInfo.Write; } else if (operation.Parent is IVariableInitializerOperation variableInitializerOperation) { if (variableInitializerOperation.Parent is IVariableDeclaratorOperation variableDeclaratorOperation) { switch (variableDeclaratorOperation.Symbol.RefKind) { case RefKind.Ref: return ValueUsageInfo.ReadableWritableReference; case RefKind.RefReadOnly: return ValueUsageInfo.ReadableReference; } } } return ValueUsageInfo.Read; } public static RefKind GetRefKind(this IReturnOperation? operation, ISymbol containingSymbol) { var containingMethod = TryGetContainingAnonymousFunctionOrLocalFunction(operation) ?? (containingSymbol as IMethodSymbol); return containingMethod?.RefKind ?? RefKind.None; } public static IMethodSymbol? TryGetContainingAnonymousFunctionOrLocalFunction(this IOperation? operation) { operation = operation?.Parent; while (operation != null) { switch (operation.Kind) { case OperationKind.AnonymousFunction: return ((IAnonymousFunctionOperation)operation).Symbol; case OperationKind.LocalFunction: return ((ILocalFunctionOperation)operation).Symbol; } operation = operation.Parent; } return null; } public static bool IsInLeftOfDeconstructionAssignment(this IOperation operation, [NotNullWhen(true)] out IDeconstructionAssignmentOperation? deconstructionAssignment) { deconstructionAssignment = null; var previousOperation = operation; var current = operation.Parent; while (current != null) { switch (current.Kind) { case OperationKind.DeconstructionAssignment: deconstructionAssignment = (IDeconstructionAssignmentOperation)current; return deconstructionAssignment.Target == previousOperation; case OperationKind.Tuple: case OperationKind.Conversion: case OperationKind.Parenthesized: previousOperation = current; current = current.Parent; continue; default: return false; } } return false; } /// <summary> /// Retursn true if the given operation is a regular compound assignment, /// i.e. <see cref="ICompoundAssignmentOperation"/> such as <code>a += b</code>, /// or a special null coalescing compoud assignment, i.e. <see cref="ICoalesceAssignmentOperation"/> /// such as <code>a ??= b</code>. /// </summary> public static bool IsAnyCompoundAssignment(this IOperation operation) { switch (operation) { case ICompoundAssignmentOperation _: case ICoalesceAssignmentOperation _: return true; default: return false; } } public static bool IsInsideCatchRegion(this IOperation operation, ControlFlowGraph cfg) { foreach (var block in cfg.Blocks) { var isCatchRegionBlock = false; var currentRegion = block.EnclosingRegion; while (currentRegion != null) { switch (currentRegion.Kind) { case ControlFlowRegionKind.Catch: isCatchRegionBlock = true; break; } currentRegion = currentRegion.EnclosingRegion; } if (isCatchRegionBlock) { foreach (var descendant in block.DescendantOperations()) { if (operation == descendant) { return true; } } } } return false; } public static bool HasAnyOperationDescendant(this ImmutableArray<IOperation> operationBlocks, Func<IOperation, bool> predicate) { foreach (var operationBlock in operationBlocks) { if (operationBlock.HasAnyOperationDescendant(predicate)) { return true; } } return false; } public static bool HasAnyOperationDescendant(this IOperation operationBlock, Func<IOperation, bool> predicate) => operationBlock.HasAnyOperationDescendant(predicate, out _); public static bool HasAnyOperationDescendant(this IOperation operationBlock, Func<IOperation, bool> predicate, [NotNullWhen(true)] out IOperation? foundOperation) { RoslynDebug.AssertNotNull(operationBlock); RoslynDebug.AssertNotNull(predicate); foreach (var descendant in operationBlock.DescendantsAndSelf()) { if (predicate(descendant)) { foundOperation = descendant; return true; } } foundOperation = null; return false; } public static bool HasAnyOperationDescendant(this ImmutableArray<IOperation> operationBlocks, OperationKind kind) => operationBlocks.HasAnyOperationDescendant(predicate: operation => operation.Kind == kind); public static bool IsNumericLiteral(this IOperation operation) => operation.Kind == OperationKind.Literal && operation.Type.IsNumericType(); public static bool IsNullLiteral(this IOperation operand) => operand is ILiteralOperation { ConstantValue: { HasValue: true, Value: null } }; } }
-1
dotnet/roslyn
55,256
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-30T00:02:02Z
2021-07-30T09:17:54Z
6ce9c0048d37026337701fac035ac0745f6fe49f
88b59775dc6375635957ef229116460f290072aa
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/EmbeddedLanguages/Common/EmbeddedDiagnostic.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Diagnostics; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.EmbeddedLanguages.Common { /// <summary> /// Represents an error in a embedded language snippet. The error contains the message to show /// a user as well as the span of the error. This span is in actual user character coordinates. /// For example, if the user has the string "...\\p{0}..." then the span of the error would be /// for the range of characters for '\\p{0}' (even though the regex engine would only see the \\ /// translated as a virtual char to the single \ character. /// </summary> internal struct EmbeddedDiagnostic : IEquatable<EmbeddedDiagnostic> { public readonly string Message; public readonly TextSpan Span; public EmbeddedDiagnostic(string message, TextSpan span) { RoslynDebug.AssertNotNull(message); Message = message; Span = span; } public override bool Equals(object? obj) => obj is EmbeddedDiagnostic diagnostic && Equals(diagnostic); public bool Equals(EmbeddedDiagnostic other) => Message == other.Message && Span.Equals(other.Span); public override int GetHashCode() { unchecked { var hashCode = -954867195; hashCode = hashCode * -1521134295 + base.GetHashCode(); hashCode = hashCode * -1521134295 + EqualityComparer<string>.Default.GetHashCode(Message); hashCode = hashCode * -1521134295 + EqualityComparer<TextSpan>.Default.GetHashCode(Span); return hashCode; } } public static bool operator ==(EmbeddedDiagnostic diagnostic1, EmbeddedDiagnostic diagnostic2) => diagnostic1.Equals(diagnostic2); public static bool operator !=(EmbeddedDiagnostic diagnostic1, EmbeddedDiagnostic diagnostic2) => !(diagnostic1 == diagnostic2); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Diagnostics; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.EmbeddedLanguages.Common { /// <summary> /// Represents an error in a embedded language snippet. The error contains the message to show /// a user as well as the span of the error. This span is in actual user character coordinates. /// For example, if the user has the string "...\\p{0}..." then the span of the error would be /// for the range of characters for '\\p{0}' (even though the regex engine would only see the \\ /// translated as a virtual char to the single \ character. /// </summary> internal struct EmbeddedDiagnostic : IEquatable<EmbeddedDiagnostic> { public readonly string Message; public readonly TextSpan Span; public EmbeddedDiagnostic(string message, TextSpan span) { RoslynDebug.AssertNotNull(message); Message = message; Span = span; } public override bool Equals(object? obj) => obj is EmbeddedDiagnostic diagnostic && Equals(diagnostic); public bool Equals(EmbeddedDiagnostic other) => Message == other.Message && Span.Equals(other.Span); public override int GetHashCode() { unchecked { var hashCode = -954867195; hashCode = hashCode * -1521134295 + base.GetHashCode(); hashCode = hashCode * -1521134295 + EqualityComparer<string>.Default.GetHashCode(Message); hashCode = hashCode * -1521134295 + EqualityComparer<TextSpan>.Default.GetHashCode(Span); return hashCode; } } public static bool operator ==(EmbeddedDiagnostic diagnostic1, EmbeddedDiagnostic diagnostic2) => diagnostic1.Equals(diagnostic2); public static bool operator !=(EmbeddedDiagnostic diagnostic1, EmbeddedDiagnostic diagnostic2) => !(diagnostic1 == diagnostic2); } }
-1
dotnet/roslyn
55,256
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-30T00:02:02Z
2021-07-30T09:17:54Z
6ce9c0048d37026337701fac035ac0745f6fe49f
88b59775dc6375635957ef229116460f290072aa
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Compilers/CSharp/Test/IOperation/IOperation/IOperationTests_ICompoundAssignmentOperation.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Operations; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class IOperationTests_ICompoundAssignmentOperation : SemanticModelTestBase { [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void ICompoundAssignment_NullArgumentToGetConversionThrows() { ICompoundAssignmentOperation nullAssignment = null; Assert.Throws<ArgumentNullException>("compoundAssignment", () => nullAssignment.GetInConversion()); Assert.Throws<ArgumentNullException>("compoundAssignment", () => nullAssignment.GetOutConversion()); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void ICompoundAssignment_GetConversionOnValidNode_IdentityConversion() { string source = @" class C { static void M() { int x = 1, y = 1; /*<bind>*/x += y/*</bind>*/; } } "; var syntaxTree = Parse(source); var compilation = CreateCompilationWithMscorlib45(new[] { syntaxTree }); (IOperation operation, _) = GetOperationAndSyntaxForTest<AssignmentExpressionSyntax>(compilation); var compoundAssignment = (ICompoundAssignmentOperation)operation; Assert.Equal(Conversion.Identity, compoundAssignment.GetInConversion()); Assert.Equal(Conversion.Identity, compoundAssignment.GetOutConversion()); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void ICompoundAssignment_GetConversionOnValidNode_InOutConversion() { string source = @" class C { static void M() { var c = new C(); var x = 1; /*<bind>*/c += x/*</bind>*/; } public static implicit operator C(int i) { return null; } public static implicit operator int(C c) { return 0; } } "; var syntaxTree = Parse(source); var compilation = CreateCompilationWithMscorlib45(new[] { syntaxTree }); (IOperation operation, SyntaxNode node) = GetOperationAndSyntaxForTest<AssignmentExpressionSyntax>(compilation); var compoundAssignment = (ICompoundAssignmentOperation)operation; var typeSymbol = compilation.GetTypeByMetadataName("C"); var implicitSymbols = typeSymbol.GetMembers("op_Implicit").Cast<MethodSymbol>(); var inSymbol = implicitSymbols.Where(sym => sym.ReturnType.SpecialType == SpecialType.System_Int32).Single(); var outSymbol = implicitSymbols.Where(sym => sym != inSymbol).Single(); var inConversion = new Conversion(ConversionKind.ImplicitUserDefined, inSymbol, false); var outConversion = new Conversion(ConversionKind.ImplicitUserDefined, outSymbol, false); Assert.Equal(inConversion, compoundAssignment.GetInConversion()); Assert.Equal(outConversion, compoundAssignment.GetOutConversion()); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void ICompoundAssignment_BinaryOperatorInOutConversion() { string source = @" class C { static void M() { var c = new C(); var x = 1; /*<bind>*/c += x/*</bind>*/; } public static implicit operator C(int i) { return null; } public static implicit operator int(C c) { return 0; } } "; string expectedOperationTree = @" ICompoundAssignmentOperation (BinaryOperatorKind.Add) (OperationKind.CompoundAssignment, Type: C) (Syntax: 'c += x') InConversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: True) (MethodSymbol: System.Int32 C.op_Implicit(C c)) OutConversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: True) (MethodSymbol: C C.op_Implicit(System.Int32 i)) Left: ILocalReferenceOperation: c (OperationKind.LocalReference, Type: C) (Syntax: 'c') Right: ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x') "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<AssignmentExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void ICompoundAssignment_BinaryOperatorInConversion_InvalidMissingOutConversion() { string source = @" class C { static void M() { var c = new C(); var x = 1; /*<bind>*/c += x/*</bind>*/; } public static implicit operator int(C c) { return 0; } } "; string expectedOperationTree = @" ICompoundAssignmentOperation (BinaryOperatorKind.Add) (OperationKind.CompoundAssignment, Type: C, IsInvalid) (Syntax: 'c += x') InConversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: True) (MethodSymbol: System.Int32 C.op_Implicit(C c)) OutConversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Left: ILocalReferenceOperation: c (OperationKind.LocalReference, Type: C, IsInvalid) (Syntax: 'c') Right: ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'x') "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0029: Cannot implicitly convert type 'int' to 'C' // /*<bind>*/c += x/*</bind>*/; Diagnostic(ErrorCode.ERR_NoImplicitConv, "c += x").WithArguments("int", "C").WithLocation(8, 19) }; VerifyOperationTreeAndDiagnosticsForTest<AssignmentExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void ICompoundAssignment_BinaryOperatorOutConversion_InvalidMissingInConversion() { string source = @" class C { static void M() { var c = new C(); var x = 1; /*<bind>*/c += x/*</bind>*/; } public static implicit operator C(int i) { return null; } } "; string expectedOperationTree = @" ICompoundAssignmentOperation (BinaryOperatorKind.None) (OperationKind.CompoundAssignment, Type: ?, IsInvalid) (Syntax: 'c += x') InConversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Left: ILocalReferenceOperation: c (OperationKind.LocalReference, Type: C, IsInvalid) (Syntax: 'c') Right: ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'x') "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0019: Operator '+=' cannot be applied to operands of type 'C' and 'int' // /*<bind>*/c += x/*</bind>*/; Diagnostic(ErrorCode.ERR_BadBinaryOps, "c += x").WithArguments("+=", "C", "int").WithLocation(8, 19) }; VerifyOperationTreeAndDiagnosticsForTest<AssignmentExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void ICompoundAssignment_UserDefinedBinaryOperator_InConversion() { string source = @" class C { static void M() { var c = new C(); var x = 1; /*<bind>*/c += x/*</bind>*/; } public static implicit operator C(int i) { return null; } public static implicit operator int(C c) { return 0; } public static C operator +(int c1, C c2) { return null; } } "; string expectedOperationTree = @" ICompoundAssignmentOperation (BinaryOperatorKind.Add) (OperatorMethod: C C.op_Addition(System.Int32 c1, C c2)) (OperationKind.CompoundAssignment, Type: C) (Syntax: 'c += x') InConversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: True) (MethodSymbol: System.Int32 C.op_Implicit(C c)) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Left: ILocalReferenceOperation: c (OperationKind.LocalReference, Type: C) (Syntax: 'c') Right: IConversionOperation (TryCast: False, Unchecked) (OperatorMethod: C C.op_Implicit(System.Int32 i)) (OperationKind.Conversion, Type: C, IsImplicit) (Syntax: 'x') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: True) (MethodSymbol: C C.op_Implicit(System.Int32 i)) Operand: ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x') "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<AssignmentExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void ICompoundAssignment_UserDefinedBinaryOperator_OutConversion() { string source = @" class C { static void M() { var c = new C(); var x = 1; /*<bind>*/c += x/*</bind>*/; } public static implicit operator C(int i) { return null; } public static implicit operator int(C c) { return 0; } public static int operator +(C c1, C c2) { return 0; } } "; string expectedOperationTree = @" ICompoundAssignmentOperation (BinaryOperatorKind.Add) (OperatorMethod: System.Int32 C.op_Addition(C c1, C c2)) (OperationKind.CompoundAssignment, Type: C) (Syntax: 'c += x') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: True) (MethodSymbol: C C.op_Implicit(System.Int32 i)) Left: ILocalReferenceOperation: c (OperationKind.LocalReference, Type: C) (Syntax: 'c') Right: IConversionOperation (TryCast: False, Unchecked) (OperatorMethod: C C.op_Implicit(System.Int32 i)) (OperationKind.Conversion, Type: C, IsImplicit) (Syntax: 'x') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: True) (MethodSymbol: C C.op_Implicit(System.Int32 i)) Operand: ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x') "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<AssignmentExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void ICompoundAssignment_UserDefinedBinaryOperator_InOutConversion() { string source = @" class C { static void M() { var c = new C(); var x = 1; /*<bind>*/c += x/*</bind>*/; } public static implicit operator C(int i) { return null; } public static implicit operator int(C c) { return 0; } public static int operator +(int c1, C c2) { return 0; } } "; string expectedOperationTree = @" ICompoundAssignmentOperation (BinaryOperatorKind.Add) (OperatorMethod: System.Int32 C.op_Addition(System.Int32 c1, C c2)) (OperationKind.CompoundAssignment, Type: C) (Syntax: 'c += x') InConversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: True) (MethodSymbol: System.Int32 C.op_Implicit(C c)) OutConversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: True) (MethodSymbol: C C.op_Implicit(System.Int32 i)) Left: ILocalReferenceOperation: c (OperationKind.LocalReference, Type: C) (Syntax: 'c') Right: IConversionOperation (TryCast: False, Unchecked) (OperatorMethod: C C.op_Implicit(System.Int32 i)) (OperationKind.Conversion, Type: C, IsImplicit) (Syntax: 'x') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: True) (MethodSymbol: C C.op_Implicit(System.Int32 i)) Operand: ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x') "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<AssignmentExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void ICompoundAssignment_UserDefinedBinaryOperator_InvalidMissingInConversion() { string source = @" class C { static void M() { var c = new C(); var x = 1; /*<bind>*/c += x/*</bind>*/; } public static implicit operator C(int i) { return null; } public static int operator +(int c1, C c2) { return 0; } } "; string expectedOperationTree = @" ICompoundAssignmentOperation (BinaryOperatorKind.None) (OperationKind.CompoundAssignment, Type: ?, IsInvalid) (Syntax: 'c += x') InConversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Left: ILocalReferenceOperation: c (OperationKind.LocalReference, Type: C, IsInvalid) (Syntax: 'c') Right: ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'x') "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0019: Operator '+=' cannot be applied to operands of type 'C' and 'int' // /*<bind>*/c += x/*</bind>*/; Diagnostic(ErrorCode.ERR_BadBinaryOps, "c += x").WithArguments("+=", "C", "int").WithLocation(8, 19) }; VerifyOperationTreeAndDiagnosticsForTest<AssignmentExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void ICompoundAssignment_UserDefinedBinaryOperator_InvalidMissingOutConversion() { string source = @" class C { static void M() { var c = new C(); var x = 1; /*<bind>*/c += x/*</bind>*/; } public static implicit operator int(C c) { return 0; } public static int operator +(int c1, C c2) { return 0; } } "; string expectedOperationTree = @" ICompoundAssignmentOperation (BinaryOperatorKind.Add) (OperationKind.CompoundAssignment, Type: C, IsInvalid) (Syntax: 'c += x') InConversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: True) (MethodSymbol: System.Int32 C.op_Implicit(C c)) OutConversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Left: ILocalReferenceOperation: c (OperationKind.LocalReference, Type: C, IsInvalid) (Syntax: 'c') Right: ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'x') "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0029: Cannot implicitly convert type 'int' to 'C' // /*<bind>*/c += x/*</bind>*/; Diagnostic(ErrorCode.ERR_NoImplicitConv, "c += x").WithArguments("int", "C").WithLocation(8, 19) }; VerifyOperationTreeAndDiagnosticsForTest<AssignmentExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void CompoundAssignment_01() { string source = @" using System; class C { void M(int[] a, int? b, int c) /*<bind>*/{ a[0] += b ?? c; }/*</bind>*/ } "; var expectedDiagnostics = DiagnosticDescription.None; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [2] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a[0]') Value: IArrayElementReferenceOperation (OperationKind.ArrayElementReference, Type: System.Int32) (Syntax: 'a[0]') Array reference: IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Int32[]) (Syntax: 'a') Indices(1): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') Next (Regular) Block[B2] Entering: {R2} .locals {R2} { CaptureIds: [1] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'b') Value: IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'b') Jump if True (Regular) to Block[B4] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'b') Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'b') Leaving: {R2} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'b') Value: IInvocationOperation ( System.Int32 System.Int32?.GetValueOrDefault()) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'b') Instance Receiver: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'b') Arguments(0) Next (Regular) Block[B5] Leaving: {R2} } Block[B4] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c') Value: IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'c') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a[0] += b ?? c;') Expression: ICompoundAssignmentOperation (BinaryOperatorKind.Add) (OperationKind.CompoundAssignment, Type: System.Int32) (Syntax: 'a[0] += b ?? c') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'a[0]') Right: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'b ?? c') Next (Regular) Block[B6] Leaving: {R1} } Block[B6] - Exit Predecessors: [B5] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void CompoundAssignment_02() { string source = @" using System; class C { void M(int[] a, int? b, int c) /*<bind>*/{ a[0] -= b ?? c; }/*</bind>*/ } "; var expectedDiagnostics = DiagnosticDescription.None; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [2] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a[0]') Value: IArrayElementReferenceOperation (OperationKind.ArrayElementReference, Type: System.Int32) (Syntax: 'a[0]') Array reference: IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Int32[]) (Syntax: 'a') Indices(1): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') Next (Regular) Block[B2] Entering: {R2} .locals {R2} { CaptureIds: [1] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'b') Value: IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'b') Jump if True (Regular) to Block[B4] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'b') Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'b') Leaving: {R2} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'b') Value: IInvocationOperation ( System.Int32 System.Int32?.GetValueOrDefault()) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'b') Instance Receiver: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'b') Arguments(0) Next (Regular) Block[B5] Leaving: {R2} } Block[B4] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c') Value: IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'c') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a[0] -= b ?? c;') Expression: ICompoundAssignmentOperation (BinaryOperatorKind.Subtract) (OperationKind.CompoundAssignment, Type: System.Int32) (Syntax: 'a[0] -= b ?? c') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'a[0]') Right: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'b ?? c') Next (Regular) Block[B6] Leaving: {R1} } Block[B6] - Exit Predecessors: [B5] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void CompoundAssignment_03() { string source = @" using System; class C { void M(int[] a, int? b, int c) /*<bind>*/{ a[0] *= b ?? c; }/*</bind>*/ } "; var expectedDiagnostics = DiagnosticDescription.None; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [2] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a[0]') Value: IArrayElementReferenceOperation (OperationKind.ArrayElementReference, Type: System.Int32) (Syntax: 'a[0]') Array reference: IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Int32[]) (Syntax: 'a') Indices(1): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') Next (Regular) Block[B2] Entering: {R2} .locals {R2} { CaptureIds: [1] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'b') Value: IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'b') Jump if True (Regular) to Block[B4] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'b') Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'b') Leaving: {R2} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'b') Value: IInvocationOperation ( System.Int32 System.Int32?.GetValueOrDefault()) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'b') Instance Receiver: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'b') Arguments(0) Next (Regular) Block[B5] Leaving: {R2} } Block[B4] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c') Value: IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'c') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a[0] *= b ?? c;') Expression: ICompoundAssignmentOperation (BinaryOperatorKind.Multiply) (OperationKind.CompoundAssignment, Type: System.Int32) (Syntax: 'a[0] *= b ?? c') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'a[0]') Right: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'b ?? c') Next (Regular) Block[B6] Leaving: {R1} } Block[B6] - Exit Predecessors: [B5] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void CompoundAssignment_04() { string source = @" using System; class C { void M(int[] a, int? b, int c) /*<bind>*/{ a[0] /= b ?? c; }/*</bind>*/ } "; var expectedDiagnostics = DiagnosticDescription.None; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [2] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a[0]') Value: IArrayElementReferenceOperation (OperationKind.ArrayElementReference, Type: System.Int32) (Syntax: 'a[0]') Array reference: IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Int32[]) (Syntax: 'a') Indices(1): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') Next (Regular) Block[B2] Entering: {R2} .locals {R2} { CaptureIds: [1] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'b') Value: IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'b') Jump if True (Regular) to Block[B4] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'b') Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'b') Leaving: {R2} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'b') Value: IInvocationOperation ( System.Int32 System.Int32?.GetValueOrDefault()) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'b') Instance Receiver: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'b') Arguments(0) Next (Regular) Block[B5] Leaving: {R2} } Block[B4] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c') Value: IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'c') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a[0] /= b ?? c;') Expression: ICompoundAssignmentOperation (BinaryOperatorKind.Divide) (OperationKind.CompoundAssignment, Type: System.Int32) (Syntax: 'a[0] /= b ?? c') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'a[0]') Right: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'b ?? c') Next (Regular) Block[B6] Leaving: {R1} } Block[B6] - Exit Predecessors: [B5] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void CompoundAssignment_05() { string source = @" using System; class C { void M(int[] a, int? b, int c) /*<bind>*/{ a[0] %= b ?? c; }/*</bind>*/ } "; var expectedDiagnostics = DiagnosticDescription.None; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [2] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a[0]') Value: IArrayElementReferenceOperation (OperationKind.ArrayElementReference, Type: System.Int32) (Syntax: 'a[0]') Array reference: IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Int32[]) (Syntax: 'a') Indices(1): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') Next (Regular) Block[B2] Entering: {R2} .locals {R2} { CaptureIds: [1] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'b') Value: IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'b') Jump if True (Regular) to Block[B4] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'b') Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'b') Leaving: {R2} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'b') Value: IInvocationOperation ( System.Int32 System.Int32?.GetValueOrDefault()) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'b') Instance Receiver: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'b') Arguments(0) Next (Regular) Block[B5] Leaving: {R2} } Block[B4] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c') Value: IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'c') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a[0] %= b ?? c;') Expression: ICompoundAssignmentOperation (BinaryOperatorKind.Remainder) (OperationKind.CompoundAssignment, Type: System.Int32) (Syntax: 'a[0] %= b ?? c') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'a[0]') Right: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'b ?? c') Next (Regular) Block[B6] Leaving: {R1} } Block[B6] - Exit Predecessors: [B5] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void CompoundAssignment_06() { string source = @" using System; class C { void M(int[] a, int? b, int c) /*<bind>*/{ a[0] &= b ?? c; }/*</bind>*/ } "; var expectedDiagnostics = DiagnosticDescription.None; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [2] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a[0]') Value: IArrayElementReferenceOperation (OperationKind.ArrayElementReference, Type: System.Int32) (Syntax: 'a[0]') Array reference: IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Int32[]) (Syntax: 'a') Indices(1): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') Next (Regular) Block[B2] Entering: {R2} .locals {R2} { CaptureIds: [1] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'b') Value: IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'b') Jump if True (Regular) to Block[B4] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'b') Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'b') Leaving: {R2} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'b') Value: IInvocationOperation ( System.Int32 System.Int32?.GetValueOrDefault()) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'b') Instance Receiver: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'b') Arguments(0) Next (Regular) Block[B5] Leaving: {R2} } Block[B4] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c') Value: IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'c') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a[0] &= b ?? c;') Expression: ICompoundAssignmentOperation (BinaryOperatorKind.And) (OperationKind.CompoundAssignment, Type: System.Int32) (Syntax: 'a[0] &= b ?? c') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'a[0]') Right: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'b ?? c') Next (Regular) Block[B6] Leaving: {R1} } Block[B6] - Exit Predecessors: [B5] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void CompoundAssignment_07() { string source = @" using System; class C { void M(int[] a, int? b, int c) /*<bind>*/{ a[0] |= b ?? c; }/*</bind>*/ } "; var expectedDiagnostics = DiagnosticDescription.None; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [2] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a[0]') Value: IArrayElementReferenceOperation (OperationKind.ArrayElementReference, Type: System.Int32) (Syntax: 'a[0]') Array reference: IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Int32[]) (Syntax: 'a') Indices(1): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') Next (Regular) Block[B2] Entering: {R2} .locals {R2} { CaptureIds: [1] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'b') Value: IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'b') Jump if True (Regular) to Block[B4] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'b') Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'b') Leaving: {R2} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'b') Value: IInvocationOperation ( System.Int32 System.Int32?.GetValueOrDefault()) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'b') Instance Receiver: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'b') Arguments(0) Next (Regular) Block[B5] Leaving: {R2} } Block[B4] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c') Value: IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'c') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a[0] |= b ?? c;') Expression: ICompoundAssignmentOperation (BinaryOperatorKind.Or) (OperationKind.CompoundAssignment, Type: System.Int32) (Syntax: 'a[0] |= b ?? c') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'a[0]') Right: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'b ?? c') Next (Regular) Block[B6] Leaving: {R1} } Block[B6] - Exit Predecessors: [B5] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void CompoundAssignment_08() { string source = @" using System; class C { void M(int[] a, int? b, int c) /*<bind>*/{ a[0] ^= b ?? c; }/*</bind>*/ } "; var expectedDiagnostics = DiagnosticDescription.None; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [2] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a[0]') Value: IArrayElementReferenceOperation (OperationKind.ArrayElementReference, Type: System.Int32) (Syntax: 'a[0]') Array reference: IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Int32[]) (Syntax: 'a') Indices(1): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') Next (Regular) Block[B2] Entering: {R2} .locals {R2} { CaptureIds: [1] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'b') Value: IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'b') Jump if True (Regular) to Block[B4] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'b') Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'b') Leaving: {R2} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'b') Value: IInvocationOperation ( System.Int32 System.Int32?.GetValueOrDefault()) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'b') Instance Receiver: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'b') Arguments(0) Next (Regular) Block[B5] Leaving: {R2} } Block[B4] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c') Value: IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'c') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a[0] ^= b ?? c;') Expression: ICompoundAssignmentOperation (BinaryOperatorKind.ExclusiveOr) (OperationKind.CompoundAssignment, Type: System.Int32) (Syntax: 'a[0] ^= b ?? c') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'a[0]') Right: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'b ?? c') Next (Regular) Block[B6] Leaving: {R1} } Block[B6] - Exit Predecessors: [B5] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void CompoundAssignment_09() { string source = @" using System; class C { void M(int[] a, int? b, int c) /*<bind>*/{ a[0] <<= b ?? c; }/*</bind>*/ } "; var expectedDiagnostics = DiagnosticDescription.None; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [2] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a[0]') Value: IArrayElementReferenceOperation (OperationKind.ArrayElementReference, Type: System.Int32) (Syntax: 'a[0]') Array reference: IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Int32[]) (Syntax: 'a') Indices(1): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') Next (Regular) Block[B2] Entering: {R2} .locals {R2} { CaptureIds: [1] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'b') Value: IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'b') Jump if True (Regular) to Block[B4] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'b') Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'b') Leaving: {R2} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'b') Value: IInvocationOperation ( System.Int32 System.Int32?.GetValueOrDefault()) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'b') Instance Receiver: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'b') Arguments(0) Next (Regular) Block[B5] Leaving: {R2} } Block[B4] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c') Value: IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'c') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a[0] <<= b ?? c;') Expression: ICompoundAssignmentOperation (BinaryOperatorKind.LeftShift) (OperationKind.CompoundAssignment, Type: System.Int32) (Syntax: 'a[0] <<= b ?? c') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'a[0]') Right: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'b ?? c') Next (Regular) Block[B6] Leaving: {R1} } Block[B6] - Exit Predecessors: [B5] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void CompoundAssignment_10() { string source = @" using System; class C { void M(int[] a, int? b, int c) /*<bind>*/{ a[0] >>= b ?? c; }/*</bind>*/ } "; var expectedDiagnostics = DiagnosticDescription.None; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [2] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a[0]') Value: IArrayElementReferenceOperation (OperationKind.ArrayElementReference, Type: System.Int32) (Syntax: 'a[0]') Array reference: IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Int32[]) (Syntax: 'a') Indices(1): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') Next (Regular) Block[B2] Entering: {R2} .locals {R2} { CaptureIds: [1] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'b') Value: IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'b') Jump if True (Regular) to Block[B4] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'b') Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'b') Leaving: {R2} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'b') Value: IInvocationOperation ( System.Int32 System.Int32?.GetValueOrDefault()) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'b') Instance Receiver: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'b') Arguments(0) Next (Regular) Block[B5] Leaving: {R2} } Block[B4] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c') Value: IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'c') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a[0] >>= b ?? c;') Expression: ICompoundAssignmentOperation (BinaryOperatorKind.RightShift) (OperationKind.CompoundAssignment, Type: System.Int32) (Syntax: 'a[0] >>= b ?? c') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'a[0]') Right: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'b ?? c') Next (Regular) Block[B6] Leaving: {R1} } Block[B6] - Exit Predecessors: [B5] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Operations; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class IOperationTests_ICompoundAssignmentOperation : SemanticModelTestBase { [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void ICompoundAssignment_NullArgumentToGetConversionThrows() { ICompoundAssignmentOperation nullAssignment = null; Assert.Throws<ArgumentNullException>("compoundAssignment", () => nullAssignment.GetInConversion()); Assert.Throws<ArgumentNullException>("compoundAssignment", () => nullAssignment.GetOutConversion()); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void ICompoundAssignment_GetConversionOnValidNode_IdentityConversion() { string source = @" class C { static void M() { int x = 1, y = 1; /*<bind>*/x += y/*</bind>*/; } } "; var syntaxTree = Parse(source); var compilation = CreateCompilationWithMscorlib45(new[] { syntaxTree }); (IOperation operation, _) = GetOperationAndSyntaxForTest<AssignmentExpressionSyntax>(compilation); var compoundAssignment = (ICompoundAssignmentOperation)operation; Assert.Equal(Conversion.Identity, compoundAssignment.GetInConversion()); Assert.Equal(Conversion.Identity, compoundAssignment.GetOutConversion()); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void ICompoundAssignment_GetConversionOnValidNode_InOutConversion() { string source = @" class C { static void M() { var c = new C(); var x = 1; /*<bind>*/c += x/*</bind>*/; } public static implicit operator C(int i) { return null; } public static implicit operator int(C c) { return 0; } } "; var syntaxTree = Parse(source); var compilation = CreateCompilationWithMscorlib45(new[] { syntaxTree }); (IOperation operation, SyntaxNode node) = GetOperationAndSyntaxForTest<AssignmentExpressionSyntax>(compilation); var compoundAssignment = (ICompoundAssignmentOperation)operation; var typeSymbol = compilation.GetTypeByMetadataName("C"); var implicitSymbols = typeSymbol.GetMembers("op_Implicit").Cast<MethodSymbol>(); var inSymbol = implicitSymbols.Where(sym => sym.ReturnType.SpecialType == SpecialType.System_Int32).Single(); var outSymbol = implicitSymbols.Where(sym => sym != inSymbol).Single(); var inConversion = new Conversion(ConversionKind.ImplicitUserDefined, inSymbol, false); var outConversion = new Conversion(ConversionKind.ImplicitUserDefined, outSymbol, false); Assert.Equal(inConversion, compoundAssignment.GetInConversion()); Assert.Equal(outConversion, compoundAssignment.GetOutConversion()); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void ICompoundAssignment_BinaryOperatorInOutConversion() { string source = @" class C { static void M() { var c = new C(); var x = 1; /*<bind>*/c += x/*</bind>*/; } public static implicit operator C(int i) { return null; } public static implicit operator int(C c) { return 0; } } "; string expectedOperationTree = @" ICompoundAssignmentOperation (BinaryOperatorKind.Add) (OperationKind.CompoundAssignment, Type: C) (Syntax: 'c += x') InConversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: True) (MethodSymbol: System.Int32 C.op_Implicit(C c)) OutConversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: True) (MethodSymbol: C C.op_Implicit(System.Int32 i)) Left: ILocalReferenceOperation: c (OperationKind.LocalReference, Type: C) (Syntax: 'c') Right: ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x') "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<AssignmentExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void ICompoundAssignment_BinaryOperatorInConversion_InvalidMissingOutConversion() { string source = @" class C { static void M() { var c = new C(); var x = 1; /*<bind>*/c += x/*</bind>*/; } public static implicit operator int(C c) { return 0; } } "; string expectedOperationTree = @" ICompoundAssignmentOperation (BinaryOperatorKind.Add) (OperationKind.CompoundAssignment, Type: C, IsInvalid) (Syntax: 'c += x') InConversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: True) (MethodSymbol: System.Int32 C.op_Implicit(C c)) OutConversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Left: ILocalReferenceOperation: c (OperationKind.LocalReference, Type: C, IsInvalid) (Syntax: 'c') Right: ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'x') "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0029: Cannot implicitly convert type 'int' to 'C' // /*<bind>*/c += x/*</bind>*/; Diagnostic(ErrorCode.ERR_NoImplicitConv, "c += x").WithArguments("int", "C").WithLocation(8, 19) }; VerifyOperationTreeAndDiagnosticsForTest<AssignmentExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void ICompoundAssignment_BinaryOperatorOutConversion_InvalidMissingInConversion() { string source = @" class C { static void M() { var c = new C(); var x = 1; /*<bind>*/c += x/*</bind>*/; } public static implicit operator C(int i) { return null; } } "; string expectedOperationTree = @" ICompoundAssignmentOperation (BinaryOperatorKind.None) (OperationKind.CompoundAssignment, Type: ?, IsInvalid) (Syntax: 'c += x') InConversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Left: ILocalReferenceOperation: c (OperationKind.LocalReference, Type: C, IsInvalid) (Syntax: 'c') Right: ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'x') "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0019: Operator '+=' cannot be applied to operands of type 'C' and 'int' // /*<bind>*/c += x/*</bind>*/; Diagnostic(ErrorCode.ERR_BadBinaryOps, "c += x").WithArguments("+=", "C", "int").WithLocation(8, 19) }; VerifyOperationTreeAndDiagnosticsForTest<AssignmentExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void ICompoundAssignment_UserDefinedBinaryOperator_InConversion() { string source = @" class C { static void M() { var c = new C(); var x = 1; /*<bind>*/c += x/*</bind>*/; } public static implicit operator C(int i) { return null; } public static implicit operator int(C c) { return 0; } public static C operator +(int c1, C c2) { return null; } } "; string expectedOperationTree = @" ICompoundAssignmentOperation (BinaryOperatorKind.Add) (OperatorMethod: C C.op_Addition(System.Int32 c1, C c2)) (OperationKind.CompoundAssignment, Type: C) (Syntax: 'c += x') InConversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: True) (MethodSymbol: System.Int32 C.op_Implicit(C c)) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Left: ILocalReferenceOperation: c (OperationKind.LocalReference, Type: C) (Syntax: 'c') Right: IConversionOperation (TryCast: False, Unchecked) (OperatorMethod: C C.op_Implicit(System.Int32 i)) (OperationKind.Conversion, Type: C, IsImplicit) (Syntax: 'x') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: True) (MethodSymbol: C C.op_Implicit(System.Int32 i)) Operand: ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x') "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<AssignmentExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void ICompoundAssignment_UserDefinedBinaryOperator_OutConversion() { string source = @" class C { static void M() { var c = new C(); var x = 1; /*<bind>*/c += x/*</bind>*/; } public static implicit operator C(int i) { return null; } public static implicit operator int(C c) { return 0; } public static int operator +(C c1, C c2) { return 0; } } "; string expectedOperationTree = @" ICompoundAssignmentOperation (BinaryOperatorKind.Add) (OperatorMethod: System.Int32 C.op_Addition(C c1, C c2)) (OperationKind.CompoundAssignment, Type: C) (Syntax: 'c += x') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: True) (MethodSymbol: C C.op_Implicit(System.Int32 i)) Left: ILocalReferenceOperation: c (OperationKind.LocalReference, Type: C) (Syntax: 'c') Right: IConversionOperation (TryCast: False, Unchecked) (OperatorMethod: C C.op_Implicit(System.Int32 i)) (OperationKind.Conversion, Type: C, IsImplicit) (Syntax: 'x') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: True) (MethodSymbol: C C.op_Implicit(System.Int32 i)) Operand: ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x') "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<AssignmentExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void ICompoundAssignment_UserDefinedBinaryOperator_InOutConversion() { string source = @" class C { static void M() { var c = new C(); var x = 1; /*<bind>*/c += x/*</bind>*/; } public static implicit operator C(int i) { return null; } public static implicit operator int(C c) { return 0; } public static int operator +(int c1, C c2) { return 0; } } "; string expectedOperationTree = @" ICompoundAssignmentOperation (BinaryOperatorKind.Add) (OperatorMethod: System.Int32 C.op_Addition(System.Int32 c1, C c2)) (OperationKind.CompoundAssignment, Type: C) (Syntax: 'c += x') InConversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: True) (MethodSymbol: System.Int32 C.op_Implicit(C c)) OutConversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: True) (MethodSymbol: C C.op_Implicit(System.Int32 i)) Left: ILocalReferenceOperation: c (OperationKind.LocalReference, Type: C) (Syntax: 'c') Right: IConversionOperation (TryCast: False, Unchecked) (OperatorMethod: C C.op_Implicit(System.Int32 i)) (OperationKind.Conversion, Type: C, IsImplicit) (Syntax: 'x') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: True) (MethodSymbol: C C.op_Implicit(System.Int32 i)) Operand: ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x') "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<AssignmentExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void ICompoundAssignment_UserDefinedBinaryOperator_InvalidMissingInConversion() { string source = @" class C { static void M() { var c = new C(); var x = 1; /*<bind>*/c += x/*</bind>*/; } public static implicit operator C(int i) { return null; } public static int operator +(int c1, C c2) { return 0; } } "; string expectedOperationTree = @" ICompoundAssignmentOperation (BinaryOperatorKind.None) (OperationKind.CompoundAssignment, Type: ?, IsInvalid) (Syntax: 'c += x') InConversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Left: ILocalReferenceOperation: c (OperationKind.LocalReference, Type: C, IsInvalid) (Syntax: 'c') Right: ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'x') "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0019: Operator '+=' cannot be applied to operands of type 'C' and 'int' // /*<bind>*/c += x/*</bind>*/; Diagnostic(ErrorCode.ERR_BadBinaryOps, "c += x").WithArguments("+=", "C", "int").WithLocation(8, 19) }; VerifyOperationTreeAndDiagnosticsForTest<AssignmentExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void ICompoundAssignment_UserDefinedBinaryOperator_InvalidMissingOutConversion() { string source = @" class C { static void M() { var c = new C(); var x = 1; /*<bind>*/c += x/*</bind>*/; } public static implicit operator int(C c) { return 0; } public static int operator +(int c1, C c2) { return 0; } } "; string expectedOperationTree = @" ICompoundAssignmentOperation (BinaryOperatorKind.Add) (OperationKind.CompoundAssignment, Type: C, IsInvalid) (Syntax: 'c += x') InConversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: True) (MethodSymbol: System.Int32 C.op_Implicit(C c)) OutConversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Left: ILocalReferenceOperation: c (OperationKind.LocalReference, Type: C, IsInvalid) (Syntax: 'c') Right: ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'x') "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0029: Cannot implicitly convert type 'int' to 'C' // /*<bind>*/c += x/*</bind>*/; Diagnostic(ErrorCode.ERR_NoImplicitConv, "c += x").WithArguments("int", "C").WithLocation(8, 19) }; VerifyOperationTreeAndDiagnosticsForTest<AssignmentExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void CompoundAssignment_01() { string source = @" using System; class C { void M(int[] a, int? b, int c) /*<bind>*/{ a[0] += b ?? c; }/*</bind>*/ } "; var expectedDiagnostics = DiagnosticDescription.None; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [2] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a[0]') Value: IArrayElementReferenceOperation (OperationKind.ArrayElementReference, Type: System.Int32) (Syntax: 'a[0]') Array reference: IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Int32[]) (Syntax: 'a') Indices(1): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') Next (Regular) Block[B2] Entering: {R2} .locals {R2} { CaptureIds: [1] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'b') Value: IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'b') Jump if True (Regular) to Block[B4] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'b') Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'b') Leaving: {R2} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'b') Value: IInvocationOperation ( System.Int32 System.Int32?.GetValueOrDefault()) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'b') Instance Receiver: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'b') Arguments(0) Next (Regular) Block[B5] Leaving: {R2} } Block[B4] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c') Value: IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'c') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a[0] += b ?? c;') Expression: ICompoundAssignmentOperation (BinaryOperatorKind.Add) (OperationKind.CompoundAssignment, Type: System.Int32) (Syntax: 'a[0] += b ?? c') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'a[0]') Right: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'b ?? c') Next (Regular) Block[B6] Leaving: {R1} } Block[B6] - Exit Predecessors: [B5] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void CompoundAssignment_02() { string source = @" using System; class C { void M(int[] a, int? b, int c) /*<bind>*/{ a[0] -= b ?? c; }/*</bind>*/ } "; var expectedDiagnostics = DiagnosticDescription.None; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [2] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a[0]') Value: IArrayElementReferenceOperation (OperationKind.ArrayElementReference, Type: System.Int32) (Syntax: 'a[0]') Array reference: IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Int32[]) (Syntax: 'a') Indices(1): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') Next (Regular) Block[B2] Entering: {R2} .locals {R2} { CaptureIds: [1] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'b') Value: IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'b') Jump if True (Regular) to Block[B4] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'b') Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'b') Leaving: {R2} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'b') Value: IInvocationOperation ( System.Int32 System.Int32?.GetValueOrDefault()) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'b') Instance Receiver: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'b') Arguments(0) Next (Regular) Block[B5] Leaving: {R2} } Block[B4] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c') Value: IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'c') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a[0] -= b ?? c;') Expression: ICompoundAssignmentOperation (BinaryOperatorKind.Subtract) (OperationKind.CompoundAssignment, Type: System.Int32) (Syntax: 'a[0] -= b ?? c') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'a[0]') Right: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'b ?? c') Next (Regular) Block[B6] Leaving: {R1} } Block[B6] - Exit Predecessors: [B5] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void CompoundAssignment_03() { string source = @" using System; class C { void M(int[] a, int? b, int c) /*<bind>*/{ a[0] *= b ?? c; }/*</bind>*/ } "; var expectedDiagnostics = DiagnosticDescription.None; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [2] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a[0]') Value: IArrayElementReferenceOperation (OperationKind.ArrayElementReference, Type: System.Int32) (Syntax: 'a[0]') Array reference: IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Int32[]) (Syntax: 'a') Indices(1): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') Next (Regular) Block[B2] Entering: {R2} .locals {R2} { CaptureIds: [1] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'b') Value: IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'b') Jump if True (Regular) to Block[B4] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'b') Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'b') Leaving: {R2} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'b') Value: IInvocationOperation ( System.Int32 System.Int32?.GetValueOrDefault()) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'b') Instance Receiver: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'b') Arguments(0) Next (Regular) Block[B5] Leaving: {R2} } Block[B4] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c') Value: IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'c') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a[0] *= b ?? c;') Expression: ICompoundAssignmentOperation (BinaryOperatorKind.Multiply) (OperationKind.CompoundAssignment, Type: System.Int32) (Syntax: 'a[0] *= b ?? c') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'a[0]') Right: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'b ?? c') Next (Regular) Block[B6] Leaving: {R1} } Block[B6] - Exit Predecessors: [B5] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void CompoundAssignment_04() { string source = @" using System; class C { void M(int[] a, int? b, int c) /*<bind>*/{ a[0] /= b ?? c; }/*</bind>*/ } "; var expectedDiagnostics = DiagnosticDescription.None; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [2] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a[0]') Value: IArrayElementReferenceOperation (OperationKind.ArrayElementReference, Type: System.Int32) (Syntax: 'a[0]') Array reference: IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Int32[]) (Syntax: 'a') Indices(1): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') Next (Regular) Block[B2] Entering: {R2} .locals {R2} { CaptureIds: [1] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'b') Value: IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'b') Jump if True (Regular) to Block[B4] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'b') Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'b') Leaving: {R2} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'b') Value: IInvocationOperation ( System.Int32 System.Int32?.GetValueOrDefault()) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'b') Instance Receiver: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'b') Arguments(0) Next (Regular) Block[B5] Leaving: {R2} } Block[B4] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c') Value: IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'c') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a[0] /= b ?? c;') Expression: ICompoundAssignmentOperation (BinaryOperatorKind.Divide) (OperationKind.CompoundAssignment, Type: System.Int32) (Syntax: 'a[0] /= b ?? c') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'a[0]') Right: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'b ?? c') Next (Regular) Block[B6] Leaving: {R1} } Block[B6] - Exit Predecessors: [B5] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void CompoundAssignment_05() { string source = @" using System; class C { void M(int[] a, int? b, int c) /*<bind>*/{ a[0] %= b ?? c; }/*</bind>*/ } "; var expectedDiagnostics = DiagnosticDescription.None; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [2] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a[0]') Value: IArrayElementReferenceOperation (OperationKind.ArrayElementReference, Type: System.Int32) (Syntax: 'a[0]') Array reference: IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Int32[]) (Syntax: 'a') Indices(1): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') Next (Regular) Block[B2] Entering: {R2} .locals {R2} { CaptureIds: [1] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'b') Value: IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'b') Jump if True (Regular) to Block[B4] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'b') Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'b') Leaving: {R2} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'b') Value: IInvocationOperation ( System.Int32 System.Int32?.GetValueOrDefault()) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'b') Instance Receiver: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'b') Arguments(0) Next (Regular) Block[B5] Leaving: {R2} } Block[B4] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c') Value: IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'c') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a[0] %= b ?? c;') Expression: ICompoundAssignmentOperation (BinaryOperatorKind.Remainder) (OperationKind.CompoundAssignment, Type: System.Int32) (Syntax: 'a[0] %= b ?? c') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'a[0]') Right: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'b ?? c') Next (Regular) Block[B6] Leaving: {R1} } Block[B6] - Exit Predecessors: [B5] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void CompoundAssignment_06() { string source = @" using System; class C { void M(int[] a, int? b, int c) /*<bind>*/{ a[0] &= b ?? c; }/*</bind>*/ } "; var expectedDiagnostics = DiagnosticDescription.None; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [2] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a[0]') Value: IArrayElementReferenceOperation (OperationKind.ArrayElementReference, Type: System.Int32) (Syntax: 'a[0]') Array reference: IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Int32[]) (Syntax: 'a') Indices(1): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') Next (Regular) Block[B2] Entering: {R2} .locals {R2} { CaptureIds: [1] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'b') Value: IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'b') Jump if True (Regular) to Block[B4] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'b') Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'b') Leaving: {R2} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'b') Value: IInvocationOperation ( System.Int32 System.Int32?.GetValueOrDefault()) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'b') Instance Receiver: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'b') Arguments(0) Next (Regular) Block[B5] Leaving: {R2} } Block[B4] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c') Value: IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'c') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a[0] &= b ?? c;') Expression: ICompoundAssignmentOperation (BinaryOperatorKind.And) (OperationKind.CompoundAssignment, Type: System.Int32) (Syntax: 'a[0] &= b ?? c') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'a[0]') Right: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'b ?? c') Next (Regular) Block[B6] Leaving: {R1} } Block[B6] - Exit Predecessors: [B5] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void CompoundAssignment_07() { string source = @" using System; class C { void M(int[] a, int? b, int c) /*<bind>*/{ a[0] |= b ?? c; }/*</bind>*/ } "; var expectedDiagnostics = DiagnosticDescription.None; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [2] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a[0]') Value: IArrayElementReferenceOperation (OperationKind.ArrayElementReference, Type: System.Int32) (Syntax: 'a[0]') Array reference: IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Int32[]) (Syntax: 'a') Indices(1): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') Next (Regular) Block[B2] Entering: {R2} .locals {R2} { CaptureIds: [1] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'b') Value: IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'b') Jump if True (Regular) to Block[B4] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'b') Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'b') Leaving: {R2} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'b') Value: IInvocationOperation ( System.Int32 System.Int32?.GetValueOrDefault()) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'b') Instance Receiver: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'b') Arguments(0) Next (Regular) Block[B5] Leaving: {R2} } Block[B4] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c') Value: IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'c') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a[0] |= b ?? c;') Expression: ICompoundAssignmentOperation (BinaryOperatorKind.Or) (OperationKind.CompoundAssignment, Type: System.Int32) (Syntax: 'a[0] |= b ?? c') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'a[0]') Right: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'b ?? c') Next (Regular) Block[B6] Leaving: {R1} } Block[B6] - Exit Predecessors: [B5] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void CompoundAssignment_08() { string source = @" using System; class C { void M(int[] a, int? b, int c) /*<bind>*/{ a[0] ^= b ?? c; }/*</bind>*/ } "; var expectedDiagnostics = DiagnosticDescription.None; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [2] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a[0]') Value: IArrayElementReferenceOperation (OperationKind.ArrayElementReference, Type: System.Int32) (Syntax: 'a[0]') Array reference: IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Int32[]) (Syntax: 'a') Indices(1): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') Next (Regular) Block[B2] Entering: {R2} .locals {R2} { CaptureIds: [1] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'b') Value: IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'b') Jump if True (Regular) to Block[B4] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'b') Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'b') Leaving: {R2} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'b') Value: IInvocationOperation ( System.Int32 System.Int32?.GetValueOrDefault()) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'b') Instance Receiver: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'b') Arguments(0) Next (Regular) Block[B5] Leaving: {R2} } Block[B4] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c') Value: IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'c') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a[0] ^= b ?? c;') Expression: ICompoundAssignmentOperation (BinaryOperatorKind.ExclusiveOr) (OperationKind.CompoundAssignment, Type: System.Int32) (Syntax: 'a[0] ^= b ?? c') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'a[0]') Right: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'b ?? c') Next (Regular) Block[B6] Leaving: {R1} } Block[B6] - Exit Predecessors: [B5] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void CompoundAssignment_09() { string source = @" using System; class C { void M(int[] a, int? b, int c) /*<bind>*/{ a[0] <<= b ?? c; }/*</bind>*/ } "; var expectedDiagnostics = DiagnosticDescription.None; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [2] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a[0]') Value: IArrayElementReferenceOperation (OperationKind.ArrayElementReference, Type: System.Int32) (Syntax: 'a[0]') Array reference: IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Int32[]) (Syntax: 'a') Indices(1): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') Next (Regular) Block[B2] Entering: {R2} .locals {R2} { CaptureIds: [1] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'b') Value: IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'b') Jump if True (Regular) to Block[B4] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'b') Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'b') Leaving: {R2} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'b') Value: IInvocationOperation ( System.Int32 System.Int32?.GetValueOrDefault()) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'b') Instance Receiver: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'b') Arguments(0) Next (Regular) Block[B5] Leaving: {R2} } Block[B4] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c') Value: IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'c') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a[0] <<= b ?? c;') Expression: ICompoundAssignmentOperation (BinaryOperatorKind.LeftShift) (OperationKind.CompoundAssignment, Type: System.Int32) (Syntax: 'a[0] <<= b ?? c') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'a[0]') Right: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'b ?? c') Next (Regular) Block[B6] Leaving: {R1} } Block[B6] - Exit Predecessors: [B5] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void CompoundAssignment_10() { string source = @" using System; class C { void M(int[] a, int? b, int c) /*<bind>*/{ a[0] >>= b ?? c; }/*</bind>*/ } "; var expectedDiagnostics = DiagnosticDescription.None; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [2] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a[0]') Value: IArrayElementReferenceOperation (OperationKind.ArrayElementReference, Type: System.Int32) (Syntax: 'a[0]') Array reference: IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Int32[]) (Syntax: 'a') Indices(1): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') Next (Regular) Block[B2] Entering: {R2} .locals {R2} { CaptureIds: [1] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'b') Value: IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'b') Jump if True (Regular) to Block[B4] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'b') Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'b') Leaving: {R2} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'b') Value: IInvocationOperation ( System.Int32 System.Int32?.GetValueOrDefault()) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'b') Instance Receiver: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'b') Arguments(0) Next (Regular) Block[B5] Leaving: {R2} } Block[B4] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c') Value: IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'c') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a[0] >>= b ?? c;') Expression: ICompoundAssignmentOperation (BinaryOperatorKind.RightShift) (OperationKind.CompoundAssignment, Type: System.Int32) (Syntax: 'a[0] >>= b ?? c') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'a[0]') Right: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'b ?? c') Next (Regular) Block[B6] Leaving: {R1} } Block[B6] - Exit Predecessors: [B5] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } } }
-1
dotnet/roslyn
55,256
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-30T00:02:02Z
2021-07-30T09:17:54Z
6ce9c0048d37026337701fac035ac0745f6fe49f
88b59775dc6375635957ef229116460f290072aa
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/EditorFeatures/CSharpTest/ConvertForToForEach/ConvertForToForEachTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.CSharp.ConvertForToForEach; using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeRefactorings; using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.ConvertForToForEach { public class ConvertForToForEachTests : AbstractCSharpCodeActionTest { protected override CodeRefactoringProvider CreateCodeRefactoringProvider(Workspace workspace, TestParameters parameters) => new CSharpConvertForToForEachCodeRefactoringProvider(); private readonly CodeStyleOption2<bool> onWithSilent = new CodeStyleOption2<bool>(true, NotificationOption2.Silent); private OptionsCollection ImplicitTypeEverywhere() => new OptionsCollection(GetLanguage()) { { CSharpCodeStyleOptions.VarElsewhere, onWithSilent }, { CSharpCodeStyleOptions.VarWhenTypeIsApparent, onWithSilent }, { CSharpCodeStyleOptions.VarForBuiltInTypes, onWithSilent }, }; [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestArray1() { await TestInRegularAndScript1Async( @"using System; class C { void Test(string[] array) { [||]for (int i = 0; i < array.Length; i++) { Console.WriteLine(array[i]); } } }", @"using System; class C { void Test(string[] array) { foreach (string {|Rename:v|} in array) { Console.WriteLine(v); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestWarnIfCrossesFunctionBoundary() { await TestInRegularAndScript1Async( @"using System; class C { void Test(string[] array) { [||]for (int i = 0; i < array.Length; i++) { Action a = () => { Console.WriteLine(array[i]); }; } } }", @"using System; class C { void Test(string[] array) { foreach (string {|Rename:v|} in array) { Action a = () => { Console.WriteLine({|Warning:v|}); }; } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestWarnIfCollectionPotentiallyMutated1() { await TestInRegularAndScript1Async( @"using System; using System.Collections.Generic; class C { void Test(IList<string> list) { [||]for (int i = 0; i < list.Count; i++) { Console.WriteLine(list[i]); list.Add(null); } } }", @"using System; using System.Collections.Generic; class C { void Test(IList<string> list) { foreach (string {|Rename:v|} in list) { Console.WriteLine(v); {|Warning:list|}.Add(null); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestWarnIfCollectionPotentiallyMutated2() { await TestInRegularAndScript1Async( @"using System; using System.Collections.Generic; class C { void Test(IList<string> list) { [||]for (int i = 0; i < list.Count; i++) { Console.WriteLine(list[i]); list = null; } } }", @"using System; using System.Collections.Generic; class C { void Test(IList<string> list) { foreach (string {|Rename:v|} in list) { Console.WriteLine(v); {|Warning:list|} = null; } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestNoWarnIfCollectionPropertyAccess() { await TestInRegularAndScript1Async( @"using System; using System.Collections.Generic; class C { void Test(IList<string> list) { [||]for (int i = 0; i < list.Count; i++) { Console.WriteLine(list[i]); Console.WriteLine(list.Count); } } }", @"using System; using System.Collections.Generic; class C { void Test(IList<string> list) { foreach (string {|Rename:v|} in list) { Console.WriteLine(v); Console.WriteLine(list.Count); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestNoWarnIfDoesNotCrossFunctionBoundary() { await TestInRegularAndScript1Async( @"using System; class C { void Test(string[] array) { Action a = () => { [||]for (int i = 0; i < array.Length; i++) { Console.WriteLine(array[i]); } }; } }", @"using System; class C { void Test(string[] array) { Action a = () => { foreach (string {|Rename:v|} in array) { Console.WriteLine(v); } }; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestMultipleReferences() { await TestInRegularAndScript1Async( @"using System; class C { void Test(string[] array) { [||]for (int i = 0; i < array.Length; i++) { Console.WriteLine(array[i]); Console.WriteLine(array[i]); } } }", @"using System; class C { void Test(string[] array) { foreach (string {|Rename:v|} in array) { Console.WriteLine(v); Console.WriteLine(v); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestEmbeddedStatement() { await TestInRegularAndScript1Async( @"using System; class C { void Test(string[] array) { [||]for (int i = 0; i < array.Length; i++) Console.WriteLine(array[i]); } }", @"using System; class C { void Test(string[] array) { foreach (string {|Rename:v|} in array) Console.WriteLine(v); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestPostIncrement() { await TestInRegularAndScript1Async( @"using System; class C { void Test(string[] array) { [||]for (int i = 0; i < array.Length; ++i) { Console.WriteLine(array[i]); } } }", @"using System; class C { void Test(string[] array) { foreach (string {|Rename:v|} in array) { Console.WriteLine(v); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestArrayPlusEqualsIncrementor() { await TestInRegularAndScript1Async( @"using System; class C { void Test(string[] array) { [||]for (int i = 0; i < array.Length; i += 1) { Console.WriteLine(array[i]); } } }", @"using System; class C { void Test(string[] array) { foreach (string {|Rename:v|} in array) { Console.WriteLine(v); } } }"); } [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestBeforeKeyword() { await TestInRegularAndScript1Async( @"using System; class C { void Test(string[] array) { [||] for (int i = 0; i < array.Length; i++) { Console.WriteLine(array[i]); } } }", @"using System; class C { void Test(string[] array) { foreach (string {|Rename:v|} in array) { Console.WriteLine(v); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestMissingAfterOpenParen() { await TestMissingInRegularAndScriptAsync( @"using System; class C { void Test(string[] array) { for ( [||]int i = 0; i < array.Length; i++) { Console.WriteLine(array[i]); } } }"); } [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestInParentheses() { await TestInRegularAndScript1Async( @"using System; class C { void Test(string[] array) { for ([||]int i = 0; i < array.Length; i++) { Console.WriteLine(array[i]); } } }", @"using System; class C { void Test(string[] array) { foreach (string {|Rename:v|} in array) { Console.WriteLine(v); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestMissingBeforeCloseParen() { await TestMissingInRegularAndScriptAsync( @"using System; class C { void Test(string[] array) { for (int i = 0; i < array.Length; i++[||] ) { Console.WriteLine(array[i]); } } }"); } [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestInParentheses2() { await TestInRegularAndScript1Async( @"using System; class C { void Test(string[] array) { for (int i = 0; i < array.Length; i++[||]) { Console.WriteLine(array[i]); } } }", @"using System; class C { void Test(string[] array) { foreach (string {|Rename:v|} in array) { Console.WriteLine(v); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestAtEndOfFor() { await TestInRegularAndScript1Async( @"using System; class C { void Test(string[] array) { for[||] (int i = 0; i < array.Length; i++) { Console.WriteLine(array[i]); } } }", @"using System; class C { void Test(string[] array) { foreach (string {|Rename:v|} in array) { Console.WriteLine(v); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestForSelected() { await TestInRegularAndScript1Async( @"using System; class C { void Test(string[] array) { [|for|] (int i = 0; i < array.Length; i++) { Console.WriteLine(array[i]); } } }", @"using System; class C { void Test(string[] array) { foreach (string {|Rename:v|} in array) { Console.WriteLine(v); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestBeforeOpenParen() { await TestInRegularAndScript1Async( @"using System; class C { void Test(string[] array) { for [||](int i = 0; i < array.Length; i++) { Console.WriteLine(array[i]); } } }", @"using System; class C { void Test(string[] array) { foreach (string {|Rename:v|} in array) { Console.WriteLine(v); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestAfterCloseParen() { await TestInRegularAndScript1Async( @"using System; class C { void Test(string[] array) { for (int i = 0; i < array.Length; i++)[||] { Console.WriteLine(array[i]); } } }", @"using System; class C { void Test(string[] array) { foreach (string {|Rename:v|} in array) { Console.WriteLine(v); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestMissingWithoutIncrementor() { await TestMissingInRegularAndScriptAsync( @"using System; class C { void Test(string[] array) { [||]for (int i = 0; i < array.Length; ) { Console.WriteLine(array[i]); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestMissingWithoutIncorrectIncrementor1() { await TestMissingInRegularAndScriptAsync( @"using System; class C { void Test(string[] array) { [||]for (int i = 0; i < array.Length; i += 2) { Console.WriteLine(array[i]); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestMissingWithoutIncorrectIncrementor2() { await TestMissingInRegularAndScriptAsync( @"using System; class C { void Test(string[] array) { [||]for (int i = 0; i < array.Length; j += 2) { Console.WriteLine(array[i]); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestMissingWithoutCondition() { await TestMissingInRegularAndScriptAsync( @"using System; class C { void Test(string[] array) { [||]for (int i = 0; ; i++) { Console.WriteLine(array[i]); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestMissingWithIncorrectCondition1() { await TestMissingInRegularAndScriptAsync( @"using System; class C { void Test(string[] array) { [||]for (int i = 0; j < array.Length; i++) { Console.WriteLine(array[i]); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestMissingWithIncorrectCondition2() { await TestMissingInRegularAndScriptAsync( @"using System; class C { void Test(string[] array) { [||]for (int i = 0; i < GetLength(array); i++) { Console.WriteLine(array[i]); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestWithoutInitializer() { await TestMissingInRegularAndScriptAsync( @"using System; class C { void Test(string[] array) { [||]for (; i < array.Length; i++) { Console.WriteLine(array[i]); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestWithInitializerOfVariableOutsideLoop() { await TestMissingInRegularAndScriptAsync( @"using System; class C { void Test(string[] array) { int i; [||]for (i = 0; i < array.Length; i++) { Console.WriteLine(array[i]); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestWithUninitializedVariable() { await TestMissingInRegularAndScriptAsync( @"using System; class C { void Test(string[] array) { [||]for (int i; i < array.Length; i++) { Console.WriteLine(array[i]); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestNotStartingAtZero() { await TestMissingInRegularAndScriptAsync( @"using System; class C { void Test(string[] array) { [||]for (int i = 1; i < array.Length; i++) { Console.WriteLine(array[i]); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestWithMultipleVariables() { await TestMissingInRegularAndScriptAsync( @"using System; class C { void Test(string[] array) { [||]for (int i = 0, j = 0; i < array.Length; i++) { Console.WriteLine(array[i]); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestList1() { await TestInRegularAndScript1Async( @"using System; using System.Collections.Generic; class C { void Test(IList<string> list) { [||]for (int i = 0; i < list.Count; i++) { Console.WriteLine(list[i]); } } }", @"using System; using System.Collections.Generic; class C { void Test(IList<string> list) { foreach (string {|Rename:v|} in list) { Console.WriteLine(v); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestChooseNameFromDeclarationStatement() { await TestInRegularAndScript1Async( @"using System; using System.Collections.Generic; class C { void Test(IList<string> list) { [||]for (int i = 0; i < list.Count; i++) { var val = list[i]; Console.WriteLine(list[i]); } } }", @"using System; using System.Collections.Generic; class C { void Test(IList<string> list) { foreach (var val in list) { Console.WriteLine(val); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestIgnoreFormattingForReferences() { await TestInRegularAndScript1Async( @"using System; using System.Collections.Generic; class C { void Test(IList<string> list) { [||]for (int i = 0; i < list.Count; i++) { var val = list [ i ]; Console.WriteLine(list [ /*find me*/ i ]); } } }", @"using System; using System.Collections.Generic; class C { void Test(IList<string> list) { foreach (var val in list) { Console.WriteLine(val); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestChooseNameFromDeclarationStatement_PreserveComments() { await TestInRegularAndScript1Async( @"using System; using System.Collections.Generic; class C { void Test(IList<string> list) { [||]for (int i = 0; i < list.Count; i++) { // loop comment var val = list[i]; Console.WriteLine(list[i]); } } }", @"using System; using System.Collections.Generic; class C { void Test(IList<string> list) { foreach (var val in list) { // loop comment Console.WriteLine(val); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestChooseNameFromDeclarationStatement_PreserveDirectives() { await TestInRegularAndScript1Async( @"using System; using System.Collections.Generic; class C { void Test(IList<string> list) { [||]for (int i = 0; i < list.Count; i++) { #if true var val = list[i]; Console.WriteLine(list[i]); #endif } } }", @"using System; using System.Collections.Generic; class C { void Test(IList<string> list) { foreach (var val in list) { #if true Console.WriteLine(val); #endif } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestMissingIfVariableUsedNotForIndexing() { await TestMissingInRegularAndScriptAsync( @"using System; class C { void Test(string[] array) { [||]for (int i = 0; i < array.Length; i++) { Console.WriteLine(i); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestMissingIfVariableUsedForIndexingNonCollection() { await TestMissingInRegularAndScriptAsync( @"using System; class C { void Test(string[] array) { [||]for (int i = 0; i < array.Length; i++) { Console.WriteLine(other[i]); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestWarningIfCollectionWrittenTo() { await TestInRegularAndScript1Async( @"using System; class C { void Test(string[] array) { [||]for (int i = 0; i < array.Length; i++) { array[i] = 1; } } }", @"using System; class C { void Test(string[] array) { foreach (string {|Rename:v|} in array) { {|Warning:v|} = 1; } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task UseVarIfPreferred1() { await TestInRegularAndScriptAsync( @"using System; class C { void Test(string[] array) { [||]for (int i = 0; i < array.Length; i++) { Console.WriteLine(array[i]); } } }", @"using System; class C { void Test(string[] array) { foreach (var {|Rename:v|} in array) { Console.WriteLine(v); } } }", options: ImplicitTypeEverywhere()); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestDifferentIndexerAndEnumeratorType() { await TestInRegularAndScriptAsync( @"using System; class MyList { public string this[int i] { get; } public Enumerator GetEnumerator() { } public struct Enumerator { public object Current { get; } } } class C { void Test(MyList list) { // need to use 'string' here to preserve original index semantics. [||]for (int i = 0; i < list.Length; i++) { Console.WriteLine(list[i]); } } }", @"using System; class MyList { public string this[int i] { get; } public Enumerator GetEnumerator() { } public struct Enumerator { public object Current { get; } } } class C { void Test(MyList list) { // need to use 'string' here to preserve original index semantics. foreach (string {|Rename:v|} in list) { Console.WriteLine(v); } } }", options: ImplicitTypeEverywhere()); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestSameIndexerAndEnumeratorType() { await TestInRegularAndScriptAsync( @"using System; class MyList { public object this[int i] { get => default; } public Enumerator GetEnumerator() { return default; } public struct Enumerator { public object Current { get; } public bool MoveNext() => true; } } class C { void Test(MyList list) { // can use 'var' here since hte type stayed the same. [||]for (int i = 0; i < list.Length; i++) { Console.WriteLine(list[i]); } } }", @"using System; class MyList { public object this[int i] { get => default; } public Enumerator GetEnumerator() { return default; } public struct Enumerator { public object Current { get; } public bool MoveNext() => true; } } class C { void Test(MyList list) { // can use 'var' here since hte type stayed the same. foreach (var {|Rename:v|} in list) { Console.WriteLine(v); } } }", options: ImplicitTypeEverywhere()); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestTrivia() { await TestInRegularAndScript1Async( @"using System; class C { void Test(string[] array) { // trivia 1 [||]for /*trivia 2*/ ( /*trivia 3*/ int i = 0; i < array.Length; i++) /*trivia 4*/ // trivia 5 { Console.WriteLine(array[i]); } // trivia 6 } }", @"using System; class C { void Test(string[] array) { // trivia 1 foreach /*trivia 2*/ ( /*trivia 3*/ string {|Rename:v|} in array) /*trivia 4*/ // trivia 5 { Console.WriteLine(v); } // trivia 6 } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestNotWithDeconstruction() { await TestMissingInRegularAndScriptAsync( @"using System; class C { void Test(string[] array) { [||]for (var (i, j) = (0, 0); i < array.Length; i++) { Console.WriteLine(array[i]); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestMultidimensionalArray1() { await TestMissingInRegularAndScriptAsync( @"using System; class C { void Test(string[,] array) { [||]for (int i = 0; i < array.Length; i++) { Console.WriteLine(array[i, 0]); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestMultidimensionalArray2() { await TestMissingInRegularAndScriptAsync( @"using System; class C { void Test(string[,] array) { [||]for (int i = 0; i < array.Length; i++) { Console.WriteLine(array[i, i]); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestJaggedArray1() { await TestInRegularAndScript1Async( @"using System; class C { void Test(string[][] array) { [||]for (int i = 0; i < array.Length; i++) { Console.WriteLine(array[i]); } } }", @"using System; class C { void Test(string[][] array) { foreach (string[] {|Rename:v|} in array) { Console.WriteLine(v); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestJaggedArray2() { await TestInRegularAndScript1Async( @"using System; class C { void Test(string[][] array) { [||]for (int i = 0; i < array.Length; i++) { Console.WriteLine(array[i][0]); } } }", @"using System; class C { void Test(string[][] array) { foreach (string[] {|Rename:v|} in array) { Console.WriteLine(v[0]); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestJaggedArray3() { await TestInRegularAndScript1Async( @"using System; class C { void Test(string[][] array) { [||]for (int i = 0; i < array.Length; i++) { var subArray = array[i]; for (int j = 0; j < subArray.Length; j++) { Console.WriteLine(array[i][j]); } } } }", @"using System; class C { void Test(string[][] array) { foreach (var subArray in array) { for (int j = 0; j < subArray.Length; j++) { Console.WriteLine(subArray[j]); } } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestJaggedArray4() { await TestInRegularAndScript1Async( @"using System; class C { void Test(string[][] array) { [||]for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array[i].Length; j++) { Console.WriteLine(array[i][j]); } } } }", @"using System; class C { void Test(string[][] array) { foreach (string[] {|Rename:v|} in array) { for (int j = 0; j < v.Length; j++) { Console.WriteLine(v[j]); } } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestJaggedArray5() { await TestInRegularAndScript1Async( @"using System; class C { void Test(string[][] array) { for (int i = 0; i < array.Length; i++) { [||]for (int j = 0; j < array[i].Length; j++) { Console.WriteLine(array[i][j]); } } } }", @"using System; class C { void Test(string[][] array) { for (int i = 0; i < array.Length; i++) { foreach (string {|Rename:v|} in array[i]) { Console.WriteLine(v); } } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestJaggedArray6() { await TestMissingInRegularAndScriptAsync( @"using System; class C { void Test(string[][] array) { [||]for (int i = 0; i < array.Length; i++) { Console.WriteLine(array[i][i]); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestDoesNotUseLocalFunctionName() { await TestInRegularAndScript1Async( @"using System; class C { void Test(string[] array) { [||]for (int i = 0; i < array.Length; i++) { Console.WriteLine(array[i]); } void v() { } } }", @"using System; class C { void Test(string[] array) { foreach (string {|Rename:v1|} in array) { Console.WriteLine(v1); } void v() { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestUsesLocalFunctionParameterName() { await TestInRegularAndScript1Async( @"using System; class C { void Test(string[] array) { [||]for (int i = 0; i < array.Length; i++) { Console.WriteLine(array[i]); } void M(string v) { } } }", @"using System; class C { void Test(string[] array) { foreach (string {|Rename:v|} in array) { Console.WriteLine(v); } void M(string v) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestDoesNotUseLambdaParameterWithCSharpLessThan8() { await TestInRegularAndScript1Async( @"using System; class C { void Test(string[] array) { [||]for (int i = 0; i < array.Length; i++) { Console.WriteLine(array[i]); } Action<int> myLambda = v => { }; } }", @"using System; class C { void Test(string[] array) { foreach (string {|Rename:v1|} in array) { Console.WriteLine(v1); } Action<int> myLambda = v => { }; } }", parameters: new TestParameters(new CSharpParseOptions(LanguageVersion.CSharp7_3))); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestUsesLambdaParameterNameInCSharp8() { await TestInRegularAndScript1Async( @"using System; class C { void Test(string[] array) { [||]for (int i = 0; i < array.Length; i++) { Console.WriteLine(array[i]); } Action<int> myLambda = v => { }; } }", @"using System; class C { void Test(string[] array) { foreach (string {|Rename:v|} in array) { Console.WriteLine(v); } Action<int> myLambda = v => { }; } }", parameters: new TestParameters(new CSharpParseOptions(LanguageVersion.CSharp8))); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestNotWhenIteratingDifferentLists() { await TestMissingAsync( @"using System; using System.Collection.Generic; class Item { public string Value; } class C { static void Test() { var first = new { list = new List<Item>() }; var second = new { list = new List<Item>() }; [||]for (var i = 0; i < first.list.Count; i++) { first.list[i].Value = second.list[i].Value; } } }"); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.CSharp.ConvertForToForEach; using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeRefactorings; using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.ConvertForToForEach { public class ConvertForToForEachTests : AbstractCSharpCodeActionTest { protected override CodeRefactoringProvider CreateCodeRefactoringProvider(Workspace workspace, TestParameters parameters) => new CSharpConvertForToForEachCodeRefactoringProvider(); private readonly CodeStyleOption2<bool> onWithSilent = new CodeStyleOption2<bool>(true, NotificationOption2.Silent); private OptionsCollection ImplicitTypeEverywhere() => new OptionsCollection(GetLanguage()) { { CSharpCodeStyleOptions.VarElsewhere, onWithSilent }, { CSharpCodeStyleOptions.VarWhenTypeIsApparent, onWithSilent }, { CSharpCodeStyleOptions.VarForBuiltInTypes, onWithSilent }, }; [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestArray1() { await TestInRegularAndScript1Async( @"using System; class C { void Test(string[] array) { [||]for (int i = 0; i < array.Length; i++) { Console.WriteLine(array[i]); } } }", @"using System; class C { void Test(string[] array) { foreach (string {|Rename:v|} in array) { Console.WriteLine(v); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestWarnIfCrossesFunctionBoundary() { await TestInRegularAndScript1Async( @"using System; class C { void Test(string[] array) { [||]for (int i = 0; i < array.Length; i++) { Action a = () => { Console.WriteLine(array[i]); }; } } }", @"using System; class C { void Test(string[] array) { foreach (string {|Rename:v|} in array) { Action a = () => { Console.WriteLine({|Warning:v|}); }; } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestWarnIfCollectionPotentiallyMutated1() { await TestInRegularAndScript1Async( @"using System; using System.Collections.Generic; class C { void Test(IList<string> list) { [||]for (int i = 0; i < list.Count; i++) { Console.WriteLine(list[i]); list.Add(null); } } }", @"using System; using System.Collections.Generic; class C { void Test(IList<string> list) { foreach (string {|Rename:v|} in list) { Console.WriteLine(v); {|Warning:list|}.Add(null); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestWarnIfCollectionPotentiallyMutated2() { await TestInRegularAndScript1Async( @"using System; using System.Collections.Generic; class C { void Test(IList<string> list) { [||]for (int i = 0; i < list.Count; i++) { Console.WriteLine(list[i]); list = null; } } }", @"using System; using System.Collections.Generic; class C { void Test(IList<string> list) { foreach (string {|Rename:v|} in list) { Console.WriteLine(v); {|Warning:list|} = null; } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestNoWarnIfCollectionPropertyAccess() { await TestInRegularAndScript1Async( @"using System; using System.Collections.Generic; class C { void Test(IList<string> list) { [||]for (int i = 0; i < list.Count; i++) { Console.WriteLine(list[i]); Console.WriteLine(list.Count); } } }", @"using System; using System.Collections.Generic; class C { void Test(IList<string> list) { foreach (string {|Rename:v|} in list) { Console.WriteLine(v); Console.WriteLine(list.Count); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestNoWarnIfDoesNotCrossFunctionBoundary() { await TestInRegularAndScript1Async( @"using System; class C { void Test(string[] array) { Action a = () => { [||]for (int i = 0; i < array.Length; i++) { Console.WriteLine(array[i]); } }; } }", @"using System; class C { void Test(string[] array) { Action a = () => { foreach (string {|Rename:v|} in array) { Console.WriteLine(v); } }; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestMultipleReferences() { await TestInRegularAndScript1Async( @"using System; class C { void Test(string[] array) { [||]for (int i = 0; i < array.Length; i++) { Console.WriteLine(array[i]); Console.WriteLine(array[i]); } } }", @"using System; class C { void Test(string[] array) { foreach (string {|Rename:v|} in array) { Console.WriteLine(v); Console.WriteLine(v); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestEmbeddedStatement() { await TestInRegularAndScript1Async( @"using System; class C { void Test(string[] array) { [||]for (int i = 0; i < array.Length; i++) Console.WriteLine(array[i]); } }", @"using System; class C { void Test(string[] array) { foreach (string {|Rename:v|} in array) Console.WriteLine(v); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestPostIncrement() { await TestInRegularAndScript1Async( @"using System; class C { void Test(string[] array) { [||]for (int i = 0; i < array.Length; ++i) { Console.WriteLine(array[i]); } } }", @"using System; class C { void Test(string[] array) { foreach (string {|Rename:v|} in array) { Console.WriteLine(v); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestArrayPlusEqualsIncrementor() { await TestInRegularAndScript1Async( @"using System; class C { void Test(string[] array) { [||]for (int i = 0; i < array.Length; i += 1) { Console.WriteLine(array[i]); } } }", @"using System; class C { void Test(string[] array) { foreach (string {|Rename:v|} in array) { Console.WriteLine(v); } } }"); } [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestBeforeKeyword() { await TestInRegularAndScript1Async( @"using System; class C { void Test(string[] array) { [||] for (int i = 0; i < array.Length; i++) { Console.WriteLine(array[i]); } } }", @"using System; class C { void Test(string[] array) { foreach (string {|Rename:v|} in array) { Console.WriteLine(v); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestMissingAfterOpenParen() { await TestMissingInRegularAndScriptAsync( @"using System; class C { void Test(string[] array) { for ( [||]int i = 0; i < array.Length; i++) { Console.WriteLine(array[i]); } } }"); } [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestInParentheses() { await TestInRegularAndScript1Async( @"using System; class C { void Test(string[] array) { for ([||]int i = 0; i < array.Length; i++) { Console.WriteLine(array[i]); } } }", @"using System; class C { void Test(string[] array) { foreach (string {|Rename:v|} in array) { Console.WriteLine(v); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestMissingBeforeCloseParen() { await TestMissingInRegularAndScriptAsync( @"using System; class C { void Test(string[] array) { for (int i = 0; i < array.Length; i++[||] ) { Console.WriteLine(array[i]); } } }"); } [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestInParentheses2() { await TestInRegularAndScript1Async( @"using System; class C { void Test(string[] array) { for (int i = 0; i < array.Length; i++[||]) { Console.WriteLine(array[i]); } } }", @"using System; class C { void Test(string[] array) { foreach (string {|Rename:v|} in array) { Console.WriteLine(v); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestAtEndOfFor() { await TestInRegularAndScript1Async( @"using System; class C { void Test(string[] array) { for[||] (int i = 0; i < array.Length; i++) { Console.WriteLine(array[i]); } } }", @"using System; class C { void Test(string[] array) { foreach (string {|Rename:v|} in array) { Console.WriteLine(v); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestForSelected() { await TestInRegularAndScript1Async( @"using System; class C { void Test(string[] array) { [|for|] (int i = 0; i < array.Length; i++) { Console.WriteLine(array[i]); } } }", @"using System; class C { void Test(string[] array) { foreach (string {|Rename:v|} in array) { Console.WriteLine(v); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestBeforeOpenParen() { await TestInRegularAndScript1Async( @"using System; class C { void Test(string[] array) { for [||](int i = 0; i < array.Length; i++) { Console.WriteLine(array[i]); } } }", @"using System; class C { void Test(string[] array) { foreach (string {|Rename:v|} in array) { Console.WriteLine(v); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestAfterCloseParen() { await TestInRegularAndScript1Async( @"using System; class C { void Test(string[] array) { for (int i = 0; i < array.Length; i++)[||] { Console.WriteLine(array[i]); } } }", @"using System; class C { void Test(string[] array) { foreach (string {|Rename:v|} in array) { Console.WriteLine(v); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestMissingWithoutIncrementor() { await TestMissingInRegularAndScriptAsync( @"using System; class C { void Test(string[] array) { [||]for (int i = 0; i < array.Length; ) { Console.WriteLine(array[i]); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestMissingWithoutIncorrectIncrementor1() { await TestMissingInRegularAndScriptAsync( @"using System; class C { void Test(string[] array) { [||]for (int i = 0; i < array.Length; i += 2) { Console.WriteLine(array[i]); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestMissingWithoutIncorrectIncrementor2() { await TestMissingInRegularAndScriptAsync( @"using System; class C { void Test(string[] array) { [||]for (int i = 0; i < array.Length; j += 2) { Console.WriteLine(array[i]); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestMissingWithoutCondition() { await TestMissingInRegularAndScriptAsync( @"using System; class C { void Test(string[] array) { [||]for (int i = 0; ; i++) { Console.WriteLine(array[i]); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestMissingWithIncorrectCondition1() { await TestMissingInRegularAndScriptAsync( @"using System; class C { void Test(string[] array) { [||]for (int i = 0; j < array.Length; i++) { Console.WriteLine(array[i]); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestMissingWithIncorrectCondition2() { await TestMissingInRegularAndScriptAsync( @"using System; class C { void Test(string[] array) { [||]for (int i = 0; i < GetLength(array); i++) { Console.WriteLine(array[i]); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestWithoutInitializer() { await TestMissingInRegularAndScriptAsync( @"using System; class C { void Test(string[] array) { [||]for (; i < array.Length; i++) { Console.WriteLine(array[i]); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestWithInitializerOfVariableOutsideLoop() { await TestMissingInRegularAndScriptAsync( @"using System; class C { void Test(string[] array) { int i; [||]for (i = 0; i < array.Length; i++) { Console.WriteLine(array[i]); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestWithUninitializedVariable() { await TestMissingInRegularAndScriptAsync( @"using System; class C { void Test(string[] array) { [||]for (int i; i < array.Length; i++) { Console.WriteLine(array[i]); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestNotStartingAtZero() { await TestMissingInRegularAndScriptAsync( @"using System; class C { void Test(string[] array) { [||]for (int i = 1; i < array.Length; i++) { Console.WriteLine(array[i]); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestWithMultipleVariables() { await TestMissingInRegularAndScriptAsync( @"using System; class C { void Test(string[] array) { [||]for (int i = 0, j = 0; i < array.Length; i++) { Console.WriteLine(array[i]); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestList1() { await TestInRegularAndScript1Async( @"using System; using System.Collections.Generic; class C { void Test(IList<string> list) { [||]for (int i = 0; i < list.Count; i++) { Console.WriteLine(list[i]); } } }", @"using System; using System.Collections.Generic; class C { void Test(IList<string> list) { foreach (string {|Rename:v|} in list) { Console.WriteLine(v); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestChooseNameFromDeclarationStatement() { await TestInRegularAndScript1Async( @"using System; using System.Collections.Generic; class C { void Test(IList<string> list) { [||]for (int i = 0; i < list.Count; i++) { var val = list[i]; Console.WriteLine(list[i]); } } }", @"using System; using System.Collections.Generic; class C { void Test(IList<string> list) { foreach (var val in list) { Console.WriteLine(val); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestIgnoreFormattingForReferences() { await TestInRegularAndScript1Async( @"using System; using System.Collections.Generic; class C { void Test(IList<string> list) { [||]for (int i = 0; i < list.Count; i++) { var val = list [ i ]; Console.WriteLine(list [ /*find me*/ i ]); } } }", @"using System; using System.Collections.Generic; class C { void Test(IList<string> list) { foreach (var val in list) { Console.WriteLine(val); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestChooseNameFromDeclarationStatement_PreserveComments() { await TestInRegularAndScript1Async( @"using System; using System.Collections.Generic; class C { void Test(IList<string> list) { [||]for (int i = 0; i < list.Count; i++) { // loop comment var val = list[i]; Console.WriteLine(list[i]); } } }", @"using System; using System.Collections.Generic; class C { void Test(IList<string> list) { foreach (var val in list) { // loop comment Console.WriteLine(val); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestChooseNameFromDeclarationStatement_PreserveDirectives() { await TestInRegularAndScript1Async( @"using System; using System.Collections.Generic; class C { void Test(IList<string> list) { [||]for (int i = 0; i < list.Count; i++) { #if true var val = list[i]; Console.WriteLine(list[i]); #endif } } }", @"using System; using System.Collections.Generic; class C { void Test(IList<string> list) { foreach (var val in list) { #if true Console.WriteLine(val); #endif } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestMissingIfVariableUsedNotForIndexing() { await TestMissingInRegularAndScriptAsync( @"using System; class C { void Test(string[] array) { [||]for (int i = 0; i < array.Length; i++) { Console.WriteLine(i); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestMissingIfVariableUsedForIndexingNonCollection() { await TestMissingInRegularAndScriptAsync( @"using System; class C { void Test(string[] array) { [||]for (int i = 0; i < array.Length; i++) { Console.WriteLine(other[i]); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestWarningIfCollectionWrittenTo() { await TestInRegularAndScript1Async( @"using System; class C { void Test(string[] array) { [||]for (int i = 0; i < array.Length; i++) { array[i] = 1; } } }", @"using System; class C { void Test(string[] array) { foreach (string {|Rename:v|} in array) { {|Warning:v|} = 1; } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task UseVarIfPreferred1() { await TestInRegularAndScriptAsync( @"using System; class C { void Test(string[] array) { [||]for (int i = 0; i < array.Length; i++) { Console.WriteLine(array[i]); } } }", @"using System; class C { void Test(string[] array) { foreach (var {|Rename:v|} in array) { Console.WriteLine(v); } } }", options: ImplicitTypeEverywhere()); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestDifferentIndexerAndEnumeratorType() { await TestInRegularAndScriptAsync( @"using System; class MyList { public string this[int i] { get; } public Enumerator GetEnumerator() { } public struct Enumerator { public object Current { get; } } } class C { void Test(MyList list) { // need to use 'string' here to preserve original index semantics. [||]for (int i = 0; i < list.Length; i++) { Console.WriteLine(list[i]); } } }", @"using System; class MyList { public string this[int i] { get; } public Enumerator GetEnumerator() { } public struct Enumerator { public object Current { get; } } } class C { void Test(MyList list) { // need to use 'string' here to preserve original index semantics. foreach (string {|Rename:v|} in list) { Console.WriteLine(v); } } }", options: ImplicitTypeEverywhere()); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestSameIndexerAndEnumeratorType() { await TestInRegularAndScriptAsync( @"using System; class MyList { public object this[int i] { get => default; } public Enumerator GetEnumerator() { return default; } public struct Enumerator { public object Current { get; } public bool MoveNext() => true; } } class C { void Test(MyList list) { // can use 'var' here since hte type stayed the same. [||]for (int i = 0; i < list.Length; i++) { Console.WriteLine(list[i]); } } }", @"using System; class MyList { public object this[int i] { get => default; } public Enumerator GetEnumerator() { return default; } public struct Enumerator { public object Current { get; } public bool MoveNext() => true; } } class C { void Test(MyList list) { // can use 'var' here since hte type stayed the same. foreach (var {|Rename:v|} in list) { Console.WriteLine(v); } } }", options: ImplicitTypeEverywhere()); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestTrivia() { await TestInRegularAndScript1Async( @"using System; class C { void Test(string[] array) { // trivia 1 [||]for /*trivia 2*/ ( /*trivia 3*/ int i = 0; i < array.Length; i++) /*trivia 4*/ // trivia 5 { Console.WriteLine(array[i]); } // trivia 6 } }", @"using System; class C { void Test(string[] array) { // trivia 1 foreach /*trivia 2*/ ( /*trivia 3*/ string {|Rename:v|} in array) /*trivia 4*/ // trivia 5 { Console.WriteLine(v); } // trivia 6 } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestNotWithDeconstruction() { await TestMissingInRegularAndScriptAsync( @"using System; class C { void Test(string[] array) { [||]for (var (i, j) = (0, 0); i < array.Length; i++) { Console.WriteLine(array[i]); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestMultidimensionalArray1() { await TestMissingInRegularAndScriptAsync( @"using System; class C { void Test(string[,] array) { [||]for (int i = 0; i < array.Length; i++) { Console.WriteLine(array[i, 0]); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestMultidimensionalArray2() { await TestMissingInRegularAndScriptAsync( @"using System; class C { void Test(string[,] array) { [||]for (int i = 0; i < array.Length; i++) { Console.WriteLine(array[i, i]); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestJaggedArray1() { await TestInRegularAndScript1Async( @"using System; class C { void Test(string[][] array) { [||]for (int i = 0; i < array.Length; i++) { Console.WriteLine(array[i]); } } }", @"using System; class C { void Test(string[][] array) { foreach (string[] {|Rename:v|} in array) { Console.WriteLine(v); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestJaggedArray2() { await TestInRegularAndScript1Async( @"using System; class C { void Test(string[][] array) { [||]for (int i = 0; i < array.Length; i++) { Console.WriteLine(array[i][0]); } } }", @"using System; class C { void Test(string[][] array) { foreach (string[] {|Rename:v|} in array) { Console.WriteLine(v[0]); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestJaggedArray3() { await TestInRegularAndScript1Async( @"using System; class C { void Test(string[][] array) { [||]for (int i = 0; i < array.Length; i++) { var subArray = array[i]; for (int j = 0; j < subArray.Length; j++) { Console.WriteLine(array[i][j]); } } } }", @"using System; class C { void Test(string[][] array) { foreach (var subArray in array) { for (int j = 0; j < subArray.Length; j++) { Console.WriteLine(subArray[j]); } } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestJaggedArray4() { await TestInRegularAndScript1Async( @"using System; class C { void Test(string[][] array) { [||]for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array[i].Length; j++) { Console.WriteLine(array[i][j]); } } } }", @"using System; class C { void Test(string[][] array) { foreach (string[] {|Rename:v|} in array) { for (int j = 0; j < v.Length; j++) { Console.WriteLine(v[j]); } } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestJaggedArray5() { await TestInRegularAndScript1Async( @"using System; class C { void Test(string[][] array) { for (int i = 0; i < array.Length; i++) { [||]for (int j = 0; j < array[i].Length; j++) { Console.WriteLine(array[i][j]); } } } }", @"using System; class C { void Test(string[][] array) { for (int i = 0; i < array.Length; i++) { foreach (string {|Rename:v|} in array[i]) { Console.WriteLine(v); } } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestJaggedArray6() { await TestMissingInRegularAndScriptAsync( @"using System; class C { void Test(string[][] array) { [||]for (int i = 0; i < array.Length; i++) { Console.WriteLine(array[i][i]); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestDoesNotUseLocalFunctionName() { await TestInRegularAndScript1Async( @"using System; class C { void Test(string[] array) { [||]for (int i = 0; i < array.Length; i++) { Console.WriteLine(array[i]); } void v() { } } }", @"using System; class C { void Test(string[] array) { foreach (string {|Rename:v1|} in array) { Console.WriteLine(v1); } void v() { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestUsesLocalFunctionParameterName() { await TestInRegularAndScript1Async( @"using System; class C { void Test(string[] array) { [||]for (int i = 0; i < array.Length; i++) { Console.WriteLine(array[i]); } void M(string v) { } } }", @"using System; class C { void Test(string[] array) { foreach (string {|Rename:v|} in array) { Console.WriteLine(v); } void M(string v) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestDoesNotUseLambdaParameterWithCSharpLessThan8() { await TestInRegularAndScript1Async( @"using System; class C { void Test(string[] array) { [||]for (int i = 0; i < array.Length; i++) { Console.WriteLine(array[i]); } Action<int> myLambda = v => { }; } }", @"using System; class C { void Test(string[] array) { foreach (string {|Rename:v1|} in array) { Console.WriteLine(v1); } Action<int> myLambda = v => { }; } }", parameters: new TestParameters(new CSharpParseOptions(LanguageVersion.CSharp7_3))); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestUsesLambdaParameterNameInCSharp8() { await TestInRegularAndScript1Async( @"using System; class C { void Test(string[] array) { [||]for (int i = 0; i < array.Length; i++) { Console.WriteLine(array[i]); } Action<int> myLambda = v => { }; } }", @"using System; class C { void Test(string[] array) { foreach (string {|Rename:v|} in array) { Console.WriteLine(v); } Action<int> myLambda = v => { }; } }", parameters: new TestParameters(new CSharpParseOptions(LanguageVersion.CSharp8))); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestNotWhenIteratingDifferentLists() { await TestMissingAsync( @"using System; using System.Collection.Generic; class Item { public string Value; } class C { static void Test() { var first = new { list = new List<Item>() }; var second = new { list = new List<Item>() }; [||]for (var i = 0; i < first.list.Count; i++) { first.list[i].Value = second.list[i].Value; } } }"); } } }
-1
dotnet/roslyn
55,256
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-30T00:02:02Z
2021-07-30T09:17:54Z
6ce9c0048d37026337701fac035ac0745f6fe49f
88b59775dc6375635957ef229116460f290072aa
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Collections/TemporaryArray`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.Immutable; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Threading; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Shared.Collections { /// <summary> /// Provides temporary storage for a collection of elements. This type is optimized for handling of small /// collections, particularly for cases where the collection will eventually be discarded or used to produce an /// <see cref="ImmutableArray{T}"/>. /// </summary> /// <remarks> /// This type stores small collections on the stack, with the ability to transition to dynamic storage if/when /// larger number of elements are added. /// </remarks> /// <typeparam name="T">The type of elements stored in the collection.</typeparam> [NonCopyable] [StructLayout(LayoutKind.Sequential)] internal struct TemporaryArray<T> : IDisposable { /// <summary> /// The number of elements the temporary can store inline. Storing more than this many elements requires the /// array transition to dynamic storage. /// </summary> private const int InlineCapacity = 4; /// <summary> /// The first inline element. /// </summary> /// <remarks> /// This field is only used when <see cref="_builder"/> is <see langword="null"/>. In other words, this type /// stores elements inline <em>or</em> stores them in <see cref="_builder"/>, but does not use both approaches /// at the same time. /// </remarks> private T _item0; /// <summary> /// The second inline element. /// </summary> /// <seealso cref="_item0"/> private T _item1; /// <summary> /// The third inline element. /// </summary> /// <seealso cref="_item0"/> private T _item2; /// <summary> /// The fourth inline element. /// </summary> /// <seealso cref="_item0"/> private T _item3; /// <summary> /// The number of inline elements held in the array. This value is only used when <see cref="_builder"/> is /// <see langword="null"/>. /// </summary> private int _count; /// <summary> /// A builder used for dynamic storage of collections that may exceed the limit for inline elements. /// </summary> /// <remarks> /// This field is initialized to non-<see langword="null"/> the first time the <see cref="TemporaryArray{T}"/> /// needs to store more than four elements. From that point, <see cref="_builder"/> is used instead of inline /// elements, even if items are removed to make the result smaller than four elements. /// </remarks> private ArrayBuilder<T>? _builder; private TemporaryArray(in TemporaryArray<T> array) { // Intentional copy used for creating an enumerator #pragma warning disable RS0042 // Do not copy value this = array; #pragma warning restore RS0042 // Do not copy value } public static TemporaryArray<T> Empty => default; public readonly int Count => _builder?.Count ?? _count; public T this[int index] { [MethodImpl(MethodImplOptions.AggressiveInlining)] readonly get { if (_builder is not null) return _builder[index]; if ((uint)index >= _count) ThrowIndexOutOfRangeException(); return index switch { 0 => _item0, 1 => _item1, 2 => _item2, _ => _item3, }; } [MethodImpl(MethodImplOptions.AggressiveInlining)] set { if (_builder is not null) { _builder[index] = value; return; } if ((uint)index >= _count) ThrowIndexOutOfRangeException(); _ = index switch { 0 => _item0 = value, 1 => _item1 = value, 2 => _item2 = value, _ => _item3 = value, }; } } public void Dispose() { // Return _builder to the pool if necessary. There is no need to release inline storage since the majority // case for this type is stack-allocated storage and the GC is already able to reclaim objects from the // stack after the last use of a reference to them. Interlocked.Exchange(ref _builder, null)?.Free(); } public void Add(T item) { if (_builder is not null) { _builder.Add(item); } else if (_count < InlineCapacity) { // Increase _count before assigning a value since the indexer has a bounds check. _count++; this[_count - 1] = item; } else { Debug.Assert(_count == InlineCapacity); MoveInlineToBuilder(); _builder.Add(item); } } public void AddRange(ImmutableArray<T> items) { if (_builder is not null) { _builder.AddRange(items); } else if (_count + items.Length <= InlineCapacity) { foreach (var item in items) { // Increase _count before assigning values since the indexer has a bounds check. _count++; this[_count - 1] = item; } } else { MoveInlineToBuilder(); _builder.AddRange(items); } } public void AddRange(in TemporaryArray<T> items) { if (_count + items.Count <= InlineCapacity) { foreach (var item in items) { // Increase _count before assigning values since the indexer has a bounds check. _count++; this[_count - 1] = item; } } else { MoveInlineToBuilder(); foreach (var item in items) _builder.Add(item); } } public void Clear() { if (_builder is not null) { // Keep using a builder even if we now fit in inline storage to avoid churn in the object pools. _builder.Clear(); } else { this = Empty; } } public readonly Enumerator GetEnumerator() { return new Enumerator(in this); } /// <summary> /// Create an <see cref="ImmutableArray{T}"/> with the elements currently held in the temporary array, and clear /// the array. /// </summary> /// <returns></returns> public ImmutableArray<T> ToImmutableAndClear() { if (_builder is not null) { return _builder.ToImmutableAndClear(); } else { var result = _count switch { 0 => ImmutableArray<T>.Empty, 1 => ImmutableArray.Create(_item0), 2 => ImmutableArray.Create(_item0, _item1), 3 => ImmutableArray.Create(_item0, _item1, _item2), 4 => ImmutableArray.Create(_item0, _item1, _item2, _item3), _ => throw ExceptionUtilities.Unreachable, }; // Since _builder is null on this path, we can overwrite the whole structure to Empty to reset all // inline elements to their default value and the _count to 0. this = Empty; return result; } } /// <summary> /// Transitions the current <see cref="TemporaryArray{T}"/> from inline storage to dynamic storage storage. An /// <see cref="ArrayBuilder{T}"/> instance is taken from the shared pool, and all elements currently in inline /// storage are added to it. After this point, dynamic storage will be used instead of inline storage. /// </summary> [MemberNotNull(nameof(_builder))] private void MoveInlineToBuilder() { Debug.Assert(_builder is null); var builder = ArrayBuilder<T>.GetInstance(); for (var i = 0; i < _count; i++) { builder.Add(this[i]); #if NETCOREAPP if (RuntimeHelpers.IsReferenceOrContainsReferences<T>()) #endif { this[i] = default!; } } _count = 0; _builder = builder; } /// <summary> /// Throws <see cref="IndexOutOfRangeException"/>. /// </summary> /// <remarks> /// This helper improves the ability of the JIT to inline callers. /// </remarks> private static void ThrowIndexOutOfRangeException() => throw new IndexOutOfRangeException(); public struct Enumerator { private readonly TemporaryArray<T> _array; private T _current; private int _nextIndex; public Enumerator(in TemporaryArray<T> array) { // Enumerate a copy of the original _array = new TemporaryArray<T>(in array); _current = default!; _nextIndex = 0; } public T Current => _current; public bool MoveNext() { if (_nextIndex >= _array.Count) { return false; } else { _current = _array[_nextIndex]; _nextIndex++; return true; } } } internal static class TestAccessor { public static int InlineCapacity => TemporaryArray<T>.InlineCapacity; public static bool HasDynamicStorage(in TemporaryArray<T> array) => array._builder is not null; public static int InlineCount(in TemporaryArray<T> array) => array._count; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Threading; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Shared.Collections { /// <summary> /// Provides temporary storage for a collection of elements. This type is optimized for handling of small /// collections, particularly for cases where the collection will eventually be discarded or used to produce an /// <see cref="ImmutableArray{T}"/>. /// </summary> /// <remarks> /// This type stores small collections on the stack, with the ability to transition to dynamic storage if/when /// larger number of elements are added. /// </remarks> /// <typeparam name="T">The type of elements stored in the collection.</typeparam> [NonCopyable] [StructLayout(LayoutKind.Sequential)] internal struct TemporaryArray<T> : IDisposable { /// <summary> /// The number of elements the temporary can store inline. Storing more than this many elements requires the /// array transition to dynamic storage. /// </summary> private const int InlineCapacity = 4; /// <summary> /// The first inline element. /// </summary> /// <remarks> /// This field is only used when <see cref="_builder"/> is <see langword="null"/>. In other words, this type /// stores elements inline <em>or</em> stores them in <see cref="_builder"/>, but does not use both approaches /// at the same time. /// </remarks> private T _item0; /// <summary> /// The second inline element. /// </summary> /// <seealso cref="_item0"/> private T _item1; /// <summary> /// The third inline element. /// </summary> /// <seealso cref="_item0"/> private T _item2; /// <summary> /// The fourth inline element. /// </summary> /// <seealso cref="_item0"/> private T _item3; /// <summary> /// The number of inline elements held in the array. This value is only used when <see cref="_builder"/> is /// <see langword="null"/>. /// </summary> private int _count; /// <summary> /// A builder used for dynamic storage of collections that may exceed the limit for inline elements. /// </summary> /// <remarks> /// This field is initialized to non-<see langword="null"/> the first time the <see cref="TemporaryArray{T}"/> /// needs to store more than four elements. From that point, <see cref="_builder"/> is used instead of inline /// elements, even if items are removed to make the result smaller than four elements. /// </remarks> private ArrayBuilder<T>? _builder; private TemporaryArray(in TemporaryArray<T> array) { // Intentional copy used for creating an enumerator #pragma warning disable RS0042 // Do not copy value this = array; #pragma warning restore RS0042 // Do not copy value } public static TemporaryArray<T> Empty => default; public readonly int Count => _builder?.Count ?? _count; public T this[int index] { [MethodImpl(MethodImplOptions.AggressiveInlining)] readonly get { if (_builder is not null) return _builder[index]; if ((uint)index >= _count) ThrowIndexOutOfRangeException(); return index switch { 0 => _item0, 1 => _item1, 2 => _item2, _ => _item3, }; } [MethodImpl(MethodImplOptions.AggressiveInlining)] set { if (_builder is not null) { _builder[index] = value; return; } if ((uint)index >= _count) ThrowIndexOutOfRangeException(); _ = index switch { 0 => _item0 = value, 1 => _item1 = value, 2 => _item2 = value, _ => _item3 = value, }; } } public void Dispose() { // Return _builder to the pool if necessary. There is no need to release inline storage since the majority // case for this type is stack-allocated storage and the GC is already able to reclaim objects from the // stack after the last use of a reference to them. Interlocked.Exchange(ref _builder, null)?.Free(); } public void Add(T item) { if (_builder is not null) { _builder.Add(item); } else if (_count < InlineCapacity) { // Increase _count before assigning a value since the indexer has a bounds check. _count++; this[_count - 1] = item; } else { Debug.Assert(_count == InlineCapacity); MoveInlineToBuilder(); _builder.Add(item); } } public void AddRange(ImmutableArray<T> items) { if (_builder is not null) { _builder.AddRange(items); } else if (_count + items.Length <= InlineCapacity) { foreach (var item in items) { // Increase _count before assigning values since the indexer has a bounds check. _count++; this[_count - 1] = item; } } else { MoveInlineToBuilder(); _builder.AddRange(items); } } public void AddRange(in TemporaryArray<T> items) { if (_count + items.Count <= InlineCapacity) { foreach (var item in items) { // Increase _count before assigning values since the indexer has a bounds check. _count++; this[_count - 1] = item; } } else { MoveInlineToBuilder(); foreach (var item in items) _builder.Add(item); } } public void Clear() { if (_builder is not null) { // Keep using a builder even if we now fit in inline storage to avoid churn in the object pools. _builder.Clear(); } else { this = Empty; } } public readonly Enumerator GetEnumerator() { return new Enumerator(in this); } /// <summary> /// Create an <see cref="ImmutableArray{T}"/> with the elements currently held in the temporary array, and clear /// the array. /// </summary> /// <returns></returns> public ImmutableArray<T> ToImmutableAndClear() { if (_builder is not null) { return _builder.ToImmutableAndClear(); } else { var result = _count switch { 0 => ImmutableArray<T>.Empty, 1 => ImmutableArray.Create(_item0), 2 => ImmutableArray.Create(_item0, _item1), 3 => ImmutableArray.Create(_item0, _item1, _item2), 4 => ImmutableArray.Create(_item0, _item1, _item2, _item3), _ => throw ExceptionUtilities.Unreachable, }; // Since _builder is null on this path, we can overwrite the whole structure to Empty to reset all // inline elements to their default value and the _count to 0. this = Empty; return result; } } /// <summary> /// Transitions the current <see cref="TemporaryArray{T}"/> from inline storage to dynamic storage storage. An /// <see cref="ArrayBuilder{T}"/> instance is taken from the shared pool, and all elements currently in inline /// storage are added to it. After this point, dynamic storage will be used instead of inline storage. /// </summary> [MemberNotNull(nameof(_builder))] private void MoveInlineToBuilder() { Debug.Assert(_builder is null); var builder = ArrayBuilder<T>.GetInstance(); for (var i = 0; i < _count; i++) { builder.Add(this[i]); #if NETCOREAPP if (RuntimeHelpers.IsReferenceOrContainsReferences<T>()) #endif { this[i] = default!; } } _count = 0; _builder = builder; } /// <summary> /// Throws <see cref="IndexOutOfRangeException"/>. /// </summary> /// <remarks> /// This helper improves the ability of the JIT to inline callers. /// </remarks> private static void ThrowIndexOutOfRangeException() => throw new IndexOutOfRangeException(); public struct Enumerator { private readonly TemporaryArray<T> _array; private T _current; private int _nextIndex; public Enumerator(in TemporaryArray<T> array) { // Enumerate a copy of the original _array = new TemporaryArray<T>(in array); _current = default!; _nextIndex = 0; } public T Current => _current; public bool MoveNext() { if (_nextIndex >= _array.Count) { return false; } else { _current = _array[_nextIndex]; _nextIndex++; return true; } } } internal static class TestAccessor { public static int InlineCapacity => TemporaryArray<T>.InlineCapacity; public static bool HasDynamicStorage(in TemporaryArray<T> array) => array._builder is not null; public static int InlineCount(in TemporaryArray<T> array) => array._count; } } }
-1
dotnet/roslyn
55,256
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-30T00:02:02Z
2021-07-30T09:17:54Z
6ce9c0048d37026337701fac035ac0745f6fe49f
88b59775dc6375635957ef229116460f290072aa
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Workspaces/Core/Portable/CodeStyle/NotificationOption2_operators.cs
// Licensed to the .NET Foundation under one or more agreements. // 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.CodeAnalysis; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CodeStyle { internal sealed partial class NotificationOption2 { [return: NotNullIfNotNull("notificationOption")] public static explicit operator NotificationOption2?(NotificationOption? notificationOption) { if (notificationOption is null) { return null; } return notificationOption.Severity switch { ReportDiagnostic.Suppress => None, ReportDiagnostic.Hidden => Silent, ReportDiagnostic.Info => Suggestion, ReportDiagnostic.Warn => Warning, ReportDiagnostic.Error => Error, _ => throw ExceptionUtilities.UnexpectedValue(notificationOption.Severity), }; } [return: NotNullIfNotNull("notificationOption")] public static explicit operator NotificationOption?(NotificationOption2? notificationOption) { if (notificationOption is null) { return null; } return notificationOption.Severity switch { ReportDiagnostic.Suppress => NotificationOption.None, ReportDiagnostic.Hidden => NotificationOption.Silent, ReportDiagnostic.Info => NotificationOption.Suggestion, ReportDiagnostic.Warn => NotificationOption.Warning, ReportDiagnostic.Error => NotificationOption.Error, _ => throw ExceptionUtilities.UnexpectedValue(notificationOption.Severity), }; } } }
// Licensed to the .NET Foundation under one or more agreements. // 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.CodeAnalysis; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CodeStyle { internal sealed partial class NotificationOption2 { [return: NotNullIfNotNull("notificationOption")] public static explicit operator NotificationOption2?(NotificationOption? notificationOption) { if (notificationOption is null) { return null; } return notificationOption.Severity switch { ReportDiagnostic.Suppress => None, ReportDiagnostic.Hidden => Silent, ReportDiagnostic.Info => Suggestion, ReportDiagnostic.Warn => Warning, ReportDiagnostic.Error => Error, _ => throw ExceptionUtilities.UnexpectedValue(notificationOption.Severity), }; } [return: NotNullIfNotNull("notificationOption")] public static explicit operator NotificationOption?(NotificationOption2? notificationOption) { if (notificationOption is null) { return null; } return notificationOption.Severity switch { ReportDiagnostic.Suppress => NotificationOption.None, ReportDiagnostic.Hidden => NotificationOption.Silent, ReportDiagnostic.Info => NotificationOption.Suggestion, ReportDiagnostic.Warn => NotificationOption.Warning, ReportDiagnostic.Error => NotificationOption.Error, _ => throw ExceptionUtilities.UnexpectedValue(notificationOption.Severity), }; } } }
-1