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,138
Avoid cancellation exceptions in intermediate operations
Addresses the following exceptions: ![image](https://user-images.githubusercontent.com/1408396/127185947-8a005aea-ae1c-4755-bf0f-21dfb8101352.png)
sharwell
2021-07-27T15:51:28Z
2021-07-27T21:36:45Z
3d8acbd585a75e9cdb3509623bf6c39ceb46b2c2
719d4ffa2be734463e5d7d4d74b23b8006fd7727
Avoid cancellation exceptions in intermediate operations. Addresses the following exceptions: ![image](https://user-images.githubusercontent.com/1408396/127185947-8a005aea-ae1c-4755-bf0f-21dfb8101352.png)
./src/Workspaces/Core/Portable/Workspace/Solution/TextDocumentState_Checksum.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.CodeAnalysis; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.Serialization; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { internal partial class TextDocumentState { public bool TryGetStateChecksums([NotNullWhen(returnValue: true)] out DocumentStateChecksums? stateChecksums) => _lazyChecksums.TryGetValue(out stateChecksums); public Task<DocumentStateChecksums> GetStateChecksumsAsync(CancellationToken cancellationToken) => _lazyChecksums.GetValueAsync(cancellationToken); public async Task<Checksum> GetChecksumAsync(CancellationToken cancellationToken) { var collection = await _lazyChecksums.GetValueAsync(cancellationToken).ConfigureAwait(false); return collection.Checksum; } private async Task<DocumentStateChecksums> ComputeChecksumsAsync(CancellationToken cancellationToken) { try { using (Logger.LogBlock(FunctionId.DocumentState_ComputeChecksumsAsync, FilePath, cancellationToken)) { var serializer = solutionServices.Workspace.Services.GetRequiredService<ISerializerService>(); var infoChecksum = serializer.CreateChecksum(Attributes, cancellationToken); var serializableText = await SerializableSourceText.FromTextDocumentStateAsync(this, cancellationToken).ConfigureAwait(false); var textChecksum = serializer.CreateChecksum(serializableText, cancellationToken); return new DocumentStateChecksums(infoChecksum, textChecksum); } } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { 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.Diagnostics.CodeAnalysis; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.Serialization; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { internal partial class TextDocumentState { public bool TryGetStateChecksums([NotNullWhen(returnValue: true)] out DocumentStateChecksums? stateChecksums) => _lazyChecksums.TryGetValue(out stateChecksums); public Task<DocumentStateChecksums> GetStateChecksumsAsync(CancellationToken cancellationToken) => _lazyChecksums.GetValueAsync(cancellationToken); public Task<Checksum> GetChecksumAsync(CancellationToken cancellationToken) { return SpecializedTasks.TransformWithoutIntermediateCancellationExceptionAsync( static (lazyChecksums, cancellationToken) => new ValueTask<DocumentStateChecksums>(lazyChecksums.GetValueAsync(cancellationToken)), static (documentStateChecksums, _) => documentStateChecksums.Checksum, _lazyChecksums, cancellationToken).AsTask(); } private async Task<DocumentStateChecksums> ComputeChecksumsAsync(CancellationToken cancellationToken) { try { using (Logger.LogBlock(FunctionId.DocumentState_ComputeChecksumsAsync, FilePath, cancellationToken)) { var serializer = solutionServices.Workspace.Services.GetRequiredService<ISerializerService>(); var infoChecksum = serializer.CreateChecksum(Attributes, cancellationToken); var serializableText = await SerializableSourceText.FromTextDocumentStateAsync(this, cancellationToken).ConfigureAwait(false); var textChecksum = serializer.CreateChecksum(serializableText, cancellationToken); return new DocumentStateChecksums(infoChecksum, textChecksum); } } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { throw ExceptionUtilities.Unreachable; } } } }
1
dotnet/roslyn
55,138
Avoid cancellation exceptions in intermediate operations
Addresses the following exceptions: ![image](https://user-images.githubusercontent.com/1408396/127185947-8a005aea-ae1c-4755-bf0f-21dfb8101352.png)
sharwell
2021-07-27T15:51:28Z
2021-07-27T21:36:45Z
3d8acbd585a75e9cdb3509623bf6c39ceb46b2c2
719d4ffa2be734463e5d7d4d74b23b8006fd7727
Avoid cancellation exceptions in intermediate operations. Addresses the following exceptions: ![image](https://user-images.githubusercontent.com/1408396/127185947-8a005aea-ae1c-4755-bf0f-21dfb8101352.png)
./src/Workspaces/CoreTest/UtilityTest/SpecializedTasksTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Diagnostics.CodeAnalysis; using System.Threading; using System.Threading.Tasks; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.UnitTests { [SuppressMessage("Usage", "VSTHRD104:Offer async methods", Justification = "This class tests specific behavior of tasks.")] public class SpecializedTasksTests { [Fact] public void WhenAll_Null() { #pragma warning disable CA2012 // Use ValueTasks correctly (the instance is never created) Assert.Throws<ArgumentNullException>(() => SpecializedTasks.WhenAll<int>(null)); #pragma warning restore CA2012 // Use ValueTasks correctly } [Fact] public void WhenAll_Empty() { var whenAll = SpecializedTasks.WhenAll(SpecializedCollections.EmptyEnumerable<ValueTask<int>>()); Debug.Assert(whenAll.IsCompleted); Assert.True(whenAll.IsCompletedSuccessfully); Assert.Same(Array.Empty<int>(), whenAll.Result); } [Fact] public void WhenAll_AllCompletedSuccessfully() { var whenAll = SpecializedTasks.WhenAll(new[] { new ValueTask<int>(0), new ValueTask<int>(1) }); Debug.Assert(whenAll.IsCompleted); Assert.True(whenAll.IsCompletedSuccessfully); Assert.Equal(new[] { 0, 1 }, whenAll.Result); } [Fact] public void WhenAll_CompletedButCanceled() { var whenAll = SpecializedTasks.WhenAll(new[] { new ValueTask<int>(Task.FromCanceled<int>(new CancellationToken(true))) }); Assert.True(whenAll.IsCompleted); Assert.False(whenAll.IsCompletedSuccessfully); Assert.ThrowsAsync<OperationCanceledException>(async () => await whenAll); } [Fact] public void WhenAll_NotYetCompleted() { var completionSource = new TaskCompletionSource<int>(); var whenAll = SpecializedTasks.WhenAll(new[] { new ValueTask<int>(completionSource.Task) }); Assert.False(whenAll.IsCompleted); completionSource.SetResult(0); Assert.True(whenAll.IsCompleted); Debug.Assert(whenAll.IsCompleted); Assert.Equal(new[] { 0 }, whenAll.Result); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Threading; using System.Threading.Tasks; using Roslyn.Utilities; using Xunit; #pragma warning disable IDE0039 // Use local function namespace Microsoft.CodeAnalysis.UnitTests { [SuppressMessage("Usage", "VSTHRD104:Offer async methods", Justification = "This class tests specific behavior of tasks.")] public class SpecializedTasksTests { private record StateType; private record IntermediateType; private record ResultType; [Fact] public void WhenAll_Null() { #pragma warning disable CA2012 // Use ValueTasks correctly (the instance is never created) Assert.Throws<ArgumentNullException>(() => SpecializedTasks.WhenAll<int>(null!)); #pragma warning restore CA2012 // Use ValueTasks correctly } [Fact] public void WhenAll_Empty() { var whenAll = SpecializedTasks.WhenAll(SpecializedCollections.EmptyEnumerable<ValueTask<int>>()); Debug.Assert(whenAll.IsCompleted); Assert.True(whenAll.IsCompletedSuccessfully); Assert.Same(Array.Empty<int>(), whenAll.Result); } [Fact] public void WhenAll_AllCompletedSuccessfully() { var whenAll = SpecializedTasks.WhenAll(new[] { new ValueTask<int>(0), new ValueTask<int>(1) }); Debug.Assert(whenAll.IsCompleted); Assert.True(whenAll.IsCompletedSuccessfully); Assert.Equal(new[] { 0, 1 }, whenAll.Result); } [Fact] public void WhenAll_CompletedButCanceled() { var whenAll = SpecializedTasks.WhenAll(new[] { new ValueTask<int>(Task.FromCanceled<int>(new CancellationToken(true))) }); Assert.True(whenAll.IsCompleted); Assert.False(whenAll.IsCompletedSuccessfully); Assert.ThrowsAsync<OperationCanceledException>(async () => await whenAll); } [Fact] public void WhenAll_NotYetCompleted() { var completionSource = new TaskCompletionSource<int>(); var whenAll = SpecializedTasks.WhenAll(new[] { new ValueTask<int>(completionSource.Task) }); Assert.False(whenAll.IsCompleted); completionSource.SetResult(0); Assert.True(whenAll.IsCompleted); Debug.Assert(whenAll.IsCompleted); Assert.Equal(new[] { 0 }, whenAll.Result); } [Fact] public void Transform_ArgumentValidation() { Func<StateType, CancellationToken, ValueTask<IntermediateType>> func = (_, _) => new(new IntermediateType()); Func<IntermediateType, StateType, ResultType> transform = (_, _) => new(); var arg = new StateType(); var cancellationToken = new CancellationToken(canceled: false); #pragma warning disable CA2012 // Use ValueTasks correctly (the instance is never created) Assert.Throws<ArgumentNullException>("func", () => SpecializedTasks.TransformWithoutIntermediateCancellationExceptionAsync(null!, transform, arg, cancellationToken)); Assert.Throws<ArgumentNullException>("transform", () => SpecializedTasks.TransformWithoutIntermediateCancellationExceptionAsync<StateType, IntermediateType, ResultType>(func, null!, arg, cancellationToken)); #pragma warning restore CA2012 // Use ValueTasks correctly } [Fact] public void Transform_SyncCompletedFunction_CompletedTransform() { Func<StateType, CancellationToken, ValueTask<IntermediateType>> func = (_, _) => new(new IntermediateType()); Func<IntermediateType, StateType, ResultType> transform = (_, _) => new(); var arg = new StateType(); var cancellationToken = new CancellationToken(canceled: false); var task = SpecializedTasks.TransformWithoutIntermediateCancellationExceptionAsync(func, transform, arg, cancellationToken).Preserve(); Assert.True(task.IsCompletedSuccessfully); Assert.NotNull(task.Result); } [Fact] public void Transform_SyncCompletedFunction_CancellationRequested_IgnoresTransform() { using var cts = new CancellationTokenSource(); cts.Cancel(); var executedTransform = false; var cancellationToken = cts.Token; Func<StateType, CancellationToken, ValueTask<IntermediateType>> func = (_, _) => new(new IntermediateType()); Func<IntermediateType, StateType, ResultType> transform = (_, _) => { executedTransform = true; return new ResultType(); }; var arg = new StateType(); var task = SpecializedTasks.TransformWithoutIntermediateCancellationExceptionAsync(func, transform, arg, cancellationToken).Preserve(); Assert.True(task.IsCanceled); var exception = Assert.Throws<TaskCanceledException>(() => task.Result); Assert.Equal(cancellationToken, exception.CancellationToken); Assert.False(executedTransform); } [Fact] public async Task Transform_AsyncCompletedFunction_CompletedTransform() { var gate = new ManualResetEventSlim(); Func<StateType, CancellationToken, ValueTask<IntermediateType>> func = async (_, _) => { await Task.Yield(); gate.Wait(CancellationToken.None); return new IntermediateType(); }; Func<IntermediateType, StateType, ResultType> transform = (_, _) => new(); var arg = new StateType(); var cancellationToken = new CancellationToken(canceled: false); var task = SpecializedTasks.TransformWithoutIntermediateCancellationExceptionAsync(func, transform, arg, cancellationToken).Preserve(); Assert.False(task.IsCompleted); gate.Set(); Assert.NotNull(await task); } [Fact] public async Task Transform_AsyncCompletedFunction_CancellationRequested_IgnoresTransform() { using var cts = new CancellationTokenSource(); cts.Cancel(); var executedTransform = false; var cancellationToken = cts.Token; var gate = new ManualResetEventSlim(); Func<StateType, CancellationToken, ValueTask<IntermediateType>> func = async (_, _) => { await Task.Yield(); gate.Wait(CancellationToken.None); return new IntermediateType(); }; Func<IntermediateType, StateType, ResultType> transform = (_, _) => { executedTransform = true; return new ResultType(); }; var arg = new StateType(); var task = SpecializedTasks.TransformWithoutIntermediateCancellationExceptionAsync(func, transform, arg, cancellationToken).Preserve(); Assert.False(task.IsCompleted); gate.Set(); var exception = await Assert.ThrowsAsync<TaskCanceledException>(async () => await task); Assert.Equal(cancellationToken, exception.CancellationToken); Assert.False(executedTransform); } [Fact] public void Transform_SyncCanceledFunction_IgnoresTransform() { using var cts = new CancellationTokenSource(); cts.Cancel(); var executedTransform = false; var cancellationToken = cts.Token; Func<StateType, CancellationToken, ValueTask<IntermediateType>> func = (_, _) => new(Task.FromCanceled<IntermediateType>(cancellationToken)); Func<IntermediateType, StateType, ResultType> transform = (_, _) => { executedTransform = true; return new ResultType(); }; var arg = new StateType(); var task = SpecializedTasks.TransformWithoutIntermediateCancellationExceptionAsync(func, transform, arg, cancellationToken).Preserve(); Assert.True(task.IsCanceled); var exception = Assert.Throws<TaskCanceledException>(() => task.Result); Assert.Equal(cancellationToken, exception.CancellationToken); Assert.False(executedTransform); } [Fact] public async Task Transform_AsyncCanceledFunction_IgnoresTransform() { using var cts = new CancellationTokenSource(); cts.Cancel(); var executedTransform = false; var cancellationToken = cts.Token; var gate = new ManualResetEventSlim(); Func<StateType, CancellationToken, ValueTask<IntermediateType>> func = async (_, _) => { await Task.Yield(); gate.Wait(CancellationToken.None); cts.Token.ThrowIfCancellationRequested(); throw ExceptionUtilities.Unreachable; }; Func<IntermediateType, StateType, ResultType> transform = (_, _) => { executedTransform = true; return new ResultType(); }; var arg = new StateType(); var task = SpecializedTasks.TransformWithoutIntermediateCancellationExceptionAsync(func, transform, arg, cancellationToken).Preserve(); Assert.False(task.IsCompleted); gate.Set(); var exception = await Assert.ThrowsAsync<TaskCanceledException>(async () => await task); Assert.Equal(cancellationToken, exception.CancellationToken); Assert.False(executedTransform); } [Fact] public void Transform_SyncCanceledFunction_NotRequested_IgnoresTransform() { using var unexpectedCts = new CancellationTokenSource(); unexpectedCts.Cancel(); var executedTransform = false; var cancellationToken = new CancellationToken(canceled: false); Func<StateType, CancellationToken, ValueTask<IntermediateType>> func = (_, _) => new(Task.FromCanceled<IntermediateType>(unexpectedCts.Token)); Func<IntermediateType, StateType, ResultType> transform = (_, _) => { executedTransform = true; return new ResultType(); }; var arg = new StateType(); var task = SpecializedTasks.TransformWithoutIntermediateCancellationExceptionAsync(func, transform, arg, cancellationToken).Preserve(); Assert.True(task.IsCanceled); var exception = Assert.Throws<TaskCanceledException>(() => task.Result); // ⚠ Due to the way cancellation is handled in ContinueWith, the resulting exception fails to preserve the // cancellation token applied when the intermediate task was cancelled. Assert.Equal(cancellationToken, exception.CancellationToken); Assert.False(executedTransform); } [Fact] public async Task Transform_AsyncCanceledFunction_NotRequested_IgnoresTransform() { using var unexpectedCts = new CancellationTokenSource(); unexpectedCts.Cancel(); var executedTransform = false; var cancellationToken = new CancellationToken(canceled: false); var gate = new ManualResetEventSlim(); Func<StateType, CancellationToken, ValueTask<IntermediateType>> func = async (_, _) => { await Task.Yield(); gate.Wait(CancellationToken.None); unexpectedCts.Token.ThrowIfCancellationRequested(); throw ExceptionUtilities.Unreachable; }; Func<IntermediateType, StateType, ResultType> transform = (_, _) => { executedTransform = true; return new ResultType(); }; var arg = new StateType(); var task = SpecializedTasks.TransformWithoutIntermediateCancellationExceptionAsync(func, transform, arg, cancellationToken).Preserve(); Assert.False(task.IsCompleted); gate.Set(); var exception = await Assert.ThrowsAsync<TaskCanceledException>(async () => await task); Assert.True(task.IsCanceled); // ⚠ Due to the way cancellation is handled in ContinueWith, the resulting exception fails to preserve the // cancellation token applied when the intermediate task was cancelled. Assert.Equal(cancellationToken, exception.CancellationToken); Assert.False(executedTransform); } [Fact] public void Transform_SyncCanceledFunction_MismatchToken_IgnoresTransform() { using var cts = new CancellationTokenSource(); cts.Cancel(); using var unexpectedCts = new CancellationTokenSource(); unexpectedCts.Cancel(); var executedTransform = false; var cancellationToken = cts.Token; Func<StateType, CancellationToken, ValueTask<IntermediateType>> func = (_, _) => new(Task.FromCanceled<IntermediateType>(unexpectedCts.Token)); Func<IntermediateType, StateType, ResultType> transform = (_, _) => { executedTransform = true; return new ResultType(); }; var arg = new StateType(); var task = SpecializedTasks.TransformWithoutIntermediateCancellationExceptionAsync(func, transform, arg, cancellationToken).Preserve(); Assert.True(task.IsCanceled); var exception = Assert.Throws<TaskCanceledException>(() => task.Result); Assert.Equal(cancellationToken, exception.CancellationToken); Assert.False(executedTransform); } [Fact] public async Task Transform_AsyncCanceledFunction_MismatchToken_IgnoresTransform() { using var cts = new CancellationTokenSource(); cts.Cancel(); using var unexpectedCts = new CancellationTokenSource(); unexpectedCts.Cancel(); var executedTransform = false; var cancellationToken = cts.Token; var gate = new ManualResetEventSlim(); Func<StateType, CancellationToken, ValueTask<IntermediateType>> func = async (_, _) => { await Task.Yield(); gate.Wait(CancellationToken.None); unexpectedCts.Token.ThrowIfCancellationRequested(); throw ExceptionUtilities.Unreachable; }; Func<IntermediateType, StateType, ResultType> transform = (_, _) => { executedTransform = true; return new ResultType(); }; var arg = new StateType(); var task = SpecializedTasks.TransformWithoutIntermediateCancellationExceptionAsync(func, transform, arg, cancellationToken).Preserve(); Assert.False(task.IsCompleted); gate.Set(); var exception = await Assert.ThrowsAsync<TaskCanceledException>(async () => await task); Assert.True(task.IsCanceled); Assert.Equal(cancellationToken, exception.CancellationToken); Assert.False(executedTransform); } [Fact] public void Transform_SyncDirectFaultedFunction_IgnoresTransform() { var executedTransform = false; var fault = ExceptionUtilities.Unreachable; var cancellationToken = new CancellationToken(canceled: false); Func<StateType, CancellationToken, ValueTask<IntermediateType>> func = (_, _) => throw fault; Func<IntermediateType, StateType, ResultType> transform = (_, _) => { executedTransform = true; return new ResultType(); }; var arg = new StateType(); #pragma warning disable CA2012 // Use ValueTasks correctly (the instance is never created) var exception = Assert.Throws<InvalidOperationException>(() => SpecializedTasks.TransformWithoutIntermediateCancellationExceptionAsync(func, transform, arg, cancellationToken)); #pragma warning restore CA2012 // Use ValueTasks correctly Assert.Same(fault, exception); Assert.False(executedTransform); } [Fact] public void Transform_SyncFaultedFunction_IgnoresTransform() { var executedTransform = false; var fault = ExceptionUtilities.Unreachable; var cancellationToken = new CancellationToken(canceled: false); Func<StateType, CancellationToken, ValueTask<IntermediateType>> func = (_, _) => new(Task.FromException<IntermediateType>(fault)); Func<IntermediateType, StateType, ResultType> transform = (_, _) => { executedTransform = true; return new ResultType(); }; var arg = new StateType(); var task = SpecializedTasks.TransformWithoutIntermediateCancellationExceptionAsync(func, transform, arg, cancellationToken).Preserve(); Assert.True(task.IsFaulted); var exception = Assert.Throws<InvalidOperationException>(() => task.Result); Assert.Same(fault, exception); Assert.False(executedTransform); } [Fact] public async Task Transform_AsyncFaultedFunction_IgnoresTransform() { var executedTransform = false; var fault = ExceptionUtilities.Unreachable; var cancellationToken = new CancellationToken(canceled: false); var gate = new ManualResetEventSlim(); Func<StateType, CancellationToken, ValueTask<IntermediateType>> func = async (_, _) => { await Task.Yield(); gate.Wait(CancellationToken.None); throw fault; }; Func<IntermediateType, StateType, ResultType> transform = (_, _) => { executedTransform = true; return new ResultType(); }; var arg = new StateType(); var task = SpecializedTasks.TransformWithoutIntermediateCancellationExceptionAsync(func, transform, arg, cancellationToken).Preserve(); Assert.False(task.IsCompleted); gate.Set(); var exception = await Assert.ThrowsAsync<InvalidOperationException>(() => task.AsTask()); Assert.Same(fault, exception); Assert.False(executedTransform); } [Fact] public void Transform_SyncDirectFaultedFunction_CancellationRequested_IgnoresTransform() { using var cts = new CancellationTokenSource(); cts.Cancel(); var executedTransform = false; var fault = ExceptionUtilities.Unreachable; var cancellationToken = cts.Token; Func<StateType, CancellationToken, ValueTask<IntermediateType>> func = (_, _) => throw fault; Func<IntermediateType, StateType, ResultType> transform = (_, _) => { executedTransform = true; return new ResultType(); }; var arg = new StateType(); #pragma warning disable CA2012 // Use ValueTasks correctly (the instance is never created) var exception = Assert.Throws<InvalidOperationException>(() => SpecializedTasks.TransformWithoutIntermediateCancellationExceptionAsync(func, transform, arg, cancellationToken)); #pragma warning restore CA2012 // Use ValueTasks correctly Assert.Same(fault, exception); Assert.False(executedTransform); } [Fact] public void Transform_SyncFaultedFunction_CancellationRequested_IgnoresTransform() { using var cts = new CancellationTokenSource(); cts.Cancel(); var executedTransform = false; var fault = ExceptionUtilities.Unreachable; var cancellationToken = cts.Token; Func<StateType, CancellationToken, ValueTask<IntermediateType>> func = (_, _) => new(Task.FromException<IntermediateType>(fault)); Func<IntermediateType, StateType, ResultType> transform = (_, _) => { executedTransform = true; return new ResultType(); }; var arg = new StateType(); var task = SpecializedTasks.TransformWithoutIntermediateCancellationExceptionAsync(func, transform, arg, cancellationToken).Preserve(); Assert.True(task.IsCanceled); var exception = Assert.Throws<TaskCanceledException>(() => task.Result); Assert.Equal(cancellationToken, exception.CancellationToken); Assert.False(executedTransform); } [Fact] public async Task Transform_AsyncFaultedFunction_CancellationRequested_IgnoresTransform() { using var cts = new CancellationTokenSource(); cts.Cancel(); var executedTransform = false; var fault = ExceptionUtilities.Unreachable; var cancellationToken = cts.Token; var gate = new ManualResetEventSlim(); Func<StateType, CancellationToken, ValueTask<IntermediateType>> func = async (_, _) => { await Task.Yield(); gate.Wait(CancellationToken.None); throw fault; }; Func<IntermediateType, StateType, ResultType> transform = (_, _) => { executedTransform = true; return new ResultType(); }; var arg = new StateType(); var task = SpecializedTasks.TransformWithoutIntermediateCancellationExceptionAsync(func, transform, arg, cancellationToken).Preserve(); Assert.False(task.IsCompleted); gate.Set(); var exception = await Assert.ThrowsAsync<TaskCanceledException>(() => task.AsTask()); Assert.True(task.IsCanceled); Assert.Equal(cancellationToken, exception.CancellationToken); Assert.False(executedTransform); } [Fact] public void Transform_SyncCompletedFunction_FaultedTransform() { var fault = ExceptionUtilities.Unreachable; Func<StateType, CancellationToken, ValueTask<IntermediateType>> func = (_, _) => new(new IntermediateType()); Func<IntermediateType, StateType, ResultType> transform = (_, _) => throw fault; var arg = new StateType(); var cancellationToken = new CancellationToken(canceled: false); #pragma warning disable CA2012 // Use ValueTasks correctly (the instance is never created) var exception = Assert.Throws<InvalidOperationException>(() => SpecializedTasks.TransformWithoutIntermediateCancellationExceptionAsync(func, transform, arg, cancellationToken)); #pragma warning restore CA2012 // Use ValueTasks correctly Assert.Same(fault, exception); } [Fact] public async Task Transform_AsyncCompletedFunction_FaultedTransform() { var fault = ExceptionUtilities.Unreachable; var gate = new ManualResetEventSlim(); Func<StateType, CancellationToken, ValueTask<IntermediateType>> func = async (_, _) => { await Task.Yield(); gate.Wait(CancellationToken.None); return new IntermediateType(); }; Func<IntermediateType, StateType, ResultType> transform = (_, _) => throw fault; var arg = new StateType(); var cancellationToken = new CancellationToken(canceled: false); var task = SpecializedTasks.TransformWithoutIntermediateCancellationExceptionAsync(func, transform, arg, cancellationToken).Preserve(); Assert.False(task.IsCompleted); gate.Set(); var exception = await Assert.ThrowsAsync<InvalidOperationException>(() => task.AsTask()); Assert.Same(fault, exception); } } }
1
dotnet/roslyn
55,138
Avoid cancellation exceptions in intermediate operations
Addresses the following exceptions: ![image](https://user-images.githubusercontent.com/1408396/127185947-8a005aea-ae1c-4755-bf0f-21dfb8101352.png)
sharwell
2021-07-27T15:51:28Z
2021-07-27T21:36:45Z
3d8acbd585a75e9cdb3509623bf6c39ceb46b2c2
719d4ffa2be734463e5d7d4d74b23b8006fd7727
Avoid cancellation exceptions in intermediate operations. Addresses the following exceptions: ![image](https://user-images.githubusercontent.com/1408396/127185947-8a005aea-ae1c-4755-bf0f-21dfb8101352.png)
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/SpecializedTasks.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.Runtime.CompilerServices; using System.Threading.Tasks; namespace Roslyn.Utilities { internal static class SpecializedTasks { public static readonly Task<bool> True = Task.FromResult(true); public static readonly Task<bool> False = Task.FromResult(false); // This is being consumed through InternalsVisibleTo by Source-Based test discovery [Obsolete("Use Task.CompletedTask instead which is available in the framework.")] public static readonly Task EmptyTask = Task.CompletedTask; [SuppressMessage("Style", "VSTHRD200:Use \"Async\" suffix for async methods", Justification = "This is a Task wrapper, not an asynchronous method.")] public static Task<T?> AsNullable<T>(this Task<T> task) where T : class => task!; [SuppressMessage("Style", "VSTHRD200:Use \"Async\" suffix for async methods", Justification = "This is a Task wrapper, not an asynchronous method.")] public static Task<T?> Default<T>() => EmptyTasks<T>.Default; [SuppressMessage("Style", "VSTHRD200:Use \"Async\" suffix for async methods", Justification = "This is a Task wrapper, not an asynchronous method.")] public static Task<T?> Null<T>() where T : class => Default<T>(); [SuppressMessage("Style", "VSTHRD200:Use \"Async\" suffix for async methods", Justification = "This is a Task wrapper, not an asynchronous method.")] public static Task<IReadOnlyList<T>> EmptyReadOnlyList<T>() => EmptyTasks<T>.EmptyReadOnlyList; [SuppressMessage("Style", "VSTHRD200:Use \"Async\" suffix for async methods", Justification = "This is a Task wrapper, not an asynchronous method.")] public static Task<IList<T>> EmptyList<T>() => EmptyTasks<T>.EmptyList; [SuppressMessage("Style", "VSTHRD200:Use \"Async\" suffix for async methods", Justification = "This is a Task wrapper, not an asynchronous method.")] public static Task<ImmutableArray<T>> EmptyImmutableArray<T>() => EmptyTasks<T>.EmptyImmutableArray; [SuppressMessage("Style", "VSTHRD200:Use \"Async\" suffix for async methods", Justification = "This is a Task wrapper, not an asynchronous method.")] public static Task<IEnumerable<T>> EmptyEnumerable<T>() => EmptyTasks<T>.EmptyEnumerable; [SuppressMessage("Style", "VSTHRD200:Use \"Async\" suffix for async methods", Justification = "This is a Task wrapper, not an asynchronous method.")] public static Task<T> FromResult<T>(T t) where T : class => FromResultCache<T>.FromResult(t); [SuppressMessage("Style", "VSTHRD200:Use \"Async\" suffix for async methods", Justification = "Naming is modeled after Task.WhenAll.")] public static ValueTask<T[]> WhenAll<T>(IEnumerable<ValueTask<T>> tasks) { var taskArray = tasks.AsArray(); if (taskArray.Length == 0) return ValueTaskFactory.FromResult(Array.Empty<T>()); var allCompletedSuccessfully = true; for (var i = 0; i < taskArray.Length; i++) { if (!taskArray[i].IsCompletedSuccessfully) { allCompletedSuccessfully = false; break; } } if (allCompletedSuccessfully) { var result = new T[taskArray.Length]; for (var i = 0; i < taskArray.Length; i++) { result[i] = taskArray[i].Result; } return ValueTaskFactory.FromResult(result); } else { return new ValueTask<T[]>(Task.WhenAll(taskArray.Select(task => task.AsTask()))); } } private static class EmptyTasks<T> { public static readonly Task<T?> Default = Task.FromResult<T?>(default); public static readonly Task<IEnumerable<T>> EmptyEnumerable = Task.FromResult<IEnumerable<T>>(SpecializedCollections.EmptyEnumerable<T>()); public static readonly Task<ImmutableArray<T>> EmptyImmutableArray = Task.FromResult(ImmutableArray<T>.Empty); public static readonly Task<IList<T>> EmptyList = Task.FromResult(SpecializedCollections.EmptyList<T>()); public static readonly Task<IReadOnlyList<T>> EmptyReadOnlyList = Task.FromResult(SpecializedCollections.EmptyReadOnlyList<T>()); } private static class FromResultCache<T> where T : class { private static readonly ConditionalWeakTable<T, Task<T>> s_fromResultCache = new(); private static readonly ConditionalWeakTable<T, Task<T>>.CreateValueCallback s_taskCreationCallback = Task.FromResult<T>; [SuppressMessage("Style", "VSTHRD200:Use \"Async\" suffix for async methods", Justification = "This is a Task wrapper, not an asynchronous method.")] public static Task<T> FromResult(T t) => s_fromResultCache.GetValue(t, s_taskCreationCallback); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .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.Runtime.CompilerServices; using System.Threading; using System.Threading.Tasks; namespace Roslyn.Utilities { internal static class SpecializedTasks { public static readonly Task<bool> True = Task.FromResult(true); public static readonly Task<bool> False = Task.FromResult(false); // This is being consumed through InternalsVisibleTo by Source-Based test discovery [Obsolete("Use Task.CompletedTask instead which is available in the framework.")] public static readonly Task EmptyTask = Task.CompletedTask; [SuppressMessage("Style", "VSTHRD200:Use \"Async\" suffix for async methods", Justification = "This is a Task wrapper, not an asynchronous method.")] public static Task<T?> AsNullable<T>(this Task<T> task) where T : class => task!; [SuppressMessage("Style", "VSTHRD200:Use \"Async\" suffix for async methods", Justification = "This is a Task wrapper, not an asynchronous method.")] public static Task<T?> Default<T>() => EmptyTasks<T>.Default; [SuppressMessage("Style", "VSTHRD200:Use \"Async\" suffix for async methods", Justification = "This is a Task wrapper, not an asynchronous method.")] public static Task<T?> Null<T>() where T : class => Default<T>(); [SuppressMessage("Style", "VSTHRD200:Use \"Async\" suffix for async methods", Justification = "This is a Task wrapper, not an asynchronous method.")] public static Task<IReadOnlyList<T>> EmptyReadOnlyList<T>() => EmptyTasks<T>.EmptyReadOnlyList; [SuppressMessage("Style", "VSTHRD200:Use \"Async\" suffix for async methods", Justification = "This is a Task wrapper, not an asynchronous method.")] public static Task<IList<T>> EmptyList<T>() => EmptyTasks<T>.EmptyList; [SuppressMessage("Style", "VSTHRD200:Use \"Async\" suffix for async methods", Justification = "This is a Task wrapper, not an asynchronous method.")] public static Task<ImmutableArray<T>> EmptyImmutableArray<T>() => EmptyTasks<T>.EmptyImmutableArray; [SuppressMessage("Style", "VSTHRD200:Use \"Async\" suffix for async methods", Justification = "This is a Task wrapper, not an asynchronous method.")] public static Task<IEnumerable<T>> EmptyEnumerable<T>() => EmptyTasks<T>.EmptyEnumerable; [SuppressMessage("Style", "VSTHRD200:Use \"Async\" suffix for async methods", Justification = "This is a Task wrapper, not an asynchronous method.")] public static Task<T> FromResult<T>(T t) where T : class => FromResultCache<T>.FromResult(t); [SuppressMessage("Style", "VSTHRD200:Use \"Async\" suffix for async methods", Justification = "Naming is modeled after Task.WhenAll.")] public static ValueTask<T[]> WhenAll<T>(IEnumerable<ValueTask<T>> tasks) { var taskArray = tasks.AsArray(); if (taskArray.Length == 0) return ValueTaskFactory.FromResult(Array.Empty<T>()); var allCompletedSuccessfully = true; for (var i = 0; i < taskArray.Length; i++) { if (!taskArray[i].IsCompletedSuccessfully) { allCompletedSuccessfully = false; break; } } if (allCompletedSuccessfully) { var result = new T[taskArray.Length]; for (var i = 0; i < taskArray.Length; i++) { result[i] = taskArray[i].Result; } return ValueTaskFactory.FromResult(result); } else { return new ValueTask<T[]>(Task.WhenAll(taskArray.Select(task => task.AsTask()))); } } /// <summary> /// This helper method provides semantics equivalent to the following, but avoids throwing an intermediate /// <see cref="OperationCanceledException"/> in the case where the asynchronous operation is cancelled. /// /// <code><![CDATA[ /// public ValueTask<TResult> MethodAsync(TArg arg, CancellationToken cancellationToken) /// { /// var intermediate = await func(arg, cancellationToken).ConfigureAwait(false); /// return transform(intermediate); /// } /// ]]></code> /// </summary> /// <remarks> /// This helper method is only intended for use in cases where profiling reveals substantial overhead related to /// cancellation processing. /// </remarks> /// <typeparam name="TArg">The type of a state variable to pass to <paramref name="func"/> and <paramref name="transform"/>.</typeparam> /// <typeparam name="TIntermediate">The type of intermediate result produced by <paramref name="func"/>.</typeparam> /// <typeparam name="TResult">The type of result produced by <paramref name="transform"/>.</typeparam> /// <param name="func">The intermediate asynchronous operation.</param> /// <param name="transform">The synchronous transformation to apply to the result of <paramref name="func"/>.</param> /// <param name="arg">The state to pass to <paramref name="func"/> and <paramref name="transform"/>.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> that the operation will observe.</param> /// <returns></returns> public static ValueTask<TResult> TransformWithoutIntermediateCancellationExceptionAsync<TArg, TIntermediate, TResult>( Func<TArg, CancellationToken, ValueTask<TIntermediate>> func, Func<TIntermediate, TArg, TResult> transform, TArg arg, CancellationToken cancellationToken) { if (func is null) throw new ArgumentNullException(nameof(func)); if (transform is null) throw new ArgumentNullException(nameof(transform)); var intermediateResult = func(arg, cancellationToken); if (intermediateResult.IsCompletedSuccessfully) { // Synchronous fast path if 'func' completes synchronously var result = intermediateResult.Result; if (cancellationToken.IsCancellationRequested) return new ValueTask<TResult>(Task.FromCanceled<TResult>(cancellationToken)); return new ValueTask<TResult>(transform(result, arg)); } else if (intermediateResult.IsCanceled && cancellationToken.IsCancellationRequested) { // Synchronous fast path if 'func' cancels synchronously return new ValueTask<TResult>(Task.FromCanceled<TResult>(cancellationToken)); } else { // Asynchronous fallback path return UnwrapAndTransformAsync(intermediateResult, transform, arg, cancellationToken); } static ValueTask<TResult> UnwrapAndTransformAsync(ValueTask<TIntermediate> intermediateResult, Func<TIntermediate, TArg, TResult> transform, TArg arg, CancellationToken cancellationToken) { // Apply the transformation function once a result is available. The behavior depends on the final // status of 'intermediateResult' and the 'cancellationToken'. // // | 'intermediateResult' | 'cancellationToken' | Behavior | // | -------------------------- | ------------------- | ---------------------------------------- | // | Ran to completion | Not cancelled | Apply transform | // | Ran to completion | Cancelled | Cancel result without applying transform | // | Cancelled (matching token) | Cancelled | Cancel result without applying transform | // | Cancelled (mismatch token) | Not cancelled | Cancel result without applying transform | // | Cancelled (mismatch token) | Cancelled | Cancel result without applying transform | // | Direct fault¹ | Not cancelled | Directly fault (exception is not caught) | // | Direct fault¹ | Cancelled | Directly fault (exception is not caught) | // | Indirect fault | Not cancelled | Fault result without applying transform | // | Indirect fault | Cancelled | Cancel result without applying transform | // // ¹ Direct faults are exceptions thrown from 'func' prior to returning a ValueTask<TIntermediate> // instances. Indirect faults are exceptions captured by return an instance of // ValueTask<TIntermediate> which (immediately or eventually) transitions to the faulted state. The // direct fault behavior is currently handled without calling UnwrapAndTransformAsync. return new ValueTask<TResult>(intermediateResult.AsTask().ContinueWith( task => transform(task.GetAwaiter().GetResult(), arg), cancellationToken, TaskContinuationOptions.LazyCancellation | TaskContinuationOptions.NotOnCanceled | TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default)); } } private static class EmptyTasks<T> { public static readonly Task<T?> Default = Task.FromResult<T?>(default); public static readonly Task<IEnumerable<T>> EmptyEnumerable = Task.FromResult<IEnumerable<T>>(SpecializedCollections.EmptyEnumerable<T>()); public static readonly Task<ImmutableArray<T>> EmptyImmutableArray = Task.FromResult(ImmutableArray<T>.Empty); public static readonly Task<IList<T>> EmptyList = Task.FromResult(SpecializedCollections.EmptyList<T>()); public static readonly Task<IReadOnlyList<T>> EmptyReadOnlyList = Task.FromResult(SpecializedCollections.EmptyReadOnlyList<T>()); } private static class FromResultCache<T> where T : class { private static readonly ConditionalWeakTable<T, Task<T>> s_fromResultCache = new(); private static readonly ConditionalWeakTable<T, Task<T>>.CreateValueCallback s_taskCreationCallback = Task.FromResult<T>; [SuppressMessage("Style", "VSTHRD200:Use \"Async\" suffix for async methods", Justification = "This is a Task wrapper, not an asynchronous method.")] public static Task<T> FromResult(T t) => s_fromResultCache.GetValue(t, s_taskCreationCallback); } } }
1
dotnet/roslyn
55,138
Avoid cancellation exceptions in intermediate operations
Addresses the following exceptions: ![image](https://user-images.githubusercontent.com/1408396/127185947-8a005aea-ae1c-4755-bf0f-21dfb8101352.png)
sharwell
2021-07-27T15:51:28Z
2021-07-27T21:36:45Z
3d8acbd585a75e9cdb3509623bf6c39ceb46b2c2
719d4ffa2be734463e5d7d4d74b23b8006fd7727
Avoid cancellation exceptions in intermediate operations. Addresses the following exceptions: ![image](https://user-images.githubusercontent.com/1408396/127185947-8a005aea-ae1c-4755-bf0f-21dfb8101352.png)
./src/Workspaces/Core/Portable/Shared/Extensions/INamespaceSymbolExtensions.Comparer.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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 Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Shared.Extensions { internal partial class INamespaceSymbolExtensions { private class Comparer : IEqualityComparer<INamespaceSymbol?> { public bool Equals(INamespaceSymbol? x, INamespaceSymbol? y) => GetNameParts(x).SequenceEqual(GetNameParts(y)); public int GetHashCode(INamespaceSymbol? obj) => GetNameParts(obj).Aggregate(0, (a, v) => Hash.Combine(v, a)); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .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 Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Shared.Extensions { internal partial class INamespaceSymbolExtensions { private class Comparer : IEqualityComparer<INamespaceSymbol?> { public bool Equals(INamespaceSymbol? x, INamespaceSymbol? y) => GetNameParts(x).SequenceEqual(GetNameParts(y)); public int GetHashCode(INamespaceSymbol? obj) => GetNameParts(obj).Aggregate(0, (a, v) => Hash.Combine(v, a)); } } }
-1
dotnet/roslyn
55,138
Avoid cancellation exceptions in intermediate operations
Addresses the following exceptions: ![image](https://user-images.githubusercontent.com/1408396/127185947-8a005aea-ae1c-4755-bf0f-21dfb8101352.png)
sharwell
2021-07-27T15:51:28Z
2021-07-27T21:36:45Z
3d8acbd585a75e9cdb3509623bf6c39ceb46b2c2
719d4ffa2be734463e5d7d4d74b23b8006fd7727
Avoid cancellation exceptions in intermediate operations. Addresses the following exceptions: ![image](https://user-images.githubusercontent.com/1408396/127185947-8a005aea-ae1c-4755-bf0f-21dfb8101352.png)
./src/Compilers/CSharp/Portable/BoundTree/BoundLocalFunctionStatement.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Text; namespace Microsoft.CodeAnalysis.CSharp { internal partial class BoundLocalFunctionStatement { public BoundBlock? Body { get => BlockBody ?? ExpressionBody; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Text; namespace Microsoft.CodeAnalysis.CSharp { internal partial class BoundLocalFunctionStatement { public BoundBlock? Body { get => BlockBody ?? ExpressionBody; } } }
-1
dotnet/roslyn
55,138
Avoid cancellation exceptions in intermediate operations
Addresses the following exceptions: ![image](https://user-images.githubusercontent.com/1408396/127185947-8a005aea-ae1c-4755-bf0f-21dfb8101352.png)
sharwell
2021-07-27T15:51:28Z
2021-07-27T21:36:45Z
3d8acbd585a75e9cdb3509623bf6c39ceb46b2c2
719d4ffa2be734463e5d7d4d74b23b8006fd7727
Avoid cancellation exceptions in intermediate operations. Addresses the following exceptions: ![image](https://user-images.githubusercontent.com/1408396/127185947-8a005aea-ae1c-4755-bf0f-21dfb8101352.png)
./src/EditorFeatures/CSharpTest/AddUsing/AddUsingTestsWithAddImportDiagnosticProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.AddImport; using Microsoft.CodeAnalysis.CSharp.Diagnostics; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; using Xunit.Abstractions; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.AddUsing { [Trait(Traits.Feature, Traits.Features.CodeActionsAddImport)] public partial class AddUsingTestsWithAddImportDiagnosticProvider : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest { public AddUsingTestsWithAddImportDiagnosticProvider(ITestOutputHelper logger) : base(logger) { } internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace) => (new CSharpUnboundIdentifiersDiagnosticAnalyzer(), new CSharpAddImportCodeFixProvider()); [WorkItem(829970, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/829970")] [Fact] public async Task TestUnknownIdentifierGenericName() { await TestInRegularAndScriptAsync( @"class C { private [|List<int>|] }", @"using System.Collections.Generic; class C { private List<int> }"); } [WorkItem(829970, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/829970")] [Fact] public async Task TestUnknownIdentifierInAttributeSyntaxWithoutTarget() { await TestInRegularAndScriptAsync( @"class C { [[|Extension|]] }", @"using System.Runtime.CompilerServices; class C { [Extension] }"); } [Fact] public async Task TestOutsideOfMethodWithMalformedGenericParameters() { await TestInRegularAndScriptAsync( @"using System; class Program { Func<[|FlowControl|] x }", @"using System; using System.Reflection.Emit; class Program { Func<FlowControl x }"); } [WorkItem(752640, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/752640")] [Fact] public async Task TestUnknownIdentifierWithSyntaxError() { await TestInRegularAndScriptAsync( @"class C { [|Directory|] private int i; }", @"using System.IO; class C { Directory private int i; }"); } [WorkItem(855748, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/855748")] [Fact] public async Task TestGenericNameWithBrackets() { await TestInRegularAndScriptAsync( @"class Class { [|List|] }", @"using System.Collections.Generic; class Class { List }"); await TestInRegularAndScriptAsync( @"class Class { [|List<>|] }", @"using System.Collections.Generic; class Class { List<> }"); await TestInRegularAndScriptAsync( @"class Class { List[|<>|] }", @"using System.Collections.Generic; class Class { List<> }"); } [WorkItem(867496, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/867496")] [Fact] public async Task TestMalformedGenericParameters() { await TestInRegularAndScriptAsync( @"class Class { [|List<|] }", @"using System.Collections.Generic; class Class { List< }"); await TestInRegularAndScriptAsync( @"class Class { [|List<Y x;|] }", @"using System.Collections.Generic; class Class { List<Y x; }"); } [WorkItem(18621, "https://github.com/dotnet/roslyn/issues/18621")] [Fact] public async Task TestIncompleteMemberWithAsyncTaskReturnType() { await TestInRegularAndScriptAsync( @" using System.Collections.Generic; using System.Threading.Tasks; namespace X { class ProjectConfiguration { } } namespace ConsoleApp282 { class Program { public async Task<IReadOnlyCollection<[|ProjectConfiguration|]>> } }", @" using System.Collections.Generic; using System.Threading.Tasks; using X; namespace X { class ProjectConfiguration { } } namespace ConsoleApp282 { class Program { public async Task<IReadOnlyCollection<ProjectConfiguration>> } }"); } [WorkItem(23667, "https://github.com/dotnet/roslyn/issues/23667")] [Fact] public async Task TestMissingDiagnosticForNameOf() { await TestDiagnosticMissingAsync( @"using System; class C { Action action = () => { var x = [|nameof|](System); #warning xxx }; }"); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.AddImport; using Microsoft.CodeAnalysis.CSharp.Diagnostics; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; using Xunit.Abstractions; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.AddUsing { [Trait(Traits.Feature, Traits.Features.CodeActionsAddImport)] public partial class AddUsingTestsWithAddImportDiagnosticProvider : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest { public AddUsingTestsWithAddImportDiagnosticProvider(ITestOutputHelper logger) : base(logger) { } internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace) => (new CSharpUnboundIdentifiersDiagnosticAnalyzer(), new CSharpAddImportCodeFixProvider()); [WorkItem(829970, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/829970")] [Fact] public async Task TestUnknownIdentifierGenericName() { await TestInRegularAndScriptAsync( @"class C { private [|List<int>|] }", @"using System.Collections.Generic; class C { private List<int> }"); } [WorkItem(829970, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/829970")] [Fact] public async Task TestUnknownIdentifierInAttributeSyntaxWithoutTarget() { await TestInRegularAndScriptAsync( @"class C { [[|Extension|]] }", @"using System.Runtime.CompilerServices; class C { [Extension] }"); } [Fact] public async Task TestOutsideOfMethodWithMalformedGenericParameters() { await TestInRegularAndScriptAsync( @"using System; class Program { Func<[|FlowControl|] x }", @"using System; using System.Reflection.Emit; class Program { Func<FlowControl x }"); } [WorkItem(752640, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/752640")] [Fact] public async Task TestUnknownIdentifierWithSyntaxError() { await TestInRegularAndScriptAsync( @"class C { [|Directory|] private int i; }", @"using System.IO; class C { Directory private int i; }"); } [WorkItem(855748, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/855748")] [Fact] public async Task TestGenericNameWithBrackets() { await TestInRegularAndScriptAsync( @"class Class { [|List|] }", @"using System.Collections.Generic; class Class { List }"); await TestInRegularAndScriptAsync( @"class Class { [|List<>|] }", @"using System.Collections.Generic; class Class { List<> }"); await TestInRegularAndScriptAsync( @"class Class { List[|<>|] }", @"using System.Collections.Generic; class Class { List<> }"); } [WorkItem(867496, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/867496")] [Fact] public async Task TestMalformedGenericParameters() { await TestInRegularAndScriptAsync( @"class Class { [|List<|] }", @"using System.Collections.Generic; class Class { List< }"); await TestInRegularAndScriptAsync( @"class Class { [|List<Y x;|] }", @"using System.Collections.Generic; class Class { List<Y x; }"); } [WorkItem(18621, "https://github.com/dotnet/roslyn/issues/18621")] [Fact] public async Task TestIncompleteMemberWithAsyncTaskReturnType() { await TestInRegularAndScriptAsync( @" using System.Collections.Generic; using System.Threading.Tasks; namespace X { class ProjectConfiguration { } } namespace ConsoleApp282 { class Program { public async Task<IReadOnlyCollection<[|ProjectConfiguration|]>> } }", @" using System.Collections.Generic; using System.Threading.Tasks; using X; namespace X { class ProjectConfiguration { } } namespace ConsoleApp282 { class Program { public async Task<IReadOnlyCollection<ProjectConfiguration>> } }"); } [WorkItem(23667, "https://github.com/dotnet/roslyn/issues/23667")] [Fact] public async Task TestMissingDiagnosticForNameOf() { await TestDiagnosticMissingAsync( @"using System; class C { Action action = () => { var x = [|nameof|](System); #warning xxx }; }"); } } }
-1
dotnet/roslyn
55,138
Avoid cancellation exceptions in intermediate operations
Addresses the following exceptions: ![image](https://user-images.githubusercontent.com/1408396/127185947-8a005aea-ae1c-4755-bf0f-21dfb8101352.png)
sharwell
2021-07-27T15:51:28Z
2021-07-27T21:36:45Z
3d8acbd585a75e9cdb3509623bf6c39ceb46b2c2
719d4ffa2be734463e5d7d4d74b23b8006fd7727
Avoid cancellation exceptions in intermediate operations. Addresses the following exceptions: ![image](https://user-images.githubusercontent.com/1408396/127185947-8a005aea-ae1c-4755-bf0f-21dfb8101352.png)
./src/Compilers/CSharp/Test/Emit/CodeGen/GotoTest.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.CodeGen { public class GotoTests : EmitMetadataTestBase { [Fact] public void Goto() { string source = @" using System; public class Program { public static void Main(string[] args) { Console.WriteLine(""goo""); goto bar; Console.Write(""you won't see me""); bar: Console.WriteLine(""bar""); return; } } "; string expectedOutput = @"goo bar "; CompileAndVerify(source, expectedOutput: expectedOutput); } // Identical to last test, but without "return" statement. (This was failing once.) [Fact] public void GotoWithoutReturn() { string source = @" using System; public class Program { public static void Main(string[] args) { Console.WriteLine(""goo""); goto bar; Console.Write(""you won't see me""); bar: Console.WriteLine(""bar""); } } "; string expectedOutput = @"goo bar "; CompileAndVerify(source, expectedOutput: expectedOutput); } // The goto can also be used to jump to a case or default statement in a switch [Fact] public void GotoInSwitch() { var text = @" class C { static void Main(string[] args) { string Fruit = ""Apple""; switch (Fruit) { case ""Banana"": break; case ""Chair"": break; case ""Apple"": goto case ""Banana""; case ""Table"": goto default; default: break; } } } "; CompileAndVerify(text).VerifyIL("C.Main", @" { // Code size 58 (0x3a) .maxstack 2 .locals init (string V_0) //Fruit IL_0000: ldstr ""Apple"" IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: ldstr ""Banana"" IL_000c: call ""bool string.op_Equality(string, string)"" IL_0011: brtrue.s IL_0039 IL_0013: ldloc.0 IL_0014: ldstr ""Chair"" IL_0019: call ""bool string.op_Equality(string, string)"" IL_001e: brtrue.s IL_0039 IL_0020: ldloc.0 IL_0021: ldstr ""Apple"" IL_0026: call ""bool string.op_Equality(string, string)"" IL_002b: brtrue.s IL_0039 IL_002d: ldloc.0 IL_002e: ldstr ""Table"" IL_0033: call ""bool string.op_Equality(string, string)"" IL_0038: pop IL_0039: ret }"); } // Goto location outside enclosing block [WorkItem(527952, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527952")] [Fact] public void LocationOfGotoOutofClosure() { var text = @" class C { static void Main(string[] args) { int i = 0; if (i == 1) goto Lab1; else goto Lab2; Lab1: i = 2; Lab2: i = 3; System.Console.WriteLine(i); } } "; CompileAndVerify(text).VerifyIL("C.Main", @" { // Code size 11 (0xb) .maxstack 2 IL_0000: ldc.i4.0 IL_0001: ldc.i4.1 IL_0002: pop IL_0003: pop IL_0004: ldc.i4.3 IL_0005: call ""void System.Console.WriteLine(int)"" IL_000a: ret }"); } // Goto location in enclosing block [WorkItem(527952, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527952")] [Fact] public void LocationOfGotoInClosure() { var text = @" class C { static void Main(string[] args) { int i = 0; if (i == 1) goto Lab1; else goto Lab2; Lab1: i = 2; Lab2: i = 3; System.Console.WriteLine(i); } } "; CompileAndVerify(text).VerifyIL("C.Main", @" { // Code size 11 (0xb) .maxstack 2 IL_0000: ldc.i4.0 IL_0001: ldc.i4.1 IL_0002: pop IL_0003: pop IL_0004: ldc.i4.3 IL_0005: call ""void System.Console.WriteLine(int)"" IL_000a: ret }"); } // Same label in different scope [WorkItem(539876, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539876")] [Fact] public void SameLabelInDiffScope() { var text = @" class C { static void Main(string[] args) { { Lab1: goto Lab1; } { Lab1: return; } } } "; var c = CompileAndVerify(text); c.VerifyDiagnostics( // (11,9): warning CS0162: Unreachable code detected // Lab1: Diagnostic(ErrorCode.WRN_UnreachableCode, "Lab1"), // (11,9): warning CS0164: This label has not been referenced // Lab1: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "Lab1")); c.VerifyIL("C.Main", @" { // Code size 2 (0x2) .maxstack 0 IL_0000: br.s IL_0000 } "); } // Label Next to Label [WorkItem(539877, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539877")] [Fact] public void LabelNexttoLabel() { var text = @" class C { static void Main(string[] args) { Lab3: // Lab1: goto Lab2; Lab2: goto Lab3; } } "; CompileAndVerify(text).VerifyIL("C.Main", @" { // Code size 2 (0x2) .maxstack 0 IL_0000: br.s IL_0000 } "); } // Infinite loop [WorkItem(527952, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527952")] [Fact] public void Infiniteloop() { var text = @" class C { static void Main(string[] args) { A: goto B; B: goto A; } } "; CompileAndVerify(text).VerifyDiagnostics().VerifyIL("C.Main", @" { // Code size 2 (0x2) .maxstack 0 IL_0000: br.s IL_0000 } "); } // unreachable code [WorkItem(527952, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527952")] [Fact] public void CS0162WRN_UnreachableCode() { var text = @" class C { static void Main(string[] args) { for (int i = 0; i < 5;) { i = 2; goto Lab2; i = 1; break; Lab2: return ; } } } "; var c = CompileAndVerify(text); c.VerifyDiagnostics(Diagnostic(ErrorCode.WRN_UnreachableCode, "i")); c.VerifyIL("C.Main", @" { // Code size 12 (0xc) .maxstack 2 .locals init (int V_0) //i IL_0000: ldc.i4.0 IL_0001: stloc.0 IL_0002: br.s IL_0007 IL_0004: ldc.i4.2 IL_0005: stloc.0 IL_0006: ret IL_0007: ldloc.0 IL_0008: ldc.i4.5 IL_0009: blt.s IL_0004 IL_000b: ret } "); } // Declare variable after goto [WorkItem(527952, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527952")] [Fact] public void DeclareVariableAfterGoto() { var text = @" class C { static void Main(string[] args) { goto label1; string s = ""A""; // unreachable label1: s = ""B""; System.Console.WriteLine(s); } } "; var c = CompileAndVerify(text); c.VerifyDiagnostics(Diagnostic(ErrorCode.WRN_UnreachableCode, "string")); c.VerifyIL("C.Main", @" { // Code size 11 (0xb) .maxstack 1 IL_0000: ldstr ""B"" IL_0005: call ""void System.Console.WriteLine(string)"" IL_000a: ret } "); } // Finally is executed while use 'goto' to exit try block [WorkItem(540721, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540721")] [Fact] public void GotoInTry() { var text = @" class C { static void Main(string[] args) { int i = 0; try { i = 1; goto lab1; } catch { i = 2; } finally { System.Console.WriteLine(""a""); } lab1: System.Console.WriteLine(i); return; } } "; var c = CompileAndVerify(text, expectedOutput: @"a 1"); c.VerifyIL("C.Main", @" { // Code size 29 (0x1d) .maxstack 1 .locals init (int V_0) //i IL_0000: ldc.i4.0 IL_0001: stloc.0 .try { .try { IL_0002: ldc.i4.1 IL_0003: stloc.0 IL_0004: leave.s IL_0016 } catch object { IL_0006: pop IL_0007: ldc.i4.2 IL_0008: stloc.0 IL_0009: leave.s IL_0016 } } finally { IL_000b: ldstr ""a"" IL_0010: call ""void System.Console.WriteLine(string)"" IL_0015: endfinally } IL_0016: ldloc.0 IL_0017: call ""void System.Console.WriteLine(int)"" IL_001c: ret }"); } [WorkItem(540716, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540716")] [Fact] public void GotoInFinallyBlock() { var text = @" class C { static void Main(string[] args) { int i = 0; try { i = 1; } catch { i = 2; } finally { lab1: i = 3; goto lab1; } System.Console.WriteLine(i); } } "; CompileAndVerify(text).VerifyIL("C.Main", @" { // Code size 17 (0x11) .maxstack 1 .locals init (int V_0) //i IL_0000: ldc.i4.0 IL_0001: stloc.0 .try { .try { IL_0002: ldc.i4.1 IL_0003: stloc.0 IL_0004: leave.s IL_000f } catch object { IL_0006: pop IL_0007: ldc.i4.2 IL_0008: stloc.0 IL_0009: leave.s IL_000f } } finally { IL_000b: ldc.i4.3 IL_000c: stloc.0 IL_000d: br.s IL_000b } IL_000f: br.s IL_000f }"); } // Optimization redundant branch for code generate [Fact, WorkItem(527952, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527952")] public void OptimizationForGoto() { var source = @" class C { static int Main(string[] args) { goto Lab1; Lab1: goto Lab2; Lab2: goto Lab3; Lab3: goto Lab4; Lab4: return 0; } } "; var c = CompileAndVerify(source, options: TestOptions.ReleaseDll); c.VerifyIL("C.Main", @" { // Code size 2 (0x2) .maxstack 1 IL_0000: ldc.i4.0 IL_0001: ret } "); } [Fact, WorkItem(528010, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528010")] public void GotoInLambda() { var text = @" delegate int del(int i); class C { static void Main(string[] args) { del q = x => { label2: goto label1; label1: goto label2; }; System.Console.WriteLine(q); } } "; CompileAndVerify(text).VerifyIL("C.Main", @" { // Code size 37 (0x25) .maxstack 2 IL_0000: ldsfld ""del C.<>c.<>9__0_0"" IL_0005: dup IL_0006: brtrue.s IL_001f IL_0008: pop IL_0009: ldsfld ""C.<>c C.<>c.<>9"" IL_000e: ldftn ""int C.<>c.<Main>b__0_0(int)"" IL_0014: newobj ""del..ctor(object, System.IntPtr)"" IL_0019: dup IL_001a: stsfld ""del C.<>c.<>9__0_0"" IL_001f: call ""void System.Console.WriteLine(object)"" IL_0024: ret } "); } // Definition same label in different lambdas [WorkItem(5991, "DevDiv_Projects/Roslyn")] [Fact] public void SameLabelInDiffLambda() { var text = @" delegate int del(int i); class C { static void Main(string[] args) { del q = x => { goto label1; label1: return x * x; }; System.Console.WriteLine(q); del p = x => { goto label1; label1: return x * x; }; System.Console.WriteLine(p); } } "; CompileAndVerify(text).VerifyIL("C.Main", @" { // Code size 73 (0x49) .maxstack 2 IL_0000: ldsfld ""del C.<>c.<>9__0_0"" IL_0005: dup IL_0006: brtrue.s IL_001f IL_0008: pop IL_0009: ldsfld ""C.<>c C.<>c.<>9"" IL_000e: ldftn ""int C.<>c.<Main>b__0_0(int)"" IL_0014: newobj ""del..ctor(object, System.IntPtr)"" IL_0019: dup IL_001a: stsfld ""del C.<>c.<>9__0_0"" IL_001f: call ""void System.Console.WriteLine(object)"" IL_0024: ldsfld ""del C.<>c.<>9__0_1"" IL_0029: dup IL_002a: brtrue.s IL_0043 IL_002c: pop IL_002d: ldsfld ""C.<>c C.<>c.<>9"" IL_0032: ldftn ""int C.<>c.<Main>b__0_1(int)"" IL_0038: newobj ""del..ctor(object, System.IntPtr)"" IL_003d: dup IL_003e: stsfld ""del C.<>c.<>9__0_1"" IL_0043: call ""void System.Console.WriteLine(object)"" IL_0048: ret } "); } // Control is transferred to the target of the goto statement after finally [WorkItem(540720, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540720")] [Fact] public void ControlTransferred() { var text = @" class C { public static void Main() { try { goto Label1; } catch { throw; } finally { Finally(); } Label1: Label(); } private static void Finally() { System.Console.WriteLine(""Finally""); } private static void Label() { System.Console.WriteLine(""Label""); } } "; CompileAndVerify(text, expectedOutput: @" Finally Label "); } // Control is transferred to the target of the goto statement in nested try [WorkItem(540720, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540720")] [Fact] public void ControlTransferred_02() { var text = @" class C { public static void Main() { int i = 0; try { i = 1; try { goto lab1; } catch { throw; } finally { System.Console.WriteLine(""inner finally""); } } catch { i = 2; } finally { System.Console.WriteLine(""outer finally""); } lab1: System.Console.WriteLine(""label""); } } "; CompileAndVerify(text, expectedOutput: @" inner finally outer finally label "); } [Fact] public void ControlTransferred_03() { var text = @" using System.Collections; class C { public static void Main() { foreach (int i in Power(2, 3)) { System.Console.WriteLine(i); } } public static IEnumerable Power(int number, int exponent) { int counter = 0; int result = 1; try { while (counter++ < exponent) { result = result * number; yield return result; } goto Label1; } finally { System.Console.WriteLine(""finally""); } Label1: System.Console.WriteLine(""label""); } } "; string expectedOutput = @"2 4 8 finally label "; CompileAndVerify(text, expectedOutput: expectedOutput); } [WorkItem(540719, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540719")] [Fact] public void LabelBetweenLocalAndInitialize() { var text = @" class C { static void M(int x) { NoInitializers: int w, y; Const1: Const2: const int z = 0; w = z; y = x + w; x = y; } }"; CompileAndVerify(text); } [WorkItem(540719, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540719")] [Fact] public void LabelBetweenLocalAndInitialize02() { var text = @" public class A { public static int Main() { int i = 0; int retVal = 1; try { L: int k; try { i++; goto L; } finally { if (i == 10) throw new System.Exception(); } } catch (System.Exception) { System.Console.Write(""Catch""); retVal = 0; } return retVal; } } "; CompileAndVerify(text, expectedOutput: "Catch"); } [WorkItem(540719, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540719")] [Fact] public void LabelBetweenLocalAndInitialize03() { var text = @" public class A { public static int Main() { int i = 0; int retVal = 1; try { L: { int k; } try { i++; goto L; } finally { if (i == 10) throw new System.Exception(); } } catch (System.Exception) { System.Console.Write(""Catch""); retVal = 0; } return retVal; } } "; CompileAndVerify(text, expectedOutput: "Catch"); } [Fact] public void OutOfScriptBlock() { string source = @"bool b = true; L0: ; { { System.Console.WriteLine(b); if (b) b = !b; else goto L1; goto L0; } L1: ; }"; string expectedOutput = @"True False"; var compilation = CreateCompilationWithMscorlib45(source, references: new[] { SystemCoreRef }, parseOptions: TestOptions.Script, options: TestOptions.DebugExe); CompileAndVerify(compilation, expectedOutput: expectedOutput, verify: Verification.Passes); } [Fact] public void IntoScriptBlock() { string source = @"goto L0; { L0: goto L1; } { L1: ; }"; var compilation = CreateCompilationWithMscorlib45(source, references: new[] { SystemCoreRef }, parseOptions: TestOptions.Script, options: TestOptions.DebugExe); compilation.VerifyDiagnostics( // (1,6): error CS0159: No such label 'L0' within the scope of the goto statement // goto L0; Diagnostic(ErrorCode.ERR_LabelNotFound, "L0").WithArguments("L0").WithLocation(1, 6), // (3,14): error CS0159: No such label 'L1' within the scope of the goto statement // L0: goto L1; Diagnostic(ErrorCode.ERR_LabelNotFound, "L1").WithArguments("L1").WithLocation(3, 14), // (3,5): warning CS0164: This label has not been referenced // L0: goto L1; Diagnostic(ErrorCode.WRN_UnreferencedLabel, "L0").WithLocation(3, 5), // (6,5): warning CS0164: This label has not been referenced // L1: ; Diagnostic(ErrorCode.WRN_UnreferencedLabel, "L1").WithLocation(6, 5)); } [ConditionalFact(typeof(IsRelease), Reason = "https://github.com/dotnet/roslyn/issues/25702")] public void AcrossScriptDeclarations() { string source = @"int P { get; } = G(""P""); L: int F = G(""F""); int Q { get; } = G(""Q""); static int x = 2; static int G(string s) { System.Console.WriteLine(""{0}: {1}"", x, s); x++; return x; } if (Q < 4) goto L;"; string expectedOutput = @"2: P 3: F 4: Q"; var compilation = CreateCompilationWithMscorlib45(source, references: new[] { SystemCoreRef }, parseOptions: TestOptions.Script, options: TestOptions.DebugExe); CompileAndVerify(compilation, expectedOutput: expectedOutput, verify: Verification.Fails); } [Fact] public void AcrossSubmissions() { var references = new[] { MscorlibRef_v4_0_30316_17626, SystemCoreRef }; var source0 = @"bool b = false; L: ; if (b) { goto L; }"; var source1 = @"goto L;"; var s0 = CSharpCompilation.CreateScriptCompilation("s0.dll", SyntaxFactory.ParseSyntaxTree(source0, options: TestOptions.Script), references); s0.VerifyDiagnostics(); var s1 = CSharpCompilation.CreateScriptCompilation("s1.dll", SyntaxFactory.ParseSyntaxTree(source1, options: TestOptions.Script), references, previousScriptCompilation: s0); s1.VerifyDiagnostics( // (1,6): error CS0159: No such label 'L' within the scope of the goto statement // goto L; Diagnostic(ErrorCode.ERR_LabelNotFound, "L").WithArguments("L").WithLocation(1, 6)); } [Fact] public void OutOfScriptMethod() { string source = @"static void F(bool b) { if (b) goto L; } L: F(true);"; var compilation = CreateCompilationWithMscorlib45(source, references: new[] { SystemCoreRef }, parseOptions: TestOptions.Script); compilation.VerifyDiagnostics( // (5,1): warning CS0164: This label has not been referenced // L: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "L").WithLocation(5, 1), // (3,17): error CS0159: No such label 'L' within the scope of the goto statement // if (b) goto L; Diagnostic(ErrorCode.ERR_LabelNotFound, "L").WithArguments("L").WithLocation(3, 17)); } [Fact] public void IntoScriptMethod() { string source = @"static void F() { L: return; } goto L;"; var compilation = CreateCompilationWithMscorlib45(source, references: new[] { SystemCoreRef }, parseOptions: TestOptions.Script); compilation.VerifyDiagnostics( // (6,6): error CS0159: No such label 'L' within the scope of the goto statement // goto L; Diagnostic(ErrorCode.ERR_LabelNotFound, "L").WithArguments("L").WithLocation(6, 6), // (3,1): warning CS0164: This label has not been referenced // L: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "L").WithLocation(3, 1)); } [Fact] public void InScriptSwitch() { string source = @"int x = 3; switch (x) { case 1: break; case 2: System.Console.WriteLine(x); break; default: goto case 2; }"; string expectedOutput = @"3"; var compilation = CreateCompilationWithMscorlib45(source, references: new[] { SystemCoreRef }, parseOptions: TestOptions.Script, options: TestOptions.DebugExe); CompileAndVerify(compilation, expectedOutput: expectedOutput, verify: Verification.Passes); } [Fact] public void DuplicateLabelInScript() { string source = @"bool b = false; L: ; if (b) { goto L; } else { b = !b; if (b) goto L; L: ; }"; var compilation = CreateCompilationWithMscorlib45(source, references: new[] { SystemCoreRef }, parseOptions: TestOptions.Script, options: TestOptions.DebugExe); compilation.VerifyDiagnostics( // (11,1): error CS0158: The label 'L' shadows another label by the same name in a contained scope // L: ; Diagnostic(ErrorCode.ERR_LabelShadow, "L").WithArguments("L").WithLocation(11, 1)); } [Fact] public void DuplicateLabelInSeparateSubmissions() { var references = new[] { MscorlibRef_v4_0_30316_17626, SystemCoreRef }; var source0 = @"bool b = false; L: ; if (b) { goto L; }"; var source1 = @"if (!b) { b = !b; if (b) goto L; L: ; }"; var s0 = CSharpCompilation.CreateScriptCompilation("s0.dll", SyntaxFactory.ParseSyntaxTree(source0, options: TestOptions.Script), references); s0.VerifyDiagnostics(); var s1 = CSharpCompilation.CreateScriptCompilation("s1.dll", SyntaxFactory.ParseSyntaxTree(source1, options: TestOptions.Script), references, previousScriptCompilation: s0); s1.VerifyDiagnostics(); } [Fact] public void LoadedFile() { var sourceA = @"goto A; A: goto B;"; var sourceB = @"#load ""a.csx"" goto B; B: goto A;"; var resolver = TestSourceReferenceResolver.Create(KeyValuePairUtil.Create("a.csx", sourceA)); var options = TestOptions.DebugDll.WithSourceReferenceResolver(resolver); var compilation = CreateCompilationWithMscorlib45(sourceB, options: options, parseOptions: TestOptions.Script); compilation.GetDiagnostics().Verify( // a.csx(2,9): error CS0159: No such label 'B' within the scope of the goto statement // A: goto B; Diagnostic(ErrorCode.ERR_LabelNotFound, "B").WithArguments("B").WithLocation(2, 9), // (3,9): error CS0159: No such label 'A' within the scope of the goto statement // B: goto A; Diagnostic(ErrorCode.ERR_LabelNotFound, "A").WithArguments("A").WithLocation(3, 9)); } [Fact, WorkItem(3712, "https://github.com/dotnet/roslyn/pull/3172")] public void Label_GetDeclaredSymbol_Script() { string source = @"L0: goto L1; static void F() { } L1: goto L0;"; var tree = Parse(source, options: TestOptions.Script); var model = CreateCompilationWithMscorlib45(new[] { tree }).GetSemanticModel(tree, ignoreAccessibility: false); var label = (LabeledStatementSyntax)tree.FindNodeOrTokenByKind(SyntaxKind.LabeledStatement); var symbol = model.GetDeclaredSymbol(label); Assert.Equal("L0", symbol.Name); } [Fact, WorkItem(3712, "https://github.com/dotnet/roslyn/pull/3172")] public void Label_GetDeclaredSymbol_Error_Script() { string source = @" C: \a\b\ "; var tree = Parse(source, options: TestOptions.Script); var model = CreateCompilationWithMscorlib45(new[] { tree }).GetSemanticModel(tree, ignoreAccessibility: false); var label = (LabeledStatementSyntax)tree.FindNodeOrTokenByKind(SyntaxKind.LabeledStatement); var symbol = model.GetDeclaredSymbol(label); Assert.Equal("C", symbol.Name); } [Fact] public void TrailingExpression() { var source = @" goto EOF; EOF:"; var compilation = CreateCompilationWithMscorlib45(source, parseOptions: TestOptions.Script); compilation.GetDiagnostics().Verify( // (3,5): error CS1733: Expected expression // EOF: Diagnostic(ErrorCode.ERR_ExpressionExpected, "").WithLocation(3, 5)); compilation = CreateSubmission(source); compilation.GetDiagnostics().Verify( // (3,5): error CS1733: Expected expression // EOF: Diagnostic(ErrorCode.ERR_ExpressionExpected, "").WithLocation(3, 5)); source = @" goto EOF; EOF: 42"; compilation = CreateCompilationWithMscorlib45(source, parseOptions: TestOptions.Script); compilation.GetDiagnostics().Verify( // (3,8): error CS1002: ; expected // EOF: 42 Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(3, 8)); source = @" var obj = new object(); goto L1; L1: L2: EOF: obj.ToString()"; compilation = CreateCompilationWithMscorlib45(source, parseOptions: TestOptions.Script); compilation.GetDiagnostics().Verify( // (6,20): error CS1002: ; expected // EOF: obj.ToString() Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(6, 20), // (5,1): warning CS0164: This label has not been referenced // L2: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "L2").WithLocation(5, 1), // (6,1): warning CS0164: This label has not been referenced // EOF: obj.ToString() Diagnostic(ErrorCode.WRN_UnreferencedLabel, "EOF").WithLocation(6, 1)); compilation = CreateSubmission(source); compilation.GetDiagnostics().Verify( // (6,20): error CS1002: ; expected // EOF: obj.ToString() Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(6, 20), // (5,1): warning CS0164: This label has not been referenced // L2: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "L2").WithLocation(5, 1), // (6,1): warning CS0164: This label has not been referenced // EOF: obj.ToString() Diagnostic(ErrorCode.WRN_UnreferencedLabel, "EOF").WithLocation(6, 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 Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.CodeGen { public class GotoTests : EmitMetadataTestBase { [Fact] public void Goto() { string source = @" using System; public class Program { public static void Main(string[] args) { Console.WriteLine(""goo""); goto bar; Console.Write(""you won't see me""); bar: Console.WriteLine(""bar""); return; } } "; string expectedOutput = @"goo bar "; CompileAndVerify(source, expectedOutput: expectedOutput); } // Identical to last test, but without "return" statement. (This was failing once.) [Fact] public void GotoWithoutReturn() { string source = @" using System; public class Program { public static void Main(string[] args) { Console.WriteLine(""goo""); goto bar; Console.Write(""you won't see me""); bar: Console.WriteLine(""bar""); } } "; string expectedOutput = @"goo bar "; CompileAndVerify(source, expectedOutput: expectedOutput); } // The goto can also be used to jump to a case or default statement in a switch [Fact] public void GotoInSwitch() { var text = @" class C { static void Main(string[] args) { string Fruit = ""Apple""; switch (Fruit) { case ""Banana"": break; case ""Chair"": break; case ""Apple"": goto case ""Banana""; case ""Table"": goto default; default: break; } } } "; CompileAndVerify(text).VerifyIL("C.Main", @" { // Code size 58 (0x3a) .maxstack 2 .locals init (string V_0) //Fruit IL_0000: ldstr ""Apple"" IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: ldstr ""Banana"" IL_000c: call ""bool string.op_Equality(string, string)"" IL_0011: brtrue.s IL_0039 IL_0013: ldloc.0 IL_0014: ldstr ""Chair"" IL_0019: call ""bool string.op_Equality(string, string)"" IL_001e: brtrue.s IL_0039 IL_0020: ldloc.0 IL_0021: ldstr ""Apple"" IL_0026: call ""bool string.op_Equality(string, string)"" IL_002b: brtrue.s IL_0039 IL_002d: ldloc.0 IL_002e: ldstr ""Table"" IL_0033: call ""bool string.op_Equality(string, string)"" IL_0038: pop IL_0039: ret }"); } // Goto location outside enclosing block [WorkItem(527952, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527952")] [Fact] public void LocationOfGotoOutofClosure() { var text = @" class C { static void Main(string[] args) { int i = 0; if (i == 1) goto Lab1; else goto Lab2; Lab1: i = 2; Lab2: i = 3; System.Console.WriteLine(i); } } "; CompileAndVerify(text).VerifyIL("C.Main", @" { // Code size 11 (0xb) .maxstack 2 IL_0000: ldc.i4.0 IL_0001: ldc.i4.1 IL_0002: pop IL_0003: pop IL_0004: ldc.i4.3 IL_0005: call ""void System.Console.WriteLine(int)"" IL_000a: ret }"); } // Goto location in enclosing block [WorkItem(527952, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527952")] [Fact] public void LocationOfGotoInClosure() { var text = @" class C { static void Main(string[] args) { int i = 0; if (i == 1) goto Lab1; else goto Lab2; Lab1: i = 2; Lab2: i = 3; System.Console.WriteLine(i); } } "; CompileAndVerify(text).VerifyIL("C.Main", @" { // Code size 11 (0xb) .maxstack 2 IL_0000: ldc.i4.0 IL_0001: ldc.i4.1 IL_0002: pop IL_0003: pop IL_0004: ldc.i4.3 IL_0005: call ""void System.Console.WriteLine(int)"" IL_000a: ret }"); } // Same label in different scope [WorkItem(539876, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539876")] [Fact] public void SameLabelInDiffScope() { var text = @" class C { static void Main(string[] args) { { Lab1: goto Lab1; } { Lab1: return; } } } "; var c = CompileAndVerify(text); c.VerifyDiagnostics( // (11,9): warning CS0162: Unreachable code detected // Lab1: Diagnostic(ErrorCode.WRN_UnreachableCode, "Lab1"), // (11,9): warning CS0164: This label has not been referenced // Lab1: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "Lab1")); c.VerifyIL("C.Main", @" { // Code size 2 (0x2) .maxstack 0 IL_0000: br.s IL_0000 } "); } // Label Next to Label [WorkItem(539877, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539877")] [Fact] public void LabelNexttoLabel() { var text = @" class C { static void Main(string[] args) { Lab3: // Lab1: goto Lab2; Lab2: goto Lab3; } } "; CompileAndVerify(text).VerifyIL("C.Main", @" { // Code size 2 (0x2) .maxstack 0 IL_0000: br.s IL_0000 } "); } // Infinite loop [WorkItem(527952, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527952")] [Fact] public void Infiniteloop() { var text = @" class C { static void Main(string[] args) { A: goto B; B: goto A; } } "; CompileAndVerify(text).VerifyDiagnostics().VerifyIL("C.Main", @" { // Code size 2 (0x2) .maxstack 0 IL_0000: br.s IL_0000 } "); } // unreachable code [WorkItem(527952, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527952")] [Fact] public void CS0162WRN_UnreachableCode() { var text = @" class C { static void Main(string[] args) { for (int i = 0; i < 5;) { i = 2; goto Lab2; i = 1; break; Lab2: return ; } } } "; var c = CompileAndVerify(text); c.VerifyDiagnostics(Diagnostic(ErrorCode.WRN_UnreachableCode, "i")); c.VerifyIL("C.Main", @" { // Code size 12 (0xc) .maxstack 2 .locals init (int V_0) //i IL_0000: ldc.i4.0 IL_0001: stloc.0 IL_0002: br.s IL_0007 IL_0004: ldc.i4.2 IL_0005: stloc.0 IL_0006: ret IL_0007: ldloc.0 IL_0008: ldc.i4.5 IL_0009: blt.s IL_0004 IL_000b: ret } "); } // Declare variable after goto [WorkItem(527952, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527952")] [Fact] public void DeclareVariableAfterGoto() { var text = @" class C { static void Main(string[] args) { goto label1; string s = ""A""; // unreachable label1: s = ""B""; System.Console.WriteLine(s); } } "; var c = CompileAndVerify(text); c.VerifyDiagnostics(Diagnostic(ErrorCode.WRN_UnreachableCode, "string")); c.VerifyIL("C.Main", @" { // Code size 11 (0xb) .maxstack 1 IL_0000: ldstr ""B"" IL_0005: call ""void System.Console.WriteLine(string)"" IL_000a: ret } "); } // Finally is executed while use 'goto' to exit try block [WorkItem(540721, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540721")] [Fact] public void GotoInTry() { var text = @" class C { static void Main(string[] args) { int i = 0; try { i = 1; goto lab1; } catch { i = 2; } finally { System.Console.WriteLine(""a""); } lab1: System.Console.WriteLine(i); return; } } "; var c = CompileAndVerify(text, expectedOutput: @"a 1"); c.VerifyIL("C.Main", @" { // Code size 29 (0x1d) .maxstack 1 .locals init (int V_0) //i IL_0000: ldc.i4.0 IL_0001: stloc.0 .try { .try { IL_0002: ldc.i4.1 IL_0003: stloc.0 IL_0004: leave.s IL_0016 } catch object { IL_0006: pop IL_0007: ldc.i4.2 IL_0008: stloc.0 IL_0009: leave.s IL_0016 } } finally { IL_000b: ldstr ""a"" IL_0010: call ""void System.Console.WriteLine(string)"" IL_0015: endfinally } IL_0016: ldloc.0 IL_0017: call ""void System.Console.WriteLine(int)"" IL_001c: ret }"); } [WorkItem(540716, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540716")] [Fact] public void GotoInFinallyBlock() { var text = @" class C { static void Main(string[] args) { int i = 0; try { i = 1; } catch { i = 2; } finally { lab1: i = 3; goto lab1; } System.Console.WriteLine(i); } } "; CompileAndVerify(text).VerifyIL("C.Main", @" { // Code size 17 (0x11) .maxstack 1 .locals init (int V_0) //i IL_0000: ldc.i4.0 IL_0001: stloc.0 .try { .try { IL_0002: ldc.i4.1 IL_0003: stloc.0 IL_0004: leave.s IL_000f } catch object { IL_0006: pop IL_0007: ldc.i4.2 IL_0008: stloc.0 IL_0009: leave.s IL_000f } } finally { IL_000b: ldc.i4.3 IL_000c: stloc.0 IL_000d: br.s IL_000b } IL_000f: br.s IL_000f }"); } // Optimization redundant branch for code generate [Fact, WorkItem(527952, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527952")] public void OptimizationForGoto() { var source = @" class C { static int Main(string[] args) { goto Lab1; Lab1: goto Lab2; Lab2: goto Lab3; Lab3: goto Lab4; Lab4: return 0; } } "; var c = CompileAndVerify(source, options: TestOptions.ReleaseDll); c.VerifyIL("C.Main", @" { // Code size 2 (0x2) .maxstack 1 IL_0000: ldc.i4.0 IL_0001: ret } "); } [Fact, WorkItem(528010, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528010")] public void GotoInLambda() { var text = @" delegate int del(int i); class C { static void Main(string[] args) { del q = x => { label2: goto label1; label1: goto label2; }; System.Console.WriteLine(q); } } "; CompileAndVerify(text).VerifyIL("C.Main", @" { // Code size 37 (0x25) .maxstack 2 IL_0000: ldsfld ""del C.<>c.<>9__0_0"" IL_0005: dup IL_0006: brtrue.s IL_001f IL_0008: pop IL_0009: ldsfld ""C.<>c C.<>c.<>9"" IL_000e: ldftn ""int C.<>c.<Main>b__0_0(int)"" IL_0014: newobj ""del..ctor(object, System.IntPtr)"" IL_0019: dup IL_001a: stsfld ""del C.<>c.<>9__0_0"" IL_001f: call ""void System.Console.WriteLine(object)"" IL_0024: ret } "); } // Definition same label in different lambdas [WorkItem(5991, "DevDiv_Projects/Roslyn")] [Fact] public void SameLabelInDiffLambda() { var text = @" delegate int del(int i); class C { static void Main(string[] args) { del q = x => { goto label1; label1: return x * x; }; System.Console.WriteLine(q); del p = x => { goto label1; label1: return x * x; }; System.Console.WriteLine(p); } } "; CompileAndVerify(text).VerifyIL("C.Main", @" { // Code size 73 (0x49) .maxstack 2 IL_0000: ldsfld ""del C.<>c.<>9__0_0"" IL_0005: dup IL_0006: brtrue.s IL_001f IL_0008: pop IL_0009: ldsfld ""C.<>c C.<>c.<>9"" IL_000e: ldftn ""int C.<>c.<Main>b__0_0(int)"" IL_0014: newobj ""del..ctor(object, System.IntPtr)"" IL_0019: dup IL_001a: stsfld ""del C.<>c.<>9__0_0"" IL_001f: call ""void System.Console.WriteLine(object)"" IL_0024: ldsfld ""del C.<>c.<>9__0_1"" IL_0029: dup IL_002a: brtrue.s IL_0043 IL_002c: pop IL_002d: ldsfld ""C.<>c C.<>c.<>9"" IL_0032: ldftn ""int C.<>c.<Main>b__0_1(int)"" IL_0038: newobj ""del..ctor(object, System.IntPtr)"" IL_003d: dup IL_003e: stsfld ""del C.<>c.<>9__0_1"" IL_0043: call ""void System.Console.WriteLine(object)"" IL_0048: ret } "); } // Control is transferred to the target of the goto statement after finally [WorkItem(540720, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540720")] [Fact] public void ControlTransferred() { var text = @" class C { public static void Main() { try { goto Label1; } catch { throw; } finally { Finally(); } Label1: Label(); } private static void Finally() { System.Console.WriteLine(""Finally""); } private static void Label() { System.Console.WriteLine(""Label""); } } "; CompileAndVerify(text, expectedOutput: @" Finally Label "); } // Control is transferred to the target of the goto statement in nested try [WorkItem(540720, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540720")] [Fact] public void ControlTransferred_02() { var text = @" class C { public static void Main() { int i = 0; try { i = 1; try { goto lab1; } catch { throw; } finally { System.Console.WriteLine(""inner finally""); } } catch { i = 2; } finally { System.Console.WriteLine(""outer finally""); } lab1: System.Console.WriteLine(""label""); } } "; CompileAndVerify(text, expectedOutput: @" inner finally outer finally label "); } [Fact] public void ControlTransferred_03() { var text = @" using System.Collections; class C { public static void Main() { foreach (int i in Power(2, 3)) { System.Console.WriteLine(i); } } public static IEnumerable Power(int number, int exponent) { int counter = 0; int result = 1; try { while (counter++ < exponent) { result = result * number; yield return result; } goto Label1; } finally { System.Console.WriteLine(""finally""); } Label1: System.Console.WriteLine(""label""); } } "; string expectedOutput = @"2 4 8 finally label "; CompileAndVerify(text, expectedOutput: expectedOutput); } [WorkItem(540719, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540719")] [Fact] public void LabelBetweenLocalAndInitialize() { var text = @" class C { static void M(int x) { NoInitializers: int w, y; Const1: Const2: const int z = 0; w = z; y = x + w; x = y; } }"; CompileAndVerify(text); } [WorkItem(540719, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540719")] [Fact] public void LabelBetweenLocalAndInitialize02() { var text = @" public class A { public static int Main() { int i = 0; int retVal = 1; try { L: int k; try { i++; goto L; } finally { if (i == 10) throw new System.Exception(); } } catch (System.Exception) { System.Console.Write(""Catch""); retVal = 0; } return retVal; } } "; CompileAndVerify(text, expectedOutput: "Catch"); } [WorkItem(540719, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540719")] [Fact] public void LabelBetweenLocalAndInitialize03() { var text = @" public class A { public static int Main() { int i = 0; int retVal = 1; try { L: { int k; } try { i++; goto L; } finally { if (i == 10) throw new System.Exception(); } } catch (System.Exception) { System.Console.Write(""Catch""); retVal = 0; } return retVal; } } "; CompileAndVerify(text, expectedOutput: "Catch"); } [Fact] public void OutOfScriptBlock() { string source = @"bool b = true; L0: ; { { System.Console.WriteLine(b); if (b) b = !b; else goto L1; goto L0; } L1: ; }"; string expectedOutput = @"True False"; var compilation = CreateCompilationWithMscorlib45(source, references: new[] { SystemCoreRef }, parseOptions: TestOptions.Script, options: TestOptions.DebugExe); CompileAndVerify(compilation, expectedOutput: expectedOutput, verify: Verification.Passes); } [Fact] public void IntoScriptBlock() { string source = @"goto L0; { L0: goto L1; } { L1: ; }"; var compilation = CreateCompilationWithMscorlib45(source, references: new[] { SystemCoreRef }, parseOptions: TestOptions.Script, options: TestOptions.DebugExe); compilation.VerifyDiagnostics( // (1,6): error CS0159: No such label 'L0' within the scope of the goto statement // goto L0; Diagnostic(ErrorCode.ERR_LabelNotFound, "L0").WithArguments("L0").WithLocation(1, 6), // (3,14): error CS0159: No such label 'L1' within the scope of the goto statement // L0: goto L1; Diagnostic(ErrorCode.ERR_LabelNotFound, "L1").WithArguments("L1").WithLocation(3, 14), // (3,5): warning CS0164: This label has not been referenced // L0: goto L1; Diagnostic(ErrorCode.WRN_UnreferencedLabel, "L0").WithLocation(3, 5), // (6,5): warning CS0164: This label has not been referenced // L1: ; Diagnostic(ErrorCode.WRN_UnreferencedLabel, "L1").WithLocation(6, 5)); } [ConditionalFact(typeof(IsRelease), Reason = "https://github.com/dotnet/roslyn/issues/25702")] public void AcrossScriptDeclarations() { string source = @"int P { get; } = G(""P""); L: int F = G(""F""); int Q { get; } = G(""Q""); static int x = 2; static int G(string s) { System.Console.WriteLine(""{0}: {1}"", x, s); x++; return x; } if (Q < 4) goto L;"; string expectedOutput = @"2: P 3: F 4: Q"; var compilation = CreateCompilationWithMscorlib45(source, references: new[] { SystemCoreRef }, parseOptions: TestOptions.Script, options: TestOptions.DebugExe); CompileAndVerify(compilation, expectedOutput: expectedOutput, verify: Verification.Fails); } [Fact] public void AcrossSubmissions() { var references = new[] { MscorlibRef_v4_0_30316_17626, SystemCoreRef }; var source0 = @"bool b = false; L: ; if (b) { goto L; }"; var source1 = @"goto L;"; var s0 = CSharpCompilation.CreateScriptCompilation("s0.dll", SyntaxFactory.ParseSyntaxTree(source0, options: TestOptions.Script), references); s0.VerifyDiagnostics(); var s1 = CSharpCompilation.CreateScriptCompilation("s1.dll", SyntaxFactory.ParseSyntaxTree(source1, options: TestOptions.Script), references, previousScriptCompilation: s0); s1.VerifyDiagnostics( // (1,6): error CS0159: No such label 'L' within the scope of the goto statement // goto L; Diagnostic(ErrorCode.ERR_LabelNotFound, "L").WithArguments("L").WithLocation(1, 6)); } [Fact] public void OutOfScriptMethod() { string source = @"static void F(bool b) { if (b) goto L; } L: F(true);"; var compilation = CreateCompilationWithMscorlib45(source, references: new[] { SystemCoreRef }, parseOptions: TestOptions.Script); compilation.VerifyDiagnostics( // (5,1): warning CS0164: This label has not been referenced // L: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "L").WithLocation(5, 1), // (3,17): error CS0159: No such label 'L' within the scope of the goto statement // if (b) goto L; Diagnostic(ErrorCode.ERR_LabelNotFound, "L").WithArguments("L").WithLocation(3, 17)); } [Fact] public void IntoScriptMethod() { string source = @"static void F() { L: return; } goto L;"; var compilation = CreateCompilationWithMscorlib45(source, references: new[] { SystemCoreRef }, parseOptions: TestOptions.Script); compilation.VerifyDiagnostics( // (6,6): error CS0159: No such label 'L' within the scope of the goto statement // goto L; Diagnostic(ErrorCode.ERR_LabelNotFound, "L").WithArguments("L").WithLocation(6, 6), // (3,1): warning CS0164: This label has not been referenced // L: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "L").WithLocation(3, 1)); } [Fact] public void InScriptSwitch() { string source = @"int x = 3; switch (x) { case 1: break; case 2: System.Console.WriteLine(x); break; default: goto case 2; }"; string expectedOutput = @"3"; var compilation = CreateCompilationWithMscorlib45(source, references: new[] { SystemCoreRef }, parseOptions: TestOptions.Script, options: TestOptions.DebugExe); CompileAndVerify(compilation, expectedOutput: expectedOutput, verify: Verification.Passes); } [Fact] public void DuplicateLabelInScript() { string source = @"bool b = false; L: ; if (b) { goto L; } else { b = !b; if (b) goto L; L: ; }"; var compilation = CreateCompilationWithMscorlib45(source, references: new[] { SystemCoreRef }, parseOptions: TestOptions.Script, options: TestOptions.DebugExe); compilation.VerifyDiagnostics( // (11,1): error CS0158: The label 'L' shadows another label by the same name in a contained scope // L: ; Diagnostic(ErrorCode.ERR_LabelShadow, "L").WithArguments("L").WithLocation(11, 1)); } [Fact] public void DuplicateLabelInSeparateSubmissions() { var references = new[] { MscorlibRef_v4_0_30316_17626, SystemCoreRef }; var source0 = @"bool b = false; L: ; if (b) { goto L; }"; var source1 = @"if (!b) { b = !b; if (b) goto L; L: ; }"; var s0 = CSharpCompilation.CreateScriptCompilation("s0.dll", SyntaxFactory.ParseSyntaxTree(source0, options: TestOptions.Script), references); s0.VerifyDiagnostics(); var s1 = CSharpCompilation.CreateScriptCompilation("s1.dll", SyntaxFactory.ParseSyntaxTree(source1, options: TestOptions.Script), references, previousScriptCompilation: s0); s1.VerifyDiagnostics(); } [Fact] public void LoadedFile() { var sourceA = @"goto A; A: goto B;"; var sourceB = @"#load ""a.csx"" goto B; B: goto A;"; var resolver = TestSourceReferenceResolver.Create(KeyValuePairUtil.Create("a.csx", sourceA)); var options = TestOptions.DebugDll.WithSourceReferenceResolver(resolver); var compilation = CreateCompilationWithMscorlib45(sourceB, options: options, parseOptions: TestOptions.Script); compilation.GetDiagnostics().Verify( // a.csx(2,9): error CS0159: No such label 'B' within the scope of the goto statement // A: goto B; Diagnostic(ErrorCode.ERR_LabelNotFound, "B").WithArguments("B").WithLocation(2, 9), // (3,9): error CS0159: No such label 'A' within the scope of the goto statement // B: goto A; Diagnostic(ErrorCode.ERR_LabelNotFound, "A").WithArguments("A").WithLocation(3, 9)); } [Fact, WorkItem(3712, "https://github.com/dotnet/roslyn/pull/3172")] public void Label_GetDeclaredSymbol_Script() { string source = @"L0: goto L1; static void F() { } L1: goto L0;"; var tree = Parse(source, options: TestOptions.Script); var model = CreateCompilationWithMscorlib45(new[] { tree }).GetSemanticModel(tree, ignoreAccessibility: false); var label = (LabeledStatementSyntax)tree.FindNodeOrTokenByKind(SyntaxKind.LabeledStatement); var symbol = model.GetDeclaredSymbol(label); Assert.Equal("L0", symbol.Name); } [Fact, WorkItem(3712, "https://github.com/dotnet/roslyn/pull/3172")] public void Label_GetDeclaredSymbol_Error_Script() { string source = @" C: \a\b\ "; var tree = Parse(source, options: TestOptions.Script); var model = CreateCompilationWithMscorlib45(new[] { tree }).GetSemanticModel(tree, ignoreAccessibility: false); var label = (LabeledStatementSyntax)tree.FindNodeOrTokenByKind(SyntaxKind.LabeledStatement); var symbol = model.GetDeclaredSymbol(label); Assert.Equal("C", symbol.Name); } [Fact] public void TrailingExpression() { var source = @" goto EOF; EOF:"; var compilation = CreateCompilationWithMscorlib45(source, parseOptions: TestOptions.Script); compilation.GetDiagnostics().Verify( // (3,5): error CS1733: Expected expression // EOF: Diagnostic(ErrorCode.ERR_ExpressionExpected, "").WithLocation(3, 5)); compilation = CreateSubmission(source); compilation.GetDiagnostics().Verify( // (3,5): error CS1733: Expected expression // EOF: Diagnostic(ErrorCode.ERR_ExpressionExpected, "").WithLocation(3, 5)); source = @" goto EOF; EOF: 42"; compilation = CreateCompilationWithMscorlib45(source, parseOptions: TestOptions.Script); compilation.GetDiagnostics().Verify( // (3,8): error CS1002: ; expected // EOF: 42 Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(3, 8)); source = @" var obj = new object(); goto L1; L1: L2: EOF: obj.ToString()"; compilation = CreateCompilationWithMscorlib45(source, parseOptions: TestOptions.Script); compilation.GetDiagnostics().Verify( // (6,20): error CS1002: ; expected // EOF: obj.ToString() Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(6, 20), // (5,1): warning CS0164: This label has not been referenced // L2: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "L2").WithLocation(5, 1), // (6,1): warning CS0164: This label has not been referenced // EOF: obj.ToString() Diagnostic(ErrorCode.WRN_UnreferencedLabel, "EOF").WithLocation(6, 1)); compilation = CreateSubmission(source); compilation.GetDiagnostics().Verify( // (6,20): error CS1002: ; expected // EOF: obj.ToString() Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(6, 20), // (5,1): warning CS0164: This label has not been referenced // L2: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "L2").WithLocation(5, 1), // (6,1): warning CS0164: This label has not been referenced // EOF: obj.ToString() Diagnostic(ErrorCode.WRN_UnreferencedLabel, "EOF").WithLocation(6, 1)); } } }
-1
dotnet/roslyn
55,138
Avoid cancellation exceptions in intermediate operations
Addresses the following exceptions: ![image](https://user-images.githubusercontent.com/1408396/127185947-8a005aea-ae1c-4755-bf0f-21dfb8101352.png)
sharwell
2021-07-27T15:51:28Z
2021-07-27T21:36:45Z
3d8acbd585a75e9cdb3509623bf6c39ceb46b2c2
719d4ffa2be734463e5d7d4d74b23b8006fd7727
Avoid cancellation exceptions in intermediate operations. Addresses the following exceptions: ![image](https://user-images.githubusercontent.com/1408396/127185947-8a005aea-ae1c-4755-bf0f-21dfb8101352.png)
./src/Compilers/CSharp/Test/IOperation/IOperation/IOperationTests_IAddressOfOperation.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class IOperationTests_IAddressOfOperation : SemanticModelTestBase { [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void AddressOfFlow_01() { string source = @" class C { unsafe void M(int i) /*<bind>*/{ int* p = &i; }/*</bind>*/ }"; var expectedDiagnostics = DiagnosticDescription.None; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [System.Int32* p] Block[B1] - Block Predecessors: [B0] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32*, IsImplicit) (Syntax: 'p = &i') Left: ILocalReferenceOperation: p (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32*, IsImplicit) (Syntax: 'p = &i') Right: IAddressOfOperation (OperationKind.AddressOf, Type: System.Int32*) (Syntax: '&i') Reference: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i') Next (Regular) Block[B2] Leaving: {R1} } Block[B2] - Exit Predecessors: [B1] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics, compilationOptions: TestOptions.UnsafeDebugDll); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void AddressOfFlow_02() { string source = @" struct S2 { unsafe void M(bool x, S2* p1, S2* p2, int* p3) /*<bind>*/ { p3 = &(x ? p1 : p2)->i; }/*</bind>*/ public int i; }"; var expectedDiagnostics = DiagnosticDescription.None; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [1] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'p3') Value: IParameterReferenceOperation: p3 (OperationKind.ParameterReference, Type: System.Int32*) (Syntax: 'p3') Jump if False (Regular) to Block[B3] IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'x') Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'p1') Value: IParameterReferenceOperation: p1 (OperationKind.ParameterReference, Type: S2*) (Syntax: 'p1') Next (Regular) Block[B4] Block[B3] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'p2') Value: IParameterReferenceOperation: p2 (OperationKind.ParameterReference, Type: S2*) (Syntax: 'p2') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B2] [B3] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'p3 = &(x ? p1 : p2)->i;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32*) (Syntax: 'p3 = &(x ? p1 : p2)->i') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32*, IsImplicit) (Syntax: 'p3') Right: IAddressOfOperation (OperationKind.AddressOf, Type: System.Int32*) (Syntax: '&(x ? p1 : p2)->i') Reference: IFieldReferenceOperation: System.Int32 S2.i (OperationKind.FieldReference, Type: System.Int32) (Syntax: '(x ? p1 : p2)->i') Instance Receiver: IOperation: (OperationKind.None, Type: null, IsImplicit) (Syntax: '(x ? p1 : p2)') Children(1): IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: S2*, IsImplicit) (Syntax: 'x ? p1 : p2') Next (Regular) Block[B5] Leaving: {R1} } Block[B5] - Exit Predecessors: [B4] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics, TestOptions.UnsafeDebugDll); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class IOperationTests_IAddressOfOperation : SemanticModelTestBase { [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void AddressOfFlow_01() { string source = @" class C { unsafe void M(int i) /*<bind>*/{ int* p = &i; }/*</bind>*/ }"; var expectedDiagnostics = DiagnosticDescription.None; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [System.Int32* p] Block[B1] - Block Predecessors: [B0] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32*, IsImplicit) (Syntax: 'p = &i') Left: ILocalReferenceOperation: p (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32*, IsImplicit) (Syntax: 'p = &i') Right: IAddressOfOperation (OperationKind.AddressOf, Type: System.Int32*) (Syntax: '&i') Reference: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i') Next (Regular) Block[B2] Leaving: {R1} } Block[B2] - Exit Predecessors: [B1] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics, compilationOptions: TestOptions.UnsafeDebugDll); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void AddressOfFlow_02() { string source = @" struct S2 { unsafe void M(bool x, S2* p1, S2* p2, int* p3) /*<bind>*/ { p3 = &(x ? p1 : p2)->i; }/*</bind>*/ public int i; }"; var expectedDiagnostics = DiagnosticDescription.None; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [1] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'p3') Value: IParameterReferenceOperation: p3 (OperationKind.ParameterReference, Type: System.Int32*) (Syntax: 'p3') Jump if False (Regular) to Block[B3] IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'x') Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'p1') Value: IParameterReferenceOperation: p1 (OperationKind.ParameterReference, Type: S2*) (Syntax: 'p1') Next (Regular) Block[B4] Block[B3] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'p2') Value: IParameterReferenceOperation: p2 (OperationKind.ParameterReference, Type: S2*) (Syntax: 'p2') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B2] [B3] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'p3 = &(x ? p1 : p2)->i;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32*) (Syntax: 'p3 = &(x ? p1 : p2)->i') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32*, IsImplicit) (Syntax: 'p3') Right: IAddressOfOperation (OperationKind.AddressOf, Type: System.Int32*) (Syntax: '&(x ? p1 : p2)->i') Reference: IFieldReferenceOperation: System.Int32 S2.i (OperationKind.FieldReference, Type: System.Int32) (Syntax: '(x ? p1 : p2)->i') Instance Receiver: IOperation: (OperationKind.None, Type: null, IsImplicit) (Syntax: '(x ? p1 : p2)') Children(1): IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: S2*, IsImplicit) (Syntax: 'x ? p1 : p2') Next (Regular) Block[B5] Leaving: {R1} } Block[B5] - Exit Predecessors: [B4] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics, TestOptions.UnsafeDebugDll); } } }
-1
dotnet/roslyn
55,138
Avoid cancellation exceptions in intermediate operations
Addresses the following exceptions: ![image](https://user-images.githubusercontent.com/1408396/127185947-8a005aea-ae1c-4755-bf0f-21dfb8101352.png)
sharwell
2021-07-27T15:51:28Z
2021-07-27T21:36:45Z
3d8acbd585a75e9cdb3509623bf6c39ceb46b2c2
719d4ffa2be734463e5d7d4d74b23b8006fd7727
Avoid cancellation exceptions in intermediate operations. Addresses the following exceptions: ![image](https://user-images.githubusercontent.com/1408396/127185947-8a005aea-ae1c-4755-bf0f-21dfb8101352.png)
./src/Compilers/Core/Portable/DiagnosticAnalyzer/SymbolDeclaredCompilationEvent.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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; namespace Microsoft.CodeAnalysis.Diagnostics { /// <summary> /// An event for each declaration in the program (namespace, type, method, field, parameter, etc). /// Note that some symbols may have multiple declarations (namespaces, partial types) and may therefore /// have multiple events. /// </summary> internal sealed class SymbolDeclaredCompilationEvent : CompilationEvent { private readonly Lazy<ImmutableArray<SyntaxReference>> _lazyCachedDeclaringReferences; public SymbolDeclaredCompilationEvent(Compilation compilation, ISymbol symbol, SemanticModel? semanticModelWithCachedBoundNodes = null) : base(compilation) { Symbol = symbol; SemanticModelWithCachedBoundNodes = semanticModelWithCachedBoundNodes; _lazyCachedDeclaringReferences = new Lazy<ImmutableArray<SyntaxReference>>(() => symbol.DeclaringSyntaxReferences); } public ISymbol Symbol { get; } public SemanticModel? SemanticModelWithCachedBoundNodes { get; } // PERF: We avoid allocations in re-computing syntax references for declared symbol during event processing by caching them directly on this member. public ImmutableArray<SyntaxReference> DeclaringSyntaxReferences => _lazyCachedDeclaringReferences.Value; public override string ToString() { var name = Symbol.Name; if (name == "") name = "<empty>"; var loc = DeclaringSyntaxReferences.Length != 0 ? " @ " + string.Join(", ", System.Linq.Enumerable.Select(DeclaringSyntaxReferences, r => r.GetLocation().GetLineSpan())) : null; return "SymbolDeclaredCompilationEvent(" + name + " " + Symbol.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat) + loc + ")"; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .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; namespace Microsoft.CodeAnalysis.Diagnostics { /// <summary> /// An event for each declaration in the program (namespace, type, method, field, parameter, etc). /// Note that some symbols may have multiple declarations (namespaces, partial types) and may therefore /// have multiple events. /// </summary> internal sealed class SymbolDeclaredCompilationEvent : CompilationEvent { private readonly Lazy<ImmutableArray<SyntaxReference>> _lazyCachedDeclaringReferences; public SymbolDeclaredCompilationEvent(Compilation compilation, ISymbol symbol, SemanticModel? semanticModelWithCachedBoundNodes = null) : base(compilation) { Symbol = symbol; SemanticModelWithCachedBoundNodes = semanticModelWithCachedBoundNodes; _lazyCachedDeclaringReferences = new Lazy<ImmutableArray<SyntaxReference>>(() => symbol.DeclaringSyntaxReferences); } public ISymbol Symbol { get; } public SemanticModel? SemanticModelWithCachedBoundNodes { get; } // PERF: We avoid allocations in re-computing syntax references for declared symbol during event processing by caching them directly on this member. public ImmutableArray<SyntaxReference> DeclaringSyntaxReferences => _lazyCachedDeclaringReferences.Value; public override string ToString() { var name = Symbol.Name; if (name == "") name = "<empty>"; var loc = DeclaringSyntaxReferences.Length != 0 ? " @ " + string.Join(", ", System.Linq.Enumerable.Select(DeclaringSyntaxReferences, r => r.GetLocation().GetLineSpan())) : null; return "SymbolDeclaredCompilationEvent(" + name + " " + Symbol.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat) + loc + ")"; } } }
-1
dotnet/roslyn
55,138
Avoid cancellation exceptions in intermediate operations
Addresses the following exceptions: ![image](https://user-images.githubusercontent.com/1408396/127185947-8a005aea-ae1c-4755-bf0f-21dfb8101352.png)
sharwell
2021-07-27T15:51:28Z
2021-07-27T21:36:45Z
3d8acbd585a75e9cdb3509623bf6c39ceb46b2c2
719d4ffa2be734463e5d7d4d74b23b8006fd7727
Avoid cancellation exceptions in intermediate operations. Addresses the following exceptions: ![image](https://user-images.githubusercontent.com/1408396/127185947-8a005aea-ae1c-4755-bf0f-21dfb8101352.png)
./src/VisualStudio/CSharp/Impl/LanguageService/CSharpLanguageService_ICSharpProjectHost.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.IO; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Host; using Microsoft.VisualStudio.LanguageServices.CSharp.ProjectSystemShim; using Microsoft.VisualStudio.LanguageServices.CSharp.ProjectSystemShim.Interop; using Microsoft.VisualStudio.LanguageServices.Implementation.TaskList; using Microsoft.VisualStudio.Shell.Interop; namespace Microsoft.VisualStudio.LanguageServices.CSharp.LanguageService { internal partial class CSharpLanguageService : ICSharpProjectHost { public void BindToProject(ICSharpProjectRoot projectRoot, IVsHierarchy hierarchy) { var projectName = Path.GetFileName(projectRoot.GetFullProjectName()); // GetFullProjectName returns the path to the project file w/o the extension? var project = new CSharpProjectShim( projectRoot, projectName, hierarchy, this.SystemServiceProvider, this.Package.ComponentModel.GetService<IThreadingContext>()); projectRoot.SetProjectSite(project); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.IO; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Host; using Microsoft.VisualStudio.LanguageServices.CSharp.ProjectSystemShim; using Microsoft.VisualStudio.LanguageServices.CSharp.ProjectSystemShim.Interop; using Microsoft.VisualStudio.LanguageServices.Implementation.TaskList; using Microsoft.VisualStudio.Shell.Interop; namespace Microsoft.VisualStudio.LanguageServices.CSharp.LanguageService { internal partial class CSharpLanguageService : ICSharpProjectHost { public void BindToProject(ICSharpProjectRoot projectRoot, IVsHierarchy hierarchy) { var projectName = Path.GetFileName(projectRoot.GetFullProjectName()); // GetFullProjectName returns the path to the project file w/o the extension? var project = new CSharpProjectShim( projectRoot, projectName, hierarchy, this.SystemServiceProvider, this.Package.ComponentModel.GetService<IThreadingContext>()); projectRoot.SetProjectSite(project); } } }
-1
dotnet/roslyn
55,138
Avoid cancellation exceptions in intermediate operations
Addresses the following exceptions: ![image](https://user-images.githubusercontent.com/1408396/127185947-8a005aea-ae1c-4755-bf0f-21dfb8101352.png)
sharwell
2021-07-27T15:51:28Z
2021-07-27T21:36:45Z
3d8acbd585a75e9cdb3509623bf6c39ceb46b2c2
719d4ffa2be734463e5d7d4d74b23b8006fd7727
Avoid cancellation exceptions in intermediate operations. Addresses the following exceptions: ![image](https://user-images.githubusercontent.com/1408396/127185947-8a005aea-ae1c-4755-bf0f-21dfb8101352.png)
./src/VisualStudio/Core/Def/Implementation/TableDataSource/AbstractTableDataSource.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.VisualStudio.Shell.TableManager; using Microsoft.VisualStudio.Text; using Roslyn.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.TableDataSource { /// <summary> /// Base implementation of ITableDataSource /// </summary> internal abstract class AbstractTableDataSource<TItem, TData> : ITableDataSource where TItem : TableItem { private readonly object _gate; // This map holds aggregation key to factory // Any data that shares same aggregation key will de-duplicated to same factory private readonly Dictionary<object, TableEntriesFactory<TItem, TData>> _map; // This map holds each data source key to its aggregation key private readonly Dictionary<object, object> _aggregateKeyMap; private ImmutableArray<SubscriptionWithoutLock> _subscriptions; protected bool IsStable; public AbstractTableDataSource(Workspace workspace) { _gate = new object(); _map = new Dictionary<object, TableEntriesFactory<TItem, TData>>(); _aggregateKeyMap = new Dictionary<object, object>(); _subscriptions = ImmutableArray<SubscriptionWithoutLock>.Empty; Workspace = workspace; IsStable = true; } public Workspace Workspace { get; } public abstract string DisplayName { get; } public abstract string SourceTypeIdentifier { get; } public abstract string Identifier { get; } public void RefreshAllFactories() { ImmutableArray<SubscriptionWithoutLock> snapshot; List<TableEntriesFactory<TItem, TData>> factories; lock (_gate) { snapshot = _subscriptions; factories = _map.Values.ToList(); } // let table manager know that we want to refresh factories. for (var i = 0; i < snapshot.Length; i++) { foreach (var factory in factories) { factory.OnRefreshed(); snapshot[i].AddOrUpdate(factory, newFactory: false); } } } public void Refresh(TableEntriesFactory<TItem, TData> factory) { var snapshot = _subscriptions; for (var i = 0; i < snapshot.Length; i++) { snapshot[i].AddOrUpdate(factory, newFactory: false); } } public void Shutdown() { // editor team wants us to update snapshot versions before // removing factories on shutdown. RefreshAllFactories(); // and then remove all factories. ImmutableArray<SubscriptionWithoutLock> snapshot; lock (_gate) { snapshot = _subscriptions; _map.Clear(); } // let table manager know that we want to clear all factories for (var i = 0; i < snapshot.Length; i++) { snapshot[i].RemoveAll(); } } public ImmutableArray<TItem> AggregateItems<TKey>(IEnumerable<IGrouping<TKey, TItem>> groupedItems) { using var _0 = ArrayBuilder<TItem>.GetInstance(out var aggregateItems); using var _1 = ArrayBuilder<string>.GetInstance(out var projectNames); using var _2 = ArrayBuilder<Guid>.GetInstance(out var projectGuids); string[] stringArrayCache = null; Guid[] guidArrayCache = null; static T[] GetOrCreateArray<T>(ref T[] cache, ArrayBuilder<T> value) => (cache != null && Enumerable.SequenceEqual(cache, value)) ? cache : (cache = value.ToArray()); foreach (var (_, items) in groupedItems) { TItem firstItem = null; var hasSingle = true; foreach (var item in items) { if (firstItem == null) { firstItem = item; } else { hasSingle = false; } if (item.ProjectName != null) { projectNames.Add(item.ProjectName); } if (item.ProjectGuid != Guid.Empty) { projectGuids.Add(item.ProjectGuid); } } if (hasSingle) { aggregateItems.Add(firstItem); } else { projectNames.SortAndRemoveDuplicates(StringComparer.Ordinal); projectGuids.SortAndRemoveDuplicates(Comparer<Guid>.Default); aggregateItems.Add((TItem)firstItem.WithAggregatedData(GetOrCreateArray(ref stringArrayCache, projectNames), GetOrCreateArray(ref guidArrayCache, projectGuids))); } projectNames.Clear(); projectGuids.Clear(); } return Order(aggregateItems).ToImmutableArray(); } public abstract IEqualityComparer<TItem> GroupingComparer { get; } public abstract IEnumerable<TItem> Order(IEnumerable<TItem> groupedItems); public abstract AbstractTableEntriesSnapshot<TItem> CreateSnapshot(AbstractTableEntriesSource<TItem> source, int version, ImmutableArray<TItem> items, ImmutableArray<ITrackingPoint> trackingPoints); /// <summary> /// Get unique ID per given data such as DiagnosticUpdatedArgs or TodoUpdatedArgs. /// Data contains multiple items belong to one logical chunk. and the Id represents this particular /// chunk of the data /// </summary> public abstract object GetItemKey(TData data); /// <summary> /// Create TableEntriesSource for the given data. /// </summary> public abstract AbstractTableEntriesSource<TItem> CreateTableEntriesSource(object data); /// <summary> /// Get unique ID for given data that will be used to find data whose items needed to be merged together. /// /// for example, for linked files, data that belong to same physical file will be gathered and items that belong to /// those data will be de-duplicated. /// </summary> protected abstract object GetOrUpdateAggregationKey(TData data); protected void OnDataAddedOrChanged(TData data) { // reuse factory. it is okay to re-use factory since we make sure we remove the factory before // adding it back ImmutableArray<SubscriptionWithoutLock> snapshot; lock (_gate) { snapshot = _subscriptions; GetOrCreateFactory_NoLock(data, out var factory, out var newFactory); factory.OnDataAddedOrChanged(data); NotifySubscriptionOnDataAddedOrChanged_NoLock(snapshot, factory, newFactory); } } protected void OnDataRemoved(TData data) { lock (_gate) { RemoveStaledData(data); } } protected void RemoveStaledData(TData data) { OnDataRemoved_NoLock(data); RemoveAggregateKey_NoLock(data); } private void OnDataRemoved_NoLock(TData data) { ImmutableArray<SubscriptionWithoutLock> snapshot; var key = TryGetAggregateKey(data); if (key == null) { // never created before. return; } snapshot = _subscriptions; if (!_map.TryGetValue(key, out var factory)) { // never reported about this before return; } // remove this particular item from map if (!factory.OnDataRemoved(data)) { // let error list know that factory has changed. NotifySubscriptionOnDataAddedOrChanged_NoLock(snapshot, factory, newFactory: false); return; } // everything belong to the factory has removed. remove the factory _map.Remove(key); // let table manager know that we want to clear the entries NotifySubscriptionOnDataRemoved_NoLock(snapshot, factory); } private static void NotifySubscriptionOnDataAddedOrChanged_NoLock(ImmutableArray<SubscriptionWithoutLock> snapshot, TableEntriesFactory<TItem, TData> factory, bool newFactory) { for (var i = 0; i < snapshot.Length; i++) { snapshot[i].AddOrUpdate(factory, newFactory); } } private static void NotifySubscriptionOnDataRemoved_NoLock(ImmutableArray<SubscriptionWithoutLock> snapshot, TableEntriesFactory<TItem, TData> factory) { for (var i = 0; i < snapshot.Length; i++) { snapshot[i].Remove(factory); } } private void GetOrCreateFactory_NoLock(TData data, out TableEntriesFactory<TItem, TData> factory, out bool newFactory) { newFactory = false; var key = GetOrUpdateAggregationKey(data); if (_map.TryGetValue(key, out factory)) { return; } var source = CreateTableEntriesSource(data); factory = new TableEntriesFactory<TItem, TData>(this, source); _map.Add(key, factory); newFactory = true; } protected void ChangeStableState(bool stable) { ImmutableArray<SubscriptionWithoutLock> snapshot; lock (_gate) { snapshot = _subscriptions; } for (var i = 0; i < snapshot.Length; i++) { snapshot[i].IsStable = stable; } } protected void AddAggregateKey(TData data, object aggregateKey) => _aggregateKeyMap.Add(GetItemKey(data), aggregateKey); protected object TryGetAggregateKey(TData data) { var key = GetItemKey(data); if (_aggregateKeyMap.TryGetValue(key, out var aggregateKey)) { return aggregateKey; } return null; } private void RemoveAggregateKey_NoLock(TData data) => _aggregateKeyMap.Remove(GetItemKey(data)); IDisposable ITableDataSource.Subscribe(ITableDataSink sink) { lock (_gate) { return new SubscriptionWithoutLock(this, sink); } } internal int NumberOfSubscription_TestOnly { get { return _subscriptions.Length; } } protected class SubscriptionWithoutLock : IDisposable { private readonly AbstractTableDataSource<TItem, TData> _source; private readonly ITableDataSink _sink; public SubscriptionWithoutLock(AbstractTableDataSource<TItem, TData> source, ITableDataSink sink) { _source = source; _sink = sink; Register(); ReportInitialData(); } public bool IsStable { get { return _sink.IsStable; } set { _sink.IsStable = value; } } public void AddOrUpdate(ITableEntriesSnapshotFactory provider, bool newFactory) { if (newFactory) { _sink.AddFactory(provider); return; } _sink.FactorySnapshotChanged(provider); } public void Remove(ITableEntriesSnapshotFactory factory) => _sink.RemoveFactory(factory); public void RemoveAll() => _sink.RemoveAllFactories(); public void Dispose() { // REVIEW: will closing task hub dispose this subscription? UnRegister(); } private void ReportInitialData() { foreach (var provider in _source._map.Values) { AddOrUpdate(provider, newFactory: true); } IsStable = _source.IsStable; } private void Register() => UpdateSubscriptions(s => s.Add(this)); private void UnRegister() => UpdateSubscriptions(s => s.Remove(this)); private void UpdateSubscriptions(Func<ImmutableArray<SubscriptionWithoutLock>, ImmutableArray<SubscriptionWithoutLock>> update) { while (true) { var current = _source._subscriptions; var @new = update(current); // try replace with new list var registered = ImmutableInterlocked.InterlockedCompareExchange(ref _source._subscriptions, @new, current); if (registered == current) { // succeeded break; } } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.VisualStudio.Shell.TableManager; using Microsoft.VisualStudio.Text; using Roslyn.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.TableDataSource { /// <summary> /// Base implementation of ITableDataSource /// </summary> internal abstract class AbstractTableDataSource<TItem, TData> : ITableDataSource where TItem : TableItem { private readonly object _gate; // This map holds aggregation key to factory // Any data that shares same aggregation key will de-duplicated to same factory private readonly Dictionary<object, TableEntriesFactory<TItem, TData>> _map; // This map holds each data source key to its aggregation key private readonly Dictionary<object, object> _aggregateKeyMap; private ImmutableArray<SubscriptionWithoutLock> _subscriptions; protected bool IsStable; public AbstractTableDataSource(Workspace workspace) { _gate = new object(); _map = new Dictionary<object, TableEntriesFactory<TItem, TData>>(); _aggregateKeyMap = new Dictionary<object, object>(); _subscriptions = ImmutableArray<SubscriptionWithoutLock>.Empty; Workspace = workspace; IsStable = true; } public Workspace Workspace { get; } public abstract string DisplayName { get; } public abstract string SourceTypeIdentifier { get; } public abstract string Identifier { get; } public void RefreshAllFactories() { ImmutableArray<SubscriptionWithoutLock> snapshot; List<TableEntriesFactory<TItem, TData>> factories; lock (_gate) { snapshot = _subscriptions; factories = _map.Values.ToList(); } // let table manager know that we want to refresh factories. for (var i = 0; i < snapshot.Length; i++) { foreach (var factory in factories) { factory.OnRefreshed(); snapshot[i].AddOrUpdate(factory, newFactory: false); } } } public void Refresh(TableEntriesFactory<TItem, TData> factory) { var snapshot = _subscriptions; for (var i = 0; i < snapshot.Length; i++) { snapshot[i].AddOrUpdate(factory, newFactory: false); } } public void Shutdown() { // editor team wants us to update snapshot versions before // removing factories on shutdown. RefreshAllFactories(); // and then remove all factories. ImmutableArray<SubscriptionWithoutLock> snapshot; lock (_gate) { snapshot = _subscriptions; _map.Clear(); } // let table manager know that we want to clear all factories for (var i = 0; i < snapshot.Length; i++) { snapshot[i].RemoveAll(); } } public ImmutableArray<TItem> AggregateItems<TKey>(IEnumerable<IGrouping<TKey, TItem>> groupedItems) { using var _0 = ArrayBuilder<TItem>.GetInstance(out var aggregateItems); using var _1 = ArrayBuilder<string>.GetInstance(out var projectNames); using var _2 = ArrayBuilder<Guid>.GetInstance(out var projectGuids); string[] stringArrayCache = null; Guid[] guidArrayCache = null; static T[] GetOrCreateArray<T>(ref T[] cache, ArrayBuilder<T> value) => (cache != null && Enumerable.SequenceEqual(cache, value)) ? cache : (cache = value.ToArray()); foreach (var (_, items) in groupedItems) { TItem firstItem = null; var hasSingle = true; foreach (var item in items) { if (firstItem == null) { firstItem = item; } else { hasSingle = false; } if (item.ProjectName != null) { projectNames.Add(item.ProjectName); } if (item.ProjectGuid != Guid.Empty) { projectGuids.Add(item.ProjectGuid); } } if (hasSingle) { aggregateItems.Add(firstItem); } else { projectNames.SortAndRemoveDuplicates(StringComparer.Ordinal); projectGuids.SortAndRemoveDuplicates(Comparer<Guid>.Default); aggregateItems.Add((TItem)firstItem.WithAggregatedData(GetOrCreateArray(ref stringArrayCache, projectNames), GetOrCreateArray(ref guidArrayCache, projectGuids))); } projectNames.Clear(); projectGuids.Clear(); } return Order(aggregateItems).ToImmutableArray(); } public abstract IEqualityComparer<TItem> GroupingComparer { get; } public abstract IEnumerable<TItem> Order(IEnumerable<TItem> groupedItems); public abstract AbstractTableEntriesSnapshot<TItem> CreateSnapshot(AbstractTableEntriesSource<TItem> source, int version, ImmutableArray<TItem> items, ImmutableArray<ITrackingPoint> trackingPoints); /// <summary> /// Get unique ID per given data such as DiagnosticUpdatedArgs or TodoUpdatedArgs. /// Data contains multiple items belong to one logical chunk. and the Id represents this particular /// chunk of the data /// </summary> public abstract object GetItemKey(TData data); /// <summary> /// Create TableEntriesSource for the given data. /// </summary> public abstract AbstractTableEntriesSource<TItem> CreateTableEntriesSource(object data); /// <summary> /// Get unique ID for given data that will be used to find data whose items needed to be merged together. /// /// for example, for linked files, data that belong to same physical file will be gathered and items that belong to /// those data will be de-duplicated. /// </summary> protected abstract object GetOrUpdateAggregationKey(TData data); protected void OnDataAddedOrChanged(TData data) { // reuse factory. it is okay to re-use factory since we make sure we remove the factory before // adding it back ImmutableArray<SubscriptionWithoutLock> snapshot; lock (_gate) { snapshot = _subscriptions; GetOrCreateFactory_NoLock(data, out var factory, out var newFactory); factory.OnDataAddedOrChanged(data); NotifySubscriptionOnDataAddedOrChanged_NoLock(snapshot, factory, newFactory); } } protected void OnDataRemoved(TData data) { lock (_gate) { RemoveStaledData(data); } } protected void RemoveStaledData(TData data) { OnDataRemoved_NoLock(data); RemoveAggregateKey_NoLock(data); } private void OnDataRemoved_NoLock(TData data) { ImmutableArray<SubscriptionWithoutLock> snapshot; var key = TryGetAggregateKey(data); if (key == null) { // never created before. return; } snapshot = _subscriptions; if (!_map.TryGetValue(key, out var factory)) { // never reported about this before return; } // remove this particular item from map if (!factory.OnDataRemoved(data)) { // let error list know that factory has changed. NotifySubscriptionOnDataAddedOrChanged_NoLock(snapshot, factory, newFactory: false); return; } // everything belong to the factory has removed. remove the factory _map.Remove(key); // let table manager know that we want to clear the entries NotifySubscriptionOnDataRemoved_NoLock(snapshot, factory); } private static void NotifySubscriptionOnDataAddedOrChanged_NoLock(ImmutableArray<SubscriptionWithoutLock> snapshot, TableEntriesFactory<TItem, TData> factory, bool newFactory) { for (var i = 0; i < snapshot.Length; i++) { snapshot[i].AddOrUpdate(factory, newFactory); } } private static void NotifySubscriptionOnDataRemoved_NoLock(ImmutableArray<SubscriptionWithoutLock> snapshot, TableEntriesFactory<TItem, TData> factory) { for (var i = 0; i < snapshot.Length; i++) { snapshot[i].Remove(factory); } } private void GetOrCreateFactory_NoLock(TData data, out TableEntriesFactory<TItem, TData> factory, out bool newFactory) { newFactory = false; var key = GetOrUpdateAggregationKey(data); if (_map.TryGetValue(key, out factory)) { return; } var source = CreateTableEntriesSource(data); factory = new TableEntriesFactory<TItem, TData>(this, source); _map.Add(key, factory); newFactory = true; } protected void ChangeStableState(bool stable) { ImmutableArray<SubscriptionWithoutLock> snapshot; lock (_gate) { snapshot = _subscriptions; } for (var i = 0; i < snapshot.Length; i++) { snapshot[i].IsStable = stable; } } protected void AddAggregateKey(TData data, object aggregateKey) => _aggregateKeyMap.Add(GetItemKey(data), aggregateKey); protected object TryGetAggregateKey(TData data) { var key = GetItemKey(data); if (_aggregateKeyMap.TryGetValue(key, out var aggregateKey)) { return aggregateKey; } return null; } private void RemoveAggregateKey_NoLock(TData data) => _aggregateKeyMap.Remove(GetItemKey(data)); IDisposable ITableDataSource.Subscribe(ITableDataSink sink) { lock (_gate) { return new SubscriptionWithoutLock(this, sink); } } internal int NumberOfSubscription_TestOnly { get { return _subscriptions.Length; } } protected class SubscriptionWithoutLock : IDisposable { private readonly AbstractTableDataSource<TItem, TData> _source; private readonly ITableDataSink _sink; public SubscriptionWithoutLock(AbstractTableDataSource<TItem, TData> source, ITableDataSink sink) { _source = source; _sink = sink; Register(); ReportInitialData(); } public bool IsStable { get { return _sink.IsStable; } set { _sink.IsStable = value; } } public void AddOrUpdate(ITableEntriesSnapshotFactory provider, bool newFactory) { if (newFactory) { _sink.AddFactory(provider); return; } _sink.FactorySnapshotChanged(provider); } public void Remove(ITableEntriesSnapshotFactory factory) => _sink.RemoveFactory(factory); public void RemoveAll() => _sink.RemoveAllFactories(); public void Dispose() { // REVIEW: will closing task hub dispose this subscription? UnRegister(); } private void ReportInitialData() { foreach (var provider in _source._map.Values) { AddOrUpdate(provider, newFactory: true); } IsStable = _source.IsStable; } private void Register() => UpdateSubscriptions(s => s.Add(this)); private void UnRegister() => UpdateSubscriptions(s => s.Remove(this)); private void UpdateSubscriptions(Func<ImmutableArray<SubscriptionWithoutLock>, ImmutableArray<SubscriptionWithoutLock>> update) { while (true) { var current = _source._subscriptions; var @new = update(current); // try replace with new list var registered = ImmutableInterlocked.InterlockedCompareExchange(ref _source._subscriptions, @new, current); if (registered == current) { // succeeded break; } } } } } }
-1
dotnet/roslyn
55,138
Avoid cancellation exceptions in intermediate operations
Addresses the following exceptions: ![image](https://user-images.githubusercontent.com/1408396/127185947-8a005aea-ae1c-4755-bf0f-21dfb8101352.png)
sharwell
2021-07-27T15:51:28Z
2021-07-27T21:36:45Z
3d8acbd585a75e9cdb3509623bf6c39ceb46b2c2
719d4ffa2be734463e5d7d4d74b23b8006fd7727
Avoid cancellation exceptions in intermediate operations. Addresses the following exceptions: ![image](https://user-images.githubusercontent.com/1408396/127185947-8a005aea-ae1c-4755-bf0f-21dfb8101352.png)
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Log/LogMessage.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.PooledObjects; namespace Microsoft.CodeAnalysis.Internal.Log { /// <summary> /// log message that can generate string lazily /// </summary> internal abstract class LogMessage { public LogLevel LogLevel { get; protected set; } = LogLevel.Debug; public static LogMessage Create(string message, LogLevel logLevel) => StaticLogMessage.Construct(message, logLevel); public static LogMessage Create(Func<string> messageGetter, LogLevel logLevel) => LazyLogMessage.Construct(messageGetter, logLevel); public static LogMessage Create<TArg>(Func<TArg, string> messageGetter, TArg arg, LogLevel logLevel) => LazyLogMessage<TArg>.Construct(messageGetter, arg, logLevel); public static LogMessage Create<TArg0, TArg1>(Func<TArg0, TArg1, string> messageGetter, TArg0 arg0, TArg1 arg1, LogLevel logLevel) => LazyLogMessage<TArg0, TArg1>.Construct(messageGetter, arg0, arg1, logLevel); public static LogMessage Create<TArg0, TArg1, TArg2>(Func<TArg0, TArg1, TArg2, string> messageGetter, TArg0 arg0, TArg1 arg1, TArg2 arg2, LogLevel logLevel) => LazyLogMessage<TArg0, TArg1, TArg2>.Construct(messageGetter, arg0, arg1, arg2, logLevel); public static LogMessage Create<TArg0, TArg1, TArg2, TArg3>(Func<TArg0, TArg1, TArg2, TArg3, string> messageGetter, TArg0 arg0, TArg1 arg1, TArg2 arg2, TArg3 arg3, LogLevel logLevel) => LazyLogMessage<TArg0, TArg1, TArg2, TArg3>.Construct(messageGetter, arg0, arg1, arg2, arg3, logLevel); // message will be either initially set or lazily set by caller private string? _message; protected abstract string CreateMessage(); /// <summary> /// Logger will call this to return LogMessage to its pool /// </summary> protected abstract void FreeCore(); public string GetMessage() { if (_message == null) { _message = CreateMessage(); } return _message; } public void Free() { _message = null; FreeCore(); } private sealed class StaticLogMessage : LogMessage { private static readonly ObjectPool<StaticLogMessage> s_pool = SharedPools.Default<StaticLogMessage>(); public static LogMessage Construct(string message, LogLevel logLevel) { var logMessage = s_pool.Allocate(); logMessage._message = message; logMessage.LogLevel = logLevel; return logMessage; } protected override string CreateMessage() => _message!; protected override void FreeCore() { if (_message == null) { return; } _message = null; s_pool.Free(this); } } private sealed class LazyLogMessage : LogMessage { private static readonly ObjectPool<LazyLogMessage> s_pool = SharedPools.Default<LazyLogMessage>(); private Func<string>? _messageGetter; public static LogMessage Construct(Func<string> messageGetter, LogLevel logLevel) { var logMessage = s_pool.Allocate(); logMessage._messageGetter = messageGetter; logMessage.LogLevel = logLevel; return logMessage; } protected override string CreateMessage() => _messageGetter!(); protected override void FreeCore() { if (_messageGetter == null) { return; } _messageGetter = null; s_pool.Free(this); } } private sealed class LazyLogMessage<TArg0> : LogMessage { private static readonly ObjectPool<LazyLogMessage<TArg0>> s_pool = SharedPools.Default<LazyLogMessage<TArg0>>(); private Func<TArg0, string>? _messageGetter; private TArg0? _arg; public static LogMessage Construct(Func<TArg0, string> messageGetter, TArg0 arg, LogLevel logLevel) { var logMessage = s_pool.Allocate(); logMessage._messageGetter = messageGetter; logMessage._arg = arg; logMessage.LogLevel = logLevel; return logMessage; } protected override string CreateMessage() => _messageGetter!(_arg!); protected override void FreeCore() { if (_messageGetter == null) { return; } _messageGetter = null; _arg = default; s_pool.Free(this); } } private sealed class LazyLogMessage<TArg0, TArg1> : LogMessage { private static readonly ObjectPool<LazyLogMessage<TArg0, TArg1>> s_pool = SharedPools.Default<LazyLogMessage<TArg0, TArg1>>(); private Func<TArg0, TArg1, string>? _messageGetter; private TArg0? _arg0; private TArg1? _arg1; internal static LogMessage Construct(Func<TArg0, TArg1, string> messageGetter, TArg0 arg0, TArg1 arg1, LogLevel logLevel) { var logMessage = s_pool.Allocate(); logMessage._messageGetter = messageGetter; logMessage._arg0 = arg0; logMessage._arg1 = arg1; logMessage.LogLevel = logLevel; return logMessage; } protected override string CreateMessage() => _messageGetter!(_arg0!, _arg1!); protected override void FreeCore() { if (_messageGetter == null) { return; } _messageGetter = null; _arg0 = default; _arg1 = default; s_pool.Free(this); } } private sealed class LazyLogMessage<TArg0, TArg1, TArg2> : LogMessage { private static readonly ObjectPool<LazyLogMessage<TArg0, TArg1, TArg2>> s_pool = SharedPools.Default<LazyLogMessage<TArg0, TArg1, TArg2>>(); private Func<TArg0, TArg1, TArg2, string>? _messageGetter; private TArg0? _arg0; private TArg1? _arg1; private TArg2? _arg2; public static LogMessage Construct(Func<TArg0, TArg1, TArg2, string> messageGetter, TArg0 arg0, TArg1 arg1, TArg2 arg2, LogLevel logLevel) { var logMessage = s_pool.Allocate(); logMessage._messageGetter = messageGetter; logMessage._arg0 = arg0; logMessage._arg1 = arg1; logMessage._arg2 = arg2; logMessage.LogLevel = logLevel; return logMessage; } protected override string CreateMessage() => _messageGetter!(_arg0!, _arg1!, _arg2!); protected override void FreeCore() { if (_messageGetter == null) { return; } _messageGetter = null; _arg0 = default; _arg1 = default; _arg2 = default; s_pool.Free(this); } } private sealed class LazyLogMessage<TArg0, TArg1, TArg2, TArg3> : LogMessage { private static readonly ObjectPool<LazyLogMessage<TArg0, TArg1, TArg2, TArg3>> s_pool = SharedPools.Default<LazyLogMessage<TArg0, TArg1, TArg2, TArg3>>(); private Func<TArg0, TArg1, TArg2, TArg3, string>? _messageGetter; private TArg0? _arg0; private TArg1? _arg1; private TArg2? _arg2; private TArg3? _arg3; public static LogMessage Construct(Func<TArg0, TArg1, TArg2, TArg3, string> messageGetter, TArg0 arg0, TArg1 arg1, TArg2 arg2, TArg3 arg3, LogLevel logLevel) { var logMessage = s_pool.Allocate(); logMessage._messageGetter = messageGetter; logMessage._arg0 = arg0; logMessage._arg1 = arg1; logMessage._arg2 = arg2; logMessage._arg3 = arg3; logMessage.LogLevel = logLevel; return logMessage; } protected override string CreateMessage() => _messageGetter!(_arg0!, _arg1!, _arg2!, _arg3!); protected override void FreeCore() { if (_messageGetter == null) { return; } _messageGetter = null; _arg0 = default; _arg1 = default; _arg2 = default; _arg3 = default; s_pool.Free(this); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using Microsoft.CodeAnalysis.PooledObjects; namespace Microsoft.CodeAnalysis.Internal.Log { /// <summary> /// log message that can generate string lazily /// </summary> internal abstract class LogMessage { public LogLevel LogLevel { get; protected set; } = LogLevel.Debug; public static LogMessage Create(string message, LogLevel logLevel) => StaticLogMessage.Construct(message, logLevel); public static LogMessage Create(Func<string> messageGetter, LogLevel logLevel) => LazyLogMessage.Construct(messageGetter, logLevel); public static LogMessage Create<TArg>(Func<TArg, string> messageGetter, TArg arg, LogLevel logLevel) => LazyLogMessage<TArg>.Construct(messageGetter, arg, logLevel); public static LogMessage Create<TArg0, TArg1>(Func<TArg0, TArg1, string> messageGetter, TArg0 arg0, TArg1 arg1, LogLevel logLevel) => LazyLogMessage<TArg0, TArg1>.Construct(messageGetter, arg0, arg1, logLevel); public static LogMessage Create<TArg0, TArg1, TArg2>(Func<TArg0, TArg1, TArg2, string> messageGetter, TArg0 arg0, TArg1 arg1, TArg2 arg2, LogLevel logLevel) => LazyLogMessage<TArg0, TArg1, TArg2>.Construct(messageGetter, arg0, arg1, arg2, logLevel); public static LogMessage Create<TArg0, TArg1, TArg2, TArg3>(Func<TArg0, TArg1, TArg2, TArg3, string> messageGetter, TArg0 arg0, TArg1 arg1, TArg2 arg2, TArg3 arg3, LogLevel logLevel) => LazyLogMessage<TArg0, TArg1, TArg2, TArg3>.Construct(messageGetter, arg0, arg1, arg2, arg3, logLevel); // message will be either initially set or lazily set by caller private string? _message; protected abstract string CreateMessage(); /// <summary> /// Logger will call this to return LogMessage to its pool /// </summary> protected abstract void FreeCore(); public string GetMessage() { if (_message == null) { _message = CreateMessage(); } return _message; } public void Free() { _message = null; FreeCore(); } private sealed class StaticLogMessage : LogMessage { private static readonly ObjectPool<StaticLogMessage> s_pool = SharedPools.Default<StaticLogMessage>(); public static LogMessage Construct(string message, LogLevel logLevel) { var logMessage = s_pool.Allocate(); logMessage._message = message; logMessage.LogLevel = logLevel; return logMessage; } protected override string CreateMessage() => _message!; protected override void FreeCore() { if (_message == null) { return; } _message = null; s_pool.Free(this); } } private sealed class LazyLogMessage : LogMessage { private static readonly ObjectPool<LazyLogMessage> s_pool = SharedPools.Default<LazyLogMessage>(); private Func<string>? _messageGetter; public static LogMessage Construct(Func<string> messageGetter, LogLevel logLevel) { var logMessage = s_pool.Allocate(); logMessage._messageGetter = messageGetter; logMessage.LogLevel = logLevel; return logMessage; } protected override string CreateMessage() => _messageGetter!(); protected override void FreeCore() { if (_messageGetter == null) { return; } _messageGetter = null; s_pool.Free(this); } } private sealed class LazyLogMessage<TArg0> : LogMessage { private static readonly ObjectPool<LazyLogMessage<TArg0>> s_pool = SharedPools.Default<LazyLogMessage<TArg0>>(); private Func<TArg0, string>? _messageGetter; private TArg0? _arg; public static LogMessage Construct(Func<TArg0, string> messageGetter, TArg0 arg, LogLevel logLevel) { var logMessage = s_pool.Allocate(); logMessage._messageGetter = messageGetter; logMessage._arg = arg; logMessage.LogLevel = logLevel; return logMessage; } protected override string CreateMessage() => _messageGetter!(_arg!); protected override void FreeCore() { if (_messageGetter == null) { return; } _messageGetter = null; _arg = default; s_pool.Free(this); } } private sealed class LazyLogMessage<TArg0, TArg1> : LogMessage { private static readonly ObjectPool<LazyLogMessage<TArg0, TArg1>> s_pool = SharedPools.Default<LazyLogMessage<TArg0, TArg1>>(); private Func<TArg0, TArg1, string>? _messageGetter; private TArg0? _arg0; private TArg1? _arg1; internal static LogMessage Construct(Func<TArg0, TArg1, string> messageGetter, TArg0 arg0, TArg1 arg1, LogLevel logLevel) { var logMessage = s_pool.Allocate(); logMessage._messageGetter = messageGetter; logMessage._arg0 = arg0; logMessage._arg1 = arg1; logMessage.LogLevel = logLevel; return logMessage; } protected override string CreateMessage() => _messageGetter!(_arg0!, _arg1!); protected override void FreeCore() { if (_messageGetter == null) { return; } _messageGetter = null; _arg0 = default; _arg1 = default; s_pool.Free(this); } } private sealed class LazyLogMessage<TArg0, TArg1, TArg2> : LogMessage { private static readonly ObjectPool<LazyLogMessage<TArg0, TArg1, TArg2>> s_pool = SharedPools.Default<LazyLogMessage<TArg0, TArg1, TArg2>>(); private Func<TArg0, TArg1, TArg2, string>? _messageGetter; private TArg0? _arg0; private TArg1? _arg1; private TArg2? _arg2; public static LogMessage Construct(Func<TArg0, TArg1, TArg2, string> messageGetter, TArg0 arg0, TArg1 arg1, TArg2 arg2, LogLevel logLevel) { var logMessage = s_pool.Allocate(); logMessage._messageGetter = messageGetter; logMessage._arg0 = arg0; logMessage._arg1 = arg1; logMessage._arg2 = arg2; logMessage.LogLevel = logLevel; return logMessage; } protected override string CreateMessage() => _messageGetter!(_arg0!, _arg1!, _arg2!); protected override void FreeCore() { if (_messageGetter == null) { return; } _messageGetter = null; _arg0 = default; _arg1 = default; _arg2 = default; s_pool.Free(this); } } private sealed class LazyLogMessage<TArg0, TArg1, TArg2, TArg3> : LogMessage { private static readonly ObjectPool<LazyLogMessage<TArg0, TArg1, TArg2, TArg3>> s_pool = SharedPools.Default<LazyLogMessage<TArg0, TArg1, TArg2, TArg3>>(); private Func<TArg0, TArg1, TArg2, TArg3, string>? _messageGetter; private TArg0? _arg0; private TArg1? _arg1; private TArg2? _arg2; private TArg3? _arg3; public static LogMessage Construct(Func<TArg0, TArg1, TArg2, TArg3, string> messageGetter, TArg0 arg0, TArg1 arg1, TArg2 arg2, TArg3 arg3, LogLevel logLevel) { var logMessage = s_pool.Allocate(); logMessage._messageGetter = messageGetter; logMessage._arg0 = arg0; logMessage._arg1 = arg1; logMessage._arg2 = arg2; logMessage._arg3 = arg3; logMessage.LogLevel = logLevel; return logMessage; } protected override string CreateMessage() => _messageGetter!(_arg0!, _arg1!, _arg2!, _arg3!); protected override void FreeCore() { if (_messageGetter == null) { return; } _messageGetter = null; _arg0 = default; _arg1 = default; _arg2 = default; _arg3 = default; s_pool.Free(this); } } } }
-1
dotnet/roslyn
55,138
Avoid cancellation exceptions in intermediate operations
Addresses the following exceptions: ![image](https://user-images.githubusercontent.com/1408396/127185947-8a005aea-ae1c-4755-bf0f-21dfb8101352.png)
sharwell
2021-07-27T15:51:28Z
2021-07-27T21:36:45Z
3d8acbd585a75e9cdb3509623bf6c39ceb46b2c2
719d4ffa2be734463e5d7d4d74b23b8006fd7727
Avoid cancellation exceptions in intermediate operations. Addresses the following exceptions: ![image](https://user-images.githubusercontent.com/1408396/127185947-8a005aea-ae1c-4755-bf0f-21dfb8101352.png)
./src/Workspaces/CSharp/Portable/CodeGeneration/MethodGenerator.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis.CodeGeneration; using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using static Microsoft.CodeAnalysis.CodeGeneration.CodeGenerationHelpers; using static Microsoft.CodeAnalysis.CSharp.CodeGeneration.CSharpCodeGenerationHelpers; namespace Microsoft.CodeAnalysis.CSharp.CodeGeneration { internal static class MethodGenerator { internal static BaseNamespaceDeclarationSyntax AddMethodTo( BaseNamespaceDeclarationSyntax destination, IMethodSymbol method, CodeGenerationOptions options, IList<bool> availableIndices) { var declaration = GenerateMethodDeclaration( method, CodeGenerationDestination.Namespace, options, destination?.SyntaxTree.Options ?? options.ParseOptions); var members = Insert(destination.Members, declaration, options, availableIndices, after: LastMethod); return destination.WithMembers(members.ToSyntaxList()); } internal static CompilationUnitSyntax AddMethodTo( CompilationUnitSyntax destination, IMethodSymbol method, CodeGenerationOptions options, IList<bool> availableIndices) { var declaration = GenerateMethodDeclaration( method, CodeGenerationDestination.CompilationUnit, options, destination?.SyntaxTree.Options ?? options.ParseOptions); var members = Insert(destination.Members, declaration, options, availableIndices, after: LastMethod); return destination.WithMembers(members.ToSyntaxList()); } internal static TypeDeclarationSyntax AddMethodTo( TypeDeclarationSyntax destination, IMethodSymbol method, CodeGenerationOptions options, IList<bool> availableIndices) { var methodDeclaration = GenerateMethodDeclaration( method, GetDestination(destination), options, destination?.SyntaxTree.Options ?? options.ParseOptions); // Create a clone of the original type with the new method inserted. var members = Insert(destination.Members, methodDeclaration, options, availableIndices, after: LastMethod); return AddMembersTo(destination, members); } public static MethodDeclarationSyntax GenerateMethodDeclaration( IMethodSymbol method, CodeGenerationDestination destination, CodeGenerationOptions options, ParseOptions parseOptions) { options ??= CodeGenerationOptions.Default; var reusableSyntax = GetReuseableSyntaxNodeForSymbol<MethodDeclarationSyntax>(method, options); if (reusableSyntax != null) { return reusableSyntax; } var declaration = GenerateMethodDeclarationWorker( method, destination, options, parseOptions); return AddAnnotationsTo(method, ConditionallyAddDocumentationCommentTo(declaration, method, options)); } public static LocalFunctionStatementSyntax GenerateLocalFunctionDeclaration( IMethodSymbol method, CodeGenerationDestination destination, CodeGenerationOptions options, ParseOptions parseOptions) { options ??= CodeGenerationOptions.Default; var reusableSyntax = GetReuseableSyntaxNodeForSymbol<LocalFunctionStatementSyntax>(method, options); if (reusableSyntax != null) { return reusableSyntax; } var declaration = GenerateLocalFunctionDeclarationWorker( method, destination, options, parseOptions); return AddAnnotationsTo(method, ConditionallyAddDocumentationCommentTo(declaration, method, options)); } private static MethodDeclarationSyntax GenerateMethodDeclarationWorker( IMethodSymbol method, CodeGenerationDestination destination, CodeGenerationOptions options, ParseOptions parseOptions) { // Don't rely on destination to decide if method body should be generated. // Users of this service need to express their intention explicitly, either by // setting `CodeGenerationOptions.GenerateMethodBodies` to true, or making // `method` abstract. This would provide more flexibility. var hasNoBody = !options.GenerateMethodBodies || method.IsAbstract; var explicitInterfaceSpecifier = GenerateExplicitInterfaceSpecifier(method.ExplicitInterfaceImplementations); var methodDeclaration = SyntaxFactory.MethodDeclaration( attributeLists: GenerateAttributes(method, options, explicitInterfaceSpecifier != null), modifiers: GenerateModifiers(method, destination, options), returnType: method.GenerateReturnTypeSyntax(), explicitInterfaceSpecifier: explicitInterfaceSpecifier, identifier: method.Name.ToIdentifierToken(), typeParameterList: GenerateTypeParameterList(method, options), parameterList: ParameterGenerator.GenerateParameterList(method.Parameters, explicitInterfaceSpecifier != null, options), constraintClauses: GenerateConstraintClauses(method), body: hasNoBody ? null : StatementGenerator.GenerateBlock(method), expressionBody: null, semicolonToken: hasNoBody ? SyntaxFactory.Token(SyntaxKind.SemicolonToken) : default); methodDeclaration = UseExpressionBodyIfDesired(options, methodDeclaration, parseOptions); return AddFormatterAndCodeGeneratorAnnotationsTo(methodDeclaration); } private static LocalFunctionStatementSyntax GenerateLocalFunctionDeclarationWorker( IMethodSymbol method, CodeGenerationDestination destination, CodeGenerationOptions options, ParseOptions parseOptions) { var localFunctionDeclaration = SyntaxFactory.LocalFunctionStatement( modifiers: GenerateModifiers(method, destination, options), returnType: method.GenerateReturnTypeSyntax(), identifier: method.Name.ToIdentifierToken(), typeParameterList: GenerateTypeParameterList(method, options), parameterList: ParameterGenerator.GenerateParameterList(method.Parameters, isExplicit: false, options), constraintClauses: GenerateConstraintClauses(method), body: StatementGenerator.GenerateBlock(method), expressionBody: null, semicolonToken: default); localFunctionDeclaration = UseExpressionBodyIfDesired(options, localFunctionDeclaration, parseOptions); return AddFormatterAndCodeGeneratorAnnotationsTo(localFunctionDeclaration); } private static MethodDeclarationSyntax UseExpressionBodyIfDesired( CodeGenerationOptions options, MethodDeclarationSyntax methodDeclaration, ParseOptions parseOptions) { if (methodDeclaration.ExpressionBody == null) { var expressionBodyPreference = options.Options.GetOption(CSharpCodeStyleOptions.PreferExpressionBodiedMethods).Value; if (methodDeclaration.Body.TryConvertToArrowExpressionBody( methodDeclaration.Kind(), parseOptions, expressionBodyPreference, out var expressionBody, out var semicolonToken)) { return methodDeclaration.WithBody(null) .WithExpressionBody(expressionBody) .WithSemicolonToken(semicolonToken); } } return methodDeclaration; } private static LocalFunctionStatementSyntax UseExpressionBodyIfDesired( CodeGenerationOptions options, LocalFunctionStatementSyntax localFunctionDeclaration, ParseOptions parseOptions) { if (localFunctionDeclaration.ExpressionBody == null) { var expressionBodyPreference = options.Options.GetOption(CSharpCodeStyleOptions.PreferExpressionBodiedLocalFunctions).Value; if (localFunctionDeclaration.Body.TryConvertToArrowExpressionBody( localFunctionDeclaration.Kind(), parseOptions, expressionBodyPreference, out var expressionBody, out var semicolonToken)) { return localFunctionDeclaration.WithBody(null) .WithExpressionBody(expressionBody) .WithSemicolonToken(semicolonToken); } } return localFunctionDeclaration; } private static SyntaxList<AttributeListSyntax> GenerateAttributes( IMethodSymbol method, CodeGenerationOptions options, bool isExplicit) { var attributes = new List<AttributeListSyntax>(); if (!isExplicit) { attributes.AddRange(AttributeGenerator.GenerateAttributeLists(method.GetAttributes(), options)); attributes.AddRange(AttributeGenerator.GenerateAttributeLists(method.GetReturnTypeAttributes(), options, SyntaxFactory.Token(SyntaxKind.ReturnKeyword))); } return attributes.ToSyntaxList(); } private static SyntaxList<TypeParameterConstraintClauseSyntax> GenerateConstraintClauses( IMethodSymbol method) { return !method.ExplicitInterfaceImplementations.Any() && !method.IsOverride ? method.TypeParameters.GenerateConstraintClauses() : default; } private static TypeParameterListSyntax GenerateTypeParameterList( IMethodSymbol method, CodeGenerationOptions options) { return TypeParameterGenerator.GenerateTypeParameterList(method.TypeParameters, options); } private static SyntaxTokenList GenerateModifiers( IMethodSymbol method, CodeGenerationDestination destination, CodeGenerationOptions options) { var tokens = ArrayBuilder<SyntaxToken>.GetInstance(); // Only "static" and "unsafe" modifiers allowed if we're an explicit impl. if (method.ExplicitInterfaceImplementations.Any()) { if (method.IsStatic) { tokens.Add(SyntaxFactory.Token(SyntaxKind.StaticKeyword)); } if (CodeGenerationMethodInfo.GetIsUnsafe(method)) { tokens.Add(SyntaxFactory.Token(SyntaxKind.UnsafeKeyword)); } } else { // If we're generating into an interface, then we don't use any modifiers. if (destination != CodeGenerationDestination.CompilationUnit && destination != CodeGenerationDestination.Namespace && destination != CodeGenerationDestination.InterfaceType) { AddAccessibilityModifiers(method.DeclaredAccessibility, tokens, options, Accessibility.Private); if (method.IsStatic) { tokens.Add(SyntaxFactory.Token(SyntaxKind.StaticKeyword)); } if (method.IsAbstract) { tokens.Add(SyntaxFactory.Token(SyntaxKind.AbstractKeyword)); } if (method.IsSealed) { tokens.Add(SyntaxFactory.Token(SyntaxKind.SealedKeyword)); } // Don't show the readonly modifier if the containing type is already readonly // ContainingSymbol is used to guard against methods which are not members of their ContainingType (e.g. lambdas and local functions) if (method.IsReadOnly && (method.ContainingSymbol as INamedTypeSymbol)?.IsReadOnly != true) { tokens.Add(SyntaxFactory.Token(SyntaxKind.ReadOnlyKeyword)); } if (method.IsOverride) { tokens.Add(SyntaxFactory.Token(SyntaxKind.OverrideKeyword)); } if (method.IsVirtual) { tokens.Add(SyntaxFactory.Token(SyntaxKind.VirtualKeyword)); } if (CodeGenerationMethodInfo.GetIsPartial(method) && !method.IsAsync) { tokens.Add(SyntaxFactory.Token(SyntaxKind.PartialKeyword)); } } if (CodeGenerationMethodInfo.GetIsUnsafe(method)) { tokens.Add(SyntaxFactory.Token(SyntaxKind.UnsafeKeyword)); } if (CodeGenerationMethodInfo.GetIsNew(method)) { tokens.Add(SyntaxFactory.Token(SyntaxKind.NewKeyword)); } } if (destination != CodeGenerationDestination.InterfaceType) { if (CodeGenerationMethodInfo.GetIsAsyncMethod(method)) { tokens.Add(SyntaxFactory.Token(SyntaxKind.AsyncKeyword)); } } if (CodeGenerationMethodInfo.GetIsPartial(method) && method.IsAsync) { tokens.Add(SyntaxFactory.Token(SyntaxKind.PartialKeyword)); } return tokens.ToSyntaxTokenListAndFree(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis.CodeGeneration; using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using static Microsoft.CodeAnalysis.CodeGeneration.CodeGenerationHelpers; using static Microsoft.CodeAnalysis.CSharp.CodeGeneration.CSharpCodeGenerationHelpers; namespace Microsoft.CodeAnalysis.CSharp.CodeGeneration { internal static class MethodGenerator { internal static BaseNamespaceDeclarationSyntax AddMethodTo( BaseNamespaceDeclarationSyntax destination, IMethodSymbol method, CodeGenerationOptions options, IList<bool> availableIndices) { var declaration = GenerateMethodDeclaration( method, CodeGenerationDestination.Namespace, options, destination?.SyntaxTree.Options ?? options.ParseOptions); var members = Insert(destination.Members, declaration, options, availableIndices, after: LastMethod); return destination.WithMembers(members.ToSyntaxList()); } internal static CompilationUnitSyntax AddMethodTo( CompilationUnitSyntax destination, IMethodSymbol method, CodeGenerationOptions options, IList<bool> availableIndices) { var declaration = GenerateMethodDeclaration( method, CodeGenerationDestination.CompilationUnit, options, destination?.SyntaxTree.Options ?? options.ParseOptions); var members = Insert(destination.Members, declaration, options, availableIndices, after: LastMethod); return destination.WithMembers(members.ToSyntaxList()); } internal static TypeDeclarationSyntax AddMethodTo( TypeDeclarationSyntax destination, IMethodSymbol method, CodeGenerationOptions options, IList<bool> availableIndices) { var methodDeclaration = GenerateMethodDeclaration( method, GetDestination(destination), options, destination?.SyntaxTree.Options ?? options.ParseOptions); // Create a clone of the original type with the new method inserted. var members = Insert(destination.Members, methodDeclaration, options, availableIndices, after: LastMethod); return AddMembersTo(destination, members); } public static MethodDeclarationSyntax GenerateMethodDeclaration( IMethodSymbol method, CodeGenerationDestination destination, CodeGenerationOptions options, ParseOptions parseOptions) { options ??= CodeGenerationOptions.Default; var reusableSyntax = GetReuseableSyntaxNodeForSymbol<MethodDeclarationSyntax>(method, options); if (reusableSyntax != null) { return reusableSyntax; } var declaration = GenerateMethodDeclarationWorker( method, destination, options, parseOptions); return AddAnnotationsTo(method, ConditionallyAddDocumentationCommentTo(declaration, method, options)); } public static LocalFunctionStatementSyntax GenerateLocalFunctionDeclaration( IMethodSymbol method, CodeGenerationDestination destination, CodeGenerationOptions options, ParseOptions parseOptions) { options ??= CodeGenerationOptions.Default; var reusableSyntax = GetReuseableSyntaxNodeForSymbol<LocalFunctionStatementSyntax>(method, options); if (reusableSyntax != null) { return reusableSyntax; } var declaration = GenerateLocalFunctionDeclarationWorker( method, destination, options, parseOptions); return AddAnnotationsTo(method, ConditionallyAddDocumentationCommentTo(declaration, method, options)); } private static MethodDeclarationSyntax GenerateMethodDeclarationWorker( IMethodSymbol method, CodeGenerationDestination destination, CodeGenerationOptions options, ParseOptions parseOptions) { // Don't rely on destination to decide if method body should be generated. // Users of this service need to express their intention explicitly, either by // setting `CodeGenerationOptions.GenerateMethodBodies` to true, or making // `method` abstract. This would provide more flexibility. var hasNoBody = !options.GenerateMethodBodies || method.IsAbstract; var explicitInterfaceSpecifier = GenerateExplicitInterfaceSpecifier(method.ExplicitInterfaceImplementations); var methodDeclaration = SyntaxFactory.MethodDeclaration( attributeLists: GenerateAttributes(method, options, explicitInterfaceSpecifier != null), modifiers: GenerateModifiers(method, destination, options), returnType: method.GenerateReturnTypeSyntax(), explicitInterfaceSpecifier: explicitInterfaceSpecifier, identifier: method.Name.ToIdentifierToken(), typeParameterList: GenerateTypeParameterList(method, options), parameterList: ParameterGenerator.GenerateParameterList(method.Parameters, explicitInterfaceSpecifier != null, options), constraintClauses: GenerateConstraintClauses(method), body: hasNoBody ? null : StatementGenerator.GenerateBlock(method), expressionBody: null, semicolonToken: hasNoBody ? SyntaxFactory.Token(SyntaxKind.SemicolonToken) : default); methodDeclaration = UseExpressionBodyIfDesired(options, methodDeclaration, parseOptions); return AddFormatterAndCodeGeneratorAnnotationsTo(methodDeclaration); } private static LocalFunctionStatementSyntax GenerateLocalFunctionDeclarationWorker( IMethodSymbol method, CodeGenerationDestination destination, CodeGenerationOptions options, ParseOptions parseOptions) { var localFunctionDeclaration = SyntaxFactory.LocalFunctionStatement( modifiers: GenerateModifiers(method, destination, options), returnType: method.GenerateReturnTypeSyntax(), identifier: method.Name.ToIdentifierToken(), typeParameterList: GenerateTypeParameterList(method, options), parameterList: ParameterGenerator.GenerateParameterList(method.Parameters, isExplicit: false, options), constraintClauses: GenerateConstraintClauses(method), body: StatementGenerator.GenerateBlock(method), expressionBody: null, semicolonToken: default); localFunctionDeclaration = UseExpressionBodyIfDesired(options, localFunctionDeclaration, parseOptions); return AddFormatterAndCodeGeneratorAnnotationsTo(localFunctionDeclaration); } private static MethodDeclarationSyntax UseExpressionBodyIfDesired( CodeGenerationOptions options, MethodDeclarationSyntax methodDeclaration, ParseOptions parseOptions) { if (methodDeclaration.ExpressionBody == null) { var expressionBodyPreference = options.Options.GetOption(CSharpCodeStyleOptions.PreferExpressionBodiedMethods).Value; if (methodDeclaration.Body.TryConvertToArrowExpressionBody( methodDeclaration.Kind(), parseOptions, expressionBodyPreference, out var expressionBody, out var semicolonToken)) { return methodDeclaration.WithBody(null) .WithExpressionBody(expressionBody) .WithSemicolonToken(semicolonToken); } } return methodDeclaration; } private static LocalFunctionStatementSyntax UseExpressionBodyIfDesired( CodeGenerationOptions options, LocalFunctionStatementSyntax localFunctionDeclaration, ParseOptions parseOptions) { if (localFunctionDeclaration.ExpressionBody == null) { var expressionBodyPreference = options.Options.GetOption(CSharpCodeStyleOptions.PreferExpressionBodiedLocalFunctions).Value; if (localFunctionDeclaration.Body.TryConvertToArrowExpressionBody( localFunctionDeclaration.Kind(), parseOptions, expressionBodyPreference, out var expressionBody, out var semicolonToken)) { return localFunctionDeclaration.WithBody(null) .WithExpressionBody(expressionBody) .WithSemicolonToken(semicolonToken); } } return localFunctionDeclaration; } private static SyntaxList<AttributeListSyntax> GenerateAttributes( IMethodSymbol method, CodeGenerationOptions options, bool isExplicit) { var attributes = new List<AttributeListSyntax>(); if (!isExplicit) { attributes.AddRange(AttributeGenerator.GenerateAttributeLists(method.GetAttributes(), options)); attributes.AddRange(AttributeGenerator.GenerateAttributeLists(method.GetReturnTypeAttributes(), options, SyntaxFactory.Token(SyntaxKind.ReturnKeyword))); } return attributes.ToSyntaxList(); } private static SyntaxList<TypeParameterConstraintClauseSyntax> GenerateConstraintClauses( IMethodSymbol method) { return !method.ExplicitInterfaceImplementations.Any() && !method.IsOverride ? method.TypeParameters.GenerateConstraintClauses() : default; } private static TypeParameterListSyntax GenerateTypeParameterList( IMethodSymbol method, CodeGenerationOptions options) { return TypeParameterGenerator.GenerateTypeParameterList(method.TypeParameters, options); } private static SyntaxTokenList GenerateModifiers( IMethodSymbol method, CodeGenerationDestination destination, CodeGenerationOptions options) { var tokens = ArrayBuilder<SyntaxToken>.GetInstance(); // Only "static" and "unsafe" modifiers allowed if we're an explicit impl. if (method.ExplicitInterfaceImplementations.Any()) { if (method.IsStatic) { tokens.Add(SyntaxFactory.Token(SyntaxKind.StaticKeyword)); } if (CodeGenerationMethodInfo.GetIsUnsafe(method)) { tokens.Add(SyntaxFactory.Token(SyntaxKind.UnsafeKeyword)); } } else { // If we're generating into an interface, then we don't use any modifiers. if (destination != CodeGenerationDestination.CompilationUnit && destination != CodeGenerationDestination.Namespace && destination != CodeGenerationDestination.InterfaceType) { AddAccessibilityModifiers(method.DeclaredAccessibility, tokens, options, Accessibility.Private); if (method.IsStatic) { tokens.Add(SyntaxFactory.Token(SyntaxKind.StaticKeyword)); } if (method.IsAbstract) { tokens.Add(SyntaxFactory.Token(SyntaxKind.AbstractKeyword)); } if (method.IsSealed) { tokens.Add(SyntaxFactory.Token(SyntaxKind.SealedKeyword)); } // Don't show the readonly modifier if the containing type is already readonly // ContainingSymbol is used to guard against methods which are not members of their ContainingType (e.g. lambdas and local functions) if (method.IsReadOnly && (method.ContainingSymbol as INamedTypeSymbol)?.IsReadOnly != true) { tokens.Add(SyntaxFactory.Token(SyntaxKind.ReadOnlyKeyword)); } if (method.IsOverride) { tokens.Add(SyntaxFactory.Token(SyntaxKind.OverrideKeyword)); } if (method.IsVirtual) { tokens.Add(SyntaxFactory.Token(SyntaxKind.VirtualKeyword)); } if (CodeGenerationMethodInfo.GetIsPartial(method) && !method.IsAsync) { tokens.Add(SyntaxFactory.Token(SyntaxKind.PartialKeyword)); } } if (CodeGenerationMethodInfo.GetIsUnsafe(method)) { tokens.Add(SyntaxFactory.Token(SyntaxKind.UnsafeKeyword)); } if (CodeGenerationMethodInfo.GetIsNew(method)) { tokens.Add(SyntaxFactory.Token(SyntaxKind.NewKeyword)); } } if (destination != CodeGenerationDestination.InterfaceType) { if (CodeGenerationMethodInfo.GetIsAsyncMethod(method)) { tokens.Add(SyntaxFactory.Token(SyntaxKind.AsyncKeyword)); } } if (CodeGenerationMethodInfo.GetIsPartial(method) && method.IsAsync) { tokens.Add(SyntaxFactory.Token(SyntaxKind.PartialKeyword)); } return tokens.ToSyntaxTokenListAndFree(); } } }
-1
dotnet/roslyn
55,138
Avoid cancellation exceptions in intermediate operations
Addresses the following exceptions: ![image](https://user-images.githubusercontent.com/1408396/127185947-8a005aea-ae1c-4755-bf0f-21dfb8101352.png)
sharwell
2021-07-27T15:51:28Z
2021-07-27T21:36:45Z
3d8acbd585a75e9cdb3509623bf6c39ceb46b2c2
719d4ffa2be734463e5d7d4d74b23b8006fd7727
Avoid cancellation exceptions in intermediate operations. Addresses the following exceptions: ![image](https://user-images.githubusercontent.com/1408396/127185947-8a005aea-ae1c-4755-bf0f-21dfb8101352.png)
./src/VisualStudio/Core/Def/Implementation/InheritanceMargin/MarginGlyph/InheritanceMarginViewModel.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.Windows; using System.Windows.Controls; using System.Windows.Documents; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.VisualStudio.Imaging.Interop; using Microsoft.VisualStudio.Text.Classification; namespace Microsoft.VisualStudio.LanguageServices.Implementation.InheritanceMargin.MarginGlyph { internal class InheritanceMarginViewModel { /// <summary> /// ImageMoniker used for the margin. /// </summary> public ImageMoniker ImageMoniker { get; } /// <summary> /// Tooltip for the margin. /// </summary> public TextBlock ToolTipTextBlock { get; } /// <summary> /// Text used for automation. /// </summary> public string AutomationName { get; } /// <summary> /// ViewModels for the context menu items. /// </summary> public ImmutableArray<InheritanceMenuItemViewModel> MenuItemViewModels { get; } /// <summary> /// Scale factor for the margin. /// </summary> public double ScaleFactor { get; } // Internal for testing purpose internal InheritanceMarginViewModel( ImageMoniker imageMoniker, TextBlock toolTipTextBlock, string automationName, double scaleFactor, ImmutableArray<InheritanceMenuItemViewModel> menuItemViewModels) { ImageMoniker = imageMoniker; ToolTipTextBlock = toolTipTextBlock; AutomationName = automationName; MenuItemViewModels = menuItemViewModels; ScaleFactor = scaleFactor; } public static InheritanceMarginViewModel Create( ClassificationTypeMap classificationTypeMap, IClassificationFormatMap classificationFormatMap, InheritanceMarginTag tag, double zoomLevel) { var members = tag.MembersOnLine; // ZoomLevel is 100 based. (e.g. 150%, 100%) // ScaleFactor is 1 based. (e.g. 1.5, 1) var scaleFactor = zoomLevel / 100; if (members.Length == 1) { var member = tag.MembersOnLine[0]; // Here we want to show a classified text with loc text, // e.g. 'Bar' is inherited. // But the classified text are inlines, so can't directly use string.format to generate the string var inlines = member.DisplayTexts.ToInlines(classificationFormatMap, classificationTypeMap); var startOfThePlaceholder = ServicesVSResources._0_is_inherited.IndexOf("{0}", StringComparison.Ordinal); var prefixString = ServicesVSResources._0_is_inherited[..startOfThePlaceholder]; var suffixString = ServicesVSResources._0_is_inherited[(startOfThePlaceholder + "{0}".Length)..]; inlines.Insert(0, new Run(prefixString)); inlines.Add(new Run(suffixString)); var toolTipTextBlock = inlines.ToTextBlock(classificationFormatMap); toolTipTextBlock.FlowDirection = FlowDirection.LeftToRight; var automationName = string.Format(ServicesVSResources._0_is_inherited, member.DisplayTexts.JoinText()); var menuItemViewModels = InheritanceMarginHelpers.CreateMenuItemViewModelsForSingleMember(member.TargetItems); return new InheritanceMarginViewModel(tag.Moniker, toolTipTextBlock, automationName, scaleFactor, menuItemViewModels); } else { var textBlock = new TextBlock { Text = ServicesVSResources.Multiple_members_are_inherited }; // Same automation name can't be set for control for accessibility purpose. So add the line number info. var automationName = string.Format(ServicesVSResources.Multiple_members_are_inherited_on_line_0, tag.LineNumber); var menuItemViewModels = InheritanceMarginHelpers.CreateMenuItemViewModelsForMultipleMembers(tag.MembersOnLine); return new InheritanceMarginViewModel(tag.Moniker, textBlock, automationName, scaleFactor, menuItemViewModels); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .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.Windows; using System.Windows.Controls; using System.Windows.Documents; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.VisualStudio.Imaging.Interop; using Microsoft.VisualStudio.Text.Classification; namespace Microsoft.VisualStudio.LanguageServices.Implementation.InheritanceMargin.MarginGlyph { internal class InheritanceMarginViewModel { /// <summary> /// ImageMoniker used for the margin. /// </summary> public ImageMoniker ImageMoniker { get; } /// <summary> /// Tooltip for the margin. /// </summary> public TextBlock ToolTipTextBlock { get; } /// <summary> /// Text used for automation. /// </summary> public string AutomationName { get; } /// <summary> /// ViewModels for the context menu items. /// </summary> public ImmutableArray<InheritanceMenuItemViewModel> MenuItemViewModels { get; } /// <summary> /// Scale factor for the margin. /// </summary> public double ScaleFactor { get; } // Internal for testing purpose internal InheritanceMarginViewModel( ImageMoniker imageMoniker, TextBlock toolTipTextBlock, string automationName, double scaleFactor, ImmutableArray<InheritanceMenuItemViewModel> menuItemViewModels) { ImageMoniker = imageMoniker; ToolTipTextBlock = toolTipTextBlock; AutomationName = automationName; MenuItemViewModels = menuItemViewModels; ScaleFactor = scaleFactor; } public static InheritanceMarginViewModel Create( ClassificationTypeMap classificationTypeMap, IClassificationFormatMap classificationFormatMap, InheritanceMarginTag tag, double zoomLevel) { var members = tag.MembersOnLine; // ZoomLevel is 100 based. (e.g. 150%, 100%) // ScaleFactor is 1 based. (e.g. 1.5, 1) var scaleFactor = zoomLevel / 100; if (members.Length == 1) { var member = tag.MembersOnLine[0]; // Here we want to show a classified text with loc text, // e.g. 'Bar' is inherited. // But the classified text are inlines, so can't directly use string.format to generate the string var inlines = member.DisplayTexts.ToInlines(classificationFormatMap, classificationTypeMap); var startOfThePlaceholder = ServicesVSResources._0_is_inherited.IndexOf("{0}", StringComparison.Ordinal); var prefixString = ServicesVSResources._0_is_inherited[..startOfThePlaceholder]; var suffixString = ServicesVSResources._0_is_inherited[(startOfThePlaceholder + "{0}".Length)..]; inlines.Insert(0, new Run(prefixString)); inlines.Add(new Run(suffixString)); var toolTipTextBlock = inlines.ToTextBlock(classificationFormatMap); toolTipTextBlock.FlowDirection = FlowDirection.LeftToRight; var automationName = string.Format(ServicesVSResources._0_is_inherited, member.DisplayTexts.JoinText()); var menuItemViewModels = InheritanceMarginHelpers.CreateMenuItemViewModelsForSingleMember(member.TargetItems); return new InheritanceMarginViewModel(tag.Moniker, toolTipTextBlock, automationName, scaleFactor, menuItemViewModels); } else { var textBlock = new TextBlock { Text = ServicesVSResources.Multiple_members_are_inherited }; // Same automation name can't be set for control for accessibility purpose. So add the line number info. var automationName = string.Format(ServicesVSResources.Multiple_members_are_inherited_on_line_0, tag.LineNumber); var menuItemViewModels = InheritanceMarginHelpers.CreateMenuItemViewModelsForMultipleMembers(tag.MembersOnLine); return new InheritanceMarginViewModel(tag.Moniker, textBlock, automationName, scaleFactor, menuItemViewModels); } } } }
-1
dotnet/roslyn
55,138
Avoid cancellation exceptions in intermediate operations
Addresses the following exceptions: ![image](https://user-images.githubusercontent.com/1408396/127185947-8a005aea-ae1c-4755-bf0f-21dfb8101352.png)
sharwell
2021-07-27T15:51:28Z
2021-07-27T21:36:45Z
3d8acbd585a75e9cdb3509623bf6c39ceb46b2c2
719d4ffa2be734463e5d7d4d74b23b8006fd7727
Avoid cancellation exceptions in intermediate operations. Addresses the following exceptions: ![image](https://user-images.githubusercontent.com/1408396/127185947-8a005aea-ae1c-4755-bf0f-21dfb8101352.png)
./src/ExpressionEvaluator/Core/Test/ResultProvider/ReflectionUtilities.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET 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.VisualStudio.Debugger.Clr; using System; using System.Collections.Immutable; using System.Linq; using System.Reflection; namespace Microsoft.CodeAnalysis.ExpressionEvaluator { internal static class ReflectionUtilities { internal static Assembly Load(ImmutableArray<byte> assembly) { return Assembly.Load(assembly.ToArray()); } internal static object Instantiate(this Type type, params object[] args) { return Activator.CreateInstance( type, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.CreateInstance, binder: null, args: args, culture: null); } internal static AssemblyLoadContext Load(this DkmClrRuntimeInstance runtime) { return new AssemblyLoadContext(runtime.Assemblies); } internal static AssemblyLoadContext LoadAssemblies(params Assembly[] assemblies) { return new AssemblyLoadContext(assemblies); } internal static Assembly[] GetMscorlib(params Assembly[] additionalAssemblies) { var builder = ArrayBuilder<Assembly>.GetInstance(); builder.Add(typeof(object).Assembly); // mscorlib.dll builder.AddRange(additionalAssemblies); return builder.ToArrayAndFree(); } internal static Assembly[] GetMscorlibAndSystemCore(params Assembly[] additionalAssemblies) { var builder = ArrayBuilder<Assembly>.GetInstance(); builder.Add(typeof(object).Assembly); // mscorlib.dll builder.Add(typeof(Enumerable).Assembly); // System.Core.dll builder.AddRange(additionalAssemblies); return builder.ToArrayAndFree(); } internal sealed class AssemblyLoadContext : IDisposable { private readonly AppDomain _appDomain; private readonly Assembly[] _assemblies; public AssemblyLoadContext(Assembly[] assemblies) { _appDomain = AppDomain.CurrentDomain; _assemblies = assemblies; _appDomain.AssemblyResolve += OnAssemblyResolve; } private Assembly OnAssemblyResolve(object sender, ResolveEventArgs args) { var name = args.Name; return _assemblies.FirstOrDefault(a => a.FullName == name); } public void Dispose() { _appDomain.AssemblyResolve -= OnAssemblyResolve; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET 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.VisualStudio.Debugger.Clr; using System; using System.Collections.Immutable; using System.Linq; using System.Reflection; namespace Microsoft.CodeAnalysis.ExpressionEvaluator { internal static class ReflectionUtilities { internal static Assembly Load(ImmutableArray<byte> assembly) { return Assembly.Load(assembly.ToArray()); } internal static object Instantiate(this Type type, params object[] args) { return Activator.CreateInstance( type, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.CreateInstance, binder: null, args: args, culture: null); } internal static AssemblyLoadContext Load(this DkmClrRuntimeInstance runtime) { return new AssemblyLoadContext(runtime.Assemblies); } internal static AssemblyLoadContext LoadAssemblies(params Assembly[] assemblies) { return new AssemblyLoadContext(assemblies); } internal static Assembly[] GetMscorlib(params Assembly[] additionalAssemblies) { var builder = ArrayBuilder<Assembly>.GetInstance(); builder.Add(typeof(object).Assembly); // mscorlib.dll builder.AddRange(additionalAssemblies); return builder.ToArrayAndFree(); } internal static Assembly[] GetMscorlibAndSystemCore(params Assembly[] additionalAssemblies) { var builder = ArrayBuilder<Assembly>.GetInstance(); builder.Add(typeof(object).Assembly); // mscorlib.dll builder.Add(typeof(Enumerable).Assembly); // System.Core.dll builder.AddRange(additionalAssemblies); return builder.ToArrayAndFree(); } internal sealed class AssemblyLoadContext : IDisposable { private readonly AppDomain _appDomain; private readonly Assembly[] _assemblies; public AssemblyLoadContext(Assembly[] assemblies) { _appDomain = AppDomain.CurrentDomain; _assemblies = assemblies; _appDomain.AssemblyResolve += OnAssemblyResolve; } private Assembly OnAssemblyResolve(object sender, ResolveEventArgs args) { var name = args.Name; return _assemblies.FirstOrDefault(a => a.FullName == name); } public void Dispose() { _appDomain.AssemblyResolve -= OnAssemblyResolve; } } } }
-1
dotnet/roslyn
55,138
Avoid cancellation exceptions in intermediate operations
Addresses the following exceptions: ![image](https://user-images.githubusercontent.com/1408396/127185947-8a005aea-ae1c-4755-bf0f-21dfb8101352.png)
sharwell
2021-07-27T15:51:28Z
2021-07-27T21:36:45Z
3d8acbd585a75e9cdb3509623bf6c39ceb46b2c2
719d4ffa2be734463e5d7d4d74b23b8006fd7727
Avoid cancellation exceptions in intermediate operations. Addresses the following exceptions: ![image](https://user-images.githubusercontent.com/1408396/127185947-8a005aea-ae1c-4755-bf0f-21dfb8101352.png)
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Options/EditorConfig/NamingStylePreferenceEditorConfigStorageLocation.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.Diagnostics.Analyzers.NamingStyles; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Options { internal sealed class NamingStylePreferenceEditorConfigStorageLocation : OptionStorageLocation2, IEditorConfigStorageLocation { public bool TryGetOption(IReadOnlyDictionary<string, string?> rawOptions, Type type, out object result) { var tuple = ParseDictionary(rawOptions, type); result = tuple.result; return tuple.succeeded; } private static (object result, bool succeeded) ParseDictionary( IReadOnlyDictionary<string, string?> allRawConventions, Type type) { if (type == typeof(NamingStylePreferences)) { var editorconfigNamingStylePreferences = EditorConfigNamingStyleParser.GetNamingStylesFromDictionary(allRawConventions); if (!editorconfigNamingStylePreferences.NamingRules.Any() && !editorconfigNamingStylePreferences.NamingStyles.Any() && !editorconfigNamingStylePreferences.SymbolSpecifications.Any()) { // We were not able to parse any rules from editorconfig, tell the caller that the parse failed return (result: editorconfigNamingStylePreferences, succeeded: false); } // no existing naming styles were passed so just return the set of styles that were parsed from editorconfig return (result: editorconfigNamingStylePreferences, succeeded: true); } throw ExceptionUtilities.UnexpectedValue(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.Generic; using System.Linq; using Microsoft.CodeAnalysis.Diagnostics.Analyzers.NamingStyles; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Options { internal sealed class NamingStylePreferenceEditorConfigStorageLocation : OptionStorageLocation2, IEditorConfigStorageLocation { public bool TryGetOption(IReadOnlyDictionary<string, string?> rawOptions, Type type, out object result) { var tuple = ParseDictionary(rawOptions, type); result = tuple.result; return tuple.succeeded; } private static (object result, bool succeeded) ParseDictionary( IReadOnlyDictionary<string, string?> allRawConventions, Type type) { if (type == typeof(NamingStylePreferences)) { var editorconfigNamingStylePreferences = EditorConfigNamingStyleParser.GetNamingStylesFromDictionary(allRawConventions); if (!editorconfigNamingStylePreferences.NamingRules.Any() && !editorconfigNamingStylePreferences.NamingStyles.Any() && !editorconfigNamingStylePreferences.SymbolSpecifications.Any()) { // We were not able to parse any rules from editorconfig, tell the caller that the parse failed return (result: editorconfigNamingStylePreferences, succeeded: false); } // no existing naming styles were passed so just return the set of styles that were parsed from editorconfig return (result: editorconfigNamingStylePreferences, succeeded: true); } throw ExceptionUtilities.UnexpectedValue(type); } } }
-1
dotnet/roslyn
55,138
Avoid cancellation exceptions in intermediate operations
Addresses the following exceptions: ![image](https://user-images.githubusercontent.com/1408396/127185947-8a005aea-ae1c-4755-bf0f-21dfb8101352.png)
sharwell
2021-07-27T15:51:28Z
2021-07-27T21:36:45Z
3d8acbd585a75e9cdb3509623bf6c39ceb46b2c2
719d4ffa2be734463e5d7d4d74b23b8006fd7727
Avoid cancellation exceptions in intermediate operations. Addresses the following exceptions: ![image](https://user-images.githubusercontent.com/1408396/127185947-8a005aea-ae1c-4755-bf0f-21dfb8101352.png)
./src/Features/Core/Portable/UseAutoProperty/AbstractUseAutoPropertyCodeFixProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Formatting.Rules; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Rename; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.UseAutoProperty { internal abstract class AbstractUseAutoPropertyCodeFixProvider<TTypeDeclarationSyntax, TPropertyDeclaration, TVariableDeclarator, TConstructorDeclaration, TExpression> : CodeFixProvider where TTypeDeclarationSyntax : SyntaxNode where TPropertyDeclaration : SyntaxNode where TVariableDeclarator : SyntaxNode where TConstructorDeclaration : SyntaxNode where TExpression : SyntaxNode { protected static SyntaxAnnotation SpecializedFormattingAnnotation = new(); public sealed override ImmutableArray<string> FixableDiagnosticIds => ImmutableArray.Create(IDEDiagnosticIds.UseAutoPropertyDiagnosticId); public sealed override FixAllProvider GetFixAllProvider() => WellKnownFixAllProviders.BatchFixer; protected abstract TPropertyDeclaration GetPropertyDeclaration(SyntaxNode node); protected abstract SyntaxNode GetNodeToRemove(TVariableDeclarator declarator); protected abstract IEnumerable<AbstractFormattingRule> GetFormattingRules(Document document); protected abstract Task<SyntaxNode> UpdatePropertyAsync( Document propertyDocument, Compilation compilation, IFieldSymbol fieldSymbol, IPropertySymbol propertySymbol, TPropertyDeclaration propertyDeclaration, bool isWrittenOutsideConstructor, CancellationToken cancellationToken); public sealed override Task RegisterCodeFixesAsync(CodeFixContext context) { foreach (var diagnostic in context.Diagnostics) { var priority = diagnostic.Severity == DiagnosticSeverity.Hidden ? CodeActionPriority.Low : CodeActionPriority.Medium; context.RegisterCodeFix( new UseAutoPropertyCodeAction( AnalyzersResources.Use_auto_property, c => ProcessResultAsync(context, diagnostic, c), priority), diagnostic); } return Task.CompletedTask; } private async Task<Solution> ProcessResultAsync(CodeFixContext context, Diagnostic diagnostic, CancellationToken cancellationToken) { var locations = diagnostic.AdditionalLocations; var propertyLocation = locations[0]; var declaratorLocation = locations[1]; var solution = context.Document.Project.Solution; var declarator = (TVariableDeclarator)declaratorLocation.FindNode(cancellationToken); var fieldDocument = solution.GetRequiredDocument(declarator.SyntaxTree); var fieldSemanticModel = await fieldDocument.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); var fieldSymbol = (IFieldSymbol)fieldSemanticModel.GetRequiredDeclaredSymbol(declarator, cancellationToken); var property = GetPropertyDeclaration(propertyLocation.FindNode(cancellationToken)); var propertyDocument = solution.GetRequiredDocument(property.SyntaxTree); var propertySemanticModel = await propertyDocument.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); var propertySymbol = (IPropertySymbol)propertySemanticModel.GetRequiredDeclaredSymbol(property, cancellationToken); Debug.Assert(fieldDocument.Project == propertyDocument.Project); var project = fieldDocument.Project; var compilation = await project.GetRequiredCompilationAsync(cancellationToken).ConfigureAwait(false); var fieldLocations = await Renamer.FindRenameLocationsAsync( solution, fieldSymbol, RenameOptionSet.From(solution), cancellationToken).ConfigureAwait(false); // First, create the updated property we want to replace the old property with var isWrittenToOutsideOfConstructor = IsWrittenToOutsideOfConstructorOrProperty(fieldSymbol, fieldLocations, property, cancellationToken); var updatedProperty = await UpdatePropertyAsync( propertyDocument, compilation, fieldSymbol, propertySymbol, property, isWrittenToOutsideOfConstructor, cancellationToken).ConfigureAwait(false); // Note: rename will try to update all the references in linked files as well. However, // this can lead to some very bad behavior as we will change the references in linked files // but only remove the field and update the property in a single document. So, you can // end in the state where you do this in one of the linked file: // // int Prop { get { return this.field; } } => int Prop { get { return this.Prop } } // // But in the main file we'll replace: // // int Prop { get { return this.field; } } => int Prop { get; } // // The workspace will see these as two irreconcilable edits. To avoid this, we disallow // any edits to the other links for the files containing the field and property. i.e. // rename will only be allowed to edit the exact same doc we're removing the field from // and the exact doc we're updating the property in. It can't touch the other linked // files for those docs. (It can of course touch any other documents unrelated to the // docs that the field and prop are declared in). var linkedFiles = new HashSet<DocumentId>(); linkedFiles.AddRange(fieldDocument.GetLinkedDocumentIds()); linkedFiles.AddRange(propertyDocument.GetLinkedDocumentIds()); var canEdit = new Dictionary<SyntaxTree, bool>(); // Now, rename all usages of the field to point at the property. Except don't actually // rename the field itself. We want to be able to find it again post rename. // // We're asking the rename API to update a bunch of references to an existing field to the same name as an // existing property. Rename will often flag this situation as an unresolvable conflict because the new // name won't bind to the field anymore. // // To address this, we let rename know that there is no conflict if the new symbol it resolves to is the // same as the property we're trying to get the references pointing to. var filteredLocations = fieldLocations.Filter( location => location.SourceTree != null && !location.IntersectsWith(declaratorLocation) && CanEditDocument(solution, location.SourceTree, linkedFiles, canEdit)); var resolution = await filteredLocations.ResolveConflictsAsync( propertySymbol.Name, nonConflictSymbols: ImmutableHashSet.Create<ISymbol>(propertySymbol), cancellationToken).ConfigureAwait(false); Contract.ThrowIfTrue(resolution.ErrorMessage != null); solution = resolution.NewSolution; // Now find the field and property again post rename. fieldDocument = solution.GetRequiredDocument(fieldDocument.Id); propertyDocument = solution.GetRequiredDocument(propertyDocument.Id); Debug.Assert(fieldDocument.Project == propertyDocument.Project); compilation = await fieldDocument.Project.GetRequiredCompilationAsync(cancellationToken).ConfigureAwait(false); fieldSymbol = (IFieldSymbol?)fieldSymbol.GetSymbolKey(cancellationToken).Resolve(compilation, cancellationToken: cancellationToken).Symbol; propertySymbol = (IPropertySymbol?)propertySymbol.GetSymbolKey(cancellationToken).Resolve(compilation, cancellationToken: cancellationToken).Symbol; Contract.ThrowIfTrue(fieldSymbol == null || propertySymbol == null); declarator = (TVariableDeclarator)await fieldSymbol.DeclaringSyntaxReferences[0].GetSyntaxAsync(cancellationToken).ConfigureAwait(false); property = GetPropertyDeclaration(await propertySymbol.DeclaringSyntaxReferences[0].GetSyntaxAsync(cancellationToken).ConfigureAwait(false)); var nodeToRemove = GetNodeToRemove(declarator); // If we have a situation where the property is the second member in a type, and it // would become the first, then remove any leading blank lines from it so we don't have // random blanks above it that used to space it from the field that was there. // // The reason we do this special processing is that the first member of a type tends to // be special wrt leading trivia. i.e. users do not normally put blank lines before the // first member. And so, when a type now becomes the first member, we want to follow the // user's common pattern here. // // In all other code cases, i.e.when there are multiple fields above, or the field is // below the property, then the property isn't now becoming "the first member", and as // such, it doesn't want this special behavior about it's leading blank lines. i.e. if // the user has: // // class C // { // int i; // int j; // // int Prop => j; // } // // Then if we remove 'j' (or even 'i'), then 'Prop' would stay the non-first member, and // would definitely want to keep that blank line above it. // // In essence, the blank line above the property exists for separation from what's above // it. As long as something is above it, we keep the separation. However, if the // property becomes the first member in the type, the separation is now inappropriate // because there's nothing to actually separate it from. if (fieldDocument == propertyDocument) { var syntaxFacts = fieldDocument.GetRequiredLanguageService<ISyntaxFactsService>(); if (WillRemoveFirstFieldInTypeDirectlyAboveProperty(syntaxFacts, property, nodeToRemove) && syntaxFacts.GetLeadingBlankLines(nodeToRemove).Length == 0) { updatedProperty = syntaxFacts.GetNodeWithoutLeadingBlankLines(updatedProperty); } } var syntaxRemoveOptions = CreateSyntaxRemoveOptions(nodeToRemove); if (fieldDocument == propertyDocument) { // Same file. Have to do this in a slightly complicated fashion. var declaratorTreeRoot = await fieldDocument.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var editor = new SyntaxEditor(declaratorTreeRoot, fieldDocument.Project.Solution.Workspace); editor.ReplaceNode(property, updatedProperty); editor.RemoveNode(nodeToRemove, syntaxRemoveOptions); var newRoot = editor.GetChangedRoot(); newRoot = await FormatAsync(newRoot, fieldDocument, cancellationToken).ConfigureAwait(false); return solution.WithDocumentSyntaxRoot(fieldDocument.Id, newRoot); } else { // In different files. Just update both files. var fieldTreeRoot = await fieldDocument.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var propertyTreeRoot = await propertyDocument.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var newFieldTreeRoot = fieldTreeRoot.RemoveNode(nodeToRemove, syntaxRemoveOptions); Contract.ThrowIfNull(newFieldTreeRoot); var newPropertyTreeRoot = propertyTreeRoot.ReplaceNode(property, updatedProperty); newFieldTreeRoot = await FormatAsync(newFieldTreeRoot, fieldDocument, cancellationToken).ConfigureAwait(false); newPropertyTreeRoot = await FormatAsync(newPropertyTreeRoot, propertyDocument, cancellationToken).ConfigureAwait(false); var updatedSolution = solution.WithDocumentSyntaxRoot(fieldDocument.Id, newFieldTreeRoot); updatedSolution = updatedSolution.WithDocumentSyntaxRoot(propertyDocument.Id, newPropertyTreeRoot); return updatedSolution; } } private static SyntaxRemoveOptions CreateSyntaxRemoveOptions(SyntaxNode nodeToRemove) { var syntaxRemoveOptions = SyntaxGenerator.DefaultRemoveOptions; var hasDirective = nodeToRemove.GetLeadingTrivia().Any(t => t.IsDirective); if (hasDirective) { syntaxRemoveOptions |= SyntaxRemoveOptions.KeepLeadingTrivia; } return syntaxRemoveOptions; } private static bool WillRemoveFirstFieldInTypeDirectlyAboveProperty( ISyntaxFactsService syntaxFacts, TPropertyDeclaration property, SyntaxNode fieldToRemove) { if (fieldToRemove.Parent == property.Parent && fieldToRemove.Parent is TTypeDeclarationSyntax typeDeclaration) { var members = syntaxFacts.GetMembersOfTypeDeclaration(typeDeclaration); return members[0] == fieldToRemove && members[1] == property; } return false; } private static bool CanEditDocument( Solution solution, SyntaxTree sourceTree, HashSet<DocumentId> linkedDocuments, Dictionary<SyntaxTree, bool> canEdit) { if (!canEdit.ContainsKey(sourceTree)) { var document = solution.GetDocument(sourceTree); canEdit[sourceTree] = document != null && !linkedDocuments.Contains(document.Id); } return canEdit[sourceTree]; } private async Task<SyntaxNode> FormatAsync(SyntaxNode newRoot, Document document, CancellationToken cancellationToken) { var formattingRules = GetFormattingRules(document); if (formattingRules == null) { return newRoot; } var options = await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false); return Formatter.Format(newRoot, SpecializedFormattingAnnotation, document.Project.Solution.Workspace, options, formattingRules, cancellationToken); } private static bool IsWrittenToOutsideOfConstructorOrProperty( IFieldSymbol field, RenameLocations renameLocations, TPropertyDeclaration propertyDeclaration, CancellationToken cancellationToken) { var constructorNodes = field.ContainingType.GetMembers() .Where(m => m.IsConstructor()) .SelectMany(c => c.DeclaringSyntaxReferences) .Select(s => s.GetSyntax(cancellationToken)) .Select(n => n.FirstAncestorOrSelf<TConstructorDeclaration>()) .WhereNotNull() .ToSet(); return renameLocations.Locations.Any( loc => IsWrittenToOutsideOfConstructorOrProperty( renameLocations.Solution, loc, propertyDeclaration, constructorNodes, cancellationToken)); } private static bool IsWrittenToOutsideOfConstructorOrProperty( Solution solution, RenameLocation location, TPropertyDeclaration propertyDeclaration, ISet<TConstructorDeclaration> constructorNodes, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); if (!location.IsWrittenTo) { // We don't need a setter if we're not writing to this field. return false; } var syntaxFacts = solution.GetRequiredDocument(location.DocumentId).GetRequiredLanguageService<ISyntaxFactsService>(); var node = location.Location.FindToken(cancellationToken).Parent; while (node != null && !syntaxFacts.IsAnonymousOrLocalFunction(node)) { if (node == propertyDeclaration) { // Not a write outside the property declaration. return false; } if (constructorNodes.Contains(node)) { // Not a write outside a constructor of the field's class return false; } node = node.Parent; } // We do need a setter return true; } private class UseAutoPropertyCodeAction : CustomCodeActions.SolutionChangeAction { public UseAutoPropertyCodeAction(string title, Func<CancellationToken, Task<Solution>> createChangedSolution, CodeActionPriority priority) : base(title, createChangedSolution, title) { Priority = priority; } internal override CodeActionPriority Priority { get; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; 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.Formatting; using Microsoft.CodeAnalysis.Formatting.Rules; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Rename; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.UseAutoProperty { internal abstract class AbstractUseAutoPropertyCodeFixProvider<TTypeDeclarationSyntax, TPropertyDeclaration, TVariableDeclarator, TConstructorDeclaration, TExpression> : CodeFixProvider where TTypeDeclarationSyntax : SyntaxNode where TPropertyDeclaration : SyntaxNode where TVariableDeclarator : SyntaxNode where TConstructorDeclaration : SyntaxNode where TExpression : SyntaxNode { protected static SyntaxAnnotation SpecializedFormattingAnnotation = new(); public sealed override ImmutableArray<string> FixableDiagnosticIds => ImmutableArray.Create(IDEDiagnosticIds.UseAutoPropertyDiagnosticId); public sealed override FixAllProvider GetFixAllProvider() => WellKnownFixAllProviders.BatchFixer; protected abstract TPropertyDeclaration GetPropertyDeclaration(SyntaxNode node); protected abstract SyntaxNode GetNodeToRemove(TVariableDeclarator declarator); protected abstract IEnumerable<AbstractFormattingRule> GetFormattingRules(Document document); protected abstract Task<SyntaxNode> UpdatePropertyAsync( Document propertyDocument, Compilation compilation, IFieldSymbol fieldSymbol, IPropertySymbol propertySymbol, TPropertyDeclaration propertyDeclaration, bool isWrittenOutsideConstructor, CancellationToken cancellationToken); public sealed override Task RegisterCodeFixesAsync(CodeFixContext context) { foreach (var diagnostic in context.Diagnostics) { var priority = diagnostic.Severity == DiagnosticSeverity.Hidden ? CodeActionPriority.Low : CodeActionPriority.Medium; context.RegisterCodeFix( new UseAutoPropertyCodeAction( AnalyzersResources.Use_auto_property, c => ProcessResultAsync(context, diagnostic, c), priority), diagnostic); } return Task.CompletedTask; } private async Task<Solution> ProcessResultAsync(CodeFixContext context, Diagnostic diagnostic, CancellationToken cancellationToken) { var locations = diagnostic.AdditionalLocations; var propertyLocation = locations[0]; var declaratorLocation = locations[1]; var solution = context.Document.Project.Solution; var declarator = (TVariableDeclarator)declaratorLocation.FindNode(cancellationToken); var fieldDocument = solution.GetRequiredDocument(declarator.SyntaxTree); var fieldSemanticModel = await fieldDocument.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); var fieldSymbol = (IFieldSymbol)fieldSemanticModel.GetRequiredDeclaredSymbol(declarator, cancellationToken); var property = GetPropertyDeclaration(propertyLocation.FindNode(cancellationToken)); var propertyDocument = solution.GetRequiredDocument(property.SyntaxTree); var propertySemanticModel = await propertyDocument.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); var propertySymbol = (IPropertySymbol)propertySemanticModel.GetRequiredDeclaredSymbol(property, cancellationToken); Debug.Assert(fieldDocument.Project == propertyDocument.Project); var project = fieldDocument.Project; var compilation = await project.GetRequiredCompilationAsync(cancellationToken).ConfigureAwait(false); var fieldLocations = await Renamer.FindRenameLocationsAsync( solution, fieldSymbol, RenameOptionSet.From(solution), cancellationToken).ConfigureAwait(false); // First, create the updated property we want to replace the old property with var isWrittenToOutsideOfConstructor = IsWrittenToOutsideOfConstructorOrProperty(fieldSymbol, fieldLocations, property, cancellationToken); var updatedProperty = await UpdatePropertyAsync( propertyDocument, compilation, fieldSymbol, propertySymbol, property, isWrittenToOutsideOfConstructor, cancellationToken).ConfigureAwait(false); // Note: rename will try to update all the references in linked files as well. However, // this can lead to some very bad behavior as we will change the references in linked files // but only remove the field and update the property in a single document. So, you can // end in the state where you do this in one of the linked file: // // int Prop { get { return this.field; } } => int Prop { get { return this.Prop } } // // But in the main file we'll replace: // // int Prop { get { return this.field; } } => int Prop { get; } // // The workspace will see these as two irreconcilable edits. To avoid this, we disallow // any edits to the other links for the files containing the field and property. i.e. // rename will only be allowed to edit the exact same doc we're removing the field from // and the exact doc we're updating the property in. It can't touch the other linked // files for those docs. (It can of course touch any other documents unrelated to the // docs that the field and prop are declared in). var linkedFiles = new HashSet<DocumentId>(); linkedFiles.AddRange(fieldDocument.GetLinkedDocumentIds()); linkedFiles.AddRange(propertyDocument.GetLinkedDocumentIds()); var canEdit = new Dictionary<SyntaxTree, bool>(); // Now, rename all usages of the field to point at the property. Except don't actually // rename the field itself. We want to be able to find it again post rename. // // We're asking the rename API to update a bunch of references to an existing field to the same name as an // existing property. Rename will often flag this situation as an unresolvable conflict because the new // name won't bind to the field anymore. // // To address this, we let rename know that there is no conflict if the new symbol it resolves to is the // same as the property we're trying to get the references pointing to. var filteredLocations = fieldLocations.Filter( location => location.SourceTree != null && !location.IntersectsWith(declaratorLocation) && CanEditDocument(solution, location.SourceTree, linkedFiles, canEdit)); var resolution = await filteredLocations.ResolveConflictsAsync( propertySymbol.Name, nonConflictSymbols: ImmutableHashSet.Create<ISymbol>(propertySymbol), cancellationToken).ConfigureAwait(false); Contract.ThrowIfTrue(resolution.ErrorMessage != null); solution = resolution.NewSolution; // Now find the field and property again post rename. fieldDocument = solution.GetRequiredDocument(fieldDocument.Id); propertyDocument = solution.GetRequiredDocument(propertyDocument.Id); Debug.Assert(fieldDocument.Project == propertyDocument.Project); compilation = await fieldDocument.Project.GetRequiredCompilationAsync(cancellationToken).ConfigureAwait(false); fieldSymbol = (IFieldSymbol?)fieldSymbol.GetSymbolKey(cancellationToken).Resolve(compilation, cancellationToken: cancellationToken).Symbol; propertySymbol = (IPropertySymbol?)propertySymbol.GetSymbolKey(cancellationToken).Resolve(compilation, cancellationToken: cancellationToken).Symbol; Contract.ThrowIfTrue(fieldSymbol == null || propertySymbol == null); declarator = (TVariableDeclarator)await fieldSymbol.DeclaringSyntaxReferences[0].GetSyntaxAsync(cancellationToken).ConfigureAwait(false); property = GetPropertyDeclaration(await propertySymbol.DeclaringSyntaxReferences[0].GetSyntaxAsync(cancellationToken).ConfigureAwait(false)); var nodeToRemove = GetNodeToRemove(declarator); // If we have a situation where the property is the second member in a type, and it // would become the first, then remove any leading blank lines from it so we don't have // random blanks above it that used to space it from the field that was there. // // The reason we do this special processing is that the first member of a type tends to // be special wrt leading trivia. i.e. users do not normally put blank lines before the // first member. And so, when a type now becomes the first member, we want to follow the // user's common pattern here. // // In all other code cases, i.e.when there are multiple fields above, or the field is // below the property, then the property isn't now becoming "the first member", and as // such, it doesn't want this special behavior about it's leading blank lines. i.e. if // the user has: // // class C // { // int i; // int j; // // int Prop => j; // } // // Then if we remove 'j' (or even 'i'), then 'Prop' would stay the non-first member, and // would definitely want to keep that blank line above it. // // In essence, the blank line above the property exists for separation from what's above // it. As long as something is above it, we keep the separation. However, if the // property becomes the first member in the type, the separation is now inappropriate // because there's nothing to actually separate it from. if (fieldDocument == propertyDocument) { var syntaxFacts = fieldDocument.GetRequiredLanguageService<ISyntaxFactsService>(); if (WillRemoveFirstFieldInTypeDirectlyAboveProperty(syntaxFacts, property, nodeToRemove) && syntaxFacts.GetLeadingBlankLines(nodeToRemove).Length == 0) { updatedProperty = syntaxFacts.GetNodeWithoutLeadingBlankLines(updatedProperty); } } var syntaxRemoveOptions = CreateSyntaxRemoveOptions(nodeToRemove); if (fieldDocument == propertyDocument) { // Same file. Have to do this in a slightly complicated fashion. var declaratorTreeRoot = await fieldDocument.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var editor = new SyntaxEditor(declaratorTreeRoot, fieldDocument.Project.Solution.Workspace); editor.ReplaceNode(property, updatedProperty); editor.RemoveNode(nodeToRemove, syntaxRemoveOptions); var newRoot = editor.GetChangedRoot(); newRoot = await FormatAsync(newRoot, fieldDocument, cancellationToken).ConfigureAwait(false); return solution.WithDocumentSyntaxRoot(fieldDocument.Id, newRoot); } else { // In different files. Just update both files. var fieldTreeRoot = await fieldDocument.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var propertyTreeRoot = await propertyDocument.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var newFieldTreeRoot = fieldTreeRoot.RemoveNode(nodeToRemove, syntaxRemoveOptions); Contract.ThrowIfNull(newFieldTreeRoot); var newPropertyTreeRoot = propertyTreeRoot.ReplaceNode(property, updatedProperty); newFieldTreeRoot = await FormatAsync(newFieldTreeRoot, fieldDocument, cancellationToken).ConfigureAwait(false); newPropertyTreeRoot = await FormatAsync(newPropertyTreeRoot, propertyDocument, cancellationToken).ConfigureAwait(false); var updatedSolution = solution.WithDocumentSyntaxRoot(fieldDocument.Id, newFieldTreeRoot); updatedSolution = updatedSolution.WithDocumentSyntaxRoot(propertyDocument.Id, newPropertyTreeRoot); return updatedSolution; } } private static SyntaxRemoveOptions CreateSyntaxRemoveOptions(SyntaxNode nodeToRemove) { var syntaxRemoveOptions = SyntaxGenerator.DefaultRemoveOptions; var hasDirective = nodeToRemove.GetLeadingTrivia().Any(t => t.IsDirective); if (hasDirective) { syntaxRemoveOptions |= SyntaxRemoveOptions.KeepLeadingTrivia; } return syntaxRemoveOptions; } private static bool WillRemoveFirstFieldInTypeDirectlyAboveProperty( ISyntaxFactsService syntaxFacts, TPropertyDeclaration property, SyntaxNode fieldToRemove) { if (fieldToRemove.Parent == property.Parent && fieldToRemove.Parent is TTypeDeclarationSyntax typeDeclaration) { var members = syntaxFacts.GetMembersOfTypeDeclaration(typeDeclaration); return members[0] == fieldToRemove && members[1] == property; } return false; } private static bool CanEditDocument( Solution solution, SyntaxTree sourceTree, HashSet<DocumentId> linkedDocuments, Dictionary<SyntaxTree, bool> canEdit) { if (!canEdit.ContainsKey(sourceTree)) { var document = solution.GetDocument(sourceTree); canEdit[sourceTree] = document != null && !linkedDocuments.Contains(document.Id); } return canEdit[sourceTree]; } private async Task<SyntaxNode> FormatAsync(SyntaxNode newRoot, Document document, CancellationToken cancellationToken) { var formattingRules = GetFormattingRules(document); if (formattingRules == null) { return newRoot; } var options = await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false); return Formatter.Format(newRoot, SpecializedFormattingAnnotation, document.Project.Solution.Workspace, options, formattingRules, cancellationToken); } private static bool IsWrittenToOutsideOfConstructorOrProperty( IFieldSymbol field, RenameLocations renameLocations, TPropertyDeclaration propertyDeclaration, CancellationToken cancellationToken) { var constructorNodes = field.ContainingType.GetMembers() .Where(m => m.IsConstructor()) .SelectMany(c => c.DeclaringSyntaxReferences) .Select(s => s.GetSyntax(cancellationToken)) .Select(n => n.FirstAncestorOrSelf<TConstructorDeclaration>()) .WhereNotNull() .ToSet(); return renameLocations.Locations.Any( loc => IsWrittenToOutsideOfConstructorOrProperty( renameLocations.Solution, loc, propertyDeclaration, constructorNodes, cancellationToken)); } private static bool IsWrittenToOutsideOfConstructorOrProperty( Solution solution, RenameLocation location, TPropertyDeclaration propertyDeclaration, ISet<TConstructorDeclaration> constructorNodes, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); if (!location.IsWrittenTo) { // We don't need a setter if we're not writing to this field. return false; } var syntaxFacts = solution.GetRequiredDocument(location.DocumentId).GetRequiredLanguageService<ISyntaxFactsService>(); var node = location.Location.FindToken(cancellationToken).Parent; while (node != null && !syntaxFacts.IsAnonymousOrLocalFunction(node)) { if (node == propertyDeclaration) { // Not a write outside the property declaration. return false; } if (constructorNodes.Contains(node)) { // Not a write outside a constructor of the field's class return false; } node = node.Parent; } // We do need a setter return true; } private class UseAutoPropertyCodeAction : CustomCodeActions.SolutionChangeAction { public UseAutoPropertyCodeAction(string title, Func<CancellationToken, Task<Solution>> createChangedSolution, CodeActionPriority priority) : base(title, createChangedSolution, title) { Priority = priority; } internal override CodeActionPriority Priority { get; } } } }
-1
dotnet/roslyn
55,138
Avoid cancellation exceptions in intermediate operations
Addresses the following exceptions: ![image](https://user-images.githubusercontent.com/1408396/127185947-8a005aea-ae1c-4755-bf0f-21dfb8101352.png)
sharwell
2021-07-27T15:51:28Z
2021-07-27T21:36:45Z
3d8acbd585a75e9cdb3509623bf6c39ceb46b2c2
719d4ffa2be734463e5d7d4d74b23b8006fd7727
Avoid cancellation exceptions in intermediate operations. Addresses the following exceptions: ![image](https://user-images.githubusercontent.com/1408396/127185947-8a005aea-ae1c-4755-bf0f-21dfb8101352.png)
./src/Tools/ExternalAccess/Razor/IRazorDynamicFileInfoProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host; namespace Microsoft.CodeAnalysis.ExternalAccess.Razor { internal interface IRazorDynamicFileInfoProvider { /// <summary> /// return <see cref="DynamicFileInfo"/> for the context given /// </summary> /// <param name="projectId"><see cref="ProjectId"/> this file belongs to</param> /// <param name="projectFilePath">full path to project file (ex, csproj)</param> /// <param name="filePath">full path to non source file (ex, cshtml)</param> /// <returns>null if this provider can't handle the given file</returns> Task<RazorDynamicFileInfo> GetDynamicFileInfoAsync(ProjectId projectId, string projectFilePath, string filePath, CancellationToken cancellationToken); /// <summary> /// let provider know certain file has been removed /// </summary> /// <param name="projectId"><see cref="ProjectId"/> this file belongs to</param> /// <param name="projectFilePath">full path to project file (ex, csproj)</param> /// <param name="filePath">full path to non source file (ex, cshtml)</param> Task RemoveDynamicFileInfoAsync(ProjectId projectId, string projectFilePath, string filePath, CancellationToken cancellationToken); /// <summary> /// indicate content of a file has updated. the event argument "string" should be same as "filepath" given to <see cref="GetDynamicFileInfoAsync(ProjectId, string, string, CancellationToken)"/> /// </summary> event EventHandler<string> Updated; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host; namespace Microsoft.CodeAnalysis.ExternalAccess.Razor { internal interface IRazorDynamicFileInfoProvider { /// <summary> /// return <see cref="DynamicFileInfo"/> for the context given /// </summary> /// <param name="projectId"><see cref="ProjectId"/> this file belongs to</param> /// <param name="projectFilePath">full path to project file (ex, csproj)</param> /// <param name="filePath">full path to non source file (ex, cshtml)</param> /// <returns>null if this provider can't handle the given file</returns> Task<RazorDynamicFileInfo> GetDynamicFileInfoAsync(ProjectId projectId, string projectFilePath, string filePath, CancellationToken cancellationToken); /// <summary> /// let provider know certain file has been removed /// </summary> /// <param name="projectId"><see cref="ProjectId"/> this file belongs to</param> /// <param name="projectFilePath">full path to project file (ex, csproj)</param> /// <param name="filePath">full path to non source file (ex, cshtml)</param> Task RemoveDynamicFileInfoAsync(ProjectId projectId, string projectFilePath, string filePath, CancellationToken cancellationToken); /// <summary> /// indicate content of a file has updated. the event argument "string" should be same as "filepath" given to <see cref="GetDynamicFileInfoAsync(ProjectId, string, string, CancellationToken)"/> /// </summary> event EventHandler<string> Updated; } }
-1
dotnet/roslyn
55,138
Avoid cancellation exceptions in intermediate operations
Addresses the following exceptions: ![image](https://user-images.githubusercontent.com/1408396/127185947-8a005aea-ae1c-4755-bf0f-21dfb8101352.png)
sharwell
2021-07-27T15:51:28Z
2021-07-27T21:36:45Z
3d8acbd585a75e9cdb3509623bf6c39ceb46b2c2
719d4ffa2be734463e5d7d4d74b23b8006fd7727
Avoid cancellation exceptions in intermediate operations. Addresses the following exceptions: ![image](https://user-images.githubusercontent.com/1408396/127185947-8a005aea-ae1c-4755-bf0f-21dfb8101352.png)
./src/Features/CSharp/Portable/Completion/CompletionProviders/ExternAliasCompletionProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Immutable; using System.Composition; using System.Linq; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Completion; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Completion.Providers { [ExportCompletionProvider(nameof(ExternAliasCompletionProvider), LanguageNames.CSharp)] [ExtensionOrder(After = nameof(SnippetCompletionProvider))] [Shared] internal class ExternAliasCompletionProvider : LSPCompletionProvider { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public ExternAliasCompletionProvider() { } public override bool IsInsertionTrigger(SourceText text, int characterPosition, OptionSet options) => CompletionUtilities.IsTriggerCharacter(text, characterPosition, options); public override ImmutableHashSet<char> TriggerCharacters { get; } = CompletionUtilities.CommonTriggerCharacters; public override async Task ProvideCompletionsAsync(CompletionContext context) { try { var document = context.Document; var position = context.Position; var cancellationToken = context.CancellationToken; var tree = await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); if (tree.IsInNonUserCode(position, cancellationToken)) { return; } var targetToken = tree .FindTokenOnLeftOfPosition(position, cancellationToken) .GetPreviousTokenIfTouchingWord(position); if (!targetToken.IsKind(SyntaxKind.AliasKeyword) && !(targetToken.IsKind(SyntaxKind.IdentifierToken) && targetToken.HasMatchingText(SyntaxKind.AliasKeyword))) { return; } if (targetToken.Parent.IsKind(SyntaxKind.ExternAliasDirective) || (targetToken.Parent.IsKind(SyntaxKind.IdentifierName) && targetToken.Parent.IsParentKind(SyntaxKind.IncompleteMember))) { var compilation = await document.Project.GetCompilationAsync(cancellationToken).ConfigureAwait(false); var aliases = compilation.ExternalReferences.SelectMany(r => r.Properties.Aliases).ToSet(); if (aliases.Any()) { var root = await tree.GetRootAsync(cancellationToken).ConfigureAwait(false); var usedAliases = root.ChildNodes().OfType<ExternAliasDirectiveSyntax>() .Where(e => !e.Identifier.IsMissing) .Select(e => e.Identifier.ValueText); aliases.RemoveRange(usedAliases); aliases.Remove(MetadataReferenceProperties.GlobalAlias); var text = await document.GetTextAsync(cancellationToken).ConfigureAwait(false); foreach (var alias in aliases) { context.AddItem(CommonCompletionItem.Create( alias, displayTextSuffix: "", CompletionItemRules.Default, glyph: Glyph.Namespace)); } } } } catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e)) { // nop } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Immutable; using System.Composition; using System.Linq; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Completion; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Completion.Providers { [ExportCompletionProvider(nameof(ExternAliasCompletionProvider), LanguageNames.CSharp)] [ExtensionOrder(After = nameof(SnippetCompletionProvider))] [Shared] internal class ExternAliasCompletionProvider : LSPCompletionProvider { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public ExternAliasCompletionProvider() { } public override bool IsInsertionTrigger(SourceText text, int characterPosition, OptionSet options) => CompletionUtilities.IsTriggerCharacter(text, characterPosition, options); public override ImmutableHashSet<char> TriggerCharacters { get; } = CompletionUtilities.CommonTriggerCharacters; public override async Task ProvideCompletionsAsync(CompletionContext context) { try { var document = context.Document; var position = context.Position; var cancellationToken = context.CancellationToken; var tree = await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); if (tree.IsInNonUserCode(position, cancellationToken)) { return; } var targetToken = tree .FindTokenOnLeftOfPosition(position, cancellationToken) .GetPreviousTokenIfTouchingWord(position); if (!targetToken.IsKind(SyntaxKind.AliasKeyword) && !(targetToken.IsKind(SyntaxKind.IdentifierToken) && targetToken.HasMatchingText(SyntaxKind.AliasKeyword))) { return; } if (targetToken.Parent.IsKind(SyntaxKind.ExternAliasDirective) || (targetToken.Parent.IsKind(SyntaxKind.IdentifierName) && targetToken.Parent.IsParentKind(SyntaxKind.IncompleteMember))) { var compilation = await document.Project.GetCompilationAsync(cancellationToken).ConfigureAwait(false); var aliases = compilation.ExternalReferences.SelectMany(r => r.Properties.Aliases).ToSet(); if (aliases.Any()) { var root = await tree.GetRootAsync(cancellationToken).ConfigureAwait(false); var usedAliases = root.ChildNodes().OfType<ExternAliasDirectiveSyntax>() .Where(e => !e.Identifier.IsMissing) .Select(e => e.Identifier.ValueText); aliases.RemoveRange(usedAliases); aliases.Remove(MetadataReferenceProperties.GlobalAlias); var text = await document.GetTextAsync(cancellationToken).ConfigureAwait(false); foreach (var alias in aliases) { context.AddItem(CommonCompletionItem.Create( alias, displayTextSuffix: "", CompletionItemRules.Default, glyph: Glyph.Namespace)); } } } } catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e)) { // nop } } } }
-1
dotnet/roslyn
55,138
Avoid cancellation exceptions in intermediate operations
Addresses the following exceptions: ![image](https://user-images.githubusercontent.com/1408396/127185947-8a005aea-ae1c-4755-bf0f-21dfb8101352.png)
sharwell
2021-07-27T15:51:28Z
2021-07-27T21:36:45Z
3d8acbd585a75e9cdb3509623bf6c39ceb46b2c2
719d4ffa2be734463e5d7d4d74b23b8006fd7727
Avoid cancellation exceptions in intermediate operations. Addresses the following exceptions: ![image](https://user-images.githubusercontent.com/1408396/127185947-8a005aea-ae1c-4755-bf0f-21dfb8101352.png)
./src/Compilers/Core/Portable/SymbolDisplay/SymbolDisplayPartKind.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace Microsoft.CodeAnalysis { /// <summary> /// Specifies the kinds of a piece of classified text (SymbolDisplayPart). /// </summary> public enum SymbolDisplayPartKind { /// <summary>The name of an alias.</summary> AliasName = 0, /// <summary>The name of an assembly.</summary> AssemblyName = 1, /// <summary>The name of a class.</summary> ClassName = 2, /// <summary>The name of a delegate.</summary> DelegateName = 3, /// <summary>The name of an enum.</summary> EnumName = 4, /// <summary>The name of an error type.</summary> /// <seealso cref="IErrorTypeSymbol"/> ErrorTypeName = 5, /// <summary>The name of an event.</summary> EventName = 6, /// <summary>The name of a field.</summary> FieldName = 7, /// <summary>The name of an interface.</summary> InterfaceName = 8, /// <summary>A language keyword.</summary> Keyword = 9, /// <summary>The name of a label.</summary> LabelName = 10, /// <summary>A line-break (i.e. whitespace).</summary> LineBreak = 11, /// <summary>A numeric literal.</summary> /// <remarks>Typically for the default values of parameters and the constant values of fields.</remarks> NumericLiteral = 12, /// <summary>A string literal.</summary> /// <remarks>Typically for the default values of parameters and the constant values of fields.</remarks> StringLiteral = 13, /// <summary>The name of a local.</summary> LocalName = 14, /// <summary>The name of a method.</summary> MethodName = 15, /// <summary>The name of a module.</summary> ModuleName = 16, /// <summary>The name of a namespace.</summary> NamespaceName = 17, /// <summary>The symbol of an operator (e.g. "+").</summary> Operator = 18, /// <summary>The name of a parameter.</summary> ParameterName = 19, /// <summary>The name of a property.</summary> PropertyName = 20, /// <summary>A punctuation character (e.g. "(", ".", ",") other than an <see cref="Operator"/>.</summary> Punctuation = 21, /// <summary>A single space character.</summary> Space = 22, /// <summary>The name of a struct (structure in Visual Basic).</summary> StructName = 23, /// <summary>A keyword-like part for anonymous types (not actually a keyword).</summary> AnonymousTypeIndicator = 24, /// <summary>An unclassified part.</summary> /// <remarks>Never returned - only set in user-constructed parts.</remarks> Text = 25, /// <summary>The name of a type parameter.</summary> TypeParameterName = 26, /// <summary>The name of a query range variable.</summary> RangeVariableName = 27, /// <summary>The name of an enum member.</summary> EnumMemberName = 28, /// <summary>The name of a reduced extension method.</summary> /// <remarks> /// When an extension method is in it's non-reduced form it will be will be marked as MethodName. /// </remarks> ExtensionMethodName = 29, /// <summary>The name of a field or local constant.</summary> ConstantName = 30, /// <summary>The name of a record class.</summary> RecordClassName = 31, /// <summary>The name of a record struct.</summary> RecordStructName = 32, } internal static class InternalSymbolDisplayPartKind { private const SymbolDisplayPartKind @base = SymbolDisplayPartKind.RecordStructName + 1; public const SymbolDisplayPartKind Arity = @base + 0; public const SymbolDisplayPartKind Other = @base + 1; } internal static partial class EnumBounds { internal static bool IsValid(this SymbolDisplayPartKind value) { return (value >= SymbolDisplayPartKind.AliasName && value <= SymbolDisplayPartKind.RecordStructName) || (value >= InternalSymbolDisplayPartKind.Arity && value <= InternalSymbolDisplayPartKind.Other); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace Microsoft.CodeAnalysis { /// <summary> /// Specifies the kinds of a piece of classified text (SymbolDisplayPart). /// </summary> public enum SymbolDisplayPartKind { /// <summary>The name of an alias.</summary> AliasName = 0, /// <summary>The name of an assembly.</summary> AssemblyName = 1, /// <summary>The name of a class.</summary> ClassName = 2, /// <summary>The name of a delegate.</summary> DelegateName = 3, /// <summary>The name of an enum.</summary> EnumName = 4, /// <summary>The name of an error type.</summary> /// <seealso cref="IErrorTypeSymbol"/> ErrorTypeName = 5, /// <summary>The name of an event.</summary> EventName = 6, /// <summary>The name of a field.</summary> FieldName = 7, /// <summary>The name of an interface.</summary> InterfaceName = 8, /// <summary>A language keyword.</summary> Keyword = 9, /// <summary>The name of a label.</summary> LabelName = 10, /// <summary>A line-break (i.e. whitespace).</summary> LineBreak = 11, /// <summary>A numeric literal.</summary> /// <remarks>Typically for the default values of parameters and the constant values of fields.</remarks> NumericLiteral = 12, /// <summary>A string literal.</summary> /// <remarks>Typically for the default values of parameters and the constant values of fields.</remarks> StringLiteral = 13, /// <summary>The name of a local.</summary> LocalName = 14, /// <summary>The name of a method.</summary> MethodName = 15, /// <summary>The name of a module.</summary> ModuleName = 16, /// <summary>The name of a namespace.</summary> NamespaceName = 17, /// <summary>The symbol of an operator (e.g. "+").</summary> Operator = 18, /// <summary>The name of a parameter.</summary> ParameterName = 19, /// <summary>The name of a property.</summary> PropertyName = 20, /// <summary>A punctuation character (e.g. "(", ".", ",") other than an <see cref="Operator"/>.</summary> Punctuation = 21, /// <summary>A single space character.</summary> Space = 22, /// <summary>The name of a struct (structure in Visual Basic).</summary> StructName = 23, /// <summary>A keyword-like part for anonymous types (not actually a keyword).</summary> AnonymousTypeIndicator = 24, /// <summary>An unclassified part.</summary> /// <remarks>Never returned - only set in user-constructed parts.</remarks> Text = 25, /// <summary>The name of a type parameter.</summary> TypeParameterName = 26, /// <summary>The name of a query range variable.</summary> RangeVariableName = 27, /// <summary>The name of an enum member.</summary> EnumMemberName = 28, /// <summary>The name of a reduced extension method.</summary> /// <remarks> /// When an extension method is in it's non-reduced form it will be will be marked as MethodName. /// </remarks> ExtensionMethodName = 29, /// <summary>The name of a field or local constant.</summary> ConstantName = 30, /// <summary>The name of a record class.</summary> RecordClassName = 31, /// <summary>The name of a record struct.</summary> RecordStructName = 32, } internal static class InternalSymbolDisplayPartKind { private const SymbolDisplayPartKind @base = SymbolDisplayPartKind.RecordStructName + 1; public const SymbolDisplayPartKind Arity = @base + 0; public const SymbolDisplayPartKind Other = @base + 1; } internal static partial class EnumBounds { internal static bool IsValid(this SymbolDisplayPartKind value) { return (value >= SymbolDisplayPartKind.AliasName && value <= SymbolDisplayPartKind.RecordStructName) || (value >= InternalSymbolDisplayPartKind.Arity && value <= InternalSymbolDisplayPartKind.Other); } } }
-1
dotnet/roslyn
55,138
Avoid cancellation exceptions in intermediate operations
Addresses the following exceptions: ![image](https://user-images.githubusercontent.com/1408396/127185947-8a005aea-ae1c-4755-bf0f-21dfb8101352.png)
sharwell
2021-07-27T15:51:28Z
2021-07-27T21:36:45Z
3d8acbd585a75e9cdb3509623bf6c39ceb46b2c2
719d4ffa2be734463e5d7d4d74b23b8006fd7727
Avoid cancellation exceptions in intermediate operations. Addresses the following exceptions: ![image](https://user-images.githubusercontent.com/1408396/127185947-8a005aea-ae1c-4755-bf0f-21dfb8101352.png)
./src/Workspaces/Core/MSBuild/MSBuild/ProjectFile/IProjectFileLoader.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.MSBuild.Build; namespace Microsoft.CodeAnalysis.MSBuild { internal interface IProjectFileLoader : ILanguageService { string Language { get; } Task<IProjectFile> LoadProjectFileAsync( string path, ProjectBuildManager buildManager, 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.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.MSBuild.Build; namespace Microsoft.CodeAnalysis.MSBuild { internal interface IProjectFileLoader : ILanguageService { string Language { get; } Task<IProjectFile> LoadProjectFileAsync( string path, ProjectBuildManager buildManager, CancellationToken cancellationToken); } }
-1
dotnet/roslyn
55,138
Avoid cancellation exceptions in intermediate operations
Addresses the following exceptions: ![image](https://user-images.githubusercontent.com/1408396/127185947-8a005aea-ae1c-4755-bf0f-21dfb8101352.png)
sharwell
2021-07-27T15:51:28Z
2021-07-27T21:36:45Z
3d8acbd585a75e9cdb3509623bf6c39ceb46b2c2
719d4ffa2be734463e5d7d4d74b23b8006fd7727
Avoid cancellation exceptions in intermediate operations. Addresses the following exceptions: ![image](https://user-images.githubusercontent.com/1408396/127185947-8a005aea-ae1c-4755-bf0f-21dfb8101352.png)
./src/Compilers/CSharp/Portable/Symbols/SynthesizedNamespaceSymbol.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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 Roslyn.Utilities; using System.Diagnostics; using System; using Microsoft.CodeAnalysis.Emit; namespace Microsoft.CodeAnalysis.CSharp.Symbols { /// <summary> /// Synthesized namespace that contains synthesized types or subnamespaces. /// All its members are stored in a table on <see cref="CommonPEModuleBuilder"/>. /// </summary> internal sealed class SynthesizedNamespaceSymbol : NamespaceSymbol { private readonly string _name; private readonly NamespaceSymbol _containingSymbol; public SynthesizedNamespaceSymbol(NamespaceSymbol containingNamespace, string name) { Debug.Assert(containingNamespace is object); Debug.Assert(name is object); _containingSymbol = containingNamespace; _name = name; } public override int GetHashCode() => Hash.Combine(_containingSymbol.GetHashCode(), _name.GetHashCode()); public override bool Equals(Symbol obj, TypeCompareKind compareKind) => obj is SynthesizedNamespaceSymbol other && Equals(other, compareKind); public bool Equals(SynthesizedNamespaceSymbol other, TypeCompareKind compareKind) { if (ReferenceEquals(this, other)) { return true; } return other is object && _name.Equals(other._name) && _containingSymbol.Equals(other._containingSymbol); } internal override NamespaceExtent Extent => _containingSymbol.Extent; public override string Name => _name; public override Symbol ContainingSymbol => _containingSymbol; public override AssemblySymbol ContainingAssembly => _containingSymbol.ContainingAssembly; public override ImmutableArray<Location> Locations => ImmutableArray<Location>.Empty; public override ImmutableArray<SyntaxReference> DeclaringSyntaxReferences => ImmutableArray<SyntaxReference>.Empty; public override ImmutableArray<NamedTypeSymbol> GetTypeMembers() => ImmutableArray<NamedTypeSymbol>.Empty; public override ImmutableArray<NamedTypeSymbol> GetTypeMembers(string name) => ImmutableArray<NamedTypeSymbol>.Empty; public override ImmutableArray<NamedTypeSymbol> GetTypeMembers(string name, int arity) => ImmutableArray<NamedTypeSymbol>.Empty; public override ImmutableArray<Symbol> GetMembers() => ImmutableArray<Symbol>.Empty; public override ImmutableArray<Symbol> GetMembers(string name) => ImmutableArray<Symbol>.Empty; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using Roslyn.Utilities; using System.Diagnostics; using System; using Microsoft.CodeAnalysis.Emit; namespace Microsoft.CodeAnalysis.CSharp.Symbols { /// <summary> /// Synthesized namespace that contains synthesized types or subnamespaces. /// All its members are stored in a table on <see cref="CommonPEModuleBuilder"/>. /// </summary> internal sealed class SynthesizedNamespaceSymbol : NamespaceSymbol { private readonly string _name; private readonly NamespaceSymbol _containingSymbol; public SynthesizedNamespaceSymbol(NamespaceSymbol containingNamespace, string name) { Debug.Assert(containingNamespace is object); Debug.Assert(name is object); _containingSymbol = containingNamespace; _name = name; } public override int GetHashCode() => Hash.Combine(_containingSymbol.GetHashCode(), _name.GetHashCode()); public override bool Equals(Symbol obj, TypeCompareKind compareKind) => obj is SynthesizedNamespaceSymbol other && Equals(other, compareKind); public bool Equals(SynthesizedNamespaceSymbol other, TypeCompareKind compareKind) { if (ReferenceEquals(this, other)) { return true; } return other is object && _name.Equals(other._name) && _containingSymbol.Equals(other._containingSymbol); } internal override NamespaceExtent Extent => _containingSymbol.Extent; public override string Name => _name; public override Symbol ContainingSymbol => _containingSymbol; public override AssemblySymbol ContainingAssembly => _containingSymbol.ContainingAssembly; public override ImmutableArray<Location> Locations => ImmutableArray<Location>.Empty; public override ImmutableArray<SyntaxReference> DeclaringSyntaxReferences => ImmutableArray<SyntaxReference>.Empty; public override ImmutableArray<NamedTypeSymbol> GetTypeMembers() => ImmutableArray<NamedTypeSymbol>.Empty; public override ImmutableArray<NamedTypeSymbol> GetTypeMembers(string name) => ImmutableArray<NamedTypeSymbol>.Empty; public override ImmutableArray<NamedTypeSymbol> GetTypeMembers(string name, int arity) => ImmutableArray<NamedTypeSymbol>.Empty; public override ImmutableArray<Symbol> GetMembers() => ImmutableArray<Symbol>.Empty; public override ImmutableArray<Symbol> GetMembers(string name) => ImmutableArray<Symbol>.Empty; } }
-1
dotnet/roslyn
55,138
Avoid cancellation exceptions in intermediate operations
Addresses the following exceptions: ![image](https://user-images.githubusercontent.com/1408396/127185947-8a005aea-ae1c-4755-bf0f-21dfb8101352.png)
sharwell
2021-07-27T15:51:28Z
2021-07-27T21:36:45Z
3d8acbd585a75e9cdb3509623bf6c39ceb46b2c2
719d4ffa2be734463e5d7d4d74b23b8006fd7727
Avoid cancellation exceptions in intermediate operations. Addresses the following exceptions: ![image](https://user-images.githubusercontent.com/1408396/127185947-8a005aea-ae1c-4755-bf0f-21dfb8101352.png)
./src/Compilers/CSharp/Portable/Syntax/CSharpSyntaxNode.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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 System.IO; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { /// <summary> /// Represents a non-terminal node in the syntax tree. /// </summary> //The fact that this type implements IMessageSerializable //enables it to be used as an argument to a diagnostic. This allows diagnostics //to defer the realization of strings. Often diagnostics generated while binding //in service of a SemanticModel API are never realized. So this //deferral can result in meaningful savings of strings. public abstract partial class CSharpSyntaxNode : SyntaxNode, IFormattable { internal CSharpSyntaxNode(GreenNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } /// <summary> /// Used by structured trivia which has "parent == null", and therefore must know its /// SyntaxTree explicitly when created. /// </summary> internal CSharpSyntaxNode(GreenNode green, int position, SyntaxTree syntaxTree) : base(green, position, syntaxTree) { } /// <summary> /// Returns a non-null <see cref="SyntaxTree"/> that owns this node. /// If this node was created with an explicit non-null <see cref="SyntaxTree"/>, returns that tree. /// Otherwise, if this node has a non-null parent, then returns the parent's <see cref="SyntaxTree"/>. /// Otherwise, returns a newly created <see cref="SyntaxTree"/> rooted at this node, preserving this node's reference identity. /// </summary> internal new SyntaxTree SyntaxTree { get { var result = this._syntaxTree ?? ComputeSyntaxTree(this); Debug.Assert(result != null); return result; } } private static SyntaxTree ComputeSyntaxTree(CSharpSyntaxNode node) { ArrayBuilder<CSharpSyntaxNode>? nodes = null; SyntaxTree? tree = null; // Find the nearest parent with a non-null syntax tree while (true) { tree = node._syntaxTree; if (tree != null) { break; } var parent = node.Parent; if (parent == null) { // set the tree on the root node atomically Interlocked.CompareExchange(ref node._syntaxTree, CSharpSyntaxTree.CreateWithoutClone(node), null); tree = node._syntaxTree; break; } tree = parent._syntaxTree; if (tree != null) { node._syntaxTree = tree; break; } (nodes ?? (nodes = ArrayBuilder<CSharpSyntaxNode>.GetInstance())).Add(node); node = parent; } // Propagate the syntax tree downwards if necessary if (nodes != null) { Debug.Assert(tree != null); foreach (var n in nodes) { var existingTree = n._syntaxTree; if (existingTree != null) { Debug.Assert(existingTree == tree, "how could this node belong to a different tree?"); // yield the race break; } n._syntaxTree = tree; } nodes.Free(); } return tree; } public abstract TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor); public abstract void Accept(CSharpSyntaxVisitor visitor); /// <summary> /// The node that contains this node in its Children collection. /// </summary> internal new CSharpSyntaxNode? Parent { get { return (CSharpSyntaxNode?)base.Parent; } } internal new CSharpSyntaxNode? ParentOrStructuredTriviaParent { get { return (CSharpSyntaxNode?)base.ParentOrStructuredTriviaParent; } } // TODO: may be eventually not needed internal Syntax.InternalSyntax.CSharpSyntaxNode CsGreen { get { return (Syntax.InternalSyntax.CSharpSyntaxNode)this.Green; } } /// <summary> /// Returns the <see cref="SyntaxKind"/> of the node. /// </summary> public SyntaxKind Kind() { return (SyntaxKind)this.Green.RawKind; } /// <summary> /// The language name that this node is syntax of. /// </summary> public override string Language { get { return LanguageNames.CSharp; } } /// <summary> /// The list of trivia that appears before this node in the source code. /// </summary> public new SyntaxTriviaList GetLeadingTrivia() { var firstToken = this.GetFirstToken(includeZeroWidth: true); return firstToken.LeadingTrivia; } /// <summary> /// The list of trivia that appears after this node in the source code. /// </summary> public new SyntaxTriviaList GetTrailingTrivia() { var lastToken = this.GetLastToken(includeZeroWidth: true); return lastToken.TrailingTrivia; } #region serialization /// <summary> /// Deserialize a syntax node from the byte stream. /// </summary> public static SyntaxNode DeserializeFrom(Stream stream, CancellationToken cancellationToken = default) { if (stream == null) { throw new ArgumentNullException(nameof(stream)); } if (!stream.CanRead) { throw new InvalidOperationException(CodeAnalysisResources.TheStreamCannotBeReadFrom); } using var reader = ObjectReader.TryGetReader(stream, leaveOpen: true, cancellationToken); if (reader == null) { throw new ArgumentException(CodeAnalysisResources.Stream_contains_invalid_data, nameof(stream)); } var root = (Syntax.InternalSyntax.CSharpSyntaxNode)reader.ReadValue(); return root.CreateRed(); } #endregion /// <summary> /// Gets a <see cref="Location"/> for this node. /// </summary> public new Location GetLocation() { return new SourceLocation(this); } /// <summary> /// Gets a SyntaxReference for this syntax node. SyntaxReferences can be used to /// regain access to a syntax node without keeping the entire tree and source text in /// memory. /// </summary> internal new SyntaxReference GetReference() { return this.SyntaxTree.GetReference(this); } /// <summary> /// Gets a list of all the diagnostics in the sub tree that has this node as its root. /// This method does not filter diagnostics based on #pragmas and compiler options /// like nowarn, warnaserror etc. /// </summary> public new IEnumerable<Diagnostic> GetDiagnostics() { return this.SyntaxTree.GetDiagnostics(this); } #region Directives internal IList<DirectiveTriviaSyntax> GetDirectives(Func<DirectiveTriviaSyntax, bool>? filter = null) { return ((SyntaxNodeOrToken)this).GetDirectives<DirectiveTriviaSyntax>(filter); } /// <summary> /// Gets the first directive of the tree rooted by this node. /// </summary> public DirectiveTriviaSyntax? GetFirstDirective(Func<DirectiveTriviaSyntax, bool>? predicate = null) { foreach (var child in this.ChildNodesAndTokens()) { if (child.ContainsDirectives) { if (child.AsNode(out var node)) { var d = node.GetFirstDirective(predicate); if (d != null) { return d; } } else { var token = child.AsToken(); // directives can only occur in leading trivia foreach (var tr in token.LeadingTrivia) { if (tr.IsDirective) { var d = (DirectiveTriviaSyntax)tr.GetStructure()!; if (predicate == null || predicate(d)) { return d; } } } } } } return null; } /// <summary> /// Gets the last directive of the tree rooted by this node. /// </summary> public DirectiveTriviaSyntax? GetLastDirective(Func<DirectiveTriviaSyntax, bool>? predicate = null) { foreach (var child in this.ChildNodesAndTokens().Reverse()) { if (child.ContainsDirectives) { if (child.AsNode(out var node)) { var d = node.GetLastDirective(predicate); if (d != null) { return d; } } else { var token = child.AsToken(); // directives can only occur in leading trivia foreach (var tr in token.LeadingTrivia.Reverse()) { if (tr.IsDirective) { var d = (DirectiveTriviaSyntax)tr.GetStructure()!; if (predicate == null || predicate(d)) { return d; } } } } } } return null; } #endregion #region Token Lookup /// <summary> /// Gets the first token of the tree rooted by this node. /// </summary> /// <param name="includeZeroWidth">True if zero width tokens should be included, false by /// default.</param> /// <param name="includeSkipped">True if skipped tokens should be included, false by default.</param> /// <param name="includeDirectives">True if directives should be included, false by default.</param> /// <param name="includeDocumentationComments">True if documentation comments should be /// included, false by default.</param> /// <returns></returns> public new SyntaxToken GetFirstToken(bool includeZeroWidth = false, bool includeSkipped = false, bool includeDirectives = false, bool includeDocumentationComments = false) { return base.GetFirstToken(includeZeroWidth, includeSkipped, includeDirectives, includeDocumentationComments); } /// <summary> /// Gets the first token of the tree rooted by this node. /// </summary> /// <param name="predicate">Only tokens for which this predicate returns true are included. Pass null to include /// all tokens.</param> /// <param name="stepInto">Steps into trivia if this is not null. Only trivia for which this delegate returns /// true are included.</param> /// <returns></returns> internal SyntaxToken GetFirstToken(Func<SyntaxToken, bool>? predicate, Func<SyntaxTrivia, bool>? stepInto = null) { return SyntaxNavigator.Instance.GetFirstToken(this, predicate, stepInto); } /// <summary> /// Gets the last non-zero-width token of the tree rooted by this node. /// </summary> /// <param name="includeZeroWidth">True if zero width tokens should be included, false by /// default.</param> /// <param name="includeSkipped">True if skipped tokens should be included, false by default.</param> /// <param name="includeDirectives">True if directives should be included, false by default.</param> /// <param name="includeDocumentationComments">True if documentation comments should be /// included, false by default.</param> /// <returns></returns> public new SyntaxToken GetLastToken(bool includeZeroWidth = false, bool includeSkipped = false, bool includeDirectives = false, bool includeDocumentationComments = false) { return base.GetLastToken(includeZeroWidth, includeSkipped, includeDirectives, includeDocumentationComments); } /// <summary> /// Finds a token according to the following rules: /// 1) If position matches the End of the node/s FullSpan and the node is CompilationUnit, /// then EoF is returned. /// /// 2) If node.FullSpan.Contains(position) then the token that contains given position is /// returned. /// /// 3) Otherwise an ArgumentOutOfRangeException is thrown /// </summary> public new SyntaxToken FindToken(int position, bool findInsideTrivia = false) { return base.FindToken(position, findInsideTrivia); } /// <summary> /// Finds a token according to the following rules: /// 1) If position matches the End of the node/s FullSpan and the node is CompilationUnit, /// then EoF is returned. /// /// 2) If node.FullSpan.Contains(position) then the token that contains given position is /// returned. /// /// 3) Otherwise an ArgumentOutOfRangeException is thrown /// </summary> internal SyntaxToken FindTokenIncludingCrefAndNameAttributes(int position) { SyntaxToken nonTriviaToken = this.FindToken(position, findInsideTrivia: false); SyntaxTrivia trivia = GetTriviaFromSyntaxToken(position, nonTriviaToken); if (!SyntaxFacts.IsDocumentationCommentTrivia(trivia.Kind())) { return nonTriviaToken; } Debug.Assert(trivia.HasStructure); SyntaxToken triviaToken = ((CSharpSyntaxNode)trivia.GetStructure()!).FindTokenInternal(position); // CONSIDER: We might want to use the trivia token anywhere within a doc comment. // Otherwise, we'll fall back on the enclosing scope outside of name and cref // attribute values. CSharpSyntaxNode? curr = (CSharpSyntaxNode?)triviaToken.Parent; while (curr != null) { // Don't return a trivia token unless we're in the scope of a cref or name attribute. if (curr.Kind() == SyntaxKind.XmlCrefAttribute || curr.Kind() == SyntaxKind.XmlNameAttribute) { return LookupPosition.IsInXmlAttributeValue(position, (XmlAttributeSyntax)curr) ? triviaToken : nonTriviaToken; } curr = curr.Parent; } return nonTriviaToken; } #endregion #region Trivia Lookup /// <summary> /// Finds a descendant trivia of this node at the specified position, where the position is /// within the span of the node. /// </summary> /// <param name="position">The character position of the trivia relative to the beginning of /// the file.</param> /// <param name="stepInto">Specifies a function that determines per trivia node, whether to /// descend into structured trivia of that node.</param> /// <returns></returns> public new SyntaxTrivia FindTrivia(int position, Func<SyntaxTrivia, bool> stepInto) { return base.FindTrivia(position, stepInto); } /// <summary> /// Finds a descendant trivia of this node whose span includes the supplied position. /// </summary> /// <param name="position">The character position of the trivia relative to the beginning of /// the file.</param> /// <param name="findInsideTrivia">Whether to search inside structured trivia.</param> public new SyntaxTrivia FindTrivia(int position, bool findInsideTrivia = false) { return base.FindTrivia(position, findInsideTrivia); } #endregion #region SyntaxNode members /// <summary> /// Determine if this node is structurally equivalent to another. /// </summary> /// <param name="other"></param> /// <returns></returns> protected override bool EquivalentToCore(SyntaxNode other) { throw ExceptionUtilities.Unreachable; } protected override SyntaxTree SyntaxTreeCore { get { return this.SyntaxTree; } } protected internal override SyntaxNode ReplaceCore<TNode>( IEnumerable<TNode>? nodes = null, Func<TNode, TNode, SyntaxNode>? computeReplacementNode = null, IEnumerable<SyntaxToken>? tokens = null, Func<SyntaxToken, SyntaxToken, SyntaxToken>? computeReplacementToken = null, IEnumerable<SyntaxTrivia>? trivia = null, Func<SyntaxTrivia, SyntaxTrivia, SyntaxTrivia>? computeReplacementTrivia = null) { return SyntaxReplacer.Replace(this, nodes, computeReplacementNode, tokens, computeReplacementToken, trivia, computeReplacementTrivia).AsRootOfNewTreeWithOptionsFrom(this.SyntaxTree); } protected internal override SyntaxNode ReplaceNodeInListCore(SyntaxNode originalNode, IEnumerable<SyntaxNode> replacementNodes) { return SyntaxReplacer.ReplaceNodeInList(this, originalNode, replacementNodes).AsRootOfNewTreeWithOptionsFrom(this.SyntaxTree); } protected internal override SyntaxNode InsertNodesInListCore(SyntaxNode nodeInList, IEnumerable<SyntaxNode> nodesToInsert, bool insertBefore) { return SyntaxReplacer.InsertNodeInList(this, nodeInList, nodesToInsert, insertBefore).AsRootOfNewTreeWithOptionsFrom(this.SyntaxTree); } protected internal override SyntaxNode ReplaceTokenInListCore(SyntaxToken originalToken, IEnumerable<SyntaxToken> newTokens) { return SyntaxReplacer.ReplaceTokenInList(this, originalToken, newTokens).AsRootOfNewTreeWithOptionsFrom(this.SyntaxTree); } protected internal override SyntaxNode InsertTokensInListCore(SyntaxToken originalToken, IEnumerable<SyntaxToken> newTokens, bool insertBefore) { return SyntaxReplacer.InsertTokenInList(this, originalToken, newTokens, insertBefore).AsRootOfNewTreeWithOptionsFrom(this.SyntaxTree); } protected internal override SyntaxNode ReplaceTriviaInListCore(SyntaxTrivia originalTrivia, IEnumerable<SyntaxTrivia> newTrivia) { return SyntaxReplacer.ReplaceTriviaInList(this, originalTrivia, newTrivia).AsRootOfNewTreeWithOptionsFrom(this.SyntaxTree); } protected internal override SyntaxNode InsertTriviaInListCore(SyntaxTrivia originalTrivia, IEnumerable<SyntaxTrivia> newTrivia, bool insertBefore) { return SyntaxReplacer.InsertTriviaInList(this, originalTrivia, newTrivia, insertBefore).AsRootOfNewTreeWithOptionsFrom(this.SyntaxTree); } protected internal override SyntaxNode? RemoveNodesCore(IEnumerable<SyntaxNode> nodes, SyntaxRemoveOptions options) { return SyntaxNodeRemover.RemoveNodes(this, nodes.Cast<CSharpSyntaxNode>(), options).AsRootOfNewTreeWithOptionsFrom(this.SyntaxTree); } protected internal override SyntaxNode NormalizeWhitespaceCore(string indentation, string eol, bool elasticTrivia) { return SyntaxNormalizer.Normalize(this, indentation, eol, elasticTrivia).AsRootOfNewTreeWithOptionsFrom(this.SyntaxTree); } protected override bool IsEquivalentToCore(SyntaxNode node, bool topLevel = false) { return SyntaxFactory.AreEquivalent(this, (CSharpSyntaxNode)node, topLevel); } internal override bool ShouldCreateWeakList() { if (this.Kind() == SyntaxKind.Block) { var parent = this.Parent; if (parent is MemberDeclarationSyntax || parent is AccessorDeclarationSyntax) { return true; } } return false; } #endregion string IFormattable.ToString(string? format, IFormatProvider? formatProvider) { return ToString(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { /// <summary> /// Represents a non-terminal node in the syntax tree. /// </summary> //The fact that this type implements IMessageSerializable //enables it to be used as an argument to a diagnostic. This allows diagnostics //to defer the realization of strings. Often diagnostics generated while binding //in service of a SemanticModel API are never realized. So this //deferral can result in meaningful savings of strings. public abstract partial class CSharpSyntaxNode : SyntaxNode, IFormattable { internal CSharpSyntaxNode(GreenNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } /// <summary> /// Used by structured trivia which has "parent == null", and therefore must know its /// SyntaxTree explicitly when created. /// </summary> internal CSharpSyntaxNode(GreenNode green, int position, SyntaxTree syntaxTree) : base(green, position, syntaxTree) { } /// <summary> /// Returns a non-null <see cref="SyntaxTree"/> that owns this node. /// If this node was created with an explicit non-null <see cref="SyntaxTree"/>, returns that tree. /// Otherwise, if this node has a non-null parent, then returns the parent's <see cref="SyntaxTree"/>. /// Otherwise, returns a newly created <see cref="SyntaxTree"/> rooted at this node, preserving this node's reference identity. /// </summary> internal new SyntaxTree SyntaxTree { get { var result = this._syntaxTree ?? ComputeSyntaxTree(this); Debug.Assert(result != null); return result; } } private static SyntaxTree ComputeSyntaxTree(CSharpSyntaxNode node) { ArrayBuilder<CSharpSyntaxNode>? nodes = null; SyntaxTree? tree = null; // Find the nearest parent with a non-null syntax tree while (true) { tree = node._syntaxTree; if (tree != null) { break; } var parent = node.Parent; if (parent == null) { // set the tree on the root node atomically Interlocked.CompareExchange(ref node._syntaxTree, CSharpSyntaxTree.CreateWithoutClone(node), null); tree = node._syntaxTree; break; } tree = parent._syntaxTree; if (tree != null) { node._syntaxTree = tree; break; } (nodes ?? (nodes = ArrayBuilder<CSharpSyntaxNode>.GetInstance())).Add(node); node = parent; } // Propagate the syntax tree downwards if necessary if (nodes != null) { Debug.Assert(tree != null); foreach (var n in nodes) { var existingTree = n._syntaxTree; if (existingTree != null) { Debug.Assert(existingTree == tree, "how could this node belong to a different tree?"); // yield the race break; } n._syntaxTree = tree; } nodes.Free(); } return tree; } public abstract TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor); public abstract void Accept(CSharpSyntaxVisitor visitor); /// <summary> /// The node that contains this node in its Children collection. /// </summary> internal new CSharpSyntaxNode? Parent { get { return (CSharpSyntaxNode?)base.Parent; } } internal new CSharpSyntaxNode? ParentOrStructuredTriviaParent { get { return (CSharpSyntaxNode?)base.ParentOrStructuredTriviaParent; } } // TODO: may be eventually not needed internal Syntax.InternalSyntax.CSharpSyntaxNode CsGreen { get { return (Syntax.InternalSyntax.CSharpSyntaxNode)this.Green; } } /// <summary> /// Returns the <see cref="SyntaxKind"/> of the node. /// </summary> public SyntaxKind Kind() { return (SyntaxKind)this.Green.RawKind; } /// <summary> /// The language name that this node is syntax of. /// </summary> public override string Language { get { return LanguageNames.CSharp; } } /// <summary> /// The list of trivia that appears before this node in the source code. /// </summary> public new SyntaxTriviaList GetLeadingTrivia() { var firstToken = this.GetFirstToken(includeZeroWidth: true); return firstToken.LeadingTrivia; } /// <summary> /// The list of trivia that appears after this node in the source code. /// </summary> public new SyntaxTriviaList GetTrailingTrivia() { var lastToken = this.GetLastToken(includeZeroWidth: true); return lastToken.TrailingTrivia; } #region serialization /// <summary> /// Deserialize a syntax node from the byte stream. /// </summary> public static SyntaxNode DeserializeFrom(Stream stream, CancellationToken cancellationToken = default) { if (stream == null) { throw new ArgumentNullException(nameof(stream)); } if (!stream.CanRead) { throw new InvalidOperationException(CodeAnalysisResources.TheStreamCannotBeReadFrom); } using var reader = ObjectReader.TryGetReader(stream, leaveOpen: true, cancellationToken); if (reader == null) { throw new ArgumentException(CodeAnalysisResources.Stream_contains_invalid_data, nameof(stream)); } var root = (Syntax.InternalSyntax.CSharpSyntaxNode)reader.ReadValue(); return root.CreateRed(); } #endregion /// <summary> /// Gets a <see cref="Location"/> for this node. /// </summary> public new Location GetLocation() { return new SourceLocation(this); } /// <summary> /// Gets a SyntaxReference for this syntax node. SyntaxReferences can be used to /// regain access to a syntax node without keeping the entire tree and source text in /// memory. /// </summary> internal new SyntaxReference GetReference() { return this.SyntaxTree.GetReference(this); } /// <summary> /// Gets a list of all the diagnostics in the sub tree that has this node as its root. /// This method does not filter diagnostics based on #pragmas and compiler options /// like nowarn, warnaserror etc. /// </summary> public new IEnumerable<Diagnostic> GetDiagnostics() { return this.SyntaxTree.GetDiagnostics(this); } #region Directives internal IList<DirectiveTriviaSyntax> GetDirectives(Func<DirectiveTriviaSyntax, bool>? filter = null) { return ((SyntaxNodeOrToken)this).GetDirectives<DirectiveTriviaSyntax>(filter); } /// <summary> /// Gets the first directive of the tree rooted by this node. /// </summary> public DirectiveTriviaSyntax? GetFirstDirective(Func<DirectiveTriviaSyntax, bool>? predicate = null) { foreach (var child in this.ChildNodesAndTokens()) { if (child.ContainsDirectives) { if (child.AsNode(out var node)) { var d = node.GetFirstDirective(predicate); if (d != null) { return d; } } else { var token = child.AsToken(); // directives can only occur in leading trivia foreach (var tr in token.LeadingTrivia) { if (tr.IsDirective) { var d = (DirectiveTriviaSyntax)tr.GetStructure()!; if (predicate == null || predicate(d)) { return d; } } } } } } return null; } /// <summary> /// Gets the last directive of the tree rooted by this node. /// </summary> public DirectiveTriviaSyntax? GetLastDirective(Func<DirectiveTriviaSyntax, bool>? predicate = null) { foreach (var child in this.ChildNodesAndTokens().Reverse()) { if (child.ContainsDirectives) { if (child.AsNode(out var node)) { var d = node.GetLastDirective(predicate); if (d != null) { return d; } } else { var token = child.AsToken(); // directives can only occur in leading trivia foreach (var tr in token.LeadingTrivia.Reverse()) { if (tr.IsDirective) { var d = (DirectiveTriviaSyntax)tr.GetStructure()!; if (predicate == null || predicate(d)) { return d; } } } } } } return null; } #endregion #region Token Lookup /// <summary> /// Gets the first token of the tree rooted by this node. /// </summary> /// <param name="includeZeroWidth">True if zero width tokens should be included, false by /// default.</param> /// <param name="includeSkipped">True if skipped tokens should be included, false by default.</param> /// <param name="includeDirectives">True if directives should be included, false by default.</param> /// <param name="includeDocumentationComments">True if documentation comments should be /// included, false by default.</param> /// <returns></returns> public new SyntaxToken GetFirstToken(bool includeZeroWidth = false, bool includeSkipped = false, bool includeDirectives = false, bool includeDocumentationComments = false) { return base.GetFirstToken(includeZeroWidth, includeSkipped, includeDirectives, includeDocumentationComments); } /// <summary> /// Gets the first token of the tree rooted by this node. /// </summary> /// <param name="predicate">Only tokens for which this predicate returns true are included. Pass null to include /// all tokens.</param> /// <param name="stepInto">Steps into trivia if this is not null. Only trivia for which this delegate returns /// true are included.</param> /// <returns></returns> internal SyntaxToken GetFirstToken(Func<SyntaxToken, bool>? predicate, Func<SyntaxTrivia, bool>? stepInto = null) { return SyntaxNavigator.Instance.GetFirstToken(this, predicate, stepInto); } /// <summary> /// Gets the last non-zero-width token of the tree rooted by this node. /// </summary> /// <param name="includeZeroWidth">True if zero width tokens should be included, false by /// default.</param> /// <param name="includeSkipped">True if skipped tokens should be included, false by default.</param> /// <param name="includeDirectives">True if directives should be included, false by default.</param> /// <param name="includeDocumentationComments">True if documentation comments should be /// included, false by default.</param> /// <returns></returns> public new SyntaxToken GetLastToken(bool includeZeroWidth = false, bool includeSkipped = false, bool includeDirectives = false, bool includeDocumentationComments = false) { return base.GetLastToken(includeZeroWidth, includeSkipped, includeDirectives, includeDocumentationComments); } /// <summary> /// Finds a token according to the following rules: /// 1) If position matches the End of the node/s FullSpan and the node is CompilationUnit, /// then EoF is returned. /// /// 2) If node.FullSpan.Contains(position) then the token that contains given position is /// returned. /// /// 3) Otherwise an ArgumentOutOfRangeException is thrown /// </summary> public new SyntaxToken FindToken(int position, bool findInsideTrivia = false) { return base.FindToken(position, findInsideTrivia); } /// <summary> /// Finds a token according to the following rules: /// 1) If position matches the End of the node/s FullSpan and the node is CompilationUnit, /// then EoF is returned. /// /// 2) If node.FullSpan.Contains(position) then the token that contains given position is /// returned. /// /// 3) Otherwise an ArgumentOutOfRangeException is thrown /// </summary> internal SyntaxToken FindTokenIncludingCrefAndNameAttributes(int position) { SyntaxToken nonTriviaToken = this.FindToken(position, findInsideTrivia: false); SyntaxTrivia trivia = GetTriviaFromSyntaxToken(position, nonTriviaToken); if (!SyntaxFacts.IsDocumentationCommentTrivia(trivia.Kind())) { return nonTriviaToken; } Debug.Assert(trivia.HasStructure); SyntaxToken triviaToken = ((CSharpSyntaxNode)trivia.GetStructure()!).FindTokenInternal(position); // CONSIDER: We might want to use the trivia token anywhere within a doc comment. // Otherwise, we'll fall back on the enclosing scope outside of name and cref // attribute values. CSharpSyntaxNode? curr = (CSharpSyntaxNode?)triviaToken.Parent; while (curr != null) { // Don't return a trivia token unless we're in the scope of a cref or name attribute. if (curr.Kind() == SyntaxKind.XmlCrefAttribute || curr.Kind() == SyntaxKind.XmlNameAttribute) { return LookupPosition.IsInXmlAttributeValue(position, (XmlAttributeSyntax)curr) ? triviaToken : nonTriviaToken; } curr = curr.Parent; } return nonTriviaToken; } #endregion #region Trivia Lookup /// <summary> /// Finds a descendant trivia of this node at the specified position, where the position is /// within the span of the node. /// </summary> /// <param name="position">The character position of the trivia relative to the beginning of /// the file.</param> /// <param name="stepInto">Specifies a function that determines per trivia node, whether to /// descend into structured trivia of that node.</param> /// <returns></returns> public new SyntaxTrivia FindTrivia(int position, Func<SyntaxTrivia, bool> stepInto) { return base.FindTrivia(position, stepInto); } /// <summary> /// Finds a descendant trivia of this node whose span includes the supplied position. /// </summary> /// <param name="position">The character position of the trivia relative to the beginning of /// the file.</param> /// <param name="findInsideTrivia">Whether to search inside structured trivia.</param> public new SyntaxTrivia FindTrivia(int position, bool findInsideTrivia = false) { return base.FindTrivia(position, findInsideTrivia); } #endregion #region SyntaxNode members /// <summary> /// Determine if this node is structurally equivalent to another. /// </summary> /// <param name="other"></param> /// <returns></returns> protected override bool EquivalentToCore(SyntaxNode other) { throw ExceptionUtilities.Unreachable; } protected override SyntaxTree SyntaxTreeCore { get { return this.SyntaxTree; } } protected internal override SyntaxNode ReplaceCore<TNode>( IEnumerable<TNode>? nodes = null, Func<TNode, TNode, SyntaxNode>? computeReplacementNode = null, IEnumerable<SyntaxToken>? tokens = null, Func<SyntaxToken, SyntaxToken, SyntaxToken>? computeReplacementToken = null, IEnumerable<SyntaxTrivia>? trivia = null, Func<SyntaxTrivia, SyntaxTrivia, SyntaxTrivia>? computeReplacementTrivia = null) { return SyntaxReplacer.Replace(this, nodes, computeReplacementNode, tokens, computeReplacementToken, trivia, computeReplacementTrivia).AsRootOfNewTreeWithOptionsFrom(this.SyntaxTree); } protected internal override SyntaxNode ReplaceNodeInListCore(SyntaxNode originalNode, IEnumerable<SyntaxNode> replacementNodes) { return SyntaxReplacer.ReplaceNodeInList(this, originalNode, replacementNodes).AsRootOfNewTreeWithOptionsFrom(this.SyntaxTree); } protected internal override SyntaxNode InsertNodesInListCore(SyntaxNode nodeInList, IEnumerable<SyntaxNode> nodesToInsert, bool insertBefore) { return SyntaxReplacer.InsertNodeInList(this, nodeInList, nodesToInsert, insertBefore).AsRootOfNewTreeWithOptionsFrom(this.SyntaxTree); } protected internal override SyntaxNode ReplaceTokenInListCore(SyntaxToken originalToken, IEnumerable<SyntaxToken> newTokens) { return SyntaxReplacer.ReplaceTokenInList(this, originalToken, newTokens).AsRootOfNewTreeWithOptionsFrom(this.SyntaxTree); } protected internal override SyntaxNode InsertTokensInListCore(SyntaxToken originalToken, IEnumerable<SyntaxToken> newTokens, bool insertBefore) { return SyntaxReplacer.InsertTokenInList(this, originalToken, newTokens, insertBefore).AsRootOfNewTreeWithOptionsFrom(this.SyntaxTree); } protected internal override SyntaxNode ReplaceTriviaInListCore(SyntaxTrivia originalTrivia, IEnumerable<SyntaxTrivia> newTrivia) { return SyntaxReplacer.ReplaceTriviaInList(this, originalTrivia, newTrivia).AsRootOfNewTreeWithOptionsFrom(this.SyntaxTree); } protected internal override SyntaxNode InsertTriviaInListCore(SyntaxTrivia originalTrivia, IEnumerable<SyntaxTrivia> newTrivia, bool insertBefore) { return SyntaxReplacer.InsertTriviaInList(this, originalTrivia, newTrivia, insertBefore).AsRootOfNewTreeWithOptionsFrom(this.SyntaxTree); } protected internal override SyntaxNode? RemoveNodesCore(IEnumerable<SyntaxNode> nodes, SyntaxRemoveOptions options) { return SyntaxNodeRemover.RemoveNodes(this, nodes.Cast<CSharpSyntaxNode>(), options).AsRootOfNewTreeWithOptionsFrom(this.SyntaxTree); } protected internal override SyntaxNode NormalizeWhitespaceCore(string indentation, string eol, bool elasticTrivia) { return SyntaxNormalizer.Normalize(this, indentation, eol, elasticTrivia).AsRootOfNewTreeWithOptionsFrom(this.SyntaxTree); } protected override bool IsEquivalentToCore(SyntaxNode node, bool topLevel = false) { return SyntaxFactory.AreEquivalent(this, (CSharpSyntaxNode)node, topLevel); } internal override bool ShouldCreateWeakList() { if (this.Kind() == SyntaxKind.Block) { var parent = this.Parent; if (parent is MemberDeclarationSyntax || parent is AccessorDeclarationSyntax) { return true; } } return false; } #endregion string IFormattable.ToString(string? format, IFormatProvider? formatProvider) { return ToString(); } } }
-1
dotnet/roslyn
55,138
Avoid cancellation exceptions in intermediate operations
Addresses the following exceptions: ![image](https://user-images.githubusercontent.com/1408396/127185947-8a005aea-ae1c-4755-bf0f-21dfb8101352.png)
sharwell
2021-07-27T15:51:28Z
2021-07-27T21:36:45Z
3d8acbd585a75e9cdb3509623bf6c39ceb46b2c2
719d4ffa2be734463e5d7d4d74b23b8006fd7727
Avoid cancellation exceptions in intermediate operations. Addresses the following exceptions: ![image](https://user-images.githubusercontent.com/1408396/127185947-8a005aea-ae1c-4755-bf0f-21dfb8101352.png)
./src/Workspaces/Core/Portable/PatternMatching/SimplePatternMatcher.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Globalization; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Collections; namespace Microsoft.CodeAnalysis.PatternMatching { internal partial class PatternMatcher { private sealed partial class SimplePatternMatcher : PatternMatcher { private PatternSegment _fullPatternSegment; public SimplePatternMatcher( string pattern, CultureInfo culture, bool includeMatchedSpans, bool allowFuzzyMatching) : base(includeMatchedSpans, culture, allowFuzzyMatching) { pattern = pattern.Trim(); _fullPatternSegment = new PatternSegment(pattern, allowFuzzyMatching); _invalidPattern = _fullPatternSegment.IsInvalid; } public override void Dispose() { base.Dispose(); _fullPatternSegment.Dispose(); } /// <summary> /// Determines if a given candidate string matches under a multiple word query text, as you /// would find in features like Navigate To. /// </summary> /// <returns>If this was a match, a set of match types that occurred while matching the /// patterns. If it was not a match, it returns null.</returns> public override bool AddMatches(string candidate, ref TemporaryArray<PatternMatch> matches) { if (SkipMatch(candidate)) { return false; } return MatchPatternSegment(candidate, in _fullPatternSegment, ref matches, fuzzyMatch: false) || MatchPatternSegment(candidate, in _fullPatternSegment, ref matches, fuzzyMatch: 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.Globalization; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Collections; namespace Microsoft.CodeAnalysis.PatternMatching { internal partial class PatternMatcher { private sealed partial class SimplePatternMatcher : PatternMatcher { private PatternSegment _fullPatternSegment; public SimplePatternMatcher( string pattern, CultureInfo culture, bool includeMatchedSpans, bool allowFuzzyMatching) : base(includeMatchedSpans, culture, allowFuzzyMatching) { pattern = pattern.Trim(); _fullPatternSegment = new PatternSegment(pattern, allowFuzzyMatching); _invalidPattern = _fullPatternSegment.IsInvalid; } public override void Dispose() { base.Dispose(); _fullPatternSegment.Dispose(); } /// <summary> /// Determines if a given candidate string matches under a multiple word query text, as you /// would find in features like Navigate To. /// </summary> /// <returns>If this was a match, a set of match types that occurred while matching the /// patterns. If it was not a match, it returns null.</returns> public override bool AddMatches(string candidate, ref TemporaryArray<PatternMatch> matches) { if (SkipMatch(candidate)) { return false; } return MatchPatternSegment(candidate, in _fullPatternSegment, ref matches, fuzzyMatch: false) || MatchPatternSegment(candidate, in _fullPatternSegment, ref matches, fuzzyMatch: true); } } } }
-1
dotnet/roslyn
55,138
Avoid cancellation exceptions in intermediate operations
Addresses the following exceptions: ![image](https://user-images.githubusercontent.com/1408396/127185947-8a005aea-ae1c-4755-bf0f-21dfb8101352.png)
sharwell
2021-07-27T15:51:28Z
2021-07-27T21:36:45Z
3d8acbd585a75e9cdb3509623bf6c39ceb46b2c2
719d4ffa2be734463e5d7d4d74b23b8006fd7727
Avoid cancellation exceptions in intermediate operations. Addresses the following exceptions: ![image](https://user-images.githubusercontent.com/1408396/127185947-8a005aea-ae1c-4755-bf0f-21dfb8101352.png)
./src/Workspaces/Core/Portable/Workspace/Host/EventListener/IEventListener`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. #nullable disable namespace Microsoft.CodeAnalysis.Host { /// <summary> /// provide a way for features to lazily subscribe to a service event for particular workspace /// /// see <see cref="WellKnownEventListeners"/> for supported services /// </summary> internal interface IEventListener<TService> : IEventListener { void StartListening(Workspace workspace, TService serviceOpt); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable namespace Microsoft.CodeAnalysis.Host { /// <summary> /// provide a way for features to lazily subscribe to a service event for particular workspace /// /// see <see cref="WellKnownEventListeners"/> for supported services /// </summary> internal interface IEventListener<TService> : IEventListener { void StartListening(Workspace workspace, TService serviceOpt); } }
-1
dotnet/roslyn
55,138
Avoid cancellation exceptions in intermediate operations
Addresses the following exceptions: ![image](https://user-images.githubusercontent.com/1408396/127185947-8a005aea-ae1c-4755-bf0f-21dfb8101352.png)
sharwell
2021-07-27T15:51:28Z
2021-07-27T21:36:45Z
3d8acbd585a75e9cdb3509623bf6c39ceb46b2c2
719d4ffa2be734463e5d7d4d74b23b8006fd7727
Avoid cancellation exceptions in intermediate operations. Addresses the following exceptions: ![image](https://user-images.githubusercontent.com/1408396/127185947-8a005aea-ae1c-4755-bf0f-21dfb8101352.png)
./src/EditorFeatures/CSharpTest/CommentSelection/CSharpToggleBlockCommentCommandHandlerTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Editor.CSharp.CommentSelection; using Microsoft.CodeAnalysis.Editor.Implementation.CommentSelection; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities.CommentSelection; using Microsoft.VisualStudio.Commanding; using Microsoft.VisualStudio.Composition; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CommentSelection { [UseExportProvider] public class CSharpToggleBlockCommentCommandHandlerTests : AbstractToggleCommentTestBase { [WpfFact, Trait(Traits.Feature, Traits.Features.ToggleBlockComment)] public void AddComment_CommentMarkerStringBeforeSelection() { var markup = @" class C { void M() { string s = '/*'; [|var j = 2; var k = 3;|] } }"; var expected = @" class C { void M() { string s = '/*'; [|/*var j = 2; var k = 3;*/|] } }"; ToggleComment(markup, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.ToggleBlockComment)] public void AddComment_DirectiveWithCommentInsideSelection() { var markup = @" class C { void M() { [|var i = 1; #if false /*var j = 2;*/ #endif var k = 3;|] } }"; var expected = @" class C { void M() { [|/*var i = 1; #if false /*var j = 2;*/ #endif var k = 3;*/|] } }"; ToggleComment(markup, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.ToggleBlockComment)] public void AddComment_MarkerInsideSelection() { var markup = @" class C { void M() { [|var i = 1; string s = '/*'; var k = 3;|] } }"; var expected = @" class C { void M() { [|/*var i = 1; string s = '/*'; var k = 3;*/|] } }"; ToggleComment(markup, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.ToggleBlockComment)] public void AddComment_CloseCommentMarkerStringInSelection() { var markup = @" class C { void M() { [|var i = 1; string s = '*/'; var k = 3;|] } }"; var expected = @" class C { void M() { [|/*var i = 1; string s = '*/'; var k = 3;*/|] } }"; ToggleComment(markup, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.ToggleBlockComment)] public void AddComment_CommentMarkerStringAfterSelection() { var markup = @" class C { void M() { [|var i = 1; var j = 2;|] string s = '*/'; } }"; var expected = @" class C { void M() { [|/*var i = 1; var j = 2;*/|] string s = '*/'; } }"; ToggleComment(markup, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.ToggleBlockComment)] public void RemoveComment_CommentMarkerStringNearSelection() { var markup = @" class C { void M() { string s = '/*'; [|/*var i = 1; var j = 2; var k = 3;*/|] } }"; var expected = @" class C { void M() { string s = '/*'; [|var i = 1; var j = 2; var k = 3;|] } }"; ToggleComment(markup, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.ToggleBlockComment)] public void RemoveComment_CommentMarkerStringInSelection() { var markup = @" class C { void M() { [|/*string s = '/*';*/|] } }"; var expected = @" class C { void M() { [|string s = '/*';|] } }"; ToggleComment(markup, expected); } internal override AbstractCommentSelectionBase<ValueTuple> GetToggleCommentCommandHandler(TestWorkspace workspace) { return (AbstractCommentSelectionBase<ValueTuple>)workspace.ExportProvider.GetExportedValues<ICommandHandler>() .First(export => typeof(CSharpToggleBlockCommentCommandHandler).Equals(export.GetType())); } internal override TestWorkspace GetWorkspace(string markup, TestComposition composition) => TestWorkspace.CreateCSharp(markup, composition: composition); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Editor.CSharp.CommentSelection; using Microsoft.CodeAnalysis.Editor.Implementation.CommentSelection; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities.CommentSelection; using Microsoft.VisualStudio.Commanding; using Microsoft.VisualStudio.Composition; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CommentSelection { [UseExportProvider] public class CSharpToggleBlockCommentCommandHandlerTests : AbstractToggleCommentTestBase { [WpfFact, Trait(Traits.Feature, Traits.Features.ToggleBlockComment)] public void AddComment_CommentMarkerStringBeforeSelection() { var markup = @" class C { void M() { string s = '/*'; [|var j = 2; var k = 3;|] } }"; var expected = @" class C { void M() { string s = '/*'; [|/*var j = 2; var k = 3;*/|] } }"; ToggleComment(markup, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.ToggleBlockComment)] public void AddComment_DirectiveWithCommentInsideSelection() { var markup = @" class C { void M() { [|var i = 1; #if false /*var j = 2;*/ #endif var k = 3;|] } }"; var expected = @" class C { void M() { [|/*var i = 1; #if false /*var j = 2;*/ #endif var k = 3;*/|] } }"; ToggleComment(markup, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.ToggleBlockComment)] public void AddComment_MarkerInsideSelection() { var markup = @" class C { void M() { [|var i = 1; string s = '/*'; var k = 3;|] } }"; var expected = @" class C { void M() { [|/*var i = 1; string s = '/*'; var k = 3;*/|] } }"; ToggleComment(markup, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.ToggleBlockComment)] public void AddComment_CloseCommentMarkerStringInSelection() { var markup = @" class C { void M() { [|var i = 1; string s = '*/'; var k = 3;|] } }"; var expected = @" class C { void M() { [|/*var i = 1; string s = '*/'; var k = 3;*/|] } }"; ToggleComment(markup, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.ToggleBlockComment)] public void AddComment_CommentMarkerStringAfterSelection() { var markup = @" class C { void M() { [|var i = 1; var j = 2;|] string s = '*/'; } }"; var expected = @" class C { void M() { [|/*var i = 1; var j = 2;*/|] string s = '*/'; } }"; ToggleComment(markup, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.ToggleBlockComment)] public void RemoveComment_CommentMarkerStringNearSelection() { var markup = @" class C { void M() { string s = '/*'; [|/*var i = 1; var j = 2; var k = 3;*/|] } }"; var expected = @" class C { void M() { string s = '/*'; [|var i = 1; var j = 2; var k = 3;|] } }"; ToggleComment(markup, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.ToggleBlockComment)] public void RemoveComment_CommentMarkerStringInSelection() { var markup = @" class C { void M() { [|/*string s = '/*';*/|] } }"; var expected = @" class C { void M() { [|string s = '/*';|] } }"; ToggleComment(markup, expected); } internal override AbstractCommentSelectionBase<ValueTuple> GetToggleCommentCommandHandler(TestWorkspace workspace) { return (AbstractCommentSelectionBase<ValueTuple>)workspace.ExportProvider.GetExportedValues<ICommandHandler>() .First(export => typeof(CSharpToggleBlockCommentCommandHandler).Equals(export.GetType())); } internal override TestWorkspace GetWorkspace(string markup, TestComposition composition) => TestWorkspace.CreateCSharp(markup, composition: composition); } }
-1
dotnet/roslyn
55,138
Avoid cancellation exceptions in intermediate operations
Addresses the following exceptions: ![image](https://user-images.githubusercontent.com/1408396/127185947-8a005aea-ae1c-4755-bf0f-21dfb8101352.png)
sharwell
2021-07-27T15:51:28Z
2021-07-27T21:36:45Z
3d8acbd585a75e9cdb3509623bf6c39ceb46b2c2
719d4ffa2be734463e5d7d4d74b23b8006fd7727
Avoid cancellation exceptions in intermediate operations. Addresses the following exceptions: ![image](https://user-images.githubusercontent.com/1408396/127185947-8a005aea-ae1c-4755-bf0f-21dfb8101352.png)
./src/Compilers/CSharp/Portable/FlowAnalysis/FlowAnalysisPass.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Diagnostics; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.PooledObjects; namespace Microsoft.CodeAnalysis.CSharp { internal class FlowAnalysisPass { /// <summary> /// The flow analysis pass. This pass reports required diagnostics for unreachable /// statements and uninitialized variables (through the call to FlowAnalysisWalker.Analyze), /// and inserts a final return statement if the end of a void-returning method is reachable. /// </summary> /// <param name="method">the method to be analyzed</param> /// <param name="block">the method's body</param> /// <param name="diagnostics">the receiver of the reported diagnostics</param> /// <param name="hasTrailingExpression">indicates whether this Script had a trailing expression</param> /// <param name="originalBodyNested">the original method body is the last statement in the block</param> /// <returns>the rewritten block for the method (with a return statement possibly inserted)</returns> public static BoundBlock Rewrite( MethodSymbol method, BoundBlock block, DiagnosticBag diagnostics, bool hasTrailingExpression, bool originalBodyNested) { #if DEBUG // We should only see a trailingExpression if we're in a Script initializer. Debug.Assert(!hasTrailingExpression || method.IsScriptInitializer); var initialDiagnosticCount = diagnostics.ToReadOnly().Length; #endif var compilation = method.DeclaringCompilation; if (method.ReturnsVoid || method.IsIterator || method.IsAsyncEffectivelyReturningTask(compilation)) { // we don't analyze synthesized void methods. if ((method.IsImplicitlyDeclared && !method.IsScriptInitializer) || Analyze(compilation, method, block, diagnostics)) { block = AppendImplicitReturn(block, method, originalBodyNested); } } else if (Analyze(compilation, method, block, diagnostics)) { // If the method is a lambda expression being converted to a non-void delegate type // and the end point is reachable then suppress the error here; a special error // will be reported by the lambda binder. Debug.Assert(method.MethodKind != MethodKind.AnonymousFunction); // Add implicit "return default(T)" if this is a submission that does not have a trailing expression. var submissionResultType = (method as SynthesizedInteractiveInitializerMethod)?.ResultType; if (!hasTrailingExpression && ((object)submissionResultType != null)) { Debug.Assert(!submissionResultType.IsVoidType()); var trailingExpression = new BoundDefaultExpression(method.GetNonNullSyntaxNode(), submissionResultType); var newStatements = block.Statements.Add(new BoundReturnStatement(trailingExpression.Syntax, RefKind.None, trailingExpression)); block = new BoundBlock(block.Syntax, ImmutableArray<LocalSymbol>.Empty, newStatements) { WasCompilerGenerated = true }; #if DEBUG // It should not be necessary to repeat analysis after adding this node, because adding a trailing // return in cases where one was missing should never produce different Diagnostics. IEnumerable<Diagnostic> GetErrorsOnly(IEnumerable<Diagnostic> diags) => diags.Where(d => d.Severity == DiagnosticSeverity.Error); var flowAnalysisDiagnostics = DiagnosticBag.GetInstance(); Debug.Assert(!Analyze(compilation, method, block, flowAnalysisDiagnostics)); // Ignore warnings since flow analysis reports nullability mismatches. Debug.Assert(GetErrorsOnly(flowAnalysisDiagnostics.ToReadOnly()).SequenceEqual(GetErrorsOnly(diagnostics.ToReadOnly().Skip(initialDiagnosticCount)))); flowAnalysisDiagnostics.Free(); #endif } // If there's more than one location, then the method is partial and we // have already reported a non-void partial method error. else if (method.Locations.Length == 1) { diagnostics.Add(ErrorCode.ERR_ReturnExpected, method.Locations[0], method); } } return block; } private static BoundBlock AppendImplicitReturn(BoundBlock body, MethodSymbol method, bool originalBodyNested) { if (originalBodyNested) { var statements = body.Statements; int n = statements.Length; var builder = ArrayBuilder<BoundStatement>.GetInstance(n); builder.AddRange(statements, n - 1); builder.Add(AppendImplicitReturn((BoundBlock)statements[n - 1], method)); return body.Update(body.Locals, ImmutableArray<LocalFunctionSymbol>.Empty, builder.ToImmutableAndFree()); } else { return AppendImplicitReturn(body, method); } } // insert the implicit "return" statement at the end of the method body // Normally, we wouldn't bother attaching syntax trees to compiler-generated nodes, but these // ones are going to have sequence points. internal static BoundBlock AppendImplicitReturn(BoundBlock body, MethodSymbol method) { Debug.Assert(body != null); Debug.Assert(method != null); SyntaxNode syntax = body.Syntax; Debug.Assert(body.WasCompilerGenerated || syntax.IsKind(SyntaxKind.Block) || syntax.IsKind(SyntaxKind.ArrowExpressionClause) || syntax.IsKind(SyntaxKind.ConstructorDeclaration) || syntax.IsKind(SyntaxKind.CompilationUnit)); BoundStatement ret = (method.IsIterator && !method.IsAsync) ? (BoundStatement)BoundYieldBreakStatement.Synthesized(syntax) : BoundReturnStatement.Synthesized(syntax, RefKind.None, null); return body.Update(body.Locals, body.LocalFunctions, body.Statements.Add(ret)); } private static bool Analyze( CSharpCompilation compilation, MethodSymbol method, BoundBlock block, DiagnosticBag diagnostics) { var result = ControlFlowPass.Analyze(compilation, method, block, diagnostics); DefiniteAssignmentPass.Analyze(compilation, method, block, diagnostics); 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.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Diagnostics; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.PooledObjects; namespace Microsoft.CodeAnalysis.CSharp { internal class FlowAnalysisPass { /// <summary> /// The flow analysis pass. This pass reports required diagnostics for unreachable /// statements and uninitialized variables (through the call to FlowAnalysisWalker.Analyze), /// and inserts a final return statement if the end of a void-returning method is reachable. /// </summary> /// <param name="method">the method to be analyzed</param> /// <param name="block">the method's body</param> /// <param name="diagnostics">the receiver of the reported diagnostics</param> /// <param name="hasTrailingExpression">indicates whether this Script had a trailing expression</param> /// <param name="originalBodyNested">the original method body is the last statement in the block</param> /// <returns>the rewritten block for the method (with a return statement possibly inserted)</returns> public static BoundBlock Rewrite( MethodSymbol method, BoundBlock block, DiagnosticBag diagnostics, bool hasTrailingExpression, bool originalBodyNested) { #if DEBUG // We should only see a trailingExpression if we're in a Script initializer. Debug.Assert(!hasTrailingExpression || method.IsScriptInitializer); var initialDiagnosticCount = diagnostics.ToReadOnly().Length; #endif var compilation = method.DeclaringCompilation; if (method.ReturnsVoid || method.IsIterator || method.IsAsyncEffectivelyReturningTask(compilation)) { // we don't analyze synthesized void methods. if ((method.IsImplicitlyDeclared && !method.IsScriptInitializer) || Analyze(compilation, method, block, diagnostics)) { block = AppendImplicitReturn(block, method, originalBodyNested); } } else if (Analyze(compilation, method, block, diagnostics)) { // If the method is a lambda expression being converted to a non-void delegate type // and the end point is reachable then suppress the error here; a special error // will be reported by the lambda binder. Debug.Assert(method.MethodKind != MethodKind.AnonymousFunction); // Add implicit "return default(T)" if this is a submission that does not have a trailing expression. var submissionResultType = (method as SynthesizedInteractiveInitializerMethod)?.ResultType; if (!hasTrailingExpression && ((object)submissionResultType != null)) { Debug.Assert(!submissionResultType.IsVoidType()); var trailingExpression = new BoundDefaultExpression(method.GetNonNullSyntaxNode(), submissionResultType); var newStatements = block.Statements.Add(new BoundReturnStatement(trailingExpression.Syntax, RefKind.None, trailingExpression)); block = new BoundBlock(block.Syntax, ImmutableArray<LocalSymbol>.Empty, newStatements) { WasCompilerGenerated = true }; #if DEBUG // It should not be necessary to repeat analysis after adding this node, because adding a trailing // return in cases where one was missing should never produce different Diagnostics. IEnumerable<Diagnostic> GetErrorsOnly(IEnumerable<Diagnostic> diags) => diags.Where(d => d.Severity == DiagnosticSeverity.Error); var flowAnalysisDiagnostics = DiagnosticBag.GetInstance(); Debug.Assert(!Analyze(compilation, method, block, flowAnalysisDiagnostics)); // Ignore warnings since flow analysis reports nullability mismatches. Debug.Assert(GetErrorsOnly(flowAnalysisDiagnostics.ToReadOnly()).SequenceEqual(GetErrorsOnly(diagnostics.ToReadOnly().Skip(initialDiagnosticCount)))); flowAnalysisDiagnostics.Free(); #endif } // If there's more than one location, then the method is partial and we // have already reported a non-void partial method error. else if (method.Locations.Length == 1) { diagnostics.Add(ErrorCode.ERR_ReturnExpected, method.Locations[0], method); } } return block; } private static BoundBlock AppendImplicitReturn(BoundBlock body, MethodSymbol method, bool originalBodyNested) { if (originalBodyNested) { var statements = body.Statements; int n = statements.Length; var builder = ArrayBuilder<BoundStatement>.GetInstance(n); builder.AddRange(statements, n - 1); builder.Add(AppendImplicitReturn((BoundBlock)statements[n - 1], method)); return body.Update(body.Locals, ImmutableArray<LocalFunctionSymbol>.Empty, builder.ToImmutableAndFree()); } else { return AppendImplicitReturn(body, method); } } // insert the implicit "return" statement at the end of the method body // Normally, we wouldn't bother attaching syntax trees to compiler-generated nodes, but these // ones are going to have sequence points. internal static BoundBlock AppendImplicitReturn(BoundBlock body, MethodSymbol method) { Debug.Assert(body != null); Debug.Assert(method != null); SyntaxNode syntax = body.Syntax; Debug.Assert(body.WasCompilerGenerated || syntax.IsKind(SyntaxKind.Block) || syntax.IsKind(SyntaxKind.ArrowExpressionClause) || syntax.IsKind(SyntaxKind.ConstructorDeclaration) || syntax.IsKind(SyntaxKind.CompilationUnit)); BoundStatement ret = (method.IsIterator && !method.IsAsync) ? (BoundStatement)BoundYieldBreakStatement.Synthesized(syntax) : BoundReturnStatement.Synthesized(syntax, RefKind.None, null); return body.Update(body.Locals, body.LocalFunctions, body.Statements.Add(ret)); } private static bool Analyze( CSharpCompilation compilation, MethodSymbol method, BoundBlock block, DiagnosticBag diagnostics) { var result = ControlFlowPass.Analyze(compilation, method, block, diagnostics); DefiniteAssignmentPass.Analyze(compilation, method, block, diagnostics); return result; } } }
-1
dotnet/roslyn
55,138
Avoid cancellation exceptions in intermediate operations
Addresses the following exceptions: ![image](https://user-images.githubusercontent.com/1408396/127185947-8a005aea-ae1c-4755-bf0f-21dfb8101352.png)
sharwell
2021-07-27T15:51:28Z
2021-07-27T21:36:45Z
3d8acbd585a75e9cdb3509623bf6c39ceb46b2c2
719d4ffa2be734463e5d7d4d74b23b8006fd7727
Avoid cancellation exceptions in intermediate operations. Addresses the following exceptions: ![image](https://user-images.githubusercontent.com/1408396/127185947-8a005aea-ae1c-4755-bf0f-21dfb8101352.png)
./src/Scripting/Core/ScriptCompiler.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Text; using System.Threading; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.Scripting { internal abstract class ScriptCompiler { public abstract Compilation CreateSubmission(Script script); public abstract DiagnosticFormatter DiagnosticFormatter { get; } public abstract StringComparer IdentifierComparer { get; } public abstract SyntaxTree ParseSubmission(SourceText text, ParseOptions parseOptions, CancellationToken cancellationToken); public abstract bool IsCompleteSubmission(SyntaxTree tree); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Text; using System.Threading; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.Scripting { internal abstract class ScriptCompiler { public abstract Compilation CreateSubmission(Script script); public abstract DiagnosticFormatter DiagnosticFormatter { get; } public abstract StringComparer IdentifierComparer { get; } public abstract SyntaxTree ParseSubmission(SourceText text, ParseOptions parseOptions, CancellationToken cancellationToken); public abstract bool IsCompleteSubmission(SyntaxTree tree); } }
-1
dotnet/roslyn
55,138
Avoid cancellation exceptions in intermediate operations
Addresses the following exceptions: ![image](https://user-images.githubusercontent.com/1408396/127185947-8a005aea-ae1c-4755-bf0f-21dfb8101352.png)
sharwell
2021-07-27T15:51:28Z
2021-07-27T21:36:45Z
3d8acbd585a75e9cdb3509623bf6c39ceb46b2c2
719d4ffa2be734463e5d7d4d74b23b8006fd7727
Avoid cancellation exceptions in intermediate operations. Addresses the following exceptions: ![image](https://user-images.githubusercontent.com/1408396/127185947-8a005aea-ae1c-4755-bf0f-21dfb8101352.png)
./src/Compilers/Core/Portable/Emit/ErrorType.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Reflection; using System.Reflection.Metadata; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Emit { /// <summary> /// Error type symbols should be replaced with an object of this class /// in the translation layer for emit. /// </summary> internal class ErrorType : Cci.INamespaceTypeReference { public static readonly ErrorType Singleton = new ErrorType(); /// <summary> /// For the name we will use a word "Error" followed by a guid, generated on the spot. /// </summary> private static readonly string s_name = "Error" + Guid.NewGuid().ToString("B"); Cci.IUnitReference Cci.INamespaceTypeReference.GetUnit(EmitContext context) { return ErrorAssembly.Singleton; } string Cci.INamespaceTypeReference.NamespaceName { get { return ""; } } ushort Cci.INamedTypeReference.GenericParameterCount { get { return 0; } } bool Cci.INamedTypeReference.MangleName { get { return false; } } bool Cci.ITypeReference.IsEnum { get { return false; } } bool Cci.ITypeReference.IsValueType { get { return false; } } Cci.ITypeDefinition Cci.ITypeReference.GetResolvedType(EmitContext context) { return null; } Cci.PrimitiveTypeCode Cci.ITypeReference.TypeCode { get { return Cci.PrimitiveTypeCode.NotPrimitive; } } TypeDefinitionHandle Cci.ITypeReference.TypeDef { get { return default(TypeDefinitionHandle); } } Cci.IGenericMethodParameterReference Cci.ITypeReference.AsGenericMethodParameterReference { get { return null; } } Cci.IGenericTypeInstanceReference Cci.ITypeReference.AsGenericTypeInstanceReference { get { return null; } } Cci.IGenericTypeParameterReference Cci.ITypeReference.AsGenericTypeParameterReference { get { return null; } } Cci.INamespaceTypeDefinition Cci.ITypeReference.AsNamespaceTypeDefinition(EmitContext context) { return null; } Cci.INamespaceTypeReference Cci.ITypeReference.AsNamespaceTypeReference { get { return this; } } Cci.INestedTypeDefinition Cci.ITypeReference.AsNestedTypeDefinition(EmitContext context) { return null; } Cci.INestedTypeReference Cci.ITypeReference.AsNestedTypeReference { get { return null; } } Cci.ISpecializedNestedTypeReference Cci.ITypeReference.AsSpecializedNestedTypeReference { get { return null; } } Cci.ITypeDefinition Cci.ITypeReference.AsTypeDefinition(EmitContext context) { return null; } IEnumerable<Cci.ICustomAttribute> Cci.IReference.GetAttributes(EmitContext context) { return SpecializedCollections.EmptyEnumerable<Cci.ICustomAttribute>(); } void Cci.IReference.Dispatch(Cci.MetadataVisitor visitor) { visitor.Visit((Cci.INamespaceTypeReference)this); } Cci.IDefinition Cci.IReference.AsDefinition(EmitContext context) { return null; } Symbols.ISymbolInternal Cci.IReference.GetInternalSymbol() => null; string Cci.INamedEntity.Name { get { return s_name; } } public sealed override bool Equals(object obj) { // It is not supported to rely on default equality of these Cci objects, an explicit way to compare and hash them should be used. throw Roslyn.Utilities.ExceptionUtilities.Unreachable; } public sealed override int GetHashCode() { // It is not supported to rely on default equality of these Cci objects, an explicit way to compare and hash them should be used. throw Roslyn.Utilities.ExceptionUtilities.Unreachable; } /// <summary> /// A fake containing assembly for an ErrorType object. /// </summary> private sealed class ErrorAssembly : Cci.IAssemblyReference { public static readonly ErrorAssembly Singleton = new ErrorAssembly(); /// <summary> /// For the name we will use a word "Error" followed by a guid, generated on the spot. /// </summary> private static readonly AssemblyIdentity s_identity = new AssemblyIdentity( name: "Error" + Guid.NewGuid().ToString("B"), version: AssemblyIdentity.NullVersion, cultureName: "", publicKeyOrToken: ImmutableArray<byte>.Empty, hasPublicKey: false, isRetargetable: false, contentType: AssemblyContentType.Default); AssemblyIdentity Cci.IAssemblyReference.Identity => s_identity; Version Cci.IAssemblyReference.AssemblyVersionPattern => null; Cci.IAssemblyReference Cci.IModuleReference.GetContainingAssembly(EmitContext context) { return this; } IEnumerable<Cci.ICustomAttribute> Cci.IReference.GetAttributes(EmitContext context) { return SpecializedCollections.EmptyEnumerable<Cci.ICustomAttribute>(); } void Cci.IReference.Dispatch(Cci.MetadataVisitor visitor) { visitor.Visit((Cci.IAssemblyReference)this); } Cci.IDefinition Cci.IReference.AsDefinition(EmitContext context) { return null; } Symbols.ISymbolInternal Cci.IReference.GetInternalSymbol() => null; string Cci.INamedEntity.Name => s_identity.Name; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Reflection; using System.Reflection.Metadata; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Emit { /// <summary> /// Error type symbols should be replaced with an object of this class /// in the translation layer for emit. /// </summary> internal class ErrorType : Cci.INamespaceTypeReference { public static readonly ErrorType Singleton = new ErrorType(); /// <summary> /// For the name we will use a word "Error" followed by a guid, generated on the spot. /// </summary> private static readonly string s_name = "Error" + Guid.NewGuid().ToString("B"); Cci.IUnitReference Cci.INamespaceTypeReference.GetUnit(EmitContext context) { return ErrorAssembly.Singleton; } string Cci.INamespaceTypeReference.NamespaceName { get { return ""; } } ushort Cci.INamedTypeReference.GenericParameterCount { get { return 0; } } bool Cci.INamedTypeReference.MangleName { get { return false; } } bool Cci.ITypeReference.IsEnum { get { return false; } } bool Cci.ITypeReference.IsValueType { get { return false; } } Cci.ITypeDefinition Cci.ITypeReference.GetResolvedType(EmitContext context) { return null; } Cci.PrimitiveTypeCode Cci.ITypeReference.TypeCode { get { return Cci.PrimitiveTypeCode.NotPrimitive; } } TypeDefinitionHandle Cci.ITypeReference.TypeDef { get { return default(TypeDefinitionHandle); } } Cci.IGenericMethodParameterReference Cci.ITypeReference.AsGenericMethodParameterReference { get { return null; } } Cci.IGenericTypeInstanceReference Cci.ITypeReference.AsGenericTypeInstanceReference { get { return null; } } Cci.IGenericTypeParameterReference Cci.ITypeReference.AsGenericTypeParameterReference { get { return null; } } Cci.INamespaceTypeDefinition Cci.ITypeReference.AsNamespaceTypeDefinition(EmitContext context) { return null; } Cci.INamespaceTypeReference Cci.ITypeReference.AsNamespaceTypeReference { get { return this; } } Cci.INestedTypeDefinition Cci.ITypeReference.AsNestedTypeDefinition(EmitContext context) { return null; } Cci.INestedTypeReference Cci.ITypeReference.AsNestedTypeReference { get { return null; } } Cci.ISpecializedNestedTypeReference Cci.ITypeReference.AsSpecializedNestedTypeReference { get { return null; } } Cci.ITypeDefinition Cci.ITypeReference.AsTypeDefinition(EmitContext context) { return null; } IEnumerable<Cci.ICustomAttribute> Cci.IReference.GetAttributes(EmitContext context) { return SpecializedCollections.EmptyEnumerable<Cci.ICustomAttribute>(); } void Cci.IReference.Dispatch(Cci.MetadataVisitor visitor) { visitor.Visit((Cci.INamespaceTypeReference)this); } Cci.IDefinition Cci.IReference.AsDefinition(EmitContext context) { return null; } Symbols.ISymbolInternal Cci.IReference.GetInternalSymbol() => null; string Cci.INamedEntity.Name { get { return s_name; } } public sealed override bool Equals(object obj) { // It is not supported to rely on default equality of these Cci objects, an explicit way to compare and hash them should be used. throw Roslyn.Utilities.ExceptionUtilities.Unreachable; } public sealed override int GetHashCode() { // It is not supported to rely on default equality of these Cci objects, an explicit way to compare and hash them should be used. throw Roslyn.Utilities.ExceptionUtilities.Unreachable; } /// <summary> /// A fake containing assembly for an ErrorType object. /// </summary> private sealed class ErrorAssembly : Cci.IAssemblyReference { public static readonly ErrorAssembly Singleton = new ErrorAssembly(); /// <summary> /// For the name we will use a word "Error" followed by a guid, generated on the spot. /// </summary> private static readonly AssemblyIdentity s_identity = new AssemblyIdentity( name: "Error" + Guid.NewGuid().ToString("B"), version: AssemblyIdentity.NullVersion, cultureName: "", publicKeyOrToken: ImmutableArray<byte>.Empty, hasPublicKey: false, isRetargetable: false, contentType: AssemblyContentType.Default); AssemblyIdentity Cci.IAssemblyReference.Identity => s_identity; Version Cci.IAssemblyReference.AssemblyVersionPattern => null; Cci.IAssemblyReference Cci.IModuleReference.GetContainingAssembly(EmitContext context) { return this; } IEnumerable<Cci.ICustomAttribute> Cci.IReference.GetAttributes(EmitContext context) { return SpecializedCollections.EmptyEnumerable<Cci.ICustomAttribute>(); } void Cci.IReference.Dispatch(Cci.MetadataVisitor visitor) { visitor.Visit((Cci.IAssemblyReference)this); } Cci.IDefinition Cci.IReference.AsDefinition(EmitContext context) { return null; } Symbols.ISymbolInternal Cci.IReference.GetInternalSymbol() => null; string Cci.INamedEntity.Name => s_identity.Name; } } }
-1
dotnet/roslyn
55,138
Avoid cancellation exceptions in intermediate operations
Addresses the following exceptions: ![image](https://user-images.githubusercontent.com/1408396/127185947-8a005aea-ae1c-4755-bf0f-21dfb8101352.png)
sharwell
2021-07-27T15:51:28Z
2021-07-27T21:36:45Z
3d8acbd585a75e9cdb3509623bf6c39ceb46b2c2
719d4ffa2be734463e5d7d4d74b23b8006fd7727
Avoid cancellation exceptions in intermediate operations. Addresses the following exceptions: ![image](https://user-images.githubusercontent.com/1408396/127185947-8a005aea-ae1c-4755-bf0f-21dfb8101352.png)
./src/EditorFeatures/Core.Wpf/NavigateTo/DefaultNavigateToPreviewService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET 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.VisualStudio.Language.NavigateTo.Interfaces; namespace Microsoft.CodeAnalysis.Editor.Implementation.NavigateTo { internal sealed class DefaultNavigateToPreviewService : INavigateToPreviewService { public int GetProvisionalViewingStatus(Document document) => 0; public bool CanPreview(Document document) => true; public void PreviewItem(INavigateToItemDisplay itemDisplay) { } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET 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.VisualStudio.Language.NavigateTo.Interfaces; namespace Microsoft.CodeAnalysis.Editor.Implementation.NavigateTo { internal sealed class DefaultNavigateToPreviewService : INavigateToPreviewService { public int GetProvisionalViewingStatus(Document document) => 0; public bool CanPreview(Document document) => true; public void PreviewItem(INavigateToItemDisplay itemDisplay) { } } }
-1
dotnet/roslyn
55,138
Avoid cancellation exceptions in intermediate operations
Addresses the following exceptions: ![image](https://user-images.githubusercontent.com/1408396/127185947-8a005aea-ae1c-4755-bf0f-21dfb8101352.png)
sharwell
2021-07-27T15:51:28Z
2021-07-27T21:36:45Z
3d8acbd585a75e9cdb3509623bf6c39ceb46b2c2
719d4ffa2be734463e5d7d4d74b23b8006fd7727
Avoid cancellation exceptions in intermediate operations. Addresses the following exceptions: ![image](https://user-images.githubusercontent.com/1408396/127185947-8a005aea-ae1c-4755-bf0f-21dfb8101352.png)
./src/Compilers/Core/Portable/DiagnosticAnalyzer/SuppressMessageAttributeState.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Runtime.CompilerServices; using System.Threading; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Diagnostics { internal partial class SuppressMessageAttributeState { private static readonly SmallDictionary<string, TargetScope> s_suppressMessageScopeTypes = new SmallDictionary<string, TargetScope>(StringComparer.OrdinalIgnoreCase) { { string.Empty, TargetScope.None }, { "module", TargetScope.Module }, { "namespace", TargetScope.Namespace }, { "resource", TargetScope.Resource }, { "type", TargetScope.Type }, { "member", TargetScope.Member }, { "namespaceanddescendants", TargetScope.NamespaceAndDescendants } }; private static bool TryGetTargetScope(SuppressMessageInfo info, out TargetScope scope) => s_suppressMessageScopeTypes.TryGetValue(info.Scope ?? string.Empty, out scope); private readonly Compilation _compilation; private GlobalSuppressions? _lazyGlobalSuppressions; private readonly ConcurrentDictionary<ISymbol, ImmutableDictionary<string, SuppressMessageInfo>> _localSuppressionsBySymbol; private StrongBox<ISymbol?>? _lazySuppressMessageAttribute; private StrongBox<ISymbol?>? _lazyUnconditionalSuppressMessageAttribute; private class GlobalSuppressions { private readonly Dictionary<string, SuppressMessageInfo> _compilationWideSuppressions = new Dictionary<string, SuppressMessageInfo>(); private readonly Dictionary<ISymbol, Dictionary<string, SuppressMessageInfo>> _globalSymbolSuppressions = new Dictionary<ISymbol, Dictionary<string, SuppressMessageInfo>>(); public void AddCompilationWideSuppression(SuppressMessageInfo info) { AddOrUpdate(info, _compilationWideSuppressions); } public void AddGlobalSymbolSuppression(ISymbol symbol, SuppressMessageInfo info) { Dictionary<string, SuppressMessageInfo>? suppressions; if (_globalSymbolSuppressions.TryGetValue(symbol, out suppressions)) { AddOrUpdate(info, suppressions); } else { suppressions = new Dictionary<string, SuppressMessageInfo>() { { info.Id, info } }; _globalSymbolSuppressions.Add(symbol, suppressions); } } public bool HasCompilationWideSuppression(string id, out SuppressMessageInfo info) { return _compilationWideSuppressions.TryGetValue(id, out info); } public bool HasGlobalSymbolSuppression(ISymbol symbol, string id, bool isImmediatelyContainingSymbol, out SuppressMessageInfo info) { Debug.Assert(symbol != null); Dictionary<string, SuppressMessageInfo>? suppressions; if (_globalSymbolSuppressions.TryGetValue(symbol, out suppressions) && suppressions.TryGetValue(id, out info)) { if (symbol.Kind != SymbolKind.Namespace) { return true; } if (TryGetTargetScope(info, out TargetScope targetScope)) { switch (targetScope) { case TargetScope.Namespace: // Special case: Only suppress syntax diagnostics in namespace declarations if the namespace is the closest containing symbol. // In other words, only apply suppression to the immediately containing namespace declaration and not to its children or parents. return isImmediatelyContainingSymbol; case TargetScope.NamespaceAndDescendants: return true; } } } info = default(SuppressMessageInfo); return false; } } internal SuppressMessageAttributeState(Compilation compilation) { _compilation = compilation; _localSuppressionsBySymbol = new ConcurrentDictionary<ISymbol, ImmutableDictionary<string, SuppressMessageInfo>>(); } public Diagnostic ApplySourceSuppressions(Diagnostic diagnostic) { if (diagnostic.IsSuppressed) { // Diagnostic already has a source suppression. return diagnostic; } SuppressMessageInfo info; if (IsDiagnosticSuppressed(diagnostic, out info)) { // Attach the suppression info to the diagnostic. diagnostic = diagnostic.WithIsSuppressed(true); } return diagnostic; } public bool IsDiagnosticSuppressed(Diagnostic diagnostic, [NotNullWhen(true)] out AttributeData? suppressingAttribute) { SuppressMessageInfo info; if (IsDiagnosticSuppressed(diagnostic, out info)) { suppressingAttribute = info.Attribute; return true; } suppressingAttribute = null; return false; } private bool IsDiagnosticSuppressed(Diagnostic diagnostic, out SuppressMessageInfo info) { info = default; if (diagnostic.CustomTags.Contains(WellKnownDiagnosticTags.Compiler)) { // SuppressMessage attributes do not apply to compiler diagnostics. return false; } var id = diagnostic.Id; var location = diagnostic.Location; if (IsDiagnosticGloballySuppressed(id, symbolOpt: null, isImmediatelyContainingSymbol: false, info: out info)) { return true; } // Walk up the syntax tree checking for suppression by any declared symbols encountered if (location.IsInSource) { var model = _compilation.GetSemanticModel(location.SourceTree); bool inImmediatelyContainingSymbol = true; for (var node = location.SourceTree.GetRoot().FindNode(location.SourceSpan, getInnermostNodeForTie: true); node != null; node = node.Parent) { var declaredSymbols = model.GetDeclaredSymbolsForNode(node); Debug.Assert(declaredSymbols != null); foreach (var symbol in declaredSymbols) { if (symbol.Kind == SymbolKind.Namespace) { return hasNamespaceSuppression((INamespaceSymbol)symbol, inImmediatelyContainingSymbol); } else if (IsDiagnosticLocallySuppressed(id, symbol, out info) || IsDiagnosticGloballySuppressed(id, symbol, inImmediatelyContainingSymbol, out info)) { return true; } } if (!declaredSymbols.IsEmpty) { inImmediatelyContainingSymbol = false; } } } return false; bool hasNamespaceSuppression(INamespaceSymbol namespaceSymbol, bool inImmediatelyContainingSymbol) { do { if (IsDiagnosticGloballySuppressed(id, namespaceSymbol, inImmediatelyContainingSymbol, out _)) { return true; } namespaceSymbol = namespaceSymbol.ContainingNamespace; inImmediatelyContainingSymbol = false; } while (namespaceSymbol != null); return false; } } private bool IsDiagnosticGloballySuppressed(string id, ISymbol? symbolOpt, bool isImmediatelyContainingSymbol, out SuppressMessageInfo info) { var globalSuppressions = this.DecodeGlobalSuppressMessageAttributes(); return globalSuppressions.HasCompilationWideSuppression(id, out info) || symbolOpt != null && globalSuppressions.HasGlobalSymbolSuppression(symbolOpt, id, isImmediatelyContainingSymbol, out info); } private bool IsDiagnosticLocallySuppressed(string id, ISymbol symbol, out SuppressMessageInfo info) { var suppressions = _localSuppressionsBySymbol.GetOrAdd(symbol, this.DecodeLocalSuppressMessageAttributes); return suppressions.TryGetValue(id, out info); } private ISymbol? SuppressMessageAttribute { get { if (_lazySuppressMessageAttribute is null) { Interlocked.CompareExchange( ref _lazySuppressMessageAttribute, new StrongBox<ISymbol?>(_compilation.GetTypeByMetadataName("System.Diagnostics.CodeAnalysis.SuppressMessageAttribute")), null); } return _lazySuppressMessageAttribute.Value; } } private ISymbol? UnconditionalSuppressMessageAttribute { get { if (_lazyUnconditionalSuppressMessageAttribute is null) { Interlocked.CompareExchange( ref _lazyUnconditionalSuppressMessageAttribute, new StrongBox<ISymbol?>(_compilation.GetTypeByMetadataName("System.Diagnostics.CodeAnalysis.UnconditionalSuppressMessageAttribute")), null); } return _lazyUnconditionalSuppressMessageAttribute.Value; } } private GlobalSuppressions DecodeGlobalSuppressMessageAttributes() { if (_lazyGlobalSuppressions == null) { var suppressions = new GlobalSuppressions(); DecodeGlobalSuppressMessageAttributes(_compilation, _compilation.Assembly, suppressions); foreach (var module in _compilation.Assembly.Modules) { DecodeGlobalSuppressMessageAttributes(_compilation, module, suppressions); } Interlocked.CompareExchange(ref _lazyGlobalSuppressions, suppressions, null); } return _lazyGlobalSuppressions; } private bool IsSuppressionAttribute(AttributeData a) => a.AttributeClass == SuppressMessageAttribute || a.AttributeClass == UnconditionalSuppressMessageAttribute; private ImmutableDictionary<string, SuppressMessageInfo> DecodeLocalSuppressMessageAttributes(ISymbol symbol) { var attributes = symbol.GetAttributes().Where(a => IsSuppressionAttribute(a)); return DecodeLocalSuppressMessageAttributes(symbol, attributes); } private static ImmutableDictionary<string, SuppressMessageInfo> DecodeLocalSuppressMessageAttributes(ISymbol symbol, IEnumerable<AttributeData> attributes) { var builder = ImmutableDictionary.CreateBuilder<string, SuppressMessageInfo>(); foreach (var attribute in attributes) { SuppressMessageInfo info; if (!TryDecodeSuppressMessageAttributeData(attribute, out info)) { continue; } AddOrUpdate(info, builder); } return builder.ToImmutable(); } private static void AddOrUpdate(SuppressMessageInfo info, IDictionary<string, SuppressMessageInfo> builder) { // TODO: How should we deal with multiple SuppressMessage attributes, with different suppression info/states? // For now, we just pick the last attribute, if not suppressed. SuppressMessageInfo currentInfo; if (!builder.TryGetValue(info.Id, out currentInfo)) { builder[info.Id] = info; } } private void DecodeGlobalSuppressMessageAttributes(Compilation compilation, ISymbol symbol, GlobalSuppressions globalSuppressions) { Debug.Assert(symbol is IAssemblySymbol || symbol is IModuleSymbol); var attributes = symbol.GetAttributes().Where(a => IsSuppressionAttribute(a)); DecodeGlobalSuppressMessageAttributes(compilation, symbol, globalSuppressions, attributes); } private static void DecodeGlobalSuppressMessageAttributes(Compilation compilation, ISymbol symbol, GlobalSuppressions globalSuppressions, IEnumerable<AttributeData> attributes) { foreach (var instance in attributes) { SuppressMessageInfo info; if (!TryDecodeSuppressMessageAttributeData(instance, out info)) { continue; } if (TryGetTargetScope(info, out TargetScope scope)) { if ((scope == TargetScope.Module || scope == TargetScope.None) && info.Target == null) { // This suppression is applies to the entire compilation globalSuppressions.AddCompilationWideSuppression(info); continue; } } else { // Invalid value for scope continue; } // Decode Target if (info.Target == null) { continue; } foreach (var target in ResolveTargetSymbols(compilation, info.Target, scope)) { globalSuppressions.AddGlobalSymbolSuppression(target, info); } } } internal static ImmutableArray<ISymbol> ResolveTargetSymbols(Compilation compilation, string target, TargetScope scope) { switch (scope) { case TargetScope.Namespace: case TargetScope.Type: case TargetScope.Member: return new TargetSymbolResolver(compilation, scope, target).Resolve(out _); case TargetScope.NamespaceAndDescendants: return ResolveTargetSymbols(compilation, target, TargetScope.Namespace); default: return ImmutableArray<ISymbol>.Empty; } } private static bool TryDecodeSuppressMessageAttributeData(AttributeData attribute, out SuppressMessageInfo info) { info = default(SuppressMessageInfo); // We need at least the Category and Id to decode the diagnostic to suppress. // The only SuppressMessageAttribute constructor requires those two parameters. if (attribute.CommonConstructorArguments.Length < 2) { return false; } // Ignore the category parameter because it does not identify the diagnostic // and category information can be obtained from diagnostics themselves. info.Id = attribute.CommonConstructorArguments[1].ValueInternal as string; if (info.Id == null) { return false; } // Allow an optional human-readable descriptive name on the end of an Id. // See http://msdn.microsoft.com/en-us/library/ms244717.aspx var separatorIndex = info.Id.IndexOf(':'); if (separatorIndex != -1) { info.Id = info.Id.Remove(separatorIndex); } info.Scope = attribute.DecodeNamedArgument<string>("Scope", SpecialType.System_String); info.Target = attribute.DecodeNamedArgument<string>("Target", SpecialType.System_String); info.MessageId = attribute.DecodeNamedArgument<string>("MessageId", SpecialType.System_String); info.Attribute = attribute; 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; using System.Collections.Concurrent; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Runtime.CompilerServices; using System.Threading; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Diagnostics { internal partial class SuppressMessageAttributeState { private static readonly SmallDictionary<string, TargetScope> s_suppressMessageScopeTypes = new SmallDictionary<string, TargetScope>(StringComparer.OrdinalIgnoreCase) { { string.Empty, TargetScope.None }, { "module", TargetScope.Module }, { "namespace", TargetScope.Namespace }, { "resource", TargetScope.Resource }, { "type", TargetScope.Type }, { "member", TargetScope.Member }, { "namespaceanddescendants", TargetScope.NamespaceAndDescendants } }; private static bool TryGetTargetScope(SuppressMessageInfo info, out TargetScope scope) => s_suppressMessageScopeTypes.TryGetValue(info.Scope ?? string.Empty, out scope); private readonly Compilation _compilation; private GlobalSuppressions? _lazyGlobalSuppressions; private readonly ConcurrentDictionary<ISymbol, ImmutableDictionary<string, SuppressMessageInfo>> _localSuppressionsBySymbol; private StrongBox<ISymbol?>? _lazySuppressMessageAttribute; private StrongBox<ISymbol?>? _lazyUnconditionalSuppressMessageAttribute; private class GlobalSuppressions { private readonly Dictionary<string, SuppressMessageInfo> _compilationWideSuppressions = new Dictionary<string, SuppressMessageInfo>(); private readonly Dictionary<ISymbol, Dictionary<string, SuppressMessageInfo>> _globalSymbolSuppressions = new Dictionary<ISymbol, Dictionary<string, SuppressMessageInfo>>(); public void AddCompilationWideSuppression(SuppressMessageInfo info) { AddOrUpdate(info, _compilationWideSuppressions); } public void AddGlobalSymbolSuppression(ISymbol symbol, SuppressMessageInfo info) { Dictionary<string, SuppressMessageInfo>? suppressions; if (_globalSymbolSuppressions.TryGetValue(symbol, out suppressions)) { AddOrUpdate(info, suppressions); } else { suppressions = new Dictionary<string, SuppressMessageInfo>() { { info.Id, info } }; _globalSymbolSuppressions.Add(symbol, suppressions); } } public bool HasCompilationWideSuppression(string id, out SuppressMessageInfo info) { return _compilationWideSuppressions.TryGetValue(id, out info); } public bool HasGlobalSymbolSuppression(ISymbol symbol, string id, bool isImmediatelyContainingSymbol, out SuppressMessageInfo info) { Debug.Assert(symbol != null); Dictionary<string, SuppressMessageInfo>? suppressions; if (_globalSymbolSuppressions.TryGetValue(symbol, out suppressions) && suppressions.TryGetValue(id, out info)) { if (symbol.Kind != SymbolKind.Namespace) { return true; } if (TryGetTargetScope(info, out TargetScope targetScope)) { switch (targetScope) { case TargetScope.Namespace: // Special case: Only suppress syntax diagnostics in namespace declarations if the namespace is the closest containing symbol. // In other words, only apply suppression to the immediately containing namespace declaration and not to its children or parents. return isImmediatelyContainingSymbol; case TargetScope.NamespaceAndDescendants: return true; } } } info = default(SuppressMessageInfo); return false; } } internal SuppressMessageAttributeState(Compilation compilation) { _compilation = compilation; _localSuppressionsBySymbol = new ConcurrentDictionary<ISymbol, ImmutableDictionary<string, SuppressMessageInfo>>(); } public Diagnostic ApplySourceSuppressions(Diagnostic diagnostic) { if (diagnostic.IsSuppressed) { // Diagnostic already has a source suppression. return diagnostic; } SuppressMessageInfo info; if (IsDiagnosticSuppressed(diagnostic, out info)) { // Attach the suppression info to the diagnostic. diagnostic = diagnostic.WithIsSuppressed(true); } return diagnostic; } public bool IsDiagnosticSuppressed(Diagnostic diagnostic, [NotNullWhen(true)] out AttributeData? suppressingAttribute) { SuppressMessageInfo info; if (IsDiagnosticSuppressed(diagnostic, out info)) { suppressingAttribute = info.Attribute; return true; } suppressingAttribute = null; return false; } private bool IsDiagnosticSuppressed(Diagnostic diagnostic, out SuppressMessageInfo info) { info = default; if (diagnostic.CustomTags.Contains(WellKnownDiagnosticTags.Compiler)) { // SuppressMessage attributes do not apply to compiler diagnostics. return false; } var id = diagnostic.Id; var location = diagnostic.Location; if (IsDiagnosticGloballySuppressed(id, symbolOpt: null, isImmediatelyContainingSymbol: false, info: out info)) { return true; } // Walk up the syntax tree checking for suppression by any declared symbols encountered if (location.IsInSource) { var model = _compilation.GetSemanticModel(location.SourceTree); bool inImmediatelyContainingSymbol = true; for (var node = location.SourceTree.GetRoot().FindNode(location.SourceSpan, getInnermostNodeForTie: true); node != null; node = node.Parent) { var declaredSymbols = model.GetDeclaredSymbolsForNode(node); Debug.Assert(declaredSymbols != null); foreach (var symbol in declaredSymbols) { if (symbol.Kind == SymbolKind.Namespace) { return hasNamespaceSuppression((INamespaceSymbol)symbol, inImmediatelyContainingSymbol); } else if (IsDiagnosticLocallySuppressed(id, symbol, out info) || IsDiagnosticGloballySuppressed(id, symbol, inImmediatelyContainingSymbol, out info)) { return true; } } if (!declaredSymbols.IsEmpty) { inImmediatelyContainingSymbol = false; } } } return false; bool hasNamespaceSuppression(INamespaceSymbol namespaceSymbol, bool inImmediatelyContainingSymbol) { do { if (IsDiagnosticGloballySuppressed(id, namespaceSymbol, inImmediatelyContainingSymbol, out _)) { return true; } namespaceSymbol = namespaceSymbol.ContainingNamespace; inImmediatelyContainingSymbol = false; } while (namespaceSymbol != null); return false; } } private bool IsDiagnosticGloballySuppressed(string id, ISymbol? symbolOpt, bool isImmediatelyContainingSymbol, out SuppressMessageInfo info) { var globalSuppressions = this.DecodeGlobalSuppressMessageAttributes(); return globalSuppressions.HasCompilationWideSuppression(id, out info) || symbolOpt != null && globalSuppressions.HasGlobalSymbolSuppression(symbolOpt, id, isImmediatelyContainingSymbol, out info); } private bool IsDiagnosticLocallySuppressed(string id, ISymbol symbol, out SuppressMessageInfo info) { var suppressions = _localSuppressionsBySymbol.GetOrAdd(symbol, this.DecodeLocalSuppressMessageAttributes); return suppressions.TryGetValue(id, out info); } private ISymbol? SuppressMessageAttribute { get { if (_lazySuppressMessageAttribute is null) { Interlocked.CompareExchange( ref _lazySuppressMessageAttribute, new StrongBox<ISymbol?>(_compilation.GetTypeByMetadataName("System.Diagnostics.CodeAnalysis.SuppressMessageAttribute")), null); } return _lazySuppressMessageAttribute.Value; } } private ISymbol? UnconditionalSuppressMessageAttribute { get { if (_lazyUnconditionalSuppressMessageAttribute is null) { Interlocked.CompareExchange( ref _lazyUnconditionalSuppressMessageAttribute, new StrongBox<ISymbol?>(_compilation.GetTypeByMetadataName("System.Diagnostics.CodeAnalysis.UnconditionalSuppressMessageAttribute")), null); } return _lazyUnconditionalSuppressMessageAttribute.Value; } } private GlobalSuppressions DecodeGlobalSuppressMessageAttributes() { if (_lazyGlobalSuppressions == null) { var suppressions = new GlobalSuppressions(); DecodeGlobalSuppressMessageAttributes(_compilation, _compilation.Assembly, suppressions); foreach (var module in _compilation.Assembly.Modules) { DecodeGlobalSuppressMessageAttributes(_compilation, module, suppressions); } Interlocked.CompareExchange(ref _lazyGlobalSuppressions, suppressions, null); } return _lazyGlobalSuppressions; } private bool IsSuppressionAttribute(AttributeData a) => a.AttributeClass == SuppressMessageAttribute || a.AttributeClass == UnconditionalSuppressMessageAttribute; private ImmutableDictionary<string, SuppressMessageInfo> DecodeLocalSuppressMessageAttributes(ISymbol symbol) { var attributes = symbol.GetAttributes().Where(a => IsSuppressionAttribute(a)); return DecodeLocalSuppressMessageAttributes(symbol, attributes); } private static ImmutableDictionary<string, SuppressMessageInfo> DecodeLocalSuppressMessageAttributes(ISymbol symbol, IEnumerable<AttributeData> attributes) { var builder = ImmutableDictionary.CreateBuilder<string, SuppressMessageInfo>(); foreach (var attribute in attributes) { SuppressMessageInfo info; if (!TryDecodeSuppressMessageAttributeData(attribute, out info)) { continue; } AddOrUpdate(info, builder); } return builder.ToImmutable(); } private static void AddOrUpdate(SuppressMessageInfo info, IDictionary<string, SuppressMessageInfo> builder) { // TODO: How should we deal with multiple SuppressMessage attributes, with different suppression info/states? // For now, we just pick the last attribute, if not suppressed. SuppressMessageInfo currentInfo; if (!builder.TryGetValue(info.Id, out currentInfo)) { builder[info.Id] = info; } } private void DecodeGlobalSuppressMessageAttributes(Compilation compilation, ISymbol symbol, GlobalSuppressions globalSuppressions) { Debug.Assert(symbol is IAssemblySymbol || symbol is IModuleSymbol); var attributes = symbol.GetAttributes().Where(a => IsSuppressionAttribute(a)); DecodeGlobalSuppressMessageAttributes(compilation, symbol, globalSuppressions, attributes); } private static void DecodeGlobalSuppressMessageAttributes(Compilation compilation, ISymbol symbol, GlobalSuppressions globalSuppressions, IEnumerable<AttributeData> attributes) { foreach (var instance in attributes) { SuppressMessageInfo info; if (!TryDecodeSuppressMessageAttributeData(instance, out info)) { continue; } if (TryGetTargetScope(info, out TargetScope scope)) { if ((scope == TargetScope.Module || scope == TargetScope.None) && info.Target == null) { // This suppression is applies to the entire compilation globalSuppressions.AddCompilationWideSuppression(info); continue; } } else { // Invalid value for scope continue; } // Decode Target if (info.Target == null) { continue; } foreach (var target in ResolveTargetSymbols(compilation, info.Target, scope)) { globalSuppressions.AddGlobalSymbolSuppression(target, info); } } } internal static ImmutableArray<ISymbol> ResolveTargetSymbols(Compilation compilation, string target, TargetScope scope) { switch (scope) { case TargetScope.Namespace: case TargetScope.Type: case TargetScope.Member: return new TargetSymbolResolver(compilation, scope, target).Resolve(out _); case TargetScope.NamespaceAndDescendants: return ResolveTargetSymbols(compilation, target, TargetScope.Namespace); default: return ImmutableArray<ISymbol>.Empty; } } private static bool TryDecodeSuppressMessageAttributeData(AttributeData attribute, out SuppressMessageInfo info) { info = default(SuppressMessageInfo); // We need at least the Category and Id to decode the diagnostic to suppress. // The only SuppressMessageAttribute constructor requires those two parameters. if (attribute.CommonConstructorArguments.Length < 2) { return false; } // Ignore the category parameter because it does not identify the diagnostic // and category information can be obtained from diagnostics themselves. info.Id = attribute.CommonConstructorArguments[1].ValueInternal as string; if (info.Id == null) { return false; } // Allow an optional human-readable descriptive name on the end of an Id. // See http://msdn.microsoft.com/en-us/library/ms244717.aspx var separatorIndex = info.Id.IndexOf(':'); if (separatorIndex != -1) { info.Id = info.Id.Remove(separatorIndex); } info.Scope = attribute.DecodeNamedArgument<string>("Scope", SpecialType.System_String); info.Target = attribute.DecodeNamedArgument<string>("Target", SpecialType.System_String); info.MessageId = attribute.DecodeNamedArgument<string>("MessageId", SpecialType.System_String); info.Attribute = attribute; return true; } } }
-1
dotnet/roslyn
55,138
Avoid cancellation exceptions in intermediate operations
Addresses the following exceptions: ![image](https://user-images.githubusercontent.com/1408396/127185947-8a005aea-ae1c-4755-bf0f-21dfb8101352.png)
sharwell
2021-07-27T15:51:28Z
2021-07-27T21:36:45Z
3d8acbd585a75e9cdb3509623bf6c39ceb46b2c2
719d4ffa2be734463e5d7d4d74b23b8006fd7727
Avoid cancellation exceptions in intermediate operations. Addresses the following exceptions: ![image](https://user-images.githubusercontent.com/1408396/127185947-8a005aea-ae1c-4755-bf0f-21dfb8101352.png)
./src/EditorFeatures/TestUtilities/RefactoringHelpers/RefactoringHelpersTestBase.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.CodeRefactorings; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.UnitTests.RefactoringHelpers { [UseExportProvider] public abstract class RefactoringHelpersTestBase<TWorkspaceFixture> : TestBase where TWorkspaceFixture : TestWorkspaceFixture, new() { private readonly TestFixtureHelper<TWorkspaceFixture> _fixtureHelper = new(); private protected ReferenceCountedDisposable<TWorkspaceFixture> GetOrCreateWorkspaceFixture() => _fixtureHelper.GetOrCreateFixture(); protected Task TestAsync<TNode>(string text) where TNode : SyntaxNode => TestAsync<TNode>(text, Functions<TNode>.True); protected async Task TestAsync<TNode>(string text, Func<TNode, bool> predicate) where TNode : SyntaxNode { text = GetSelectionAndResultSpans(text, out var selection, out var result); var resultNode = await GetNodeForSelectionAsync<TNode>(text, selection, predicate).ConfigureAwait(false); Assert.NotNull(resultNode); Assert.Equal(result, resultNode.Span); } protected async Task TestUnderselectedAsync<TNode>(string text) where TNode : SyntaxNode { text = GetSelectionSpan(text, out var selection); var resultNode = await GetNodeForSelectionAsync<TNode>(text, selection, Functions<TNode>.True).ConfigureAwait(false); Assert.NotNull(resultNode); Assert.True(CodeRefactoringHelpers.IsNodeUnderselected(resultNode, selection)); } protected async Task TestNotUnderselectedAsync<TNode>(string text) where TNode : SyntaxNode { text = GetSelectionAndResultSpans(text, out var selection, out var result); var resultNode = await GetNodeForSelectionAsync<TNode>(text, selection, Functions<TNode>.True).ConfigureAwait(false); Assert.Equal(result, resultNode.Span); Assert.False(CodeRefactoringHelpers.IsNodeUnderselected(resultNode, selection)); } protected Task TestMissingAsync<TNode>(string text) where TNode : SyntaxNode => TestMissingAsync<TNode>(text, Functions<TNode>.True); protected async Task TestMissingAsync<TNode>(string text, Func<TNode, bool> predicate) where TNode : SyntaxNode { text = GetSelectionSpan(text, out var selection); var resultNode = await GetNodeForSelectionAsync<TNode>(text, selection, predicate).ConfigureAwait(false); Assert.Null(resultNode); } private static string GetSelectionSpan(string text, out TextSpan selection) { MarkupTestFile.GetSpans(text.NormalizeLineEndings(), out text, out IDictionary<string, ImmutableArray<TextSpan>> spans); if (spans.Count != 1 || !spans.TryGetValue(string.Empty, out var selections) || selections.Length != 1) { throw new ArgumentException("Invalid missing test format: only `[|...|]` (selection) should be present."); } selection = selections.Single(); return text; } private static string GetSelectionAndResultSpans(string text, out TextSpan selection, out TextSpan result) { MarkupTestFile.GetSpans(text.NormalizeLineEndings(), out text, out IDictionary<string, ImmutableArray<TextSpan>> spans); if (spans.Count != 2 || !spans.TryGetValue(string.Empty, out var selections) || selections.Length != 1 || !spans.TryGetValue("result", out var results) || results.Length != 1) { throw new ArgumentException("Invalid test format: both `[|...|]` (selection) and `{|result:...|}` (retrieved node span) selections are required for a test."); } selection = selections.Single(); result = results.Single(); return text; } private async Task<TNode> GetNodeForSelectionAsync<TNode>(string text, TextSpan selection, Func<TNode, bool> predicate) where TNode : SyntaxNode { using var workspaceFixture = GetOrCreateWorkspaceFixture(); var document = workspaceFixture.Target.UpdateDocument(text, SourceCodeKind.Regular); var relevantNodes = await document.GetRelevantNodesAsync<TNode>(selection, CancellationToken.None).ConfigureAwait(false); return relevantNodes.FirstOrDefault(predicate); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.CodeRefactorings; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.UnitTests.RefactoringHelpers { [UseExportProvider] public abstract class RefactoringHelpersTestBase<TWorkspaceFixture> : TestBase where TWorkspaceFixture : TestWorkspaceFixture, new() { private readonly TestFixtureHelper<TWorkspaceFixture> _fixtureHelper = new(); private protected ReferenceCountedDisposable<TWorkspaceFixture> GetOrCreateWorkspaceFixture() => _fixtureHelper.GetOrCreateFixture(); protected Task TestAsync<TNode>(string text) where TNode : SyntaxNode => TestAsync<TNode>(text, Functions<TNode>.True); protected async Task TestAsync<TNode>(string text, Func<TNode, bool> predicate) where TNode : SyntaxNode { text = GetSelectionAndResultSpans(text, out var selection, out var result); var resultNode = await GetNodeForSelectionAsync<TNode>(text, selection, predicate).ConfigureAwait(false); Assert.NotNull(resultNode); Assert.Equal(result, resultNode.Span); } protected async Task TestUnderselectedAsync<TNode>(string text) where TNode : SyntaxNode { text = GetSelectionSpan(text, out var selection); var resultNode = await GetNodeForSelectionAsync<TNode>(text, selection, Functions<TNode>.True).ConfigureAwait(false); Assert.NotNull(resultNode); Assert.True(CodeRefactoringHelpers.IsNodeUnderselected(resultNode, selection)); } protected async Task TestNotUnderselectedAsync<TNode>(string text) where TNode : SyntaxNode { text = GetSelectionAndResultSpans(text, out var selection, out var result); var resultNode = await GetNodeForSelectionAsync<TNode>(text, selection, Functions<TNode>.True).ConfigureAwait(false); Assert.Equal(result, resultNode.Span); Assert.False(CodeRefactoringHelpers.IsNodeUnderselected(resultNode, selection)); } protected Task TestMissingAsync<TNode>(string text) where TNode : SyntaxNode => TestMissingAsync<TNode>(text, Functions<TNode>.True); protected async Task TestMissingAsync<TNode>(string text, Func<TNode, bool> predicate) where TNode : SyntaxNode { text = GetSelectionSpan(text, out var selection); var resultNode = await GetNodeForSelectionAsync<TNode>(text, selection, predicate).ConfigureAwait(false); Assert.Null(resultNode); } private static string GetSelectionSpan(string text, out TextSpan selection) { MarkupTestFile.GetSpans(text.NormalizeLineEndings(), out text, out IDictionary<string, ImmutableArray<TextSpan>> spans); if (spans.Count != 1 || !spans.TryGetValue(string.Empty, out var selections) || selections.Length != 1) { throw new ArgumentException("Invalid missing test format: only `[|...|]` (selection) should be present."); } selection = selections.Single(); return text; } private static string GetSelectionAndResultSpans(string text, out TextSpan selection, out TextSpan result) { MarkupTestFile.GetSpans(text.NormalizeLineEndings(), out text, out IDictionary<string, ImmutableArray<TextSpan>> spans); if (spans.Count != 2 || !spans.TryGetValue(string.Empty, out var selections) || selections.Length != 1 || !spans.TryGetValue("result", out var results) || results.Length != 1) { throw new ArgumentException("Invalid test format: both `[|...|]` (selection) and `{|result:...|}` (retrieved node span) selections are required for a test."); } selection = selections.Single(); result = results.Single(); return text; } private async Task<TNode> GetNodeForSelectionAsync<TNode>(string text, TextSpan selection, Func<TNode, bool> predicate) where TNode : SyntaxNode { using var workspaceFixture = GetOrCreateWorkspaceFixture(); var document = workspaceFixture.Target.UpdateDocument(text, SourceCodeKind.Regular); var relevantNodes = await document.GetRelevantNodesAsync<TNode>(selection, CancellationToken.None).ConfigureAwait(false); return relevantNodes.FirstOrDefault(predicate); } } }
-1
dotnet/roslyn
55,138
Avoid cancellation exceptions in intermediate operations
Addresses the following exceptions: ![image](https://user-images.githubusercontent.com/1408396/127185947-8a005aea-ae1c-4755-bf0f-21dfb8101352.png)
sharwell
2021-07-27T15:51:28Z
2021-07-27T21:36:45Z
3d8acbd585a75e9cdb3509623bf6c39ceb46b2c2
719d4ffa2be734463e5d7d4d74b23b8006fd7727
Avoid cancellation exceptions in intermediate operations. Addresses the following exceptions: ![image](https://user-images.githubusercontent.com/1408396/127185947-8a005aea-ae1c-4755-bf0f-21dfb8101352.png)
./src/VisualStudio/Xaml/Impl/Features/AutoInsert/IXamlAutoInsertService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Host; namespace Microsoft.VisualStudio.LanguageServices.Xaml.Features.AutoInsert { internal interface IXamlAutoInsertService : ILanguageService { public Task<XamlAutoInsertResult> GetAutoInsertAsync(TextDocument document, char typedChar, int position, CancellationToken cancellationToken); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Host; namespace Microsoft.VisualStudio.LanguageServices.Xaml.Features.AutoInsert { internal interface IXamlAutoInsertService : ILanguageService { public Task<XamlAutoInsertResult> GetAutoInsertAsync(TextDocument document, char typedChar, int position, CancellationToken cancellationToken); } }
-1
dotnet/roslyn
55,138
Avoid cancellation exceptions in intermediate operations
Addresses the following exceptions: ![image](https://user-images.githubusercontent.com/1408396/127185947-8a005aea-ae1c-4755-bf0f-21dfb8101352.png)
sharwell
2021-07-27T15:51:28Z
2021-07-27T21:36:45Z
3d8acbd585a75e9cdb3509623bf6c39ceb46b2c2
719d4ffa2be734463e5d7d4d74b23b8006fd7727
Avoid cancellation exceptions in intermediate operations. Addresses the following exceptions: ![image](https://user-images.githubusercontent.com/1408396/127185947-8a005aea-ae1c-4755-bf0f-21dfb8101352.png)
./src/Compilers/Core/Rebuild/VisualBasicCompilationFactory.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.IO; using System.Linq; using Microsoft.Cci; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.VisualBasic; using Roslyn.Utilities; using VB = Microsoft.CodeAnalysis.VisualBasic; namespace Microsoft.CodeAnalysis.Rebuild { public sealed class VisualBasicCompilationFactory : CompilationFactory { public new VisualBasicCompilationOptions CompilationOptions { get; } public new VisualBasicParseOptions ParseOptions => CompilationOptions.ParseOptions; protected override ParseOptions CommonParseOptions => ParseOptions; protected override CompilationOptions CommonCompilationOptions => CompilationOptions; private VisualBasicCompilationFactory( string assemblyFileName, CompilationOptionsReader optionsReader, VisualBasicCompilationOptions compilationOptions) : base(assemblyFileName, optionsReader) { CompilationOptions = compilationOptions; } internal static new VisualBasicCompilationFactory Create(string assemblyFileName, CompilationOptionsReader optionsReader) { Debug.Assert(optionsReader.GetLanguageName() == LanguageNames.VisualBasic); var compilationOptions = CreateVisualBasicCompilationOptions(assemblyFileName, optionsReader); return new VisualBasicCompilationFactory(assemblyFileName, optionsReader, compilationOptions); } public override SyntaxTree CreateSyntaxTree(string filePath, SourceText sourceText) => VisualBasicSyntaxTree.ParseText(sourceText, ParseOptions, filePath); public override Compilation CreateCompilation( ImmutableArray<SyntaxTree> syntaxTrees, ImmutableArray<MetadataReference> metadataReferences) => VisualBasicCompilation.Create( Path.GetFileNameWithoutExtension(AssemblyFileName), syntaxTrees: syntaxTrees, references: metadataReferences, options: CompilationOptions); private static VisualBasicCompilationOptions CreateVisualBasicCompilationOptions(string assemblyFileName, CompilationOptionsReader optionsReader) { var pdbOptions = optionsReader.GetMetadataCompilationOptions(); var langVersionString = pdbOptions.GetUniqueOption(CompilationOptionNames.LanguageVersion); pdbOptions.TryGetUniqueOption(CompilationOptionNames.Optimization, out var optimization); pdbOptions.TryGetUniqueOption(CompilationOptionNames.Platform, out var platform); pdbOptions.TryGetUniqueOption(CompilationOptionNames.GlobalNamespaces, out var globalNamespacesString); IEnumerable<GlobalImport>? globalImports = null; if (!string.IsNullOrEmpty(globalNamespacesString)) { globalImports = GlobalImport.Parse(globalNamespacesString.Split(';')); } VB.LanguageVersion langVersion = default; VB.LanguageVersionFacts.TryParse(langVersionString, ref langVersion); IReadOnlyDictionary<string, object>? preprocessorSymbols = null; if (pdbOptions.OptionToString(CompilationOptionNames.Define) is string defineString) { preprocessorSymbols = VisualBasicCommandLineParser.ParseConditionalCompilationSymbols(defineString, out var diagnostics); var diagnostic = diagnostics?.FirstOrDefault(x => x.IsUnsuppressedError); if (diagnostic is object) { throw new Exception(string.Format(RebuildResources.Cannot_create_compilation_options_0, diagnostic)); } } var parseOptions = VisualBasicParseOptions .Default .WithLanguageVersion(langVersion) .WithPreprocessorSymbols(preprocessorSymbols.ToImmutableArrayOrEmpty()); var (optimizationLevel, plus) = GetOptimizationLevel(optimization); var isChecked = pdbOptions.OptionToBool(CompilationOptionNames.Checked) ?? true; var embedVBRuntime = pdbOptions.OptionToBool(CompilationOptionNames.EmbedRuntime) ?? false; var rootNamespace = pdbOptions.OptionToString(CompilationOptionNames.RootNamespace); var compilationOptions = new VisualBasicCompilationOptions( pdbOptions.OptionToEnum<OutputKind>(CompilationOptionNames.OutputKind) ?? OutputKind.DynamicallyLinkedLibrary, moduleName: assemblyFileName, mainTypeName: optionsReader.GetMainTypeName(), scriptClassName: "Script", globalImports: globalImports, rootNamespace: rootNamespace, optionStrict: pdbOptions.OptionToEnum<OptionStrict>(CompilationOptionNames.OptionStrict) ?? OptionStrict.Off, optionInfer: pdbOptions.OptionToBool(CompilationOptionNames.OptionInfer) ?? false, optionExplicit: pdbOptions.OptionToBool(CompilationOptionNames.OptionExplicit) ?? false, optionCompareText: pdbOptions.OptionToBool(CompilationOptionNames.OptionCompareText) ?? false, parseOptions: parseOptions, embedVbCoreRuntime: embedVBRuntime, optimizationLevel: optimizationLevel, checkOverflow: isChecked, cryptoKeyContainer: null, cryptoKeyFile: null, cryptoPublicKey: optionsReader.GetPublicKey()?.ToImmutableArray() ?? default, delaySign: null, platform: GetPlatform(platform), generalDiagnosticOption: ReportDiagnostic.Default, specificDiagnosticOptions: null, concurrentBuild: true, deterministic: true, xmlReferenceResolver: null, sourceReferenceResolver: RebuildSourceReferenceResolver.Instance, metadataReferenceResolver: null, assemblyIdentityComparer: null, strongNameProvider: null, publicSign: false, reportSuppressedDiagnostics: false, metadataImportOptions: MetadataImportOptions.Public); compilationOptions.DebugPlusMode = plus; return compilationOptions; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.IO; using System.Linq; using Microsoft.Cci; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.VisualBasic; using Roslyn.Utilities; using VB = Microsoft.CodeAnalysis.VisualBasic; namespace Microsoft.CodeAnalysis.Rebuild { public sealed class VisualBasicCompilationFactory : CompilationFactory { public new VisualBasicCompilationOptions CompilationOptions { get; } public new VisualBasicParseOptions ParseOptions => CompilationOptions.ParseOptions; protected override ParseOptions CommonParseOptions => ParseOptions; protected override CompilationOptions CommonCompilationOptions => CompilationOptions; private VisualBasicCompilationFactory( string assemblyFileName, CompilationOptionsReader optionsReader, VisualBasicCompilationOptions compilationOptions) : base(assemblyFileName, optionsReader) { CompilationOptions = compilationOptions; } internal static new VisualBasicCompilationFactory Create(string assemblyFileName, CompilationOptionsReader optionsReader) { Debug.Assert(optionsReader.GetLanguageName() == LanguageNames.VisualBasic); var compilationOptions = CreateVisualBasicCompilationOptions(assemblyFileName, optionsReader); return new VisualBasicCompilationFactory(assemblyFileName, optionsReader, compilationOptions); } public override SyntaxTree CreateSyntaxTree(string filePath, SourceText sourceText) => VisualBasicSyntaxTree.ParseText(sourceText, ParseOptions, filePath); public override Compilation CreateCompilation( ImmutableArray<SyntaxTree> syntaxTrees, ImmutableArray<MetadataReference> metadataReferences) => VisualBasicCompilation.Create( Path.GetFileNameWithoutExtension(AssemblyFileName), syntaxTrees: syntaxTrees, references: metadataReferences, options: CompilationOptions); private static VisualBasicCompilationOptions CreateVisualBasicCompilationOptions(string assemblyFileName, CompilationOptionsReader optionsReader) { var pdbOptions = optionsReader.GetMetadataCompilationOptions(); var langVersionString = pdbOptions.GetUniqueOption(CompilationOptionNames.LanguageVersion); pdbOptions.TryGetUniqueOption(CompilationOptionNames.Optimization, out var optimization); pdbOptions.TryGetUniqueOption(CompilationOptionNames.Platform, out var platform); pdbOptions.TryGetUniqueOption(CompilationOptionNames.GlobalNamespaces, out var globalNamespacesString); IEnumerable<GlobalImport>? globalImports = null; if (!string.IsNullOrEmpty(globalNamespacesString)) { globalImports = GlobalImport.Parse(globalNamespacesString.Split(';')); } VB.LanguageVersion langVersion = default; VB.LanguageVersionFacts.TryParse(langVersionString, ref langVersion); IReadOnlyDictionary<string, object>? preprocessorSymbols = null; if (pdbOptions.OptionToString(CompilationOptionNames.Define) is string defineString) { preprocessorSymbols = VisualBasicCommandLineParser.ParseConditionalCompilationSymbols(defineString, out var diagnostics); var diagnostic = diagnostics?.FirstOrDefault(x => x.IsUnsuppressedError); if (diagnostic is object) { throw new Exception(string.Format(RebuildResources.Cannot_create_compilation_options_0, diagnostic)); } } var parseOptions = VisualBasicParseOptions .Default .WithLanguageVersion(langVersion) .WithPreprocessorSymbols(preprocessorSymbols.ToImmutableArrayOrEmpty()); var (optimizationLevel, plus) = GetOptimizationLevel(optimization); var isChecked = pdbOptions.OptionToBool(CompilationOptionNames.Checked) ?? true; var embedVBRuntime = pdbOptions.OptionToBool(CompilationOptionNames.EmbedRuntime) ?? false; var rootNamespace = pdbOptions.OptionToString(CompilationOptionNames.RootNamespace); var compilationOptions = new VisualBasicCompilationOptions( pdbOptions.OptionToEnum<OutputKind>(CompilationOptionNames.OutputKind) ?? OutputKind.DynamicallyLinkedLibrary, moduleName: assemblyFileName, mainTypeName: optionsReader.GetMainTypeName(), scriptClassName: "Script", globalImports: globalImports, rootNamespace: rootNamespace, optionStrict: pdbOptions.OptionToEnum<OptionStrict>(CompilationOptionNames.OptionStrict) ?? OptionStrict.Off, optionInfer: pdbOptions.OptionToBool(CompilationOptionNames.OptionInfer) ?? false, optionExplicit: pdbOptions.OptionToBool(CompilationOptionNames.OptionExplicit) ?? false, optionCompareText: pdbOptions.OptionToBool(CompilationOptionNames.OptionCompareText) ?? false, parseOptions: parseOptions, embedVbCoreRuntime: embedVBRuntime, optimizationLevel: optimizationLevel, checkOverflow: isChecked, cryptoKeyContainer: null, cryptoKeyFile: null, cryptoPublicKey: optionsReader.GetPublicKey()?.ToImmutableArray() ?? default, delaySign: null, platform: GetPlatform(platform), generalDiagnosticOption: ReportDiagnostic.Default, specificDiagnosticOptions: null, concurrentBuild: true, deterministic: true, xmlReferenceResolver: null, sourceReferenceResolver: RebuildSourceReferenceResolver.Instance, metadataReferenceResolver: null, assemblyIdentityComparer: null, strongNameProvider: null, publicSign: false, reportSuppressedDiagnostics: false, metadataImportOptions: MetadataImportOptions.Public); compilationOptions.DebugPlusMode = plus; return compilationOptions; } } }
-1
dotnet/roslyn
55,138
Avoid cancellation exceptions in intermediate operations
Addresses the following exceptions: ![image](https://user-images.githubusercontent.com/1408396/127185947-8a005aea-ae1c-4755-bf0f-21dfb8101352.png)
sharwell
2021-07-27T15:51:28Z
2021-07-27T21:36:45Z
3d8acbd585a75e9cdb3509623bf6c39ceb46b2c2
719d4ffa2be734463e5d7d4d74b23b8006fd7727
Avoid cancellation exceptions in intermediate operations. Addresses the following exceptions: ![image](https://user-images.githubusercontent.com/1408396/127185947-8a005aea-ae1c-4755-bf0f-21dfb8101352.png)
./src/Workspaces/Core/Portable/LinkedFileDiffMerging/AbstractLinkedFileMergeConflictCommentAdditionService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis { internal abstract class AbstractLinkedFileMergeConflictCommentAdditionService : IMergeConflictHandler, ILanguageService, ILinkedFileMergeConflictCommentAdditionService { internal abstract string GetConflictCommentText(string header, string beforeString, string afterString); public IEnumerable<TextChange> CreateEdits(SourceText originalSourceText, IEnumerable<UnmergedDocumentChanges> unmergedChanges) { var commentChanges = new List<TextChange>(); foreach (var documentWithChanges in unmergedChanges) { var partitionedChanges = PartitionChangesForDocument(documentWithChanges.UnmergedChanges, originalSourceText); var comments = GetCommentChangesForDocument(partitionedChanges, documentWithChanges.ProjectName, originalSourceText); commentChanges.AddRange(comments); } return commentChanges; } private static IEnumerable<IEnumerable<TextChange>> PartitionChangesForDocument(IEnumerable<TextChange> changes, SourceText originalSourceText) { var partitionedChanges = new List<IEnumerable<TextChange>>(); var currentPartition = new List<TextChange>(); currentPartition.Add(changes.First()); var currentPartitionEndLine = originalSourceText.Lines.GetLineFromPosition(changes.First().Span.End); foreach (var change in changes.Skip(1)) { // If changes are on adjacent lines, consider them part of the same change. var changeStartLine = originalSourceText.Lines.GetLineFromPosition(change.Span.Start); if (changeStartLine.LineNumber >= currentPartitionEndLine.LineNumber + 2) { partitionedChanges.Add(currentPartition); currentPartition = new List<TextChange>(); } currentPartition.Add(change); currentPartitionEndLine = originalSourceText.Lines.GetLineFromPosition(change.Span.End); } if (currentPartition.Any()) { partitionedChanges.Add(currentPartition); } return partitionedChanges; } private List<TextChange> GetCommentChangesForDocument(IEnumerable<IEnumerable<TextChange>> partitionedChanges, string projectName, SourceText oldDocumentText) { var commentChanges = new List<TextChange>(); foreach (var changePartition in partitionedChanges) { var startPosition = changePartition.First().Span.Start; var endPosition = changePartition.Last().Span.End; var startLineStartPosition = oldDocumentText.Lines.GetLineFromPosition(startPosition).Start; var endLineEndPosition = oldDocumentText.Lines.GetLineFromPosition(endPosition).End; var oldText = oldDocumentText.GetSubText(TextSpan.FromBounds(startLineStartPosition, endLineEndPosition)); var adjustedChanges = changePartition.Select(c => new TextChange(TextSpan.FromBounds(c.Span.Start - startLineStartPosition, c.Span.End - startLineStartPosition), c.NewText)); var newText = oldText.WithChanges(adjustedChanges); var warningText = GetConflictCommentText( string.Format(WorkspacesResources.Unmerged_change_from_project_0, projectName), TrimBlankLines(oldText), TrimBlankLines(newText)); if (warningText != null) { commentChanges.Add(new TextChange(TextSpan.FromBounds(startLineStartPosition, startLineStartPosition), warningText)); } } return commentChanges; } private static string TrimBlankLines(SourceText text) { int startLine, endLine; for (startLine = 0; startLine < text.Lines.Count; startLine++) { if (!text.Lines[startLine].IsEmptyOrWhitespace()) { break; } } for (endLine = text.Lines.Count - 1; endLine > startLine; endLine--) { if (!text.Lines[endLine].IsEmptyOrWhitespace()) { break; } } return startLine <= endLine ? text.GetSubText(TextSpan.FromBounds(text.Lines[startLine].Start, text.Lines[endLine].End)).ToString() : null; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis { internal abstract class AbstractLinkedFileMergeConflictCommentAdditionService : IMergeConflictHandler, ILanguageService, ILinkedFileMergeConflictCommentAdditionService { internal abstract string GetConflictCommentText(string header, string beforeString, string afterString); public IEnumerable<TextChange> CreateEdits(SourceText originalSourceText, IEnumerable<UnmergedDocumentChanges> unmergedChanges) { var commentChanges = new List<TextChange>(); foreach (var documentWithChanges in unmergedChanges) { var partitionedChanges = PartitionChangesForDocument(documentWithChanges.UnmergedChanges, originalSourceText); var comments = GetCommentChangesForDocument(partitionedChanges, documentWithChanges.ProjectName, originalSourceText); commentChanges.AddRange(comments); } return commentChanges; } private static IEnumerable<IEnumerable<TextChange>> PartitionChangesForDocument(IEnumerable<TextChange> changes, SourceText originalSourceText) { var partitionedChanges = new List<IEnumerable<TextChange>>(); var currentPartition = new List<TextChange>(); currentPartition.Add(changes.First()); var currentPartitionEndLine = originalSourceText.Lines.GetLineFromPosition(changes.First().Span.End); foreach (var change in changes.Skip(1)) { // If changes are on adjacent lines, consider them part of the same change. var changeStartLine = originalSourceText.Lines.GetLineFromPosition(change.Span.Start); if (changeStartLine.LineNumber >= currentPartitionEndLine.LineNumber + 2) { partitionedChanges.Add(currentPartition); currentPartition = new List<TextChange>(); } currentPartition.Add(change); currentPartitionEndLine = originalSourceText.Lines.GetLineFromPosition(change.Span.End); } if (currentPartition.Any()) { partitionedChanges.Add(currentPartition); } return partitionedChanges; } private List<TextChange> GetCommentChangesForDocument(IEnumerable<IEnumerable<TextChange>> partitionedChanges, string projectName, SourceText oldDocumentText) { var commentChanges = new List<TextChange>(); foreach (var changePartition in partitionedChanges) { var startPosition = changePartition.First().Span.Start; var endPosition = changePartition.Last().Span.End; var startLineStartPosition = oldDocumentText.Lines.GetLineFromPosition(startPosition).Start; var endLineEndPosition = oldDocumentText.Lines.GetLineFromPosition(endPosition).End; var oldText = oldDocumentText.GetSubText(TextSpan.FromBounds(startLineStartPosition, endLineEndPosition)); var adjustedChanges = changePartition.Select(c => new TextChange(TextSpan.FromBounds(c.Span.Start - startLineStartPosition, c.Span.End - startLineStartPosition), c.NewText)); var newText = oldText.WithChanges(adjustedChanges); var warningText = GetConflictCommentText( string.Format(WorkspacesResources.Unmerged_change_from_project_0, projectName), TrimBlankLines(oldText), TrimBlankLines(newText)); if (warningText != null) { commentChanges.Add(new TextChange(TextSpan.FromBounds(startLineStartPosition, startLineStartPosition), warningText)); } } return commentChanges; } private static string TrimBlankLines(SourceText text) { int startLine, endLine; for (startLine = 0; startLine < text.Lines.Count; startLine++) { if (!text.Lines[startLine].IsEmptyOrWhitespace()) { break; } } for (endLine = text.Lines.Count - 1; endLine > startLine; endLine--) { if (!text.Lines[endLine].IsEmptyOrWhitespace()) { break; } } return startLine <= endLine ? text.GetSubText(TextSpan.FromBounds(text.Lines[startLine].Start, text.Lines[endLine].End)).ToString() : null; } } }
-1
dotnet/roslyn
55,138
Avoid cancellation exceptions in intermediate operations
Addresses the following exceptions: ![image](https://user-images.githubusercontent.com/1408396/127185947-8a005aea-ae1c-4755-bf0f-21dfb8101352.png)
sharwell
2021-07-27T15:51:28Z
2021-07-27T21:36:45Z
3d8acbd585a75e9cdb3509623bf6c39ceb46b2c2
719d4ffa2be734463e5d7d4d74b23b8006fd7727
Avoid cancellation exceptions in intermediate operations. Addresses the following exceptions: ![image](https://user-images.githubusercontent.com/1408396/127185947-8a005aea-ae1c-4755-bf0f-21dfb8101352.png)
./src/Compilers/Test/Core/Traits/Traits.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable namespace Microsoft.CodeAnalysis.Test.Utilities { public static class Traits { public const string Editor = nameof(Editor); public static class Editors { public const string KeyProcessors = nameof(KeyProcessors); public const string KeyProcessorProviders = nameof(KeyProcessorProviders); public const string Preview = nameof(Preview); public const string LanguageServerProtocol = nameof(LanguageServerProtocol); } public const string Feature = nameof(Feature); public static class Features { public const string AddAwait = "Refactoring.AddAwait"; public const string AddMissingImports = "Refactoring.AddMissingImports"; public const string AddMissingReference = nameof(AddMissingReference); public const string AddMissingTokens = nameof(AddMissingTokens); public const string Adornments = nameof(Adornments); public const string AsyncLazy = nameof(AsyncLazy); public const string AutomaticCompletion = nameof(AutomaticCompletion); public const string AutomaticEndConstructCorrection = nameof(AutomaticEndConstructCorrection); public const string BlockCommentEditing = nameof(BlockCommentEditing); public const string BraceHighlighting = nameof(BraceHighlighting); public const string BraceMatching = nameof(BraceMatching); public const string Build = nameof(Build); public const string CallHierarchy = nameof(CallHierarchy); public const string CaseCorrection = nameof(CaseCorrection); public const string ChangeSignature = nameof(ChangeSignature); public const string ClassView = nameof(ClassView); public const string Classification = nameof(Classification); public const string CodeActionsAddAccessibilityModifiers = "CodeActions.AddAccessibilityModifiers"; public const string CodeActionsAddAnonymousTypeMemberName = "CodeActions.AddAnonymousTypeMemberName"; public const string CodeActionsAddAwait = "CodeActions.AddAwait"; public const string CodeActionsAddBraces = "CodeActions.AddBraces"; public const string CodeActionsAddConstructorParametersFromMembers = "CodeActions.AddConstructorParametersFromMembers"; public const string CodeActionsAddDebuggerDisplay = "CodeActions.AddDebuggerDisplay"; public const string CodeActionsAddDocCommentNodes = "CodeActions.AddDocCommentParamNodes"; public const string CodeActionsAddExplicitCast = "CodeActions.AddExplicitCast"; public const string CodeActionsAddFileBanner = "CodeActions.AddFileBanner"; public const string CodeActionsAddImport = "CodeActions.AddImport"; public const string CodeActionsAddMissingReference = "CodeActions.AddMissingReference"; public const string CodeActionsAddNew = "CodeActions.AddNew"; public const string CodeActionsRemoveNewModifier = "CodeActions.RemoveNewModifier"; public const string CodeActionsAddObsoleteAttribute = "CodeActions.AddObsoleteAttribute"; public const string CodeActionsAddOverload = "CodeActions.AddOverloads"; public const string CodeActionsAddParameter = "CodeActions.AddParameter"; public const string CodeActionsAddParenthesesAroundConditionalExpressionInInterpolatedString = "CodeActions.AddParenthesesAroundConditionalExpressionInInterpolatedString"; public const string CodeActionsAddRequiredParentheses = "CodeActions.AddRequiredParentheses"; public const string CodeActionsAddShadows = "CodeActions.AddShadows"; public const string CodeActionsMakeMemberStatic = "CodeActions.MakeMemberStatic"; public const string CodeActionsAliasAmbiguousType = "CodeActions.AliasAmbiguousType"; public const string CodeActionsAssignOutParameters = "CodeActions.AssignOutParameters"; public const string CodeActionsChangeToAsync = "CodeActions.ChangeToAsync"; public const string CodeActionsChangeToIEnumerable = "CodeActions.ChangeToIEnumerable"; public const string CodeActionsChangeToYield = "CodeActions.ChangeToYield"; public const string CodeActionsConfiguration = "CodeActions.Configuration"; public const string CodeActionsConvertAnonymousTypeToClass = "CodeActions.ConvertAnonymousTypeToClass"; public const string CodeActionsConvertAnonymousTypeToTuple = "CodeActions.ConvertAnonymousTypeToTuple"; public const string CodeActionsConvertBetweenRegularAndVerbatimString = "CodeActions.ConvertBetweenRegularAndVerbatimString"; public const string CodeActionsConvertForEachToFor = "CodeActions.ConvertForEachToFor"; public const string CodeActionsConvertForEachToQuery = "CodeActions.ConvertForEachToQuery"; public const string CodeActionsConvertForToForEach = "CodeActions.ConvertForToForEach"; public const string CodeActionsConvertIfToSwitch = "CodeActions.ConvertIfToSwitch"; public const string CodeActionsConvertLocalFunctionToMethod = "CodeActions.ConvertLocalFunctionToMethod"; public const string CodeActionsConvertNumericLiteral = "CodeActions.ConvertNumericLiteral"; public const string CodeActionsConvertQueryToForEach = "CodeActions.ConvertQueryToForEach"; public const string CodeActionsConvertSwitchStatementToExpression = "CodeActions.ConvertSwitchStatementToExpression"; public const string CodeActionsConvertToInterpolatedString = "CodeActions.ConvertToInterpolatedString"; public const string CodeActionsConvertToIterator = "CodeActions.ConvertToIterator"; public const string CodeActionsConvertTupleToStruct = "CodeActions.ConvertTupleToStruct"; public const string CodeActionsCorrectExitContinue = "CodeActions.CorrectExitContinue"; public const string CodeActionsCorrectFunctionReturnType = "CodeActions.CorrectFunctionReturnType"; public const string CodeActionsCorrectNextControlVariable = "CodeActions.CorrectNextControlVariable"; public const string CodeActionsDeclareAsNullable = "CodeActions.DeclareAsNullable"; public const string CodeActionsExtractInterface = "CodeActions.ExtractInterface"; public const string CodeActionsExtractLocalFunction = "CodeActions.ExtractLocalFunction"; public const string CodeActionsExtractMethod = "CodeActions.ExtractMethod"; public const string CodeActionsFixAllOccurrences = "CodeActions.FixAllOccurrences"; public const string CodeActionsFixReturnType = "CodeActions.FixReturnType"; public const string CodeActionsFullyQualify = "CodeActions.FullyQualify"; public const string CodeActionsGenerateComparisonOperators = "CodeActions.GenerateComparisonOperators"; public const string CodeActionsGenerateConstructor = "CodeActions.GenerateConstructor"; public const string CodeActionsGenerateConstructorFromMembers = "CodeActions.GenerateConstructorFromMembers"; public const string CodeActionsGenerateDefaultConstructors = "CodeActions.GenerateDefaultConstructors"; public const string CodeActionsGenerateEndConstruct = "CodeActions.GenerateEndConstruct"; public const string CodeActionsGenerateEnumMember = "CodeActions.GenerateEnumMember"; public const string CodeActionsGenerateEqualsAndGetHashCode = "CodeActions.GenerateEqualsAndGetHashCodeFromMembers"; public const string CodeActionsGenerateEvent = "CodeActions.GenerateEvent"; public const string CodeActionsGenerateLocal = "CodeActions.GenerateLocal"; public const string CodeActionsGenerateMethod = "CodeActions.GenerateMethod"; public const string CodeActionsGenerateOverrides = "CodeActions.GenerateOverrides"; public const string CodeActionsGenerateType = "CodeActions.GenerateType"; public const string CodeActionsGenerateVariable = "CodeActions.GenerateVariable"; public const string CodeActionsImplementAbstractClass = "CodeActions.ImplementAbstractClass"; public const string CodeActionsImplementInterface = "CodeActions.ImplementInterface"; public const string CodeActionsInitializeParameter = "CodeActions.InitializeParameter"; public const string CodeActionsInlineMethod = "CodeActions.InlineMethod"; public const string CodeActionsInlineDeclaration = "CodeActions.InlineDeclaration"; public const string CodeActionsInlineTemporary = "CodeActions.InlineTemporary"; public const string CodeActionsInlineTypeCheck = "CodeActions.InlineTypeCheck"; public const string CodeActionsInsertBraces = "CodeActions.InsertBraces"; public const string CodeActionsInsertMissingTokens = "CodeActions.InsertMissingTokens"; public const string CodeActionsIntroduceLocalForExpression = "CodeActions.IntroduceLocalForExpression"; public const string CodeActionsIntroduceParameter = "CodeActions.IntroduceParameter"; public const string CodeActionsIntroduceUsingStatement = "CodeActions.IntroduceUsingStatement"; public const string CodeActionsIntroduceVariable = "CodeActions.IntroduceVariable"; public const string CodeActionsInvertConditional = "CodeActions.InvertConditional"; public const string CodeActionsInvertIf = "CodeActions.InvertIf"; public const string CodeActionsInvertLogical = "CodeActions.InvertLogical"; public const string CodeActionsInvokeDelegateWithConditionalAccess = "CodeActions.InvokeDelegateWithConditionalAccess"; public const string CodeActionsLambdaSimplifier = "CodeActions.LambdaSimplifier"; public const string CodeActionsMakeFieldReadonly = "CodeActions.MakeFieldReadonly"; public const string CodeActionsMakeLocalFunctionStatic = "CodeActions.MakeLocalFunctionStatic"; public const string CodeActionsMakeMethodAsynchronous = "CodeActions.MakeMethodAsynchronous"; public const string CodeActionsMakeMethodSynchronous = "CodeActions.MakeMethodSynchronous"; public const string CodeActionsMakeRefStruct = "CodeActions.MakeRefStruct"; public const string CodeActionsMakeStatementAsynchronous = "CodeActions.MakeStatementAsynchronous"; public const string CodeActionsMakeStructFieldsWritable = "CodeActions.MakeStructFieldsWritable"; public const string CodeActionsMakeTypeAbstract = "CodeActions.MakeTypeAbstract"; public const string CodeActionsMergeConsecutiveIfStatements = "CodeActions.MergeConsecutiveIfStatements"; public const string CodeActionsMergeNestedIfStatements = "CodeActions.MergeNestedIfStatements"; public const string CodeActionsMoveDeclarationNearReference = "CodeActions.MoveDeclarationNearReference"; public const string CodeActionsMoveToNamespace = nameof(CodeActionsMoveToNamespace); public const string CodeActionsMoveToTopOfFile = "CodeActions.MoveToTopOfFile"; public const string CodeActionsMoveType = "CodeActions.MoveType"; public const string CodeActionsNameTupleElement = "CodeActions.NameTupleElement"; public const string CodeActionsOrderModifiers = "CodeActions.OrderModifiers"; public const string CodeActionsPopulateSwitch = "CodeActions.PopulateSwitch"; public const string CodeActionsPullMemberUp = "CodeActions.PullMemberUp"; public const string CodeActionsQualifyMemberAccess = "CodeActions.QualifyMemberAccess"; public const string CodeActionsRemoveAsyncModifier = "CodeActions.RemoveAsyncModifier"; public const string CodeActionsRemoveByVal = "CodeActions.RemoveByVal"; public const string CodeActionsRemoveDocCommentNode = "CodeActions.RemoveDocCommentNode"; public const string CodeActionsRemoveInKeyword = "CodeActions.RemoveInKeyword"; public const string CodeActionsRemoveUnnecessarySuppressions = "CodeActions.RemoveUnnecessarySuppressions"; public const string CodeActionsRemoveUnnecessaryCast = "CodeActions.RemoveUnnecessaryCast"; public const string CodeActionsRemoveUnnecessaryDiscardDesignation = "CodeActions.RemoveUnnecessaryDiscardDesignation"; public const string CodeActionsRemoveUnnecessaryImports = "CodeActions.RemoveUnnecessaryImports"; public const string CodeActionsRemoveUnnecessaryParentheses = "CodeActions.RemoveUnnecessaryParentheses"; public const string CodeActionsRemoveUnreachableCode = "CodeActions.RemoveUnreachableCode"; public const string CodeActionsRemoveUnusedLocalFunction = "CodeActions.RemoveUnusedLocalFunction"; public const string CodeActionsRemoveUnusedMembers = "CodeActions.RemoveUnusedMembers"; public const string CodeActionsRemoveUnusedParameters = "CodeActions.RemoveUnusedParameters"; public const string CodeActionsRemoveUnusedValues = "CodeActions.RemoveUnusedValues"; public const string CodeActionsRemoveUnusedVariable = "CodeActions.RemoveUnusedVariable"; public const string CodeActionsReplaceDefaultLiteral = "CodeActions.ReplaceDefaultLiteral"; public const string CodeActionsReplaceDocCommentTextWithTag = "CodeActions.ReplaceDocCommentTextWithTag"; public const string CodeActionsReplaceMethodWithProperty = "CodeActions.ReplaceMethodWithProperty"; public const string CodeActionsReplacePropertyWithMethods = "CodeActions.ReplacePropertyWithMethods"; public const string CodeActionsResolveConflictMarker = "CodeActions.ResolveConflictMarker"; public const string CodeActionsReverseForStatement = "CodeActions.ReverseForStatement"; public const string CodeActionsSimplifyConditional = "CodeActions.SimplifyConditional"; public const string CodeActionsSimplifyInterpolation = "CodeActions.SimplifyInterpolation"; public const string CodeActionsSimplifyLinqExpression = "CodeActions.SimplifyLinqExpression"; public const string CodeActionsSimplifyThisOrMe = "CodeActions.SimplifyThisOrMe"; public const string CodeActionsSimplifyTypeNames = "CodeActions.SimplifyTypeNames"; public const string CodeActionsSpellcheck = "CodeActions.Spellcheck"; public const string CodeActionsSplitIntoConsecutiveIfStatements = "CodeActions.SplitIntoConsecutiveIfStatements"; public const string CodeActionsSplitIntoNestedIfStatements = "CodeActions.SplitIntoNestedIfStatements"; public const string CodeActionsSuppression = "CodeActions.Suppression"; public const string CodeActionsSyncNamespace = "CodeActions.SyncNamespace"; public const string CodeActionsUnsealClass = "CodeActions.UnsealClass"; public const string CodeActionsUpdateLegacySuppressions = "CodeActions.UpdateLegacySuppressions"; public const string CodeActionsUpdateProjectToAllowUnsafe = "CodeActions.UpdateProjectToAllowUnsafe"; public const string CodeActionsUpgradeProject = "CodeActions.UpgradeProject"; public const string CodeActionsUseAutoProperty = "CodeActions.UseAutoProperty"; public const string CodeActionsUseCoalesceExpression = "CodeActions.UseCoalesceExpression"; public const string CodeActionsUseCollectionInitializer = "CodeActions.UseCollectionInitializer"; public const string CodeActionsUseCompoundAssignment = "CodeActions.UseCompoundAssignment"; public const string CodeActionsUseConditionalExpression = "CodeActions.UseConditionalExpression"; public const string CodeActionsUseDeconstruction = "CodeActions.UseDeconstruction"; public const string CodeActionsUseDefaultLiteral = "CodeActions.UseDefaultLiteral"; public const string CodeActionsUseExplicitTupleName = "CodeActions.UseExplicitTupleName"; public const string CodeActionsUseExplicitType = "CodeActions.UseExplicitType"; public const string CodeActionsUseExplicitTypeForConst = "CodeActions.UseExplicitTypeForConst"; public const string CodeActionsUseExpressionBody = "CodeActions.UseExpressionBody"; public const string CodeActionsUseFrameworkType = "CodeActions.UseFrameworkType"; public const string CodeActionsUseImplicitObjectCreation = "CodeActions.UseImplicitObjectCreation"; public const string CodeActionsUseImplicitType = "CodeActions.UseImplicitType"; public const string CodeActionsUseIndexOperator = "CodeActions.UseIndexOperator"; public const string CodeActionsUseInferredMemberName = "CodeActions.UseInferredMemberName"; public const string CodeActionsUseInterpolatedVerbatimString = "CodeActions.UseInterpolatedVerbatimString"; public const string CodeActionsUseIsNotExpression = "CodeActions.UseIsNotExpression"; public const string CodeActionsUseIsNullCheck = "CodeActions.UseIsNullCheck"; public const string CodeActionsUseLocalFunction = "CodeActions.UseLocalFunction"; public const string CodeActionsUseNamedArguments = "CodeActions.UseNamedArguments"; public const string CodeActionsUseNotPattern = "CodeActions.UseNotPattern"; public const string CodeActionsUsePatternCombinators = "CodeActions.UsePatternCombinators"; public const string CodeActionsUseNullPropagation = "CodeActions.UseNullPropagation"; public const string CodeActionsUseObjectInitializer = "CodeActions.UseObjectInitializer"; public const string CodeActionsUseRangeOperator = "CodeActions.UseRangeOperator"; public const string CodeActionsUseSimpleUsingStatement = "CodeActions.UseSimpleUsingStatement"; public const string CodeActionsUseSystemHashCode = "CodeActions.UseSystemHashCode"; public const string CodeActionsUseThrowExpression = "CodeActions.UseThrowExpression"; public const string CodeActionsWrapping = "CodeActions.Wrapping"; public const string CodeCleanup = nameof(CodeCleanup); public const string CodeGeneration = nameof(CodeGeneration); public const string CodeGenerationSortDeclarations = "CodeGeneration.SortDeclarations"; public const string CodeLens = nameof(CodeLens); public const string CodeModel = nameof(CodeModel); public const string CodeModelEvents = "CodeModel.Events"; public const string CodeModelMethodXml = "CodeModel.MethodXml"; public const string CommentSelection = nameof(CommentSelection); public const string CompleteStatement = nameof(CompleteStatement); public const string Completion = nameof(Completion); public const string ConvertAutoPropertyToFullProperty = nameof(ConvertAutoPropertyToFullProperty); public const string ConvertCast = nameof(ConvertCast); public const string ConvertTypeOfToNameOf = nameof(ConvertTypeOfToNameOf); public const string DebuggingBreakpoints = "Debugging.Breakpoints"; public const string DebuggingDataTips = "Debugging.DataTips"; public const string DebuggingEditAndContinue = "Debugging.EditAndContinue"; public const string DebuggingIntelliSense = "Debugging.IntelliSense"; public const string DebuggingLocationName = "Debugging.LocationName"; public const string DebuggingNameResolver = "Debugging.NameResolver"; public const string DebuggingProximityExpressions = "Debugging.ProximityExpressions"; public const string DecompiledSource = nameof(DecompiledSource); public const string Diagnostics = nameof(Diagnostics); public const string DisposeAnalysis = nameof(DisposeAnalysis); public const string DocCommentFormatting = nameof(DocCommentFormatting); public const string DocumentationComments = nameof(DocumentationComments); public const string EditorConfig = nameof(EditorConfig); public const string EditorConfigUI = nameof(EditorConfigUI); public const string EncapsulateField = nameof(EncapsulateField); public const string EndConstructGeneration = nameof(EndConstructGeneration); public const string ErrorList = nameof(ErrorList); public const string ErrorSquiggles = nameof(ErrorSquiggles); public const string EventHookup = nameof(EventHookup); public const string Expansion = nameof(Expansion); public const string ExtractInterface = "Refactoring.ExtractInterface"; public const string ExtractMethod = "Refactoring.ExtractMethod"; public const string F1Help = nameof(F1Help); public const string FindReferences = nameof(FindReferences); public const string FixIncorrectTokens = nameof(FixIncorrectTokens); public const string FixInterpolatedVerbatimString = nameof(FixInterpolatedVerbatimString); public const string Formatting = nameof(Formatting); public const string GoToAdjacentMember = nameof(GoToAdjacentMember); public const string GoToBase = nameof(GoToBase); public const string GoToDefinition = nameof(GoToDefinition); public const string GoToImplementation = nameof(GoToImplementation); public const string InheritanceMargin = nameof(InheritanceMargin); public const string InlineHints = nameof(InlineHints); public const string Interactive = nameof(Interactive); public const string InteractiveHost = nameof(InteractiveHost); public const string KeywordHighlighting = nameof(KeywordHighlighting); public const string KeywordRecommending = nameof(KeywordRecommending); public const string LineCommit = nameof(LineCommit); public const string LineSeparators = nameof(LineSeparators); public const string LinkedFileDiffMerging = nameof(LinkedFileDiffMerging); public const string MSBuildWorkspace = nameof(MSBuildWorkspace); public const string MetadataAsSource = nameof(MetadataAsSource); public const string MoveToNamespace = nameof(MoveToNamespace); public const string NamingStyle = nameof(NamingStyle); public const string NavigableSymbols = nameof(NavigableSymbols); public const string NavigateTo = nameof(NavigateTo); public const string NavigationBar = nameof(NavigationBar); public const string NetCore = nameof(NetCore); public const string NormalizeModifiersOrOperators = nameof(NormalizeModifiersOrOperators); public const string ObjectBrowser = nameof(ObjectBrowser); public const string Options = nameof(Options); public const string Organizing = nameof(Organizing); public const string Outlining = nameof(Outlining); public const string Packaging = nameof(Packaging); public const string PasteTracking = nameof(PasteTracking); public const string Peek = nameof(Peek); public const string Progression = nameof(Progression); public const string ProjectSystemShims = nameof(ProjectSystemShims); public const string SarifErrorLogging = nameof(SarifErrorLogging); public const string QuickInfo = nameof(QuickInfo); public const string RQName = nameof(RQName); public const string ReduceTokens = nameof(ReduceTokens); public const string ReferenceHighlighting = nameof(ReferenceHighlighting); public const string RemoteHost = nameof(RemoteHost); public const string RemoveUnnecessaryLineContinuation = nameof(RemoveUnnecessaryLineContinuation); public const string Rename = nameof(Rename); public const string RenameTracking = nameof(RenameTracking); public const string SignatureHelp = nameof(SignatureHelp); public const string Simplification = nameof(Simplification); public const string SmartIndent = nameof(SmartIndent); public const string SmartTokenFormatting = nameof(SmartTokenFormatting); public const string Snippets = nameof(Snippets); public const string SourceGenerators = nameof(SourceGenerators); public const string SplitComment = nameof(SplitComment); public const string SplitStringLiteral = nameof(SplitStringLiteral); public const string SuggestionTags = nameof(SuggestionTags); public const string TargetTypedCompletion = nameof(TargetTypedCompletion); public const string TextStructureNavigator = nameof(TextStructureNavigator); public const string TodoComments = nameof(TodoComments); public const string ToggleBlockComment = nameof(ToggleBlockComment); public const string ToggleLineComment = nameof(ToggleLineComment); public const string TypeInferenceService = nameof(TypeInferenceService); public const string UnusedReferences = nameof(UnusedReferences); public const string ValidateFormatString = nameof(ValidateFormatString); public const string ValidateRegexString = nameof(ValidateRegexString); public const string Venus = nameof(Venus); public const string VsLanguageBlock = nameof(VsLanguageBlock); public const string VsNavInfo = nameof(VsNavInfo); public const string VsSearch = nameof(VsSearch); public const string WinForms = nameof(WinForms); public const string Workspace = nameof(Workspace); public const string XmlTagCompletion = nameof(XmlTagCompletion); } public const string Environment = nameof(Environment); public static class Environments { public const string VSProductInstall = nameof(VSProductInstall); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable namespace Microsoft.CodeAnalysis.Test.Utilities { public static class Traits { public const string Editor = nameof(Editor); public static class Editors { public const string KeyProcessors = nameof(KeyProcessors); public const string KeyProcessorProviders = nameof(KeyProcessorProviders); public const string Preview = nameof(Preview); public const string LanguageServerProtocol = nameof(LanguageServerProtocol); } public const string Feature = nameof(Feature); public static class Features { public const string AddAwait = "Refactoring.AddAwait"; public const string AddMissingImports = "Refactoring.AddMissingImports"; public const string AddMissingReference = nameof(AddMissingReference); public const string AddMissingTokens = nameof(AddMissingTokens); public const string Adornments = nameof(Adornments); public const string AsyncLazy = nameof(AsyncLazy); public const string AutomaticCompletion = nameof(AutomaticCompletion); public const string AutomaticEndConstructCorrection = nameof(AutomaticEndConstructCorrection); public const string BlockCommentEditing = nameof(BlockCommentEditing); public const string BraceHighlighting = nameof(BraceHighlighting); public const string BraceMatching = nameof(BraceMatching); public const string Build = nameof(Build); public const string CallHierarchy = nameof(CallHierarchy); public const string CaseCorrection = nameof(CaseCorrection); public const string ChangeSignature = nameof(ChangeSignature); public const string ClassView = nameof(ClassView); public const string Classification = nameof(Classification); public const string CodeActionsAddAccessibilityModifiers = "CodeActions.AddAccessibilityModifiers"; public const string CodeActionsAddAnonymousTypeMemberName = "CodeActions.AddAnonymousTypeMemberName"; public const string CodeActionsAddAwait = "CodeActions.AddAwait"; public const string CodeActionsAddBraces = "CodeActions.AddBraces"; public const string CodeActionsAddConstructorParametersFromMembers = "CodeActions.AddConstructorParametersFromMembers"; public const string CodeActionsAddDebuggerDisplay = "CodeActions.AddDebuggerDisplay"; public const string CodeActionsAddDocCommentNodes = "CodeActions.AddDocCommentParamNodes"; public const string CodeActionsAddExplicitCast = "CodeActions.AddExplicitCast"; public const string CodeActionsAddFileBanner = "CodeActions.AddFileBanner"; public const string CodeActionsAddImport = "CodeActions.AddImport"; public const string CodeActionsAddMissingReference = "CodeActions.AddMissingReference"; public const string CodeActionsAddNew = "CodeActions.AddNew"; public const string CodeActionsRemoveNewModifier = "CodeActions.RemoveNewModifier"; public const string CodeActionsAddObsoleteAttribute = "CodeActions.AddObsoleteAttribute"; public const string CodeActionsAddOverload = "CodeActions.AddOverloads"; public const string CodeActionsAddParameter = "CodeActions.AddParameter"; public const string CodeActionsAddParenthesesAroundConditionalExpressionInInterpolatedString = "CodeActions.AddParenthesesAroundConditionalExpressionInInterpolatedString"; public const string CodeActionsAddRequiredParentheses = "CodeActions.AddRequiredParentheses"; public const string CodeActionsAddShadows = "CodeActions.AddShadows"; public const string CodeActionsMakeMemberStatic = "CodeActions.MakeMemberStatic"; public const string CodeActionsAliasAmbiguousType = "CodeActions.AliasAmbiguousType"; public const string CodeActionsAssignOutParameters = "CodeActions.AssignOutParameters"; public const string CodeActionsChangeToAsync = "CodeActions.ChangeToAsync"; public const string CodeActionsChangeToIEnumerable = "CodeActions.ChangeToIEnumerable"; public const string CodeActionsChangeToYield = "CodeActions.ChangeToYield"; public const string CodeActionsConfiguration = "CodeActions.Configuration"; public const string CodeActionsConvertAnonymousTypeToClass = "CodeActions.ConvertAnonymousTypeToClass"; public const string CodeActionsConvertAnonymousTypeToTuple = "CodeActions.ConvertAnonymousTypeToTuple"; public const string CodeActionsConvertBetweenRegularAndVerbatimString = "CodeActions.ConvertBetweenRegularAndVerbatimString"; public const string CodeActionsConvertForEachToFor = "CodeActions.ConvertForEachToFor"; public const string CodeActionsConvertForEachToQuery = "CodeActions.ConvertForEachToQuery"; public const string CodeActionsConvertForToForEach = "CodeActions.ConvertForToForEach"; public const string CodeActionsConvertIfToSwitch = "CodeActions.ConvertIfToSwitch"; public const string CodeActionsConvertLocalFunctionToMethod = "CodeActions.ConvertLocalFunctionToMethod"; public const string CodeActionsConvertNumericLiteral = "CodeActions.ConvertNumericLiteral"; public const string CodeActionsConvertQueryToForEach = "CodeActions.ConvertQueryToForEach"; public const string CodeActionsConvertSwitchStatementToExpression = "CodeActions.ConvertSwitchStatementToExpression"; public const string CodeActionsConvertToInterpolatedString = "CodeActions.ConvertToInterpolatedString"; public const string CodeActionsConvertToIterator = "CodeActions.ConvertToIterator"; public const string CodeActionsConvertTupleToStruct = "CodeActions.ConvertTupleToStruct"; public const string CodeActionsCorrectExitContinue = "CodeActions.CorrectExitContinue"; public const string CodeActionsCorrectFunctionReturnType = "CodeActions.CorrectFunctionReturnType"; public const string CodeActionsCorrectNextControlVariable = "CodeActions.CorrectNextControlVariable"; public const string CodeActionsDeclareAsNullable = "CodeActions.DeclareAsNullable"; public const string CodeActionsExtractInterface = "CodeActions.ExtractInterface"; public const string CodeActionsExtractLocalFunction = "CodeActions.ExtractLocalFunction"; public const string CodeActionsExtractMethod = "CodeActions.ExtractMethod"; public const string CodeActionsFixAllOccurrences = "CodeActions.FixAllOccurrences"; public const string CodeActionsFixReturnType = "CodeActions.FixReturnType"; public const string CodeActionsFullyQualify = "CodeActions.FullyQualify"; public const string CodeActionsGenerateComparisonOperators = "CodeActions.GenerateComparisonOperators"; public const string CodeActionsGenerateConstructor = "CodeActions.GenerateConstructor"; public const string CodeActionsGenerateConstructorFromMembers = "CodeActions.GenerateConstructorFromMembers"; public const string CodeActionsGenerateDefaultConstructors = "CodeActions.GenerateDefaultConstructors"; public const string CodeActionsGenerateEndConstruct = "CodeActions.GenerateEndConstruct"; public const string CodeActionsGenerateEnumMember = "CodeActions.GenerateEnumMember"; public const string CodeActionsGenerateEqualsAndGetHashCode = "CodeActions.GenerateEqualsAndGetHashCodeFromMembers"; public const string CodeActionsGenerateEvent = "CodeActions.GenerateEvent"; public const string CodeActionsGenerateLocal = "CodeActions.GenerateLocal"; public const string CodeActionsGenerateMethod = "CodeActions.GenerateMethod"; public const string CodeActionsGenerateOverrides = "CodeActions.GenerateOverrides"; public const string CodeActionsGenerateType = "CodeActions.GenerateType"; public const string CodeActionsGenerateVariable = "CodeActions.GenerateVariable"; public const string CodeActionsImplementAbstractClass = "CodeActions.ImplementAbstractClass"; public const string CodeActionsImplementInterface = "CodeActions.ImplementInterface"; public const string CodeActionsInitializeParameter = "CodeActions.InitializeParameter"; public const string CodeActionsInlineMethod = "CodeActions.InlineMethod"; public const string CodeActionsInlineDeclaration = "CodeActions.InlineDeclaration"; public const string CodeActionsInlineTemporary = "CodeActions.InlineTemporary"; public const string CodeActionsInlineTypeCheck = "CodeActions.InlineTypeCheck"; public const string CodeActionsInsertBraces = "CodeActions.InsertBraces"; public const string CodeActionsInsertMissingTokens = "CodeActions.InsertMissingTokens"; public const string CodeActionsIntroduceLocalForExpression = "CodeActions.IntroduceLocalForExpression"; public const string CodeActionsIntroduceParameter = "CodeActions.IntroduceParameter"; public const string CodeActionsIntroduceUsingStatement = "CodeActions.IntroduceUsingStatement"; public const string CodeActionsIntroduceVariable = "CodeActions.IntroduceVariable"; public const string CodeActionsInvertConditional = "CodeActions.InvertConditional"; public const string CodeActionsInvertIf = "CodeActions.InvertIf"; public const string CodeActionsInvertLogical = "CodeActions.InvertLogical"; public const string CodeActionsInvokeDelegateWithConditionalAccess = "CodeActions.InvokeDelegateWithConditionalAccess"; public const string CodeActionsLambdaSimplifier = "CodeActions.LambdaSimplifier"; public const string CodeActionsMakeFieldReadonly = "CodeActions.MakeFieldReadonly"; public const string CodeActionsMakeLocalFunctionStatic = "CodeActions.MakeLocalFunctionStatic"; public const string CodeActionsMakeMethodAsynchronous = "CodeActions.MakeMethodAsynchronous"; public const string CodeActionsMakeMethodSynchronous = "CodeActions.MakeMethodSynchronous"; public const string CodeActionsMakeRefStruct = "CodeActions.MakeRefStruct"; public const string CodeActionsMakeStatementAsynchronous = "CodeActions.MakeStatementAsynchronous"; public const string CodeActionsMakeStructFieldsWritable = "CodeActions.MakeStructFieldsWritable"; public const string CodeActionsMakeTypeAbstract = "CodeActions.MakeTypeAbstract"; public const string CodeActionsMergeConsecutiveIfStatements = "CodeActions.MergeConsecutiveIfStatements"; public const string CodeActionsMergeNestedIfStatements = "CodeActions.MergeNestedIfStatements"; public const string CodeActionsMoveDeclarationNearReference = "CodeActions.MoveDeclarationNearReference"; public const string CodeActionsMoveToNamespace = nameof(CodeActionsMoveToNamespace); public const string CodeActionsMoveToTopOfFile = "CodeActions.MoveToTopOfFile"; public const string CodeActionsMoveType = "CodeActions.MoveType"; public const string CodeActionsNameTupleElement = "CodeActions.NameTupleElement"; public const string CodeActionsOrderModifiers = "CodeActions.OrderModifiers"; public const string CodeActionsPopulateSwitch = "CodeActions.PopulateSwitch"; public const string CodeActionsPullMemberUp = "CodeActions.PullMemberUp"; public const string CodeActionsQualifyMemberAccess = "CodeActions.QualifyMemberAccess"; public const string CodeActionsRemoveAsyncModifier = "CodeActions.RemoveAsyncModifier"; public const string CodeActionsRemoveByVal = "CodeActions.RemoveByVal"; public const string CodeActionsRemoveDocCommentNode = "CodeActions.RemoveDocCommentNode"; public const string CodeActionsRemoveInKeyword = "CodeActions.RemoveInKeyword"; public const string CodeActionsRemoveUnnecessarySuppressions = "CodeActions.RemoveUnnecessarySuppressions"; public const string CodeActionsRemoveUnnecessaryCast = "CodeActions.RemoveUnnecessaryCast"; public const string CodeActionsRemoveUnnecessaryDiscardDesignation = "CodeActions.RemoveUnnecessaryDiscardDesignation"; public const string CodeActionsRemoveUnnecessaryImports = "CodeActions.RemoveUnnecessaryImports"; public const string CodeActionsRemoveUnnecessaryParentheses = "CodeActions.RemoveUnnecessaryParentheses"; public const string CodeActionsRemoveUnreachableCode = "CodeActions.RemoveUnreachableCode"; public const string CodeActionsRemoveUnusedLocalFunction = "CodeActions.RemoveUnusedLocalFunction"; public const string CodeActionsRemoveUnusedMembers = "CodeActions.RemoveUnusedMembers"; public const string CodeActionsRemoveUnusedParameters = "CodeActions.RemoveUnusedParameters"; public const string CodeActionsRemoveUnusedValues = "CodeActions.RemoveUnusedValues"; public const string CodeActionsRemoveUnusedVariable = "CodeActions.RemoveUnusedVariable"; public const string CodeActionsReplaceDefaultLiteral = "CodeActions.ReplaceDefaultLiteral"; public const string CodeActionsReplaceDocCommentTextWithTag = "CodeActions.ReplaceDocCommentTextWithTag"; public const string CodeActionsReplaceMethodWithProperty = "CodeActions.ReplaceMethodWithProperty"; public const string CodeActionsReplacePropertyWithMethods = "CodeActions.ReplacePropertyWithMethods"; public const string CodeActionsResolveConflictMarker = "CodeActions.ResolveConflictMarker"; public const string CodeActionsReverseForStatement = "CodeActions.ReverseForStatement"; public const string CodeActionsSimplifyConditional = "CodeActions.SimplifyConditional"; public const string CodeActionsSimplifyInterpolation = "CodeActions.SimplifyInterpolation"; public const string CodeActionsSimplifyLinqExpression = "CodeActions.SimplifyLinqExpression"; public const string CodeActionsSimplifyThisOrMe = "CodeActions.SimplifyThisOrMe"; public const string CodeActionsSimplifyTypeNames = "CodeActions.SimplifyTypeNames"; public const string CodeActionsSpellcheck = "CodeActions.Spellcheck"; public const string CodeActionsSplitIntoConsecutiveIfStatements = "CodeActions.SplitIntoConsecutiveIfStatements"; public const string CodeActionsSplitIntoNestedIfStatements = "CodeActions.SplitIntoNestedIfStatements"; public const string CodeActionsSuppression = "CodeActions.Suppression"; public const string CodeActionsSyncNamespace = "CodeActions.SyncNamespace"; public const string CodeActionsUnsealClass = "CodeActions.UnsealClass"; public const string CodeActionsUpdateLegacySuppressions = "CodeActions.UpdateLegacySuppressions"; public const string CodeActionsUpdateProjectToAllowUnsafe = "CodeActions.UpdateProjectToAllowUnsafe"; public const string CodeActionsUpgradeProject = "CodeActions.UpgradeProject"; public const string CodeActionsUseAutoProperty = "CodeActions.UseAutoProperty"; public const string CodeActionsUseCoalesceExpression = "CodeActions.UseCoalesceExpression"; public const string CodeActionsUseCollectionInitializer = "CodeActions.UseCollectionInitializer"; public const string CodeActionsUseCompoundAssignment = "CodeActions.UseCompoundAssignment"; public const string CodeActionsUseConditionalExpression = "CodeActions.UseConditionalExpression"; public const string CodeActionsUseDeconstruction = "CodeActions.UseDeconstruction"; public const string CodeActionsUseDefaultLiteral = "CodeActions.UseDefaultLiteral"; public const string CodeActionsUseExplicitTupleName = "CodeActions.UseExplicitTupleName"; public const string CodeActionsUseExplicitType = "CodeActions.UseExplicitType"; public const string CodeActionsUseExplicitTypeForConst = "CodeActions.UseExplicitTypeForConst"; public const string CodeActionsUseExpressionBody = "CodeActions.UseExpressionBody"; public const string CodeActionsUseFrameworkType = "CodeActions.UseFrameworkType"; public const string CodeActionsUseImplicitObjectCreation = "CodeActions.UseImplicitObjectCreation"; public const string CodeActionsUseImplicitType = "CodeActions.UseImplicitType"; public const string CodeActionsUseIndexOperator = "CodeActions.UseIndexOperator"; public const string CodeActionsUseInferredMemberName = "CodeActions.UseInferredMemberName"; public const string CodeActionsUseInterpolatedVerbatimString = "CodeActions.UseInterpolatedVerbatimString"; public const string CodeActionsUseIsNotExpression = "CodeActions.UseIsNotExpression"; public const string CodeActionsUseIsNullCheck = "CodeActions.UseIsNullCheck"; public const string CodeActionsUseLocalFunction = "CodeActions.UseLocalFunction"; public const string CodeActionsUseNamedArguments = "CodeActions.UseNamedArguments"; public const string CodeActionsUseNotPattern = "CodeActions.UseNotPattern"; public const string CodeActionsUsePatternCombinators = "CodeActions.UsePatternCombinators"; public const string CodeActionsUseNullPropagation = "CodeActions.UseNullPropagation"; public const string CodeActionsUseObjectInitializer = "CodeActions.UseObjectInitializer"; public const string CodeActionsUseRangeOperator = "CodeActions.UseRangeOperator"; public const string CodeActionsUseSimpleUsingStatement = "CodeActions.UseSimpleUsingStatement"; public const string CodeActionsUseSystemHashCode = "CodeActions.UseSystemHashCode"; public const string CodeActionsUseThrowExpression = "CodeActions.UseThrowExpression"; public const string CodeActionsWrapping = "CodeActions.Wrapping"; public const string CodeCleanup = nameof(CodeCleanup); public const string CodeGeneration = nameof(CodeGeneration); public const string CodeGenerationSortDeclarations = "CodeGeneration.SortDeclarations"; public const string CodeLens = nameof(CodeLens); public const string CodeModel = nameof(CodeModel); public const string CodeModelEvents = "CodeModel.Events"; public const string CodeModelMethodXml = "CodeModel.MethodXml"; public const string CommentSelection = nameof(CommentSelection); public const string CompleteStatement = nameof(CompleteStatement); public const string Completion = nameof(Completion); public const string ConvertAutoPropertyToFullProperty = nameof(ConvertAutoPropertyToFullProperty); public const string ConvertCast = nameof(ConvertCast); public const string ConvertTypeOfToNameOf = nameof(ConvertTypeOfToNameOf); public const string DebuggingBreakpoints = "Debugging.Breakpoints"; public const string DebuggingDataTips = "Debugging.DataTips"; public const string DebuggingEditAndContinue = "Debugging.EditAndContinue"; public const string DebuggingIntelliSense = "Debugging.IntelliSense"; public const string DebuggingLocationName = "Debugging.LocationName"; public const string DebuggingNameResolver = "Debugging.NameResolver"; public const string DebuggingProximityExpressions = "Debugging.ProximityExpressions"; public const string DecompiledSource = nameof(DecompiledSource); public const string Diagnostics = nameof(Diagnostics); public const string DisposeAnalysis = nameof(DisposeAnalysis); public const string DocCommentFormatting = nameof(DocCommentFormatting); public const string DocumentationComments = nameof(DocumentationComments); public const string EditorConfig = nameof(EditorConfig); public const string EditorConfigUI = nameof(EditorConfigUI); public const string EncapsulateField = nameof(EncapsulateField); public const string EndConstructGeneration = nameof(EndConstructGeneration); public const string ErrorList = nameof(ErrorList); public const string ErrorSquiggles = nameof(ErrorSquiggles); public const string EventHookup = nameof(EventHookup); public const string Expansion = nameof(Expansion); public const string ExtractInterface = "Refactoring.ExtractInterface"; public const string ExtractMethod = "Refactoring.ExtractMethod"; public const string F1Help = nameof(F1Help); public const string FindReferences = nameof(FindReferences); public const string FixIncorrectTokens = nameof(FixIncorrectTokens); public const string FixInterpolatedVerbatimString = nameof(FixInterpolatedVerbatimString); public const string Formatting = nameof(Formatting); public const string GoToAdjacentMember = nameof(GoToAdjacentMember); public const string GoToBase = nameof(GoToBase); public const string GoToDefinition = nameof(GoToDefinition); public const string GoToImplementation = nameof(GoToImplementation); public const string InheritanceMargin = nameof(InheritanceMargin); public const string InlineHints = nameof(InlineHints); public const string Interactive = nameof(Interactive); public const string InteractiveHost = nameof(InteractiveHost); public const string KeywordHighlighting = nameof(KeywordHighlighting); public const string KeywordRecommending = nameof(KeywordRecommending); public const string LineCommit = nameof(LineCommit); public const string LineSeparators = nameof(LineSeparators); public const string LinkedFileDiffMerging = nameof(LinkedFileDiffMerging); public const string MSBuildWorkspace = nameof(MSBuildWorkspace); public const string MetadataAsSource = nameof(MetadataAsSource); public const string MoveToNamespace = nameof(MoveToNamespace); public const string NamingStyle = nameof(NamingStyle); public const string NavigableSymbols = nameof(NavigableSymbols); public const string NavigateTo = nameof(NavigateTo); public const string NavigationBar = nameof(NavigationBar); public const string NetCore = nameof(NetCore); public const string NormalizeModifiersOrOperators = nameof(NormalizeModifiersOrOperators); public const string ObjectBrowser = nameof(ObjectBrowser); public const string Options = nameof(Options); public const string Organizing = nameof(Organizing); public const string Outlining = nameof(Outlining); public const string Packaging = nameof(Packaging); public const string PasteTracking = nameof(PasteTracking); public const string Peek = nameof(Peek); public const string Progression = nameof(Progression); public const string ProjectSystemShims = nameof(ProjectSystemShims); public const string SarifErrorLogging = nameof(SarifErrorLogging); public const string QuickInfo = nameof(QuickInfo); public const string RQName = nameof(RQName); public const string ReduceTokens = nameof(ReduceTokens); public const string ReferenceHighlighting = nameof(ReferenceHighlighting); public const string RemoteHost = nameof(RemoteHost); public const string RemoveUnnecessaryLineContinuation = nameof(RemoveUnnecessaryLineContinuation); public const string Rename = nameof(Rename); public const string RenameTracking = nameof(RenameTracking); public const string SignatureHelp = nameof(SignatureHelp); public const string Simplification = nameof(Simplification); public const string SmartIndent = nameof(SmartIndent); public const string SmartTokenFormatting = nameof(SmartTokenFormatting); public const string Snippets = nameof(Snippets); public const string SourceGenerators = nameof(SourceGenerators); public const string SplitComment = nameof(SplitComment); public const string SplitStringLiteral = nameof(SplitStringLiteral); public const string SuggestionTags = nameof(SuggestionTags); public const string TargetTypedCompletion = nameof(TargetTypedCompletion); public const string TextStructureNavigator = nameof(TextStructureNavigator); public const string TodoComments = nameof(TodoComments); public const string ToggleBlockComment = nameof(ToggleBlockComment); public const string ToggleLineComment = nameof(ToggleLineComment); public const string TypeInferenceService = nameof(TypeInferenceService); public const string UnusedReferences = nameof(UnusedReferences); public const string ValidateFormatString = nameof(ValidateFormatString); public const string ValidateRegexString = nameof(ValidateRegexString); public const string Venus = nameof(Venus); public const string VsLanguageBlock = nameof(VsLanguageBlock); public const string VsNavInfo = nameof(VsNavInfo); public const string VsSearch = nameof(VsSearch); public const string WinForms = nameof(WinForms); public const string Workspace = nameof(Workspace); public const string XmlTagCompletion = nameof(XmlTagCompletion); } public const string Environment = nameof(Environment); public static class Environments { public const string VSProductInstall = nameof(VSProductInstall); } } }
-1
dotnet/roslyn
55,138
Avoid cancellation exceptions in intermediate operations
Addresses the following exceptions: ![image](https://user-images.githubusercontent.com/1408396/127185947-8a005aea-ae1c-4755-bf0f-21dfb8101352.png)
sharwell
2021-07-27T15:51:28Z
2021-07-27T21:36:45Z
3d8acbd585a75e9cdb3509623bf6c39ceb46b2c2
719d4ffa2be734463e5d7d4d74b23b8006fd7727
Avoid cancellation exceptions in intermediate operations. Addresses the following exceptions: ![image](https://user-images.githubusercontent.com/1408396/127185947-8a005aea-ae1c-4755-bf0f-21dfb8101352.png)
./src/VisualStudio/Core/Def/Implementation/ProjectSystem/MetadataReferences/FileWatchedPortableExecutableReferenceFactory.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.ComponentModel.Composition; using System.IO; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Host.Mef; namespace Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem.MetadataReferences { [Export] internal sealed class FileWatchedPortableExecutableReferenceFactory { private readonly object _gate = new(); /// <summary> /// This right now acquires the entire VisualStudioWorkspace because right now the production /// of metadata references depends on other workspace services. See the comments on /// <see cref="VisualStudioMetadataReferenceManagerFactory"/> that this strictly shouldn't be necessary /// but for now is quite the tangle to fix. /// </summary> private readonly Lazy<VisualStudioWorkspace> _visualStudioWorkspace; /// <summary> /// A file change context used to watch metadata references. /// </summary> private readonly FileChangeWatcher.IContext _fileReferenceChangeContext; /// <summary> /// File watching tokens from <see cref="_fileReferenceChangeContext"/> that are watching metadata references. These are only created once we are actually applying a batch because /// we don't determine until the batch is applied if the file reference will actually be a file reference or it'll be a converted project reference. /// </summary> private readonly Dictionary<PortableExecutableReference, FileChangeWatcher.IFileWatchingToken> _metadataReferenceFileWatchingTokens = new(); /// <summary> /// <see cref="CancellationTokenSource"/>s for in-flight refreshing of metadata references. When we see a file change, we wait a bit before trying to actually /// update the workspace. We need cancellation tokens for those so we can cancel them either when a flurry of events come in (so we only do the delay after the last /// modification), or when we know the project is going away entirely. /// </summary> private readonly Dictionary<string, CancellationTokenSource> _metadataReferenceRefreshCancellationTokenSources = new(); [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public FileWatchedPortableExecutableReferenceFactory( Lazy<VisualStudioWorkspace> visualStudioWorkspace, FileChangeWatcherProvider fileChangeWatcherProvider) { _visualStudioWorkspace = visualStudioWorkspace; // We will do a single directory watch on the Reference Assemblies folder to avoid having to create separate file // watches on individual .dlls that effectively never change. var referenceAssembliesPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86), "Reference Assemblies", "Microsoft", "Framework"); var referenceAssemblies = new FileChangeWatcher.WatchedDirectory(referenceAssembliesPath, ".dll"); // TODO: set this to watch the NuGet directory as well; there's some concern that watching the entire directory // might make restores take longer because we'll be watching changes that may not impact your project. _fileReferenceChangeContext = fileChangeWatcherProvider.Watcher.CreateContext(referenceAssemblies); _fileReferenceChangeContext.FileChanged += FileReferenceChangeContext_FileChanged; } public event EventHandler<string> ReferenceChanged; public PortableExecutableReference CreateReferenceAndStartWatchingFile(string fullFilePath, MetadataReferenceProperties properties) { lock (_gate) { var reference = _visualStudioWorkspace.Value.CreatePortableExecutableReference(fullFilePath, properties); var fileWatchingToken = _fileReferenceChangeContext.EnqueueWatchingFile(fullFilePath); _metadataReferenceFileWatchingTokens.Add(reference, fileWatchingToken); return reference; } } public void StopWatchingReference(PortableExecutableReference reference) { lock (_gate) { if (!_metadataReferenceFileWatchingTokens.TryGetValue(reference, out var token)) { throw new ArgumentException("The reference was already not being watched."); } _fileReferenceChangeContext.StopWatchingFile(token); _metadataReferenceFileWatchingTokens.Remove(reference); // Note we still potentially have an outstanding change that we haven't raised a notification // for due to the delay we use. We could cancel the notification for that file path, // but we may still have another outstanding PortableExecutableReference that isn't this one // that does want that notification. We're OK just leaving the delay still running for two // reasons: // // 1. Technically, we did see a file change before the call to StopWatchingReference, so // arguably we should still raise it. // 2. Since we raise the notification for a file path, it's up to the consumer of this to still // track down which actual reference needs to be changed. That'll automatically handle any // race where the event comes late, which is a scenario this must always deal with no matter // what -- another thread might already be gearing up to notify the caller of this reference // and we can't stop it. } } private void FileReferenceChangeContext_FileChanged(object sender, string fullFilePath) { lock (_gate) { if (_metadataReferenceRefreshCancellationTokenSources.TryGetValue(fullFilePath, out var cancellationTokenSource)) { cancellationTokenSource.Cancel(); _metadataReferenceRefreshCancellationTokenSources.Remove(fullFilePath); } cancellationTokenSource = new CancellationTokenSource(); _metadataReferenceRefreshCancellationTokenSources.Add(fullFilePath, cancellationTokenSource); Task.Delay(TimeSpan.FromSeconds(5), cancellationTokenSource.Token).ContinueWith(_ => { var needsNotification = false; lock (_gate) { // We need to re-check the cancellation token source under the lock, since it might have been cancelled and restarted // due to another event cancellationTokenSource.Token.ThrowIfCancellationRequested(); needsNotification = true; _metadataReferenceRefreshCancellationTokenSources.Remove(fullFilePath); } if (needsNotification) { ReferenceChanged?.Invoke(this, fullFilePath); } }, cancellationTokenSource.Token, TaskContinuationOptions.OnlyOnRanToCompletion, TaskScheduler.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.ComponentModel.Composition; using System.IO; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Host.Mef; namespace Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem.MetadataReferences { [Export] internal sealed class FileWatchedPortableExecutableReferenceFactory { private readonly object _gate = new(); /// <summary> /// This right now acquires the entire VisualStudioWorkspace because right now the production /// of metadata references depends on other workspace services. See the comments on /// <see cref="VisualStudioMetadataReferenceManagerFactory"/> that this strictly shouldn't be necessary /// but for now is quite the tangle to fix. /// </summary> private readonly Lazy<VisualStudioWorkspace> _visualStudioWorkspace; /// <summary> /// A file change context used to watch metadata references. /// </summary> private readonly FileChangeWatcher.IContext _fileReferenceChangeContext; /// <summary> /// File watching tokens from <see cref="_fileReferenceChangeContext"/> that are watching metadata references. These are only created once we are actually applying a batch because /// we don't determine until the batch is applied if the file reference will actually be a file reference or it'll be a converted project reference. /// </summary> private readonly Dictionary<PortableExecutableReference, FileChangeWatcher.IFileWatchingToken> _metadataReferenceFileWatchingTokens = new(); /// <summary> /// <see cref="CancellationTokenSource"/>s for in-flight refreshing of metadata references. When we see a file change, we wait a bit before trying to actually /// update the workspace. We need cancellation tokens for those so we can cancel them either when a flurry of events come in (so we only do the delay after the last /// modification), or when we know the project is going away entirely. /// </summary> private readonly Dictionary<string, CancellationTokenSource> _metadataReferenceRefreshCancellationTokenSources = new(); [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public FileWatchedPortableExecutableReferenceFactory( Lazy<VisualStudioWorkspace> visualStudioWorkspace, FileChangeWatcherProvider fileChangeWatcherProvider) { _visualStudioWorkspace = visualStudioWorkspace; // We will do a single directory watch on the Reference Assemblies folder to avoid having to create separate file // watches on individual .dlls that effectively never change. var referenceAssembliesPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86), "Reference Assemblies", "Microsoft", "Framework"); var referenceAssemblies = new FileChangeWatcher.WatchedDirectory(referenceAssembliesPath, ".dll"); // TODO: set this to watch the NuGet directory as well; there's some concern that watching the entire directory // might make restores take longer because we'll be watching changes that may not impact your project. _fileReferenceChangeContext = fileChangeWatcherProvider.Watcher.CreateContext(referenceAssemblies); _fileReferenceChangeContext.FileChanged += FileReferenceChangeContext_FileChanged; } public event EventHandler<string> ReferenceChanged; public PortableExecutableReference CreateReferenceAndStartWatchingFile(string fullFilePath, MetadataReferenceProperties properties) { lock (_gate) { var reference = _visualStudioWorkspace.Value.CreatePortableExecutableReference(fullFilePath, properties); var fileWatchingToken = _fileReferenceChangeContext.EnqueueWatchingFile(fullFilePath); _metadataReferenceFileWatchingTokens.Add(reference, fileWatchingToken); return reference; } } public void StopWatchingReference(PortableExecutableReference reference) { lock (_gate) { if (!_metadataReferenceFileWatchingTokens.TryGetValue(reference, out var token)) { throw new ArgumentException("The reference was already not being watched."); } _fileReferenceChangeContext.StopWatchingFile(token); _metadataReferenceFileWatchingTokens.Remove(reference); // Note we still potentially have an outstanding change that we haven't raised a notification // for due to the delay we use. We could cancel the notification for that file path, // but we may still have another outstanding PortableExecutableReference that isn't this one // that does want that notification. We're OK just leaving the delay still running for two // reasons: // // 1. Technically, we did see a file change before the call to StopWatchingReference, so // arguably we should still raise it. // 2. Since we raise the notification for a file path, it's up to the consumer of this to still // track down which actual reference needs to be changed. That'll automatically handle any // race where the event comes late, which is a scenario this must always deal with no matter // what -- another thread might already be gearing up to notify the caller of this reference // and we can't stop it. } } private void FileReferenceChangeContext_FileChanged(object sender, string fullFilePath) { lock (_gate) { if (_metadataReferenceRefreshCancellationTokenSources.TryGetValue(fullFilePath, out var cancellationTokenSource)) { cancellationTokenSource.Cancel(); _metadataReferenceRefreshCancellationTokenSources.Remove(fullFilePath); } cancellationTokenSource = new CancellationTokenSource(); _metadataReferenceRefreshCancellationTokenSources.Add(fullFilePath, cancellationTokenSource); Task.Delay(TimeSpan.FromSeconds(5), cancellationTokenSource.Token).ContinueWith(_ => { var needsNotification = false; lock (_gate) { // We need to re-check the cancellation token source under the lock, since it might have been cancelled and restarted // due to another event cancellationTokenSource.Token.ThrowIfCancellationRequested(); needsNotification = true; _metadataReferenceRefreshCancellationTokenSources.Remove(fullFilePath); } if (needsNotification) { ReferenceChanged?.Invoke(this, fullFilePath); } }, cancellationTokenSource.Token, TaskContinuationOptions.OnlyOnRanToCompletion, TaskScheduler.Default); } } } }
-1
dotnet/roslyn
55,138
Avoid cancellation exceptions in intermediate operations
Addresses the following exceptions: ![image](https://user-images.githubusercontent.com/1408396/127185947-8a005aea-ae1c-4755-bf0f-21dfb8101352.png)
sharwell
2021-07-27T15:51:28Z
2021-07-27T21:36:45Z
3d8acbd585a75e9cdb3509623bf6c39ceb46b2c2
719d4ffa2be734463e5d7d4d74b23b8006fd7727
Avoid cancellation exceptions in intermediate operations. Addresses the following exceptions: ![image](https://user-images.githubusercontent.com/1408396/127185947-8a005aea-ae1c-4755-bf0f-21dfb8101352.png)
./src/EditorFeatures/CSharpTest2/Recommendations/RecordKeywordRecommenderTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations { public class RecordKeywordRecommenderTests : KeywordRecommenderTests { [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAtRoot_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterClass_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"class C { } $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterGlobalStatement_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"System.Console.WriteLine(); $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterGlobalVariableDeclaration_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"int i = 0; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInUsingAlias() { await VerifyAbsenceAsync( @"using Goo = $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInGlobalUsingAlias() { await VerifyAbsenceAsync( @"global using Goo = $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInEmptyStatement() { await VerifyAbsenceAsync(AddInsideMethod( @"$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInCompilationUnit() { await VerifyKeywordAsync( @"$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterExtern() { await VerifyKeywordAsync( @"extern alias Goo; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterUsing() { await VerifyKeywordAsync( @"using Goo; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterGlobalUsing() { await VerifyKeywordAsync( @"global using Goo; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNamespace() { await VerifyKeywordAsync( @"namespace N {} $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterFileScopedNamespace() { await VerifyKeywordAsync( @"namespace N; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterTypeDeclaration() { await VerifyKeywordAsync( @"class C {} $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterDelegateDeclaration() { await VerifyKeywordAsync( @"delegate void Goo(); $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterMethod() { await VerifyKeywordAsync( @"class C { void Goo() {} $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterField() { await VerifyKeywordAsync( @"class C { int i; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterProperty() { await VerifyKeywordAsync( @"class C { int i { get; } $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotBeforeUsing() { await VerifyAbsenceAsync(SourceCodeKind.Regular, @"$$ using Goo;"); } [WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/9880"), Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotBeforeUsing_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"$$ using Goo;"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotBeforeGlobalUsing() { await VerifyAbsenceAsync(SourceCodeKind.Regular, @"$$ global using Goo;"); } [WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/9880"), Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotBeforeGlobalUsing_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"$$ global using Goo;"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterAssemblyAttribute() { await VerifyKeywordAsync( @"[assembly: goo] $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterRootAttribute() { await VerifyKeywordAsync( @"[goo] $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedAttribute() { await VerifyKeywordAsync( @"class C { [goo] $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInsideStruct() { await VerifyKeywordAsync( @"struct S { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInsideInterface() { await VerifyKeywordAsync(@"interface I { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInsideClass() { await VerifyKeywordAsync( @"class C { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInsideRecord1() { // The recommender doesn't work in record in script // Tracked by https://github.com/dotnet/roslyn/issues/44865 await VerifyWorkerAsync( @"record C { $$", absent: false, options: TestOptions.RegularPreview); } [WorkItem(50783, "https://github.com/dotnet/roslyn/issues/50783")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInsideRecord2() { // The recommender doesn't work in record in script // Tracked by https://github.com/dotnet/roslyn/issues/44865 await VerifyWorkerAsync( @"record C { public $$", absent: false, options: TestOptions.RegularPreview); } [WorkItem(50783, "https://github.com/dotnet/roslyn/issues/50783")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInsideRecord3() { // The recommender doesn't work in record in script // Tracked by https://github.com/dotnet/roslyn/issues/44865 await VerifyWorkerAsync( @"record C { [X] $$", absent: false, options: TestOptions.RegularPreview); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterPartial() { await VerifyKeywordAsync( @"partial $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterPublicRecord() { await VerifyAbsenceAsync( @"public record $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterAbstract() { await VerifyKeywordAsync( @"abstract $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterInternal() { await VerifyKeywordAsync( @"internal $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterStaticPublic() { await VerifyKeywordAsync( @"static public $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterPublicStatic() { await VerifyKeywordAsync( @"public static $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterInvalidPublic() => await VerifyAbsenceAsync(@"virtual public $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterPublic() { await VerifyKeywordAsync( @"public $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterPrivate() { await VerifyKeywordAsync( @"private $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterProtected() { await VerifyKeywordAsync( @"protected $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterSealed() { await VerifyKeywordAsync( @"sealed $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterStatic() { await VerifyKeywordAsync( @"static $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterStaticInUsingDirective() { await VerifyAbsenceAsync( @"using static $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterStaticInGlobalUsingDirective() { await VerifyAbsenceAsync( @"global using static $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterClass() => await VerifyAbsenceAsync(@"class $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem(32214, "https://github.com/dotnet/roslyn/issues/32214")] public async Task TestNotBetweenUsings() { // Recommendation in scripting is not stable. See https://github.com/dotnet/roslyn/issues/32214 await VerifyAbsenceAsync(SourceCodeKind.Regular, @"using Goo; $$ using Bar;"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem(32214, "https://github.com/dotnet/roslyn/issues/32214")] public async Task TestNotBetweenGlobalUsings_01() { // Recommendation in scripting is not stable. See https://github.com/dotnet/roslyn/issues/32214 await VerifyAbsenceAsync(SourceCodeKind.Regular, @"global using Goo; $$ using Bar;"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem(32214, "https://github.com/dotnet/roslyn/issues/32214")] public async Task TestNotBetweenGlobalUsings_02() { // Recommendation in scripting is not stable. See https://github.com/dotnet/roslyn/issues/32214 await VerifyAbsenceAsync(SourceCodeKind.Regular, @"global using Goo; $$ global using Bar;"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterClassTypeParameterConstraint() { await VerifyAbsenceAsync( @"class C<T> where T : $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterClassTypeParameterConstraint2() { await VerifyAbsenceAsync( @"class C<T> where T : $$ where U : U"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterMethodTypeParameterConstraint() { await VerifyAbsenceAsync( @"class C { void Goo<T>() where T : $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterMethodTypeParameterConstraint2() { await VerifyAbsenceAsync( @"class C { void Goo<T>() where T : $$ where U : T"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNew() { await VerifyKeywordAsync( @"class C { new $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterReadonly() { // readonly record struct is allowed. await VerifyKeywordAsync("readonly $$"); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations { public class RecordKeywordRecommenderTests : KeywordRecommenderTests { [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAtRoot_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterClass_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"class C { } $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterGlobalStatement_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"System.Console.WriteLine(); $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterGlobalVariableDeclaration_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"int i = 0; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInUsingAlias() { await VerifyAbsenceAsync( @"using Goo = $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInGlobalUsingAlias() { await VerifyAbsenceAsync( @"global using Goo = $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInEmptyStatement() { await VerifyAbsenceAsync(AddInsideMethod( @"$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInCompilationUnit() { await VerifyKeywordAsync( @"$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterExtern() { await VerifyKeywordAsync( @"extern alias Goo; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterUsing() { await VerifyKeywordAsync( @"using Goo; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterGlobalUsing() { await VerifyKeywordAsync( @"global using Goo; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNamespace() { await VerifyKeywordAsync( @"namespace N {} $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterFileScopedNamespace() { await VerifyKeywordAsync( @"namespace N; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterTypeDeclaration() { await VerifyKeywordAsync( @"class C {} $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterDelegateDeclaration() { await VerifyKeywordAsync( @"delegate void Goo(); $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterMethod() { await VerifyKeywordAsync( @"class C { void Goo() {} $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterField() { await VerifyKeywordAsync( @"class C { int i; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterProperty() { await VerifyKeywordAsync( @"class C { int i { get; } $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotBeforeUsing() { await VerifyAbsenceAsync(SourceCodeKind.Regular, @"$$ using Goo;"); } [WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/9880"), Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotBeforeUsing_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"$$ using Goo;"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotBeforeGlobalUsing() { await VerifyAbsenceAsync(SourceCodeKind.Regular, @"$$ global using Goo;"); } [WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/9880"), Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotBeforeGlobalUsing_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"$$ global using Goo;"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterAssemblyAttribute() { await VerifyKeywordAsync( @"[assembly: goo] $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterRootAttribute() { await VerifyKeywordAsync( @"[goo] $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedAttribute() { await VerifyKeywordAsync( @"class C { [goo] $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInsideStruct() { await VerifyKeywordAsync( @"struct S { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInsideInterface() { await VerifyKeywordAsync(@"interface I { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInsideClass() { await VerifyKeywordAsync( @"class C { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInsideRecord1() { // The recommender doesn't work in record in script // Tracked by https://github.com/dotnet/roslyn/issues/44865 await VerifyWorkerAsync( @"record C { $$", absent: false, options: TestOptions.RegularPreview); } [WorkItem(50783, "https://github.com/dotnet/roslyn/issues/50783")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInsideRecord2() { // The recommender doesn't work in record in script // Tracked by https://github.com/dotnet/roslyn/issues/44865 await VerifyWorkerAsync( @"record C { public $$", absent: false, options: TestOptions.RegularPreview); } [WorkItem(50783, "https://github.com/dotnet/roslyn/issues/50783")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInsideRecord3() { // The recommender doesn't work in record in script // Tracked by https://github.com/dotnet/roslyn/issues/44865 await VerifyWorkerAsync( @"record C { [X] $$", absent: false, options: TestOptions.RegularPreview); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterPartial() { await VerifyKeywordAsync( @"partial $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterPublicRecord() { await VerifyAbsenceAsync( @"public record $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterAbstract() { await VerifyKeywordAsync( @"abstract $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterInternal() { await VerifyKeywordAsync( @"internal $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterStaticPublic() { await VerifyKeywordAsync( @"static public $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterPublicStatic() { await VerifyKeywordAsync( @"public static $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterInvalidPublic() => await VerifyAbsenceAsync(@"virtual public $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterPublic() { await VerifyKeywordAsync( @"public $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterPrivate() { await VerifyKeywordAsync( @"private $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterProtected() { await VerifyKeywordAsync( @"protected $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterSealed() { await VerifyKeywordAsync( @"sealed $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterStatic() { await VerifyKeywordAsync( @"static $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterStaticInUsingDirective() { await VerifyAbsenceAsync( @"using static $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterStaticInGlobalUsingDirective() { await VerifyAbsenceAsync( @"global using static $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterClass() => await VerifyAbsenceAsync(@"class $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem(32214, "https://github.com/dotnet/roslyn/issues/32214")] public async Task TestNotBetweenUsings() { // Recommendation in scripting is not stable. See https://github.com/dotnet/roslyn/issues/32214 await VerifyAbsenceAsync(SourceCodeKind.Regular, @"using Goo; $$ using Bar;"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem(32214, "https://github.com/dotnet/roslyn/issues/32214")] public async Task TestNotBetweenGlobalUsings_01() { // Recommendation in scripting is not stable. See https://github.com/dotnet/roslyn/issues/32214 await VerifyAbsenceAsync(SourceCodeKind.Regular, @"global using Goo; $$ using Bar;"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem(32214, "https://github.com/dotnet/roslyn/issues/32214")] public async Task TestNotBetweenGlobalUsings_02() { // Recommendation in scripting is not stable. See https://github.com/dotnet/roslyn/issues/32214 await VerifyAbsenceAsync(SourceCodeKind.Regular, @"global using Goo; $$ global using Bar;"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterClassTypeParameterConstraint() { await VerifyAbsenceAsync( @"class C<T> where T : $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterClassTypeParameterConstraint2() { await VerifyAbsenceAsync( @"class C<T> where T : $$ where U : U"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterMethodTypeParameterConstraint() { await VerifyAbsenceAsync( @"class C { void Goo<T>() where T : $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterMethodTypeParameterConstraint2() { await VerifyAbsenceAsync( @"class C { void Goo<T>() where T : $$ where U : T"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNew() { await VerifyKeywordAsync( @"class C { new $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterReadonly() { // readonly record struct is allowed. await VerifyKeywordAsync("readonly $$"); } } }
-1
dotnet/roslyn
55,138
Avoid cancellation exceptions in intermediate operations
Addresses the following exceptions: ![image](https://user-images.githubusercontent.com/1408396/127185947-8a005aea-ae1c-4755-bf0f-21dfb8101352.png)
sharwell
2021-07-27T15:51:28Z
2021-07-27T21:36:45Z
3d8acbd585a75e9cdb3509623bf6c39ceb46b2c2
719d4ffa2be734463e5d7d4d74b23b8006fd7727
Avoid cancellation exceptions in intermediate operations. Addresses the following exceptions: ![image](https://user-images.githubusercontent.com/1408396/127185947-8a005aea-ae1c-4755-bf0f-21dfb8101352.png)
./src/VisualStudio/Core/Def/Implementation/ChangeSignature/VisualStudioChangeSignatureOptionsService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.ChangeSignature; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.VisualStudio.Text.Classification; namespace Microsoft.VisualStudio.LanguageServices.Implementation.ChangeSignature { [ExportWorkspaceService(typeof(IChangeSignatureOptionsService), ServiceLayer.Host), Shared] internal class VisualStudioChangeSignatureOptionsService : ForegroundThreadAffinitizedObject, IChangeSignatureOptionsService { private readonly IClassificationFormatMap _classificationFormatMap; private readonly ClassificationTypeMap _classificationTypeMap; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public VisualStudioChangeSignatureOptionsService( IClassificationFormatMapService classificationFormatMapService, ClassificationTypeMap classificationTypeMap, IThreadingContext threadingContext) : base(threadingContext) { _classificationFormatMap = classificationFormatMapService.GetClassificationFormatMap("tooltip"); _classificationTypeMap = classificationTypeMap; } public ChangeSignatureOptionsResult? GetChangeSignatureOptions( Document document, int positionForTypeBinding, ISymbol symbol, ParameterConfiguration parameters) { this.AssertIsForeground(); var viewModel = new ChangeSignatureDialogViewModel( parameters, symbol, document, positionForTypeBinding, _classificationFormatMap, _classificationTypeMap); ChangeSignatureLogger.LogChangeSignatureDialogLaunched(); var dialog = new ChangeSignatureDialog(viewModel); var result = dialog.ShowModal(); if (result.HasValue && result.Value) { ChangeSignatureLogger.LogChangeSignatureDialogCommitted(); var signatureChange = new SignatureChange(parameters, viewModel.GetParameterConfiguration()); signatureChange.LogTelemetry(); return new ChangeSignatureOptionsResult(signatureChange, previewChanges: viewModel.PreviewChanges); } return null; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Composition; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.ChangeSignature; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.VisualStudio.Text.Classification; namespace Microsoft.VisualStudio.LanguageServices.Implementation.ChangeSignature { [ExportWorkspaceService(typeof(IChangeSignatureOptionsService), ServiceLayer.Host), Shared] internal class VisualStudioChangeSignatureOptionsService : ForegroundThreadAffinitizedObject, IChangeSignatureOptionsService { private readonly IClassificationFormatMap _classificationFormatMap; private readonly ClassificationTypeMap _classificationTypeMap; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public VisualStudioChangeSignatureOptionsService( IClassificationFormatMapService classificationFormatMapService, ClassificationTypeMap classificationTypeMap, IThreadingContext threadingContext) : base(threadingContext) { _classificationFormatMap = classificationFormatMapService.GetClassificationFormatMap("tooltip"); _classificationTypeMap = classificationTypeMap; } public ChangeSignatureOptionsResult? GetChangeSignatureOptions( Document document, int positionForTypeBinding, ISymbol symbol, ParameterConfiguration parameters) { this.AssertIsForeground(); var viewModel = new ChangeSignatureDialogViewModel( parameters, symbol, document, positionForTypeBinding, _classificationFormatMap, _classificationTypeMap); ChangeSignatureLogger.LogChangeSignatureDialogLaunched(); var dialog = new ChangeSignatureDialog(viewModel); var result = dialog.ShowModal(); if (result.HasValue && result.Value) { ChangeSignatureLogger.LogChangeSignatureDialogCommitted(); var signatureChange = new SignatureChange(parameters, viewModel.GetParameterConfiguration()); signatureChange.LogTelemetry(); return new ChangeSignatureOptionsResult(signatureChange, previewChanges: viewModel.PreviewChanges); } return null; } } }
-1
dotnet/roslyn
55,138
Avoid cancellation exceptions in intermediate operations
Addresses the following exceptions: ![image](https://user-images.githubusercontent.com/1408396/127185947-8a005aea-ae1c-4755-bf0f-21dfb8101352.png)
sharwell
2021-07-27T15:51:28Z
2021-07-27T21:36:45Z
3d8acbd585a75e9cdb3509623bf6c39ceb46b2c2
719d4ffa2be734463e5d7d4d74b23b8006fd7727
Avoid cancellation exceptions in intermediate operations. Addresses the following exceptions: ![image](https://user-images.githubusercontent.com/1408396/127185947-8a005aea-ae1c-4755-bf0f-21dfb8101352.png)
./src/EditorFeatures/Text/xlf/TextEditorResources.pl.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="pl" original="../TextEditorResources.resx"> <body> <trans-unit id="The_snapshot_does_not_contain_the_specified_position"> <source>The snapshot does not contain the specified position.</source> <target state="translated">Migawka nie zawiera określonej pozycji.</target> <note /> </trans-unit> <trans-unit id="The_snapshot_does_not_contain_the_specified_span"> <source>The snapshot does not contain the specified span.</source> <target state="translated">Migawka nie zawiera podanego okresu.</target> <note /> </trans-unit> <trans-unit id="textContainer_is_not_a_SourceTextContainer_that_was_created_from_an_ITextBuffer"> <source>textContainer is not a SourceTextContainer that was created from an ITextBuffer.</source> <target state="translated">Element textContainer nie jest elementem SourceTextContainer utworzonym na podstawie elementu ITextBuffer.</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="pl" original="../TextEditorResources.resx"> <body> <trans-unit id="The_snapshot_does_not_contain_the_specified_position"> <source>The snapshot does not contain the specified position.</source> <target state="translated">Migawka nie zawiera określonej pozycji.</target> <note /> </trans-unit> <trans-unit id="The_snapshot_does_not_contain_the_specified_span"> <source>The snapshot does not contain the specified span.</source> <target state="translated">Migawka nie zawiera podanego okresu.</target> <note /> </trans-unit> <trans-unit id="textContainer_is_not_a_SourceTextContainer_that_was_created_from_an_ITextBuffer"> <source>textContainer is not a SourceTextContainer that was created from an ITextBuffer.</source> <target state="translated">Element textContainer nie jest elementem SourceTextContainer utworzonym na podstawie elementu ITextBuffer.</target> <note /> </trans-unit> </body> </file> </xliff>
-1
dotnet/roslyn
55,138
Avoid cancellation exceptions in intermediate operations
Addresses the following exceptions: ![image](https://user-images.githubusercontent.com/1408396/127185947-8a005aea-ae1c-4755-bf0f-21dfb8101352.png)
sharwell
2021-07-27T15:51:28Z
2021-07-27T21:36:45Z
3d8acbd585a75e9cdb3509623bf6c39ceb46b2c2
719d4ffa2be734463e5d7d4d74b23b8006fd7727
Avoid cancellation exceptions in intermediate operations. Addresses the following exceptions: ![image](https://user-images.githubusercontent.com/1408396/127185947-8a005aea-ae1c-4755-bf0f-21dfb8101352.png)
./docs/compilers/CSharp/COM Interop.md
COM interop =========== [This is a placeholder. We need some more documentation here] We have a number of features in the compiler/language to support COM interop, none of which is described in the language specification.
COM interop =========== [This is a placeholder. We need some more documentation here] We have a number of features in the compiler/language to support COM interop, none of which is described in the language specification.
-1
dotnet/roslyn
55,138
Avoid cancellation exceptions in intermediate operations
Addresses the following exceptions: ![image](https://user-images.githubusercontent.com/1408396/127185947-8a005aea-ae1c-4755-bf0f-21dfb8101352.png)
sharwell
2021-07-27T15:51:28Z
2021-07-27T21:36:45Z
3d8acbd585a75e9cdb3509623bf6c39ceb46b2c2
719d4ffa2be734463e5d7d4d74b23b8006fd7727
Avoid cancellation exceptions in intermediate operations. Addresses the following exceptions: ![image](https://user-images.githubusercontent.com/1408396/127185947-8a005aea-ae1c-4755-bf0f-21dfb8101352.png)
./src/EditorFeatures/DiagnosticsTestUtilities/CodeActions/VisualBasicCodeFixVerifier`2+Test.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.Net; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Testing.Verifiers; using Microsoft.CodeAnalysis.VisualBasic; using Microsoft.CodeAnalysis.VisualBasic.Testing; using Xunit; #if !CODE_STYLE using Roslyn.Utilities; #endif namespace Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions { public static partial class VisualBasicCodeFixVerifier<TAnalyzer, TCodeFix> where TAnalyzer : DiagnosticAnalyzer, new() where TCodeFix : CodeFixProvider, new() { public class Test : VisualBasicCodeFixTest<TAnalyzer, TCodeFix, XUnitVerifier> { private readonly SharedVerifierState _sharedState; static Test() { // If we have outdated defaults from the host unit test application targeting an older .NET Framework, use more // reasonable TLS protocol version for outgoing connections. #pragma warning disable CA5364 // Do Not Use Deprecated Security Protocols #pragma warning disable CS0618 // Type or member is obsolete if (ServicePointManager.SecurityProtocol == (SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls)) #pragma warning restore CS0618 // Type or member is obsolete #pragma warning restore CA5364 // Do Not Use Deprecated Security Protocols { ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; } } public Test() { _sharedState = new SharedVerifierState(this, DefaultFileExt); MarkupOptions = Testing.MarkupOptions.UseFirstDescriptor; SolutionTransforms.Add((solution, projectId) => { var parseOptions = (VisualBasicParseOptions)solution.GetProject(projectId)!.ParseOptions!; solution = solution.WithProjectParseOptions(projectId, parseOptions.WithLanguageVersion(LanguageVersion)); return solution; }); } /// <summary> /// Gets or sets the language version to use for the test. The default value is /// <see cref="LanguageVersion.VisualBasic16"/>. /// </summary> public LanguageVersion LanguageVersion { get; set; } = LanguageVersion.VisualBasic16; /// <inheritdoc cref="SharedVerifierState.Options"/> internal OptionsCollection Options => _sharedState.Options; /// <inheritdoc cref="SharedVerifierState.EditorConfig"/> public string? EditorConfig { get => _sharedState.EditorConfig; set => _sharedState.EditorConfig = value; } public Func<ImmutableArray<Diagnostic>, Diagnostic?>? DiagnosticSelector { get; set; } protected override async Task RunImplAsync(CancellationToken cancellationToken = default) { if (DiagnosticSelector is object) { Assert.True(CodeFixTestBehaviors.HasFlag(Testing.CodeFixTestBehaviors.FixOne), $"'{nameof(DiagnosticSelector)}' can only be used with '{nameof(Testing.CodeFixTestBehaviors)}.{nameof(Testing.CodeFixTestBehaviors.FixOne)}'"); } _sharedState.Apply(); await base.RunImplAsync(cancellationToken); } #if !CODE_STYLE protected override AnalyzerOptions GetAnalyzerOptions(Project project) => new WorkspaceAnalyzerOptions(base.GetAnalyzerOptions(project), project.Solution); #endif protected override Diagnostic? TrySelectDiagnosticToFix(ImmutableArray<Diagnostic> fixableDiagnostics) { return DiagnosticSelector?.Invoke(fixableDiagnostics) ?? base.TrySelectDiagnosticToFix(fixableDiagnostics); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .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.Net; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Testing.Verifiers; using Microsoft.CodeAnalysis.VisualBasic; using Microsoft.CodeAnalysis.VisualBasic.Testing; using Xunit; #if !CODE_STYLE using Roslyn.Utilities; #endif namespace Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions { public static partial class VisualBasicCodeFixVerifier<TAnalyzer, TCodeFix> where TAnalyzer : DiagnosticAnalyzer, new() where TCodeFix : CodeFixProvider, new() { public class Test : VisualBasicCodeFixTest<TAnalyzer, TCodeFix, XUnitVerifier> { private readonly SharedVerifierState _sharedState; static Test() { // If we have outdated defaults from the host unit test application targeting an older .NET Framework, use more // reasonable TLS protocol version for outgoing connections. #pragma warning disable CA5364 // Do Not Use Deprecated Security Protocols #pragma warning disable CS0618 // Type or member is obsolete if (ServicePointManager.SecurityProtocol == (SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls)) #pragma warning restore CS0618 // Type or member is obsolete #pragma warning restore CA5364 // Do Not Use Deprecated Security Protocols { ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; } } public Test() { _sharedState = new SharedVerifierState(this, DefaultFileExt); MarkupOptions = Testing.MarkupOptions.UseFirstDescriptor; SolutionTransforms.Add((solution, projectId) => { var parseOptions = (VisualBasicParseOptions)solution.GetProject(projectId)!.ParseOptions!; solution = solution.WithProjectParseOptions(projectId, parseOptions.WithLanguageVersion(LanguageVersion)); return solution; }); } /// <summary> /// Gets or sets the language version to use for the test. The default value is /// <see cref="LanguageVersion.VisualBasic16"/>. /// </summary> public LanguageVersion LanguageVersion { get; set; } = LanguageVersion.VisualBasic16; /// <inheritdoc cref="SharedVerifierState.Options"/> internal OptionsCollection Options => _sharedState.Options; /// <inheritdoc cref="SharedVerifierState.EditorConfig"/> public string? EditorConfig { get => _sharedState.EditorConfig; set => _sharedState.EditorConfig = value; } public Func<ImmutableArray<Diagnostic>, Diagnostic?>? DiagnosticSelector { get; set; } protected override async Task RunImplAsync(CancellationToken cancellationToken = default) { if (DiagnosticSelector is object) { Assert.True(CodeFixTestBehaviors.HasFlag(Testing.CodeFixTestBehaviors.FixOne), $"'{nameof(DiagnosticSelector)}' can only be used with '{nameof(Testing.CodeFixTestBehaviors)}.{nameof(Testing.CodeFixTestBehaviors.FixOne)}'"); } _sharedState.Apply(); await base.RunImplAsync(cancellationToken); } #if !CODE_STYLE protected override AnalyzerOptions GetAnalyzerOptions(Project project) => new WorkspaceAnalyzerOptions(base.GetAnalyzerOptions(project), project.Solution); #endif protected override Diagnostic? TrySelectDiagnosticToFix(ImmutableArray<Diagnostic> fixableDiagnostics) { return DiagnosticSelector?.Invoke(fixableDiagnostics) ?? base.TrySelectDiagnosticToFix(fixableDiagnostics); } } } }
-1
dotnet/roslyn
55,138
Avoid cancellation exceptions in intermediate operations
Addresses the following exceptions: ![image](https://user-images.githubusercontent.com/1408396/127185947-8a005aea-ae1c-4755-bf0f-21dfb8101352.png)
sharwell
2021-07-27T15:51:28Z
2021-07-27T21:36:45Z
3d8acbd585a75e9cdb3509623bf6c39ceb46b2c2
719d4ffa2be734463e5d7d4d74b23b8006fd7727
Avoid cancellation exceptions in intermediate operations. Addresses the following exceptions: ![image](https://user-images.githubusercontent.com/1408396/127185947-8a005aea-ae1c-4755-bf0f-21dfb8101352.png)
./src/EditorFeatures/Core.Cocoa/Snippets/CSharpSnippets/SnippetCommandHandler.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Commanding; using Microsoft.VisualStudio.Language.Intellisense.AsyncCompletion; using Microsoft.VisualStudio.LanguageServices.Implementation.Snippets; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Text.Editor.Commanding.Commands; using Microsoft.VisualStudio.Text.Editor.Expansion; using Microsoft.VisualStudio.UI; using Microsoft.VisualStudio.Utilities; namespace Microsoft.VisualStudio.LanguageServices.CSharp.Snippets { [Export(typeof(ICommandHandler))] [ContentType(CodeAnalysis.Editor.ContentTypeNames.CSharpContentType)] [Name("CSharp Snippets")] [Order(After = PredefinedCompletionNames.CompletionCommandHandler)] [Order(After = CodeAnalysis.Editor.PredefinedCommandHandlerNames.SignatureHelpAfterCompletion)] internal sealed class SnippetCommandHandler : AbstractSnippetCommandHandler, ICommandHandler<SurroundWithCommandArgs> { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public SnippetCommandHandler(IThreadingContext threadingContext, IExpansionServiceProvider expansionServiceProvider, IExpansionManager expansionManager) : base(threadingContext, expansionServiceProvider, expansionManager) { } public bool ExecuteCommand(SurroundWithCommandArgs args, CommandExecutionContext context) { AssertIsForeground(); if (!AreSnippetsEnabled(args)) { return false; } return TryInvokeInsertionUI(args.TextView, args.SubjectBuffer, surroundWith: true); } public CommandState GetCommandState(SurroundWithCommandArgs args) { AssertIsForeground(); if (!AreSnippetsEnabled(args)) { return CommandState.Unspecified; } if (!CodeAnalysis.Workspace.TryGetWorkspace(args.SubjectBuffer.AsTextContainer(), out var workspace)) { return CommandState.Unspecified; } if (!workspace.CanApplyChange(ApplyChangesKind.ChangeDocument)) { return CommandState.Unspecified; } return CommandState.Available; } protected override AbstractSnippetExpansionClient GetSnippetExpansionClient(ITextView textView, ITextBuffer subjectBuffer) { if (!textView.Properties.TryGetProperty(typeof(AbstractSnippetExpansionClient), out AbstractSnippetExpansionClient expansionClient)) { expansionClient = new SnippetExpansionClient(ThreadingContext, subjectBuffer.ContentType, textView, subjectBuffer, ExpansionServiceProvider); textView.Properties.AddProperty(typeof(AbstractSnippetExpansionClient), expansionClient); } return expansionClient; } protected override bool TryInvokeInsertionUI(ITextView textView, ITextBuffer subjectBuffer, bool surroundWith = false) { ExpansionServiceProvider.GetExpansionService(textView).InvokeInsertionUI( GetSnippetExpansionClient(textView, subjectBuffer), subjectBuffer.ContentType, types: surroundWith ? new[] { "SurroundsWith" } : new[] { "Expansion", "SurroundsWith" }, includeNullType: true, kinds: null, includeNullKind: false, prefixText: surroundWith ? GettextCatalog.GetString("Surround With") : GettextCatalog.GetString("Insert Snippet"), completionChar: null); return true; } protected override bool IsSnippetExpansionContext(Document document, int startPosition, CancellationToken cancellationToken) { var syntaxTree = document.GetRequiredSyntaxTreeSynchronously(cancellationToken); var token = syntaxTree.GetRoot(cancellationToken).FindToken(startPosition); var trivia = syntaxTree.GetRoot(cancellationToken).FindTrivia(startPosition); return !(trivia.IsKind(SyntaxKind.MultiLineCommentTrivia) || trivia.IsKind(SyntaxKind.SingleLineCommentTrivia) || token.IsKind(SyntaxKind.StringLiteralToken)); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .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.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Commanding; using Microsoft.VisualStudio.Language.Intellisense.AsyncCompletion; using Microsoft.VisualStudio.LanguageServices.Implementation.Snippets; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Text.Editor.Commanding.Commands; using Microsoft.VisualStudio.Text.Editor.Expansion; using Microsoft.VisualStudio.UI; using Microsoft.VisualStudio.Utilities; namespace Microsoft.VisualStudio.LanguageServices.CSharp.Snippets { [Export(typeof(ICommandHandler))] [ContentType(CodeAnalysis.Editor.ContentTypeNames.CSharpContentType)] [Name("CSharp Snippets")] [Order(After = PredefinedCompletionNames.CompletionCommandHandler)] [Order(After = CodeAnalysis.Editor.PredefinedCommandHandlerNames.SignatureHelpAfterCompletion)] internal sealed class SnippetCommandHandler : AbstractSnippetCommandHandler, ICommandHandler<SurroundWithCommandArgs> { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public SnippetCommandHandler(IThreadingContext threadingContext, IExpansionServiceProvider expansionServiceProvider, IExpansionManager expansionManager) : base(threadingContext, expansionServiceProvider, expansionManager) { } public bool ExecuteCommand(SurroundWithCommandArgs args, CommandExecutionContext context) { AssertIsForeground(); if (!AreSnippetsEnabled(args)) { return false; } return TryInvokeInsertionUI(args.TextView, args.SubjectBuffer, surroundWith: true); } public CommandState GetCommandState(SurroundWithCommandArgs args) { AssertIsForeground(); if (!AreSnippetsEnabled(args)) { return CommandState.Unspecified; } if (!CodeAnalysis.Workspace.TryGetWorkspace(args.SubjectBuffer.AsTextContainer(), out var workspace)) { return CommandState.Unspecified; } if (!workspace.CanApplyChange(ApplyChangesKind.ChangeDocument)) { return CommandState.Unspecified; } return CommandState.Available; } protected override AbstractSnippetExpansionClient GetSnippetExpansionClient(ITextView textView, ITextBuffer subjectBuffer) { if (!textView.Properties.TryGetProperty(typeof(AbstractSnippetExpansionClient), out AbstractSnippetExpansionClient expansionClient)) { expansionClient = new SnippetExpansionClient(ThreadingContext, subjectBuffer.ContentType, textView, subjectBuffer, ExpansionServiceProvider); textView.Properties.AddProperty(typeof(AbstractSnippetExpansionClient), expansionClient); } return expansionClient; } protected override bool TryInvokeInsertionUI(ITextView textView, ITextBuffer subjectBuffer, bool surroundWith = false) { ExpansionServiceProvider.GetExpansionService(textView).InvokeInsertionUI( GetSnippetExpansionClient(textView, subjectBuffer), subjectBuffer.ContentType, types: surroundWith ? new[] { "SurroundsWith" } : new[] { "Expansion", "SurroundsWith" }, includeNullType: true, kinds: null, includeNullKind: false, prefixText: surroundWith ? GettextCatalog.GetString("Surround With") : GettextCatalog.GetString("Insert Snippet"), completionChar: null); return true; } protected override bool IsSnippetExpansionContext(Document document, int startPosition, CancellationToken cancellationToken) { var syntaxTree = document.GetRequiredSyntaxTreeSynchronously(cancellationToken); var token = syntaxTree.GetRoot(cancellationToken).FindToken(startPosition); var trivia = syntaxTree.GetRoot(cancellationToken).FindTrivia(startPosition); return !(trivia.IsKind(SyntaxKind.MultiLineCommentTrivia) || trivia.IsKind(SyntaxKind.SingleLineCommentTrivia) || token.IsKind(SyntaxKind.StringLiteralToken)); } } }
-1
dotnet/roslyn
55,138
Avoid cancellation exceptions in intermediate operations
Addresses the following exceptions: ![image](https://user-images.githubusercontent.com/1408396/127185947-8a005aea-ae1c-4755-bf0f-21dfb8101352.png)
sharwell
2021-07-27T15:51:28Z
2021-07-27T21:36:45Z
3d8acbd585a75e9cdb3509623bf6c39ceb46b2c2
719d4ffa2be734463e5d7d4d74b23b8006fd7727
Avoid cancellation exceptions in intermediate operations. Addresses the following exceptions: ![image](https://user-images.githubusercontent.com/1408396/127185947-8a005aea-ae1c-4755-bf0f-21dfb8101352.png)
./src/Compilers/Test/Resources/Core/SymbolsTests/Versioning/V1/C.dll
MZ@ !L!This program cannot be run in DOS mode. $PEL;P!  ^$ @ @$W@`  H.textd  `.rsrc@@@.reloc ` @B@$H  t ( *0 +*( * Z~#Ty TVuXo 21OƁG1rr։_xg/W:)fWOYICMǾ2;kWM`c[8!gOBSJB v4.0.30319l #~x#Strings#US#GUID(#BlobG %3 T4t4P ' X -l '  ' '' .. 2<Module>mscorlibCD`1SystemObject.ctorMainTSystem.Runtime.CompilerServicesCompilationRelaxationsAttributeRuntimeCompatibilityAttributeC.dll NMt>F@-i%z\V4  $$RSA1oO6vk3$jMҭ2eRcعU[IFo2eު3J߾plV nY½%R;=3! K`ay0TWrapNonExceptionThrows,$N$ @$_CorDllMainmscoree.dll% 0HX@,,4VS_VERSION_INFO?DVarFileInfo$TranslationStringFileInfoh000004b0,FileDescription 0FileVersion1.0.0.0,InternalNameC.dll(LegalCopyright 4OriginalFilenameC.dll4ProductVersion1.0.0.08Assembly Version1.0.0.0 `4
MZ@ !L!This program cannot be run in DOS mode. $PEL;P!  ^$ @ @$W@`  H.textd  `.rsrc@@@.reloc ` @B@$H  t ( *0 +*( * Z~#Ty TVuXo 21OƁG1rr։_xg/W:)fWOYICMǾ2;kWM`c[8!gOBSJB v4.0.30319l #~x#Strings#US#GUID(#BlobG %3 T4t4P ' X -l '  ' '' .. 2<Module>mscorlibCD`1SystemObject.ctorMainTSystem.Runtime.CompilerServicesCompilationRelaxationsAttributeRuntimeCompatibilityAttributeC.dll NMt>F@-i%z\V4  $$RSA1oO6vk3$jMҭ2eRcعU[IFo2eު3J߾plV nY½%R;=3! K`ay0TWrapNonExceptionThrows,$N$ @$_CorDllMainmscoree.dll% 0HX@,,4VS_VERSION_INFO?DVarFileInfo$TranslationStringFileInfoh000004b0,FileDescription 0FileVersion1.0.0.0,InternalNameC.dll(LegalCopyright 4OriginalFilenameC.dll4ProductVersion1.0.0.08Assembly Version1.0.0.0 `4
-1
dotnet/roslyn
55,138
Avoid cancellation exceptions in intermediate operations
Addresses the following exceptions: ![image](https://user-images.githubusercontent.com/1408396/127185947-8a005aea-ae1c-4755-bf0f-21dfb8101352.png)
sharwell
2021-07-27T15:51:28Z
2021-07-27T21:36:45Z
3d8acbd585a75e9cdb3509623bf6c39ceb46b2c2
719d4ffa2be734463e5d7d4d74b23b8006fd7727
Avoid cancellation exceptions in intermediate operations. Addresses the following exceptions: ![image](https://user-images.githubusercontent.com/1408396/127185947-8a005aea-ae1c-4755-bf0f-21dfb8101352.png)
./src/Workspaces/MSBuildTest/Resources/ProjectFiles/CSharp/CSharpProject.csproj
<?xml version="1.0" encoding="utf-8"?> <!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE file in the project root for more information. --> <Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <PropertyGroup> <Configuration Condition="'$(Configuration)' == ''">Debug</Configuration> <Platform Condition="'$(Platform)' == ''">AnyCPU</Platform> <PlatformTarget>AnyCPU</PlatformTarget> <ProductVersion>8.0.30703</ProductVersion> <SchemaVersion>2.0</SchemaVersion> <ProjectGuid>{686DD036-86AA-443E-8A10-DDB43266A8C4}</ProjectGuid> <OutputType>Library</OutputType> <AppDesignerFolder>Properties</AppDesignerFolder> <RootNamespace>CSharpProject</RootNamespace> <AssemblyName>CSharpProject</AssemblyName> <TargetFrameworkVersion>v4.6</TargetFrameworkVersion> <FileAlignment>512</FileAlignment> <AssemblyOriginatorKeyFile>snKey.snk</AssemblyOriginatorKeyFile> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|AnyCPU'"> <DebugSymbols>true</DebugSymbols> <DebugType>full</DebugType> <Optimize>false</Optimize> <OutputPath>bin\Debug\</OutputPath> <DefineConstants>DEBUG;TRACE</DefineConstants> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|AnyCPU'"> <DebugType>pdbonly</DebugType> <Optimize>true</Optimize> <OutputPath>bin\Release\</OutputPath> <DefineConstants>TRACE</DefineConstants> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> </PropertyGroup> <ItemGroup> <Reference Include="Microsoft.CSharp" /> <Reference Include="System" /> <Reference Include="System.Core" /> </ItemGroup> <ItemGroup> <Compile Include="CSharpClass.cs" /> <Compile Include="Properties\AssemblyInfo.cs" /> </ItemGroup> <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" /> <!-- To modify your build process, add your task inside one of the targets below and uncomment it. Other similar extension points exist, see Microsoft.Common.targets. <Target Name="BeforeBuild"> </Target> <Target Name="AfterBuild"> </Target> --> </Project>
<?xml version="1.0" encoding="utf-8"?> <!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE file in the project root for more information. --> <Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <PropertyGroup> <Configuration Condition="'$(Configuration)' == ''">Debug</Configuration> <Platform Condition="'$(Platform)' == ''">AnyCPU</Platform> <PlatformTarget>AnyCPU</PlatformTarget> <ProductVersion>8.0.30703</ProductVersion> <SchemaVersion>2.0</SchemaVersion> <ProjectGuid>{686DD036-86AA-443E-8A10-DDB43266A8C4}</ProjectGuid> <OutputType>Library</OutputType> <AppDesignerFolder>Properties</AppDesignerFolder> <RootNamespace>CSharpProject</RootNamespace> <AssemblyName>CSharpProject</AssemblyName> <TargetFrameworkVersion>v4.6</TargetFrameworkVersion> <FileAlignment>512</FileAlignment> <AssemblyOriginatorKeyFile>snKey.snk</AssemblyOriginatorKeyFile> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|AnyCPU'"> <DebugSymbols>true</DebugSymbols> <DebugType>full</DebugType> <Optimize>false</Optimize> <OutputPath>bin\Debug\</OutputPath> <DefineConstants>DEBUG;TRACE</DefineConstants> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|AnyCPU'"> <DebugType>pdbonly</DebugType> <Optimize>true</Optimize> <OutputPath>bin\Release\</OutputPath> <DefineConstants>TRACE</DefineConstants> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> </PropertyGroup> <ItemGroup> <Reference Include="Microsoft.CSharp" /> <Reference Include="System" /> <Reference Include="System.Core" /> </ItemGroup> <ItemGroup> <Compile Include="CSharpClass.cs" /> <Compile Include="Properties\AssemblyInfo.cs" /> </ItemGroup> <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" /> <!-- To modify your build process, add your task inside one of the targets below and uncomment it. Other similar extension points exist, see Microsoft.Common.targets. <Target Name="BeforeBuild"> </Target> <Target Name="AfterBuild"> </Target> --> </Project>
-1
dotnet/roslyn
55,138
Avoid cancellation exceptions in intermediate operations
Addresses the following exceptions: ![image](https://user-images.githubusercontent.com/1408396/127185947-8a005aea-ae1c-4755-bf0f-21dfb8101352.png)
sharwell
2021-07-27T15:51:28Z
2021-07-27T21:36:45Z
3d8acbd585a75e9cdb3509623bf6c39ceb46b2c2
719d4ffa2be734463e5d7d4d74b23b8006fd7727
Avoid cancellation exceptions in intermediate operations. Addresses the following exceptions: ![image](https://user-images.githubusercontent.com/1408396/127185947-8a005aea-ae1c-4755-bf0f-21dfb8101352.png)
./src/VisualStudio/Xaml/Impl/Features/Diagnostics/XamlDiagnosticSeverity.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace Microsoft.VisualStudio.LanguageServices.Xaml.Features.Diagnostics { internal enum XamlDiagnosticSeverity { /// <summary> /// Represents an error. /// </summary> Error, /// <summary> /// Represent a warning. /// </summary> Warning, /// <summary> /// Represents an informational note. /// </summary> Message, /// <summary> /// Represents a hidden note. /// </summary> Hidden, /// <summary> /// Represents a hinted suggestion. /// </summary> HintedSuggestion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace Microsoft.VisualStudio.LanguageServices.Xaml.Features.Diagnostics { internal enum XamlDiagnosticSeverity { /// <summary> /// Represents an error. /// </summary> Error, /// <summary> /// Represent a warning. /// </summary> Warning, /// <summary> /// Represents an informational note. /// </summary> Message, /// <summary> /// Represents a hidden note. /// </summary> Hidden, /// <summary> /// Represents a hinted suggestion. /// </summary> HintedSuggestion } }
-1
dotnet/roslyn
55,138
Avoid cancellation exceptions in intermediate operations
Addresses the following exceptions: ![image](https://user-images.githubusercontent.com/1408396/127185947-8a005aea-ae1c-4755-bf0f-21dfb8101352.png)
sharwell
2021-07-27T15:51:28Z
2021-07-27T21:36:45Z
3d8acbd585a75e9cdb3509623bf6c39ceb46b2c2
719d4ffa2be734463e5d7d4d74b23b8006fd7727
Avoid cancellation exceptions in intermediate operations. Addresses the following exceptions: ![image](https://user-images.githubusercontent.com/1408396/127185947-8a005aea-ae1c-4755-bf0f-21dfb8101352.png)
./src/Analyzers/CSharp/Tests/OrderModifiers/OrderModifiersTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.OrderModifiers; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; using Xunit.Abstractions; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.OrderModifiers { public class OrderModifiersTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest { public OrderModifiersTests(ITestOutputHelper logger) : base(logger) { } internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace) => (new CSharpOrderModifiersDiagnosticAnalyzer(), new CSharpOrderModifiersCodeFixProvider()); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsOrderModifiers)] public async Task TestClass() { await TestInRegularAndScript1Async( @"[|static|] internal class C { }", @"internal static class C { }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsOrderModifiers)] public async Task TestStruct() { await TestInRegularAndScript1Async( @"[|unsafe|] public struct C { }", @"public unsafe struct C { }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsOrderModifiers)] public async Task TestInterface() { await TestInRegularAndScript1Async( @"[|unsafe|] public interface C { }", @"public unsafe interface C { }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsOrderModifiers)] public async Task TestEnum() { await TestInRegularAndScript1Async( @"[|internal|] protected enum C { }", @"protected internal enum C { }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsOrderModifiers)] public async Task TestDelegate() { await TestInRegularAndScript1Async( @"[|unsafe|] public delegate void D();", @"public unsafe delegate void D();"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsOrderModifiers)] public async Task TestMethod() { await TestInRegularAndScript1Async( @"class C { [|unsafe|] public void M() { } }", @"class C { public unsafe void M() { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsOrderModifiers)] public async Task TestField() { await TestInRegularAndScript1Async( @"class C { [|unsafe|] public int a; }", @"class C { public unsafe int a; }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsOrderModifiers)] public async Task TestConstructor() { await TestInRegularAndScript1Async( @"class C { [|unsafe|] public C() { } }", @"class C { public unsafe C() { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsOrderModifiers)] public async Task TestProperty() { await TestInRegularAndScript1Async( @"class C { [|unsafe|] public int P { get; } }", @"class C { public unsafe int P { get; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsOrderModifiers)] public async Task TestAccessor() { await TestInRegularAndScript1Async( @"class C { int P { [|internal|] protected get; } }", @"class C { int P { protected internal get; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsOrderModifiers)] public async Task TestPropertyEvent() { await TestInRegularAndScript1Async( @"class C { [|internal|] protected event Action P { add { } remove { } } }", @"class C { protected internal event Action P { add { } remove { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsOrderModifiers)] public async Task TestFieldEvent() { await TestInRegularAndScript1Async( @"class C { [|internal|] protected event Action P; }", @"class C { protected internal event Action P; }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsOrderModifiers)] public async Task TestOperator() { await TestInRegularAndScript1Async( @"class C { [|static|] public C operator +(C c1, C c2) { } }", @"class C { public static C operator +(C c1, C c2) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsOrderModifiers)] public async Task TestConversionOperator() { await TestInRegularAndScript1Async( @"class C { [|static|] public implicit operator bool(C c1) { } }", @"class C { public static implicit operator bool(C c1) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsOrderModifiers)] public async Task TestFixAll1() { await TestInRegularAndScript1Async( @"{|FixAllInDocument:static|} internal class C { static internal class Nested { } }", @"internal static class C { internal static class Nested { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsOrderModifiers)] public async Task TestFixAll2() { await TestInRegularAndScript1Async( @"static internal class C { {|FixAllInDocument:static|} internal class Nested { } }", @"internal static class C { internal static class Nested { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsOrderModifiers)] public async Task TestTrivia1() { await TestInRegularAndScript1Async( @" /// Doc comment [|static|] internal class C { }", @" /// Doc comment internal static class C { }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsOrderModifiers)] public async Task TestTrivia2() { await TestInRegularAndScript1Async( @" /* start */ [|static|] /* middle */ internal /* end */ class C { }", @" /* start */ internal /* middle */ static /* end */ class C { }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsOrderModifiers)] public async Task TestTrivia3() { await TestInRegularAndScript1Async( @" #if true [|static|] internal class C { } #endif ", @" #if true internal static class C { } #endif "); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsOrderModifiers)] public async Task PartialAtTheEndClass1() { await TestInRegularAndScript1Async( @"[|partial|] public class C { }", @"public partial class C { }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsOrderModifiers)] public async Task PartialAtTheEndClass2() { await TestInRegularAndScript1Async( @"[|partial|] abstract class C { }", @"abstract partial class C { }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsOrderModifiers)] public async Task PartialAtTheEndClass3() { await TestInRegularAndScript1Async( @"[|partial|] sealed class C { }", @"sealed partial class C { }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsOrderModifiers)] public async Task PartialAtTheEndClass4() { await TestInRegularAndScript1Async( @"[|partial|] static class C { }", @"static partial class C { }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsOrderModifiers)] public async Task PartialAtTheEndClass5() { await TestInRegularAndScript1Async( @"[|partial|] unsafe class C { }", @"unsafe partial class C { }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsOrderModifiers)] public async Task PartialAtTheEndStruct1() { await TestInRegularAndScript1Async( @"[|partial|] public struct S { }", @"public partial struct S { }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsOrderModifiers)] public async Task PartialAtTheEndStruct2() { await TestInRegularAndScript1Async( @"[|partial|] unsafe struct S { }", @"unsafe partial struct S { }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsOrderModifiers)] public async Task PartialAtTheEndInterface() { await TestInRegularAndScript1Async( @"[|partial|] public interface I { }", @"public partial interface I { }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsOrderModifiers)] public async Task PartialAtTheEndMethod1() { await TestInRegularAndScript1Async( @"partial class C { [|partial|] static void M(); }", @"partial class C { static partial void M(); }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsOrderModifiers)] public async Task PartialAtTheEndMethod2() { await TestInRegularAndScript1Async( @"partial class C { [|partial|] unsafe void M(); }", @"partial class C { unsafe partial void M(); }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsOrderModifiers)] [WorkItem(52297, "https://github.com/dotnet/roslyn/pull/52297")] public async Task TestInLocalFunction() { // Not handled for performance reason. await TestMissingInRegularAndScriptAsync( @"class C { public static async void M() { [|async|] static void Local() { } } }"); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.OrderModifiers; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; using Xunit.Abstractions; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.OrderModifiers { public class OrderModifiersTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest { public OrderModifiersTests(ITestOutputHelper logger) : base(logger) { } internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace) => (new CSharpOrderModifiersDiagnosticAnalyzer(), new CSharpOrderModifiersCodeFixProvider()); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsOrderModifiers)] public async Task TestClass() { await TestInRegularAndScript1Async( @"[|static|] internal class C { }", @"internal static class C { }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsOrderModifiers)] public async Task TestStruct() { await TestInRegularAndScript1Async( @"[|unsafe|] public struct C { }", @"public unsafe struct C { }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsOrderModifiers)] public async Task TestInterface() { await TestInRegularAndScript1Async( @"[|unsafe|] public interface C { }", @"public unsafe interface C { }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsOrderModifiers)] public async Task TestEnum() { await TestInRegularAndScript1Async( @"[|internal|] protected enum C { }", @"protected internal enum C { }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsOrderModifiers)] public async Task TestDelegate() { await TestInRegularAndScript1Async( @"[|unsafe|] public delegate void D();", @"public unsafe delegate void D();"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsOrderModifiers)] public async Task TestMethod() { await TestInRegularAndScript1Async( @"class C { [|unsafe|] public void M() { } }", @"class C { public unsafe void M() { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsOrderModifiers)] public async Task TestField() { await TestInRegularAndScript1Async( @"class C { [|unsafe|] public int a; }", @"class C { public unsafe int a; }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsOrderModifiers)] public async Task TestConstructor() { await TestInRegularAndScript1Async( @"class C { [|unsafe|] public C() { } }", @"class C { public unsafe C() { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsOrderModifiers)] public async Task TestProperty() { await TestInRegularAndScript1Async( @"class C { [|unsafe|] public int P { get; } }", @"class C { public unsafe int P { get; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsOrderModifiers)] public async Task TestAccessor() { await TestInRegularAndScript1Async( @"class C { int P { [|internal|] protected get; } }", @"class C { int P { protected internal get; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsOrderModifiers)] public async Task TestPropertyEvent() { await TestInRegularAndScript1Async( @"class C { [|internal|] protected event Action P { add { } remove { } } }", @"class C { protected internal event Action P { add { } remove { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsOrderModifiers)] public async Task TestFieldEvent() { await TestInRegularAndScript1Async( @"class C { [|internal|] protected event Action P; }", @"class C { protected internal event Action P; }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsOrderModifiers)] public async Task TestOperator() { await TestInRegularAndScript1Async( @"class C { [|static|] public C operator +(C c1, C c2) { } }", @"class C { public static C operator +(C c1, C c2) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsOrderModifiers)] public async Task TestConversionOperator() { await TestInRegularAndScript1Async( @"class C { [|static|] public implicit operator bool(C c1) { } }", @"class C { public static implicit operator bool(C c1) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsOrderModifiers)] public async Task TestFixAll1() { await TestInRegularAndScript1Async( @"{|FixAllInDocument:static|} internal class C { static internal class Nested { } }", @"internal static class C { internal static class Nested { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsOrderModifiers)] public async Task TestFixAll2() { await TestInRegularAndScript1Async( @"static internal class C { {|FixAllInDocument:static|} internal class Nested { } }", @"internal static class C { internal static class Nested { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsOrderModifiers)] public async Task TestTrivia1() { await TestInRegularAndScript1Async( @" /// Doc comment [|static|] internal class C { }", @" /// Doc comment internal static class C { }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsOrderModifiers)] public async Task TestTrivia2() { await TestInRegularAndScript1Async( @" /* start */ [|static|] /* middle */ internal /* end */ class C { }", @" /* start */ internal /* middle */ static /* end */ class C { }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsOrderModifiers)] public async Task TestTrivia3() { await TestInRegularAndScript1Async( @" #if true [|static|] internal class C { } #endif ", @" #if true internal static class C { } #endif "); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsOrderModifiers)] public async Task PartialAtTheEndClass1() { await TestInRegularAndScript1Async( @"[|partial|] public class C { }", @"public partial class C { }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsOrderModifiers)] public async Task PartialAtTheEndClass2() { await TestInRegularAndScript1Async( @"[|partial|] abstract class C { }", @"abstract partial class C { }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsOrderModifiers)] public async Task PartialAtTheEndClass3() { await TestInRegularAndScript1Async( @"[|partial|] sealed class C { }", @"sealed partial class C { }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsOrderModifiers)] public async Task PartialAtTheEndClass4() { await TestInRegularAndScript1Async( @"[|partial|] static class C { }", @"static partial class C { }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsOrderModifiers)] public async Task PartialAtTheEndClass5() { await TestInRegularAndScript1Async( @"[|partial|] unsafe class C { }", @"unsafe partial class C { }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsOrderModifiers)] public async Task PartialAtTheEndStruct1() { await TestInRegularAndScript1Async( @"[|partial|] public struct S { }", @"public partial struct S { }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsOrderModifiers)] public async Task PartialAtTheEndStruct2() { await TestInRegularAndScript1Async( @"[|partial|] unsafe struct S { }", @"unsafe partial struct S { }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsOrderModifiers)] public async Task PartialAtTheEndInterface() { await TestInRegularAndScript1Async( @"[|partial|] public interface I { }", @"public partial interface I { }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsOrderModifiers)] public async Task PartialAtTheEndMethod1() { await TestInRegularAndScript1Async( @"partial class C { [|partial|] static void M(); }", @"partial class C { static partial void M(); }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsOrderModifiers)] public async Task PartialAtTheEndMethod2() { await TestInRegularAndScript1Async( @"partial class C { [|partial|] unsafe void M(); }", @"partial class C { unsafe partial void M(); }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsOrderModifiers)] [WorkItem(52297, "https://github.com/dotnet/roslyn/pull/52297")] public async Task TestInLocalFunction() { // Not handled for performance reason. await TestMissingInRegularAndScriptAsync( @"class C { public static async void M() { [|async|] static void Local() { } } }"); } } }
-1
dotnet/roslyn
55,138
Avoid cancellation exceptions in intermediate operations
Addresses the following exceptions: ![image](https://user-images.githubusercontent.com/1408396/127185947-8a005aea-ae1c-4755-bf0f-21dfb8101352.png)
sharwell
2021-07-27T15:51:28Z
2021-07-27T21:36:45Z
3d8acbd585a75e9cdb3509623bf6c39ceb46b2c2
719d4ffa2be734463e5d7d4d74b23b8006fd7727
Avoid cancellation exceptions in intermediate operations. Addresses the following exceptions: ![image](https://user-images.githubusercontent.com/1408396/127185947-8a005aea-ae1c-4755-bf0f-21dfb8101352.png)
./src/Compilers/CSharp/Portable/Symbols/Source/SourceParameterSymbol.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Threading; using Microsoft.CodeAnalysis.CSharp.Syntax; namespace Microsoft.CodeAnalysis.CSharp.Symbols { /// <summary> /// Base class for parameters can be referred to from source code. /// </summary> /// <remarks> /// These parameters can potentially be targeted by an attribute specified in source code. /// As an optimization we distinguish simple parameters (no attributes, no modifiers, etc.) and complex parameters. /// </remarks> internal abstract class SourceParameterSymbol : SourceParameterSymbolBase { protected SymbolCompletionState state; protected readonly TypeWithAnnotations parameterType; private readonly string _name; private readonly ImmutableArray<Location> _locations; private readonly RefKind _refKind; public static SourceParameterSymbol Create( Binder context, Symbol owner, TypeWithAnnotations parameterType, ParameterSyntax syntax, RefKind refKind, SyntaxToken identifier, int ordinal, bool isParams, bool isExtensionMethodThis, bool addRefReadOnlyModifier, BindingDiagnosticBag declarationDiagnostics) { Debug.Assert(!(owner is LambdaSymbol)); // therefore we don't need to deal with discard parameters var name = identifier.ValueText; var locations = ImmutableArray.Create<Location>(new SourceLocation(identifier)); if (isParams) { // touch the constructor in order to generate proper use-site diagnostics Binder.ReportUseSiteDiagnosticForSynthesizedAttribute(context.Compilation, WellKnownMember.System_ParamArrayAttribute__ctor, declarationDiagnostics, identifier.Parent.GetLocation()); } ImmutableArray<CustomModifier> inModifiers = ParameterHelpers.ConditionallyCreateInModifiers(refKind, addRefReadOnlyModifier, context, declarationDiagnostics, syntax); if (!inModifiers.IsDefaultOrEmpty) { return new SourceComplexParameterSymbolWithCustomModifiersPrecedingByRef( owner, ordinal, parameterType, refKind, inModifiers, name, locations, syntax.GetReference(), isParams, isExtensionMethodThis); } if (!isParams && !isExtensionMethodThis && (syntax.Default == null) && (syntax.AttributeLists.Count == 0) && !owner.IsPartialMethod()) { return new SourceSimpleParameterSymbol(owner, parameterType, ordinal, refKind, name, locations); } return new SourceComplexParameterSymbol( owner, ordinal, parameterType, refKind, name, locations, syntax.GetReference(), isParams, isExtensionMethodThis); } protected SourceParameterSymbol( Symbol owner, TypeWithAnnotations parameterType, int ordinal, RefKind refKind, string name, ImmutableArray<Location> locations) : base(owner, ordinal) { #if DEBUG foreach (var location in locations) { Debug.Assert(location != null); } #endif Debug.Assert((owner.Kind == SymbolKind.Method) || (owner.Kind == SymbolKind.Property)); this.parameterType = parameterType; _refKind = refKind; _name = name; _locations = locations; } internal override ParameterSymbol WithCustomModifiersAndParams(TypeSymbol newType, ImmutableArray<CustomModifier> newCustomModifiers, ImmutableArray<CustomModifier> newRefCustomModifiers, bool newIsParams) { return WithCustomModifiersAndParamsCore(newType, newCustomModifiers, newRefCustomModifiers, newIsParams); } internal SourceParameterSymbol WithCustomModifiersAndParamsCore(TypeSymbol newType, ImmutableArray<CustomModifier> newCustomModifiers, ImmutableArray<CustomModifier> newRefCustomModifiers, bool newIsParams) { newType = CustomModifierUtils.CopyTypeCustomModifiers(newType, this.Type, this.ContainingAssembly); TypeWithAnnotations newTypeWithModifiers = this.TypeWithAnnotations.WithTypeAndModifiers(newType, newCustomModifiers); if (newRefCustomModifiers.IsEmpty) { return new SourceComplexParameterSymbol( this.ContainingSymbol, this.Ordinal, newTypeWithModifiers, _refKind, _name, _locations, this.SyntaxReference, newIsParams, this.IsExtensionMethodThis); } // Local functions should never have custom modifiers Debug.Assert(!(ContainingSymbol is LocalFunctionSymbol)); return new SourceComplexParameterSymbolWithCustomModifiersPrecedingByRef( this.ContainingSymbol, this.Ordinal, newTypeWithModifiers, _refKind, newRefCustomModifiers, _name, _locations, this.SyntaxReference, newIsParams, this.IsExtensionMethodThis); } internal sealed override bool RequiresCompletion { get { return true; } } internal sealed override bool HasComplete(CompletionPart part) { return state.HasComplete(part); } internal override void ForceComplete(SourceLocation locationOpt, CancellationToken cancellationToken) { state.DefaultForceComplete(this, cancellationToken); } /// <summary> /// True if the parameter is marked by <see cref="System.Runtime.InteropServices.OptionalAttribute"/>. /// </summary> internal abstract bool HasOptionalAttribute { get; } /// <summary> /// True if the parameter has default argument syntax. /// </summary> internal abstract bool HasDefaultArgumentSyntax { get; } internal abstract SyntaxList<AttributeListSyntax> AttributeDeclarationList { get; } internal abstract CustomAttributesBag<CSharpAttributeData> GetAttributesBag(); /// <summary> /// Gets the attributes applied on this symbol. /// Returns an empty array if there are no attributes. /// </summary> public sealed override ImmutableArray<CSharpAttributeData> GetAttributes() { return this.GetAttributesBag().Attributes; } /// <summary> /// The declaration diagnostics for a parameter depend on the containing symbol. /// For instance, if the containing symbol is a method the declaration diagnostics /// go on the compilation, but if it is a local function it is part of the local /// function's declaration diagnostics. /// </summary> internal override void AddDeclarationDiagnostics(BindingDiagnosticBag diagnostics) => ContainingSymbol.AddDeclarationDiagnostics(diagnostics); internal abstract SyntaxReference SyntaxReference { get; } internal abstract bool IsExtensionMethodThis { get; } public sealed override RefKind RefKind { get { return _refKind; } } public sealed override string Name { get { return _name; } } public sealed override ImmutableArray<Location> Locations { get { return _locations; } } public sealed override ImmutableArray<SyntaxReference> DeclaringSyntaxReferences { get { return IsImplicitlyDeclared ? ImmutableArray<SyntaxReference>.Empty : GetDeclaringSyntaxReferenceHelper<ParameterSyntax>(_locations); } } public sealed override TypeWithAnnotations TypeWithAnnotations { get { return this.parameterType; } } public override bool IsImplicitlyDeclared { get { // Parameters of accessors are always synthesized. (e.g., parameter of indexer accessors). // The non-synthesized accessors are on the property/event itself. MethodSymbol owningMethod = ContainingSymbol as MethodSymbol; return (object)owningMethod != null && owningMethod.IsAccessor(); } } internal override bool IsMetadataIn => RefKind == RefKind.In; internal override bool IsMetadataOut => RefKind == RefKind.Out; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Threading; using Microsoft.CodeAnalysis.CSharp.Syntax; namespace Microsoft.CodeAnalysis.CSharp.Symbols { /// <summary> /// Base class for parameters can be referred to from source code. /// </summary> /// <remarks> /// These parameters can potentially be targeted by an attribute specified in source code. /// As an optimization we distinguish simple parameters (no attributes, no modifiers, etc.) and complex parameters. /// </remarks> internal abstract class SourceParameterSymbol : SourceParameterSymbolBase { protected SymbolCompletionState state; protected readonly TypeWithAnnotations parameterType; private readonly string _name; private readonly ImmutableArray<Location> _locations; private readonly RefKind _refKind; public static SourceParameterSymbol Create( Binder context, Symbol owner, TypeWithAnnotations parameterType, ParameterSyntax syntax, RefKind refKind, SyntaxToken identifier, int ordinal, bool isParams, bool isExtensionMethodThis, bool addRefReadOnlyModifier, BindingDiagnosticBag declarationDiagnostics) { Debug.Assert(!(owner is LambdaSymbol)); // therefore we don't need to deal with discard parameters var name = identifier.ValueText; var locations = ImmutableArray.Create<Location>(new SourceLocation(identifier)); if (isParams) { // touch the constructor in order to generate proper use-site diagnostics Binder.ReportUseSiteDiagnosticForSynthesizedAttribute(context.Compilation, WellKnownMember.System_ParamArrayAttribute__ctor, declarationDiagnostics, identifier.Parent.GetLocation()); } ImmutableArray<CustomModifier> inModifiers = ParameterHelpers.ConditionallyCreateInModifiers(refKind, addRefReadOnlyModifier, context, declarationDiagnostics, syntax); if (!inModifiers.IsDefaultOrEmpty) { return new SourceComplexParameterSymbolWithCustomModifiersPrecedingByRef( owner, ordinal, parameterType, refKind, inModifiers, name, locations, syntax.GetReference(), isParams, isExtensionMethodThis); } if (!isParams && !isExtensionMethodThis && (syntax.Default == null) && (syntax.AttributeLists.Count == 0) && !owner.IsPartialMethod()) { return new SourceSimpleParameterSymbol(owner, parameterType, ordinal, refKind, name, locations); } return new SourceComplexParameterSymbol( owner, ordinal, parameterType, refKind, name, locations, syntax.GetReference(), isParams, isExtensionMethodThis); } protected SourceParameterSymbol( Symbol owner, TypeWithAnnotations parameterType, int ordinal, RefKind refKind, string name, ImmutableArray<Location> locations) : base(owner, ordinal) { #if DEBUG foreach (var location in locations) { Debug.Assert(location != null); } #endif Debug.Assert((owner.Kind == SymbolKind.Method) || (owner.Kind == SymbolKind.Property)); this.parameterType = parameterType; _refKind = refKind; _name = name; _locations = locations; } internal override ParameterSymbol WithCustomModifiersAndParams(TypeSymbol newType, ImmutableArray<CustomModifier> newCustomModifiers, ImmutableArray<CustomModifier> newRefCustomModifiers, bool newIsParams) { return WithCustomModifiersAndParamsCore(newType, newCustomModifiers, newRefCustomModifiers, newIsParams); } internal SourceParameterSymbol WithCustomModifiersAndParamsCore(TypeSymbol newType, ImmutableArray<CustomModifier> newCustomModifiers, ImmutableArray<CustomModifier> newRefCustomModifiers, bool newIsParams) { newType = CustomModifierUtils.CopyTypeCustomModifiers(newType, this.Type, this.ContainingAssembly); TypeWithAnnotations newTypeWithModifiers = this.TypeWithAnnotations.WithTypeAndModifiers(newType, newCustomModifiers); if (newRefCustomModifiers.IsEmpty) { return new SourceComplexParameterSymbol( this.ContainingSymbol, this.Ordinal, newTypeWithModifiers, _refKind, _name, _locations, this.SyntaxReference, newIsParams, this.IsExtensionMethodThis); } // Local functions should never have custom modifiers Debug.Assert(!(ContainingSymbol is LocalFunctionSymbol)); return new SourceComplexParameterSymbolWithCustomModifiersPrecedingByRef( this.ContainingSymbol, this.Ordinal, newTypeWithModifiers, _refKind, newRefCustomModifiers, _name, _locations, this.SyntaxReference, newIsParams, this.IsExtensionMethodThis); } internal sealed override bool RequiresCompletion { get { return true; } } internal sealed override bool HasComplete(CompletionPart part) { return state.HasComplete(part); } internal override void ForceComplete(SourceLocation locationOpt, CancellationToken cancellationToken) { state.DefaultForceComplete(this, cancellationToken); } /// <summary> /// True if the parameter is marked by <see cref="System.Runtime.InteropServices.OptionalAttribute"/>. /// </summary> internal abstract bool HasOptionalAttribute { get; } /// <summary> /// True if the parameter has default argument syntax. /// </summary> internal abstract bool HasDefaultArgumentSyntax { get; } internal abstract SyntaxList<AttributeListSyntax> AttributeDeclarationList { get; } internal abstract CustomAttributesBag<CSharpAttributeData> GetAttributesBag(); /// <summary> /// Gets the attributes applied on this symbol. /// Returns an empty array if there are no attributes. /// </summary> public sealed override ImmutableArray<CSharpAttributeData> GetAttributes() { return this.GetAttributesBag().Attributes; } /// <summary> /// The declaration diagnostics for a parameter depend on the containing symbol. /// For instance, if the containing symbol is a method the declaration diagnostics /// go on the compilation, but if it is a local function it is part of the local /// function's declaration diagnostics. /// </summary> internal override void AddDeclarationDiagnostics(BindingDiagnosticBag diagnostics) => ContainingSymbol.AddDeclarationDiagnostics(diagnostics); internal abstract SyntaxReference SyntaxReference { get; } internal abstract bool IsExtensionMethodThis { get; } public sealed override RefKind RefKind { get { return _refKind; } } public sealed override string Name { get { return _name; } } public sealed override ImmutableArray<Location> Locations { get { return _locations; } } public sealed override ImmutableArray<SyntaxReference> DeclaringSyntaxReferences { get { return IsImplicitlyDeclared ? ImmutableArray<SyntaxReference>.Empty : GetDeclaringSyntaxReferenceHelper<ParameterSyntax>(_locations); } } public sealed override TypeWithAnnotations TypeWithAnnotations { get { return this.parameterType; } } public override bool IsImplicitlyDeclared { get { // Parameters of accessors are always synthesized. (e.g., parameter of indexer accessors). // The non-synthesized accessors are on the property/event itself. MethodSymbol owningMethod = ContainingSymbol as MethodSymbol; return (object)owningMethod != null && owningMethod.IsAccessor(); } } internal override bool IsMetadataIn => RefKind == RefKind.In; internal override bool IsMetadataOut => RefKind == RefKind.Out; } }
-1
dotnet/roslyn
55,138
Avoid cancellation exceptions in intermediate operations
Addresses the following exceptions: ![image](https://user-images.githubusercontent.com/1408396/127185947-8a005aea-ae1c-4755-bf0f-21dfb8101352.png)
sharwell
2021-07-27T15:51:28Z
2021-07-27T21:36:45Z
3d8acbd585a75e9cdb3509623bf6c39ceb46b2c2
719d4ffa2be734463e5d7d4d74b23b8006fd7727
Avoid cancellation exceptions in intermediate operations. Addresses the following exceptions: ![image](https://user-images.githubusercontent.com/1408396/127185947-8a005aea-ae1c-4755-bf0f-21dfb8101352.png)
./src/EditorFeatures/CSharp/EditorConfigSettings/DataProvider/Formatting/CSharpFormattingSettingsProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Formatting; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.CSharp; using Microsoft.CodeAnalysis.Editor.EditorConfigSettings.Data; using Microsoft.CodeAnalysis.Editor.EditorConfigSettings.DataProvider; using Microsoft.CodeAnalysis.Editor.EditorConfigSettings.Updater; using Microsoft.CodeAnalysis.Options; namespace Microsoft.VisualStudio.LanguageServices.CSharp.EditorConfigSettings.DataProvider.Formatting { internal class CSharpFormattingSettingsProvider : SettingsProviderBase<FormattingSetting, OptionUpdater, IOption2, object> { public CSharpFormattingSettingsProvider(string filePath, OptionUpdater updaterService, Workspace workspace) : base(filePath, updaterService, workspace) { Update(); } protected override void UpdateOptions(AnalyzerConfigOptions editorConfigOptions, OptionSet visualStudioOptions) { var spacingOptions = GetSpacingOptions(editorConfigOptions, visualStudioOptions, SettingsUpdater); AddRange(spacingOptions.ToImmutableArray()); var newLineOptions = GetNewLineOptions(editorConfigOptions, visualStudioOptions, SettingsUpdater); AddRange(newLineOptions.ToImmutableArray()); var indentationOptions = GetIndentationOptions(editorConfigOptions, visualStudioOptions, SettingsUpdater); AddRange(indentationOptions.ToImmutableArray()); var wrappingOptions = GetWrappingOptions(editorConfigOptions, visualStudioOptions, SettingsUpdater); AddRange(wrappingOptions.ToImmutableArray()); } private static IEnumerable<FormattingSetting> GetSpacingOptions(AnalyzerConfigOptions editorConfigOptions, OptionSet visualStudioOptions, OptionUpdater updaterService) { yield return FormattingSetting.Create(CSharpFormattingOptions2.SpacingAfterMethodDeclarationName, CSharpEditorResources.Insert_space_between_method_name_and_its_opening_parenthesis2, editorConfigOptions, visualStudioOptions, updaterService); yield return FormattingSetting.Create(CSharpFormattingOptions2.SpaceWithinMethodDeclarationParenthesis, CSharpEditorResources.Insert_space_within_parameter_list_parentheses, editorConfigOptions, visualStudioOptions, updaterService); yield return FormattingSetting.Create(CSharpFormattingOptions2.SpaceBetweenEmptyMethodDeclarationParentheses, CSharpEditorResources.Insert_space_within_empty_parameter_list_parentheses, editorConfigOptions, visualStudioOptions, updaterService); yield return FormattingSetting.Create(CSharpFormattingOptions2.SpaceAfterMethodCallName, CSharpEditorResources.Insert_space_between_method_name_and_its_opening_parenthesis1, editorConfigOptions, visualStudioOptions, updaterService); yield return FormattingSetting.Create(CSharpFormattingOptions2.SpaceWithinMethodCallParentheses, CSharpEditorResources.Insert_space_within_argument_list_parentheses, editorConfigOptions, visualStudioOptions, updaterService); yield return FormattingSetting.Create(CSharpFormattingOptions2.SpaceBetweenEmptyMethodCallParentheses, CSharpEditorResources.Insert_space_within_empty_argument_list_parentheses, editorConfigOptions, visualStudioOptions, updaterService); yield return FormattingSetting.Create(CSharpFormattingOptions2.SpaceAfterControlFlowStatementKeyword, CSharpEditorResources.Insert_space_after_keywords_in_control_flow_statements, editorConfigOptions, visualStudioOptions, updaterService); yield return FormattingSetting.Create(CSharpFormattingOptions2.SpaceWithinExpressionParentheses, CSharpEditorResources.Insert_space_within_parentheses_of_expressions, editorConfigOptions, visualStudioOptions, updaterService); yield return FormattingSetting.Create(CSharpFormattingOptions2.SpaceWithinCastParentheses, CSharpEditorResources.Insert_space_within_parentheses_of_type_casts, editorConfigOptions, visualStudioOptions, updaterService); yield return FormattingSetting.Create(CSharpFormattingOptions2.SpaceWithinOtherParentheses, CSharpEditorResources.Insert_spaces_within_parentheses_of_control_flow_statements, editorConfigOptions, visualStudioOptions, updaterService); yield return FormattingSetting.Create(CSharpFormattingOptions2.SpaceAfterCast, CSharpEditorResources.Insert_space_after_cast, editorConfigOptions, visualStudioOptions, updaterService); yield return FormattingSetting.Create(CSharpFormattingOptions2.SpacesIgnoreAroundVariableDeclaration, CSharpEditorResources.Ignore_spaces_in_declaration_statements, editorConfigOptions, visualStudioOptions, updaterService); yield return FormattingSetting.Create(CSharpFormattingOptions2.SpaceBeforeOpenSquareBracket, CSharpEditorResources.Insert_space_before_open_square_bracket, editorConfigOptions, visualStudioOptions, updaterService); yield return FormattingSetting.Create(CSharpFormattingOptions2.SpaceBetweenEmptySquareBrackets, CSharpEditorResources.Insert_space_within_empty_square_brackets, editorConfigOptions, visualStudioOptions, updaterService); yield return FormattingSetting.Create(CSharpFormattingOptions2.SpaceWithinSquareBrackets, CSharpEditorResources.Insert_spaces_within_square_brackets, editorConfigOptions, visualStudioOptions, updaterService); yield return FormattingSetting.Create(CSharpFormattingOptions2.SpaceAfterColonInBaseTypeDeclaration, CSharpEditorResources.Insert_space_after_colon_for_base_or_interface_in_type_declaration, editorConfigOptions, visualStudioOptions, updaterService); yield return FormattingSetting.Create(CSharpFormattingOptions2.SpaceAfterComma, CSharpEditorResources.Insert_space_after_comma, editorConfigOptions, visualStudioOptions, updaterService); yield return FormattingSetting.Create(CSharpFormattingOptions2.SpaceAfterDot, CSharpEditorResources.Insert_space_after_dot, editorConfigOptions, visualStudioOptions, updaterService); yield return FormattingSetting.Create(CSharpFormattingOptions2.SpaceAfterSemicolonsInForStatement, CSharpEditorResources.Insert_space_after_semicolon_in_for_statement, editorConfigOptions, visualStudioOptions, updaterService); yield return FormattingSetting.Create(CSharpFormattingOptions2.SpaceBeforeColonInBaseTypeDeclaration, CSharpEditorResources.Insert_space_before_colon_for_base_or_interface_in_type_declaration, editorConfigOptions, visualStudioOptions, updaterService); yield return FormattingSetting.Create(CSharpFormattingOptions2.SpaceBeforeComma, CSharpEditorResources.Insert_space_before_comma, editorConfigOptions, visualStudioOptions, updaterService); yield return FormattingSetting.Create(CSharpFormattingOptions2.SpaceBeforeDot, CSharpEditorResources.Insert_space_before_dot, editorConfigOptions, visualStudioOptions, updaterService); yield return FormattingSetting.Create(CSharpFormattingOptions2.SpaceBeforeSemicolonsInForStatement, CSharpEditorResources.Insert_space_before_semicolon_in_for_statement, editorConfigOptions, visualStudioOptions, updaterService); yield return FormattingSetting.Create(CSharpFormattingOptions2.SpacingAroundBinaryOperator, CSharpEditorResources.Set_spacing_for_operators, editorConfigOptions, visualStudioOptions, updaterService); } private static IEnumerable<FormattingSetting> GetNewLineOptions(AnalyzerConfigOptions editorConfigOptions, OptionSet visualStudioOptions, OptionUpdater updaterService) { yield return FormattingSetting.Create(CSharpFormattingOptions2.NewLinesForBracesInTypes, CSharpEditorResources.Place_open_brace_on_new_line_for_types, editorConfigOptions, visualStudioOptions, updaterService); yield return FormattingSetting.Create(CSharpFormattingOptions2.NewLinesForBracesInMethods, CSharpEditorResources.Place_open_brace_on_new_line_for_methods_local_functions, editorConfigOptions, visualStudioOptions, updaterService); yield return FormattingSetting.Create(CSharpFormattingOptions2.NewLinesForBracesInProperties, CSharpEditorResources.Place_open_brace_on_new_line_for_properties_indexers_and_events, editorConfigOptions, visualStudioOptions, updaterService); yield return FormattingSetting.Create(CSharpFormattingOptions2.NewLinesForBracesInAccessors, CSharpEditorResources.Place_open_brace_on_new_line_for_property_indexer_and_event_accessors, editorConfigOptions, visualStudioOptions, updaterService); yield return FormattingSetting.Create(CSharpFormattingOptions2.NewLinesForBracesInAnonymousMethods, CSharpEditorResources.Place_open_brace_on_new_line_for_anonymous_methods, editorConfigOptions, visualStudioOptions, updaterService); yield return FormattingSetting.Create(CSharpFormattingOptions2.NewLinesForBracesInControlBlocks, CSharpEditorResources.Place_open_brace_on_new_line_for_control_blocks, editorConfigOptions, visualStudioOptions, updaterService); yield return FormattingSetting.Create(CSharpFormattingOptions2.NewLinesForBracesInAnonymousTypes, CSharpEditorResources.Place_open_brace_on_new_line_for_anonymous_types, editorConfigOptions, visualStudioOptions, updaterService); yield return FormattingSetting.Create(CSharpFormattingOptions2.NewLinesForBracesInObjectCollectionArrayInitializers, CSharpEditorResources.Place_open_brace_on_new_line_for_object_collection_array_and_with_initializers, editorConfigOptions, visualStudioOptions, updaterService); yield return FormattingSetting.Create(CSharpFormattingOptions2.NewLinesForBracesInLambdaExpressionBody, CSharpEditorResources.Place_open_brace_on_new_line_for_lambda_expression, editorConfigOptions, visualStudioOptions, updaterService); yield return FormattingSetting.Create(CSharpFormattingOptions2.NewLineForElse, CSharpEditorResources.Place_else_on_new_line, editorConfigOptions, visualStudioOptions, updaterService); yield return FormattingSetting.Create(CSharpFormattingOptions2.NewLineForCatch, CSharpEditorResources.Place_catch_on_new_line, editorConfigOptions, visualStudioOptions, updaterService); yield return FormattingSetting.Create(CSharpFormattingOptions2.NewLineForFinally, CSharpEditorResources.Place_finally_on_new_line, editorConfigOptions, visualStudioOptions, updaterService); yield return FormattingSetting.Create(CSharpFormattingOptions2.NewLineForMembersInObjectInit, CSharpEditorResources.Place_members_in_object_initializers_on_new_line, editorConfigOptions, visualStudioOptions, updaterService); yield return FormattingSetting.Create(CSharpFormattingOptions2.NewLineForMembersInAnonymousTypes, CSharpEditorResources.Place_members_in_anonymous_types_on_new_line, editorConfigOptions, visualStudioOptions, updaterService); yield return FormattingSetting.Create(CSharpFormattingOptions2.NewLineForClausesInQuery, CSharpEditorResources.Place_query_expression_clauses_on_new_line, editorConfigOptions, visualStudioOptions, updaterService); } private static IEnumerable<FormattingSetting> GetIndentationOptions(AnalyzerConfigOptions editorConfigOptions, OptionSet visualStudioOptions, OptionUpdater updaterService) { yield return FormattingSetting.Create(CSharpFormattingOptions2.IndentBlock, CSharpEditorResources.Indent_block_contents, editorConfigOptions, visualStudioOptions, updaterService); yield return FormattingSetting.Create(CSharpFormattingOptions2.IndentBraces, CSharpEditorResources.Indent_open_and_close_braces, editorConfigOptions, visualStudioOptions, updaterService); yield return FormattingSetting.Create(CSharpFormattingOptions2.IndentSwitchCaseSection, CSharpEditorResources.Indent_case_contents, editorConfigOptions, visualStudioOptions, updaterService); yield return FormattingSetting.Create(CSharpFormattingOptions2.IndentSwitchCaseSectionWhenBlock, CSharpEditorResources.Indent_case_contents_when_block, editorConfigOptions, visualStudioOptions, updaterService); yield return FormattingSetting.Create(CSharpFormattingOptions2.IndentSwitchSection, CSharpEditorResources.Indent_case_labels, editorConfigOptions, visualStudioOptions, updaterService); yield return FormattingSetting.Create(CSharpFormattingOptions2.LabelPositioning, CSharpEditorResources.Label_Indentation, editorConfigOptions, visualStudioOptions, updaterService); } private static IEnumerable<FormattingSetting> GetWrappingOptions(AnalyzerConfigOptions editorConfigOptions, OptionSet visualStudioOptions, OptionUpdater updaterService) { yield return FormattingSetting.Create(CSharpFormattingOptions2.WrappingPreserveSingleLine, CSharpEditorResources.Leave_block_on_single_line, editorConfigOptions, visualStudioOptions, updaterService); yield return FormattingSetting.Create(CSharpFormattingOptions2.WrappingKeepStatementsOnSingleLine, CSharpEditorResources.Leave_statements_and_member_declarations_on_the_same_line, editorConfigOptions, visualStudioOptions, updaterService); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Formatting; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.CSharp; using Microsoft.CodeAnalysis.Editor.EditorConfigSettings.Data; using Microsoft.CodeAnalysis.Editor.EditorConfigSettings.DataProvider; using Microsoft.CodeAnalysis.Editor.EditorConfigSettings.Updater; using Microsoft.CodeAnalysis.Options; namespace Microsoft.VisualStudio.LanguageServices.CSharp.EditorConfigSettings.DataProvider.Formatting { internal class CSharpFormattingSettingsProvider : SettingsProviderBase<FormattingSetting, OptionUpdater, IOption2, object> { public CSharpFormattingSettingsProvider(string filePath, OptionUpdater updaterService, Workspace workspace) : base(filePath, updaterService, workspace) { Update(); } protected override void UpdateOptions(AnalyzerConfigOptions editorConfigOptions, OptionSet visualStudioOptions) { var spacingOptions = GetSpacingOptions(editorConfigOptions, visualStudioOptions, SettingsUpdater); AddRange(spacingOptions.ToImmutableArray()); var newLineOptions = GetNewLineOptions(editorConfigOptions, visualStudioOptions, SettingsUpdater); AddRange(newLineOptions.ToImmutableArray()); var indentationOptions = GetIndentationOptions(editorConfigOptions, visualStudioOptions, SettingsUpdater); AddRange(indentationOptions.ToImmutableArray()); var wrappingOptions = GetWrappingOptions(editorConfigOptions, visualStudioOptions, SettingsUpdater); AddRange(wrappingOptions.ToImmutableArray()); } private static IEnumerable<FormattingSetting> GetSpacingOptions(AnalyzerConfigOptions editorConfigOptions, OptionSet visualStudioOptions, OptionUpdater updaterService) { yield return FormattingSetting.Create(CSharpFormattingOptions2.SpacingAfterMethodDeclarationName, CSharpEditorResources.Insert_space_between_method_name_and_its_opening_parenthesis2, editorConfigOptions, visualStudioOptions, updaterService); yield return FormattingSetting.Create(CSharpFormattingOptions2.SpaceWithinMethodDeclarationParenthesis, CSharpEditorResources.Insert_space_within_parameter_list_parentheses, editorConfigOptions, visualStudioOptions, updaterService); yield return FormattingSetting.Create(CSharpFormattingOptions2.SpaceBetweenEmptyMethodDeclarationParentheses, CSharpEditorResources.Insert_space_within_empty_parameter_list_parentheses, editorConfigOptions, visualStudioOptions, updaterService); yield return FormattingSetting.Create(CSharpFormattingOptions2.SpaceAfterMethodCallName, CSharpEditorResources.Insert_space_between_method_name_and_its_opening_parenthesis1, editorConfigOptions, visualStudioOptions, updaterService); yield return FormattingSetting.Create(CSharpFormattingOptions2.SpaceWithinMethodCallParentheses, CSharpEditorResources.Insert_space_within_argument_list_parentheses, editorConfigOptions, visualStudioOptions, updaterService); yield return FormattingSetting.Create(CSharpFormattingOptions2.SpaceBetweenEmptyMethodCallParentheses, CSharpEditorResources.Insert_space_within_empty_argument_list_parentheses, editorConfigOptions, visualStudioOptions, updaterService); yield return FormattingSetting.Create(CSharpFormattingOptions2.SpaceAfterControlFlowStatementKeyword, CSharpEditorResources.Insert_space_after_keywords_in_control_flow_statements, editorConfigOptions, visualStudioOptions, updaterService); yield return FormattingSetting.Create(CSharpFormattingOptions2.SpaceWithinExpressionParentheses, CSharpEditorResources.Insert_space_within_parentheses_of_expressions, editorConfigOptions, visualStudioOptions, updaterService); yield return FormattingSetting.Create(CSharpFormattingOptions2.SpaceWithinCastParentheses, CSharpEditorResources.Insert_space_within_parentheses_of_type_casts, editorConfigOptions, visualStudioOptions, updaterService); yield return FormattingSetting.Create(CSharpFormattingOptions2.SpaceWithinOtherParentheses, CSharpEditorResources.Insert_spaces_within_parentheses_of_control_flow_statements, editorConfigOptions, visualStudioOptions, updaterService); yield return FormattingSetting.Create(CSharpFormattingOptions2.SpaceAfterCast, CSharpEditorResources.Insert_space_after_cast, editorConfigOptions, visualStudioOptions, updaterService); yield return FormattingSetting.Create(CSharpFormattingOptions2.SpacesIgnoreAroundVariableDeclaration, CSharpEditorResources.Ignore_spaces_in_declaration_statements, editorConfigOptions, visualStudioOptions, updaterService); yield return FormattingSetting.Create(CSharpFormattingOptions2.SpaceBeforeOpenSquareBracket, CSharpEditorResources.Insert_space_before_open_square_bracket, editorConfigOptions, visualStudioOptions, updaterService); yield return FormattingSetting.Create(CSharpFormattingOptions2.SpaceBetweenEmptySquareBrackets, CSharpEditorResources.Insert_space_within_empty_square_brackets, editorConfigOptions, visualStudioOptions, updaterService); yield return FormattingSetting.Create(CSharpFormattingOptions2.SpaceWithinSquareBrackets, CSharpEditorResources.Insert_spaces_within_square_brackets, editorConfigOptions, visualStudioOptions, updaterService); yield return FormattingSetting.Create(CSharpFormattingOptions2.SpaceAfterColonInBaseTypeDeclaration, CSharpEditorResources.Insert_space_after_colon_for_base_or_interface_in_type_declaration, editorConfigOptions, visualStudioOptions, updaterService); yield return FormattingSetting.Create(CSharpFormattingOptions2.SpaceAfterComma, CSharpEditorResources.Insert_space_after_comma, editorConfigOptions, visualStudioOptions, updaterService); yield return FormattingSetting.Create(CSharpFormattingOptions2.SpaceAfterDot, CSharpEditorResources.Insert_space_after_dot, editorConfigOptions, visualStudioOptions, updaterService); yield return FormattingSetting.Create(CSharpFormattingOptions2.SpaceAfterSemicolonsInForStatement, CSharpEditorResources.Insert_space_after_semicolon_in_for_statement, editorConfigOptions, visualStudioOptions, updaterService); yield return FormattingSetting.Create(CSharpFormattingOptions2.SpaceBeforeColonInBaseTypeDeclaration, CSharpEditorResources.Insert_space_before_colon_for_base_or_interface_in_type_declaration, editorConfigOptions, visualStudioOptions, updaterService); yield return FormattingSetting.Create(CSharpFormattingOptions2.SpaceBeforeComma, CSharpEditorResources.Insert_space_before_comma, editorConfigOptions, visualStudioOptions, updaterService); yield return FormattingSetting.Create(CSharpFormattingOptions2.SpaceBeforeDot, CSharpEditorResources.Insert_space_before_dot, editorConfigOptions, visualStudioOptions, updaterService); yield return FormattingSetting.Create(CSharpFormattingOptions2.SpaceBeforeSemicolonsInForStatement, CSharpEditorResources.Insert_space_before_semicolon_in_for_statement, editorConfigOptions, visualStudioOptions, updaterService); yield return FormattingSetting.Create(CSharpFormattingOptions2.SpacingAroundBinaryOperator, CSharpEditorResources.Set_spacing_for_operators, editorConfigOptions, visualStudioOptions, updaterService); } private static IEnumerable<FormattingSetting> GetNewLineOptions(AnalyzerConfigOptions editorConfigOptions, OptionSet visualStudioOptions, OptionUpdater updaterService) { yield return FormattingSetting.Create(CSharpFormattingOptions2.NewLinesForBracesInTypes, CSharpEditorResources.Place_open_brace_on_new_line_for_types, editorConfigOptions, visualStudioOptions, updaterService); yield return FormattingSetting.Create(CSharpFormattingOptions2.NewLinesForBracesInMethods, CSharpEditorResources.Place_open_brace_on_new_line_for_methods_local_functions, editorConfigOptions, visualStudioOptions, updaterService); yield return FormattingSetting.Create(CSharpFormattingOptions2.NewLinesForBracesInProperties, CSharpEditorResources.Place_open_brace_on_new_line_for_properties_indexers_and_events, editorConfigOptions, visualStudioOptions, updaterService); yield return FormattingSetting.Create(CSharpFormattingOptions2.NewLinesForBracesInAccessors, CSharpEditorResources.Place_open_brace_on_new_line_for_property_indexer_and_event_accessors, editorConfigOptions, visualStudioOptions, updaterService); yield return FormattingSetting.Create(CSharpFormattingOptions2.NewLinesForBracesInAnonymousMethods, CSharpEditorResources.Place_open_brace_on_new_line_for_anonymous_methods, editorConfigOptions, visualStudioOptions, updaterService); yield return FormattingSetting.Create(CSharpFormattingOptions2.NewLinesForBracesInControlBlocks, CSharpEditorResources.Place_open_brace_on_new_line_for_control_blocks, editorConfigOptions, visualStudioOptions, updaterService); yield return FormattingSetting.Create(CSharpFormattingOptions2.NewLinesForBracesInAnonymousTypes, CSharpEditorResources.Place_open_brace_on_new_line_for_anonymous_types, editorConfigOptions, visualStudioOptions, updaterService); yield return FormattingSetting.Create(CSharpFormattingOptions2.NewLinesForBracesInObjectCollectionArrayInitializers, CSharpEditorResources.Place_open_brace_on_new_line_for_object_collection_array_and_with_initializers, editorConfigOptions, visualStudioOptions, updaterService); yield return FormattingSetting.Create(CSharpFormattingOptions2.NewLinesForBracesInLambdaExpressionBody, CSharpEditorResources.Place_open_brace_on_new_line_for_lambda_expression, editorConfigOptions, visualStudioOptions, updaterService); yield return FormattingSetting.Create(CSharpFormattingOptions2.NewLineForElse, CSharpEditorResources.Place_else_on_new_line, editorConfigOptions, visualStudioOptions, updaterService); yield return FormattingSetting.Create(CSharpFormattingOptions2.NewLineForCatch, CSharpEditorResources.Place_catch_on_new_line, editorConfigOptions, visualStudioOptions, updaterService); yield return FormattingSetting.Create(CSharpFormattingOptions2.NewLineForFinally, CSharpEditorResources.Place_finally_on_new_line, editorConfigOptions, visualStudioOptions, updaterService); yield return FormattingSetting.Create(CSharpFormattingOptions2.NewLineForMembersInObjectInit, CSharpEditorResources.Place_members_in_object_initializers_on_new_line, editorConfigOptions, visualStudioOptions, updaterService); yield return FormattingSetting.Create(CSharpFormattingOptions2.NewLineForMembersInAnonymousTypes, CSharpEditorResources.Place_members_in_anonymous_types_on_new_line, editorConfigOptions, visualStudioOptions, updaterService); yield return FormattingSetting.Create(CSharpFormattingOptions2.NewLineForClausesInQuery, CSharpEditorResources.Place_query_expression_clauses_on_new_line, editorConfigOptions, visualStudioOptions, updaterService); } private static IEnumerable<FormattingSetting> GetIndentationOptions(AnalyzerConfigOptions editorConfigOptions, OptionSet visualStudioOptions, OptionUpdater updaterService) { yield return FormattingSetting.Create(CSharpFormattingOptions2.IndentBlock, CSharpEditorResources.Indent_block_contents, editorConfigOptions, visualStudioOptions, updaterService); yield return FormattingSetting.Create(CSharpFormattingOptions2.IndentBraces, CSharpEditorResources.Indent_open_and_close_braces, editorConfigOptions, visualStudioOptions, updaterService); yield return FormattingSetting.Create(CSharpFormattingOptions2.IndentSwitchCaseSection, CSharpEditorResources.Indent_case_contents, editorConfigOptions, visualStudioOptions, updaterService); yield return FormattingSetting.Create(CSharpFormattingOptions2.IndentSwitchCaseSectionWhenBlock, CSharpEditorResources.Indent_case_contents_when_block, editorConfigOptions, visualStudioOptions, updaterService); yield return FormattingSetting.Create(CSharpFormattingOptions2.IndentSwitchSection, CSharpEditorResources.Indent_case_labels, editorConfigOptions, visualStudioOptions, updaterService); yield return FormattingSetting.Create(CSharpFormattingOptions2.LabelPositioning, CSharpEditorResources.Label_Indentation, editorConfigOptions, visualStudioOptions, updaterService); } private static IEnumerable<FormattingSetting> GetWrappingOptions(AnalyzerConfigOptions editorConfigOptions, OptionSet visualStudioOptions, OptionUpdater updaterService) { yield return FormattingSetting.Create(CSharpFormattingOptions2.WrappingPreserveSingleLine, CSharpEditorResources.Leave_block_on_single_line, editorConfigOptions, visualStudioOptions, updaterService); yield return FormattingSetting.Create(CSharpFormattingOptions2.WrappingKeepStatementsOnSingleLine, CSharpEditorResources.Leave_statements_and_member_declarations_on_the_same_line, editorConfigOptions, visualStudioOptions, updaterService); } } }
-1
dotnet/roslyn
55,138
Avoid cancellation exceptions in intermediate operations
Addresses the following exceptions: ![image](https://user-images.githubusercontent.com/1408396/127185947-8a005aea-ae1c-4755-bf0f-21dfb8101352.png)
sharwell
2021-07-27T15:51:28Z
2021-07-27T21:36:45Z
3d8acbd585a75e9cdb3509623bf6c39ceb46b2c2
719d4ffa2be734463e5d7d4d74b23b8006fd7727
Avoid cancellation exceptions in intermediate operations. Addresses the following exceptions: ![image](https://user-images.githubusercontent.com/1408396/127185947-8a005aea-ae1c-4755-bf0f-21dfb8101352.png)
./src/Compilers/Core/Portable/Symbols/ITypeParameterSymbolInternal.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable namespace Microsoft.CodeAnalysis.Symbols { internal interface ITypeParameterSymbolInternal : ITypeSymbolInternal { } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable namespace Microsoft.CodeAnalysis.Symbols { internal interface ITypeParameterSymbolInternal : ITypeSymbolInternal { } }
-1
dotnet/roslyn
55,138
Avoid cancellation exceptions in intermediate operations
Addresses the following exceptions: ![image](https://user-images.githubusercontent.com/1408396/127185947-8a005aea-ae1c-4755-bf0f-21dfb8101352.png)
sharwell
2021-07-27T15:51:28Z
2021-07-27T21:36:45Z
3d8acbd585a75e9cdb3509623bf6c39ceb46b2c2
719d4ffa2be734463e5d7d4d74b23b8006fd7727
Avoid cancellation exceptions in intermediate operations. Addresses the following exceptions: ![image](https://user-images.githubusercontent.com/1408396/127185947-8a005aea-ae1c-4755-bf0f-21dfb8101352.png)
./src/EditorFeatures/VisualBasicTest/Recommendations/Expressions/CastOperatorsKeywordRecommenderTests.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.VisualBasic.Completion.KeywordRecommenders.Expressions Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Recommendations.Expressions Public Class CastOperatorsKeywordRecommenderTests Private Shared ReadOnly Property AllTypeConversionOperatorKeywords As String() Get Dim keywords As New List(Of String) From {"CType", "DirectCast", "TryCast"} For Each k In CastOperatorsKeywordRecommender.PredefinedKeywordList keywords.Add(SyntaxFacts.GetText(k)) Next Return keywords.ToArray() End Get End Property <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub DirectCastHelpTextTest() VerifyRecommendationDescriptionTextIs(<MethodBody>Return |</MethodBody>, "DirectCast", $"{VBFeaturesResources.DirectCast_function} {VBWorkspaceResources.Introduces_a_type_conversion_operation_similar_to_CType_The_difference_is_that_CType_succeeds_as_long_as_there_is_a_valid_conversion_whereas_DirectCast_requires_that_one_type_inherit_from_or_implement_the_other_type} DirectCast({VBWorkspaceResources.expression}, {VBWorkspaceResources.typeName}) As {VBWorkspaceResources.result}") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub TryCastHelpTextTest() VerifyRecommendationDescriptionTextIs(<MethodBody>Return |</MethodBody>, "TryCast", $"{VBFeaturesResources.TryCast_function} {VBWorkspaceResources.Introduces_a_type_conversion_operation_that_does_not_throw_an_exception_If_an_attempted_conversion_fails_TryCast_returns_Nothing_which_your_program_can_test_for} TryCast({VBWorkspaceResources.expression}, {VBWorkspaceResources.typeName}) As {VBWorkspaceResources.result}") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub CTypeHelpTextTest() VerifyRecommendationDescriptionTextIs(<MethodBody>Return |</MethodBody>, "CType", $"{VBFeaturesResources.CType_function} {VBWorkspaceResources.Returns_the_result_of_explicitly_converting_an_expression_to_a_specified_data_type} CType({VBWorkspaceResources.expression}, {VBWorkspaceResources.typeName}) As {VBWorkspaceResources.result}") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub CBoolHelpTextTest() VerifyRecommendationDescriptionTextIs(<MethodBody>Return |</MethodBody>, "CBool", $"{String.Format(VBFeaturesResources._0_function, "CBool")} {String.Format(VBWorkspaceResources.Converts_an_expression_to_the_0_data_type, "Boolean")} CBool({VBWorkspaceResources.expression}) As Boolean") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NoneInClassDeclarationTest() VerifyRecommendationsMissing(<ClassDeclaration>|</ClassDeclaration>, AllTypeConversionOperatorKeywords) End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AllInStatementTest() VerifyRecommendationsContain(<MethodBody>|</MethodBody>, AllTypeConversionOperatorKeywords) End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AllAfterReturnTest() VerifyRecommendationsContain(<MethodBody>Return |</MethodBody>, AllTypeConversionOperatorKeywords) End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AllAfterArgument1Test() VerifyRecommendationsContain(<MethodBody>Goo(|</MethodBody>, AllTypeConversionOperatorKeywords) End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AllAfterArgument2Test() VerifyRecommendationsContain(<MethodBody>Goo(bar, |</MethodBody>, AllTypeConversionOperatorKeywords) End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AllAfterBinaryExpressionTest() VerifyRecommendationsContain(<MethodBody>Goo(bar + |</MethodBody>, AllTypeConversionOperatorKeywords) End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AllAfterNotTest() VerifyRecommendationsContain(<MethodBody>Goo(Not |</MethodBody>, AllTypeConversionOperatorKeywords) End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AllAfterTypeOfTest() VerifyRecommendationsContain(<MethodBody>If TypeOf |</MethodBody>, AllTypeConversionOperatorKeywords) End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AllAfterDoWhileTest() VerifyRecommendationsContain(<MethodBody>Do While |</MethodBody>, AllTypeConversionOperatorKeywords) End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AllAfterDoUntilTest() VerifyRecommendationsContain(<MethodBody>Do Until |</MethodBody>, AllTypeConversionOperatorKeywords) End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AllAfterLoopWhileTest() VerifyRecommendationsContain(<MethodBody> Do Loop While |</MethodBody>, AllTypeConversionOperatorKeywords) End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AllAfterLoopUntilTest() VerifyRecommendationsContain(<MethodBody> Do Loop Until |</MethodBody>, AllTypeConversionOperatorKeywords) End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AllAfterIfTest() VerifyRecommendationsContain(<MethodBody>If |</MethodBody>, AllTypeConversionOperatorKeywords) End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AllAfterElseIfTest() VerifyRecommendationsContain(<MethodBody>ElseIf |</MethodBody>, AllTypeConversionOperatorKeywords) End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AllAfterElseSpaceIfTest() VerifyRecommendationsContain(<MethodBody>Else If |</MethodBody>, AllTypeConversionOperatorKeywords) End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AllAfterErrorTest() VerifyRecommendationsContain(<MethodBody>Error |</MethodBody>, AllTypeConversionOperatorKeywords) End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AllAfterThrowTest() VerifyRecommendationsContain(<MethodBody>Throw |</MethodBody>, AllTypeConversionOperatorKeywords) End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AllAfterInitializerTest() VerifyRecommendationsContain(<MethodBody>Dim x = |</MethodBody>, AllTypeConversionOperatorKeywords) End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AllAfterArrayInitializerSquiggleTest() VerifyRecommendationsContain(<MethodBody>Dim x = {|</MethodBody>, AllTypeConversionOperatorKeywords) End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AllAfterArrayInitializerCommaTest() VerifyRecommendationsContain(<MethodBody>Dim x = {0, |</MethodBody>, AllTypeConversionOperatorKeywords) End Sub <WorkItem(543270, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543270")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NoneInDelegateCreationTest() Dim code = <File> Module Program Sub Main(args As String()) Dim f1 As New Goo2( | End Sub Delegate Sub Goo2() Function Bar2() As Object Return Nothing End Function End Module </File> VerifyRecommendationsMissing(code, AllTypeConversionOperatorKeywords) 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.VisualBasic.Completion.KeywordRecommenders.Expressions Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Recommendations.Expressions Public Class CastOperatorsKeywordRecommenderTests Private Shared ReadOnly Property AllTypeConversionOperatorKeywords As String() Get Dim keywords As New List(Of String) From {"CType", "DirectCast", "TryCast"} For Each k In CastOperatorsKeywordRecommender.PredefinedKeywordList keywords.Add(SyntaxFacts.GetText(k)) Next Return keywords.ToArray() End Get End Property <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub DirectCastHelpTextTest() VerifyRecommendationDescriptionTextIs(<MethodBody>Return |</MethodBody>, "DirectCast", $"{VBFeaturesResources.DirectCast_function} {VBWorkspaceResources.Introduces_a_type_conversion_operation_similar_to_CType_The_difference_is_that_CType_succeeds_as_long_as_there_is_a_valid_conversion_whereas_DirectCast_requires_that_one_type_inherit_from_or_implement_the_other_type} DirectCast({VBWorkspaceResources.expression}, {VBWorkspaceResources.typeName}) As {VBWorkspaceResources.result}") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub TryCastHelpTextTest() VerifyRecommendationDescriptionTextIs(<MethodBody>Return |</MethodBody>, "TryCast", $"{VBFeaturesResources.TryCast_function} {VBWorkspaceResources.Introduces_a_type_conversion_operation_that_does_not_throw_an_exception_If_an_attempted_conversion_fails_TryCast_returns_Nothing_which_your_program_can_test_for} TryCast({VBWorkspaceResources.expression}, {VBWorkspaceResources.typeName}) As {VBWorkspaceResources.result}") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub CTypeHelpTextTest() VerifyRecommendationDescriptionTextIs(<MethodBody>Return |</MethodBody>, "CType", $"{VBFeaturesResources.CType_function} {VBWorkspaceResources.Returns_the_result_of_explicitly_converting_an_expression_to_a_specified_data_type} CType({VBWorkspaceResources.expression}, {VBWorkspaceResources.typeName}) As {VBWorkspaceResources.result}") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub CBoolHelpTextTest() VerifyRecommendationDescriptionTextIs(<MethodBody>Return |</MethodBody>, "CBool", $"{String.Format(VBFeaturesResources._0_function, "CBool")} {String.Format(VBWorkspaceResources.Converts_an_expression_to_the_0_data_type, "Boolean")} CBool({VBWorkspaceResources.expression}) As Boolean") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NoneInClassDeclarationTest() VerifyRecommendationsMissing(<ClassDeclaration>|</ClassDeclaration>, AllTypeConversionOperatorKeywords) End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AllInStatementTest() VerifyRecommendationsContain(<MethodBody>|</MethodBody>, AllTypeConversionOperatorKeywords) End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AllAfterReturnTest() VerifyRecommendationsContain(<MethodBody>Return |</MethodBody>, AllTypeConversionOperatorKeywords) End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AllAfterArgument1Test() VerifyRecommendationsContain(<MethodBody>Goo(|</MethodBody>, AllTypeConversionOperatorKeywords) End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AllAfterArgument2Test() VerifyRecommendationsContain(<MethodBody>Goo(bar, |</MethodBody>, AllTypeConversionOperatorKeywords) End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AllAfterBinaryExpressionTest() VerifyRecommendationsContain(<MethodBody>Goo(bar + |</MethodBody>, AllTypeConversionOperatorKeywords) End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AllAfterNotTest() VerifyRecommendationsContain(<MethodBody>Goo(Not |</MethodBody>, AllTypeConversionOperatorKeywords) End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AllAfterTypeOfTest() VerifyRecommendationsContain(<MethodBody>If TypeOf |</MethodBody>, AllTypeConversionOperatorKeywords) End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AllAfterDoWhileTest() VerifyRecommendationsContain(<MethodBody>Do While |</MethodBody>, AllTypeConversionOperatorKeywords) End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AllAfterDoUntilTest() VerifyRecommendationsContain(<MethodBody>Do Until |</MethodBody>, AllTypeConversionOperatorKeywords) End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AllAfterLoopWhileTest() VerifyRecommendationsContain(<MethodBody> Do Loop While |</MethodBody>, AllTypeConversionOperatorKeywords) End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AllAfterLoopUntilTest() VerifyRecommendationsContain(<MethodBody> Do Loop Until |</MethodBody>, AllTypeConversionOperatorKeywords) End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AllAfterIfTest() VerifyRecommendationsContain(<MethodBody>If |</MethodBody>, AllTypeConversionOperatorKeywords) End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AllAfterElseIfTest() VerifyRecommendationsContain(<MethodBody>ElseIf |</MethodBody>, AllTypeConversionOperatorKeywords) End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AllAfterElseSpaceIfTest() VerifyRecommendationsContain(<MethodBody>Else If |</MethodBody>, AllTypeConversionOperatorKeywords) End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AllAfterErrorTest() VerifyRecommendationsContain(<MethodBody>Error |</MethodBody>, AllTypeConversionOperatorKeywords) End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AllAfterThrowTest() VerifyRecommendationsContain(<MethodBody>Throw |</MethodBody>, AllTypeConversionOperatorKeywords) End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AllAfterInitializerTest() VerifyRecommendationsContain(<MethodBody>Dim x = |</MethodBody>, AllTypeConversionOperatorKeywords) End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AllAfterArrayInitializerSquiggleTest() VerifyRecommendationsContain(<MethodBody>Dim x = {|</MethodBody>, AllTypeConversionOperatorKeywords) End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AllAfterArrayInitializerCommaTest() VerifyRecommendationsContain(<MethodBody>Dim x = {0, |</MethodBody>, AllTypeConversionOperatorKeywords) End Sub <WorkItem(543270, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543270")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NoneInDelegateCreationTest() Dim code = <File> Module Program Sub Main(args As String()) Dim f1 As New Goo2( | End Sub Delegate Sub Goo2() Function Bar2() As Object Return Nothing End Function End Module </File> VerifyRecommendationsMissing(code, AllTypeConversionOperatorKeywords) End Sub End Class End Namespace
-1
dotnet/roslyn
55,138
Avoid cancellation exceptions in intermediate operations
Addresses the following exceptions: ![image](https://user-images.githubusercontent.com/1408396/127185947-8a005aea-ae1c-4755-bf0f-21dfb8101352.png)
sharwell
2021-07-27T15:51:28Z
2021-07-27T21:36:45Z
3d8acbd585a75e9cdb3509623bf6c39ceb46b2c2
719d4ffa2be734463e5d7d4d74b23b8006fd7727
Avoid cancellation exceptions in intermediate operations. Addresses the following exceptions: ![image](https://user-images.githubusercontent.com/1408396/127185947-8a005aea-ae1c-4755-bf0f-21dfb8101352.png)
./src/Features/Core/Portable/Diagnostics/AbstractHostDiagnosticUpdateSource.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Diagnostics { /// <summary> /// Diagnostic update source for reporting workspace host specific diagnostics, /// which may not be related to any given project/document in the solution. /// For example, these include diagnostics generated for exceptions from third party analyzers. /// </summary> internal abstract class AbstractHostDiagnosticUpdateSource : IDiagnosticUpdateSource { private ImmutableDictionary<DiagnosticAnalyzer, ImmutableHashSet<DiagnosticData>> _analyzerHostDiagnosticsMap = ImmutableDictionary<DiagnosticAnalyzer, ImmutableHashSet<DiagnosticData>>.Empty; public abstract Workspace Workspace { get; } public bool SupportGetDiagnostics => false; public ValueTask<ImmutableArray<DiagnosticData>> GetDiagnosticsAsync(Workspace workspace, ProjectId projectId, DocumentId documentId, object id, bool includeSuppressedDiagnostics, CancellationToken cancellationToken) => new(ImmutableArray<DiagnosticData>.Empty); public event EventHandler<DiagnosticsUpdatedArgs>? DiagnosticsUpdated; public event EventHandler DiagnosticsCleared { add { } remove { } } public void RaiseDiagnosticsUpdated(DiagnosticsUpdatedArgs args) => DiagnosticsUpdated?.Invoke(this, args); public void ReportAnalyzerDiagnostic(DiagnosticAnalyzer analyzer, Diagnostic diagnostic, ProjectId? projectId) { // check whether we are reporting project specific diagnostic or workspace wide diagnostic var project = (projectId != null) ? Workspace.CurrentSolution.GetProject(projectId) : null; // check whether project the diagnostic belong to still exist if (projectId != null && project == null) { // project the diagnostic belong to already removed from the solution. // ignore the diagnostic return; } var diagnosticData = (project != null) ? DiagnosticData.Create(diagnostic, project) : DiagnosticData.Create(diagnostic, Workspace.Options); ReportAnalyzerDiagnostic(analyzer, diagnosticData, project); } public void ReportAnalyzerDiagnostic(DiagnosticAnalyzer analyzer, DiagnosticData diagnosticData, Project? project) { var raiseDiagnosticsUpdated = true; var dxs = ImmutableInterlocked.AddOrUpdate(ref _analyzerHostDiagnosticsMap, analyzer, ImmutableHashSet.Create(diagnosticData), (a, existing) => { var newDiags = existing.Add(diagnosticData); raiseDiagnosticsUpdated = newDiags.Count > existing.Count; return newDiags; }); if (raiseDiagnosticsUpdated) { RaiseDiagnosticsUpdated(MakeCreatedArgs(analyzer, dxs, project)); } } public void ClearAnalyzerReferenceDiagnostics(AnalyzerFileReference analyzerReference, string language, ProjectId projectId) { var analyzers = analyzerReference.GetAnalyzers(language); ClearAnalyzerDiagnostics(analyzers, projectId); } public void ClearAnalyzerDiagnostics(ImmutableArray<DiagnosticAnalyzer> analyzers, ProjectId projectId) { foreach (var analyzer in analyzers) { ClearAnalyzerDiagnostics(analyzer, projectId); } } public void ClearAnalyzerDiagnostics(ProjectId projectId) { foreach (var (analyzer, _) in _analyzerHostDiagnosticsMap) { ClearAnalyzerDiagnostics(analyzer, projectId); } } private void ClearAnalyzerDiagnostics(DiagnosticAnalyzer analyzer, ProjectId projectId) { if (!_analyzerHostDiagnosticsMap.TryGetValue(analyzer, out var existing)) { return; } // Check if analyzer is shared by analyzer references from different projects. var sharedAnalyzer = existing.Contains(d => d.ProjectId != null && d.ProjectId != projectId); if (sharedAnalyzer) { var newDiags = existing.Where(d => d.ProjectId != projectId).ToImmutableHashSet(); if (newDiags.Count < existing.Count && ImmutableInterlocked.TryUpdate(ref _analyzerHostDiagnosticsMap, analyzer, newDiags, existing)) { var project = Workspace.CurrentSolution.GetProject(projectId); RaiseDiagnosticsUpdated(MakeRemovedArgs(analyzer, project)); } } else if (ImmutableInterlocked.TryRemove(ref _analyzerHostDiagnosticsMap, analyzer, out existing)) { var project = Workspace.CurrentSolution.GetProject(projectId); RaiseDiagnosticsUpdated(MakeRemovedArgs(analyzer, project)); if (existing.Any(d => d.ProjectId == null)) { RaiseDiagnosticsUpdated(MakeRemovedArgs(analyzer, project: null)); } } } private DiagnosticsUpdatedArgs MakeCreatedArgs(DiagnosticAnalyzer analyzer, ImmutableHashSet<DiagnosticData> items, Project? project) { return DiagnosticsUpdatedArgs.DiagnosticsCreated( CreateId(analyzer, project), Workspace, project?.Solution, project?.Id, documentId: null, diagnostics: items.ToImmutableArray()); } private DiagnosticsUpdatedArgs MakeRemovedArgs(DiagnosticAnalyzer analyzer, Project? project) { return DiagnosticsUpdatedArgs.DiagnosticsRemoved( CreateId(analyzer, project), Workspace, project?.Solution, project?.Id, documentId: null); } private HostArgsId CreateId(DiagnosticAnalyzer analyzer, Project? project) => new(this, analyzer, project?.Id); internal TestAccessor GetTestAccessor() => new(this); internal readonly struct TestAccessor { private readonly AbstractHostDiagnosticUpdateSource _abstractHostDiagnosticUpdateSource; public TestAccessor(AbstractHostDiagnosticUpdateSource abstractHostDiagnosticUpdateSource) => _abstractHostDiagnosticUpdateSource = abstractHostDiagnosticUpdateSource; internal ImmutableArray<DiagnosticData> GetReportedDiagnostics() => _abstractHostDiagnosticUpdateSource._analyzerHostDiagnosticsMap.Values.Flatten().ToImmutableArray(); internal ImmutableHashSet<DiagnosticData> GetReportedDiagnostics(DiagnosticAnalyzer analyzer) { if (!_abstractHostDiagnosticUpdateSource._analyzerHostDiagnosticsMap.TryGetValue(analyzer, out var diagnostics)) { diagnostics = ImmutableHashSet<DiagnosticData>.Empty; } return diagnostics; } } private sealed class HostArgsId : AnalyzerUpdateArgsId { private readonly AbstractHostDiagnosticUpdateSource _source; private readonly ProjectId? _projectId; public HostArgsId(AbstractHostDiagnosticUpdateSource source, DiagnosticAnalyzer analyzer, ProjectId? projectId) : base(analyzer) { _source = source; _projectId = projectId; } public override bool Equals(object? obj) { if (obj is not HostArgsId other) { return false; } return _source == other._source && _projectId == other._projectId && base.Equals(obj); } public override int GetHashCode() => Hash.Combine(_source.GetHashCode(), Hash.Combine(_projectId == null ? 1 : _projectId.GetHashCode(), base.GetHashCode())); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Diagnostics { /// <summary> /// Diagnostic update source for reporting workspace host specific diagnostics, /// which may not be related to any given project/document in the solution. /// For example, these include diagnostics generated for exceptions from third party analyzers. /// </summary> internal abstract class AbstractHostDiagnosticUpdateSource : IDiagnosticUpdateSource { private ImmutableDictionary<DiagnosticAnalyzer, ImmutableHashSet<DiagnosticData>> _analyzerHostDiagnosticsMap = ImmutableDictionary<DiagnosticAnalyzer, ImmutableHashSet<DiagnosticData>>.Empty; public abstract Workspace Workspace { get; } public bool SupportGetDiagnostics => false; public ValueTask<ImmutableArray<DiagnosticData>> GetDiagnosticsAsync(Workspace workspace, ProjectId projectId, DocumentId documentId, object id, bool includeSuppressedDiagnostics, CancellationToken cancellationToken) => new(ImmutableArray<DiagnosticData>.Empty); public event EventHandler<DiagnosticsUpdatedArgs>? DiagnosticsUpdated; public event EventHandler DiagnosticsCleared { add { } remove { } } public void RaiseDiagnosticsUpdated(DiagnosticsUpdatedArgs args) => DiagnosticsUpdated?.Invoke(this, args); public void ReportAnalyzerDiagnostic(DiagnosticAnalyzer analyzer, Diagnostic diagnostic, ProjectId? projectId) { // check whether we are reporting project specific diagnostic or workspace wide diagnostic var project = (projectId != null) ? Workspace.CurrentSolution.GetProject(projectId) : null; // check whether project the diagnostic belong to still exist if (projectId != null && project == null) { // project the diagnostic belong to already removed from the solution. // ignore the diagnostic return; } var diagnosticData = (project != null) ? DiagnosticData.Create(diagnostic, project) : DiagnosticData.Create(diagnostic, Workspace.Options); ReportAnalyzerDiagnostic(analyzer, diagnosticData, project); } public void ReportAnalyzerDiagnostic(DiagnosticAnalyzer analyzer, DiagnosticData diagnosticData, Project? project) { var raiseDiagnosticsUpdated = true; var dxs = ImmutableInterlocked.AddOrUpdate(ref _analyzerHostDiagnosticsMap, analyzer, ImmutableHashSet.Create(diagnosticData), (a, existing) => { var newDiags = existing.Add(diagnosticData); raiseDiagnosticsUpdated = newDiags.Count > existing.Count; return newDiags; }); if (raiseDiagnosticsUpdated) { RaiseDiagnosticsUpdated(MakeCreatedArgs(analyzer, dxs, project)); } } public void ClearAnalyzerReferenceDiagnostics(AnalyzerFileReference analyzerReference, string language, ProjectId projectId) { var analyzers = analyzerReference.GetAnalyzers(language); ClearAnalyzerDiagnostics(analyzers, projectId); } public void ClearAnalyzerDiagnostics(ImmutableArray<DiagnosticAnalyzer> analyzers, ProjectId projectId) { foreach (var analyzer in analyzers) { ClearAnalyzerDiagnostics(analyzer, projectId); } } public void ClearAnalyzerDiagnostics(ProjectId projectId) { foreach (var (analyzer, _) in _analyzerHostDiagnosticsMap) { ClearAnalyzerDiagnostics(analyzer, projectId); } } private void ClearAnalyzerDiagnostics(DiagnosticAnalyzer analyzer, ProjectId projectId) { if (!_analyzerHostDiagnosticsMap.TryGetValue(analyzer, out var existing)) { return; } // Check if analyzer is shared by analyzer references from different projects. var sharedAnalyzer = existing.Contains(d => d.ProjectId != null && d.ProjectId != projectId); if (sharedAnalyzer) { var newDiags = existing.Where(d => d.ProjectId != projectId).ToImmutableHashSet(); if (newDiags.Count < existing.Count && ImmutableInterlocked.TryUpdate(ref _analyzerHostDiagnosticsMap, analyzer, newDiags, existing)) { var project = Workspace.CurrentSolution.GetProject(projectId); RaiseDiagnosticsUpdated(MakeRemovedArgs(analyzer, project)); } } else if (ImmutableInterlocked.TryRemove(ref _analyzerHostDiagnosticsMap, analyzer, out existing)) { var project = Workspace.CurrentSolution.GetProject(projectId); RaiseDiagnosticsUpdated(MakeRemovedArgs(analyzer, project)); if (existing.Any(d => d.ProjectId == null)) { RaiseDiagnosticsUpdated(MakeRemovedArgs(analyzer, project: null)); } } } private DiagnosticsUpdatedArgs MakeCreatedArgs(DiagnosticAnalyzer analyzer, ImmutableHashSet<DiagnosticData> items, Project? project) { return DiagnosticsUpdatedArgs.DiagnosticsCreated( CreateId(analyzer, project), Workspace, project?.Solution, project?.Id, documentId: null, diagnostics: items.ToImmutableArray()); } private DiagnosticsUpdatedArgs MakeRemovedArgs(DiagnosticAnalyzer analyzer, Project? project) { return DiagnosticsUpdatedArgs.DiagnosticsRemoved( CreateId(analyzer, project), Workspace, project?.Solution, project?.Id, documentId: null); } private HostArgsId CreateId(DiagnosticAnalyzer analyzer, Project? project) => new(this, analyzer, project?.Id); internal TestAccessor GetTestAccessor() => new(this); internal readonly struct TestAccessor { private readonly AbstractHostDiagnosticUpdateSource _abstractHostDiagnosticUpdateSource; public TestAccessor(AbstractHostDiagnosticUpdateSource abstractHostDiagnosticUpdateSource) => _abstractHostDiagnosticUpdateSource = abstractHostDiagnosticUpdateSource; internal ImmutableArray<DiagnosticData> GetReportedDiagnostics() => _abstractHostDiagnosticUpdateSource._analyzerHostDiagnosticsMap.Values.Flatten().ToImmutableArray(); internal ImmutableHashSet<DiagnosticData> GetReportedDiagnostics(DiagnosticAnalyzer analyzer) { if (!_abstractHostDiagnosticUpdateSource._analyzerHostDiagnosticsMap.TryGetValue(analyzer, out var diagnostics)) { diagnostics = ImmutableHashSet<DiagnosticData>.Empty; } return diagnostics; } } private sealed class HostArgsId : AnalyzerUpdateArgsId { private readonly AbstractHostDiagnosticUpdateSource _source; private readonly ProjectId? _projectId; public HostArgsId(AbstractHostDiagnosticUpdateSource source, DiagnosticAnalyzer analyzer, ProjectId? projectId) : base(analyzer) { _source = source; _projectId = projectId; } public override bool Equals(object? obj) { if (obj is not HostArgsId other) { return false; } return _source == other._source && _projectId == other._projectId && base.Equals(obj); } public override int GetHashCode() => Hash.Combine(_source.GetHashCode(), Hash.Combine(_projectId == null ? 1 : _projectId.GetHashCode(), base.GetHashCode())); } } }
-1
dotnet/roslyn
55,138
Avoid cancellation exceptions in intermediate operations
Addresses the following exceptions: ![image](https://user-images.githubusercontent.com/1408396/127185947-8a005aea-ae1c-4755-bf0f-21dfb8101352.png)
sharwell
2021-07-27T15:51:28Z
2021-07-27T21:36:45Z
3d8acbd585a75e9cdb3509623bf6c39ceb46b2c2
719d4ffa2be734463e5d7d4d74b23b8006fd7727
Avoid cancellation exceptions in intermediate operations. Addresses the following exceptions: ![image](https://user-images.githubusercontent.com/1408396/127185947-8a005aea-ae1c-4755-bf0f-21dfb8101352.png)
./src/Workspaces/Core/Portable/LinkedFileDiffMerging/DefaultDocumentTextDifferencingService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.Diagnostics.CodeAnalysis; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis { [ExportWorkspaceService(typeof(IDocumentTextDifferencingService), ServiceLayer.Default), Shared] internal class DefaultDocumentTextDifferencingService : IDocumentTextDifferencingService { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public DefaultDocumentTextDifferencingService() { } public Task<ImmutableArray<TextChange>> GetTextChangesAsync(Document oldDocument, Document newDocument, CancellationToken cancellationToken) => GetTextChangesAsync(oldDocument, newDocument, TextDifferenceTypes.Word, cancellationToken); public async Task<ImmutableArray<TextChange>> GetTextChangesAsync(Document oldDocument, Document newDocument, TextDifferenceTypes preferredDifferenceType, CancellationToken cancellationToken) { var changes = await newDocument.GetTextChangesAsync(oldDocument, cancellationToken).ConfigureAwait(false); return changes.ToImmutableArray(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Composition; using System.Diagnostics.CodeAnalysis; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis { [ExportWorkspaceService(typeof(IDocumentTextDifferencingService), ServiceLayer.Default), Shared] internal class DefaultDocumentTextDifferencingService : IDocumentTextDifferencingService { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public DefaultDocumentTextDifferencingService() { } public Task<ImmutableArray<TextChange>> GetTextChangesAsync(Document oldDocument, Document newDocument, CancellationToken cancellationToken) => GetTextChangesAsync(oldDocument, newDocument, TextDifferenceTypes.Word, cancellationToken); public async Task<ImmutableArray<TextChange>> GetTextChangesAsync(Document oldDocument, Document newDocument, TextDifferenceTypes preferredDifferenceType, CancellationToken cancellationToken) { var changes = await newDocument.GetTextChangesAsync(oldDocument, cancellationToken).ConfigureAwait(false); return changes.ToImmutableArray(); } } }
-1
dotnet/roslyn
55,138
Avoid cancellation exceptions in intermediate operations
Addresses the following exceptions: ![image](https://user-images.githubusercontent.com/1408396/127185947-8a005aea-ae1c-4755-bf0f-21dfb8101352.png)
sharwell
2021-07-27T15:51:28Z
2021-07-27T21:36:45Z
3d8acbd585a75e9cdb3509623bf6c39ceb46b2c2
719d4ffa2be734463e5d7d4d74b23b8006fd7727
Avoid cancellation exceptions in intermediate operations. Addresses the following exceptions: ![image](https://user-images.githubusercontent.com/1408396/127185947-8a005aea-ae1c-4755-bf0f-21dfb8101352.png)
./src/Workspaces/VisualBasic/Portable/Formatting/Engine/Trivia/TriviaDataFactory.Analyzer.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Namespace Microsoft.CodeAnalysis.VisualBasic.Formatting Partial Friend Class TriviaDataFactory Private Class Analyzer Public Shared Function Leading(token As SyntaxToken) As AnalysisResult Dim result As AnalysisResult Analyze(token.LeadingTrivia, result) Return result End Function Public Shared Function Trailing(token As SyntaxToken) As AnalysisResult Dim result As AnalysisResult Analyze(token.TrailingTrivia, result) Return result End Function Public Shared Function Between(token1 As SyntaxToken, token2 As SyntaxToken) As AnalysisResult If (Not token1.HasTrailingTrivia) AndAlso (Not token2.HasLeadingTrivia) Then Return Nothing End If Dim result As AnalysisResult Analyze(token1.TrailingTrivia, result) Analyze(token2.LeadingTrivia, result) Return result End Function Private Shared Sub Analyze(list As SyntaxTriviaList, ByRef result As AnalysisResult) If list.Count = 0 Then Return End If For Each trivia In list If trivia.Kind = SyntaxKind.WhitespaceTrivia Then AnalyzeWhitespacesInTrivia(trivia, result) ElseIf trivia.Kind = SyntaxKind.EndOfLineTrivia Then AnalyzeLineBreak(trivia, result) ElseIf trivia.Kind = SyntaxKind.CommentTrivia OrElse trivia.Kind = SyntaxKind.DocumentationCommentTrivia Then result.HasComments = True ElseIf trivia.Kind = SyntaxKind.DisabledTextTrivia OrElse trivia.Kind = SyntaxKind.SkippedTokensTrivia Then result.HasSkippedOrDisabledText = True ElseIf trivia.Kind = SyntaxKind.LineContinuationTrivia Then AnalyzeLineContinuation(trivia, result) ElseIf trivia.Kind = SyntaxKind.ColonTrivia Then result.HasColonTrivia = True ElseIf trivia.Kind = SyntaxKind.ConflictMarkerTrivia Then result.HasConflictMarker = True Else Contract.ThrowIfFalse(SyntaxFacts.IsPreprocessorDirective(trivia.Kind)) result.HasPreprocessor = True End If Next End Sub Private Shared Sub AnalyzeLineContinuation(trivia As SyntaxTrivia, ByRef result As AnalysisResult) result.LineBreaks += 1 result.HasTrailingSpace = trivia.ToFullString().Length <> 3 result.HasLineContinuation = True result.HasOnlyOneSpaceBeforeLineContinuation = result.Space = 1 AndAlso result.Tab = 0 result.HasTabAfterSpace = False result.Space = 0 result.Tab = 0 End Sub Private Shared Sub AnalyzeLineBreak(trivia As SyntaxTrivia, ByRef result As AnalysisResult) ' if there was any space before line break, then we have trailing spaces If result.Space > 0 OrElse result.Tab > 0 Then result.HasTrailingSpace = True End If ' reset space and tab information result.LineBreaks += 1 result.HasTabAfterSpace = False result.Space = 0 result.Tab = 0 result.TreatAsElastic = result.TreatAsElastic Or trivia.IsElastic() End Sub Private Shared Sub AnalyzeWhitespacesInTrivia(trivia As SyntaxTrivia, ByRef result As AnalysisResult) ' trivia already has text. getting text should be noop Debug.Assert(trivia.Kind = SyntaxKind.WhitespaceTrivia) Debug.Assert(trivia.Width = trivia.FullWidth) Dim space As Integer = 0 Dim tab As Integer = 0 Dim unknownWhitespace As Integer = 0 Dim text = trivia.ToString() For i As Integer = 0 To trivia.Width - 1 If text(i) = " "c Then space += 1 ElseIf text(i) = vbTab Then If result.Space > 0 Then result.HasTabAfterSpace = True End If tab += 1 Else unknownWhitespace += 1 End If Next i ' set result result.Space += space result.Tab += tab result.HasUnknownWhitespace = result.HasUnknownWhitespace Or unknownWhitespace > 0 result.TreatAsElastic = result.TreatAsElastic Or trivia.IsElastic() End Sub Friend Structure AnalysisResult Friend Property LineBreaks() As Integer Friend Property Space() As Integer Friend Property Tab() As Integer Friend Property HasTabAfterSpace() As Boolean Friend Property HasUnknownWhitespace() As Boolean Friend Property HasTrailingSpace() As Boolean Friend Property HasSkippedOrDisabledText() As Boolean Friend Property HasComments() As Boolean Friend Property HasPreprocessor() As Boolean Friend Property HasConflictMarker() As Boolean Friend Property HasOnlyOneSpaceBeforeLineContinuation() As Boolean Friend Property HasLineContinuation() As Boolean Friend Property HasColonTrivia() As Boolean Friend Property TreatAsElastic() As Boolean End Structure End Class End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Namespace Microsoft.CodeAnalysis.VisualBasic.Formatting Partial Friend Class TriviaDataFactory Private Class Analyzer Public Shared Function Leading(token As SyntaxToken) As AnalysisResult Dim result As AnalysisResult Analyze(token.LeadingTrivia, result) Return result End Function Public Shared Function Trailing(token As SyntaxToken) As AnalysisResult Dim result As AnalysisResult Analyze(token.TrailingTrivia, result) Return result End Function Public Shared Function Between(token1 As SyntaxToken, token2 As SyntaxToken) As AnalysisResult If (Not token1.HasTrailingTrivia) AndAlso (Not token2.HasLeadingTrivia) Then Return Nothing End If Dim result As AnalysisResult Analyze(token1.TrailingTrivia, result) Analyze(token2.LeadingTrivia, result) Return result End Function Private Shared Sub Analyze(list As SyntaxTriviaList, ByRef result As AnalysisResult) If list.Count = 0 Then Return End If For Each trivia In list If trivia.Kind = SyntaxKind.WhitespaceTrivia Then AnalyzeWhitespacesInTrivia(trivia, result) ElseIf trivia.Kind = SyntaxKind.EndOfLineTrivia Then AnalyzeLineBreak(trivia, result) ElseIf trivia.Kind = SyntaxKind.CommentTrivia OrElse trivia.Kind = SyntaxKind.DocumentationCommentTrivia Then result.HasComments = True ElseIf trivia.Kind = SyntaxKind.DisabledTextTrivia OrElse trivia.Kind = SyntaxKind.SkippedTokensTrivia Then result.HasSkippedOrDisabledText = True ElseIf trivia.Kind = SyntaxKind.LineContinuationTrivia Then AnalyzeLineContinuation(trivia, result) ElseIf trivia.Kind = SyntaxKind.ColonTrivia Then result.HasColonTrivia = True ElseIf trivia.Kind = SyntaxKind.ConflictMarkerTrivia Then result.HasConflictMarker = True Else Contract.ThrowIfFalse(SyntaxFacts.IsPreprocessorDirective(trivia.Kind)) result.HasPreprocessor = True End If Next End Sub Private Shared Sub AnalyzeLineContinuation(trivia As SyntaxTrivia, ByRef result As AnalysisResult) result.LineBreaks += 1 result.HasTrailingSpace = trivia.ToFullString().Length <> 3 result.HasLineContinuation = True result.HasOnlyOneSpaceBeforeLineContinuation = result.Space = 1 AndAlso result.Tab = 0 result.HasTabAfterSpace = False result.Space = 0 result.Tab = 0 End Sub Private Shared Sub AnalyzeLineBreak(trivia As SyntaxTrivia, ByRef result As AnalysisResult) ' if there was any space before line break, then we have trailing spaces If result.Space > 0 OrElse result.Tab > 0 Then result.HasTrailingSpace = True End If ' reset space and tab information result.LineBreaks += 1 result.HasTabAfterSpace = False result.Space = 0 result.Tab = 0 result.TreatAsElastic = result.TreatAsElastic Or trivia.IsElastic() End Sub Private Shared Sub AnalyzeWhitespacesInTrivia(trivia As SyntaxTrivia, ByRef result As AnalysisResult) ' trivia already has text. getting text should be noop Debug.Assert(trivia.Kind = SyntaxKind.WhitespaceTrivia) Debug.Assert(trivia.Width = trivia.FullWidth) Dim space As Integer = 0 Dim tab As Integer = 0 Dim unknownWhitespace As Integer = 0 Dim text = trivia.ToString() For i As Integer = 0 To trivia.Width - 1 If text(i) = " "c Then space += 1 ElseIf text(i) = vbTab Then If result.Space > 0 Then result.HasTabAfterSpace = True End If tab += 1 Else unknownWhitespace += 1 End If Next i ' set result result.Space += space result.Tab += tab result.HasUnknownWhitespace = result.HasUnknownWhitespace Or unknownWhitespace > 0 result.TreatAsElastic = result.TreatAsElastic Or trivia.IsElastic() End Sub Friend Structure AnalysisResult Friend Property LineBreaks() As Integer Friend Property Space() As Integer Friend Property Tab() As Integer Friend Property HasTabAfterSpace() As Boolean Friend Property HasUnknownWhitespace() As Boolean Friend Property HasTrailingSpace() As Boolean Friend Property HasSkippedOrDisabledText() As Boolean Friend Property HasComments() As Boolean Friend Property HasPreprocessor() As Boolean Friend Property HasConflictMarker() As Boolean Friend Property HasOnlyOneSpaceBeforeLineContinuation() As Boolean Friend Property HasLineContinuation() As Boolean Friend Property HasColonTrivia() As Boolean Friend Property TreatAsElastic() As Boolean End Structure End Class End Class End Namespace
-1
dotnet/roslyn
55,138
Avoid cancellation exceptions in intermediate operations
Addresses the following exceptions: ![image](https://user-images.githubusercontent.com/1408396/127185947-8a005aea-ae1c-4755-bf0f-21dfb8101352.png)
sharwell
2021-07-27T15:51:28Z
2021-07-27T21:36:45Z
3d8acbd585a75e9cdb3509623bf6c39ceb46b2c2
719d4ffa2be734463e5d7d4d74b23b8006fd7727
Avoid cancellation exceptions in intermediate operations. Addresses the following exceptions: ![image](https://user-images.githubusercontent.com/1408396/127185947-8a005aea-ae1c-4755-bf0f-21dfb8101352.png)
./src/Workspaces/Core/Portable/Simplification/ISimplificationService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.Simplification { internal interface ISimplificationService : ILanguageService { SyntaxNode Expand( SyntaxNode node, SemanticModel semanticModel, SyntaxAnnotation annotationForReplacedAliasIdentifier, Func<SyntaxNode, bool> expandInsideNode, bool expandParameter, CancellationToken cancellationToken); SyntaxToken Expand( SyntaxToken token, SemanticModel semanticModel, Func<SyntaxNode, bool> expandInsideNode, CancellationToken cancellationToken); Task<Document> ReduceAsync( Document document, ImmutableArray<TextSpan> spans, OptionSet optionSet = null, ImmutableArray<AbstractReducer> reducers = default, CancellationToken cancellationToken = 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.Immutable; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.Simplification { internal interface ISimplificationService : ILanguageService { SyntaxNode Expand( SyntaxNode node, SemanticModel semanticModel, SyntaxAnnotation annotationForReplacedAliasIdentifier, Func<SyntaxNode, bool> expandInsideNode, bool expandParameter, CancellationToken cancellationToken); SyntaxToken Expand( SyntaxToken token, SemanticModel semanticModel, Func<SyntaxNode, bool> expandInsideNode, CancellationToken cancellationToken); Task<Document> ReduceAsync( Document document, ImmutableArray<TextSpan> spans, OptionSet optionSet = null, ImmutableArray<AbstractReducer> reducers = default, CancellationToken cancellationToken = default); } }
-1
dotnet/roslyn
55,138
Avoid cancellation exceptions in intermediate operations
Addresses the following exceptions: ![image](https://user-images.githubusercontent.com/1408396/127185947-8a005aea-ae1c-4755-bf0f-21dfb8101352.png)
sharwell
2021-07-27T15:51:28Z
2021-07-27T21:36:45Z
3d8acbd585a75e9cdb3509623bf6c39ceb46b2c2
719d4ffa2be734463e5d7d4d74b23b8006fd7727
Avoid cancellation exceptions in intermediate operations. Addresses the following exceptions: ![image](https://user-images.githubusercontent.com/1408396/127185947-8a005aea-ae1c-4755-bf0f-21dfb8101352.png)
./src/Features/Lsif/GeneratorTest/CompilerInvocationTests.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.Test.Utilities Namespace Microsoft.CodeAnalysis.LanguageServerIndexFormat.Generator.UnitTests <UseExportProvider> Public Class CompilerInvocationTests <Fact> Public Async Function TestCSharpProject() As Task ' PortableExecutableReference.CreateFromFile implicitly reads the file so the file must exist. Dim referencePath = GetType(Object).Assembly.Location Dim compilerInvocation = Await Microsoft.CodeAnalysis.LanguageServerIndexFormat.Generator.CompilerInvocation.CreateFromJsonAsync(" { ""tool"": ""csc"", ""arguments"": ""/noconfig /nowarn:1701,1702 /fullpaths /define:DEBUG /reference:" + referencePath.Replace("\", "\\") + " Z:\\SourceFile.cs /target:library /out:Z:\\Output.dll"", ""projectFilePath"": ""Z:\\Project.csproj"", ""sourceRootPath"": ""Z:\\"" }") Assert.Equal(LanguageNames.CSharp, compilerInvocation.Compilation.Language) Assert.Equal("Z:\Project.csproj", compilerInvocation.ProjectFilePath) Assert.Equal(OutputKind.DynamicallyLinkedLibrary, compilerInvocation.Compilation.Options.OutputKind) Dim syntaxTree = Assert.Single(compilerInvocation.Compilation.SyntaxTrees) Assert.Equal("Z:\SourceFile.cs", syntaxTree.FilePath) Assert.Equal("DEBUG", Assert.Single(syntaxTree.Options.PreprocessorSymbolNames)) Dim metadataReference = Assert.Single(compilerInvocation.Compilation.References) Assert.Equal(referencePath, DirectCast(metadataReference, PortableExecutableReference).FilePath) End Function <Fact> Public Async Function TestVisualBasicProject() As Task ' PortableExecutableReference.CreateFromFile implicitly reads the file so the file must exist. Dim referencePath = GetType(Object).Assembly.Location Dim compilerInvocation = Await Microsoft.CodeAnalysis.LanguageServerIndexFormat.Generator.CompilerInvocation.CreateFromJsonAsync(" { ""tool"": ""vbc"", ""arguments"": ""/noconfig /nowarn:1701,1702 /fullpaths /define:DEBUG /reference:" + referencePath.Replace("\", "\\") + " Z:\\SourceFile.vb /target:library /out:Z:\\Output.dll"", ""projectFilePath"": ""Z:\\Project.vbproj"", ""sourceRootPath"": ""Z:\\"" }") Assert.Equal(LanguageNames.VisualBasic, compilerInvocation.Compilation.Language) Assert.Equal("Z:\Project.vbproj", compilerInvocation.ProjectFilePath) Assert.Equal(OutputKind.DynamicallyLinkedLibrary, compilerInvocation.Compilation.Options.OutputKind) Dim syntaxTree = Assert.Single(compilerInvocation.Compilation.SyntaxTrees) Assert.Equal("Z:\SourceFile.vb", syntaxTree.FilePath) Assert.Contains("DEBUG", syntaxTree.Options.PreprocessorSymbolNames) Dim metadataReference = Assert.Single(compilerInvocation.Compilation.References) Assert.Equal(referencePath, DirectCast(metadataReference, PortableExecutableReference).FilePath) End Function <Theory> <CombinatorialData> Public Async Function TestSourceFilePathMappingWithDriveLetters(<CombinatorialValues("F:", "F:\")> from As String, <CombinatorialValues("T:", "T:\")> [to] As String) As Task Dim compilerInvocation = Await Microsoft.CodeAnalysis.LanguageServerIndexFormat.Generator.CompilerInvocation.CreateFromJsonAsync(" { ""tool"": ""csc"", ""arguments"": ""/noconfig /nowarn:1701,1702 /fullpaths /define:DEBUG F:\\SourceFile.cs /target:library /out:F:\\Output.dll"", ""projectFilePath"": ""F:\\Project.csproj"", ""sourceRootPath"": ""F:\\"", ""pathMappings"": [ { ""from"": """ + from.Replace("\", "\\") + """, ""to"": """ + [to].Replace("\", "\\") + """ }] }") Dim syntaxTree = Assert.Single(compilerInvocation.Compilation.SyntaxTrees) Assert.Equal("T:\SourceFile.cs", syntaxTree.FilePath) End Function <Fact> Public Async Function TestSourceFilePathMappingWithSubdirectoriesWithoutTrailingSlashes() As Task Dim compilerInvocation = Await Microsoft.CodeAnalysis.LanguageServerIndexFormat.Generator.CompilerInvocation.CreateFromJsonAsync(" { ""tool"": ""csc"", ""arguments"": ""/noconfig /nowarn:1701,1702 /fullpaths /define:DEBUG F:\\Directory\\SourceFile.cs /target:library /out:F:\\Output.dll"", ""projectFilePath"": ""F:\\Project.csproj"", ""sourceRootPath"": ""F:\\"", ""pathMappings"": [ { ""from"": ""F:\\Directory"", ""to"": ""T:\\Directory"" }] }") Dim syntaxTree = Assert.Single(compilerInvocation.Compilation.SyntaxTrees) Assert.Equal("T:\Directory\SourceFile.cs", syntaxTree.FilePath) End Function <Fact> Public Async Function TestSourceFilePathMappingWithSubdirectoriesWithDoubleSlashesInFilePath() As Task Dim compilerInvocation = Await Microsoft.CodeAnalysis.LanguageServerIndexFormat.Generator.CompilerInvocation.CreateFromJsonAsync(" { ""tool"": ""csc"", ""arguments"": ""/noconfig /nowarn:1701,1702 /fullpaths /define:DEBUG F:\\Directory\\\\SourceFile.cs /target:library /out:F:\\Output.dll"", ""projectFilePath"": ""F:\\Project.csproj"", ""sourceRootPath"": ""F:\\"", ""pathMappings"": [ { ""from"": ""F:\\Directory"", ""to"": ""T:\\Directory"" }] }") Dim syntaxTree = Assert.Single(compilerInvocation.Compilation.SyntaxTrees) Assert.Equal("T:\Directory\SourceFile.cs", syntaxTree.FilePath) End Function <Fact> Public Async Function TestRuleSetPathMapping() As Task Const RuleSetContents = "<?xml version=""1.0""?> <RuleSet Name=""Name"" ToolsVersion=""10.0""> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1001"" Action=""Warning"" /> </Rules> </RuleSet>" Using ruleSet = New DisposableFile(extension:=".ruleset") ruleSet.WriteAllText(RuleSetContents) ' We will test that if we redirect the ruleset to the temporary file that we wrote that the values are still read. Dim compilerInvocation = Await Microsoft.CodeAnalysis.LanguageServerIndexFormat.Generator.CompilerInvocation.CreateFromJsonAsync(" { ""tool"": ""csc"", ""arguments"": ""/noconfig /nowarn:1701,1702 /fullpaths /define:DEBUG /ruleset:F:\\Ruleset.ruleset /out:Output.dll"", ""projectFilePath"": ""F:\\Project.csproj"", ""sourceRootPath"": ""F:\\"", ""pathMappings"": [ { ""from"": ""F:\\Ruleset.ruleset"", ""to"": """ + ruleSet.Path.Replace("\", "\\") + """ }] }") Assert.Equal(ReportDiagnostic.Warn, compilerInvocation.Compilation.Options.SpecificDiagnosticOptions("CA1001")) End Using End Function <Fact> Public Async Function TestSourceGeneratorOutputIncludedInCompilation() As Task Dim sourceGeneratorLocation = GetType(TestSourceGenerator.HelloWorldGenerator).Assembly.Location Dim compilerInvocation = Await Microsoft.CodeAnalysis.LanguageServerIndexFormat.Generator.CompilerInvocation.CreateFromJsonAsync(" { ""tool"": ""csc"", ""arguments"": ""/noconfig /analyzer:\""" + sourceGeneratorLocation.Replace("\", "\\") + "\"" /out:Output.dll"", ""projectFilePath"": ""F:\\Project.csproj"", ""sourceRootPath"": ""F:\\"" }") Dim generatedTrees = compilerInvocation.Compilation.SyntaxTrees Assert.Single(generatedTrees, Function(t) t.FilePath.EndsWith(TestSourceGenerator.HelloWorldGenerator.GeneratedEnglishClassName + ".cs")) Assert.Single(generatedTrees, Function(t) t.FilePath.EndsWith(TestSourceGenerator.HelloWorldGenerator.GeneratedSpanishClassName + ".cs")) End Function End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.Test.Utilities Namespace Microsoft.CodeAnalysis.LanguageServerIndexFormat.Generator.UnitTests <UseExportProvider> Public Class CompilerInvocationTests <Fact> Public Async Function TestCSharpProject() As Task ' PortableExecutableReference.CreateFromFile implicitly reads the file so the file must exist. Dim referencePath = GetType(Object).Assembly.Location Dim compilerInvocation = Await Microsoft.CodeAnalysis.LanguageServerIndexFormat.Generator.CompilerInvocation.CreateFromJsonAsync(" { ""tool"": ""csc"", ""arguments"": ""/noconfig /nowarn:1701,1702 /fullpaths /define:DEBUG /reference:" + referencePath.Replace("\", "\\") + " Z:\\SourceFile.cs /target:library /out:Z:\\Output.dll"", ""projectFilePath"": ""Z:\\Project.csproj"", ""sourceRootPath"": ""Z:\\"" }") Assert.Equal(LanguageNames.CSharp, compilerInvocation.Compilation.Language) Assert.Equal("Z:\Project.csproj", compilerInvocation.ProjectFilePath) Assert.Equal(OutputKind.DynamicallyLinkedLibrary, compilerInvocation.Compilation.Options.OutputKind) Dim syntaxTree = Assert.Single(compilerInvocation.Compilation.SyntaxTrees) Assert.Equal("Z:\SourceFile.cs", syntaxTree.FilePath) Assert.Equal("DEBUG", Assert.Single(syntaxTree.Options.PreprocessorSymbolNames)) Dim metadataReference = Assert.Single(compilerInvocation.Compilation.References) Assert.Equal(referencePath, DirectCast(metadataReference, PortableExecutableReference).FilePath) End Function <Fact> Public Async Function TestVisualBasicProject() As Task ' PortableExecutableReference.CreateFromFile implicitly reads the file so the file must exist. Dim referencePath = GetType(Object).Assembly.Location Dim compilerInvocation = Await Microsoft.CodeAnalysis.LanguageServerIndexFormat.Generator.CompilerInvocation.CreateFromJsonAsync(" { ""tool"": ""vbc"", ""arguments"": ""/noconfig /nowarn:1701,1702 /fullpaths /define:DEBUG /reference:" + referencePath.Replace("\", "\\") + " Z:\\SourceFile.vb /target:library /out:Z:\\Output.dll"", ""projectFilePath"": ""Z:\\Project.vbproj"", ""sourceRootPath"": ""Z:\\"" }") Assert.Equal(LanguageNames.VisualBasic, compilerInvocation.Compilation.Language) Assert.Equal("Z:\Project.vbproj", compilerInvocation.ProjectFilePath) Assert.Equal(OutputKind.DynamicallyLinkedLibrary, compilerInvocation.Compilation.Options.OutputKind) Dim syntaxTree = Assert.Single(compilerInvocation.Compilation.SyntaxTrees) Assert.Equal("Z:\SourceFile.vb", syntaxTree.FilePath) Assert.Contains("DEBUG", syntaxTree.Options.PreprocessorSymbolNames) Dim metadataReference = Assert.Single(compilerInvocation.Compilation.References) Assert.Equal(referencePath, DirectCast(metadataReference, PortableExecutableReference).FilePath) End Function <Theory> <CombinatorialData> Public Async Function TestSourceFilePathMappingWithDriveLetters(<CombinatorialValues("F:", "F:\")> from As String, <CombinatorialValues("T:", "T:\")> [to] As String) As Task Dim compilerInvocation = Await Microsoft.CodeAnalysis.LanguageServerIndexFormat.Generator.CompilerInvocation.CreateFromJsonAsync(" { ""tool"": ""csc"", ""arguments"": ""/noconfig /nowarn:1701,1702 /fullpaths /define:DEBUG F:\\SourceFile.cs /target:library /out:F:\\Output.dll"", ""projectFilePath"": ""F:\\Project.csproj"", ""sourceRootPath"": ""F:\\"", ""pathMappings"": [ { ""from"": """ + from.Replace("\", "\\") + """, ""to"": """ + [to].Replace("\", "\\") + """ }] }") Dim syntaxTree = Assert.Single(compilerInvocation.Compilation.SyntaxTrees) Assert.Equal("T:\SourceFile.cs", syntaxTree.FilePath) End Function <Fact> Public Async Function TestSourceFilePathMappingWithSubdirectoriesWithoutTrailingSlashes() As Task Dim compilerInvocation = Await Microsoft.CodeAnalysis.LanguageServerIndexFormat.Generator.CompilerInvocation.CreateFromJsonAsync(" { ""tool"": ""csc"", ""arguments"": ""/noconfig /nowarn:1701,1702 /fullpaths /define:DEBUG F:\\Directory\\SourceFile.cs /target:library /out:F:\\Output.dll"", ""projectFilePath"": ""F:\\Project.csproj"", ""sourceRootPath"": ""F:\\"", ""pathMappings"": [ { ""from"": ""F:\\Directory"", ""to"": ""T:\\Directory"" }] }") Dim syntaxTree = Assert.Single(compilerInvocation.Compilation.SyntaxTrees) Assert.Equal("T:\Directory\SourceFile.cs", syntaxTree.FilePath) End Function <Fact> Public Async Function TestSourceFilePathMappingWithSubdirectoriesWithDoubleSlashesInFilePath() As Task Dim compilerInvocation = Await Microsoft.CodeAnalysis.LanguageServerIndexFormat.Generator.CompilerInvocation.CreateFromJsonAsync(" { ""tool"": ""csc"", ""arguments"": ""/noconfig /nowarn:1701,1702 /fullpaths /define:DEBUG F:\\Directory\\\\SourceFile.cs /target:library /out:F:\\Output.dll"", ""projectFilePath"": ""F:\\Project.csproj"", ""sourceRootPath"": ""F:\\"", ""pathMappings"": [ { ""from"": ""F:\\Directory"", ""to"": ""T:\\Directory"" }] }") Dim syntaxTree = Assert.Single(compilerInvocation.Compilation.SyntaxTrees) Assert.Equal("T:\Directory\SourceFile.cs", syntaxTree.FilePath) End Function <Fact> Public Async Function TestRuleSetPathMapping() As Task Const RuleSetContents = "<?xml version=""1.0""?> <RuleSet Name=""Name"" ToolsVersion=""10.0""> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1001"" Action=""Warning"" /> </Rules> </RuleSet>" Using ruleSet = New DisposableFile(extension:=".ruleset") ruleSet.WriteAllText(RuleSetContents) ' We will test that if we redirect the ruleset to the temporary file that we wrote that the values are still read. Dim compilerInvocation = Await Microsoft.CodeAnalysis.LanguageServerIndexFormat.Generator.CompilerInvocation.CreateFromJsonAsync(" { ""tool"": ""csc"", ""arguments"": ""/noconfig /nowarn:1701,1702 /fullpaths /define:DEBUG /ruleset:F:\\Ruleset.ruleset /out:Output.dll"", ""projectFilePath"": ""F:\\Project.csproj"", ""sourceRootPath"": ""F:\\"", ""pathMappings"": [ { ""from"": ""F:\\Ruleset.ruleset"", ""to"": """ + ruleSet.Path.Replace("\", "\\") + """ }] }") Assert.Equal(ReportDiagnostic.Warn, compilerInvocation.Compilation.Options.SpecificDiagnosticOptions("CA1001")) End Using End Function <Fact> Public Async Function TestSourceGeneratorOutputIncludedInCompilation() As Task Dim sourceGeneratorLocation = GetType(TestSourceGenerator.HelloWorldGenerator).Assembly.Location Dim compilerInvocation = Await Microsoft.CodeAnalysis.LanguageServerIndexFormat.Generator.CompilerInvocation.CreateFromJsonAsync(" { ""tool"": ""csc"", ""arguments"": ""/noconfig /analyzer:\""" + sourceGeneratorLocation.Replace("\", "\\") + "\"" /out:Output.dll"", ""projectFilePath"": ""F:\\Project.csproj"", ""sourceRootPath"": ""F:\\"" }") Dim generatedTrees = compilerInvocation.Compilation.SyntaxTrees Assert.Single(generatedTrees, Function(t) t.FilePath.EndsWith(TestSourceGenerator.HelloWorldGenerator.GeneratedEnglishClassName + ".cs")) Assert.Single(generatedTrees, Function(t) t.FilePath.EndsWith(TestSourceGenerator.HelloWorldGenerator.GeneratedSpanishClassName + ".cs")) End Function End Class End Namespace
-1
dotnet/roslyn
55,138
Avoid cancellation exceptions in intermediate operations
Addresses the following exceptions: ![image](https://user-images.githubusercontent.com/1408396/127185947-8a005aea-ae1c-4755-bf0f-21dfb8101352.png)
sharwell
2021-07-27T15:51:28Z
2021-07-27T21:36:45Z
3d8acbd585a75e9cdb3509623bf6c39ceb46b2c2
719d4ffa2be734463e5d7d4d74b23b8006fd7727
Avoid cancellation exceptions in intermediate operations. Addresses the following exceptions: ![image](https://user-images.githubusercontent.com/1408396/127185947-8a005aea-ae1c-4755-bf0f-21dfb8101352.png)
./src/Compilers/CSharp/Portable/Symbols/ConstructedNamedTypeSymbol.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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 Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols { /// <summary> /// A named type symbol that results from substituting a new owner for a type declaration. /// </summary> internal sealed class SubstitutedNestedTypeSymbol : SubstitutedNamedTypeSymbol { internal SubstitutedNestedTypeSymbol(SubstitutedNamedTypeSymbol newContainer, NamedTypeSymbol originalDefinition) : base( newContainer: newContainer, map: newContainer.TypeSubstitution, originalDefinition: originalDefinition, // An Arity-0 member of an unbound type, e.g. A<>.B, is unbound. unbound: newContainer.IsUnboundGenericType && originalDefinition.Arity == 0) { } internal override bool GetUnificationUseSiteDiagnosticRecursive(ref DiagnosticInfo result, Symbol owner, ref HashSet<TypeSymbol> checkedTypes) => OriginalDefinition.GetUnificationUseSiteDiagnosticRecursive(ref result, owner, ref checkedTypes); internal override ImmutableArray<TypeWithAnnotations> TypeArgumentsWithAnnotationsNoUseSiteDiagnostics { get { return GetTypeParametersAsTypeArguments(); } } public override NamedTypeSymbol ConstructedFrom { get { return this; } } public sealed override bool AreLocalsZeroed { get { throw ExceptionUtilities.Unreachable; } } protected override NamedTypeSymbol WithTupleDataCore(TupleExtraData newData) { throw ExceptionUtilities.Unreachable; } } /// <summary> /// A generic named type symbol that has been constructed with type arguments distinct from its own type parameters. /// </summary> internal sealed class ConstructedNamedTypeSymbol : SubstitutedNamedTypeSymbol { private readonly ImmutableArray<TypeWithAnnotations> _typeArgumentsWithAnnotations; private readonly NamedTypeSymbol _constructedFrom; internal ConstructedNamedTypeSymbol(NamedTypeSymbol constructedFrom, ImmutableArray<TypeWithAnnotations> typeArgumentsWithAnnotations, bool unbound = false, TupleExtraData tupleData = null) : base(newContainer: constructedFrom.ContainingSymbol, map: new TypeMap(constructedFrom.ContainingType, constructedFrom.OriginalDefinition.TypeParameters, typeArgumentsWithAnnotations), originalDefinition: constructedFrom.OriginalDefinition, constructedFrom: constructedFrom, unbound: unbound, tupleData: tupleData) { _typeArgumentsWithAnnotations = typeArgumentsWithAnnotations; _constructedFrom = constructedFrom; Debug.Assert(constructedFrom.Arity == typeArgumentsWithAnnotations.Length); Debug.Assert(constructedFrom.Arity != 0); } protected override NamedTypeSymbol WithTupleDataCore(TupleExtraData newData) { return new ConstructedNamedTypeSymbol(_constructedFrom, _typeArgumentsWithAnnotations, IsUnboundGenericType, tupleData: newData); } public override NamedTypeSymbol ConstructedFrom { get { return _constructedFrom; } } internal override ImmutableArray<TypeWithAnnotations> TypeArgumentsWithAnnotationsNoUseSiteDiagnostics { get { return _typeArgumentsWithAnnotations; } } internal static bool TypeParametersMatchTypeArguments(ImmutableArray<TypeParameterSymbol> typeParameters, ImmutableArray<TypeWithAnnotations> typeArguments) { int n = typeParameters.Length; Debug.Assert(typeArguments.Length == n); Debug.Assert(typeArguments.Length > 0); for (int i = 0; i < n; i++) { if (!typeArguments[i].Is(typeParameters[i])) { return false; } } return true; } internal sealed override bool GetUnificationUseSiteDiagnosticRecursive(ref DiagnosticInfo result, Symbol owner, ref HashSet<TypeSymbol> checkedTypes) { if (ConstructedFrom.GetUnificationUseSiteDiagnosticRecursive(ref result, owner, ref checkedTypes) || GetUnificationUseSiteDiagnosticRecursive(ref result, _typeArgumentsWithAnnotations, owner, ref checkedTypes)) { return true; } var typeArguments = this.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics; foreach (var typeArg in typeArguments) { if (GetUnificationUseSiteDiagnosticRecursive(ref result, typeArg.CustomModifiers, owner, ref checkedTypes)) { return true; } } return false; } public sealed override bool AreLocalsZeroed { get { 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. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols { /// <summary> /// A named type symbol that results from substituting a new owner for a type declaration. /// </summary> internal sealed class SubstitutedNestedTypeSymbol : SubstitutedNamedTypeSymbol { internal SubstitutedNestedTypeSymbol(SubstitutedNamedTypeSymbol newContainer, NamedTypeSymbol originalDefinition) : base( newContainer: newContainer, map: newContainer.TypeSubstitution, originalDefinition: originalDefinition, // An Arity-0 member of an unbound type, e.g. A<>.B, is unbound. unbound: newContainer.IsUnboundGenericType && originalDefinition.Arity == 0) { } internal override bool GetUnificationUseSiteDiagnosticRecursive(ref DiagnosticInfo result, Symbol owner, ref HashSet<TypeSymbol> checkedTypes) => OriginalDefinition.GetUnificationUseSiteDiagnosticRecursive(ref result, owner, ref checkedTypes); internal override ImmutableArray<TypeWithAnnotations> TypeArgumentsWithAnnotationsNoUseSiteDiagnostics { get { return GetTypeParametersAsTypeArguments(); } } public override NamedTypeSymbol ConstructedFrom { get { return this; } } public sealed override bool AreLocalsZeroed { get { throw ExceptionUtilities.Unreachable; } } protected override NamedTypeSymbol WithTupleDataCore(TupleExtraData newData) { throw ExceptionUtilities.Unreachable; } } /// <summary> /// A generic named type symbol that has been constructed with type arguments distinct from its own type parameters. /// </summary> internal sealed class ConstructedNamedTypeSymbol : SubstitutedNamedTypeSymbol { private readonly ImmutableArray<TypeWithAnnotations> _typeArgumentsWithAnnotations; private readonly NamedTypeSymbol _constructedFrom; internal ConstructedNamedTypeSymbol(NamedTypeSymbol constructedFrom, ImmutableArray<TypeWithAnnotations> typeArgumentsWithAnnotations, bool unbound = false, TupleExtraData tupleData = null) : base(newContainer: constructedFrom.ContainingSymbol, map: new TypeMap(constructedFrom.ContainingType, constructedFrom.OriginalDefinition.TypeParameters, typeArgumentsWithAnnotations), originalDefinition: constructedFrom.OriginalDefinition, constructedFrom: constructedFrom, unbound: unbound, tupleData: tupleData) { _typeArgumentsWithAnnotations = typeArgumentsWithAnnotations; _constructedFrom = constructedFrom; Debug.Assert(constructedFrom.Arity == typeArgumentsWithAnnotations.Length); Debug.Assert(constructedFrom.Arity != 0); } protected override NamedTypeSymbol WithTupleDataCore(TupleExtraData newData) { return new ConstructedNamedTypeSymbol(_constructedFrom, _typeArgumentsWithAnnotations, IsUnboundGenericType, tupleData: newData); } public override NamedTypeSymbol ConstructedFrom { get { return _constructedFrom; } } internal override ImmutableArray<TypeWithAnnotations> TypeArgumentsWithAnnotationsNoUseSiteDiagnostics { get { return _typeArgumentsWithAnnotations; } } internal static bool TypeParametersMatchTypeArguments(ImmutableArray<TypeParameterSymbol> typeParameters, ImmutableArray<TypeWithAnnotations> typeArguments) { int n = typeParameters.Length; Debug.Assert(typeArguments.Length == n); Debug.Assert(typeArguments.Length > 0); for (int i = 0; i < n; i++) { if (!typeArguments[i].Is(typeParameters[i])) { return false; } } return true; } internal sealed override bool GetUnificationUseSiteDiagnosticRecursive(ref DiagnosticInfo result, Symbol owner, ref HashSet<TypeSymbol> checkedTypes) { if (ConstructedFrom.GetUnificationUseSiteDiagnosticRecursive(ref result, owner, ref checkedTypes) || GetUnificationUseSiteDiagnosticRecursive(ref result, _typeArgumentsWithAnnotations, owner, ref checkedTypes)) { return true; } var typeArguments = this.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics; foreach (var typeArg in typeArguments) { if (GetUnificationUseSiteDiagnosticRecursive(ref result, typeArg.CustomModifiers, owner, ref checkedTypes)) { return true; } } return false; } public sealed override bool AreLocalsZeroed { get { throw ExceptionUtilities.Unreachable; } } } }
-1
dotnet/roslyn
55,138
Avoid cancellation exceptions in intermediate operations
Addresses the following exceptions: ![image](https://user-images.githubusercontent.com/1408396/127185947-8a005aea-ae1c-4755-bf0f-21dfb8101352.png)
sharwell
2021-07-27T15:51:28Z
2021-07-27T21:36:45Z
3d8acbd585a75e9cdb3509623bf6c39ceb46b2c2
719d4ffa2be734463e5d7d4d74b23b8006fd7727
Avoid cancellation exceptions in intermediate operations. Addresses the following exceptions: ![image](https://user-images.githubusercontent.com/1408396/127185947-8a005aea-ae1c-4755-bf0f-21dfb8101352.png)
./src/Compilers/VisualBasic/Test/IOperation/IOperation/IOperationTests_ITupleExpression.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Microsoft.CodeAnalysis.Test.Utilities Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics Partial Public Class IOperationTests Inherits SemanticModelTestBase <CompilerTrait(CompilerFeature.IOperation)> <Fact, WorkItem(10856, "https://github.com/dotnet/roslyn/issues/10856")> Public Sub TupleExpression_NoConversions() Dim source = <![CDATA[ Imports System Class C Shared Sub Main() Dim t As (Integer, Integer) = (1, 2)'BIND:"(1, 2)" End Sub End Class]]>.Value Dim expectedOperationTree = <![CDATA[ ITupleOperation (OperationKind.Tuple, Type: (System.Int32, System.Int32)) (Syntax: '(1, 2)') NaturalType: (System.Int32, System.Int32) Elements(2): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of TupleExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact, WorkItem(10856, "https://github.com/dotnet/roslyn/issues/10856")> Public Sub TupleExpression_NoConversions_ParentVariableDeclaration() Dim source = <![CDATA[ Imports System Class C Shared Sub Main() Dim t As (Integer, Integer) = (1, 2)'BIND:"Dim t As (Integer, Integer) = (1, 2)" End Sub End Class]]>.Value Dim expectedOperationTree = <![CDATA[ IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'Dim t As (I ... r) = (1, 2)') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 't As (Integ ... r) = (1, 2)') Declarators: IVariableDeclaratorOperation (Symbol: t As (System.Int32, System.Int32)) (OperationKind.VariableDeclarator, Type: null) (Syntax: 't') Initializer: null Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= (1, 2)') ITupleOperation (OperationKind.Tuple, Type: (System.Int32, System.Int32)) (Syntax: '(1, 2)') NaturalType: (System.Int32, System.Int32) Elements(2): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of LocalDeclarationStatementSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact, WorkItem(10856, "https://github.com/dotnet/roslyn/issues/10856")> Public Sub TupleExpression_ImplicitConversions() Dim source = <![CDATA[ Imports System Class C Shared Sub Main() Dim t As (UInteger, UInteger) = (1, 2)'BIND:"(1, 2)" End Sub End Class]]>.Value Dim expectedOperationTree = <![CDATA[ ITupleOperation (OperationKind.Tuple, Type: (System.UInt32, System.UInt32)) (Syntax: '(1, 2)') NaturalType: (System.Int32, System.Int32) Elements(2): IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.UInt32, Constant: 1, IsImplicit) (Syntax: '1') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.UInt32, Constant: 2, IsImplicit) (Syntax: '2') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of TupleExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact, WorkItem(10856, "https://github.com/dotnet/roslyn/issues/10856")> Public Sub TupleExpression_ImplicitConversions_ParentVariableDeclaration() Dim source = <![CDATA[ Imports System Class C Shared Sub Main() Dim t As (UInteger, UInteger) = (1, 2)'BIND:"Dim t As (UInteger, UInteger) = (1, 2)" End Sub End Class]]>.Value Dim expectedOperationTree = <![CDATA[ IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'Dim t As (U ... r) = (1, 2)') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 't As (UInte ... r) = (1, 2)') Declarators: IVariableDeclaratorOperation (Symbol: t As (System.UInt32, System.UInt32)) (OperationKind.VariableDeclarator, Type: null) (Syntax: 't') Initializer: null Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= (1, 2)') ITupleOperation (OperationKind.Tuple, Type: (System.UInt32, System.UInt32)) (Syntax: '(1, 2)') NaturalType: (System.Int32, System.Int32) Elements(2): IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.UInt32, Constant: 1, IsImplicit) (Syntax: '1') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.UInt32, Constant: 2, IsImplicit) (Syntax: '2') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of LocalDeclarationStatementSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact, WorkItem(10856, "https://github.com/dotnet/roslyn/issues/10856")> Public Sub TupleExpression_ImplicitConversionFromNull() Dim source = <![CDATA[ Imports System Class C Shared Sub Main() Dim t As (UInteger, String) = (1, Nothing)'BIND:"(1, Nothing)" End Sub End Class]]>.Value Dim expectedOperationTree = <![CDATA[ ITupleOperation (OperationKind.Tuple, Type: (System.UInt32, System.String)) (Syntax: '(1, Nothing)') NaturalType: null Elements(2): IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.UInt32, Constant: 1, IsImplicit) (Syntax: '1') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.String, Constant: null, IsImplicit) (Syntax: 'Nothing') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'Nothing') ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of TupleExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact, WorkItem(10856, "https://github.com/dotnet/roslyn/issues/10856")> Public Sub TupleExpression_ImplicitConversionFromNull_ParentVariableDeclaration() Dim source = <![CDATA[ Imports System Class C Shared Sub Main() Dim t As (UInteger, String) = (1, Nothing)'BIND:"Dim t As (UInteger, String) = (1, Nothing)" End Sub End Class]]>.Value Dim expectedOperationTree = <![CDATA[ IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'Dim t As (U ... 1, Nothing)') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 't As (UInte ... 1, Nothing)') Declarators: IVariableDeclaratorOperation (Symbol: t As (System.UInt32, System.String)) (OperationKind.VariableDeclarator, Type: null) (Syntax: 't') Initializer: null Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= (1, Nothing)') ITupleOperation (OperationKind.Tuple, Type: (System.UInt32, System.String)) (Syntax: '(1, Nothing)') NaturalType: null Elements(2): IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.UInt32, Constant: 1, IsImplicit) (Syntax: '1') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.String, Constant: null, IsImplicit) (Syntax: 'Nothing') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'Nothing') ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of LocalDeclarationStatementSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact, WorkItem(10856, "https://github.com/dotnet/roslyn/issues/10856")> Public Sub TupleExpression_NamedArguments() Dim source = <![CDATA[ Option Strict Off Imports System Class C Shared Sub Main() Dim t = (A:=1, B:=2)'BIND:"(A:=1, B:=2)" End Sub End Class]]>.Value Dim expectedOperationTree = <![CDATA[ ITupleOperation (OperationKind.Tuple, Type: (A As System.Int32, B As System.Int32)) (Syntax: '(A:=1, B:=2)') NaturalType: (A As System.Int32, B As System.Int32) Elements(2): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of TupleExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact, WorkItem(10856, "https://github.com/dotnet/roslyn/issues/10856")> Public Sub TupleExpression_NamedArguments_ParentVariableDeclaration() Dim source = <![CDATA[ Option Strict Off Imports System Class C Shared Sub Main() Dim t = (A:=1, B:=2)'BIND:"Dim t = (A:=1, B:=2)" End Sub End Class]]>.Value Dim expectedOperationTree = <![CDATA[ IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'Dim t = (A:=1, B:=2)') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 't = (A:=1, B:=2)') Declarators: IVariableDeclaratorOperation (Symbol: t As (A As System.Int32, B As System.Int32)) (OperationKind.VariableDeclarator, Type: null) (Syntax: 't') Initializer: null Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= (A:=1, B:=2)') ITupleOperation (OperationKind.Tuple, Type: (A As System.Int32, B As System.Int32)) (Syntax: '(A:=1, B:=2)') NaturalType: (A As System.Int32, B As System.Int32) Elements(2): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of LocalDeclarationStatementSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact, WorkItem(10856, "https://github.com/dotnet/roslyn/issues/10856")> Public Sub TupleExpression_NamedElementsInTupleType() Dim source = <![CDATA[ Option Strict Off Imports System Class C Shared Sub Main() Dim t As (A As Integer, B As Integer) = (1, 2)'BIND:"(1, 2)" End Sub End Class]]>.Value Dim expectedOperationTree = <![CDATA[ ITupleOperation (OperationKind.Tuple, Type: (System.Int32, System.Int32)) (Syntax: '(1, 2)') NaturalType: (System.Int32, System.Int32) Elements(2): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of TupleExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact, WorkItem(10856, "https://github.com/dotnet/roslyn/issues/10856")> Public Sub TupleExpression_NamedElementsInTupleType_ParentVariableDeclaration() Dim source = <![CDATA[ Option Strict Off Imports System Class C Shared Sub Main() Dim t As (A As Integer, B As Integer) = (1, 2)'BIND:"Dim t As (A As Integer, B As Integer) = (1, 2)" End Sub End Class]]>.Value Dim expectedOperationTree = <![CDATA[ IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'Dim t As (A ... r) = (1, 2)') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 't As (A As ... r) = (1, 2)') Declarators: IVariableDeclaratorOperation (Symbol: t As (A As System.Int32, B As System.Int32)) (OperationKind.VariableDeclarator, Type: null) (Syntax: 't') Initializer: null Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= (1, 2)') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: (A As System.Int32, B As System.Int32), IsImplicit) (Syntax: '(1, 2)') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ITupleOperation (OperationKind.Tuple, Type: (System.Int32, System.Int32)) (Syntax: '(1, 2)') NaturalType: (System.Int32, System.Int32) Elements(2): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of LocalDeclarationStatementSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact, WorkItem(10856, "https://github.com/dotnet/roslyn/issues/10856")> Public Sub TupleExpression_NamedElementsAndImplicitConversions() Dim source = <![CDATA[ Option Strict Off Imports System Class C Shared Sub Main() Dim t As (A As Int16, B As String) = (A:=1, B:=Nothing)'BIND:"(A:=1, B:=Nothing)" End Sub End Class]]>.Value Dim expectedOperationTree = <![CDATA[ ITupleOperation (OperationKind.Tuple, Type: (A As System.Int16, B As System.String)) (Syntax: '(A:=1, B:=Nothing)') NaturalType: null Elements(2): IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int16, Constant: 1, IsImplicit) (Syntax: '1') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.String, Constant: null, IsImplicit) (Syntax: 'Nothing') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'Nothing') ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of TupleExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact, WorkItem(10856, "https://github.com/dotnet/roslyn/issues/10856")> Public Sub TupleExpression_NamedElementsAndImplicitConversions_ParentVariableDeclaration() Dim source = <![CDATA[ Option Strict Off Imports System Class C Shared Sub Main() Dim t As (A As Int16, B As String) = (A:=1, B:=Nothing)'BIND:"Dim t As (A As Int16, B As String) = (A:=1, B:=Nothing)" End Sub End Class]]>.Value Dim expectedOperationTree = <![CDATA[ IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'Dim t As (A ... B:=Nothing)') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 't As (A As ... B:=Nothing)') Declarators: IVariableDeclaratorOperation (Symbol: t As (A As System.Int16, B As System.String)) (OperationKind.VariableDeclarator, Type: null) (Syntax: 't') Initializer: null Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= (A:=1, B:=Nothing)') ITupleOperation (OperationKind.Tuple, Type: (A As System.Int16, B As System.String)) (Syntax: '(A:=1, B:=Nothing)') NaturalType: null Elements(2): IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int16, Constant: 1, IsImplicit) (Syntax: '1') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.String, Constant: null, IsImplicit) (Syntax: 'Nothing') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'Nothing') ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of LocalDeclarationStatementSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact, WorkItem(10856, "https://github.com/dotnet/roslyn/issues/10856")> Public Sub TupleExpression_UserDefinedConversionsForArguments() Dim source = <![CDATA[ Imports System Class C Private ReadOnly _x As Integer Public Sub New(x As Integer) _x = x End Sub Public Shared Widening Operator CType(value As Integer) As C Return New C(value) End Operator Public Shared Widening Operator CType(c As C) As Short Return CShort(c._x) End Operator Public Shared Widening Operator CType(c As C) As String Return c._x.ToString() End Operator Public Sub M(c1 As C) Dim t As (A As Int16, B As String) = (New C(0), c1)'BIND:"(New C(0), c1)" End Sub End Class]]>.Value Dim expectedOperationTree = <![CDATA[ ITupleOperation (OperationKind.Tuple, Type: (System.Int16, c1 As System.String)) (Syntax: '(New C(0), c1)') NaturalType: (C, c1 As C) Elements(2): IConversionOperation (TryCast: False, Unchecked) (OperatorMethod: Function C.op_Implicit(c As C) As System.Int16) (OperationKind.Conversion, Type: System.Int16, IsImplicit) (Syntax: 'New C(0)') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: True) (MethodSymbol: Function C.op_Implicit(c As C) As System.Int16) Operand: IObjectCreationOperation (Constructor: Sub C..ctor(x As System.Int32)) (OperationKind.ObjectCreation, Type: C) (Syntax: 'New C(0)') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null) (Syntax: '0') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Initializer: null IConversionOperation (TryCast: False, Unchecked) (OperatorMethod: Function C.op_Implicit(c As C) As System.String) (OperationKind.Conversion, Type: System.String, IsImplicit) (Syntax: 'c1') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: True) (MethodSymbol: Function C.op_Implicit(c As C) As System.String) Operand: IParameterReferenceOperation: c1 (OperationKind.ParameterReference, Type: C) (Syntax: 'c1') ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of TupleExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact, WorkItem(10856, "https://github.com/dotnet/roslyn/issues/10856")> Public Sub TupleExpression_UserDefinedConversionsForArguments_ParentVariableDeclaration() Dim source = <![CDATA[ Imports System Class C Private ReadOnly _x As Integer Public Sub New(x As Integer) _x = x End Sub Public Shared Widening Operator CType(value As Integer) As C Return New C(value) End Operator Public Shared Widening Operator CType(c As C) As Short Return CShort(c._x) End Operator Public Shared Widening Operator CType(c As C) As String Return c._x.ToString() End Operator Public Sub M(c1 As C) Dim t As (A As Int16, B As String) = (New C(0), c1)'BIND:"Dim t As (A As Int16, B As String) = (New C(0), c1)" End Sub End Class]]>.Value Dim expectedOperationTree = <![CDATA[ IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'Dim t As (A ... w C(0), c1)') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 't As (A As ... w C(0), c1)') Declarators: IVariableDeclaratorOperation (Symbol: t As (A As System.Int16, B As System.String)) (OperationKind.VariableDeclarator, Type: null) (Syntax: 't') Initializer: null Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= (New C(0), c1)') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: (A As System.Int16, B As System.String), IsImplicit) (Syntax: '(New C(0), c1)') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ITupleOperation (OperationKind.Tuple, Type: (System.Int16, c1 As System.String)) (Syntax: '(New C(0), c1)') NaturalType: (C, c1 As C) Elements(2): IConversionOperation (TryCast: False, Unchecked) (OperatorMethod: Function C.op_Implicit(c As C) As System.Int16) (OperationKind.Conversion, Type: System.Int16, IsImplicit) (Syntax: 'New C(0)') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: True) (MethodSymbol: Function C.op_Implicit(c As C) As System.Int16) Operand: IObjectCreationOperation (Constructor: Sub C..ctor(x As System.Int32)) (OperationKind.ObjectCreation, Type: C) (Syntax: 'New C(0)') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null) (Syntax: '0') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Initializer: null IConversionOperation (TryCast: False, Unchecked) (OperatorMethod: Function C.op_Implicit(c As C) As System.String) (OperationKind.Conversion, Type: System.String, IsImplicit) (Syntax: 'c1') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: True) (MethodSymbol: Function C.op_Implicit(c As C) As System.String) Operand: IParameterReferenceOperation: c1 (OperationKind.ParameterReference, Type: C) (Syntax: 'c1') ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of LocalDeclarationStatementSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact, WorkItem(10856, "https://github.com/dotnet/roslyn/issues/10856")> Public Sub TupleExpression_UserDefinedConversionFromTupleExpression() Dim source = <![CDATA[ Imports System Class C Private ReadOnly _x As Integer Public Sub New(x As Integer) _x = x End Sub Public Shared Widening Operator CType(x As (Integer, String)) As C Return New C(x.Item1) End Operator Public Shared Widening Operator CType(c As C) As (Integer, String) Return (c._x, c._x.ToString) End Operator Public Sub M(c1 As C) Dim t As C = (0, Nothing)'BIND:"(0, Nothing)" End Sub End Class]]>.Value Dim expectedOperationTree = <![CDATA[ ITupleOperation (OperationKind.Tuple, Type: (System.Int32, System.Object)) (Syntax: '(0, Nothing)') NaturalType: null Elements(2): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, Constant: null, IsImplicit) (Syntax: 'Nothing') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'Nothing') ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of TupleExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact, WorkItem(10856, "https://github.com/dotnet/roslyn/issues/10856")> Public Sub TupleExpression_UserDefinedConversionFromTupleExpression_ParentVariableDeclaration() Dim source = <![CDATA[ Imports System Class C Private ReadOnly _x As Integer Public Sub New(x As Integer) _x = x End Sub Public Shared Widening Operator CType(x As (Integer, String)) As C Return New C(x.Item1) End Operator Public Shared Widening Operator CType(c As C) As (Integer, String) Return (c._x, c._x.ToString) End Operator Public Sub M(c1 As C) Dim t As C = (0, Nothing)'BIND:"Dim t As C = (0, Nothing)" End Sub End Class]]>.Value Dim expectedOperationTree = <![CDATA[ IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'Dim t As C ... 0, Nothing)') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 't As C = (0, Nothing)') Declarators: IVariableDeclaratorOperation (Symbol: t As C) (OperationKind.VariableDeclarator, Type: null) (Syntax: 't') Initializer: null Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= (0, Nothing)') IConversionOperation (TryCast: False, Unchecked) (OperatorMethod: Function C.op_Implicit(x As (System.Int32, System.String)) As C) (OperationKind.Conversion, Type: C, IsImplicit) (Syntax: '(0, Nothing)') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: True) (MethodSymbol: Function C.op_Implicit(x As (System.Int32, System.String)) As C) Operand: ITupleOperation (OperationKind.Tuple, Type: (System.Int32, System.Object)) (Syntax: '(0, Nothing)') NaturalType: null Elements(2): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, Constant: null, IsImplicit) (Syntax: 'Nothing') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'Nothing') ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of LocalDeclarationStatementSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact, WorkItem(10856, "https://github.com/dotnet/roslyn/issues/10856")> Public Sub TupleExpression_UserDefinedConversionToTupleType() Dim source = <![CDATA[ Imports System Class C Private ReadOnly _x As Integer Public Sub New(x As Integer) _x = x End Sub Public Shared Widening Operator CType(x As (Integer, String)) As C Return New C(x.Item1) End Operator Public Shared Widening Operator CType(c As C) As (Integer, String) Return (c._x, c._x.ToString) End Operator Public Sub M(c1 As C) Dim t As (Integer, String) = c1'BIND:"c1" End Sub End Class]]>.Value Dim expectedOperationTree = <![CDATA[ IParameterReferenceOperation: c1 (OperationKind.ParameterReference, Type: C) (Syntax: 'c1') ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of IdentifierNameSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact, WorkItem(10856, "https://github.com/dotnet/roslyn/issues/10856")> Public Sub TupleExpression_UserDefinedConversionToTupleType_ParentVariableDeclaration() Dim source = <![CDATA[ Imports System Class C Private ReadOnly _x As Integer Public Sub New(x As Integer) _x = x End Sub Public Shared Widening Operator CType(x As (Integer, String)) As C Return New C(x.Item1) End Operator Public Shared Widening Operator CType(c As C) As (Integer, String) Return (c._x, c._x.ToString) End Operator Public Sub M(c1 As C) Dim t As (Integer, String) = c1'BIND:"Dim t As (Integer, String) = c1" End Sub End Class]]>.Value Dim expectedOperationTree = <![CDATA[ IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'Dim t As (I ... tring) = c1') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 't As (Integ ... tring) = c1') Declarators: IVariableDeclaratorOperation (Symbol: t As (System.Int32, System.String)) (OperationKind.VariableDeclarator, Type: null) (Syntax: 't') Initializer: null Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= c1') IConversionOperation (TryCast: False, Unchecked) (OperatorMethod: Function C.op_Implicit(c As C) As (System.Int32, System.String)) (OperationKind.Conversion, Type: (System.Int32, System.String), IsImplicit) (Syntax: 'c1') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: True) (MethodSymbol: Function C.op_Implicit(c As C) As (System.Int32, System.String)) Operand: IParameterReferenceOperation: c1 (OperationKind.ParameterReference, Type: C) (Syntax: 'c1') ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of LocalDeclarationStatementSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact, WorkItem(10856, "https://github.com/dotnet/roslyn/issues/10856")> Public Sub TupleExpression_InvalidConversion() Dim source = <![CDATA[ Class C Private ReadOnly _x As Integer Public Sub New(x As Integer) _x = x End Sub Public Shared Widening Operator CType(value As Integer) As C Return New C(value) End Operator Public Shared Widening Operator CType(c As C) As Integer Return CShort(c._x) End Operator Public Shared Widening Operator CType(c As C) As String Return c._x.ToString() End Operator Public Sub M(c1 As C) Dim t As (Short, String) = (New C(0), c1)'BIND:"(New C(0), c1)" End Sub End Class]]>.Value Dim expectedOperationTree = <![CDATA[ ITupleOperation (OperationKind.Tuple, Type: (System.Int16, c1 As System.String), IsInvalid) (Syntax: '(New C(0), c1)') NaturalType: (C, c1 As C) Elements(2): IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int16, IsInvalid, IsImplicit) (Syntax: 'New C(0)') Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IObjectCreationOperation (Constructor: Sub C..ctor(x As System.Int32)) (OperationKind.ObjectCreation, Type: C, IsInvalid) (Syntax: 'New C(0)') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null, IsInvalid) (Syntax: '0') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0, IsInvalid) (Syntax: '0') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Initializer: null IConversionOperation (TryCast: False, Unchecked) (OperatorMethod: Function C.op_Implicit(c As C) As System.String) (OperationKind.Conversion, Type: System.String, IsImplicit) (Syntax: 'c1') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: True) (MethodSymbol: Function C.op_Implicit(c As C) As System.String) Operand: IParameterReferenceOperation: c1 (OperationKind.ParameterReference, Type: C) (Syntax: 'c1') ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC30311: Value of type 'C' cannot be converted to 'Short'. Dim t As (Short, String) = (New C(0), c1)'BIND:"(New C(0), c1)" ~~~~~~~~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of TupleExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact, WorkItem(10856, "https://github.com/dotnet/roslyn/issues/10856")> Public Sub TupleExpression_InvalidConversion_ParentVariableDeclaration() Dim source = <![CDATA[ Class C Private ReadOnly _x As Integer Public Sub New(x As Integer) _x = x End Sub Public Shared Widening Operator CType(value As Integer) As C Return New C(value) End Operator Public Shared Widening Operator CType(c As C) As Integer Return CShort(c._x) End Operator Public Shared Widening Operator CType(c As C) As String Return c._x.ToString() End Operator Public Sub M(c1 As C) Dim t As (Short, String) = (New C(0), c1)'BIND:"Dim t As (Short, String) = (New C(0), c1)" End Sub End Class ]]>.Value Dim expectedOperationTree = <![CDATA[ IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsInvalid) (Syntax: 'Dim t As (S ... w C(0), c1)') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 't As (Short ... w C(0), c1)') Declarators: IVariableDeclaratorOperation (Symbol: t As (System.Int16, System.String)) (OperationKind.VariableDeclarator, Type: null) (Syntax: 't') Initializer: null Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: '= (New C(0), c1)') ITupleOperation (OperationKind.Tuple, Type: (System.Int16, c1 As System.String), IsInvalid) (Syntax: '(New C(0), c1)') NaturalType: (C, c1 As C) Elements(2): IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int16, IsInvalid, IsImplicit) (Syntax: 'New C(0)') Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IObjectCreationOperation (Constructor: Sub C..ctor(x As System.Int32)) (OperationKind.ObjectCreation, Type: C, IsInvalid) (Syntax: 'New C(0)') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null, IsInvalid) (Syntax: '0') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0, IsInvalid) (Syntax: '0') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Initializer: null IConversionOperation (TryCast: False, Unchecked) (OperatorMethod: Function C.op_Implicit(c As C) As System.String) (OperationKind.Conversion, Type: System.String, IsImplicit) (Syntax: 'c1') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: True) (MethodSymbol: Function C.op_Implicit(c As C) As System.String) Operand: IParameterReferenceOperation: c1 (OperationKind.ParameterReference, Type: C) (Syntax: 'c1') ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC30311: Value of type 'C' cannot be converted to 'Short'. Dim t As (Short, String) = (New C(0), c1)'BIND:"Dim t As (Short, String) = (New C(0), c1)" ~~~~~~~~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of LocalDeclarationStatementSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact()> Public Sub TupleFlow_01() Dim source = <![CDATA[ Class C Sub M(b As Boolean)'BIND:"Sub M(b As Boolean)" Dim t As (Integer, Integer) = (1, If(b, 2, 3)) End Sub End Class]]>.Value Dim expectedDiagnostics = String.Empty Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [t As (System.Int32, System.Int32)] CaptureIds: [0] [1] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '1') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Jump if False (Regular) to Block[B3] IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b') Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '2') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') Next (Regular) Block[B4] Block[B3] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '3') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B2] [B3] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: (System.Int32, System.Int32), IsImplicit) (Syntax: 't As (Integ ... f(b, 2, 3))') Left: ILocalReferenceOperation: t (IsDeclaration: True) (OperationKind.LocalReference, Type: (System.Int32, System.Int32), IsImplicit) (Syntax: 't') Right: ITupleOperation (OperationKind.Tuple, Type: (System.Int32, System.Int32)) (Syntax: '(1, If(b, 2, 3))') NaturalType: (System.Int32, System.Int32) Elements(2): IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: '1') IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'If(b, 2, 3)') Next (Regular) Block[B5] Leaving: {R1} } Block[B5] - Exit Predecessors: [B4] Statements (0) ]]>.Value VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact()> Public Sub TupleFlow_02() Dim source = <![CDATA[ Class C Sub M(b As Boolean)'BIND:"Sub M(b As Boolean)" Dim t As (Integer, (Integer, Integer)) = (1, (2, If(b, 2, 3))) End Sub End Class]]>.Value Dim expectedDiagnostics = String.Empty Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [t As (System.Int32, (System.Int32, System.Int32))] CaptureIds: [0] [1] [2] Block[B1] - Block Predecessors: [B0] Statements (2) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '1') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '2') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') Jump if False (Regular) to Block[B3] IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b') Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '2') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') Next (Regular) Block[B4] Block[B3] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '3') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B2] [B3] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: (System.Int32, (System.Int32, System.Int32)), IsImplicit) (Syntax: 't As (Integ ... (b, 2, 3)))') Left: ILocalReferenceOperation: t (IsDeclaration: True) (OperationKind.LocalReference, Type: (System.Int32, (System.Int32, System.Int32)), IsImplicit) (Syntax: 't') Right: ITupleOperation (OperationKind.Tuple, Type: (System.Int32, (System.Int32, System.Int32))) (Syntax: '(1, (2, If(b, 2, 3)))') NaturalType: (System.Int32, (System.Int32, System.Int32)) Elements(2): IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: '1') ITupleOperation (OperationKind.Tuple, Type: (System.Int32, System.Int32)) (Syntax: '(2, If(b, 2, 3))') NaturalType: (System.Int32, System.Int32) Elements(2): IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 2, IsImplicit) (Syntax: '2') IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'If(b, 2, 3)') Next (Regular) Block[B5] Leaving: {R1} } Block[B5] - Exit Predecessors: [B4] Statements (0) ]]>.Value VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact()> Public Sub TupleFlow_03() Dim source = <![CDATA[ Class C Sub M(b As Boolean)'BIND:"Sub M(b As Boolean)" M2((1, If(b, 2, 3))) End Sub Sub M2(arg As (Integer, Integer)) End Sub End Class]]>.Value Dim expectedDiagnostics = String.Empty Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [1] [2] Block[B1] - Block Predecessors: [B0] Statements (2) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'M2') Value: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: 'M2') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '1') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Jump if False (Regular) to Block[B3] IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b') Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '2') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') Next (Regular) Block[B4] Block[B3] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '3') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B2] [B3] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'M2((1, If(b, 2, 3)))') Expression: IInvocationOperation ( Sub C.M2(arg As (System.Int32, System.Int32))) (OperationKind.Invocation, Type: System.Void) (Syntax: 'M2((1, If(b, 2, 3)))') Instance Receiver: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'M2') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: arg) (OperationKind.Argument, Type: null) (Syntax: '(1, If(b, 2, 3))') ITupleOperation (OperationKind.Tuple, Type: (System.Int32, System.Int32)) (Syntax: '(1, If(b, 2, 3))') NaturalType: (System.Int32, System.Int32) Elements(2): IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: '1') IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'If(b, 2, 3)') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Next (Regular) Block[B5] Leaving: {R1} } Block[B5] - Exit Predecessors: [B4] Statements (0) ]]>.Value VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact()> Public Sub TupleFlow_04() Dim source = <![CDATA[ Class C Sub M(b As Boolean)'BIND:"Sub M(b As Boolean)" Dim t As (Integer, Integer) = (If(b, 2, 3), 1) End Sub End Class]]>.Value Dim expectedDiagnostics = String.Empty Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [t As (System.Int32, System.Int32)] CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (0) Jump if False (Regular) to Block[B3] IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b') Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '2') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') Next (Regular) Block[B4] Block[B3] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '3') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B2] [B3] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: (System.Int32, System.Int32), IsImplicit) (Syntax: 't As (Integ ... , 2, 3), 1)') Left: ILocalReferenceOperation: t (IsDeclaration: True) (OperationKind.LocalReference, Type: (System.Int32, System.Int32), IsImplicit) (Syntax: 't') Right: ITupleOperation (OperationKind.Tuple, Type: (System.Int32, System.Int32)) (Syntax: '(If(b, 2, 3), 1)') NaturalType: (System.Int32, System.Int32) Elements(2): IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'If(b, 2, 3)') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Next (Regular) Block[B5] Leaving: {R1} } Block[B5] - Exit Predecessors: [B4] Statements (0) ]]>.Value VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) End Sub End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Microsoft.CodeAnalysis.Test.Utilities Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics Partial Public Class IOperationTests Inherits SemanticModelTestBase <CompilerTrait(CompilerFeature.IOperation)> <Fact, WorkItem(10856, "https://github.com/dotnet/roslyn/issues/10856")> Public Sub TupleExpression_NoConversions() Dim source = <![CDATA[ Imports System Class C Shared Sub Main() Dim t As (Integer, Integer) = (1, 2)'BIND:"(1, 2)" End Sub End Class]]>.Value Dim expectedOperationTree = <![CDATA[ ITupleOperation (OperationKind.Tuple, Type: (System.Int32, System.Int32)) (Syntax: '(1, 2)') NaturalType: (System.Int32, System.Int32) Elements(2): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of TupleExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact, WorkItem(10856, "https://github.com/dotnet/roslyn/issues/10856")> Public Sub TupleExpression_NoConversions_ParentVariableDeclaration() Dim source = <![CDATA[ Imports System Class C Shared Sub Main() Dim t As (Integer, Integer) = (1, 2)'BIND:"Dim t As (Integer, Integer) = (1, 2)" End Sub End Class]]>.Value Dim expectedOperationTree = <![CDATA[ IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'Dim t As (I ... r) = (1, 2)') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 't As (Integ ... r) = (1, 2)') Declarators: IVariableDeclaratorOperation (Symbol: t As (System.Int32, System.Int32)) (OperationKind.VariableDeclarator, Type: null) (Syntax: 't') Initializer: null Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= (1, 2)') ITupleOperation (OperationKind.Tuple, Type: (System.Int32, System.Int32)) (Syntax: '(1, 2)') NaturalType: (System.Int32, System.Int32) Elements(2): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of LocalDeclarationStatementSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact, WorkItem(10856, "https://github.com/dotnet/roslyn/issues/10856")> Public Sub TupleExpression_ImplicitConversions() Dim source = <![CDATA[ Imports System Class C Shared Sub Main() Dim t As (UInteger, UInteger) = (1, 2)'BIND:"(1, 2)" End Sub End Class]]>.Value Dim expectedOperationTree = <![CDATA[ ITupleOperation (OperationKind.Tuple, Type: (System.UInt32, System.UInt32)) (Syntax: '(1, 2)') NaturalType: (System.Int32, System.Int32) Elements(2): IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.UInt32, Constant: 1, IsImplicit) (Syntax: '1') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.UInt32, Constant: 2, IsImplicit) (Syntax: '2') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of TupleExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact, WorkItem(10856, "https://github.com/dotnet/roslyn/issues/10856")> Public Sub TupleExpression_ImplicitConversions_ParentVariableDeclaration() Dim source = <![CDATA[ Imports System Class C Shared Sub Main() Dim t As (UInteger, UInteger) = (1, 2)'BIND:"Dim t As (UInteger, UInteger) = (1, 2)" End Sub End Class]]>.Value Dim expectedOperationTree = <![CDATA[ IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'Dim t As (U ... r) = (1, 2)') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 't As (UInte ... r) = (1, 2)') Declarators: IVariableDeclaratorOperation (Symbol: t As (System.UInt32, System.UInt32)) (OperationKind.VariableDeclarator, Type: null) (Syntax: 't') Initializer: null Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= (1, 2)') ITupleOperation (OperationKind.Tuple, Type: (System.UInt32, System.UInt32)) (Syntax: '(1, 2)') NaturalType: (System.Int32, System.Int32) Elements(2): IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.UInt32, Constant: 1, IsImplicit) (Syntax: '1') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.UInt32, Constant: 2, IsImplicit) (Syntax: '2') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of LocalDeclarationStatementSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact, WorkItem(10856, "https://github.com/dotnet/roslyn/issues/10856")> Public Sub TupleExpression_ImplicitConversionFromNull() Dim source = <![CDATA[ Imports System Class C Shared Sub Main() Dim t As (UInteger, String) = (1, Nothing)'BIND:"(1, Nothing)" End Sub End Class]]>.Value Dim expectedOperationTree = <![CDATA[ ITupleOperation (OperationKind.Tuple, Type: (System.UInt32, System.String)) (Syntax: '(1, Nothing)') NaturalType: null Elements(2): IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.UInt32, Constant: 1, IsImplicit) (Syntax: '1') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.String, Constant: null, IsImplicit) (Syntax: 'Nothing') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'Nothing') ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of TupleExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact, WorkItem(10856, "https://github.com/dotnet/roslyn/issues/10856")> Public Sub TupleExpression_ImplicitConversionFromNull_ParentVariableDeclaration() Dim source = <![CDATA[ Imports System Class C Shared Sub Main() Dim t As (UInteger, String) = (1, Nothing)'BIND:"Dim t As (UInteger, String) = (1, Nothing)" End Sub End Class]]>.Value Dim expectedOperationTree = <![CDATA[ IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'Dim t As (U ... 1, Nothing)') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 't As (UInte ... 1, Nothing)') Declarators: IVariableDeclaratorOperation (Symbol: t As (System.UInt32, System.String)) (OperationKind.VariableDeclarator, Type: null) (Syntax: 't') Initializer: null Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= (1, Nothing)') ITupleOperation (OperationKind.Tuple, Type: (System.UInt32, System.String)) (Syntax: '(1, Nothing)') NaturalType: null Elements(2): IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.UInt32, Constant: 1, IsImplicit) (Syntax: '1') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.String, Constant: null, IsImplicit) (Syntax: 'Nothing') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'Nothing') ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of LocalDeclarationStatementSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact, WorkItem(10856, "https://github.com/dotnet/roslyn/issues/10856")> Public Sub TupleExpression_NamedArguments() Dim source = <![CDATA[ Option Strict Off Imports System Class C Shared Sub Main() Dim t = (A:=1, B:=2)'BIND:"(A:=1, B:=2)" End Sub End Class]]>.Value Dim expectedOperationTree = <![CDATA[ ITupleOperation (OperationKind.Tuple, Type: (A As System.Int32, B As System.Int32)) (Syntax: '(A:=1, B:=2)') NaturalType: (A As System.Int32, B As System.Int32) Elements(2): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of TupleExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact, WorkItem(10856, "https://github.com/dotnet/roslyn/issues/10856")> Public Sub TupleExpression_NamedArguments_ParentVariableDeclaration() Dim source = <![CDATA[ Option Strict Off Imports System Class C Shared Sub Main() Dim t = (A:=1, B:=2)'BIND:"Dim t = (A:=1, B:=2)" End Sub End Class]]>.Value Dim expectedOperationTree = <![CDATA[ IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'Dim t = (A:=1, B:=2)') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 't = (A:=1, B:=2)') Declarators: IVariableDeclaratorOperation (Symbol: t As (A As System.Int32, B As System.Int32)) (OperationKind.VariableDeclarator, Type: null) (Syntax: 't') Initializer: null Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= (A:=1, B:=2)') ITupleOperation (OperationKind.Tuple, Type: (A As System.Int32, B As System.Int32)) (Syntax: '(A:=1, B:=2)') NaturalType: (A As System.Int32, B As System.Int32) Elements(2): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of LocalDeclarationStatementSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact, WorkItem(10856, "https://github.com/dotnet/roslyn/issues/10856")> Public Sub TupleExpression_NamedElementsInTupleType() Dim source = <![CDATA[ Option Strict Off Imports System Class C Shared Sub Main() Dim t As (A As Integer, B As Integer) = (1, 2)'BIND:"(1, 2)" End Sub End Class]]>.Value Dim expectedOperationTree = <![CDATA[ ITupleOperation (OperationKind.Tuple, Type: (System.Int32, System.Int32)) (Syntax: '(1, 2)') NaturalType: (System.Int32, System.Int32) Elements(2): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of TupleExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact, WorkItem(10856, "https://github.com/dotnet/roslyn/issues/10856")> Public Sub TupleExpression_NamedElementsInTupleType_ParentVariableDeclaration() Dim source = <![CDATA[ Option Strict Off Imports System Class C Shared Sub Main() Dim t As (A As Integer, B As Integer) = (1, 2)'BIND:"Dim t As (A As Integer, B As Integer) = (1, 2)" End Sub End Class]]>.Value Dim expectedOperationTree = <![CDATA[ IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'Dim t As (A ... r) = (1, 2)') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 't As (A As ... r) = (1, 2)') Declarators: IVariableDeclaratorOperation (Symbol: t As (A As System.Int32, B As System.Int32)) (OperationKind.VariableDeclarator, Type: null) (Syntax: 't') Initializer: null Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= (1, 2)') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: (A As System.Int32, B As System.Int32), IsImplicit) (Syntax: '(1, 2)') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ITupleOperation (OperationKind.Tuple, Type: (System.Int32, System.Int32)) (Syntax: '(1, 2)') NaturalType: (System.Int32, System.Int32) Elements(2): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of LocalDeclarationStatementSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact, WorkItem(10856, "https://github.com/dotnet/roslyn/issues/10856")> Public Sub TupleExpression_NamedElementsAndImplicitConversions() Dim source = <![CDATA[ Option Strict Off Imports System Class C Shared Sub Main() Dim t As (A As Int16, B As String) = (A:=1, B:=Nothing)'BIND:"(A:=1, B:=Nothing)" End Sub End Class]]>.Value Dim expectedOperationTree = <![CDATA[ ITupleOperation (OperationKind.Tuple, Type: (A As System.Int16, B As System.String)) (Syntax: '(A:=1, B:=Nothing)') NaturalType: null Elements(2): IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int16, Constant: 1, IsImplicit) (Syntax: '1') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.String, Constant: null, IsImplicit) (Syntax: 'Nothing') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'Nothing') ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of TupleExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact, WorkItem(10856, "https://github.com/dotnet/roslyn/issues/10856")> Public Sub TupleExpression_NamedElementsAndImplicitConversions_ParentVariableDeclaration() Dim source = <![CDATA[ Option Strict Off Imports System Class C Shared Sub Main() Dim t As (A As Int16, B As String) = (A:=1, B:=Nothing)'BIND:"Dim t As (A As Int16, B As String) = (A:=1, B:=Nothing)" End Sub End Class]]>.Value Dim expectedOperationTree = <![CDATA[ IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'Dim t As (A ... B:=Nothing)') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 't As (A As ... B:=Nothing)') Declarators: IVariableDeclaratorOperation (Symbol: t As (A As System.Int16, B As System.String)) (OperationKind.VariableDeclarator, Type: null) (Syntax: 't') Initializer: null Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= (A:=1, B:=Nothing)') ITupleOperation (OperationKind.Tuple, Type: (A As System.Int16, B As System.String)) (Syntax: '(A:=1, B:=Nothing)') NaturalType: null Elements(2): IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int16, Constant: 1, IsImplicit) (Syntax: '1') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.String, Constant: null, IsImplicit) (Syntax: 'Nothing') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'Nothing') ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of LocalDeclarationStatementSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact, WorkItem(10856, "https://github.com/dotnet/roslyn/issues/10856")> Public Sub TupleExpression_UserDefinedConversionsForArguments() Dim source = <![CDATA[ Imports System Class C Private ReadOnly _x As Integer Public Sub New(x As Integer) _x = x End Sub Public Shared Widening Operator CType(value As Integer) As C Return New C(value) End Operator Public Shared Widening Operator CType(c As C) As Short Return CShort(c._x) End Operator Public Shared Widening Operator CType(c As C) As String Return c._x.ToString() End Operator Public Sub M(c1 As C) Dim t As (A As Int16, B As String) = (New C(0), c1)'BIND:"(New C(0), c1)" End Sub End Class]]>.Value Dim expectedOperationTree = <![CDATA[ ITupleOperation (OperationKind.Tuple, Type: (System.Int16, c1 As System.String)) (Syntax: '(New C(0), c1)') NaturalType: (C, c1 As C) Elements(2): IConversionOperation (TryCast: False, Unchecked) (OperatorMethod: Function C.op_Implicit(c As C) As System.Int16) (OperationKind.Conversion, Type: System.Int16, IsImplicit) (Syntax: 'New C(0)') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: True) (MethodSymbol: Function C.op_Implicit(c As C) As System.Int16) Operand: IObjectCreationOperation (Constructor: Sub C..ctor(x As System.Int32)) (OperationKind.ObjectCreation, Type: C) (Syntax: 'New C(0)') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null) (Syntax: '0') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Initializer: null IConversionOperation (TryCast: False, Unchecked) (OperatorMethod: Function C.op_Implicit(c As C) As System.String) (OperationKind.Conversion, Type: System.String, IsImplicit) (Syntax: 'c1') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: True) (MethodSymbol: Function C.op_Implicit(c As C) As System.String) Operand: IParameterReferenceOperation: c1 (OperationKind.ParameterReference, Type: C) (Syntax: 'c1') ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of TupleExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact, WorkItem(10856, "https://github.com/dotnet/roslyn/issues/10856")> Public Sub TupleExpression_UserDefinedConversionsForArguments_ParentVariableDeclaration() Dim source = <![CDATA[ Imports System Class C Private ReadOnly _x As Integer Public Sub New(x As Integer) _x = x End Sub Public Shared Widening Operator CType(value As Integer) As C Return New C(value) End Operator Public Shared Widening Operator CType(c As C) As Short Return CShort(c._x) End Operator Public Shared Widening Operator CType(c As C) As String Return c._x.ToString() End Operator Public Sub M(c1 As C) Dim t As (A As Int16, B As String) = (New C(0), c1)'BIND:"Dim t As (A As Int16, B As String) = (New C(0), c1)" End Sub End Class]]>.Value Dim expectedOperationTree = <![CDATA[ IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'Dim t As (A ... w C(0), c1)') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 't As (A As ... w C(0), c1)') Declarators: IVariableDeclaratorOperation (Symbol: t As (A As System.Int16, B As System.String)) (OperationKind.VariableDeclarator, Type: null) (Syntax: 't') Initializer: null Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= (New C(0), c1)') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: (A As System.Int16, B As System.String), IsImplicit) (Syntax: '(New C(0), c1)') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ITupleOperation (OperationKind.Tuple, Type: (System.Int16, c1 As System.String)) (Syntax: '(New C(0), c1)') NaturalType: (C, c1 As C) Elements(2): IConversionOperation (TryCast: False, Unchecked) (OperatorMethod: Function C.op_Implicit(c As C) As System.Int16) (OperationKind.Conversion, Type: System.Int16, IsImplicit) (Syntax: 'New C(0)') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: True) (MethodSymbol: Function C.op_Implicit(c As C) As System.Int16) Operand: IObjectCreationOperation (Constructor: Sub C..ctor(x As System.Int32)) (OperationKind.ObjectCreation, Type: C) (Syntax: 'New C(0)') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null) (Syntax: '0') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Initializer: null IConversionOperation (TryCast: False, Unchecked) (OperatorMethod: Function C.op_Implicit(c As C) As System.String) (OperationKind.Conversion, Type: System.String, IsImplicit) (Syntax: 'c1') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: True) (MethodSymbol: Function C.op_Implicit(c As C) As System.String) Operand: IParameterReferenceOperation: c1 (OperationKind.ParameterReference, Type: C) (Syntax: 'c1') ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of LocalDeclarationStatementSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact, WorkItem(10856, "https://github.com/dotnet/roslyn/issues/10856")> Public Sub TupleExpression_UserDefinedConversionFromTupleExpression() Dim source = <![CDATA[ Imports System Class C Private ReadOnly _x As Integer Public Sub New(x As Integer) _x = x End Sub Public Shared Widening Operator CType(x As (Integer, String)) As C Return New C(x.Item1) End Operator Public Shared Widening Operator CType(c As C) As (Integer, String) Return (c._x, c._x.ToString) End Operator Public Sub M(c1 As C) Dim t As C = (0, Nothing)'BIND:"(0, Nothing)" End Sub End Class]]>.Value Dim expectedOperationTree = <![CDATA[ ITupleOperation (OperationKind.Tuple, Type: (System.Int32, System.Object)) (Syntax: '(0, Nothing)') NaturalType: null Elements(2): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, Constant: null, IsImplicit) (Syntax: 'Nothing') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'Nothing') ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of TupleExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact, WorkItem(10856, "https://github.com/dotnet/roslyn/issues/10856")> Public Sub TupleExpression_UserDefinedConversionFromTupleExpression_ParentVariableDeclaration() Dim source = <![CDATA[ Imports System Class C Private ReadOnly _x As Integer Public Sub New(x As Integer) _x = x End Sub Public Shared Widening Operator CType(x As (Integer, String)) As C Return New C(x.Item1) End Operator Public Shared Widening Operator CType(c As C) As (Integer, String) Return (c._x, c._x.ToString) End Operator Public Sub M(c1 As C) Dim t As C = (0, Nothing)'BIND:"Dim t As C = (0, Nothing)" End Sub End Class]]>.Value Dim expectedOperationTree = <![CDATA[ IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'Dim t As C ... 0, Nothing)') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 't As C = (0, Nothing)') Declarators: IVariableDeclaratorOperation (Symbol: t As C) (OperationKind.VariableDeclarator, Type: null) (Syntax: 't') Initializer: null Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= (0, Nothing)') IConversionOperation (TryCast: False, Unchecked) (OperatorMethod: Function C.op_Implicit(x As (System.Int32, System.String)) As C) (OperationKind.Conversion, Type: C, IsImplicit) (Syntax: '(0, Nothing)') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: True) (MethodSymbol: Function C.op_Implicit(x As (System.Int32, System.String)) As C) Operand: ITupleOperation (OperationKind.Tuple, Type: (System.Int32, System.Object)) (Syntax: '(0, Nothing)') NaturalType: null Elements(2): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, Constant: null, IsImplicit) (Syntax: 'Nothing') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'Nothing') ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of LocalDeclarationStatementSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact, WorkItem(10856, "https://github.com/dotnet/roslyn/issues/10856")> Public Sub TupleExpression_UserDefinedConversionToTupleType() Dim source = <![CDATA[ Imports System Class C Private ReadOnly _x As Integer Public Sub New(x As Integer) _x = x End Sub Public Shared Widening Operator CType(x As (Integer, String)) As C Return New C(x.Item1) End Operator Public Shared Widening Operator CType(c As C) As (Integer, String) Return (c._x, c._x.ToString) End Operator Public Sub M(c1 As C) Dim t As (Integer, String) = c1'BIND:"c1" End Sub End Class]]>.Value Dim expectedOperationTree = <![CDATA[ IParameterReferenceOperation: c1 (OperationKind.ParameterReference, Type: C) (Syntax: 'c1') ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of IdentifierNameSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact, WorkItem(10856, "https://github.com/dotnet/roslyn/issues/10856")> Public Sub TupleExpression_UserDefinedConversionToTupleType_ParentVariableDeclaration() Dim source = <![CDATA[ Imports System Class C Private ReadOnly _x As Integer Public Sub New(x As Integer) _x = x End Sub Public Shared Widening Operator CType(x As (Integer, String)) As C Return New C(x.Item1) End Operator Public Shared Widening Operator CType(c As C) As (Integer, String) Return (c._x, c._x.ToString) End Operator Public Sub M(c1 As C) Dim t As (Integer, String) = c1'BIND:"Dim t As (Integer, String) = c1" End Sub End Class]]>.Value Dim expectedOperationTree = <![CDATA[ IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'Dim t As (I ... tring) = c1') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 't As (Integ ... tring) = c1') Declarators: IVariableDeclaratorOperation (Symbol: t As (System.Int32, System.String)) (OperationKind.VariableDeclarator, Type: null) (Syntax: 't') Initializer: null Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= c1') IConversionOperation (TryCast: False, Unchecked) (OperatorMethod: Function C.op_Implicit(c As C) As (System.Int32, System.String)) (OperationKind.Conversion, Type: (System.Int32, System.String), IsImplicit) (Syntax: 'c1') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: True) (MethodSymbol: Function C.op_Implicit(c As C) As (System.Int32, System.String)) Operand: IParameterReferenceOperation: c1 (OperationKind.ParameterReference, Type: C) (Syntax: 'c1') ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of LocalDeclarationStatementSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact, WorkItem(10856, "https://github.com/dotnet/roslyn/issues/10856")> Public Sub TupleExpression_InvalidConversion() Dim source = <![CDATA[ Class C Private ReadOnly _x As Integer Public Sub New(x As Integer) _x = x End Sub Public Shared Widening Operator CType(value As Integer) As C Return New C(value) End Operator Public Shared Widening Operator CType(c As C) As Integer Return CShort(c._x) End Operator Public Shared Widening Operator CType(c As C) As String Return c._x.ToString() End Operator Public Sub M(c1 As C) Dim t As (Short, String) = (New C(0), c1)'BIND:"(New C(0), c1)" End Sub End Class]]>.Value Dim expectedOperationTree = <![CDATA[ ITupleOperation (OperationKind.Tuple, Type: (System.Int16, c1 As System.String), IsInvalid) (Syntax: '(New C(0), c1)') NaturalType: (C, c1 As C) Elements(2): IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int16, IsInvalid, IsImplicit) (Syntax: 'New C(0)') Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IObjectCreationOperation (Constructor: Sub C..ctor(x As System.Int32)) (OperationKind.ObjectCreation, Type: C, IsInvalid) (Syntax: 'New C(0)') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null, IsInvalid) (Syntax: '0') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0, IsInvalid) (Syntax: '0') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Initializer: null IConversionOperation (TryCast: False, Unchecked) (OperatorMethod: Function C.op_Implicit(c As C) As System.String) (OperationKind.Conversion, Type: System.String, IsImplicit) (Syntax: 'c1') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: True) (MethodSymbol: Function C.op_Implicit(c As C) As System.String) Operand: IParameterReferenceOperation: c1 (OperationKind.ParameterReference, Type: C) (Syntax: 'c1') ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC30311: Value of type 'C' cannot be converted to 'Short'. Dim t As (Short, String) = (New C(0), c1)'BIND:"(New C(0), c1)" ~~~~~~~~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of TupleExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact, WorkItem(10856, "https://github.com/dotnet/roslyn/issues/10856")> Public Sub TupleExpression_InvalidConversion_ParentVariableDeclaration() Dim source = <![CDATA[ Class C Private ReadOnly _x As Integer Public Sub New(x As Integer) _x = x End Sub Public Shared Widening Operator CType(value As Integer) As C Return New C(value) End Operator Public Shared Widening Operator CType(c As C) As Integer Return CShort(c._x) End Operator Public Shared Widening Operator CType(c As C) As String Return c._x.ToString() End Operator Public Sub M(c1 As C) Dim t As (Short, String) = (New C(0), c1)'BIND:"Dim t As (Short, String) = (New C(0), c1)" End Sub End Class ]]>.Value Dim expectedOperationTree = <![CDATA[ IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsInvalid) (Syntax: 'Dim t As (S ... w C(0), c1)') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 't As (Short ... w C(0), c1)') Declarators: IVariableDeclaratorOperation (Symbol: t As (System.Int16, System.String)) (OperationKind.VariableDeclarator, Type: null) (Syntax: 't') Initializer: null Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: '= (New C(0), c1)') ITupleOperation (OperationKind.Tuple, Type: (System.Int16, c1 As System.String), IsInvalid) (Syntax: '(New C(0), c1)') NaturalType: (C, c1 As C) Elements(2): IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int16, IsInvalid, IsImplicit) (Syntax: 'New C(0)') Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IObjectCreationOperation (Constructor: Sub C..ctor(x As System.Int32)) (OperationKind.ObjectCreation, Type: C, IsInvalid) (Syntax: 'New C(0)') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null, IsInvalid) (Syntax: '0') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0, IsInvalid) (Syntax: '0') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Initializer: null IConversionOperation (TryCast: False, Unchecked) (OperatorMethod: Function C.op_Implicit(c As C) As System.String) (OperationKind.Conversion, Type: System.String, IsImplicit) (Syntax: 'c1') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: True) (MethodSymbol: Function C.op_Implicit(c As C) As System.String) Operand: IParameterReferenceOperation: c1 (OperationKind.ParameterReference, Type: C) (Syntax: 'c1') ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC30311: Value of type 'C' cannot be converted to 'Short'. Dim t As (Short, String) = (New C(0), c1)'BIND:"Dim t As (Short, String) = (New C(0), c1)" ~~~~~~~~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of LocalDeclarationStatementSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact()> Public Sub TupleFlow_01() Dim source = <![CDATA[ Class C Sub M(b As Boolean)'BIND:"Sub M(b As Boolean)" Dim t As (Integer, Integer) = (1, If(b, 2, 3)) End Sub End Class]]>.Value Dim expectedDiagnostics = String.Empty Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [t As (System.Int32, System.Int32)] CaptureIds: [0] [1] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '1') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Jump if False (Regular) to Block[B3] IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b') Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '2') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') Next (Regular) Block[B4] Block[B3] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '3') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B2] [B3] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: (System.Int32, System.Int32), IsImplicit) (Syntax: 't As (Integ ... f(b, 2, 3))') Left: ILocalReferenceOperation: t (IsDeclaration: True) (OperationKind.LocalReference, Type: (System.Int32, System.Int32), IsImplicit) (Syntax: 't') Right: ITupleOperation (OperationKind.Tuple, Type: (System.Int32, System.Int32)) (Syntax: '(1, If(b, 2, 3))') NaturalType: (System.Int32, System.Int32) Elements(2): IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: '1') IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'If(b, 2, 3)') Next (Regular) Block[B5] Leaving: {R1} } Block[B5] - Exit Predecessors: [B4] Statements (0) ]]>.Value VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact()> Public Sub TupleFlow_02() Dim source = <![CDATA[ Class C Sub M(b As Boolean)'BIND:"Sub M(b As Boolean)" Dim t As (Integer, (Integer, Integer)) = (1, (2, If(b, 2, 3))) End Sub End Class]]>.Value Dim expectedDiagnostics = String.Empty Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [t As (System.Int32, (System.Int32, System.Int32))] CaptureIds: [0] [1] [2] Block[B1] - Block Predecessors: [B0] Statements (2) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '1') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '2') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') Jump if False (Regular) to Block[B3] IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b') Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '2') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') Next (Regular) Block[B4] Block[B3] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '3') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B2] [B3] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: (System.Int32, (System.Int32, System.Int32)), IsImplicit) (Syntax: 't As (Integ ... (b, 2, 3)))') Left: ILocalReferenceOperation: t (IsDeclaration: True) (OperationKind.LocalReference, Type: (System.Int32, (System.Int32, System.Int32)), IsImplicit) (Syntax: 't') Right: ITupleOperation (OperationKind.Tuple, Type: (System.Int32, (System.Int32, System.Int32))) (Syntax: '(1, (2, If(b, 2, 3)))') NaturalType: (System.Int32, (System.Int32, System.Int32)) Elements(2): IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: '1') ITupleOperation (OperationKind.Tuple, Type: (System.Int32, System.Int32)) (Syntax: '(2, If(b, 2, 3))') NaturalType: (System.Int32, System.Int32) Elements(2): IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 2, IsImplicit) (Syntax: '2') IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'If(b, 2, 3)') Next (Regular) Block[B5] Leaving: {R1} } Block[B5] - Exit Predecessors: [B4] Statements (0) ]]>.Value VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact()> Public Sub TupleFlow_03() Dim source = <![CDATA[ Class C Sub M(b As Boolean)'BIND:"Sub M(b As Boolean)" M2((1, If(b, 2, 3))) End Sub Sub M2(arg As (Integer, Integer)) End Sub End Class]]>.Value Dim expectedDiagnostics = String.Empty Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [1] [2] Block[B1] - Block Predecessors: [B0] Statements (2) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'M2') Value: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: 'M2') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '1') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Jump if False (Regular) to Block[B3] IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b') Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '2') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') Next (Regular) Block[B4] Block[B3] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '3') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B2] [B3] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'M2((1, If(b, 2, 3)))') Expression: IInvocationOperation ( Sub C.M2(arg As (System.Int32, System.Int32))) (OperationKind.Invocation, Type: System.Void) (Syntax: 'M2((1, If(b, 2, 3)))') Instance Receiver: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'M2') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: arg) (OperationKind.Argument, Type: null) (Syntax: '(1, If(b, 2, 3))') ITupleOperation (OperationKind.Tuple, Type: (System.Int32, System.Int32)) (Syntax: '(1, If(b, 2, 3))') NaturalType: (System.Int32, System.Int32) Elements(2): IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: '1') IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'If(b, 2, 3)') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Next (Regular) Block[B5] Leaving: {R1} } Block[B5] - Exit Predecessors: [B4] Statements (0) ]]>.Value VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact()> Public Sub TupleFlow_04() Dim source = <![CDATA[ Class C Sub M(b As Boolean)'BIND:"Sub M(b As Boolean)" Dim t As (Integer, Integer) = (If(b, 2, 3), 1) End Sub End Class]]>.Value Dim expectedDiagnostics = String.Empty Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [t As (System.Int32, System.Int32)] CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (0) Jump if False (Regular) to Block[B3] IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b') Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '2') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') Next (Regular) Block[B4] Block[B3] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '3') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B2] [B3] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: (System.Int32, System.Int32), IsImplicit) (Syntax: 't As (Integ ... , 2, 3), 1)') Left: ILocalReferenceOperation: t (IsDeclaration: True) (OperationKind.LocalReference, Type: (System.Int32, System.Int32), IsImplicit) (Syntax: 't') Right: ITupleOperation (OperationKind.Tuple, Type: (System.Int32, System.Int32)) (Syntax: '(If(b, 2, 3), 1)') NaturalType: (System.Int32, System.Int32) Elements(2): IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'If(b, 2, 3)') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Next (Regular) Block[B5] Leaving: {R1} } Block[B5] - Exit Predecessors: [B4] Statements (0) ]]>.Value VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) End Sub End Class End Namespace
-1
dotnet/roslyn
55,138
Avoid cancellation exceptions in intermediate operations
Addresses the following exceptions: ![image](https://user-images.githubusercontent.com/1408396/127185947-8a005aea-ae1c-4755-bf0f-21dfb8101352.png)
sharwell
2021-07-27T15:51:28Z
2021-07-27T21:36:45Z
3d8acbd585a75e9cdb3509623bf6c39ceb46b2c2
719d4ffa2be734463e5d7d4d74b23b8006fd7727
Avoid cancellation exceptions in intermediate operations. Addresses the following exceptions: ![image](https://user-images.githubusercontent.com/1408396/127185947-8a005aea-ae1c-4755-bf0f-21dfb8101352.png)
./src/VisualStudio/IntegrationTest/IntegrationTests/VisualBasic/BasicF1Help.cs
// Licensed to the .NET Foundation under one or more agreements. // 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; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.VisualStudio.IntegrationTest.Utilities; using Roslyn.Test.Utilities; using Xunit; using Xunit.Abstractions; namespace Roslyn.VisualStudio.IntegrationTests.VisualBasic { [Collection(nameof(SharedIntegrationHostFixture))] public class BasicF1Help : AbstractEditorTest { protected override string LanguageName => LanguageNames.VisualBasic; public BasicF1Help(VisualStudioInstanceFactory instanceFactory) : base(instanceFactory, nameof(BasicF1Help)) { } [WpfFact, Trait(Traits.Feature, Traits.Features.F1Help)] private void F1Help() { var text = @" Imports System Imports System.Collections.Generic Imports System.Linq Module Program$$ Sub Main(args As String()) Dim query = From arg In args Select args.Any(Function(a) a.Length > 5) Dim x = 0 x += 1 End Sub Public Function F() As Object Return Nothing End Function End Module"; SetUpEditor(text); Verify("Linq", "System.Linq"); Verify("String", "vb.String"); Verify("Any", "System.Linq.Enumerable.Any"); Verify("From", "vb.QueryFrom"); Verify("+=", "vb.+="); Verify("Nothing", "vb.Nothing"); } private void Verify(string word, string expectedKeyword) { VisualStudio.Editor.PlaceCaret(word, charsOffset: -1); Assert.Contains(expectedKeyword, VisualStudio.Editor.GetF1Keyword()); } } }
// Licensed to the .NET Foundation under one or more agreements. // 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; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.VisualStudio.IntegrationTest.Utilities; using Roslyn.Test.Utilities; using Xunit; using Xunit.Abstractions; namespace Roslyn.VisualStudio.IntegrationTests.VisualBasic { [Collection(nameof(SharedIntegrationHostFixture))] public class BasicF1Help : AbstractEditorTest { protected override string LanguageName => LanguageNames.VisualBasic; public BasicF1Help(VisualStudioInstanceFactory instanceFactory) : base(instanceFactory, nameof(BasicF1Help)) { } [WpfFact, Trait(Traits.Feature, Traits.Features.F1Help)] private void F1Help() { var text = @" Imports System Imports System.Collections.Generic Imports System.Linq Module Program$$ Sub Main(args As String()) Dim query = From arg In args Select args.Any(Function(a) a.Length > 5) Dim x = 0 x += 1 End Sub Public Function F() As Object Return Nothing End Function End Module"; SetUpEditor(text); Verify("Linq", "System.Linq"); Verify("String", "vb.String"); Verify("Any", "System.Linq.Enumerable.Any"); Verify("From", "vb.QueryFrom"); Verify("+=", "vb.+="); Verify("Nothing", "vb.Nothing"); } private void Verify(string word, string expectedKeyword) { VisualStudio.Editor.PlaceCaret(word, charsOffset: -1); Assert.Contains(expectedKeyword, VisualStudio.Editor.GetF1Keyword()); } } }
-1
dotnet/roslyn
55,138
Avoid cancellation exceptions in intermediate operations
Addresses the following exceptions: ![image](https://user-images.githubusercontent.com/1408396/127185947-8a005aea-ae1c-4755-bf0f-21dfb8101352.png)
sharwell
2021-07-27T15:51:28Z
2021-07-27T21:36:45Z
3d8acbd585a75e9cdb3509623bf6c39ceb46b2c2
719d4ffa2be734463e5d7d4d74b23b8006fd7727
Avoid cancellation exceptions in intermediate operations. Addresses the following exceptions: ![image](https://user-images.githubusercontent.com/1408396/127185947-8a005aea-ae1c-4755-bf0f-21dfb8101352.png)
./src/Tools/Source/CompilerGeneratorTools/Source/CSharpSyntaxGenerator/CachingSourceGenerator.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. // We only build the Source Generator in the netstandard target #if NETSTANDARD using System; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Runtime.CompilerServices; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Text; namespace CSharpSyntaxGenerator { public abstract class CachingSourceGenerator : ISourceGenerator { /// <summary> /// ⚠ This value may be accessed by multiple threads. /// </summary> private static readonly WeakReference<CachedSourceGeneratorResult> s_cachedResult = new(null); protected abstract bool TryGetRelevantInput(in GeneratorExecutionContext context, out AdditionalText? input, out SourceText? inputText); protected abstract bool TryGenerateSources( AdditionalText input, SourceText inputText, out ImmutableArray<(string hintName, SourceText sourceText)> sources, out ImmutableArray<Diagnostic> diagnostics, CancellationToken cancellationToken); public void Initialize(GeneratorInitializationContext context) { } public void Execute(GeneratorExecutionContext context) { if (!TryGetRelevantInput(in context, out var input, out var inputText)) { return; } // Get the current input checksum, which will either be used for verifying the current cache or updating it // with the new results. var currentChecksum = inputText.GetChecksum(); // Read the current cached result once to avoid race conditions if (s_cachedResult.TryGetTarget(out var cachedResult) && cachedResult.Checksum.SequenceEqual(currentChecksum)) { // Add the previously-cached sources, and leave the cache as it was AddSources(in context, sources: cachedResult.Sources); return; } if (TryGenerateSources(input, inputText, out var sources, out var diagnostics, context.CancellationToken)) { AddSources(in context, sources); if (diagnostics.IsEmpty) { var result = new CachedSourceGeneratorResult(currentChecksum, sources); // Default Large Object Heap size threshold // https://github.com/dotnet/runtime/blob/c9d69e38d0e54bea5d188593ef6c3b30139f3ab1/src/coreclr/src/gc/gc.h#L111 const int Threshold = 85000; // Overwrite the cached result with the new result. This is an opportunistic cache, so as long as // the write is atomic (which it is for SetTarget) synchronization is unnecessary. We allocate an // array on the Large Object Heap (which is always part of Generation 2) and give it a reference to // the cached object to ensure this weak reference is not reclaimed prior to a full GC pass. var largeArray = new CachedSourceGeneratorResult[Threshold / Unsafe.SizeOf<CachedSourceGeneratorResult>()]; Debug.Assert(GC.GetGeneration(largeArray) >= 2); largeArray[0] = result; s_cachedResult.SetTarget(result); GC.KeepAlive(largeArray); } else { // Invalidate the cache since we cannot currently cache diagnostics s_cachedResult.SetTarget(null); } } else { // Invalidate the cache since generation failed s_cachedResult.SetTarget(null); } // Always report the diagnostics (if any) foreach (var diagnostic in diagnostics) { context.ReportDiagnostic(diagnostic); } } private static void AddSources( in GeneratorExecutionContext context, ImmutableArray<(string hintName, SourceText sourceText)> sources) { foreach (var (hintName, sourceText) in sources) { context.AddSource(hintName, sourceText); } } private sealed record CachedSourceGeneratorResult( ImmutableArray<byte> Checksum, ImmutableArray<(string hintName, SourceText sourceText)> Sources); } } #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. // We only build the Source Generator in the netstandard target #if NETSTANDARD using System; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Runtime.CompilerServices; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Text; namespace CSharpSyntaxGenerator { public abstract class CachingSourceGenerator : ISourceGenerator { /// <summary> /// ⚠ This value may be accessed by multiple threads. /// </summary> private static readonly WeakReference<CachedSourceGeneratorResult> s_cachedResult = new(null); protected abstract bool TryGetRelevantInput(in GeneratorExecutionContext context, out AdditionalText? input, out SourceText? inputText); protected abstract bool TryGenerateSources( AdditionalText input, SourceText inputText, out ImmutableArray<(string hintName, SourceText sourceText)> sources, out ImmutableArray<Diagnostic> diagnostics, CancellationToken cancellationToken); public void Initialize(GeneratorInitializationContext context) { } public void Execute(GeneratorExecutionContext context) { if (!TryGetRelevantInput(in context, out var input, out var inputText)) { return; } // Get the current input checksum, which will either be used for verifying the current cache or updating it // with the new results. var currentChecksum = inputText.GetChecksum(); // Read the current cached result once to avoid race conditions if (s_cachedResult.TryGetTarget(out var cachedResult) && cachedResult.Checksum.SequenceEqual(currentChecksum)) { // Add the previously-cached sources, and leave the cache as it was AddSources(in context, sources: cachedResult.Sources); return; } if (TryGenerateSources(input, inputText, out var sources, out var diagnostics, context.CancellationToken)) { AddSources(in context, sources); if (diagnostics.IsEmpty) { var result = new CachedSourceGeneratorResult(currentChecksum, sources); // Default Large Object Heap size threshold // https://github.com/dotnet/runtime/blob/c9d69e38d0e54bea5d188593ef6c3b30139f3ab1/src/coreclr/src/gc/gc.h#L111 const int Threshold = 85000; // Overwrite the cached result with the new result. This is an opportunistic cache, so as long as // the write is atomic (which it is for SetTarget) synchronization is unnecessary. We allocate an // array on the Large Object Heap (which is always part of Generation 2) and give it a reference to // the cached object to ensure this weak reference is not reclaimed prior to a full GC pass. var largeArray = new CachedSourceGeneratorResult[Threshold / Unsafe.SizeOf<CachedSourceGeneratorResult>()]; Debug.Assert(GC.GetGeneration(largeArray) >= 2); largeArray[0] = result; s_cachedResult.SetTarget(result); GC.KeepAlive(largeArray); } else { // Invalidate the cache since we cannot currently cache diagnostics s_cachedResult.SetTarget(null); } } else { // Invalidate the cache since generation failed s_cachedResult.SetTarget(null); } // Always report the diagnostics (if any) foreach (var diagnostic in diagnostics) { context.ReportDiagnostic(diagnostic); } } private static void AddSources( in GeneratorExecutionContext context, ImmutableArray<(string hintName, SourceText sourceText)> sources) { foreach (var (hintName, sourceText) in sources) { context.AddSource(hintName, sourceText); } } private sealed record CachedSourceGeneratorResult( ImmutableArray<byte> Checksum, ImmutableArray<(string hintName, SourceText sourceText)> Sources); } } #endif
-1
dotnet/roslyn
55,138
Avoid cancellation exceptions in intermediate operations
Addresses the following exceptions: ![image](https://user-images.githubusercontent.com/1408396/127185947-8a005aea-ae1c-4755-bf0f-21dfb8101352.png)
sharwell
2021-07-27T15:51:28Z
2021-07-27T21:36:45Z
3d8acbd585a75e9cdb3509623bf6c39ceb46b2c2
719d4ffa2be734463e5d7d4d74b23b8006fd7727
Avoid cancellation exceptions in intermediate operations. Addresses the following exceptions: ![image](https://user-images.githubusercontent.com/1408396/127185947-8a005aea-ae1c-4755-bf0f-21dfb8101352.png)
./src/Dependencies/CodeAnalysis.Debugging/Microsoft.CodeAnalysis.Debugging.shproj
<?xml version="1.0" encoding="utf-8"?> <!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE file in the project root for more information. --> <Project> <PropertyGroup Label="Globals"> <ProjectGuid>d73adf7d-2c1c-42ae-b2ab-edc9497e4b71</ProjectGuid> <MinimumVisualStudioVersion>14.0</MinimumVisualStudioVersion> </PropertyGroup> <Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" /> <Import Project="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\CodeSharing\Microsoft.CodeSharing.Common.Default.props" /> <Import Project="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\CodeSharing\Microsoft.CodeSharing.Common.props" /> <PropertyGroup /> <Import Project="Microsoft.CodeAnalysis.Debugging.projitems" Label="Shared" /> <Import Project="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\CodeSharing\Microsoft.CodeSharing.CSharp.targets" /> </Project>
<?xml version="1.0" encoding="utf-8"?> <!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE file in the project root for more information. --> <Project> <PropertyGroup Label="Globals"> <ProjectGuid>d73adf7d-2c1c-42ae-b2ab-edc9497e4b71</ProjectGuid> <MinimumVisualStudioVersion>14.0</MinimumVisualStudioVersion> </PropertyGroup> <Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" /> <Import Project="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\CodeSharing\Microsoft.CodeSharing.Common.Default.props" /> <Import Project="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\CodeSharing\Microsoft.CodeSharing.Common.props" /> <PropertyGroup /> <Import Project="Microsoft.CodeAnalysis.Debugging.projitems" Label="Shared" /> <Import Project="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\CodeSharing\Microsoft.CodeSharing.CSharp.targets" /> </Project>
-1
dotnet/roslyn
55,138
Avoid cancellation exceptions in intermediate operations
Addresses the following exceptions: ![image](https://user-images.githubusercontent.com/1408396/127185947-8a005aea-ae1c-4755-bf0f-21dfb8101352.png)
sharwell
2021-07-27T15:51:28Z
2021-07-27T21:36:45Z
3d8acbd585a75e9cdb3509623bf6c39ceb46b2c2
719d4ffa2be734463e5d7d4d74b23b8006fd7727
Avoid cancellation exceptions in intermediate operations. Addresses the following exceptions: ![image](https://user-images.githubusercontent.com/1408396/127185947-8a005aea-ae1c-4755-bf0f-21dfb8101352.png)
./src/Compilers/VisualBasic/Test/Syntax/Syntax/SyntaxFactsTest.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.IO Imports System.Text Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities Public Class SyntaxFactsTests Private Shared ReadOnly s_allInOneSource As String Shared Sub New() Using stream = New StreamReader(GetType(SyntaxFactsTests).Assembly.GetManifestResourceStream("AllInOne.vb"), Encoding.UTF8) s_allInOneSource = stream.ReadToEnd() End Using End Sub <Fact> Public Sub IsKeyword1() Assert.False(CType(Nothing, SyntaxToken).IsKeyword()) End Sub <Fact> Public Sub IsKeyword2() Assert.True(SyntaxFactory.Token(SyntaxKind.MyClassKeyword).IsKeyword()) End Sub <Fact> Public Sub IsKeyword3() Assert.False(SyntaxFactory.IntegerLiteralToken("1", LiteralBase.Decimal, TypeCharacter.None, 1).IsKeyword()) End Sub <Fact> Public Sub IsXmlTextToken1() Assert.False(SyntaxFacts.IsXmlTextToken(Nothing)) End Sub <Fact> Public Sub IsXmlTextToken2() Assert.True(SyntaxFacts.IsXmlTextToken(SyntaxKind.XmlTextLiteralToken)) End Sub <Fact> Public Sub IsXmlTextToken3() Assert.False(SyntaxFacts.IsXmlTextToken(SyntaxKind.AtToken)) End Sub <Fact> Public Sub Bug2644() Assert.Equal(SyntaxKind.ClassKeyword, SyntaxFacts.GetKeywordKind("Class")) Assert.Equal(SyntaxKind.None, SyntaxFacts.GetKeywordKind("Where")) End Sub <Fact> Public Sub GetAccessorStatementKind() Assert.Equal(SyntaxKind.GetAccessorStatement, SyntaxFacts.GetAccessorStatementKind(SyntaxKind.GetKeyword)) Assert.Equal(SyntaxKind.SetAccessorStatement, SyntaxFacts.GetAccessorStatementKind(SyntaxKind.SetKeyword)) Assert.Equal(SyntaxKind.RemoveHandlerStatement, SyntaxFacts.GetAccessorStatementKind(SyntaxKind.RemoveHandlerKeyword)) Assert.Equal(SyntaxKind.AddHandlerStatement, SyntaxFacts.GetAccessorStatementKind(SyntaxKind.AddHandlerKeyword)) Assert.Equal(SyntaxKind.RaiseEventAccessorStatement, SyntaxFacts.GetAccessorStatementKind(SyntaxKind.RaiseEventKeyword)) Assert.Equal(SyntaxKind.None, SyntaxFacts.GetAccessorStatementKind(SyntaxKind.AddressOfKeyword)) End Sub <Fact> Public Sub GetBaseTypeStatementKind() Assert.Equal(SyntaxKind.EnumStatement, SyntaxFacts.GetBaseTypeStatementKind(SyntaxKind.EnumKeyword)) Assert.Equal(SyntaxKind.ClassStatement, SyntaxFacts.GetBaseTypeStatementKind(SyntaxKind.ClassKeyword)) Assert.Equal(SyntaxKind.StructureStatement, SyntaxFacts.GetBaseTypeStatementKind(SyntaxKind.StructureKeyword)) Assert.Equal(SyntaxKind.InterfaceStatement, SyntaxFacts.GetBaseTypeStatementKind(SyntaxKind.InterfaceKeyword)) Assert.Equal(SyntaxKind.None, SyntaxFacts.GetBaseTypeStatementKind(SyntaxKind.ForKeyword)) End Sub <Fact> Public Sub GetBinaryExpression() For Each item As SyntaxKind In {SyntaxKind.IsKeyword, SyntaxKind.IsNotKeyword, SyntaxKind.LikeKeyword, SyntaxKind.AndKeyword, SyntaxKind.AndAlsoKeyword, SyntaxKind.OrKeyword, SyntaxKind.OrElseKeyword, SyntaxKind.XorKeyword, SyntaxKind.AmpersandToken, SyntaxKind.AsteriskToken, SyntaxKind.PlusToken, SyntaxKind.MinusToken, SyntaxKind.SlashToken, SyntaxKind.BackslashToken, SyntaxKind.ModKeyword, SyntaxKind.CaretToken, SyntaxKind.LessThanToken, SyntaxKind.LessThanEqualsToken, SyntaxKind.LessThanGreaterThanToken, SyntaxKind.EqualsToken, SyntaxKind.GreaterThanToken, SyntaxKind.GreaterThanEqualsToken, SyntaxKind.LessThanLessThanToken, SyntaxKind.GreaterThanGreaterThanToken} Assert.NotEqual(SyntaxKind.None, SyntaxFacts.GetBinaryExpression(item)) Next Assert.Equal(SyntaxKind.SubtractExpression, SyntaxFacts.GetBinaryExpression(SyntaxKind.MinusToken)) Assert.Equal(SyntaxKind.AndAlsoExpression, SyntaxFacts.GetBinaryExpression(SyntaxKind.AndAlsoKeyword)) Assert.Equal(SyntaxKind.None, SyntaxFacts.GetBinaryExpression(SyntaxKind.ForKeyword)) Assert.Equal(SyntaxKind.None, SyntaxFacts.GetBaseTypeStatementKind(SyntaxKind.ForKeyword)) End Sub <Fact> Public Sub GetBlockName() Assert.Equal("Case", SyntaxFacts.GetBlockName(SyntaxKind.CaseBlock)) Assert.Equal("Do Loop", SyntaxFacts.GetBlockName(SyntaxKind.SimpleDoLoopBlock)) Assert.Equal("Do Loop", SyntaxFacts.GetBlockName(SyntaxKind.DoWhileLoopBlock)) Assert.Equal("Do Loop", SyntaxFacts.GetBlockName(SyntaxKind.DoUntilLoopBlock)) Assert.Equal("Do Loop", SyntaxFacts.GetBlockName(SyntaxKind.DoLoopWhileBlock)) Assert.Equal("Do Loop", SyntaxFacts.GetBlockName(SyntaxKind.DoLoopUntilBlock)) Assert.Equal("While", SyntaxFacts.GetBlockName(SyntaxKind.WhileBlock)) Assert.Equal("With", SyntaxFacts.GetBlockName(SyntaxKind.WithBlock)) Assert.Equal("SyncLock", SyntaxFacts.GetBlockName(SyntaxKind.SyncLockBlock)) Assert.Equal("Using", SyntaxFacts.GetBlockName(SyntaxKind.UsingBlock)) Assert.Equal("For", SyntaxFacts.GetBlockName(SyntaxKind.ForBlock)) Assert.Equal("For Each", SyntaxFacts.GetBlockName(SyntaxKind.ForEachBlock)) Assert.Equal("Select", SyntaxFacts.GetBlockName(SyntaxKind.SelectBlock)) Assert.Equal("If", SyntaxFacts.GetBlockName(SyntaxKind.MultiLineIfBlock)) Assert.Equal("Else If", SyntaxFacts.GetBlockName(SyntaxKind.ElseIfBlock)) Assert.Equal("Else", SyntaxFacts.GetBlockName(SyntaxKind.ElseBlock)) Assert.Equal("Try", SyntaxFacts.GetBlockName(SyntaxKind.TryBlock)) Assert.Equal("Catch", SyntaxFacts.GetBlockName(SyntaxKind.CatchBlock)) Assert.Equal("Finally", SyntaxFacts.GetBlockName(SyntaxKind.FinallyBlock)) End Sub <Fact> Public Sub GetContextualKeywordKind() Assert.Equal(SyntaxKind.MidKeyword, SyntaxFacts.GetContextualKeywordKind("mid")) Assert.Equal(SyntaxKind.FromKeyword, SyntaxFacts.GetContextualKeywordKind("from")) Assert.Equal(SyntaxKind.None, SyntaxFacts.GetContextualKeywordKind(String.Empty)) Assert.Equal(SyntaxKind.None, SyntaxFacts.GetBaseTypeStatementKind(SyntaxKind.ForKeyword)) Dim expected = New String() {"aggregate", "all", "ansi", "ascending", "assembly", "async", "auto", "await", "binary", "by", "compare", "custom", "descending", "distinct", "equals", "explicit", "externalsource", "externalchecksum", "from", "group", "infer", "into", "isfalse", "istrue", "iterator", "join", "key", "mid", "off", "order", "out", "preserve", "r", "region", "skip", "strict", "take", "text", "unicode", "until", "where", "type", "xml", "yield", "enable", "disable", "warning"} For Each item In expected Assert.NotEqual(SyntaxKind.None, SyntaxFacts.GetContextualKeywordKind(item)) Next Dim actualCount = SyntaxFacts.GetContextualKeywordKinds.Count Assert.Equal(expected.Count, actualCount) End Sub <Fact> <WorkItem(15925, "DevDiv_Projects/Roslyn")> Public Sub GetContextualKeywordsKinds() Assert.NotEqual(0, SyntaxFacts.GetContextualKeywordKinds.Count) Assert.Contains(SyntaxKind.FromKeyword, SyntaxFacts.GetContextualKeywordKinds) Assert.DoesNotContain(SyntaxKind.DimKeyword, SyntaxFacts.GetContextualKeywordKinds) Assert.DoesNotContain(SyntaxKind.StaticKeyword, SyntaxFacts.GetContextualKeywordKinds) End Sub <Fact> Public Sub GetInstanceExpression() Assert.Equal(SyntaxKind.None, SyntaxFacts.GetInstanceExpression(SyntaxKind.DeclareKeyword)) Assert.Equal(SyntaxKind.MeExpression, SyntaxFacts.GetInstanceExpression(SyntaxKind.MeKeyword)) Assert.Equal(SyntaxKind.MyBaseExpression, SyntaxFacts.GetInstanceExpression(SyntaxKind.MyBaseKeyword)) Assert.Equal(SyntaxKind.MyClassExpression, SyntaxFacts.GetInstanceExpression(SyntaxKind.MyClassKeyword)) End Sub <Fact> Public Sub GetKeywordkinds() Assert.NotEqual(0, SyntaxFacts.GetKeywordKinds.Count) Assert.Contains(SyntaxKind.CIntKeyword, SyntaxFacts.GetKeywordKinds) End Sub <Fact> Public Sub GetPreprocessorKeywordKind() Dim item As String For Each item In New String() {"if", "elseif", "else", "endif", "region", "end", "const", "externalsource", "externalchecksum", "enable", "disable"} Assert.NotEqual(SyntaxKind.None, SyntaxFacts.GetPreprocessorKeywordKind(item)) Next Assert.Equal(SyntaxKind.ExternalSourceKeyword, SyntaxFacts.GetPreprocessorKeywordKind("externalsource")) Assert.Equal(SyntaxKind.EndKeyword, SyntaxFacts.GetPreprocessorKeywordKind("end")) Assert.Equal(SyntaxKind.DisableKeyword, SyntaxFacts.GetPreprocessorKeywordKind("disable")) Assert.Equal(SyntaxKind.EnableKeyword, SyntaxFacts.GetPreprocessorKeywordKind("enable")) Assert.Equal(SyntaxKind.None, SyntaxFacts.GetPreprocessorKeywordKind(String.Empty)) Assert.Equal(SyntaxKind.None, SyntaxFacts.GetPreprocessorKeywordKind("d")) End Sub <Fact> Public Sub GetPreprocessorKeywordKinds() Assert.Contains(SyntaxKind.RegionKeyword, SyntaxFacts.GetPreprocessorKeywordKinds) Assert.Contains(SyntaxKind.EnableKeyword, SyntaxFacts.GetPreprocessorKeywordKinds) Assert.Contains(SyntaxKind.WarningKeyword, SyntaxFacts.GetPreprocessorKeywordKinds) Assert.Contains(SyntaxKind.DisableKeyword, SyntaxFacts.GetPreprocessorKeywordKinds) Assert.DoesNotContain(SyntaxKind.PublicKeyword, SyntaxFacts.GetPreprocessorKeywordKinds) End Sub <Fact> Public Sub GetPunctuationKinds() Assert.NotEqual(0, SyntaxFacts.GetPunctuationKinds.Count) Assert.Contains(SyntaxKind.ExclamationToken, SyntaxFacts.GetPunctuationKinds) Assert.Contains(SyntaxKind.EmptyToken, SyntaxFacts.GetPunctuationKinds) Assert.DoesNotContain(SyntaxKind.NumericLabel, SyntaxFacts.GetPunctuationKinds) End Sub <Fact> Public Sub GetReservedKeywordsKinds() Assert.NotEqual(0, SyntaxFacts.GetReservedKeywordKinds.Count) Assert.Contains(SyntaxKind.AddressOfKeyword, SyntaxFacts.GetReservedKeywordKinds) Assert.DoesNotContain(SyntaxKind.QualifiedName, SyntaxFacts.GetReservedKeywordKinds) End Sub <Fact> Public Sub IsAccessorStatement() For Each item As SyntaxKind In {SyntaxKind.GetAccessorStatement, SyntaxKind.SetAccessorStatement, SyntaxKind.AddHandlerAccessorStatement, SyntaxKind.RemoveHandlerAccessorStatement, SyntaxKind.RaiseEventAccessorStatement} Assert.True(SyntaxFacts.IsAccessorStatement(item)) Next Assert.False(SyntaxFacts.IsAccessorStatement(SyntaxKind.SubKeyword)) Assert.False(SyntaxFacts.IsAccessorStatement(SyntaxKind.None)) End Sub <Fact> Public Sub IsAccessorStatementKeyword() For Each item As SyntaxKind In {SyntaxKind.GetKeyword, SyntaxKind.SetKeyword, SyntaxKind.AddHandlerKeyword, SyntaxKind.RemoveHandlerKeyword, SyntaxKind.RaiseEventKeyword} Assert.True(SyntaxFacts.IsAccessorStatementAccessorKeyword(item)) Next Assert.False(SyntaxFacts.IsAccessorStatementAccessorKeyword(SyntaxKind.SubKeyword)) Assert.False(SyntaxFacts.IsAccessorStatementAccessorKeyword(SyntaxKind.None)) End Sub <Fact> Public Sub IsAddRemoveHandlerStatement() For Each item As SyntaxKind In {SyntaxKind.AddHandlerStatement, SyntaxKind.RemoveHandlerStatement} Assert.True(SyntaxFacts.IsAddRemoveHandlerStatement(item)) Next Assert.False(SyntaxFacts.IsAddRemoveHandlerStatement(SyntaxKind.ExitKeyword)) Assert.False(SyntaxFacts.IsAddRemoveHandlerStatement(SyntaxKind.None)) End Sub <Fact> Public Sub IsAddRemoveHandlerStatementAddHandlerOrRemoveHandlerKeyword() For Each item As SyntaxKind In {SyntaxKind.AddHandlerKeyword, SyntaxKind.RemoveHandlerKeyword} Assert.True(SyntaxFacts.IsAddRemoveHandlerStatementAddHandlerOrRemoveHandlerKeyword(item)) Next Assert.False(SyntaxFacts.IsAddRemoveHandlerStatementAddHandlerOrRemoveHandlerKeyword(SyntaxKind.ExitKeyword)) Assert.False(SyntaxFacts.IsAddRemoveHandlerStatementAddHandlerOrRemoveHandlerKeyword(SyntaxKind.None)) End Sub <Fact> Public Sub IsaddressofOperand() Dim source = <compilation name="TestAddressof"> <file name="a.vb"> <![CDATA[ #If Debug Then #End If Namespace NS1 Module Module1 Delegate Sub DelGoo(xx As Integer) Sub Goo(xx As Integer) End Sub Sub Main() Dim a1 = GetType(Integer) Dim d As DelGoo = AddressOf Goo d.Invoke(xx:=1) Dim Obj Gen As New genClass(Of Integer) End Sub <Obsolete> Sub OldMethod() End Sub End Module Class genClass(Of t) End Class End Namespace ]]></file> </compilation> Dim tree = CreateCompilationWithMscorlib40(source).SyntaxTrees.Item(0) Dim symNode = FindNodeOrTokenByKind(tree, SyntaxKind.AddressOfExpression, 1).AsNode Assert.False(SyntaxFacts.IsAddressOfOperand(DirectCast(symNode, ExpressionSyntax))) Assert.False(SyntaxFacts.IsInvocationOrAddressOfOperand(DirectCast(symNode, ExpressionSyntax))) Assert.True(SyntaxFacts.IsAddressOfOperand(CType(symNode.ChildNodes(0), ExpressionSyntax))) Assert.True(SyntaxFacts.IsInvocationOrAddressOfOperand(CType(symNode.ChildNodes(0), ExpressionSyntax))) Assert.False(SyntaxFacts.IsInvoked(DirectCast(FindNodeOrTokenByKind(tree, SyntaxKind.InvocationExpression, 1).AsNode, ExpressionSyntax))) symNode = FindNodeOrTokenByKind(tree, SyntaxKind.InvocationExpression, 1).AsNode Assert.False(SyntaxFacts.IsInvoked(CType(symNode, ExpressionSyntax))) Assert.True(SyntaxFacts.IsInvoked(CType(symNode.ChildNodes(0), ExpressionSyntax))) symNode = FindNodeOrTokenByKind(tree, SyntaxKind.Attribute, 1).AsNode Assert.False(SyntaxFacts.IsAttributeName(symNode)) Assert.True(SyntaxFacts.IsAttributeName(symNode.ChildNodes(0))) symNode = FindNodeOrTokenByKind(tree, SyntaxKind.Attribute, 1).AsNode End Sub <Fact> Public Sub IsAssignmentStatement() For Each item As SyntaxKind In {SyntaxKind.SimpleAssignmentStatement, SyntaxKind.MidAssignmentStatement, SyntaxKind.AddAssignmentStatement, SyntaxKind.SubtractAssignmentStatement, SyntaxKind.MultiplyAssignmentStatement, SyntaxKind.DivideAssignmentStatement, SyntaxKind.IntegerDivideAssignmentStatement, SyntaxKind.ExponentiateAssignmentStatement, SyntaxKind.LeftShiftAssignmentStatement, SyntaxKind.RightShiftAssignmentStatement, SyntaxKind.ConcatenateAssignmentStatement} Assert.True(SyntaxFacts.IsAssignmentStatement(item)) Next Assert.False(SyntaxFacts.IsAssignmentStatement(SyntaxKind.ExitKeyword)) Assert.False(SyntaxFacts.IsAssignmentStatement(SyntaxKind.None)) End Sub <Fact> Public Sub IsAssignmentStatementOperatorToken() For Each item As SyntaxKind In {SyntaxKind.EqualsToken, SyntaxKind.PlusEqualsToken, SyntaxKind.MinusEqualsToken, SyntaxKind.AsteriskEqualsToken, SyntaxKind.SlashEqualsToken, SyntaxKind.BackslashEqualsToken, SyntaxKind.CaretEqualsToken, SyntaxKind.LessThanLessThanEqualsToken, SyntaxKind.GreaterThanGreaterThanEqualsToken, SyntaxKind.AmpersandEqualsToken} Assert.True(SyntaxFacts.IsAssignmentStatementOperatorToken(item)) Next Assert.False(SyntaxFacts.IsAssignmentStatementOperatorToken(SyntaxKind.ExitKeyword)) Assert.False(SyntaxFacts.IsAssignmentStatementOperatorToken(SyntaxKind.None)) End Sub <Fact> Public Sub IsAttributeTargetAttributeModifier() For Each item As SyntaxKind In {SyntaxKind.AssemblyKeyword, SyntaxKind.ModuleKeyword} Assert.True(SyntaxFacts.IsAttributeTargetAttributeModifier(item)) Next Assert.False(SyntaxFacts.IsAttributeTargetAttributeModifier(SyntaxKind.SubKeyword)) Assert.False(SyntaxFacts.IsAttributeTargetAttributeModifier(SyntaxKind.None)) End Sub <Fact> Public Sub IsBinaryExpression() For Each item As SyntaxKind In {SyntaxKind.AddExpression, SyntaxKind.SubtractExpression, SyntaxKind.MultiplyExpression, SyntaxKind.DivideExpression, SyntaxKind.IntegerDivideExpression, SyntaxKind.ExponentiateExpression, SyntaxKind.LeftShiftExpression, SyntaxKind.RightShiftExpression, SyntaxKind.ConcatenateExpression, SyntaxKind.ModuloExpression, SyntaxKind.EqualsExpression, SyntaxKind.NotEqualsExpression, SyntaxKind.LessThanExpression, SyntaxKind.LessThanOrEqualExpression, SyntaxKind.GreaterThanOrEqualExpression, SyntaxKind.GreaterThanExpression, SyntaxKind.IsExpression, SyntaxKind.IsNotExpression, SyntaxKind.LikeExpression, SyntaxKind.OrExpression, SyntaxKind.ExclusiveOrExpression, SyntaxKind.AndExpression, SyntaxKind.OrElseExpression, SyntaxKind.AndAlsoExpression} Assert.True(SyntaxFacts.IsBinaryExpression(item)) Next Assert.False(SyntaxFacts.IsBinaryExpression(SyntaxKind.MinusToken)) Assert.False(SyntaxFacts.IsBinaryExpression(SyntaxKind.None)) End Sub <Fact> Public Sub IsBinaryExpressionOperatorToken() For Each item As SyntaxKind In {SyntaxKind.PlusToken, SyntaxKind.MinusToken, SyntaxKind.AsteriskToken, SyntaxKind.SlashToken, SyntaxKind.BackslashToken, SyntaxKind.CaretToken, SyntaxKind.LessThanLessThanToken, SyntaxKind.GreaterThanGreaterThanToken, SyntaxKind.AmpersandToken, SyntaxKind.ModKeyword, SyntaxKind.EqualsToken, SyntaxKind.LessThanGreaterThanToken, SyntaxKind.LessThanToken, SyntaxKind.LessThanEqualsToken, SyntaxKind.GreaterThanEqualsToken, SyntaxKind.GreaterThanToken, SyntaxKind.IsKeyword, SyntaxKind.IsNotKeyword, SyntaxKind.LikeKeyword, SyntaxKind.OrKeyword, SyntaxKind.XorKeyword, SyntaxKind.AndKeyword, SyntaxKind.OrElseKeyword, SyntaxKind.AndAlsoKeyword} Assert.True(SyntaxFacts.IsBinaryExpressionOperatorToken(item)) Next Assert.False(SyntaxFacts.IsBinaryExpressionOperatorToken(SyntaxKind.MinusEqualsToken)) Assert.False(SyntaxFacts.IsBinaryExpressionOperatorToken(SyntaxKind.None)) End Sub <Fact> Public Sub IsCaseBlock() For Each item As SyntaxKind In {SyntaxKind.CaseBlock, SyntaxKind.CaseElseBlock} Assert.True(SyntaxFacts.IsCaseBlock(item)) Next Assert.False(SyntaxFacts.IsCaseBlock(SyntaxKind.ExitKeyword)) Assert.False(SyntaxFacts.IsCaseBlock(SyntaxKind.None)) End Sub <Fact> Public Sub IsRelationalCaseClause() For Each item As SyntaxKind In {SyntaxKind.CaseEqualsClause, SyntaxKind.CaseNotEqualsClause, SyntaxKind.CaseLessThanClause, SyntaxKind.CaseLessThanOrEqualClause, SyntaxKind.CaseGreaterThanOrEqualClause, SyntaxKind.CaseGreaterThanClause} Assert.True(SyntaxFacts.IsRelationalCaseClause(item)) Next Assert.False(SyntaxFacts.IsRelationalCaseClause(SyntaxKind.ExitKeyword)) Assert.False(SyntaxFacts.IsRelationalCaseClause(SyntaxKind.None)) End Sub <Fact> Public Sub IsRelationalCaseClauseOperatorToken() For Each item As SyntaxKind In {SyntaxKind.EqualsToken, SyntaxKind.LessThanGreaterThanToken, SyntaxKind.LessThanToken, SyntaxKind.LessThanEqualsToken, SyntaxKind.GreaterThanEqualsToken, SyntaxKind.GreaterThanToken} Assert.True(SyntaxFacts.IsRelationalCaseClauseOperatorToken(item)) Next Assert.False(SyntaxFacts.IsRelationalCaseClauseOperatorToken(SyntaxKind.ExitKeyword)) Assert.False(SyntaxFacts.IsRelationalCaseClauseOperatorToken(SyntaxKind.None)) End Sub <Fact> Public Sub IsCaseStatement() For Each item As SyntaxKind In {SyntaxKind.CaseStatement, SyntaxKind.CaseElseStatement} Assert.True(SyntaxFacts.IsCaseStatement(item)) Next Assert.False(SyntaxFacts.IsCaseStatement(SyntaxKind.ExitKeyword)) Assert.False(SyntaxFacts.IsCaseStatement(SyntaxKind.None)) End Sub <Fact> Public Sub IsContextualKeyword1() Assert.False(SyntaxFacts.IsContextualKeyword(SyntaxKind.GosubKeyword)) Assert.True(SyntaxFacts.IsContextualKeyword(SyntaxKind.AggregateKeyword)) End Sub <Fact> Public Sub IsReservedKeyword() Assert.False(SyntaxFacts.IsReservedKeyword(SyntaxKind.OrderByClause)) Assert.True(SyntaxFacts.IsReservedKeyword(SyntaxKind.AddHandlerKeyword)) End Sub <Fact> Public Sub IsContinueStatement() For Each item As SyntaxKind In {SyntaxKind.ContinueWhileStatement, SyntaxKind.ContinueDoStatement, SyntaxKind.ContinueForStatement} Assert.True(SyntaxFacts.IsContinueStatement(item)) Next Assert.False(SyntaxFacts.IsContinueStatement(SyntaxKind.WithKeyword)) Assert.False(SyntaxFacts.IsContinueStatement(SyntaxKind.None)) End Sub <Fact> Public Sub IsContinueStatementBlockKeyword() For Each item As SyntaxKind In {SyntaxKind.WhileKeyword, SyntaxKind.DoKeyword, SyntaxKind.ForKeyword} Assert.True(SyntaxFacts.IsContinueStatementBlockKeyword(item)) Next Assert.False(SyntaxFacts.IsContinueStatementBlockKeyword(SyntaxKind.ExitKeyword)) Assert.False(SyntaxFacts.IsContinueStatementBlockKeyword(SyntaxKind.None)) End Sub <Fact> Public Sub IsDeclareStatement() For Each item As SyntaxKind In {SyntaxKind.DeclareSubStatement, SyntaxKind.DeclareFunctionStatement} Assert.True(SyntaxFacts.IsDeclareStatement(item)) Next Assert.False(SyntaxFacts.IsDeclareStatement(SyntaxKind.NamespaceBlock)) Assert.False(SyntaxFacts.IsDeclareStatement(SyntaxKind.None)) End Sub <Fact> Public Sub IsDeclareStatementCharsetKeyword() For Each item As SyntaxKind In {SyntaxKind.AnsiKeyword, SyntaxKind.UnicodeKeyword, SyntaxKind.AutoKeyword} Assert.True(SyntaxFacts.IsDeclareStatementCharsetKeyword(item)) Next Assert.False(SyntaxFacts.IsDeclareStatementCharsetKeyword(SyntaxKind.FunctionKeyword)) Assert.False(SyntaxFacts.IsDeclareStatementCharsetKeyword(SyntaxKind.None)) End Sub <Fact> Public Sub IsDeclareStatementKeyword() For Each item As SyntaxKind In {SyntaxKind.SubKeyword, SyntaxKind.FunctionKeyword} Assert.True(SyntaxFacts.IsDeclareStatementSubOrFunctionKeyword(item)) Next Assert.False(SyntaxFacts.IsDeclareStatementSubOrFunctionKeyword(SyntaxKind.NamespaceBlock)) Assert.False(SyntaxFacts.IsDeclareStatementSubOrFunctionKeyword(SyntaxKind.None)) End Sub <Fact> Public Sub IsDelegateStatement() For Each item As SyntaxKind In {SyntaxKind.DelegateSubStatement, SyntaxKind.DelegateFunctionStatement} Assert.True(SyntaxFacts.IsDelegateStatement(item)) Next Assert.False(SyntaxFacts.IsDelegateStatement(SyntaxKind.NamespaceBlock)) Assert.False(SyntaxFacts.IsDelegateStatement(SyntaxKind.None)) End Sub <Fact> Public Sub IsDelegateStatementKeyword() For Each item As SyntaxKind In {SyntaxKind.SubKeyword, SyntaxKind.FunctionKeyword} Assert.True(SyntaxFacts.IsDelegateStatementSubOrFunctionKeyword(item)) Next Assert.False(SyntaxFacts.IsDelegateStatementSubOrFunctionKeyword(SyntaxKind.NamespaceBlock)) Assert.False(SyntaxFacts.IsDelegateStatementSubOrFunctionKeyword(SyntaxKind.None)) End Sub <Fact> Public Sub IsDoLoopBlock() For Each item As SyntaxKind In {SyntaxKind.SimpleDoLoopBlock, SyntaxKind.DoWhileLoopBlock, SyntaxKind.DoUntilLoopBlock, SyntaxKind.DoLoopWhileBlock, SyntaxKind.DoLoopUntilBlock} Assert.True(SyntaxFacts.IsDoLoopBlock(item)) Next Assert.False(SyntaxFacts.IsDoLoopBlock(SyntaxKind.ExitKeyword)) Assert.False(SyntaxFacts.IsDoLoopBlock(SyntaxKind.None)) End Sub <Fact> Public Sub IsEndBlockStatement() For Each item As SyntaxKind In {SyntaxKind.EndIfStatement, SyntaxKind.EndUsingStatement, SyntaxKind.EndWithStatement, SyntaxKind.EndSelectStatement, SyntaxKind.EndStructureStatement, SyntaxKind.EndEnumStatement, SyntaxKind.EndInterfaceStatement, SyntaxKind.EndClassStatement, SyntaxKind.EndModuleStatement, SyntaxKind.EndNamespaceStatement, SyntaxKind.EndSubStatement, SyntaxKind.EndFunctionStatement, SyntaxKind.EndGetStatement, SyntaxKind.EndSetStatement, SyntaxKind.EndPropertyStatement, SyntaxKind.EndOperatorStatement, SyntaxKind.EndEventStatement, SyntaxKind.EndAddHandlerStatement, SyntaxKind.EndRemoveHandlerStatement, SyntaxKind.EndRaiseEventStatement, SyntaxKind.EndWhileStatement, SyntaxKind.EndTryStatement, SyntaxKind.EndSyncLockStatement} Assert.True(SyntaxFacts.IsEndBlockStatement(item)) Next Assert.False(SyntaxFacts.IsEndBlockStatement(SyntaxKind.AddHandlerStatement)) End Sub <Fact> Public Sub IsEndBlockStatementBlockKeyword() For Each item As SyntaxKind In {SyntaxKind.IfKeyword, SyntaxKind.UsingKeyword, SyntaxKind.WithKeyword, SyntaxKind.SelectKeyword, SyntaxKind.StructureKeyword, SyntaxKind.EnumKeyword, SyntaxKind.InterfaceKeyword, SyntaxKind.ClassKeyword, SyntaxKind.ModuleKeyword, SyntaxKind.NamespaceKeyword, SyntaxKind.SubKeyword, SyntaxKind.FunctionKeyword, SyntaxKind.GetKeyword, SyntaxKind.SetKeyword, SyntaxKind.PropertyKeyword, SyntaxKind.OperatorKeyword, SyntaxKind.EventKeyword, SyntaxKind.AddHandlerKeyword, SyntaxKind.RemoveHandlerKeyword, SyntaxKind.RaiseEventKeyword, SyntaxKind.WhileKeyword, SyntaxKind.TryKeyword, SyntaxKind.SyncLockKeyword} Assert.True(SyntaxFacts.IsEndBlockStatementBlockKeyword(item)) Next Assert.False(SyntaxFacts.IsEndBlockStatementBlockKeyword(SyntaxKind.AddHandlerStatement)) Assert.False(SyntaxFacts.IsEndBlockStatementBlockKeyword(SyntaxKind.None)) End Sub <Fact> Public Sub IsExitStatement() For Each item As SyntaxKind In {SyntaxKind.ExitDoStatement, SyntaxKind.ExitForStatement, SyntaxKind.ExitSubStatement, SyntaxKind.ExitFunctionStatement, SyntaxKind.ExitOperatorStatement, SyntaxKind.ExitPropertyStatement, SyntaxKind.ExitTryStatement, SyntaxKind.ExitSelectStatement, SyntaxKind.ExitWhileStatement} Assert.True(SyntaxFacts.IsExitStatement(item)) Next Assert.False(SyntaxFacts.IsExitStatement(SyntaxKind.WithKeyword)) Assert.False(SyntaxFacts.IsExitStatement(SyntaxKind.None)) End Sub <Fact> Public Sub IsExitStatementBlockKeyword() For Each item As SyntaxKind In {SyntaxKind.DoKeyword, SyntaxKind.ForKeyword, SyntaxKind.SubKeyword, SyntaxKind.FunctionKeyword, SyntaxKind.OperatorKeyword, SyntaxKind.PropertyKeyword, SyntaxKind.TryKeyword, SyntaxKind.SelectKeyword, SyntaxKind.WhileKeyword} Assert.True(SyntaxFacts.IsExitStatementBlockKeyword(item)) Next Assert.False(SyntaxFacts.IsExitStatementBlockKeyword(SyntaxKind.ExitKeyword)) Assert.False(SyntaxFacts.IsExitStatementBlockKeyword(SyntaxKind.None)) End Sub <Fact> Public Sub IsIfDirective() For Each item As SyntaxKind In {SyntaxKind.IfDirectiveTrivia, SyntaxKind.ElseIfDirectiveTrivia} Assert.True(SyntaxFacts.IsIfDirectiveTrivia(item)) Next Assert.False(SyntaxFacts.IsIfDirectiveTrivia(SyntaxKind.ExitKeyword)) Assert.False(SyntaxFacts.IsIfDirectiveTrivia(SyntaxKind.None)) End Sub <Fact> Public Sub IsIfDirectiveIfOrElseIfKeyword() For Each item As SyntaxKind In {SyntaxKind.IfKeyword, SyntaxKind.ElseIfKeyword} Assert.True(SyntaxFacts.IsIfDirectiveTriviaIfOrElseIfKeyword(item)) Next Assert.False(SyntaxFacts.IsIfDirectiveTriviaIfOrElseIfKeyword(SyntaxKind.ExitKeyword)) Assert.False(SyntaxFacts.IsIfDirectiveTriviaIfOrElseIfKeyword(SyntaxKind.None)) End Sub <Fact> Public Sub IsInstanceExpression() Assert.True(SyntaxFacts.IsInstanceExpression(SyntaxKind.MeKeyword)) Assert.True(SyntaxFacts.IsInstanceExpression(SyntaxKind.MyBaseKeyword)) Assert.False(SyntaxFacts.IsInstanceExpression(SyntaxKind.REMKeyword)) End Sub <Fact> Public Sub IsKeywordEventContainerKeyword() For Each item As SyntaxKind In {SyntaxKind.MyBaseKeyword, SyntaxKind.MeKeyword, SyntaxKind.MyClassKeyword} Assert.True(SyntaxFacts.IsKeywordEventContainerKeyword(item)) Next Assert.False(SyntaxFacts.IsKeywordEventContainerKeyword(SyntaxKind.SubKeyword)) Assert.False(SyntaxFacts.IsKeywordEventContainerKeyword(SyntaxKind.None)) End Sub <Fact> Public Sub IsKeywordKind() For Each item As SyntaxKind In {SyntaxKind.AddHandlerKeyword, SyntaxKind.AddressOfKeyword, SyntaxKind.AliasKeyword, SyntaxKind.AndKeyword, SyntaxKind.AndAlsoKeyword, SyntaxKind.AsKeyword, SyntaxKind.BooleanKeyword, SyntaxKind.ByRefKeyword, SyntaxKind.ByteKeyword, SyntaxKind.ByValKeyword, SyntaxKind.CallKeyword, SyntaxKind.CaseKeyword, SyntaxKind.CatchKeyword, SyntaxKind.CBoolKeyword, SyntaxKind.CByteKeyword, SyntaxKind.CCharKeyword, SyntaxKind.CDateKeyword, SyntaxKind.CDecKeyword, SyntaxKind.CDblKeyword, SyntaxKind.CharKeyword, SyntaxKind.CIntKeyword, SyntaxKind.ClassKeyword, SyntaxKind.CLngKeyword, SyntaxKind.CObjKeyword, SyntaxKind.ConstKeyword, SyntaxKind.ReferenceKeyword, SyntaxKind.ContinueKeyword, SyntaxKind.CSByteKeyword, SyntaxKind.CShortKeyword, SyntaxKind.CSngKeyword, SyntaxKind.CStrKeyword, SyntaxKind.CTypeKeyword, SyntaxKind.CUIntKeyword, SyntaxKind.CULngKeyword, SyntaxKind.CUShortKeyword, SyntaxKind.DateKeyword, SyntaxKind.DecimalKeyword, SyntaxKind.DeclareKeyword, SyntaxKind.DefaultKeyword, SyntaxKind.DelegateKeyword, SyntaxKind.DimKeyword, SyntaxKind.DirectCastKeyword, SyntaxKind.DoKeyword, SyntaxKind.DoubleKeyword, SyntaxKind.EachKeyword, SyntaxKind.ElseKeyword, SyntaxKind.ElseIfKeyword, SyntaxKind.EndKeyword, SyntaxKind.EnumKeyword, SyntaxKind.EraseKeyword, SyntaxKind.ErrorKeyword, SyntaxKind.EventKeyword, SyntaxKind.ExitKeyword, SyntaxKind.FalseKeyword, SyntaxKind.FinallyKeyword, SyntaxKind.ForKeyword, SyntaxKind.FriendKeyword, SyntaxKind.FunctionKeyword, SyntaxKind.GetKeyword, SyntaxKind.GetTypeKeyword, SyntaxKind.GetXmlNamespaceKeyword, SyntaxKind.GlobalKeyword, SyntaxKind.GoToKeyword, SyntaxKind.HandlesKeyword, SyntaxKind.IfKeyword, SyntaxKind.ImplementsKeyword, SyntaxKind.ImportsKeyword, SyntaxKind.InKeyword, SyntaxKind.InheritsKeyword, SyntaxKind.IntegerKeyword, SyntaxKind.InterfaceKeyword, SyntaxKind.IsKeyword, SyntaxKind.IsNotKeyword, SyntaxKind.LetKeyword, SyntaxKind.LibKeyword, SyntaxKind.LikeKeyword, SyntaxKind.LongKeyword, SyntaxKind.LoopKeyword, SyntaxKind.MeKeyword, SyntaxKind.ModKeyword, SyntaxKind.ModuleKeyword, SyntaxKind.MustInheritKeyword, SyntaxKind.MustOverrideKeyword, SyntaxKind.MyBaseKeyword, SyntaxKind.MyClassKeyword, SyntaxKind.NamespaceKeyword, SyntaxKind.NarrowingKeyword, SyntaxKind.NextKeyword, SyntaxKind.NewKeyword, SyntaxKind.NotKeyword, SyntaxKind.NothingKeyword, SyntaxKind.NotInheritableKeyword, SyntaxKind.NotOverridableKeyword, SyntaxKind.ObjectKeyword, SyntaxKind.OfKeyword, SyntaxKind.OnKeyword, SyntaxKind.OperatorKeyword, SyntaxKind.OptionKeyword, SyntaxKind.OptionalKeyword, SyntaxKind.OrKeyword, SyntaxKind.OrElseKeyword, SyntaxKind.OverloadsKeyword, SyntaxKind.OverridableKeyword, SyntaxKind.OverridesKeyword, SyntaxKind.ParamArrayKeyword, SyntaxKind.PartialKeyword, SyntaxKind.PrivateKeyword, SyntaxKind.PropertyKeyword, SyntaxKind.ProtectedKeyword, SyntaxKind.PublicKeyword, SyntaxKind.RaiseEventKeyword, SyntaxKind.ReadOnlyKeyword, SyntaxKind.ReDimKeyword, SyntaxKind.REMKeyword, SyntaxKind.RemoveHandlerKeyword, SyntaxKind.ResumeKeyword, SyntaxKind.ReturnKeyword, SyntaxKind.SByteKeyword, SyntaxKind.SelectKeyword, SyntaxKind.SetKeyword, SyntaxKind.ShadowsKeyword, SyntaxKind.SharedKeyword, SyntaxKind.ShortKeyword, SyntaxKind.SingleKeyword, SyntaxKind.StaticKeyword, SyntaxKind.StepKeyword, SyntaxKind.StopKeyword, SyntaxKind.StringKeyword, SyntaxKind.StructureKeyword, SyntaxKind.SubKeyword, SyntaxKind.SyncLockKeyword, SyntaxKind.ThenKeyword, SyntaxKind.ThrowKeyword, SyntaxKind.ToKeyword, SyntaxKind.TrueKeyword, SyntaxKind.TryKeyword, SyntaxKind.TryCastKeyword, SyntaxKind.TypeOfKeyword, SyntaxKind.UIntegerKeyword, SyntaxKind.ULongKeyword, SyntaxKind.UShortKeyword, SyntaxKind.UsingKeyword, SyntaxKind.WhenKeyword, SyntaxKind.WhileKeyword, SyntaxKind.WideningKeyword, SyntaxKind.WithKeyword, SyntaxKind.WithEventsKeyword, SyntaxKind.WriteOnlyKeyword, SyntaxKind.XorKeyword, SyntaxKind.EndIfKeyword, SyntaxKind.GosubKeyword, SyntaxKind.VariantKeyword, SyntaxKind.WendKeyword, SyntaxKind.AggregateKeyword, SyntaxKind.AllKeyword, SyntaxKind.AnsiKeyword, SyntaxKind.AscendingKeyword, SyntaxKind.AssemblyKeyword, SyntaxKind.AutoKeyword, SyntaxKind.BinaryKeyword, SyntaxKind.ByKeyword, SyntaxKind.CompareKeyword, SyntaxKind.CustomKeyword, SyntaxKind.DescendingKeyword, SyntaxKind.DistinctKeyword, SyntaxKind.EqualsKeyword, SyntaxKind.ExplicitKeyword, SyntaxKind.ExternalSourceKeyword, SyntaxKind.ExternalChecksumKeyword, SyntaxKind.FromKeyword, SyntaxKind.GroupKeyword, SyntaxKind.InferKeyword, SyntaxKind.IntoKeyword, SyntaxKind.IsFalseKeyword, SyntaxKind.IsTrueKeyword, SyntaxKind.JoinKeyword, SyntaxKind.KeyKeyword, SyntaxKind.MidKeyword, SyntaxKind.OffKeyword, SyntaxKind.OrderKeyword, SyntaxKind.OutKeyword, SyntaxKind.PreserveKeyword, SyntaxKind.RegionKeyword, SyntaxKind.SkipKeyword, SyntaxKind.StrictKeyword, SyntaxKind.TakeKeyword, SyntaxKind.TextKeyword, SyntaxKind.UnicodeKeyword, SyntaxKind.UntilKeyword, SyntaxKind.WhereKeyword, SyntaxKind.TypeKeyword, SyntaxKind.XmlKeyword} Assert.True(SyntaxFacts.IsKeywordKind(item)) Next Assert.False(SyntaxFacts.IsKeywordKind(SyntaxKind.MinusEqualsToken)) Assert.False(SyntaxFacts.IsKeywordKind(SyntaxKind.None)) End Sub <Fact> Public Sub IsLabelStatementLabelToken() For Each item As SyntaxKind In {SyntaxKind.IdentifierToken, SyntaxKind.IntegerLiteralToken} Assert.True(SyntaxFacts.IsLabelStatementLabelToken(item)) Next Assert.False(SyntaxFacts.IsLabelStatementLabelToken(SyntaxKind.WithKeyword)) Assert.False(SyntaxFacts.IsLabelStatementLabelToken(SyntaxKind.None)) End Sub <Fact> Public Sub IsLambdaHeader() For Each item As SyntaxKind In {SyntaxKind.SubLambdaHeader, SyntaxKind.FunctionLambdaHeader} Assert.True(SyntaxFacts.IsLambdaHeader(item)) Next Assert.False(SyntaxFacts.IsLambdaHeader(SyntaxKind.ExitKeyword)) Assert.False(SyntaxFacts.IsLambdaHeader(SyntaxKind.None)) End Sub <Fact> Public Sub IsLambdaHeaderKeyword() For Each item As SyntaxKind In {SyntaxKind.SubKeyword, SyntaxKind.FunctionKeyword} Assert.True(SyntaxFacts.IsLambdaHeaderSubOrFunctionKeyword(item)) Next Assert.False(SyntaxFacts.IsLambdaHeaderSubOrFunctionKeyword(SyntaxKind.ExitKeyword)) Assert.False(SyntaxFacts.IsLambdaHeaderSubOrFunctionKeyword(SyntaxKind.None)) End Sub <Fact> Public Sub IsLanguagePunctuation() Assert.True(SyntaxFacts.IsLanguagePunctuation(SyntaxKind.ExclamationToken)) Assert.False(SyntaxFacts.IsLanguagePunctuation(SyntaxKind.ConstKeyword)) Assert.False(SyntaxFacts.IsLanguagePunctuation(SyntaxKind.FromKeyword)) End Sub <Fact> Public Sub IsLiteralExpression() For Each item As SyntaxKind In {SyntaxKind.CharacterLiteralExpression, SyntaxKind.TrueLiteralExpression, SyntaxKind.FalseLiteralExpression, SyntaxKind.NumericLiteralExpression, SyntaxKind.DateLiteralExpression, SyntaxKind.StringLiteralExpression, SyntaxKind.NothingLiteralExpression} Assert.True(SyntaxFacts.IsLiteralExpression(item)) Next Assert.False(SyntaxFacts.IsLiteralExpression(SyntaxKind.ExitKeyword)) Assert.False(SyntaxFacts.IsLiteralExpression(SyntaxKind.None)) End Sub <Fact> Public Sub IsMemberAccessExpression() For Each item As SyntaxKind In {SyntaxKind.SimpleMemberAccessExpression, SyntaxKind.DictionaryAccessExpression} Assert.True(SyntaxFacts.IsMemberAccessExpression(item)) Next Assert.False(SyntaxFacts.IsMemberAccessExpression(SyntaxKind.ExitKeyword)) Assert.False(SyntaxFacts.IsMemberAccessExpression(SyntaxKind.None)) End Sub <Fact> Public Sub IsMemberAccessExpressionOperatorToken() For Each item As SyntaxKind In {SyntaxKind.DotToken, SyntaxKind.ExclamationToken} Assert.True(SyntaxFacts.IsMemberAccessExpressionOperatorToken(item)) Next Assert.False(SyntaxFacts.IsMemberAccessExpressionOperatorToken(SyntaxKind.ExitKeyword)) Assert.False(SyntaxFacts.IsMemberAccessExpressionOperatorToken(SyntaxKind.None)) End Sub <Fact> Public Sub IsmethodBlock() For Each item As SyntaxKind In {SyntaxKind.SubBlock, SyntaxKind.FunctionBlock} Assert.True(SyntaxFacts.IsMethodBlock(item)) Next For Each item As SyntaxKind In {SyntaxKind.ConstructorBlock, SyntaxKind.OperatorBlock, SyntaxKind.GetAccessorBlock, SyntaxKind.SetAccessorBlock, SyntaxKind.AddHandlerAccessorBlock, SyntaxKind.RemoveHandlerAccessorBlock, SyntaxKind.RaiseEventAccessorBlock} Assert.False(SyntaxFacts.IsMethodBlock(item)) Next For Each item As SyntaxKind In {SyntaxKind.GetAccessorBlock, SyntaxKind.SetAccessorBlock, SyntaxKind.AddHandlerAccessorBlock, SyntaxKind.RemoveHandlerAccessorBlock, SyntaxKind.RaiseEventAccessorBlock} Assert.True(SyntaxFacts.IsAccessorBlock(item)) Next For Each item As SyntaxKind In {SyntaxKind.SubBlock, SyntaxKind.FunctionBlock, SyntaxKind.ConstructorBlock, SyntaxKind.OperatorBlock} Assert.False(SyntaxFacts.IsAccessorBlock(item)) Next Assert.False(SyntaxFacts.IsMethodBlock(SyntaxKind.MultiLineIfBlock)) Assert.False(SyntaxFacts.IsMethodBlock(SyntaxKind.None)) End Sub <Fact> Public Sub IsMethodStatement() For Each item As SyntaxKind In {SyntaxKind.SubStatement, SyntaxKind.FunctionStatement} Assert.True(SyntaxFacts.IsMethodStatement(item)) Next Assert.False(SyntaxFacts.IsMethodStatement(SyntaxKind.NamespaceBlock)) Assert.False(SyntaxFacts.IsMethodStatement(SyntaxKind.None)) End Sub <Fact> Public Sub IsMethodStatementKeyword() For Each item As SyntaxKind In {SyntaxKind.SubKeyword, SyntaxKind.FunctionKeyword} Assert.True(SyntaxFacts.IsMethodStatementSubOrFunctionKeyword(item)) Next Assert.False(SyntaxFacts.IsMethodStatementSubOrFunctionKeyword(SyntaxKind.NamespaceBlock)) Assert.False(SyntaxFacts.IsMethodStatementSubOrFunctionKeyword(SyntaxKind.None)) End Sub <Fact> Public Sub IsMultiLineLambdaExpression() For Each item As SyntaxKind In {SyntaxKind.SingleLineFunctionLambdaExpression, SyntaxKind.SingleLineSubLambdaExpression} Assert.False(SyntaxFacts.IsMultiLineLambdaExpression(item)) Next For Each item As SyntaxKind In {SyntaxKind.MultiLineFunctionLambdaExpression, SyntaxKind.MultiLineSubLambdaExpression} Assert.True(SyntaxFacts.IsMultiLineLambdaExpression(item)) Next Assert.False(SyntaxFacts.IsMultiLineLambdaExpression(SyntaxKind.None)) End Sub <Fact> Public Sub IsName() Assert.True(SyntaxFacts.IsName(SyntaxKind.IdentifierName)) Assert.True(SyntaxFacts.IsName(SyntaxKind.GenericName)) Assert.True(SyntaxFacts.IsName(SyntaxKind.QualifiedName)) Assert.True(SyntaxFacts.IsName(SyntaxKind.GlobalName)) Assert.False(SyntaxFacts.IsName(SyntaxKind.GlobalKeyword)) Assert.False(SyntaxFacts.IsName(SyntaxKind.CommaToken)) Assert.False(SyntaxFacts.IsName(SyntaxKind.FunctionKeyword)) End Sub <Fact> Public Sub IsNamespaceDeclaration() Assert.True(SyntaxFacts.IsNamespaceMemberDeclaration(SyntaxKind.ClassStatement)) Assert.True(SyntaxFacts.IsNamespaceMemberDeclaration(SyntaxKind.InterfaceStatement)) Assert.True(SyntaxFacts.IsNamespaceMemberDeclaration(SyntaxKind.StructureStatement)) Assert.True(SyntaxFacts.IsNamespaceMemberDeclaration(SyntaxKind.EnumStatement)) Assert.True(SyntaxFacts.IsNamespaceMemberDeclaration(SyntaxKind.ModuleStatement)) Assert.True(SyntaxFacts.IsNamespaceMemberDeclaration(SyntaxKind.NamespaceStatement)) Assert.True(SyntaxFacts.IsNamespaceMemberDeclaration(SyntaxKind.DelegateFunctionStatement)) Assert.True(SyntaxFacts.IsNamespaceMemberDeclaration(SyntaxKind.DelegateSubStatement)) Assert.False(SyntaxFacts.IsName(SyntaxKind.FunctionStatement)) Assert.False(SyntaxFacts.IsName(SyntaxKind.SubStatement)) End Sub <Fact> Public Sub IsOnErrorGoToStatement() For Each item As SyntaxKind In {SyntaxKind.OnErrorGoToZeroStatement, SyntaxKind.OnErrorGoToMinusOneStatement, SyntaxKind.OnErrorGoToLabelStatement} Assert.True(SyntaxFacts.IsOnErrorGoToStatement(item)) Next Assert.False(SyntaxFacts.IsOnErrorGoToStatement(SyntaxKind.ExitKeyword)) Assert.False(SyntaxFacts.IsOnErrorGoToStatement(SyntaxKind.None)) End Sub <Fact> Public Sub IsOperator() Assert.True(SyntaxFacts.IsOperator(SyntaxKind.AndKeyword)) Assert.False(SyntaxFacts.IsOperator(SyntaxKind.ForKeyword)) End Sub <Fact> Public Sub IsOperatorStatementOperator() For Each item As SyntaxKind In {SyntaxKind.CTypeKeyword, SyntaxKind.IsTrueKeyword, SyntaxKind.IsFalseKeyword, SyntaxKind.NotKeyword, SyntaxKind.PlusToken, SyntaxKind.MinusToken, SyntaxKind.AsteriskToken, SyntaxKind.SlashToken, SyntaxKind.CaretToken, SyntaxKind.BackslashToken, SyntaxKind.AmpersandToken, SyntaxKind.LessThanLessThanToken, SyntaxKind.GreaterThanGreaterThanToken, SyntaxKind.ModKeyword, SyntaxKind.OrKeyword, SyntaxKind.XorKeyword, SyntaxKind.AndKeyword, SyntaxKind.LikeKeyword, SyntaxKind.EqualsToken, SyntaxKind.LessThanGreaterThanToken, SyntaxKind.LessThanToken, SyntaxKind.LessThanEqualsToken, SyntaxKind.GreaterThanEqualsToken, SyntaxKind.GreaterThanToken} Assert.True(SyntaxFacts.IsOperatorStatementOperatorToken(item)) Next Assert.False(SyntaxFacts.IsOperatorStatementOperatorToken(SyntaxKind.SubKeyword)) Assert.False(SyntaxFacts.IsOperatorStatementOperatorToken(SyntaxKind.None)) End Sub <Fact> Public Sub IsOptionStatementNameKeyword() For Each item As SyntaxKind In {SyntaxKind.ExplicitKeyword, SyntaxKind.StrictKeyword, SyntaxKind.CompareKeyword, SyntaxKind.InferKeyword} Assert.True(SyntaxFacts.IsOptionStatementNameKeyword(item)) Next Assert.False(SyntaxFacts.IsOptionStatementNameKeyword(SyntaxKind.AddHandlerStatement)) Assert.False(SyntaxFacts.IsOptionStatementNameKeyword(SyntaxKind.None)) End Sub <Fact> Public Sub IsOrdering() For Each item As SyntaxKind In {SyntaxKind.AscendingOrdering, SyntaxKind.DescendingOrdering} Assert.True(SyntaxFacts.IsOrdering(item)) Next Assert.False(SyntaxFacts.IsOrdering(SyntaxKind.ExitKeyword)) Assert.False(SyntaxFacts.IsOrdering(SyntaxKind.None)) End Sub <Fact> Public Sub IsOrderingAscendingOrDescendingKeyword() For Each item As SyntaxKind In {SyntaxKind.AscendingKeyword, SyntaxKind.DescendingKeyword} Assert.True(SyntaxFacts.IsOrderingAscendingOrDescendingKeyword(item)) Next Assert.False(SyntaxFacts.IsOrderingAscendingOrDescendingKeyword(SyntaxKind.ExitKeyword)) Assert.False(SyntaxFacts.IsOrderingAscendingOrDescendingKeyword(SyntaxKind.None)) End Sub <Fact> Public Sub IsPartitionClause() For Each item As SyntaxKind In {SyntaxKind.SkipClause, SyntaxKind.TakeClause} Assert.True(SyntaxFacts.IsPartitionClause(item)) Next Assert.False(SyntaxFacts.IsPartitionClause(SyntaxKind.ExitKeyword)) Assert.False(SyntaxFacts.IsPartitionClause(SyntaxKind.None)) End Sub <Fact> Public Sub IsPartitionClauseSkipOrTakeKeyword() For Each item As SyntaxKind In {SyntaxKind.SkipKeyword, SyntaxKind.TakeKeyword} Assert.True(SyntaxFacts.IsPartitionClauseSkipOrTakeKeyword(item)) Next Assert.False(SyntaxFacts.IsPartitionClauseSkipOrTakeKeyword(SyntaxKind.ExitKeyword)) Assert.False(SyntaxFacts.IsPartitionClauseSkipOrTakeKeyword(SyntaxKind.None)) End Sub <Fact> Public Sub IsPartitionWhileClause() For Each item As SyntaxKind In {SyntaxKind.SkipWhileClause, SyntaxKind.TakeWhileClause} Assert.True(SyntaxFacts.IsPartitionWhileClause(item)) Next Assert.False(SyntaxFacts.IsPartitionWhileClause(SyntaxKind.ExitKeyword)) Assert.False(SyntaxFacts.IsPartitionWhileClause(SyntaxKind.None)) End Sub <Fact> Public Sub IsPartitionWhileClauseSkipOrTakeKeyword() For Each item As SyntaxKind In {SyntaxKind.SkipKeyword, SyntaxKind.TakeKeyword} Assert.True(SyntaxFacts.IsPartitionWhileClauseSkipOrTakeKeyword(item)) Next Assert.False(SyntaxFacts.IsPartitionWhileClauseSkipOrTakeKeyword(SyntaxKind.ExitKeyword)) Assert.False(SyntaxFacts.IsPartitionWhileClauseSkipOrTakeKeyword(SyntaxKind.None)) End Sub <Fact> Public Sub IsPredefinedCastExpressionKeyword() For Each item As SyntaxKind In {SyntaxKind.CObjKeyword, SyntaxKind.CBoolKeyword, SyntaxKind.CDateKeyword, SyntaxKind.CCharKeyword, SyntaxKind.CStrKeyword, SyntaxKind.CDecKeyword, SyntaxKind.CByteKeyword, SyntaxKind.CSByteKeyword, SyntaxKind.CUShortKeyword, SyntaxKind.CShortKeyword, SyntaxKind.CUIntKeyword, SyntaxKind.CIntKeyword, SyntaxKind.CULngKeyword, SyntaxKind.CLngKeyword, SyntaxKind.CSngKeyword, SyntaxKind.CDblKeyword} Assert.True(SyntaxFacts.IsPredefinedCastExpressionKeyword(item)) Next Assert.False(SyntaxFacts.IsPredefinedCastExpressionKeyword(SyntaxKind.MinusToken)) Assert.False(SyntaxFacts.IsPredefinedCastExpressionKeyword(SyntaxKind.None)) End Sub <Fact> Public Sub IsPredefinedType() Assert.True(SyntaxFacts.IsPredefinedType(SyntaxKind.IntegerKeyword)) Assert.True(SyntaxFacts.IsPredefinedType(SyntaxKind.ObjectKeyword)) Assert.False(SyntaxFacts.IsPredefinedType(SyntaxKind.NothingKeyword)) End Sub <Fact> Public Sub IsPreprocessorDirective() Assert.True(SyntaxFacts.IsPreprocessorDirective(SyntaxKind.IfDirectiveTrivia)) Assert.False(SyntaxFacts.IsPreprocessorDirective(SyntaxKind.IfKeyword)) End Sub <Fact> Public Sub IsPreProcessorKeyword() Assert.True(SyntaxFacts.IsPreprocessorKeyword(SyntaxKind.ExternalSourceKeyword)) Assert.True(SyntaxFacts.IsPreprocessorKeyword(SyntaxKind.EnableKeyword)) Assert.True(SyntaxFacts.IsPreprocessorKeyword(SyntaxKind.DisableKeyword)) Assert.True(SyntaxFacts.IsPreprocessorKeyword(SyntaxKind.IfKeyword)) Assert.False(SyntaxFacts.IsPreprocessorKeyword(SyntaxKind.FromKeyword)) End Sub <Fact> Public Sub IsPreProcessorPunctuation() Assert.True(SyntaxFacts.IsPreprocessorPunctuation(SyntaxKind.HashToken)) Assert.False(SyntaxFacts.IsPreprocessorPunctuation(SyntaxKind.DotToken)) Assert.False(SyntaxFacts.IsPreprocessorPunctuation(SyntaxKind.AmpersandToken)) End Sub <Fact> Public Sub IsPunctuation() For Each item As SyntaxKind In {SyntaxKind.ExclamationToken, SyntaxKind.AtToken, SyntaxKind.CommaToken, SyntaxKind.HashToken, SyntaxKind.AmpersandToken, SyntaxKind.SingleQuoteToken, SyntaxKind.OpenParenToken, SyntaxKind.CloseParenToken, SyntaxKind.OpenBraceToken, SyntaxKind.CloseBraceToken, SyntaxKind.SemicolonToken, SyntaxKind.AsteriskToken, SyntaxKind.PlusToken, SyntaxKind.MinusToken, SyntaxKind.DotToken, SyntaxKind.SlashToken, SyntaxKind.ColonToken, SyntaxKind.LessThanToken, SyntaxKind.LessThanEqualsToken, SyntaxKind.LessThanGreaterThanToken, SyntaxKind.EqualsToken, SyntaxKind.GreaterThanToken, SyntaxKind.GreaterThanEqualsToken, SyntaxKind.BackslashToken, SyntaxKind.CaretToken, SyntaxKind.ColonEqualsToken, SyntaxKind.AmpersandEqualsToken, SyntaxKind.AsteriskEqualsToken, SyntaxKind.PlusEqualsToken, SyntaxKind.MinusEqualsToken, SyntaxKind.SlashEqualsToken, SyntaxKind.BackslashEqualsToken, SyntaxKind.CaretEqualsToken, SyntaxKind.LessThanLessThanToken, SyntaxKind.GreaterThanGreaterThanToken, SyntaxKind.LessThanLessThanEqualsToken, SyntaxKind.GreaterThanGreaterThanEqualsToken, SyntaxKind.QuestionToken, SyntaxKind.DoubleQuoteToken, SyntaxKind.StatementTerminatorToken, SyntaxKind.EndOfFileToken, SyntaxKind.EmptyToken, SyntaxKind.SlashGreaterThanToken, SyntaxKind.LessThanSlashToken, SyntaxKind.LessThanExclamationMinusMinusToken, SyntaxKind.MinusMinusGreaterThanToken, SyntaxKind.LessThanQuestionToken, SyntaxKind.QuestionGreaterThanToken, SyntaxKind.LessThanPercentEqualsToken, SyntaxKind.PercentGreaterThanToken, SyntaxKind.BeginCDataToken, SyntaxKind.EndCDataToken, SyntaxKind.EndOfXmlToken, SyntaxKind.DollarSignDoubleQuoteToken, SyntaxKind.EndOfInterpolatedStringToken} Assert.True(SyntaxFacts.IsPunctuation(item)) Next Assert.False(SyntaxFacts.IsPunctuation(SyntaxKind.ExitKeyword)) Assert.False(SyntaxFacts.IsPunctuation(SyntaxKind.None)) End Sub <Fact> Public Sub IsPunctuationOrKeyword() Assert.True(SyntaxFacts.IsPunctuationOrKeyword(SyntaxKind.AddHandlerKeyword)) Assert.True(SyntaxFacts.IsPunctuationOrKeyword(SyntaxKind.EndOfXmlToken)) Assert.True(SyntaxFacts.IsPunctuationOrKeyword(SyntaxKind.DollarSignDoubleQuoteToken)) Assert.True(SyntaxFacts.IsPunctuationOrKeyword(SyntaxKind.EndOfInterpolatedStringToken)) Assert.False(SyntaxFacts.IsPunctuationOrKeyword(SyntaxKind.XmlNameToken)) Assert.False(SyntaxFacts.IsPunctuationOrKeyword(SyntaxKind.ImportAliasClause)) Assert.False(SyntaxFacts.IsPunctuationOrKeyword(SyntaxKind.ForStatement)) End Sub <Fact> Public Sub IsReDimStatement() For Each item As SyntaxKind In {SyntaxKind.ReDimStatement, SyntaxKind.ReDimPreserveStatement} Assert.True(SyntaxFacts.IsReDimStatement(item)) Next Assert.False(SyntaxFacts.IsReDimStatement(SyntaxKind.SimpleAssignmentStatement)) Assert.False(SyntaxFacts.IsReDimStatement(SyntaxKind.None)) End Sub <Fact> Public Sub IsRelationalOperator() Assert.True(SyntaxFacts.IsRelationalOperator(SyntaxKind.LessThanToken)) Assert.False(SyntaxFacts.IsRelationalOperator(SyntaxKind.DotToken)) End Sub <Fact> Public Sub IsReservedKeyword1() Dim VB1 As New SyntaxToken Assert.False(VB1.IsReservedKeyword()) Assert.True(SyntaxFacts.IsReservedKeyword(SyntaxKind.AddHandlerKeyword)) End Sub <Fact> Public Sub IsResumeStatement() For Each item As SyntaxKind In {SyntaxKind.ResumeStatement, SyntaxKind.ResumeLabelStatement, SyntaxKind.ResumeNextStatement} Assert.True(SyntaxFacts.IsResumeStatement(item)) Next Assert.False(SyntaxFacts.IsResumeStatement(SyntaxKind.ExitKeyword)) Assert.False(SyntaxFacts.IsResumeStatement(SyntaxKind.None)) End Sub <Fact> Public Sub IsSingleLineLambdaExpression() For Each item As SyntaxKind In {SyntaxKind.SingleLineFunctionLambdaExpression, SyntaxKind.SingleLineSubLambdaExpression} Assert.True(SyntaxFacts.IsSingleLineLambdaExpression(item)) Next Assert.False(SyntaxFacts.IsSingleLineLambdaExpression(SyntaxKind.MinusToken)) Assert.False(SyntaxFacts.IsSingleLineLambdaExpression(SyntaxKind.None)) End Sub <Fact> Public Sub IsSpecialConstraint() For Each item As SyntaxKind In {SyntaxKind.NewConstraint, SyntaxKind.ClassConstraint, SyntaxKind.StructureConstraint} Assert.True(SyntaxFacts.IsSpecialConstraint(item)) Next Assert.False(SyntaxFacts.IsSpecialConstraint(SyntaxKind.ConstDirectiveTrivia)) Assert.False(SyntaxFacts.IsSpecialConstraint(SyntaxKind.None)) End Sub <Fact> Public Sub IsSpecialConstraintKeyword() For Each item As SyntaxKind In {SyntaxKind.NewKeyword, SyntaxKind.ClassKeyword, SyntaxKind.StructureKeyword} Assert.True(SyntaxFacts.IsSpecialConstraintConstraintKeyword(item)) Next Assert.False(SyntaxFacts.IsSpecialConstraintConstraintKeyword(SyntaxKind.ModuleKeyword)) Assert.False(SyntaxFacts.IsSpecialConstraintConstraintKeyword(SyntaxKind.None)) End Sub <Fact> Public Sub IsStopOrEndStatement() For Each item As SyntaxKind In {SyntaxKind.StopStatement, SyntaxKind.EndStatement} Assert.True(SyntaxFacts.IsStopOrEndStatement(item)) Next Assert.False(SyntaxFacts.IsStopOrEndStatement(SyntaxKind.WithKeyword)) Assert.False(SyntaxFacts.IsStopOrEndStatement(SyntaxKind.None)) End Sub <Fact> Public Sub IsStopOrEndStatementStopOrEndKeyword() For Each item As SyntaxKind In {SyntaxKind.StopKeyword, SyntaxKind.EndKeyword} Assert.True(SyntaxFacts.IsStopOrEndStatementStopOrEndKeyword(item)) Next Assert.False(SyntaxFacts.IsStopOrEndStatementStopOrEndKeyword(SyntaxKind.WithKeyword)) Assert.False(SyntaxFacts.IsStopOrEndStatementStopOrEndKeyword(SyntaxKind.None)) End Sub <Fact> Public Sub IsToken() Assert.True(SyntaxFacts.IsAnyToken(SyntaxKind.AddHandlerKeyword)) Assert.True(SyntaxFacts.IsAnyToken(SyntaxKind.CharacterLiteralToken)) Assert.False(SyntaxFacts.IsAnyToken(SyntaxKind.GlobalName)) Assert.False(SyntaxFacts.IsAnyToken(SyntaxKind.DocumentationCommentTrivia)) End Sub <Fact> Public Sub IsTrivia() Assert.True(SyntaxFacts.IsTrivia(SyntaxKind.WhitespaceTrivia)) Assert.False(SyntaxFacts.IsTrivia(SyntaxKind.REMKeyword)) End Sub <Fact> Public Sub IsTypeOfExpression() For Each item As SyntaxKind In {SyntaxKind.TypeOfIsExpression, SyntaxKind.TypeOfIsNotExpression} Assert.True(SyntaxFacts.IsTypeOfExpression(item)) Next Assert.False(SyntaxFacts.IsTypeOfExpression(SyntaxKind.ExitKeyword)) Assert.False(SyntaxFacts.IsTypeOfExpression(SyntaxKind.None)) End Sub <Fact> Public Sub IsTypeOfExpressionOperatorToken() For Each item As SyntaxKind In {SyntaxKind.IsKeyword, SyntaxKind.IsNotKeyword} Assert.True(SyntaxFacts.IsTypeOfExpressionOperatorToken(item)) Next Assert.False(SyntaxFacts.IsTypeOfExpressionOperatorToken(SyntaxKind.ExitKeyword)) Assert.False(SyntaxFacts.IsTypeOfExpressionOperatorToken(SyntaxKind.None)) End Sub <Fact> Public Sub IsTypeParameterVarianceKeyword() For Each item As SyntaxKind In {SyntaxKind.InKeyword, SyntaxKind.OutKeyword} Assert.True(SyntaxFacts.IsTypeParameterVarianceKeyword(item)) Next Assert.False(SyntaxFacts.IsTypeParameterVarianceKeyword(SyntaxKind.GetKeyword)) Assert.False(SyntaxFacts.IsTypeParameterVarianceKeyword(SyntaxKind.None)) End Sub <Fact> Public Sub IsUnaryExpression() For Each item As SyntaxKind In {SyntaxKind.UnaryPlusExpression, SyntaxKind.UnaryMinusExpression, SyntaxKind.NotExpression, SyntaxKind.AddressOfExpression} Assert.True(SyntaxFacts.IsUnaryExpression(item)) Next Assert.False(SyntaxFacts.IsUnaryExpression(SyntaxKind.MinusToken)) Assert.False(SyntaxFacts.IsUnaryExpression(SyntaxKind.None)) End Sub <Fact> Public Sub IsUnaryExpressionOperatorToken() For Each item As SyntaxKind In {SyntaxKind.PlusToken, SyntaxKind.MinusToken, SyntaxKind.NotKeyword, SyntaxKind.AddressOfKeyword} Assert.True(SyntaxFacts.IsUnaryExpressionOperatorToken(item)) Next Assert.False(SyntaxFacts.IsUnaryExpressionOperatorToken(SyntaxKind.MinusEqualsToken)) Assert.False(SyntaxFacts.IsUnaryExpressionOperatorToken(SyntaxKind.None)) End Sub <Fact> Public Sub IsWhileOrUntilClause() For Each item As SyntaxKind In {SyntaxKind.WhileClause, SyntaxKind.UntilClause} Assert.True(SyntaxFacts.IsWhileOrUntilClause(item)) Next Assert.False(SyntaxFacts.IsWhileOrUntilClause(SyntaxKind.ExitKeyword)) Assert.False(SyntaxFacts.IsWhileOrUntilClause(SyntaxKind.None)) End Sub <Fact> Public Sub IsWhileOrUntilClauseWhileOrUntilKeyword() For Each item As SyntaxKind In {SyntaxKind.WhileKeyword, SyntaxKind.UntilKeyword} Assert.True(SyntaxFacts.IsWhileOrUntilClauseWhileOrUntilKeyword(item)) Next Assert.False(SyntaxFacts.IsWhileOrUntilClauseWhileOrUntilKeyword(SyntaxKind.ExitKeyword)) Assert.False(SyntaxFacts.IsWhileOrUntilClauseWhileOrUntilKeyword(SyntaxKind.None)) End Sub <Fact> Public Sub IsXmlMemberAccessExpression() For Each item As SyntaxKind In {SyntaxKind.XmlElementAccessExpression, SyntaxKind.XmlDescendantAccessExpression, SyntaxKind.XmlAttributeAccessExpression} Assert.True(SyntaxFacts.IsXmlMemberAccessExpression(item)) Next Assert.False(SyntaxFacts.IsXmlMemberAccessExpression(SyntaxKind.ExitKeyword)) Assert.False(SyntaxFacts.IsXmlMemberAccessExpression(SyntaxKind.None)) End Sub <Fact> Public Sub IsXmlMemberAccessExpressionToken2() For Each item As SyntaxKind In {SyntaxKind.DotToken, SyntaxKind.AtToken} Assert.True(SyntaxFacts.IsXmlMemberAccessExpressionToken2(item)) Next Assert.False(SyntaxFacts.IsXmlMemberAccessExpressionToken2(SyntaxKind.MinusToken)) Assert.False(SyntaxFacts.IsXmlMemberAccessExpressionToken2(SyntaxKind.None)) End Sub <Fact> Public Sub IsXmlStringEndQuoteToken() For Each item As SyntaxKind In {SyntaxKind.DoubleQuoteToken, SyntaxKind.SingleQuoteToken} Assert.True(SyntaxFacts.IsXmlStringEndQuoteToken(item)) Next Assert.False(SyntaxFacts.IsXmlStringEndQuoteToken(SyntaxKind.ExitKeyword)) Assert.False(SyntaxFacts.IsXmlStringEndQuoteToken(SyntaxKind.None)) End Sub <Fact> Public Sub IsXmlStringStartQuoteToken() For Each item As SyntaxKind In {SyntaxKind.DoubleQuoteToken, SyntaxKind.SingleQuoteToken} Assert.True(SyntaxFacts.IsXmlStringStartQuoteToken(item)) Next Assert.False(SyntaxFacts.IsXmlStringStartQuoteToken(SyntaxKind.ExitKeyword)) Assert.False(SyntaxFacts.IsXmlStringStartQuoteToken(SyntaxKind.None)) End Sub <Fact> Public Sub IsXmlTextToken() For Each item As SyntaxKind In {SyntaxKind.XmlTextLiteralToken, SyntaxKind.XmlEntityLiteralToken, SyntaxKind.DocumentationCommentLineBreakToken} Assert.True(SyntaxFacts.IsXmlTextToken(item)) Next Assert.False(SyntaxFacts.IsXmlTextToken(SyntaxKind.ExitKeyword)) Assert.False(SyntaxFacts.IsXmlTextToken(SyntaxKind.None)) End Sub <Fact> Public Sub VarianceKindFromToken() Dim keywordToken As SyntaxToken = SyntaxFactory.Token(SyntaxKind.InKeyword, text:=Nothing) Assert.Equal(VarianceKind.In, SyntaxFacts.VarianceKindFromToken(keywordToken)) keywordToken = SyntaxFactory.Token(SyntaxKind.OutKeyword, text:=Nothing) Assert.Equal(VarianceKind.Out, SyntaxFacts.VarianceKindFromToken(keywordToken)) keywordToken = SyntaxFactory.Token(SyntaxKind.FriendKeyword, text:=Nothing) Assert.Equal(VarianceKind.None, SyntaxFacts.VarianceKindFromToken(keywordToken)) End Sub <ConditionalFact(GetType(DesktopClrOnly))> <WorkItem(10841, "https://github.com/mono/mono/issues/10841")> Public Sub AllowsLeadingOrTrailingImplicitLineContinuation() Dim cu = SyntaxFactory.ParseCompilationUnit(s_allInOneSource) Assert.False(cu.ContainsDiagnostics, "Baseline has diagnostics.") Dim tokens = cu.DescendantTokens(descendIntoTrivia:=False) Dim builder As New System.Text.StringBuilder(cu.FullSpan.Length * 2) Const explicitLineContinuation = " _" & vbCrLf ' For every token in the file ' If there is explicit continuation that can be removed, remove it ' If there is implicit continuation, assert that it's allowed ' Otherwise if there is no continuation, add an explicit line continuation Using enumerator = tokens.GetEnumerator() If Not enumerator.MoveNext() Then Return Dim currentToken = enumerator.Current Dim nextToken = enumerator.Current Do While enumerator.MoveNext() currentToken = nextToken nextToken = enumerator.Current If currentToken = currentToken.Parent.AncestorsAndSelf.OfType(Of StatementSyntax).First.GetLastToken() OrElse nextToken.Kind = SyntaxKind.EndOfFileToken Then builder.Append(currentToken.ToFullString()) Continue Do End If If currentToken.HasLeadingTrivia Then For Each trivia In currentToken.LeadingTrivia builder.Append(trivia.ToFullString()) Next End If builder.Append(currentToken.ToString()) If currentToken.HasTrailingTrivia Then Dim hasContinuation = False For Each trivia In currentToken.TrailingTrivia If trivia.Kind = SyntaxKind.LineContinuationTrivia Then If SyntaxFacts.AllowsTrailingImplicitLineContinuation(currentToken) OrElse SyntaxFacts.AllowsLeadingImplicitLineContinuation(nextToken) Then builder.Append(vbCrLf) Else builder.Append(trivia.ToFullString()) End If hasContinuation = True ElseIf trivia.Kind = SyntaxKind.EndOfLineTrivia Then If Not hasContinuation Then hasContinuation = True builder.Append(trivia.ToFullString()) End If Else builder.Append(trivia.ToFullString()) End If Next If Not hasContinuation AndAlso currentToken <> currentToken.Parent.AncestorsAndSelf.OfType(Of StatementSyntax).First.GetLastToken() AndAlso nextToken.Kind <> SyntaxKind.EndOfFileToken Then If SyntaxFacts.AllowsTrailingImplicitLineContinuation(currentToken) OrElse SyntaxFacts.AllowsLeadingImplicitLineContinuation(nextToken) Then builder.Append(vbCrLf) ' These tokens appear in XML literals, explicit line continuation is illegal in these contexts. ElseIf currentToken.Kind <> SyntaxKind.XmlKeyword AndAlso currentToken.Kind <> SyntaxKind.XmlNameToken AndAlso currentToken.Kind <> SyntaxKind.DoubleQuoteToken AndAlso currentToken.Kind <> SyntaxKind.XmlTextLiteralToken Then builder.Append(explicitLineContinuation) End If End If End If Loop End Using cu = SyntaxFactory.ParseCompilationUnit(builder.ToString()) Assert.False(cu.ContainsDiagnostics, "Transformed tree has diagnostics.") End Sub <ConditionalFact(GetType(DesktopClrOnly))> <WorkItem(10841, "https://github.com/mono/mono/issues/10841")> Public Sub AllowsLeadingOrTrailingImplicitLineContinuationNegativeTests() Dim cu = SyntaxFactory.ParseCompilationUnit(s_allInOneSource) Assert.False(cu.ContainsDiagnostics, "Baseline has diagnostics.") Dim tokens = cu.DescendantTokens(descendIntoTrivia:=False) Dim checked As New HashSet(Of Tuple(Of SyntaxKind, SyntaxKind)) ' For every token in the file ' If implicit line continuation is not allowed after it or before the next token add one and ' verify a parse error is reported. Using enumerator = tokens.GetEnumerator() If Not enumerator.MoveNext() Then Return Dim currentToken = enumerator.Current Dim nextToken = enumerator.Current Do While enumerator.MoveNext() currentToken = nextToken nextToken = enumerator.Current ' Tokens for which adding trailing newline does nothing or ' creates a new text which could parse differently but valid code. If currentToken.TrailingTrivia.Any(Function(t) Return t.Kind = SyntaxKind.ColonTrivia OrElse t.Kind = SyntaxKind.EndOfLineTrivia End Function) OrElse currentToken.Kind = SyntaxKind.ColonToken OrElse currentToken.Kind = SyntaxKind.NextKeyword OrElse nextToken.Kind = SyntaxKind.DotToken OrElse nextToken.Kind = SyntaxKind.ColonToken OrElse nextToken.Kind = SyntaxKind.EndOfFileToken Then Continue Do End If Dim kindAndParentKind = Tuple.Create(currentToken.Kind(), currentToken.Parent.Kind()) If checked.Contains(kindAndParentKind) Then Continue Do If Not (SyntaxFacts.AllowsTrailingImplicitLineContinuation(currentToken) OrElse SyntaxFacts.AllowsLeadingImplicitLineContinuation(nextToken)) Then Dim newTrailing = Aggregate trivia In currentToken.TrailingTrivia Where trivia.Kind <> SyntaxKind.EndOfLineTrivia Into ToList() newTrailing.Add(SyntaxFactory.EndOfLineTrivia(vbCrLf)) Assert.True(SyntaxFactory.ParseCompilationUnit(cu.ReplaceToken(currentToken, currentToken.WithTrailingTrivia(newTrailing)).ToFullString()).ContainsDiagnostics, "Expected diagnostic when adding line continuation to " & currentToken.Kind.ToString() & " in " & currentToken.Parent.ToString() & ".") checked.Add(kindAndParentKind) End If Loop End Using End Sub <WorkItem(531480, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531480")> <Fact> Public Sub ImplicitLineContinuationAfterQuery() Dim tree = ParseAndVerify(<![CDATA[ Module M Sub M() If Nothing Is From c In "" Distinct Then End If If Nothing Is From c In "" Order By c Ascending Then End If If Nothing Is From c In "" Order By c Descending Then End If End Sub End Module ]]>) Dim tokens = tree.GetRoot().DescendantTokens().ToArray() Dim index = 0 For Each token In tokens If token.Kind = SyntaxKind.ThenKeyword Then Dim prevToken = tokens(index - 1) Dim nextToken = tokens(index) Assert.False(SyntaxFacts.AllowsTrailingImplicitLineContinuation(prevToken)) Assert.False(SyntaxFacts.AllowsLeadingImplicitLineContinuation(nextToken)) End If index += 1 Next End Sub <WorkItem(530665, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530665")> <Fact> Public Sub ImplicitLineContinuationAfterDictionaryAccessOperator() Dim tree = ParseAndVerify(<![CDATA[ Imports System.Collections Module Program Sub Main() Dim x As New Hashtable Dim y = x ! _ Goo End Sub End Module ]]>) Dim memberAccess = tree.GetRoot().DescendantNodes().OfType(Of MemberAccessExpressionSyntax).Single() Assert.False(SyntaxFacts.AllowsLeadingImplicitLineContinuation(memberAccess.Name.Identifier)) Assert.False(SyntaxFacts.AllowsTrailingImplicitLineContinuation(memberAccess.OperatorToken)) End Sub <WorkItem(990618, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/990618")> <Fact> Public Sub Bug990618() Dim text = SyntaxFacts.GetText(SyntaxKind.BeginCDataToken) Assert.Equal("<![CDATA[", text) End Sub <Theory> <InlineData("x", "x")> <InlineData("x.y", "y")> <InlineData("x?.y", "y")> <InlineData("Me.y", "y")> <InlineData("M()", "M")> <InlineData("x.M()", "M")> <InlineData("TypeOf(x)", Nothing)> <InlineData("GetType(x)", Nothing)> <InlineData("-x", Nothing)> <InlineData("x!y", "y")> <InlineData("Me", Nothing)> <InlineData("[Me]", "Me")> <InlineData("x.Me", "Me")> <InlineData("M()()", "M")> <InlineData("New C()", Nothing)> Public Sub TestTryGetInferredMemberName(source As String, expected As String) Dim expr = SyntaxFactory.ParseExpression(source) Dim actual = expr.TryGetInferredMemberName() Assert.Equal(expected, actual) End Sub <Theory> <InlineData("Item0", False)> <InlineData("Item1", True)> <InlineData("Item2", True)> <InlineData("Item10", True)> <InlineData("Rest", True)> <InlineData("ToString", True)> <InlineData("GetHashCode", True)> <InlineData("item1", True)> <InlineData("item01", False)> <InlineData("item10", True)> <InlineData("Alice", False)> Public Sub TestIsReservedTupleElementName(elementName As String, isReserved As Boolean) Assert.Equal(isReserved, SyntaxFacts.IsReservedTupleElementName(elementName)) End Sub End Class
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.IO Imports System.Text Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities Public Class SyntaxFactsTests Private Shared ReadOnly s_allInOneSource As String Shared Sub New() Using stream = New StreamReader(GetType(SyntaxFactsTests).Assembly.GetManifestResourceStream("AllInOne.vb"), Encoding.UTF8) s_allInOneSource = stream.ReadToEnd() End Using End Sub <Fact> Public Sub IsKeyword1() Assert.False(CType(Nothing, SyntaxToken).IsKeyword()) End Sub <Fact> Public Sub IsKeyword2() Assert.True(SyntaxFactory.Token(SyntaxKind.MyClassKeyword).IsKeyword()) End Sub <Fact> Public Sub IsKeyword3() Assert.False(SyntaxFactory.IntegerLiteralToken("1", LiteralBase.Decimal, TypeCharacter.None, 1).IsKeyword()) End Sub <Fact> Public Sub IsXmlTextToken1() Assert.False(SyntaxFacts.IsXmlTextToken(Nothing)) End Sub <Fact> Public Sub IsXmlTextToken2() Assert.True(SyntaxFacts.IsXmlTextToken(SyntaxKind.XmlTextLiteralToken)) End Sub <Fact> Public Sub IsXmlTextToken3() Assert.False(SyntaxFacts.IsXmlTextToken(SyntaxKind.AtToken)) End Sub <Fact> Public Sub Bug2644() Assert.Equal(SyntaxKind.ClassKeyword, SyntaxFacts.GetKeywordKind("Class")) Assert.Equal(SyntaxKind.None, SyntaxFacts.GetKeywordKind("Where")) End Sub <Fact> Public Sub GetAccessorStatementKind() Assert.Equal(SyntaxKind.GetAccessorStatement, SyntaxFacts.GetAccessorStatementKind(SyntaxKind.GetKeyword)) Assert.Equal(SyntaxKind.SetAccessorStatement, SyntaxFacts.GetAccessorStatementKind(SyntaxKind.SetKeyword)) Assert.Equal(SyntaxKind.RemoveHandlerStatement, SyntaxFacts.GetAccessorStatementKind(SyntaxKind.RemoveHandlerKeyword)) Assert.Equal(SyntaxKind.AddHandlerStatement, SyntaxFacts.GetAccessorStatementKind(SyntaxKind.AddHandlerKeyword)) Assert.Equal(SyntaxKind.RaiseEventAccessorStatement, SyntaxFacts.GetAccessorStatementKind(SyntaxKind.RaiseEventKeyword)) Assert.Equal(SyntaxKind.None, SyntaxFacts.GetAccessorStatementKind(SyntaxKind.AddressOfKeyword)) End Sub <Fact> Public Sub GetBaseTypeStatementKind() Assert.Equal(SyntaxKind.EnumStatement, SyntaxFacts.GetBaseTypeStatementKind(SyntaxKind.EnumKeyword)) Assert.Equal(SyntaxKind.ClassStatement, SyntaxFacts.GetBaseTypeStatementKind(SyntaxKind.ClassKeyword)) Assert.Equal(SyntaxKind.StructureStatement, SyntaxFacts.GetBaseTypeStatementKind(SyntaxKind.StructureKeyword)) Assert.Equal(SyntaxKind.InterfaceStatement, SyntaxFacts.GetBaseTypeStatementKind(SyntaxKind.InterfaceKeyword)) Assert.Equal(SyntaxKind.None, SyntaxFacts.GetBaseTypeStatementKind(SyntaxKind.ForKeyword)) End Sub <Fact> Public Sub GetBinaryExpression() For Each item As SyntaxKind In {SyntaxKind.IsKeyword, SyntaxKind.IsNotKeyword, SyntaxKind.LikeKeyword, SyntaxKind.AndKeyword, SyntaxKind.AndAlsoKeyword, SyntaxKind.OrKeyword, SyntaxKind.OrElseKeyword, SyntaxKind.XorKeyword, SyntaxKind.AmpersandToken, SyntaxKind.AsteriskToken, SyntaxKind.PlusToken, SyntaxKind.MinusToken, SyntaxKind.SlashToken, SyntaxKind.BackslashToken, SyntaxKind.ModKeyword, SyntaxKind.CaretToken, SyntaxKind.LessThanToken, SyntaxKind.LessThanEqualsToken, SyntaxKind.LessThanGreaterThanToken, SyntaxKind.EqualsToken, SyntaxKind.GreaterThanToken, SyntaxKind.GreaterThanEqualsToken, SyntaxKind.LessThanLessThanToken, SyntaxKind.GreaterThanGreaterThanToken} Assert.NotEqual(SyntaxKind.None, SyntaxFacts.GetBinaryExpression(item)) Next Assert.Equal(SyntaxKind.SubtractExpression, SyntaxFacts.GetBinaryExpression(SyntaxKind.MinusToken)) Assert.Equal(SyntaxKind.AndAlsoExpression, SyntaxFacts.GetBinaryExpression(SyntaxKind.AndAlsoKeyword)) Assert.Equal(SyntaxKind.None, SyntaxFacts.GetBinaryExpression(SyntaxKind.ForKeyword)) Assert.Equal(SyntaxKind.None, SyntaxFacts.GetBaseTypeStatementKind(SyntaxKind.ForKeyword)) End Sub <Fact> Public Sub GetBlockName() Assert.Equal("Case", SyntaxFacts.GetBlockName(SyntaxKind.CaseBlock)) Assert.Equal("Do Loop", SyntaxFacts.GetBlockName(SyntaxKind.SimpleDoLoopBlock)) Assert.Equal("Do Loop", SyntaxFacts.GetBlockName(SyntaxKind.DoWhileLoopBlock)) Assert.Equal("Do Loop", SyntaxFacts.GetBlockName(SyntaxKind.DoUntilLoopBlock)) Assert.Equal("Do Loop", SyntaxFacts.GetBlockName(SyntaxKind.DoLoopWhileBlock)) Assert.Equal("Do Loop", SyntaxFacts.GetBlockName(SyntaxKind.DoLoopUntilBlock)) Assert.Equal("While", SyntaxFacts.GetBlockName(SyntaxKind.WhileBlock)) Assert.Equal("With", SyntaxFacts.GetBlockName(SyntaxKind.WithBlock)) Assert.Equal("SyncLock", SyntaxFacts.GetBlockName(SyntaxKind.SyncLockBlock)) Assert.Equal("Using", SyntaxFacts.GetBlockName(SyntaxKind.UsingBlock)) Assert.Equal("For", SyntaxFacts.GetBlockName(SyntaxKind.ForBlock)) Assert.Equal("For Each", SyntaxFacts.GetBlockName(SyntaxKind.ForEachBlock)) Assert.Equal("Select", SyntaxFacts.GetBlockName(SyntaxKind.SelectBlock)) Assert.Equal("If", SyntaxFacts.GetBlockName(SyntaxKind.MultiLineIfBlock)) Assert.Equal("Else If", SyntaxFacts.GetBlockName(SyntaxKind.ElseIfBlock)) Assert.Equal("Else", SyntaxFacts.GetBlockName(SyntaxKind.ElseBlock)) Assert.Equal("Try", SyntaxFacts.GetBlockName(SyntaxKind.TryBlock)) Assert.Equal("Catch", SyntaxFacts.GetBlockName(SyntaxKind.CatchBlock)) Assert.Equal("Finally", SyntaxFacts.GetBlockName(SyntaxKind.FinallyBlock)) End Sub <Fact> Public Sub GetContextualKeywordKind() Assert.Equal(SyntaxKind.MidKeyword, SyntaxFacts.GetContextualKeywordKind("mid")) Assert.Equal(SyntaxKind.FromKeyword, SyntaxFacts.GetContextualKeywordKind("from")) Assert.Equal(SyntaxKind.None, SyntaxFacts.GetContextualKeywordKind(String.Empty)) Assert.Equal(SyntaxKind.None, SyntaxFacts.GetBaseTypeStatementKind(SyntaxKind.ForKeyword)) Dim expected = New String() {"aggregate", "all", "ansi", "ascending", "assembly", "async", "auto", "await", "binary", "by", "compare", "custom", "descending", "distinct", "equals", "explicit", "externalsource", "externalchecksum", "from", "group", "infer", "into", "isfalse", "istrue", "iterator", "join", "key", "mid", "off", "order", "out", "preserve", "r", "region", "skip", "strict", "take", "text", "unicode", "until", "where", "type", "xml", "yield", "enable", "disable", "warning"} For Each item In expected Assert.NotEqual(SyntaxKind.None, SyntaxFacts.GetContextualKeywordKind(item)) Next Dim actualCount = SyntaxFacts.GetContextualKeywordKinds.Count Assert.Equal(expected.Count, actualCount) End Sub <Fact> <WorkItem(15925, "DevDiv_Projects/Roslyn")> Public Sub GetContextualKeywordsKinds() Assert.NotEqual(0, SyntaxFacts.GetContextualKeywordKinds.Count) Assert.Contains(SyntaxKind.FromKeyword, SyntaxFacts.GetContextualKeywordKinds) Assert.DoesNotContain(SyntaxKind.DimKeyword, SyntaxFacts.GetContextualKeywordKinds) Assert.DoesNotContain(SyntaxKind.StaticKeyword, SyntaxFacts.GetContextualKeywordKinds) End Sub <Fact> Public Sub GetInstanceExpression() Assert.Equal(SyntaxKind.None, SyntaxFacts.GetInstanceExpression(SyntaxKind.DeclareKeyword)) Assert.Equal(SyntaxKind.MeExpression, SyntaxFacts.GetInstanceExpression(SyntaxKind.MeKeyword)) Assert.Equal(SyntaxKind.MyBaseExpression, SyntaxFacts.GetInstanceExpression(SyntaxKind.MyBaseKeyword)) Assert.Equal(SyntaxKind.MyClassExpression, SyntaxFacts.GetInstanceExpression(SyntaxKind.MyClassKeyword)) End Sub <Fact> Public Sub GetKeywordkinds() Assert.NotEqual(0, SyntaxFacts.GetKeywordKinds.Count) Assert.Contains(SyntaxKind.CIntKeyword, SyntaxFacts.GetKeywordKinds) End Sub <Fact> Public Sub GetPreprocessorKeywordKind() Dim item As String For Each item In New String() {"if", "elseif", "else", "endif", "region", "end", "const", "externalsource", "externalchecksum", "enable", "disable"} Assert.NotEqual(SyntaxKind.None, SyntaxFacts.GetPreprocessorKeywordKind(item)) Next Assert.Equal(SyntaxKind.ExternalSourceKeyword, SyntaxFacts.GetPreprocessorKeywordKind("externalsource")) Assert.Equal(SyntaxKind.EndKeyword, SyntaxFacts.GetPreprocessorKeywordKind("end")) Assert.Equal(SyntaxKind.DisableKeyword, SyntaxFacts.GetPreprocessorKeywordKind("disable")) Assert.Equal(SyntaxKind.EnableKeyword, SyntaxFacts.GetPreprocessorKeywordKind("enable")) Assert.Equal(SyntaxKind.None, SyntaxFacts.GetPreprocessorKeywordKind(String.Empty)) Assert.Equal(SyntaxKind.None, SyntaxFacts.GetPreprocessorKeywordKind("d")) End Sub <Fact> Public Sub GetPreprocessorKeywordKinds() Assert.Contains(SyntaxKind.RegionKeyword, SyntaxFacts.GetPreprocessorKeywordKinds) Assert.Contains(SyntaxKind.EnableKeyword, SyntaxFacts.GetPreprocessorKeywordKinds) Assert.Contains(SyntaxKind.WarningKeyword, SyntaxFacts.GetPreprocessorKeywordKinds) Assert.Contains(SyntaxKind.DisableKeyword, SyntaxFacts.GetPreprocessorKeywordKinds) Assert.DoesNotContain(SyntaxKind.PublicKeyword, SyntaxFacts.GetPreprocessorKeywordKinds) End Sub <Fact> Public Sub GetPunctuationKinds() Assert.NotEqual(0, SyntaxFacts.GetPunctuationKinds.Count) Assert.Contains(SyntaxKind.ExclamationToken, SyntaxFacts.GetPunctuationKinds) Assert.Contains(SyntaxKind.EmptyToken, SyntaxFacts.GetPunctuationKinds) Assert.DoesNotContain(SyntaxKind.NumericLabel, SyntaxFacts.GetPunctuationKinds) End Sub <Fact> Public Sub GetReservedKeywordsKinds() Assert.NotEqual(0, SyntaxFacts.GetReservedKeywordKinds.Count) Assert.Contains(SyntaxKind.AddressOfKeyword, SyntaxFacts.GetReservedKeywordKinds) Assert.DoesNotContain(SyntaxKind.QualifiedName, SyntaxFacts.GetReservedKeywordKinds) End Sub <Fact> Public Sub IsAccessorStatement() For Each item As SyntaxKind In {SyntaxKind.GetAccessorStatement, SyntaxKind.SetAccessorStatement, SyntaxKind.AddHandlerAccessorStatement, SyntaxKind.RemoveHandlerAccessorStatement, SyntaxKind.RaiseEventAccessorStatement} Assert.True(SyntaxFacts.IsAccessorStatement(item)) Next Assert.False(SyntaxFacts.IsAccessorStatement(SyntaxKind.SubKeyword)) Assert.False(SyntaxFacts.IsAccessorStatement(SyntaxKind.None)) End Sub <Fact> Public Sub IsAccessorStatementKeyword() For Each item As SyntaxKind In {SyntaxKind.GetKeyword, SyntaxKind.SetKeyword, SyntaxKind.AddHandlerKeyword, SyntaxKind.RemoveHandlerKeyword, SyntaxKind.RaiseEventKeyword} Assert.True(SyntaxFacts.IsAccessorStatementAccessorKeyword(item)) Next Assert.False(SyntaxFacts.IsAccessorStatementAccessorKeyword(SyntaxKind.SubKeyword)) Assert.False(SyntaxFacts.IsAccessorStatementAccessorKeyword(SyntaxKind.None)) End Sub <Fact> Public Sub IsAddRemoveHandlerStatement() For Each item As SyntaxKind In {SyntaxKind.AddHandlerStatement, SyntaxKind.RemoveHandlerStatement} Assert.True(SyntaxFacts.IsAddRemoveHandlerStatement(item)) Next Assert.False(SyntaxFacts.IsAddRemoveHandlerStatement(SyntaxKind.ExitKeyword)) Assert.False(SyntaxFacts.IsAddRemoveHandlerStatement(SyntaxKind.None)) End Sub <Fact> Public Sub IsAddRemoveHandlerStatementAddHandlerOrRemoveHandlerKeyword() For Each item As SyntaxKind In {SyntaxKind.AddHandlerKeyword, SyntaxKind.RemoveHandlerKeyword} Assert.True(SyntaxFacts.IsAddRemoveHandlerStatementAddHandlerOrRemoveHandlerKeyword(item)) Next Assert.False(SyntaxFacts.IsAddRemoveHandlerStatementAddHandlerOrRemoveHandlerKeyword(SyntaxKind.ExitKeyword)) Assert.False(SyntaxFacts.IsAddRemoveHandlerStatementAddHandlerOrRemoveHandlerKeyword(SyntaxKind.None)) End Sub <Fact> Public Sub IsaddressofOperand() Dim source = <compilation name="TestAddressof"> <file name="a.vb"> <![CDATA[ #If Debug Then #End If Namespace NS1 Module Module1 Delegate Sub DelGoo(xx As Integer) Sub Goo(xx As Integer) End Sub Sub Main() Dim a1 = GetType(Integer) Dim d As DelGoo = AddressOf Goo d.Invoke(xx:=1) Dim Obj Gen As New genClass(Of Integer) End Sub <Obsolete> Sub OldMethod() End Sub End Module Class genClass(Of t) End Class End Namespace ]]></file> </compilation> Dim tree = CreateCompilationWithMscorlib40(source).SyntaxTrees.Item(0) Dim symNode = FindNodeOrTokenByKind(tree, SyntaxKind.AddressOfExpression, 1).AsNode Assert.False(SyntaxFacts.IsAddressOfOperand(DirectCast(symNode, ExpressionSyntax))) Assert.False(SyntaxFacts.IsInvocationOrAddressOfOperand(DirectCast(symNode, ExpressionSyntax))) Assert.True(SyntaxFacts.IsAddressOfOperand(CType(symNode.ChildNodes(0), ExpressionSyntax))) Assert.True(SyntaxFacts.IsInvocationOrAddressOfOperand(CType(symNode.ChildNodes(0), ExpressionSyntax))) Assert.False(SyntaxFacts.IsInvoked(DirectCast(FindNodeOrTokenByKind(tree, SyntaxKind.InvocationExpression, 1).AsNode, ExpressionSyntax))) symNode = FindNodeOrTokenByKind(tree, SyntaxKind.InvocationExpression, 1).AsNode Assert.False(SyntaxFacts.IsInvoked(CType(symNode, ExpressionSyntax))) Assert.True(SyntaxFacts.IsInvoked(CType(symNode.ChildNodes(0), ExpressionSyntax))) symNode = FindNodeOrTokenByKind(tree, SyntaxKind.Attribute, 1).AsNode Assert.False(SyntaxFacts.IsAttributeName(symNode)) Assert.True(SyntaxFacts.IsAttributeName(symNode.ChildNodes(0))) symNode = FindNodeOrTokenByKind(tree, SyntaxKind.Attribute, 1).AsNode End Sub <Fact> Public Sub IsAssignmentStatement() For Each item As SyntaxKind In {SyntaxKind.SimpleAssignmentStatement, SyntaxKind.MidAssignmentStatement, SyntaxKind.AddAssignmentStatement, SyntaxKind.SubtractAssignmentStatement, SyntaxKind.MultiplyAssignmentStatement, SyntaxKind.DivideAssignmentStatement, SyntaxKind.IntegerDivideAssignmentStatement, SyntaxKind.ExponentiateAssignmentStatement, SyntaxKind.LeftShiftAssignmentStatement, SyntaxKind.RightShiftAssignmentStatement, SyntaxKind.ConcatenateAssignmentStatement} Assert.True(SyntaxFacts.IsAssignmentStatement(item)) Next Assert.False(SyntaxFacts.IsAssignmentStatement(SyntaxKind.ExitKeyword)) Assert.False(SyntaxFacts.IsAssignmentStatement(SyntaxKind.None)) End Sub <Fact> Public Sub IsAssignmentStatementOperatorToken() For Each item As SyntaxKind In {SyntaxKind.EqualsToken, SyntaxKind.PlusEqualsToken, SyntaxKind.MinusEqualsToken, SyntaxKind.AsteriskEqualsToken, SyntaxKind.SlashEqualsToken, SyntaxKind.BackslashEqualsToken, SyntaxKind.CaretEqualsToken, SyntaxKind.LessThanLessThanEqualsToken, SyntaxKind.GreaterThanGreaterThanEqualsToken, SyntaxKind.AmpersandEqualsToken} Assert.True(SyntaxFacts.IsAssignmentStatementOperatorToken(item)) Next Assert.False(SyntaxFacts.IsAssignmentStatementOperatorToken(SyntaxKind.ExitKeyword)) Assert.False(SyntaxFacts.IsAssignmentStatementOperatorToken(SyntaxKind.None)) End Sub <Fact> Public Sub IsAttributeTargetAttributeModifier() For Each item As SyntaxKind In {SyntaxKind.AssemblyKeyword, SyntaxKind.ModuleKeyword} Assert.True(SyntaxFacts.IsAttributeTargetAttributeModifier(item)) Next Assert.False(SyntaxFacts.IsAttributeTargetAttributeModifier(SyntaxKind.SubKeyword)) Assert.False(SyntaxFacts.IsAttributeTargetAttributeModifier(SyntaxKind.None)) End Sub <Fact> Public Sub IsBinaryExpression() For Each item As SyntaxKind In {SyntaxKind.AddExpression, SyntaxKind.SubtractExpression, SyntaxKind.MultiplyExpression, SyntaxKind.DivideExpression, SyntaxKind.IntegerDivideExpression, SyntaxKind.ExponentiateExpression, SyntaxKind.LeftShiftExpression, SyntaxKind.RightShiftExpression, SyntaxKind.ConcatenateExpression, SyntaxKind.ModuloExpression, SyntaxKind.EqualsExpression, SyntaxKind.NotEqualsExpression, SyntaxKind.LessThanExpression, SyntaxKind.LessThanOrEqualExpression, SyntaxKind.GreaterThanOrEqualExpression, SyntaxKind.GreaterThanExpression, SyntaxKind.IsExpression, SyntaxKind.IsNotExpression, SyntaxKind.LikeExpression, SyntaxKind.OrExpression, SyntaxKind.ExclusiveOrExpression, SyntaxKind.AndExpression, SyntaxKind.OrElseExpression, SyntaxKind.AndAlsoExpression} Assert.True(SyntaxFacts.IsBinaryExpression(item)) Next Assert.False(SyntaxFacts.IsBinaryExpression(SyntaxKind.MinusToken)) Assert.False(SyntaxFacts.IsBinaryExpression(SyntaxKind.None)) End Sub <Fact> Public Sub IsBinaryExpressionOperatorToken() For Each item As SyntaxKind In {SyntaxKind.PlusToken, SyntaxKind.MinusToken, SyntaxKind.AsteriskToken, SyntaxKind.SlashToken, SyntaxKind.BackslashToken, SyntaxKind.CaretToken, SyntaxKind.LessThanLessThanToken, SyntaxKind.GreaterThanGreaterThanToken, SyntaxKind.AmpersandToken, SyntaxKind.ModKeyword, SyntaxKind.EqualsToken, SyntaxKind.LessThanGreaterThanToken, SyntaxKind.LessThanToken, SyntaxKind.LessThanEqualsToken, SyntaxKind.GreaterThanEqualsToken, SyntaxKind.GreaterThanToken, SyntaxKind.IsKeyword, SyntaxKind.IsNotKeyword, SyntaxKind.LikeKeyword, SyntaxKind.OrKeyword, SyntaxKind.XorKeyword, SyntaxKind.AndKeyword, SyntaxKind.OrElseKeyword, SyntaxKind.AndAlsoKeyword} Assert.True(SyntaxFacts.IsBinaryExpressionOperatorToken(item)) Next Assert.False(SyntaxFacts.IsBinaryExpressionOperatorToken(SyntaxKind.MinusEqualsToken)) Assert.False(SyntaxFacts.IsBinaryExpressionOperatorToken(SyntaxKind.None)) End Sub <Fact> Public Sub IsCaseBlock() For Each item As SyntaxKind In {SyntaxKind.CaseBlock, SyntaxKind.CaseElseBlock} Assert.True(SyntaxFacts.IsCaseBlock(item)) Next Assert.False(SyntaxFacts.IsCaseBlock(SyntaxKind.ExitKeyword)) Assert.False(SyntaxFacts.IsCaseBlock(SyntaxKind.None)) End Sub <Fact> Public Sub IsRelationalCaseClause() For Each item As SyntaxKind In {SyntaxKind.CaseEqualsClause, SyntaxKind.CaseNotEqualsClause, SyntaxKind.CaseLessThanClause, SyntaxKind.CaseLessThanOrEqualClause, SyntaxKind.CaseGreaterThanOrEqualClause, SyntaxKind.CaseGreaterThanClause} Assert.True(SyntaxFacts.IsRelationalCaseClause(item)) Next Assert.False(SyntaxFacts.IsRelationalCaseClause(SyntaxKind.ExitKeyword)) Assert.False(SyntaxFacts.IsRelationalCaseClause(SyntaxKind.None)) End Sub <Fact> Public Sub IsRelationalCaseClauseOperatorToken() For Each item As SyntaxKind In {SyntaxKind.EqualsToken, SyntaxKind.LessThanGreaterThanToken, SyntaxKind.LessThanToken, SyntaxKind.LessThanEqualsToken, SyntaxKind.GreaterThanEqualsToken, SyntaxKind.GreaterThanToken} Assert.True(SyntaxFacts.IsRelationalCaseClauseOperatorToken(item)) Next Assert.False(SyntaxFacts.IsRelationalCaseClauseOperatorToken(SyntaxKind.ExitKeyword)) Assert.False(SyntaxFacts.IsRelationalCaseClauseOperatorToken(SyntaxKind.None)) End Sub <Fact> Public Sub IsCaseStatement() For Each item As SyntaxKind In {SyntaxKind.CaseStatement, SyntaxKind.CaseElseStatement} Assert.True(SyntaxFacts.IsCaseStatement(item)) Next Assert.False(SyntaxFacts.IsCaseStatement(SyntaxKind.ExitKeyword)) Assert.False(SyntaxFacts.IsCaseStatement(SyntaxKind.None)) End Sub <Fact> Public Sub IsContextualKeyword1() Assert.False(SyntaxFacts.IsContextualKeyword(SyntaxKind.GosubKeyword)) Assert.True(SyntaxFacts.IsContextualKeyword(SyntaxKind.AggregateKeyword)) End Sub <Fact> Public Sub IsReservedKeyword() Assert.False(SyntaxFacts.IsReservedKeyword(SyntaxKind.OrderByClause)) Assert.True(SyntaxFacts.IsReservedKeyword(SyntaxKind.AddHandlerKeyword)) End Sub <Fact> Public Sub IsContinueStatement() For Each item As SyntaxKind In {SyntaxKind.ContinueWhileStatement, SyntaxKind.ContinueDoStatement, SyntaxKind.ContinueForStatement} Assert.True(SyntaxFacts.IsContinueStatement(item)) Next Assert.False(SyntaxFacts.IsContinueStatement(SyntaxKind.WithKeyword)) Assert.False(SyntaxFacts.IsContinueStatement(SyntaxKind.None)) End Sub <Fact> Public Sub IsContinueStatementBlockKeyword() For Each item As SyntaxKind In {SyntaxKind.WhileKeyword, SyntaxKind.DoKeyword, SyntaxKind.ForKeyword} Assert.True(SyntaxFacts.IsContinueStatementBlockKeyword(item)) Next Assert.False(SyntaxFacts.IsContinueStatementBlockKeyword(SyntaxKind.ExitKeyword)) Assert.False(SyntaxFacts.IsContinueStatementBlockKeyword(SyntaxKind.None)) End Sub <Fact> Public Sub IsDeclareStatement() For Each item As SyntaxKind In {SyntaxKind.DeclareSubStatement, SyntaxKind.DeclareFunctionStatement} Assert.True(SyntaxFacts.IsDeclareStatement(item)) Next Assert.False(SyntaxFacts.IsDeclareStatement(SyntaxKind.NamespaceBlock)) Assert.False(SyntaxFacts.IsDeclareStatement(SyntaxKind.None)) End Sub <Fact> Public Sub IsDeclareStatementCharsetKeyword() For Each item As SyntaxKind In {SyntaxKind.AnsiKeyword, SyntaxKind.UnicodeKeyword, SyntaxKind.AutoKeyword} Assert.True(SyntaxFacts.IsDeclareStatementCharsetKeyword(item)) Next Assert.False(SyntaxFacts.IsDeclareStatementCharsetKeyword(SyntaxKind.FunctionKeyword)) Assert.False(SyntaxFacts.IsDeclareStatementCharsetKeyword(SyntaxKind.None)) End Sub <Fact> Public Sub IsDeclareStatementKeyword() For Each item As SyntaxKind In {SyntaxKind.SubKeyword, SyntaxKind.FunctionKeyword} Assert.True(SyntaxFacts.IsDeclareStatementSubOrFunctionKeyword(item)) Next Assert.False(SyntaxFacts.IsDeclareStatementSubOrFunctionKeyword(SyntaxKind.NamespaceBlock)) Assert.False(SyntaxFacts.IsDeclareStatementSubOrFunctionKeyword(SyntaxKind.None)) End Sub <Fact> Public Sub IsDelegateStatement() For Each item As SyntaxKind In {SyntaxKind.DelegateSubStatement, SyntaxKind.DelegateFunctionStatement} Assert.True(SyntaxFacts.IsDelegateStatement(item)) Next Assert.False(SyntaxFacts.IsDelegateStatement(SyntaxKind.NamespaceBlock)) Assert.False(SyntaxFacts.IsDelegateStatement(SyntaxKind.None)) End Sub <Fact> Public Sub IsDelegateStatementKeyword() For Each item As SyntaxKind In {SyntaxKind.SubKeyword, SyntaxKind.FunctionKeyword} Assert.True(SyntaxFacts.IsDelegateStatementSubOrFunctionKeyword(item)) Next Assert.False(SyntaxFacts.IsDelegateStatementSubOrFunctionKeyword(SyntaxKind.NamespaceBlock)) Assert.False(SyntaxFacts.IsDelegateStatementSubOrFunctionKeyword(SyntaxKind.None)) End Sub <Fact> Public Sub IsDoLoopBlock() For Each item As SyntaxKind In {SyntaxKind.SimpleDoLoopBlock, SyntaxKind.DoWhileLoopBlock, SyntaxKind.DoUntilLoopBlock, SyntaxKind.DoLoopWhileBlock, SyntaxKind.DoLoopUntilBlock} Assert.True(SyntaxFacts.IsDoLoopBlock(item)) Next Assert.False(SyntaxFacts.IsDoLoopBlock(SyntaxKind.ExitKeyword)) Assert.False(SyntaxFacts.IsDoLoopBlock(SyntaxKind.None)) End Sub <Fact> Public Sub IsEndBlockStatement() For Each item As SyntaxKind In {SyntaxKind.EndIfStatement, SyntaxKind.EndUsingStatement, SyntaxKind.EndWithStatement, SyntaxKind.EndSelectStatement, SyntaxKind.EndStructureStatement, SyntaxKind.EndEnumStatement, SyntaxKind.EndInterfaceStatement, SyntaxKind.EndClassStatement, SyntaxKind.EndModuleStatement, SyntaxKind.EndNamespaceStatement, SyntaxKind.EndSubStatement, SyntaxKind.EndFunctionStatement, SyntaxKind.EndGetStatement, SyntaxKind.EndSetStatement, SyntaxKind.EndPropertyStatement, SyntaxKind.EndOperatorStatement, SyntaxKind.EndEventStatement, SyntaxKind.EndAddHandlerStatement, SyntaxKind.EndRemoveHandlerStatement, SyntaxKind.EndRaiseEventStatement, SyntaxKind.EndWhileStatement, SyntaxKind.EndTryStatement, SyntaxKind.EndSyncLockStatement} Assert.True(SyntaxFacts.IsEndBlockStatement(item)) Next Assert.False(SyntaxFacts.IsEndBlockStatement(SyntaxKind.AddHandlerStatement)) End Sub <Fact> Public Sub IsEndBlockStatementBlockKeyword() For Each item As SyntaxKind In {SyntaxKind.IfKeyword, SyntaxKind.UsingKeyword, SyntaxKind.WithKeyword, SyntaxKind.SelectKeyword, SyntaxKind.StructureKeyword, SyntaxKind.EnumKeyword, SyntaxKind.InterfaceKeyword, SyntaxKind.ClassKeyword, SyntaxKind.ModuleKeyword, SyntaxKind.NamespaceKeyword, SyntaxKind.SubKeyword, SyntaxKind.FunctionKeyword, SyntaxKind.GetKeyword, SyntaxKind.SetKeyword, SyntaxKind.PropertyKeyword, SyntaxKind.OperatorKeyword, SyntaxKind.EventKeyword, SyntaxKind.AddHandlerKeyword, SyntaxKind.RemoveHandlerKeyword, SyntaxKind.RaiseEventKeyword, SyntaxKind.WhileKeyword, SyntaxKind.TryKeyword, SyntaxKind.SyncLockKeyword} Assert.True(SyntaxFacts.IsEndBlockStatementBlockKeyword(item)) Next Assert.False(SyntaxFacts.IsEndBlockStatementBlockKeyword(SyntaxKind.AddHandlerStatement)) Assert.False(SyntaxFacts.IsEndBlockStatementBlockKeyword(SyntaxKind.None)) End Sub <Fact> Public Sub IsExitStatement() For Each item As SyntaxKind In {SyntaxKind.ExitDoStatement, SyntaxKind.ExitForStatement, SyntaxKind.ExitSubStatement, SyntaxKind.ExitFunctionStatement, SyntaxKind.ExitOperatorStatement, SyntaxKind.ExitPropertyStatement, SyntaxKind.ExitTryStatement, SyntaxKind.ExitSelectStatement, SyntaxKind.ExitWhileStatement} Assert.True(SyntaxFacts.IsExitStatement(item)) Next Assert.False(SyntaxFacts.IsExitStatement(SyntaxKind.WithKeyword)) Assert.False(SyntaxFacts.IsExitStatement(SyntaxKind.None)) End Sub <Fact> Public Sub IsExitStatementBlockKeyword() For Each item As SyntaxKind In {SyntaxKind.DoKeyword, SyntaxKind.ForKeyword, SyntaxKind.SubKeyword, SyntaxKind.FunctionKeyword, SyntaxKind.OperatorKeyword, SyntaxKind.PropertyKeyword, SyntaxKind.TryKeyword, SyntaxKind.SelectKeyword, SyntaxKind.WhileKeyword} Assert.True(SyntaxFacts.IsExitStatementBlockKeyword(item)) Next Assert.False(SyntaxFacts.IsExitStatementBlockKeyword(SyntaxKind.ExitKeyword)) Assert.False(SyntaxFacts.IsExitStatementBlockKeyword(SyntaxKind.None)) End Sub <Fact> Public Sub IsIfDirective() For Each item As SyntaxKind In {SyntaxKind.IfDirectiveTrivia, SyntaxKind.ElseIfDirectiveTrivia} Assert.True(SyntaxFacts.IsIfDirectiveTrivia(item)) Next Assert.False(SyntaxFacts.IsIfDirectiveTrivia(SyntaxKind.ExitKeyword)) Assert.False(SyntaxFacts.IsIfDirectiveTrivia(SyntaxKind.None)) End Sub <Fact> Public Sub IsIfDirectiveIfOrElseIfKeyword() For Each item As SyntaxKind In {SyntaxKind.IfKeyword, SyntaxKind.ElseIfKeyword} Assert.True(SyntaxFacts.IsIfDirectiveTriviaIfOrElseIfKeyword(item)) Next Assert.False(SyntaxFacts.IsIfDirectiveTriviaIfOrElseIfKeyword(SyntaxKind.ExitKeyword)) Assert.False(SyntaxFacts.IsIfDirectiveTriviaIfOrElseIfKeyword(SyntaxKind.None)) End Sub <Fact> Public Sub IsInstanceExpression() Assert.True(SyntaxFacts.IsInstanceExpression(SyntaxKind.MeKeyword)) Assert.True(SyntaxFacts.IsInstanceExpression(SyntaxKind.MyBaseKeyword)) Assert.False(SyntaxFacts.IsInstanceExpression(SyntaxKind.REMKeyword)) End Sub <Fact> Public Sub IsKeywordEventContainerKeyword() For Each item As SyntaxKind In {SyntaxKind.MyBaseKeyword, SyntaxKind.MeKeyword, SyntaxKind.MyClassKeyword} Assert.True(SyntaxFacts.IsKeywordEventContainerKeyword(item)) Next Assert.False(SyntaxFacts.IsKeywordEventContainerKeyword(SyntaxKind.SubKeyword)) Assert.False(SyntaxFacts.IsKeywordEventContainerKeyword(SyntaxKind.None)) End Sub <Fact> Public Sub IsKeywordKind() For Each item As SyntaxKind In {SyntaxKind.AddHandlerKeyword, SyntaxKind.AddressOfKeyword, SyntaxKind.AliasKeyword, SyntaxKind.AndKeyword, SyntaxKind.AndAlsoKeyword, SyntaxKind.AsKeyword, SyntaxKind.BooleanKeyword, SyntaxKind.ByRefKeyword, SyntaxKind.ByteKeyword, SyntaxKind.ByValKeyword, SyntaxKind.CallKeyword, SyntaxKind.CaseKeyword, SyntaxKind.CatchKeyword, SyntaxKind.CBoolKeyword, SyntaxKind.CByteKeyword, SyntaxKind.CCharKeyword, SyntaxKind.CDateKeyword, SyntaxKind.CDecKeyword, SyntaxKind.CDblKeyword, SyntaxKind.CharKeyword, SyntaxKind.CIntKeyword, SyntaxKind.ClassKeyword, SyntaxKind.CLngKeyword, SyntaxKind.CObjKeyword, SyntaxKind.ConstKeyword, SyntaxKind.ReferenceKeyword, SyntaxKind.ContinueKeyword, SyntaxKind.CSByteKeyword, SyntaxKind.CShortKeyword, SyntaxKind.CSngKeyword, SyntaxKind.CStrKeyword, SyntaxKind.CTypeKeyword, SyntaxKind.CUIntKeyword, SyntaxKind.CULngKeyword, SyntaxKind.CUShortKeyword, SyntaxKind.DateKeyword, SyntaxKind.DecimalKeyword, SyntaxKind.DeclareKeyword, SyntaxKind.DefaultKeyword, SyntaxKind.DelegateKeyword, SyntaxKind.DimKeyword, SyntaxKind.DirectCastKeyword, SyntaxKind.DoKeyword, SyntaxKind.DoubleKeyword, SyntaxKind.EachKeyword, SyntaxKind.ElseKeyword, SyntaxKind.ElseIfKeyword, SyntaxKind.EndKeyword, SyntaxKind.EnumKeyword, SyntaxKind.EraseKeyword, SyntaxKind.ErrorKeyword, SyntaxKind.EventKeyword, SyntaxKind.ExitKeyword, SyntaxKind.FalseKeyword, SyntaxKind.FinallyKeyword, SyntaxKind.ForKeyword, SyntaxKind.FriendKeyword, SyntaxKind.FunctionKeyword, SyntaxKind.GetKeyword, SyntaxKind.GetTypeKeyword, SyntaxKind.GetXmlNamespaceKeyword, SyntaxKind.GlobalKeyword, SyntaxKind.GoToKeyword, SyntaxKind.HandlesKeyword, SyntaxKind.IfKeyword, SyntaxKind.ImplementsKeyword, SyntaxKind.ImportsKeyword, SyntaxKind.InKeyword, SyntaxKind.InheritsKeyword, SyntaxKind.IntegerKeyword, SyntaxKind.InterfaceKeyword, SyntaxKind.IsKeyword, SyntaxKind.IsNotKeyword, SyntaxKind.LetKeyword, SyntaxKind.LibKeyword, SyntaxKind.LikeKeyword, SyntaxKind.LongKeyword, SyntaxKind.LoopKeyword, SyntaxKind.MeKeyword, SyntaxKind.ModKeyword, SyntaxKind.ModuleKeyword, SyntaxKind.MustInheritKeyword, SyntaxKind.MustOverrideKeyword, SyntaxKind.MyBaseKeyword, SyntaxKind.MyClassKeyword, SyntaxKind.NamespaceKeyword, SyntaxKind.NarrowingKeyword, SyntaxKind.NextKeyword, SyntaxKind.NewKeyword, SyntaxKind.NotKeyword, SyntaxKind.NothingKeyword, SyntaxKind.NotInheritableKeyword, SyntaxKind.NotOverridableKeyword, SyntaxKind.ObjectKeyword, SyntaxKind.OfKeyword, SyntaxKind.OnKeyword, SyntaxKind.OperatorKeyword, SyntaxKind.OptionKeyword, SyntaxKind.OptionalKeyword, SyntaxKind.OrKeyword, SyntaxKind.OrElseKeyword, SyntaxKind.OverloadsKeyword, SyntaxKind.OverridableKeyword, SyntaxKind.OverridesKeyword, SyntaxKind.ParamArrayKeyword, SyntaxKind.PartialKeyword, SyntaxKind.PrivateKeyword, SyntaxKind.PropertyKeyword, SyntaxKind.ProtectedKeyword, SyntaxKind.PublicKeyword, SyntaxKind.RaiseEventKeyword, SyntaxKind.ReadOnlyKeyword, SyntaxKind.ReDimKeyword, SyntaxKind.REMKeyword, SyntaxKind.RemoveHandlerKeyword, SyntaxKind.ResumeKeyword, SyntaxKind.ReturnKeyword, SyntaxKind.SByteKeyword, SyntaxKind.SelectKeyword, SyntaxKind.SetKeyword, SyntaxKind.ShadowsKeyword, SyntaxKind.SharedKeyword, SyntaxKind.ShortKeyword, SyntaxKind.SingleKeyword, SyntaxKind.StaticKeyword, SyntaxKind.StepKeyword, SyntaxKind.StopKeyword, SyntaxKind.StringKeyword, SyntaxKind.StructureKeyword, SyntaxKind.SubKeyword, SyntaxKind.SyncLockKeyword, SyntaxKind.ThenKeyword, SyntaxKind.ThrowKeyword, SyntaxKind.ToKeyword, SyntaxKind.TrueKeyword, SyntaxKind.TryKeyword, SyntaxKind.TryCastKeyword, SyntaxKind.TypeOfKeyword, SyntaxKind.UIntegerKeyword, SyntaxKind.ULongKeyword, SyntaxKind.UShortKeyword, SyntaxKind.UsingKeyword, SyntaxKind.WhenKeyword, SyntaxKind.WhileKeyword, SyntaxKind.WideningKeyword, SyntaxKind.WithKeyword, SyntaxKind.WithEventsKeyword, SyntaxKind.WriteOnlyKeyword, SyntaxKind.XorKeyword, SyntaxKind.EndIfKeyword, SyntaxKind.GosubKeyword, SyntaxKind.VariantKeyword, SyntaxKind.WendKeyword, SyntaxKind.AggregateKeyword, SyntaxKind.AllKeyword, SyntaxKind.AnsiKeyword, SyntaxKind.AscendingKeyword, SyntaxKind.AssemblyKeyword, SyntaxKind.AutoKeyword, SyntaxKind.BinaryKeyword, SyntaxKind.ByKeyword, SyntaxKind.CompareKeyword, SyntaxKind.CustomKeyword, SyntaxKind.DescendingKeyword, SyntaxKind.DistinctKeyword, SyntaxKind.EqualsKeyword, SyntaxKind.ExplicitKeyword, SyntaxKind.ExternalSourceKeyword, SyntaxKind.ExternalChecksumKeyword, SyntaxKind.FromKeyword, SyntaxKind.GroupKeyword, SyntaxKind.InferKeyword, SyntaxKind.IntoKeyword, SyntaxKind.IsFalseKeyword, SyntaxKind.IsTrueKeyword, SyntaxKind.JoinKeyword, SyntaxKind.KeyKeyword, SyntaxKind.MidKeyword, SyntaxKind.OffKeyword, SyntaxKind.OrderKeyword, SyntaxKind.OutKeyword, SyntaxKind.PreserveKeyword, SyntaxKind.RegionKeyword, SyntaxKind.SkipKeyword, SyntaxKind.StrictKeyword, SyntaxKind.TakeKeyword, SyntaxKind.TextKeyword, SyntaxKind.UnicodeKeyword, SyntaxKind.UntilKeyword, SyntaxKind.WhereKeyword, SyntaxKind.TypeKeyword, SyntaxKind.XmlKeyword} Assert.True(SyntaxFacts.IsKeywordKind(item)) Next Assert.False(SyntaxFacts.IsKeywordKind(SyntaxKind.MinusEqualsToken)) Assert.False(SyntaxFacts.IsKeywordKind(SyntaxKind.None)) End Sub <Fact> Public Sub IsLabelStatementLabelToken() For Each item As SyntaxKind In {SyntaxKind.IdentifierToken, SyntaxKind.IntegerLiteralToken} Assert.True(SyntaxFacts.IsLabelStatementLabelToken(item)) Next Assert.False(SyntaxFacts.IsLabelStatementLabelToken(SyntaxKind.WithKeyword)) Assert.False(SyntaxFacts.IsLabelStatementLabelToken(SyntaxKind.None)) End Sub <Fact> Public Sub IsLambdaHeader() For Each item As SyntaxKind In {SyntaxKind.SubLambdaHeader, SyntaxKind.FunctionLambdaHeader} Assert.True(SyntaxFacts.IsLambdaHeader(item)) Next Assert.False(SyntaxFacts.IsLambdaHeader(SyntaxKind.ExitKeyword)) Assert.False(SyntaxFacts.IsLambdaHeader(SyntaxKind.None)) End Sub <Fact> Public Sub IsLambdaHeaderKeyword() For Each item As SyntaxKind In {SyntaxKind.SubKeyword, SyntaxKind.FunctionKeyword} Assert.True(SyntaxFacts.IsLambdaHeaderSubOrFunctionKeyword(item)) Next Assert.False(SyntaxFacts.IsLambdaHeaderSubOrFunctionKeyword(SyntaxKind.ExitKeyword)) Assert.False(SyntaxFacts.IsLambdaHeaderSubOrFunctionKeyword(SyntaxKind.None)) End Sub <Fact> Public Sub IsLanguagePunctuation() Assert.True(SyntaxFacts.IsLanguagePunctuation(SyntaxKind.ExclamationToken)) Assert.False(SyntaxFacts.IsLanguagePunctuation(SyntaxKind.ConstKeyword)) Assert.False(SyntaxFacts.IsLanguagePunctuation(SyntaxKind.FromKeyword)) End Sub <Fact> Public Sub IsLiteralExpression() For Each item As SyntaxKind In {SyntaxKind.CharacterLiteralExpression, SyntaxKind.TrueLiteralExpression, SyntaxKind.FalseLiteralExpression, SyntaxKind.NumericLiteralExpression, SyntaxKind.DateLiteralExpression, SyntaxKind.StringLiteralExpression, SyntaxKind.NothingLiteralExpression} Assert.True(SyntaxFacts.IsLiteralExpression(item)) Next Assert.False(SyntaxFacts.IsLiteralExpression(SyntaxKind.ExitKeyword)) Assert.False(SyntaxFacts.IsLiteralExpression(SyntaxKind.None)) End Sub <Fact> Public Sub IsMemberAccessExpression() For Each item As SyntaxKind In {SyntaxKind.SimpleMemberAccessExpression, SyntaxKind.DictionaryAccessExpression} Assert.True(SyntaxFacts.IsMemberAccessExpression(item)) Next Assert.False(SyntaxFacts.IsMemberAccessExpression(SyntaxKind.ExitKeyword)) Assert.False(SyntaxFacts.IsMemberAccessExpression(SyntaxKind.None)) End Sub <Fact> Public Sub IsMemberAccessExpressionOperatorToken() For Each item As SyntaxKind In {SyntaxKind.DotToken, SyntaxKind.ExclamationToken} Assert.True(SyntaxFacts.IsMemberAccessExpressionOperatorToken(item)) Next Assert.False(SyntaxFacts.IsMemberAccessExpressionOperatorToken(SyntaxKind.ExitKeyword)) Assert.False(SyntaxFacts.IsMemberAccessExpressionOperatorToken(SyntaxKind.None)) End Sub <Fact> Public Sub IsmethodBlock() For Each item As SyntaxKind In {SyntaxKind.SubBlock, SyntaxKind.FunctionBlock} Assert.True(SyntaxFacts.IsMethodBlock(item)) Next For Each item As SyntaxKind In {SyntaxKind.ConstructorBlock, SyntaxKind.OperatorBlock, SyntaxKind.GetAccessorBlock, SyntaxKind.SetAccessorBlock, SyntaxKind.AddHandlerAccessorBlock, SyntaxKind.RemoveHandlerAccessorBlock, SyntaxKind.RaiseEventAccessorBlock} Assert.False(SyntaxFacts.IsMethodBlock(item)) Next For Each item As SyntaxKind In {SyntaxKind.GetAccessorBlock, SyntaxKind.SetAccessorBlock, SyntaxKind.AddHandlerAccessorBlock, SyntaxKind.RemoveHandlerAccessorBlock, SyntaxKind.RaiseEventAccessorBlock} Assert.True(SyntaxFacts.IsAccessorBlock(item)) Next For Each item As SyntaxKind In {SyntaxKind.SubBlock, SyntaxKind.FunctionBlock, SyntaxKind.ConstructorBlock, SyntaxKind.OperatorBlock} Assert.False(SyntaxFacts.IsAccessorBlock(item)) Next Assert.False(SyntaxFacts.IsMethodBlock(SyntaxKind.MultiLineIfBlock)) Assert.False(SyntaxFacts.IsMethodBlock(SyntaxKind.None)) End Sub <Fact> Public Sub IsMethodStatement() For Each item As SyntaxKind In {SyntaxKind.SubStatement, SyntaxKind.FunctionStatement} Assert.True(SyntaxFacts.IsMethodStatement(item)) Next Assert.False(SyntaxFacts.IsMethodStatement(SyntaxKind.NamespaceBlock)) Assert.False(SyntaxFacts.IsMethodStatement(SyntaxKind.None)) End Sub <Fact> Public Sub IsMethodStatementKeyword() For Each item As SyntaxKind In {SyntaxKind.SubKeyword, SyntaxKind.FunctionKeyword} Assert.True(SyntaxFacts.IsMethodStatementSubOrFunctionKeyword(item)) Next Assert.False(SyntaxFacts.IsMethodStatementSubOrFunctionKeyword(SyntaxKind.NamespaceBlock)) Assert.False(SyntaxFacts.IsMethodStatementSubOrFunctionKeyword(SyntaxKind.None)) End Sub <Fact> Public Sub IsMultiLineLambdaExpression() For Each item As SyntaxKind In {SyntaxKind.SingleLineFunctionLambdaExpression, SyntaxKind.SingleLineSubLambdaExpression} Assert.False(SyntaxFacts.IsMultiLineLambdaExpression(item)) Next For Each item As SyntaxKind In {SyntaxKind.MultiLineFunctionLambdaExpression, SyntaxKind.MultiLineSubLambdaExpression} Assert.True(SyntaxFacts.IsMultiLineLambdaExpression(item)) Next Assert.False(SyntaxFacts.IsMultiLineLambdaExpression(SyntaxKind.None)) End Sub <Fact> Public Sub IsName() Assert.True(SyntaxFacts.IsName(SyntaxKind.IdentifierName)) Assert.True(SyntaxFacts.IsName(SyntaxKind.GenericName)) Assert.True(SyntaxFacts.IsName(SyntaxKind.QualifiedName)) Assert.True(SyntaxFacts.IsName(SyntaxKind.GlobalName)) Assert.False(SyntaxFacts.IsName(SyntaxKind.GlobalKeyword)) Assert.False(SyntaxFacts.IsName(SyntaxKind.CommaToken)) Assert.False(SyntaxFacts.IsName(SyntaxKind.FunctionKeyword)) End Sub <Fact> Public Sub IsNamespaceDeclaration() Assert.True(SyntaxFacts.IsNamespaceMemberDeclaration(SyntaxKind.ClassStatement)) Assert.True(SyntaxFacts.IsNamespaceMemberDeclaration(SyntaxKind.InterfaceStatement)) Assert.True(SyntaxFacts.IsNamespaceMemberDeclaration(SyntaxKind.StructureStatement)) Assert.True(SyntaxFacts.IsNamespaceMemberDeclaration(SyntaxKind.EnumStatement)) Assert.True(SyntaxFacts.IsNamespaceMemberDeclaration(SyntaxKind.ModuleStatement)) Assert.True(SyntaxFacts.IsNamespaceMemberDeclaration(SyntaxKind.NamespaceStatement)) Assert.True(SyntaxFacts.IsNamespaceMemberDeclaration(SyntaxKind.DelegateFunctionStatement)) Assert.True(SyntaxFacts.IsNamespaceMemberDeclaration(SyntaxKind.DelegateSubStatement)) Assert.False(SyntaxFacts.IsName(SyntaxKind.FunctionStatement)) Assert.False(SyntaxFacts.IsName(SyntaxKind.SubStatement)) End Sub <Fact> Public Sub IsOnErrorGoToStatement() For Each item As SyntaxKind In {SyntaxKind.OnErrorGoToZeroStatement, SyntaxKind.OnErrorGoToMinusOneStatement, SyntaxKind.OnErrorGoToLabelStatement} Assert.True(SyntaxFacts.IsOnErrorGoToStatement(item)) Next Assert.False(SyntaxFacts.IsOnErrorGoToStatement(SyntaxKind.ExitKeyword)) Assert.False(SyntaxFacts.IsOnErrorGoToStatement(SyntaxKind.None)) End Sub <Fact> Public Sub IsOperator() Assert.True(SyntaxFacts.IsOperator(SyntaxKind.AndKeyword)) Assert.False(SyntaxFacts.IsOperator(SyntaxKind.ForKeyword)) End Sub <Fact> Public Sub IsOperatorStatementOperator() For Each item As SyntaxKind In {SyntaxKind.CTypeKeyword, SyntaxKind.IsTrueKeyword, SyntaxKind.IsFalseKeyword, SyntaxKind.NotKeyword, SyntaxKind.PlusToken, SyntaxKind.MinusToken, SyntaxKind.AsteriskToken, SyntaxKind.SlashToken, SyntaxKind.CaretToken, SyntaxKind.BackslashToken, SyntaxKind.AmpersandToken, SyntaxKind.LessThanLessThanToken, SyntaxKind.GreaterThanGreaterThanToken, SyntaxKind.ModKeyword, SyntaxKind.OrKeyword, SyntaxKind.XorKeyword, SyntaxKind.AndKeyword, SyntaxKind.LikeKeyword, SyntaxKind.EqualsToken, SyntaxKind.LessThanGreaterThanToken, SyntaxKind.LessThanToken, SyntaxKind.LessThanEqualsToken, SyntaxKind.GreaterThanEqualsToken, SyntaxKind.GreaterThanToken} Assert.True(SyntaxFacts.IsOperatorStatementOperatorToken(item)) Next Assert.False(SyntaxFacts.IsOperatorStatementOperatorToken(SyntaxKind.SubKeyword)) Assert.False(SyntaxFacts.IsOperatorStatementOperatorToken(SyntaxKind.None)) End Sub <Fact> Public Sub IsOptionStatementNameKeyword() For Each item As SyntaxKind In {SyntaxKind.ExplicitKeyword, SyntaxKind.StrictKeyword, SyntaxKind.CompareKeyword, SyntaxKind.InferKeyword} Assert.True(SyntaxFacts.IsOptionStatementNameKeyword(item)) Next Assert.False(SyntaxFacts.IsOptionStatementNameKeyword(SyntaxKind.AddHandlerStatement)) Assert.False(SyntaxFacts.IsOptionStatementNameKeyword(SyntaxKind.None)) End Sub <Fact> Public Sub IsOrdering() For Each item As SyntaxKind In {SyntaxKind.AscendingOrdering, SyntaxKind.DescendingOrdering} Assert.True(SyntaxFacts.IsOrdering(item)) Next Assert.False(SyntaxFacts.IsOrdering(SyntaxKind.ExitKeyword)) Assert.False(SyntaxFacts.IsOrdering(SyntaxKind.None)) End Sub <Fact> Public Sub IsOrderingAscendingOrDescendingKeyword() For Each item As SyntaxKind In {SyntaxKind.AscendingKeyword, SyntaxKind.DescendingKeyword} Assert.True(SyntaxFacts.IsOrderingAscendingOrDescendingKeyword(item)) Next Assert.False(SyntaxFacts.IsOrderingAscendingOrDescendingKeyword(SyntaxKind.ExitKeyword)) Assert.False(SyntaxFacts.IsOrderingAscendingOrDescendingKeyword(SyntaxKind.None)) End Sub <Fact> Public Sub IsPartitionClause() For Each item As SyntaxKind In {SyntaxKind.SkipClause, SyntaxKind.TakeClause} Assert.True(SyntaxFacts.IsPartitionClause(item)) Next Assert.False(SyntaxFacts.IsPartitionClause(SyntaxKind.ExitKeyword)) Assert.False(SyntaxFacts.IsPartitionClause(SyntaxKind.None)) End Sub <Fact> Public Sub IsPartitionClauseSkipOrTakeKeyword() For Each item As SyntaxKind In {SyntaxKind.SkipKeyword, SyntaxKind.TakeKeyword} Assert.True(SyntaxFacts.IsPartitionClauseSkipOrTakeKeyword(item)) Next Assert.False(SyntaxFacts.IsPartitionClauseSkipOrTakeKeyword(SyntaxKind.ExitKeyword)) Assert.False(SyntaxFacts.IsPartitionClauseSkipOrTakeKeyword(SyntaxKind.None)) End Sub <Fact> Public Sub IsPartitionWhileClause() For Each item As SyntaxKind In {SyntaxKind.SkipWhileClause, SyntaxKind.TakeWhileClause} Assert.True(SyntaxFacts.IsPartitionWhileClause(item)) Next Assert.False(SyntaxFacts.IsPartitionWhileClause(SyntaxKind.ExitKeyword)) Assert.False(SyntaxFacts.IsPartitionWhileClause(SyntaxKind.None)) End Sub <Fact> Public Sub IsPartitionWhileClauseSkipOrTakeKeyword() For Each item As SyntaxKind In {SyntaxKind.SkipKeyword, SyntaxKind.TakeKeyword} Assert.True(SyntaxFacts.IsPartitionWhileClauseSkipOrTakeKeyword(item)) Next Assert.False(SyntaxFacts.IsPartitionWhileClauseSkipOrTakeKeyword(SyntaxKind.ExitKeyword)) Assert.False(SyntaxFacts.IsPartitionWhileClauseSkipOrTakeKeyword(SyntaxKind.None)) End Sub <Fact> Public Sub IsPredefinedCastExpressionKeyword() For Each item As SyntaxKind In {SyntaxKind.CObjKeyword, SyntaxKind.CBoolKeyword, SyntaxKind.CDateKeyword, SyntaxKind.CCharKeyword, SyntaxKind.CStrKeyword, SyntaxKind.CDecKeyword, SyntaxKind.CByteKeyword, SyntaxKind.CSByteKeyword, SyntaxKind.CUShortKeyword, SyntaxKind.CShortKeyword, SyntaxKind.CUIntKeyword, SyntaxKind.CIntKeyword, SyntaxKind.CULngKeyword, SyntaxKind.CLngKeyword, SyntaxKind.CSngKeyword, SyntaxKind.CDblKeyword} Assert.True(SyntaxFacts.IsPredefinedCastExpressionKeyword(item)) Next Assert.False(SyntaxFacts.IsPredefinedCastExpressionKeyword(SyntaxKind.MinusToken)) Assert.False(SyntaxFacts.IsPredefinedCastExpressionKeyword(SyntaxKind.None)) End Sub <Fact> Public Sub IsPredefinedType() Assert.True(SyntaxFacts.IsPredefinedType(SyntaxKind.IntegerKeyword)) Assert.True(SyntaxFacts.IsPredefinedType(SyntaxKind.ObjectKeyword)) Assert.False(SyntaxFacts.IsPredefinedType(SyntaxKind.NothingKeyword)) End Sub <Fact> Public Sub IsPreprocessorDirective() Assert.True(SyntaxFacts.IsPreprocessorDirective(SyntaxKind.IfDirectiveTrivia)) Assert.False(SyntaxFacts.IsPreprocessorDirective(SyntaxKind.IfKeyword)) End Sub <Fact> Public Sub IsPreProcessorKeyword() Assert.True(SyntaxFacts.IsPreprocessorKeyword(SyntaxKind.ExternalSourceKeyword)) Assert.True(SyntaxFacts.IsPreprocessorKeyword(SyntaxKind.EnableKeyword)) Assert.True(SyntaxFacts.IsPreprocessorKeyword(SyntaxKind.DisableKeyword)) Assert.True(SyntaxFacts.IsPreprocessorKeyword(SyntaxKind.IfKeyword)) Assert.False(SyntaxFacts.IsPreprocessorKeyword(SyntaxKind.FromKeyword)) End Sub <Fact> Public Sub IsPreProcessorPunctuation() Assert.True(SyntaxFacts.IsPreprocessorPunctuation(SyntaxKind.HashToken)) Assert.False(SyntaxFacts.IsPreprocessorPunctuation(SyntaxKind.DotToken)) Assert.False(SyntaxFacts.IsPreprocessorPunctuation(SyntaxKind.AmpersandToken)) End Sub <Fact> Public Sub IsPunctuation() For Each item As SyntaxKind In {SyntaxKind.ExclamationToken, SyntaxKind.AtToken, SyntaxKind.CommaToken, SyntaxKind.HashToken, SyntaxKind.AmpersandToken, SyntaxKind.SingleQuoteToken, SyntaxKind.OpenParenToken, SyntaxKind.CloseParenToken, SyntaxKind.OpenBraceToken, SyntaxKind.CloseBraceToken, SyntaxKind.SemicolonToken, SyntaxKind.AsteriskToken, SyntaxKind.PlusToken, SyntaxKind.MinusToken, SyntaxKind.DotToken, SyntaxKind.SlashToken, SyntaxKind.ColonToken, SyntaxKind.LessThanToken, SyntaxKind.LessThanEqualsToken, SyntaxKind.LessThanGreaterThanToken, SyntaxKind.EqualsToken, SyntaxKind.GreaterThanToken, SyntaxKind.GreaterThanEqualsToken, SyntaxKind.BackslashToken, SyntaxKind.CaretToken, SyntaxKind.ColonEqualsToken, SyntaxKind.AmpersandEqualsToken, SyntaxKind.AsteriskEqualsToken, SyntaxKind.PlusEqualsToken, SyntaxKind.MinusEqualsToken, SyntaxKind.SlashEqualsToken, SyntaxKind.BackslashEqualsToken, SyntaxKind.CaretEqualsToken, SyntaxKind.LessThanLessThanToken, SyntaxKind.GreaterThanGreaterThanToken, SyntaxKind.LessThanLessThanEqualsToken, SyntaxKind.GreaterThanGreaterThanEqualsToken, SyntaxKind.QuestionToken, SyntaxKind.DoubleQuoteToken, SyntaxKind.StatementTerminatorToken, SyntaxKind.EndOfFileToken, SyntaxKind.EmptyToken, SyntaxKind.SlashGreaterThanToken, SyntaxKind.LessThanSlashToken, SyntaxKind.LessThanExclamationMinusMinusToken, SyntaxKind.MinusMinusGreaterThanToken, SyntaxKind.LessThanQuestionToken, SyntaxKind.QuestionGreaterThanToken, SyntaxKind.LessThanPercentEqualsToken, SyntaxKind.PercentGreaterThanToken, SyntaxKind.BeginCDataToken, SyntaxKind.EndCDataToken, SyntaxKind.EndOfXmlToken, SyntaxKind.DollarSignDoubleQuoteToken, SyntaxKind.EndOfInterpolatedStringToken} Assert.True(SyntaxFacts.IsPunctuation(item)) Next Assert.False(SyntaxFacts.IsPunctuation(SyntaxKind.ExitKeyword)) Assert.False(SyntaxFacts.IsPunctuation(SyntaxKind.None)) End Sub <Fact> Public Sub IsPunctuationOrKeyword() Assert.True(SyntaxFacts.IsPunctuationOrKeyword(SyntaxKind.AddHandlerKeyword)) Assert.True(SyntaxFacts.IsPunctuationOrKeyword(SyntaxKind.EndOfXmlToken)) Assert.True(SyntaxFacts.IsPunctuationOrKeyword(SyntaxKind.DollarSignDoubleQuoteToken)) Assert.True(SyntaxFacts.IsPunctuationOrKeyword(SyntaxKind.EndOfInterpolatedStringToken)) Assert.False(SyntaxFacts.IsPunctuationOrKeyword(SyntaxKind.XmlNameToken)) Assert.False(SyntaxFacts.IsPunctuationOrKeyword(SyntaxKind.ImportAliasClause)) Assert.False(SyntaxFacts.IsPunctuationOrKeyword(SyntaxKind.ForStatement)) End Sub <Fact> Public Sub IsReDimStatement() For Each item As SyntaxKind In {SyntaxKind.ReDimStatement, SyntaxKind.ReDimPreserveStatement} Assert.True(SyntaxFacts.IsReDimStatement(item)) Next Assert.False(SyntaxFacts.IsReDimStatement(SyntaxKind.SimpleAssignmentStatement)) Assert.False(SyntaxFacts.IsReDimStatement(SyntaxKind.None)) End Sub <Fact> Public Sub IsRelationalOperator() Assert.True(SyntaxFacts.IsRelationalOperator(SyntaxKind.LessThanToken)) Assert.False(SyntaxFacts.IsRelationalOperator(SyntaxKind.DotToken)) End Sub <Fact> Public Sub IsReservedKeyword1() Dim VB1 As New SyntaxToken Assert.False(VB1.IsReservedKeyword()) Assert.True(SyntaxFacts.IsReservedKeyword(SyntaxKind.AddHandlerKeyword)) End Sub <Fact> Public Sub IsResumeStatement() For Each item As SyntaxKind In {SyntaxKind.ResumeStatement, SyntaxKind.ResumeLabelStatement, SyntaxKind.ResumeNextStatement} Assert.True(SyntaxFacts.IsResumeStatement(item)) Next Assert.False(SyntaxFacts.IsResumeStatement(SyntaxKind.ExitKeyword)) Assert.False(SyntaxFacts.IsResumeStatement(SyntaxKind.None)) End Sub <Fact> Public Sub IsSingleLineLambdaExpression() For Each item As SyntaxKind In {SyntaxKind.SingleLineFunctionLambdaExpression, SyntaxKind.SingleLineSubLambdaExpression} Assert.True(SyntaxFacts.IsSingleLineLambdaExpression(item)) Next Assert.False(SyntaxFacts.IsSingleLineLambdaExpression(SyntaxKind.MinusToken)) Assert.False(SyntaxFacts.IsSingleLineLambdaExpression(SyntaxKind.None)) End Sub <Fact> Public Sub IsSpecialConstraint() For Each item As SyntaxKind In {SyntaxKind.NewConstraint, SyntaxKind.ClassConstraint, SyntaxKind.StructureConstraint} Assert.True(SyntaxFacts.IsSpecialConstraint(item)) Next Assert.False(SyntaxFacts.IsSpecialConstraint(SyntaxKind.ConstDirectiveTrivia)) Assert.False(SyntaxFacts.IsSpecialConstraint(SyntaxKind.None)) End Sub <Fact> Public Sub IsSpecialConstraintKeyword() For Each item As SyntaxKind In {SyntaxKind.NewKeyword, SyntaxKind.ClassKeyword, SyntaxKind.StructureKeyword} Assert.True(SyntaxFacts.IsSpecialConstraintConstraintKeyword(item)) Next Assert.False(SyntaxFacts.IsSpecialConstraintConstraintKeyword(SyntaxKind.ModuleKeyword)) Assert.False(SyntaxFacts.IsSpecialConstraintConstraintKeyword(SyntaxKind.None)) End Sub <Fact> Public Sub IsStopOrEndStatement() For Each item As SyntaxKind In {SyntaxKind.StopStatement, SyntaxKind.EndStatement} Assert.True(SyntaxFacts.IsStopOrEndStatement(item)) Next Assert.False(SyntaxFacts.IsStopOrEndStatement(SyntaxKind.WithKeyword)) Assert.False(SyntaxFacts.IsStopOrEndStatement(SyntaxKind.None)) End Sub <Fact> Public Sub IsStopOrEndStatementStopOrEndKeyword() For Each item As SyntaxKind In {SyntaxKind.StopKeyword, SyntaxKind.EndKeyword} Assert.True(SyntaxFacts.IsStopOrEndStatementStopOrEndKeyword(item)) Next Assert.False(SyntaxFacts.IsStopOrEndStatementStopOrEndKeyword(SyntaxKind.WithKeyword)) Assert.False(SyntaxFacts.IsStopOrEndStatementStopOrEndKeyword(SyntaxKind.None)) End Sub <Fact> Public Sub IsToken() Assert.True(SyntaxFacts.IsAnyToken(SyntaxKind.AddHandlerKeyword)) Assert.True(SyntaxFacts.IsAnyToken(SyntaxKind.CharacterLiteralToken)) Assert.False(SyntaxFacts.IsAnyToken(SyntaxKind.GlobalName)) Assert.False(SyntaxFacts.IsAnyToken(SyntaxKind.DocumentationCommentTrivia)) End Sub <Fact> Public Sub IsTrivia() Assert.True(SyntaxFacts.IsTrivia(SyntaxKind.WhitespaceTrivia)) Assert.False(SyntaxFacts.IsTrivia(SyntaxKind.REMKeyword)) End Sub <Fact> Public Sub IsTypeOfExpression() For Each item As SyntaxKind In {SyntaxKind.TypeOfIsExpression, SyntaxKind.TypeOfIsNotExpression} Assert.True(SyntaxFacts.IsTypeOfExpression(item)) Next Assert.False(SyntaxFacts.IsTypeOfExpression(SyntaxKind.ExitKeyword)) Assert.False(SyntaxFacts.IsTypeOfExpression(SyntaxKind.None)) End Sub <Fact> Public Sub IsTypeOfExpressionOperatorToken() For Each item As SyntaxKind In {SyntaxKind.IsKeyword, SyntaxKind.IsNotKeyword} Assert.True(SyntaxFacts.IsTypeOfExpressionOperatorToken(item)) Next Assert.False(SyntaxFacts.IsTypeOfExpressionOperatorToken(SyntaxKind.ExitKeyword)) Assert.False(SyntaxFacts.IsTypeOfExpressionOperatorToken(SyntaxKind.None)) End Sub <Fact> Public Sub IsTypeParameterVarianceKeyword() For Each item As SyntaxKind In {SyntaxKind.InKeyword, SyntaxKind.OutKeyword} Assert.True(SyntaxFacts.IsTypeParameterVarianceKeyword(item)) Next Assert.False(SyntaxFacts.IsTypeParameterVarianceKeyword(SyntaxKind.GetKeyword)) Assert.False(SyntaxFacts.IsTypeParameterVarianceKeyword(SyntaxKind.None)) End Sub <Fact> Public Sub IsUnaryExpression() For Each item As SyntaxKind In {SyntaxKind.UnaryPlusExpression, SyntaxKind.UnaryMinusExpression, SyntaxKind.NotExpression, SyntaxKind.AddressOfExpression} Assert.True(SyntaxFacts.IsUnaryExpression(item)) Next Assert.False(SyntaxFacts.IsUnaryExpression(SyntaxKind.MinusToken)) Assert.False(SyntaxFacts.IsUnaryExpression(SyntaxKind.None)) End Sub <Fact> Public Sub IsUnaryExpressionOperatorToken() For Each item As SyntaxKind In {SyntaxKind.PlusToken, SyntaxKind.MinusToken, SyntaxKind.NotKeyword, SyntaxKind.AddressOfKeyword} Assert.True(SyntaxFacts.IsUnaryExpressionOperatorToken(item)) Next Assert.False(SyntaxFacts.IsUnaryExpressionOperatorToken(SyntaxKind.MinusEqualsToken)) Assert.False(SyntaxFacts.IsUnaryExpressionOperatorToken(SyntaxKind.None)) End Sub <Fact> Public Sub IsWhileOrUntilClause() For Each item As SyntaxKind In {SyntaxKind.WhileClause, SyntaxKind.UntilClause} Assert.True(SyntaxFacts.IsWhileOrUntilClause(item)) Next Assert.False(SyntaxFacts.IsWhileOrUntilClause(SyntaxKind.ExitKeyword)) Assert.False(SyntaxFacts.IsWhileOrUntilClause(SyntaxKind.None)) End Sub <Fact> Public Sub IsWhileOrUntilClauseWhileOrUntilKeyword() For Each item As SyntaxKind In {SyntaxKind.WhileKeyword, SyntaxKind.UntilKeyword} Assert.True(SyntaxFacts.IsWhileOrUntilClauseWhileOrUntilKeyword(item)) Next Assert.False(SyntaxFacts.IsWhileOrUntilClauseWhileOrUntilKeyword(SyntaxKind.ExitKeyword)) Assert.False(SyntaxFacts.IsWhileOrUntilClauseWhileOrUntilKeyword(SyntaxKind.None)) End Sub <Fact> Public Sub IsXmlMemberAccessExpression() For Each item As SyntaxKind In {SyntaxKind.XmlElementAccessExpression, SyntaxKind.XmlDescendantAccessExpression, SyntaxKind.XmlAttributeAccessExpression} Assert.True(SyntaxFacts.IsXmlMemberAccessExpression(item)) Next Assert.False(SyntaxFacts.IsXmlMemberAccessExpression(SyntaxKind.ExitKeyword)) Assert.False(SyntaxFacts.IsXmlMemberAccessExpression(SyntaxKind.None)) End Sub <Fact> Public Sub IsXmlMemberAccessExpressionToken2() For Each item As SyntaxKind In {SyntaxKind.DotToken, SyntaxKind.AtToken} Assert.True(SyntaxFacts.IsXmlMemberAccessExpressionToken2(item)) Next Assert.False(SyntaxFacts.IsXmlMemberAccessExpressionToken2(SyntaxKind.MinusToken)) Assert.False(SyntaxFacts.IsXmlMemberAccessExpressionToken2(SyntaxKind.None)) End Sub <Fact> Public Sub IsXmlStringEndQuoteToken() For Each item As SyntaxKind In {SyntaxKind.DoubleQuoteToken, SyntaxKind.SingleQuoteToken} Assert.True(SyntaxFacts.IsXmlStringEndQuoteToken(item)) Next Assert.False(SyntaxFacts.IsXmlStringEndQuoteToken(SyntaxKind.ExitKeyword)) Assert.False(SyntaxFacts.IsXmlStringEndQuoteToken(SyntaxKind.None)) End Sub <Fact> Public Sub IsXmlStringStartQuoteToken() For Each item As SyntaxKind In {SyntaxKind.DoubleQuoteToken, SyntaxKind.SingleQuoteToken} Assert.True(SyntaxFacts.IsXmlStringStartQuoteToken(item)) Next Assert.False(SyntaxFacts.IsXmlStringStartQuoteToken(SyntaxKind.ExitKeyword)) Assert.False(SyntaxFacts.IsXmlStringStartQuoteToken(SyntaxKind.None)) End Sub <Fact> Public Sub IsXmlTextToken() For Each item As SyntaxKind In {SyntaxKind.XmlTextLiteralToken, SyntaxKind.XmlEntityLiteralToken, SyntaxKind.DocumentationCommentLineBreakToken} Assert.True(SyntaxFacts.IsXmlTextToken(item)) Next Assert.False(SyntaxFacts.IsXmlTextToken(SyntaxKind.ExitKeyword)) Assert.False(SyntaxFacts.IsXmlTextToken(SyntaxKind.None)) End Sub <Fact> Public Sub VarianceKindFromToken() Dim keywordToken As SyntaxToken = SyntaxFactory.Token(SyntaxKind.InKeyword, text:=Nothing) Assert.Equal(VarianceKind.In, SyntaxFacts.VarianceKindFromToken(keywordToken)) keywordToken = SyntaxFactory.Token(SyntaxKind.OutKeyword, text:=Nothing) Assert.Equal(VarianceKind.Out, SyntaxFacts.VarianceKindFromToken(keywordToken)) keywordToken = SyntaxFactory.Token(SyntaxKind.FriendKeyword, text:=Nothing) Assert.Equal(VarianceKind.None, SyntaxFacts.VarianceKindFromToken(keywordToken)) End Sub <ConditionalFact(GetType(DesktopClrOnly))> <WorkItem(10841, "https://github.com/mono/mono/issues/10841")> Public Sub AllowsLeadingOrTrailingImplicitLineContinuation() Dim cu = SyntaxFactory.ParseCompilationUnit(s_allInOneSource) Assert.False(cu.ContainsDiagnostics, "Baseline has diagnostics.") Dim tokens = cu.DescendantTokens(descendIntoTrivia:=False) Dim builder As New System.Text.StringBuilder(cu.FullSpan.Length * 2) Const explicitLineContinuation = " _" & vbCrLf ' For every token in the file ' If there is explicit continuation that can be removed, remove it ' If there is implicit continuation, assert that it's allowed ' Otherwise if there is no continuation, add an explicit line continuation Using enumerator = tokens.GetEnumerator() If Not enumerator.MoveNext() Then Return Dim currentToken = enumerator.Current Dim nextToken = enumerator.Current Do While enumerator.MoveNext() currentToken = nextToken nextToken = enumerator.Current If currentToken = currentToken.Parent.AncestorsAndSelf.OfType(Of StatementSyntax).First.GetLastToken() OrElse nextToken.Kind = SyntaxKind.EndOfFileToken Then builder.Append(currentToken.ToFullString()) Continue Do End If If currentToken.HasLeadingTrivia Then For Each trivia In currentToken.LeadingTrivia builder.Append(trivia.ToFullString()) Next End If builder.Append(currentToken.ToString()) If currentToken.HasTrailingTrivia Then Dim hasContinuation = False For Each trivia In currentToken.TrailingTrivia If trivia.Kind = SyntaxKind.LineContinuationTrivia Then If SyntaxFacts.AllowsTrailingImplicitLineContinuation(currentToken) OrElse SyntaxFacts.AllowsLeadingImplicitLineContinuation(nextToken) Then builder.Append(vbCrLf) Else builder.Append(trivia.ToFullString()) End If hasContinuation = True ElseIf trivia.Kind = SyntaxKind.EndOfLineTrivia Then If Not hasContinuation Then hasContinuation = True builder.Append(trivia.ToFullString()) End If Else builder.Append(trivia.ToFullString()) End If Next If Not hasContinuation AndAlso currentToken <> currentToken.Parent.AncestorsAndSelf.OfType(Of StatementSyntax).First.GetLastToken() AndAlso nextToken.Kind <> SyntaxKind.EndOfFileToken Then If SyntaxFacts.AllowsTrailingImplicitLineContinuation(currentToken) OrElse SyntaxFacts.AllowsLeadingImplicitLineContinuation(nextToken) Then builder.Append(vbCrLf) ' These tokens appear in XML literals, explicit line continuation is illegal in these contexts. ElseIf currentToken.Kind <> SyntaxKind.XmlKeyword AndAlso currentToken.Kind <> SyntaxKind.XmlNameToken AndAlso currentToken.Kind <> SyntaxKind.DoubleQuoteToken AndAlso currentToken.Kind <> SyntaxKind.XmlTextLiteralToken Then builder.Append(explicitLineContinuation) End If End If End If Loop End Using cu = SyntaxFactory.ParseCompilationUnit(builder.ToString()) Assert.False(cu.ContainsDiagnostics, "Transformed tree has diagnostics.") End Sub <ConditionalFact(GetType(DesktopClrOnly))> <WorkItem(10841, "https://github.com/mono/mono/issues/10841")> Public Sub AllowsLeadingOrTrailingImplicitLineContinuationNegativeTests() Dim cu = SyntaxFactory.ParseCompilationUnit(s_allInOneSource) Assert.False(cu.ContainsDiagnostics, "Baseline has diagnostics.") Dim tokens = cu.DescendantTokens(descendIntoTrivia:=False) Dim checked As New HashSet(Of Tuple(Of SyntaxKind, SyntaxKind)) ' For every token in the file ' If implicit line continuation is not allowed after it or before the next token add one and ' verify a parse error is reported. Using enumerator = tokens.GetEnumerator() If Not enumerator.MoveNext() Then Return Dim currentToken = enumerator.Current Dim nextToken = enumerator.Current Do While enumerator.MoveNext() currentToken = nextToken nextToken = enumerator.Current ' Tokens for which adding trailing newline does nothing or ' creates a new text which could parse differently but valid code. If currentToken.TrailingTrivia.Any(Function(t) Return t.Kind = SyntaxKind.ColonTrivia OrElse t.Kind = SyntaxKind.EndOfLineTrivia End Function) OrElse currentToken.Kind = SyntaxKind.ColonToken OrElse currentToken.Kind = SyntaxKind.NextKeyword OrElse nextToken.Kind = SyntaxKind.DotToken OrElse nextToken.Kind = SyntaxKind.ColonToken OrElse nextToken.Kind = SyntaxKind.EndOfFileToken Then Continue Do End If Dim kindAndParentKind = Tuple.Create(currentToken.Kind(), currentToken.Parent.Kind()) If checked.Contains(kindAndParentKind) Then Continue Do If Not (SyntaxFacts.AllowsTrailingImplicitLineContinuation(currentToken) OrElse SyntaxFacts.AllowsLeadingImplicitLineContinuation(nextToken)) Then Dim newTrailing = Aggregate trivia In currentToken.TrailingTrivia Where trivia.Kind <> SyntaxKind.EndOfLineTrivia Into ToList() newTrailing.Add(SyntaxFactory.EndOfLineTrivia(vbCrLf)) Assert.True(SyntaxFactory.ParseCompilationUnit(cu.ReplaceToken(currentToken, currentToken.WithTrailingTrivia(newTrailing)).ToFullString()).ContainsDiagnostics, "Expected diagnostic when adding line continuation to " & currentToken.Kind.ToString() & " in " & currentToken.Parent.ToString() & ".") checked.Add(kindAndParentKind) End If Loop End Using End Sub <WorkItem(531480, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531480")> <Fact> Public Sub ImplicitLineContinuationAfterQuery() Dim tree = ParseAndVerify(<![CDATA[ Module M Sub M() If Nothing Is From c In "" Distinct Then End If If Nothing Is From c In "" Order By c Ascending Then End If If Nothing Is From c In "" Order By c Descending Then End If End Sub End Module ]]>) Dim tokens = tree.GetRoot().DescendantTokens().ToArray() Dim index = 0 For Each token In tokens If token.Kind = SyntaxKind.ThenKeyword Then Dim prevToken = tokens(index - 1) Dim nextToken = tokens(index) Assert.False(SyntaxFacts.AllowsTrailingImplicitLineContinuation(prevToken)) Assert.False(SyntaxFacts.AllowsLeadingImplicitLineContinuation(nextToken)) End If index += 1 Next End Sub <WorkItem(530665, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530665")> <Fact> Public Sub ImplicitLineContinuationAfterDictionaryAccessOperator() Dim tree = ParseAndVerify(<![CDATA[ Imports System.Collections Module Program Sub Main() Dim x As New Hashtable Dim y = x ! _ Goo End Sub End Module ]]>) Dim memberAccess = tree.GetRoot().DescendantNodes().OfType(Of MemberAccessExpressionSyntax).Single() Assert.False(SyntaxFacts.AllowsLeadingImplicitLineContinuation(memberAccess.Name.Identifier)) Assert.False(SyntaxFacts.AllowsTrailingImplicitLineContinuation(memberAccess.OperatorToken)) End Sub <WorkItem(990618, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/990618")> <Fact> Public Sub Bug990618() Dim text = SyntaxFacts.GetText(SyntaxKind.BeginCDataToken) Assert.Equal("<![CDATA[", text) End Sub <Theory> <InlineData("x", "x")> <InlineData("x.y", "y")> <InlineData("x?.y", "y")> <InlineData("Me.y", "y")> <InlineData("M()", "M")> <InlineData("x.M()", "M")> <InlineData("TypeOf(x)", Nothing)> <InlineData("GetType(x)", Nothing)> <InlineData("-x", Nothing)> <InlineData("x!y", "y")> <InlineData("Me", Nothing)> <InlineData("[Me]", "Me")> <InlineData("x.Me", "Me")> <InlineData("M()()", "M")> <InlineData("New C()", Nothing)> Public Sub TestTryGetInferredMemberName(source As String, expected As String) Dim expr = SyntaxFactory.ParseExpression(source) Dim actual = expr.TryGetInferredMemberName() Assert.Equal(expected, actual) End Sub <Theory> <InlineData("Item0", False)> <InlineData("Item1", True)> <InlineData("Item2", True)> <InlineData("Item10", True)> <InlineData("Rest", True)> <InlineData("ToString", True)> <InlineData("GetHashCode", True)> <InlineData("item1", True)> <InlineData("item01", False)> <InlineData("item10", True)> <InlineData("Alice", False)> Public Sub TestIsReservedTupleElementName(elementName As String, isReserved As Boolean) Assert.Equal(isReserved, SyntaxFacts.IsReservedTupleElementName(elementName)) End Sub End Class
-1
dotnet/roslyn
55,138
Avoid cancellation exceptions in intermediate operations
Addresses the following exceptions: ![image](https://user-images.githubusercontent.com/1408396/127185947-8a005aea-ae1c-4755-bf0f-21dfb8101352.png)
sharwell
2021-07-27T15:51:28Z
2021-07-27T21:36:45Z
3d8acbd585a75e9cdb3509623bf6c39ceb46b2c2
719d4ffa2be734463e5d7d4d74b23b8006fd7727
Avoid cancellation exceptions in intermediate operations. Addresses the following exceptions: ![image](https://user-images.githubusercontent.com/1408396/127185947-8a005aea-ae1c-4755-bf0f-21dfb8101352.png)
./src/Compilers/Core/Portable/Text/TextChangeRange.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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 Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Text { /// <summary> /// Represents the change to a span of text. /// </summary> [DebuggerDisplay("{GetDebuggerDisplay(),nq}")] public readonly struct TextChangeRange : IEquatable<TextChangeRange> { /// <summary> /// The span of text before the edit which is being changed /// </summary> public TextSpan Span { get; } /// <summary> /// Width of the span after the edit. A 0 here would represent a delete /// </summary> public int NewLength { get; } internal int NewEnd => Span.Start + NewLength; /// <summary> /// Initializes a new instance of <see cref="TextChangeRange"/>. /// </summary> /// <param name="span"></param> /// <param name="newLength"></param> public TextChangeRange(TextSpan span, int newLength) : this() { if (newLength < 0) { throw new ArgumentOutOfRangeException(nameof(newLength)); } this.Span = span; this.NewLength = newLength; } /// <summary> /// Compares current instance of <see cref="TextChangeRange"/> to another. /// </summary> public bool Equals(TextChangeRange other) { return other.Span == this.Span && other.NewLength == this.NewLength; } /// <summary> /// Compares current instance of <see cref="TextChangeRange"/> to another. /// </summary> public override bool Equals(object? obj) { return obj is TextChangeRange range && Equals(range); } /// <summary> /// Provides hash code for current instance of <see cref="TextChangeRange"/>. /// </summary> /// <returns></returns> public override int GetHashCode() { return Hash.Combine(this.NewLength, this.Span.GetHashCode()); } /// <summary> /// Determines if two instances of <see cref="TextChangeRange"/> are same. /// </summary> public static bool operator ==(TextChangeRange left, TextChangeRange right) { return left.Equals(right); } /// <summary> /// Determines if two instances of <see cref="TextChangeRange"/> are different. /// </summary> public static bool operator !=(TextChangeRange left, TextChangeRange right) { return !(left == right); } /// <summary> /// An empty set of changes. /// </summary> public static IReadOnlyList<TextChangeRange> NoChanges => SpecializedCollections.EmptyReadOnlyList<TextChangeRange>(); /// <summary> /// Collapse a set of <see cref="TextChangeRange"/>s into a single encompassing range. If /// the set of ranges provided is empty, an empty range is returned. /// </summary> public static TextChangeRange Collapse(IEnumerable<TextChangeRange> changes) { var diff = 0; var start = int.MaxValue; var end = 0; foreach (var change in changes) { diff += change.NewLength - change.Span.Length; if (change.Span.Start < start) { start = change.Span.Start; } if (change.Span.End > end) { end = change.Span.End; } } if (start > end) { // there were no changes. return default(TextChangeRange); } var combined = TextSpan.FromBounds(start, end); var newLen = combined.Length + diff; return new TextChangeRange(combined, newLen); } private string GetDebuggerDisplay() { return $"new TextChangeRange(new TextSpan({Span.Start}, {Span.Length}), {NewLength})"; } public override string ToString() { return $"TextChangeRange(Span={Span}, NewLength={NewLength})"; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .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 Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Text { /// <summary> /// Represents the change to a span of text. /// </summary> [DebuggerDisplay("{GetDebuggerDisplay(),nq}")] public readonly struct TextChangeRange : IEquatable<TextChangeRange> { /// <summary> /// The span of text before the edit which is being changed /// </summary> public TextSpan Span { get; } /// <summary> /// Width of the span after the edit. A 0 here would represent a delete /// </summary> public int NewLength { get; } internal int NewEnd => Span.Start + NewLength; /// <summary> /// Initializes a new instance of <see cref="TextChangeRange"/>. /// </summary> /// <param name="span"></param> /// <param name="newLength"></param> public TextChangeRange(TextSpan span, int newLength) : this() { if (newLength < 0) { throw new ArgumentOutOfRangeException(nameof(newLength)); } this.Span = span; this.NewLength = newLength; } /// <summary> /// Compares current instance of <see cref="TextChangeRange"/> to another. /// </summary> public bool Equals(TextChangeRange other) { return other.Span == this.Span && other.NewLength == this.NewLength; } /// <summary> /// Compares current instance of <see cref="TextChangeRange"/> to another. /// </summary> public override bool Equals(object? obj) { return obj is TextChangeRange range && Equals(range); } /// <summary> /// Provides hash code for current instance of <see cref="TextChangeRange"/>. /// </summary> /// <returns></returns> public override int GetHashCode() { return Hash.Combine(this.NewLength, this.Span.GetHashCode()); } /// <summary> /// Determines if two instances of <see cref="TextChangeRange"/> are same. /// </summary> public static bool operator ==(TextChangeRange left, TextChangeRange right) { return left.Equals(right); } /// <summary> /// Determines if two instances of <see cref="TextChangeRange"/> are different. /// </summary> public static bool operator !=(TextChangeRange left, TextChangeRange right) { return !(left == right); } /// <summary> /// An empty set of changes. /// </summary> public static IReadOnlyList<TextChangeRange> NoChanges => SpecializedCollections.EmptyReadOnlyList<TextChangeRange>(); /// <summary> /// Collapse a set of <see cref="TextChangeRange"/>s into a single encompassing range. If /// the set of ranges provided is empty, an empty range is returned. /// </summary> public static TextChangeRange Collapse(IEnumerable<TextChangeRange> changes) { var diff = 0; var start = int.MaxValue; var end = 0; foreach (var change in changes) { diff += change.NewLength - change.Span.Length; if (change.Span.Start < start) { start = change.Span.Start; } if (change.Span.End > end) { end = change.Span.End; } } if (start > end) { // there were no changes. return default(TextChangeRange); } var combined = TextSpan.FromBounds(start, end); var newLen = combined.Length + diff; return new TextChangeRange(combined, newLen); } private string GetDebuggerDisplay() { return $"new TextChangeRange(new TextSpan({Span.Start}, {Span.Length}), {NewLength})"; } public override string ToString() { return $"TextChangeRange(Span={Span}, NewLength={NewLength})"; } } }
-1
dotnet/roslyn
55,132
Support lambda expressions and method groups as `var` initializers
```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
cston
2021-07-27T03:12:21Z
2021-07-27T18:26:42Z
61a565cfcd777158cb6354351436aff997ad7bf6
5840335153dcca42570a853cdacd06d660fe9596
Support lambda expressions and method groups as `var` initializers. ```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
./src/Analyzers/CSharp/Tests/UseImplicitOrExplicitType/UseExplicitTypeTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.CodeStyle; using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.CSharp.Diagnostics.TypeStyle; using Microsoft.CodeAnalysis.CSharp.TypeStyle; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; using Xunit.Abstractions; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics.UseExplicitType { public partial class UseExplicitTypeTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest { public UseExplicitTypeTests(ITestOutputHelper logger) : base(logger) { } internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace) => (new CSharpUseExplicitTypeDiagnosticAnalyzer(), new UseExplicitTypeCodeFixProvider()); private readonly CodeStyleOption2<bool> offWithSilent = new CodeStyleOption2<bool>(false, NotificationOption2.Silent); private readonly CodeStyleOption2<bool> onWithInfo = new CodeStyleOption2<bool>(true, NotificationOption2.Suggestion); private readonly CodeStyleOption2<bool> offWithInfo = new CodeStyleOption2<bool>(false, NotificationOption2.Suggestion); private readonly CodeStyleOption2<bool> offWithWarning = new CodeStyleOption2<bool>(false, NotificationOption2.Warning); private readonly CodeStyleOption2<bool> offWithError = new CodeStyleOption2<bool>(false, NotificationOption2.Error); // specify all options explicitly to override defaults. private OptionsCollection ExplicitTypeEverywhere() => new OptionsCollection(GetLanguage()) { { CSharpCodeStyleOptions.VarElsewhere, offWithInfo }, { CSharpCodeStyleOptions.VarWhenTypeIsApparent, offWithInfo }, { CSharpCodeStyleOptions.VarForBuiltInTypes, offWithInfo }, }; private OptionsCollection ExplicitTypeExceptWhereApparent() => new OptionsCollection(GetLanguage()) { { CSharpCodeStyleOptions.VarElsewhere, offWithInfo }, { CSharpCodeStyleOptions.VarWhenTypeIsApparent, onWithInfo }, { CSharpCodeStyleOptions.VarForBuiltInTypes, offWithInfo }, }; private OptionsCollection ExplicitTypeForBuiltInTypesOnly() => new OptionsCollection(GetLanguage()) { { CSharpCodeStyleOptions.VarElsewhere, onWithInfo }, { CSharpCodeStyleOptions.VarWhenTypeIsApparent, onWithInfo }, { CSharpCodeStyleOptions.VarForBuiltInTypes, offWithInfo }, }; private OptionsCollection ExplicitTypeEnforcements() => new OptionsCollection(GetLanguage()) { { CSharpCodeStyleOptions.VarElsewhere, offWithWarning }, { CSharpCodeStyleOptions.VarWhenTypeIsApparent, offWithError }, { CSharpCodeStyleOptions.VarForBuiltInTypes, offWithInfo }, }; private OptionsCollection ExplicitTypeSilentEnforcement() => new OptionsCollection(GetLanguage()) { { CSharpCodeStyleOptions.VarElsewhere, offWithSilent }, { CSharpCodeStyleOptions.VarWhenTypeIsApparent, offWithSilent }, { CSharpCodeStyleOptions.VarForBuiltInTypes, offWithSilent }, }; #region Error Cases [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] public async Task NotOnFieldDeclaration() { await TestMissingInRegularAndScriptAsync( @"using System; class Program { [|var|] _myfield = 5; }", new TestParameters(options: ExplicitTypeEverywhere())); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] public async Task NotOnFieldLikeEvents() { await TestMissingInRegularAndScriptAsync( @"using System; class Program { public event [|var|] _myevent; }", new TestParameters(options: ExplicitTypeEverywhere())); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] public async Task NotOnAnonymousMethodExpression() { await TestMissingInRegularAndScriptAsync( @"using System; class Program { void Method() { [|var|] comparer = delegate (string value) { return value != ""0""; }; } }", new TestParameters(options: ExplicitTypeEverywhere())); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] public async Task NotOnLambdaExpression() { await TestMissingInRegularAndScriptAsync( @"using System; class Program { void Method() { [|var|] x = y => y * y; } }", new TestParameters(options: ExplicitTypeEverywhere())); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] public async Task NotOnDeclarationWithMultipleDeclarators() { await TestMissingInRegularAndScriptAsync( @"using System; class Program { void Method() { [|var|] x = 5, y = x; } }", new TestParameters(options: ExplicitTypeEverywhere())); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] public async Task NotOnDeclarationWithoutInitializer() { await TestMissingInRegularAndScriptAsync( @"using System; class Program { void Method() { [|var|] x; } }", new TestParameters(options: ExplicitTypeEverywhere())); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] public async Task NotDuringConflicts() { await TestMissingInRegularAndScriptAsync( @"using System; class Program { void Method() { [|var|] p = new var(); } class var { } }", new TestParameters(options: ExplicitTypeEverywhere())); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] public async Task NotIfAlreadyExplicitlyTyped() { await TestMissingInRegularAndScriptAsync( @"using System; class Program { void Method() { [|Program|] p = new Program(); } }", new TestParameters(options: ExplicitTypeEverywhere())); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] [WorkItem(27221, "https://github.com/dotnet/roslyn/issues/27221")] public async Task NotIfRefTypeAlreadyExplicitlyTyped() { await TestMissingInRegularAndScriptAsync( @"using System; struct Program { void Method() { ref [|Program|] p = Ref(); } ref Program Ref() => throw null; }", new TestParameters(options: ExplicitTypeEverywhere())); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] public async Task NotOnRHS() { await TestMissingInRegularAndScriptAsync( @"using System; class C { void M() { var c = new [|var|](); } } class var { }"); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] public async Task NotOnErrorSymbol() { await TestMissingInRegularAndScriptAsync( @"using System; class Program { void Method() { [|var|] x = new Goo(); } }", new TestParameters(options: ExplicitTypeEverywhere())); } [WorkItem(29718, "https://github.com/dotnet/roslyn/issues/29718")] [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] public async Task NotOnErrorConvertedType_ForEachVariableStatement() { await TestMissingInRegularAndScriptAsync( @"using System; using System.Collections.Generic; class C { void M() { // Error CS1061: 'KeyValuePair<int, int>' does not contain a definition for 'Deconstruct' and no accessible extension method 'Deconstruct' accepting a first argument of type 'KeyValuePair<int, int>' could be found (are you missing a using directive or an assembly reference?) // Error CS8129: No suitable 'Deconstruct' instance or extension method was found for type 'KeyValuePair<int, int>', with 2 out parameters and a void return type. foreach ([|var|] (key, value) in new Dictionary<int, int>()) { } } }", new TestParameters(options: ExplicitTypeEverywhere())); } [WorkItem(29718, "https://github.com/dotnet/roslyn/issues/29718")] [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] public async Task NotOnErrorConvertedType_AssignmentExpressionStatement() { await TestMissingInRegularAndScriptAsync( @"using System; using System.Collections.Generic; class C { void M(C c) { // 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?) // Error CS8129: No suitable 'Deconstruct' instance or extension method was found for type 'C', with 2 out parameters and a void return type. [|var|] (key, value) = c; } }", new TestParameters(options: ExplicitTypeEverywhere())); } #endregion [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] [WorkItem(23907, "https://github.com/dotnet/roslyn/issues/23907")] public async Task InArrayType() { var before = @" class Program { void Method() { [|var|] x = new Program[0]; } }"; var after = @" class Program { void Method() { Program[] x = new Program[0]; } }"; // The type is apparent and not intrinsic await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere()); await TestMissingInRegularAndScriptAsync(before, new TestParameters(options: ExplicitTypeForBuiltInTypesOnly())); await TestMissingInRegularAndScriptAsync(before, new TestParameters(options: ExplicitTypeExceptWhereApparent())); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] [WorkItem(23907, "https://github.com/dotnet/roslyn/issues/23907")] public async Task InArrayTypeWithIntrinsicType() { var before = @" class Program { void Method() { [|var|] x = new int[0]; } }"; var after = @" class Program { void Method() { int[] x = new int[0]; } }"; await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere()); await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeForBuiltInTypesOnly()); await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent()); // preference for builtin types dominates } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] [WorkItem(23907, "https://github.com/dotnet/roslyn/issues/23907")] public async Task InNullableIntrinsicType() { var before = @" class Program { void Method(int? x) { [|var|] y = x; } }"; var after = @" class Program { void Method(int? x) { int? y = x; } }"; // The type is intrinsic and not apparent await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere()); await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeForBuiltInTypesOnly()); await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] [WorkItem(42986, "https://github.com/dotnet/roslyn/issues/42986")] public async Task InNativeIntIntrinsicType() { var before = @" class Program { void Method(nint x) { [|var|] y = x; } }"; var after = @" class Program { void Method(nint x) { nint y = x; } }"; // The type is intrinsic and not apparent await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere()); await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeForBuiltInTypesOnly()); await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] [WorkItem(42986, "https://github.com/dotnet/roslyn/issues/42986")] public async Task InNativeUnsignedIntIntrinsicType() { var before = @" class Program { void Method(nuint x) { [|var|] y = x; } }"; var after = @" class Program { void Method(nuint x) { nuint y = x; } }"; // The type is intrinsic and not apparent await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere()); await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeForBuiltInTypesOnly()); await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] [WorkItem(27221, "https://github.com/dotnet/roslyn/issues/27221")] public async Task WithRefIntrinsicType() { var before = @" class Program { void Method() { ref [|var|] y = Ref(); } ref int Ref() => throw null; }"; var after = @" class Program { void Method() { ref int y = Ref(); } ref int Ref() => throw null; }"; // The type is intrinsic and not apparent await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere()); await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeForBuiltInTypesOnly()); await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] [WorkItem(27221, "https://github.com/dotnet/roslyn/issues/27221")] public async Task WithRefIntrinsicTypeInForeach() { var before = @" class E { public ref int Current => throw null; public bool MoveNext() => throw null; public E GetEnumerator() => throw null; void M() { foreach (ref [|var|] x in this) { } } }"; var after = @" class E { public ref int Current => throw null; public bool MoveNext() => throw null; public E GetEnumerator() => throw null; void M() { foreach (ref int x in this) { } } }"; // The type is intrinsic and not apparent await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere()); await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeForBuiltInTypesOnly()); await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] [WorkItem(23907, "https://github.com/dotnet/roslyn/issues/23907")] public async Task InArrayOfNullableIntrinsicType() { var before = @" class Program { void Method(int?[] x) { [|var|] y = x; } }"; var after = @" class Program { void Method(int?[] x) { int?[] y = x; } }"; // The type is intrinsic and not apparent await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere()); await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeForBuiltInTypesOnly()); await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] [WorkItem(23907, "https://github.com/dotnet/roslyn/issues/23907")] public async Task InNullableCustomType() { var before = @" struct Program { void Method(Program? x) { [|var|] y = x; } }"; var after = @" struct Program { void Method(Program? x) { Program? y = x; } }"; // The type is not intrinsic and not apparent await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere()); await TestMissingInRegularAndScriptAsync(before, new TestParameters(options: ExplicitTypeForBuiltInTypesOnly())); await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] [WorkItem(40477, "https://github.com/dotnet/roslyn/issues/40477")] public async Task NullableType() { var before = @" #nullable enable class Program { void Method(Program x) { [|var|] y = x; y = null; } }"; var after = @" #nullable enable class Program { void Method(Program x) { Program? y = x; y = null; } }"; // The type is not intrinsic and not apparent await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere()); await TestMissingInRegularAndScriptAsync(before, new TestParameters(options: ExplicitTypeForBuiltInTypesOnly())); await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] [WorkItem(40477, "https://github.com/dotnet/roslyn/issues/40477")] public async Task ObliviousType() { var before = @" #nullable enable class Program { void Method(Program x) { #nullable disable [|var|] y = x; y = null; } }"; var after = @" #nullable enable class Program { void Method(Program x) { #nullable disable Program y = x; y = null; } }"; // The type is not intrinsic and not apparent await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere()); await TestMissingInRegularAndScriptAsync(before, new TestParameters(options: ExplicitTypeForBuiltInTypesOnly())); await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] [WorkItem(40477, "https://github.com/dotnet/roslyn/issues/40477")] public async Task NotNullableType() { var before = @" class Program { void Method(Program x) { #nullable enable [|var|] y = x; y = null; } }"; var after = @" class Program { void Method(Program x) { #nullable enable Program? y = x; y = null; } }"; // The type is not intrinsic and not apparent await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere()); await TestMissingInRegularAndScriptAsync(before, new TestParameters(options: ExplicitTypeForBuiltInTypesOnly())); await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] [WorkItem(40477, "https://github.com/dotnet/roslyn/issues/40477")] public async Task NullableType_OutVar() { var before = @" #nullable enable class Program { void Method(out Program? x) { Method(out [|var|] y1); throw null!; } }"; var after = @" #nullable enable class Program { void Method(out Program? x) { Method(out Program? y1); throw null!; } }"; // The type is not intrinsic and not apparent await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere()); await TestMissingInRegularAndScriptAsync(before, new TestParameters(options: ExplicitTypeForBuiltInTypesOnly())); await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] [WorkItem(40477, "https://github.com/dotnet/roslyn/issues/40477")] public async Task NotNullableType_OutVar() { var before = @" #nullable enable class Program { void Method(out Program x) { Method(out [|var|] y1); throw null!; } }"; var after = @" #nullable enable class Program { void Method(out Program x) { Method(out Program? y1); throw null!; } }"; // The type is not intrinsic and not apparent await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere()); await TestMissingInRegularAndScriptAsync(before, new TestParameters(options: ExplicitTypeForBuiltInTypesOnly())); await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] [WorkItem(40477, "https://github.com/dotnet/roslyn/issues/40477")] public async Task ObliviousType_OutVar() { var before = @" class Program { void Method(out Program x) { Method(out [|var|] y1); throw null; } }"; var after = @" class Program { void Method(out Program x) { Method(out Program y1); throw null; } }"; // The type is not intrinsic and not apparent await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere()); await TestMissingInRegularAndScriptAsync(before, new TestParameters(options: ExplicitTypeForBuiltInTypesOnly())); await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent()); } [WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/40925"), Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] [WorkItem(40477, "https://github.com/dotnet/roslyn/issues/40477")] [WorkItem(40925, "https://github.com/dotnet/roslyn/issues/40925")] public async Task NullableTypeAndNotNullableType_VarDeconstruction() { var before = @" #nullable enable class Program2 { } class Program { void Method(Program? x, Program2 x2) { [|var|] (y1, y2) = (x, x2); } }"; var after = @" #nullable enable class Program2 { } class Program { void Method(Program? x, Program2 x2) { (Program? y1, Program2? y2) = (x, x2); } }"; // The type is not intrinsic and not apparent await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere()); await TestMissingInRegularAndScriptAsync(before, new TestParameters(options: ExplicitTypeForBuiltInTypesOnly())); await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] [WorkItem(40477, "https://github.com/dotnet/roslyn/issues/40477")] public async Task ObliviousType_VarDeconstruction() { var before = @" #nullable enable class Program2 { } class Program { void Method(Program x, Program2 x2) { #nullable disable [|var|] (y1, y2) = (x, x2); } }"; var after = @" #nullable enable class Program2 { } class Program { void Method(Program x, Program2 x2) { #nullable disable (Program y1, Program2 y2) = (x, x2); } }"; // The type is not intrinsic and not apparent await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere()); await TestMissingInRegularAndScriptAsync(before, new TestParameters(options: ExplicitTypeForBuiltInTypesOnly())); await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] [WorkItem(40477, "https://github.com/dotnet/roslyn/issues/40477")] public async Task ObliviousType_Deconstruction() { var before = @" #nullable enable class Program { void Method(Program x) { #nullable disable ([|var|] y1, Program y2) = (x, x); } }"; var after = @" #nullable enable class Program { void Method(Program x) { #nullable disable (Program y1, Program y2) = (x, x); } }"; // The type is not intrinsic and not apparent await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere()); await TestMissingInRegularAndScriptAsync(before, new TestParameters(options: ExplicitTypeForBuiltInTypesOnly())); await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] [WorkItem(40477, "https://github.com/dotnet/roslyn/issues/40477")] public async Task NotNullableType_Deconstruction() { var before = @" class Program { void Method(Program x) { #nullable enable ([|var|] y1, Program y2) = (x, x); } }"; var after = @" class Program { void Method(Program x) { #nullable enable (Program? y1, Program y2) = (x, x); } }"; // The type is not intrinsic and not apparent await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere()); await TestMissingInRegularAndScriptAsync(before, new TestParameters(options: ExplicitTypeForBuiltInTypesOnly())); await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] [WorkItem(40477, "https://github.com/dotnet/roslyn/issues/40477")] public async Task NullableType_Deconstruction() { var before = @" class Program { void Method(Program? x) { #nullable enable ([|var|] y1, Program y2) = (x, x); } }"; var after = @" class Program { void Method(Program? x) { #nullable enable (Program? y1, Program y2) = (x, x); } }"; // The type is not intrinsic and not apparent await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere()); await TestMissingInRegularAndScriptAsync(before, new TestParameters(options: ExplicitTypeForBuiltInTypesOnly())); await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] [WorkItem(40477, "https://github.com/dotnet/roslyn/issues/40477")] public async Task ObliviousType_Foreach() { var before = @" #nullable enable class Program { void Method(System.Collections.Generic.IEnumerable<Program> x) { #nullable disable foreach ([|var|] y in x) { } } }"; var after = @" #nullable enable class Program { void Method(System.Collections.Generic.IEnumerable<Program> x) { #nullable disable foreach ([|Program|] y in x) { } } }"; // The type is not intrinsic and not apparent await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere()); await TestMissingInRegularAndScriptAsync(before, new TestParameters(options: ExplicitTypeForBuiltInTypesOnly())); await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] [WorkItem(40477, "https://github.com/dotnet/roslyn/issues/40477")] public async Task NotNullableType_Foreach() { var before = @" class Program { void Method(System.Collections.Generic.IEnumerable<Program> x) { #nullable enable foreach ([|var|] y in x) { } } }"; var after = @" class Program { void Method(System.Collections.Generic.IEnumerable<Program> x) { #nullable enable foreach (Program? y in x) { } } }"; // The type is not intrinsic and not apparent await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere()); await TestMissingInRegularAndScriptAsync(before, new TestParameters(options: ExplicitTypeForBuiltInTypesOnly())); await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] [WorkItem(40477, "https://github.com/dotnet/roslyn/issues/40477")] public async Task NullableType_Foreach() { var before = @" class Program { void Method(System.Collections.Generic.IEnumerable<Program> x) { #nullable enable foreach ([|var|] y in x) { } } }"; var after = @" class Program { void Method(System.Collections.Generic.IEnumerable<Program> x) { #nullable enable foreach (Program? y in x) { } } }"; // The type is not intrinsic and not apparent await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere()); await TestMissingInRegularAndScriptAsync(before, new TestParameters(options: ExplicitTypeForBuiltInTypesOnly())); await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent()); } [WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/37491"), Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] [WorkItem(40477, "https://github.com/dotnet/roslyn/issues/40477")] public async Task NotNullableType_ForeachVarDeconstruction() { // Semantic model doesn't yet handle var deconstruction foreach // https://github.com/dotnet/roslyn/issues/37491 // https://github.com/dotnet/roslyn/issues/35010 var before = @" class Program { void Method(System.Collections.Generic.IEnumerable<(Program, Program)> x) { #nullable enable foreach ([|var|] (y1, y2) in x) { } } }"; var after = @" class Program { void Method(System.Collections.Generic.IEnumerable<(Program, Program)> x) { #nullable enable foreach ((Program? y1, Program? y2) in x) { } } }"; // The type is not intrinsic and not apparent await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere()); await TestMissingInRegularAndScriptAsync(before, new TestParameters(options: ExplicitTypeForBuiltInTypesOnly())); await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] [WorkItem(40477, "https://github.com/dotnet/roslyn/issues/40477")] public async Task NotNullableType_ForeachDeconstruction() { var before = @" class Program { void Method(System.Collections.Generic.IEnumerable<(Program, Program)> x) { #nullable enable foreach (([|var|] y1, var y2) in x) { } } }"; var after = @" class Program { void Method(System.Collections.Generic.IEnumerable<(Program, Program)> x) { #nullable enable foreach ((Program? y1, var y2) in x) { } } }"; // The type is not intrinsic and not apparent await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere()); await TestMissingInRegularAndScriptAsync(before, new TestParameters(options: ExplicitTypeForBuiltInTypesOnly())); await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] [WorkItem(23907, "https://github.com/dotnet/roslyn/issues/23907")] public async Task InPointerTypeWithIntrinsicType() { var before = @" unsafe class Program { void Method(int* y) { [|var|] x = y; } }"; var after = @" unsafe class Program { void Method(int* y) { int* x = y; } }"; // The type is intrinsic and not apparent await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere()); await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeForBuiltInTypesOnly()); await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent()); // preference for builtin types dominates } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] [WorkItem(23907, "https://github.com/dotnet/roslyn/issues/23907")] public async Task InPointerTypeWithCustomType() { var before = @" unsafe class Program { void Method(Program* y) { [|var|] x = y; } }"; var after = @" unsafe class Program { void Method(Program* y) { Program* x = y; } }"; // The type is not intrinsic and not apparent await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere()); await TestMissingInRegularAndScriptAsync(before, new TestParameters(options: ExplicitTypeForBuiltInTypesOnly())); await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] [WorkItem(23893, "https://github.com/dotnet/roslyn/issues/23893")] public async Task InOutParameter() { var before = @" class Program { void Method(out int x) { Method(out [|var|] x); } }"; var after = @" class Program { void Method(out int x) { Method(out int x); } }"; await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere()); await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeForBuiltInTypesOnly()); await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] public async Task NotOnDynamic() { await TestMissingInRegularAndScriptAsync( @"using System; class Program { void Method() { [|dynamic|] x = 1; } }", new TestParameters(options: ExplicitTypeEverywhere())); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] public async Task NotOnForEachVarWithAnonymousType() { await TestMissingInRegularAndScriptAsync( @"using System; using System.Linq; class Program { void Method() { var values = Enumerable.Range(1, 5).Select(i => new { Value = i }); foreach ([|var|] value in values) { Console.WriteLine(value.Value); } } }", new TestParameters(options: ExplicitTypeEverywhere())); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] [WorkItem(23752, "https://github.com/dotnet/roslyn/issues/23752")] public async Task OnDeconstructionVarParens() { await TestInRegularAndScriptAsync( @"using System; class Program { void M() { [|var|] (x, y) = new Program(); } void Deconstruct(out int i, out string s) { i = 1; s = ""hello""; } }", @"using System; class Program { void M() { (int x, string y) = new Program(); } void Deconstruct(out int i, out string s) { i = 1; s = ""hello""; } }", options: ExplicitTypeEverywhere()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] public async Task OnDeconstructionVar() { await TestInRegularAndScriptAsync( @"using System; class Program { void M() { ([|var|] x, var y) = new Program(); } void Deconstruct(out int i, out string s) { i = 1; s = ""hello""; } }", @"using System; class Program { void M() { (int x, var y) = new Program(); } void Deconstruct(out int i, out string s) { i = 1; s = ""hello""; } }", options: ExplicitTypeEverywhere()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] [WorkItem(23752, "https://github.com/dotnet/roslyn/issues/23752")] public async Task OnNestedDeconstructionVar() { await TestInRegularAndScriptAsync( @"using System; class Program { void M() { [|var|] (x, (y, z)) = new Program(); } void Deconstruct(out int i, out Program s) { i = 1; s = null; } }", @"using System; class Program { void M() { (int x, (int y, Program z)) = new Program(); } void Deconstruct(out int i, out Program s) { i = 1; s = null; } }", options: ExplicitTypeEverywhere()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] [WorkItem(23752, "https://github.com/dotnet/roslyn/issues/23752")] public async Task OnBadlyFormattedNestedDeconstructionVar() { await TestInRegularAndScriptAsync( @"using System; class Program { void M() { [|var|](x,(y,z)) = new Program(); } void Deconstruct(out int i, out Program s) { i = 1; s = null; } }", @"using System; class Program { void M() { (int x, (int y, Program z)) = new Program(); } void Deconstruct(out int i, out Program s) { i = 1; s = null; } }", options: ExplicitTypeEverywhere()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] [WorkItem(23752, "https://github.com/dotnet/roslyn/issues/23752")] public async Task OnForeachNestedDeconstructionVar() { await TestInRegularAndScriptAsync( @"using System; class Program { void M() { foreach ([|var|] (x, (y, z)) in new[] { new Program() } { } } void Deconstruct(out int i, out Program s) { i = 1; s = null; } }", @"using System; class Program { void M() { foreach ((int x, (int y, Program z)) in new[] { new Program() } { } } void Deconstruct(out int i, out Program s) { i = 1; s = null; } }", options: ExplicitTypeEverywhere()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] [WorkItem(23752, "https://github.com/dotnet/roslyn/issues/23752")] public async Task OnNestedDeconstructionVarWithTrivia() { await TestInRegularAndScriptAsync( @"using System; class Program { void M() { /*before*/[|var|]/*after*/ (/*x1*/x/*x2*/, /*yz1*/(/*y1*/y/*y2*/, /*z1*/z/*z2*/)/*yz2*/) /*end*/ = new Program(); } void Deconstruct(out int i, out Program s) { i = 1; s = null; } }", @"using System; class Program { void M() { /*before*//*after*/(/*x1*/int x/*x2*/, /*yz1*/(/*y1*/int y/*y2*/, /*z1*/Program z/*z2*/)/*yz2*/) /*end*/ = new Program(); } void Deconstruct(out int i, out Program s) { i = 1; s = null; } }", options: ExplicitTypeEverywhere()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] [WorkItem(23752, "https://github.com/dotnet/roslyn/issues/23752")] public async Task OnDeconstructionVarWithDiscard() { await TestInRegularAndScriptAsync( @"using System; class Program { void M() { [|var|] (x, _) = new Program(); } void Deconstruct(out int i, out string s) { i = 1; s = ""hello""; } }", @"using System; class Program { void M() { (int x, string _) = new Program(); } void Deconstruct(out int i, out string s) { i = 1; s = ""hello""; } }", options: ExplicitTypeEverywhere()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] [WorkItem(23752, "https://github.com/dotnet/roslyn/issues/23752")] public async Task OnDeconstructionVarWithErrorType() { await TestInRegularAndScriptAsync( @"using System; class Program { void M() { [|var|] (x, y) = new Program(); } void Deconstruct(out int i, out Error s) { i = 1; s = null; } }", @"using System; class Program { void M() { (int x, Error y) = new Program(); } void Deconstruct(out int i, out Error s) { i = 1; s = null; } }", options: ExplicitTypeEverywhere()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] public async Task OnForEachVarWithExplicitType() { await TestInRegularAndScriptAsync( @"using System; using System.Linq; class Program { void Method() { var values = Enumerable.Range(1, 5); foreach ([|var|] value in values) { Console.WriteLine(value.Value); } } }", @"using System; using System.Linq; class Program { void Method() { var values = Enumerable.Range(1, 5); foreach (int value in values) { Console.WriteLine(value.Value); } } }", options: ExplicitTypeEverywhere()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] public async Task NotOnAnonymousType() { await TestMissingInRegularAndScriptAsync( @"using System; class Program { void Method() { [|var|] x = new { Amount = 108, Message = ""Hello"" }; } }", new TestParameters(options: ExplicitTypeEverywhere())); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] public async Task NotOnArrayOfAnonymousType() { await TestMissingInRegularAndScriptAsync( @"using System; class Program { void Method() { [|var|] x = new[] { new { name = ""apple"", diam = 4 }, new { name = ""grape"", diam = 1 } }; } }", new TestParameters(options: ExplicitTypeEverywhere())); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] public async Task NotOnEnumerableOfAnonymousTypeFromAQueryExpression() { await TestMissingInRegularAndScriptAsync( @"using System; using System.Collections.Generic; using System.Linq; class Program { void Method() { var products = new List<Product>(); [|var|] productQuery = from prod in products select new { prod.Color, prod.Price }; } } class Product { public ConsoleColor Color { get; set; } public int Price { get; set; } }"); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] public async Task SuggestExplicitTypeOnLocalWithIntrinsicTypeString() { await TestInRegularAndScriptAsync( @"using System; class C { static void M() { [|var|] s = ""hello""; } }", @"using System; class C { static void M() { string s = ""hello""; } }", options: ExplicitTypeEverywhere()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] public async Task SuggestExplicitTypeOnIntrinsicType() { await TestInRegularAndScriptAsync( @"using System; class C { static void M() { [|var|] s = 5; } }", @"using System; class C { static void M() { int s = 5; } }", options: ExplicitTypeEverywhere()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] public async Task SuggestExplicitTypeOnFrameworkType() { await TestInRegularAndScriptAsync( @"using System.Collections.Generic; class C { static void M() { [|var|] c = new List<int>(); } }", @"using System.Collections.Generic; class C { static void M() { List<int> c = new List<int>(); } }", options: ExplicitTypeEverywhere()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] public async Task SuggestExplicitTypeOnUserDefinedType() { await TestInRegularAndScriptAsync( @"using System; class C { void M() { [|var|] c = new C(); } }", @"using System; class C { void M() { C c = new C(); } }", options: ExplicitTypeEverywhere()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] public async Task SuggestExplicitTypeOnGenericType() { await TestInRegularAndScriptAsync( @"using System; class C<T> { static void M() { [|var|] c = new C<int>(); } }", @"using System; class C<T> { static void M() { C<int> c = new C<int>(); } }", options: ExplicitTypeEverywhere()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] public async Task SuggestExplicitTypeOnSingleDimensionalArrayTypeWithNewOperator() { await TestInRegularAndScriptAsync( @"using System; class C { static void M() { [|var|] n1 = new int[4] { 2, 4, 6, 8 }; } }", @"using System; class C { static void M() { int[] n1 = new int[4] { 2, 4, 6, 8 }; } }", options: ExplicitTypeEverywhere()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] public async Task SuggestExplicitTypeOnSingleDimensionalArrayTypeWithNewOperator2() { await TestInRegularAndScriptAsync( @"using System; class C { static void M() { [|var|] n1 = new[] { 2, 4, 6, 8 }; } }", @"using System; class C { static void M() { int[] n1 = new[] { 2, 4, 6, 8 }; } }", options: ExplicitTypeEverywhere()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] public async Task SuggestExplicitTypeOnSingleDimensionalJaggedArrayType() { await TestInRegularAndScriptAsync( @"using System; class C { static void M() { [|var|] cs = new[] { new[] { 1, 2, 3, 4 }, new[] { 5, 6, 7, 8 } }; } }", @"using System; class C { static void M() { int[][] cs = new[] { new[] { 1, 2, 3, 4 }, new[] { 5, 6, 7, 8 } }; } }", options: ExplicitTypeEverywhere()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] public async Task SuggestExplicitTypeOnDeclarationWithObjectInitializer() { await TestInRegularAndScriptAsync( @"using System; class C { static void M() { [|var|] cc = new Customer { City = ""Chennai"" }; } private class Customer { public string City { get; set; } } }", @"using System; class C { static void M() { Customer cc = new Customer { City = ""Chennai"" }; } private class Customer { public string City { get; set; } } }", options: ExplicitTypeEverywhere()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] public async Task SuggestExplicitTypeOnDeclarationWithCollectionInitializer() { await TestInRegularAndScriptAsync( @"using System; using System.Collections.Generic; class C { static void M() { [|var|] digits = new List<int> { 1, 2, 3 }; } }", @"using System; using System.Collections.Generic; class C { static void M() { List<int> digits = new List<int> { 1, 2, 3 }; } }", options: ExplicitTypeEverywhere()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] public async Task SuggestExplicitTypeOnDeclarationWithCollectionAndObjectInitializers() { await TestInRegularAndScriptAsync( @"using System; using System.Collections.Generic; class C { static void M() { [|var|] cs = new List<Customer> { new Customer { City = ""Chennai"" } }; } private class Customer { public string City { get; set; } } }", @"using System; using System.Collections.Generic; class C { static void M() { List<Customer> cs = new List<Customer> { new Customer { City = ""Chennai"" } }; } private class Customer { public string City { get; set; } } }", options: ExplicitTypeEverywhere()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] public async Task SuggestExplicitTypeOnForStatement() { await TestInRegularAndScriptAsync( @"using System; class C { static void M() { for ([|var|] i = 0; i < 5; i++) { } } }", @"using System; class C { static void M() { for (int i = 0; i < 5; i++) { } } }", options: ExplicitTypeEverywhere()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] public async Task SuggestExplicitTypeOnForeachStatement() { await TestInRegularAndScriptAsync( @"using System; using System.Collections.Generic; class C { static void M() { var l = new List<int> { 1, 3, 5 }; foreach ([|var|] item in l) { } } }", @"using System; using System.Collections.Generic; class C { static void M() { var l = new List<int> { 1, 3, 5 }; foreach (int item in l) { } } }", options: ExplicitTypeEverywhere()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] public async Task SuggestExplicitTypeOnQueryExpression() { await TestInRegularAndScriptAsync( @"using System; using System.Collections.Generic; using System.Linq; class C { static void M() { var customers = new List<Customer>(); [|var|] expr = from c in customers where c.City == ""London"" select c; } private class Customer { public string City { get; set; } } } }", @"using System; using System.Collections.Generic; using System.Linq; class C { static void M() { var customers = new List<Customer>(); IEnumerable<Customer> expr = from c in customers where c.City == ""London"" select c; } private class Customer { public string City { get; set; } } } }", options: ExplicitTypeEverywhere()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] public async Task SuggestExplicitTypeInUsingStatement() { await TestInRegularAndScriptAsync( @"using System; class C { static void M() { using ([|var|] r = new Res()) { } } private class Res : IDisposable { public void Dispose() { throw new NotImplementedException(); } } }", @"using System; class C { static void M() { using (Res r = new Res()) { } } private class Res : IDisposable { public void Dispose() { throw new NotImplementedException(); } } }", options: ExplicitTypeEverywhere()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] public async Task SuggestExplicitTypeOnInterpolatedString() { await TestInRegularAndScriptAsync( @"using System; class Program { void Method() { [|var|] s = $""Hello, {name}"" } }", @"using System; class Program { void Method() { string s = $""Hello, {name}"" } }", options: ExplicitTypeEverywhere()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] public async Task SuggestExplicitTypeOnExplicitConversion() { await TestInRegularAndScriptAsync( @"using System; class C { static void M() { double x = 1234.7; [|var|] a = (int)x; } }", @"using System; class C { static void M() { double x = 1234.7; int a = (int)x; } }", options: ExplicitTypeEverywhere()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] public async Task SuggestExplicitTypeOnConditionalAccessExpression() { await TestInRegularAndScriptAsync( @"using System; class C { static void M() { C obj = new C(); [|var|] anotherObj = obj?.Test(); } C Test() { return this; } }", @"using System; class C { static void M() { C obj = new C(); C anotherObj = obj?.Test(); } C Test() { return this; } }", options: ExplicitTypeEverywhere()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] public async Task SuggestExplicitTypeInCheckedExpression() { await TestInRegularAndScriptAsync( @"using System; class C { static void M() { long number1 = int.MaxValue + 20L; [|var|] intNumber = checked((int)number1); } }", @"using System; class C { static void M() { long number1 = int.MaxValue + 20L; int intNumber = checked((int)number1); } }", options: ExplicitTypeEverywhere()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] public async Task SuggestExplicitTypeInAwaitExpression() { await TestInRegularAndScriptAsync( @"using System; using System.Threading.Tasks; class C { public async void ProcessRead() { [|var|] text = await ReadTextAsync(null); } private async Task<string> ReadTextAsync(string filePath) { return string.Empty; } }", @"using System; using System.Threading.Tasks; class C { public async void ProcessRead() { string text = await ReadTextAsync(null); } private async Task<string> ReadTextAsync(string filePath) { return string.Empty; } }", options: ExplicitTypeEverywhere()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] public async Task SuggestExplicitTypeInBuiltInNumericType() { await TestInRegularAndScriptAsync( @"using System; class C { public void ProcessRead() { [|var|] text = 1; } }", @"using System; class C { public void ProcessRead() { int text = 1; } }", options: ExplicitTypeForBuiltInTypesOnly()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] public async Task SuggestExplicitTypeInBuiltInCharType() { await TestInRegularAndScriptAsync( @"using System; class C { public void ProcessRead() { [|var|] text = GetChar(); } public char GetChar() => 'c'; }", @"using System; class C { public void ProcessRead() { char text = GetChar(); } public char GetChar() => 'c'; }", options: ExplicitTypeForBuiltInTypesOnly()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] public async Task SuggestExplicitTypeInBuiltInType_string() { // though string isn't an intrinsic type per the compiler // we in the IDE treat it as an intrinsic type for this feature. await TestInRegularAndScriptAsync( @"using System; class C { public void ProcessRead() { [|var|] text = string.Empty; } }", @"using System; class C { public void ProcessRead() { string text = string.Empty; } }", options: ExplicitTypeForBuiltInTypesOnly()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] public async Task SuggestExplicitTypeInBuiltInType_object() { // object isn't an intrinsic type per the compiler // we in the IDE treat it as an intrinsic type for this feature. await TestInRegularAndScriptAsync( @"using System; class C { public void ProcessRead() { object j = new C(); [|var|] text = j; } }", @"using System; class C { public void ProcessRead() { object j = new C(); object text = j; } }", options: ExplicitTypeForBuiltInTypesOnly()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] public async Task SuggestExplicitTypeNotificationLevelSilent() { var source = @"using System; class C { static void M() { [|var|] n1 = new C(); } }"; await TestDiagnosticInfoAsync(source, options: ExplicitTypeSilentEnforcement(), diagnosticId: IDEDiagnosticIds.UseExplicitTypeDiagnosticId, diagnosticSeverity: DiagnosticSeverity.Hidden); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] public async Task SuggestExplicitTypeNotificationLevelInfo() { var source = @"using System; class C { static void M() { [|var|] s = 5; } }"; await TestDiagnosticInfoAsync(source, options: ExplicitTypeEnforcements(), diagnosticId: IDEDiagnosticIds.UseExplicitTypeDiagnosticId, diagnosticSeverity: DiagnosticSeverity.Info); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] [WorkItem(23907, "https://github.com/dotnet/roslyn/issues/23907")] public async Task SuggestExplicitTypeNotificationLevelWarning() { var source = @"using System; class C { static void M() { [|var|] n1 = new[] { new C() }; // type not apparent and not intrinsic } }"; await TestDiagnosticInfoAsync(source, options: ExplicitTypeEnforcements(), diagnosticId: IDEDiagnosticIds.UseExplicitTypeDiagnosticId, diagnosticSeverity: DiagnosticSeverity.Warning); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] public async Task SuggestExplicitTypeNotificationLevelError() { var source = @"using System; class C { static void M() { [|var|] n1 = new C(); } }"; await TestDiagnosticInfoAsync(source, options: ExplicitTypeEnforcements(), diagnosticId: IDEDiagnosticIds.UseExplicitTypeDiagnosticId, diagnosticSeverity: DiagnosticSeverity.Error); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] public async Task SuggestExplicitTypeOnLocalWithIntrinsicTypeTuple() { await TestInRegularAndScriptAsync( @"class C { static void M() { [|var|] s = (1, ""hello""); } }", @"class C { static void M() { (int, string) s = (1, ""hello""); } }", options: ExplicitTypeEverywhere()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] public async Task SuggestExplicitTypeOnLocalWithIntrinsicTypeTupleWithNames() { await TestInRegularAndScriptAsync( @"class C { static void M() { [|var|] s = (a: 1, b: ""hello""); } }", @"class C { static void M() { (int a, string b) s = (a: 1, b: ""hello""); } }", options: ExplicitTypeEverywhere()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] public async Task SuggestExplicitTypeOnLocalWithIntrinsicTypeTupleWithOneName() { await TestInRegularAndScriptAsync( @"class C { static void M() { [|var|] s = (a: 1, ""hello""); } }", @"class C { static void M() { (int a, string) s = (a: 1, ""hello""); } }", options: ExplicitTypeEverywhere()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] [WorkItem(20437, "https://github.com/dotnet/roslyn/issues/20437")] public async Task SuggestExplicitTypeOnDeclarationExpressionSyntax() { await TestInRegularAndScriptAsync( @"using System; class C { static void M() { DateTime.TryParse(string.Empty, [|out var|] date); } }", @"using System; class C { static void M() { DateTime.TryParse(string.Empty, out DateTime date); } }", options: ExplicitTypeEverywhere()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] [WorkItem(20244, "https://github.com/dotnet/roslyn/issues/20244")] public async Task ExplicitTypeOnPredefinedTypesByTheirMetadataNames1() { await TestMissingInRegularAndScriptAsync( @"using System; class Program { void Method() { [|String|] test = new String(' ', 4); } }", new TestParameters(options: ExplicitTypeForBuiltInTypesOnly())); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] [WorkItem(20244, "https://github.com/dotnet/roslyn/issues/20244")] public async Task ExplicitTypeOnPredefinedTypesByTheirMetadataNames2() { await TestMissingInRegularAndScriptAsync( @"using System; class Program { void Main() { foreach ([|String|] test in new String[] { ""test1"", ""test2"" }) { } } }", new TestParameters(options: ExplicitTypeForBuiltInTypesOnly())); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] [WorkItem(20244, "https://github.com/dotnet/roslyn/issues/20244")] public async Task ExplicitTypeOnPredefinedTypesByTheirMetadataNames3() { await TestMissingInRegularAndScriptAsync( @"using System; class Program { void Main() { [|Int32[]|] array = new[] { 1, 2, 3 }; } }", new TestParameters(options: ExplicitTypeForBuiltInTypesOnly())); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] [WorkItem(20244, "https://github.com/dotnet/roslyn/issues/20244")] public async Task ExplicitTypeOnPredefinedTypesByTheirMetadataNames4() { await TestMissingInRegularAndScriptAsync( @"using System; class Program { void Main() { [|Int32[][]|] a = new Int32[][] { new[] { 1, 2 }, new[] { 3, 4 } }; } }", new TestParameters(options: ExplicitTypeForBuiltInTypesOnly())); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] [WorkItem(20244, "https://github.com/dotnet/roslyn/issues/20244")] public async Task ExplicitTypeOnPredefinedTypesByTheirMetadataNames5() { await TestMissingInRegularAndScriptAsync( @"using System; using System.Collections.Generic; class Program { void Main() { [|IEnumerable<Int32>|] a = new List<Int32> { 1, 2 }.Where(x => x > 1); } }", new TestParameters(options: ExplicitTypeForBuiltInTypesOnly())); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] [WorkItem(20244, "https://github.com/dotnet/roslyn/issues/20244")] public async Task ExplicitTypeOnPredefinedTypesByTheirMetadataNames6() { await TestMissingInRegularAndScriptAsync( @"using System; class Program { void Main() { String name = ""name""; [|String|] s = $""Hello, {name}"" } }", new TestParameters(options: ExplicitTypeForBuiltInTypesOnly())); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] [WorkItem(20244, "https://github.com/dotnet/roslyn/issues/20244")] public async Task ExplicitTypeOnPredefinedTypesByTheirMetadataNames7() { await TestMissingInRegularAndScriptAsync( @"using System; class Program { void Main() { Object name = ""name""; [|String|] s = (String) name; } }", new TestParameters(options: ExplicitTypeForBuiltInTypesOnly())); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] [WorkItem(20244, "https://github.com/dotnet/roslyn/issues/20244")] public async Task ExplicitTypeOnPredefinedTypesByTheirMetadataNames8() { await TestMissingInRegularAndScriptAsync( @"using System; using System.Threading.Tasks; class C { public async void ProcessRead() { [|String|] text = await ReadTextAsync(null); } private async Task<string> ReadTextAsync(string filePath) { return String.Empty; } }", new TestParameters(options: ExplicitTypeForBuiltInTypesOnly())); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] [WorkItem(20244, "https://github.com/dotnet/roslyn/issues/20244")] public async Task ExplicitTypeOnPredefinedTypesByTheirMetadataNames9() { await TestMissingInRegularAndScriptAsync( @"using System; class Program { void Main() { String number = ""12""; Int32.TryParse(name, out [|Int32|] number) } }", new TestParameters(options: ExplicitTypeForBuiltInTypesOnly())); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] [WorkItem(20244, "https://github.com/dotnet/roslyn/issues/20244")] public async Task ExplicitTypeOnPredefinedTypesByTheirMetadataNames10() { await TestMissingInRegularAndScriptAsync( @"using System; class Program { void Main() { for ([|Int32|] i = 0; i < 5; i++) { } } }", new TestParameters(options: ExplicitTypeForBuiltInTypesOnly())); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] [WorkItem(20244, "https://github.com/dotnet/roslyn/issues/20244")] public async Task ExplicitTypeOnPredefinedTypesByTheirMetadataNames11() { await TestMissingInRegularAndScriptAsync( @"using System; using System.Collections.Generic; class Program { void Main() { [|List<Int32>|] a = new List<Int32> { 1, 2 }; } }", new TestParameters(options: ExplicitTypeForBuiltInTypesOnly())); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] [WorkItem(26923, "https://github.com/dotnet/roslyn/issues/26923")] public async Task NoSuggestionOnForeachCollectionExpression() { await TestMissingInRegularAndScriptAsync( @"using System; using System.Collections.Generic; class Program { void Method(List<int> var) { foreach (int value in [|var|]) { Console.WriteLine(value.Value); } } }", new TestParameters(options: ExplicitTypeEverywhere())); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] public async Task NotOnConstVar() { // This error case is handled by a separate code fix (UseExplicitTypeForConst). await TestMissingInRegularAndScriptAsync( @"class C { void M() { const [|var|] v = 0; } }", new TestParameters(options: ExplicitTypeEverywhere())); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.CodeStyle; using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.CSharp.Diagnostics.TypeStyle; using Microsoft.CodeAnalysis.CSharp.TypeStyle; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; using Xunit.Abstractions; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics.UseExplicitType { public partial class UseExplicitTypeTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest { public UseExplicitTypeTests(ITestOutputHelper logger) : base(logger) { } internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace) => (new CSharpUseExplicitTypeDiagnosticAnalyzer(), new UseExplicitTypeCodeFixProvider()); private readonly CodeStyleOption2<bool> offWithSilent = new CodeStyleOption2<bool>(false, NotificationOption2.Silent); private readonly CodeStyleOption2<bool> onWithInfo = new CodeStyleOption2<bool>(true, NotificationOption2.Suggestion); private readonly CodeStyleOption2<bool> offWithInfo = new CodeStyleOption2<bool>(false, NotificationOption2.Suggestion); private readonly CodeStyleOption2<bool> offWithWarning = new CodeStyleOption2<bool>(false, NotificationOption2.Warning); private readonly CodeStyleOption2<bool> offWithError = new CodeStyleOption2<bool>(false, NotificationOption2.Error); // specify all options explicitly to override defaults. private OptionsCollection ExplicitTypeEverywhere() => new OptionsCollection(GetLanguage()) { { CSharpCodeStyleOptions.VarElsewhere, offWithInfo }, { CSharpCodeStyleOptions.VarWhenTypeIsApparent, offWithInfo }, { CSharpCodeStyleOptions.VarForBuiltInTypes, offWithInfo }, }; private OptionsCollection ExplicitTypeExceptWhereApparent() => new OptionsCollection(GetLanguage()) { { CSharpCodeStyleOptions.VarElsewhere, offWithInfo }, { CSharpCodeStyleOptions.VarWhenTypeIsApparent, onWithInfo }, { CSharpCodeStyleOptions.VarForBuiltInTypes, offWithInfo }, }; private OptionsCollection ExplicitTypeForBuiltInTypesOnly() => new OptionsCollection(GetLanguage()) { { CSharpCodeStyleOptions.VarElsewhere, onWithInfo }, { CSharpCodeStyleOptions.VarWhenTypeIsApparent, onWithInfo }, { CSharpCodeStyleOptions.VarForBuiltInTypes, offWithInfo }, }; private OptionsCollection ExplicitTypeEnforcements() => new OptionsCollection(GetLanguage()) { { CSharpCodeStyleOptions.VarElsewhere, offWithWarning }, { CSharpCodeStyleOptions.VarWhenTypeIsApparent, offWithError }, { CSharpCodeStyleOptions.VarForBuiltInTypes, offWithInfo }, }; private OptionsCollection ExplicitTypeSilentEnforcement() => new OptionsCollection(GetLanguage()) { { CSharpCodeStyleOptions.VarElsewhere, offWithSilent }, { CSharpCodeStyleOptions.VarWhenTypeIsApparent, offWithSilent }, { CSharpCodeStyleOptions.VarForBuiltInTypes, offWithSilent }, }; #region Error Cases [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] public async Task NotOnFieldDeclaration() { await TestMissingInRegularAndScriptAsync( @"using System; class Program { [|var|] _myfield = 5; }", new TestParameters(options: ExplicitTypeEverywhere())); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] public async Task NotOnFieldLikeEvents() { await TestMissingInRegularAndScriptAsync( @"using System; class Program { public event [|var|] _myevent; }", new TestParameters(options: ExplicitTypeEverywhere())); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] public async Task OnAnonymousMethodExpression() { var before = @"using System; class Program { void Method() { [|var|] comparer = delegate (string value) { return value != ""0""; }; } }"; var after = @"using System; class Program { void Method() { Func<string, bool> comparer = delegate (string value) { return value != ""0""; }; } }"; await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere()); await TestMissingInRegularAndScriptAsync(before, new TestParameters(options: ExplicitTypeForBuiltInTypesOnly())); await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] public async Task OnLambdaExpression() { var before = @"using System; class Program { void Method() { [|var|] x = (int y) => y * y; } }"; var after = @"using System; class Program { void Method() { Func<int, int> x = (int y) => y * y; } }"; await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere()); await TestMissingInRegularAndScriptAsync(before, new TestParameters(options: ExplicitTypeForBuiltInTypesOnly())); await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] public async Task NotOnDeclarationWithMultipleDeclarators() { await TestMissingInRegularAndScriptAsync( @"using System; class Program { void Method() { [|var|] x = 5, y = x; } }", new TestParameters(options: ExplicitTypeEverywhere())); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] public async Task NotOnDeclarationWithoutInitializer() { await TestMissingInRegularAndScriptAsync( @"using System; class Program { void Method() { [|var|] x; } }", new TestParameters(options: ExplicitTypeEverywhere())); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] public async Task NotDuringConflicts() { await TestMissingInRegularAndScriptAsync( @"using System; class Program { void Method() { [|var|] p = new var(); } class var { } }", new TestParameters(options: ExplicitTypeEverywhere())); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] public async Task NotIfAlreadyExplicitlyTyped() { await TestMissingInRegularAndScriptAsync( @"using System; class Program { void Method() { [|Program|] p = new Program(); } }", new TestParameters(options: ExplicitTypeEverywhere())); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] [WorkItem(27221, "https://github.com/dotnet/roslyn/issues/27221")] public async Task NotIfRefTypeAlreadyExplicitlyTyped() { await TestMissingInRegularAndScriptAsync( @"using System; struct Program { void Method() { ref [|Program|] p = Ref(); } ref Program Ref() => throw null; }", new TestParameters(options: ExplicitTypeEverywhere())); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] public async Task NotOnRHS() { await TestMissingInRegularAndScriptAsync( @"using System; class C { void M() { var c = new [|var|](); } } class var { }"); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] public async Task NotOnErrorSymbol() { await TestMissingInRegularAndScriptAsync( @"using System; class Program { void Method() { [|var|] x = new Goo(); } }", new TestParameters(options: ExplicitTypeEverywhere())); } [WorkItem(29718, "https://github.com/dotnet/roslyn/issues/29718")] [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] public async Task NotOnErrorConvertedType_ForEachVariableStatement() { await TestMissingInRegularAndScriptAsync( @"using System; using System.Collections.Generic; class C { void M() { // Error CS1061: 'KeyValuePair<int, int>' does not contain a definition for 'Deconstruct' and no accessible extension method 'Deconstruct' accepting a first argument of type 'KeyValuePair<int, int>' could be found (are you missing a using directive or an assembly reference?) // Error CS8129: No suitable 'Deconstruct' instance or extension method was found for type 'KeyValuePair<int, int>', with 2 out parameters and a void return type. foreach ([|var|] (key, value) in new Dictionary<int, int>()) { } } }", new TestParameters(options: ExplicitTypeEverywhere())); } [WorkItem(29718, "https://github.com/dotnet/roslyn/issues/29718")] [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] public async Task NotOnErrorConvertedType_AssignmentExpressionStatement() { await TestMissingInRegularAndScriptAsync( @"using System; using System.Collections.Generic; class C { void M(C c) { // 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?) // Error CS8129: No suitable 'Deconstruct' instance or extension method was found for type 'C', with 2 out parameters and a void return type. [|var|] (key, value) = c; } }", new TestParameters(options: ExplicitTypeEverywhere())); } #endregion [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] [WorkItem(23907, "https://github.com/dotnet/roslyn/issues/23907")] public async Task InArrayType() { var before = @" class Program { void Method() { [|var|] x = new Program[0]; } }"; var after = @" class Program { void Method() { Program[] x = new Program[0]; } }"; // The type is apparent and not intrinsic await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere()); await TestMissingInRegularAndScriptAsync(before, new TestParameters(options: ExplicitTypeForBuiltInTypesOnly())); await TestMissingInRegularAndScriptAsync(before, new TestParameters(options: ExplicitTypeExceptWhereApparent())); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] [WorkItem(23907, "https://github.com/dotnet/roslyn/issues/23907")] public async Task InArrayTypeWithIntrinsicType() { var before = @" class Program { void Method() { [|var|] x = new int[0]; } }"; var after = @" class Program { void Method() { int[] x = new int[0]; } }"; await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere()); await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeForBuiltInTypesOnly()); await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent()); // preference for builtin types dominates } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] [WorkItem(23907, "https://github.com/dotnet/roslyn/issues/23907")] public async Task InNullableIntrinsicType() { var before = @" class Program { void Method(int? x) { [|var|] y = x; } }"; var after = @" class Program { void Method(int? x) { int? y = x; } }"; // The type is intrinsic and not apparent await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere()); await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeForBuiltInTypesOnly()); await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] [WorkItem(42986, "https://github.com/dotnet/roslyn/issues/42986")] public async Task InNativeIntIntrinsicType() { var before = @" class Program { void Method(nint x) { [|var|] y = x; } }"; var after = @" class Program { void Method(nint x) { nint y = x; } }"; // The type is intrinsic and not apparent await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere()); await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeForBuiltInTypesOnly()); await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] [WorkItem(42986, "https://github.com/dotnet/roslyn/issues/42986")] public async Task InNativeUnsignedIntIntrinsicType() { var before = @" class Program { void Method(nuint x) { [|var|] y = x; } }"; var after = @" class Program { void Method(nuint x) { nuint y = x; } }"; // The type is intrinsic and not apparent await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere()); await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeForBuiltInTypesOnly()); await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] [WorkItem(27221, "https://github.com/dotnet/roslyn/issues/27221")] public async Task WithRefIntrinsicType() { var before = @" class Program { void Method() { ref [|var|] y = Ref(); } ref int Ref() => throw null; }"; var after = @" class Program { void Method() { ref int y = Ref(); } ref int Ref() => throw null; }"; // The type is intrinsic and not apparent await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere()); await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeForBuiltInTypesOnly()); await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] [WorkItem(27221, "https://github.com/dotnet/roslyn/issues/27221")] public async Task WithRefIntrinsicTypeInForeach() { var before = @" class E { public ref int Current => throw null; public bool MoveNext() => throw null; public E GetEnumerator() => throw null; void M() { foreach (ref [|var|] x in this) { } } }"; var after = @" class E { public ref int Current => throw null; public bool MoveNext() => throw null; public E GetEnumerator() => throw null; void M() { foreach (ref int x in this) { } } }"; // The type is intrinsic and not apparent await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere()); await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeForBuiltInTypesOnly()); await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] [WorkItem(23907, "https://github.com/dotnet/roslyn/issues/23907")] public async Task InArrayOfNullableIntrinsicType() { var before = @" class Program { void Method(int?[] x) { [|var|] y = x; } }"; var after = @" class Program { void Method(int?[] x) { int?[] y = x; } }"; // The type is intrinsic and not apparent await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere()); await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeForBuiltInTypesOnly()); await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] [WorkItem(23907, "https://github.com/dotnet/roslyn/issues/23907")] public async Task InNullableCustomType() { var before = @" struct Program { void Method(Program? x) { [|var|] y = x; } }"; var after = @" struct Program { void Method(Program? x) { Program? y = x; } }"; // The type is not intrinsic and not apparent await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere()); await TestMissingInRegularAndScriptAsync(before, new TestParameters(options: ExplicitTypeForBuiltInTypesOnly())); await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] [WorkItem(40477, "https://github.com/dotnet/roslyn/issues/40477")] public async Task NullableType() { var before = @" #nullable enable class Program { void Method(Program x) { [|var|] y = x; y = null; } }"; var after = @" #nullable enable class Program { void Method(Program x) { Program? y = x; y = null; } }"; // The type is not intrinsic and not apparent await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere()); await TestMissingInRegularAndScriptAsync(before, new TestParameters(options: ExplicitTypeForBuiltInTypesOnly())); await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] [WorkItem(40477, "https://github.com/dotnet/roslyn/issues/40477")] public async Task ObliviousType() { var before = @" #nullable enable class Program { void Method(Program x) { #nullable disable [|var|] y = x; y = null; } }"; var after = @" #nullable enable class Program { void Method(Program x) { #nullable disable Program y = x; y = null; } }"; // The type is not intrinsic and not apparent await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere()); await TestMissingInRegularAndScriptAsync(before, new TestParameters(options: ExplicitTypeForBuiltInTypesOnly())); await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] [WorkItem(40477, "https://github.com/dotnet/roslyn/issues/40477")] public async Task NotNullableType() { var before = @" class Program { void Method(Program x) { #nullable enable [|var|] y = x; y = null; } }"; var after = @" class Program { void Method(Program x) { #nullable enable Program? y = x; y = null; } }"; // The type is not intrinsic and not apparent await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere()); await TestMissingInRegularAndScriptAsync(before, new TestParameters(options: ExplicitTypeForBuiltInTypesOnly())); await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] [WorkItem(40477, "https://github.com/dotnet/roslyn/issues/40477")] public async Task NullableType_OutVar() { var before = @" #nullable enable class Program { void Method(out Program? x) { Method(out [|var|] y1); throw null!; } }"; var after = @" #nullable enable class Program { void Method(out Program? x) { Method(out Program? y1); throw null!; } }"; // The type is not intrinsic and not apparent await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere()); await TestMissingInRegularAndScriptAsync(before, new TestParameters(options: ExplicitTypeForBuiltInTypesOnly())); await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] [WorkItem(40477, "https://github.com/dotnet/roslyn/issues/40477")] public async Task NotNullableType_OutVar() { var before = @" #nullable enable class Program { void Method(out Program x) { Method(out [|var|] y1); throw null!; } }"; var after = @" #nullable enable class Program { void Method(out Program x) { Method(out Program? y1); throw null!; } }"; // The type is not intrinsic and not apparent await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere()); await TestMissingInRegularAndScriptAsync(before, new TestParameters(options: ExplicitTypeForBuiltInTypesOnly())); await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] [WorkItem(40477, "https://github.com/dotnet/roslyn/issues/40477")] public async Task ObliviousType_OutVar() { var before = @" class Program { void Method(out Program x) { Method(out [|var|] y1); throw null; } }"; var after = @" class Program { void Method(out Program x) { Method(out Program y1); throw null; } }"; // The type is not intrinsic and not apparent await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere()); await TestMissingInRegularAndScriptAsync(before, new TestParameters(options: ExplicitTypeForBuiltInTypesOnly())); await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent()); } [WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/40925"), Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] [WorkItem(40477, "https://github.com/dotnet/roslyn/issues/40477")] [WorkItem(40925, "https://github.com/dotnet/roslyn/issues/40925")] public async Task NullableTypeAndNotNullableType_VarDeconstruction() { var before = @" #nullable enable class Program2 { } class Program { void Method(Program? x, Program2 x2) { [|var|] (y1, y2) = (x, x2); } }"; var after = @" #nullable enable class Program2 { } class Program { void Method(Program? x, Program2 x2) { (Program? y1, Program2? y2) = (x, x2); } }"; // The type is not intrinsic and not apparent await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere()); await TestMissingInRegularAndScriptAsync(before, new TestParameters(options: ExplicitTypeForBuiltInTypesOnly())); await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] [WorkItem(40477, "https://github.com/dotnet/roslyn/issues/40477")] public async Task ObliviousType_VarDeconstruction() { var before = @" #nullable enable class Program2 { } class Program { void Method(Program x, Program2 x2) { #nullable disable [|var|] (y1, y2) = (x, x2); } }"; var after = @" #nullable enable class Program2 { } class Program { void Method(Program x, Program2 x2) { #nullable disable (Program y1, Program2 y2) = (x, x2); } }"; // The type is not intrinsic and not apparent await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere()); await TestMissingInRegularAndScriptAsync(before, new TestParameters(options: ExplicitTypeForBuiltInTypesOnly())); await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] [WorkItem(40477, "https://github.com/dotnet/roslyn/issues/40477")] public async Task ObliviousType_Deconstruction() { var before = @" #nullable enable class Program { void Method(Program x) { #nullable disable ([|var|] y1, Program y2) = (x, x); } }"; var after = @" #nullable enable class Program { void Method(Program x) { #nullable disable (Program y1, Program y2) = (x, x); } }"; // The type is not intrinsic and not apparent await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere()); await TestMissingInRegularAndScriptAsync(before, new TestParameters(options: ExplicitTypeForBuiltInTypesOnly())); await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] [WorkItem(40477, "https://github.com/dotnet/roslyn/issues/40477")] public async Task NotNullableType_Deconstruction() { var before = @" class Program { void Method(Program x) { #nullable enable ([|var|] y1, Program y2) = (x, x); } }"; var after = @" class Program { void Method(Program x) { #nullable enable (Program? y1, Program y2) = (x, x); } }"; // The type is not intrinsic and not apparent await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere()); await TestMissingInRegularAndScriptAsync(before, new TestParameters(options: ExplicitTypeForBuiltInTypesOnly())); await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] [WorkItem(40477, "https://github.com/dotnet/roslyn/issues/40477")] public async Task NullableType_Deconstruction() { var before = @" class Program { void Method(Program? x) { #nullable enable ([|var|] y1, Program y2) = (x, x); } }"; var after = @" class Program { void Method(Program? x) { #nullable enable (Program? y1, Program y2) = (x, x); } }"; // The type is not intrinsic and not apparent await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere()); await TestMissingInRegularAndScriptAsync(before, new TestParameters(options: ExplicitTypeForBuiltInTypesOnly())); await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] [WorkItem(40477, "https://github.com/dotnet/roslyn/issues/40477")] public async Task ObliviousType_Foreach() { var before = @" #nullable enable class Program { void Method(System.Collections.Generic.IEnumerable<Program> x) { #nullable disable foreach ([|var|] y in x) { } } }"; var after = @" #nullable enable class Program { void Method(System.Collections.Generic.IEnumerable<Program> x) { #nullable disable foreach ([|Program|] y in x) { } } }"; // The type is not intrinsic and not apparent await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere()); await TestMissingInRegularAndScriptAsync(before, new TestParameters(options: ExplicitTypeForBuiltInTypesOnly())); await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] [WorkItem(40477, "https://github.com/dotnet/roslyn/issues/40477")] public async Task NotNullableType_Foreach() { var before = @" class Program { void Method(System.Collections.Generic.IEnumerable<Program> x) { #nullable enable foreach ([|var|] y in x) { } } }"; var after = @" class Program { void Method(System.Collections.Generic.IEnumerable<Program> x) { #nullable enable foreach (Program? y in x) { } } }"; // The type is not intrinsic and not apparent await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere()); await TestMissingInRegularAndScriptAsync(before, new TestParameters(options: ExplicitTypeForBuiltInTypesOnly())); await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] [WorkItem(40477, "https://github.com/dotnet/roslyn/issues/40477")] public async Task NullableType_Foreach() { var before = @" class Program { void Method(System.Collections.Generic.IEnumerable<Program> x) { #nullable enable foreach ([|var|] y in x) { } } }"; var after = @" class Program { void Method(System.Collections.Generic.IEnumerable<Program> x) { #nullable enable foreach (Program? y in x) { } } }"; // The type is not intrinsic and not apparent await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere()); await TestMissingInRegularAndScriptAsync(before, new TestParameters(options: ExplicitTypeForBuiltInTypesOnly())); await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent()); } [WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/37491"), Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] [WorkItem(40477, "https://github.com/dotnet/roslyn/issues/40477")] public async Task NotNullableType_ForeachVarDeconstruction() { // Semantic model doesn't yet handle var deconstruction foreach // https://github.com/dotnet/roslyn/issues/37491 // https://github.com/dotnet/roslyn/issues/35010 var before = @" class Program { void Method(System.Collections.Generic.IEnumerable<(Program, Program)> x) { #nullable enable foreach ([|var|] (y1, y2) in x) { } } }"; var after = @" class Program { void Method(System.Collections.Generic.IEnumerable<(Program, Program)> x) { #nullable enable foreach ((Program? y1, Program? y2) in x) { } } }"; // The type is not intrinsic and not apparent await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere()); await TestMissingInRegularAndScriptAsync(before, new TestParameters(options: ExplicitTypeForBuiltInTypesOnly())); await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] [WorkItem(40477, "https://github.com/dotnet/roslyn/issues/40477")] public async Task NotNullableType_ForeachDeconstruction() { var before = @" class Program { void Method(System.Collections.Generic.IEnumerable<(Program, Program)> x) { #nullable enable foreach (([|var|] y1, var y2) in x) { } } }"; var after = @" class Program { void Method(System.Collections.Generic.IEnumerable<(Program, Program)> x) { #nullable enable foreach ((Program? y1, var y2) in x) { } } }"; // The type is not intrinsic and not apparent await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere()); await TestMissingInRegularAndScriptAsync(before, new TestParameters(options: ExplicitTypeForBuiltInTypesOnly())); await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] [WorkItem(23907, "https://github.com/dotnet/roslyn/issues/23907")] public async Task InPointerTypeWithIntrinsicType() { var before = @" unsafe class Program { void Method(int* y) { [|var|] x = y; } }"; var after = @" unsafe class Program { void Method(int* y) { int* x = y; } }"; // The type is intrinsic and not apparent await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere()); await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeForBuiltInTypesOnly()); await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent()); // preference for builtin types dominates } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] [WorkItem(23907, "https://github.com/dotnet/roslyn/issues/23907")] public async Task InPointerTypeWithCustomType() { var before = @" unsafe class Program { void Method(Program* y) { [|var|] x = y; } }"; var after = @" unsafe class Program { void Method(Program* y) { Program* x = y; } }"; // The type is not intrinsic and not apparent await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere()); await TestMissingInRegularAndScriptAsync(before, new TestParameters(options: ExplicitTypeForBuiltInTypesOnly())); await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] [WorkItem(23893, "https://github.com/dotnet/roslyn/issues/23893")] public async Task InOutParameter() { var before = @" class Program { void Method(out int x) { Method(out [|var|] x); } }"; var after = @" class Program { void Method(out int x) { Method(out int x); } }"; await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere()); await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeForBuiltInTypesOnly()); await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] public async Task NotOnDynamic() { await TestMissingInRegularAndScriptAsync( @"using System; class Program { void Method() { [|dynamic|] x = 1; } }", new TestParameters(options: ExplicitTypeEverywhere())); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] public async Task NotOnForEachVarWithAnonymousType() { await TestMissingInRegularAndScriptAsync( @"using System; using System.Linq; class Program { void Method() { var values = Enumerable.Range(1, 5).Select(i => new { Value = i }); foreach ([|var|] value in values) { Console.WriteLine(value.Value); } } }", new TestParameters(options: ExplicitTypeEverywhere())); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] [WorkItem(23752, "https://github.com/dotnet/roslyn/issues/23752")] public async Task OnDeconstructionVarParens() { await TestInRegularAndScriptAsync( @"using System; class Program { void M() { [|var|] (x, y) = new Program(); } void Deconstruct(out int i, out string s) { i = 1; s = ""hello""; } }", @"using System; class Program { void M() { (int x, string y) = new Program(); } void Deconstruct(out int i, out string s) { i = 1; s = ""hello""; } }", options: ExplicitTypeEverywhere()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] public async Task OnDeconstructionVar() { await TestInRegularAndScriptAsync( @"using System; class Program { void M() { ([|var|] x, var y) = new Program(); } void Deconstruct(out int i, out string s) { i = 1; s = ""hello""; } }", @"using System; class Program { void M() { (int x, var y) = new Program(); } void Deconstruct(out int i, out string s) { i = 1; s = ""hello""; } }", options: ExplicitTypeEverywhere()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] [WorkItem(23752, "https://github.com/dotnet/roslyn/issues/23752")] public async Task OnNestedDeconstructionVar() { await TestInRegularAndScriptAsync( @"using System; class Program { void M() { [|var|] (x, (y, z)) = new Program(); } void Deconstruct(out int i, out Program s) { i = 1; s = null; } }", @"using System; class Program { void M() { (int x, (int y, Program z)) = new Program(); } void Deconstruct(out int i, out Program s) { i = 1; s = null; } }", options: ExplicitTypeEverywhere()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] [WorkItem(23752, "https://github.com/dotnet/roslyn/issues/23752")] public async Task OnBadlyFormattedNestedDeconstructionVar() { await TestInRegularAndScriptAsync( @"using System; class Program { void M() { [|var|](x,(y,z)) = new Program(); } void Deconstruct(out int i, out Program s) { i = 1; s = null; } }", @"using System; class Program { void M() { (int x, (int y, Program z)) = new Program(); } void Deconstruct(out int i, out Program s) { i = 1; s = null; } }", options: ExplicitTypeEverywhere()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] [WorkItem(23752, "https://github.com/dotnet/roslyn/issues/23752")] public async Task OnForeachNestedDeconstructionVar() { await TestInRegularAndScriptAsync( @"using System; class Program { void M() { foreach ([|var|] (x, (y, z)) in new[] { new Program() } { } } void Deconstruct(out int i, out Program s) { i = 1; s = null; } }", @"using System; class Program { void M() { foreach ((int x, (int y, Program z)) in new[] { new Program() } { } } void Deconstruct(out int i, out Program s) { i = 1; s = null; } }", options: ExplicitTypeEverywhere()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] [WorkItem(23752, "https://github.com/dotnet/roslyn/issues/23752")] public async Task OnNestedDeconstructionVarWithTrivia() { await TestInRegularAndScriptAsync( @"using System; class Program { void M() { /*before*/[|var|]/*after*/ (/*x1*/x/*x2*/, /*yz1*/(/*y1*/y/*y2*/, /*z1*/z/*z2*/)/*yz2*/) /*end*/ = new Program(); } void Deconstruct(out int i, out Program s) { i = 1; s = null; } }", @"using System; class Program { void M() { /*before*//*after*/(/*x1*/int x/*x2*/, /*yz1*/(/*y1*/int y/*y2*/, /*z1*/Program z/*z2*/)/*yz2*/) /*end*/ = new Program(); } void Deconstruct(out int i, out Program s) { i = 1; s = null; } }", options: ExplicitTypeEverywhere()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] [WorkItem(23752, "https://github.com/dotnet/roslyn/issues/23752")] public async Task OnDeconstructionVarWithDiscard() { await TestInRegularAndScriptAsync( @"using System; class Program { void M() { [|var|] (x, _) = new Program(); } void Deconstruct(out int i, out string s) { i = 1; s = ""hello""; } }", @"using System; class Program { void M() { (int x, string _) = new Program(); } void Deconstruct(out int i, out string s) { i = 1; s = ""hello""; } }", options: ExplicitTypeEverywhere()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] [WorkItem(23752, "https://github.com/dotnet/roslyn/issues/23752")] public async Task OnDeconstructionVarWithErrorType() { await TestInRegularAndScriptAsync( @"using System; class Program { void M() { [|var|] (x, y) = new Program(); } void Deconstruct(out int i, out Error s) { i = 1; s = null; } }", @"using System; class Program { void M() { (int x, Error y) = new Program(); } void Deconstruct(out int i, out Error s) { i = 1; s = null; } }", options: ExplicitTypeEverywhere()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] public async Task OnForEachVarWithExplicitType() { await TestInRegularAndScriptAsync( @"using System; using System.Linq; class Program { void Method() { var values = Enumerable.Range(1, 5); foreach ([|var|] value in values) { Console.WriteLine(value.Value); } } }", @"using System; using System.Linq; class Program { void Method() { var values = Enumerable.Range(1, 5); foreach (int value in values) { Console.WriteLine(value.Value); } } }", options: ExplicitTypeEverywhere()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] public async Task NotOnAnonymousType() { await TestMissingInRegularAndScriptAsync( @"using System; class Program { void Method() { [|var|] x = new { Amount = 108, Message = ""Hello"" }; } }", new TestParameters(options: ExplicitTypeEverywhere())); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] public async Task NotOnArrayOfAnonymousType() { await TestMissingInRegularAndScriptAsync( @"using System; class Program { void Method() { [|var|] x = new[] { new { name = ""apple"", diam = 4 }, new { name = ""grape"", diam = 1 } }; } }", new TestParameters(options: ExplicitTypeEverywhere())); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] public async Task NotOnEnumerableOfAnonymousTypeFromAQueryExpression() { await TestMissingInRegularAndScriptAsync( @"using System; using System.Collections.Generic; using System.Linq; class Program { void Method() { var products = new List<Product>(); [|var|] productQuery = from prod in products select new { prod.Color, prod.Price }; } } class Product { public ConsoleColor Color { get; set; } public int Price { get; set; } }"); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] public async Task SuggestExplicitTypeOnLocalWithIntrinsicTypeString() { await TestInRegularAndScriptAsync( @"using System; class C { static void M() { [|var|] s = ""hello""; } }", @"using System; class C { static void M() { string s = ""hello""; } }", options: ExplicitTypeEverywhere()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] public async Task SuggestExplicitTypeOnIntrinsicType() { await TestInRegularAndScriptAsync( @"using System; class C { static void M() { [|var|] s = 5; } }", @"using System; class C { static void M() { int s = 5; } }", options: ExplicitTypeEverywhere()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] public async Task SuggestExplicitTypeOnFrameworkType() { await TestInRegularAndScriptAsync( @"using System.Collections.Generic; class C { static void M() { [|var|] c = new List<int>(); } }", @"using System.Collections.Generic; class C { static void M() { List<int> c = new List<int>(); } }", options: ExplicitTypeEverywhere()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] public async Task SuggestExplicitTypeOnUserDefinedType() { await TestInRegularAndScriptAsync( @"using System; class C { void M() { [|var|] c = new C(); } }", @"using System; class C { void M() { C c = new C(); } }", options: ExplicitTypeEverywhere()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] public async Task SuggestExplicitTypeOnGenericType() { await TestInRegularAndScriptAsync( @"using System; class C<T> { static void M() { [|var|] c = new C<int>(); } }", @"using System; class C<T> { static void M() { C<int> c = new C<int>(); } }", options: ExplicitTypeEverywhere()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] public async Task SuggestExplicitTypeOnSingleDimensionalArrayTypeWithNewOperator() { await TestInRegularAndScriptAsync( @"using System; class C { static void M() { [|var|] n1 = new int[4] { 2, 4, 6, 8 }; } }", @"using System; class C { static void M() { int[] n1 = new int[4] { 2, 4, 6, 8 }; } }", options: ExplicitTypeEverywhere()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] public async Task SuggestExplicitTypeOnSingleDimensionalArrayTypeWithNewOperator2() { await TestInRegularAndScriptAsync( @"using System; class C { static void M() { [|var|] n1 = new[] { 2, 4, 6, 8 }; } }", @"using System; class C { static void M() { int[] n1 = new[] { 2, 4, 6, 8 }; } }", options: ExplicitTypeEverywhere()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] public async Task SuggestExplicitTypeOnSingleDimensionalJaggedArrayType() { await TestInRegularAndScriptAsync( @"using System; class C { static void M() { [|var|] cs = new[] { new[] { 1, 2, 3, 4 }, new[] { 5, 6, 7, 8 } }; } }", @"using System; class C { static void M() { int[][] cs = new[] { new[] { 1, 2, 3, 4 }, new[] { 5, 6, 7, 8 } }; } }", options: ExplicitTypeEverywhere()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] public async Task SuggestExplicitTypeOnDeclarationWithObjectInitializer() { await TestInRegularAndScriptAsync( @"using System; class C { static void M() { [|var|] cc = new Customer { City = ""Chennai"" }; } private class Customer { public string City { get; set; } } }", @"using System; class C { static void M() { Customer cc = new Customer { City = ""Chennai"" }; } private class Customer { public string City { get; set; } } }", options: ExplicitTypeEverywhere()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] public async Task SuggestExplicitTypeOnDeclarationWithCollectionInitializer() { await TestInRegularAndScriptAsync( @"using System; using System.Collections.Generic; class C { static void M() { [|var|] digits = new List<int> { 1, 2, 3 }; } }", @"using System; using System.Collections.Generic; class C { static void M() { List<int> digits = new List<int> { 1, 2, 3 }; } }", options: ExplicitTypeEverywhere()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] public async Task SuggestExplicitTypeOnDeclarationWithCollectionAndObjectInitializers() { await TestInRegularAndScriptAsync( @"using System; using System.Collections.Generic; class C { static void M() { [|var|] cs = new List<Customer> { new Customer { City = ""Chennai"" } }; } private class Customer { public string City { get; set; } } }", @"using System; using System.Collections.Generic; class C { static void M() { List<Customer> cs = new List<Customer> { new Customer { City = ""Chennai"" } }; } private class Customer { public string City { get; set; } } }", options: ExplicitTypeEverywhere()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] public async Task SuggestExplicitTypeOnForStatement() { await TestInRegularAndScriptAsync( @"using System; class C { static void M() { for ([|var|] i = 0; i < 5; i++) { } } }", @"using System; class C { static void M() { for (int i = 0; i < 5; i++) { } } }", options: ExplicitTypeEverywhere()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] public async Task SuggestExplicitTypeOnForeachStatement() { await TestInRegularAndScriptAsync( @"using System; using System.Collections.Generic; class C { static void M() { var l = new List<int> { 1, 3, 5 }; foreach ([|var|] item in l) { } } }", @"using System; using System.Collections.Generic; class C { static void M() { var l = new List<int> { 1, 3, 5 }; foreach (int item in l) { } } }", options: ExplicitTypeEverywhere()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] public async Task SuggestExplicitTypeOnQueryExpression() { await TestInRegularAndScriptAsync( @"using System; using System.Collections.Generic; using System.Linq; class C { static void M() { var customers = new List<Customer>(); [|var|] expr = from c in customers where c.City == ""London"" select c; } private class Customer { public string City { get; set; } } } }", @"using System; using System.Collections.Generic; using System.Linq; class C { static void M() { var customers = new List<Customer>(); IEnumerable<Customer> expr = from c in customers where c.City == ""London"" select c; } private class Customer { public string City { get; set; } } } }", options: ExplicitTypeEverywhere()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] public async Task SuggestExplicitTypeInUsingStatement() { await TestInRegularAndScriptAsync( @"using System; class C { static void M() { using ([|var|] r = new Res()) { } } private class Res : IDisposable { public void Dispose() { throw new NotImplementedException(); } } }", @"using System; class C { static void M() { using (Res r = new Res()) { } } private class Res : IDisposable { public void Dispose() { throw new NotImplementedException(); } } }", options: ExplicitTypeEverywhere()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] public async Task SuggestExplicitTypeOnInterpolatedString() { await TestInRegularAndScriptAsync( @"using System; class Program { void Method() { [|var|] s = $""Hello, {name}"" } }", @"using System; class Program { void Method() { string s = $""Hello, {name}"" } }", options: ExplicitTypeEverywhere()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] public async Task SuggestExplicitTypeOnExplicitConversion() { await TestInRegularAndScriptAsync( @"using System; class C { static void M() { double x = 1234.7; [|var|] a = (int)x; } }", @"using System; class C { static void M() { double x = 1234.7; int a = (int)x; } }", options: ExplicitTypeEverywhere()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] public async Task SuggestExplicitTypeOnConditionalAccessExpression() { await TestInRegularAndScriptAsync( @"using System; class C { static void M() { C obj = new C(); [|var|] anotherObj = obj?.Test(); } C Test() { return this; } }", @"using System; class C { static void M() { C obj = new C(); C anotherObj = obj?.Test(); } C Test() { return this; } }", options: ExplicitTypeEverywhere()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] public async Task SuggestExplicitTypeInCheckedExpression() { await TestInRegularAndScriptAsync( @"using System; class C { static void M() { long number1 = int.MaxValue + 20L; [|var|] intNumber = checked((int)number1); } }", @"using System; class C { static void M() { long number1 = int.MaxValue + 20L; int intNumber = checked((int)number1); } }", options: ExplicitTypeEverywhere()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] public async Task SuggestExplicitTypeInAwaitExpression() { await TestInRegularAndScriptAsync( @"using System; using System.Threading.Tasks; class C { public async void ProcessRead() { [|var|] text = await ReadTextAsync(null); } private async Task<string> ReadTextAsync(string filePath) { return string.Empty; } }", @"using System; using System.Threading.Tasks; class C { public async void ProcessRead() { string text = await ReadTextAsync(null); } private async Task<string> ReadTextAsync(string filePath) { return string.Empty; } }", options: ExplicitTypeEverywhere()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] public async Task SuggestExplicitTypeInBuiltInNumericType() { await TestInRegularAndScriptAsync( @"using System; class C { public void ProcessRead() { [|var|] text = 1; } }", @"using System; class C { public void ProcessRead() { int text = 1; } }", options: ExplicitTypeForBuiltInTypesOnly()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] public async Task SuggestExplicitTypeInBuiltInCharType() { await TestInRegularAndScriptAsync( @"using System; class C { public void ProcessRead() { [|var|] text = GetChar(); } public char GetChar() => 'c'; }", @"using System; class C { public void ProcessRead() { char text = GetChar(); } public char GetChar() => 'c'; }", options: ExplicitTypeForBuiltInTypesOnly()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] public async Task SuggestExplicitTypeInBuiltInType_string() { // though string isn't an intrinsic type per the compiler // we in the IDE treat it as an intrinsic type for this feature. await TestInRegularAndScriptAsync( @"using System; class C { public void ProcessRead() { [|var|] text = string.Empty; } }", @"using System; class C { public void ProcessRead() { string text = string.Empty; } }", options: ExplicitTypeForBuiltInTypesOnly()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] public async Task SuggestExplicitTypeInBuiltInType_object() { // object isn't an intrinsic type per the compiler // we in the IDE treat it as an intrinsic type for this feature. await TestInRegularAndScriptAsync( @"using System; class C { public void ProcessRead() { object j = new C(); [|var|] text = j; } }", @"using System; class C { public void ProcessRead() { object j = new C(); object text = j; } }", options: ExplicitTypeForBuiltInTypesOnly()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] public async Task SuggestExplicitTypeNotificationLevelSilent() { var source = @"using System; class C { static void M() { [|var|] n1 = new C(); } }"; await TestDiagnosticInfoAsync(source, options: ExplicitTypeSilentEnforcement(), diagnosticId: IDEDiagnosticIds.UseExplicitTypeDiagnosticId, diagnosticSeverity: DiagnosticSeverity.Hidden); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] public async Task SuggestExplicitTypeNotificationLevelInfo() { var source = @"using System; class C { static void M() { [|var|] s = 5; } }"; await TestDiagnosticInfoAsync(source, options: ExplicitTypeEnforcements(), diagnosticId: IDEDiagnosticIds.UseExplicitTypeDiagnosticId, diagnosticSeverity: DiagnosticSeverity.Info); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] [WorkItem(23907, "https://github.com/dotnet/roslyn/issues/23907")] public async Task SuggestExplicitTypeNotificationLevelWarning() { var source = @"using System; class C { static void M() { [|var|] n1 = new[] { new C() }; // type not apparent and not intrinsic } }"; await TestDiagnosticInfoAsync(source, options: ExplicitTypeEnforcements(), diagnosticId: IDEDiagnosticIds.UseExplicitTypeDiagnosticId, diagnosticSeverity: DiagnosticSeverity.Warning); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] public async Task SuggestExplicitTypeNotificationLevelError() { var source = @"using System; class C { static void M() { [|var|] n1 = new C(); } }"; await TestDiagnosticInfoAsync(source, options: ExplicitTypeEnforcements(), diagnosticId: IDEDiagnosticIds.UseExplicitTypeDiagnosticId, diagnosticSeverity: DiagnosticSeverity.Error); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] public async Task SuggestExplicitTypeOnLocalWithIntrinsicTypeTuple() { await TestInRegularAndScriptAsync( @"class C { static void M() { [|var|] s = (1, ""hello""); } }", @"class C { static void M() { (int, string) s = (1, ""hello""); } }", options: ExplicitTypeEverywhere()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] public async Task SuggestExplicitTypeOnLocalWithIntrinsicTypeTupleWithNames() { await TestInRegularAndScriptAsync( @"class C { static void M() { [|var|] s = (a: 1, b: ""hello""); } }", @"class C { static void M() { (int a, string b) s = (a: 1, b: ""hello""); } }", options: ExplicitTypeEverywhere()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] public async Task SuggestExplicitTypeOnLocalWithIntrinsicTypeTupleWithOneName() { await TestInRegularAndScriptAsync( @"class C { static void M() { [|var|] s = (a: 1, ""hello""); } }", @"class C { static void M() { (int a, string) s = (a: 1, ""hello""); } }", options: ExplicitTypeEverywhere()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] [WorkItem(20437, "https://github.com/dotnet/roslyn/issues/20437")] public async Task SuggestExplicitTypeOnDeclarationExpressionSyntax() { await TestInRegularAndScriptAsync( @"using System; class C { static void M() { DateTime.TryParse(string.Empty, [|out var|] date); } }", @"using System; class C { static void M() { DateTime.TryParse(string.Empty, out DateTime date); } }", options: ExplicitTypeEverywhere()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] [WorkItem(20244, "https://github.com/dotnet/roslyn/issues/20244")] public async Task ExplicitTypeOnPredefinedTypesByTheirMetadataNames1() { await TestMissingInRegularAndScriptAsync( @"using System; class Program { void Method() { [|String|] test = new String(' ', 4); } }", new TestParameters(options: ExplicitTypeForBuiltInTypesOnly())); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] [WorkItem(20244, "https://github.com/dotnet/roslyn/issues/20244")] public async Task ExplicitTypeOnPredefinedTypesByTheirMetadataNames2() { await TestMissingInRegularAndScriptAsync( @"using System; class Program { void Main() { foreach ([|String|] test in new String[] { ""test1"", ""test2"" }) { } } }", new TestParameters(options: ExplicitTypeForBuiltInTypesOnly())); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] [WorkItem(20244, "https://github.com/dotnet/roslyn/issues/20244")] public async Task ExplicitTypeOnPredefinedTypesByTheirMetadataNames3() { await TestMissingInRegularAndScriptAsync( @"using System; class Program { void Main() { [|Int32[]|] array = new[] { 1, 2, 3 }; } }", new TestParameters(options: ExplicitTypeForBuiltInTypesOnly())); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] [WorkItem(20244, "https://github.com/dotnet/roslyn/issues/20244")] public async Task ExplicitTypeOnPredefinedTypesByTheirMetadataNames4() { await TestMissingInRegularAndScriptAsync( @"using System; class Program { void Main() { [|Int32[][]|] a = new Int32[][] { new[] { 1, 2 }, new[] { 3, 4 } }; } }", new TestParameters(options: ExplicitTypeForBuiltInTypesOnly())); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] [WorkItem(20244, "https://github.com/dotnet/roslyn/issues/20244")] public async Task ExplicitTypeOnPredefinedTypesByTheirMetadataNames5() { await TestMissingInRegularAndScriptAsync( @"using System; using System.Collections.Generic; class Program { void Main() { [|IEnumerable<Int32>|] a = new List<Int32> { 1, 2 }.Where(x => x > 1); } }", new TestParameters(options: ExplicitTypeForBuiltInTypesOnly())); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] [WorkItem(20244, "https://github.com/dotnet/roslyn/issues/20244")] public async Task ExplicitTypeOnPredefinedTypesByTheirMetadataNames6() { await TestMissingInRegularAndScriptAsync( @"using System; class Program { void Main() { String name = ""name""; [|String|] s = $""Hello, {name}"" } }", new TestParameters(options: ExplicitTypeForBuiltInTypesOnly())); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] [WorkItem(20244, "https://github.com/dotnet/roslyn/issues/20244")] public async Task ExplicitTypeOnPredefinedTypesByTheirMetadataNames7() { await TestMissingInRegularAndScriptAsync( @"using System; class Program { void Main() { Object name = ""name""; [|String|] s = (String) name; } }", new TestParameters(options: ExplicitTypeForBuiltInTypesOnly())); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] [WorkItem(20244, "https://github.com/dotnet/roslyn/issues/20244")] public async Task ExplicitTypeOnPredefinedTypesByTheirMetadataNames8() { await TestMissingInRegularAndScriptAsync( @"using System; using System.Threading.Tasks; class C { public async void ProcessRead() { [|String|] text = await ReadTextAsync(null); } private async Task<string> ReadTextAsync(string filePath) { return String.Empty; } }", new TestParameters(options: ExplicitTypeForBuiltInTypesOnly())); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] [WorkItem(20244, "https://github.com/dotnet/roslyn/issues/20244")] public async Task ExplicitTypeOnPredefinedTypesByTheirMetadataNames9() { await TestMissingInRegularAndScriptAsync( @"using System; class Program { void Main() { String number = ""12""; Int32.TryParse(name, out [|Int32|] number) } }", new TestParameters(options: ExplicitTypeForBuiltInTypesOnly())); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] [WorkItem(20244, "https://github.com/dotnet/roslyn/issues/20244")] public async Task ExplicitTypeOnPredefinedTypesByTheirMetadataNames10() { await TestMissingInRegularAndScriptAsync( @"using System; class Program { void Main() { for ([|Int32|] i = 0; i < 5; i++) { } } }", new TestParameters(options: ExplicitTypeForBuiltInTypesOnly())); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] [WorkItem(20244, "https://github.com/dotnet/roslyn/issues/20244")] public async Task ExplicitTypeOnPredefinedTypesByTheirMetadataNames11() { await TestMissingInRegularAndScriptAsync( @"using System; using System.Collections.Generic; class Program { void Main() { [|List<Int32>|] a = new List<Int32> { 1, 2 }; } }", new TestParameters(options: ExplicitTypeForBuiltInTypesOnly())); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] [WorkItem(26923, "https://github.com/dotnet/roslyn/issues/26923")] public async Task NoSuggestionOnForeachCollectionExpression() { await TestMissingInRegularAndScriptAsync( @"using System; using System.Collections.Generic; class Program { void Method(List<int> var) { foreach (int value in [|var|]) { Console.WriteLine(value.Value); } } }", new TestParameters(options: ExplicitTypeEverywhere())); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] public async Task NotOnConstVar() { // This error case is handled by a separate code fix (UseExplicitTypeForConst). await TestMissingInRegularAndScriptAsync( @"class C { void M() { const [|var|] v = 0; } }", new TestParameters(options: ExplicitTypeEverywhere())); } } }
1
dotnet/roslyn
55,132
Support lambda expressions and method groups as `var` initializers
```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
cston
2021-07-27T03:12:21Z
2021-07-27T18:26:42Z
61a565cfcd777158cb6354351436aff997ad7bf6
5840335153dcca42570a853cdacd06d660fe9596
Support lambda expressions and method groups as `var` initializers. ```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
./src/Compilers/CSharp/Portable/Binder/Binder_Expressions.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; namespace Microsoft.CodeAnalysis.CSharp { /// <summary> /// This portion of the binder converts an <see cref="ExpressionSyntax"/> into a <see cref="BoundExpression"/>. /// </summary> internal partial class Binder { /// <summary> /// Determines whether "this" reference is available within the current context. /// </summary> /// <param name="isExplicit">The reference was explicitly specified in syntax.</param> /// <param name="inStaticContext">True if "this" is not available due to the current method/property/field initializer being static.</param> /// <returns>True if a reference to "this" is available.</returns> internal bool HasThis(bool isExplicit, out bool inStaticContext) { var memberOpt = this.ContainingMemberOrLambda?.ContainingNonLambdaMember(); if (memberOpt?.IsStatic == true) { inStaticContext = memberOpt.Kind == SymbolKind.Field || memberOpt.Kind == SymbolKind.Method || memberOpt.Kind == SymbolKind.Property; return false; } inStaticContext = false; if (InConstructorInitializer || InAttributeArgument) { return false; } var containingType = memberOpt?.ContainingType; bool inTopLevelScriptMember = (object)containingType != null && containingType.IsScriptClass; // "this" is not allowed in field initializers (that are not script variable initializers): if (InFieldInitializer && !inTopLevelScriptMember) { return false; } // top-level script code only allows implicit "this" reference: return !inTopLevelScriptMember || !isExplicit; } internal bool InFieldInitializer { get { return this.Flags.Includes(BinderFlags.FieldInitializer); } } internal bool InParameterDefaultValue { get { return this.Flags.Includes(BinderFlags.ParameterDefaultValue); } } protected bool InConstructorInitializer { get { return this.Flags.Includes(BinderFlags.ConstructorInitializer); } } internal bool InAttributeArgument { get { return this.Flags.Includes(BinderFlags.AttributeArgument); } } internal bool InCref { get { return this.Flags.Includes(BinderFlags.Cref); } } protected bool InCrefButNotParameterOrReturnType { get { return InCref && !this.Flags.Includes(BinderFlags.CrefParameterOrReturnType); } } /// <summary> /// Returns true if the node is in a position where an unbound type /// such as (C&lt;,&gt;) is allowed. /// </summary> protected virtual bool IsUnboundTypeAllowed(GenericNameSyntax syntax) { return Next.IsUnboundTypeAllowed(syntax); } /// <summary> /// Generates a new <see cref="BoundBadExpression"/> with no known type /// </summary> private BoundBadExpression BadExpression(SyntaxNode syntax) { return BadExpression(syntax, LookupResultKind.Empty, ImmutableArray<Symbol>.Empty); } /// <summary> /// Generates a new <see cref="BoundBadExpression"/> with no known type, and the given bound child. /// </summary> private BoundBadExpression BadExpression(SyntaxNode syntax, BoundExpression childNode) { return BadExpression(syntax, LookupResultKind.Empty, ImmutableArray<Symbol>.Empty, childNode); } /// <summary> /// Generates a new <see cref="BoundBadExpression"/> with no known type, and the given bound children. /// </summary> private BoundBadExpression BadExpression(SyntaxNode syntax, ImmutableArray<BoundExpression> childNodes) { return BadExpression(syntax, LookupResultKind.Empty, ImmutableArray<Symbol>.Empty, childNodes); } /// <summary> /// Generates a new <see cref="BoundBadExpression"/> with no known type, given lookup resultKind. /// </summary> protected BoundBadExpression BadExpression(SyntaxNode syntax, LookupResultKind lookupResultKind) { return BadExpression(syntax, lookupResultKind, ImmutableArray<Symbol>.Empty); } /// <summary> /// Generates a new <see cref="BoundBadExpression"/> with no known type, given lookup resultKind and the given bound child. /// </summary> protected BoundBadExpression BadExpression(SyntaxNode syntax, LookupResultKind lookupResultKind, BoundExpression childNode) { return BadExpression(syntax, lookupResultKind, ImmutableArray<Symbol>.Empty, childNode); } /// <summary> /// Generates a new <see cref="BoundBadExpression"/> with no known type, given lookupResultKind and given symbols for GetSemanticInfo API. /// </summary> private BoundBadExpression BadExpression(SyntaxNode syntax, LookupResultKind resultKind, ImmutableArray<Symbol> symbols) { return new BoundBadExpression(syntax, resultKind, symbols, ImmutableArray<BoundExpression>.Empty, CreateErrorType()); } /// <summary> /// Generates a new <see cref="BoundBadExpression"/> with no known type, given lookupResultKind and given symbols for GetSemanticInfo API, /// and the given bound child. /// </summary> private BoundBadExpression BadExpression(SyntaxNode syntax, LookupResultKind resultKind, ImmutableArray<Symbol> symbols, BoundExpression childNode) { return new BoundBadExpression(syntax, resultKind, symbols, ImmutableArray.Create(BindToTypeForErrorRecovery(childNode)), CreateErrorType()); } /// <summary> /// Generates a new <see cref="BoundBadExpression"/> with no known type, given lookupResultKind and given symbols for GetSemanticInfo API, /// and the given bound children. /// </summary> private BoundBadExpression BadExpression(SyntaxNode syntax, LookupResultKind resultKind, ImmutableArray<Symbol> symbols, ImmutableArray<BoundExpression> childNodes, bool wasCompilerGenerated = false) { return new BoundBadExpression(syntax, resultKind, symbols, childNodes.SelectAsArray((e, self) => self.BindToTypeForErrorRecovery(e), this), CreateErrorType()) { WasCompilerGenerated = wasCompilerGenerated }; } /// <summary> /// Helper method to generate a bound expression with HasErrors set to true. /// Returned bound expression is guaranteed to have a non-null type, except when <paramref name="expr"/> is an unbound lambda. /// If <paramref name="expr"/> already has errors and meets the above type requirements, then it is returned unchanged. /// Otherwise, if <paramref name="expr"/> is a BoundBadExpression, then it is updated with the <paramref name="resultKind"/> and non-null type. /// Otherwise, a new <see cref="BoundBadExpression"/> wrapping <paramref name="expr"/> is returned. /// </summary> /// <remarks> /// Returned expression need not be a <see cref="BoundBadExpression"/>, but is guaranteed to have HasErrors set to true. /// </remarks> private BoundExpression ToBadExpression(BoundExpression expr, LookupResultKind resultKind = LookupResultKind.Empty) { Debug.Assert(expr != null); Debug.Assert(resultKind != LookupResultKind.Viable); TypeSymbol resultType = expr.Type; BoundKind exprKind = expr.Kind; if (expr.HasAnyErrors && ((object)resultType != null || exprKind == BoundKind.UnboundLambda || exprKind == BoundKind.DefaultLiteral)) { return expr; } if (exprKind == BoundKind.BadExpression) { var badExpression = (BoundBadExpression)expr; return badExpression.Update(resultKind, badExpression.Symbols, badExpression.ChildBoundNodes, resultType); } else { ArrayBuilder<Symbol> symbols = ArrayBuilder<Symbol>.GetInstance(); expr.GetExpressionSymbols(symbols, parent: null, binder: this); return new BoundBadExpression( expr.Syntax, resultKind, symbols.ToImmutableAndFree(), ImmutableArray.Create(BindToTypeForErrorRecovery(expr)), resultType ?? CreateErrorType()); } } internal NamedTypeSymbol CreateErrorType(string name = "") { return new ExtendedErrorTypeSymbol(this.Compilation, name, arity: 0, errorInfo: null, unreported: false); } /// <summary> /// Bind the expression and verify the expression matches the combination of lvalue and /// rvalue requirements given by valueKind. If the expression was bound successfully, but /// did not meet the requirements, the return value will be a <see cref="BoundBadExpression"/> that /// (typically) wraps the subexpression. /// </summary> internal BoundExpression BindValue(ExpressionSyntax node, BindingDiagnosticBag diagnostics, BindValueKind valueKind) { var result = this.BindExpression(node, diagnostics: diagnostics, invoked: false, indexed: false); return CheckValue(result, valueKind, diagnostics); } internal BoundExpression BindRValueWithoutTargetType(ExpressionSyntax node, BindingDiagnosticBag diagnostics, bool reportNoTargetType = true) { return BindToNaturalType(BindValue(node, diagnostics, BindValueKind.RValue), diagnostics, reportNoTargetType); } /// <summary> /// When binding a switch case's expression, it is possible that it resolves to a type (technically, a type pattern). /// This implementation permits either an rvalue or a BoundTypeExpression. /// </summary> internal BoundExpression BindTypeOrRValue(ExpressionSyntax node, BindingDiagnosticBag diagnostics) { var valueOrType = BindExpression(node, diagnostics: diagnostics, invoked: false, indexed: false); if (valueOrType.Kind == BoundKind.TypeExpression) { // In the Color Color case (Kind == BoundKind.TypeOrValueExpression), we treat it as a value // by not entering this if statement return valueOrType; } return CheckValue(valueOrType, BindValueKind.RValue, diagnostics); } internal BoundExpression BindToTypeForErrorRecovery(BoundExpression expression, TypeSymbol type = null) { if (expression is null) return null; var result = !expression.NeedsToBeConverted() ? expression : type is null ? BindToNaturalType(expression, BindingDiagnosticBag.Discarded, reportNoTargetType: false) : GenerateConversionForAssignment(type, expression, BindingDiagnosticBag.Discarded); return result; } /// <summary> /// Bind an rvalue expression to its natural type. For example, a switch expression that has not been /// converted to another type has to be converted to its own natural type by applying a conversion to /// that type to each of the arms of the switch expression. This method is a bottleneck for ensuring /// that such a conversion occurs when needed. It also handles tuple expressions which need to be /// converted to their own natural type because they may contain switch expressions. /// </summary> internal BoundExpression BindToNaturalType(BoundExpression expression, BindingDiagnosticBag diagnostics, bool reportNoTargetType = true) { if (!expression.NeedsToBeConverted()) return expression; BoundExpression result; switch (expression) { case BoundUnconvertedSwitchExpression expr: { var commonType = expr.Type; var exprSyntax = (SwitchExpressionSyntax)expr.Syntax; bool hasErrors = expression.HasErrors; if (commonType is null) { diagnostics.Add(ErrorCode.ERR_SwitchExpressionNoBestType, exprSyntax.SwitchKeyword.GetLocation()); commonType = CreateErrorType(); hasErrors = true; } result = ConvertSwitchExpression(expr, commonType, conversionIfTargetTyped: null, diagnostics, hasErrors); } break; case BoundUnconvertedConditionalOperator op: { TypeSymbol type = op.Type; bool hasErrors = op.HasErrors; if (type is null) { Debug.Assert(op.NoCommonTypeError != 0); type = CreateErrorType(); hasErrors = true; object trueArg = op.Consequence.Display; object falseArg = op.Alternative.Display; if (op.NoCommonTypeError == ErrorCode.ERR_InvalidQM && trueArg is Symbol trueSymbol && falseArg is Symbol falseSymbol) { // ERR_InvalidQM is an error that there is no conversion between the two types. They might be the same // type name from different assemblies, so we disambiguate the display. SymbolDistinguisher distinguisher = new SymbolDistinguisher(this.Compilation, trueSymbol, falseSymbol); trueArg = distinguisher.First; falseArg = distinguisher.Second; } diagnostics.Add(op.NoCommonTypeError, op.Syntax.Location, trueArg, falseArg); } result = ConvertConditionalExpression(op, type, conversionIfTargetTyped: null, diagnostics, hasErrors); } break; case BoundTupleLiteral sourceTuple: { var boundArgs = ArrayBuilder<BoundExpression>.GetInstance(sourceTuple.Arguments.Length); foreach (var arg in sourceTuple.Arguments) { boundArgs.Add(BindToNaturalType(arg, diagnostics, reportNoTargetType)); } result = new BoundConvertedTupleLiteral( sourceTuple.Syntax, sourceTuple, wasTargetTyped: false, boundArgs.ToImmutableAndFree(), sourceTuple.ArgumentNamesOpt, sourceTuple.InferredNamesOpt, sourceTuple.Type, // same type to keep original element names sourceTuple.HasErrors).WithSuppression(sourceTuple.IsSuppressed); } break; case BoundDefaultLiteral defaultExpr: { if (reportNoTargetType) { // In some cases, we let the caller report the error diagnostics.Add(ErrorCode.ERR_DefaultLiteralNoTargetType, defaultExpr.Syntax.GetLocation()); } result = new BoundDefaultExpression( defaultExpr.Syntax, targetType: null, defaultExpr.ConstantValue, CreateErrorType(), hasErrors: true).WithSuppression(defaultExpr.IsSuppressed); } break; case BoundStackAllocArrayCreation { Type: null } boundStackAlloc: { // This is a context in which the stackalloc could be either a pointer // or a span. For backward compatibility we treat it as a pointer. var type = new PointerTypeSymbol(TypeWithAnnotations.Create(boundStackAlloc.ElementType)); result = GenerateConversionForAssignment(type, boundStackAlloc, diagnostics); } break; case BoundUnconvertedObjectCreationExpression expr: { if (reportNoTargetType && !expr.HasAnyErrors) { diagnostics.Add(ErrorCode.ERR_ImplicitObjectCreationNoTargetType, expr.Syntax.GetLocation(), expr.Display); } result = BindObjectCreationForErrorRecovery(expr, diagnostics); } break; case BoundUnconvertedInterpolatedString unconvertedInterpolatedString: { result = BindUnconvertedInterpolatedStringToString(unconvertedInterpolatedString, diagnostics); } break; default: result = expression; break; } return result?.WithWasConverted(); } internal BoundExpression BindValueAllowArgList(ExpressionSyntax node, BindingDiagnosticBag diagnostics, BindValueKind valueKind) { var result = this.BindExpressionAllowArgList(node, diagnostics: diagnostics); return CheckValue(result, valueKind, diagnostics); } internal BoundFieldEqualsValue BindFieldInitializer( FieldSymbol field, EqualsValueClauseSyntax initializerOpt, BindingDiagnosticBag diagnostics) { Debug.Assert((object)this.ContainingMemberOrLambda == field); if (initializerOpt == null) { return null; } Binder initializerBinder = this.GetBinder(initializerOpt); Debug.Assert(initializerBinder != null); BoundExpression result = initializerBinder.BindVariableOrAutoPropInitializerValue(initializerOpt, RefKind.None, field.GetFieldType(initializerBinder.FieldsBeingBound).Type, diagnostics); return new BoundFieldEqualsValue(initializerOpt, field, initializerBinder.GetDeclaredLocalsForScope(initializerOpt), result); } internal BoundExpression BindVariableOrAutoPropInitializerValue( EqualsValueClauseSyntax initializerOpt, RefKind refKind, TypeSymbol varType, BindingDiagnosticBag diagnostics) { if (initializerOpt == null) { return null; } BindValueKind valueKind; ExpressionSyntax value; IsInitializerRefKindValid(initializerOpt, initializerOpt, refKind, diagnostics, out valueKind, out value); BoundExpression initializer = BindPossibleArrayInitializer(value, varType, valueKind, diagnostics); initializer = GenerateConversionForAssignment(varType, initializer, diagnostics); return initializer; } internal Binder CreateBinderForParameterDefaultValue( ParameterSymbol parameter, EqualsValueClauseSyntax defaultValueSyntax) { var binder = new LocalScopeBinder(this.WithContainingMemberOrLambda(parameter.ContainingSymbol).WithAdditionalFlags(BinderFlags.ParameterDefaultValue)); return new ExecutableCodeBinder(defaultValueSyntax, parameter.ContainingSymbol, binder); } internal BoundParameterEqualsValue BindParameterDefaultValue( EqualsValueClauseSyntax defaultValueSyntax, ParameterSymbol parameter, BindingDiagnosticBag diagnostics, out BoundExpression valueBeforeConversion) { Debug.Assert(this.InParameterDefaultValue); Debug.Assert(this.ContainingMemberOrLambda.Kind == SymbolKind.Method || this.ContainingMemberOrLambda.Kind == SymbolKind.Property); // UNDONE: The binding and conversion has to be executed in a checked context. Binder defaultValueBinder = this.GetBinder(defaultValueSyntax); Debug.Assert(defaultValueBinder != null); valueBeforeConversion = defaultValueBinder.BindValue(defaultValueSyntax.Value, diagnostics, BindValueKind.RValue); // Always generate the conversion, even if the expression is not convertible to the given type. // We want the erroneous conversion in the tree. var result = new BoundParameterEqualsValue(defaultValueSyntax, parameter, defaultValueBinder.GetDeclaredLocalsForScope(defaultValueSyntax), defaultValueBinder.GenerateConversionForAssignment(parameter.Type, valueBeforeConversion, diagnostics, isDefaultParameter: true)); return result; } internal BoundFieldEqualsValue BindEnumConstantInitializer( SourceEnumConstantSymbol symbol, EqualsValueClauseSyntax equalsValueSyntax, BindingDiagnosticBag diagnostics) { Binder initializerBinder = this.GetBinder(equalsValueSyntax); Debug.Assert(initializerBinder != null); var initializer = initializerBinder.BindValue(equalsValueSyntax.Value, diagnostics, BindValueKind.RValue); initializer = initializerBinder.GenerateConversionForAssignment(symbol.ContainingType.EnumUnderlyingType, initializer, diagnostics); return new BoundFieldEqualsValue(equalsValueSyntax, symbol, initializerBinder.GetDeclaredLocalsForScope(equalsValueSyntax), initializer); } public BoundExpression BindExpression(ExpressionSyntax node, BindingDiagnosticBag diagnostics) { return BindExpression(node, diagnostics: diagnostics, invoked: false, indexed: false); } protected BoundExpression BindExpression(ExpressionSyntax node, BindingDiagnosticBag diagnostics, bool invoked, bool indexed) { BoundExpression expr = BindExpressionInternal(node, diagnostics, invoked, indexed); VerifyUnchecked(node, diagnostics, expr); if (expr.Kind == BoundKind.ArgListOperator) { // CS0226: An __arglist expression may only appear inside of a call or new expression Error(diagnostics, ErrorCode.ERR_IllegalArglist, node); expr = ToBadExpression(expr); } return expr; } // PERF: allowArgList is not a parameter because it is fairly uncommon case where arglists are allowed // so we do not want to pass that argument to every BindExpression which is often recursive // and extra arguments contribute to the stack size. protected BoundExpression BindExpressionAllowArgList(ExpressionSyntax node, BindingDiagnosticBag diagnostics) { BoundExpression expr = BindExpressionInternal(node, diagnostics, invoked: false, indexed: false); VerifyUnchecked(node, diagnostics, expr); return expr; } private void VerifyUnchecked(ExpressionSyntax node, BindingDiagnosticBag diagnostics, BoundExpression expr) { if (!expr.HasAnyErrors && !IsInsideNameof) { TypeSymbol exprType = expr.Type; if ((object)exprType != null && exprType.IsUnsafe()) { ReportUnsafeIfNotAllowed(node, diagnostics); //CONSIDER: Return a bad expression so that HasErrors is true? } } } private BoundExpression BindExpressionInternal(ExpressionSyntax node, BindingDiagnosticBag diagnostics, bool invoked, bool indexed) { if (IsEarlyAttributeBinder && !EarlyWellKnownAttributeBinder.CanBeValidAttributeArgument(node, this)) { return BadExpression(node, LookupResultKind.NotAValue); } Debug.Assert(node != null); switch (node.Kind()) { case SyntaxKind.AnonymousMethodExpression: case SyntaxKind.ParenthesizedLambdaExpression: case SyntaxKind.SimpleLambdaExpression: return BindAnonymousFunction((AnonymousFunctionExpressionSyntax)node, diagnostics); case SyntaxKind.ThisExpression: return BindThis((ThisExpressionSyntax)node, diagnostics); case SyntaxKind.BaseExpression: return BindBase((BaseExpressionSyntax)node, diagnostics); case SyntaxKind.InvocationExpression: return BindInvocationExpression((InvocationExpressionSyntax)node, diagnostics); case SyntaxKind.ArrayInitializerExpression: return BindUnexpectedArrayInitializer((InitializerExpressionSyntax)node, diagnostics, ErrorCode.ERR_ArrayInitInBadPlace); case SyntaxKind.ArrayCreationExpression: return BindArrayCreationExpression((ArrayCreationExpressionSyntax)node, diagnostics); case SyntaxKind.ImplicitArrayCreationExpression: return BindImplicitArrayCreationExpression((ImplicitArrayCreationExpressionSyntax)node, diagnostics); case SyntaxKind.StackAllocArrayCreationExpression: return BindStackAllocArrayCreationExpression((StackAllocArrayCreationExpressionSyntax)node, diagnostics); case SyntaxKind.ImplicitStackAllocArrayCreationExpression: return BindImplicitStackAllocArrayCreationExpression((ImplicitStackAllocArrayCreationExpressionSyntax)node, diagnostics); case SyntaxKind.ObjectCreationExpression: return BindObjectCreationExpression((ObjectCreationExpressionSyntax)node, diagnostics); case SyntaxKind.ImplicitObjectCreationExpression: return BindImplicitObjectCreationExpression((ImplicitObjectCreationExpressionSyntax)node, diagnostics); case SyntaxKind.IdentifierName: case SyntaxKind.GenericName: return BindIdentifier((SimpleNameSyntax)node, invoked, indexed, diagnostics); case SyntaxKind.SimpleMemberAccessExpression: case SyntaxKind.PointerMemberAccessExpression: return BindMemberAccess((MemberAccessExpressionSyntax)node, invoked, indexed, diagnostics: diagnostics); case SyntaxKind.SimpleAssignmentExpression: return BindAssignment((AssignmentExpressionSyntax)node, diagnostics); case SyntaxKind.CastExpression: return BindCast((CastExpressionSyntax)node, diagnostics); case SyntaxKind.ElementAccessExpression: return BindElementAccess((ElementAccessExpressionSyntax)node, diagnostics); case SyntaxKind.AddExpression: case SyntaxKind.MultiplyExpression: case SyntaxKind.SubtractExpression: case SyntaxKind.DivideExpression: case SyntaxKind.ModuloExpression: case SyntaxKind.EqualsExpression: case SyntaxKind.NotEqualsExpression: case SyntaxKind.GreaterThanExpression: case SyntaxKind.LessThanExpression: case SyntaxKind.GreaterThanOrEqualExpression: case SyntaxKind.LessThanOrEqualExpression: case SyntaxKind.BitwiseAndExpression: case SyntaxKind.BitwiseOrExpression: case SyntaxKind.ExclusiveOrExpression: case SyntaxKind.LeftShiftExpression: case SyntaxKind.RightShiftExpression: return BindSimpleBinaryOperator((BinaryExpressionSyntax)node, diagnostics); case SyntaxKind.LogicalAndExpression: case SyntaxKind.LogicalOrExpression: return BindConditionalLogicalOperator((BinaryExpressionSyntax)node, diagnostics); case SyntaxKind.CoalesceExpression: return BindNullCoalescingOperator((BinaryExpressionSyntax)node, diagnostics); case SyntaxKind.ConditionalAccessExpression: return BindConditionalAccessExpression((ConditionalAccessExpressionSyntax)node, diagnostics); case SyntaxKind.MemberBindingExpression: return BindMemberBindingExpression((MemberBindingExpressionSyntax)node, invoked, indexed, diagnostics); case SyntaxKind.ElementBindingExpression: return BindElementBindingExpression((ElementBindingExpressionSyntax)node, diagnostics); case SyntaxKind.IsExpression: return BindIsOperator((BinaryExpressionSyntax)node, diagnostics); case SyntaxKind.AsExpression: return BindAsOperator((BinaryExpressionSyntax)node, diagnostics); case SyntaxKind.UnaryPlusExpression: case SyntaxKind.UnaryMinusExpression: case SyntaxKind.LogicalNotExpression: case SyntaxKind.BitwiseNotExpression: return BindUnaryOperator((PrefixUnaryExpressionSyntax)node, diagnostics); case SyntaxKind.IndexExpression: return BindFromEndIndexExpression((PrefixUnaryExpressionSyntax)node, diagnostics); case SyntaxKind.RangeExpression: return BindRangeExpression((RangeExpressionSyntax)node, diagnostics); case SyntaxKind.AddressOfExpression: return BindAddressOfExpression((PrefixUnaryExpressionSyntax)node, diagnostics); case SyntaxKind.PointerIndirectionExpression: return BindPointerIndirectionExpression((PrefixUnaryExpressionSyntax)node, diagnostics); case SyntaxKind.PostIncrementExpression: case SyntaxKind.PostDecrementExpression: return BindIncrementOperator(node, ((PostfixUnaryExpressionSyntax)node).Operand, ((PostfixUnaryExpressionSyntax)node).OperatorToken, diagnostics); case SyntaxKind.PreIncrementExpression: case SyntaxKind.PreDecrementExpression: return BindIncrementOperator(node, ((PrefixUnaryExpressionSyntax)node).Operand, ((PrefixUnaryExpressionSyntax)node).OperatorToken, diagnostics); case SyntaxKind.ConditionalExpression: return BindConditionalOperator((ConditionalExpressionSyntax)node, diagnostics); case SyntaxKind.SwitchExpression: return BindSwitchExpression((SwitchExpressionSyntax)node, diagnostics); case SyntaxKind.NumericLiteralExpression: case SyntaxKind.StringLiteralExpression: case SyntaxKind.CharacterLiteralExpression: case SyntaxKind.TrueLiteralExpression: case SyntaxKind.FalseLiteralExpression: case SyntaxKind.NullLiteralExpression: return BindLiteralConstant((LiteralExpressionSyntax)node, diagnostics); case SyntaxKind.DefaultLiteralExpression: return new BoundDefaultLiteral(node); case SyntaxKind.ParenthesizedExpression: // Parenthesis tokens are ignored, and operand is bound in the context of parent // expression. return BindParenthesizedExpression(((ParenthesizedExpressionSyntax)node).Expression, diagnostics); case SyntaxKind.UncheckedExpression: case SyntaxKind.CheckedExpression: return BindCheckedExpression((CheckedExpressionSyntax)node, diagnostics); case SyntaxKind.DefaultExpression: return BindDefaultExpression((DefaultExpressionSyntax)node, diagnostics); case SyntaxKind.TypeOfExpression: return BindTypeOf((TypeOfExpressionSyntax)node, diagnostics); case SyntaxKind.SizeOfExpression: return BindSizeOf((SizeOfExpressionSyntax)node, diagnostics); case SyntaxKind.AddAssignmentExpression: case SyntaxKind.AndAssignmentExpression: case SyntaxKind.DivideAssignmentExpression: case SyntaxKind.ExclusiveOrAssignmentExpression: case SyntaxKind.LeftShiftAssignmentExpression: case SyntaxKind.ModuloAssignmentExpression: case SyntaxKind.MultiplyAssignmentExpression: case SyntaxKind.OrAssignmentExpression: case SyntaxKind.RightShiftAssignmentExpression: case SyntaxKind.SubtractAssignmentExpression: return BindCompoundAssignment((AssignmentExpressionSyntax)node, diagnostics); case SyntaxKind.CoalesceAssignmentExpression: return BindNullCoalescingAssignmentOperator((AssignmentExpressionSyntax)node, diagnostics); case SyntaxKind.AliasQualifiedName: case SyntaxKind.PredefinedType: return this.BindNamespaceOrType(node, diagnostics); case SyntaxKind.QueryExpression: return this.BindQuery((QueryExpressionSyntax)node, diagnostics); case SyntaxKind.AnonymousObjectCreationExpression: return BindAnonymousObjectCreation((AnonymousObjectCreationExpressionSyntax)node, diagnostics); case SyntaxKind.QualifiedName: return BindQualifiedName((QualifiedNameSyntax)node, diagnostics); case SyntaxKind.ComplexElementInitializerExpression: return BindUnexpectedComplexElementInitializer((InitializerExpressionSyntax)node, diagnostics); case SyntaxKind.ArgListExpression: return BindArgList(node, diagnostics); case SyntaxKind.RefTypeExpression: return BindRefType((RefTypeExpressionSyntax)node, diagnostics); case SyntaxKind.MakeRefExpression: return BindMakeRef((MakeRefExpressionSyntax)node, diagnostics); case SyntaxKind.RefValueExpression: return BindRefValue((RefValueExpressionSyntax)node, diagnostics); case SyntaxKind.AwaitExpression: return BindAwait((AwaitExpressionSyntax)node, diagnostics); case SyntaxKind.OmittedArraySizeExpression: case SyntaxKind.OmittedTypeArgument: case SyntaxKind.ObjectInitializerExpression: // Not reachable during method body binding, but // may be used by SemanticModel for error cases. return BadExpression(node); case SyntaxKind.NullableType: // Not reachable during method body binding, but // may be used by SemanticModel for error cases. // NOTE: This happens when there's a problem with the Nullable<T> type (e.g. it's missing). // There is no corresponding problem for array or pointer types (which seem analogous), since // they are not constructed types; the element type can be an error type, but the array/pointer // type cannot. return BadExpression(node); case SyntaxKind.InterpolatedStringExpression: return BindInterpolatedString((InterpolatedStringExpressionSyntax)node, diagnostics); case SyntaxKind.IsPatternExpression: return BindIsPatternExpression((IsPatternExpressionSyntax)node, diagnostics); case SyntaxKind.TupleExpression: return BindTupleExpression((TupleExpressionSyntax)node, diagnostics); case SyntaxKind.ThrowExpression: return BindThrowExpression((ThrowExpressionSyntax)node, diagnostics); case SyntaxKind.RefType: return BindRefType(node, diagnostics); case SyntaxKind.RefExpression: return BindRefExpression(node, diagnostics); case SyntaxKind.DeclarationExpression: return BindDeclarationExpressionAsError((DeclarationExpressionSyntax)node, diagnostics); case SyntaxKind.SuppressNullableWarningExpression: return BindSuppressNullableWarningExpression((PostfixUnaryExpressionSyntax)node, diagnostics); case SyntaxKind.WithExpression: return BindWithExpression((WithExpressionSyntax)node, diagnostics); 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. Debug.Assert(false, "Unexpected SyntaxKind " + node.Kind()); diagnostics.Add(ErrorCode.ERR_InternalError, node.Location); return BadExpression(node); } } #nullable enable internal virtual BoundSwitchExpressionArm BindSwitchExpressionArm(SwitchExpressionArmSyntax node, TypeSymbol switchGoverningType, uint switchGoverningValEscape, BindingDiagnosticBag diagnostics) { return this.NextRequired.BindSwitchExpressionArm(node, switchGoverningType, switchGoverningValEscape, diagnostics); } #nullable disable private BoundExpression BindRefExpression(ExpressionSyntax node, BindingDiagnosticBag diagnostics) { var firstToken = node.GetFirstToken(); diagnostics.Add(ErrorCode.ERR_UnexpectedToken, firstToken.GetLocation(), firstToken.ValueText); return new BoundBadExpression( node, LookupResultKind.Empty, ImmutableArray<Symbol>.Empty, ImmutableArray<BoundExpression>.Empty, CreateErrorType("ref")); } private BoundExpression BindRefType(ExpressionSyntax node, BindingDiagnosticBag diagnostics) { var firstToken = node.GetFirstToken(); diagnostics.Add(ErrorCode.ERR_UnexpectedToken, firstToken.GetLocation(), firstToken.ValueText); return new BoundTypeExpression(node, null, CreateErrorType("ref")); } private BoundExpression BindThrowExpression(ThrowExpressionSyntax node, BindingDiagnosticBag diagnostics) { bool hasErrors = node.HasErrors; if (!IsThrowExpressionInProperContext(node)) { diagnostics.Add(ErrorCode.ERR_ThrowMisplaced, node.ThrowKeyword.GetLocation()); hasErrors = true; } var thrownExpression = BindThrownExpression(node.Expression, diagnostics, ref hasErrors); return new BoundThrowExpression(node, thrownExpression, null, hasErrors); } private static bool IsThrowExpressionInProperContext(ThrowExpressionSyntax node) { var parent = node.Parent; if (parent == null || node.HasErrors) { return true; } switch (parent.Kind()) { case SyntaxKind.ConditionalExpression: // ?: { var conditionalParent = (ConditionalExpressionSyntax)parent; return node == conditionalParent.WhenTrue || node == conditionalParent.WhenFalse; } case SyntaxKind.CoalesceExpression: // ?? { var binaryParent = (BinaryExpressionSyntax)parent; return node == binaryParent.Right; } case SyntaxKind.SwitchExpressionArm: case SyntaxKind.ArrowExpressionClause: case SyntaxKind.ParenthesizedLambdaExpression: case SyntaxKind.SimpleLambdaExpression: return true; // We do not support && and || because // 1. The precedence would not syntactically allow it // 2. It isn't clear what the semantics should be // 3. It isn't clear what use cases would motivate us to change the precedence to support it default: return false; } } // Bind a declaration expression where it isn't permitted. private BoundExpression BindDeclarationExpressionAsError(DeclarationExpressionSyntax node, BindingDiagnosticBag diagnostics) { // This is an error, as declaration expressions are handled specially in every context in which // they are permitted. So we have a context in which they are *not* permitted. Nevertheless, we // bind it and then give one nice message. bool isVar; bool isConst = false; AliasSymbol alias; var declType = BindVariableTypeWithAnnotations(node.Designation, diagnostics, node.Type, ref isConst, out isVar, out alias); Error(diagnostics, ErrorCode.ERR_DeclarationExpressionNotPermitted, node); return BindDeclarationVariablesForErrorRecovery(declType, node.Designation, node, diagnostics); } /// <summary> /// Bind a declaration variable where it isn't permitted. The caller is expected to produce a diagnostic. /// </summary> private BoundExpression BindDeclarationVariablesForErrorRecovery(TypeWithAnnotations declTypeWithAnnotations, VariableDesignationSyntax node, CSharpSyntaxNode syntax, BindingDiagnosticBag diagnostics) { declTypeWithAnnotations = declTypeWithAnnotations.HasType ? declTypeWithAnnotations : TypeWithAnnotations.Create(CreateErrorType("var")); switch (node.Kind()) { case SyntaxKind.SingleVariableDesignation: { var single = (SingleVariableDesignationSyntax)node; var result = BindDeconstructionVariable(declTypeWithAnnotations, single, syntax, diagnostics); return BindToTypeForErrorRecovery(result); } case SyntaxKind.DiscardDesignation: { return BindDiscardExpression(syntax, declTypeWithAnnotations); } case SyntaxKind.ParenthesizedVariableDesignation: { var tuple = (ParenthesizedVariableDesignationSyntax)node; int count = tuple.Variables.Count; var builder = ArrayBuilder<BoundExpression>.GetInstance(count); var namesBuilder = ArrayBuilder<string>.GetInstance(count); foreach (var n in tuple.Variables) { builder.Add(BindDeclarationVariablesForErrorRecovery(declTypeWithAnnotations, n, n, diagnostics)); namesBuilder.Add(InferTupleElementName(n)); } ImmutableArray<BoundExpression> subExpressions = builder.ToImmutableAndFree(); var uniqueFieldNames = PooledHashSet<string>.GetInstance(); RemoveDuplicateInferredTupleNamesAndFreeIfEmptied(ref namesBuilder, uniqueFieldNames); uniqueFieldNames.Free(); ImmutableArray<string> tupleNames = namesBuilder is null ? default : namesBuilder.ToImmutableAndFree(); ImmutableArray<bool> inferredPositions = tupleNames.IsDefault ? default : tupleNames.SelectAsArray(n => n != null); bool disallowInferredNames = this.Compilation.LanguageVersion.DisallowInferredTupleElementNames(); // We will not check constraints at this point as this code path // is failure-only and the caller is expected to produce a diagnostic. var tupleType = NamedTypeSymbol.CreateTuple( locationOpt: null, subExpressions.SelectAsArray(e => TypeWithAnnotations.Create(e.Type)), elementLocations: default, tupleNames, Compilation, shouldCheckConstraints: false, includeNullability: false, errorPositions: disallowInferredNames ? inferredPositions : default); return new BoundConvertedTupleLiteral(syntax, sourceTuple: null, wasTargetTyped: true, subExpressions, tupleNames, inferredPositions, tupleType); } default: throw ExceptionUtilities.UnexpectedValue(node.Kind()); } } private BoundExpression BindTupleExpression(TupleExpressionSyntax node, BindingDiagnosticBag diagnostics) { SeparatedSyntaxList<ArgumentSyntax> arguments = node.Arguments; int numElements = arguments.Count; if (numElements < 2) { // this should be a parse error already. var args = numElements == 1 ? ImmutableArray.Create(BindValue(arguments[0].Expression, diagnostics, BindValueKind.RValue)) : ImmutableArray<BoundExpression>.Empty; return BadExpression(node, args); } bool hasNaturalType = true; var boundArguments = ArrayBuilder<BoundExpression>.GetInstance(arguments.Count); var elementTypesWithAnnotations = ArrayBuilder<TypeWithAnnotations>.GetInstance(arguments.Count); var elementLocations = ArrayBuilder<Location>.GetInstance(arguments.Count); // prepare names var (elementNames, inferredPositions, hasErrors) = ExtractTupleElementNames(arguments, diagnostics); // prepare types and locations for (int i = 0; i < numElements; i++) { ArgumentSyntax argumentSyntax = arguments[i]; IdentifierNameSyntax nameSyntax = argumentSyntax.NameColon?.Name; if (nameSyntax != null) { elementLocations.Add(nameSyntax.Location); } else { elementLocations.Add(argumentSyntax.Location); } BoundExpression boundArgument = BindValue(argumentSyntax.Expression, diagnostics, BindValueKind.RValue); if (boundArgument.Type?.SpecialType == SpecialType.System_Void) { diagnostics.Add(ErrorCode.ERR_VoidInTuple, argumentSyntax.Location); boundArgument = new BoundBadExpression( argumentSyntax, LookupResultKind.Empty, ImmutableArray<Symbol>.Empty, ImmutableArray.Create<BoundExpression>(boundArgument), CreateErrorType("void")); } boundArguments.Add(boundArgument); var elementTypeWithAnnotations = TypeWithAnnotations.Create(boundArgument.Type); elementTypesWithAnnotations.Add(elementTypeWithAnnotations); if (!elementTypeWithAnnotations.HasType) { hasNaturalType = false; } } NamedTypeSymbol tupleTypeOpt = null; var elements = elementTypesWithAnnotations.ToImmutableAndFree(); var locations = elementLocations.ToImmutableAndFree(); if (hasNaturalType) { bool disallowInferredNames = this.Compilation.LanguageVersion.DisallowInferredTupleElementNames(); tupleTypeOpt = NamedTypeSymbol.CreateTuple(node.Location, elements, locations, elementNames, this.Compilation, syntax: node, diagnostics: diagnostics, shouldCheckConstraints: true, includeNullability: false, errorPositions: disallowInferredNames ? inferredPositions : default(ImmutableArray<bool>)); } else { NamedTypeSymbol.VerifyTupleTypePresent(elements.Length, node, this.Compilation, diagnostics); } // Always track the inferred positions in the bound node, so that conversions don't produce a warning // for "dropped names" on tuple literal when the name was inferred. return new BoundTupleLiteral(node, boundArguments.ToImmutableAndFree(), elementNames, inferredPositions, tupleTypeOpt, hasErrors); } private static (ImmutableArray<string> elementNamesArray, ImmutableArray<bool> inferredArray, bool hasErrors) ExtractTupleElementNames( SeparatedSyntaxList<ArgumentSyntax> arguments, BindingDiagnosticBag diagnostics) { bool hasErrors = false; int numElements = arguments.Count; var uniqueFieldNames = PooledHashSet<string>.GetInstance(); ArrayBuilder<string> elementNames = null; ArrayBuilder<string> inferredElementNames = null; for (int i = 0; i < numElements; i++) { ArgumentSyntax argumentSyntax = arguments[i]; IdentifierNameSyntax nameSyntax = argumentSyntax.NameColon?.Name; string name = null; string inferredName = null; if (nameSyntax != null) { name = nameSyntax.Identifier.ValueText; if (diagnostics != null && !CheckTupleMemberName(name, i, argumentSyntax.NameColon.Name, diagnostics, uniqueFieldNames)) { hasErrors = true; } } else { inferredName = InferTupleElementName(argumentSyntax.Expression); } CollectTupleFieldMemberName(name, i, numElements, ref elementNames); CollectTupleFieldMemberName(inferredName, i, numElements, ref inferredElementNames); } RemoveDuplicateInferredTupleNamesAndFreeIfEmptied(ref inferredElementNames, uniqueFieldNames); uniqueFieldNames.Free(); var result = MergeTupleElementNames(elementNames, inferredElementNames); elementNames?.Free(); inferredElementNames?.Free(); return (result.names, result.inferred, hasErrors); } private static (ImmutableArray<string> names, ImmutableArray<bool> inferred) MergeTupleElementNames( ArrayBuilder<string> elementNames, ArrayBuilder<string> inferredElementNames) { if (elementNames == null) { if (inferredElementNames == null) { return (default(ImmutableArray<string>), default(ImmutableArray<bool>)); } else { var finalNames = inferredElementNames.ToImmutable(); return (finalNames, finalNames.SelectAsArray(n => n != null)); } } if (inferredElementNames == null) { return (elementNames.ToImmutable(), default(ImmutableArray<bool>)); } Debug.Assert(elementNames.Count == inferredElementNames.Count); var builder = ArrayBuilder<bool>.GetInstance(elementNames.Count); for (int i = 0; i < elementNames.Count; i++) { string inferredName = inferredElementNames[i]; if (elementNames[i] == null && inferredName != null) { elementNames[i] = inferredName; builder.Add(true); } else { builder.Add(false); } } return (elementNames.ToImmutable(), builder.ToImmutableAndFree()); } /// <summary> /// Removes duplicate entries in <paramref name="inferredElementNames"/> and frees it if only nulls remain. /// </summary> private static void RemoveDuplicateInferredTupleNamesAndFreeIfEmptied(ref ArrayBuilder<string> inferredElementNames, HashSet<string> uniqueFieldNames) { if (inferredElementNames == null) { return; } // Inferred names that duplicate an explicit name or a previous inferred name are tagged for removal var toRemove = PooledHashSet<string>.GetInstance(); foreach (var name in inferredElementNames) { if (name != null && !uniqueFieldNames.Add(name)) { toRemove.Add(name); } } for (int i = 0; i < inferredElementNames.Count; i++) { var inferredName = inferredElementNames[i]; if (inferredName != null && toRemove.Contains(inferredName)) { inferredElementNames[i] = null; } } toRemove.Free(); if (inferredElementNames.All(n => n is null)) { inferredElementNames.Free(); inferredElementNames = null; } } private static string InferTupleElementName(SyntaxNode syntax) { string name = syntax.TryGetInferredMemberName(); // Reserved names are never candidates to be inferred names, at any position if (name == null || NamedTypeSymbol.IsTupleElementNameReserved(name) != -1) { return null; } return name; } private BoundExpression BindRefValue(RefValueExpressionSyntax node, BindingDiagnosticBag diagnostics) { // __refvalue(tr, T) requires that tr be a TypedReference and T be a type. // The result is a *variable* of type T. BoundExpression argument = BindValue(node.Expression, diagnostics, BindValueKind.RValue); bool hasErrors = argument.HasAnyErrors; TypeSymbol typedReferenceType = this.Compilation.GetSpecialType(SpecialType.System_TypedReference); CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); Conversion conversion = this.Conversions.ClassifyConversionFromExpression(argument, typedReferenceType, ref useSiteInfo); diagnostics.Add(node, useSiteInfo); if (!conversion.IsImplicit || !conversion.IsValid) { hasErrors = true; GenerateImplicitConversionError(diagnostics, node, conversion, argument, typedReferenceType); } argument = CreateConversion(argument, conversion, typedReferenceType, diagnostics); TypeWithAnnotations typeWithAnnotations = BindType(node.Type, diagnostics); return new BoundRefValueOperator(node, typeWithAnnotations.NullableAnnotation, argument, typeWithAnnotations.Type, hasErrors); } private BoundExpression BindMakeRef(MakeRefExpressionSyntax node, BindingDiagnosticBag diagnostics) { // __makeref(x) requires that x be a variable, and not be of a restricted type. BoundExpression argument = this.BindValue(node.Expression, diagnostics, BindValueKind.RefOrOut); bool hasErrors = argument.HasAnyErrors; TypeSymbol typedReferenceType = GetSpecialType(SpecialType.System_TypedReference, diagnostics, node); if ((object)argument.Type != null && argument.Type.IsRestrictedType()) { // CS1601: Cannot make reference to variable of type '{0}' Error(diagnostics, ErrorCode.ERR_MethodArgCantBeRefAny, node, argument.Type); hasErrors = true; } // UNDONE: We do not yet implement warnings anywhere for: // UNDONE: * taking a ref to a volatile field // UNDONE: * taking a ref to a "non-agile" field // UNDONE: We should do so here when we implement this feature for regular out/ref parameters. return new BoundMakeRefOperator(node, argument, typedReferenceType, hasErrors); } private BoundExpression BindRefType(RefTypeExpressionSyntax node, BindingDiagnosticBag diagnostics) { // __reftype(x) requires that x be implicitly convertible to TypedReference. BoundExpression argument = BindValue(node.Expression, diagnostics, BindValueKind.RValue); bool hasErrors = argument.HasAnyErrors; TypeSymbol typedReferenceType = this.Compilation.GetSpecialType(SpecialType.System_TypedReference); TypeSymbol typeType = this.GetWellKnownType(WellKnownType.System_Type, diagnostics, node); CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); Conversion conversion = this.Conversions.ClassifyConversionFromExpression(argument, typedReferenceType, ref useSiteInfo); diagnostics.Add(node, useSiteInfo); if (!conversion.IsImplicit || !conversion.IsValid) { hasErrors = true; GenerateImplicitConversionError(diagnostics, node, conversion, argument, typedReferenceType); } argument = CreateConversion(argument, conversion, typedReferenceType, diagnostics); return new BoundRefTypeOperator(node, argument, null, typeType, hasErrors); } private BoundExpression BindArgList(CSharpSyntaxNode node, BindingDiagnosticBag diagnostics) { // There are two forms of __arglist expression. In a method with an __arglist parameter, // it is legal to use __arglist as an expression of type RuntimeArgumentHandle. In // a call to such a method, it is legal to use __arglist(x, y, z) as the final argument. // This method only handles the first usage; the second usage is parsed as a call syntax. // The native compiler allows __arglist in a lambda: // // class C // { // delegate int D(RuntimeArgumentHandle r); // static void M(__arglist) // { // D f = null; // f = r=>f(__arglist); // } // } // // This is clearly wrong. Either the developer intends __arglist to refer to the // arg list of the *lambda*, or to the arg list of *M*. The former makes no sense; // lambdas cannot have an arg list. The latter we have no way to generate code for; // you cannot hoist the arg list to a field of a closure class. // // The native compiler allows this and generates code as though the developer // was attempting to access the arg list of the lambda! We should simply disallow it. TypeSymbol runtimeArgumentHandleType = GetSpecialType(SpecialType.System_RuntimeArgumentHandle, diagnostics, node); MethodSymbol method = this.ContainingMember() as MethodSymbol; bool hasError = false; if ((object)method == null || !method.IsVararg) { // CS0190: The __arglist construct is valid only within a variable argument method Error(diagnostics, ErrorCode.ERR_ArgsInvalid, node); hasError = true; } else { // We're in a varargs method; are we also inside a lambda? Symbol container = this.ContainingMemberOrLambda; if (container != method) { // We also need to report this any time a local variable of a restricted type // would be hoisted into a closure for an anonymous function, iterator or async method. // We do that during the actual rewrites. // CS4013: Instance of type '{0}' cannot be used inside an anonymous function, query expression, iterator block or async method Error(diagnostics, ErrorCode.ERR_SpecialByRefInLambda, node, runtimeArgumentHandleType); hasError = true; } } return new BoundArgList(node, runtimeArgumentHandleType, hasError); } /// <summary> /// This can be reached for the qualified name on the right-hand-side of an `is` operator. /// For compatibility we parse it as a qualified name, as the is-type expression only permitted /// a type on the right-hand-side in C# 6. But the same syntax now, in C# 7 and later, can /// refer to a constant, which would normally be represented as a *simple member access expression*. /// Since the parser cannot distinguish, it parses it as before and depends on the binder /// to handle a qualified name appearing as an expression. /// </summary> private BoundExpression BindQualifiedName(QualifiedNameSyntax node, BindingDiagnosticBag diagnostics) { return BindMemberAccessWithBoundLeft(node, this.BindLeftOfPotentialColorColorMemberAccess(node.Left, diagnostics), node.Right, node.DotToken, invoked: false, indexed: false, diagnostics: diagnostics); } private BoundExpression BindParenthesizedExpression(ExpressionSyntax innerExpression, BindingDiagnosticBag diagnostics) { var result = BindExpression(innerExpression, diagnostics); // A parenthesized expression may not be a namespace or a type. If it is a parenthesized // namespace or type then report the error but let it go; we'll just ignore the // parenthesis and keep on trucking. CheckNotNamespaceOrType(result, diagnostics); return result; } #nullable enable private BoundExpression BindTypeOf(TypeOfExpressionSyntax node, BindingDiagnosticBag diagnostics) { ExpressionSyntax typeSyntax = node.Type; TypeofBinder typeofBinder = new TypeofBinder(typeSyntax, this); //has special handling for unbound types AliasSymbol alias; TypeWithAnnotations typeWithAnnotations = typeofBinder.BindType(typeSyntax, diagnostics, out alias); TypeSymbol type = typeWithAnnotations.Type; bool hasError = false; // NB: Dev10 has an error for typeof(dynamic), but allows typeof(dynamic[]), // typeof(C<dynamic>), etc. if (type.IsDynamic()) { diagnostics.Add(ErrorCode.ERR_BadDynamicTypeof, node.Location); hasError = true; } else if (typeWithAnnotations.NullableAnnotation.IsAnnotated() && type.IsReferenceType) { // error: cannot take the `typeof` a nullable reference type. diagnostics.Add(ErrorCode.ERR_BadNullableTypeof, node.Location); hasError = true; } else if (this.InAttributeArgument && type.ContainsFunctionPointer()) { // https://github.com/dotnet/roslyn/issues/48765 tracks removing this error and properly supporting function // pointers in attribute types. Until then, we don't know how serialize them, so error instead of crashing // during emit. diagnostics.Add(ErrorCode.ERR_FunctionPointerTypesInAttributeNotSupported, node.Location); hasError = true; } BoundTypeExpression boundType = new BoundTypeExpression(typeSyntax, alias, typeWithAnnotations, type.IsErrorType()); return new BoundTypeOfOperator(node, boundType, null, this.GetWellKnownType(WellKnownType.System_Type, diagnostics, node), hasError); } private BoundExpression BindSizeOf(SizeOfExpressionSyntax node, BindingDiagnosticBag diagnostics) { ExpressionSyntax typeSyntax = node.Type; AliasSymbol alias; TypeWithAnnotations typeWithAnnotations = this.BindType(typeSyntax, diagnostics, out alias); TypeSymbol type = typeWithAnnotations.Type; bool typeHasErrors = type.IsErrorType() || CheckManagedAddr(Compilation, type, node.Location, diagnostics); BoundTypeExpression boundType = new BoundTypeExpression(typeSyntax, alias, typeWithAnnotations, typeHasErrors); ConstantValue constantValue = GetConstantSizeOf(type); bool hasErrors = constantValue is null && ReportUnsafeIfNotAllowed(node, diagnostics, type); return new BoundSizeOfOperator(node, boundType, constantValue, this.GetSpecialType(SpecialType.System_Int32, diagnostics, node), hasErrors); } /// <returns>true if managed type-related errors were found, otherwise false.</returns> internal static bool CheckManagedAddr(CSharpCompilation compilation, TypeSymbol type, Location location, BindingDiagnosticBag diagnostics) { var useSiteInfo = new CompoundUseSiteInfo<AssemblySymbol>(diagnostics, compilation.Assembly); var managedKind = type.GetManagedKind(ref useSiteInfo); diagnostics.Add(location, useSiteInfo); return CheckManagedAddr(compilation, type, managedKind, location, diagnostics); } /// <returns>true if managed type-related errors were found, otherwise false.</returns> internal static bool CheckManagedAddr(CSharpCompilation compilation, TypeSymbol type, ManagedKind managedKind, Location location, BindingDiagnosticBag diagnostics) { switch (managedKind) { case ManagedKind.Managed: diagnostics.Add(ErrorCode.ERR_ManagedAddr, location, type); return true; case ManagedKind.UnmanagedWithGenerics when MessageID.IDS_FeatureUnmanagedConstructedTypes.GetFeatureAvailabilityDiagnosticInfo(compilation) is CSDiagnosticInfo diagnosticInfo: diagnostics.Add(diagnosticInfo, location); return true; case ManagedKind.Unknown: throw ExceptionUtilities.UnexpectedValue(managedKind); default: return false; } } #nullable disable internal static ConstantValue GetConstantSizeOf(TypeSymbol type) { return ConstantValue.CreateSizeOf((type.GetEnumUnderlyingType() ?? type).SpecialType); } private BoundExpression BindDefaultExpression(DefaultExpressionSyntax node, BindingDiagnosticBag diagnostics) { TypeWithAnnotations typeWithAnnotations = this.BindType(node.Type, diagnostics, out AliasSymbol alias); var typeExpression = new BoundTypeExpression(node.Type, aliasOpt: alias, typeWithAnnotations); TypeSymbol type = typeWithAnnotations.Type; return new BoundDefaultExpression(node, typeExpression, constantValueOpt: type.GetDefaultValue(), type); } /// <summary> /// Binds a simple identifier. /// </summary> private BoundExpression BindIdentifier( SimpleNameSyntax node, bool invoked, bool indexed, BindingDiagnosticBag diagnostics) { Debug.Assert(node != null); // If the syntax tree is ill-formed and the identifier is missing then we've already // given a parse error. Just return an error local and continue with analysis. if (node.IsMissing) { return BadExpression(node); } // A simple-name is either of the form I or of the form I<A1, ..., AK>, where I is a // single identifier and <A1, ..., AK> is an optional type-argument-list. When no // type-argument-list is specified, consider K to be zero. The simple-name is evaluated // and classified as follows: // If K is zero and the simple-name appears within a block and if the block's (or an // enclosing block's) local variable declaration space contains a local variable, // parameter or constant with name I, then the simple-name refers to that local // variable, parameter or constant and is classified as a variable or value. // If K is zero and the simple-name appears within the body of a generic method // declaration and if that declaration includes a type parameter with name I, then the // simple-name refers to that type parameter. BoundExpression expression; // It's possible that the argument list is malformed; if so, do not attempt to bind it; // just use the null array. int arity = node.Arity; bool hasTypeArguments = arity > 0; SeparatedSyntaxList<TypeSyntax> typeArgumentList = node.Kind() == SyntaxKind.GenericName ? ((GenericNameSyntax)node).TypeArgumentList.Arguments : default(SeparatedSyntaxList<TypeSyntax>); Debug.Assert(arity == typeArgumentList.Count); var typeArgumentsWithAnnotations = hasTypeArguments ? BindTypeArguments(typeArgumentList, diagnostics) : default(ImmutableArray<TypeWithAnnotations>); var lookupResult = LookupResult.GetInstance(); LookupOptions options = LookupOptions.AllMethodsOnArityZero; if (invoked) { options |= LookupOptions.MustBeInvocableIfMember; } if (!IsInMethodBody && !IsInsideNameof) { Debug.Assert((options & LookupOptions.NamespacesOrTypesOnly) == 0); options |= LookupOptions.MustNotBeMethodTypeParameter; } var name = node.Identifier.ValueText; CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); this.LookupSymbolsWithFallback(lookupResult, name, arity: arity, useSiteInfo: ref useSiteInfo, options: options); diagnostics.Add(node, useSiteInfo); if (lookupResult.Kind != LookupResultKind.Empty) { // have we detected an error with the current node? bool isError; var members = ArrayBuilder<Symbol>.GetInstance(); Symbol symbol = GetSymbolOrMethodOrPropertyGroup(lookupResult, node, name, node.Arity, members, diagnostics, out isError, qualifierOpt: null); // reports diagnostics in result. if ((object)symbol == null) { Debug.Assert(members.Count > 0); var receiver = SynthesizeMethodGroupReceiver(node, members); expression = ConstructBoundMemberGroupAndReportOmittedTypeArguments( node, typeArgumentList, typeArgumentsWithAnnotations, receiver, name, members, lookupResult, receiver != null ? BoundMethodGroupFlags.HasImplicitReceiver : BoundMethodGroupFlags.None, isError, diagnostics); ReportSimpleProgramLocalReferencedOutsideOfTopLevelStatement(node, members[0], diagnostics); } else { bool isNamedType = (symbol.Kind == SymbolKind.NamedType) || (symbol.Kind == SymbolKind.ErrorType); if (hasTypeArguments && isNamedType) { symbol = ConstructNamedTypeUnlessTypeArgumentOmitted(node, (NamedTypeSymbol)symbol, typeArgumentList, typeArgumentsWithAnnotations, diagnostics); } expression = BindNonMethod(node, symbol, diagnostics, lookupResult.Kind, indexed, isError); if (!isNamedType && (hasTypeArguments || node.Kind() == SyntaxKind.GenericName)) { Debug.Assert(isError); // Should have been reported by GetSymbolOrMethodOrPropertyGroup. expression = new BoundBadExpression( syntax: node, resultKind: LookupResultKind.WrongArity, symbols: ImmutableArray.Create(symbol), childBoundNodes: ImmutableArray.Create(BindToTypeForErrorRecovery(expression)), type: expression.Type, hasErrors: isError); } } members.Free(); } else { expression = null; if (node is IdentifierNameSyntax identifier) { var type = BindNativeIntegerSymbolIfAny(identifier, diagnostics); if (type is { }) { expression = new BoundTypeExpression(node, null, type); } else if (FallBackOnDiscard(identifier, diagnostics)) { expression = new BoundDiscardExpression(node, type: null); } } // Otherwise, the simple-name is undefined and a compile-time error occurs. if (expression is null) { expression = BadExpression(node); if (lookupResult.Error != null) { Error(diagnostics, lookupResult.Error, node); } else if (IsJoinRangeVariableInLeftKey(node)) { Error(diagnostics, ErrorCode.ERR_QueryOuterKey, node, name); } else if (IsInJoinRightKey(node)) { Error(diagnostics, ErrorCode.ERR_QueryInnerKey, node, name); } else { Error(diagnostics, ErrorCode.ERR_NameNotInContext, node, name); } } } lookupResult.Free(); return expression; } /// <summary> /// Is this is an _ identifier in a context where discards are allowed? /// </summary> private static bool FallBackOnDiscard(IdentifierNameSyntax node, BindingDiagnosticBag diagnostics) { if (!node.Identifier.IsUnderscoreToken()) { return false; } CSharpSyntaxNode containingDeconstruction = node.GetContainingDeconstruction(); bool isDiscard = containingDeconstruction != null || IsOutVarDiscardIdentifier(node); if (isDiscard) { CheckFeatureAvailability(node, MessageID.IDS_FeatureDiscards, diagnostics); } return isDiscard; } private static bool IsOutVarDiscardIdentifier(SimpleNameSyntax node) { Debug.Assert(node.Identifier.IsUnderscoreToken()); CSharpSyntaxNode parent = node.Parent; return (parent?.Kind() == SyntaxKind.Argument && ((ArgumentSyntax)parent).RefOrOutKeyword.Kind() == SyntaxKind.OutKeyword); } private BoundExpression SynthesizeMethodGroupReceiver(CSharpSyntaxNode syntax, ArrayBuilder<Symbol> members) { // SPEC: For each instance type T starting with the instance type of the immediately // SPEC: enclosing type declaration, and continuing with the instance type of each // SPEC: enclosing class or struct declaration, [do a lot of things to find a match]. // SPEC: ... // SPEC: If T is the instance type of the immediately enclosing class or struct type // SPEC: and the lookup identifies one or more methods, the result is a method group // SPEC: with an associated instance expression of this. // Explanation of spec: // // We are looping over a set of types, from inner to outer, attempting to resolve the // meaning of a simple name; for example "M(123)". // // There are a number of possibilities: // // If the lookup finds M in an outer class: // // class Outer { // static void M(int x) {} // class Inner { // void X() { M(123); } // } // } // // or the base class of an outer class: // // class Base { // public static void M(int x) {} // } // class Outer : Base { // class Inner { // void X() { M(123); } // } // } // // Then there is no "associated instance expression" of the method group. That is, there // is no possibility of there being an "implicit this". // // If the lookup finds M on the class that triggered the lookup on the other hand, or // one of its base classes: // // class Base { // public static void M(int x) {} // } // class Derived : Base { // void X() { M(123); } // } // // Then the associated instance expression is "this" *even if one or more methods in the // method group are static*. If it turns out that the method was static, then we'll // check later to determine if there was a receiver actually present in the source code // or not. (That happens during the "final validation" phase of overload resolution. // Implementation explanation: // // If we're here, then lookup has identified one or more methods. Debug.Assert(members.Count > 0); // The lookup implementation loops over the set of types from inner to outer, and stops // when it makes a match. (This is correct because any matches found on more-outer types // would be hidden, and discarded.) This means that we only find members associated with // one containing class or struct. The method is possibly on that type directly, or via // inheritance from a base type of the type. // // The question then is what the "associated instance expression" is; is it "this" or // nothing at all? If the type that we found the method on is the current type, or is a // base type of the current type, then there should be a "this" associated with the // method group. Otherwise, it should be null. var currentType = this.ContainingType; if ((object)currentType == null) { // This may happen if there is no containing type, // e.g. we are binding an expression in an assembly-level attribute return null; } var declaringType = members[0].ContainingType; var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; if (currentType.IsEqualToOrDerivedFrom(declaringType, TypeCompareKind.ConsiderEverything, useSiteInfo: ref discardedUseSiteInfo) || (currentType.IsInterface && (declaringType.IsObjectType() || currentType.AllInterfacesNoUseSiteDiagnostics.Contains(declaringType)))) { return ThisReference(syntax, currentType, wasCompilerGenerated: true); } else { return TryBindInteractiveReceiver(syntax, declaringType); } } private bool IsBadLocalOrParameterCapture(Symbol symbol, TypeSymbol type, RefKind refKind) { if (refKind != RefKind.None || type.IsRefLikeType) { var containingMethod = this.ContainingMemberOrLambda as MethodSymbol; if ((object)containingMethod != null && (object)symbol.ContainingSymbol != (object)containingMethod) { // Not expecting symbol from constructed method. Debug.Assert(!symbol.ContainingSymbol.Equals(containingMethod)); // Captured in a lambda. return (containingMethod.MethodKind == MethodKind.AnonymousFunction || containingMethod.MethodKind == MethodKind.LocalFunction) && !IsInsideNameof; // false in EE evaluation method } } return false; } private BoundExpression BindNonMethod(SimpleNameSyntax node, Symbol symbol, BindingDiagnosticBag diagnostics, LookupResultKind resultKind, bool indexed, bool isError) { // Events are handled later as we don't know yet if we are binding to the event or it's backing field. if (symbol.Kind != SymbolKind.Event) { ReportDiagnosticsIfObsolete(diagnostics, symbol, node, hasBaseReceiver: false); } switch (symbol.Kind) { case SymbolKind.Local: { var localSymbol = (LocalSymbol)symbol; TypeSymbol type; bool isNullableUnknown; if (ReportSimpleProgramLocalReferencedOutsideOfTopLevelStatement(node, localSymbol, diagnostics)) { type = new ExtendedErrorTypeSymbol( this.Compilation, name: "var", arity: 0, errorInfo: null, variableUsedBeforeDeclaration: true); isNullableUnknown = true; } else if (isUsedBeforeDeclaration(node, localSymbol)) { // Here we report a local variable being used before its declaration // // There are two possible diagnostics for this: // // CS0841: ERR_VariableUsedBeforeDeclaration // Cannot use local variable 'x' before it is declared // // CS0844: ERR_VariableUsedBeforeDeclarationAndHidesField // Cannot use local variable 'x' before it is declared. The // declaration of the local variable hides the field 'C.x'. // // There are two situations in which we give these errors. // // First, the scope of a local variable -- that is, the region of program // text in which it can be looked up by name -- is throughout the entire // block which declares it. It is therefore possible to use a local // before it is declared, which is an error. // // As an additional help to the user, we give a special error for this // scenario: // // class C { // int x; // void M() { // Print(x); // int x = 5; // } } // // Because a too-clever C++ user might be attempting to deliberately // bind to "this.x" in the "Print". (In C++ the local does not come // into scope until its declaration.) // FieldSymbol possibleField = null; var lookupResult = LookupResult.GetInstance(); CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); this.LookupMembersInType( lookupResult, ContainingType, localSymbol.Name, arity: 0, basesBeingResolved: null, options: LookupOptions.Default, originalBinder: this, diagnose: false, useSiteInfo: ref useSiteInfo); diagnostics.Add(node, useSiteInfo); possibleField = lookupResult.SingleSymbolOrDefault as FieldSymbol; lookupResult.Free(); if ((object)possibleField != null) { Error(diagnostics, ErrorCode.ERR_VariableUsedBeforeDeclarationAndHidesField, node, node, possibleField); } else { Error(diagnostics, ErrorCode.ERR_VariableUsedBeforeDeclaration, node, node); } type = new ExtendedErrorTypeSymbol( this.Compilation, name: "var", arity: 0, errorInfo: null, variableUsedBeforeDeclaration: true); isNullableUnknown = true; } else if ((localSymbol as SourceLocalSymbol)?.IsVar == true && localSymbol.ForbiddenZone?.Contains(node) == true) { // A var (type-inferred) local variable has been used in its own initialization (the "forbidden zone"). // There are many cases where this occurs, including: // // 1. var x = M(out x); // 2. M(out var x, out x); // 3. var (x, y) = (y, x); // // localSymbol.ForbiddenDiagnostic provides a suitable diagnostic for whichever case applies. // diagnostics.Add(localSymbol.ForbiddenDiagnostic, node.Location, node); type = new ExtendedErrorTypeSymbol( this.Compilation, name: "var", arity: 0, errorInfo: null, variableUsedBeforeDeclaration: true); isNullableUnknown = true; } else { type = localSymbol.Type; isNullableUnknown = false; if (IsBadLocalOrParameterCapture(localSymbol, type, localSymbol.RefKind)) { isError = true; Error(diagnostics, ErrorCode.ERR_AnonDelegateCantUseLocal, node, localSymbol); } } var constantValueOpt = localSymbol.IsConst && !IsInsideNameof && !type.IsErrorType() ? localSymbol.GetConstantValue(node, this.LocalInProgress, diagnostics) : null; return new BoundLocal(node, localSymbol, BoundLocalDeclarationKind.None, constantValueOpt: constantValueOpt, isNullableUnknown: isNullableUnknown, type: type, hasErrors: isError); } case SymbolKind.Parameter: { var parameter = (ParameterSymbol)symbol; if (IsBadLocalOrParameterCapture(parameter, parameter.Type, parameter.RefKind)) { isError = true; Error(diagnostics, ErrorCode.ERR_AnonDelegateCantUse, node, parameter.Name); } return new BoundParameter(node, parameter, hasErrors: isError); } case SymbolKind.NamedType: case SymbolKind.ErrorType: case SymbolKind.TypeParameter: // If I identifies a type, then the result is that type constructed with the // given type arguments. UNDONE: Construct the child type if it is generic! return new BoundTypeExpression(node, null, (TypeSymbol)symbol, hasErrors: isError); case SymbolKind.Property: { BoundExpression receiver = SynthesizeReceiver(node, symbol, diagnostics); return BindPropertyAccess(node, receiver, (PropertySymbol)symbol, diagnostics, resultKind, hasErrors: isError); } case SymbolKind.Event: { BoundExpression receiver = SynthesizeReceiver(node, symbol, diagnostics); return BindEventAccess(node, receiver, (EventSymbol)symbol, diagnostics, resultKind, hasErrors: isError); } case SymbolKind.Field: { BoundExpression receiver = SynthesizeReceiver(node, symbol, diagnostics); return BindFieldAccess(node, receiver, (FieldSymbol)symbol, diagnostics, resultKind, indexed, hasErrors: isError); } case SymbolKind.Namespace: return new BoundNamespaceExpression(node, (NamespaceSymbol)symbol, hasErrors: isError); case SymbolKind.Alias: { var alias = (AliasSymbol)symbol; symbol = alias.Target; switch (symbol.Kind) { case SymbolKind.NamedType: case SymbolKind.ErrorType: return new BoundTypeExpression(node, alias, (NamedTypeSymbol)symbol, hasErrors: isError); case SymbolKind.Namespace: return new BoundNamespaceExpression(node, (NamespaceSymbol)symbol, alias, hasErrors: isError); default: throw ExceptionUtilities.UnexpectedValue(symbol.Kind); } } case SymbolKind.RangeVariable: return BindRangeVariable(node, (RangeVariableSymbol)symbol, diagnostics); default: throw ExceptionUtilities.UnexpectedValue(symbol.Kind); } bool isUsedBeforeDeclaration(SimpleNameSyntax node, LocalSymbol localSymbol) { Location localSymbolLocation = localSymbol.Locations[0]; if (node.SyntaxTree == localSymbolLocation.SourceTree) { return node.SpanStart < localSymbolLocation.SourceSpan.Start; } return false; } } private static bool ReportSimpleProgramLocalReferencedOutsideOfTopLevelStatement(SimpleNameSyntax node, Symbol symbol, BindingDiagnosticBag diagnostics) { if (symbol.ContainingSymbol is SynthesizedSimpleProgramEntryPointSymbol) { if (!SyntaxFacts.IsTopLevelStatement(node.Ancestors(ascendOutOfTrivia: false).OfType<GlobalStatementSyntax>().FirstOrDefault())) { Error(diagnostics, ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, node, node); return true; } } return false; } protected virtual BoundExpression BindRangeVariable(SimpleNameSyntax node, RangeVariableSymbol qv, BindingDiagnosticBag diagnostics) { return Next.BindRangeVariable(node, qv, diagnostics); } private BoundExpression SynthesizeReceiver(SyntaxNode node, Symbol member, BindingDiagnosticBag diagnostics) { // SPEC: Otherwise, if T is the instance type of the immediately enclosing class or // struct type, if the lookup identifies an instance member, and if the reference occurs // within the block of an instance constructor, an instance method, or an instance // accessor, the result is the same as a member access of the form this.I. This can only // happen when K is zero. if (!member.RequiresInstanceReceiver()) { return null; } var currentType = this.ContainingType; var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; NamedTypeSymbol declaringType = member.ContainingType; if (currentType.IsEqualToOrDerivedFrom(declaringType, TypeCompareKind.ConsiderEverything, useSiteInfo: ref discardedUseSiteInfo) || (currentType.IsInterface && (declaringType.IsObjectType() || currentType.AllInterfacesNoUseSiteDiagnostics.Contains(declaringType)))) { bool hasErrors = false; if (EnclosingNameofArgument != node) { if (InFieldInitializer && !currentType.IsScriptClass) { //can't access "this" in field initializers Error(diagnostics, ErrorCode.ERR_FieldInitRefNonstatic, node, member); hasErrors = true; } else if (InConstructorInitializer || InAttributeArgument) { //can't access "this" in constructor initializers or attribute arguments Error(diagnostics, ErrorCode.ERR_ObjectRequired, node, member); hasErrors = true; } else { // not an instance member if the container is a type, like when binding default parameter values. var containingMember = ContainingMember(); bool locationIsInstanceMember = !containingMember.IsStatic && (containingMember.Kind != SymbolKind.NamedType || currentType.IsScriptClass); if (!locationIsInstanceMember) { // error CS0120: An object reference is required for the non-static field, method, or property '{0}' Error(diagnostics, ErrorCode.ERR_ObjectRequired, node, member); hasErrors = true; } } hasErrors = hasErrors || IsRefOrOutThisParameterCaptured(node, diagnostics); } return ThisReference(node, currentType, hasErrors, wasCompilerGenerated: true); } else { return TryBindInteractiveReceiver(node, declaringType); } } internal Symbol ContainingMember() { return this.ContainingMemberOrLambda.ContainingNonLambdaMember(); } private BoundExpression TryBindInteractiveReceiver(SyntaxNode syntax, NamedTypeSymbol memberDeclaringType) { if (this.ContainingType.TypeKind == TypeKind.Submission // check we have access to `this` && isInstanceContext()) { if (memberDeclaringType.TypeKind == TypeKind.Submission) { return new BoundPreviousSubmissionReference(syntax, memberDeclaringType) { WasCompilerGenerated = true }; } else { TypeSymbol hostObjectType = Compilation.GetHostObjectTypeSymbol(); var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; if ((object)hostObjectType != null && hostObjectType.IsEqualToOrDerivedFrom(memberDeclaringType, TypeCompareKind.ConsiderEverything, useSiteInfo: ref discardedUseSiteInfo)) { return new BoundHostObjectMemberReference(syntax, hostObjectType) { WasCompilerGenerated = true }; } } } return null; bool isInstanceContext() { var containingMember = this.ContainingMemberOrLambda; do { if (containingMember.IsStatic) { return false; } if (containingMember.Kind == SymbolKind.NamedType) { break; } containingMember = containingMember.ContainingSymbol; } while ((object)containingMember != null); return true; } } public BoundExpression BindNamespaceOrTypeOrExpression(ExpressionSyntax node, BindingDiagnosticBag diagnostics) { if (node.Kind() == SyntaxKind.PredefinedType) { return this.BindNamespaceOrType(node, diagnostics); } if (SyntaxFacts.IsName(node.Kind())) { if (SyntaxFacts.IsNamespaceAliasQualifier(node)) { return this.BindNamespaceAlias((IdentifierNameSyntax)node, diagnostics); } else if (SyntaxFacts.IsInNamespaceOrTypeContext(node)) { return this.BindNamespaceOrType(node, diagnostics); } } else if (SyntaxFacts.IsTypeSyntax(node.Kind())) { return this.BindNamespaceOrType(node, diagnostics); } return this.BindExpression(node, diagnostics, SyntaxFacts.IsInvoked(node), SyntaxFacts.IsIndexed(node)); } public BoundExpression BindLabel(ExpressionSyntax node, BindingDiagnosticBag diagnostics) { var name = node as IdentifierNameSyntax; if (name == null) { Debug.Assert(node.ContainsDiagnostics); return BadExpression(node, LookupResultKind.NotLabel); } var result = LookupResult.GetInstance(); string labelName = name.Identifier.ValueText; CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); this.LookupSymbolsWithFallback(result, labelName, arity: 0, useSiteInfo: ref useSiteInfo, options: LookupOptions.LabelsOnly); diagnostics.Add(node, useSiteInfo); if (!result.IsMultiViable) { Error(diagnostics, ErrorCode.ERR_LabelNotFound, node, labelName); result.Free(); return BadExpression(node, result.Kind); } Debug.Assert(result.IsSingleViable, "If this happens, we need to deal with multiple label definitions."); var symbol = (LabelSymbol)result.Symbols.First(); result.Free(); return new BoundLabel(node, symbol, null); } public BoundExpression BindNamespaceOrType(ExpressionSyntax node, BindingDiagnosticBag diagnostics) { var symbol = this.BindNamespaceOrTypeOrAliasSymbol(node, diagnostics, null, false); return CreateBoundNamespaceOrTypeExpression(node, symbol.Symbol); } public BoundExpression BindNamespaceAlias(IdentifierNameSyntax node, BindingDiagnosticBag diagnostics) { var symbol = this.BindNamespaceAliasSymbol(node, diagnostics); return CreateBoundNamespaceOrTypeExpression(node, symbol); } private static BoundExpression CreateBoundNamespaceOrTypeExpression(ExpressionSyntax node, Symbol symbol) { var alias = symbol as AliasSymbol; if ((object)alias != null) { symbol = alias.Target; } var type = symbol as TypeSymbol; if ((object)type != null) { return new BoundTypeExpression(node, alias, type); } var namespaceSymbol = symbol as NamespaceSymbol; if ((object)namespaceSymbol != null) { return new BoundNamespaceExpression(node, namespaceSymbol, alias); } throw ExceptionUtilities.UnexpectedValue(symbol); } private BoundThisReference BindThis(ThisExpressionSyntax node, BindingDiagnosticBag diagnostics) { Debug.Assert(node != null); bool hasErrors = true; bool inStaticContext; if (!HasThis(isExplicit: true, inStaticContext: out inStaticContext)) { //this error is returned in the field initializer case Error(diagnostics, inStaticContext ? ErrorCode.ERR_ThisInStaticMeth : ErrorCode.ERR_ThisInBadContext, node); } else { hasErrors = IsRefOrOutThisParameterCaptured(node.Token, diagnostics); } return ThisReference(node, this.ContainingType, hasErrors); } private BoundThisReference ThisReference(SyntaxNode node, NamedTypeSymbol thisTypeOpt, bool hasErrors = false, bool wasCompilerGenerated = false) { return new BoundThisReference(node, thisTypeOpt ?? CreateErrorType(), hasErrors) { WasCompilerGenerated = wasCompilerGenerated }; } private bool IsRefOrOutThisParameterCaptured(SyntaxNodeOrToken thisOrBaseToken, BindingDiagnosticBag diagnostics) { ParameterSymbol thisSymbol = this.ContainingMemberOrLambda.EnclosingThisSymbol(); // If there is no this parameter, then it is definitely not captured and // any diagnostic would be cascading. if ((object)thisSymbol != null && thisSymbol.ContainingSymbol != ContainingMemberOrLambda && thisSymbol.RefKind != RefKind.None) { Error(diagnostics, ErrorCode.ERR_ThisStructNotInAnonMeth, thisOrBaseToken); return true; } return false; } private BoundBaseReference BindBase(BaseExpressionSyntax node, BindingDiagnosticBag diagnostics) { bool hasErrors = false; TypeSymbol baseType = this.ContainingType is null ? null : this.ContainingType.BaseTypeNoUseSiteDiagnostics; bool inStaticContext; if (!HasThis(isExplicit: true, inStaticContext: out inStaticContext)) { //this error is returned in the field initializer case Error(diagnostics, inStaticContext ? ErrorCode.ERR_BaseInStaticMeth : ErrorCode.ERR_BaseInBadContext, node.Token); hasErrors = true; } else if ((object)baseType == null) // e.g. in System.Object { Error(diagnostics, ErrorCode.ERR_NoBaseClass, node); hasErrors = true; } else if (this.ContainingType is null || node.Parent is null || (node.Parent.Kind() != SyntaxKind.SimpleMemberAccessExpression && node.Parent.Kind() != SyntaxKind.ElementAccessExpression)) { Error(diagnostics, ErrorCode.ERR_BaseIllegal, node.Token); hasErrors = true; } else if (IsRefOrOutThisParameterCaptured(node.Token, diagnostics)) { // error has been reported by IsRefOrOutThisParameterCaptured hasErrors = true; } return new BoundBaseReference(node, baseType, hasErrors); } private BoundExpression BindCast(CastExpressionSyntax node, BindingDiagnosticBag diagnostics) { BoundExpression operand = this.BindValue(node.Expression, diagnostics, BindValueKind.RValue); TypeWithAnnotations targetTypeWithAnnotations = this.BindType(node.Type, diagnostics); TypeSymbol targetType = targetTypeWithAnnotations.Type; if (targetType.IsNullableType() && !operand.HasAnyErrors && (object)operand.Type != null && !operand.Type.IsNullableType() && !TypeSymbol.Equals(targetType.GetNullableUnderlyingType(), operand.Type, TypeCompareKind.ConsiderEverything2)) { return BindExplicitNullableCastFromNonNullable(node, operand, targetTypeWithAnnotations, diagnostics); } return BindCastCore(node, operand, targetTypeWithAnnotations, wasCompilerGenerated: operand.WasCompilerGenerated, diagnostics: diagnostics); } private BoundExpression BindFromEndIndexExpression(PrefixUnaryExpressionSyntax node, BindingDiagnosticBag diagnostics) { Debug.Assert(node.OperatorToken.IsKind(SyntaxKind.CaretToken)); CheckFeatureAvailability(node, MessageID.IDS_FeatureIndexOperator, diagnostics); // Used in lowering as the second argument to the constructor. Example: new Index(value, fromEnd: true) GetSpecialType(SpecialType.System_Boolean, diagnostics, node); BoundExpression boundOperand = BindValue(node.Operand, diagnostics, BindValueKind.RValue); TypeSymbol intType = GetSpecialType(SpecialType.System_Int32, diagnostics, node); TypeSymbol indexType = GetWellKnownType(WellKnownType.System_Index, diagnostics, node); if ((object)boundOperand.Type != null && boundOperand.Type.IsNullableType()) { // Used in lowering to construct the nullable GetSpecialTypeMember(SpecialMember.System_Nullable_T__ctor, diagnostics, node); NamedTypeSymbol nullableType = GetSpecialType(SpecialType.System_Nullable_T, diagnostics, node); if (!indexType.IsNonNullableValueType()) { Error(diagnostics, ErrorCode.ERR_ValConstraintNotSatisfied, node, nullableType, nullableType.TypeParameters.Single(), indexType); } intType = nullableType.Construct(intType); indexType = nullableType.Construct(indexType); } CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); Conversion conversion = this.Conversions.ClassifyImplicitConversionFromExpression(boundOperand, intType, ref useSiteInfo); diagnostics.Add(node, useSiteInfo); if (!conversion.IsValid) { GenerateImplicitConversionError(diagnostics, node, conversion, boundOperand, intType); } BoundExpression boundConversion = CreateConversion(boundOperand, conversion, intType, diagnostics); MethodSymbol symbolOpt = GetWellKnownTypeMember(WellKnownMember.System_Index__ctor, diagnostics, syntax: node) as MethodSymbol; return new BoundFromEndIndexExpression(node, boundConversion, symbolOpt, indexType); } private BoundExpression BindRangeExpression(RangeExpressionSyntax node, BindingDiagnosticBag diagnostics) { CheckFeatureAvailability(node, MessageID.IDS_FeatureRangeOperator, diagnostics); TypeSymbol rangeType = GetWellKnownType(WellKnownType.System_Range, diagnostics, node); MethodSymbol symbolOpt = null; if (!rangeType.IsErrorType()) { // Depending on the available arguments to the range expression, there are four // possible well-known members we could bind to. The constructor is always the // fallback member, usable in any situation. However, if any of the other members // are available and applicable, we will prefer that. WellKnownMember? memberOpt = null; if (node.LeftOperand is null && node.RightOperand is null) { memberOpt = WellKnownMember.System_Range__get_All; } else if (node.LeftOperand is null) { memberOpt = WellKnownMember.System_Range__EndAt; } else if (node.RightOperand is null) { memberOpt = WellKnownMember.System_Range__StartAt; } if (memberOpt is object) { symbolOpt = (MethodSymbol)GetWellKnownTypeMember( memberOpt.GetValueOrDefault(), diagnostics, syntax: node, isOptional: true); } if (symbolOpt is null) { symbolOpt = (MethodSymbol)GetWellKnownTypeMember( WellKnownMember.System_Range__ctor, diagnostics, syntax: node); } } BoundExpression left = BindRangeExpressionOperand(node.LeftOperand, diagnostics); BoundExpression right = BindRangeExpressionOperand(node.RightOperand, diagnostics); if (left?.Type.IsNullableType() == true || right?.Type.IsNullableType() == true) { // Used in lowering to construct the nullable GetSpecialType(SpecialType.System_Boolean, diagnostics, node); GetSpecialTypeMember(SpecialMember.System_Nullable_T__ctor, diagnostics, node); NamedTypeSymbol nullableType = GetSpecialType(SpecialType.System_Nullable_T, diagnostics, node); if (!rangeType.IsNonNullableValueType()) { Error(diagnostics, ErrorCode.ERR_ValConstraintNotSatisfied, node, nullableType, nullableType.TypeParameters.Single(), rangeType); } rangeType = nullableType.Construct(rangeType); } return new BoundRangeExpression(node, left, right, symbolOpt, rangeType); } private BoundExpression BindRangeExpressionOperand(ExpressionSyntax operand, BindingDiagnosticBag diagnostics) { if (operand is null) { return null; } BoundExpression boundOperand = BindValue(operand, diagnostics, BindValueKind.RValue); TypeSymbol indexType = GetWellKnownType(WellKnownType.System_Index, diagnostics, operand); if (boundOperand.Type?.IsNullableType() == true) { // Used in lowering to construct the nullable GetSpecialTypeMember(SpecialMember.System_Nullable_T__ctor, diagnostics, operand); NamedTypeSymbol nullableType = GetSpecialType(SpecialType.System_Nullable_T, diagnostics, operand); if (!indexType.IsNonNullableValueType()) { Error(diagnostics, ErrorCode.ERR_ValConstraintNotSatisfied, operand, nullableType, nullableType.TypeParameters.Single(), indexType); } indexType = nullableType.Construct(indexType); } CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); Conversion conversion = this.Conversions.ClassifyImplicitConversionFromExpression(boundOperand, indexType, ref useSiteInfo); diagnostics.Add(operand, useSiteInfo); if (!conversion.IsValid) { GenerateImplicitConversionError(diagnostics, operand, conversion, boundOperand, indexType); } return CreateConversion(boundOperand, conversion, indexType, diagnostics); } private BoundExpression BindCastCore(ExpressionSyntax node, BoundExpression operand, TypeWithAnnotations targetTypeWithAnnotations, bool wasCompilerGenerated, BindingDiagnosticBag diagnostics) { TypeSymbol targetType = targetTypeWithAnnotations.Type; CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); Conversion conversion = this.Conversions.ClassifyConversionFromExpression(operand, targetType, ref useSiteInfo, forCast: true); diagnostics.Add(node, useSiteInfo); var conversionGroup = new ConversionGroup(conversion, targetTypeWithAnnotations); bool suppressErrors = operand.HasAnyErrors || targetType.IsErrorType(); bool hasErrors = !conversion.IsValid || targetType.IsStatic; if (hasErrors && !suppressErrors) { GenerateExplicitConversionErrors(diagnostics, node, conversion, operand, targetType); } return CreateConversion(node, operand, conversion, isCast: true, conversionGroupOpt: conversionGroup, wasCompilerGenerated: wasCompilerGenerated, destination: targetType, diagnostics: diagnostics, hasErrors: hasErrors | suppressErrors); } private void GenerateExplicitConversionErrors( BindingDiagnosticBag diagnostics, SyntaxNode syntax, Conversion conversion, BoundExpression operand, TypeSymbol targetType) { // Make sure that errors within the unbound lambda don't get lost. if (operand.Kind == BoundKind.UnboundLambda) { GenerateAnonymousFunctionConversionError(diagnostics, operand.Syntax, (UnboundLambda)operand, targetType); return; } if (operand.HasAnyErrors || targetType.IsErrorType()) { // an error has already been reported elsewhere return; } if (targetType.IsStatic) { // The specification states in the section titled "Referencing Static // Class Types" that it is always illegal to have a static class in a // cast operator. diagnostics.Add(ErrorCode.ERR_ConvertToStaticClass, syntax.Location, targetType); return; } if (!targetType.IsReferenceType && !targetType.IsNullableType() && operand.IsLiteralNull()) { diagnostics.Add(ErrorCode.ERR_ValueCantBeNull, syntax.Location, targetType); return; } if (conversion.ResultKind == LookupResultKind.OverloadResolutionFailure) { Debug.Assert(conversion.IsUserDefined); ImmutableArray<MethodSymbol> originalUserDefinedConversions = conversion.OriginalUserDefinedConversions; if (originalUserDefinedConversions.Length > 1) { diagnostics.Add(ErrorCode.ERR_AmbigUDConv, syntax.Location, originalUserDefinedConversions[0], originalUserDefinedConversions[1], operand.Display, targetType); } else { Debug.Assert(originalUserDefinedConversions.Length == 0, "How can there be exactly one applicable user-defined conversion if the conversion doesn't exist?"); SymbolDistinguisher distinguisher1 = new SymbolDistinguisher(this.Compilation, operand.Type, targetType); diagnostics.Add(ErrorCode.ERR_NoExplicitConv, syntax.Location, distinguisher1.First, distinguisher1.Second); } return; } switch (operand.Kind) { case BoundKind.MethodGroup: { if (targetType.TypeKind != TypeKind.Delegate || !MethodGroupConversionDoesNotExistOrHasErrors((BoundMethodGroup)operand, (NamedTypeSymbol)targetType, syntax.Location, diagnostics, out _)) { diagnostics.Add(ErrorCode.ERR_NoExplicitConv, syntax.Location, MessageID.IDS_SK_METHOD.Localize(), targetType); } return; } case BoundKind.TupleLiteral: { var tuple = (BoundTupleLiteral)operand; var targetElementTypesWithAnnotations = 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 targetElementTypesWithAnnotations) && targetElementTypesWithAnnotations.Length == tuple.Arguments.Length) { GenerateExplicitConversionErrorsForTupleLiteralArguments(diagnostics, tuple.Arguments, targetElementTypesWithAnnotations); 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.StackAllocArrayCreation: { var stackAllocExpression = (BoundStackAllocArrayCreation)operand; Error(diagnostics, ErrorCode.ERR_StackAllocConversionNotPossible, syntax, stackAllocExpression.ElementType, targetType); return; } case BoundKind.UnconvertedConditionalOperator when operand.Type is null: case BoundKind.UnconvertedSwitchExpression when operand.Type is null: { GenerateImplicitConversionError(diagnostics, operand.Syntax, conversion, operand, targetType); return; } case BoundKind.UnconvertedAddressOfOperator: { var errorCode = targetType.TypeKind switch { TypeKind.FunctionPointer => ErrorCode.ERR_MethFuncPtrMismatch, TypeKind.Delegate => ErrorCode.ERR_CannotConvertAddressOfToDelegate, _ => ErrorCode.ERR_AddressOfToNonFunctionPointer }; diagnostics.Add(errorCode, syntax.Location, ((BoundUnconvertedAddressOfOperator)operand).Operand.Name, targetType); return; } } Debug.Assert((object)operand.Type != null); SymbolDistinguisher distinguisher = new SymbolDistinguisher(this.Compilation, operand.Type, targetType); diagnostics.Add(ErrorCode.ERR_NoExplicitConv, syntax.Location, distinguisher.First, distinguisher.Second); } private void GenerateExplicitConversionErrorsForTupleLiteralArguments( BindingDiagnosticBag diagnostics, ImmutableArray<BoundExpression> tupleArguments, ImmutableArray<TypeWithAnnotations> targetElementTypesWithAnnotations) { // 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 < targetElementTypesWithAnnotations.Length; i++) { var argument = tupleArguments[i]; var targetElementType = targetElementTypesWithAnnotations[i].Type; var elementConversion = Conversions.ClassifyConversionFromExpression(argument, targetElementType, ref discardedUseSiteInfo); if (!elementConversion.IsValid) { GenerateExplicitConversionErrors(diagnostics, argument.Syntax, elementConversion, argument, targetElementType); } } } /// <summary> /// This implements the casting behavior described in section 6.2.3 of the spec: /// /// - If the nullable conversion is from S to T?, the conversion is evaluated as the underlying conversion /// from S to T followed by a wrapping from T to T?. /// /// This particular check is done in the binder because it involves conversion processing rules (like overflow /// checking and constant folding) which are not handled by Conversions. /// </summary> private BoundExpression BindExplicitNullableCastFromNonNullable(ExpressionSyntax node, BoundExpression operand, TypeWithAnnotations targetTypeWithAnnotations, BindingDiagnosticBag diagnostics) { Debug.Assert(targetTypeWithAnnotations.HasType && targetTypeWithAnnotations.IsNullableType()); Debug.Assert((object)operand.Type != null && !operand.Type.IsNullableType()); // Section 6.2.3 of the spec only applies when the non-null version of the types involved have a // built in conversion. var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; TypeWithAnnotations underlyingTargetTypeWithAnnotations = targetTypeWithAnnotations.Type.GetNullableUnderlyingTypeWithAnnotations(); var underlyingConversion = Conversions.ClassifyBuiltInConversion(operand.Type, underlyingTargetTypeWithAnnotations.Type, ref discardedUseSiteInfo); if (!underlyingConversion.Exists) { return BindCastCore(node, operand, targetTypeWithAnnotations, wasCompilerGenerated: operand.WasCompilerGenerated, diagnostics: diagnostics); } var bag = new BindingDiagnosticBag(DiagnosticBag.GetInstance(), diagnostics.DependenciesBag); try { var underlyingExpr = BindCastCore(node, operand, underlyingTargetTypeWithAnnotations, wasCompilerGenerated: false, diagnostics: bag); if (underlyingExpr.HasErrors || bag.HasAnyErrors()) { Error(diagnostics, ErrorCode.ERR_NoExplicitConv, node, operand.Type, targetTypeWithAnnotations.Type); return new BoundConversion( node, operand, Conversion.NoConversion, @checked: CheckOverflowAtRuntime, explicitCastInCode: true, conversionGroupOpt: new ConversionGroup(Conversion.NoConversion, explicitType: targetTypeWithAnnotations), constantValueOpt: ConstantValue.NotAvailable, type: targetTypeWithAnnotations.Type, hasErrors: true); } // It's possible for the S -> T conversion to produce a 'better' constant value. If this // constant value is produced place it in the tree so that it gets emitted. This maintains // parity with the native compiler which also evaluated the conversion at compile time. if (underlyingExpr.ConstantValue != null) { underlyingExpr.WasCompilerGenerated = true; return BindCastCore(node, underlyingExpr, targetTypeWithAnnotations, wasCompilerGenerated: operand.WasCompilerGenerated, diagnostics: diagnostics); } return BindCastCore(node, operand, targetTypeWithAnnotations, wasCompilerGenerated: operand.WasCompilerGenerated, diagnostics: diagnostics); } finally { bag.DiagnosticBag.Free(); } } private static NameSyntax GetNameSyntax(SyntaxNode syntax) { string nameString; return GetNameSyntax(syntax, out nameString); } /// <summary> /// Gets the NameSyntax associated with the syntax node /// If no syntax is attached it sets the nameString to plain text /// name and returns a null NameSyntax /// </summary> /// <param name="syntax">Syntax node</param> /// <param name="nameString">Plain text name</param> internal static NameSyntax GetNameSyntax(SyntaxNode syntax, out string nameString) { nameString = string.Empty; while (true) { switch (syntax.Kind()) { case SyntaxKind.PredefinedType: nameString = ((PredefinedTypeSyntax)syntax).Keyword.ValueText; return null; case SyntaxKind.SimpleLambdaExpression: nameString = MessageID.IDS_Lambda.Localize().ToString(); return null; case SyntaxKind.ParenthesizedExpression: syntax = ((ParenthesizedExpressionSyntax)syntax).Expression; continue; case SyntaxKind.CastExpression: syntax = ((CastExpressionSyntax)syntax).Expression; continue; case SyntaxKind.SimpleMemberAccessExpression: case SyntaxKind.PointerMemberAccessExpression: return ((MemberAccessExpressionSyntax)syntax).Name; case SyntaxKind.MemberBindingExpression: return ((MemberBindingExpressionSyntax)syntax).Name; default: return syntax as NameSyntax; } } } /// <summary> /// Gets the plain text name associated with the expression syntax node /// </summary> /// <param name="syntax">Expression syntax node</param> /// <returns>Plain text name</returns> private static string GetName(ExpressionSyntax syntax) { string nameString; var nameSyntax = GetNameSyntax(syntax, out nameString); if (nameSyntax != null) { return nameSyntax.GetUnqualifiedName().Identifier.ValueText; } return nameString; } // Given a list of arguments, create arrays of the bound arguments and the names of those // arguments. private void BindArgumentsAndNames(ArgumentListSyntax argumentListOpt, BindingDiagnosticBag diagnostics, AnalyzedArguments result, bool allowArglist = false, bool isDelegateCreation = false) { if (argumentListOpt != null) { BindArgumentsAndNames(argumentListOpt.Arguments, diagnostics, result, allowArglist, isDelegateCreation: isDelegateCreation); } } private void BindArgumentsAndNames(BracketedArgumentListSyntax argumentListOpt, BindingDiagnosticBag diagnostics, AnalyzedArguments result) { if (argumentListOpt != null) { BindArgumentsAndNames(argumentListOpt.Arguments, diagnostics, result, allowArglist: false); } } private void BindArgumentsAndNames( SeparatedSyntaxList<ArgumentSyntax> arguments, BindingDiagnosticBag diagnostics, AnalyzedArguments result, bool allowArglist, bool isDelegateCreation = false) { // Only report the first "duplicate name" or "named before positional" error, // so as to avoid "cascading" errors. bool hadError = false; // Only report the first "non-trailing named args required C# 7.2" error, // so as to avoid "cascading" errors. bool hadLangVersionError = false; foreach (var argumentSyntax in arguments) { BindArgumentAndName(result, diagnostics, ref hadError, ref hadLangVersionError, argumentSyntax, allowArglist, isDelegateCreation: isDelegateCreation); } } private bool RefMustBeObeyed(bool isDelegateCreation, ArgumentSyntax argumentSyntax) { if (Compilation.FeatureStrictEnabled || !isDelegateCreation) { return true; } switch (argumentSyntax.Expression.Kind()) { // The next 3 cases should never be allowed as they cannot be ref/out. Assuming a bug in legacy compiler. case SyntaxKind.ParenthesizedLambdaExpression: case SyntaxKind.SimpleLambdaExpression: case SyntaxKind.AnonymousMethodExpression: case SyntaxKind.InvocationExpression: case SyntaxKind.ObjectCreationExpression: case SyntaxKind.ImplicitObjectCreationExpression: case SyntaxKind.ParenthesizedExpression: // this is never allowed in legacy compiler case SyntaxKind.DeclarationExpression: // A property/indexer is also invalid as it cannot be ref/out, but cannot be checked here. Assuming a bug in legacy compiler. return true; default: // The only ones that concern us here for compat is: locals, params, fields // BindArgumentAndName correctly rejects all other cases, except for properties and indexers. // They are handled after BindArgumentAndName returns and the binding can be checked. return false; } } private void BindArgumentAndName( AnalyzedArguments result, BindingDiagnosticBag diagnostics, ref bool hadError, ref bool hadLangVersionError, ArgumentSyntax argumentSyntax, bool allowArglist, bool isDelegateCreation = false) { RefKind origRefKind = argumentSyntax.RefOrOutKeyword.Kind().GetRefKind(); // The old native compiler ignores ref/out in a delegate creation expression. // For compatibility we implement the same bug except in strict mode. // Note: Some others should still be rejected when ref/out present. See RefMustBeObeyed. RefKind refKind = origRefKind == RefKind.None || RefMustBeObeyed(isDelegateCreation, argumentSyntax) ? origRefKind : RefKind.None; BoundExpression boundArgument = BindArgumentValue(diagnostics, argumentSyntax, allowArglist, refKind); BindArgumentAndName( result, diagnostics, ref hadLangVersionError, argumentSyntax, boundArgument, argumentSyntax.NameColon, refKind); // check for ref/out property/indexer, only needed for 1 parameter version if (!hadError && isDelegateCreation && origRefKind != RefKind.None && result.Arguments.Count == 1) { var arg = result.Argument(0); switch (arg.Kind) { case BoundKind.PropertyAccess: case BoundKind.IndexerAccess: var requiredValueKind = origRefKind == RefKind.In ? BindValueKind.ReadonlyRef : BindValueKind.RefOrOut; hadError = !CheckValueKind(argumentSyntax, arg, requiredValueKind, false, diagnostics); return; } } if (argumentSyntax.RefOrOutKeyword.Kind() != SyntaxKind.None) { argumentSyntax.Expression.CheckDeconstructionCompatibleArgument(diagnostics); } } private BoundExpression BindArgumentValue(BindingDiagnosticBag diagnostics, ArgumentSyntax argumentSyntax, bool allowArglist, RefKind refKind) { if (argumentSyntax.Expression.Kind() == SyntaxKind.DeclarationExpression) { var declarationExpression = (DeclarationExpressionSyntax)argumentSyntax.Expression; if (declarationExpression.IsOutDeclaration()) { return BindOutDeclarationArgument(declarationExpression, diagnostics); } } return BindArgumentExpression(diagnostics, argumentSyntax.Expression, refKind, allowArglist); } private BoundExpression BindOutDeclarationArgument(DeclarationExpressionSyntax declarationExpression, BindingDiagnosticBag diagnostics) { TypeSyntax typeSyntax = declarationExpression.Type; VariableDesignationSyntax designation = declarationExpression.Designation; if (typeSyntax.GetRefKind() != RefKind.None) { diagnostics.Add(ErrorCode.ERR_OutVariableCannotBeByRef, declarationExpression.Type.Location); } switch (designation.Kind()) { case SyntaxKind.DiscardDesignation: { bool isVar; bool isConst = false; AliasSymbol alias; var declType = BindVariableTypeWithAnnotations(designation, diagnostics, typeSyntax, ref isConst, out isVar, out alias); Debug.Assert(isVar != declType.HasType); return new BoundDiscardExpression(declarationExpression, declType.Type); } case SyntaxKind.SingleVariableDesignation: return BindOutVariableDeclarationArgument(declarationExpression, diagnostics); default: throw ExceptionUtilities.UnexpectedValue(designation.Kind()); } } private BoundExpression BindOutVariableDeclarationArgument( DeclarationExpressionSyntax declarationExpression, BindingDiagnosticBag diagnostics) { Debug.Assert(declarationExpression.IsOutVarDeclaration()); bool isVar; var designation = (SingleVariableDesignationSyntax)declarationExpression.Designation; TypeSyntax typeSyntax = declarationExpression.Type; // Is this a local? SourceLocalSymbol localSymbol = this.LookupLocal(designation.Identifier); if ((object)localSymbol != null) { Debug.Assert(localSymbol.DeclarationKind == LocalDeclarationKind.OutVariable); if ((InConstructorInitializer || InFieldInitializer) && ContainingMemberOrLambda.ContainingSymbol.Kind == SymbolKind.NamedType) { CheckFeatureAvailability(declarationExpression, MessageID.IDS_FeatureExpressionVariablesInQueriesAndInitializers, diagnostics); } bool isConst = false; AliasSymbol alias; var declType = BindVariableTypeWithAnnotations(declarationExpression, diagnostics, typeSyntax, ref isConst, out isVar, out alias); localSymbol.ScopeBinder.ValidateDeclarationNameConflictsInScope(localSymbol, diagnostics); if (isVar) { return new OutVariablePendingInference(declarationExpression, localSymbol, null); } CheckRestrictedTypeInAsyncMethod(this.ContainingMemberOrLambda, declType.Type, diagnostics, typeSyntax); return new BoundLocal(declarationExpression, localSymbol, BoundLocalDeclarationKind.WithExplicitType, constantValueOpt: null, isNullableUnknown: false, type: declType.Type); } // Is this a field? GlobalExpressionVariable expressionVariableField = LookupDeclaredField(designation); if ((object)expressionVariableField == null) { // We should have the right binder in the chain, cannot continue otherwise. throw ExceptionUtilities.Unreachable; } BoundExpression receiver = SynthesizeReceiver(designation, expressionVariableField, diagnostics); if (typeSyntax.IsVar) { BindTypeOrAliasOrVarKeyword(typeSyntax, BindingDiagnosticBag.Discarded, out isVar); if (isVar) { return new OutVariablePendingInference(declarationExpression, expressionVariableField, receiver); } } TypeSymbol fieldType = expressionVariableField.GetFieldType(this.FieldsBeingBound).Type; return new BoundFieldAccess(declarationExpression, receiver, expressionVariableField, null, LookupResultKind.Viable, isDeclaration: true, type: fieldType); } /// <summary> /// Returns true if a bad special by ref local was found. /// </summary> internal static bool CheckRestrictedTypeInAsyncMethod(Symbol containingSymbol, TypeSymbol type, BindingDiagnosticBag diagnostics, SyntaxNode syntax) { if (containingSymbol.Kind == SymbolKind.Method && ((MethodSymbol)containingSymbol).IsAsync && type.IsRestrictedType()) { Error(diagnostics, ErrorCode.ERR_BadSpecialByRefLocal, syntax, type); return true; } return false; } internal GlobalExpressionVariable LookupDeclaredField(SingleVariableDesignationSyntax variableDesignator) { return LookupDeclaredField(variableDesignator, variableDesignator.Identifier.ValueText); } internal GlobalExpressionVariable LookupDeclaredField(SyntaxNode node, string identifier) { foreach (Symbol member in ContainingType?.GetMembers(identifier) ?? ImmutableArray<Symbol>.Empty) { GlobalExpressionVariable field; if (member.Kind == SymbolKind.Field && (field = member as GlobalExpressionVariable)?.SyntaxTree == node.SyntaxTree && field.SyntaxNode == node) { return field; } } return null; } // Bind a named/positional argument. // Prevent cascading diagnostic by considering the previous // error state and returning the updated error state. private void BindArgumentAndName( AnalyzedArguments result, BindingDiagnosticBag diagnostics, ref bool hadLangVersionError, CSharpSyntaxNode argumentSyntax, BoundExpression boundArgumentExpression, NameColonSyntax nameColonSyntax, RefKind refKind) { Debug.Assert(argumentSyntax is ArgumentSyntax || argumentSyntax is AttributeArgumentSyntax); bool hasRefKinds = result.RefKinds.Any(); if (refKind != RefKind.None) { // The common case is no ref or out arguments. So we defer all work until the first one is seen. if (!hasRefKinds) { hasRefKinds = true; int argCount = result.Arguments.Count; for (int i = 0; i < argCount; ++i) { result.RefKinds.Add(RefKind.None); } } } if (hasRefKinds) { result.RefKinds.Add(refKind); } bool hasNames = result.Names.Any(); if (nameColonSyntax != null) { // The common case is no named arguments. So we defer all work until the first named argument is seen. if (!hasNames) { hasNames = true; int argCount = result.Arguments.Count; for (int i = 0; i < argCount; ++i) { result.Names.Add(null); } } result.AddName(nameColonSyntax.Name); } else if (hasNames) { // We just saw a fixed-position argument after a named argument. if (!hadLangVersionError && !Compilation.LanguageVersion.AllowNonTrailingNamedArguments()) { // CS1738: Named argument specifications must appear after all fixed arguments have been specified Error(diagnostics, ErrorCode.ERR_NamedArgumentSpecificationBeforeFixedArgument, argumentSyntax, new CSharpRequiredLanguageVersion(MessageID.IDS_FeatureNonTrailingNamedArguments.RequiredVersion())); hadLangVersionError = true; } result.Names.Add(null); } result.Arguments.Add(boundArgumentExpression); } /// <summary> /// Bind argument and verify argument matches rvalue or out param requirements. /// </summary> private BoundExpression BindArgumentExpression(BindingDiagnosticBag diagnostics, ExpressionSyntax argumentExpression, RefKind refKind, bool allowArglist) { BindValueKind valueKind = refKind == RefKind.None ? BindValueKind.RValue : refKind == RefKind.In ? BindValueKind.ReadonlyRef : BindValueKind.RefOrOut; BoundExpression argument; if (allowArglist) { argument = this.BindValueAllowArgList(argumentExpression, diagnostics, valueKind); } else { argument = this.BindValue(argumentExpression, diagnostics, valueKind); } return argument; } #nullable enable private void CoerceArguments<TMember>( MemberResolutionResult<TMember> methodResult, ArrayBuilder<BoundExpression> arguments, BindingDiagnosticBag diagnostics, TypeSymbol? receiverType, RefKind? receiverRefKind, uint receiverEscapeScope) where TMember : Symbol { var result = methodResult.Result; // Parameter types should be taken from the least overridden member: var parameters = methodResult.LeastOverriddenMember.GetParameters(); for (int arg = 0; arg < arguments.Count; ++arg) { var kind = result.ConversionForArg(arg); BoundExpression argument = arguments[arg]; if (kind.IsInterpolatedStringHandler) { Debug.Assert(argument is BoundUnconvertedInterpolatedString); TypeWithAnnotations parameterTypeWithAnnotations = GetCorrespondingParameterTypeWithAnnotations(ref result, parameters, arg); reportUnsafeIfNeeded(methodResult, diagnostics, argument, parameterTypeWithAnnotations); arguments[arg] = BindInterpolatedStringHandlerInMemberCall((BoundUnconvertedInterpolatedString)argument, arguments, parameters, ref result, arg, receiverType, receiverRefKind, receiverEscapeScope, diagnostics); } // https://github.com/dotnet/roslyn/issues/37119 : should we create an (Identity) conversion when the kind is Identity but the types differ? else if (!kind.IsIdentity) { TypeWithAnnotations parameterTypeWithAnnotations = GetCorrespondingParameterTypeWithAnnotations(ref result, parameters, arg); reportUnsafeIfNeeded(methodResult, diagnostics, argument, parameterTypeWithAnnotations); arguments[arg] = CreateConversion(argument.Syntax, argument, kind, isCast: false, conversionGroupOpt: null, parameterTypeWithAnnotations.Type, diagnostics); } else if (argument.Kind == BoundKind.OutVariablePendingInference) { TypeWithAnnotations parameterTypeWithAnnotations = GetCorrespondingParameterTypeWithAnnotations(ref result, parameters, arg); arguments[arg] = ((OutVariablePendingInference)argument).SetInferredTypeWithAnnotations(parameterTypeWithAnnotations, diagnostics); } else if (argument.Kind == BoundKind.OutDeconstructVarPendingInference) { TypeWithAnnotations parameterTypeWithAnnotations = GetCorrespondingParameterTypeWithAnnotations(ref result, parameters, arg); arguments[arg] = ((OutDeconstructVarPendingInference)argument).SetInferredTypeWithAnnotations(parameterTypeWithAnnotations, this, success: true); } else if (argument.Kind == BoundKind.DiscardExpression && !argument.HasExpressionType()) { TypeWithAnnotations parameterTypeWithAnnotations = GetCorrespondingParameterTypeWithAnnotations(ref result, parameters, arg); Debug.Assert(parameterTypeWithAnnotations.HasType); arguments[arg] = ((BoundDiscardExpression)argument).SetInferredTypeWithAnnotations(parameterTypeWithAnnotations); } else if (argument.NeedsToBeConverted()) { Debug.Assert(kind.IsIdentity); if (argument is BoundTupleLiteral) { TypeWithAnnotations parameterTypeWithAnnotations = GetCorrespondingParameterTypeWithAnnotations(ref result, parameters, arg); // CreateConversion reports tuple literal name mismatches, and constructs the expected pattern of bound nodes. arguments[arg] = CreateConversion(argument.Syntax, argument, kind, isCast: false, conversionGroupOpt: null, parameterTypeWithAnnotations.Type, diagnostics); } else { arguments[arg] = BindToNaturalType(argument, diagnostics); } } } void reportUnsafeIfNeeded(MemberResolutionResult<TMember> methodResult, BindingDiagnosticBag diagnostics, BoundExpression argument, TypeWithAnnotations parameterTypeWithAnnotations) { // NOTE: for some reason, dev10 doesn't report this for indexer accesses. if (!methodResult.Member.IsIndexer() && !argument.HasAnyErrors && parameterTypeWithAnnotations.Type.IsUnsafe()) { // CONSIDER: dev10 uses the call syntax, but this seems clearer. ReportUnsafeIfNotAllowed(argument.Syntax, diagnostics); //CONSIDER: Return a bad expression so that HasErrors is true? } } } private static ParameterSymbol GetCorrespondingParameter(ref MemberAnalysisResult result, ImmutableArray<ParameterSymbol> parameters, int arg) { int paramNum = result.ParameterFromArgument(arg); return parameters[paramNum]; } #nullable disable private static TypeWithAnnotations GetCorrespondingParameterTypeWithAnnotations(ref MemberAnalysisResult result, ImmutableArray<ParameterSymbol> parameters, int arg) { int paramNum = result.ParameterFromArgument(arg); var type = parameters[paramNum].TypeWithAnnotations; if (paramNum == parameters.Length - 1 && result.Kind == MemberResolutionKind.ApplicableInExpandedForm) { type = ((ArrayTypeSymbol)type.Type).ElementTypeWithAnnotations; } return type; } private BoundExpression BindArrayCreationExpression(ArrayCreationExpressionSyntax node, BindingDiagnosticBag diagnostics) { // SPEC begins // // An array-creation-expression is used to create a new instance of an array-type. // // array-creation-expression: // new non-array-type[expression-list] rank-specifiersopt array-initializeropt // new array-type array-initializer // new rank-specifier array-initializer // // An array creation expression of the first form allocates an array instance of the // type that results from deleting each of the individual expressions from the // expression list. For example, the array creation expression new int[10, 20] produces // an array instance of type int[,], and the array creation expression new int[10][,] // produces an array of type int[][,]. Each expression in the expression list must be of // type int, uint, long, or ulong, or implicitly convertible to one or more of these // types. The value of each expression determines the length of the corresponding // dimension in the newly allocated array instance. Since the length of an array // dimension must be nonnegative, it is a compile-time error to have a // constant-expression with a negative value in the expression list. // // If an array creation expression of the first form includes an array initializer, each // expression in the expression list must be a constant and the rank and dimension // lengths specified by the expression list must match those of the array initializer. // // In an array creation expression of the second or third form, the rank of the // specified array type or rank specifier must match that of the array initializer. The // individual dimension lengths are inferred from the number of elements in each of the // corresponding nesting levels of the array initializer. Thus, the expression new // int[,] {{0, 1}, {2, 3}, {4, 5}} exactly corresponds to new int[3, 2] {{0, 1}, {2, 3}, // {4, 5}} // // An array creation expression of the third form is referred to as an implicitly typed // array creation expression. It is similar to the second form, except that the element // type of the array is not explicitly given, but determined as the best common type // (7.5.2.14) of the set of expressions in the array initializer. For a multidimensional // array, i.e., one where the rank-specifier contains at least one comma, this set // comprises all expressions found in nested array-initializers. // // An array creation expression permits instantiation of an array with elements of an // array type, but the elements of such an array must be manually initialized. For // example, the statement // // int[][] a = new int[100][]; // // creates a single-dimensional array with 100 elements of type int[]. The initial value // of each element is null. It is not possible for the same array creation expression to // also instantiate the sub-arrays, and the statement // // int[][] a = new int[100][5]; // Error // // results in a compile-time error. // // The following are examples of implicitly typed array creation expressions: // // var a = new[] { 1, 10, 100, 1000 }; // int[] // var b = new[] { 1, 1.5, 2, 2.5 }; // double[] // var c = new[,] { { "hello", null }, { "world", "!" } }; // string[,] // var d = new[] { 1, "one", 2, "two" }; // Error // // The last expression causes a compile-time error because neither int nor string is // implicitly convertible to the other, and so there is no best common type. An // explicitly typed array creation expression must be used in this case, for example // specifying the type to be object[]. Alternatively, one of the elements can be cast to // a common base type, which would then become the inferred element type. // // SPEC ends var type = (ArrayTypeSymbol)BindArrayType(node.Type, diagnostics, permitDimensions: true, basesBeingResolved: null, disallowRestrictedTypes: true).Type; // CONSIDER: // // There may be erroneous rank specifiers in the source code, for example: // // int y = 123; // int[][] z = new int[10][y]; // // The "10" is legal but the "y" is not. If we are in such a situation we do have the // "y" expression syntax stashed away in the syntax tree. However, we do *not* perform // semantic analysis. This means that "go to definition" on "y" does not work, and so // on. We might consider doing a semantic analysis here (with error suppression; a parse // error has already been reported) so that "go to definition" works. ArrayBuilder<BoundExpression> sizes = ArrayBuilder<BoundExpression>.GetInstance(); ArrayRankSpecifierSyntax firstRankSpecifier = node.Type.RankSpecifiers[0]; bool hasErrors = false; foreach (var arg in firstRankSpecifier.Sizes) { var size = BindArrayDimension(arg, diagnostics, ref hasErrors); if (size != null) { sizes.Add(size); } else if (node.Initializer is null && arg == firstRankSpecifier.Sizes[0]) { Error(diagnostics, ErrorCode.ERR_MissingArraySize, firstRankSpecifier); hasErrors = true; } } // produce errors for additional sizes in the ranks for (int additionalRankIndex = 1; additionalRankIndex < node.Type.RankSpecifiers.Count; additionalRankIndex++) { var rank = node.Type.RankSpecifiers[additionalRankIndex]; var dimension = rank.Sizes; foreach (var arg in dimension) { if (arg.Kind() != SyntaxKind.OmittedArraySizeExpression) { var size = BindRValueWithoutTargetType(arg, diagnostics); Error(diagnostics, ErrorCode.ERR_InvalidArray, arg); hasErrors = true; // Capture the invalid sizes for `SemanticModel` and `IOperation` sizes.Add(size); } } } ImmutableArray<BoundExpression> arraySizes = sizes.ToImmutableAndFree(); return node.Initializer == null ? new BoundArrayCreation(node, arraySizes, null, type, hasErrors) : BindArrayCreationWithInitializer(diagnostics, node, node.Initializer, type, arraySizes, hasErrors: hasErrors); } private BoundExpression BindArrayDimension(ExpressionSyntax dimension, BindingDiagnosticBag diagnostics, ref bool hasErrors) { // These make the parse tree nicer, but they shouldn't actually appear in the bound tree. if (dimension.Kind() != SyntaxKind.OmittedArraySizeExpression) { var size = BindValue(dimension, diagnostics, BindValueKind.RValue); if (!size.HasAnyErrors) { size = ConvertToArrayIndex(size, diagnostics, allowIndexAndRange: false); if (IsNegativeConstantForArraySize(size)) { Error(diagnostics, ErrorCode.ERR_NegativeArraySize, dimension); hasErrors = true; } } else { size = BindToTypeForErrorRecovery(size); } return size; } return null; } private BoundExpression BindImplicitArrayCreationExpression(ImplicitArrayCreationExpressionSyntax node, BindingDiagnosticBag diagnostics) { // See BindArrayCreationExpression method above for implicitly typed array creation SPEC. InitializerExpressionSyntax initializer = node.Initializer; int rank = node.Commas.Count + 1; ImmutableArray<BoundExpression> boundInitializerExpressions = BindArrayInitializerExpressions(initializer, diagnostics, dimension: 1, rank: rank); CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); TypeSymbol bestType = BestTypeInferrer.InferBestType(boundInitializerExpressions, this.Conversions, ref useSiteInfo); diagnostics.Add(node, useSiteInfo); if ((object)bestType == null || bestType.IsVoidType()) // Dev10 also reports ERR_ImplicitlyTypedArrayNoBestType for void. { Error(diagnostics, ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, node); bestType = CreateErrorType(); } if (bestType.IsRestrictedType()) { // CS0611: Array elements cannot be of type '{0}' Error(diagnostics, ErrorCode.ERR_ArrayElementCantBeRefAny, node, bestType); } // Element type nullability will be inferred in flow analysis and does not need to be set here. var arrayType = ArrayTypeSymbol.CreateCSharpArray(Compilation.Assembly, TypeWithAnnotations.Create(bestType), rank); return BindArrayCreationWithInitializer(diagnostics, node, initializer, arrayType, sizes: ImmutableArray<BoundExpression>.Empty, boundInitExprOpt: boundInitializerExpressions); } private BoundExpression BindImplicitStackAllocArrayCreationExpression(ImplicitStackAllocArrayCreationExpressionSyntax node, BindingDiagnosticBag diagnostics) { InitializerExpressionSyntax initializer = node.Initializer; ImmutableArray<BoundExpression> boundInitializerExpressions = BindArrayInitializerExpressions(initializer, diagnostics, dimension: 1, rank: 1); CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); TypeSymbol bestType = BestTypeInferrer.InferBestType(boundInitializerExpressions, this.Conversions, ref useSiteInfo); diagnostics.Add(node, useSiteInfo); if ((object)bestType == null || bestType.IsVoidType()) { Error(diagnostics, ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, node); bestType = CreateErrorType(); } if (!bestType.IsErrorType()) { CheckManagedAddr(Compilation, bestType, node.Location, diagnostics); } return BindStackAllocWithInitializer( node, initializer, type: GetStackAllocType(node, TypeWithAnnotations.Create(bestType), diagnostics, out bool hasErrors), elementType: bestType, sizeOpt: null, diagnostics, hasErrors: hasErrors, boundInitializerExpressions); } // This method binds all the array initializer expressions. // NOTE: It doesn't convert the bound initializer expressions to array's element type. // NOTE: This is done separately in ConvertAndBindArrayInitialization method below. private ImmutableArray<BoundExpression> BindArrayInitializerExpressions(InitializerExpressionSyntax initializer, BindingDiagnosticBag diagnostics, int dimension, int rank) { var exprBuilder = ArrayBuilder<BoundExpression>.GetInstance(); BindArrayInitializerExpressions(initializer, exprBuilder, diagnostics, dimension, rank); return exprBuilder.ToImmutableAndFree(); } /// <summary> /// This method walks through the array's InitializerExpressionSyntax and binds all the initializer expressions recursively. /// NOTE: It doesn't convert the bound initializer expressions to array's element type. /// NOTE: This is done separately in ConvertAndBindArrayInitialization method below. /// </summary> /// <param name="initializer">Initializer Syntax.</param> /// <param name="exprBuilder">Bound expression builder.</param> /// <param name="diagnostics">Diagnostics.</param> /// <param name="dimension">Current array dimension being processed.</param> /// <param name="rank">Rank of the array type.</param> private void BindArrayInitializerExpressions(InitializerExpressionSyntax initializer, ArrayBuilder<BoundExpression> exprBuilder, BindingDiagnosticBag diagnostics, int dimension, int rank) { Debug.Assert(rank > 0); Debug.Assert(dimension > 0 && dimension <= rank); Debug.Assert(exprBuilder != null); if (dimension == rank) { // We are processing the nth dimension of a rank-n array. We expect that these will // only be values, not array initializers. foreach (var expression in initializer.Expressions) { var boundExpression = BindValue(expression, diagnostics, BindValueKind.RValue); exprBuilder.Add(boundExpression); } } else { // Inductive case; we'd better have another array initializer foreach (var expression in initializer.Expressions) { if (expression.Kind() == SyntaxKind.ArrayInitializerExpression) { BindArrayInitializerExpressions((InitializerExpressionSyntax)expression, exprBuilder, diagnostics, dimension + 1, rank); } else { // We have non-array initializer expression, but we expected an array initializer expression. var boundExpression = BindValue(expression, diagnostics, BindValueKind.RValue); if ((object)boundExpression.Type == null || !boundExpression.Type.IsErrorType()) { if (!boundExpression.HasAnyErrors) { Error(diagnostics, ErrorCode.ERR_ArrayInitializerExpected, expression); } // Wrap the expression with a bound bad expression with error type. boundExpression = BadExpression( expression, LookupResultKind.Empty, ImmutableArray.Create(boundExpression.ExpressionSymbol), ImmutableArray.Create(boundExpression)); } exprBuilder.Add(boundExpression); } } } } /// <summary> /// Given an array of bound initializer expressions, this method converts these bound expressions /// to array's element type and generates a BoundArrayInitialization with the converted initializers. /// </summary> /// <param name="diagnostics">Diagnostics.</param> /// <param name="node">Initializer Syntax.</param> /// <param name="type">Array type.</param> /// <param name="knownSizes">Known array bounds.</param> /// <param name="dimension">Current array dimension being processed.</param> /// <param name="boundInitExpr">Array of bound initializer expressions.</param> /// <param name="boundInitExprIndex"> /// Index into the array of bound initializer expressions to fetch the next bound expression. /// </param> /// <returns></returns> private BoundArrayInitialization ConvertAndBindArrayInitialization( BindingDiagnosticBag diagnostics, InitializerExpressionSyntax node, ArrayTypeSymbol type, int?[] knownSizes, int dimension, ImmutableArray<BoundExpression> boundInitExpr, ref int boundInitExprIndex) { Debug.Assert(!boundInitExpr.IsDefault); ArrayBuilder<BoundExpression> initializers = ArrayBuilder<BoundExpression>.GetInstance(); if (dimension == type.Rank) { // We are processing the nth dimension of a rank-n array. We expect that these will // only be values, not array initializers. TypeSymbol elemType = type.ElementType; foreach (var expressionSyntax in node.Expressions) { Debug.Assert(boundInitExprIndex >= 0 && boundInitExprIndex < boundInitExpr.Length); BoundExpression boundExpression = boundInitExpr[boundInitExprIndex]; boundInitExprIndex++; BoundExpression convertedExpression = GenerateConversionForAssignment(elemType, boundExpression, diagnostics); initializers.Add(convertedExpression); } } else { // Inductive case; we'd better have another array initializer foreach (var expr in node.Expressions) { BoundExpression init = null; if (expr.Kind() == SyntaxKind.ArrayInitializerExpression) { init = ConvertAndBindArrayInitialization(diagnostics, (InitializerExpressionSyntax)expr, type, knownSizes, dimension + 1, boundInitExpr, ref boundInitExprIndex); } else { // We have non-array initializer expression, but we expected an array initializer expression. // We have already generated the diagnostics during binding, so just fetch the bound expression. Debug.Assert(boundInitExprIndex >= 0 && boundInitExprIndex < boundInitExpr.Length); init = boundInitExpr[boundInitExprIndex]; Debug.Assert(init.HasAnyErrors); Debug.Assert(init.Type.IsErrorType()); boundInitExprIndex++; } initializers.Add(init); } } bool hasErrors = false; var knownSizeOpt = knownSizes[dimension - 1]; if (knownSizeOpt == null) { knownSizes[dimension - 1] = initializers.Count; } else if (knownSizeOpt != initializers.Count) { // No need to report an error if the known size is negative // since we've already reported CS0248 earlier and it's // expected that the number of initializers won't match. if (knownSizeOpt >= 0) { Error(diagnostics, ErrorCode.ERR_ArrayInitializerIncorrectLength, node, knownSizeOpt.Value); hasErrors = true; } } return new BoundArrayInitialization(node, initializers.ToImmutableAndFree(), hasErrors: hasErrors); } private BoundArrayInitialization BindArrayInitializerList( BindingDiagnosticBag diagnostics, InitializerExpressionSyntax node, ArrayTypeSymbol type, int?[] knownSizes, int dimension, ImmutableArray<BoundExpression> boundInitExprOpt = default(ImmutableArray<BoundExpression>)) { // Bind the array initializer expressions, if not already bound. // NOTE: Initializer expressions might already be bound for implicitly type array creation // NOTE: during array's element type inference. if (boundInitExprOpt.IsDefault) { boundInitExprOpt = BindArrayInitializerExpressions(node, diagnostics, dimension, type.Rank); } // Convert the bound array initializer expressions to array's element type and // generate BoundArrayInitialization with the converted initializers. int boundInitExprIndex = 0; return ConvertAndBindArrayInitialization(diagnostics, node, type, knownSizes, dimension, boundInitExprOpt, ref boundInitExprIndex); } private BoundArrayInitialization BindUnexpectedArrayInitializer( InitializerExpressionSyntax node, BindingDiagnosticBag diagnostics, ErrorCode errorCode, CSharpSyntaxNode errorNode = null) { var result = BindArrayInitializerList( diagnostics, node, this.Compilation.CreateArrayTypeSymbol(GetSpecialType(SpecialType.System_Object, diagnostics, node)), new int?[1], dimension: 1); if (!result.HasAnyErrors) { result = new BoundArrayInitialization(node, result.Initializers, hasErrors: true); } Error(diagnostics, errorCode, errorNode ?? node); return result; } // We could be in the cases // // (1) int[] x = { a, b } // (2) new int[] { a, b } // (3) new int[2] { a, b } // (4) new [] { a, b } // // In case (1) there is no creation syntax. // In cases (2) and (3) creation syntax is an ArrayCreationExpression. // In case (4) creation syntax is an ImplicitArrayCreationExpression. // // In cases (1), (2) and (4) there are no sizes. // // The initializer syntax is always provided. // // If we are in case (3) and sizes are provided then the number of sizes must match the rank // of the array type passed in. // For case (4), i.e. ImplicitArrayCreationExpression, we must have already bound the // initializer expressions for best type inference. // These bound expressions are stored in boundInitExprOpt and reused in creating // BoundArrayInitialization to avoid binding them twice. private BoundArrayCreation BindArrayCreationWithInitializer( BindingDiagnosticBag diagnostics, ExpressionSyntax creationSyntax, InitializerExpressionSyntax initSyntax, ArrayTypeSymbol type, ImmutableArray<BoundExpression> sizes, ImmutableArray<BoundExpression> boundInitExprOpt = default(ImmutableArray<BoundExpression>), bool hasErrors = false) { Debug.Assert(creationSyntax == null || creationSyntax.Kind() == SyntaxKind.ArrayCreationExpression || creationSyntax.Kind() == SyntaxKind.ImplicitArrayCreationExpression); Debug.Assert(initSyntax != null); Debug.Assert((object)type != null); Debug.Assert(boundInitExprOpt.IsDefault || creationSyntax.Kind() == SyntaxKind.ImplicitArrayCreationExpression); // NOTE: In error scenarios, it may be the case sizes.Count > type.Rank. // For example, new int[1 2] has 2 sizes, but rank 1 (since there are 0 commas). int rank = type.Rank; int numSizes = sizes.Length; int?[] knownSizes = new int?[Math.Max(rank, numSizes)]; // If there are sizes given and there is an array initializer, then every size must be a // constant. (We'll check later that it matches) for (int i = 0; i < numSizes; ++i) { // Here we are being bug-for-bug compatible with C# 4. When you have code like // byte[] b = new[uint.MaxValue] { 2 }; // you might expect an error that says that the number of elements in the initializer does // not match the size of the array. But in C# 4 if the constant does not fit into an integer // then we confusingly give the error "that's not a constant". // NOTE: in the example above, GetIntegerConstantForArraySize is returning null because the // size doesn't fit in an int - not because it doesn't match the initializer length. var size = sizes[i]; knownSizes[i] = GetIntegerConstantForArraySize(size); if (!size.HasAnyErrors && knownSizes[i] == null) { Error(diagnostics, ErrorCode.ERR_ConstantExpected, size.Syntax); hasErrors = true; } } // KnownSizes is further mutated by BindArrayInitializerList as it works out more // information about the sizes. BoundArrayInitialization initializer = BindArrayInitializerList(diagnostics, initSyntax, type, knownSizes, 1, boundInitExprOpt); hasErrors = hasErrors || initializer.HasAnyErrors; bool hasCreationSyntax = creationSyntax != null; CSharpSyntaxNode nonNullSyntax = (CSharpSyntaxNode)creationSyntax ?? initSyntax; // Construct a set of size expressions if we were not given any. // // It is possible in error scenarios that some of the bounds were not determined. Substitute // zeroes for those. if (numSizes == 0) { BoundExpression[] sizeArray = new BoundExpression[rank]; for (int i = 0; i < rank; i++) { sizeArray[i] = new BoundLiteral( nonNullSyntax, ConstantValue.Create(knownSizes[i] ?? 0), GetSpecialType(SpecialType.System_Int32, diagnostics, nonNullSyntax)) { WasCompilerGenerated = true }; } sizes = sizeArray.AsImmutableOrNull(); } else if (!hasErrors && rank != numSizes) { Error(diagnostics, ErrorCode.ERR_BadIndexCount, nonNullSyntax, type.Rank); hasErrors = true; } return new BoundArrayCreation(nonNullSyntax, sizes, initializer, type, hasErrors: hasErrors) { WasCompilerGenerated = !hasCreationSyntax && (initSyntax.Parent == null || initSyntax.Parent.Kind() != SyntaxKind.EqualsValueClause || ((EqualsValueClauseSyntax)initSyntax.Parent).Value != initSyntax) }; } private BoundExpression BindStackAllocArrayCreationExpression( StackAllocArrayCreationExpressionSyntax node, BindingDiagnosticBag diagnostics) { TypeSyntax typeSyntax = node.Type; if (typeSyntax.Kind() != SyntaxKind.ArrayType) { Error(diagnostics, ErrorCode.ERR_BadStackAllocExpr, typeSyntax); return new BoundBadExpression( node, LookupResultKind.NotCreatable, //in this context, anyway ImmutableArray<Symbol>.Empty, ImmutableArray<BoundExpression>.Empty, new PointerTypeSymbol(BindType(typeSyntax, diagnostics))); } ArrayTypeSyntax arrayTypeSyntax = (ArrayTypeSyntax)typeSyntax; var elementTypeSyntax = arrayTypeSyntax.ElementType; var arrayType = (ArrayTypeSymbol)BindArrayType(arrayTypeSyntax, diagnostics, permitDimensions: true, basesBeingResolved: null, disallowRestrictedTypes: false).Type; var elementType = arrayType.ElementTypeWithAnnotations; TypeSymbol type = GetStackAllocType(node, elementType, diagnostics, out bool hasErrors); if (!elementType.Type.IsErrorType()) { hasErrors = hasErrors || CheckManagedAddr(Compilation, elementType.Type, elementTypeSyntax.Location, diagnostics); } SyntaxList<ArrayRankSpecifierSyntax> rankSpecifiers = arrayTypeSyntax.RankSpecifiers; if (rankSpecifiers.Count != 1 || rankSpecifiers[0].Sizes.Count != 1) { // NOTE: Dev10 reported several parse errors here. Error(diagnostics, ErrorCode.ERR_BadStackAllocExpr, typeSyntax); var builder = ArrayBuilder<BoundExpression>.GetInstance(); foreach (ArrayRankSpecifierSyntax rankSpecifier in rankSpecifiers) { foreach (ExpressionSyntax size in rankSpecifier.Sizes) { if (size.Kind() != SyntaxKind.OmittedArraySizeExpression) { builder.Add(BindExpression(size, BindingDiagnosticBag.Discarded)); } } } return new BoundBadExpression( node, LookupResultKind.Empty, ImmutableArray<Symbol>.Empty, builder.ToImmutableAndFree(), new PointerTypeSymbol(elementType)); } ExpressionSyntax countSyntax = rankSpecifiers[0].Sizes[0]; BoundExpression count = null; if (countSyntax.Kind() != SyntaxKind.OmittedArraySizeExpression) { count = BindValue(countSyntax, diagnostics, BindValueKind.RValue); count = GenerateConversionForAssignment(GetSpecialType(SpecialType.System_Int32, diagnostics, node), count, diagnostics); if (IsNegativeConstantForArraySize(count)) { Error(diagnostics, ErrorCode.ERR_NegativeStackAllocSize, countSyntax); hasErrors = true; } } else if (node.Initializer == null) { Error(diagnostics, ErrorCode.ERR_MissingArraySize, rankSpecifiers[0]); count = BadExpression(countSyntax); hasErrors = true; } return node.Initializer == null ? new BoundStackAllocArrayCreation(node, elementType.Type, count, initializerOpt: null, type, hasErrors: hasErrors) : BindStackAllocWithInitializer(node, node.Initializer, type, elementType.Type, count, diagnostics, hasErrors); } private bool ReportBadStackAllocPosition(SyntaxNode node, BindingDiagnosticBag diagnostics) { Debug.Assert(node is StackAllocArrayCreationExpressionSyntax || node is ImplicitStackAllocArrayCreationExpressionSyntax); bool inLegalPosition = true; // If we are using a language version that does not restrict the position of a stackalloc expression, skip that test. LanguageVersion requiredVersion = MessageID.IDS_FeatureNestedStackalloc.RequiredVersion(); if (requiredVersion > Compilation.LanguageVersion) { inLegalPosition = (IsInMethodBody || IsLocalFunctionsScopeBinder) && node.IsLegalCSharp73SpanStackAllocPosition(); if (!inLegalPosition) { MessageID.IDS_FeatureNestedStackalloc.CheckFeatureAvailability(diagnostics, node, node.GetFirstToken().GetLocation()); } } // Check if we're syntactically within a catch or finally clause. if (this.Flags.IncludesAny(BinderFlags.InCatchBlock | BinderFlags.InCatchFilter | BinderFlags.InFinallyBlock)) { Error(diagnostics, ErrorCode.ERR_StackallocInCatchFinally, node); } return inLegalPosition; } private TypeSymbol GetStackAllocType(SyntaxNode node, TypeWithAnnotations elementTypeWithAnnotations, BindingDiagnosticBag diagnostics, out bool hasErrors) { var inLegalPosition = ReportBadStackAllocPosition(node, diagnostics); hasErrors = !inLegalPosition; if (inLegalPosition && !isStackallocTargetTyped(node)) { CheckFeatureAvailability(node, MessageID.IDS_FeatureRefStructs, diagnostics); var spanType = GetWellKnownType(WellKnownType.System_Span_T, diagnostics, node); return ConstructNamedType( type: spanType, typeSyntax: node.Kind() == SyntaxKind.StackAllocArrayCreationExpression ? ((StackAllocArrayCreationExpressionSyntax)node).Type : node, typeArgumentsSyntax: default, typeArguments: ImmutableArray.Create(elementTypeWithAnnotations), basesBeingResolved: null, diagnostics: diagnostics); } // We treat the stackalloc as target-typed, so we give it a null type for now. return null; // Is this a context in which a stackalloc expression could be converted to the corresponding pointer // type? The only context that permits it is the initialization of a local variable declaration (when // the declaration appears as a statement or as the first part of a for loop). static bool isStackallocTargetTyped(SyntaxNode node) { Debug.Assert(node != null); SyntaxNode equalsValueClause = node.Parent; if (!equalsValueClause.IsKind(SyntaxKind.EqualsValueClause)) { return false; } SyntaxNode variableDeclarator = equalsValueClause.Parent; if (!variableDeclarator.IsKind(SyntaxKind.VariableDeclarator)) { return false; } SyntaxNode variableDeclaration = variableDeclarator.Parent; if (!variableDeclaration.IsKind(SyntaxKind.VariableDeclaration)) { return false; } return variableDeclaration.Parent.IsKind(SyntaxKind.LocalDeclarationStatement) || variableDeclaration.Parent.IsKind(SyntaxKind.ForStatement); } } private BoundExpression BindStackAllocWithInitializer( SyntaxNode node, InitializerExpressionSyntax initSyntax, TypeSymbol type, TypeSymbol elementType, BoundExpression sizeOpt, BindingDiagnosticBag diagnostics, bool hasErrors, ImmutableArray<BoundExpression> boundInitExprOpt = default) { Debug.Assert(node.IsKind(SyntaxKind.ImplicitStackAllocArrayCreationExpression) || node.IsKind(SyntaxKind.StackAllocArrayCreationExpression)); if (boundInitExprOpt.IsDefault) { boundInitExprOpt = BindArrayInitializerExpressions(initSyntax, diagnostics, dimension: 1, rank: 1); } boundInitExprOpt = boundInitExprOpt.SelectAsArray((expr, t) => GenerateConversionForAssignment(t.elementType, expr, t.diagnostics), (elementType, diagnostics)); if (sizeOpt != null) { if (!sizeOpt.HasAnyErrors) { int? constantSizeOpt = GetIntegerConstantForArraySize(sizeOpt); if (constantSizeOpt == null) { Error(diagnostics, ErrorCode.ERR_ConstantExpected, sizeOpt.Syntax); hasErrors = true; } else if (boundInitExprOpt.Length != constantSizeOpt) { Error(diagnostics, ErrorCode.ERR_ArrayInitializerIncorrectLength, node, constantSizeOpt.Value); hasErrors = true; } } } else { sizeOpt = new BoundLiteral( node, ConstantValue.Create(boundInitExprOpt.Length), GetSpecialType(SpecialType.System_Int32, diagnostics, node)) { WasCompilerGenerated = true }; } return new BoundStackAllocArrayCreation(node, elementType, sizeOpt, new BoundArrayInitialization(initSyntax, boundInitExprOpt), type, hasErrors); } private static int? GetIntegerConstantForArraySize(BoundExpression expression) { // If the bound could have been converted to int, then it was. If it could not have been // converted to int, and it was a constant, then it was out of range. Debug.Assert(expression != null); if (expression.HasAnyErrors) { return null; } var constantValue = expression.ConstantValue; if (constantValue == null || constantValue.IsBad || expression.Type.SpecialType != SpecialType.System_Int32) { return null; } return constantValue.Int32Value; } private static bool IsNegativeConstantForArraySize(BoundExpression expression) { Debug.Assert(expression != null); if (expression.HasAnyErrors) { return false; } var constantValue = expression.ConstantValue; if (constantValue == null || constantValue.IsBad) { return false; } var type = expression.Type.SpecialType; if (type == SpecialType.System_Int32) { return constantValue.Int32Value < 0; } if (type == SpecialType.System_Int64) { return constantValue.Int64Value < 0; } // By the time we get here we definitely have int, long, uint or ulong. Obviously the // latter two are never negative. Debug.Assert(type == SpecialType.System_UInt32 || type == SpecialType.System_UInt64); return false; } /// <summary> /// Bind the (implicit or explicit) constructor initializer of a constructor symbol (in source). /// </summary> /// <param name="initializerArgumentListOpt"> /// Null for implicit, /// <see cref="ConstructorInitializerSyntax.ArgumentList"/>, or /// <see cref="PrimaryConstructorBaseTypeSyntax.ArgumentList"/> for explicit.</param> /// <param name="constructor">Constructor containing the initializer.</param> /// <param name="diagnostics">Accumulates errors (e.g. unable to find constructor to invoke).</param> /// <returns>A bound expression for the constructor initializer call.</returns> /// <remarks> /// This method should be kept consistent with Compiler.BindConstructorInitializer (e.g. same error codes). /// </remarks> internal BoundExpression BindConstructorInitializer( ArgumentListSyntax initializerArgumentListOpt, MethodSymbol constructor, BindingDiagnosticBag diagnostics) { Binder argumentListBinder = null; if (initializerArgumentListOpt != null) { argumentListBinder = this.GetBinder(initializerArgumentListOpt); } var result = (argumentListBinder ?? this).BindConstructorInitializerCore(initializerArgumentListOpt, constructor, diagnostics); if (argumentListBinder != null) { // This code is reachable only for speculative SemanticModel. Debug.Assert(argumentListBinder.IsSemanticModelBinder); result = argumentListBinder.WrapWithVariablesIfAny(initializerArgumentListOpt, result); } return result; } private BoundExpression BindConstructorInitializerCore( ArgumentListSyntax initializerArgumentListOpt, MethodSymbol constructor, BindingDiagnosticBag diagnostics) { // Either our base type is not object, or we have an initializer syntax, or both. We're going to // need to do overload resolution on the set of constructors of the base type, either on // the provided initializer syntax, or on an implicit ": base()" syntax. // SPEC ERROR: The specification states that if you have the situation // SPEC ERROR: class B { ... } class D1 : B {} then the default constructor // SPEC ERROR: generated for D1 must call an accessible *parameterless* constructor // SPEC ERROR: in B. However, it also states that if you have // SPEC ERROR: class B { ... } class D2 : B { D2() {} } or // SPEC ERROR: class B { ... } class D3 : B { D3() : base() {} } then // SPEC ERROR: the compiler performs *overload resolution* to determine // SPEC ERROR: which accessible constructor of B is called. Since B might have // SPEC ERROR: a ctor with all optional parameters, overload resolution might // SPEC ERROR: succeed even if there is no parameterless constructor. This // SPEC ERROR: is unintentionally inconsistent, and the native compiler does not // SPEC ERROR: implement this behavior. Rather, we should say in the spec that // SPEC ERROR: if there is no ctor in D1, then a ctor is created for you exactly // SPEC ERROR: as though you'd said "D1() : base() {}". // SPEC ERROR: This is what we now do in Roslyn. Debug.Assert((object)constructor != null); Debug.Assert(constructor.MethodKind == MethodKind.Constructor || constructor.MethodKind == MethodKind.StaticConstructor); // error scenario: constructor initializer on static constructor Debug.Assert(diagnostics != null); NamedTypeSymbol containingType = constructor.ContainingType; // Structs and enums do not have implicit constructor initializers. if ((containingType.TypeKind == TypeKind.Enum || containingType.TypeKind == TypeKind.Struct) && initializerArgumentListOpt == null) { return null; } AnalyzedArguments analyzedArguments = AnalyzedArguments.GetInstance(); try { TypeSymbol constructorReturnType = constructor.ReturnType; Debug.Assert(constructorReturnType.IsVoidType()); //true of all constructors NamedTypeSymbol baseType = containingType.BaseTypeNoUseSiteDiagnostics; // Get the bound arguments and the argument names. // : this(__arglist()) is legal if (initializerArgumentListOpt != null) { this.BindArgumentsAndNames(initializerArgumentListOpt, diagnostics, analyzedArguments, allowArglist: true); } NamedTypeSymbol initializerType = containingType; bool isBaseConstructorInitializer = initializerArgumentListOpt == null || initializerArgumentListOpt.Parent.Kind() != SyntaxKind.ThisConstructorInitializer; if (isBaseConstructorInitializer) { initializerType = initializerType.BaseTypeNoUseSiteDiagnostics; // Soft assert: we think this is the case, and we're asserting to catch scenarios that violate our expectations Debug.Assert((object)initializerType != null || containingType.SpecialType == SpecialType.System_Object || containingType.IsInterface); if ((object)initializerType == null || containingType.SpecialType == SpecialType.System_Object) //e.g. when defining System.Object in source { // If the constructor initializer is implicit and there is no base type, we're done. // Otherwise, if the constructor initializer is explicit, we're in an error state. if (initializerArgumentListOpt == null) { return null; } else { diagnostics.Add(ErrorCode.ERR_ObjectCallingBaseConstructor, constructor.Locations[0], containingType); return new BoundBadExpression( syntax: initializerArgumentListOpt.Parent, resultKind: LookupResultKind.Empty, symbols: ImmutableArray<Symbol>.Empty, childBoundNodes: BuildArgumentsForErrorRecovery(analyzedArguments), type: constructorReturnType); } } else if (initializerArgumentListOpt != null && containingType.TypeKind == TypeKind.Struct) { diagnostics.Add(ErrorCode.ERR_StructWithBaseConstructorCall, constructor.Locations[0], containingType); return new BoundBadExpression( syntax: initializerArgumentListOpt.Parent, resultKind: LookupResultKind.Empty, symbols: ImmutableArray<Symbol>.Empty, //CONSIDER: we could look for a matching constructor on System.ValueType childBoundNodes: BuildArgumentsForErrorRecovery(analyzedArguments), type: constructorReturnType); } } else { Debug.Assert(initializerArgumentListOpt.Parent.Kind() == SyntaxKind.ThisConstructorInitializer); } CSharpSyntaxNode nonNullSyntax; Location errorLocation; bool enableCallerInfo; switch (initializerArgumentListOpt?.Parent) { case ConstructorInitializerSyntax initializerSyntax: nonNullSyntax = initializerSyntax; errorLocation = initializerSyntax.ThisOrBaseKeyword.GetLocation(); enableCallerInfo = true; break; case PrimaryConstructorBaseTypeSyntax baseWithArguments: nonNullSyntax = baseWithArguments; errorLocation = initializerArgumentListOpt.GetLocation(); enableCallerInfo = true; break; default: // Note: use syntax node of constructor with initializer, not constructor invoked by initializer (i.e. methodResolutionResult). nonNullSyntax = constructor.GetNonNullSyntaxNode(); errorLocation = constructor.Locations[0]; enableCallerInfo = false; break; } if (initializerArgumentListOpt != null && analyzedArguments.HasDynamicArgument) { diagnostics.Add(ErrorCode.ERR_NoDynamicPhantomOnBaseCtor, errorLocation); return new BoundBadExpression( syntax: initializerArgumentListOpt.Parent, resultKind: LookupResultKind.Empty, symbols: ImmutableArray<Symbol>.Empty, //CONSIDER: we could look for a matching constructor on System.ValueType childBoundNodes: BuildArgumentsForErrorRecovery(analyzedArguments), type: constructorReturnType); } BoundExpression receiver = ThisReference(nonNullSyntax, initializerType, wasCompilerGenerated: true); MemberResolutionResult<MethodSymbol> memberResolutionResult; ImmutableArray<MethodSymbol> candidateConstructors; bool found = TryPerformConstructorOverloadResolution( initializerType, analyzedArguments, WellKnownMemberNames.InstanceConstructorName, errorLocation, false, // Don't suppress result diagnostics diagnostics, out memberResolutionResult, out candidateConstructors, allowProtectedConstructorsOfBaseType: true); MethodSymbol resultMember = memberResolutionResult.Member; validateRecordCopyConstructor(constructor, baseType, resultMember, errorLocation, diagnostics); if (found) { bool hasErrors = false; if (resultMember == constructor) { Debug.Assert(initializerType.IsErrorType() || (initializerArgumentListOpt != null && initializerArgumentListOpt.Parent.Kind() == SyntaxKind.ThisConstructorInitializer)); diagnostics.Add(ErrorCode.ERR_RecursiveConstructorCall, errorLocation, constructor); hasErrors = true; // prevent recursive constructor from being emitted } else if (resultMember.HasUnsafeParameter()) { // What if some of the arguments are implicit? Dev10 reports unsafe errors // if the implied argument would have an unsafe type. We need to check // the parameters explicitly, since there won't be bound nodes for the implied // arguments until lowering. // Don't worry about double reporting (i.e. for both the argument and the parameter) // because only one unsafe diagnostic is allowed per scope - the others are suppressed. hasErrors = ReportUnsafeIfNotAllowed(errorLocation, diagnostics); } ReportDiagnosticsIfObsolete(diagnostics, resultMember, nonNullSyntax, hasBaseReceiver: isBaseConstructorInitializer); var expanded = memberResolutionResult.Result.Kind == MemberResolutionKind.ApplicableInExpandedForm; var argsToParamsOpt = memberResolutionResult.Result.ArgsToParamsOpt; BindDefaultArguments(nonNullSyntax, resultMember.Parameters, analyzedArguments.Arguments, analyzedArguments.RefKinds, ref argsToParamsOpt, out var defaultArguments, expanded, enableCallerInfo, diagnostics); var arguments = analyzedArguments.Arguments.ToImmutable(); var refKinds = analyzedArguments.RefKinds.ToImmutableOrNull(); if (!hasErrors) { hasErrors = !CheckInvocationArgMixing( nonNullSyntax, resultMember, receiver, resultMember.Parameters, arguments, argsToParamsOpt, this.LocalScopeDepth, diagnostics); } return new BoundCall( nonNullSyntax, receiver, resultMember, arguments, analyzedArguments.GetNames(), refKinds, isDelegateCall: false, expanded, invokedAsExtensionMethod: false, argsToParamsOpt: argsToParamsOpt, defaultArguments: defaultArguments, resultKind: LookupResultKind.Viable, type: constructorReturnType, hasErrors: hasErrors) { WasCompilerGenerated = initializerArgumentListOpt == null }; } else { var result = CreateBadCall( node: nonNullSyntax, name: WellKnownMemberNames.InstanceConstructorName, receiver: receiver, methods: candidateConstructors, resultKind: LookupResultKind.OverloadResolutionFailure, typeArgumentsWithAnnotations: ImmutableArray<TypeWithAnnotations>.Empty, analyzedArguments: analyzedArguments, invokedAsExtensionMethod: false, isDelegate: false); result.WasCompilerGenerated = initializerArgumentListOpt == null; return result; } } finally { analyzedArguments.Free(); } static void validateRecordCopyConstructor(MethodSymbol constructor, NamedTypeSymbol baseType, MethodSymbol resultMember, Location errorLocation, BindingDiagnosticBag diagnostics) { if (IsUserDefinedRecordCopyConstructor(constructor)) { if (baseType.SpecialType == SpecialType.System_Object) { if (resultMember is null || resultMember.ContainingType.SpecialType != SpecialType.System_Object) { // Record deriving from object must use `base()`, not `this()` diagnostics.Add(ErrorCode.ERR_CopyConstructorMustInvokeBaseCopyConstructor, errorLocation); } return; } // Unless the base type is 'object', the constructor should invoke a base type copy constructor if (resultMember is null || !SynthesizedRecordCopyCtor.HasCopyConstructorSignature(resultMember)) { diagnostics.Add(ErrorCode.ERR_CopyConstructorMustInvokeBaseCopyConstructor, errorLocation); } } } } internal static bool IsUserDefinedRecordCopyConstructor(MethodSymbol constructor) { return constructor.ContainingType is SourceNamedTypeSymbol sourceType && sourceType.IsRecord && constructor is not SynthesizedRecordConstructor && SynthesizedRecordCopyCtor.HasCopyConstructorSignature(constructor); } private BoundExpression BindImplicitObjectCreationExpression(ImplicitObjectCreationExpressionSyntax node, BindingDiagnosticBag diagnostics) { var arguments = AnalyzedArguments.GetInstance(); BindArgumentsAndNames(node.ArgumentList, diagnostics, arguments, allowArglist: true); var result = new BoundUnconvertedObjectCreationExpression( node, arguments.Arguments.ToImmutable(), arguments.Names.ToImmutableOrNull(), arguments.RefKinds.ToImmutableOrNull(), node.Initializer); arguments.Free(); return result; } protected BoundExpression BindObjectCreationExpression(ObjectCreationExpressionSyntax node, BindingDiagnosticBag diagnostics) { var typeWithAnnotations = BindType(node.Type, diagnostics); var type = typeWithAnnotations.Type; var originalType = type; if (typeWithAnnotations.NullableAnnotation.IsAnnotated() && !type.IsNullableType()) { diagnostics.Add(ErrorCode.ERR_AnnotationDisallowedInObjectCreation, node.Location, type); } switch (type.TypeKind) { case TypeKind.Struct: case TypeKind.Class: case TypeKind.Enum: case TypeKind.Error: return BindClassCreationExpression(node, (NamedTypeSymbol)type, GetName(node.Type), diagnostics, originalType); case TypeKind.Delegate: return BindDelegateCreationExpression(node, (NamedTypeSymbol)type, diagnostics); case TypeKind.Interface: return BindInterfaceCreationExpression(node, (NamedTypeSymbol)type, diagnostics); case TypeKind.TypeParameter: return BindTypeParameterCreationExpression(node, (TypeParameterSymbol)type, diagnostics); case TypeKind.Submission: // script class is synthesized and should not be used as a type of a new expression: throw ExceptionUtilities.UnexpectedValue(type.TypeKind); case TypeKind.Pointer: case TypeKind.FunctionPointer: type = new ExtendedErrorTypeSymbol(type, LookupResultKind.NotCreatable, diagnostics.Add(ErrorCode.ERR_UnsafeTypeInObjectCreation, node.Location, type)); goto case TypeKind.Class; case TypeKind.Dynamic: // we didn't find any type called "dynamic" so we are using the builtin dynamic type, which has no constructors: case TypeKind.Array: // ex: new ref[] type = new ExtendedErrorTypeSymbol(type, LookupResultKind.NotCreatable, diagnostics.Add(ErrorCode.ERR_InvalidObjectCreation, node.Type.Location, type)); goto case TypeKind.Class; default: throw ExceptionUtilities.UnexpectedValue(type.TypeKind); } } private BoundExpression BindDelegateCreationExpression(ObjectCreationExpressionSyntax node, NamedTypeSymbol type, BindingDiagnosticBag diagnostics) { AnalyzedArguments analyzedArguments = AnalyzedArguments.GetInstance(); BindArgumentsAndNames(node.ArgumentList, diagnostics, analyzedArguments, isDelegateCreation: true); var result = BindDelegateCreationExpression(node, type, analyzedArguments, node.Initializer, diagnostics); analyzedArguments.Free(); return result; } private BoundExpression BindDelegateCreationExpression(SyntaxNode node, NamedTypeSymbol type, AnalyzedArguments analyzedArguments, InitializerExpressionSyntax initializerOpt, BindingDiagnosticBag diagnostics) { bool hasErrors = false; if (analyzedArguments.HasErrors) { // Let's skip this part of further error checking without marking hasErrors = true here, // as the argument could be an unbound lambda, and the error could come from inside. // We'll check analyzedArguments.HasErrors again after we find if this is not the case. } else if (analyzedArguments.Arguments.Count == 0) { diagnostics.Add(ErrorCode.ERR_BadCtorArgCount, node.Location, type, 0); hasErrors = true; } else if (analyzedArguments.Names.Count != 0 || analyzedArguments.RefKinds.Count != 0 || analyzedArguments.Arguments.Count != 1) { // Use a smaller span that excludes the parens. var argSyntax = analyzedArguments.Arguments[0].Syntax; var start = argSyntax.SpanStart; var end = analyzedArguments.Arguments[analyzedArguments.Arguments.Count - 1].Syntax.Span.End; var errorSpan = new TextSpan(start, end - start); var loc = new SourceLocation(argSyntax.SyntaxTree, errorSpan); diagnostics.Add(ErrorCode.ERR_MethodNameExpected, loc); hasErrors = true; } if (initializerOpt != null) { Error(diagnostics, ErrorCode.ERR_ObjectOrCollectionInitializerWithDelegateCreation, node); hasErrors = true; } BoundExpression argument = analyzedArguments.Arguments.Count >= 1 ? BindToNaturalType(analyzedArguments.Arguments[0], diagnostics) : null; if (hasErrors) { // skip the rest of this binding } // There are four cases for a delegate creation expression (7.6.10.5): // 1. An anonymous function is treated as a conversion from the anonymous function to the delegate type. else if (argument is UnboundLambda unboundLambda) { // analyzedArguments.HasErrors could be true, // but here the argument is an unbound lambda, the error comes from inside // eg: new Action<int>(x => x.) // We should try to bind it anyway in order for intellisense to work. CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); var conversion = this.Conversions.ClassifyConversionFromExpression(unboundLambda, type, ref useSiteInfo); diagnostics.Add(node, useSiteInfo); // Attempting to make the conversion caches the diagnostics and the bound state inside // the unbound lambda. Fetch the result from the cache. BoundLambda boundLambda = unboundLambda.Bind(type); if (!conversion.IsImplicit || !conversion.IsValid) { GenerateImplicitConversionError(diagnostics, unboundLambda.Syntax, conversion, unboundLambda, type); } else { // We're not going to produce an error, but it is possible that the conversion from // the lambda to the delegate type produced a warning, which we have not reported. // Instead, we've cached it in the bound lambda. Report it now. diagnostics.AddRange(boundLambda.Diagnostics); } // Just stuff the bound lambda into the delegate creation expression. When we lower the lambda to // its method form we will rewrite this expression to refer to the method. return new BoundDelegateCreationExpression(node, boundLambda, methodOpt: null, isExtensionMethod: false, type: type, hasErrors: !conversion.IsImplicit); } else if (analyzedArguments.HasErrors) { // There is no hope, skip. } // 2. A method group else if (argument.Kind == BoundKind.MethodGroup) { Conversion conversion; BoundMethodGroup methodGroup = (BoundMethodGroup)argument; hasErrors = MethodGroupConversionDoesNotExistOrHasErrors(methodGroup, type, node.Location, diagnostics, out conversion); methodGroup = FixMethodGroupWithTypeOrValue(methodGroup, conversion, diagnostics); return new BoundDelegateCreationExpression(node, methodGroup, conversion.Method, conversion.IsExtensionMethod, type, hasErrors); } else if ((object)argument.Type == null) { diagnostics.Add(ErrorCode.ERR_MethodNameExpected, argument.Syntax.Location); } // 3. A value of the compile-time type dynamic (which is dynamically case 4), or else if (argument.HasDynamicType()) { return new BoundDelegateCreationExpression(node, argument, methodOpt: null, isExtensionMethod: false, type: type); } // 4. A delegate type. else if (argument.Type.TypeKind == TypeKind.Delegate) { var sourceDelegate = (NamedTypeSymbol)argument.Type; MethodGroup methodGroup = MethodGroup.GetInstance(); try { if (ReportDelegateInvokeUseSiteDiagnostic(diagnostics, argument.Type, node: node)) { // We want failed "new" expression to use the constructors as their symbols. return new BoundBadExpression(node, LookupResultKind.NotInvocable, StaticCast<Symbol>.From(type.InstanceConstructors), ImmutableArray.Create(argument), type); } methodGroup.PopulateWithSingleMethod(argument, sourceDelegate.DelegateInvokeMethod); CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); Conversion conv = Conversions.MethodGroupConversion(argument.Syntax, methodGroup, type, ref useSiteInfo); diagnostics.Add(node, useSiteInfo); if (!conv.Exists) { var boundMethodGroup = new BoundMethodGroup( argument.Syntax, default, WellKnownMemberNames.DelegateInvokeName, ImmutableArray.Create(sourceDelegate.DelegateInvokeMethod), sourceDelegate.DelegateInvokeMethod, null, BoundMethodGroupFlags.None, argument, LookupResultKind.Viable); if (!Conversions.ReportDelegateOrFunctionPointerMethodGroupDiagnostics(this, boundMethodGroup, type, diagnostics)) { // If we could not produce a more specialized diagnostic, we report // No overload for '{0}' matches delegate '{1}' diagnostics.Add(ErrorCode.ERR_MethDelegateMismatch, node.Location, sourceDelegate.DelegateInvokeMethod, type); } } else { Debug.Assert(!conv.IsExtensionMethod); Debug.Assert(conv.IsValid); // i.e. if it exists, then it is valid. if (!this.MethodGroupConversionHasErrors(argument.Syntax, conv, argument, conv.IsExtensionMethod, isAddressOf: false, type, diagnostics)) { // we do not place the "Invoke" method in the node, indicating that it did not appear in source. return new BoundDelegateCreationExpression(node, argument, methodOpt: null, isExtensionMethod: false, type: type); } } } finally { methodGroup.Free(); } } // Not a valid delegate creation expression else { diagnostics.Add(ErrorCode.ERR_MethodNameExpected, argument.Syntax.Location); } // Note that we want failed "new" expression to use the constructors as their symbols. var childNodes = BuildArgumentsForErrorRecovery(analyzedArguments); return new BoundBadExpression(node, LookupResultKind.OverloadResolutionFailure, StaticCast<Symbol>.From(type.InstanceConstructors), childNodes, type); } private BoundExpression BindClassCreationExpression(ObjectCreationExpressionSyntax node, NamedTypeSymbol type, string typeName, BindingDiagnosticBag diagnostics, TypeSymbol initializerType = null) { // Get the bound arguments and the argument names. AnalyzedArguments analyzedArguments = AnalyzedArguments.GetInstance(); try { // new C(__arglist()) is legal BindArgumentsAndNames(node.ArgumentList, diagnostics, analyzedArguments, allowArglist: true); // No point in performing overload resolution if the type is static or a tuple literal. // Just return a bad expression containing the arguments. if (type.IsStatic) { diagnostics.Add(ErrorCode.ERR_InstantiatingStaticClass, node.Location, type); return MakeBadExpressionForObjectCreation(node, type, analyzedArguments, diagnostics); } else if (node.Type.Kind() == SyntaxKind.TupleType) { diagnostics.Add(ErrorCode.ERR_NewWithTupleTypeSyntax, node.Type.GetLocation()); return MakeBadExpressionForObjectCreation(node, type, analyzedArguments, diagnostics); } return BindClassCreationExpression(node, typeName, node.Type, type, analyzedArguments, diagnostics, node.Initializer, initializerType); } finally { analyzedArguments.Free(); } } #nullable enable /// <summary> /// Helper method to create a synthesized constructor invocation. /// </summary> private BoundExpression MakeConstructorInvocation( NamedTypeSymbol type, ArrayBuilder<BoundExpression> arguments, ArrayBuilder<RefKind> refKinds, SyntaxNode node, BindingDiagnosticBag diagnostics) { Debug.Assert(type.TypeKind is TypeKind.Class or TypeKind.Struct); var analyzedArguments = AnalyzedArguments.GetInstance(); try { analyzedArguments.Arguments.AddRange(arguments); analyzedArguments.RefKinds.AddRange(refKinds); if (type.IsStatic) { diagnostics.Add(ErrorCode.ERR_InstantiatingStaticClass, node.Location, type); return MakeBadExpressionForObjectCreation(node, type, analyzedArguments, initializerOpt: null, typeSyntax: null, diagnostics, wasCompilerGenerated: true); } var creation = BindClassCreationExpression(node, type.Name, node, type, analyzedArguments, diagnostics); creation.WasCompilerGenerated = true; return creation; } finally { analyzedArguments.Free(); } } internal BoundExpression BindObjectCreationForErrorRecovery(BoundUnconvertedObjectCreationExpression node, BindingDiagnosticBag diagnostics) { var arguments = AnalyzedArguments.GetInstance(node.Arguments, node.ArgumentRefKindsOpt, node.ArgumentNamesOpt); var result = MakeBadExpressionForObjectCreation(node.Syntax, CreateErrorType(), arguments, node.InitializerOpt, typeSyntax: node.Syntax, diagnostics); arguments.Free(); return result; } private BoundExpression MakeBadExpressionForObjectCreation(ObjectCreationExpressionSyntax node, TypeSymbol type, AnalyzedArguments analyzedArguments, BindingDiagnosticBag diagnostics, bool wasCompilerGenerated = false) { return MakeBadExpressionForObjectCreation(node, type, analyzedArguments, node.Initializer, node.Type, diagnostics, wasCompilerGenerated); } /// <param name="typeSyntax">Shouldn't be null if <paramref name="initializerOpt"/> is not null.</param> private BoundExpression MakeBadExpressionForObjectCreation(SyntaxNode node, TypeSymbol type, AnalyzedArguments analyzedArguments, InitializerExpressionSyntax? initializerOpt, SyntaxNode? typeSyntax, BindingDiagnosticBag diagnostics, bool wasCompilerGenerated = false) { var children = ArrayBuilder<BoundExpression>.GetInstance(); children.AddRange(BuildArgumentsForErrorRecovery(analyzedArguments)); if (initializerOpt != null) { Debug.Assert(typeSyntax is not null); var boundInitializer = BindInitializerExpression(syntax: initializerOpt, type: type, typeSyntax: typeSyntax, isForNewInstance: true, diagnostics: diagnostics); children.Add(boundInitializer); } return new BoundBadExpression(node, LookupResultKind.NotCreatable, ImmutableArray.Create<Symbol?>(type), children.ToImmutableAndFree(), type) { WasCompilerGenerated = wasCompilerGenerated }; } #nullable disable private BoundObjectInitializerExpressionBase BindInitializerExpression( InitializerExpressionSyntax syntax, TypeSymbol type, SyntaxNode typeSyntax, bool isForNewInstance, BindingDiagnosticBag diagnostics) { Debug.Assert(syntax != null); Debug.Assert((object)type != null); var implicitReceiver = new BoundObjectOrCollectionValuePlaceholder(typeSyntax, isForNewInstance, type) { WasCompilerGenerated = true }; switch (syntax.Kind()) { case SyntaxKind.ObjectInitializerExpression: // Uses a special binder to produce customized diagnostics for the object initializer return BindObjectInitializerExpression( syntax, type, diagnostics, implicitReceiver, useObjectInitDiagnostics: true); case SyntaxKind.WithInitializerExpression: return BindObjectInitializerExpression( syntax, type, diagnostics, implicitReceiver, useObjectInitDiagnostics: false); case SyntaxKind.CollectionInitializerExpression: return BindCollectionInitializerExpression(syntax, type, diagnostics, implicitReceiver); default: throw ExceptionUtilities.Unreachable; } } private BoundExpression BindInitializerExpressionOrValue( ExpressionSyntax syntax, TypeSymbol type, SyntaxNode typeSyntax, BindingDiagnosticBag diagnostics) { Debug.Assert(syntax != null); Debug.Assert((object)type != null); switch (syntax.Kind()) { case SyntaxKind.ObjectInitializerExpression: case SyntaxKind.CollectionInitializerExpression: Debug.Assert(syntax.Parent.Parent.Kind() != SyntaxKind.WithInitializerExpression); return BindInitializerExpression((InitializerExpressionSyntax)syntax, type, typeSyntax, isForNewInstance: false, diagnostics); default: return BindValue(syntax, diagnostics, BindValueKind.RValue); } } private BoundObjectInitializerExpression BindObjectInitializerExpression( InitializerExpressionSyntax initializerSyntax, TypeSymbol initializerType, BindingDiagnosticBag diagnostics, BoundObjectOrCollectionValuePlaceholder implicitReceiver, bool useObjectInitDiagnostics) { // SPEC: 7.6.10.2 Object initializers // // SPEC: An object initializer consists of a sequence of member initializers, enclosed by { and } tokens and separated by commas. // SPEC: Each member initializer must name an accessible field or property of the object being initialized, followed by an equals sign and // SPEC: an expression or an object initializer or collection initializer. Debug.Assert(initializerSyntax.Kind() == SyntaxKind.ObjectInitializerExpression || initializerSyntax.Kind() == SyntaxKind.WithInitializerExpression); Debug.Assert((object)initializerType != null); // We use a location specific binder for binding object initializer field/property access to generate object initializer specific diagnostics: // 1) CS1914 (ERR_StaticMemberInObjectInitializer) // 2) CS1917 (ERR_ReadonlyValueTypeInObjectInitializer) // 3) CS1918 (ERR_ValueTypePropertyInObjectInitializer) // Note that this is only used for the LHS of the assignment - these diagnostics do not apply on the RHS. // For this reason, we will actually need two binders: this and this.WithAdditionalFlags. var objectInitializerMemberBinder = useObjectInitDiagnostics ? this.WithAdditionalFlags(BinderFlags.ObjectInitializerMember) : this; var initializers = ArrayBuilder<BoundExpression>.GetInstance(initializerSyntax.Expressions.Count); // Member name map to report duplicate assignments to a field/property. var memberNameMap = PooledHashSet<string>.GetInstance(); foreach (var memberInitializer in initializerSyntax.Expressions) { BoundExpression boundMemberInitializer = BindInitializerMemberAssignment( memberInitializer, initializerType, objectInitializerMemberBinder, diagnostics, implicitReceiver); initializers.Add(boundMemberInitializer); ReportDuplicateObjectMemberInitializers(boundMemberInitializer, memberNameMap, diagnostics); } return new BoundObjectInitializerExpression( initializerSyntax, implicitReceiver, initializers.ToImmutableAndFree(), initializerType); } private BoundExpression BindInitializerMemberAssignment( ExpressionSyntax memberInitializer, TypeSymbol initializerType, Binder objectInitializerMemberBinder, BindingDiagnosticBag diagnostics, BoundObjectOrCollectionValuePlaceholder implicitReceiver) { // SPEC: A member initializer that specifies an expression after the equals sign is processed in the same way as an assignment (spec 7.17.1) to the field or property. if (memberInitializer.Kind() == SyntaxKind.SimpleAssignmentExpression) { var initializer = (AssignmentExpressionSyntax)memberInitializer; // Bind member initializer identifier, i.e. left part of assignment BoundExpression boundLeft = null; var leftSyntax = initializer.Left; if (initializerType.IsDynamic() && leftSyntax.Kind() == SyntaxKind.IdentifierName) { { // D = { ..., <identifier> = <expr>, ... }, where D : dynamic var memberName = ((IdentifierNameSyntax)leftSyntax).Identifier.Text; boundLeft = new BoundDynamicObjectInitializerMember(leftSyntax, memberName, implicitReceiver.Type, initializerType, hasErrors: false); } } else { // We use a location specific binder for binding object initializer field/property access to generate object initializer specific diagnostics: // 1) CS1914 (ERR_StaticMemberInObjectInitializer) // 2) CS1917 (ERR_ReadonlyValueTypeInObjectInitializer) // 3) CS1918 (ERR_ValueTypePropertyInObjectInitializer) // See comments in BindObjectInitializerExpression for more details. Debug.Assert(objectInitializerMemberBinder != null); boundLeft = objectInitializerMemberBinder.BindObjectInitializerMember(initializer, implicitReceiver, diagnostics); } if (boundLeft != null) { Debug.Assert((object)boundLeft.Type != null); // Bind member initializer value, i.e. right part of assignment BoundExpression boundRight = BindInitializerExpressionOrValue( syntax: initializer.Right, type: boundLeft.Type, typeSyntax: boundLeft.Syntax, diagnostics: diagnostics); // Bind member initializer assignment expression return BindAssignment(initializer, boundLeft, boundRight, isRef: false, diagnostics); } } var boundExpression = BindValue(memberInitializer, diagnostics, BindValueKind.RValue); Error(diagnostics, ErrorCode.ERR_InvalidInitializerElementInitializer, memberInitializer); return ToBadExpression(boundExpression, LookupResultKind.NotAValue); } // returns BadBoundExpression or BoundObjectInitializerMember private BoundExpression BindObjectInitializerMember( AssignmentExpressionSyntax namedAssignment, BoundObjectOrCollectionValuePlaceholder implicitReceiver, BindingDiagnosticBag diagnostics) { BoundExpression boundMember; LookupResultKind resultKind; bool hasErrors; if (namedAssignment.Left.Kind() == SyntaxKind.IdentifierName) { var memberName = (IdentifierNameSyntax)namedAssignment.Left; // SPEC: Each member initializer must name an accessible field or property of the object being initialized, followed by an equals sign and // SPEC: an expression or an object initializer or collection initializer. // SPEC: A member initializer that specifies an expression after the equals sign is processed in the same way as an assignment (7.17.1) to the field or property. // SPEC VIOLATION: Native compiler also allows initialization of field-like events in object initializers, so we allow it as well. boundMember = BindInstanceMemberAccess( node: memberName, right: memberName, boundLeft: implicitReceiver, rightName: memberName.Identifier.ValueText, rightArity: 0, typeArgumentsSyntax: default(SeparatedSyntaxList<TypeSyntax>), typeArgumentsWithAnnotations: default(ImmutableArray<TypeWithAnnotations>), invoked: false, indexed: false, diagnostics: diagnostics); resultKind = boundMember.ResultKind; hasErrors = boundMember.HasAnyErrors || implicitReceiver.HasAnyErrors; if (boundMember.Kind == BoundKind.PropertyGroup) { boundMember = BindIndexedPropertyAccess((BoundPropertyGroup)boundMember, mustHaveAllOptionalParameters: true, diagnostics: diagnostics); if (boundMember.HasAnyErrors) { hasErrors = true; } } } else if (namedAssignment.Left.Kind() == SyntaxKind.ImplicitElementAccess) { var implicitIndexing = (ImplicitElementAccessSyntax)namedAssignment.Left; boundMember = BindElementAccess(implicitIndexing, implicitReceiver, implicitIndexing.ArgumentList, diagnostics); resultKind = boundMember.ResultKind; hasErrors = boundMember.HasAnyErrors || implicitReceiver.HasAnyErrors; } else { return null; } // SPEC: A member initializer that specifies an object initializer after the equals sign is a nested object initializer, // SPEC: i.e. an initialization of an embedded object. Instead of assigning a new value to the field or property, // SPEC: the assignments in the nested object initializer are treated as assignments to members of the field or property. // SPEC: Nested object initializers cannot be applied to properties with a value type, or to read-only fields with a value type. // NOTE: The dev11 behavior does not match the spec that was current at the time (quoted above). However, in the roslyn // NOTE: timeframe, the spec will be updated to apply the same restriction to nested collection initializers. Therefore, // NOTE: roslyn will implement the dev11 behavior and it will be spec-compliant. // NOTE: In the roslyn timeframe, an additional restriction will (likely) be added to the spec - it is not sufficient for the // NOTE: type of the member to not be a value type - it must actually be a reference type (i.e. unconstrained type parameters // NOTE: should be prohibited). To avoid breaking existing code, roslyn will not implement this new spec clause. // TODO: If/when we have a way to version warnings, we should add a warning for this. BoundKind boundMemberKind = boundMember.Kind; SyntaxKind rhsKind = namedAssignment.Right.Kind(); bool isRhsNestedInitializer = rhsKind == SyntaxKind.ObjectInitializerExpression || rhsKind == SyntaxKind.CollectionInitializerExpression; BindValueKind valueKind = isRhsNestedInitializer ? BindValueKind.RValue : BindValueKind.Assignable; ImmutableArray<BoundExpression> arguments = ImmutableArray<BoundExpression>.Empty; ImmutableArray<string> argumentNamesOpt = default(ImmutableArray<string>); ImmutableArray<int> argsToParamsOpt = default(ImmutableArray<int>); ImmutableArray<RefKind> argumentRefKindsOpt = default(ImmutableArray<RefKind>); BitVector defaultArguments = default(BitVector); bool expanded = false; switch (boundMemberKind) { case BoundKind.FieldAccess: { var fieldSymbol = ((BoundFieldAccess)boundMember).FieldSymbol; if (isRhsNestedInitializer && fieldSymbol.IsReadOnly && fieldSymbol.Type.IsValueType) { if (!hasErrors) { // TODO: distinct error code for collection initializers? (Dev11 doesn't have one.) Error(diagnostics, ErrorCode.ERR_ReadonlyValueTypeInObjectInitializer, namedAssignment.Left, fieldSymbol, fieldSymbol.Type); hasErrors = true; } resultKind = LookupResultKind.NotAValue; } break; } case BoundKind.EventAccess: break; case BoundKind.PropertyAccess: hasErrors |= isRhsNestedInitializer && !CheckNestedObjectInitializerPropertySymbol(((BoundPropertyAccess)boundMember).PropertySymbol, namedAssignment.Left, diagnostics, hasErrors, ref resultKind); break; case BoundKind.IndexerAccess: { var indexer = BindIndexerDefaultArguments((BoundIndexerAccess)boundMember, valueKind, diagnostics); boundMember = indexer; hasErrors |= isRhsNestedInitializer && !CheckNestedObjectInitializerPropertySymbol(indexer.Indexer, namedAssignment.Left, diagnostics, hasErrors, ref resultKind); arguments = indexer.Arguments; argumentNamesOpt = indexer.ArgumentNamesOpt; argsToParamsOpt = indexer.ArgsToParamsOpt; argumentRefKindsOpt = indexer.ArgumentRefKindsOpt; defaultArguments = indexer.DefaultArguments; expanded = indexer.Expanded; break; } case BoundKind.DynamicIndexerAccess: { var indexer = (BoundDynamicIndexerAccess)boundMember; arguments = indexer.Arguments; argumentNamesOpt = indexer.ArgumentNamesOpt; argumentRefKindsOpt = indexer.ArgumentRefKindsOpt; } break; case BoundKind.ArrayAccess: case BoundKind.PointerElementAccess: return boundMember; default: return BadObjectInitializerMemberAccess(boundMember, implicitReceiver, namedAssignment.Left, diagnostics, valueKind, hasErrors); } if (!hasErrors) { // CheckValueKind to generate possible diagnostics for invalid initializers non-viable member lookup result: // 1) CS0154 (ERR_PropertyLacksGet) // 2) CS0200 (ERR_AssgReadonlyProp) if (!CheckValueKind(boundMember.Syntax, boundMember, valueKind, checkingReceiver: false, diagnostics: diagnostics)) { hasErrors = true; resultKind = isRhsNestedInitializer ? LookupResultKind.NotAValue : LookupResultKind.NotAVariable; } } return new BoundObjectInitializerMember( namedAssignment.Left, boundMember.ExpressionSymbol, arguments, argumentNamesOpt, argumentRefKindsOpt, expanded, argsToParamsOpt, defaultArguments, resultKind, implicitReceiver.Type, type: boundMember.Type, hasErrors: hasErrors); } private static bool CheckNestedObjectInitializerPropertySymbol( PropertySymbol propertySymbol, ExpressionSyntax memberNameSyntax, BindingDiagnosticBag diagnostics, bool suppressErrors, ref LookupResultKind resultKind) { bool hasErrors = false; if (propertySymbol.Type.IsValueType) { if (!suppressErrors) { // TODO: distinct error code for collection initializers? (Dev11 doesn't have one.) Error(diagnostics, ErrorCode.ERR_ValueTypePropertyInObjectInitializer, memberNameSyntax, propertySymbol, propertySymbol.Type); hasErrors = true; } resultKind = LookupResultKind.NotAValue; } return !hasErrors; } private BoundExpression BadObjectInitializerMemberAccess( BoundExpression boundMember, BoundObjectOrCollectionValuePlaceholder implicitReceiver, ExpressionSyntax memberNameSyntax, BindingDiagnosticBag diagnostics, BindValueKind valueKind, bool suppressErrors) { if (!suppressErrors) { string member; var identName = memberNameSyntax as IdentifierNameSyntax; if (identName != null) { member = identName.Identifier.ValueText; } else { member = memberNameSyntax.ToString(); } switch (boundMember.ResultKind) { case LookupResultKind.Empty: Error(diagnostics, ErrorCode.ERR_NoSuchMember, memberNameSyntax, implicitReceiver.Type, member); break; case LookupResultKind.Inaccessible: boundMember = CheckValue(boundMember, valueKind, diagnostics); Debug.Assert(boundMember.HasAnyErrors); break; default: Error(diagnostics, ErrorCode.ERR_MemberCannotBeInitialized, memberNameSyntax, member); break; } } return ToBadExpression(boundMember, (valueKind == BindValueKind.RValue) ? LookupResultKind.NotAValue : LookupResultKind.NotAVariable); } private static void ReportDuplicateObjectMemberInitializers(BoundExpression boundMemberInitializer, HashSet<string> memberNameMap, BindingDiagnosticBag diagnostics) { Debug.Assert(memberNameMap != null); // SPEC: It is an error for an object initializer to include more than one member initializer for the same field or property. if (!boundMemberInitializer.HasAnyErrors) { // SPEC: A member initializer that specifies an expression after the equals sign is processed in the same way as an assignment (7.17.1) to the field or property. var memberInitializerSyntax = boundMemberInitializer.Syntax; Debug.Assert(memberInitializerSyntax.Kind() == SyntaxKind.SimpleAssignmentExpression); var namedAssignment = (AssignmentExpressionSyntax)memberInitializerSyntax; var memberNameSyntax = namedAssignment.Left as IdentifierNameSyntax; if (memberNameSyntax != null) { var memberName = memberNameSyntax.Identifier.ValueText; if (!memberNameMap.Add(memberName)) { Error(diagnostics, ErrorCode.ERR_MemberAlreadyInitialized, memberNameSyntax, memberName); } } } } private BoundCollectionInitializerExpression BindCollectionInitializerExpression( InitializerExpressionSyntax initializerSyntax, TypeSymbol initializerType, BindingDiagnosticBag diagnostics, BoundObjectOrCollectionValuePlaceholder implicitReceiver) { // SPEC: 7.6.10.3 Collection initializers // // SPEC: A collection initializer consists of a sequence of element initializers, enclosed by { and } tokens and separated by commas. // SPEC: The following is an example of an object creation expression that includes a collection initializer: // SPEC: List<int> digits = new List<int> { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; // SPEC: The collection object to which a collection initializer is applied must be of a type that implements System.Collections.IEnumerable or // SPEC: a compile-time error occurs. For each specified element in order, the collection initializer invokes an Add method on the target object // SPEC: with the expression list of the element initializer as argument list, applying normal overload resolution for each invocation. // SPEC: Thus, the collection object must contain an applicable Add method for each element initializer. Debug.Assert(initializerSyntax.Kind() == SyntaxKind.CollectionInitializerExpression); Debug.Assert(initializerSyntax.Expressions.Any()); Debug.Assert((object)initializerType != null); var initializerBuilder = ArrayBuilder<BoundExpression>.GetInstance(); // SPEC: The collection object to which a collection initializer is applied must be of a type that implements System.Collections.IEnumerable or // SPEC: a compile-time error occurs. bool hasEnumerableInitializerType = CollectionInitializerTypeImplementsIEnumerable(initializerType, initializerSyntax, diagnostics); if (!hasEnumerableInitializerType && !initializerSyntax.HasErrors && !initializerType.IsErrorType()) { Error(diagnostics, ErrorCode.ERR_CollectionInitRequiresIEnumerable, initializerSyntax, initializerType); } // We use a location specific binder for binding collection initializer Add method to generate specific overload resolution diagnostics: // 1) CS1921 (ERR_InitializerAddHasWrongSignature) // 2) CS1950 (ERR_BadArgTypesForCollectionAdd) // 3) CS1954 (ERR_InitializerAddHasParamModifiers) var collectionInitializerAddMethodBinder = this.WithAdditionalFlags(BinderFlags.CollectionInitializerAddMethod); foreach (var elementInitializer in initializerSyntax.Expressions) { // NOTE: collectionInitializerAddMethodBinder is used only for binding the Add method invocation expression, but not the entire initializer. // NOTE: Hence it is being passed as a parameter to BindCollectionInitializerElement(). // NOTE: Ideally we would want to avoid this and bind the entire initializer with the collectionInitializerAddMethodBinder. // NOTE: However, this approach has few issues. These issues also occur when binding object initializer member assignment. // NOTE: See comments for objectInitializerMemberBinder in BindObjectInitializerExpression method for details about the pitfalls of alternate approaches. BoundExpression boundElementInitializer = BindCollectionInitializerElement(elementInitializer, initializerType, hasEnumerableInitializerType, collectionInitializerAddMethodBinder, diagnostics, implicitReceiver); initializerBuilder.Add(boundElementInitializer); } return new BoundCollectionInitializerExpression(initializerSyntax, implicitReceiver, initializerBuilder.ToImmutableAndFree(), initializerType); } private bool CollectionInitializerTypeImplementsIEnumerable(TypeSymbol initializerType, CSharpSyntaxNode node, BindingDiagnosticBag diagnostics) { // SPEC: The collection object to which a collection initializer is applied must be of a type that implements System.Collections.IEnumerable or // SPEC: a compile-time error occurs. if (initializerType.IsDynamic()) { // We cannot determine at compile time if initializerType implements System.Collections.IEnumerable, we must assume that it does. return true; } else if (!initializerType.IsErrorType()) { TypeSymbol collectionsIEnumerableType = this.GetSpecialType(SpecialType.System_Collections_IEnumerable, diagnostics, node); // NOTE: Ideally, to check if the initializer type implements System.Collections.IEnumerable we can walk through // NOTE: its implemented interfaces. However the native compiler checks to see if there is conversion from initializer // NOTE: type to the predefined System.Collections.IEnumerable type, so we do the same. CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); var result = Conversions.ClassifyImplicitConversionFromType(initializerType, collectionsIEnumerableType, ref useSiteInfo).IsValid; diagnostics.Add(node, useSiteInfo); return result; } else { return false; } } private BoundExpression BindCollectionInitializerElement( ExpressionSyntax elementInitializer, TypeSymbol initializerType, bool hasEnumerableInitializerType, Binder collectionInitializerAddMethodBinder, BindingDiagnosticBag diagnostics, BoundObjectOrCollectionValuePlaceholder implicitReceiver) { // SPEC: Each element initializer specifies an element to be added to the collection object being initialized, and consists of // SPEC: a list of expressions enclosed by { and } tokens and separated by commas. // SPEC: A single-expression element initializer can be written without braces, but cannot then be an assignment expression, // SPEC: to avoid ambiguity with member initializers. The non-assignment-expression production is defined in 7.18. if (elementInitializer.Kind() == SyntaxKind.ComplexElementInitializerExpression) { return BindComplexElementInitializerExpression( (InitializerExpressionSyntax)elementInitializer, diagnostics, hasEnumerableInitializerType, collectionInitializerAddMethodBinder, implicitReceiver); } else { // Must be a non-assignment expression. if (SyntaxFacts.IsAssignmentExpression(elementInitializer.Kind())) { Error(diagnostics, ErrorCode.ERR_InvalidInitializerElementInitializer, elementInitializer); } var boundElementInitializer = BindInitializerExpressionOrValue(elementInitializer, initializerType, implicitReceiver.Syntax, diagnostics); BoundExpression result = BindCollectionInitializerElementAddMethod( elementInitializer, ImmutableArray.Create(boundElementInitializer), hasEnumerableInitializerType, collectionInitializerAddMethodBinder, diagnostics, implicitReceiver); result.WasCompilerGenerated = true; return result; } } private BoundExpression BindComplexElementInitializerExpression( InitializerExpressionSyntax elementInitializer, BindingDiagnosticBag diagnostics, bool hasEnumerableInitializerType, Binder collectionInitializerAddMethodBinder = null, BoundObjectOrCollectionValuePlaceholder implicitReceiver = null) { var elementInitializerExpressions = elementInitializer.Expressions; if (elementInitializerExpressions.Any()) { var exprBuilder = ArrayBuilder<BoundExpression>.GetInstance(); foreach (var childElementInitializer in elementInitializerExpressions) { exprBuilder.Add(BindValue(childElementInitializer, diagnostics, BindValueKind.RValue)); } return BindCollectionInitializerElementAddMethod( elementInitializer, exprBuilder.ToImmutableAndFree(), hasEnumerableInitializerType, collectionInitializerAddMethodBinder, diagnostics, implicitReceiver); } else { Error(diagnostics, ErrorCode.ERR_EmptyElementInitializer, elementInitializer); return BadExpression(elementInitializer, LookupResultKind.NotInvocable); } } private BoundExpression BindUnexpectedComplexElementInitializer(InitializerExpressionSyntax node, BindingDiagnosticBag diagnostics) { Debug.Assert(node.Kind() == SyntaxKind.ComplexElementInitializerExpression); return BindComplexElementInitializerExpression(node, diagnostics, hasEnumerableInitializerType: false); } private BoundExpression BindCollectionInitializerElementAddMethod( ExpressionSyntax elementInitializer, ImmutableArray<BoundExpression> boundElementInitializerExpressions, bool hasEnumerableInitializerType, Binder collectionInitializerAddMethodBinder, BindingDiagnosticBag diagnostics, BoundObjectOrCollectionValuePlaceholder implicitReceiver) { // SPEC: For each specified element in order, the collection initializer invokes an Add method on the target object // SPEC: with the expression list of the element initializer as argument list, applying normal overload resolution for each invocation. // SPEC: Thus, the collection object must contain an applicable Add method for each element initializer. // We use a location specific binder for binding collection initializer Add method to generate specific overload resolution diagnostics. // 1) CS1921 (ERR_InitializerAddHasWrongSignature) // 2) CS1950 (ERR_BadArgTypesForCollectionAdd) // 3) CS1954 (ERR_InitializerAddHasParamModifiers) // See comments in BindCollectionInitializerExpression for more details. Debug.Assert(!boundElementInitializerExpressions.IsEmpty); if (!hasEnumerableInitializerType) { return BadExpression(elementInitializer, LookupResultKind.NotInvocable, ImmutableArray<Symbol>.Empty, boundElementInitializerExpressions); } Debug.Assert(collectionInitializerAddMethodBinder != null); Debug.Assert(collectionInitializerAddMethodBinder.Flags.Includes(BinderFlags.CollectionInitializerAddMethod)); Debug.Assert(implicitReceiver != null); Debug.Assert((object)implicitReceiver.Type != null); if (implicitReceiver.Type.IsDynamic()) { var hasErrors = ReportBadDynamicArguments(elementInitializer, boundElementInitializerExpressions, refKinds: default, diagnostics, queryClause: null); return new BoundDynamicCollectionElementInitializer( elementInitializer, applicableMethods: ImmutableArray<MethodSymbol>.Empty, implicitReceiver, arguments: boundElementInitializerExpressions.SelectAsArray(e => BindToNaturalType(e, diagnostics)), type: GetSpecialType(SpecialType.System_Void, diagnostics, elementInitializer), hasErrors: hasErrors); } // Receiver is early bound, find method Add and invoke it (may still be a dynamic invocation): var addMethodInvocation = collectionInitializerAddMethodBinder.MakeInvocationExpression( elementInitializer, implicitReceiver, methodName: WellKnownMemberNames.CollectionInitializerAddMethodName, args: boundElementInitializerExpressions, diagnostics: diagnostics); if (addMethodInvocation.Kind == BoundKind.DynamicInvocation) { var dynamicInvocation = (BoundDynamicInvocation)addMethodInvocation; return new BoundDynamicCollectionElementInitializer( elementInitializer, dynamicInvocation.ApplicableMethods, implicitReceiver, dynamicInvocation.Arguments, dynamicInvocation.Type, hasErrors: dynamicInvocation.HasAnyErrors); } else if (addMethodInvocation.Kind == BoundKind.Call) { var boundCall = (BoundCall)addMethodInvocation; // Either overload resolution succeeded for this call or it did not. If it // did not succeed then we've stashed the original method symbols from the // method group, and we should use those as the symbols displayed for the // call. If it did succeed then we did not stash any symbols. if (boundCall.HasErrors && !boundCall.OriginalMethodsOpt.IsDefault) { return boundCall; } return new BoundCollectionElementInitializer( elementInitializer, boundCall.Method, boundCall.Arguments, boundCall.ReceiverOpt, boundCall.Expanded, boundCall.ArgsToParamsOpt, boundCall.DefaultArguments, boundCall.InvokedAsExtensionMethod, boundCall.ResultKind, boundCall.Type, boundCall.HasAnyErrors) { WasCompilerGenerated = true }; } else { Debug.Assert(addMethodInvocation.Kind == BoundKind.BadExpression); return addMethodInvocation; } } internal ImmutableArray<MethodSymbol> FilterInaccessibleConstructors(ImmutableArray<MethodSymbol> constructors, bool allowProtectedConstructorsOfBaseType, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { ArrayBuilder<MethodSymbol> builder = null; for (int i = 0; i < constructors.Length; i++) { MethodSymbol constructor = constructors[i]; if (!IsConstructorAccessible(constructor, ref useSiteInfo, allowProtectedConstructorsOfBaseType)) { if (builder == null) { builder = ArrayBuilder<MethodSymbol>.GetInstance(); builder.AddRange(constructors, i); } } else { builder?.Add(constructor); } } return builder == null ? constructors : builder.ToImmutableAndFree(); } private bool IsConstructorAccessible(MethodSymbol constructor, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, bool allowProtectedConstructorsOfBaseType = false) { Debug.Assert((object)constructor != null); Debug.Assert(constructor.MethodKind == MethodKind.Constructor || constructor.MethodKind == MethodKind.StaticConstructor); NamedTypeSymbol containingType = this.ContainingType; if ((object)containingType != null) { // SPEC VIOLATION: The specification implies that when considering // SPEC VIOLATION: instance methods or instance constructors, we first // SPEC VIOLATION: do overload resolution on the accessible members, and // SPEC VIOLATION: then if the best method chosen is protected and accessed // SPEC VIOLATION: through the wrong type, then an error occurs. The native // SPEC VIOLATION: compiler however does it in the opposite order. First it // SPEC VIOLATION: filters out the protected methods that cannot be called // SPEC VIOLATION: through the given type, and then it does overload resolution // SPEC VIOLATION: on the rest. // // That said, it is somewhat odd that the same rule applies to constructors // as instance methods. A protected constructor is never going to be called // via an instance of a *more derived but different class* the way a // virtual method might be. Nevertheless, that's what we do. // // A constructor is accessed through an instance of the type being constructed: return allowProtectedConstructorsOfBaseType ? this.IsAccessible(constructor, ref useSiteInfo, null) : this.IsSymbolAccessibleConditional(constructor, containingType, ref useSiteInfo, constructor.ContainingType); } else { Debug.Assert((object)this.Compilation.Assembly != null); return IsSymbolAccessibleConditional(constructor, this.Compilation.Assembly, ref useSiteInfo); } } protected BoundExpression BindClassCreationExpression( SyntaxNode node, string typeName, SyntaxNode typeNode, NamedTypeSymbol type, AnalyzedArguments analyzedArguments, BindingDiagnosticBag diagnostics, InitializerExpressionSyntax initializerSyntaxOpt = null, TypeSymbol initializerTypeOpt = null, bool wasTargetTyped = false) { BoundExpression result = null; bool hasErrors = type.IsErrorType(); if (type.IsAbstract) { // Report error for new of abstract type. diagnostics.Add(ErrorCode.ERR_NoNewAbstract, node.Location, type); hasErrors = true; } CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); BoundObjectInitializerExpressionBase boundInitializerOpt = null; // If we have a dynamic argument then do overload resolution to see if there are one or more // applicable candidates. If there are, then this is a dynamic object creation; we'll work out // which ctor to call at runtime. If we have a dynamic argument but no applicable candidates // then we do the analysis again for error reporting purposes. if (analyzedArguments.HasDynamicArgument) { OverloadResolutionResult<MethodSymbol> overloadResolutionResult = OverloadResolutionResult<MethodSymbol>.GetInstance(); this.OverloadResolution.ObjectCreationOverloadResolution(GetAccessibleConstructorsForOverloadResolution(type, ref useSiteInfo), analyzedArguments, overloadResolutionResult, ref useSiteInfo); diagnostics.Add(node, useSiteInfo); useSiteInfo = new CompoundUseSiteInfo<AssemblySymbol>(useSiteInfo); if (overloadResolutionResult.HasAnyApplicableMember) { var argArray = BuildArgumentsForDynamicInvocation(analyzedArguments, diagnostics); var refKindsArray = analyzedArguments.RefKinds.ToImmutableOrNull(); hasErrors &= ReportBadDynamicArguments(node, argArray, refKindsArray, diagnostics, queryClause: null); boundInitializerOpt = makeBoundInitializerOpt(); result = new BoundDynamicObjectCreationExpression( node, typeName, argArray, analyzedArguments.GetNames(), refKindsArray, boundInitializerOpt, overloadResolutionResult.GetAllApplicableMembers(), type, hasErrors); } overloadResolutionResult.Free(); if (result != null) { return result; } } if (TryPerformConstructorOverloadResolution( type, analyzedArguments, typeName, typeNode.Location, hasErrors, //don't cascade in these cases diagnostics, out MemberResolutionResult<MethodSymbol> memberResolutionResult, out ImmutableArray<MethodSymbol> candidateConstructors, allowProtectedConstructorsOfBaseType: false)) { var method = memberResolutionResult.Member; bool hasError = false; // What if some of the arguments are implicit? Dev10 reports unsafe errors // if the implied argument would have an unsafe type. We need to check // the parameters explicitly, since there won't be bound nodes for the implied // arguments until lowering. if (method.HasUnsafeParameter()) { // Don't worry about double reporting (i.e. for both the argument and the parameter) // because only one unsafe diagnostic is allowed per scope - the others are suppressed. hasError = ReportUnsafeIfNotAllowed(node, diagnostics) || hasError; } ReportDiagnosticsIfObsolete(diagnostics, method, node, hasBaseReceiver: false); // NOTE: Use-site diagnostics were reported during overload resolution. ConstantValue constantValueOpt = (initializerSyntaxOpt == null && method.IsDefaultValueTypeConstructor(requireZeroInit: true)) ? FoldParameterlessValueTypeConstructor(type) : null; var expanded = memberResolutionResult.Result.Kind == MemberResolutionKind.ApplicableInExpandedForm; var argToParams = memberResolutionResult.Result.ArgsToParamsOpt; BindDefaultArguments(node, method.Parameters, analyzedArguments.Arguments, analyzedArguments.RefKinds, ref argToParams, out var defaultArguments, expanded, enableCallerInfo: true, diagnostics); var arguments = analyzedArguments.Arguments.ToImmutable(); var refKinds = analyzedArguments.RefKinds.ToImmutableOrNull(); if (!hasError) { hasError = !CheckInvocationArgMixing( node, method, null, method.Parameters, arguments, argToParams, this.LocalScopeDepth, diagnostics); } boundInitializerOpt = makeBoundInitializerOpt(); result = new BoundObjectCreationExpression( node, method, candidateConstructors, arguments, analyzedArguments.GetNames(), refKinds, expanded, argToParams, defaultArguments, constantValueOpt, boundInitializerOpt, wasTargetTyped, type, hasError); // CONSIDER: Add ResultKind field to BoundObjectCreationExpression to avoid wrapping result with BoundBadExpression. if (type.IsAbstract) { result = BadExpression(node, LookupResultKind.NotCreatable, result); } return result; } LookupResultKind resultKind; if (type.IsAbstract) { resultKind = LookupResultKind.NotCreatable; } else if (memberResolutionResult.IsValid && !IsConstructorAccessible(memberResolutionResult.Member, ref useSiteInfo)) { resultKind = LookupResultKind.Inaccessible; } else { resultKind = LookupResultKind.OverloadResolutionFailure; } diagnostics.Add(node, useSiteInfo); ArrayBuilder<Symbol> symbols = ArrayBuilder<Symbol>.GetInstance(); symbols.AddRange(candidateConstructors); // NOTE: The use site diagnostics of the candidate constructors have already been reported (in PerformConstructorOverloadResolution). var childNodes = ArrayBuilder<BoundExpression>.GetInstance(); childNodes.AddRange(BuildArgumentsForErrorRecovery(analyzedArguments, candidateConstructors)); if (initializerSyntaxOpt != null) { childNodes.Add(boundInitializerOpt ?? makeBoundInitializerOpt()); } return new BoundBadExpression(node, resultKind, symbols.ToImmutableAndFree(), childNodes.ToImmutableAndFree(), type); BoundObjectInitializerExpressionBase makeBoundInitializerOpt() { if (initializerSyntaxOpt != null) { return BindInitializerExpression(syntax: initializerSyntaxOpt, type: initializerTypeOpt ?? type, typeSyntax: typeNode, isForNewInstance: true, diagnostics: diagnostics); } return null; } } private BoundExpression BindInterfaceCreationExpression(ObjectCreationExpressionSyntax node, NamedTypeSymbol type, BindingDiagnosticBag diagnostics) { AnalyzedArguments analyzedArguments = AnalyzedArguments.GetInstance(); BindArgumentsAndNames(node.ArgumentList, diagnostics, analyzedArguments); var result = BindInterfaceCreationExpression(node, type, diagnostics, node.Type, analyzedArguments, node.Initializer, wasTargetTyped: false); analyzedArguments.Free(); return result; } private BoundExpression BindInterfaceCreationExpression(SyntaxNode node, NamedTypeSymbol type, BindingDiagnosticBag diagnostics, SyntaxNode typeNode, AnalyzedArguments analyzedArguments, InitializerExpressionSyntax initializerOpt, bool wasTargetTyped) { Debug.Assert((object)type != null); // COM interfaces which have ComImportAttribute and CoClassAttribute can be instantiated with "new". // CoClassAttribute contains the type information of the original CoClass for the interface. // We replace the interface creation with CoClass object creation for this case. // NOTE: We don't attempt binding interface creation to CoClass creation if we are within an attribute argument. // NOTE: This is done to prevent a cycle in an error scenario where we have a "new InterfaceType" expression in an attribute argument. // NOTE: Accessing IsComImport/ComImportCoClass properties on given type symbol would attempt ForceCompeteAttributes, which would again try binding all attributes on the symbol. // NOTE: causing infinite recursion. We avoid this cycle by checking if we are within in context of an Attribute argument. if (!this.InAttributeArgument && type.IsComImport) { NamedTypeSymbol coClassType = type.ComImportCoClass; if ((object)coClassType != null) { return BindComImportCoClassCreationExpression(node, type, coClassType, diagnostics, typeNode, analyzedArguments, initializerOpt, wasTargetTyped); } } // interfaces can't be instantiated in C# diagnostics.Add(ErrorCode.ERR_NoNewAbstract, node.Location, type); return MakeBadExpressionForObjectCreation(node, type, analyzedArguments, initializerOpt, typeNode, diagnostics); } private BoundExpression BindComImportCoClassCreationExpression(SyntaxNode node, NamedTypeSymbol interfaceType, NamedTypeSymbol coClassType, BindingDiagnosticBag diagnostics, SyntaxNode typeNode, AnalyzedArguments analyzedArguments, InitializerExpressionSyntax initializerOpt, bool wasTargetTyped) { Debug.Assert((object)interfaceType != null); Debug.Assert(interfaceType.IsInterfaceType()); Debug.Assert((object)coClassType != null); Debug.Assert(TypeSymbol.Equals(interfaceType.ComImportCoClass, coClassType, TypeCompareKind.ConsiderEverything2)); Debug.Assert(coClassType.TypeKind == TypeKind.Class || coClassType.TypeKind == TypeKind.Error); if (coClassType.IsErrorType()) { Error(diagnostics, ErrorCode.ERR_MissingCoClass, node, coClassType, interfaceType); } else if (coClassType.IsUnboundGenericType) { // BREAKING CHANGE: Dev10 allows the following code to compile, even though the output assembly is not verifiable and generates a runtime exception: // // [ComImport, Guid("00020810-0000-0000-C000-000000000046")] // [CoClass(typeof(GenericClass<>))] // public interface InterfaceType {} // public class GenericClass<T>: InterfaceType {} // // public class Program // { // public static void Main() { var i = new InterfaceType(); } // } // // We disallow CoClass creation if coClassType is an unbound generic type and report a compile time error. Error(diagnostics, ErrorCode.ERR_BadCoClassSig, node, coClassType, interfaceType); } else { // NoPIA support if (interfaceType.ContainingAssembly.IsLinked) { return BindNoPiaObjectCreationExpression(node, interfaceType, coClassType, diagnostics, typeNode, analyzedArguments, initializerOpt); } var classCreation = BindClassCreationExpression( node, coClassType.Name, typeNode, coClassType, analyzedArguments, diagnostics, initializerOpt, interfaceType, wasTargetTyped); CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); Conversion conversion = this.Conversions.ClassifyConversionFromExpression(classCreation, interfaceType, ref useSiteInfo, forCast: true); diagnostics.Add(node, useSiteInfo); if (!conversion.IsValid) { SymbolDistinguisher distinguisher = new SymbolDistinguisher(this.Compilation, coClassType, interfaceType); Error(diagnostics, ErrorCode.ERR_NoExplicitConv, node, distinguisher.First, distinguisher.Second); } // Bind the conversion, but drop the conversion node. CreateConversion(classCreation, conversion, interfaceType, diagnostics); // Override result type to be the interface type. switch (classCreation.Kind) { case BoundKind.ObjectCreationExpression: var creation = (BoundObjectCreationExpression)classCreation; return creation.Update(creation.Constructor, creation.ConstructorsGroup, creation.Arguments, creation.ArgumentNamesOpt, creation.ArgumentRefKindsOpt, creation.Expanded, creation.ArgsToParamsOpt, creation.DefaultArguments, creation.ConstantValueOpt, creation.InitializerExpressionOpt, interfaceType); case BoundKind.BadExpression: var bad = (BoundBadExpression)classCreation; return bad.Update(bad.ResultKind, bad.Symbols, bad.ChildBoundNodes, interfaceType); default: throw ExceptionUtilities.UnexpectedValue(classCreation.Kind); } } return MakeBadExpressionForObjectCreation(node, interfaceType, analyzedArguments, initializerOpt, typeNode, diagnostics); } private BoundExpression BindNoPiaObjectCreationExpression( SyntaxNode node, NamedTypeSymbol interfaceType, NamedTypeSymbol coClassType, BindingDiagnosticBag diagnostics, SyntaxNode typeNode, AnalyzedArguments analyzedArguments, InitializerExpressionSyntax initializerOpt) { string guidString; if (!coClassType.GetGuidString(out guidString)) { // At this point, VB reports ERRID_NoPIAAttributeMissing2 if guid isn't there. // C# doesn't complain and instead uses zero guid. guidString = System.Guid.Empty.ToString("D"); } var boundInitializerOpt = initializerOpt == null ? null : BindInitializerExpression(syntax: initializerOpt, type: interfaceType, typeSyntax: typeNode, isForNewInstance: true, diagnostics: diagnostics); var creation = new BoundNoPiaObjectCreationExpression(node, guidString, boundInitializerOpt, interfaceType); if (analyzedArguments.Arguments.Count > 0) { diagnostics.Add(ErrorCode.ERR_BadCtorArgCount, typeNode.Location, interfaceType, analyzedArguments.Arguments.Count); var children = BuildArgumentsForErrorRecovery(analyzedArguments).Add(creation); return new BoundBadExpression(node, LookupResultKind.OverloadResolutionFailure, ImmutableArray<Symbol>.Empty, children, creation.Type); } return creation; } private BoundExpression BindTypeParameterCreationExpression(ObjectCreationExpressionSyntax node, TypeParameterSymbol typeParameter, BindingDiagnosticBag diagnostics) { AnalyzedArguments analyzedArguments = AnalyzedArguments.GetInstance(); BindArgumentsAndNames(node.ArgumentList, diagnostics, analyzedArguments); var result = BindTypeParameterCreationExpression(node, typeParameter, analyzedArguments, node.Initializer, node.Type, diagnostics); analyzedArguments.Free(); return result; } private BoundExpression BindTypeParameterCreationExpression(SyntaxNode node, TypeParameterSymbol typeParameter, AnalyzedArguments analyzedArguments, InitializerExpressionSyntax initializerOpt, SyntaxNode typeSyntax, BindingDiagnosticBag diagnostics) { if (!typeParameter.HasConstructorConstraint && !typeParameter.IsValueType) { diagnostics.Add(ErrorCode.ERR_NoNewTyvar, node.Location, typeParameter); } else if (analyzedArguments.Arguments.Count > 0) { diagnostics.Add(ErrorCode.ERR_NewTyvarWithArgs, node.Location, typeParameter); } else { var boundInitializerOpt = initializerOpt == null ? null : BindInitializerExpression( syntax: initializerOpt, type: typeParameter, typeSyntax: typeSyntax, isForNewInstance: true, diagnostics: diagnostics); return new BoundNewT(node, boundInitializerOpt, typeParameter); } return MakeBadExpressionForObjectCreation(node, typeParameter, analyzedArguments, initializerOpt, typeSyntax, diagnostics); } /// <summary> /// Given the type containing constructors, gets the list of candidate instance constructors and uses overload resolution to determine which one should be called. /// </summary> /// <param name="typeContainingConstructors">The containing type of the constructors.</param> /// <param name="analyzedArguments">The already bound arguments to the constructor.</param> /// <param name="errorName">The name to use in diagnostics if overload resolution fails.</param> /// <param name="errorLocation">The location at which to report overload resolution result diagnostics.</param> /// <param name="suppressResultDiagnostics">True to suppress overload resolution result diagnostics (but not argument diagnostics).</param> /// <param name="diagnostics">Where diagnostics will be reported.</param> /// <param name="memberResolutionResult">If this method returns true, then it will contain a valid MethodResolutionResult. /// Otherwise, it may contain a MethodResolutionResult for an inaccessible constructor (in which case, it will incorrectly indicate success) or nothing at all.</param> /// <param name="candidateConstructors">Candidate instance constructors of type <paramref name="typeContainingConstructors"/> used for overload resolution.</param> /// <param name="allowProtectedConstructorsOfBaseType">It is always legal to access a protected base class constructor /// via a constructor initializer, but not from an object creation expression.</param> /// <returns>True if overload resolution successfully chose an accessible constructor.</returns> /// <remarks> /// The two-pass algorithm (accessible constructors, then all constructors) is the reason for the unusual signature /// of this method (i.e. not populating a pre-existing <see cref="OverloadResolutionResult{MethodSymbol}"/>). /// Presently, rationalizing this behavior is not worthwhile. /// </remarks> internal bool TryPerformConstructorOverloadResolution( NamedTypeSymbol typeContainingConstructors, AnalyzedArguments analyzedArguments, string errorName, Location errorLocation, bool suppressResultDiagnostics, BindingDiagnosticBag diagnostics, out MemberResolutionResult<MethodSymbol> memberResolutionResult, out ImmutableArray<MethodSymbol> candidateConstructors, bool allowProtectedConstructorsOfBaseType) // Last to make named arguments more convenient. { // Get accessible constructors for performing overload resolution. ImmutableArray<MethodSymbol> allInstanceConstructors; CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); candidateConstructors = GetAccessibleConstructorsForOverloadResolution(typeContainingConstructors, allowProtectedConstructorsOfBaseType, out allInstanceConstructors, ref useSiteInfo); OverloadResolutionResult<MethodSymbol> result = OverloadResolutionResult<MethodSymbol>.GetInstance(); // Indicates whether overload resolution successfully chose an accessible constructor. bool succeededConsideringAccessibility = false; // Indicates whether overload resolution resulted in a single best match, even though it might be inaccessible. bool succeededIgnoringAccessibility = false; if (candidateConstructors.Any()) { // We have at least one accessible candidate constructor, perform overload resolution with accessible candidateConstructors. this.OverloadResolution.ObjectCreationOverloadResolution(candidateConstructors, analyzedArguments, result, ref useSiteInfo); if (result.Succeeded) { succeededConsideringAccessibility = true; succeededIgnoringAccessibility = true; } } if (!succeededConsideringAccessibility && allInstanceConstructors.Length > candidateConstructors.Length) { // Overload resolution failed on the accessible candidateConstructors, but we have at least one inaccessible constructor. // We might have a best match constructor which is inaccessible. // Try overload resolution with all instance constructors to generate correct diagnostics and semantic info for this case. OverloadResolutionResult<MethodSymbol> inaccessibleResult = OverloadResolutionResult<MethodSymbol>.GetInstance(); this.OverloadResolution.ObjectCreationOverloadResolution(allInstanceConstructors, analyzedArguments, inaccessibleResult, ref useSiteInfo); if (inaccessibleResult.Succeeded) { succeededIgnoringAccessibility = true; candidateConstructors = allInstanceConstructors; result.Free(); result = inaccessibleResult; } else { inaccessibleResult.Free(); } } diagnostics.Add(errorLocation, useSiteInfo); if (succeededIgnoringAccessibility) { this.CoerceArguments<MethodSymbol>(result.ValidResult, analyzedArguments.Arguments, diagnostics, receiverType: null, receiverRefKind: null, receiverEscapeScope: Binder.ExternalScope); } // Fill in the out parameter with the result, if there was one; it might be inaccessible. memberResolutionResult = succeededIgnoringAccessibility ? result.ValidResult : default(MemberResolutionResult<MethodSymbol>); // Invalid results are not interesting - we have enough info in candidateConstructors. // If something failed and we are reporting errors, then report the right errors. // * If the failure was due to inaccessibility, just report that. // * If the failure was not due to inaccessibility then only report an error // on the constructor if there were no errors on the arguments. if (!succeededConsideringAccessibility && !suppressResultDiagnostics) { if (succeededIgnoringAccessibility) { // It is not legal to directly call a protected constructor on a base class unless // the "this" of the call is known to be of the current type. That is, it is // perfectly legal to say ": base()" to call a protected base class ctor, but // it is not legal to say "new MyBase()" if the ctor is protected. // // The native compiler produces the error CS1540: // // Cannot access protected member 'MyBase.MyBase' via a qualifier of type 'MyBase'; // the qualifier must be of type 'Derived' (or derived from it) // // Though technically correct, this is a very confusing error message for this scenario; // one does not typically think of the constructor as being a method that is // called with an implicit "this" of a particular receiver type, even though of course // that is exactly what it is. // // The better error message here is to simply say that the best possible ctor cannot // be accessed because it is not accessible. // // CONSIDER: We might consider making up a new error message for this situation. // // CS0122: 'MyBase.MyBase' is inaccessible due to its protection level diagnostics.Add(ErrorCode.ERR_BadAccess, errorLocation, result.ValidResult.Member); } else { result.ReportDiagnostics( binder: this, location: errorLocation, nodeOpt: null, diagnostics, name: errorName, receiver: null, invokedExpression: null, analyzedArguments, memberGroup: candidateConstructors, typeContainingConstructors, delegateTypeBeingInvoked: null); } } result.Free(); return succeededConsideringAccessibility; } private ImmutableArray<MethodSymbol> GetAccessibleConstructorsForOverloadResolution(NamedTypeSymbol type, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { ImmutableArray<MethodSymbol> allInstanceConstructors; return GetAccessibleConstructorsForOverloadResolution(type, false, out allInstanceConstructors, ref useSiteInfo); } private ImmutableArray<MethodSymbol> GetAccessibleConstructorsForOverloadResolution(NamedTypeSymbol type, bool allowProtectedConstructorsOfBaseType, out ImmutableArray<MethodSymbol> allInstanceConstructors, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { if (type.IsErrorType()) { // For Caas, we want to supply the constructors even in error cases // We may end up supplying the constructors of an unconstructed symbol, // but that's better than nothing. type = type.GetNonErrorGuess() as NamedTypeSymbol ?? type; } allInstanceConstructors = type.InstanceConstructors; return FilterInaccessibleConstructors(allInstanceConstructors, allowProtectedConstructorsOfBaseType, ref useSiteInfo); } private static ConstantValue FoldParameterlessValueTypeConstructor(NamedTypeSymbol type) { // DELIBERATE SPEC VIOLATION: // // Object creation expressions like "new int()" are not considered constant expressions // by the specification but they are by the native compiler; we maintain compatibility // with this bug. // // Additionally, it also treats "new X()", where X is an enum type, as a // constant expression with default value 0, we maintain compatibility with it. var specialType = type.SpecialType; if (type.TypeKind == TypeKind.Enum) { specialType = type.EnumUnderlyingType.SpecialType; } switch (specialType) { case SpecialType.System_SByte: case SpecialType.System_Int16: case SpecialType.System_Int32: case SpecialType.System_Int64: case SpecialType.System_Byte: case SpecialType.System_UInt16: case SpecialType.System_UInt32: case SpecialType.System_UInt64: case SpecialType.System_Single: case SpecialType.System_Double: case SpecialType.System_Decimal: case SpecialType.System_Boolean: case SpecialType.System_Char: return ConstantValue.Default(specialType); } return null; } private BoundLiteral BindLiteralConstant(LiteralExpressionSyntax node, BindingDiagnosticBag diagnostics) { // bug.Assert(node.Kind == SyntaxKind.LiteralExpression); var value = node.Token.Value; ConstantValue cv; TypeSymbol type = null; if (value == null) { cv = ConstantValue.Null; } else { Debug.Assert(!value.GetType().GetTypeInfo().IsEnum); var specialType = SpecialTypeExtensions.FromRuntimeTypeOfLiteralValue(value); // C# literals can't be of type byte, sbyte, short, ushort: Debug.Assert( specialType != SpecialType.None && specialType != SpecialType.System_Byte && specialType != SpecialType.System_SByte && specialType != SpecialType.System_Int16 && specialType != SpecialType.System_UInt16); cv = ConstantValue.Create(value, specialType); type = GetSpecialType(specialType, diagnostics, node); } return new BoundLiteral(node, cv, type); } private BoundExpression BindCheckedExpression(CheckedExpressionSyntax node, BindingDiagnosticBag diagnostics) { // the binder is not cached since we only cache statement level binders return this.WithCheckedOrUncheckedRegion(node.Kind() == SyntaxKind.CheckedExpression). BindParenthesizedExpression(node.Expression, diagnostics); } /// <summary> /// Binds a member access expression /// </summary> private BoundExpression BindMemberAccess( MemberAccessExpressionSyntax node, bool invoked, bool indexed, BindingDiagnosticBag diagnostics) { Debug.Assert(node != null); BoundExpression boundLeft; ExpressionSyntax exprSyntax = node.Expression; if (node.Kind() == SyntaxKind.SimpleMemberAccessExpression) { // NOTE: CheckValue will be called explicitly in BindMemberAccessWithBoundLeft. boundLeft = BindLeftOfPotentialColorColorMemberAccess(exprSyntax, diagnostics); } else { Debug.Assert(node.Kind() == SyntaxKind.PointerMemberAccessExpression); boundLeft = BindRValueWithoutTargetType(exprSyntax, diagnostics); // Not Color Color issues with -> // CONSIDER: another approach would be to construct a BoundPointerMemberAccess (assuming such a type existed), // but that would be much more cumbersome because we'd be unable to build upon the BindMemberAccess infrastructure, // which expects a receiver. // Dereference before binding member; TypeSymbol pointedAtType; bool hasErrors; BindPointerIndirectionExpressionInternal(node, boundLeft, diagnostics, out pointedAtType, out hasErrors); // If there is no pointed-at type, fall back on the actual type (i.e. assume the user meant "." instead of "->"). if (ReferenceEquals(pointedAtType, null)) { boundLeft = ToBadExpression(boundLeft); } else { boundLeft = new BoundPointerIndirectionOperator(exprSyntax, boundLeft, pointedAtType, hasErrors) { WasCompilerGenerated = true, // don't interfere with the type info for exprSyntax. }; } } return BindMemberAccessWithBoundLeft(node, boundLeft, node.Name, node.OperatorToken, invoked, indexed, diagnostics); } /// <summary> /// Attempt to bind the LHS of a member access expression. If this is a Color Color case (spec 7.6.4.1), /// then return a BoundExpression if we can easily disambiguate or a BoundTypeOrValueExpression if we /// cannot. If this is not a Color Color case, then return null. /// </summary> private BoundExpression BindLeftOfPotentialColorColorMemberAccess(ExpressionSyntax left, BindingDiagnosticBag diagnostics) { if (left is IdentifierNameSyntax identifier) { return BindLeftIdentifierOfPotentialColorColorMemberAccess(identifier, diagnostics); } // NOTE: it is up to the caller to call CheckValue on the result. return BindExpression(left, diagnostics); } // Avoid inlining to minimize stack size in caller. [MethodImpl(MethodImplOptions.NoInlining)] private BoundExpression BindLeftIdentifierOfPotentialColorColorMemberAccess(IdentifierNameSyntax left, BindingDiagnosticBag diagnostics) { // SPEC: 7.6.4.1 Identical simple names and type names // SPEC: In a member access of the form E.I, if E is a single identifier, and if the meaning of E as // SPEC: a simple-name (spec 7.6.2) is a constant, field, property, local variable, or parameter with the // SPEC: same type as the meaning of E as a type-name (spec 3.8), then both possible meanings of E are // SPEC: permitted. The two possible meanings of E.I are never ambiguous, since I must necessarily be // SPEC: a member of the type E in both cases. In other words, the rule simply permits access to the // SPEC: static members and nested types of E where a compile-time error would otherwise have occurred. var valueDiagnostics = BindingDiagnosticBag.Create(diagnostics); var boundValue = BindIdentifier(left, invoked: false, indexed: false, diagnostics: valueDiagnostics); Symbol leftSymbol; if (boundValue.Kind == BoundKind.Conversion) { // BindFieldAccess may insert a conversion if binding occurs // within an enum member initializer. leftSymbol = ((BoundConversion)boundValue).Operand.ExpressionSymbol; } else { leftSymbol = boundValue.ExpressionSymbol; } if ((object)leftSymbol != null) { switch (leftSymbol.Kind) { case SymbolKind.Field: case SymbolKind.Local: case SymbolKind.Parameter: case SymbolKind.Property: case SymbolKind.RangeVariable: var leftType = boundValue.Type; Debug.Assert((object)leftType != null); var leftName = left.Identifier.ValueText; if (leftType.Name == leftName || IsUsingAliasInScope(leftName)) { var typeDiagnostics = BindingDiagnosticBag.Create(diagnostics); var boundType = BindNamespaceOrType(left, typeDiagnostics); if (TypeSymbol.Equals(boundType.Type, leftType, TypeCompareKind.ConsiderEverything2)) { // NOTE: ReplaceTypeOrValueReceiver will call CheckValue explicitly. boundValue = BindToNaturalType(boundValue, valueDiagnostics); return new BoundTypeOrValueExpression(left, new BoundTypeOrValueData(leftSymbol, boundValue, valueDiagnostics, boundType, typeDiagnostics), leftType); } } break; // case SymbolKind.Event: //SPEC: 7.6.4.1 (a.k.a. Color Color) doesn't cover events } } // Not a Color Color case; return the bound member. // NOTE: it is up to the caller to call CheckValue on the result. diagnostics.AddRange(valueDiagnostics); return boundValue; } // returns true if name matches a using alias in scope // NOTE: when true is returned, the corresponding using is also marked as "used" private bool IsUsingAliasInScope(string name) { var isSemanticModel = this.IsSemanticModelBinder; for (var chain = this.ImportChain; chain != null; chain = chain.ParentOpt) { if (IsUsingAlias(chain.Imports.UsingAliases, name, isSemanticModel)) { return true; } } return false; } private BoundExpression BindDynamicMemberAccess( ExpressionSyntax node, BoundExpression boundLeft, SimpleNameSyntax right, bool invoked, bool indexed, BindingDiagnosticBag diagnostics) { // We have an expression of the form "dynExpr.Name" or "dynExpr.Name<X>" SeparatedSyntaxList<TypeSyntax> typeArgumentsSyntax = right.Kind() == SyntaxKind.GenericName ? ((GenericNameSyntax)right).TypeArgumentList.Arguments : default(SeparatedSyntaxList<TypeSyntax>); bool rightHasTypeArguments = typeArgumentsSyntax.Count > 0; ImmutableArray<TypeWithAnnotations> typeArgumentsWithAnnotations = rightHasTypeArguments ? BindTypeArguments(typeArgumentsSyntax, diagnostics) : default(ImmutableArray<TypeWithAnnotations>); bool hasErrors = false; if (!invoked && rightHasTypeArguments) { // error CS0307: The property 'P' cannot be used with type arguments Error(diagnostics, ErrorCode.ERR_TypeArgsNotAllowed, right, right.Identifier.Text, SymbolKind.Property.Localize()); hasErrors = true; } if (rightHasTypeArguments) { for (int i = 0; i < typeArgumentsWithAnnotations.Length; ++i) { var typeArgument = typeArgumentsWithAnnotations[i]; if (typeArgument.Type.IsPointerOrFunctionPointer() || typeArgument.Type.IsRestrictedType()) { // "The type '{0}' may not be used as a type argument" Error(diagnostics, ErrorCode.ERR_BadTypeArgument, typeArgumentsSyntax[i], typeArgument.Type); hasErrors = true; } } } return new BoundDynamicMemberAccess( syntax: node, receiver: boundLeft, typeArgumentsOpt: typeArgumentsWithAnnotations, name: right.Identifier.ValueText, invoked: invoked, indexed: indexed, type: Compilation.DynamicType, hasErrors: hasErrors); } /// <summary> /// Bind the RHS of a member access expression, given the bound LHS. /// It is assumed that CheckValue has not been called on the LHS. /// </summary> /// <remarks> /// If new checks are added to this method, they will also need to be added to <see cref="MakeQueryInvocation(CSharpSyntaxNode, BoundExpression, string, TypeSyntax, TypeWithAnnotations, BindingDiagnosticBag)"/>. /// </remarks> private BoundExpression BindMemberAccessWithBoundLeft( ExpressionSyntax node, BoundExpression boundLeft, SimpleNameSyntax right, SyntaxToken operatorToken, bool invoked, bool indexed, BindingDiagnosticBag diagnostics) { Debug.Assert(node != null); Debug.Assert(boundLeft != null); boundLeft = MakeMemberAccessValue(boundLeft, diagnostics); TypeSymbol leftType = boundLeft.Type; if ((object)leftType != null && leftType.IsDynamic()) { // There are some sources of a `dynamic` typed value that can be known before runtime // to be invalid. For example, accessing a set-only property whose type is dynamic: // dynamic Goo { set; } // If Goo itself is a dynamic thing (e.g. in `x.Goo.Bar`, `x` is dynamic, and we're // currently checking Bar), then CheckValue will do nothing. boundLeft = CheckValue(boundLeft, BindValueKind.RValue, diagnostics); return BindDynamicMemberAccess(node, boundLeft, right, invoked, indexed, diagnostics); } // No member accesses on void if ((object)leftType != null && leftType.IsVoidType()) { diagnostics.Add(ErrorCode.ERR_BadUnaryOp, operatorToken.GetLocation(), SyntaxFacts.GetText(operatorToken.Kind()), leftType); return BadExpression(node, boundLeft); } // No member accesses on default if (boundLeft.IsLiteralDefault()) { DiagnosticInfo diagnosticInfo = new CSDiagnosticInfo(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, SyntaxFacts.GetText(operatorToken.Kind()), boundLeft.Display); diagnostics.Add(new CSDiagnostic(diagnosticInfo, operatorToken.GetLocation())); return BadExpression(node, boundLeft); } if (boundLeft.Kind == BoundKind.UnboundLambda) { Debug.Assert((object)leftType == null); var msgId = ((UnboundLambda)boundLeft).MessageID; diagnostics.Add(ErrorCode.ERR_BadUnaryOp, node.Location, SyntaxFacts.GetText(operatorToken.Kind()), msgId.Localize()); return BadExpression(node, boundLeft); } boundLeft = BindToNaturalType(boundLeft, diagnostics); leftType = boundLeft.Type; var lookupResult = LookupResult.GetInstance(); try { LookupOptions options = LookupOptions.AllMethodsOnArityZero; if (invoked) { options |= LookupOptions.MustBeInvocableIfMember; } var typeArgumentsSyntax = right.Kind() == SyntaxKind.GenericName ? ((GenericNameSyntax)right).TypeArgumentList.Arguments : default(SeparatedSyntaxList<TypeSyntax>); var typeArguments = typeArgumentsSyntax.Count > 0 ? BindTypeArguments(typeArgumentsSyntax, diagnostics) : default(ImmutableArray<TypeWithAnnotations>); // A member-access consists of a primary-expression, a predefined-type, or a // qualified-alias-member, followed by a "." token, followed by an identifier, // optionally followed by a type-argument-list. // A member-access is either of the form E.I or of the form E.I<A1, ..., AK>, where // E is a primary-expression, I is a single identifier and <A1, ..., AK> is an // optional type-argument-list. When no type-argument-list is specified, consider K // to be zero. // UNDONE: A member-access with a primary-expression of type dynamic is dynamically bound. // UNDONE: In this case the compiler classifies the member access as a property access of // UNDONE: type dynamic. The rules below to determine the meaning of the member-access are // UNDONE: then applied at run-time, using the run-time type instead of the compile-time // UNDONE: type of the primary-expression. If this run-time classification leads to a method // UNDONE: group, then the member access must be the primary-expression of an invocation-expression. // The member-access is evaluated and classified as follows: var rightName = right.Identifier.ValueText; var rightArity = right.Arity; BoundExpression result; switch (boundLeft.Kind) { case BoundKind.NamespaceExpression: { result = tryBindMemberAccessWithBoundNamespaceLeft(((BoundNamespaceExpression)boundLeft).NamespaceSymbol, node, boundLeft, right, diagnostics, lookupResult, options, typeArgumentsSyntax, typeArguments, rightName, rightArity); if (result is object) { return result; } break; } case BoundKind.TypeExpression: { result = tryBindMemberAccessWithBoundTypeLeft(node, boundLeft, right, invoked, indexed, diagnostics, leftType, lookupResult, options, typeArgumentsSyntax, typeArguments, rightName, rightArity); if (result is object) { return result; } break; } case BoundKind.TypeOrValueExpression: { // CheckValue call will occur in ReplaceTypeOrValueReceiver. // NOTE: This means that we won't get CheckValue diagnostics in error scenarios, // but they would be cascading anyway. return BindInstanceMemberAccess(node, right, boundLeft, rightName, rightArity, typeArgumentsSyntax, typeArguments, invoked, indexed, diagnostics); } default: { // Can't dot into the null literal if (boundLeft.Kind == BoundKind.Literal && ((BoundLiteral)boundLeft).ConstantValueOpt == ConstantValue.Null) { if (!boundLeft.HasAnyErrors) { Error(diagnostics, ErrorCode.ERR_BadUnaryOp, node, operatorToken.Text, boundLeft.Display); } return BadExpression(node, boundLeft); } else if ((object)leftType != null) { // NB: We don't know if we really only need RValue access, or if we are actually // passing the receiver implicitly by ref (e.g. in a struct instance method invocation). // These checks occur later. boundLeft = CheckValue(boundLeft, BindValueKind.RValue, diagnostics); boundLeft = BindToNaturalType(boundLeft, diagnostics); return BindInstanceMemberAccess(node, right, boundLeft, rightName, rightArity, typeArgumentsSyntax, typeArguments, invoked, indexed, diagnostics); } break; } } this.BindMemberAccessReportError(node, right, rightName, boundLeft, lookupResult.Error, diagnostics); return BindMemberAccessBadResult(node, rightName, boundLeft, lookupResult.Error, lookupResult.Symbols.ToImmutable(), lookupResult.Kind); } finally { lookupResult.Free(); } [MethodImpl(MethodImplOptions.NoInlining)] BoundExpression tryBindMemberAccessWithBoundNamespaceLeft( NamespaceSymbol ns, ExpressionSyntax node, BoundExpression boundLeft, SimpleNameSyntax right, BindingDiagnosticBag diagnostics, LookupResult lookupResult, LookupOptions options, SeparatedSyntaxList<TypeSyntax> typeArgumentsSyntax, ImmutableArray<TypeWithAnnotations> typeArguments, string rightName, int rightArity) { // If K is zero and E is a namespace and E contains a nested namespace with name I, // then the result is that namespace. CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); this.LookupMembersWithFallback(lookupResult, ns, rightName, rightArity, ref useSiteInfo, options: options); diagnostics.Add(right, useSiteInfo); ArrayBuilder<Symbol> symbols = lookupResult.Symbols; if (lookupResult.IsMultiViable) { bool wasError; Symbol sym = ResultSymbol(lookupResult, rightName, rightArity, node, diagnostics, false, out wasError, ns, options); if (wasError) { return new BoundBadExpression(node, LookupResultKind.Ambiguous, lookupResult.Symbols.AsImmutable(), ImmutableArray.Create(boundLeft), CreateErrorType(rightName), hasErrors: true); } else if (sym.Kind == SymbolKind.Namespace) { return new BoundNamespaceExpression(node, (NamespaceSymbol)sym); } else { Debug.Assert(sym.Kind == SymbolKind.NamedType); var type = (NamedTypeSymbol)sym; if (!typeArguments.IsDefault) { type = ConstructNamedTypeUnlessTypeArgumentOmitted(right, type, typeArgumentsSyntax, typeArguments, diagnostics); } ReportDiagnosticsIfObsolete(diagnostics, type, node, hasBaseReceiver: false); return new BoundTypeExpression(node, null, type); } } else if (lookupResult.Kind == LookupResultKind.WrongArity) { Debug.Assert(symbols.Count > 0); Debug.Assert(symbols[0].Kind == SymbolKind.NamedType); Error(diagnostics, lookupResult.Error, right); return new BoundTypeExpression(node, null, new ExtendedErrorTypeSymbol(GetContainingNamespaceOrType(symbols[0]), symbols.ToImmutable(), lookupResult.Kind, lookupResult.Error, rightArity)); } else if (lookupResult.Kind == LookupResultKind.Empty) { Debug.Assert(lookupResult.IsClear, "If there's a legitimate reason for having candidates without a reason, then we should produce something intelligent in such cases."); Debug.Assert(lookupResult.Error == null); NotFound(node, rightName, rightArity, rightName, diagnostics, aliasOpt: null, qualifierOpt: ns, options: options); return new BoundBadExpression(node, lookupResult.Kind, symbols.AsImmutable(), ImmutableArray.Create(boundLeft), CreateErrorType(rightName), hasErrors: true); } return null; } [MethodImpl(MethodImplOptions.NoInlining)] BoundExpression tryBindMemberAccessWithBoundTypeLeft( ExpressionSyntax node, BoundExpression boundLeft, SimpleNameSyntax right, bool invoked, bool indexed, BindingDiagnosticBag diagnostics, TypeSymbol leftType, LookupResult lookupResult, LookupOptions options, SeparatedSyntaxList<TypeSyntax> typeArgumentsSyntax, ImmutableArray<TypeWithAnnotations> typeArguments, string rightName, int rightArity) { Debug.Assert((object)leftType != null); if (leftType.TypeKind == TypeKind.TypeParameter) { CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); this.LookupMembersWithFallback(lookupResult, leftType, rightName, rightArity, ref useSiteInfo, basesBeingResolved: null, options: options | LookupOptions.MustNotBeInstance | LookupOptions.MustBeAbstract); diagnostics.Add(right, useSiteInfo); if (lookupResult.IsMultiViable) { CheckFeatureAvailability(boundLeft.Syntax, MessageID.IDS_FeatureStaticAbstractMembersInInterfaces, diagnostics); return BindMemberOfType(node, right, rightName, rightArity, indexed, boundLeft, typeArgumentsSyntax, typeArguments, lookupResult, BoundMethodGroupFlags.None, diagnostics: diagnostics); } else if (lookupResult.IsClear) { Error(diagnostics, ErrorCode.ERR_BadSKunknown, boundLeft.Syntax, leftType, MessageID.IDS_SK_TYVAR.Localize()); return BadExpression(node, LookupResultKind.NotAValue, boundLeft); } } else if (this.EnclosingNameofArgument == node) { // Support selecting an extension method from a type name in nameof(.) return BindInstanceMemberAccess(node, right, boundLeft, rightName, rightArity, typeArgumentsSyntax, typeArguments, invoked, indexed, diagnostics); } else { CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); this.LookupMembersWithFallback(lookupResult, leftType, rightName, rightArity, ref useSiteInfo, basesBeingResolved: null, options: options); diagnostics.Add(right, useSiteInfo); if (lookupResult.IsMultiViable) { return BindMemberOfType(node, right, rightName, rightArity, indexed, boundLeft, typeArgumentsSyntax, typeArguments, lookupResult, BoundMethodGroupFlags.None, diagnostics: diagnostics); } } return null; } } private void WarnOnAccessOfOffDefault(SyntaxNode node, BoundExpression boundLeft, BindingDiagnosticBag diagnostics) { if ((boundLeft is BoundDefaultLiteral || boundLeft is BoundDefaultExpression) && boundLeft.ConstantValue == ConstantValue.Null && Compilation.LanguageVersion < MessageID.IDS_FeatureNullableReferenceTypes.RequiredVersion()) { Error(diagnostics, ErrorCode.WRN_DotOnDefault, node, boundLeft.Type); } } /// <summary> /// Create a value from the expression that can be used as a left-hand-side /// of a member access. This method special-cases method and property /// groups only. All other expressions are returned as is. /// </summary> private BoundExpression MakeMemberAccessValue(BoundExpression expr, BindingDiagnosticBag diagnostics) { switch (expr.Kind) { case BoundKind.MethodGroup: { var methodGroup = (BoundMethodGroup)expr; CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); var resolution = this.ResolveMethodGroup(methodGroup, analyzedArguments: null, isMethodGroupConversion: false, useSiteInfo: ref useSiteInfo); diagnostics.Add(expr.Syntax, useSiteInfo); if (!expr.HasAnyErrors) { diagnostics.AddRange(resolution.Diagnostics); if (resolution.MethodGroup != null && !resolution.HasAnyErrors) { Debug.Assert(!resolution.IsEmpty); var method = resolution.MethodGroup.Methods[0]; Error(diagnostics, ErrorCode.ERR_BadSKunknown, methodGroup.NameSyntax, method, MessageID.IDS_SK_METHOD.Localize()); } } expr = this.BindMemberAccessBadResult(methodGroup); resolution.Free(); return expr; } case BoundKind.PropertyGroup: return BindIndexedPropertyAccess((BoundPropertyGroup)expr, mustHaveAllOptionalParameters: false, diagnostics: diagnostics); default: return BindToNaturalType(expr, diagnostics); } } private BoundExpression BindInstanceMemberAccess( SyntaxNode node, SyntaxNode right, BoundExpression boundLeft, string rightName, int rightArity, SeparatedSyntaxList<TypeSyntax> typeArgumentsSyntax, ImmutableArray<TypeWithAnnotations> typeArgumentsWithAnnotations, bool invoked, bool indexed, BindingDiagnosticBag diagnostics, bool searchExtensionMethodsIfNecessary = true) { Debug.Assert(rightArity == (typeArgumentsWithAnnotations.IsDefault ? 0 : typeArgumentsWithAnnotations.Length)); var leftType = boundLeft.Type; LookupOptions options = LookupOptions.AllMethodsOnArityZero; if (invoked) { options |= LookupOptions.MustBeInvocableIfMember; } var lookupResult = LookupResult.GetInstance(); try { // If E is a property access, indexer access, variable, or value, the type of // which is T, and a member lookup of I in T with K type arguments produces a // match, then E.I is evaluated and classified as follows: // UNDONE: Classify E as prop access, indexer access, variable or value bool leftIsBaseReference = boundLeft.Kind == BoundKind.BaseReference; if (leftIsBaseReference) { options |= LookupOptions.UseBaseReferenceAccessibility; } CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); this.LookupMembersWithFallback(lookupResult, leftType, rightName, rightArity, ref useSiteInfo, basesBeingResolved: null, options: options); diagnostics.Add(right, useSiteInfo); // SPEC: Otherwise, an attempt is made to process E.I as an extension method invocation. // SPEC: If this fails, E.I is an invalid member reference, and a binding-time error occurs. searchExtensionMethodsIfNecessary = searchExtensionMethodsIfNecessary && !leftIsBaseReference; BoundMethodGroupFlags flags = 0; if (searchExtensionMethodsIfNecessary) { flags |= BoundMethodGroupFlags.SearchExtensionMethods; } if (lookupResult.IsMultiViable) { return BindMemberOfType(node, right, rightName, rightArity, indexed, boundLeft, typeArgumentsSyntax, typeArgumentsWithAnnotations, lookupResult, flags, diagnostics); } if (searchExtensionMethodsIfNecessary) { var boundMethodGroup = new BoundMethodGroup( node, typeArgumentsWithAnnotations, boundLeft, rightName, lookupResult.Symbols.All(s => s.Kind == SymbolKind.Method) ? lookupResult.Symbols.SelectAsArray(s_toMethodSymbolFunc) : ImmutableArray<MethodSymbol>.Empty, lookupResult, flags); if (!boundMethodGroup.HasErrors && typeArgumentsSyntax.Any(SyntaxKind.OmittedTypeArgument)) { Error(diagnostics, ErrorCode.ERR_OmittedTypeArgument, node); } return boundMethodGroup; } this.BindMemberAccessReportError(node, right, rightName, boundLeft, lookupResult.Error, diagnostics); return BindMemberAccessBadResult(node, rightName, boundLeft, lookupResult.Error, lookupResult.Symbols.ToImmutable(), lookupResult.Kind); } finally { lookupResult.Free(); } } private void BindMemberAccessReportError(BoundMethodGroup node, BindingDiagnosticBag diagnostics) { var nameSyntax = node.NameSyntax; var syntax = node.MemberAccessExpressionSyntax ?? nameSyntax; this.BindMemberAccessReportError(syntax, nameSyntax, node.Name, node.ReceiverOpt, node.LookupError, diagnostics); } /// <summary> /// Report the error from member access lookup. Or, if there /// was no explicit error from lookup, report "no such member". /// </summary> private void BindMemberAccessReportError( SyntaxNode node, SyntaxNode name, string plainName, BoundExpression boundLeft, DiagnosticInfo lookupError, BindingDiagnosticBag diagnostics) { if (boundLeft.HasAnyErrors && boundLeft.Kind != BoundKind.TypeOrValueExpression) { return; } if (lookupError != null) { // CONSIDER: there are some cases where Dev10 uses the span of "node", // rather than "right". diagnostics.Add(new CSDiagnostic(lookupError, name.Location)); } else if (node.IsQuery()) { ReportQueryLookupFailed(node, boundLeft, plainName, ImmutableArray<Symbol>.Empty, diagnostics); } else { if ((object)boundLeft.Type == null) { Error(diagnostics, ErrorCode.ERR_NoSuchMember, name, boundLeft.Display, plainName); } else if (boundLeft.Kind == BoundKind.TypeExpression || boundLeft.Kind == BoundKind.BaseReference || node.Kind() == SyntaxKind.AwaitExpression && plainName == WellKnownMemberNames.GetResult) { Error(diagnostics, ErrorCode.ERR_NoSuchMember, name, boundLeft.Type, plainName); } else if (WouldUsingSystemFindExtension(boundLeft.Type, plainName)) { Error(diagnostics, ErrorCode.ERR_NoSuchMemberOrExtensionNeedUsing, name, boundLeft.Type, plainName, "System"); } else { Error(diagnostics, ErrorCode.ERR_NoSuchMemberOrExtension, name, boundLeft.Type, plainName); } } } private bool WouldUsingSystemFindExtension(TypeSymbol receiver, string methodName) { // we have a special case to make the diagnostic for await expressions more clear for Windows: // if the receiver type is a windows RT async interface and the method name is GetAwaiter, // then we would suggest a using directive for "System". // TODO: we should check if such a using directive would actually help, or if there is already one in scope. return methodName == WellKnownMemberNames.GetAwaiter && ImplementsWinRTAsyncInterface(receiver); } /// <summary> /// Return true if the given type is or implements a WinRTAsyncInterface. /// </summary> private bool ImplementsWinRTAsyncInterface(TypeSymbol type) { return IsWinRTAsyncInterface(type) || type.AllInterfacesNoUseSiteDiagnostics.Any(i => IsWinRTAsyncInterface(i)); } private bool IsWinRTAsyncInterface(TypeSymbol type) { if (!type.IsInterfaceType()) { return false; } var namedType = ((NamedTypeSymbol)type).ConstructedFrom; return TypeSymbol.Equals(namedType, Compilation.GetWellKnownType(WellKnownType.Windows_Foundation_IAsyncAction), TypeCompareKind.ConsiderEverything2) || TypeSymbol.Equals(namedType, Compilation.GetWellKnownType(WellKnownType.Windows_Foundation_IAsyncActionWithProgress_T), TypeCompareKind.ConsiderEverything2) || TypeSymbol.Equals(namedType, Compilation.GetWellKnownType(WellKnownType.Windows_Foundation_IAsyncOperation_T), TypeCompareKind.ConsiderEverything2) || TypeSymbol.Equals(namedType, Compilation.GetWellKnownType(WellKnownType.Windows_Foundation_IAsyncOperationWithProgress_T2), TypeCompareKind.ConsiderEverything2); } private BoundExpression BindMemberAccessBadResult(BoundMethodGroup node) { var nameSyntax = node.NameSyntax; var syntax = node.MemberAccessExpressionSyntax ?? nameSyntax; return this.BindMemberAccessBadResult(syntax, node.Name, node.ReceiverOpt, node.LookupError, StaticCast<Symbol>.From(node.Methods), node.ResultKind); } /// <summary> /// Return a BoundExpression representing the invalid member. /// </summary> private BoundExpression BindMemberAccessBadResult( SyntaxNode node, string nameString, BoundExpression boundLeft, DiagnosticInfo lookupError, ImmutableArray<Symbol> symbols, LookupResultKind lookupKind) { if (symbols.Length > 0 && symbols[0].Kind == SymbolKind.Method) { var builder = ArrayBuilder<MethodSymbol>.GetInstance(); foreach (var s in symbols) { var m = s as MethodSymbol; if ((object)m != null) builder.Add(m); } var methods = builder.ToImmutableAndFree(); // Expose the invalid methods as a BoundMethodGroup. // Since we do not want to perform further method // lookup, searchExtensionMethods is set to false. // Don't bother calling ConstructBoundMethodGroupAndReportOmittedTypeArguments - // we've reported other errors. return new BoundMethodGroup( node, default(ImmutableArray<TypeWithAnnotations>), nameString, methods, methods.Length == 1 ? methods[0] : null, lookupError, flags: BoundMethodGroupFlags.None, receiverOpt: boundLeft, resultKind: lookupKind, hasErrors: true); } var symbolOpt = symbols.Length == 1 ? symbols[0] : null; return new BoundBadExpression( node, lookupKind, (object)symbolOpt == null ? ImmutableArray<Symbol>.Empty : ImmutableArray.Create(symbolOpt), boundLeft == null ? ImmutableArray<BoundExpression>.Empty : ImmutableArray.Create(BindToTypeForErrorRecovery(boundLeft)), GetNonMethodMemberType(symbolOpt)); } private TypeSymbol GetNonMethodMemberType(Symbol symbolOpt) { TypeSymbol resultType = null; if ((object)symbolOpt != null) { switch (symbolOpt.Kind) { case SymbolKind.Field: resultType = ((FieldSymbol)symbolOpt).GetFieldType(this.FieldsBeingBound).Type; break; case SymbolKind.Property: resultType = ((PropertySymbol)symbolOpt).Type; break; case SymbolKind.Event: resultType = ((EventSymbol)symbolOpt).Type; break; } } return resultType ?? CreateErrorType(); } /// <summary> /// Combine the receiver and arguments of an extension method /// invocation into a single argument list to allow overload resolution /// to treat the invocation as a static method invocation with no receiver. /// </summary> private static void CombineExtensionMethodArguments(BoundExpression receiver, AnalyzedArguments originalArguments, AnalyzedArguments extensionMethodArguments) { Debug.Assert(receiver != null); Debug.Assert(extensionMethodArguments.Arguments.Count == 0); Debug.Assert(extensionMethodArguments.Names.Count == 0); Debug.Assert(extensionMethodArguments.RefKinds.Count == 0); extensionMethodArguments.IsExtensionMethodInvocation = true; extensionMethodArguments.Arguments.Add(receiver); extensionMethodArguments.Arguments.AddRange(originalArguments.Arguments); if (originalArguments.Names.Count > 0) { extensionMethodArguments.Names.Add(null); extensionMethodArguments.Names.AddRange(originalArguments.Names); } if (originalArguments.RefKinds.Count > 0) { extensionMethodArguments.RefKinds.Add(RefKind.None); extensionMethodArguments.RefKinds.AddRange(originalArguments.RefKinds); } } /// <summary> /// Binds a static or instance member access. /// </summary> private BoundExpression BindMemberOfType( SyntaxNode node, SyntaxNode right, string plainName, int arity, bool indexed, BoundExpression left, SeparatedSyntaxList<TypeSyntax> typeArgumentsSyntax, ImmutableArray<TypeWithAnnotations> typeArgumentsWithAnnotations, LookupResult lookupResult, BoundMethodGroupFlags methodGroupFlags, BindingDiagnosticBag diagnostics) { Debug.Assert(node != null); Debug.Assert(left != null); Debug.Assert(lookupResult.IsMultiViable); Debug.Assert(lookupResult.Symbols.Any()); var members = ArrayBuilder<Symbol>.GetInstance(); BoundExpression result; bool wasError; Symbol symbol = GetSymbolOrMethodOrPropertyGroup(lookupResult, right, plainName, arity, members, diagnostics, out wasError, qualifierOpt: left is BoundTypeExpression typeExpr ? typeExpr.Type : null); if ((object)symbol == null) { Debug.Assert(members.Count > 0); // If I identifies one or more methods, then the result is a method group with // no associated instance expression. If a type argument list was specified, it // is used in calling a generic method. // (Note that for static methods, we are stashing away the type expression in // the receiver of the method group, even though the spec notes that there is // no associated instance expression.) result = ConstructBoundMemberGroupAndReportOmittedTypeArguments( node, typeArgumentsSyntax, typeArgumentsWithAnnotations, left, plainName, members, lookupResult, methodGroupFlags, wasError, diagnostics); } else { // methods are special because of extension methods. Debug.Assert(symbol.Kind != SymbolKind.Method); left = ReplaceTypeOrValueReceiver(left, symbol.IsStatic || symbol.Kind == SymbolKind.NamedType, diagnostics); // Events are handled later as we don't know yet if we are binding to the event or it's backing field. if (symbol.Kind != SymbolKind.Event) { ReportDiagnosticsIfObsolete(diagnostics, symbol, node, hasBaseReceiver: left.Kind == BoundKind.BaseReference); } switch (symbol.Kind) { case SymbolKind.NamedType: case SymbolKind.ErrorType: if (IsInstanceReceiver(left) == true && !wasError) { // CS0572: 'B': cannot reference a type through an expression; try 'A.B' instead Error(diagnostics, ErrorCode.ERR_BadTypeReference, right, plainName, symbol); wasError = true; } // If I identifies a type, then the result is that type constructed with // the given type arguments. var type = (NamedTypeSymbol)symbol; if (!typeArgumentsWithAnnotations.IsDefault) { type = ConstructNamedTypeUnlessTypeArgumentOmitted(right, type, typeArgumentsSyntax, typeArgumentsWithAnnotations, diagnostics); } result = new BoundTypeExpression( syntax: node, aliasOpt: null, boundContainingTypeOpt: left as BoundTypeExpression, boundDimensionsOpt: ImmutableArray<BoundExpression>.Empty, typeWithAnnotations: TypeWithAnnotations.Create(type)); break; case SymbolKind.Property: // If I identifies a static property, then the result is a property // access with no associated instance expression. result = BindPropertyAccess(node, left, (PropertySymbol)symbol, diagnostics, lookupResult.Kind, hasErrors: wasError); break; case SymbolKind.Event: // If I identifies a static event, then the result is an event // access with no associated instance expression. result = BindEventAccess(node, left, (EventSymbol)symbol, diagnostics, lookupResult.Kind, hasErrors: wasError); break; case SymbolKind.Field: // If I identifies a static field: // UNDONE: If the field is readonly and the reference occurs outside the static constructor of // UNDONE: the class or struct in which the field is declared, then the result is a value, namely // UNDONE: the value of the static field I in E. // UNDONE: Otherwise, the result is a variable, namely the static field I in E. // UNDONE: Need a way to mark an expression node as "I am a variable, not a value". result = BindFieldAccess(node, left, (FieldSymbol)symbol, diagnostics, lookupResult.Kind, indexed, hasErrors: wasError); break; default: throw ExceptionUtilities.UnexpectedValue(symbol.Kind); } } members.Free(); return result; } protected MethodGroupResolution BindExtensionMethod( SyntaxNode expression, string methodName, AnalyzedArguments analyzedArguments, BoundExpression left, ImmutableArray<TypeWithAnnotations> typeArgumentsWithAnnotations, bool isMethodGroupConversion, RefKind returnRefKind, TypeSymbol returnType, bool withDependencies) { var firstResult = new MethodGroupResolution(); AnalyzedArguments actualArguments = null; foreach (var scope in new ExtensionMethodScopes(this)) { var methodGroup = MethodGroup.GetInstance(); var diagnostics = BindingDiagnosticBag.GetInstance(withDiagnostics: true, withDependencies); this.PopulateExtensionMethodsFromSingleBinder(scope, methodGroup, expression, left, methodName, typeArgumentsWithAnnotations, diagnostics); // analyzedArguments will be null if the caller is resolving for error recovery to the first method group // that can accept that receiver, regardless of arguments, when the signature cannot be inferred. // (In the error case of nameof(o.M) or the error case of o.M = null; for instance.) if (analyzedArguments == null) { if (expression == EnclosingNameofArgument) { for (int i = methodGroup.Methods.Count - 1; i >= 0; i--) { if ((object)methodGroup.Methods[i].ReduceExtensionMethod(left.Type, this.Compilation) == null) methodGroup.Methods.RemoveAt(i); } } if (methodGroup.Methods.Count != 0) { return new MethodGroupResolution(methodGroup, diagnostics.ToReadOnlyAndFree()); } } if (methodGroup.Methods.Count == 0) { methodGroup.Free(); diagnostics.Free(); continue; } if (actualArguments == null) { // Create a set of arguments for overload resolution of the // extension methods that includes the "this" parameter. actualArguments = AnalyzedArguments.GetInstance(); CombineExtensionMethodArguments(left, analyzedArguments, actualArguments); } var overloadResolutionResult = OverloadResolutionResult<MethodSymbol>.GetInstance(); bool allowRefOmittedArguments = methodGroup.Receiver.IsExpressionOfComImportType(); CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); OverloadResolution.MethodInvocationOverloadResolution( methods: methodGroup.Methods, typeArguments: methodGroup.TypeArguments, receiver: methodGroup.Receiver, arguments: actualArguments, result: overloadResolutionResult, useSiteInfo: ref useSiteInfo, isMethodGroupConversion: isMethodGroupConversion, allowRefOmittedArguments: allowRefOmittedArguments, returnRefKind: returnRefKind, returnType: returnType); diagnostics.Add(expression, useSiteInfo); var sealedDiagnostics = diagnostics.ToReadOnlyAndFree(); // Note: the MethodGroupResolution instance is responsible for freeing its copy of actual arguments var result = new MethodGroupResolution(methodGroup, null, overloadResolutionResult, AnalyzedArguments.GetInstance(actualArguments), methodGroup.ResultKind, sealedDiagnostics); // If the search in the current scope resulted in any applicable method (regardless of whether a best // applicable method could be determined) then our search is complete. Otherwise, store aside the // first non-applicable result and continue searching for an applicable result. if (result.HasAnyApplicableMethod) { if (!firstResult.IsEmpty) { firstResult.MethodGroup.Free(); firstResult.OverloadResolutionResult.Free(); } return result; } else if (firstResult.IsEmpty) { firstResult = result; } else { // Neither the first result, nor applicable. No need to save result. overloadResolutionResult.Free(); methodGroup.Free(); } } Debug.Assert((actualArguments == null) || !firstResult.IsEmpty); actualArguments?.Free(); return firstResult; } private void PopulateExtensionMethodsFromSingleBinder( ExtensionMethodScope scope, MethodGroup methodGroup, SyntaxNode node, BoundExpression left, string rightName, ImmutableArray<TypeWithAnnotations> typeArgumentsWithAnnotations, BindingDiagnosticBag diagnostics) { int arity; LookupOptions options; if (typeArgumentsWithAnnotations.IsDefault) { arity = 0; options = LookupOptions.AllMethodsOnArityZero; } else { arity = typeArgumentsWithAnnotations.Length; options = LookupOptions.Default; } var lookupResult = LookupResult.GetInstance(); CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); this.LookupExtensionMethodsInSingleBinder(scope, lookupResult, rightName, arity, options, ref useSiteInfo); diagnostics.Add(node, useSiteInfo); if (lookupResult.IsMultiViable) { Debug.Assert(lookupResult.Symbols.Any()); var members = ArrayBuilder<Symbol>.GetInstance(); bool wasError; Symbol symbol = GetSymbolOrMethodOrPropertyGroup(lookupResult, node, rightName, arity, members, diagnostics, out wasError, qualifierOpt: null); Debug.Assert((object)symbol == null); Debug.Assert(members.Count > 0); methodGroup.PopulateWithExtensionMethods(left, members, typeArgumentsWithAnnotations, lookupResult.Kind); members.Free(); } lookupResult.Free(); } protected BoundExpression BindFieldAccess( SyntaxNode node, BoundExpression receiver, FieldSymbol fieldSymbol, BindingDiagnosticBag diagnostics, LookupResultKind resultKind, bool indexed, bool hasErrors) { bool hasError = false; NamedTypeSymbol type = fieldSymbol.ContainingType; var isEnumField = (fieldSymbol.IsStatic && type.IsEnumType()); if (isEnumField && !type.IsValidEnumType()) { Error(diagnostics, ErrorCode.ERR_BindToBogus, node, fieldSymbol); hasError = true; } if (!hasError) { hasError = this.CheckInstanceOrStatic(node, receiver, fieldSymbol, ref resultKind, diagnostics); } if (!hasError && fieldSymbol.IsFixedSizeBuffer && !IsInsideNameof) { // SPEC: In a member access of the form E.I, if E is of a struct type and a member lookup of I in // that struct type identifies a fixed size member, then E.I is evaluated and classified as follows: // * If the expression E.I does not occur in an unsafe context, a compile-time error occurs. // * If E is classified as a value, a compile-time error occurs. // * Otherwise, if E is a moveable variable and the expression E.I is not a fixed_pointer_initializer, // a compile-time error occurs. // * Otherwise, E references a fixed variable and the result of the expression is a pointer to the // first element of the fixed size buffer member I in E. The result is of type S*, where S is // the element type of I, and is classified as a value. TypeSymbol receiverType = receiver.Type; // Reflect errors that have been reported elsewhere... hasError = (object)receiverType == null || !receiverType.IsValueType; if (!hasError) { var isFixedStatementExpression = SyntaxFacts.IsFixedStatementExpression(node); if (IsMoveableVariable(receiver, out Symbol accessedLocalOrParameterOpt) != isFixedStatementExpression) { if (indexed) { // SPEC C# 7.3: If the fixed size buffer access is the receiver of an element_access_expression, // E may be either fixed or moveable CheckFeatureAvailability(node, MessageID.IDS_FeatureIndexingMovableFixedBuffers, diagnostics); } else { Error(diagnostics, isFixedStatementExpression ? ErrorCode.ERR_FixedNotNeeded : ErrorCode.ERR_FixedBufferNotFixed, node); hasErrors = hasError = true; } } } if (!hasError) { hasError = !CheckValueKind(node, receiver, BindValueKind.FixedReceiver, checkingReceiver: false, diagnostics: diagnostics); } } ConstantValue constantValueOpt = null; if (fieldSymbol.IsConst && !IsInsideNameof) { constantValueOpt = fieldSymbol.GetConstantValue(this.ConstantFieldsInProgress, this.IsEarlyAttributeBinder); if (constantValueOpt == ConstantValue.Unset) { // Evaluating constant expression before dependencies // have been evaluated. Treat this as a Bad value. constantValueOpt = ConstantValue.Bad; } } if (!fieldSymbol.IsStatic) { WarnOnAccessOfOffDefault(node, receiver, diagnostics); } if (!IsBadBaseAccess(node, receiver, fieldSymbol, diagnostics)) { CheckReceiverAndRuntimeSupportForSymbolAccess(node, receiver, fieldSymbol, diagnostics); } TypeSymbol fieldType = fieldSymbol.GetFieldType(this.FieldsBeingBound).Type; BoundExpression expr = new BoundFieldAccess(node, receiver, fieldSymbol, constantValueOpt, resultKind, fieldType, hasErrors: (hasErrors || hasError)); // Spec 14.3: "Within an enum member initializer, values of other enum members are // always treated as having the type of their underlying type" if (this.InEnumMemberInitializer()) { NamedTypeSymbol enumType = null; if (isEnumField) { // This is an obvious consequence of the spec. // It is for cases like: // enum E { // A, // B = A + 1, //A is implicitly converted to int (underlying type) // } enumType = type; } else if (constantValueOpt != null && fieldType.IsEnumType()) { // This seems like a borderline SPEC VIOLATION that we're preserving for back compat. // It is for cases like: // const E e = E.A; // enum E { // A, // B = e + 1, //e is implicitly converted to int (underlying type) // } enumType = (NamedTypeSymbol)fieldType; } if ((object)enumType != null) { NamedTypeSymbol underlyingType = enumType.EnumUnderlyingType; Debug.Assert((object)underlyingType != null); expr = new BoundConversion( node, expr, Conversion.ImplicitNumeric, @checked: true, explicitCastInCode: false, conversionGroupOpt: null, constantValueOpt: expr.ConstantValue, type: underlyingType); } } return expr; } private bool InEnumMemberInitializer() { var containingType = this.ContainingType; return this.InFieldInitializer && (object)containingType != null && containingType.IsEnumType(); } private BoundExpression BindPropertyAccess( SyntaxNode node, BoundExpression receiver, PropertySymbol propertySymbol, BindingDiagnosticBag diagnostics, LookupResultKind lookupResult, bool hasErrors) { bool hasError = this.CheckInstanceOrStatic(node, receiver, propertySymbol, ref lookupResult, diagnostics); if (!propertySymbol.IsStatic) { WarnOnAccessOfOffDefault(node, receiver, diagnostics); } return new BoundPropertyAccess(node, receiver, propertySymbol, lookupResult, propertySymbol.Type, hasErrors: (hasErrors || hasError)); } private void CheckReceiverAndRuntimeSupportForSymbolAccess(SyntaxNode node, BoundExpression receiverOpt, Symbol symbol, BindingDiagnosticBag diagnostics) { if (symbol.ContainingType?.IsInterface == true) { if (symbol.IsStatic && symbol.IsAbstract) { Debug.Assert(symbol is not TypeSymbol); if (receiverOpt is BoundQueryClause { Value: var value }) { receiverOpt = value; } if (receiverOpt is not BoundTypeExpression { Type: { TypeKind: TypeKind.TypeParameter } }) { Error(diagnostics, ErrorCode.ERR_BadAbstractStaticMemberAccess, node); return; } if (!Compilation.Assembly.RuntimeSupportsStaticAbstractMembersInInterfaces && Compilation.SourceModule != symbol.ContainingModule) { Error(diagnostics, ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, node); return; } } if (!Compilation.Assembly.RuntimeSupportsDefaultInterfaceImplementation && Compilation.SourceModule != symbol.ContainingModule) { if (!symbol.IsStatic && !(symbol is TypeSymbol) && !symbol.IsImplementableInterfaceMember()) { Error(diagnostics, ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, node); } else { switch (symbol.DeclaredAccessibility) { case Accessibility.Protected: case Accessibility.ProtectedOrInternal: case Accessibility.ProtectedAndInternal: Error(diagnostics, ErrorCode.ERR_RuntimeDoesNotSupportProtectedAccessForInterfaceMember, node); break; } } } } } private BoundExpression BindEventAccess( SyntaxNode node, BoundExpression receiver, EventSymbol eventSymbol, BindingDiagnosticBag diagnostics, LookupResultKind lookupResult, bool hasErrors) { CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); bool isUsableAsField = eventSymbol.HasAssociatedField && this.IsAccessible(eventSymbol.AssociatedField, ref useSiteInfo, (receiver != null) ? receiver.Type : null); diagnostics.Add(node, useSiteInfo); bool hasError = this.CheckInstanceOrStatic(node, receiver, eventSymbol, ref lookupResult, diagnostics); if (!eventSymbol.IsStatic) { WarnOnAccessOfOffDefault(node, receiver, diagnostics); } return new BoundEventAccess(node, receiver, eventSymbol, isUsableAsField, lookupResult, eventSymbol.Type, hasErrors: (hasErrors || hasError)); } // Say if the receive is an instance or a type, or could be either (returns null). private static bool? IsInstanceReceiver(BoundExpression receiver) { if (receiver == null) { return false; } else { switch (receiver.Kind) { case BoundKind.PreviousSubmissionReference: // Could be either instance or static reference. return null; case BoundKind.TypeExpression: return false; case BoundKind.QueryClause: return IsInstanceReceiver(((BoundQueryClause)receiver).Value); default: return true; } } } private bool CheckInstanceOrStatic( SyntaxNode node, BoundExpression receiver, Symbol symbol, ref LookupResultKind resultKind, BindingDiagnosticBag diagnostics) { bool? instanceReceiver = IsInstanceReceiver(receiver); if (!symbol.RequiresInstanceReceiver()) { if (instanceReceiver == true) { ErrorCode errorCode = this.Flags.Includes(BinderFlags.ObjectInitializerMember) ? ErrorCode.ERR_StaticMemberInObjectInitializer : ErrorCode.ERR_ObjectProhibited; Error(diagnostics, errorCode, node, symbol); resultKind = LookupResultKind.StaticInstanceMismatch; return true; } } else { if (instanceReceiver == false && !IsInsideNameof) { Error(diagnostics, ErrorCode.ERR_ObjectRequired, node, symbol); resultKind = LookupResultKind.StaticInstanceMismatch; return true; } } return false; } /// <summary> /// Given a viable LookupResult, report any ambiguity errors and return either a single /// non-method symbol or a method or property group. If the result set represents a /// collection of methods or a collection of properties where at least one of the properties /// is an indexed property, then 'methodOrPropertyGroup' is populated with the method or /// property group and the method returns null. Otherwise, the method returns a single /// symbol and 'methodOrPropertyGroup' is empty. (Since the result set is viable, there /// must be at least one symbol.) If the result set is ambiguous - either containing multiple /// members of different member types, or multiple properties but no indexed properties - /// then a diagnostic is reported for the ambiguity and a single symbol is returned. /// </summary> private Symbol GetSymbolOrMethodOrPropertyGroup(LookupResult result, SyntaxNode node, string plainName, int arity, ArrayBuilder<Symbol> methodOrPropertyGroup, BindingDiagnosticBag diagnostics, out bool wasError, NamespaceOrTypeSymbol qualifierOpt) { Debug.Assert(!methodOrPropertyGroup.Any()); node = GetNameSyntax(node) ?? node; wasError = false; Debug.Assert(result.Kind != LookupResultKind.Empty); Debug.Assert(!result.Symbols.Any(s => s.IsIndexer())); Symbol other = null; // different member type from 'methodOrPropertyGroup' // Populate 'methodOrPropertyGroup' with a set of methods if any, // or a set of properties if properties but no methods. If there are // other member types, 'other' will be set to one of those members. foreach (var symbol in result.Symbols) { var kind = symbol.Kind; if (methodOrPropertyGroup.Count > 0) { var existingKind = methodOrPropertyGroup[0].Kind; if (existingKind != kind) { // Mix of different member kinds. Prefer methods over // properties and properties over other members. if ((existingKind == SymbolKind.Method) || ((existingKind == SymbolKind.Property) && (kind != SymbolKind.Method))) { other = symbol; continue; } other = methodOrPropertyGroup[0]; methodOrPropertyGroup.Clear(); } } if ((kind == SymbolKind.Method) || (kind == SymbolKind.Property)) { // SPEC VIOLATION: The spec states "Members that include an override modifier are excluded from the set" // SPEC VIOLATION: However, we are not going to do that here; we will keep the overriding member // SPEC VIOLATION: in the method group. The reason is because for features like "go to definition" // SPEC VIOLATION: we wish to go to the overriding member, not to the member of the base class. // SPEC VIOLATION: Or, for code generation of a call to Int32.ToString() we want to generate // SPEC VIOLATION: code that directly calls the Int32.ToString method with an int on the stack, // SPEC VIOLATION: rather than making a virtual call to ToString on a boxed int. methodOrPropertyGroup.Add(symbol); } else { other = symbol; } } Debug.Assert(methodOrPropertyGroup.Any() || ((object)other != null)); if ((methodOrPropertyGroup.Count > 0) && IsMethodOrPropertyGroup(methodOrPropertyGroup)) { // Ambiguities between methods and non-methods are reported here, // but all other ambiguities, including those between properties and // non-methods, are reported in ResultSymbol. if ((methodOrPropertyGroup[0].Kind == SymbolKind.Method) || ((object)other == null)) { // Result will be treated as a method or property group. Any additional // checks, such as use-site errors, must be handled by the caller when // converting to method invocation or property access. if (result.Error != null) { Error(diagnostics, result.Error, node); wasError = (result.Error.Severity == DiagnosticSeverity.Error); } return null; } } methodOrPropertyGroup.Clear(); return ResultSymbol(result, plainName, arity, node, diagnostics, false, out wasError, qualifierOpt); } private static bool IsMethodOrPropertyGroup(ArrayBuilder<Symbol> members) { Debug.Assert(members.Count > 0); var member = members[0]; // Members should be a consistent type. Debug.Assert(members.All(m => m.Kind == member.Kind)); switch (member.Kind) { case SymbolKind.Method: return true; case SymbolKind.Property: Debug.Assert(members.All(m => !m.IsIndexer())); // Do not treat a set of non-indexed properties as a property group, to // avoid the overhead of a BoundPropertyGroup node and overload // resolution for the common property access case. If there are multiple // non-indexed properties (two properties P that differ by custom attributes // for instance), the expectation is that the caller will report an ambiguity // and choose one for error recovery. foreach (PropertySymbol property in members) { if (property.IsIndexedProperty) { return true; } } return false; default: throw ExceptionUtilities.UnexpectedValue(member.Kind); } } private BoundExpression BindElementAccess(ElementAccessExpressionSyntax node, BindingDiagnosticBag diagnostics) { BoundExpression receiver = BindExpression(node.Expression, diagnostics: diagnostics, invoked: false, indexed: true); return BindElementAccess(node, receiver, node.ArgumentList, diagnostics); } private BoundExpression BindElementAccess(ExpressionSyntax node, BoundExpression receiver, BracketedArgumentListSyntax argumentList, BindingDiagnosticBag diagnostics) { AnalyzedArguments analyzedArguments = AnalyzedArguments.GetInstance(); try { BindArgumentsAndNames(argumentList, diagnostics, analyzedArguments); if (receiver.Kind == BoundKind.PropertyGroup) { var propertyGroup = (BoundPropertyGroup)receiver; return BindIndexedPropertyAccess(node, propertyGroup.ReceiverOpt, propertyGroup.Properties, analyzedArguments, diagnostics); } receiver = CheckValue(receiver, BindValueKind.RValue, diagnostics); receiver = BindToNaturalType(receiver, diagnostics); return BindElementOrIndexerAccess(node, receiver, analyzedArguments, diagnostics); } finally { analyzedArguments.Free(); } } private BoundExpression BindElementOrIndexerAccess(ExpressionSyntax node, BoundExpression expr, AnalyzedArguments analyzedArguments, BindingDiagnosticBag diagnostics) { if ((object)expr.Type == null) { return BadIndexerExpression(node, expr, analyzedArguments, null, diagnostics); } WarnOnAccessOfOffDefault(node, expr, diagnostics); // Did we have any errors? if (analyzedArguments.HasErrors || expr.HasAnyErrors) { // At this point we definitely have reported an error, but we still might be // able to get more semantic analysis of the indexing operation. We do not // want to report cascading errors. BoundExpression result = BindElementAccessCore(node, expr, analyzedArguments, BindingDiagnosticBag.Discarded); return result; } return BindElementAccessCore(node, expr, analyzedArguments, diagnostics); } private BoundExpression BadIndexerExpression(ExpressionSyntax node, BoundExpression expr, AnalyzedArguments analyzedArguments, DiagnosticInfo errorOpt, BindingDiagnosticBag diagnostics) { if (!expr.HasAnyErrors) { diagnostics.Add(errorOpt ?? new CSDiagnosticInfo(ErrorCode.ERR_BadIndexLHS, expr.Display), node.Location); } var childBoundNodes = BuildArgumentsForErrorRecovery(analyzedArguments).Add(expr); return new BoundBadExpression(node, LookupResultKind.Empty, ImmutableArray<Symbol>.Empty, childBoundNodes, CreateErrorType(), hasErrors: true); } private BoundExpression BindElementAccessCore( ExpressionSyntax node, BoundExpression expr, AnalyzedArguments arguments, BindingDiagnosticBag diagnostics) { Debug.Assert(node != null); Debug.Assert(expr != null); Debug.Assert((object)expr.Type != null); Debug.Assert(arguments != null); var exprType = expr.Type; switch (exprType.TypeKind) { case TypeKind.Array: return BindArrayAccess(node, expr, arguments, diagnostics); case TypeKind.Dynamic: return BindDynamicIndexer(node, expr, arguments, ImmutableArray<PropertySymbol>.Empty, diagnostics); case TypeKind.Pointer: return BindPointerElementAccess(node, expr, arguments, diagnostics); case TypeKind.Class: case TypeKind.Struct: case TypeKind.Interface: case TypeKind.TypeParameter: return BindIndexerAccess(node, expr, arguments, diagnostics); case TypeKind.Submission: // script class is synthesized and should not be used as a type of an indexer expression: default: return BadIndexerExpression(node, expr, arguments, null, diagnostics); } } private BoundExpression BindArrayAccess(ExpressionSyntax node, BoundExpression expr, AnalyzedArguments arguments, BindingDiagnosticBag diagnostics) { Debug.Assert(node != null); Debug.Assert(expr != null); Debug.Assert(arguments != null); // For an array access, the primary-no-array-creation-expression of the element-access // must be a value of an array-type. Furthermore, the argument-list of an array access // is not allowed to contain named arguments.The number of expressions in the // argument-list must be the same as the rank of the array-type, and each expression // must be of type int, uint, long, ulong, or must be implicitly convertible to one or // more of these types. if (arguments.Names.Count > 0) { Error(diagnostics, ErrorCode.ERR_NamedArgumentForArray, node); } bool hasErrors = ReportRefOrOutArgument(arguments, diagnostics); var arrayType = (ArrayTypeSymbol)expr.Type; // Note that the spec says to determine which of {int, uint, long, ulong} *each* index // expression is convertible to. That is not what C# 1 through 4 did; the // implementations instead determined which of those four types *all* of the index // expressions converted to. int rank = arrayType.Rank; if (arguments.Arguments.Count != rank) { Error(diagnostics, ErrorCode.ERR_BadIndexCount, node, rank); return new BoundArrayAccess(node, expr, BuildArgumentsForErrorRecovery(arguments), arrayType.ElementType, hasErrors: true); } // Convert all the arguments to the array index type. BoundExpression[] convertedArguments = new BoundExpression[arguments.Arguments.Count]; for (int i = 0; i < arguments.Arguments.Count; ++i) { BoundExpression argument = arguments.Arguments[i]; BoundExpression index = ConvertToArrayIndex(argument, diagnostics, allowIndexAndRange: rank == 1); convertedArguments[i] = index; // NOTE: Dev10 only warns if rank == 1 // Question: Why do we limit this warning to one-dimensional arrays? // Answer: Because multidimensional arrays can have nonzero lower bounds in the CLR. if (rank == 1 && !index.HasAnyErrors) { ConstantValue constant = index.ConstantValue; if (constant != null && constant.IsNegativeNumeric) { Error(diagnostics, ErrorCode.WRN_NegativeArrayIndex, index.Syntax); } } } TypeSymbol resultType = rank == 1 && TypeSymbol.Equals( convertedArguments[0].Type, Compilation.GetWellKnownType(WellKnownType.System_Range), TypeCompareKind.ConsiderEverything) ? arrayType : arrayType.ElementType; return hasErrors ? new BoundArrayAccess(node, BindToTypeForErrorRecovery(expr), convertedArguments.Select(e => BindToTypeForErrorRecovery(e)).AsImmutableOrNull(), resultType, hasErrors: true) : new BoundArrayAccess(node, expr, convertedArguments.AsImmutableOrNull(), resultType, hasErrors: false); } private BoundExpression ConvertToArrayIndex(BoundExpression index, BindingDiagnosticBag diagnostics, bool allowIndexAndRange) { Debug.Assert(index != null); if (index.Kind == BoundKind.OutVariablePendingInference) { return ((OutVariablePendingInference)index).FailInference(this, diagnostics); } else if (index.Kind == BoundKind.DiscardExpression && !index.HasExpressionType()) { return ((BoundDiscardExpression)index).FailInference(this, diagnostics); } var node = index.Syntax; var result = TryImplicitConversionToArrayIndex(index, SpecialType.System_Int32, node, diagnostics) ?? TryImplicitConversionToArrayIndex(index, SpecialType.System_UInt32, node, diagnostics) ?? TryImplicitConversionToArrayIndex(index, SpecialType.System_Int64, node, diagnostics) ?? TryImplicitConversionToArrayIndex(index, SpecialType.System_UInt64, node, diagnostics); if (result is null && allowIndexAndRange) { result = TryImplicitConversionToArrayIndex(index, WellKnownType.System_Index, node, diagnostics); if (result is null) { result = TryImplicitConversionToArrayIndex(index, WellKnownType.System_Range, node, diagnostics); if (result is object) { // This member is needed for lowering and should produce an error if not present _ = GetWellKnownTypeMember( WellKnownMember.System_Runtime_CompilerServices_RuntimeHelpers__GetSubArray_T, diagnostics, syntax: node); } } else { // This member is needed for lowering and should produce an error if not present _ = GetWellKnownTypeMember( WellKnownMember.System_Index__GetOffset, diagnostics, syntax: node); } } if (result is null) { // Give the error that would be given upon conversion to int32. NamedTypeSymbol int32 = GetSpecialType(SpecialType.System_Int32, diagnostics, node); CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); Conversion failedConversion = this.Conversions.ClassifyConversionFromExpression(index, int32, ref useSiteInfo); diagnostics.Add(node, useSiteInfo); GenerateImplicitConversionError(diagnostics, node, failedConversion, index, int32); // Suppress any additional diagnostics return CreateConversion(node, index, failedConversion, isCast: false, conversionGroupOpt: null, destination: int32, diagnostics: BindingDiagnosticBag.Discarded); } return result; } private BoundExpression TryImplicitConversionToArrayIndex(BoundExpression expr, WellKnownType wellKnownType, SyntaxNode node, BindingDiagnosticBag diagnostics) { CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); TypeSymbol type = GetWellKnownType(wellKnownType, ref useSiteInfo); if (type.IsErrorType()) { return null; } var attemptDiagnostics = BindingDiagnosticBag.GetInstance(diagnostics); var result = TryImplicitConversionToArrayIndex(expr, type, node, attemptDiagnostics); if (result is object) { diagnostics.Add(node, useSiteInfo); diagnostics.AddRange(attemptDiagnostics); } attemptDiagnostics.Free(); return result; } private BoundExpression TryImplicitConversionToArrayIndex(BoundExpression expr, SpecialType specialType, SyntaxNode node, BindingDiagnosticBag diagnostics) { var attemptDiagnostics = BindingDiagnosticBag.GetInstance(diagnostics); TypeSymbol type = GetSpecialType(specialType, attemptDiagnostics, node); var result = TryImplicitConversionToArrayIndex(expr, type, node, attemptDiagnostics); if (result is object) { diagnostics.AddRange(attemptDiagnostics); } attemptDiagnostics.Free(); return result; } private BoundExpression TryImplicitConversionToArrayIndex(BoundExpression expr, TypeSymbol targetType, SyntaxNode node, BindingDiagnosticBag diagnostics) { Debug.Assert(expr != null); Debug.Assert((object)targetType != null); CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); Conversion conversion = this.Conversions.ClassifyImplicitConversionFromExpression(expr, targetType, ref useSiteInfo); diagnostics.Add(node, useSiteInfo); if (!conversion.Exists) { return null; } if (conversion.IsDynamic) { conversion = conversion.SetArrayIndexConversionForDynamic(); } BoundExpression result = CreateConversion(expr.Syntax, expr, conversion, isCast: false, conversionGroupOpt: null, destination: targetType, diagnostics); // UNDONE: was cast? Debug.Assert(result != null); // If this ever fails (it shouldn't), then put a null-check around the diagnostics update. return result; } private BoundExpression BindPointerElementAccess(ExpressionSyntax node, BoundExpression expr, AnalyzedArguments analyzedArguments, BindingDiagnosticBag diagnostics) { Debug.Assert(node != null); Debug.Assert(expr != null); Debug.Assert(analyzedArguments != null); bool hasErrors = false; if (analyzedArguments.Names.Count > 0) { // CONSIDER: the error text for this error code mentions "arrays". It might be nice if we had // a separate error code for pointer element access. Error(diagnostics, ErrorCode.ERR_NamedArgumentForArray, node); hasErrors = true; } hasErrors = hasErrors || ReportRefOrOutArgument(analyzedArguments, diagnostics); Debug.Assert(expr.Type.IsPointerType()); PointerTypeSymbol pointerType = (PointerTypeSymbol)expr.Type; TypeSymbol pointedAtType = pointerType.PointedAtType; ArrayBuilder<BoundExpression> arguments = analyzedArguments.Arguments; if (arguments.Count != 1) { if (!hasErrors) { Error(diagnostics, ErrorCode.ERR_PtrIndexSingle, node); } return new BoundPointerElementAccess(node, expr, BadExpression(node, BuildArgumentsForErrorRecovery(analyzedArguments)).MakeCompilerGenerated(), CheckOverflowAtRuntime, pointedAtType, hasErrors: true); } if (pointedAtType.IsVoidType()) { Error(diagnostics, ErrorCode.ERR_VoidError, expr.Syntax); hasErrors = true; } BoundExpression index = arguments[0]; index = ConvertToArrayIndex(index, diagnostics, allowIndexAndRange: false); return new BoundPointerElementAccess(node, expr, index, CheckOverflowAtRuntime, pointedAtType, hasErrors); } private static bool ReportRefOrOutArgument(AnalyzedArguments analyzedArguments, BindingDiagnosticBag diagnostics) { int numArguments = analyzedArguments.Arguments.Count; for (int i = 0; i < numArguments; i++) { RefKind refKind = analyzedArguments.RefKind(i); if (refKind != RefKind.None) { Error(diagnostics, ErrorCode.ERR_BadArgExtraRef, analyzedArguments.Argument(i).Syntax, i + 1, refKind.ToArgumentDisplayString()); return true; } } return false; } private BoundExpression BindIndexerAccess(ExpressionSyntax node, BoundExpression expr, AnalyzedArguments analyzedArguments, BindingDiagnosticBag diagnostics) { Debug.Assert(node != null); Debug.Assert(expr != null); Debug.Assert((object)expr.Type != null); Debug.Assert(analyzedArguments != null); LookupResult lookupResult = LookupResult.GetInstance(); LookupOptions lookupOptions = expr.Kind == BoundKind.BaseReference ? LookupOptions.UseBaseReferenceAccessibility : LookupOptions.Default; CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); this.LookupMembersWithFallback(lookupResult, expr.Type, WellKnownMemberNames.Indexer, arity: 0, useSiteInfo: ref useSiteInfo, options: lookupOptions); diagnostics.Add(node, useSiteInfo); // Store, rather than return, so that we can release resources. BoundExpression indexerAccessExpression; if (!lookupResult.IsMultiViable) { if (TryBindIndexOrRangeIndexer( node, expr, analyzedArguments, diagnostics, out var patternIndexerAccess)) { indexerAccessExpression = patternIndexerAccess; } else { indexerAccessExpression = BadIndexerExpression(node, expr, analyzedArguments, lookupResult.Error, diagnostics); } } else { ArrayBuilder<PropertySymbol> indexerGroup = ArrayBuilder<PropertySymbol>.GetInstance(); foreach (Symbol symbol in lookupResult.Symbols) { Debug.Assert(symbol.IsIndexer()); indexerGroup.Add((PropertySymbol)symbol); } indexerAccessExpression = BindIndexerOrIndexedPropertyAccess(node, expr, indexerGroup, analyzedArguments, diagnostics); indexerGroup.Free(); } lookupResult.Free(); return indexerAccessExpression; } private static readonly Func<PropertySymbol, bool> s_isIndexedPropertyWithNonOptionalArguments = property => { if (property.IsIndexer || !property.IsIndexedProperty) { return false; } Debug.Assert(property.ParameterCount > 0); var parameter = property.Parameters[0]; return !parameter.IsOptional && !parameter.IsParams; }; private static readonly SymbolDisplayFormat s_propertyGroupFormat = new SymbolDisplayFormat( globalNamespaceStyle: SymbolDisplayGlobalNamespaceStyle.Omitted, memberOptions: SymbolDisplayMemberOptions.IncludeContainingType, miscellaneousOptions: SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers | SymbolDisplayMiscellaneousOptions.UseSpecialTypes); private BoundExpression BindIndexedPropertyAccess(BoundPropertyGroup propertyGroup, bool mustHaveAllOptionalParameters, BindingDiagnosticBag diagnostics) { var syntax = propertyGroup.Syntax; var receiverOpt = propertyGroup.ReceiverOpt; var properties = propertyGroup.Properties; if (properties.All(s_isIndexedPropertyWithNonOptionalArguments)) { Error(diagnostics, mustHaveAllOptionalParameters ? ErrorCode.ERR_IndexedPropertyMustHaveAllOptionalParams : ErrorCode.ERR_IndexedPropertyRequiresParams, syntax, properties[0].ToDisplayString(s_propertyGroupFormat)); return BoundIndexerAccess.ErrorAccess( syntax, receiverOpt, CreateErrorPropertySymbol(properties), ImmutableArray<BoundExpression>.Empty, default(ImmutableArray<string>), default(ImmutableArray<RefKind>), properties); } var arguments = AnalyzedArguments.GetInstance(); var result = BindIndexedPropertyAccess(syntax, receiverOpt, properties, arguments, diagnostics); arguments.Free(); return result; } private BoundExpression BindIndexedPropertyAccess(SyntaxNode syntax, BoundExpression receiverOpt, ImmutableArray<PropertySymbol> propertyGroup, AnalyzedArguments arguments, BindingDiagnosticBag diagnostics) { // TODO: We're creating an extra copy of the properties array in BindIndexerOrIndexedProperty // converting the ArrayBuilder to ImmutableArray. Avoid the extra copy. var properties = ArrayBuilder<PropertySymbol>.GetInstance(); properties.AddRange(propertyGroup); var result = BindIndexerOrIndexedPropertyAccess(syntax, receiverOpt, properties, arguments, diagnostics); properties.Free(); return result; } private BoundExpression BindDynamicIndexer( SyntaxNode syntax, BoundExpression receiver, AnalyzedArguments arguments, ImmutableArray<PropertySymbol> applicableProperties, BindingDiagnosticBag diagnostics) { bool hasErrors = false; BoundKind receiverKind = receiver.Kind; if (receiverKind == BoundKind.BaseReference) { Error(diagnostics, ErrorCode.ERR_NoDynamicPhantomOnBaseIndexer, syntax); hasErrors = true; } else if (receiverKind == BoundKind.TypeOrValueExpression) { var typeOrValue = (BoundTypeOrValueExpression)receiver; // Unfortunately, the runtime binder doesn't have APIs that would allow us to pass both "type or value". // Ideally the runtime binder would choose between type and value based on the result of the overload resolution. // We need to pick one or the other here. Dev11 compiler passes the type only if the value can't be accessed. bool inStaticContext; bool useType = IsInstance(typeOrValue.Data.ValueSymbol) && !HasThis(isExplicit: false, inStaticContext: out inStaticContext); receiver = ReplaceTypeOrValueReceiver(typeOrValue, useType, diagnostics); } var argArray = BuildArgumentsForDynamicInvocation(arguments, diagnostics); var refKindsArray = arguments.RefKinds.ToImmutableOrNull(); hasErrors &= ReportBadDynamicArguments(syntax, argArray, refKindsArray, diagnostics, queryClause: null); return new BoundDynamicIndexerAccess( syntax, receiver, argArray, arguments.GetNames(), refKindsArray, applicableProperties, AssemblySymbol.DynamicType, hasErrors); } private BoundExpression BindIndexerOrIndexedPropertyAccess( SyntaxNode syntax, BoundExpression receiverOpt, ArrayBuilder<PropertySymbol> propertyGroup, AnalyzedArguments analyzedArguments, BindingDiagnosticBag diagnostics) { OverloadResolutionResult<PropertySymbol> overloadResolutionResult = OverloadResolutionResult<PropertySymbol>.GetInstance(); bool allowRefOmittedArguments = receiverOpt.IsExpressionOfComImportType(); CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); this.OverloadResolution.PropertyOverloadResolution(propertyGroup, receiverOpt, analyzedArguments, overloadResolutionResult, allowRefOmittedArguments, ref useSiteInfo); diagnostics.Add(syntax, useSiteInfo); BoundExpression propertyAccess; if (analyzedArguments.HasDynamicArgument && overloadResolutionResult.HasAnyApplicableMember) { // Note that the runtime binder may consider candidates that haven't passed compile-time final validation // and an ambiguity error may be reported. Also additional checks are performed in runtime final validation // that are not performed at compile-time. // Only if the set of final applicable candidates is empty we know for sure the call will fail at runtime. var finalApplicableCandidates = GetCandidatesPassingFinalValidation(syntax, overloadResolutionResult, receiverOpt, default(ImmutableArray<TypeWithAnnotations>), diagnostics); overloadResolutionResult.Free(); return BindDynamicIndexer(syntax, receiverOpt, analyzedArguments, finalApplicableCandidates, diagnostics); } ImmutableArray<string> argumentNames = analyzedArguments.GetNames(); ImmutableArray<RefKind> argumentRefKinds = analyzedArguments.RefKinds.ToImmutableOrNull(); if (!overloadResolutionResult.Succeeded) { // If the arguments had an error reported about them then suppress further error // reporting for overload resolution. ImmutableArray<PropertySymbol> candidates = propertyGroup.ToImmutable(); if (!analyzedArguments.HasErrors) { if (TryBindIndexOrRangeIndexer( syntax, receiverOpt, analyzedArguments, diagnostics, out var patternIndexerAccess)) { return patternIndexerAccess; } else { // Dev10 uses the "this" keyword as the method name for indexers. var candidate = candidates[0]; var name = candidate.IsIndexer ? SyntaxFacts.GetText(SyntaxKind.ThisKeyword) : candidate.Name; overloadResolutionResult.ReportDiagnostics( binder: this, location: syntax.Location, nodeOpt: syntax, diagnostics: diagnostics, name: name, receiver: null, invokedExpression: null, arguments: analyzedArguments, memberGroup: candidates, typeContainingConstructor: null, delegateTypeBeingInvoked: null); } } ImmutableArray<BoundExpression> arguments = BuildArgumentsForErrorRecovery(analyzedArguments, candidates); // A bad BoundIndexerAccess containing an ErrorPropertySymbol will produce better flow analysis results than // a BoundBadExpression containing the candidate indexers. PropertySymbol property = (candidates.Length == 1) ? candidates[0] : CreateErrorPropertySymbol(candidates); propertyAccess = BoundIndexerAccess.ErrorAccess( syntax, receiverOpt, property, arguments, argumentNames, argumentRefKinds, candidates); } else { MemberResolutionResult<PropertySymbol> resolutionResult = overloadResolutionResult.ValidResult; PropertySymbol property = resolutionResult.Member; RefKind? receiverRefKind = receiverOpt?.GetRefKind(); uint receiverEscapeScope = property.RequiresInstanceReceiver && receiverOpt != null ? receiverRefKind?.IsWritableReference() == true ? GetRefEscape(receiverOpt, LocalScopeDepth) : GetValEscape(receiverOpt, LocalScopeDepth) : Binder.ExternalScope; this.CoerceArguments<PropertySymbol>(resolutionResult, analyzedArguments.Arguments, diagnostics, receiverOpt?.Type, receiverRefKind, receiverEscapeScope); var isExpanded = resolutionResult.Result.Kind == MemberResolutionKind.ApplicableInExpandedForm; var argsToParams = resolutionResult.Result.ArgsToParamsOpt; ReportDiagnosticsIfObsolete(diagnostics, property, syntax, hasBaseReceiver: receiverOpt != null && receiverOpt.Kind == BoundKind.BaseReference); // Make sure that the result of overload resolution is valid. var gotError = MemberGroupFinalValidationAccessibilityChecks(receiverOpt, property, syntax, diagnostics, invokedAsExtensionMethod: false); var receiver = ReplaceTypeOrValueReceiver(receiverOpt, property.IsStatic, diagnostics); if (!gotError && receiver != null && receiver.Kind == BoundKind.ThisReference && receiver.WasCompilerGenerated) { gotError = IsRefOrOutThisParameterCaptured(syntax, diagnostics); } var arguments = analyzedArguments.Arguments.ToImmutable(); if (!gotError) { gotError = !CheckInvocationArgMixing( syntax, property, receiver, property.Parameters, arguments, argsToParams, this.LocalScopeDepth, diagnostics); } // Note that we do not bind default arguments here, because at this point we do not know whether // the indexer is being used in a 'get', or 'set', or 'get+set' (compound assignment) context. propertyAccess = new BoundIndexerAccess( syntax, receiver, property, arguments, argumentNames, argumentRefKinds, isExpanded, argsToParams, defaultArguments: default, property.Type, gotError); } overloadResolutionResult.Free(); return propertyAccess; } private bool TryBindIndexOrRangeIndexer( SyntaxNode syntax, BoundExpression receiverOpt, AnalyzedArguments arguments, BindingDiagnosticBag diagnostics, out BoundIndexOrRangePatternIndexerAccess patternIndexerAccess) { patternIndexerAccess = null; // Verify a few things up-front, namely that we have a single argument // to this indexer that has an Index or Range type and that there is // a real receiver with a known type if (arguments.Arguments.Count != 1) { return false; } var argument = arguments.Arguments[0]; var argType = argument.Type; bool argIsIndex = TypeSymbol.Equals(argType, Compilation.GetWellKnownType(WellKnownType.System_Index), TypeCompareKind.ConsiderEverything); bool argIsRange = !argIsIndex && TypeSymbol.Equals(argType, Compilation.GetWellKnownType(WellKnownType.System_Range), TypeCompareKind.ConsiderEverything); if ((!argIsIndex && !argIsRange) || !(receiverOpt?.Type is TypeSymbol receiverType)) { return false; } // SPEC: // An indexer invocation with a single argument of System.Index or System.Range will // succeed if the receiver type conforms to an appropriate pattern, namely // 1. The receiver type's original definition has an accessible property getter that returns // an int and has the name Length or Count // 2. For Index: Has an accessible indexer with a single int parameter // For Range: Has an accessible Slice method that takes two int parameters PropertySymbol lengthOrCountProperty; var lookupResult = LookupResult.GetInstance(); var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; // Look for Length first if (!tryLookupLengthOrCount(WellKnownMemberNames.LengthPropertyName, out lengthOrCountProperty) && !tryLookupLengthOrCount(WellKnownMemberNames.CountPropertyName, out lengthOrCountProperty)) { return false; } Debug.Assert(lengthOrCountProperty is { }); if (argIsIndex) { // Look for `T this[int i]` indexer LookupMembersInType( lookupResult, receiverType, WellKnownMemberNames.Indexer, arity: 0, basesBeingResolved: null, LookupOptions.Default, originalBinder: this, diagnose: false, ref discardedUseSiteInfo); if (lookupResult.IsMultiViable) { foreach (var candidate in lookupResult.Symbols) { if (!candidate.IsStatic && candidate is PropertySymbol property && IsAccessible(property, ref discardedUseSiteInfo) && property.OriginalDefinition is { ParameterCount: 1 } original && isIntNotByRef(original.Parameters[0])) { CheckImplicitThisCopyInReadOnlyMember(receiverOpt, lengthOrCountProperty.GetMethod, diagnostics); ReportDiagnosticsIfObsolete(diagnostics, property, syntax, hasBaseReceiver: false); ReportDiagnosticsIfObsolete(diagnostics, lengthOrCountProperty, syntax, hasBaseReceiver: false); // note: implicit copy check on the indexer accessor happens in CheckPropertyValueKind patternIndexerAccess = new BoundIndexOrRangePatternIndexerAccess( syntax, receiverOpt, lengthOrCountProperty, property, BindToNaturalType(argument, diagnostics), property.Type); break; } } } } else if (receiverType.SpecialType == SpecialType.System_String) { Debug.Assert(argIsRange); // Look for Substring var substring = (MethodSymbol)Compilation.GetSpecialTypeMember(SpecialMember.System_String__Substring); if (substring is object) { patternIndexerAccess = new BoundIndexOrRangePatternIndexerAccess( syntax, receiverOpt, lengthOrCountProperty, substring, BindToNaturalType(argument, diagnostics), substring.ReturnType); checkWellKnown(WellKnownMember.System_Range__get_Start); checkWellKnown(WellKnownMember.System_Range__get_End); } } else { Debug.Assert(argIsRange); // Look for `T Slice(int, int)` indexer LookupMembersInType( lookupResult, receiverType, WellKnownMemberNames.SliceMethodName, arity: 0, basesBeingResolved: null, LookupOptions.Default, originalBinder: this, diagnose: false, ref discardedUseSiteInfo); if (lookupResult.IsMultiViable) { foreach (var candidate in lookupResult.Symbols) { if (!candidate.IsStatic && IsAccessible(candidate, ref discardedUseSiteInfo) && candidate is MethodSymbol method && method.OriginalDefinition is var original && original.ParameterCount == 2 && isIntNotByRef(original.Parameters[0]) && isIntNotByRef(original.Parameters[1])) { CheckImplicitThisCopyInReadOnlyMember(receiverOpt, lengthOrCountProperty.GetMethod, diagnostics); CheckImplicitThisCopyInReadOnlyMember(receiverOpt, method, diagnostics); ReportDiagnosticsIfObsolete(diagnostics, method, syntax, hasBaseReceiver: false); ReportDiagnosticsIfObsolete(diagnostics, lengthOrCountProperty, syntax, hasBaseReceiver: false); patternIndexerAccess = new BoundIndexOrRangePatternIndexerAccess( syntax, receiverOpt, lengthOrCountProperty, method, BindToNaturalType(argument, diagnostics), method.ReturnType); checkWellKnown(WellKnownMember.System_Range__get_Start); checkWellKnown(WellKnownMember.System_Range__get_End); break; } } } } cleanup(lookupResult); if (patternIndexerAccess is null) { return false; } _ = MessageID.IDS_FeatureIndexOperator.CheckFeatureAvailability(diagnostics, syntax); checkWellKnown(WellKnownMember.System_Index__GetOffset); if (arguments.Names.Count > 0) { diagnostics.Add( argIsRange ? ErrorCode.ERR_ImplicitRangeIndexerWithName : ErrorCode.ERR_ImplicitIndexIndexerWithName, arguments.Names[0].GetValueOrDefault().Location); } return true; static void cleanup(LookupResult lookupResult) { lookupResult.Free(); } static bool isIntNotByRef(ParameterSymbol param) => param.Type.SpecialType == SpecialType.System_Int32 && param.RefKind == RefKind.None; void checkWellKnown(WellKnownMember member) { // Check required well-known member. They may not be needed // during lowering, but it's simpler to always require them to prevent // the user from getting surprising errors when optimizations fail _ = GetWellKnownTypeMember(member, diagnostics, syntax: syntax); } bool tryLookupLengthOrCount(string propertyName, out PropertySymbol valid) { LookupMembersInType( lookupResult, receiverType, propertyName, arity: 0, basesBeingResolved: null, LookupOptions.Default, originalBinder: this, diagnose: false, useSiteInfo: ref discardedUseSiteInfo); if (lookupResult.IsSingleViable && lookupResult.Symbols[0] is PropertySymbol property && property.GetOwnOrInheritedGetMethod()?.OriginalDefinition is MethodSymbol getMethod && getMethod.ReturnType.SpecialType == SpecialType.System_Int32 && getMethod.RefKind == RefKind.None && !getMethod.IsStatic && IsAccessible(getMethod, ref discardedUseSiteInfo)) { lookupResult.Clear(); valid = property; return true; } lookupResult.Clear(); valid = null; return false; } } private ErrorPropertySymbol CreateErrorPropertySymbol(ImmutableArray<PropertySymbol> propertyGroup) { TypeSymbol propertyType = GetCommonTypeOrReturnType(propertyGroup) ?? CreateErrorType(); var candidate = propertyGroup[0]; return new ErrorPropertySymbol(candidate.ContainingType, propertyType, candidate.Name, candidate.IsIndexer, candidate.IsIndexedProperty); } /// <summary> /// Perform lookup and overload resolution on methods defined directly on the class and any /// extension methods in scope. Lookup will occur for extension methods in all nested scopes /// as necessary until an appropriate method is found. If analyzedArguments is null, the first /// method group is returned, without overload resolution being performed. That method group /// will either be the methods defined on the receiver class directly (no extension methods) /// or the first set of extension methods. /// </summary> /// <param name="node">The node associated with the method group</param> /// <param name="analyzedArguments">The arguments of the invocation (or the delegate type, if a method group conversion)</param> /// <param name="isMethodGroupConversion">True if it is a method group conversion</param> /// <param name="useSiteInfo"></param> /// <param name="inferWithDynamic"></param> /// <param name="returnRefKind">If a method group conversion, the desired ref kind of the delegate</param> /// <param name="returnType">If a method group conversion, the desired return type of the delegate. /// May be null during inference if the return type of the delegate needs to be computed.</param> internal MethodGroupResolution ResolveMethodGroup( BoundMethodGroup node, AnalyzedArguments analyzedArguments, bool isMethodGroupConversion, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, bool inferWithDynamic = false, RefKind returnRefKind = default, TypeSymbol returnType = null, bool isFunctionPointerResolution = false, in CallingConventionInfo callingConventionInfo = default) { return ResolveMethodGroup( node, node.Syntax, node.Name, analyzedArguments, isMethodGroupConversion, ref useSiteInfo, inferWithDynamic: inferWithDynamic, returnRefKind: returnRefKind, returnType: returnType, isFunctionPointerResolution: isFunctionPointerResolution, callingConventionInfo: callingConventionInfo); } internal MethodGroupResolution ResolveMethodGroup( BoundMethodGroup node, SyntaxNode expression, string methodName, AnalyzedArguments analyzedArguments, bool isMethodGroupConversion, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, bool inferWithDynamic = false, bool allowUnexpandedForm = true, RefKind returnRefKind = default, TypeSymbol returnType = null, bool isFunctionPointerResolution = false, in CallingConventionInfo callingConventionInfo = default) { var methodResolution = ResolveMethodGroupInternal( node, expression, methodName, analyzedArguments, isMethodGroupConversion, ref useSiteInfo, inferWithDynamic: inferWithDynamic, allowUnexpandedForm: allowUnexpandedForm, returnRefKind: returnRefKind, returnType: returnType, isFunctionPointerResolution: isFunctionPointerResolution, callingConvention: callingConventionInfo); if (methodResolution.IsEmpty && !methodResolution.HasAnyErrors) { Debug.Assert(node.LookupError == null); var diagnostics = BindingDiagnosticBag.GetInstance(withDiagnostics: true, useSiteInfo.AccumulatesDependencies); diagnostics.AddRange(methodResolution.Diagnostics); // Could still have use site warnings. BindMemberAccessReportError(node, diagnostics); // Note: no need to free `methodResolution`, we're transferring the pooled objects it owned return new MethodGroupResolution(methodResolution.MethodGroup, methodResolution.OtherSymbol, methodResolution.OverloadResolutionResult, methodResolution.AnalyzedArguments, methodResolution.ResultKind, diagnostics.ToReadOnlyAndFree()); } return methodResolution; } internal MethodGroupResolution ResolveMethodGroupForFunctionPointer( BoundMethodGroup methodGroup, AnalyzedArguments analyzedArguments, TypeSymbol returnType, RefKind returnRefKind, in CallingConventionInfo callingConventionInfo, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { return ResolveDefaultMethodGroup( methodGroup, analyzedArguments, isMethodGroupConversion: true, ref useSiteInfo, inferWithDynamic: false, allowUnexpandedForm: true, returnRefKind, returnType, isFunctionPointerResolution: true, callingConventionInfo); } private MethodGroupResolution ResolveMethodGroupInternal( BoundMethodGroup methodGroup, SyntaxNode expression, string methodName, AnalyzedArguments analyzedArguments, bool isMethodGroupConversion, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, bool inferWithDynamic = false, bool allowUnexpandedForm = true, RefKind returnRefKind = default, TypeSymbol returnType = null, bool isFunctionPointerResolution = false, in CallingConventionInfo callingConvention = default) { var methodResolution = ResolveDefaultMethodGroup( methodGroup, analyzedArguments, isMethodGroupConversion, ref useSiteInfo, inferWithDynamic, allowUnexpandedForm, returnRefKind, returnType, isFunctionPointerResolution, callingConvention); // If the method group's receiver is dynamic then there is no point in looking for extension methods; // it's going to be a dynamic invocation. if (!methodGroup.SearchExtensionMethods || methodResolution.HasAnyApplicableMethod || methodGroup.MethodGroupReceiverIsDynamic()) { return methodResolution; } var extensionMethodResolution = BindExtensionMethod( expression, methodName, analyzedArguments, methodGroup.ReceiverOpt, methodGroup.TypeArgumentsOpt, isMethodGroupConversion, returnRefKind: returnRefKind, returnType: returnType, withDependencies: useSiteInfo.AccumulatesDependencies); bool preferExtensionMethodResolution = false; if (extensionMethodResolution.HasAnyApplicableMethod) { preferExtensionMethodResolution = true; } else if (extensionMethodResolution.IsEmpty) { preferExtensionMethodResolution = false; } else if (methodResolution.IsEmpty) { preferExtensionMethodResolution = true; } else { // At this point, both method group resolutions are non-empty but neither contains any applicable method. // Choose the MethodGroupResolution with the better (i.e. less worse) result kind. Debug.Assert(!methodResolution.HasAnyApplicableMethod); Debug.Assert(!extensionMethodResolution.HasAnyApplicableMethod); Debug.Assert(!methodResolution.IsEmpty); Debug.Assert(!extensionMethodResolution.IsEmpty); LookupResultKind methodResultKind = methodResolution.ResultKind; LookupResultKind extensionMethodResultKind = extensionMethodResolution.ResultKind; if (methodResultKind != extensionMethodResultKind && methodResultKind == extensionMethodResultKind.WorseResultKind(methodResultKind)) { preferExtensionMethodResolution = true; } } if (preferExtensionMethodResolution) { methodResolution.Free(); Debug.Assert(!extensionMethodResolution.IsEmpty); return extensionMethodResolution; //NOTE: the first argument of this MethodGroupResolution could be a BoundTypeOrValueExpression } extensionMethodResolution.Free(); return methodResolution; } private MethodGroupResolution ResolveDefaultMethodGroup( BoundMethodGroup node, AnalyzedArguments analyzedArguments, bool isMethodGroupConversion, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, bool inferWithDynamic = false, bool allowUnexpandedForm = true, RefKind returnRefKind = default, TypeSymbol returnType = null, bool isFunctionPointerResolution = false, in CallingConventionInfo callingConvention = default) { var methods = node.Methods; if (methods.Length == 0) { var method = node.LookupSymbolOpt as MethodSymbol; if ((object)method != null) { methods = ImmutableArray.Create(method); } } var sealedDiagnostics = ImmutableBindingDiagnostic<AssemblySymbol>.Empty; if (node.LookupError != null) { var diagnostics = BindingDiagnosticBag.GetInstance(withDiagnostics: true, withDependencies: false); Error(diagnostics, node.LookupError, node.NameSyntax); sealedDiagnostics = diagnostics.ToReadOnlyAndFree(); } if (methods.Length == 0) { return new MethodGroupResolution(node.LookupSymbolOpt, node.ResultKind, sealedDiagnostics); } var methodGroup = MethodGroup.GetInstance(); // NOTE: node.ReceiverOpt could be a BoundTypeOrValueExpression - users need to check. methodGroup.PopulateWithNonExtensionMethods(node.ReceiverOpt, methods, node.TypeArgumentsOpt, node.ResultKind, node.LookupError); if (node.LookupError != null) { return new MethodGroupResolution(methodGroup, sealedDiagnostics); } // Arguments will be null if the caller is resolving to the first available // method group, regardless of arguments, when the signature cannot // be inferred. (In the error case of o.M = null; for instance.) if (analyzedArguments == null) { return new MethodGroupResolution(methodGroup, sealedDiagnostics); } else { var result = OverloadResolutionResult<MethodSymbol>.GetInstance(); bool allowRefOmittedArguments = methodGroup.Receiver.IsExpressionOfComImportType(); OverloadResolution.MethodInvocationOverloadResolution( methodGroup.Methods, methodGroup.TypeArguments, methodGroup.Receiver, analyzedArguments, result, ref useSiteInfo, isMethodGroupConversion, allowRefOmittedArguments, inferWithDynamic, allowUnexpandedForm, returnRefKind, returnType, isFunctionPointerResolution, callingConvention); // Note: the MethodGroupResolution instance is responsible for freeing its copy of analyzed arguments return new MethodGroupResolution(methodGroup, null, result, AnalyzedArguments.GetInstance(analyzedArguments), methodGroup.ResultKind, sealedDiagnostics); } } #nullable enable internal NamedTypeSymbol? GetMethodGroupDelegateType(BoundMethodGroup node, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { if (GetUniqueSignatureFromMethodGroup(node) is { } method && GetMethodGroupOrLambdaDelegateType(method.RefKind, method.ReturnsVoid ? default : method.ReturnTypeWithAnnotations, method.ParameterRefKinds, method.ParameterTypesWithAnnotations, ref useSiteInfo) is { } delegateType) { return delegateType; } return null; } /// <summary> /// Returns one of the methods from the method group if all methods in the method group /// have the same signature, ignoring parameter names and custom modifiers. The particular /// method returned is not important since the caller is interested in the signature only. /// </summary> private MethodSymbol? GetUniqueSignatureFromMethodGroup(BoundMethodGroup node) { MethodSymbol? method = null; foreach (var m in node.Methods) { switch (node.ReceiverOpt) { case BoundTypeExpression: if (!m.IsStatic) continue; break; case BoundThisReference { WasCompilerGenerated: true }: break; default: if (m.IsStatic) continue; break; } if (!isCandidateUnique(ref method, m)) { return null; } } if (node.SearchExtensionMethods) { var receiver = node.ReceiverOpt!; foreach (var scope in new ExtensionMethodScopes(this)) { var methodGroup = MethodGroup.GetInstance(); PopulateExtensionMethodsFromSingleBinder(scope, methodGroup, node.Syntax, receiver, node.Name, node.TypeArgumentsOpt, BindingDiagnosticBag.Discarded); foreach (var m in methodGroup.Methods) { if (m.ReduceExtensionMethod(receiver.Type, Compilation) is { } reduced && !isCandidateUnique(ref method, reduced)) { methodGroup.Free(); return null; } } methodGroup.Free(); } } if (method is null) { return null; } int n = node.TypeArgumentsOpt.IsDefaultOrEmpty ? 0 : node.TypeArgumentsOpt.Length; if (method.Arity != n) { return null; } else if (n > 0) { method = method.ConstructedFrom.Construct(node.TypeArgumentsOpt); } return method; static bool isCandidateUnique(ref MethodSymbol? method, MethodSymbol candidate) { if (method is null) { method = candidate; return true; } if (MemberSignatureComparer.MethodGroupSignatureComparer.Equals(method, candidate)) { return true; } method = null; return false; } } // This method was adapted from LoweredDynamicOperationFactory.GetDelegateType(). // Consider using that method directly since it also synthesizes delegates if necessary. internal NamedTypeSymbol? GetMethodGroupOrLambdaDelegateType( RefKind returnRefKind, TypeWithAnnotations returnTypeOpt, ImmutableArray<RefKind> parameterRefKinds, ImmutableArray<TypeWithAnnotations> parameterTypes, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(returnTypeOpt.Type?.IsVoidType() != true); // expecting !returnTypeOpt.HasType rather than System.Void if (returnRefKind == RefKind.None && (parameterRefKinds.IsDefault || parameterRefKinds.All(refKind => refKind == RefKind.None))) { var wkDelegateType = returnTypeOpt.HasType ? WellKnownTypes.GetWellKnownFunctionDelegate(invokeArgumentCount: parameterTypes.Length) : WellKnownTypes.GetWellKnownActionDelegate(invokeArgumentCount: parameterTypes.Length); if (wkDelegateType != WellKnownType.Unknown) { var delegateType = Compilation.GetWellKnownType(wkDelegateType); delegateType.AddUseSiteInfo(ref useSiteInfo); if (returnTypeOpt.HasType) { parameterTypes = parameterTypes.Add(returnTypeOpt); } if (parameterTypes.Length == 0) { return delegateType; } if (checkConstraints(Compilation, Conversions, delegateType, parameterTypes)) { return delegateType.Construct(parameterTypes); } } } return null; static bool checkConstraints(CSharpCompilation compilation, ConversionsBase conversions, NamedTypeSymbol delegateType, ImmutableArray<TypeWithAnnotations> typeArguments) { var diagnosticsBuilder = ArrayBuilder<TypeParameterDiagnosticInfo>.GetInstance(); var typeParameters = delegateType.TypeParameters; var substitution = new TypeMap(typeParameters, typeArguments); ArrayBuilder<TypeParameterDiagnosticInfo>? useSiteDiagnosticsBuilder = null; var result = delegateType.CheckConstraints( new ConstraintsHelper.CheckConstraintsArgs(compilation, conversions, includeNullability: false, NoLocation.Singleton, diagnostics: null, template: CompoundUseSiteInfo<AssemblySymbol>.Discarded), substitution, typeParameters, typeArguments, diagnosticsBuilder, nullabilityDiagnosticsBuilderOpt: null, ref useSiteDiagnosticsBuilder); diagnosticsBuilder.Free(); return result; } } #nullable disable internal static bool ReportDelegateInvokeUseSiteDiagnostic(BindingDiagnosticBag diagnostics, TypeSymbol possibleDelegateType, Location location = null, SyntaxNode node = null) { Debug.Assert((location == null) ^ (node == null)); if (!possibleDelegateType.IsDelegateType()) { return false; } MethodSymbol invoke = possibleDelegateType.DelegateInvokeMethod(); if ((object)invoke == null) { diagnostics.Add(new CSDiagnosticInfo(ErrorCode.ERR_InvalidDelegateType, possibleDelegateType), location ?? node.Location); return true; } UseSiteInfo<AssemblySymbol> info = invoke.GetUseSiteInfo(); diagnostics.AddDependencies(info); DiagnosticInfo diagnosticInfo = info.DiagnosticInfo; if (diagnosticInfo == null) { return false; } if (location == null) { location = node.Location; } if (diagnosticInfo.Code == (int)ErrorCode.ERR_InvalidDelegateType) { diagnostics.Add(new CSDiagnostic(new CSDiagnosticInfo(ErrorCode.ERR_InvalidDelegateType, possibleDelegateType), location)); return true; } return Symbol.ReportUseSiteDiagnostic(diagnosticInfo, diagnostics, location); } private BoundConditionalAccess BindConditionalAccessExpression(ConditionalAccessExpressionSyntax node, BindingDiagnosticBag diagnostics) { BoundExpression receiver = BindConditionalAccessReceiver(node, diagnostics); var conditionalAccessBinder = new BinderWithConditionalReceiver(this, receiver); var access = conditionalAccessBinder.BindValue(node.WhenNotNull, diagnostics, BindValueKind.RValue); if (receiver.HasAnyErrors || access.HasAnyErrors) { return new BoundConditionalAccess(node, receiver, access, CreateErrorType(), hasErrors: true); } var receiverType = receiver.Type; Debug.Assert((object)receiverType != null); // access cannot be a method group if (access.Kind == BoundKind.MethodGroup) { return GenerateBadConditionalAccessNodeError(node, receiver, access, diagnostics); } var accessType = access.Type; // access cannot have no type if ((object)accessType == null) { return GenerateBadConditionalAccessNodeError(node, receiver, access, diagnostics); } // The resulting type must be either a reference type T or Nullable<T> // Therefore we must reject cases resulting in types that are not reference types and cannot be lifted into nullable. // - access cannot have unconstrained generic type // - access cannot be a pointer // - access cannot be a restricted type if ((!accessType.IsReferenceType && !accessType.IsValueType) || accessType.IsPointerOrFunctionPointer() || accessType.IsRestrictedType()) { // Result type of the access is void when result value cannot be made nullable. // For improved diagnostics we detect the cases where the value will be used and produce a // more specific (though not technically correct) diagnostic here: // "Error CS0023: Operator '?' cannot be applied to operand of type 'T'" bool resultIsUsed = true; CSharpSyntaxNode parent = node.Parent; if (parent != null) { switch (parent.Kind()) { case SyntaxKind.ExpressionStatement: resultIsUsed = ((ExpressionStatementSyntax)parent).Expression != node; break; case SyntaxKind.SimpleLambdaExpression: resultIsUsed = (((SimpleLambdaExpressionSyntax)parent).Body != node) || MethodOrLambdaRequiresValue(ContainingMemberOrLambda, Compilation); break; case SyntaxKind.ParenthesizedLambdaExpression: resultIsUsed = (((ParenthesizedLambdaExpressionSyntax)parent).Body != node) || MethodOrLambdaRequiresValue(ContainingMemberOrLambda, Compilation); break; case SyntaxKind.ArrowExpressionClause: resultIsUsed = (((ArrowExpressionClauseSyntax)parent).Expression != node) || MethodOrLambdaRequiresValue(ContainingMemberOrLambda, Compilation); break; case SyntaxKind.ForStatement: // Incrementors and Initializers doesn't have to produce a value var loop = (ForStatementSyntax)parent; resultIsUsed = !loop.Incrementors.Contains(node) && !loop.Initializers.Contains(node); break; } } if (resultIsUsed) { return GenerateBadConditionalAccessNodeError(node, receiver, access, diagnostics); } accessType = GetSpecialType(SpecialType.System_Void, diagnostics, node); } // if access has value type, the type of the conditional access is nullable of that // https://github.com/dotnet/roslyn/issues/35075: The test `accessType.IsValueType && !accessType.IsNullableType()` // should probably be `accessType.IsNonNullableValueType()` if (accessType.IsValueType && !accessType.IsNullableType() && !accessType.IsVoidType()) { accessType = GetSpecialType(SpecialType.System_Nullable_T, diagnostics, node).Construct(accessType); } return new BoundConditionalAccess(node, receiver, access, accessType); } internal static bool MethodOrLambdaRequiresValue(Symbol symbol, CSharpCompilation compilation) { return symbol is MethodSymbol method && !method.ReturnsVoid && !method.IsAsyncEffectivelyReturningTask(compilation); } private BoundConditionalAccess GenerateBadConditionalAccessNodeError(ConditionalAccessExpressionSyntax node, BoundExpression receiver, BoundExpression access, BindingDiagnosticBag diagnostics) { var operatorToken = node.OperatorToken; // TODO: need a special ERR for this. // conditional access is not really a binary operator. DiagnosticInfo diagnosticInfo = new CSDiagnosticInfo(ErrorCode.ERR_BadUnaryOp, SyntaxFacts.GetText(operatorToken.Kind()), access.Display); diagnostics.Add(new CSDiagnostic(diagnosticInfo, operatorToken.GetLocation())); receiver = BadExpression(receiver.Syntax, receiver); return new BoundConditionalAccess(node, receiver, access, CreateErrorType(), hasErrors: true); } private BoundExpression BindMemberBindingExpression(MemberBindingExpressionSyntax node, bool invoked, bool indexed, BindingDiagnosticBag diagnostics) { BoundExpression receiver = GetReceiverForConditionalBinding(node, diagnostics); var memberAccess = BindMemberAccessWithBoundLeft(node, receiver, node.Name, node.OperatorToken, invoked, indexed, diagnostics); return memberAccess; } private BoundExpression BindElementBindingExpression(ElementBindingExpressionSyntax node, BindingDiagnosticBag diagnostics) { BoundExpression receiver = GetReceiverForConditionalBinding(node, diagnostics); var memberAccess = BindElementAccess(node, receiver, node.ArgumentList, diagnostics); return memberAccess; } private static CSharpSyntaxNode GetConditionalReceiverSyntax(ConditionalAccessExpressionSyntax node) { Debug.Assert(node != null); Debug.Assert(node.Expression != null); var receiver = node.Expression; while (receiver.IsKind(SyntaxKind.ParenthesizedExpression)) { receiver = ((ParenthesizedExpressionSyntax)receiver).Expression; Debug.Assert(receiver != null); } return receiver; } private BoundExpression GetReceiverForConditionalBinding(ExpressionSyntax binding, BindingDiagnosticBag diagnostics) { var conditionalAccessNode = SyntaxFactory.FindConditionalAccessNodeForBinding(binding); Debug.Assert(conditionalAccessNode != null); BoundExpression receiver = this.ConditionalReceiverExpression; if (receiver?.Syntax != GetConditionalReceiverSyntax(conditionalAccessNode)) { // this can happen when semantic model binds parts of a Call or a broken access expression. // We may not have receiver available in such cases. // Not a problem - we only need receiver to get its type and we can bind it here. receiver = BindConditionalAccessReceiver(conditionalAccessNode, diagnostics); } // create surrogate receiver var receiverType = receiver.Type; if (receiverType?.IsNullableType() == true) { receiverType = receiverType.GetNullableUnderlyingType(); } receiver = new BoundConditionalReceiver(receiver.Syntax, 0, receiverType ?? CreateErrorType(), hasErrors: receiver.HasErrors) { WasCompilerGenerated = true }; return receiver; } private BoundExpression BindConditionalAccessReceiver(ConditionalAccessExpressionSyntax node, BindingDiagnosticBag diagnostics) { var receiverSyntax = node.Expression; var receiver = BindRValueWithoutTargetType(receiverSyntax, diagnostics); receiver = MakeMemberAccessValue(receiver, diagnostics); if (receiver.HasAnyErrors) { return receiver; } var operatorToken = node.OperatorToken; if (receiver.Kind == BoundKind.UnboundLambda) { var msgId = ((UnboundLambda)receiver).MessageID; DiagnosticInfo diagnosticInfo = new CSDiagnosticInfo(ErrorCode.ERR_BadUnaryOp, SyntaxFacts.GetText(operatorToken.Kind()), msgId.Localize()); diagnostics.Add(new CSDiagnostic(diagnosticInfo, node.Location)); return BadExpression(receiverSyntax, receiver); } var receiverType = receiver.Type; // Can't dot into the null literal or anything that has no type if ((object)receiverType == null) { Error(diagnostics, ErrorCode.ERR_BadUnaryOp, operatorToken.GetLocation(), operatorToken.Text, receiver.Display); return BadExpression(receiverSyntax, receiver); } // No member accesses on void if (receiverType.IsVoidType()) { Error(diagnostics, ErrorCode.ERR_BadUnaryOp, operatorToken.GetLocation(), operatorToken.Text, receiverType); return BadExpression(receiverSyntax, receiver); } if (receiverType.IsValueType && !receiverType.IsNullableType()) { // must be nullable or reference type Error(diagnostics, ErrorCode.ERR_BadUnaryOp, operatorToken.GetLocation(), operatorToken.Text, receiverType); return BadExpression(receiverSyntax, receiver); } return receiver; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; namespace Microsoft.CodeAnalysis.CSharp { /// <summary> /// This portion of the binder converts an <see cref="ExpressionSyntax"/> into a <see cref="BoundExpression"/>. /// </summary> internal partial class Binder { /// <summary> /// Determines whether "this" reference is available within the current context. /// </summary> /// <param name="isExplicit">The reference was explicitly specified in syntax.</param> /// <param name="inStaticContext">True if "this" is not available due to the current method/property/field initializer being static.</param> /// <returns>True if a reference to "this" is available.</returns> internal bool HasThis(bool isExplicit, out bool inStaticContext) { var memberOpt = this.ContainingMemberOrLambda?.ContainingNonLambdaMember(); if (memberOpt?.IsStatic == true) { inStaticContext = memberOpt.Kind == SymbolKind.Field || memberOpt.Kind == SymbolKind.Method || memberOpt.Kind == SymbolKind.Property; return false; } inStaticContext = false; if (InConstructorInitializer || InAttributeArgument) { return false; } var containingType = memberOpt?.ContainingType; bool inTopLevelScriptMember = (object)containingType != null && containingType.IsScriptClass; // "this" is not allowed in field initializers (that are not script variable initializers): if (InFieldInitializer && !inTopLevelScriptMember) { return false; } // top-level script code only allows implicit "this" reference: return !inTopLevelScriptMember || !isExplicit; } internal bool InFieldInitializer { get { return this.Flags.Includes(BinderFlags.FieldInitializer); } } internal bool InParameterDefaultValue { get { return this.Flags.Includes(BinderFlags.ParameterDefaultValue); } } protected bool InConstructorInitializer { get { return this.Flags.Includes(BinderFlags.ConstructorInitializer); } } internal bool InAttributeArgument { get { return this.Flags.Includes(BinderFlags.AttributeArgument); } } internal bool InCref { get { return this.Flags.Includes(BinderFlags.Cref); } } protected bool InCrefButNotParameterOrReturnType { get { return InCref && !this.Flags.Includes(BinderFlags.CrefParameterOrReturnType); } } /// <summary> /// Returns true if the node is in a position where an unbound type /// such as (C&lt;,&gt;) is allowed. /// </summary> protected virtual bool IsUnboundTypeAllowed(GenericNameSyntax syntax) { return Next.IsUnboundTypeAllowed(syntax); } /// <summary> /// Generates a new <see cref="BoundBadExpression"/> with no known type /// </summary> private BoundBadExpression BadExpression(SyntaxNode syntax) { return BadExpression(syntax, LookupResultKind.Empty, ImmutableArray<Symbol>.Empty); } /// <summary> /// Generates a new <see cref="BoundBadExpression"/> with no known type, and the given bound child. /// </summary> private BoundBadExpression BadExpression(SyntaxNode syntax, BoundExpression childNode) { return BadExpression(syntax, LookupResultKind.Empty, ImmutableArray<Symbol>.Empty, childNode); } /// <summary> /// Generates a new <see cref="BoundBadExpression"/> with no known type, and the given bound children. /// </summary> private BoundBadExpression BadExpression(SyntaxNode syntax, ImmutableArray<BoundExpression> childNodes) { return BadExpression(syntax, LookupResultKind.Empty, ImmutableArray<Symbol>.Empty, childNodes); } /// <summary> /// Generates a new <see cref="BoundBadExpression"/> with no known type, given lookup resultKind. /// </summary> protected BoundBadExpression BadExpression(SyntaxNode syntax, LookupResultKind lookupResultKind) { return BadExpression(syntax, lookupResultKind, ImmutableArray<Symbol>.Empty); } /// <summary> /// Generates a new <see cref="BoundBadExpression"/> with no known type, given lookup resultKind and the given bound child. /// </summary> protected BoundBadExpression BadExpression(SyntaxNode syntax, LookupResultKind lookupResultKind, BoundExpression childNode) { return BadExpression(syntax, lookupResultKind, ImmutableArray<Symbol>.Empty, childNode); } /// <summary> /// Generates a new <see cref="BoundBadExpression"/> with no known type, given lookupResultKind and given symbols for GetSemanticInfo API. /// </summary> private BoundBadExpression BadExpression(SyntaxNode syntax, LookupResultKind resultKind, ImmutableArray<Symbol> symbols) { return new BoundBadExpression(syntax, resultKind, symbols, ImmutableArray<BoundExpression>.Empty, CreateErrorType()); } /// <summary> /// Generates a new <see cref="BoundBadExpression"/> with no known type, given lookupResultKind and given symbols for GetSemanticInfo API, /// and the given bound child. /// </summary> private BoundBadExpression BadExpression(SyntaxNode syntax, LookupResultKind resultKind, ImmutableArray<Symbol> symbols, BoundExpression childNode) { return new BoundBadExpression(syntax, resultKind, symbols, ImmutableArray.Create(BindToTypeForErrorRecovery(childNode)), CreateErrorType()); } /// <summary> /// Generates a new <see cref="BoundBadExpression"/> with no known type, given lookupResultKind and given symbols for GetSemanticInfo API, /// and the given bound children. /// </summary> private BoundBadExpression BadExpression(SyntaxNode syntax, LookupResultKind resultKind, ImmutableArray<Symbol> symbols, ImmutableArray<BoundExpression> childNodes, bool wasCompilerGenerated = false) { return new BoundBadExpression(syntax, resultKind, symbols, childNodes.SelectAsArray((e, self) => self.BindToTypeForErrorRecovery(e), this), CreateErrorType()) { WasCompilerGenerated = wasCompilerGenerated }; } /// <summary> /// Helper method to generate a bound expression with HasErrors set to true. /// Returned bound expression is guaranteed to have a non-null type, except when <paramref name="expr"/> is an unbound lambda. /// If <paramref name="expr"/> already has errors and meets the above type requirements, then it is returned unchanged. /// Otherwise, if <paramref name="expr"/> is a BoundBadExpression, then it is updated with the <paramref name="resultKind"/> and non-null type. /// Otherwise, a new <see cref="BoundBadExpression"/> wrapping <paramref name="expr"/> is returned. /// </summary> /// <remarks> /// Returned expression need not be a <see cref="BoundBadExpression"/>, but is guaranteed to have HasErrors set to true. /// </remarks> private BoundExpression ToBadExpression(BoundExpression expr, LookupResultKind resultKind = LookupResultKind.Empty) { Debug.Assert(expr != null); Debug.Assert(resultKind != LookupResultKind.Viable); TypeSymbol resultType = expr.Type; BoundKind exprKind = expr.Kind; if (expr.HasAnyErrors && ((object)resultType != null || exprKind == BoundKind.UnboundLambda || exprKind == BoundKind.DefaultLiteral)) { return expr; } if (exprKind == BoundKind.BadExpression) { var badExpression = (BoundBadExpression)expr; return badExpression.Update(resultKind, badExpression.Symbols, badExpression.ChildBoundNodes, resultType); } else { ArrayBuilder<Symbol> symbols = ArrayBuilder<Symbol>.GetInstance(); expr.GetExpressionSymbols(symbols, parent: null, binder: this); return new BoundBadExpression( expr.Syntax, resultKind, symbols.ToImmutableAndFree(), ImmutableArray.Create(BindToTypeForErrorRecovery(expr)), resultType ?? CreateErrorType()); } } internal NamedTypeSymbol CreateErrorType(string name = "") { return new ExtendedErrorTypeSymbol(this.Compilation, name, arity: 0, errorInfo: null, unreported: false); } /// <summary> /// Bind the expression and verify the expression matches the combination of lvalue and /// rvalue requirements given by valueKind. If the expression was bound successfully, but /// did not meet the requirements, the return value will be a <see cref="BoundBadExpression"/> that /// (typically) wraps the subexpression. /// </summary> internal BoundExpression BindValue(ExpressionSyntax node, BindingDiagnosticBag diagnostics, BindValueKind valueKind) { var result = this.BindExpression(node, diagnostics: diagnostics, invoked: false, indexed: false); return CheckValue(result, valueKind, diagnostics); } internal BoundExpression BindRValueWithoutTargetType(ExpressionSyntax node, BindingDiagnosticBag diagnostics, bool reportNoTargetType = true) { return BindToNaturalType(BindValue(node, diagnostics, BindValueKind.RValue), diagnostics, reportNoTargetType); } /// <summary> /// When binding a switch case's expression, it is possible that it resolves to a type (technically, a type pattern). /// This implementation permits either an rvalue or a BoundTypeExpression. /// </summary> internal BoundExpression BindTypeOrRValue(ExpressionSyntax node, BindingDiagnosticBag diagnostics) { var valueOrType = BindExpression(node, diagnostics: diagnostics, invoked: false, indexed: false); if (valueOrType.Kind == BoundKind.TypeExpression) { // In the Color Color case (Kind == BoundKind.TypeOrValueExpression), we treat it as a value // by not entering this if statement return valueOrType; } return CheckValue(valueOrType, BindValueKind.RValue, diagnostics); } internal BoundExpression BindToTypeForErrorRecovery(BoundExpression expression, TypeSymbol type = null) { if (expression is null) return null; var result = !expression.NeedsToBeConverted() ? expression : type is null ? BindToNaturalType(expression, BindingDiagnosticBag.Discarded, reportNoTargetType: false) : GenerateConversionForAssignment(type, expression, BindingDiagnosticBag.Discarded); return result; } /// <summary> /// Bind an rvalue expression to its natural type. For example, a switch expression that has not been /// converted to another type has to be converted to its own natural type by applying a conversion to /// that type to each of the arms of the switch expression. This method is a bottleneck for ensuring /// that such a conversion occurs when needed. It also handles tuple expressions which need to be /// converted to their own natural type because they may contain switch expressions. /// </summary> internal BoundExpression BindToNaturalType(BoundExpression expression, BindingDiagnosticBag diagnostics, bool reportNoTargetType = true) { if (!expression.NeedsToBeConverted()) return expression; BoundExpression result; switch (expression) { case BoundUnconvertedSwitchExpression expr: { var commonType = expr.Type; var exprSyntax = (SwitchExpressionSyntax)expr.Syntax; bool hasErrors = expression.HasErrors; if (commonType is null) { diagnostics.Add(ErrorCode.ERR_SwitchExpressionNoBestType, exprSyntax.SwitchKeyword.GetLocation()); commonType = CreateErrorType(); hasErrors = true; } result = ConvertSwitchExpression(expr, commonType, conversionIfTargetTyped: null, diagnostics, hasErrors); } break; case BoundUnconvertedConditionalOperator op: { TypeSymbol type = op.Type; bool hasErrors = op.HasErrors; if (type is null) { Debug.Assert(op.NoCommonTypeError != 0); type = CreateErrorType(); hasErrors = true; object trueArg = op.Consequence.Display; object falseArg = op.Alternative.Display; if (op.NoCommonTypeError == ErrorCode.ERR_InvalidQM && trueArg is Symbol trueSymbol && falseArg is Symbol falseSymbol) { // ERR_InvalidQM is an error that there is no conversion between the two types. They might be the same // type name from different assemblies, so we disambiguate the display. SymbolDistinguisher distinguisher = new SymbolDistinguisher(this.Compilation, trueSymbol, falseSymbol); trueArg = distinguisher.First; falseArg = distinguisher.Second; } diagnostics.Add(op.NoCommonTypeError, op.Syntax.Location, trueArg, falseArg); } result = ConvertConditionalExpression(op, type, conversionIfTargetTyped: null, diagnostics, hasErrors); } break; case BoundTupleLiteral sourceTuple: { var boundArgs = ArrayBuilder<BoundExpression>.GetInstance(sourceTuple.Arguments.Length); foreach (var arg in sourceTuple.Arguments) { boundArgs.Add(BindToNaturalType(arg, diagnostics, reportNoTargetType)); } result = new BoundConvertedTupleLiteral( sourceTuple.Syntax, sourceTuple, wasTargetTyped: false, boundArgs.ToImmutableAndFree(), sourceTuple.ArgumentNamesOpt, sourceTuple.InferredNamesOpt, sourceTuple.Type, // same type to keep original element names sourceTuple.HasErrors).WithSuppression(sourceTuple.IsSuppressed); } break; case BoundDefaultLiteral defaultExpr: { if (reportNoTargetType) { // In some cases, we let the caller report the error diagnostics.Add(ErrorCode.ERR_DefaultLiteralNoTargetType, defaultExpr.Syntax.GetLocation()); } result = new BoundDefaultExpression( defaultExpr.Syntax, targetType: null, defaultExpr.ConstantValue, CreateErrorType(), hasErrors: true).WithSuppression(defaultExpr.IsSuppressed); } break; case BoundStackAllocArrayCreation { Type: null } boundStackAlloc: { // This is a context in which the stackalloc could be either a pointer // or a span. For backward compatibility we treat it as a pointer. var type = new PointerTypeSymbol(TypeWithAnnotations.Create(boundStackAlloc.ElementType)); result = GenerateConversionForAssignment(type, boundStackAlloc, diagnostics); } break; case BoundUnconvertedObjectCreationExpression expr: { if (reportNoTargetType && !expr.HasAnyErrors) { diagnostics.Add(ErrorCode.ERR_ImplicitObjectCreationNoTargetType, expr.Syntax.GetLocation(), expr.Display); } result = BindObjectCreationForErrorRecovery(expr, diagnostics); } break; case BoundUnconvertedInterpolatedString unconvertedInterpolatedString: { result = BindUnconvertedInterpolatedStringToString(unconvertedInterpolatedString, diagnostics); } break; default: result = expression; break; } return result?.WithWasConverted(); } private BoundExpression BindToInferredDelegateType(BoundExpression expr, BindingDiagnosticBag diagnostics) { var syntax = expr.Syntax; CheckFeatureAvailability(syntax, MessageID.IDS_FeatureInferredDelegateType, diagnostics); CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); var delegateType = expr switch { UnboundLambda unboundLambda => unboundLambda.InferDelegateType(ref useSiteInfo), BoundMethodGroup methodGroup => GetMethodGroupDelegateType(methodGroup, ref useSiteInfo), _ => throw ExceptionUtilities.UnexpectedValue(expr), }; diagnostics.Add(syntax, useSiteInfo); if (delegateType is null) { diagnostics.Add(ErrorCode.ERR_CannotInferDelegateType, syntax.GetLocation()); delegateType = CreateErrorType(); } return GenerateConversionForAssignment(delegateType, expr, diagnostics); } internal BoundExpression BindValueAllowArgList(ExpressionSyntax node, BindingDiagnosticBag diagnostics, BindValueKind valueKind) { var result = this.BindExpressionAllowArgList(node, diagnostics: diagnostics); return CheckValue(result, valueKind, diagnostics); } internal BoundFieldEqualsValue BindFieldInitializer( FieldSymbol field, EqualsValueClauseSyntax initializerOpt, BindingDiagnosticBag diagnostics) { Debug.Assert((object)this.ContainingMemberOrLambda == field); if (initializerOpt == null) { return null; } Binder initializerBinder = this.GetBinder(initializerOpt); Debug.Assert(initializerBinder != null); BoundExpression result = initializerBinder.BindVariableOrAutoPropInitializerValue(initializerOpt, RefKind.None, field.GetFieldType(initializerBinder.FieldsBeingBound).Type, diagnostics); return new BoundFieldEqualsValue(initializerOpt, field, initializerBinder.GetDeclaredLocalsForScope(initializerOpt), result); } internal BoundExpression BindVariableOrAutoPropInitializerValue( EqualsValueClauseSyntax initializerOpt, RefKind refKind, TypeSymbol varType, BindingDiagnosticBag diagnostics) { if (initializerOpt == null) { return null; } BindValueKind valueKind; ExpressionSyntax value; IsInitializerRefKindValid(initializerOpt, initializerOpt, refKind, diagnostics, out valueKind, out value); BoundExpression initializer = BindPossibleArrayInitializer(value, varType, valueKind, diagnostics); initializer = GenerateConversionForAssignment(varType, initializer, diagnostics); return initializer; } internal Binder CreateBinderForParameterDefaultValue( ParameterSymbol parameter, EqualsValueClauseSyntax defaultValueSyntax) { var binder = new LocalScopeBinder(this.WithContainingMemberOrLambda(parameter.ContainingSymbol).WithAdditionalFlags(BinderFlags.ParameterDefaultValue)); return new ExecutableCodeBinder(defaultValueSyntax, parameter.ContainingSymbol, binder); } internal BoundParameterEqualsValue BindParameterDefaultValue( EqualsValueClauseSyntax defaultValueSyntax, ParameterSymbol parameter, BindingDiagnosticBag diagnostics, out BoundExpression valueBeforeConversion) { Debug.Assert(this.InParameterDefaultValue); Debug.Assert(this.ContainingMemberOrLambda.Kind == SymbolKind.Method || this.ContainingMemberOrLambda.Kind == SymbolKind.Property); // UNDONE: The binding and conversion has to be executed in a checked context. Binder defaultValueBinder = this.GetBinder(defaultValueSyntax); Debug.Assert(defaultValueBinder != null); valueBeforeConversion = defaultValueBinder.BindValue(defaultValueSyntax.Value, diagnostics, BindValueKind.RValue); // Always generate the conversion, even if the expression is not convertible to the given type. // We want the erroneous conversion in the tree. var result = new BoundParameterEqualsValue(defaultValueSyntax, parameter, defaultValueBinder.GetDeclaredLocalsForScope(defaultValueSyntax), defaultValueBinder.GenerateConversionForAssignment(parameter.Type, valueBeforeConversion, diagnostics, isDefaultParameter: true)); return result; } internal BoundFieldEqualsValue BindEnumConstantInitializer( SourceEnumConstantSymbol symbol, EqualsValueClauseSyntax equalsValueSyntax, BindingDiagnosticBag diagnostics) { Binder initializerBinder = this.GetBinder(equalsValueSyntax); Debug.Assert(initializerBinder != null); var initializer = initializerBinder.BindValue(equalsValueSyntax.Value, diagnostics, BindValueKind.RValue); initializer = initializerBinder.GenerateConversionForAssignment(symbol.ContainingType.EnumUnderlyingType, initializer, diagnostics); return new BoundFieldEqualsValue(equalsValueSyntax, symbol, initializerBinder.GetDeclaredLocalsForScope(equalsValueSyntax), initializer); } public BoundExpression BindExpression(ExpressionSyntax node, BindingDiagnosticBag diagnostics) { return BindExpression(node, diagnostics: diagnostics, invoked: false, indexed: false); } protected BoundExpression BindExpression(ExpressionSyntax node, BindingDiagnosticBag diagnostics, bool invoked, bool indexed) { BoundExpression expr = BindExpressionInternal(node, diagnostics, invoked, indexed); VerifyUnchecked(node, diagnostics, expr); if (expr.Kind == BoundKind.ArgListOperator) { // CS0226: An __arglist expression may only appear inside of a call or new expression Error(diagnostics, ErrorCode.ERR_IllegalArglist, node); expr = ToBadExpression(expr); } return expr; } // PERF: allowArgList is not a parameter because it is fairly uncommon case where arglists are allowed // so we do not want to pass that argument to every BindExpression which is often recursive // and extra arguments contribute to the stack size. protected BoundExpression BindExpressionAllowArgList(ExpressionSyntax node, BindingDiagnosticBag diagnostics) { BoundExpression expr = BindExpressionInternal(node, diagnostics, invoked: false, indexed: false); VerifyUnchecked(node, diagnostics, expr); return expr; } private void VerifyUnchecked(ExpressionSyntax node, BindingDiagnosticBag diagnostics, BoundExpression expr) { if (!expr.HasAnyErrors && !IsInsideNameof) { TypeSymbol exprType = expr.Type; if ((object)exprType != null && exprType.IsUnsafe()) { ReportUnsafeIfNotAllowed(node, diagnostics); //CONSIDER: Return a bad expression so that HasErrors is true? } } } private BoundExpression BindExpressionInternal(ExpressionSyntax node, BindingDiagnosticBag diagnostics, bool invoked, bool indexed) { if (IsEarlyAttributeBinder && !EarlyWellKnownAttributeBinder.CanBeValidAttributeArgument(node, this)) { return BadExpression(node, LookupResultKind.NotAValue); } Debug.Assert(node != null); switch (node.Kind()) { case SyntaxKind.AnonymousMethodExpression: case SyntaxKind.ParenthesizedLambdaExpression: case SyntaxKind.SimpleLambdaExpression: return BindAnonymousFunction((AnonymousFunctionExpressionSyntax)node, diagnostics); case SyntaxKind.ThisExpression: return BindThis((ThisExpressionSyntax)node, diagnostics); case SyntaxKind.BaseExpression: return BindBase((BaseExpressionSyntax)node, diagnostics); case SyntaxKind.InvocationExpression: return BindInvocationExpression((InvocationExpressionSyntax)node, diagnostics); case SyntaxKind.ArrayInitializerExpression: return BindUnexpectedArrayInitializer((InitializerExpressionSyntax)node, diagnostics, ErrorCode.ERR_ArrayInitInBadPlace); case SyntaxKind.ArrayCreationExpression: return BindArrayCreationExpression((ArrayCreationExpressionSyntax)node, diagnostics); case SyntaxKind.ImplicitArrayCreationExpression: return BindImplicitArrayCreationExpression((ImplicitArrayCreationExpressionSyntax)node, diagnostics); case SyntaxKind.StackAllocArrayCreationExpression: return BindStackAllocArrayCreationExpression((StackAllocArrayCreationExpressionSyntax)node, diagnostics); case SyntaxKind.ImplicitStackAllocArrayCreationExpression: return BindImplicitStackAllocArrayCreationExpression((ImplicitStackAllocArrayCreationExpressionSyntax)node, diagnostics); case SyntaxKind.ObjectCreationExpression: return BindObjectCreationExpression((ObjectCreationExpressionSyntax)node, diagnostics); case SyntaxKind.ImplicitObjectCreationExpression: return BindImplicitObjectCreationExpression((ImplicitObjectCreationExpressionSyntax)node, diagnostics); case SyntaxKind.IdentifierName: case SyntaxKind.GenericName: return BindIdentifier((SimpleNameSyntax)node, invoked, indexed, diagnostics); case SyntaxKind.SimpleMemberAccessExpression: case SyntaxKind.PointerMemberAccessExpression: return BindMemberAccess((MemberAccessExpressionSyntax)node, invoked, indexed, diagnostics: diagnostics); case SyntaxKind.SimpleAssignmentExpression: return BindAssignment((AssignmentExpressionSyntax)node, diagnostics); case SyntaxKind.CastExpression: return BindCast((CastExpressionSyntax)node, diagnostics); case SyntaxKind.ElementAccessExpression: return BindElementAccess((ElementAccessExpressionSyntax)node, diagnostics); case SyntaxKind.AddExpression: case SyntaxKind.MultiplyExpression: case SyntaxKind.SubtractExpression: case SyntaxKind.DivideExpression: case SyntaxKind.ModuloExpression: case SyntaxKind.EqualsExpression: case SyntaxKind.NotEqualsExpression: case SyntaxKind.GreaterThanExpression: case SyntaxKind.LessThanExpression: case SyntaxKind.GreaterThanOrEqualExpression: case SyntaxKind.LessThanOrEqualExpression: case SyntaxKind.BitwiseAndExpression: case SyntaxKind.BitwiseOrExpression: case SyntaxKind.ExclusiveOrExpression: case SyntaxKind.LeftShiftExpression: case SyntaxKind.RightShiftExpression: return BindSimpleBinaryOperator((BinaryExpressionSyntax)node, diagnostics); case SyntaxKind.LogicalAndExpression: case SyntaxKind.LogicalOrExpression: return BindConditionalLogicalOperator((BinaryExpressionSyntax)node, diagnostics); case SyntaxKind.CoalesceExpression: return BindNullCoalescingOperator((BinaryExpressionSyntax)node, diagnostics); case SyntaxKind.ConditionalAccessExpression: return BindConditionalAccessExpression((ConditionalAccessExpressionSyntax)node, diagnostics); case SyntaxKind.MemberBindingExpression: return BindMemberBindingExpression((MemberBindingExpressionSyntax)node, invoked, indexed, diagnostics); case SyntaxKind.ElementBindingExpression: return BindElementBindingExpression((ElementBindingExpressionSyntax)node, diagnostics); case SyntaxKind.IsExpression: return BindIsOperator((BinaryExpressionSyntax)node, diagnostics); case SyntaxKind.AsExpression: return BindAsOperator((BinaryExpressionSyntax)node, diagnostics); case SyntaxKind.UnaryPlusExpression: case SyntaxKind.UnaryMinusExpression: case SyntaxKind.LogicalNotExpression: case SyntaxKind.BitwiseNotExpression: return BindUnaryOperator((PrefixUnaryExpressionSyntax)node, diagnostics); case SyntaxKind.IndexExpression: return BindFromEndIndexExpression((PrefixUnaryExpressionSyntax)node, diagnostics); case SyntaxKind.RangeExpression: return BindRangeExpression((RangeExpressionSyntax)node, diagnostics); case SyntaxKind.AddressOfExpression: return BindAddressOfExpression((PrefixUnaryExpressionSyntax)node, diagnostics); case SyntaxKind.PointerIndirectionExpression: return BindPointerIndirectionExpression((PrefixUnaryExpressionSyntax)node, diagnostics); case SyntaxKind.PostIncrementExpression: case SyntaxKind.PostDecrementExpression: return BindIncrementOperator(node, ((PostfixUnaryExpressionSyntax)node).Operand, ((PostfixUnaryExpressionSyntax)node).OperatorToken, diagnostics); case SyntaxKind.PreIncrementExpression: case SyntaxKind.PreDecrementExpression: return BindIncrementOperator(node, ((PrefixUnaryExpressionSyntax)node).Operand, ((PrefixUnaryExpressionSyntax)node).OperatorToken, diagnostics); case SyntaxKind.ConditionalExpression: return BindConditionalOperator((ConditionalExpressionSyntax)node, diagnostics); case SyntaxKind.SwitchExpression: return BindSwitchExpression((SwitchExpressionSyntax)node, diagnostics); case SyntaxKind.NumericLiteralExpression: case SyntaxKind.StringLiteralExpression: case SyntaxKind.CharacterLiteralExpression: case SyntaxKind.TrueLiteralExpression: case SyntaxKind.FalseLiteralExpression: case SyntaxKind.NullLiteralExpression: return BindLiteralConstant((LiteralExpressionSyntax)node, diagnostics); case SyntaxKind.DefaultLiteralExpression: return new BoundDefaultLiteral(node); case SyntaxKind.ParenthesizedExpression: // Parenthesis tokens are ignored, and operand is bound in the context of parent // expression. return BindParenthesizedExpression(((ParenthesizedExpressionSyntax)node).Expression, diagnostics); case SyntaxKind.UncheckedExpression: case SyntaxKind.CheckedExpression: return BindCheckedExpression((CheckedExpressionSyntax)node, diagnostics); case SyntaxKind.DefaultExpression: return BindDefaultExpression((DefaultExpressionSyntax)node, diagnostics); case SyntaxKind.TypeOfExpression: return BindTypeOf((TypeOfExpressionSyntax)node, diagnostics); case SyntaxKind.SizeOfExpression: return BindSizeOf((SizeOfExpressionSyntax)node, diagnostics); case SyntaxKind.AddAssignmentExpression: case SyntaxKind.AndAssignmentExpression: case SyntaxKind.DivideAssignmentExpression: case SyntaxKind.ExclusiveOrAssignmentExpression: case SyntaxKind.LeftShiftAssignmentExpression: case SyntaxKind.ModuloAssignmentExpression: case SyntaxKind.MultiplyAssignmentExpression: case SyntaxKind.OrAssignmentExpression: case SyntaxKind.RightShiftAssignmentExpression: case SyntaxKind.SubtractAssignmentExpression: return BindCompoundAssignment((AssignmentExpressionSyntax)node, diagnostics); case SyntaxKind.CoalesceAssignmentExpression: return BindNullCoalescingAssignmentOperator((AssignmentExpressionSyntax)node, diagnostics); case SyntaxKind.AliasQualifiedName: case SyntaxKind.PredefinedType: return this.BindNamespaceOrType(node, diagnostics); case SyntaxKind.QueryExpression: return this.BindQuery((QueryExpressionSyntax)node, diagnostics); case SyntaxKind.AnonymousObjectCreationExpression: return BindAnonymousObjectCreation((AnonymousObjectCreationExpressionSyntax)node, diagnostics); case SyntaxKind.QualifiedName: return BindQualifiedName((QualifiedNameSyntax)node, diagnostics); case SyntaxKind.ComplexElementInitializerExpression: return BindUnexpectedComplexElementInitializer((InitializerExpressionSyntax)node, diagnostics); case SyntaxKind.ArgListExpression: return BindArgList(node, diagnostics); case SyntaxKind.RefTypeExpression: return BindRefType((RefTypeExpressionSyntax)node, diagnostics); case SyntaxKind.MakeRefExpression: return BindMakeRef((MakeRefExpressionSyntax)node, diagnostics); case SyntaxKind.RefValueExpression: return BindRefValue((RefValueExpressionSyntax)node, diagnostics); case SyntaxKind.AwaitExpression: return BindAwait((AwaitExpressionSyntax)node, diagnostics); case SyntaxKind.OmittedArraySizeExpression: case SyntaxKind.OmittedTypeArgument: case SyntaxKind.ObjectInitializerExpression: // Not reachable during method body binding, but // may be used by SemanticModel for error cases. return BadExpression(node); case SyntaxKind.NullableType: // Not reachable during method body binding, but // may be used by SemanticModel for error cases. // NOTE: This happens when there's a problem with the Nullable<T> type (e.g. it's missing). // There is no corresponding problem for array or pointer types (which seem analogous), since // they are not constructed types; the element type can be an error type, but the array/pointer // type cannot. return BadExpression(node); case SyntaxKind.InterpolatedStringExpression: return BindInterpolatedString((InterpolatedStringExpressionSyntax)node, diagnostics); case SyntaxKind.IsPatternExpression: return BindIsPatternExpression((IsPatternExpressionSyntax)node, diagnostics); case SyntaxKind.TupleExpression: return BindTupleExpression((TupleExpressionSyntax)node, diagnostics); case SyntaxKind.ThrowExpression: return BindThrowExpression((ThrowExpressionSyntax)node, diagnostics); case SyntaxKind.RefType: return BindRefType(node, diagnostics); case SyntaxKind.RefExpression: return BindRefExpression(node, diagnostics); case SyntaxKind.DeclarationExpression: return BindDeclarationExpressionAsError((DeclarationExpressionSyntax)node, diagnostics); case SyntaxKind.SuppressNullableWarningExpression: return BindSuppressNullableWarningExpression((PostfixUnaryExpressionSyntax)node, diagnostics); case SyntaxKind.WithExpression: return BindWithExpression((WithExpressionSyntax)node, diagnostics); 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. Debug.Assert(false, "Unexpected SyntaxKind " + node.Kind()); diagnostics.Add(ErrorCode.ERR_InternalError, node.Location); return BadExpression(node); } } #nullable enable internal virtual BoundSwitchExpressionArm BindSwitchExpressionArm(SwitchExpressionArmSyntax node, TypeSymbol switchGoverningType, uint switchGoverningValEscape, BindingDiagnosticBag diagnostics) { return this.NextRequired.BindSwitchExpressionArm(node, switchGoverningType, switchGoverningValEscape, diagnostics); } #nullable disable private BoundExpression BindRefExpression(ExpressionSyntax node, BindingDiagnosticBag diagnostics) { var firstToken = node.GetFirstToken(); diagnostics.Add(ErrorCode.ERR_UnexpectedToken, firstToken.GetLocation(), firstToken.ValueText); return new BoundBadExpression( node, LookupResultKind.Empty, ImmutableArray<Symbol>.Empty, ImmutableArray<BoundExpression>.Empty, CreateErrorType("ref")); } private BoundExpression BindRefType(ExpressionSyntax node, BindingDiagnosticBag diagnostics) { var firstToken = node.GetFirstToken(); diagnostics.Add(ErrorCode.ERR_UnexpectedToken, firstToken.GetLocation(), firstToken.ValueText); return new BoundTypeExpression(node, null, CreateErrorType("ref")); } private BoundExpression BindThrowExpression(ThrowExpressionSyntax node, BindingDiagnosticBag diagnostics) { bool hasErrors = node.HasErrors; if (!IsThrowExpressionInProperContext(node)) { diagnostics.Add(ErrorCode.ERR_ThrowMisplaced, node.ThrowKeyword.GetLocation()); hasErrors = true; } var thrownExpression = BindThrownExpression(node.Expression, diagnostics, ref hasErrors); return new BoundThrowExpression(node, thrownExpression, null, hasErrors); } private static bool IsThrowExpressionInProperContext(ThrowExpressionSyntax node) { var parent = node.Parent; if (parent == null || node.HasErrors) { return true; } switch (parent.Kind()) { case SyntaxKind.ConditionalExpression: // ?: { var conditionalParent = (ConditionalExpressionSyntax)parent; return node == conditionalParent.WhenTrue || node == conditionalParent.WhenFalse; } case SyntaxKind.CoalesceExpression: // ?? { var binaryParent = (BinaryExpressionSyntax)parent; return node == binaryParent.Right; } case SyntaxKind.SwitchExpressionArm: case SyntaxKind.ArrowExpressionClause: case SyntaxKind.ParenthesizedLambdaExpression: case SyntaxKind.SimpleLambdaExpression: return true; // We do not support && and || because // 1. The precedence would not syntactically allow it // 2. It isn't clear what the semantics should be // 3. It isn't clear what use cases would motivate us to change the precedence to support it default: return false; } } // Bind a declaration expression where it isn't permitted. private BoundExpression BindDeclarationExpressionAsError(DeclarationExpressionSyntax node, BindingDiagnosticBag diagnostics) { // This is an error, as declaration expressions are handled specially in every context in which // they are permitted. So we have a context in which they are *not* permitted. Nevertheless, we // bind it and then give one nice message. bool isVar; bool isConst = false; AliasSymbol alias; var declType = BindVariableTypeWithAnnotations(node.Designation, diagnostics, node.Type, ref isConst, out isVar, out alias); Error(diagnostics, ErrorCode.ERR_DeclarationExpressionNotPermitted, node); return BindDeclarationVariablesForErrorRecovery(declType, node.Designation, node, diagnostics); } /// <summary> /// Bind a declaration variable where it isn't permitted. The caller is expected to produce a diagnostic. /// </summary> private BoundExpression BindDeclarationVariablesForErrorRecovery(TypeWithAnnotations declTypeWithAnnotations, VariableDesignationSyntax node, CSharpSyntaxNode syntax, BindingDiagnosticBag diagnostics) { declTypeWithAnnotations = declTypeWithAnnotations.HasType ? declTypeWithAnnotations : TypeWithAnnotations.Create(CreateErrorType("var")); switch (node.Kind()) { case SyntaxKind.SingleVariableDesignation: { var single = (SingleVariableDesignationSyntax)node; var result = BindDeconstructionVariable(declTypeWithAnnotations, single, syntax, diagnostics); return BindToTypeForErrorRecovery(result); } case SyntaxKind.DiscardDesignation: { return BindDiscardExpression(syntax, declTypeWithAnnotations); } case SyntaxKind.ParenthesizedVariableDesignation: { var tuple = (ParenthesizedVariableDesignationSyntax)node; int count = tuple.Variables.Count; var builder = ArrayBuilder<BoundExpression>.GetInstance(count); var namesBuilder = ArrayBuilder<string>.GetInstance(count); foreach (var n in tuple.Variables) { builder.Add(BindDeclarationVariablesForErrorRecovery(declTypeWithAnnotations, n, n, diagnostics)); namesBuilder.Add(InferTupleElementName(n)); } ImmutableArray<BoundExpression> subExpressions = builder.ToImmutableAndFree(); var uniqueFieldNames = PooledHashSet<string>.GetInstance(); RemoveDuplicateInferredTupleNamesAndFreeIfEmptied(ref namesBuilder, uniqueFieldNames); uniqueFieldNames.Free(); ImmutableArray<string> tupleNames = namesBuilder is null ? default : namesBuilder.ToImmutableAndFree(); ImmutableArray<bool> inferredPositions = tupleNames.IsDefault ? default : tupleNames.SelectAsArray(n => n != null); bool disallowInferredNames = this.Compilation.LanguageVersion.DisallowInferredTupleElementNames(); // We will not check constraints at this point as this code path // is failure-only and the caller is expected to produce a diagnostic. var tupleType = NamedTypeSymbol.CreateTuple( locationOpt: null, subExpressions.SelectAsArray(e => TypeWithAnnotations.Create(e.Type)), elementLocations: default, tupleNames, Compilation, shouldCheckConstraints: false, includeNullability: false, errorPositions: disallowInferredNames ? inferredPositions : default); return new BoundConvertedTupleLiteral(syntax, sourceTuple: null, wasTargetTyped: true, subExpressions, tupleNames, inferredPositions, tupleType); } default: throw ExceptionUtilities.UnexpectedValue(node.Kind()); } } private BoundExpression BindTupleExpression(TupleExpressionSyntax node, BindingDiagnosticBag diagnostics) { SeparatedSyntaxList<ArgumentSyntax> arguments = node.Arguments; int numElements = arguments.Count; if (numElements < 2) { // this should be a parse error already. var args = numElements == 1 ? ImmutableArray.Create(BindValue(arguments[0].Expression, diagnostics, BindValueKind.RValue)) : ImmutableArray<BoundExpression>.Empty; return BadExpression(node, args); } bool hasNaturalType = true; var boundArguments = ArrayBuilder<BoundExpression>.GetInstance(arguments.Count); var elementTypesWithAnnotations = ArrayBuilder<TypeWithAnnotations>.GetInstance(arguments.Count); var elementLocations = ArrayBuilder<Location>.GetInstance(arguments.Count); // prepare names var (elementNames, inferredPositions, hasErrors) = ExtractTupleElementNames(arguments, diagnostics); // prepare types and locations for (int i = 0; i < numElements; i++) { ArgumentSyntax argumentSyntax = arguments[i]; IdentifierNameSyntax nameSyntax = argumentSyntax.NameColon?.Name; if (nameSyntax != null) { elementLocations.Add(nameSyntax.Location); } else { elementLocations.Add(argumentSyntax.Location); } BoundExpression boundArgument = BindValue(argumentSyntax.Expression, diagnostics, BindValueKind.RValue); if (boundArgument.Type?.SpecialType == SpecialType.System_Void) { diagnostics.Add(ErrorCode.ERR_VoidInTuple, argumentSyntax.Location); boundArgument = new BoundBadExpression( argumentSyntax, LookupResultKind.Empty, ImmutableArray<Symbol>.Empty, ImmutableArray.Create<BoundExpression>(boundArgument), CreateErrorType("void")); } boundArguments.Add(boundArgument); var elementTypeWithAnnotations = TypeWithAnnotations.Create(boundArgument.Type); elementTypesWithAnnotations.Add(elementTypeWithAnnotations); if (!elementTypeWithAnnotations.HasType) { hasNaturalType = false; } } NamedTypeSymbol tupleTypeOpt = null; var elements = elementTypesWithAnnotations.ToImmutableAndFree(); var locations = elementLocations.ToImmutableAndFree(); if (hasNaturalType) { bool disallowInferredNames = this.Compilation.LanguageVersion.DisallowInferredTupleElementNames(); tupleTypeOpt = NamedTypeSymbol.CreateTuple(node.Location, elements, locations, elementNames, this.Compilation, syntax: node, diagnostics: diagnostics, shouldCheckConstraints: true, includeNullability: false, errorPositions: disallowInferredNames ? inferredPositions : default(ImmutableArray<bool>)); } else { NamedTypeSymbol.VerifyTupleTypePresent(elements.Length, node, this.Compilation, diagnostics); } // Always track the inferred positions in the bound node, so that conversions don't produce a warning // for "dropped names" on tuple literal when the name was inferred. return new BoundTupleLiteral(node, boundArguments.ToImmutableAndFree(), elementNames, inferredPositions, tupleTypeOpt, hasErrors); } private static (ImmutableArray<string> elementNamesArray, ImmutableArray<bool> inferredArray, bool hasErrors) ExtractTupleElementNames( SeparatedSyntaxList<ArgumentSyntax> arguments, BindingDiagnosticBag diagnostics) { bool hasErrors = false; int numElements = arguments.Count; var uniqueFieldNames = PooledHashSet<string>.GetInstance(); ArrayBuilder<string> elementNames = null; ArrayBuilder<string> inferredElementNames = null; for (int i = 0; i < numElements; i++) { ArgumentSyntax argumentSyntax = arguments[i]; IdentifierNameSyntax nameSyntax = argumentSyntax.NameColon?.Name; string name = null; string inferredName = null; if (nameSyntax != null) { name = nameSyntax.Identifier.ValueText; if (diagnostics != null && !CheckTupleMemberName(name, i, argumentSyntax.NameColon.Name, diagnostics, uniqueFieldNames)) { hasErrors = true; } } else { inferredName = InferTupleElementName(argumentSyntax.Expression); } CollectTupleFieldMemberName(name, i, numElements, ref elementNames); CollectTupleFieldMemberName(inferredName, i, numElements, ref inferredElementNames); } RemoveDuplicateInferredTupleNamesAndFreeIfEmptied(ref inferredElementNames, uniqueFieldNames); uniqueFieldNames.Free(); var result = MergeTupleElementNames(elementNames, inferredElementNames); elementNames?.Free(); inferredElementNames?.Free(); return (result.names, result.inferred, hasErrors); } private static (ImmutableArray<string> names, ImmutableArray<bool> inferred) MergeTupleElementNames( ArrayBuilder<string> elementNames, ArrayBuilder<string> inferredElementNames) { if (elementNames == null) { if (inferredElementNames == null) { return (default(ImmutableArray<string>), default(ImmutableArray<bool>)); } else { var finalNames = inferredElementNames.ToImmutable(); return (finalNames, finalNames.SelectAsArray(n => n != null)); } } if (inferredElementNames == null) { return (elementNames.ToImmutable(), default(ImmutableArray<bool>)); } Debug.Assert(elementNames.Count == inferredElementNames.Count); var builder = ArrayBuilder<bool>.GetInstance(elementNames.Count); for (int i = 0; i < elementNames.Count; i++) { string inferredName = inferredElementNames[i]; if (elementNames[i] == null && inferredName != null) { elementNames[i] = inferredName; builder.Add(true); } else { builder.Add(false); } } return (elementNames.ToImmutable(), builder.ToImmutableAndFree()); } /// <summary> /// Removes duplicate entries in <paramref name="inferredElementNames"/> and frees it if only nulls remain. /// </summary> private static void RemoveDuplicateInferredTupleNamesAndFreeIfEmptied(ref ArrayBuilder<string> inferredElementNames, HashSet<string> uniqueFieldNames) { if (inferredElementNames == null) { return; } // Inferred names that duplicate an explicit name or a previous inferred name are tagged for removal var toRemove = PooledHashSet<string>.GetInstance(); foreach (var name in inferredElementNames) { if (name != null && !uniqueFieldNames.Add(name)) { toRemove.Add(name); } } for (int i = 0; i < inferredElementNames.Count; i++) { var inferredName = inferredElementNames[i]; if (inferredName != null && toRemove.Contains(inferredName)) { inferredElementNames[i] = null; } } toRemove.Free(); if (inferredElementNames.All(n => n is null)) { inferredElementNames.Free(); inferredElementNames = null; } } private static string InferTupleElementName(SyntaxNode syntax) { string name = syntax.TryGetInferredMemberName(); // Reserved names are never candidates to be inferred names, at any position if (name == null || NamedTypeSymbol.IsTupleElementNameReserved(name) != -1) { return null; } return name; } private BoundExpression BindRefValue(RefValueExpressionSyntax node, BindingDiagnosticBag diagnostics) { // __refvalue(tr, T) requires that tr be a TypedReference and T be a type. // The result is a *variable* of type T. BoundExpression argument = BindValue(node.Expression, diagnostics, BindValueKind.RValue); bool hasErrors = argument.HasAnyErrors; TypeSymbol typedReferenceType = this.Compilation.GetSpecialType(SpecialType.System_TypedReference); CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); Conversion conversion = this.Conversions.ClassifyConversionFromExpression(argument, typedReferenceType, ref useSiteInfo); diagnostics.Add(node, useSiteInfo); if (!conversion.IsImplicit || !conversion.IsValid) { hasErrors = true; GenerateImplicitConversionError(diagnostics, node, conversion, argument, typedReferenceType); } argument = CreateConversion(argument, conversion, typedReferenceType, diagnostics); TypeWithAnnotations typeWithAnnotations = BindType(node.Type, diagnostics); return new BoundRefValueOperator(node, typeWithAnnotations.NullableAnnotation, argument, typeWithAnnotations.Type, hasErrors); } private BoundExpression BindMakeRef(MakeRefExpressionSyntax node, BindingDiagnosticBag diagnostics) { // __makeref(x) requires that x be a variable, and not be of a restricted type. BoundExpression argument = this.BindValue(node.Expression, diagnostics, BindValueKind.RefOrOut); bool hasErrors = argument.HasAnyErrors; TypeSymbol typedReferenceType = GetSpecialType(SpecialType.System_TypedReference, diagnostics, node); if ((object)argument.Type != null && argument.Type.IsRestrictedType()) { // CS1601: Cannot make reference to variable of type '{0}' Error(diagnostics, ErrorCode.ERR_MethodArgCantBeRefAny, node, argument.Type); hasErrors = true; } // UNDONE: We do not yet implement warnings anywhere for: // UNDONE: * taking a ref to a volatile field // UNDONE: * taking a ref to a "non-agile" field // UNDONE: We should do so here when we implement this feature for regular out/ref parameters. return new BoundMakeRefOperator(node, argument, typedReferenceType, hasErrors); } private BoundExpression BindRefType(RefTypeExpressionSyntax node, BindingDiagnosticBag diagnostics) { // __reftype(x) requires that x be implicitly convertible to TypedReference. BoundExpression argument = BindValue(node.Expression, diagnostics, BindValueKind.RValue); bool hasErrors = argument.HasAnyErrors; TypeSymbol typedReferenceType = this.Compilation.GetSpecialType(SpecialType.System_TypedReference); TypeSymbol typeType = this.GetWellKnownType(WellKnownType.System_Type, diagnostics, node); CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); Conversion conversion = this.Conversions.ClassifyConversionFromExpression(argument, typedReferenceType, ref useSiteInfo); diagnostics.Add(node, useSiteInfo); if (!conversion.IsImplicit || !conversion.IsValid) { hasErrors = true; GenerateImplicitConversionError(diagnostics, node, conversion, argument, typedReferenceType); } argument = CreateConversion(argument, conversion, typedReferenceType, diagnostics); return new BoundRefTypeOperator(node, argument, null, typeType, hasErrors); } private BoundExpression BindArgList(CSharpSyntaxNode node, BindingDiagnosticBag diagnostics) { // There are two forms of __arglist expression. In a method with an __arglist parameter, // it is legal to use __arglist as an expression of type RuntimeArgumentHandle. In // a call to such a method, it is legal to use __arglist(x, y, z) as the final argument. // This method only handles the first usage; the second usage is parsed as a call syntax. // The native compiler allows __arglist in a lambda: // // class C // { // delegate int D(RuntimeArgumentHandle r); // static void M(__arglist) // { // D f = null; // f = r=>f(__arglist); // } // } // // This is clearly wrong. Either the developer intends __arglist to refer to the // arg list of the *lambda*, or to the arg list of *M*. The former makes no sense; // lambdas cannot have an arg list. The latter we have no way to generate code for; // you cannot hoist the arg list to a field of a closure class. // // The native compiler allows this and generates code as though the developer // was attempting to access the arg list of the lambda! We should simply disallow it. TypeSymbol runtimeArgumentHandleType = GetSpecialType(SpecialType.System_RuntimeArgumentHandle, diagnostics, node); MethodSymbol method = this.ContainingMember() as MethodSymbol; bool hasError = false; if ((object)method == null || !method.IsVararg) { // CS0190: The __arglist construct is valid only within a variable argument method Error(diagnostics, ErrorCode.ERR_ArgsInvalid, node); hasError = true; } else { // We're in a varargs method; are we also inside a lambda? Symbol container = this.ContainingMemberOrLambda; if (container != method) { // We also need to report this any time a local variable of a restricted type // would be hoisted into a closure for an anonymous function, iterator or async method. // We do that during the actual rewrites. // CS4013: Instance of type '{0}' cannot be used inside an anonymous function, query expression, iterator block or async method Error(diagnostics, ErrorCode.ERR_SpecialByRefInLambda, node, runtimeArgumentHandleType); hasError = true; } } return new BoundArgList(node, runtimeArgumentHandleType, hasError); } /// <summary> /// This can be reached for the qualified name on the right-hand-side of an `is` operator. /// For compatibility we parse it as a qualified name, as the is-type expression only permitted /// a type on the right-hand-side in C# 6. But the same syntax now, in C# 7 and later, can /// refer to a constant, which would normally be represented as a *simple member access expression*. /// Since the parser cannot distinguish, it parses it as before and depends on the binder /// to handle a qualified name appearing as an expression. /// </summary> private BoundExpression BindQualifiedName(QualifiedNameSyntax node, BindingDiagnosticBag diagnostics) { return BindMemberAccessWithBoundLeft(node, this.BindLeftOfPotentialColorColorMemberAccess(node.Left, diagnostics), node.Right, node.DotToken, invoked: false, indexed: false, diagnostics: diagnostics); } private BoundExpression BindParenthesizedExpression(ExpressionSyntax innerExpression, BindingDiagnosticBag diagnostics) { var result = BindExpression(innerExpression, diagnostics); // A parenthesized expression may not be a namespace or a type. If it is a parenthesized // namespace or type then report the error but let it go; we'll just ignore the // parenthesis and keep on trucking. CheckNotNamespaceOrType(result, diagnostics); return result; } #nullable enable private BoundExpression BindTypeOf(TypeOfExpressionSyntax node, BindingDiagnosticBag diagnostics) { ExpressionSyntax typeSyntax = node.Type; TypeofBinder typeofBinder = new TypeofBinder(typeSyntax, this); //has special handling for unbound types AliasSymbol alias; TypeWithAnnotations typeWithAnnotations = typeofBinder.BindType(typeSyntax, diagnostics, out alias); TypeSymbol type = typeWithAnnotations.Type; bool hasError = false; // NB: Dev10 has an error for typeof(dynamic), but allows typeof(dynamic[]), // typeof(C<dynamic>), etc. if (type.IsDynamic()) { diagnostics.Add(ErrorCode.ERR_BadDynamicTypeof, node.Location); hasError = true; } else if (typeWithAnnotations.NullableAnnotation.IsAnnotated() && type.IsReferenceType) { // error: cannot take the `typeof` a nullable reference type. diagnostics.Add(ErrorCode.ERR_BadNullableTypeof, node.Location); hasError = true; } else if (this.InAttributeArgument && type.ContainsFunctionPointer()) { // https://github.com/dotnet/roslyn/issues/48765 tracks removing this error and properly supporting function // pointers in attribute types. Until then, we don't know how serialize them, so error instead of crashing // during emit. diagnostics.Add(ErrorCode.ERR_FunctionPointerTypesInAttributeNotSupported, node.Location); hasError = true; } BoundTypeExpression boundType = new BoundTypeExpression(typeSyntax, alias, typeWithAnnotations, type.IsErrorType()); return new BoundTypeOfOperator(node, boundType, null, this.GetWellKnownType(WellKnownType.System_Type, diagnostics, node), hasError); } private BoundExpression BindSizeOf(SizeOfExpressionSyntax node, BindingDiagnosticBag diagnostics) { ExpressionSyntax typeSyntax = node.Type; AliasSymbol alias; TypeWithAnnotations typeWithAnnotations = this.BindType(typeSyntax, diagnostics, out alias); TypeSymbol type = typeWithAnnotations.Type; bool typeHasErrors = type.IsErrorType() || CheckManagedAddr(Compilation, type, node.Location, diagnostics); BoundTypeExpression boundType = new BoundTypeExpression(typeSyntax, alias, typeWithAnnotations, typeHasErrors); ConstantValue constantValue = GetConstantSizeOf(type); bool hasErrors = constantValue is null && ReportUnsafeIfNotAllowed(node, diagnostics, type); return new BoundSizeOfOperator(node, boundType, constantValue, this.GetSpecialType(SpecialType.System_Int32, diagnostics, node), hasErrors); } /// <returns>true if managed type-related errors were found, otherwise false.</returns> internal static bool CheckManagedAddr(CSharpCompilation compilation, TypeSymbol type, Location location, BindingDiagnosticBag diagnostics) { var useSiteInfo = new CompoundUseSiteInfo<AssemblySymbol>(diagnostics, compilation.Assembly); var managedKind = type.GetManagedKind(ref useSiteInfo); diagnostics.Add(location, useSiteInfo); return CheckManagedAddr(compilation, type, managedKind, location, diagnostics); } /// <returns>true if managed type-related errors were found, otherwise false.</returns> internal static bool CheckManagedAddr(CSharpCompilation compilation, TypeSymbol type, ManagedKind managedKind, Location location, BindingDiagnosticBag diagnostics) { switch (managedKind) { case ManagedKind.Managed: diagnostics.Add(ErrorCode.ERR_ManagedAddr, location, type); return true; case ManagedKind.UnmanagedWithGenerics when MessageID.IDS_FeatureUnmanagedConstructedTypes.GetFeatureAvailabilityDiagnosticInfo(compilation) is CSDiagnosticInfo diagnosticInfo: diagnostics.Add(diagnosticInfo, location); return true; case ManagedKind.Unknown: throw ExceptionUtilities.UnexpectedValue(managedKind); default: return false; } } #nullable disable internal static ConstantValue GetConstantSizeOf(TypeSymbol type) { return ConstantValue.CreateSizeOf((type.GetEnumUnderlyingType() ?? type).SpecialType); } private BoundExpression BindDefaultExpression(DefaultExpressionSyntax node, BindingDiagnosticBag diagnostics) { TypeWithAnnotations typeWithAnnotations = this.BindType(node.Type, diagnostics, out AliasSymbol alias); var typeExpression = new BoundTypeExpression(node.Type, aliasOpt: alias, typeWithAnnotations); TypeSymbol type = typeWithAnnotations.Type; return new BoundDefaultExpression(node, typeExpression, constantValueOpt: type.GetDefaultValue(), type); } /// <summary> /// Binds a simple identifier. /// </summary> private BoundExpression BindIdentifier( SimpleNameSyntax node, bool invoked, bool indexed, BindingDiagnosticBag diagnostics) { Debug.Assert(node != null); // If the syntax tree is ill-formed and the identifier is missing then we've already // given a parse error. Just return an error local and continue with analysis. if (node.IsMissing) { return BadExpression(node); } // A simple-name is either of the form I or of the form I<A1, ..., AK>, where I is a // single identifier and <A1, ..., AK> is an optional type-argument-list. When no // type-argument-list is specified, consider K to be zero. The simple-name is evaluated // and classified as follows: // If K is zero and the simple-name appears within a block and if the block's (or an // enclosing block's) local variable declaration space contains a local variable, // parameter or constant with name I, then the simple-name refers to that local // variable, parameter or constant and is classified as a variable or value. // If K is zero and the simple-name appears within the body of a generic method // declaration and if that declaration includes a type parameter with name I, then the // simple-name refers to that type parameter. BoundExpression expression; // It's possible that the argument list is malformed; if so, do not attempt to bind it; // just use the null array. int arity = node.Arity; bool hasTypeArguments = arity > 0; SeparatedSyntaxList<TypeSyntax> typeArgumentList = node.Kind() == SyntaxKind.GenericName ? ((GenericNameSyntax)node).TypeArgumentList.Arguments : default(SeparatedSyntaxList<TypeSyntax>); Debug.Assert(arity == typeArgumentList.Count); var typeArgumentsWithAnnotations = hasTypeArguments ? BindTypeArguments(typeArgumentList, diagnostics) : default(ImmutableArray<TypeWithAnnotations>); var lookupResult = LookupResult.GetInstance(); LookupOptions options = LookupOptions.AllMethodsOnArityZero; if (invoked) { options |= LookupOptions.MustBeInvocableIfMember; } if (!IsInMethodBody && !IsInsideNameof) { Debug.Assert((options & LookupOptions.NamespacesOrTypesOnly) == 0); options |= LookupOptions.MustNotBeMethodTypeParameter; } var name = node.Identifier.ValueText; CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); this.LookupSymbolsWithFallback(lookupResult, name, arity: arity, useSiteInfo: ref useSiteInfo, options: options); diagnostics.Add(node, useSiteInfo); if (lookupResult.Kind != LookupResultKind.Empty) { // have we detected an error with the current node? bool isError; var members = ArrayBuilder<Symbol>.GetInstance(); Symbol symbol = GetSymbolOrMethodOrPropertyGroup(lookupResult, node, name, node.Arity, members, diagnostics, out isError, qualifierOpt: null); // reports diagnostics in result. if ((object)symbol == null) { Debug.Assert(members.Count > 0); var receiver = SynthesizeMethodGroupReceiver(node, members); expression = ConstructBoundMemberGroupAndReportOmittedTypeArguments( node, typeArgumentList, typeArgumentsWithAnnotations, receiver, name, members, lookupResult, receiver != null ? BoundMethodGroupFlags.HasImplicitReceiver : BoundMethodGroupFlags.None, isError, diagnostics); ReportSimpleProgramLocalReferencedOutsideOfTopLevelStatement(node, members[0], diagnostics); } else { bool isNamedType = (symbol.Kind == SymbolKind.NamedType) || (symbol.Kind == SymbolKind.ErrorType); if (hasTypeArguments && isNamedType) { symbol = ConstructNamedTypeUnlessTypeArgumentOmitted(node, (NamedTypeSymbol)symbol, typeArgumentList, typeArgumentsWithAnnotations, diagnostics); } expression = BindNonMethod(node, symbol, diagnostics, lookupResult.Kind, indexed, isError); if (!isNamedType && (hasTypeArguments || node.Kind() == SyntaxKind.GenericName)) { Debug.Assert(isError); // Should have been reported by GetSymbolOrMethodOrPropertyGroup. expression = new BoundBadExpression( syntax: node, resultKind: LookupResultKind.WrongArity, symbols: ImmutableArray.Create(symbol), childBoundNodes: ImmutableArray.Create(BindToTypeForErrorRecovery(expression)), type: expression.Type, hasErrors: isError); } } members.Free(); } else { expression = null; if (node is IdentifierNameSyntax identifier) { var type = BindNativeIntegerSymbolIfAny(identifier, diagnostics); if (type is { }) { expression = new BoundTypeExpression(node, null, type); } else if (FallBackOnDiscard(identifier, diagnostics)) { expression = new BoundDiscardExpression(node, type: null); } } // Otherwise, the simple-name is undefined and a compile-time error occurs. if (expression is null) { expression = BadExpression(node); if (lookupResult.Error != null) { Error(diagnostics, lookupResult.Error, node); } else if (IsJoinRangeVariableInLeftKey(node)) { Error(diagnostics, ErrorCode.ERR_QueryOuterKey, node, name); } else if (IsInJoinRightKey(node)) { Error(diagnostics, ErrorCode.ERR_QueryInnerKey, node, name); } else { Error(diagnostics, ErrorCode.ERR_NameNotInContext, node, name); } } } lookupResult.Free(); return expression; } /// <summary> /// Is this is an _ identifier in a context where discards are allowed? /// </summary> private static bool FallBackOnDiscard(IdentifierNameSyntax node, BindingDiagnosticBag diagnostics) { if (!node.Identifier.IsUnderscoreToken()) { return false; } CSharpSyntaxNode containingDeconstruction = node.GetContainingDeconstruction(); bool isDiscard = containingDeconstruction != null || IsOutVarDiscardIdentifier(node); if (isDiscard) { CheckFeatureAvailability(node, MessageID.IDS_FeatureDiscards, diagnostics); } return isDiscard; } private static bool IsOutVarDiscardIdentifier(SimpleNameSyntax node) { Debug.Assert(node.Identifier.IsUnderscoreToken()); CSharpSyntaxNode parent = node.Parent; return (parent?.Kind() == SyntaxKind.Argument && ((ArgumentSyntax)parent).RefOrOutKeyword.Kind() == SyntaxKind.OutKeyword); } private BoundExpression SynthesizeMethodGroupReceiver(CSharpSyntaxNode syntax, ArrayBuilder<Symbol> members) { // SPEC: For each instance type T starting with the instance type of the immediately // SPEC: enclosing type declaration, and continuing with the instance type of each // SPEC: enclosing class or struct declaration, [do a lot of things to find a match]. // SPEC: ... // SPEC: If T is the instance type of the immediately enclosing class or struct type // SPEC: and the lookup identifies one or more methods, the result is a method group // SPEC: with an associated instance expression of this. // Explanation of spec: // // We are looping over a set of types, from inner to outer, attempting to resolve the // meaning of a simple name; for example "M(123)". // // There are a number of possibilities: // // If the lookup finds M in an outer class: // // class Outer { // static void M(int x) {} // class Inner { // void X() { M(123); } // } // } // // or the base class of an outer class: // // class Base { // public static void M(int x) {} // } // class Outer : Base { // class Inner { // void X() { M(123); } // } // } // // Then there is no "associated instance expression" of the method group. That is, there // is no possibility of there being an "implicit this". // // If the lookup finds M on the class that triggered the lookup on the other hand, or // one of its base classes: // // class Base { // public static void M(int x) {} // } // class Derived : Base { // void X() { M(123); } // } // // Then the associated instance expression is "this" *even if one or more methods in the // method group are static*. If it turns out that the method was static, then we'll // check later to determine if there was a receiver actually present in the source code // or not. (That happens during the "final validation" phase of overload resolution. // Implementation explanation: // // If we're here, then lookup has identified one or more methods. Debug.Assert(members.Count > 0); // The lookup implementation loops over the set of types from inner to outer, and stops // when it makes a match. (This is correct because any matches found on more-outer types // would be hidden, and discarded.) This means that we only find members associated with // one containing class or struct. The method is possibly on that type directly, or via // inheritance from a base type of the type. // // The question then is what the "associated instance expression" is; is it "this" or // nothing at all? If the type that we found the method on is the current type, or is a // base type of the current type, then there should be a "this" associated with the // method group. Otherwise, it should be null. var currentType = this.ContainingType; if ((object)currentType == null) { // This may happen if there is no containing type, // e.g. we are binding an expression in an assembly-level attribute return null; } var declaringType = members[0].ContainingType; var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; if (currentType.IsEqualToOrDerivedFrom(declaringType, TypeCompareKind.ConsiderEverything, useSiteInfo: ref discardedUseSiteInfo) || (currentType.IsInterface && (declaringType.IsObjectType() || currentType.AllInterfacesNoUseSiteDiagnostics.Contains(declaringType)))) { return ThisReference(syntax, currentType, wasCompilerGenerated: true); } else { return TryBindInteractiveReceiver(syntax, declaringType); } } private bool IsBadLocalOrParameterCapture(Symbol symbol, TypeSymbol type, RefKind refKind) { if (refKind != RefKind.None || type.IsRefLikeType) { var containingMethod = this.ContainingMemberOrLambda as MethodSymbol; if ((object)containingMethod != null && (object)symbol.ContainingSymbol != (object)containingMethod) { // Not expecting symbol from constructed method. Debug.Assert(!symbol.ContainingSymbol.Equals(containingMethod)); // Captured in a lambda. return (containingMethod.MethodKind == MethodKind.AnonymousFunction || containingMethod.MethodKind == MethodKind.LocalFunction) && !IsInsideNameof; // false in EE evaluation method } } return false; } private BoundExpression BindNonMethod(SimpleNameSyntax node, Symbol symbol, BindingDiagnosticBag diagnostics, LookupResultKind resultKind, bool indexed, bool isError) { // Events are handled later as we don't know yet if we are binding to the event or it's backing field. if (symbol.Kind != SymbolKind.Event) { ReportDiagnosticsIfObsolete(diagnostics, symbol, node, hasBaseReceiver: false); } switch (symbol.Kind) { case SymbolKind.Local: { var localSymbol = (LocalSymbol)symbol; TypeSymbol type; bool isNullableUnknown; if (ReportSimpleProgramLocalReferencedOutsideOfTopLevelStatement(node, localSymbol, diagnostics)) { type = new ExtendedErrorTypeSymbol( this.Compilation, name: "var", arity: 0, errorInfo: null, variableUsedBeforeDeclaration: true); isNullableUnknown = true; } else if (isUsedBeforeDeclaration(node, localSymbol)) { // Here we report a local variable being used before its declaration // // There are two possible diagnostics for this: // // CS0841: ERR_VariableUsedBeforeDeclaration // Cannot use local variable 'x' before it is declared // // CS0844: ERR_VariableUsedBeforeDeclarationAndHidesField // Cannot use local variable 'x' before it is declared. The // declaration of the local variable hides the field 'C.x'. // // There are two situations in which we give these errors. // // First, the scope of a local variable -- that is, the region of program // text in which it can be looked up by name -- is throughout the entire // block which declares it. It is therefore possible to use a local // before it is declared, which is an error. // // As an additional help to the user, we give a special error for this // scenario: // // class C { // int x; // void M() { // Print(x); // int x = 5; // } } // // Because a too-clever C++ user might be attempting to deliberately // bind to "this.x" in the "Print". (In C++ the local does not come // into scope until its declaration.) // FieldSymbol possibleField = null; var lookupResult = LookupResult.GetInstance(); CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); this.LookupMembersInType( lookupResult, ContainingType, localSymbol.Name, arity: 0, basesBeingResolved: null, options: LookupOptions.Default, originalBinder: this, diagnose: false, useSiteInfo: ref useSiteInfo); diagnostics.Add(node, useSiteInfo); possibleField = lookupResult.SingleSymbolOrDefault as FieldSymbol; lookupResult.Free(); if ((object)possibleField != null) { Error(diagnostics, ErrorCode.ERR_VariableUsedBeforeDeclarationAndHidesField, node, node, possibleField); } else { Error(diagnostics, ErrorCode.ERR_VariableUsedBeforeDeclaration, node, node); } type = new ExtendedErrorTypeSymbol( this.Compilation, name: "var", arity: 0, errorInfo: null, variableUsedBeforeDeclaration: true); isNullableUnknown = true; } else if ((localSymbol as SourceLocalSymbol)?.IsVar == true && localSymbol.ForbiddenZone?.Contains(node) == true) { // A var (type-inferred) local variable has been used in its own initialization (the "forbidden zone"). // There are many cases where this occurs, including: // // 1. var x = M(out x); // 2. M(out var x, out x); // 3. var (x, y) = (y, x); // // localSymbol.ForbiddenDiagnostic provides a suitable diagnostic for whichever case applies. // diagnostics.Add(localSymbol.ForbiddenDiagnostic, node.Location, node); type = new ExtendedErrorTypeSymbol( this.Compilation, name: "var", arity: 0, errorInfo: null, variableUsedBeforeDeclaration: true); isNullableUnknown = true; } else { type = localSymbol.Type; isNullableUnknown = false; if (IsBadLocalOrParameterCapture(localSymbol, type, localSymbol.RefKind)) { isError = true; Error(diagnostics, ErrorCode.ERR_AnonDelegateCantUseLocal, node, localSymbol); } } var constantValueOpt = localSymbol.IsConst && !IsInsideNameof && !type.IsErrorType() ? localSymbol.GetConstantValue(node, this.LocalInProgress, diagnostics) : null; return new BoundLocal(node, localSymbol, BoundLocalDeclarationKind.None, constantValueOpt: constantValueOpt, isNullableUnknown: isNullableUnknown, type: type, hasErrors: isError); } case SymbolKind.Parameter: { var parameter = (ParameterSymbol)symbol; if (IsBadLocalOrParameterCapture(parameter, parameter.Type, parameter.RefKind)) { isError = true; Error(diagnostics, ErrorCode.ERR_AnonDelegateCantUse, node, parameter.Name); } return new BoundParameter(node, parameter, hasErrors: isError); } case SymbolKind.NamedType: case SymbolKind.ErrorType: case SymbolKind.TypeParameter: // If I identifies a type, then the result is that type constructed with the // given type arguments. UNDONE: Construct the child type if it is generic! return new BoundTypeExpression(node, null, (TypeSymbol)symbol, hasErrors: isError); case SymbolKind.Property: { BoundExpression receiver = SynthesizeReceiver(node, symbol, diagnostics); return BindPropertyAccess(node, receiver, (PropertySymbol)symbol, diagnostics, resultKind, hasErrors: isError); } case SymbolKind.Event: { BoundExpression receiver = SynthesizeReceiver(node, symbol, diagnostics); return BindEventAccess(node, receiver, (EventSymbol)symbol, diagnostics, resultKind, hasErrors: isError); } case SymbolKind.Field: { BoundExpression receiver = SynthesizeReceiver(node, symbol, diagnostics); return BindFieldAccess(node, receiver, (FieldSymbol)symbol, diagnostics, resultKind, indexed, hasErrors: isError); } case SymbolKind.Namespace: return new BoundNamespaceExpression(node, (NamespaceSymbol)symbol, hasErrors: isError); case SymbolKind.Alias: { var alias = (AliasSymbol)symbol; symbol = alias.Target; switch (symbol.Kind) { case SymbolKind.NamedType: case SymbolKind.ErrorType: return new BoundTypeExpression(node, alias, (NamedTypeSymbol)symbol, hasErrors: isError); case SymbolKind.Namespace: return new BoundNamespaceExpression(node, (NamespaceSymbol)symbol, alias, hasErrors: isError); default: throw ExceptionUtilities.UnexpectedValue(symbol.Kind); } } case SymbolKind.RangeVariable: return BindRangeVariable(node, (RangeVariableSymbol)symbol, diagnostics); default: throw ExceptionUtilities.UnexpectedValue(symbol.Kind); } bool isUsedBeforeDeclaration(SimpleNameSyntax node, LocalSymbol localSymbol) { Location localSymbolLocation = localSymbol.Locations[0]; if (node.SyntaxTree == localSymbolLocation.SourceTree) { return node.SpanStart < localSymbolLocation.SourceSpan.Start; } return false; } } private static bool ReportSimpleProgramLocalReferencedOutsideOfTopLevelStatement(SimpleNameSyntax node, Symbol symbol, BindingDiagnosticBag diagnostics) { if (symbol.ContainingSymbol is SynthesizedSimpleProgramEntryPointSymbol) { if (!SyntaxFacts.IsTopLevelStatement(node.Ancestors(ascendOutOfTrivia: false).OfType<GlobalStatementSyntax>().FirstOrDefault())) { Error(diagnostics, ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, node, node); return true; } } return false; } protected virtual BoundExpression BindRangeVariable(SimpleNameSyntax node, RangeVariableSymbol qv, BindingDiagnosticBag diagnostics) { return Next.BindRangeVariable(node, qv, diagnostics); } private BoundExpression SynthesizeReceiver(SyntaxNode node, Symbol member, BindingDiagnosticBag diagnostics) { // SPEC: Otherwise, if T is the instance type of the immediately enclosing class or // struct type, if the lookup identifies an instance member, and if the reference occurs // within the block of an instance constructor, an instance method, or an instance // accessor, the result is the same as a member access of the form this.I. This can only // happen when K is zero. if (!member.RequiresInstanceReceiver()) { return null; } var currentType = this.ContainingType; var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; NamedTypeSymbol declaringType = member.ContainingType; if (currentType.IsEqualToOrDerivedFrom(declaringType, TypeCompareKind.ConsiderEverything, useSiteInfo: ref discardedUseSiteInfo) || (currentType.IsInterface && (declaringType.IsObjectType() || currentType.AllInterfacesNoUseSiteDiagnostics.Contains(declaringType)))) { bool hasErrors = false; if (EnclosingNameofArgument != node) { if (InFieldInitializer && !currentType.IsScriptClass) { //can't access "this" in field initializers Error(diagnostics, ErrorCode.ERR_FieldInitRefNonstatic, node, member); hasErrors = true; } else if (InConstructorInitializer || InAttributeArgument) { //can't access "this" in constructor initializers or attribute arguments Error(diagnostics, ErrorCode.ERR_ObjectRequired, node, member); hasErrors = true; } else { // not an instance member if the container is a type, like when binding default parameter values. var containingMember = ContainingMember(); bool locationIsInstanceMember = !containingMember.IsStatic && (containingMember.Kind != SymbolKind.NamedType || currentType.IsScriptClass); if (!locationIsInstanceMember) { // error CS0120: An object reference is required for the non-static field, method, or property '{0}' Error(diagnostics, ErrorCode.ERR_ObjectRequired, node, member); hasErrors = true; } } hasErrors = hasErrors || IsRefOrOutThisParameterCaptured(node, diagnostics); } return ThisReference(node, currentType, hasErrors, wasCompilerGenerated: true); } else { return TryBindInteractiveReceiver(node, declaringType); } } internal Symbol ContainingMember() { return this.ContainingMemberOrLambda.ContainingNonLambdaMember(); } private BoundExpression TryBindInteractiveReceiver(SyntaxNode syntax, NamedTypeSymbol memberDeclaringType) { if (this.ContainingType.TypeKind == TypeKind.Submission // check we have access to `this` && isInstanceContext()) { if (memberDeclaringType.TypeKind == TypeKind.Submission) { return new BoundPreviousSubmissionReference(syntax, memberDeclaringType) { WasCompilerGenerated = true }; } else { TypeSymbol hostObjectType = Compilation.GetHostObjectTypeSymbol(); var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; if ((object)hostObjectType != null && hostObjectType.IsEqualToOrDerivedFrom(memberDeclaringType, TypeCompareKind.ConsiderEverything, useSiteInfo: ref discardedUseSiteInfo)) { return new BoundHostObjectMemberReference(syntax, hostObjectType) { WasCompilerGenerated = true }; } } } return null; bool isInstanceContext() { var containingMember = this.ContainingMemberOrLambda; do { if (containingMember.IsStatic) { return false; } if (containingMember.Kind == SymbolKind.NamedType) { break; } containingMember = containingMember.ContainingSymbol; } while ((object)containingMember != null); return true; } } public BoundExpression BindNamespaceOrTypeOrExpression(ExpressionSyntax node, BindingDiagnosticBag diagnostics) { if (node.Kind() == SyntaxKind.PredefinedType) { return this.BindNamespaceOrType(node, diagnostics); } if (SyntaxFacts.IsName(node.Kind())) { if (SyntaxFacts.IsNamespaceAliasQualifier(node)) { return this.BindNamespaceAlias((IdentifierNameSyntax)node, diagnostics); } else if (SyntaxFacts.IsInNamespaceOrTypeContext(node)) { return this.BindNamespaceOrType(node, diagnostics); } } else if (SyntaxFacts.IsTypeSyntax(node.Kind())) { return this.BindNamespaceOrType(node, diagnostics); } return this.BindExpression(node, diagnostics, SyntaxFacts.IsInvoked(node), SyntaxFacts.IsIndexed(node)); } public BoundExpression BindLabel(ExpressionSyntax node, BindingDiagnosticBag diagnostics) { var name = node as IdentifierNameSyntax; if (name == null) { Debug.Assert(node.ContainsDiagnostics); return BadExpression(node, LookupResultKind.NotLabel); } var result = LookupResult.GetInstance(); string labelName = name.Identifier.ValueText; CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); this.LookupSymbolsWithFallback(result, labelName, arity: 0, useSiteInfo: ref useSiteInfo, options: LookupOptions.LabelsOnly); diagnostics.Add(node, useSiteInfo); if (!result.IsMultiViable) { Error(diagnostics, ErrorCode.ERR_LabelNotFound, node, labelName); result.Free(); return BadExpression(node, result.Kind); } Debug.Assert(result.IsSingleViable, "If this happens, we need to deal with multiple label definitions."); var symbol = (LabelSymbol)result.Symbols.First(); result.Free(); return new BoundLabel(node, symbol, null); } public BoundExpression BindNamespaceOrType(ExpressionSyntax node, BindingDiagnosticBag diagnostics) { var symbol = this.BindNamespaceOrTypeOrAliasSymbol(node, diagnostics, null, false); return CreateBoundNamespaceOrTypeExpression(node, symbol.Symbol); } public BoundExpression BindNamespaceAlias(IdentifierNameSyntax node, BindingDiagnosticBag diagnostics) { var symbol = this.BindNamespaceAliasSymbol(node, diagnostics); return CreateBoundNamespaceOrTypeExpression(node, symbol); } private static BoundExpression CreateBoundNamespaceOrTypeExpression(ExpressionSyntax node, Symbol symbol) { var alias = symbol as AliasSymbol; if ((object)alias != null) { symbol = alias.Target; } var type = symbol as TypeSymbol; if ((object)type != null) { return new BoundTypeExpression(node, alias, type); } var namespaceSymbol = symbol as NamespaceSymbol; if ((object)namespaceSymbol != null) { return new BoundNamespaceExpression(node, namespaceSymbol, alias); } throw ExceptionUtilities.UnexpectedValue(symbol); } private BoundThisReference BindThis(ThisExpressionSyntax node, BindingDiagnosticBag diagnostics) { Debug.Assert(node != null); bool hasErrors = true; bool inStaticContext; if (!HasThis(isExplicit: true, inStaticContext: out inStaticContext)) { //this error is returned in the field initializer case Error(diagnostics, inStaticContext ? ErrorCode.ERR_ThisInStaticMeth : ErrorCode.ERR_ThisInBadContext, node); } else { hasErrors = IsRefOrOutThisParameterCaptured(node.Token, diagnostics); } return ThisReference(node, this.ContainingType, hasErrors); } private BoundThisReference ThisReference(SyntaxNode node, NamedTypeSymbol thisTypeOpt, bool hasErrors = false, bool wasCompilerGenerated = false) { return new BoundThisReference(node, thisTypeOpt ?? CreateErrorType(), hasErrors) { WasCompilerGenerated = wasCompilerGenerated }; } private bool IsRefOrOutThisParameterCaptured(SyntaxNodeOrToken thisOrBaseToken, BindingDiagnosticBag diagnostics) { ParameterSymbol thisSymbol = this.ContainingMemberOrLambda.EnclosingThisSymbol(); // If there is no this parameter, then it is definitely not captured and // any diagnostic would be cascading. if ((object)thisSymbol != null && thisSymbol.ContainingSymbol != ContainingMemberOrLambda && thisSymbol.RefKind != RefKind.None) { Error(diagnostics, ErrorCode.ERR_ThisStructNotInAnonMeth, thisOrBaseToken); return true; } return false; } private BoundBaseReference BindBase(BaseExpressionSyntax node, BindingDiagnosticBag diagnostics) { bool hasErrors = false; TypeSymbol baseType = this.ContainingType is null ? null : this.ContainingType.BaseTypeNoUseSiteDiagnostics; bool inStaticContext; if (!HasThis(isExplicit: true, inStaticContext: out inStaticContext)) { //this error is returned in the field initializer case Error(diagnostics, inStaticContext ? ErrorCode.ERR_BaseInStaticMeth : ErrorCode.ERR_BaseInBadContext, node.Token); hasErrors = true; } else if ((object)baseType == null) // e.g. in System.Object { Error(diagnostics, ErrorCode.ERR_NoBaseClass, node); hasErrors = true; } else if (this.ContainingType is null || node.Parent is null || (node.Parent.Kind() != SyntaxKind.SimpleMemberAccessExpression && node.Parent.Kind() != SyntaxKind.ElementAccessExpression)) { Error(diagnostics, ErrorCode.ERR_BaseIllegal, node.Token); hasErrors = true; } else if (IsRefOrOutThisParameterCaptured(node.Token, diagnostics)) { // error has been reported by IsRefOrOutThisParameterCaptured hasErrors = true; } return new BoundBaseReference(node, baseType, hasErrors); } private BoundExpression BindCast(CastExpressionSyntax node, BindingDiagnosticBag diagnostics) { BoundExpression operand = this.BindValue(node.Expression, diagnostics, BindValueKind.RValue); TypeWithAnnotations targetTypeWithAnnotations = this.BindType(node.Type, diagnostics); TypeSymbol targetType = targetTypeWithAnnotations.Type; if (targetType.IsNullableType() && !operand.HasAnyErrors && (object)operand.Type != null && !operand.Type.IsNullableType() && !TypeSymbol.Equals(targetType.GetNullableUnderlyingType(), operand.Type, TypeCompareKind.ConsiderEverything2)) { return BindExplicitNullableCastFromNonNullable(node, operand, targetTypeWithAnnotations, diagnostics); } return BindCastCore(node, operand, targetTypeWithAnnotations, wasCompilerGenerated: operand.WasCompilerGenerated, diagnostics: diagnostics); } private BoundExpression BindFromEndIndexExpression(PrefixUnaryExpressionSyntax node, BindingDiagnosticBag diagnostics) { Debug.Assert(node.OperatorToken.IsKind(SyntaxKind.CaretToken)); CheckFeatureAvailability(node, MessageID.IDS_FeatureIndexOperator, diagnostics); // Used in lowering as the second argument to the constructor. Example: new Index(value, fromEnd: true) GetSpecialType(SpecialType.System_Boolean, diagnostics, node); BoundExpression boundOperand = BindValue(node.Operand, diagnostics, BindValueKind.RValue); TypeSymbol intType = GetSpecialType(SpecialType.System_Int32, diagnostics, node); TypeSymbol indexType = GetWellKnownType(WellKnownType.System_Index, diagnostics, node); if ((object)boundOperand.Type != null && boundOperand.Type.IsNullableType()) { // Used in lowering to construct the nullable GetSpecialTypeMember(SpecialMember.System_Nullable_T__ctor, diagnostics, node); NamedTypeSymbol nullableType = GetSpecialType(SpecialType.System_Nullable_T, diagnostics, node); if (!indexType.IsNonNullableValueType()) { Error(diagnostics, ErrorCode.ERR_ValConstraintNotSatisfied, node, nullableType, nullableType.TypeParameters.Single(), indexType); } intType = nullableType.Construct(intType); indexType = nullableType.Construct(indexType); } CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); Conversion conversion = this.Conversions.ClassifyImplicitConversionFromExpression(boundOperand, intType, ref useSiteInfo); diagnostics.Add(node, useSiteInfo); if (!conversion.IsValid) { GenerateImplicitConversionError(diagnostics, node, conversion, boundOperand, intType); } BoundExpression boundConversion = CreateConversion(boundOperand, conversion, intType, diagnostics); MethodSymbol symbolOpt = GetWellKnownTypeMember(WellKnownMember.System_Index__ctor, diagnostics, syntax: node) as MethodSymbol; return new BoundFromEndIndexExpression(node, boundConversion, symbolOpt, indexType); } private BoundExpression BindRangeExpression(RangeExpressionSyntax node, BindingDiagnosticBag diagnostics) { CheckFeatureAvailability(node, MessageID.IDS_FeatureRangeOperator, diagnostics); TypeSymbol rangeType = GetWellKnownType(WellKnownType.System_Range, diagnostics, node); MethodSymbol symbolOpt = null; if (!rangeType.IsErrorType()) { // Depending on the available arguments to the range expression, there are four // possible well-known members we could bind to. The constructor is always the // fallback member, usable in any situation. However, if any of the other members // are available and applicable, we will prefer that. WellKnownMember? memberOpt = null; if (node.LeftOperand is null && node.RightOperand is null) { memberOpt = WellKnownMember.System_Range__get_All; } else if (node.LeftOperand is null) { memberOpt = WellKnownMember.System_Range__EndAt; } else if (node.RightOperand is null) { memberOpt = WellKnownMember.System_Range__StartAt; } if (memberOpt is object) { symbolOpt = (MethodSymbol)GetWellKnownTypeMember( memberOpt.GetValueOrDefault(), diagnostics, syntax: node, isOptional: true); } if (symbolOpt is null) { symbolOpt = (MethodSymbol)GetWellKnownTypeMember( WellKnownMember.System_Range__ctor, diagnostics, syntax: node); } } BoundExpression left = BindRangeExpressionOperand(node.LeftOperand, diagnostics); BoundExpression right = BindRangeExpressionOperand(node.RightOperand, diagnostics); if (left?.Type.IsNullableType() == true || right?.Type.IsNullableType() == true) { // Used in lowering to construct the nullable GetSpecialType(SpecialType.System_Boolean, diagnostics, node); GetSpecialTypeMember(SpecialMember.System_Nullable_T__ctor, diagnostics, node); NamedTypeSymbol nullableType = GetSpecialType(SpecialType.System_Nullable_T, diagnostics, node); if (!rangeType.IsNonNullableValueType()) { Error(diagnostics, ErrorCode.ERR_ValConstraintNotSatisfied, node, nullableType, nullableType.TypeParameters.Single(), rangeType); } rangeType = nullableType.Construct(rangeType); } return new BoundRangeExpression(node, left, right, symbolOpt, rangeType); } private BoundExpression BindRangeExpressionOperand(ExpressionSyntax operand, BindingDiagnosticBag diagnostics) { if (operand is null) { return null; } BoundExpression boundOperand = BindValue(operand, diagnostics, BindValueKind.RValue); TypeSymbol indexType = GetWellKnownType(WellKnownType.System_Index, diagnostics, operand); if (boundOperand.Type?.IsNullableType() == true) { // Used in lowering to construct the nullable GetSpecialTypeMember(SpecialMember.System_Nullable_T__ctor, diagnostics, operand); NamedTypeSymbol nullableType = GetSpecialType(SpecialType.System_Nullable_T, diagnostics, operand); if (!indexType.IsNonNullableValueType()) { Error(diagnostics, ErrorCode.ERR_ValConstraintNotSatisfied, operand, nullableType, nullableType.TypeParameters.Single(), indexType); } indexType = nullableType.Construct(indexType); } CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); Conversion conversion = this.Conversions.ClassifyImplicitConversionFromExpression(boundOperand, indexType, ref useSiteInfo); diagnostics.Add(operand, useSiteInfo); if (!conversion.IsValid) { GenerateImplicitConversionError(diagnostics, operand, conversion, boundOperand, indexType); } return CreateConversion(boundOperand, conversion, indexType, diagnostics); } private BoundExpression BindCastCore(ExpressionSyntax node, BoundExpression operand, TypeWithAnnotations targetTypeWithAnnotations, bool wasCompilerGenerated, BindingDiagnosticBag diagnostics) { TypeSymbol targetType = targetTypeWithAnnotations.Type; CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); Conversion conversion = this.Conversions.ClassifyConversionFromExpression(operand, targetType, ref useSiteInfo, forCast: true); diagnostics.Add(node, useSiteInfo); var conversionGroup = new ConversionGroup(conversion, targetTypeWithAnnotations); bool suppressErrors = operand.HasAnyErrors || targetType.IsErrorType(); bool hasErrors = !conversion.IsValid || targetType.IsStatic; if (hasErrors && !suppressErrors) { GenerateExplicitConversionErrors(diagnostics, node, conversion, operand, targetType); } return CreateConversion(node, operand, conversion, isCast: true, conversionGroupOpt: conversionGroup, wasCompilerGenerated: wasCompilerGenerated, destination: targetType, diagnostics: diagnostics, hasErrors: hasErrors | suppressErrors); } private void GenerateExplicitConversionErrors( BindingDiagnosticBag diagnostics, SyntaxNode syntax, Conversion conversion, BoundExpression operand, TypeSymbol targetType) { // Make sure that errors within the unbound lambda don't get lost. if (operand.Kind == BoundKind.UnboundLambda) { GenerateAnonymousFunctionConversionError(diagnostics, operand.Syntax, (UnboundLambda)operand, targetType); return; } if (operand.HasAnyErrors || targetType.IsErrorType()) { // an error has already been reported elsewhere return; } if (targetType.IsStatic) { // The specification states in the section titled "Referencing Static // Class Types" that it is always illegal to have a static class in a // cast operator. diagnostics.Add(ErrorCode.ERR_ConvertToStaticClass, syntax.Location, targetType); return; } if (!targetType.IsReferenceType && !targetType.IsNullableType() && operand.IsLiteralNull()) { diagnostics.Add(ErrorCode.ERR_ValueCantBeNull, syntax.Location, targetType); return; } if (conversion.ResultKind == LookupResultKind.OverloadResolutionFailure) { Debug.Assert(conversion.IsUserDefined); ImmutableArray<MethodSymbol> originalUserDefinedConversions = conversion.OriginalUserDefinedConversions; if (originalUserDefinedConversions.Length > 1) { diagnostics.Add(ErrorCode.ERR_AmbigUDConv, syntax.Location, originalUserDefinedConversions[0], originalUserDefinedConversions[1], operand.Display, targetType); } else { Debug.Assert(originalUserDefinedConversions.Length == 0, "How can there be exactly one applicable user-defined conversion if the conversion doesn't exist?"); SymbolDistinguisher distinguisher1 = new SymbolDistinguisher(this.Compilation, operand.Type, targetType); diagnostics.Add(ErrorCode.ERR_NoExplicitConv, syntax.Location, distinguisher1.First, distinguisher1.Second); } return; } switch (operand.Kind) { case BoundKind.MethodGroup: { if (targetType.TypeKind != TypeKind.Delegate || !MethodGroupConversionDoesNotExistOrHasErrors((BoundMethodGroup)operand, (NamedTypeSymbol)targetType, syntax.Location, diagnostics, out _)) { diagnostics.Add(ErrorCode.ERR_NoExplicitConv, syntax.Location, MessageID.IDS_SK_METHOD.Localize(), targetType); } return; } case BoundKind.TupleLiteral: { var tuple = (BoundTupleLiteral)operand; var targetElementTypesWithAnnotations = 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 targetElementTypesWithAnnotations) && targetElementTypesWithAnnotations.Length == tuple.Arguments.Length) { GenerateExplicitConversionErrorsForTupleLiteralArguments(diagnostics, tuple.Arguments, targetElementTypesWithAnnotations); 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.StackAllocArrayCreation: { var stackAllocExpression = (BoundStackAllocArrayCreation)operand; Error(diagnostics, ErrorCode.ERR_StackAllocConversionNotPossible, syntax, stackAllocExpression.ElementType, targetType); return; } case BoundKind.UnconvertedConditionalOperator when operand.Type is null: case BoundKind.UnconvertedSwitchExpression when operand.Type is null: { GenerateImplicitConversionError(diagnostics, operand.Syntax, conversion, operand, targetType); return; } case BoundKind.UnconvertedAddressOfOperator: { var errorCode = targetType.TypeKind switch { TypeKind.FunctionPointer => ErrorCode.ERR_MethFuncPtrMismatch, TypeKind.Delegate => ErrorCode.ERR_CannotConvertAddressOfToDelegate, _ => ErrorCode.ERR_AddressOfToNonFunctionPointer }; diagnostics.Add(errorCode, syntax.Location, ((BoundUnconvertedAddressOfOperator)operand).Operand.Name, targetType); return; } } Debug.Assert((object)operand.Type != null); SymbolDistinguisher distinguisher = new SymbolDistinguisher(this.Compilation, operand.Type, targetType); diagnostics.Add(ErrorCode.ERR_NoExplicitConv, syntax.Location, distinguisher.First, distinguisher.Second); } private void GenerateExplicitConversionErrorsForTupleLiteralArguments( BindingDiagnosticBag diagnostics, ImmutableArray<BoundExpression> tupleArguments, ImmutableArray<TypeWithAnnotations> targetElementTypesWithAnnotations) { // 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 < targetElementTypesWithAnnotations.Length; i++) { var argument = tupleArguments[i]; var targetElementType = targetElementTypesWithAnnotations[i].Type; var elementConversion = Conversions.ClassifyConversionFromExpression(argument, targetElementType, ref discardedUseSiteInfo); if (!elementConversion.IsValid) { GenerateExplicitConversionErrors(diagnostics, argument.Syntax, elementConversion, argument, targetElementType); } } } /// <summary> /// This implements the casting behavior described in section 6.2.3 of the spec: /// /// - If the nullable conversion is from S to T?, the conversion is evaluated as the underlying conversion /// from S to T followed by a wrapping from T to T?. /// /// This particular check is done in the binder because it involves conversion processing rules (like overflow /// checking and constant folding) which are not handled by Conversions. /// </summary> private BoundExpression BindExplicitNullableCastFromNonNullable(ExpressionSyntax node, BoundExpression operand, TypeWithAnnotations targetTypeWithAnnotations, BindingDiagnosticBag diagnostics) { Debug.Assert(targetTypeWithAnnotations.HasType && targetTypeWithAnnotations.IsNullableType()); Debug.Assert((object)operand.Type != null && !operand.Type.IsNullableType()); // Section 6.2.3 of the spec only applies when the non-null version of the types involved have a // built in conversion. var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; TypeWithAnnotations underlyingTargetTypeWithAnnotations = targetTypeWithAnnotations.Type.GetNullableUnderlyingTypeWithAnnotations(); var underlyingConversion = Conversions.ClassifyBuiltInConversion(operand.Type, underlyingTargetTypeWithAnnotations.Type, ref discardedUseSiteInfo); if (!underlyingConversion.Exists) { return BindCastCore(node, operand, targetTypeWithAnnotations, wasCompilerGenerated: operand.WasCompilerGenerated, diagnostics: diagnostics); } var bag = new BindingDiagnosticBag(DiagnosticBag.GetInstance(), diagnostics.DependenciesBag); try { var underlyingExpr = BindCastCore(node, operand, underlyingTargetTypeWithAnnotations, wasCompilerGenerated: false, diagnostics: bag); if (underlyingExpr.HasErrors || bag.HasAnyErrors()) { Error(diagnostics, ErrorCode.ERR_NoExplicitConv, node, operand.Type, targetTypeWithAnnotations.Type); return new BoundConversion( node, operand, Conversion.NoConversion, @checked: CheckOverflowAtRuntime, explicitCastInCode: true, conversionGroupOpt: new ConversionGroup(Conversion.NoConversion, explicitType: targetTypeWithAnnotations), constantValueOpt: ConstantValue.NotAvailable, type: targetTypeWithAnnotations.Type, hasErrors: true); } // It's possible for the S -> T conversion to produce a 'better' constant value. If this // constant value is produced place it in the tree so that it gets emitted. This maintains // parity with the native compiler which also evaluated the conversion at compile time. if (underlyingExpr.ConstantValue != null) { underlyingExpr.WasCompilerGenerated = true; return BindCastCore(node, underlyingExpr, targetTypeWithAnnotations, wasCompilerGenerated: operand.WasCompilerGenerated, diagnostics: diagnostics); } return BindCastCore(node, operand, targetTypeWithAnnotations, wasCompilerGenerated: operand.WasCompilerGenerated, diagnostics: diagnostics); } finally { bag.DiagnosticBag.Free(); } } private static NameSyntax GetNameSyntax(SyntaxNode syntax) { string nameString; return GetNameSyntax(syntax, out nameString); } /// <summary> /// Gets the NameSyntax associated with the syntax node /// If no syntax is attached it sets the nameString to plain text /// name and returns a null NameSyntax /// </summary> /// <param name="syntax">Syntax node</param> /// <param name="nameString">Plain text name</param> internal static NameSyntax GetNameSyntax(SyntaxNode syntax, out string nameString) { nameString = string.Empty; while (true) { switch (syntax.Kind()) { case SyntaxKind.PredefinedType: nameString = ((PredefinedTypeSyntax)syntax).Keyword.ValueText; return null; case SyntaxKind.SimpleLambdaExpression: nameString = MessageID.IDS_Lambda.Localize().ToString(); return null; case SyntaxKind.ParenthesizedExpression: syntax = ((ParenthesizedExpressionSyntax)syntax).Expression; continue; case SyntaxKind.CastExpression: syntax = ((CastExpressionSyntax)syntax).Expression; continue; case SyntaxKind.SimpleMemberAccessExpression: case SyntaxKind.PointerMemberAccessExpression: return ((MemberAccessExpressionSyntax)syntax).Name; case SyntaxKind.MemberBindingExpression: return ((MemberBindingExpressionSyntax)syntax).Name; default: return syntax as NameSyntax; } } } /// <summary> /// Gets the plain text name associated with the expression syntax node /// </summary> /// <param name="syntax">Expression syntax node</param> /// <returns>Plain text name</returns> private static string GetName(ExpressionSyntax syntax) { string nameString; var nameSyntax = GetNameSyntax(syntax, out nameString); if (nameSyntax != null) { return nameSyntax.GetUnqualifiedName().Identifier.ValueText; } return nameString; } // Given a list of arguments, create arrays of the bound arguments and the names of those // arguments. private void BindArgumentsAndNames(ArgumentListSyntax argumentListOpt, BindingDiagnosticBag diagnostics, AnalyzedArguments result, bool allowArglist = false, bool isDelegateCreation = false) { if (argumentListOpt != null) { BindArgumentsAndNames(argumentListOpt.Arguments, diagnostics, result, allowArglist, isDelegateCreation: isDelegateCreation); } } private void BindArgumentsAndNames(BracketedArgumentListSyntax argumentListOpt, BindingDiagnosticBag diagnostics, AnalyzedArguments result) { if (argumentListOpt != null) { BindArgumentsAndNames(argumentListOpt.Arguments, diagnostics, result, allowArglist: false); } } private void BindArgumentsAndNames( SeparatedSyntaxList<ArgumentSyntax> arguments, BindingDiagnosticBag diagnostics, AnalyzedArguments result, bool allowArglist, bool isDelegateCreation = false) { // Only report the first "duplicate name" or "named before positional" error, // so as to avoid "cascading" errors. bool hadError = false; // Only report the first "non-trailing named args required C# 7.2" error, // so as to avoid "cascading" errors. bool hadLangVersionError = false; foreach (var argumentSyntax in arguments) { BindArgumentAndName(result, diagnostics, ref hadError, ref hadLangVersionError, argumentSyntax, allowArglist, isDelegateCreation: isDelegateCreation); } } private bool RefMustBeObeyed(bool isDelegateCreation, ArgumentSyntax argumentSyntax) { if (Compilation.FeatureStrictEnabled || !isDelegateCreation) { return true; } switch (argumentSyntax.Expression.Kind()) { // The next 3 cases should never be allowed as they cannot be ref/out. Assuming a bug in legacy compiler. case SyntaxKind.ParenthesizedLambdaExpression: case SyntaxKind.SimpleLambdaExpression: case SyntaxKind.AnonymousMethodExpression: case SyntaxKind.InvocationExpression: case SyntaxKind.ObjectCreationExpression: case SyntaxKind.ImplicitObjectCreationExpression: case SyntaxKind.ParenthesizedExpression: // this is never allowed in legacy compiler case SyntaxKind.DeclarationExpression: // A property/indexer is also invalid as it cannot be ref/out, but cannot be checked here. Assuming a bug in legacy compiler. return true; default: // The only ones that concern us here for compat is: locals, params, fields // BindArgumentAndName correctly rejects all other cases, except for properties and indexers. // They are handled after BindArgumentAndName returns and the binding can be checked. return false; } } private void BindArgumentAndName( AnalyzedArguments result, BindingDiagnosticBag diagnostics, ref bool hadError, ref bool hadLangVersionError, ArgumentSyntax argumentSyntax, bool allowArglist, bool isDelegateCreation = false) { RefKind origRefKind = argumentSyntax.RefOrOutKeyword.Kind().GetRefKind(); // The old native compiler ignores ref/out in a delegate creation expression. // For compatibility we implement the same bug except in strict mode. // Note: Some others should still be rejected when ref/out present. See RefMustBeObeyed. RefKind refKind = origRefKind == RefKind.None || RefMustBeObeyed(isDelegateCreation, argumentSyntax) ? origRefKind : RefKind.None; BoundExpression boundArgument = BindArgumentValue(diagnostics, argumentSyntax, allowArglist, refKind); BindArgumentAndName( result, diagnostics, ref hadLangVersionError, argumentSyntax, boundArgument, argumentSyntax.NameColon, refKind); // check for ref/out property/indexer, only needed for 1 parameter version if (!hadError && isDelegateCreation && origRefKind != RefKind.None && result.Arguments.Count == 1) { var arg = result.Argument(0); switch (arg.Kind) { case BoundKind.PropertyAccess: case BoundKind.IndexerAccess: var requiredValueKind = origRefKind == RefKind.In ? BindValueKind.ReadonlyRef : BindValueKind.RefOrOut; hadError = !CheckValueKind(argumentSyntax, arg, requiredValueKind, false, diagnostics); return; } } if (argumentSyntax.RefOrOutKeyword.Kind() != SyntaxKind.None) { argumentSyntax.Expression.CheckDeconstructionCompatibleArgument(diagnostics); } } private BoundExpression BindArgumentValue(BindingDiagnosticBag diagnostics, ArgumentSyntax argumentSyntax, bool allowArglist, RefKind refKind) { if (argumentSyntax.Expression.Kind() == SyntaxKind.DeclarationExpression) { var declarationExpression = (DeclarationExpressionSyntax)argumentSyntax.Expression; if (declarationExpression.IsOutDeclaration()) { return BindOutDeclarationArgument(declarationExpression, diagnostics); } } return BindArgumentExpression(diagnostics, argumentSyntax.Expression, refKind, allowArglist); } private BoundExpression BindOutDeclarationArgument(DeclarationExpressionSyntax declarationExpression, BindingDiagnosticBag diagnostics) { TypeSyntax typeSyntax = declarationExpression.Type; VariableDesignationSyntax designation = declarationExpression.Designation; if (typeSyntax.GetRefKind() != RefKind.None) { diagnostics.Add(ErrorCode.ERR_OutVariableCannotBeByRef, declarationExpression.Type.Location); } switch (designation.Kind()) { case SyntaxKind.DiscardDesignation: { bool isVar; bool isConst = false; AliasSymbol alias; var declType = BindVariableTypeWithAnnotations(designation, diagnostics, typeSyntax, ref isConst, out isVar, out alias); Debug.Assert(isVar != declType.HasType); return new BoundDiscardExpression(declarationExpression, declType.Type); } case SyntaxKind.SingleVariableDesignation: return BindOutVariableDeclarationArgument(declarationExpression, diagnostics); default: throw ExceptionUtilities.UnexpectedValue(designation.Kind()); } } private BoundExpression BindOutVariableDeclarationArgument( DeclarationExpressionSyntax declarationExpression, BindingDiagnosticBag diagnostics) { Debug.Assert(declarationExpression.IsOutVarDeclaration()); bool isVar; var designation = (SingleVariableDesignationSyntax)declarationExpression.Designation; TypeSyntax typeSyntax = declarationExpression.Type; // Is this a local? SourceLocalSymbol localSymbol = this.LookupLocal(designation.Identifier); if ((object)localSymbol != null) { Debug.Assert(localSymbol.DeclarationKind == LocalDeclarationKind.OutVariable); if ((InConstructorInitializer || InFieldInitializer) && ContainingMemberOrLambda.ContainingSymbol.Kind == SymbolKind.NamedType) { CheckFeatureAvailability(declarationExpression, MessageID.IDS_FeatureExpressionVariablesInQueriesAndInitializers, diagnostics); } bool isConst = false; AliasSymbol alias; var declType = BindVariableTypeWithAnnotations(declarationExpression, diagnostics, typeSyntax, ref isConst, out isVar, out alias); localSymbol.ScopeBinder.ValidateDeclarationNameConflictsInScope(localSymbol, diagnostics); if (isVar) { return new OutVariablePendingInference(declarationExpression, localSymbol, null); } CheckRestrictedTypeInAsyncMethod(this.ContainingMemberOrLambda, declType.Type, diagnostics, typeSyntax); return new BoundLocal(declarationExpression, localSymbol, BoundLocalDeclarationKind.WithExplicitType, constantValueOpt: null, isNullableUnknown: false, type: declType.Type); } // Is this a field? GlobalExpressionVariable expressionVariableField = LookupDeclaredField(designation); if ((object)expressionVariableField == null) { // We should have the right binder in the chain, cannot continue otherwise. throw ExceptionUtilities.Unreachable; } BoundExpression receiver = SynthesizeReceiver(designation, expressionVariableField, diagnostics); if (typeSyntax.IsVar) { BindTypeOrAliasOrVarKeyword(typeSyntax, BindingDiagnosticBag.Discarded, out isVar); if (isVar) { return new OutVariablePendingInference(declarationExpression, expressionVariableField, receiver); } } TypeSymbol fieldType = expressionVariableField.GetFieldType(this.FieldsBeingBound).Type; return new BoundFieldAccess(declarationExpression, receiver, expressionVariableField, null, LookupResultKind.Viable, isDeclaration: true, type: fieldType); } /// <summary> /// Returns true if a bad special by ref local was found. /// </summary> internal static bool CheckRestrictedTypeInAsyncMethod(Symbol containingSymbol, TypeSymbol type, BindingDiagnosticBag diagnostics, SyntaxNode syntax) { if (containingSymbol.Kind == SymbolKind.Method && ((MethodSymbol)containingSymbol).IsAsync && type.IsRestrictedType()) { Error(diagnostics, ErrorCode.ERR_BadSpecialByRefLocal, syntax, type); return true; } return false; } internal GlobalExpressionVariable LookupDeclaredField(SingleVariableDesignationSyntax variableDesignator) { return LookupDeclaredField(variableDesignator, variableDesignator.Identifier.ValueText); } internal GlobalExpressionVariable LookupDeclaredField(SyntaxNode node, string identifier) { foreach (Symbol member in ContainingType?.GetMembers(identifier) ?? ImmutableArray<Symbol>.Empty) { GlobalExpressionVariable field; if (member.Kind == SymbolKind.Field && (field = member as GlobalExpressionVariable)?.SyntaxTree == node.SyntaxTree && field.SyntaxNode == node) { return field; } } return null; } // Bind a named/positional argument. // Prevent cascading diagnostic by considering the previous // error state and returning the updated error state. private void BindArgumentAndName( AnalyzedArguments result, BindingDiagnosticBag diagnostics, ref bool hadLangVersionError, CSharpSyntaxNode argumentSyntax, BoundExpression boundArgumentExpression, NameColonSyntax nameColonSyntax, RefKind refKind) { Debug.Assert(argumentSyntax is ArgumentSyntax || argumentSyntax is AttributeArgumentSyntax); bool hasRefKinds = result.RefKinds.Any(); if (refKind != RefKind.None) { // The common case is no ref or out arguments. So we defer all work until the first one is seen. if (!hasRefKinds) { hasRefKinds = true; int argCount = result.Arguments.Count; for (int i = 0; i < argCount; ++i) { result.RefKinds.Add(RefKind.None); } } } if (hasRefKinds) { result.RefKinds.Add(refKind); } bool hasNames = result.Names.Any(); if (nameColonSyntax != null) { // The common case is no named arguments. So we defer all work until the first named argument is seen. if (!hasNames) { hasNames = true; int argCount = result.Arguments.Count; for (int i = 0; i < argCount; ++i) { result.Names.Add(null); } } result.AddName(nameColonSyntax.Name); } else if (hasNames) { // We just saw a fixed-position argument after a named argument. if (!hadLangVersionError && !Compilation.LanguageVersion.AllowNonTrailingNamedArguments()) { // CS1738: Named argument specifications must appear after all fixed arguments have been specified Error(diagnostics, ErrorCode.ERR_NamedArgumentSpecificationBeforeFixedArgument, argumentSyntax, new CSharpRequiredLanguageVersion(MessageID.IDS_FeatureNonTrailingNamedArguments.RequiredVersion())); hadLangVersionError = true; } result.Names.Add(null); } result.Arguments.Add(boundArgumentExpression); } /// <summary> /// Bind argument and verify argument matches rvalue or out param requirements. /// </summary> private BoundExpression BindArgumentExpression(BindingDiagnosticBag diagnostics, ExpressionSyntax argumentExpression, RefKind refKind, bool allowArglist) { BindValueKind valueKind = refKind == RefKind.None ? BindValueKind.RValue : refKind == RefKind.In ? BindValueKind.ReadonlyRef : BindValueKind.RefOrOut; BoundExpression argument; if (allowArglist) { argument = this.BindValueAllowArgList(argumentExpression, diagnostics, valueKind); } else { argument = this.BindValue(argumentExpression, diagnostics, valueKind); } return argument; } #nullable enable private void CoerceArguments<TMember>( MemberResolutionResult<TMember> methodResult, ArrayBuilder<BoundExpression> arguments, BindingDiagnosticBag diagnostics, TypeSymbol? receiverType, RefKind? receiverRefKind, uint receiverEscapeScope) where TMember : Symbol { var result = methodResult.Result; // Parameter types should be taken from the least overridden member: var parameters = methodResult.LeastOverriddenMember.GetParameters(); for (int arg = 0; arg < arguments.Count; ++arg) { var kind = result.ConversionForArg(arg); BoundExpression argument = arguments[arg]; if (kind.IsInterpolatedStringHandler) { Debug.Assert(argument is BoundUnconvertedInterpolatedString); TypeWithAnnotations parameterTypeWithAnnotations = GetCorrespondingParameterTypeWithAnnotations(ref result, parameters, arg); reportUnsafeIfNeeded(methodResult, diagnostics, argument, parameterTypeWithAnnotations); arguments[arg] = BindInterpolatedStringHandlerInMemberCall((BoundUnconvertedInterpolatedString)argument, arguments, parameters, ref result, arg, receiverType, receiverRefKind, receiverEscapeScope, diagnostics); } // https://github.com/dotnet/roslyn/issues/37119 : should we create an (Identity) conversion when the kind is Identity but the types differ? else if (!kind.IsIdentity) { TypeWithAnnotations parameterTypeWithAnnotations = GetCorrespondingParameterTypeWithAnnotations(ref result, parameters, arg); reportUnsafeIfNeeded(methodResult, diagnostics, argument, parameterTypeWithAnnotations); arguments[arg] = CreateConversion(argument.Syntax, argument, kind, isCast: false, conversionGroupOpt: null, parameterTypeWithAnnotations.Type, diagnostics); } else if (argument.Kind == BoundKind.OutVariablePendingInference) { TypeWithAnnotations parameterTypeWithAnnotations = GetCorrespondingParameterTypeWithAnnotations(ref result, parameters, arg); arguments[arg] = ((OutVariablePendingInference)argument).SetInferredTypeWithAnnotations(parameterTypeWithAnnotations, diagnostics); } else if (argument.Kind == BoundKind.OutDeconstructVarPendingInference) { TypeWithAnnotations parameterTypeWithAnnotations = GetCorrespondingParameterTypeWithAnnotations(ref result, parameters, arg); arguments[arg] = ((OutDeconstructVarPendingInference)argument).SetInferredTypeWithAnnotations(parameterTypeWithAnnotations, this, success: true); } else if (argument.Kind == BoundKind.DiscardExpression && !argument.HasExpressionType()) { TypeWithAnnotations parameterTypeWithAnnotations = GetCorrespondingParameterTypeWithAnnotations(ref result, parameters, arg); Debug.Assert(parameterTypeWithAnnotations.HasType); arguments[arg] = ((BoundDiscardExpression)argument).SetInferredTypeWithAnnotations(parameterTypeWithAnnotations); } else if (argument.NeedsToBeConverted()) { Debug.Assert(kind.IsIdentity); if (argument is BoundTupleLiteral) { TypeWithAnnotations parameterTypeWithAnnotations = GetCorrespondingParameterTypeWithAnnotations(ref result, parameters, arg); // CreateConversion reports tuple literal name mismatches, and constructs the expected pattern of bound nodes. arguments[arg] = CreateConversion(argument.Syntax, argument, kind, isCast: false, conversionGroupOpt: null, parameterTypeWithAnnotations.Type, diagnostics); } else { arguments[arg] = BindToNaturalType(argument, diagnostics); } } } void reportUnsafeIfNeeded(MemberResolutionResult<TMember> methodResult, BindingDiagnosticBag diagnostics, BoundExpression argument, TypeWithAnnotations parameterTypeWithAnnotations) { // NOTE: for some reason, dev10 doesn't report this for indexer accesses. if (!methodResult.Member.IsIndexer() && !argument.HasAnyErrors && parameterTypeWithAnnotations.Type.IsUnsafe()) { // CONSIDER: dev10 uses the call syntax, but this seems clearer. ReportUnsafeIfNotAllowed(argument.Syntax, diagnostics); //CONSIDER: Return a bad expression so that HasErrors is true? } } } private static ParameterSymbol GetCorrespondingParameter(ref MemberAnalysisResult result, ImmutableArray<ParameterSymbol> parameters, int arg) { int paramNum = result.ParameterFromArgument(arg); return parameters[paramNum]; } #nullable disable private static TypeWithAnnotations GetCorrespondingParameterTypeWithAnnotations(ref MemberAnalysisResult result, ImmutableArray<ParameterSymbol> parameters, int arg) { int paramNum = result.ParameterFromArgument(arg); var type = parameters[paramNum].TypeWithAnnotations; if (paramNum == parameters.Length - 1 && result.Kind == MemberResolutionKind.ApplicableInExpandedForm) { type = ((ArrayTypeSymbol)type.Type).ElementTypeWithAnnotations; } return type; } private BoundExpression BindArrayCreationExpression(ArrayCreationExpressionSyntax node, BindingDiagnosticBag diagnostics) { // SPEC begins // // An array-creation-expression is used to create a new instance of an array-type. // // array-creation-expression: // new non-array-type[expression-list] rank-specifiersopt array-initializeropt // new array-type array-initializer // new rank-specifier array-initializer // // An array creation expression of the first form allocates an array instance of the // type that results from deleting each of the individual expressions from the // expression list. For example, the array creation expression new int[10, 20] produces // an array instance of type int[,], and the array creation expression new int[10][,] // produces an array of type int[][,]. Each expression in the expression list must be of // type int, uint, long, or ulong, or implicitly convertible to one or more of these // types. The value of each expression determines the length of the corresponding // dimension in the newly allocated array instance. Since the length of an array // dimension must be nonnegative, it is a compile-time error to have a // constant-expression with a negative value in the expression list. // // If an array creation expression of the first form includes an array initializer, each // expression in the expression list must be a constant and the rank and dimension // lengths specified by the expression list must match those of the array initializer. // // In an array creation expression of the second or third form, the rank of the // specified array type or rank specifier must match that of the array initializer. The // individual dimension lengths are inferred from the number of elements in each of the // corresponding nesting levels of the array initializer. Thus, the expression new // int[,] {{0, 1}, {2, 3}, {4, 5}} exactly corresponds to new int[3, 2] {{0, 1}, {2, 3}, // {4, 5}} // // An array creation expression of the third form is referred to as an implicitly typed // array creation expression. It is similar to the second form, except that the element // type of the array is not explicitly given, but determined as the best common type // (7.5.2.14) of the set of expressions in the array initializer. For a multidimensional // array, i.e., one where the rank-specifier contains at least one comma, this set // comprises all expressions found in nested array-initializers. // // An array creation expression permits instantiation of an array with elements of an // array type, but the elements of such an array must be manually initialized. For // example, the statement // // int[][] a = new int[100][]; // // creates a single-dimensional array with 100 elements of type int[]. The initial value // of each element is null. It is not possible for the same array creation expression to // also instantiate the sub-arrays, and the statement // // int[][] a = new int[100][5]; // Error // // results in a compile-time error. // // The following are examples of implicitly typed array creation expressions: // // var a = new[] { 1, 10, 100, 1000 }; // int[] // var b = new[] { 1, 1.5, 2, 2.5 }; // double[] // var c = new[,] { { "hello", null }, { "world", "!" } }; // string[,] // var d = new[] { 1, "one", 2, "two" }; // Error // // The last expression causes a compile-time error because neither int nor string is // implicitly convertible to the other, and so there is no best common type. An // explicitly typed array creation expression must be used in this case, for example // specifying the type to be object[]. Alternatively, one of the elements can be cast to // a common base type, which would then become the inferred element type. // // SPEC ends var type = (ArrayTypeSymbol)BindArrayType(node.Type, diagnostics, permitDimensions: true, basesBeingResolved: null, disallowRestrictedTypes: true).Type; // CONSIDER: // // There may be erroneous rank specifiers in the source code, for example: // // int y = 123; // int[][] z = new int[10][y]; // // The "10" is legal but the "y" is not. If we are in such a situation we do have the // "y" expression syntax stashed away in the syntax tree. However, we do *not* perform // semantic analysis. This means that "go to definition" on "y" does not work, and so // on. We might consider doing a semantic analysis here (with error suppression; a parse // error has already been reported) so that "go to definition" works. ArrayBuilder<BoundExpression> sizes = ArrayBuilder<BoundExpression>.GetInstance(); ArrayRankSpecifierSyntax firstRankSpecifier = node.Type.RankSpecifiers[0]; bool hasErrors = false; foreach (var arg in firstRankSpecifier.Sizes) { var size = BindArrayDimension(arg, diagnostics, ref hasErrors); if (size != null) { sizes.Add(size); } else if (node.Initializer is null && arg == firstRankSpecifier.Sizes[0]) { Error(diagnostics, ErrorCode.ERR_MissingArraySize, firstRankSpecifier); hasErrors = true; } } // produce errors for additional sizes in the ranks for (int additionalRankIndex = 1; additionalRankIndex < node.Type.RankSpecifiers.Count; additionalRankIndex++) { var rank = node.Type.RankSpecifiers[additionalRankIndex]; var dimension = rank.Sizes; foreach (var arg in dimension) { if (arg.Kind() != SyntaxKind.OmittedArraySizeExpression) { var size = BindRValueWithoutTargetType(arg, diagnostics); Error(diagnostics, ErrorCode.ERR_InvalidArray, arg); hasErrors = true; // Capture the invalid sizes for `SemanticModel` and `IOperation` sizes.Add(size); } } } ImmutableArray<BoundExpression> arraySizes = sizes.ToImmutableAndFree(); return node.Initializer == null ? new BoundArrayCreation(node, arraySizes, null, type, hasErrors) : BindArrayCreationWithInitializer(diagnostics, node, node.Initializer, type, arraySizes, hasErrors: hasErrors); } private BoundExpression BindArrayDimension(ExpressionSyntax dimension, BindingDiagnosticBag diagnostics, ref bool hasErrors) { // These make the parse tree nicer, but they shouldn't actually appear in the bound tree. if (dimension.Kind() != SyntaxKind.OmittedArraySizeExpression) { var size = BindValue(dimension, diagnostics, BindValueKind.RValue); if (!size.HasAnyErrors) { size = ConvertToArrayIndex(size, diagnostics, allowIndexAndRange: false); if (IsNegativeConstantForArraySize(size)) { Error(diagnostics, ErrorCode.ERR_NegativeArraySize, dimension); hasErrors = true; } } else { size = BindToTypeForErrorRecovery(size); } return size; } return null; } private BoundExpression BindImplicitArrayCreationExpression(ImplicitArrayCreationExpressionSyntax node, BindingDiagnosticBag diagnostics) { // See BindArrayCreationExpression method above for implicitly typed array creation SPEC. InitializerExpressionSyntax initializer = node.Initializer; int rank = node.Commas.Count + 1; ImmutableArray<BoundExpression> boundInitializerExpressions = BindArrayInitializerExpressions(initializer, diagnostics, dimension: 1, rank: rank); CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); TypeSymbol bestType = BestTypeInferrer.InferBestType(boundInitializerExpressions, this.Conversions, ref useSiteInfo); diagnostics.Add(node, useSiteInfo); if ((object)bestType == null || bestType.IsVoidType()) // Dev10 also reports ERR_ImplicitlyTypedArrayNoBestType for void. { Error(diagnostics, ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, node); bestType = CreateErrorType(); } if (bestType.IsRestrictedType()) { // CS0611: Array elements cannot be of type '{0}' Error(diagnostics, ErrorCode.ERR_ArrayElementCantBeRefAny, node, bestType); } // Element type nullability will be inferred in flow analysis and does not need to be set here. var arrayType = ArrayTypeSymbol.CreateCSharpArray(Compilation.Assembly, TypeWithAnnotations.Create(bestType), rank); return BindArrayCreationWithInitializer(diagnostics, node, initializer, arrayType, sizes: ImmutableArray<BoundExpression>.Empty, boundInitExprOpt: boundInitializerExpressions); } private BoundExpression BindImplicitStackAllocArrayCreationExpression(ImplicitStackAllocArrayCreationExpressionSyntax node, BindingDiagnosticBag diagnostics) { InitializerExpressionSyntax initializer = node.Initializer; ImmutableArray<BoundExpression> boundInitializerExpressions = BindArrayInitializerExpressions(initializer, diagnostics, dimension: 1, rank: 1); CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); TypeSymbol bestType = BestTypeInferrer.InferBestType(boundInitializerExpressions, this.Conversions, ref useSiteInfo); diagnostics.Add(node, useSiteInfo); if ((object)bestType == null || bestType.IsVoidType()) { Error(diagnostics, ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, node); bestType = CreateErrorType(); } if (!bestType.IsErrorType()) { CheckManagedAddr(Compilation, bestType, node.Location, diagnostics); } return BindStackAllocWithInitializer( node, initializer, type: GetStackAllocType(node, TypeWithAnnotations.Create(bestType), diagnostics, out bool hasErrors), elementType: bestType, sizeOpt: null, diagnostics, hasErrors: hasErrors, boundInitializerExpressions); } // This method binds all the array initializer expressions. // NOTE: It doesn't convert the bound initializer expressions to array's element type. // NOTE: This is done separately in ConvertAndBindArrayInitialization method below. private ImmutableArray<BoundExpression> BindArrayInitializerExpressions(InitializerExpressionSyntax initializer, BindingDiagnosticBag diagnostics, int dimension, int rank) { var exprBuilder = ArrayBuilder<BoundExpression>.GetInstance(); BindArrayInitializerExpressions(initializer, exprBuilder, diagnostics, dimension, rank); return exprBuilder.ToImmutableAndFree(); } /// <summary> /// This method walks through the array's InitializerExpressionSyntax and binds all the initializer expressions recursively. /// NOTE: It doesn't convert the bound initializer expressions to array's element type. /// NOTE: This is done separately in ConvertAndBindArrayInitialization method below. /// </summary> /// <param name="initializer">Initializer Syntax.</param> /// <param name="exprBuilder">Bound expression builder.</param> /// <param name="diagnostics">Diagnostics.</param> /// <param name="dimension">Current array dimension being processed.</param> /// <param name="rank">Rank of the array type.</param> private void BindArrayInitializerExpressions(InitializerExpressionSyntax initializer, ArrayBuilder<BoundExpression> exprBuilder, BindingDiagnosticBag diagnostics, int dimension, int rank) { Debug.Assert(rank > 0); Debug.Assert(dimension > 0 && dimension <= rank); Debug.Assert(exprBuilder != null); if (dimension == rank) { // We are processing the nth dimension of a rank-n array. We expect that these will // only be values, not array initializers. foreach (var expression in initializer.Expressions) { var boundExpression = BindValue(expression, diagnostics, BindValueKind.RValue); exprBuilder.Add(boundExpression); } } else { // Inductive case; we'd better have another array initializer foreach (var expression in initializer.Expressions) { if (expression.Kind() == SyntaxKind.ArrayInitializerExpression) { BindArrayInitializerExpressions((InitializerExpressionSyntax)expression, exprBuilder, diagnostics, dimension + 1, rank); } else { // We have non-array initializer expression, but we expected an array initializer expression. var boundExpression = BindValue(expression, diagnostics, BindValueKind.RValue); if ((object)boundExpression.Type == null || !boundExpression.Type.IsErrorType()) { if (!boundExpression.HasAnyErrors) { Error(diagnostics, ErrorCode.ERR_ArrayInitializerExpected, expression); } // Wrap the expression with a bound bad expression with error type. boundExpression = BadExpression( expression, LookupResultKind.Empty, ImmutableArray.Create(boundExpression.ExpressionSymbol), ImmutableArray.Create(boundExpression)); } exprBuilder.Add(boundExpression); } } } } /// <summary> /// Given an array of bound initializer expressions, this method converts these bound expressions /// to array's element type and generates a BoundArrayInitialization with the converted initializers. /// </summary> /// <param name="diagnostics">Diagnostics.</param> /// <param name="node">Initializer Syntax.</param> /// <param name="type">Array type.</param> /// <param name="knownSizes">Known array bounds.</param> /// <param name="dimension">Current array dimension being processed.</param> /// <param name="boundInitExpr">Array of bound initializer expressions.</param> /// <param name="boundInitExprIndex"> /// Index into the array of bound initializer expressions to fetch the next bound expression. /// </param> /// <returns></returns> private BoundArrayInitialization ConvertAndBindArrayInitialization( BindingDiagnosticBag diagnostics, InitializerExpressionSyntax node, ArrayTypeSymbol type, int?[] knownSizes, int dimension, ImmutableArray<BoundExpression> boundInitExpr, ref int boundInitExprIndex) { Debug.Assert(!boundInitExpr.IsDefault); ArrayBuilder<BoundExpression> initializers = ArrayBuilder<BoundExpression>.GetInstance(); if (dimension == type.Rank) { // We are processing the nth dimension of a rank-n array. We expect that these will // only be values, not array initializers. TypeSymbol elemType = type.ElementType; foreach (var expressionSyntax in node.Expressions) { Debug.Assert(boundInitExprIndex >= 0 && boundInitExprIndex < boundInitExpr.Length); BoundExpression boundExpression = boundInitExpr[boundInitExprIndex]; boundInitExprIndex++; BoundExpression convertedExpression = GenerateConversionForAssignment(elemType, boundExpression, diagnostics); initializers.Add(convertedExpression); } } else { // Inductive case; we'd better have another array initializer foreach (var expr in node.Expressions) { BoundExpression init = null; if (expr.Kind() == SyntaxKind.ArrayInitializerExpression) { init = ConvertAndBindArrayInitialization(diagnostics, (InitializerExpressionSyntax)expr, type, knownSizes, dimension + 1, boundInitExpr, ref boundInitExprIndex); } else { // We have non-array initializer expression, but we expected an array initializer expression. // We have already generated the diagnostics during binding, so just fetch the bound expression. Debug.Assert(boundInitExprIndex >= 0 && boundInitExprIndex < boundInitExpr.Length); init = boundInitExpr[boundInitExprIndex]; Debug.Assert(init.HasAnyErrors); Debug.Assert(init.Type.IsErrorType()); boundInitExprIndex++; } initializers.Add(init); } } bool hasErrors = false; var knownSizeOpt = knownSizes[dimension - 1]; if (knownSizeOpt == null) { knownSizes[dimension - 1] = initializers.Count; } else if (knownSizeOpt != initializers.Count) { // No need to report an error if the known size is negative // since we've already reported CS0248 earlier and it's // expected that the number of initializers won't match. if (knownSizeOpt >= 0) { Error(diagnostics, ErrorCode.ERR_ArrayInitializerIncorrectLength, node, knownSizeOpt.Value); hasErrors = true; } } return new BoundArrayInitialization(node, initializers.ToImmutableAndFree(), hasErrors: hasErrors); } private BoundArrayInitialization BindArrayInitializerList( BindingDiagnosticBag diagnostics, InitializerExpressionSyntax node, ArrayTypeSymbol type, int?[] knownSizes, int dimension, ImmutableArray<BoundExpression> boundInitExprOpt = default(ImmutableArray<BoundExpression>)) { // Bind the array initializer expressions, if not already bound. // NOTE: Initializer expressions might already be bound for implicitly type array creation // NOTE: during array's element type inference. if (boundInitExprOpt.IsDefault) { boundInitExprOpt = BindArrayInitializerExpressions(node, diagnostics, dimension, type.Rank); } // Convert the bound array initializer expressions to array's element type and // generate BoundArrayInitialization with the converted initializers. int boundInitExprIndex = 0; return ConvertAndBindArrayInitialization(diagnostics, node, type, knownSizes, dimension, boundInitExprOpt, ref boundInitExprIndex); } private BoundArrayInitialization BindUnexpectedArrayInitializer( InitializerExpressionSyntax node, BindingDiagnosticBag diagnostics, ErrorCode errorCode, CSharpSyntaxNode errorNode = null) { var result = BindArrayInitializerList( diagnostics, node, this.Compilation.CreateArrayTypeSymbol(GetSpecialType(SpecialType.System_Object, diagnostics, node)), new int?[1], dimension: 1); if (!result.HasAnyErrors) { result = new BoundArrayInitialization(node, result.Initializers, hasErrors: true); } Error(diagnostics, errorCode, errorNode ?? node); return result; } // We could be in the cases // // (1) int[] x = { a, b } // (2) new int[] { a, b } // (3) new int[2] { a, b } // (4) new [] { a, b } // // In case (1) there is no creation syntax. // In cases (2) and (3) creation syntax is an ArrayCreationExpression. // In case (4) creation syntax is an ImplicitArrayCreationExpression. // // In cases (1), (2) and (4) there are no sizes. // // The initializer syntax is always provided. // // If we are in case (3) and sizes are provided then the number of sizes must match the rank // of the array type passed in. // For case (4), i.e. ImplicitArrayCreationExpression, we must have already bound the // initializer expressions for best type inference. // These bound expressions are stored in boundInitExprOpt and reused in creating // BoundArrayInitialization to avoid binding them twice. private BoundArrayCreation BindArrayCreationWithInitializer( BindingDiagnosticBag diagnostics, ExpressionSyntax creationSyntax, InitializerExpressionSyntax initSyntax, ArrayTypeSymbol type, ImmutableArray<BoundExpression> sizes, ImmutableArray<BoundExpression> boundInitExprOpt = default(ImmutableArray<BoundExpression>), bool hasErrors = false) { Debug.Assert(creationSyntax == null || creationSyntax.Kind() == SyntaxKind.ArrayCreationExpression || creationSyntax.Kind() == SyntaxKind.ImplicitArrayCreationExpression); Debug.Assert(initSyntax != null); Debug.Assert((object)type != null); Debug.Assert(boundInitExprOpt.IsDefault || creationSyntax.Kind() == SyntaxKind.ImplicitArrayCreationExpression); // NOTE: In error scenarios, it may be the case sizes.Count > type.Rank. // For example, new int[1 2] has 2 sizes, but rank 1 (since there are 0 commas). int rank = type.Rank; int numSizes = sizes.Length; int?[] knownSizes = new int?[Math.Max(rank, numSizes)]; // If there are sizes given and there is an array initializer, then every size must be a // constant. (We'll check later that it matches) for (int i = 0; i < numSizes; ++i) { // Here we are being bug-for-bug compatible with C# 4. When you have code like // byte[] b = new[uint.MaxValue] { 2 }; // you might expect an error that says that the number of elements in the initializer does // not match the size of the array. But in C# 4 if the constant does not fit into an integer // then we confusingly give the error "that's not a constant". // NOTE: in the example above, GetIntegerConstantForArraySize is returning null because the // size doesn't fit in an int - not because it doesn't match the initializer length. var size = sizes[i]; knownSizes[i] = GetIntegerConstantForArraySize(size); if (!size.HasAnyErrors && knownSizes[i] == null) { Error(diagnostics, ErrorCode.ERR_ConstantExpected, size.Syntax); hasErrors = true; } } // KnownSizes is further mutated by BindArrayInitializerList as it works out more // information about the sizes. BoundArrayInitialization initializer = BindArrayInitializerList(diagnostics, initSyntax, type, knownSizes, 1, boundInitExprOpt); hasErrors = hasErrors || initializer.HasAnyErrors; bool hasCreationSyntax = creationSyntax != null; CSharpSyntaxNode nonNullSyntax = (CSharpSyntaxNode)creationSyntax ?? initSyntax; // Construct a set of size expressions if we were not given any. // // It is possible in error scenarios that some of the bounds were not determined. Substitute // zeroes for those. if (numSizes == 0) { BoundExpression[] sizeArray = new BoundExpression[rank]; for (int i = 0; i < rank; i++) { sizeArray[i] = new BoundLiteral( nonNullSyntax, ConstantValue.Create(knownSizes[i] ?? 0), GetSpecialType(SpecialType.System_Int32, diagnostics, nonNullSyntax)) { WasCompilerGenerated = true }; } sizes = sizeArray.AsImmutableOrNull(); } else if (!hasErrors && rank != numSizes) { Error(diagnostics, ErrorCode.ERR_BadIndexCount, nonNullSyntax, type.Rank); hasErrors = true; } return new BoundArrayCreation(nonNullSyntax, sizes, initializer, type, hasErrors: hasErrors) { WasCompilerGenerated = !hasCreationSyntax && (initSyntax.Parent == null || initSyntax.Parent.Kind() != SyntaxKind.EqualsValueClause || ((EqualsValueClauseSyntax)initSyntax.Parent).Value != initSyntax) }; } private BoundExpression BindStackAllocArrayCreationExpression( StackAllocArrayCreationExpressionSyntax node, BindingDiagnosticBag diagnostics) { TypeSyntax typeSyntax = node.Type; if (typeSyntax.Kind() != SyntaxKind.ArrayType) { Error(diagnostics, ErrorCode.ERR_BadStackAllocExpr, typeSyntax); return new BoundBadExpression( node, LookupResultKind.NotCreatable, //in this context, anyway ImmutableArray<Symbol>.Empty, ImmutableArray<BoundExpression>.Empty, new PointerTypeSymbol(BindType(typeSyntax, diagnostics))); } ArrayTypeSyntax arrayTypeSyntax = (ArrayTypeSyntax)typeSyntax; var elementTypeSyntax = arrayTypeSyntax.ElementType; var arrayType = (ArrayTypeSymbol)BindArrayType(arrayTypeSyntax, diagnostics, permitDimensions: true, basesBeingResolved: null, disallowRestrictedTypes: false).Type; var elementType = arrayType.ElementTypeWithAnnotations; TypeSymbol type = GetStackAllocType(node, elementType, diagnostics, out bool hasErrors); if (!elementType.Type.IsErrorType()) { hasErrors = hasErrors || CheckManagedAddr(Compilation, elementType.Type, elementTypeSyntax.Location, diagnostics); } SyntaxList<ArrayRankSpecifierSyntax> rankSpecifiers = arrayTypeSyntax.RankSpecifiers; if (rankSpecifiers.Count != 1 || rankSpecifiers[0].Sizes.Count != 1) { // NOTE: Dev10 reported several parse errors here. Error(diagnostics, ErrorCode.ERR_BadStackAllocExpr, typeSyntax); var builder = ArrayBuilder<BoundExpression>.GetInstance(); foreach (ArrayRankSpecifierSyntax rankSpecifier in rankSpecifiers) { foreach (ExpressionSyntax size in rankSpecifier.Sizes) { if (size.Kind() != SyntaxKind.OmittedArraySizeExpression) { builder.Add(BindExpression(size, BindingDiagnosticBag.Discarded)); } } } return new BoundBadExpression( node, LookupResultKind.Empty, ImmutableArray<Symbol>.Empty, builder.ToImmutableAndFree(), new PointerTypeSymbol(elementType)); } ExpressionSyntax countSyntax = rankSpecifiers[0].Sizes[0]; BoundExpression count = null; if (countSyntax.Kind() != SyntaxKind.OmittedArraySizeExpression) { count = BindValue(countSyntax, diagnostics, BindValueKind.RValue); count = GenerateConversionForAssignment(GetSpecialType(SpecialType.System_Int32, diagnostics, node), count, diagnostics); if (IsNegativeConstantForArraySize(count)) { Error(diagnostics, ErrorCode.ERR_NegativeStackAllocSize, countSyntax); hasErrors = true; } } else if (node.Initializer == null) { Error(diagnostics, ErrorCode.ERR_MissingArraySize, rankSpecifiers[0]); count = BadExpression(countSyntax); hasErrors = true; } return node.Initializer == null ? new BoundStackAllocArrayCreation(node, elementType.Type, count, initializerOpt: null, type, hasErrors: hasErrors) : BindStackAllocWithInitializer(node, node.Initializer, type, elementType.Type, count, diagnostics, hasErrors); } private bool ReportBadStackAllocPosition(SyntaxNode node, BindingDiagnosticBag diagnostics) { Debug.Assert(node is StackAllocArrayCreationExpressionSyntax || node is ImplicitStackAllocArrayCreationExpressionSyntax); bool inLegalPosition = true; // If we are using a language version that does not restrict the position of a stackalloc expression, skip that test. LanguageVersion requiredVersion = MessageID.IDS_FeatureNestedStackalloc.RequiredVersion(); if (requiredVersion > Compilation.LanguageVersion) { inLegalPosition = (IsInMethodBody || IsLocalFunctionsScopeBinder) && node.IsLegalCSharp73SpanStackAllocPosition(); if (!inLegalPosition) { MessageID.IDS_FeatureNestedStackalloc.CheckFeatureAvailability(diagnostics, node, node.GetFirstToken().GetLocation()); } } // Check if we're syntactically within a catch or finally clause. if (this.Flags.IncludesAny(BinderFlags.InCatchBlock | BinderFlags.InCatchFilter | BinderFlags.InFinallyBlock)) { Error(diagnostics, ErrorCode.ERR_StackallocInCatchFinally, node); } return inLegalPosition; } private TypeSymbol GetStackAllocType(SyntaxNode node, TypeWithAnnotations elementTypeWithAnnotations, BindingDiagnosticBag diagnostics, out bool hasErrors) { var inLegalPosition = ReportBadStackAllocPosition(node, diagnostics); hasErrors = !inLegalPosition; if (inLegalPosition && !isStackallocTargetTyped(node)) { CheckFeatureAvailability(node, MessageID.IDS_FeatureRefStructs, diagnostics); var spanType = GetWellKnownType(WellKnownType.System_Span_T, diagnostics, node); return ConstructNamedType( type: spanType, typeSyntax: node.Kind() == SyntaxKind.StackAllocArrayCreationExpression ? ((StackAllocArrayCreationExpressionSyntax)node).Type : node, typeArgumentsSyntax: default, typeArguments: ImmutableArray.Create(elementTypeWithAnnotations), basesBeingResolved: null, diagnostics: diagnostics); } // We treat the stackalloc as target-typed, so we give it a null type for now. return null; // Is this a context in which a stackalloc expression could be converted to the corresponding pointer // type? The only context that permits it is the initialization of a local variable declaration (when // the declaration appears as a statement or as the first part of a for loop). static bool isStackallocTargetTyped(SyntaxNode node) { Debug.Assert(node != null); SyntaxNode equalsValueClause = node.Parent; if (!equalsValueClause.IsKind(SyntaxKind.EqualsValueClause)) { return false; } SyntaxNode variableDeclarator = equalsValueClause.Parent; if (!variableDeclarator.IsKind(SyntaxKind.VariableDeclarator)) { return false; } SyntaxNode variableDeclaration = variableDeclarator.Parent; if (!variableDeclaration.IsKind(SyntaxKind.VariableDeclaration)) { return false; } return variableDeclaration.Parent.IsKind(SyntaxKind.LocalDeclarationStatement) || variableDeclaration.Parent.IsKind(SyntaxKind.ForStatement); } } private BoundExpression BindStackAllocWithInitializer( SyntaxNode node, InitializerExpressionSyntax initSyntax, TypeSymbol type, TypeSymbol elementType, BoundExpression sizeOpt, BindingDiagnosticBag diagnostics, bool hasErrors, ImmutableArray<BoundExpression> boundInitExprOpt = default) { Debug.Assert(node.IsKind(SyntaxKind.ImplicitStackAllocArrayCreationExpression) || node.IsKind(SyntaxKind.StackAllocArrayCreationExpression)); if (boundInitExprOpt.IsDefault) { boundInitExprOpt = BindArrayInitializerExpressions(initSyntax, diagnostics, dimension: 1, rank: 1); } boundInitExprOpt = boundInitExprOpt.SelectAsArray((expr, t) => GenerateConversionForAssignment(t.elementType, expr, t.diagnostics), (elementType, diagnostics)); if (sizeOpt != null) { if (!sizeOpt.HasAnyErrors) { int? constantSizeOpt = GetIntegerConstantForArraySize(sizeOpt); if (constantSizeOpt == null) { Error(diagnostics, ErrorCode.ERR_ConstantExpected, sizeOpt.Syntax); hasErrors = true; } else if (boundInitExprOpt.Length != constantSizeOpt) { Error(diagnostics, ErrorCode.ERR_ArrayInitializerIncorrectLength, node, constantSizeOpt.Value); hasErrors = true; } } } else { sizeOpt = new BoundLiteral( node, ConstantValue.Create(boundInitExprOpt.Length), GetSpecialType(SpecialType.System_Int32, diagnostics, node)) { WasCompilerGenerated = true }; } return new BoundStackAllocArrayCreation(node, elementType, sizeOpt, new BoundArrayInitialization(initSyntax, boundInitExprOpt), type, hasErrors); } private static int? GetIntegerConstantForArraySize(BoundExpression expression) { // If the bound could have been converted to int, then it was. If it could not have been // converted to int, and it was a constant, then it was out of range. Debug.Assert(expression != null); if (expression.HasAnyErrors) { return null; } var constantValue = expression.ConstantValue; if (constantValue == null || constantValue.IsBad || expression.Type.SpecialType != SpecialType.System_Int32) { return null; } return constantValue.Int32Value; } private static bool IsNegativeConstantForArraySize(BoundExpression expression) { Debug.Assert(expression != null); if (expression.HasAnyErrors) { return false; } var constantValue = expression.ConstantValue; if (constantValue == null || constantValue.IsBad) { return false; } var type = expression.Type.SpecialType; if (type == SpecialType.System_Int32) { return constantValue.Int32Value < 0; } if (type == SpecialType.System_Int64) { return constantValue.Int64Value < 0; } // By the time we get here we definitely have int, long, uint or ulong. Obviously the // latter two are never negative. Debug.Assert(type == SpecialType.System_UInt32 || type == SpecialType.System_UInt64); return false; } /// <summary> /// Bind the (implicit or explicit) constructor initializer of a constructor symbol (in source). /// </summary> /// <param name="initializerArgumentListOpt"> /// Null for implicit, /// <see cref="ConstructorInitializerSyntax.ArgumentList"/>, or /// <see cref="PrimaryConstructorBaseTypeSyntax.ArgumentList"/> for explicit.</param> /// <param name="constructor">Constructor containing the initializer.</param> /// <param name="diagnostics">Accumulates errors (e.g. unable to find constructor to invoke).</param> /// <returns>A bound expression for the constructor initializer call.</returns> /// <remarks> /// This method should be kept consistent with Compiler.BindConstructorInitializer (e.g. same error codes). /// </remarks> internal BoundExpression BindConstructorInitializer( ArgumentListSyntax initializerArgumentListOpt, MethodSymbol constructor, BindingDiagnosticBag diagnostics) { Binder argumentListBinder = null; if (initializerArgumentListOpt != null) { argumentListBinder = this.GetBinder(initializerArgumentListOpt); } var result = (argumentListBinder ?? this).BindConstructorInitializerCore(initializerArgumentListOpt, constructor, diagnostics); if (argumentListBinder != null) { // This code is reachable only for speculative SemanticModel. Debug.Assert(argumentListBinder.IsSemanticModelBinder); result = argumentListBinder.WrapWithVariablesIfAny(initializerArgumentListOpt, result); } return result; } private BoundExpression BindConstructorInitializerCore( ArgumentListSyntax initializerArgumentListOpt, MethodSymbol constructor, BindingDiagnosticBag diagnostics) { // Either our base type is not object, or we have an initializer syntax, or both. We're going to // need to do overload resolution on the set of constructors of the base type, either on // the provided initializer syntax, or on an implicit ": base()" syntax. // SPEC ERROR: The specification states that if you have the situation // SPEC ERROR: class B { ... } class D1 : B {} then the default constructor // SPEC ERROR: generated for D1 must call an accessible *parameterless* constructor // SPEC ERROR: in B. However, it also states that if you have // SPEC ERROR: class B { ... } class D2 : B { D2() {} } or // SPEC ERROR: class B { ... } class D3 : B { D3() : base() {} } then // SPEC ERROR: the compiler performs *overload resolution* to determine // SPEC ERROR: which accessible constructor of B is called. Since B might have // SPEC ERROR: a ctor with all optional parameters, overload resolution might // SPEC ERROR: succeed even if there is no parameterless constructor. This // SPEC ERROR: is unintentionally inconsistent, and the native compiler does not // SPEC ERROR: implement this behavior. Rather, we should say in the spec that // SPEC ERROR: if there is no ctor in D1, then a ctor is created for you exactly // SPEC ERROR: as though you'd said "D1() : base() {}". // SPEC ERROR: This is what we now do in Roslyn. Debug.Assert((object)constructor != null); Debug.Assert(constructor.MethodKind == MethodKind.Constructor || constructor.MethodKind == MethodKind.StaticConstructor); // error scenario: constructor initializer on static constructor Debug.Assert(diagnostics != null); NamedTypeSymbol containingType = constructor.ContainingType; // Structs and enums do not have implicit constructor initializers. if ((containingType.TypeKind == TypeKind.Enum || containingType.TypeKind == TypeKind.Struct) && initializerArgumentListOpt == null) { return null; } AnalyzedArguments analyzedArguments = AnalyzedArguments.GetInstance(); try { TypeSymbol constructorReturnType = constructor.ReturnType; Debug.Assert(constructorReturnType.IsVoidType()); //true of all constructors NamedTypeSymbol baseType = containingType.BaseTypeNoUseSiteDiagnostics; // Get the bound arguments and the argument names. // : this(__arglist()) is legal if (initializerArgumentListOpt != null) { this.BindArgumentsAndNames(initializerArgumentListOpt, diagnostics, analyzedArguments, allowArglist: true); } NamedTypeSymbol initializerType = containingType; bool isBaseConstructorInitializer = initializerArgumentListOpt == null || initializerArgumentListOpt.Parent.Kind() != SyntaxKind.ThisConstructorInitializer; if (isBaseConstructorInitializer) { initializerType = initializerType.BaseTypeNoUseSiteDiagnostics; // Soft assert: we think this is the case, and we're asserting to catch scenarios that violate our expectations Debug.Assert((object)initializerType != null || containingType.SpecialType == SpecialType.System_Object || containingType.IsInterface); if ((object)initializerType == null || containingType.SpecialType == SpecialType.System_Object) //e.g. when defining System.Object in source { // If the constructor initializer is implicit and there is no base type, we're done. // Otherwise, if the constructor initializer is explicit, we're in an error state. if (initializerArgumentListOpt == null) { return null; } else { diagnostics.Add(ErrorCode.ERR_ObjectCallingBaseConstructor, constructor.Locations[0], containingType); return new BoundBadExpression( syntax: initializerArgumentListOpt.Parent, resultKind: LookupResultKind.Empty, symbols: ImmutableArray<Symbol>.Empty, childBoundNodes: BuildArgumentsForErrorRecovery(analyzedArguments), type: constructorReturnType); } } else if (initializerArgumentListOpt != null && containingType.TypeKind == TypeKind.Struct) { diagnostics.Add(ErrorCode.ERR_StructWithBaseConstructorCall, constructor.Locations[0], containingType); return new BoundBadExpression( syntax: initializerArgumentListOpt.Parent, resultKind: LookupResultKind.Empty, symbols: ImmutableArray<Symbol>.Empty, //CONSIDER: we could look for a matching constructor on System.ValueType childBoundNodes: BuildArgumentsForErrorRecovery(analyzedArguments), type: constructorReturnType); } } else { Debug.Assert(initializerArgumentListOpt.Parent.Kind() == SyntaxKind.ThisConstructorInitializer); } CSharpSyntaxNode nonNullSyntax; Location errorLocation; bool enableCallerInfo; switch (initializerArgumentListOpt?.Parent) { case ConstructorInitializerSyntax initializerSyntax: nonNullSyntax = initializerSyntax; errorLocation = initializerSyntax.ThisOrBaseKeyword.GetLocation(); enableCallerInfo = true; break; case PrimaryConstructorBaseTypeSyntax baseWithArguments: nonNullSyntax = baseWithArguments; errorLocation = initializerArgumentListOpt.GetLocation(); enableCallerInfo = true; break; default: // Note: use syntax node of constructor with initializer, not constructor invoked by initializer (i.e. methodResolutionResult). nonNullSyntax = constructor.GetNonNullSyntaxNode(); errorLocation = constructor.Locations[0]; enableCallerInfo = false; break; } if (initializerArgumentListOpt != null && analyzedArguments.HasDynamicArgument) { diagnostics.Add(ErrorCode.ERR_NoDynamicPhantomOnBaseCtor, errorLocation); return new BoundBadExpression( syntax: initializerArgumentListOpt.Parent, resultKind: LookupResultKind.Empty, symbols: ImmutableArray<Symbol>.Empty, //CONSIDER: we could look for a matching constructor on System.ValueType childBoundNodes: BuildArgumentsForErrorRecovery(analyzedArguments), type: constructorReturnType); } BoundExpression receiver = ThisReference(nonNullSyntax, initializerType, wasCompilerGenerated: true); MemberResolutionResult<MethodSymbol> memberResolutionResult; ImmutableArray<MethodSymbol> candidateConstructors; bool found = TryPerformConstructorOverloadResolution( initializerType, analyzedArguments, WellKnownMemberNames.InstanceConstructorName, errorLocation, false, // Don't suppress result diagnostics diagnostics, out memberResolutionResult, out candidateConstructors, allowProtectedConstructorsOfBaseType: true); MethodSymbol resultMember = memberResolutionResult.Member; validateRecordCopyConstructor(constructor, baseType, resultMember, errorLocation, diagnostics); if (found) { bool hasErrors = false; if (resultMember == constructor) { Debug.Assert(initializerType.IsErrorType() || (initializerArgumentListOpt != null && initializerArgumentListOpt.Parent.Kind() == SyntaxKind.ThisConstructorInitializer)); diagnostics.Add(ErrorCode.ERR_RecursiveConstructorCall, errorLocation, constructor); hasErrors = true; // prevent recursive constructor from being emitted } else if (resultMember.HasUnsafeParameter()) { // What if some of the arguments are implicit? Dev10 reports unsafe errors // if the implied argument would have an unsafe type. We need to check // the parameters explicitly, since there won't be bound nodes for the implied // arguments until lowering. // Don't worry about double reporting (i.e. for both the argument and the parameter) // because only one unsafe diagnostic is allowed per scope - the others are suppressed. hasErrors = ReportUnsafeIfNotAllowed(errorLocation, diagnostics); } ReportDiagnosticsIfObsolete(diagnostics, resultMember, nonNullSyntax, hasBaseReceiver: isBaseConstructorInitializer); var expanded = memberResolutionResult.Result.Kind == MemberResolutionKind.ApplicableInExpandedForm; var argsToParamsOpt = memberResolutionResult.Result.ArgsToParamsOpt; BindDefaultArguments(nonNullSyntax, resultMember.Parameters, analyzedArguments.Arguments, analyzedArguments.RefKinds, ref argsToParamsOpt, out var defaultArguments, expanded, enableCallerInfo, diagnostics); var arguments = analyzedArguments.Arguments.ToImmutable(); var refKinds = analyzedArguments.RefKinds.ToImmutableOrNull(); if (!hasErrors) { hasErrors = !CheckInvocationArgMixing( nonNullSyntax, resultMember, receiver, resultMember.Parameters, arguments, argsToParamsOpt, this.LocalScopeDepth, diagnostics); } return new BoundCall( nonNullSyntax, receiver, resultMember, arguments, analyzedArguments.GetNames(), refKinds, isDelegateCall: false, expanded, invokedAsExtensionMethod: false, argsToParamsOpt: argsToParamsOpt, defaultArguments: defaultArguments, resultKind: LookupResultKind.Viable, type: constructorReturnType, hasErrors: hasErrors) { WasCompilerGenerated = initializerArgumentListOpt == null }; } else { var result = CreateBadCall( node: nonNullSyntax, name: WellKnownMemberNames.InstanceConstructorName, receiver: receiver, methods: candidateConstructors, resultKind: LookupResultKind.OverloadResolutionFailure, typeArgumentsWithAnnotations: ImmutableArray<TypeWithAnnotations>.Empty, analyzedArguments: analyzedArguments, invokedAsExtensionMethod: false, isDelegate: false); result.WasCompilerGenerated = initializerArgumentListOpt == null; return result; } } finally { analyzedArguments.Free(); } static void validateRecordCopyConstructor(MethodSymbol constructor, NamedTypeSymbol baseType, MethodSymbol resultMember, Location errorLocation, BindingDiagnosticBag diagnostics) { if (IsUserDefinedRecordCopyConstructor(constructor)) { if (baseType.SpecialType == SpecialType.System_Object) { if (resultMember is null || resultMember.ContainingType.SpecialType != SpecialType.System_Object) { // Record deriving from object must use `base()`, not `this()` diagnostics.Add(ErrorCode.ERR_CopyConstructorMustInvokeBaseCopyConstructor, errorLocation); } return; } // Unless the base type is 'object', the constructor should invoke a base type copy constructor if (resultMember is null || !SynthesizedRecordCopyCtor.HasCopyConstructorSignature(resultMember)) { diagnostics.Add(ErrorCode.ERR_CopyConstructorMustInvokeBaseCopyConstructor, errorLocation); } } } } internal static bool IsUserDefinedRecordCopyConstructor(MethodSymbol constructor) { return constructor.ContainingType is SourceNamedTypeSymbol sourceType && sourceType.IsRecord && constructor is not SynthesizedRecordConstructor && SynthesizedRecordCopyCtor.HasCopyConstructorSignature(constructor); } private BoundExpression BindImplicitObjectCreationExpression(ImplicitObjectCreationExpressionSyntax node, BindingDiagnosticBag diagnostics) { var arguments = AnalyzedArguments.GetInstance(); BindArgumentsAndNames(node.ArgumentList, diagnostics, arguments, allowArglist: true); var result = new BoundUnconvertedObjectCreationExpression( node, arguments.Arguments.ToImmutable(), arguments.Names.ToImmutableOrNull(), arguments.RefKinds.ToImmutableOrNull(), node.Initializer); arguments.Free(); return result; } protected BoundExpression BindObjectCreationExpression(ObjectCreationExpressionSyntax node, BindingDiagnosticBag diagnostics) { var typeWithAnnotations = BindType(node.Type, diagnostics); var type = typeWithAnnotations.Type; var originalType = type; if (typeWithAnnotations.NullableAnnotation.IsAnnotated() && !type.IsNullableType()) { diagnostics.Add(ErrorCode.ERR_AnnotationDisallowedInObjectCreation, node.Location, type); } switch (type.TypeKind) { case TypeKind.Struct: case TypeKind.Class: case TypeKind.Enum: case TypeKind.Error: return BindClassCreationExpression(node, (NamedTypeSymbol)type, GetName(node.Type), diagnostics, originalType); case TypeKind.Delegate: return BindDelegateCreationExpression(node, (NamedTypeSymbol)type, diagnostics); case TypeKind.Interface: return BindInterfaceCreationExpression(node, (NamedTypeSymbol)type, diagnostics); case TypeKind.TypeParameter: return BindTypeParameterCreationExpression(node, (TypeParameterSymbol)type, diagnostics); case TypeKind.Submission: // script class is synthesized and should not be used as a type of a new expression: throw ExceptionUtilities.UnexpectedValue(type.TypeKind); case TypeKind.Pointer: case TypeKind.FunctionPointer: type = new ExtendedErrorTypeSymbol(type, LookupResultKind.NotCreatable, diagnostics.Add(ErrorCode.ERR_UnsafeTypeInObjectCreation, node.Location, type)); goto case TypeKind.Class; case TypeKind.Dynamic: // we didn't find any type called "dynamic" so we are using the builtin dynamic type, which has no constructors: case TypeKind.Array: // ex: new ref[] type = new ExtendedErrorTypeSymbol(type, LookupResultKind.NotCreatable, diagnostics.Add(ErrorCode.ERR_InvalidObjectCreation, node.Type.Location, type)); goto case TypeKind.Class; default: throw ExceptionUtilities.UnexpectedValue(type.TypeKind); } } private BoundExpression BindDelegateCreationExpression(ObjectCreationExpressionSyntax node, NamedTypeSymbol type, BindingDiagnosticBag diagnostics) { AnalyzedArguments analyzedArguments = AnalyzedArguments.GetInstance(); BindArgumentsAndNames(node.ArgumentList, diagnostics, analyzedArguments, isDelegateCreation: true); var result = BindDelegateCreationExpression(node, type, analyzedArguments, node.Initializer, diagnostics); analyzedArguments.Free(); return result; } private BoundExpression BindDelegateCreationExpression(SyntaxNode node, NamedTypeSymbol type, AnalyzedArguments analyzedArguments, InitializerExpressionSyntax initializerOpt, BindingDiagnosticBag diagnostics) { bool hasErrors = false; if (analyzedArguments.HasErrors) { // Let's skip this part of further error checking without marking hasErrors = true here, // as the argument could be an unbound lambda, and the error could come from inside. // We'll check analyzedArguments.HasErrors again after we find if this is not the case. } else if (analyzedArguments.Arguments.Count == 0) { diagnostics.Add(ErrorCode.ERR_BadCtorArgCount, node.Location, type, 0); hasErrors = true; } else if (analyzedArguments.Names.Count != 0 || analyzedArguments.RefKinds.Count != 0 || analyzedArguments.Arguments.Count != 1) { // Use a smaller span that excludes the parens. var argSyntax = analyzedArguments.Arguments[0].Syntax; var start = argSyntax.SpanStart; var end = analyzedArguments.Arguments[analyzedArguments.Arguments.Count - 1].Syntax.Span.End; var errorSpan = new TextSpan(start, end - start); var loc = new SourceLocation(argSyntax.SyntaxTree, errorSpan); diagnostics.Add(ErrorCode.ERR_MethodNameExpected, loc); hasErrors = true; } if (initializerOpt != null) { Error(diagnostics, ErrorCode.ERR_ObjectOrCollectionInitializerWithDelegateCreation, node); hasErrors = true; } BoundExpression argument = analyzedArguments.Arguments.Count >= 1 ? BindToNaturalType(analyzedArguments.Arguments[0], diagnostics) : null; if (hasErrors) { // skip the rest of this binding } // There are four cases for a delegate creation expression (7.6.10.5): // 1. An anonymous function is treated as a conversion from the anonymous function to the delegate type. else if (argument is UnboundLambda unboundLambda) { // analyzedArguments.HasErrors could be true, // but here the argument is an unbound lambda, the error comes from inside // eg: new Action<int>(x => x.) // We should try to bind it anyway in order for intellisense to work. CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); var conversion = this.Conversions.ClassifyConversionFromExpression(unboundLambda, type, ref useSiteInfo); diagnostics.Add(node, useSiteInfo); // Attempting to make the conversion caches the diagnostics and the bound state inside // the unbound lambda. Fetch the result from the cache. BoundLambda boundLambda = unboundLambda.Bind(type); if (!conversion.IsImplicit || !conversion.IsValid) { GenerateImplicitConversionError(diagnostics, unboundLambda.Syntax, conversion, unboundLambda, type); } else { // We're not going to produce an error, but it is possible that the conversion from // the lambda to the delegate type produced a warning, which we have not reported. // Instead, we've cached it in the bound lambda. Report it now. diagnostics.AddRange(boundLambda.Diagnostics); } // Just stuff the bound lambda into the delegate creation expression. When we lower the lambda to // its method form we will rewrite this expression to refer to the method. return new BoundDelegateCreationExpression(node, boundLambda, methodOpt: null, isExtensionMethod: false, type: type, hasErrors: !conversion.IsImplicit); } else if (analyzedArguments.HasErrors) { // There is no hope, skip. } // 2. A method group else if (argument.Kind == BoundKind.MethodGroup) { Conversion conversion; BoundMethodGroup methodGroup = (BoundMethodGroup)argument; hasErrors = MethodGroupConversionDoesNotExistOrHasErrors(methodGroup, type, node.Location, diagnostics, out conversion); methodGroup = FixMethodGroupWithTypeOrValue(methodGroup, conversion, diagnostics); return new BoundDelegateCreationExpression(node, methodGroup, conversion.Method, conversion.IsExtensionMethod, type, hasErrors); } else if ((object)argument.Type == null) { diagnostics.Add(ErrorCode.ERR_MethodNameExpected, argument.Syntax.Location); } // 3. A value of the compile-time type dynamic (which is dynamically case 4), or else if (argument.HasDynamicType()) { return new BoundDelegateCreationExpression(node, argument, methodOpt: null, isExtensionMethod: false, type: type); } // 4. A delegate type. else if (argument.Type.TypeKind == TypeKind.Delegate) { var sourceDelegate = (NamedTypeSymbol)argument.Type; MethodGroup methodGroup = MethodGroup.GetInstance(); try { if (ReportDelegateInvokeUseSiteDiagnostic(diagnostics, argument.Type, node: node)) { // We want failed "new" expression to use the constructors as their symbols. return new BoundBadExpression(node, LookupResultKind.NotInvocable, StaticCast<Symbol>.From(type.InstanceConstructors), ImmutableArray.Create(argument), type); } methodGroup.PopulateWithSingleMethod(argument, sourceDelegate.DelegateInvokeMethod); CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); Conversion conv = Conversions.MethodGroupConversion(argument.Syntax, methodGroup, type, ref useSiteInfo); diagnostics.Add(node, useSiteInfo); if (!conv.Exists) { var boundMethodGroup = new BoundMethodGroup( argument.Syntax, default, WellKnownMemberNames.DelegateInvokeName, ImmutableArray.Create(sourceDelegate.DelegateInvokeMethod), sourceDelegate.DelegateInvokeMethod, null, BoundMethodGroupFlags.None, argument, LookupResultKind.Viable); if (!Conversions.ReportDelegateOrFunctionPointerMethodGroupDiagnostics(this, boundMethodGroup, type, diagnostics)) { // If we could not produce a more specialized diagnostic, we report // No overload for '{0}' matches delegate '{1}' diagnostics.Add(ErrorCode.ERR_MethDelegateMismatch, node.Location, sourceDelegate.DelegateInvokeMethod, type); } } else { Debug.Assert(!conv.IsExtensionMethod); Debug.Assert(conv.IsValid); // i.e. if it exists, then it is valid. if (!this.MethodGroupConversionHasErrors(argument.Syntax, conv, argument, conv.IsExtensionMethod, isAddressOf: false, type, diagnostics)) { // we do not place the "Invoke" method in the node, indicating that it did not appear in source. return new BoundDelegateCreationExpression(node, argument, methodOpt: null, isExtensionMethod: false, type: type); } } } finally { methodGroup.Free(); } } // Not a valid delegate creation expression else { diagnostics.Add(ErrorCode.ERR_MethodNameExpected, argument.Syntax.Location); } // Note that we want failed "new" expression to use the constructors as their symbols. var childNodes = BuildArgumentsForErrorRecovery(analyzedArguments); return new BoundBadExpression(node, LookupResultKind.OverloadResolutionFailure, StaticCast<Symbol>.From(type.InstanceConstructors), childNodes, type); } private BoundExpression BindClassCreationExpression(ObjectCreationExpressionSyntax node, NamedTypeSymbol type, string typeName, BindingDiagnosticBag diagnostics, TypeSymbol initializerType = null) { // Get the bound arguments and the argument names. AnalyzedArguments analyzedArguments = AnalyzedArguments.GetInstance(); try { // new C(__arglist()) is legal BindArgumentsAndNames(node.ArgumentList, diagnostics, analyzedArguments, allowArglist: true); // No point in performing overload resolution if the type is static or a tuple literal. // Just return a bad expression containing the arguments. if (type.IsStatic) { diagnostics.Add(ErrorCode.ERR_InstantiatingStaticClass, node.Location, type); return MakeBadExpressionForObjectCreation(node, type, analyzedArguments, diagnostics); } else if (node.Type.Kind() == SyntaxKind.TupleType) { diagnostics.Add(ErrorCode.ERR_NewWithTupleTypeSyntax, node.Type.GetLocation()); return MakeBadExpressionForObjectCreation(node, type, analyzedArguments, diagnostics); } return BindClassCreationExpression(node, typeName, node.Type, type, analyzedArguments, diagnostics, node.Initializer, initializerType); } finally { analyzedArguments.Free(); } } #nullable enable /// <summary> /// Helper method to create a synthesized constructor invocation. /// </summary> private BoundExpression MakeConstructorInvocation( NamedTypeSymbol type, ArrayBuilder<BoundExpression> arguments, ArrayBuilder<RefKind> refKinds, SyntaxNode node, BindingDiagnosticBag diagnostics) { Debug.Assert(type.TypeKind is TypeKind.Class or TypeKind.Struct); var analyzedArguments = AnalyzedArguments.GetInstance(); try { analyzedArguments.Arguments.AddRange(arguments); analyzedArguments.RefKinds.AddRange(refKinds); if (type.IsStatic) { diagnostics.Add(ErrorCode.ERR_InstantiatingStaticClass, node.Location, type); return MakeBadExpressionForObjectCreation(node, type, analyzedArguments, initializerOpt: null, typeSyntax: null, diagnostics, wasCompilerGenerated: true); } var creation = BindClassCreationExpression(node, type.Name, node, type, analyzedArguments, diagnostics); creation.WasCompilerGenerated = true; return creation; } finally { analyzedArguments.Free(); } } internal BoundExpression BindObjectCreationForErrorRecovery(BoundUnconvertedObjectCreationExpression node, BindingDiagnosticBag diagnostics) { var arguments = AnalyzedArguments.GetInstance(node.Arguments, node.ArgumentRefKindsOpt, node.ArgumentNamesOpt); var result = MakeBadExpressionForObjectCreation(node.Syntax, CreateErrorType(), arguments, node.InitializerOpt, typeSyntax: node.Syntax, diagnostics); arguments.Free(); return result; } private BoundExpression MakeBadExpressionForObjectCreation(ObjectCreationExpressionSyntax node, TypeSymbol type, AnalyzedArguments analyzedArguments, BindingDiagnosticBag diagnostics, bool wasCompilerGenerated = false) { return MakeBadExpressionForObjectCreation(node, type, analyzedArguments, node.Initializer, node.Type, diagnostics, wasCompilerGenerated); } /// <param name="typeSyntax">Shouldn't be null if <paramref name="initializerOpt"/> is not null.</param> private BoundExpression MakeBadExpressionForObjectCreation(SyntaxNode node, TypeSymbol type, AnalyzedArguments analyzedArguments, InitializerExpressionSyntax? initializerOpt, SyntaxNode? typeSyntax, BindingDiagnosticBag diagnostics, bool wasCompilerGenerated = false) { var children = ArrayBuilder<BoundExpression>.GetInstance(); children.AddRange(BuildArgumentsForErrorRecovery(analyzedArguments)); if (initializerOpt != null) { Debug.Assert(typeSyntax is not null); var boundInitializer = BindInitializerExpression(syntax: initializerOpt, type: type, typeSyntax: typeSyntax, isForNewInstance: true, diagnostics: diagnostics); children.Add(boundInitializer); } return new BoundBadExpression(node, LookupResultKind.NotCreatable, ImmutableArray.Create<Symbol?>(type), children.ToImmutableAndFree(), type) { WasCompilerGenerated = wasCompilerGenerated }; } #nullable disable private BoundObjectInitializerExpressionBase BindInitializerExpression( InitializerExpressionSyntax syntax, TypeSymbol type, SyntaxNode typeSyntax, bool isForNewInstance, BindingDiagnosticBag diagnostics) { Debug.Assert(syntax != null); Debug.Assert((object)type != null); var implicitReceiver = new BoundObjectOrCollectionValuePlaceholder(typeSyntax, isForNewInstance, type) { WasCompilerGenerated = true }; switch (syntax.Kind()) { case SyntaxKind.ObjectInitializerExpression: // Uses a special binder to produce customized diagnostics for the object initializer return BindObjectInitializerExpression( syntax, type, diagnostics, implicitReceiver, useObjectInitDiagnostics: true); case SyntaxKind.WithInitializerExpression: return BindObjectInitializerExpression( syntax, type, diagnostics, implicitReceiver, useObjectInitDiagnostics: false); case SyntaxKind.CollectionInitializerExpression: return BindCollectionInitializerExpression(syntax, type, diagnostics, implicitReceiver); default: throw ExceptionUtilities.Unreachable; } } private BoundExpression BindInitializerExpressionOrValue( ExpressionSyntax syntax, TypeSymbol type, SyntaxNode typeSyntax, BindingDiagnosticBag diagnostics) { Debug.Assert(syntax != null); Debug.Assert((object)type != null); switch (syntax.Kind()) { case SyntaxKind.ObjectInitializerExpression: case SyntaxKind.CollectionInitializerExpression: Debug.Assert(syntax.Parent.Parent.Kind() != SyntaxKind.WithInitializerExpression); return BindInitializerExpression((InitializerExpressionSyntax)syntax, type, typeSyntax, isForNewInstance: false, diagnostics); default: return BindValue(syntax, diagnostics, BindValueKind.RValue); } } private BoundObjectInitializerExpression BindObjectInitializerExpression( InitializerExpressionSyntax initializerSyntax, TypeSymbol initializerType, BindingDiagnosticBag diagnostics, BoundObjectOrCollectionValuePlaceholder implicitReceiver, bool useObjectInitDiagnostics) { // SPEC: 7.6.10.2 Object initializers // // SPEC: An object initializer consists of a sequence of member initializers, enclosed by { and } tokens and separated by commas. // SPEC: Each member initializer must name an accessible field or property of the object being initialized, followed by an equals sign and // SPEC: an expression or an object initializer or collection initializer. Debug.Assert(initializerSyntax.Kind() == SyntaxKind.ObjectInitializerExpression || initializerSyntax.Kind() == SyntaxKind.WithInitializerExpression); Debug.Assert((object)initializerType != null); // We use a location specific binder for binding object initializer field/property access to generate object initializer specific diagnostics: // 1) CS1914 (ERR_StaticMemberInObjectInitializer) // 2) CS1917 (ERR_ReadonlyValueTypeInObjectInitializer) // 3) CS1918 (ERR_ValueTypePropertyInObjectInitializer) // Note that this is only used for the LHS of the assignment - these diagnostics do not apply on the RHS. // For this reason, we will actually need two binders: this and this.WithAdditionalFlags. var objectInitializerMemberBinder = useObjectInitDiagnostics ? this.WithAdditionalFlags(BinderFlags.ObjectInitializerMember) : this; var initializers = ArrayBuilder<BoundExpression>.GetInstance(initializerSyntax.Expressions.Count); // Member name map to report duplicate assignments to a field/property. var memberNameMap = PooledHashSet<string>.GetInstance(); foreach (var memberInitializer in initializerSyntax.Expressions) { BoundExpression boundMemberInitializer = BindInitializerMemberAssignment( memberInitializer, initializerType, objectInitializerMemberBinder, diagnostics, implicitReceiver); initializers.Add(boundMemberInitializer); ReportDuplicateObjectMemberInitializers(boundMemberInitializer, memberNameMap, diagnostics); } return new BoundObjectInitializerExpression( initializerSyntax, implicitReceiver, initializers.ToImmutableAndFree(), initializerType); } private BoundExpression BindInitializerMemberAssignment( ExpressionSyntax memberInitializer, TypeSymbol initializerType, Binder objectInitializerMemberBinder, BindingDiagnosticBag diagnostics, BoundObjectOrCollectionValuePlaceholder implicitReceiver) { // SPEC: A member initializer that specifies an expression after the equals sign is processed in the same way as an assignment (spec 7.17.1) to the field or property. if (memberInitializer.Kind() == SyntaxKind.SimpleAssignmentExpression) { var initializer = (AssignmentExpressionSyntax)memberInitializer; // Bind member initializer identifier, i.e. left part of assignment BoundExpression boundLeft = null; var leftSyntax = initializer.Left; if (initializerType.IsDynamic() && leftSyntax.Kind() == SyntaxKind.IdentifierName) { { // D = { ..., <identifier> = <expr>, ... }, where D : dynamic var memberName = ((IdentifierNameSyntax)leftSyntax).Identifier.Text; boundLeft = new BoundDynamicObjectInitializerMember(leftSyntax, memberName, implicitReceiver.Type, initializerType, hasErrors: false); } } else { // We use a location specific binder for binding object initializer field/property access to generate object initializer specific diagnostics: // 1) CS1914 (ERR_StaticMemberInObjectInitializer) // 2) CS1917 (ERR_ReadonlyValueTypeInObjectInitializer) // 3) CS1918 (ERR_ValueTypePropertyInObjectInitializer) // See comments in BindObjectInitializerExpression for more details. Debug.Assert(objectInitializerMemberBinder != null); boundLeft = objectInitializerMemberBinder.BindObjectInitializerMember(initializer, implicitReceiver, diagnostics); } if (boundLeft != null) { Debug.Assert((object)boundLeft.Type != null); // Bind member initializer value, i.e. right part of assignment BoundExpression boundRight = BindInitializerExpressionOrValue( syntax: initializer.Right, type: boundLeft.Type, typeSyntax: boundLeft.Syntax, diagnostics: diagnostics); // Bind member initializer assignment expression return BindAssignment(initializer, boundLeft, boundRight, isRef: false, diagnostics); } } var boundExpression = BindValue(memberInitializer, diagnostics, BindValueKind.RValue); Error(diagnostics, ErrorCode.ERR_InvalidInitializerElementInitializer, memberInitializer); return ToBadExpression(boundExpression, LookupResultKind.NotAValue); } // returns BadBoundExpression or BoundObjectInitializerMember private BoundExpression BindObjectInitializerMember( AssignmentExpressionSyntax namedAssignment, BoundObjectOrCollectionValuePlaceholder implicitReceiver, BindingDiagnosticBag diagnostics) { BoundExpression boundMember; LookupResultKind resultKind; bool hasErrors; if (namedAssignment.Left.Kind() == SyntaxKind.IdentifierName) { var memberName = (IdentifierNameSyntax)namedAssignment.Left; // SPEC: Each member initializer must name an accessible field or property of the object being initialized, followed by an equals sign and // SPEC: an expression or an object initializer or collection initializer. // SPEC: A member initializer that specifies an expression after the equals sign is processed in the same way as an assignment (7.17.1) to the field or property. // SPEC VIOLATION: Native compiler also allows initialization of field-like events in object initializers, so we allow it as well. boundMember = BindInstanceMemberAccess( node: memberName, right: memberName, boundLeft: implicitReceiver, rightName: memberName.Identifier.ValueText, rightArity: 0, typeArgumentsSyntax: default(SeparatedSyntaxList<TypeSyntax>), typeArgumentsWithAnnotations: default(ImmutableArray<TypeWithAnnotations>), invoked: false, indexed: false, diagnostics: diagnostics); resultKind = boundMember.ResultKind; hasErrors = boundMember.HasAnyErrors || implicitReceiver.HasAnyErrors; if (boundMember.Kind == BoundKind.PropertyGroup) { boundMember = BindIndexedPropertyAccess((BoundPropertyGroup)boundMember, mustHaveAllOptionalParameters: true, diagnostics: diagnostics); if (boundMember.HasAnyErrors) { hasErrors = true; } } } else if (namedAssignment.Left.Kind() == SyntaxKind.ImplicitElementAccess) { var implicitIndexing = (ImplicitElementAccessSyntax)namedAssignment.Left; boundMember = BindElementAccess(implicitIndexing, implicitReceiver, implicitIndexing.ArgumentList, diagnostics); resultKind = boundMember.ResultKind; hasErrors = boundMember.HasAnyErrors || implicitReceiver.HasAnyErrors; } else { return null; } // SPEC: A member initializer that specifies an object initializer after the equals sign is a nested object initializer, // SPEC: i.e. an initialization of an embedded object. Instead of assigning a new value to the field or property, // SPEC: the assignments in the nested object initializer are treated as assignments to members of the field or property. // SPEC: Nested object initializers cannot be applied to properties with a value type, or to read-only fields with a value type. // NOTE: The dev11 behavior does not match the spec that was current at the time (quoted above). However, in the roslyn // NOTE: timeframe, the spec will be updated to apply the same restriction to nested collection initializers. Therefore, // NOTE: roslyn will implement the dev11 behavior and it will be spec-compliant. // NOTE: In the roslyn timeframe, an additional restriction will (likely) be added to the spec - it is not sufficient for the // NOTE: type of the member to not be a value type - it must actually be a reference type (i.e. unconstrained type parameters // NOTE: should be prohibited). To avoid breaking existing code, roslyn will not implement this new spec clause. // TODO: If/when we have a way to version warnings, we should add a warning for this. BoundKind boundMemberKind = boundMember.Kind; SyntaxKind rhsKind = namedAssignment.Right.Kind(); bool isRhsNestedInitializer = rhsKind == SyntaxKind.ObjectInitializerExpression || rhsKind == SyntaxKind.CollectionInitializerExpression; BindValueKind valueKind = isRhsNestedInitializer ? BindValueKind.RValue : BindValueKind.Assignable; ImmutableArray<BoundExpression> arguments = ImmutableArray<BoundExpression>.Empty; ImmutableArray<string> argumentNamesOpt = default(ImmutableArray<string>); ImmutableArray<int> argsToParamsOpt = default(ImmutableArray<int>); ImmutableArray<RefKind> argumentRefKindsOpt = default(ImmutableArray<RefKind>); BitVector defaultArguments = default(BitVector); bool expanded = false; switch (boundMemberKind) { case BoundKind.FieldAccess: { var fieldSymbol = ((BoundFieldAccess)boundMember).FieldSymbol; if (isRhsNestedInitializer && fieldSymbol.IsReadOnly && fieldSymbol.Type.IsValueType) { if (!hasErrors) { // TODO: distinct error code for collection initializers? (Dev11 doesn't have one.) Error(diagnostics, ErrorCode.ERR_ReadonlyValueTypeInObjectInitializer, namedAssignment.Left, fieldSymbol, fieldSymbol.Type); hasErrors = true; } resultKind = LookupResultKind.NotAValue; } break; } case BoundKind.EventAccess: break; case BoundKind.PropertyAccess: hasErrors |= isRhsNestedInitializer && !CheckNestedObjectInitializerPropertySymbol(((BoundPropertyAccess)boundMember).PropertySymbol, namedAssignment.Left, diagnostics, hasErrors, ref resultKind); break; case BoundKind.IndexerAccess: { var indexer = BindIndexerDefaultArguments((BoundIndexerAccess)boundMember, valueKind, diagnostics); boundMember = indexer; hasErrors |= isRhsNestedInitializer && !CheckNestedObjectInitializerPropertySymbol(indexer.Indexer, namedAssignment.Left, diagnostics, hasErrors, ref resultKind); arguments = indexer.Arguments; argumentNamesOpt = indexer.ArgumentNamesOpt; argsToParamsOpt = indexer.ArgsToParamsOpt; argumentRefKindsOpt = indexer.ArgumentRefKindsOpt; defaultArguments = indexer.DefaultArguments; expanded = indexer.Expanded; break; } case BoundKind.DynamicIndexerAccess: { var indexer = (BoundDynamicIndexerAccess)boundMember; arguments = indexer.Arguments; argumentNamesOpt = indexer.ArgumentNamesOpt; argumentRefKindsOpt = indexer.ArgumentRefKindsOpt; } break; case BoundKind.ArrayAccess: case BoundKind.PointerElementAccess: return boundMember; default: return BadObjectInitializerMemberAccess(boundMember, implicitReceiver, namedAssignment.Left, diagnostics, valueKind, hasErrors); } if (!hasErrors) { // CheckValueKind to generate possible diagnostics for invalid initializers non-viable member lookup result: // 1) CS0154 (ERR_PropertyLacksGet) // 2) CS0200 (ERR_AssgReadonlyProp) if (!CheckValueKind(boundMember.Syntax, boundMember, valueKind, checkingReceiver: false, diagnostics: diagnostics)) { hasErrors = true; resultKind = isRhsNestedInitializer ? LookupResultKind.NotAValue : LookupResultKind.NotAVariable; } } return new BoundObjectInitializerMember( namedAssignment.Left, boundMember.ExpressionSymbol, arguments, argumentNamesOpt, argumentRefKindsOpt, expanded, argsToParamsOpt, defaultArguments, resultKind, implicitReceiver.Type, type: boundMember.Type, hasErrors: hasErrors); } private static bool CheckNestedObjectInitializerPropertySymbol( PropertySymbol propertySymbol, ExpressionSyntax memberNameSyntax, BindingDiagnosticBag diagnostics, bool suppressErrors, ref LookupResultKind resultKind) { bool hasErrors = false; if (propertySymbol.Type.IsValueType) { if (!suppressErrors) { // TODO: distinct error code for collection initializers? (Dev11 doesn't have one.) Error(diagnostics, ErrorCode.ERR_ValueTypePropertyInObjectInitializer, memberNameSyntax, propertySymbol, propertySymbol.Type); hasErrors = true; } resultKind = LookupResultKind.NotAValue; } return !hasErrors; } private BoundExpression BadObjectInitializerMemberAccess( BoundExpression boundMember, BoundObjectOrCollectionValuePlaceholder implicitReceiver, ExpressionSyntax memberNameSyntax, BindingDiagnosticBag diagnostics, BindValueKind valueKind, bool suppressErrors) { if (!suppressErrors) { string member; var identName = memberNameSyntax as IdentifierNameSyntax; if (identName != null) { member = identName.Identifier.ValueText; } else { member = memberNameSyntax.ToString(); } switch (boundMember.ResultKind) { case LookupResultKind.Empty: Error(diagnostics, ErrorCode.ERR_NoSuchMember, memberNameSyntax, implicitReceiver.Type, member); break; case LookupResultKind.Inaccessible: boundMember = CheckValue(boundMember, valueKind, diagnostics); Debug.Assert(boundMember.HasAnyErrors); break; default: Error(diagnostics, ErrorCode.ERR_MemberCannotBeInitialized, memberNameSyntax, member); break; } } return ToBadExpression(boundMember, (valueKind == BindValueKind.RValue) ? LookupResultKind.NotAValue : LookupResultKind.NotAVariable); } private static void ReportDuplicateObjectMemberInitializers(BoundExpression boundMemberInitializer, HashSet<string> memberNameMap, BindingDiagnosticBag diagnostics) { Debug.Assert(memberNameMap != null); // SPEC: It is an error for an object initializer to include more than one member initializer for the same field or property. if (!boundMemberInitializer.HasAnyErrors) { // SPEC: A member initializer that specifies an expression after the equals sign is processed in the same way as an assignment (7.17.1) to the field or property. var memberInitializerSyntax = boundMemberInitializer.Syntax; Debug.Assert(memberInitializerSyntax.Kind() == SyntaxKind.SimpleAssignmentExpression); var namedAssignment = (AssignmentExpressionSyntax)memberInitializerSyntax; var memberNameSyntax = namedAssignment.Left as IdentifierNameSyntax; if (memberNameSyntax != null) { var memberName = memberNameSyntax.Identifier.ValueText; if (!memberNameMap.Add(memberName)) { Error(diagnostics, ErrorCode.ERR_MemberAlreadyInitialized, memberNameSyntax, memberName); } } } } private BoundCollectionInitializerExpression BindCollectionInitializerExpression( InitializerExpressionSyntax initializerSyntax, TypeSymbol initializerType, BindingDiagnosticBag diagnostics, BoundObjectOrCollectionValuePlaceholder implicitReceiver) { // SPEC: 7.6.10.3 Collection initializers // // SPEC: A collection initializer consists of a sequence of element initializers, enclosed by { and } tokens and separated by commas. // SPEC: The following is an example of an object creation expression that includes a collection initializer: // SPEC: List<int> digits = new List<int> { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; // SPEC: The collection object to which a collection initializer is applied must be of a type that implements System.Collections.IEnumerable or // SPEC: a compile-time error occurs. For each specified element in order, the collection initializer invokes an Add method on the target object // SPEC: with the expression list of the element initializer as argument list, applying normal overload resolution for each invocation. // SPEC: Thus, the collection object must contain an applicable Add method for each element initializer. Debug.Assert(initializerSyntax.Kind() == SyntaxKind.CollectionInitializerExpression); Debug.Assert(initializerSyntax.Expressions.Any()); Debug.Assert((object)initializerType != null); var initializerBuilder = ArrayBuilder<BoundExpression>.GetInstance(); // SPEC: The collection object to which a collection initializer is applied must be of a type that implements System.Collections.IEnumerable or // SPEC: a compile-time error occurs. bool hasEnumerableInitializerType = CollectionInitializerTypeImplementsIEnumerable(initializerType, initializerSyntax, diagnostics); if (!hasEnumerableInitializerType && !initializerSyntax.HasErrors && !initializerType.IsErrorType()) { Error(diagnostics, ErrorCode.ERR_CollectionInitRequiresIEnumerable, initializerSyntax, initializerType); } // We use a location specific binder for binding collection initializer Add method to generate specific overload resolution diagnostics: // 1) CS1921 (ERR_InitializerAddHasWrongSignature) // 2) CS1950 (ERR_BadArgTypesForCollectionAdd) // 3) CS1954 (ERR_InitializerAddHasParamModifiers) var collectionInitializerAddMethodBinder = this.WithAdditionalFlags(BinderFlags.CollectionInitializerAddMethod); foreach (var elementInitializer in initializerSyntax.Expressions) { // NOTE: collectionInitializerAddMethodBinder is used only for binding the Add method invocation expression, but not the entire initializer. // NOTE: Hence it is being passed as a parameter to BindCollectionInitializerElement(). // NOTE: Ideally we would want to avoid this and bind the entire initializer with the collectionInitializerAddMethodBinder. // NOTE: However, this approach has few issues. These issues also occur when binding object initializer member assignment. // NOTE: See comments for objectInitializerMemberBinder in BindObjectInitializerExpression method for details about the pitfalls of alternate approaches. BoundExpression boundElementInitializer = BindCollectionInitializerElement(elementInitializer, initializerType, hasEnumerableInitializerType, collectionInitializerAddMethodBinder, diagnostics, implicitReceiver); initializerBuilder.Add(boundElementInitializer); } return new BoundCollectionInitializerExpression(initializerSyntax, implicitReceiver, initializerBuilder.ToImmutableAndFree(), initializerType); } private bool CollectionInitializerTypeImplementsIEnumerable(TypeSymbol initializerType, CSharpSyntaxNode node, BindingDiagnosticBag diagnostics) { // SPEC: The collection object to which a collection initializer is applied must be of a type that implements System.Collections.IEnumerable or // SPEC: a compile-time error occurs. if (initializerType.IsDynamic()) { // We cannot determine at compile time if initializerType implements System.Collections.IEnumerable, we must assume that it does. return true; } else if (!initializerType.IsErrorType()) { TypeSymbol collectionsIEnumerableType = this.GetSpecialType(SpecialType.System_Collections_IEnumerable, diagnostics, node); // NOTE: Ideally, to check if the initializer type implements System.Collections.IEnumerable we can walk through // NOTE: its implemented interfaces. However the native compiler checks to see if there is conversion from initializer // NOTE: type to the predefined System.Collections.IEnumerable type, so we do the same. CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); var result = Conversions.ClassifyImplicitConversionFromType(initializerType, collectionsIEnumerableType, ref useSiteInfo).IsValid; diagnostics.Add(node, useSiteInfo); return result; } else { return false; } } private BoundExpression BindCollectionInitializerElement( ExpressionSyntax elementInitializer, TypeSymbol initializerType, bool hasEnumerableInitializerType, Binder collectionInitializerAddMethodBinder, BindingDiagnosticBag diagnostics, BoundObjectOrCollectionValuePlaceholder implicitReceiver) { // SPEC: Each element initializer specifies an element to be added to the collection object being initialized, and consists of // SPEC: a list of expressions enclosed by { and } tokens and separated by commas. // SPEC: A single-expression element initializer can be written without braces, but cannot then be an assignment expression, // SPEC: to avoid ambiguity with member initializers. The non-assignment-expression production is defined in 7.18. if (elementInitializer.Kind() == SyntaxKind.ComplexElementInitializerExpression) { return BindComplexElementInitializerExpression( (InitializerExpressionSyntax)elementInitializer, diagnostics, hasEnumerableInitializerType, collectionInitializerAddMethodBinder, implicitReceiver); } else { // Must be a non-assignment expression. if (SyntaxFacts.IsAssignmentExpression(elementInitializer.Kind())) { Error(diagnostics, ErrorCode.ERR_InvalidInitializerElementInitializer, elementInitializer); } var boundElementInitializer = BindInitializerExpressionOrValue(elementInitializer, initializerType, implicitReceiver.Syntax, diagnostics); BoundExpression result = BindCollectionInitializerElementAddMethod( elementInitializer, ImmutableArray.Create(boundElementInitializer), hasEnumerableInitializerType, collectionInitializerAddMethodBinder, diagnostics, implicitReceiver); result.WasCompilerGenerated = true; return result; } } private BoundExpression BindComplexElementInitializerExpression( InitializerExpressionSyntax elementInitializer, BindingDiagnosticBag diagnostics, bool hasEnumerableInitializerType, Binder collectionInitializerAddMethodBinder = null, BoundObjectOrCollectionValuePlaceholder implicitReceiver = null) { var elementInitializerExpressions = elementInitializer.Expressions; if (elementInitializerExpressions.Any()) { var exprBuilder = ArrayBuilder<BoundExpression>.GetInstance(); foreach (var childElementInitializer in elementInitializerExpressions) { exprBuilder.Add(BindValue(childElementInitializer, diagnostics, BindValueKind.RValue)); } return BindCollectionInitializerElementAddMethod( elementInitializer, exprBuilder.ToImmutableAndFree(), hasEnumerableInitializerType, collectionInitializerAddMethodBinder, diagnostics, implicitReceiver); } else { Error(diagnostics, ErrorCode.ERR_EmptyElementInitializer, elementInitializer); return BadExpression(elementInitializer, LookupResultKind.NotInvocable); } } private BoundExpression BindUnexpectedComplexElementInitializer(InitializerExpressionSyntax node, BindingDiagnosticBag diagnostics) { Debug.Assert(node.Kind() == SyntaxKind.ComplexElementInitializerExpression); return BindComplexElementInitializerExpression(node, diagnostics, hasEnumerableInitializerType: false); } private BoundExpression BindCollectionInitializerElementAddMethod( ExpressionSyntax elementInitializer, ImmutableArray<BoundExpression> boundElementInitializerExpressions, bool hasEnumerableInitializerType, Binder collectionInitializerAddMethodBinder, BindingDiagnosticBag diagnostics, BoundObjectOrCollectionValuePlaceholder implicitReceiver) { // SPEC: For each specified element in order, the collection initializer invokes an Add method on the target object // SPEC: with the expression list of the element initializer as argument list, applying normal overload resolution for each invocation. // SPEC: Thus, the collection object must contain an applicable Add method for each element initializer. // We use a location specific binder for binding collection initializer Add method to generate specific overload resolution diagnostics. // 1) CS1921 (ERR_InitializerAddHasWrongSignature) // 2) CS1950 (ERR_BadArgTypesForCollectionAdd) // 3) CS1954 (ERR_InitializerAddHasParamModifiers) // See comments in BindCollectionInitializerExpression for more details. Debug.Assert(!boundElementInitializerExpressions.IsEmpty); if (!hasEnumerableInitializerType) { return BadExpression(elementInitializer, LookupResultKind.NotInvocable, ImmutableArray<Symbol>.Empty, boundElementInitializerExpressions); } Debug.Assert(collectionInitializerAddMethodBinder != null); Debug.Assert(collectionInitializerAddMethodBinder.Flags.Includes(BinderFlags.CollectionInitializerAddMethod)); Debug.Assert(implicitReceiver != null); Debug.Assert((object)implicitReceiver.Type != null); if (implicitReceiver.Type.IsDynamic()) { var hasErrors = ReportBadDynamicArguments(elementInitializer, boundElementInitializerExpressions, refKinds: default, diagnostics, queryClause: null); return new BoundDynamicCollectionElementInitializer( elementInitializer, applicableMethods: ImmutableArray<MethodSymbol>.Empty, implicitReceiver, arguments: boundElementInitializerExpressions.SelectAsArray(e => BindToNaturalType(e, diagnostics)), type: GetSpecialType(SpecialType.System_Void, diagnostics, elementInitializer), hasErrors: hasErrors); } // Receiver is early bound, find method Add and invoke it (may still be a dynamic invocation): var addMethodInvocation = collectionInitializerAddMethodBinder.MakeInvocationExpression( elementInitializer, implicitReceiver, methodName: WellKnownMemberNames.CollectionInitializerAddMethodName, args: boundElementInitializerExpressions, diagnostics: diagnostics); if (addMethodInvocation.Kind == BoundKind.DynamicInvocation) { var dynamicInvocation = (BoundDynamicInvocation)addMethodInvocation; return new BoundDynamicCollectionElementInitializer( elementInitializer, dynamicInvocation.ApplicableMethods, implicitReceiver, dynamicInvocation.Arguments, dynamicInvocation.Type, hasErrors: dynamicInvocation.HasAnyErrors); } else if (addMethodInvocation.Kind == BoundKind.Call) { var boundCall = (BoundCall)addMethodInvocation; // Either overload resolution succeeded for this call or it did not. If it // did not succeed then we've stashed the original method symbols from the // method group, and we should use those as the symbols displayed for the // call. If it did succeed then we did not stash any symbols. if (boundCall.HasErrors && !boundCall.OriginalMethodsOpt.IsDefault) { return boundCall; } return new BoundCollectionElementInitializer( elementInitializer, boundCall.Method, boundCall.Arguments, boundCall.ReceiverOpt, boundCall.Expanded, boundCall.ArgsToParamsOpt, boundCall.DefaultArguments, boundCall.InvokedAsExtensionMethod, boundCall.ResultKind, boundCall.Type, boundCall.HasAnyErrors) { WasCompilerGenerated = true }; } else { Debug.Assert(addMethodInvocation.Kind == BoundKind.BadExpression); return addMethodInvocation; } } internal ImmutableArray<MethodSymbol> FilterInaccessibleConstructors(ImmutableArray<MethodSymbol> constructors, bool allowProtectedConstructorsOfBaseType, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { ArrayBuilder<MethodSymbol> builder = null; for (int i = 0; i < constructors.Length; i++) { MethodSymbol constructor = constructors[i]; if (!IsConstructorAccessible(constructor, ref useSiteInfo, allowProtectedConstructorsOfBaseType)) { if (builder == null) { builder = ArrayBuilder<MethodSymbol>.GetInstance(); builder.AddRange(constructors, i); } } else { builder?.Add(constructor); } } return builder == null ? constructors : builder.ToImmutableAndFree(); } private bool IsConstructorAccessible(MethodSymbol constructor, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, bool allowProtectedConstructorsOfBaseType = false) { Debug.Assert((object)constructor != null); Debug.Assert(constructor.MethodKind == MethodKind.Constructor || constructor.MethodKind == MethodKind.StaticConstructor); NamedTypeSymbol containingType = this.ContainingType; if ((object)containingType != null) { // SPEC VIOLATION: The specification implies that when considering // SPEC VIOLATION: instance methods or instance constructors, we first // SPEC VIOLATION: do overload resolution on the accessible members, and // SPEC VIOLATION: then if the best method chosen is protected and accessed // SPEC VIOLATION: through the wrong type, then an error occurs. The native // SPEC VIOLATION: compiler however does it in the opposite order. First it // SPEC VIOLATION: filters out the protected methods that cannot be called // SPEC VIOLATION: through the given type, and then it does overload resolution // SPEC VIOLATION: on the rest. // // That said, it is somewhat odd that the same rule applies to constructors // as instance methods. A protected constructor is never going to be called // via an instance of a *more derived but different class* the way a // virtual method might be. Nevertheless, that's what we do. // // A constructor is accessed through an instance of the type being constructed: return allowProtectedConstructorsOfBaseType ? this.IsAccessible(constructor, ref useSiteInfo, null) : this.IsSymbolAccessibleConditional(constructor, containingType, ref useSiteInfo, constructor.ContainingType); } else { Debug.Assert((object)this.Compilation.Assembly != null); return IsSymbolAccessibleConditional(constructor, this.Compilation.Assembly, ref useSiteInfo); } } protected BoundExpression BindClassCreationExpression( SyntaxNode node, string typeName, SyntaxNode typeNode, NamedTypeSymbol type, AnalyzedArguments analyzedArguments, BindingDiagnosticBag diagnostics, InitializerExpressionSyntax initializerSyntaxOpt = null, TypeSymbol initializerTypeOpt = null, bool wasTargetTyped = false) { BoundExpression result = null; bool hasErrors = type.IsErrorType(); if (type.IsAbstract) { // Report error for new of abstract type. diagnostics.Add(ErrorCode.ERR_NoNewAbstract, node.Location, type); hasErrors = true; } CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); BoundObjectInitializerExpressionBase boundInitializerOpt = null; // If we have a dynamic argument then do overload resolution to see if there are one or more // applicable candidates. If there are, then this is a dynamic object creation; we'll work out // which ctor to call at runtime. If we have a dynamic argument but no applicable candidates // then we do the analysis again for error reporting purposes. if (analyzedArguments.HasDynamicArgument) { OverloadResolutionResult<MethodSymbol> overloadResolutionResult = OverloadResolutionResult<MethodSymbol>.GetInstance(); this.OverloadResolution.ObjectCreationOverloadResolution(GetAccessibleConstructorsForOverloadResolution(type, ref useSiteInfo), analyzedArguments, overloadResolutionResult, ref useSiteInfo); diagnostics.Add(node, useSiteInfo); useSiteInfo = new CompoundUseSiteInfo<AssemblySymbol>(useSiteInfo); if (overloadResolutionResult.HasAnyApplicableMember) { var argArray = BuildArgumentsForDynamicInvocation(analyzedArguments, diagnostics); var refKindsArray = analyzedArguments.RefKinds.ToImmutableOrNull(); hasErrors &= ReportBadDynamicArguments(node, argArray, refKindsArray, diagnostics, queryClause: null); boundInitializerOpt = makeBoundInitializerOpt(); result = new BoundDynamicObjectCreationExpression( node, typeName, argArray, analyzedArguments.GetNames(), refKindsArray, boundInitializerOpt, overloadResolutionResult.GetAllApplicableMembers(), type, hasErrors); } overloadResolutionResult.Free(); if (result != null) { return result; } } if (TryPerformConstructorOverloadResolution( type, analyzedArguments, typeName, typeNode.Location, hasErrors, //don't cascade in these cases diagnostics, out MemberResolutionResult<MethodSymbol> memberResolutionResult, out ImmutableArray<MethodSymbol> candidateConstructors, allowProtectedConstructorsOfBaseType: false)) { var method = memberResolutionResult.Member; bool hasError = false; // What if some of the arguments are implicit? Dev10 reports unsafe errors // if the implied argument would have an unsafe type. We need to check // the parameters explicitly, since there won't be bound nodes for the implied // arguments until lowering. if (method.HasUnsafeParameter()) { // Don't worry about double reporting (i.e. for both the argument and the parameter) // because only one unsafe diagnostic is allowed per scope - the others are suppressed. hasError = ReportUnsafeIfNotAllowed(node, diagnostics) || hasError; } ReportDiagnosticsIfObsolete(diagnostics, method, node, hasBaseReceiver: false); // NOTE: Use-site diagnostics were reported during overload resolution. ConstantValue constantValueOpt = (initializerSyntaxOpt == null && method.IsDefaultValueTypeConstructor(requireZeroInit: true)) ? FoldParameterlessValueTypeConstructor(type) : null; var expanded = memberResolutionResult.Result.Kind == MemberResolutionKind.ApplicableInExpandedForm; var argToParams = memberResolutionResult.Result.ArgsToParamsOpt; BindDefaultArguments(node, method.Parameters, analyzedArguments.Arguments, analyzedArguments.RefKinds, ref argToParams, out var defaultArguments, expanded, enableCallerInfo: true, diagnostics); var arguments = analyzedArguments.Arguments.ToImmutable(); var refKinds = analyzedArguments.RefKinds.ToImmutableOrNull(); if (!hasError) { hasError = !CheckInvocationArgMixing( node, method, null, method.Parameters, arguments, argToParams, this.LocalScopeDepth, diagnostics); } boundInitializerOpt = makeBoundInitializerOpt(); result = new BoundObjectCreationExpression( node, method, candidateConstructors, arguments, analyzedArguments.GetNames(), refKinds, expanded, argToParams, defaultArguments, constantValueOpt, boundInitializerOpt, wasTargetTyped, type, hasError); // CONSIDER: Add ResultKind field to BoundObjectCreationExpression to avoid wrapping result with BoundBadExpression. if (type.IsAbstract) { result = BadExpression(node, LookupResultKind.NotCreatable, result); } return result; } LookupResultKind resultKind; if (type.IsAbstract) { resultKind = LookupResultKind.NotCreatable; } else if (memberResolutionResult.IsValid && !IsConstructorAccessible(memberResolutionResult.Member, ref useSiteInfo)) { resultKind = LookupResultKind.Inaccessible; } else { resultKind = LookupResultKind.OverloadResolutionFailure; } diagnostics.Add(node, useSiteInfo); ArrayBuilder<Symbol> symbols = ArrayBuilder<Symbol>.GetInstance(); symbols.AddRange(candidateConstructors); // NOTE: The use site diagnostics of the candidate constructors have already been reported (in PerformConstructorOverloadResolution). var childNodes = ArrayBuilder<BoundExpression>.GetInstance(); childNodes.AddRange(BuildArgumentsForErrorRecovery(analyzedArguments, candidateConstructors)); if (initializerSyntaxOpt != null) { childNodes.Add(boundInitializerOpt ?? makeBoundInitializerOpt()); } return new BoundBadExpression(node, resultKind, symbols.ToImmutableAndFree(), childNodes.ToImmutableAndFree(), type); BoundObjectInitializerExpressionBase makeBoundInitializerOpt() { if (initializerSyntaxOpt != null) { return BindInitializerExpression(syntax: initializerSyntaxOpt, type: initializerTypeOpt ?? type, typeSyntax: typeNode, isForNewInstance: true, diagnostics: diagnostics); } return null; } } private BoundExpression BindInterfaceCreationExpression(ObjectCreationExpressionSyntax node, NamedTypeSymbol type, BindingDiagnosticBag diagnostics) { AnalyzedArguments analyzedArguments = AnalyzedArguments.GetInstance(); BindArgumentsAndNames(node.ArgumentList, diagnostics, analyzedArguments); var result = BindInterfaceCreationExpression(node, type, diagnostics, node.Type, analyzedArguments, node.Initializer, wasTargetTyped: false); analyzedArguments.Free(); return result; } private BoundExpression BindInterfaceCreationExpression(SyntaxNode node, NamedTypeSymbol type, BindingDiagnosticBag diagnostics, SyntaxNode typeNode, AnalyzedArguments analyzedArguments, InitializerExpressionSyntax initializerOpt, bool wasTargetTyped) { Debug.Assert((object)type != null); // COM interfaces which have ComImportAttribute and CoClassAttribute can be instantiated with "new". // CoClassAttribute contains the type information of the original CoClass for the interface. // We replace the interface creation with CoClass object creation for this case. // NOTE: We don't attempt binding interface creation to CoClass creation if we are within an attribute argument. // NOTE: This is done to prevent a cycle in an error scenario where we have a "new InterfaceType" expression in an attribute argument. // NOTE: Accessing IsComImport/ComImportCoClass properties on given type symbol would attempt ForceCompeteAttributes, which would again try binding all attributes on the symbol. // NOTE: causing infinite recursion. We avoid this cycle by checking if we are within in context of an Attribute argument. if (!this.InAttributeArgument && type.IsComImport) { NamedTypeSymbol coClassType = type.ComImportCoClass; if ((object)coClassType != null) { return BindComImportCoClassCreationExpression(node, type, coClassType, diagnostics, typeNode, analyzedArguments, initializerOpt, wasTargetTyped); } } // interfaces can't be instantiated in C# diagnostics.Add(ErrorCode.ERR_NoNewAbstract, node.Location, type); return MakeBadExpressionForObjectCreation(node, type, analyzedArguments, initializerOpt, typeNode, diagnostics); } private BoundExpression BindComImportCoClassCreationExpression(SyntaxNode node, NamedTypeSymbol interfaceType, NamedTypeSymbol coClassType, BindingDiagnosticBag diagnostics, SyntaxNode typeNode, AnalyzedArguments analyzedArguments, InitializerExpressionSyntax initializerOpt, bool wasTargetTyped) { Debug.Assert((object)interfaceType != null); Debug.Assert(interfaceType.IsInterfaceType()); Debug.Assert((object)coClassType != null); Debug.Assert(TypeSymbol.Equals(interfaceType.ComImportCoClass, coClassType, TypeCompareKind.ConsiderEverything2)); Debug.Assert(coClassType.TypeKind == TypeKind.Class || coClassType.TypeKind == TypeKind.Error); if (coClassType.IsErrorType()) { Error(diagnostics, ErrorCode.ERR_MissingCoClass, node, coClassType, interfaceType); } else if (coClassType.IsUnboundGenericType) { // BREAKING CHANGE: Dev10 allows the following code to compile, even though the output assembly is not verifiable and generates a runtime exception: // // [ComImport, Guid("00020810-0000-0000-C000-000000000046")] // [CoClass(typeof(GenericClass<>))] // public interface InterfaceType {} // public class GenericClass<T>: InterfaceType {} // // public class Program // { // public static void Main() { var i = new InterfaceType(); } // } // // We disallow CoClass creation if coClassType is an unbound generic type and report a compile time error. Error(diagnostics, ErrorCode.ERR_BadCoClassSig, node, coClassType, interfaceType); } else { // NoPIA support if (interfaceType.ContainingAssembly.IsLinked) { return BindNoPiaObjectCreationExpression(node, interfaceType, coClassType, diagnostics, typeNode, analyzedArguments, initializerOpt); } var classCreation = BindClassCreationExpression( node, coClassType.Name, typeNode, coClassType, analyzedArguments, diagnostics, initializerOpt, interfaceType, wasTargetTyped); CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); Conversion conversion = this.Conversions.ClassifyConversionFromExpression(classCreation, interfaceType, ref useSiteInfo, forCast: true); diagnostics.Add(node, useSiteInfo); if (!conversion.IsValid) { SymbolDistinguisher distinguisher = new SymbolDistinguisher(this.Compilation, coClassType, interfaceType); Error(diagnostics, ErrorCode.ERR_NoExplicitConv, node, distinguisher.First, distinguisher.Second); } // Bind the conversion, but drop the conversion node. CreateConversion(classCreation, conversion, interfaceType, diagnostics); // Override result type to be the interface type. switch (classCreation.Kind) { case BoundKind.ObjectCreationExpression: var creation = (BoundObjectCreationExpression)classCreation; return creation.Update(creation.Constructor, creation.ConstructorsGroup, creation.Arguments, creation.ArgumentNamesOpt, creation.ArgumentRefKindsOpt, creation.Expanded, creation.ArgsToParamsOpt, creation.DefaultArguments, creation.ConstantValueOpt, creation.InitializerExpressionOpt, interfaceType); case BoundKind.BadExpression: var bad = (BoundBadExpression)classCreation; return bad.Update(bad.ResultKind, bad.Symbols, bad.ChildBoundNodes, interfaceType); default: throw ExceptionUtilities.UnexpectedValue(classCreation.Kind); } } return MakeBadExpressionForObjectCreation(node, interfaceType, analyzedArguments, initializerOpt, typeNode, diagnostics); } private BoundExpression BindNoPiaObjectCreationExpression( SyntaxNode node, NamedTypeSymbol interfaceType, NamedTypeSymbol coClassType, BindingDiagnosticBag diagnostics, SyntaxNode typeNode, AnalyzedArguments analyzedArguments, InitializerExpressionSyntax initializerOpt) { string guidString; if (!coClassType.GetGuidString(out guidString)) { // At this point, VB reports ERRID_NoPIAAttributeMissing2 if guid isn't there. // C# doesn't complain and instead uses zero guid. guidString = System.Guid.Empty.ToString("D"); } var boundInitializerOpt = initializerOpt == null ? null : BindInitializerExpression(syntax: initializerOpt, type: interfaceType, typeSyntax: typeNode, isForNewInstance: true, diagnostics: diagnostics); var creation = new BoundNoPiaObjectCreationExpression(node, guidString, boundInitializerOpt, interfaceType); if (analyzedArguments.Arguments.Count > 0) { diagnostics.Add(ErrorCode.ERR_BadCtorArgCount, typeNode.Location, interfaceType, analyzedArguments.Arguments.Count); var children = BuildArgumentsForErrorRecovery(analyzedArguments).Add(creation); return new BoundBadExpression(node, LookupResultKind.OverloadResolutionFailure, ImmutableArray<Symbol>.Empty, children, creation.Type); } return creation; } private BoundExpression BindTypeParameterCreationExpression(ObjectCreationExpressionSyntax node, TypeParameterSymbol typeParameter, BindingDiagnosticBag diagnostics) { AnalyzedArguments analyzedArguments = AnalyzedArguments.GetInstance(); BindArgumentsAndNames(node.ArgumentList, diagnostics, analyzedArguments); var result = BindTypeParameterCreationExpression(node, typeParameter, analyzedArguments, node.Initializer, node.Type, diagnostics); analyzedArguments.Free(); return result; } private BoundExpression BindTypeParameterCreationExpression(SyntaxNode node, TypeParameterSymbol typeParameter, AnalyzedArguments analyzedArguments, InitializerExpressionSyntax initializerOpt, SyntaxNode typeSyntax, BindingDiagnosticBag diagnostics) { if (!typeParameter.HasConstructorConstraint && !typeParameter.IsValueType) { diagnostics.Add(ErrorCode.ERR_NoNewTyvar, node.Location, typeParameter); } else if (analyzedArguments.Arguments.Count > 0) { diagnostics.Add(ErrorCode.ERR_NewTyvarWithArgs, node.Location, typeParameter); } else { var boundInitializerOpt = initializerOpt == null ? null : BindInitializerExpression( syntax: initializerOpt, type: typeParameter, typeSyntax: typeSyntax, isForNewInstance: true, diagnostics: diagnostics); return new BoundNewT(node, boundInitializerOpt, typeParameter); } return MakeBadExpressionForObjectCreation(node, typeParameter, analyzedArguments, initializerOpt, typeSyntax, diagnostics); } /// <summary> /// Given the type containing constructors, gets the list of candidate instance constructors and uses overload resolution to determine which one should be called. /// </summary> /// <param name="typeContainingConstructors">The containing type of the constructors.</param> /// <param name="analyzedArguments">The already bound arguments to the constructor.</param> /// <param name="errorName">The name to use in diagnostics if overload resolution fails.</param> /// <param name="errorLocation">The location at which to report overload resolution result diagnostics.</param> /// <param name="suppressResultDiagnostics">True to suppress overload resolution result diagnostics (but not argument diagnostics).</param> /// <param name="diagnostics">Where diagnostics will be reported.</param> /// <param name="memberResolutionResult">If this method returns true, then it will contain a valid MethodResolutionResult. /// Otherwise, it may contain a MethodResolutionResult for an inaccessible constructor (in which case, it will incorrectly indicate success) or nothing at all.</param> /// <param name="candidateConstructors">Candidate instance constructors of type <paramref name="typeContainingConstructors"/> used for overload resolution.</param> /// <param name="allowProtectedConstructorsOfBaseType">It is always legal to access a protected base class constructor /// via a constructor initializer, but not from an object creation expression.</param> /// <returns>True if overload resolution successfully chose an accessible constructor.</returns> /// <remarks> /// The two-pass algorithm (accessible constructors, then all constructors) is the reason for the unusual signature /// of this method (i.e. not populating a pre-existing <see cref="OverloadResolutionResult{MethodSymbol}"/>). /// Presently, rationalizing this behavior is not worthwhile. /// </remarks> internal bool TryPerformConstructorOverloadResolution( NamedTypeSymbol typeContainingConstructors, AnalyzedArguments analyzedArguments, string errorName, Location errorLocation, bool suppressResultDiagnostics, BindingDiagnosticBag diagnostics, out MemberResolutionResult<MethodSymbol> memberResolutionResult, out ImmutableArray<MethodSymbol> candidateConstructors, bool allowProtectedConstructorsOfBaseType) // Last to make named arguments more convenient. { // Get accessible constructors for performing overload resolution. ImmutableArray<MethodSymbol> allInstanceConstructors; CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); candidateConstructors = GetAccessibleConstructorsForOverloadResolution(typeContainingConstructors, allowProtectedConstructorsOfBaseType, out allInstanceConstructors, ref useSiteInfo); OverloadResolutionResult<MethodSymbol> result = OverloadResolutionResult<MethodSymbol>.GetInstance(); // Indicates whether overload resolution successfully chose an accessible constructor. bool succeededConsideringAccessibility = false; // Indicates whether overload resolution resulted in a single best match, even though it might be inaccessible. bool succeededIgnoringAccessibility = false; if (candidateConstructors.Any()) { // We have at least one accessible candidate constructor, perform overload resolution with accessible candidateConstructors. this.OverloadResolution.ObjectCreationOverloadResolution(candidateConstructors, analyzedArguments, result, ref useSiteInfo); if (result.Succeeded) { succeededConsideringAccessibility = true; succeededIgnoringAccessibility = true; } } if (!succeededConsideringAccessibility && allInstanceConstructors.Length > candidateConstructors.Length) { // Overload resolution failed on the accessible candidateConstructors, but we have at least one inaccessible constructor. // We might have a best match constructor which is inaccessible. // Try overload resolution with all instance constructors to generate correct diagnostics and semantic info for this case. OverloadResolutionResult<MethodSymbol> inaccessibleResult = OverloadResolutionResult<MethodSymbol>.GetInstance(); this.OverloadResolution.ObjectCreationOverloadResolution(allInstanceConstructors, analyzedArguments, inaccessibleResult, ref useSiteInfo); if (inaccessibleResult.Succeeded) { succeededIgnoringAccessibility = true; candidateConstructors = allInstanceConstructors; result.Free(); result = inaccessibleResult; } else { inaccessibleResult.Free(); } } diagnostics.Add(errorLocation, useSiteInfo); if (succeededIgnoringAccessibility) { this.CoerceArguments<MethodSymbol>(result.ValidResult, analyzedArguments.Arguments, diagnostics, receiverType: null, receiverRefKind: null, receiverEscapeScope: Binder.ExternalScope); } // Fill in the out parameter with the result, if there was one; it might be inaccessible. memberResolutionResult = succeededIgnoringAccessibility ? result.ValidResult : default(MemberResolutionResult<MethodSymbol>); // Invalid results are not interesting - we have enough info in candidateConstructors. // If something failed and we are reporting errors, then report the right errors. // * If the failure was due to inaccessibility, just report that. // * If the failure was not due to inaccessibility then only report an error // on the constructor if there were no errors on the arguments. if (!succeededConsideringAccessibility && !suppressResultDiagnostics) { if (succeededIgnoringAccessibility) { // It is not legal to directly call a protected constructor on a base class unless // the "this" of the call is known to be of the current type. That is, it is // perfectly legal to say ": base()" to call a protected base class ctor, but // it is not legal to say "new MyBase()" if the ctor is protected. // // The native compiler produces the error CS1540: // // Cannot access protected member 'MyBase.MyBase' via a qualifier of type 'MyBase'; // the qualifier must be of type 'Derived' (or derived from it) // // Though technically correct, this is a very confusing error message for this scenario; // one does not typically think of the constructor as being a method that is // called with an implicit "this" of a particular receiver type, even though of course // that is exactly what it is. // // The better error message here is to simply say that the best possible ctor cannot // be accessed because it is not accessible. // // CONSIDER: We might consider making up a new error message for this situation. // // CS0122: 'MyBase.MyBase' is inaccessible due to its protection level diagnostics.Add(ErrorCode.ERR_BadAccess, errorLocation, result.ValidResult.Member); } else { result.ReportDiagnostics( binder: this, location: errorLocation, nodeOpt: null, diagnostics, name: errorName, receiver: null, invokedExpression: null, analyzedArguments, memberGroup: candidateConstructors, typeContainingConstructors, delegateTypeBeingInvoked: null); } } result.Free(); return succeededConsideringAccessibility; } private ImmutableArray<MethodSymbol> GetAccessibleConstructorsForOverloadResolution(NamedTypeSymbol type, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { ImmutableArray<MethodSymbol> allInstanceConstructors; return GetAccessibleConstructorsForOverloadResolution(type, false, out allInstanceConstructors, ref useSiteInfo); } private ImmutableArray<MethodSymbol> GetAccessibleConstructorsForOverloadResolution(NamedTypeSymbol type, bool allowProtectedConstructorsOfBaseType, out ImmutableArray<MethodSymbol> allInstanceConstructors, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { if (type.IsErrorType()) { // For Caas, we want to supply the constructors even in error cases // We may end up supplying the constructors of an unconstructed symbol, // but that's better than nothing. type = type.GetNonErrorGuess() as NamedTypeSymbol ?? type; } allInstanceConstructors = type.InstanceConstructors; return FilterInaccessibleConstructors(allInstanceConstructors, allowProtectedConstructorsOfBaseType, ref useSiteInfo); } private static ConstantValue FoldParameterlessValueTypeConstructor(NamedTypeSymbol type) { // DELIBERATE SPEC VIOLATION: // // Object creation expressions like "new int()" are not considered constant expressions // by the specification but they are by the native compiler; we maintain compatibility // with this bug. // // Additionally, it also treats "new X()", where X is an enum type, as a // constant expression with default value 0, we maintain compatibility with it. var specialType = type.SpecialType; if (type.TypeKind == TypeKind.Enum) { specialType = type.EnumUnderlyingType.SpecialType; } switch (specialType) { case SpecialType.System_SByte: case SpecialType.System_Int16: case SpecialType.System_Int32: case SpecialType.System_Int64: case SpecialType.System_Byte: case SpecialType.System_UInt16: case SpecialType.System_UInt32: case SpecialType.System_UInt64: case SpecialType.System_Single: case SpecialType.System_Double: case SpecialType.System_Decimal: case SpecialType.System_Boolean: case SpecialType.System_Char: return ConstantValue.Default(specialType); } return null; } private BoundLiteral BindLiteralConstant(LiteralExpressionSyntax node, BindingDiagnosticBag diagnostics) { // bug.Assert(node.Kind == SyntaxKind.LiteralExpression); var value = node.Token.Value; ConstantValue cv; TypeSymbol type = null; if (value == null) { cv = ConstantValue.Null; } else { Debug.Assert(!value.GetType().GetTypeInfo().IsEnum); var specialType = SpecialTypeExtensions.FromRuntimeTypeOfLiteralValue(value); // C# literals can't be of type byte, sbyte, short, ushort: Debug.Assert( specialType != SpecialType.None && specialType != SpecialType.System_Byte && specialType != SpecialType.System_SByte && specialType != SpecialType.System_Int16 && specialType != SpecialType.System_UInt16); cv = ConstantValue.Create(value, specialType); type = GetSpecialType(specialType, diagnostics, node); } return new BoundLiteral(node, cv, type); } private BoundExpression BindCheckedExpression(CheckedExpressionSyntax node, BindingDiagnosticBag diagnostics) { // the binder is not cached since we only cache statement level binders return this.WithCheckedOrUncheckedRegion(node.Kind() == SyntaxKind.CheckedExpression). BindParenthesizedExpression(node.Expression, diagnostics); } /// <summary> /// Binds a member access expression /// </summary> private BoundExpression BindMemberAccess( MemberAccessExpressionSyntax node, bool invoked, bool indexed, BindingDiagnosticBag diagnostics) { Debug.Assert(node != null); BoundExpression boundLeft; ExpressionSyntax exprSyntax = node.Expression; if (node.Kind() == SyntaxKind.SimpleMemberAccessExpression) { // NOTE: CheckValue will be called explicitly in BindMemberAccessWithBoundLeft. boundLeft = BindLeftOfPotentialColorColorMemberAccess(exprSyntax, diagnostics); } else { Debug.Assert(node.Kind() == SyntaxKind.PointerMemberAccessExpression); boundLeft = BindRValueWithoutTargetType(exprSyntax, diagnostics); // Not Color Color issues with -> // CONSIDER: another approach would be to construct a BoundPointerMemberAccess (assuming such a type existed), // but that would be much more cumbersome because we'd be unable to build upon the BindMemberAccess infrastructure, // which expects a receiver. // Dereference before binding member; TypeSymbol pointedAtType; bool hasErrors; BindPointerIndirectionExpressionInternal(node, boundLeft, diagnostics, out pointedAtType, out hasErrors); // If there is no pointed-at type, fall back on the actual type (i.e. assume the user meant "." instead of "->"). if (ReferenceEquals(pointedAtType, null)) { boundLeft = ToBadExpression(boundLeft); } else { boundLeft = new BoundPointerIndirectionOperator(exprSyntax, boundLeft, pointedAtType, hasErrors) { WasCompilerGenerated = true, // don't interfere with the type info for exprSyntax. }; } } return BindMemberAccessWithBoundLeft(node, boundLeft, node.Name, node.OperatorToken, invoked, indexed, diagnostics); } /// <summary> /// Attempt to bind the LHS of a member access expression. If this is a Color Color case (spec 7.6.4.1), /// then return a BoundExpression if we can easily disambiguate or a BoundTypeOrValueExpression if we /// cannot. If this is not a Color Color case, then return null. /// </summary> private BoundExpression BindLeftOfPotentialColorColorMemberAccess(ExpressionSyntax left, BindingDiagnosticBag diagnostics) { if (left is IdentifierNameSyntax identifier) { return BindLeftIdentifierOfPotentialColorColorMemberAccess(identifier, diagnostics); } // NOTE: it is up to the caller to call CheckValue on the result. return BindExpression(left, diagnostics); } // Avoid inlining to minimize stack size in caller. [MethodImpl(MethodImplOptions.NoInlining)] private BoundExpression BindLeftIdentifierOfPotentialColorColorMemberAccess(IdentifierNameSyntax left, BindingDiagnosticBag diagnostics) { // SPEC: 7.6.4.1 Identical simple names and type names // SPEC: In a member access of the form E.I, if E is a single identifier, and if the meaning of E as // SPEC: a simple-name (spec 7.6.2) is a constant, field, property, local variable, or parameter with the // SPEC: same type as the meaning of E as a type-name (spec 3.8), then both possible meanings of E are // SPEC: permitted. The two possible meanings of E.I are never ambiguous, since I must necessarily be // SPEC: a member of the type E in both cases. In other words, the rule simply permits access to the // SPEC: static members and nested types of E where a compile-time error would otherwise have occurred. var valueDiagnostics = BindingDiagnosticBag.Create(diagnostics); var boundValue = BindIdentifier(left, invoked: false, indexed: false, diagnostics: valueDiagnostics); Symbol leftSymbol; if (boundValue.Kind == BoundKind.Conversion) { // BindFieldAccess may insert a conversion if binding occurs // within an enum member initializer. leftSymbol = ((BoundConversion)boundValue).Operand.ExpressionSymbol; } else { leftSymbol = boundValue.ExpressionSymbol; } if ((object)leftSymbol != null) { switch (leftSymbol.Kind) { case SymbolKind.Field: case SymbolKind.Local: case SymbolKind.Parameter: case SymbolKind.Property: case SymbolKind.RangeVariable: var leftType = boundValue.Type; Debug.Assert((object)leftType != null); var leftName = left.Identifier.ValueText; if (leftType.Name == leftName || IsUsingAliasInScope(leftName)) { var typeDiagnostics = BindingDiagnosticBag.Create(diagnostics); var boundType = BindNamespaceOrType(left, typeDiagnostics); if (TypeSymbol.Equals(boundType.Type, leftType, TypeCompareKind.ConsiderEverything2)) { // NOTE: ReplaceTypeOrValueReceiver will call CheckValue explicitly. boundValue = BindToNaturalType(boundValue, valueDiagnostics); return new BoundTypeOrValueExpression(left, new BoundTypeOrValueData(leftSymbol, boundValue, valueDiagnostics, boundType, typeDiagnostics), leftType); } } break; // case SymbolKind.Event: //SPEC: 7.6.4.1 (a.k.a. Color Color) doesn't cover events } } // Not a Color Color case; return the bound member. // NOTE: it is up to the caller to call CheckValue on the result. diagnostics.AddRange(valueDiagnostics); return boundValue; } // returns true if name matches a using alias in scope // NOTE: when true is returned, the corresponding using is also marked as "used" private bool IsUsingAliasInScope(string name) { var isSemanticModel = this.IsSemanticModelBinder; for (var chain = this.ImportChain; chain != null; chain = chain.ParentOpt) { if (IsUsingAlias(chain.Imports.UsingAliases, name, isSemanticModel)) { return true; } } return false; } private BoundExpression BindDynamicMemberAccess( ExpressionSyntax node, BoundExpression boundLeft, SimpleNameSyntax right, bool invoked, bool indexed, BindingDiagnosticBag diagnostics) { // We have an expression of the form "dynExpr.Name" or "dynExpr.Name<X>" SeparatedSyntaxList<TypeSyntax> typeArgumentsSyntax = right.Kind() == SyntaxKind.GenericName ? ((GenericNameSyntax)right).TypeArgumentList.Arguments : default(SeparatedSyntaxList<TypeSyntax>); bool rightHasTypeArguments = typeArgumentsSyntax.Count > 0; ImmutableArray<TypeWithAnnotations> typeArgumentsWithAnnotations = rightHasTypeArguments ? BindTypeArguments(typeArgumentsSyntax, diagnostics) : default(ImmutableArray<TypeWithAnnotations>); bool hasErrors = false; if (!invoked && rightHasTypeArguments) { // error CS0307: The property 'P' cannot be used with type arguments Error(diagnostics, ErrorCode.ERR_TypeArgsNotAllowed, right, right.Identifier.Text, SymbolKind.Property.Localize()); hasErrors = true; } if (rightHasTypeArguments) { for (int i = 0; i < typeArgumentsWithAnnotations.Length; ++i) { var typeArgument = typeArgumentsWithAnnotations[i]; if (typeArgument.Type.IsPointerOrFunctionPointer() || typeArgument.Type.IsRestrictedType()) { // "The type '{0}' may not be used as a type argument" Error(diagnostics, ErrorCode.ERR_BadTypeArgument, typeArgumentsSyntax[i], typeArgument.Type); hasErrors = true; } } } return new BoundDynamicMemberAccess( syntax: node, receiver: boundLeft, typeArgumentsOpt: typeArgumentsWithAnnotations, name: right.Identifier.ValueText, invoked: invoked, indexed: indexed, type: Compilation.DynamicType, hasErrors: hasErrors); } /// <summary> /// Bind the RHS of a member access expression, given the bound LHS. /// It is assumed that CheckValue has not been called on the LHS. /// </summary> /// <remarks> /// If new checks are added to this method, they will also need to be added to <see cref="MakeQueryInvocation(CSharpSyntaxNode, BoundExpression, string, TypeSyntax, TypeWithAnnotations, BindingDiagnosticBag)"/>. /// </remarks> private BoundExpression BindMemberAccessWithBoundLeft( ExpressionSyntax node, BoundExpression boundLeft, SimpleNameSyntax right, SyntaxToken operatorToken, bool invoked, bool indexed, BindingDiagnosticBag diagnostics) { Debug.Assert(node != null); Debug.Assert(boundLeft != null); boundLeft = MakeMemberAccessValue(boundLeft, diagnostics); TypeSymbol leftType = boundLeft.Type; if ((object)leftType != null && leftType.IsDynamic()) { // There are some sources of a `dynamic` typed value that can be known before runtime // to be invalid. For example, accessing a set-only property whose type is dynamic: // dynamic Goo { set; } // If Goo itself is a dynamic thing (e.g. in `x.Goo.Bar`, `x` is dynamic, and we're // currently checking Bar), then CheckValue will do nothing. boundLeft = CheckValue(boundLeft, BindValueKind.RValue, diagnostics); return BindDynamicMemberAccess(node, boundLeft, right, invoked, indexed, diagnostics); } // No member accesses on void if ((object)leftType != null && leftType.IsVoidType()) { diagnostics.Add(ErrorCode.ERR_BadUnaryOp, operatorToken.GetLocation(), SyntaxFacts.GetText(operatorToken.Kind()), leftType); return BadExpression(node, boundLeft); } // No member accesses on default if (boundLeft.IsLiteralDefault()) { DiagnosticInfo diagnosticInfo = new CSDiagnosticInfo(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, SyntaxFacts.GetText(operatorToken.Kind()), boundLeft.Display); diagnostics.Add(new CSDiagnostic(diagnosticInfo, operatorToken.GetLocation())); return BadExpression(node, boundLeft); } if (boundLeft.Kind == BoundKind.UnboundLambda) { Debug.Assert((object)leftType == null); var msgId = ((UnboundLambda)boundLeft).MessageID; diagnostics.Add(ErrorCode.ERR_BadUnaryOp, node.Location, SyntaxFacts.GetText(operatorToken.Kind()), msgId.Localize()); return BadExpression(node, boundLeft); } boundLeft = BindToNaturalType(boundLeft, diagnostics); leftType = boundLeft.Type; var lookupResult = LookupResult.GetInstance(); try { LookupOptions options = LookupOptions.AllMethodsOnArityZero; if (invoked) { options |= LookupOptions.MustBeInvocableIfMember; } var typeArgumentsSyntax = right.Kind() == SyntaxKind.GenericName ? ((GenericNameSyntax)right).TypeArgumentList.Arguments : default(SeparatedSyntaxList<TypeSyntax>); var typeArguments = typeArgumentsSyntax.Count > 0 ? BindTypeArguments(typeArgumentsSyntax, diagnostics) : default(ImmutableArray<TypeWithAnnotations>); // A member-access consists of a primary-expression, a predefined-type, or a // qualified-alias-member, followed by a "." token, followed by an identifier, // optionally followed by a type-argument-list. // A member-access is either of the form E.I or of the form E.I<A1, ..., AK>, where // E is a primary-expression, I is a single identifier and <A1, ..., AK> is an // optional type-argument-list. When no type-argument-list is specified, consider K // to be zero. // UNDONE: A member-access with a primary-expression of type dynamic is dynamically bound. // UNDONE: In this case the compiler classifies the member access as a property access of // UNDONE: type dynamic. The rules below to determine the meaning of the member-access are // UNDONE: then applied at run-time, using the run-time type instead of the compile-time // UNDONE: type of the primary-expression. If this run-time classification leads to a method // UNDONE: group, then the member access must be the primary-expression of an invocation-expression. // The member-access is evaluated and classified as follows: var rightName = right.Identifier.ValueText; var rightArity = right.Arity; BoundExpression result; switch (boundLeft.Kind) { case BoundKind.NamespaceExpression: { result = tryBindMemberAccessWithBoundNamespaceLeft(((BoundNamespaceExpression)boundLeft).NamespaceSymbol, node, boundLeft, right, diagnostics, lookupResult, options, typeArgumentsSyntax, typeArguments, rightName, rightArity); if (result is object) { return result; } break; } case BoundKind.TypeExpression: { result = tryBindMemberAccessWithBoundTypeLeft(node, boundLeft, right, invoked, indexed, diagnostics, leftType, lookupResult, options, typeArgumentsSyntax, typeArguments, rightName, rightArity); if (result is object) { return result; } break; } case BoundKind.TypeOrValueExpression: { // CheckValue call will occur in ReplaceTypeOrValueReceiver. // NOTE: This means that we won't get CheckValue diagnostics in error scenarios, // but they would be cascading anyway. return BindInstanceMemberAccess(node, right, boundLeft, rightName, rightArity, typeArgumentsSyntax, typeArguments, invoked, indexed, diagnostics); } default: { // Can't dot into the null literal if (boundLeft.Kind == BoundKind.Literal && ((BoundLiteral)boundLeft).ConstantValueOpt == ConstantValue.Null) { if (!boundLeft.HasAnyErrors) { Error(diagnostics, ErrorCode.ERR_BadUnaryOp, node, operatorToken.Text, boundLeft.Display); } return BadExpression(node, boundLeft); } else if ((object)leftType != null) { // NB: We don't know if we really only need RValue access, or if we are actually // passing the receiver implicitly by ref (e.g. in a struct instance method invocation). // These checks occur later. boundLeft = CheckValue(boundLeft, BindValueKind.RValue, diagnostics); boundLeft = BindToNaturalType(boundLeft, diagnostics); return BindInstanceMemberAccess(node, right, boundLeft, rightName, rightArity, typeArgumentsSyntax, typeArguments, invoked, indexed, diagnostics); } break; } } this.BindMemberAccessReportError(node, right, rightName, boundLeft, lookupResult.Error, diagnostics); return BindMemberAccessBadResult(node, rightName, boundLeft, lookupResult.Error, lookupResult.Symbols.ToImmutable(), lookupResult.Kind); } finally { lookupResult.Free(); } [MethodImpl(MethodImplOptions.NoInlining)] BoundExpression tryBindMemberAccessWithBoundNamespaceLeft( NamespaceSymbol ns, ExpressionSyntax node, BoundExpression boundLeft, SimpleNameSyntax right, BindingDiagnosticBag diagnostics, LookupResult lookupResult, LookupOptions options, SeparatedSyntaxList<TypeSyntax> typeArgumentsSyntax, ImmutableArray<TypeWithAnnotations> typeArguments, string rightName, int rightArity) { // If K is zero and E is a namespace and E contains a nested namespace with name I, // then the result is that namespace. CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); this.LookupMembersWithFallback(lookupResult, ns, rightName, rightArity, ref useSiteInfo, options: options); diagnostics.Add(right, useSiteInfo); ArrayBuilder<Symbol> symbols = lookupResult.Symbols; if (lookupResult.IsMultiViable) { bool wasError; Symbol sym = ResultSymbol(lookupResult, rightName, rightArity, node, diagnostics, false, out wasError, ns, options); if (wasError) { return new BoundBadExpression(node, LookupResultKind.Ambiguous, lookupResult.Symbols.AsImmutable(), ImmutableArray.Create(boundLeft), CreateErrorType(rightName), hasErrors: true); } else if (sym.Kind == SymbolKind.Namespace) { return new BoundNamespaceExpression(node, (NamespaceSymbol)sym); } else { Debug.Assert(sym.Kind == SymbolKind.NamedType); var type = (NamedTypeSymbol)sym; if (!typeArguments.IsDefault) { type = ConstructNamedTypeUnlessTypeArgumentOmitted(right, type, typeArgumentsSyntax, typeArguments, diagnostics); } ReportDiagnosticsIfObsolete(diagnostics, type, node, hasBaseReceiver: false); return new BoundTypeExpression(node, null, type); } } else if (lookupResult.Kind == LookupResultKind.WrongArity) { Debug.Assert(symbols.Count > 0); Debug.Assert(symbols[0].Kind == SymbolKind.NamedType); Error(diagnostics, lookupResult.Error, right); return new BoundTypeExpression(node, null, new ExtendedErrorTypeSymbol(GetContainingNamespaceOrType(symbols[0]), symbols.ToImmutable(), lookupResult.Kind, lookupResult.Error, rightArity)); } else if (lookupResult.Kind == LookupResultKind.Empty) { Debug.Assert(lookupResult.IsClear, "If there's a legitimate reason for having candidates without a reason, then we should produce something intelligent in such cases."); Debug.Assert(lookupResult.Error == null); NotFound(node, rightName, rightArity, rightName, diagnostics, aliasOpt: null, qualifierOpt: ns, options: options); return new BoundBadExpression(node, lookupResult.Kind, symbols.AsImmutable(), ImmutableArray.Create(boundLeft), CreateErrorType(rightName), hasErrors: true); } return null; } [MethodImpl(MethodImplOptions.NoInlining)] BoundExpression tryBindMemberAccessWithBoundTypeLeft( ExpressionSyntax node, BoundExpression boundLeft, SimpleNameSyntax right, bool invoked, bool indexed, BindingDiagnosticBag diagnostics, TypeSymbol leftType, LookupResult lookupResult, LookupOptions options, SeparatedSyntaxList<TypeSyntax> typeArgumentsSyntax, ImmutableArray<TypeWithAnnotations> typeArguments, string rightName, int rightArity) { Debug.Assert((object)leftType != null); if (leftType.TypeKind == TypeKind.TypeParameter) { CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); this.LookupMembersWithFallback(lookupResult, leftType, rightName, rightArity, ref useSiteInfo, basesBeingResolved: null, options: options | LookupOptions.MustNotBeInstance | LookupOptions.MustBeAbstract); diagnostics.Add(right, useSiteInfo); if (lookupResult.IsMultiViable) { CheckFeatureAvailability(boundLeft.Syntax, MessageID.IDS_FeatureStaticAbstractMembersInInterfaces, diagnostics); return BindMemberOfType(node, right, rightName, rightArity, indexed, boundLeft, typeArgumentsSyntax, typeArguments, lookupResult, BoundMethodGroupFlags.None, diagnostics: diagnostics); } else if (lookupResult.IsClear) { Error(diagnostics, ErrorCode.ERR_BadSKunknown, boundLeft.Syntax, leftType, MessageID.IDS_SK_TYVAR.Localize()); return BadExpression(node, LookupResultKind.NotAValue, boundLeft); } } else if (this.EnclosingNameofArgument == node) { // Support selecting an extension method from a type name in nameof(.) return BindInstanceMemberAccess(node, right, boundLeft, rightName, rightArity, typeArgumentsSyntax, typeArguments, invoked, indexed, diagnostics); } else { CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); this.LookupMembersWithFallback(lookupResult, leftType, rightName, rightArity, ref useSiteInfo, basesBeingResolved: null, options: options); diagnostics.Add(right, useSiteInfo); if (lookupResult.IsMultiViable) { return BindMemberOfType(node, right, rightName, rightArity, indexed, boundLeft, typeArgumentsSyntax, typeArguments, lookupResult, BoundMethodGroupFlags.None, diagnostics: diagnostics); } } return null; } } private void WarnOnAccessOfOffDefault(SyntaxNode node, BoundExpression boundLeft, BindingDiagnosticBag diagnostics) { if ((boundLeft is BoundDefaultLiteral || boundLeft is BoundDefaultExpression) && boundLeft.ConstantValue == ConstantValue.Null && Compilation.LanguageVersion < MessageID.IDS_FeatureNullableReferenceTypes.RequiredVersion()) { Error(diagnostics, ErrorCode.WRN_DotOnDefault, node, boundLeft.Type); } } /// <summary> /// Create a value from the expression that can be used as a left-hand-side /// of a member access. This method special-cases method and property /// groups only. All other expressions are returned as is. /// </summary> private BoundExpression MakeMemberAccessValue(BoundExpression expr, BindingDiagnosticBag diagnostics) { switch (expr.Kind) { case BoundKind.MethodGroup: { var methodGroup = (BoundMethodGroup)expr; CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); var resolution = this.ResolveMethodGroup(methodGroup, analyzedArguments: null, isMethodGroupConversion: false, useSiteInfo: ref useSiteInfo); diagnostics.Add(expr.Syntax, useSiteInfo); if (!expr.HasAnyErrors) { diagnostics.AddRange(resolution.Diagnostics); if (resolution.MethodGroup != null && !resolution.HasAnyErrors) { Debug.Assert(!resolution.IsEmpty); var method = resolution.MethodGroup.Methods[0]; Error(diagnostics, ErrorCode.ERR_BadSKunknown, methodGroup.NameSyntax, method, MessageID.IDS_SK_METHOD.Localize()); } } expr = this.BindMemberAccessBadResult(methodGroup); resolution.Free(); return expr; } case BoundKind.PropertyGroup: return BindIndexedPropertyAccess((BoundPropertyGroup)expr, mustHaveAllOptionalParameters: false, diagnostics: diagnostics); default: return BindToNaturalType(expr, diagnostics); } } private BoundExpression BindInstanceMemberAccess( SyntaxNode node, SyntaxNode right, BoundExpression boundLeft, string rightName, int rightArity, SeparatedSyntaxList<TypeSyntax> typeArgumentsSyntax, ImmutableArray<TypeWithAnnotations> typeArgumentsWithAnnotations, bool invoked, bool indexed, BindingDiagnosticBag diagnostics, bool searchExtensionMethodsIfNecessary = true) { Debug.Assert(rightArity == (typeArgumentsWithAnnotations.IsDefault ? 0 : typeArgumentsWithAnnotations.Length)); var leftType = boundLeft.Type; LookupOptions options = LookupOptions.AllMethodsOnArityZero; if (invoked) { options |= LookupOptions.MustBeInvocableIfMember; } var lookupResult = LookupResult.GetInstance(); try { // If E is a property access, indexer access, variable, or value, the type of // which is T, and a member lookup of I in T with K type arguments produces a // match, then E.I is evaluated and classified as follows: // UNDONE: Classify E as prop access, indexer access, variable or value bool leftIsBaseReference = boundLeft.Kind == BoundKind.BaseReference; if (leftIsBaseReference) { options |= LookupOptions.UseBaseReferenceAccessibility; } CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); this.LookupMembersWithFallback(lookupResult, leftType, rightName, rightArity, ref useSiteInfo, basesBeingResolved: null, options: options); diagnostics.Add(right, useSiteInfo); // SPEC: Otherwise, an attempt is made to process E.I as an extension method invocation. // SPEC: If this fails, E.I is an invalid member reference, and a binding-time error occurs. searchExtensionMethodsIfNecessary = searchExtensionMethodsIfNecessary && !leftIsBaseReference; BoundMethodGroupFlags flags = 0; if (searchExtensionMethodsIfNecessary) { flags |= BoundMethodGroupFlags.SearchExtensionMethods; } if (lookupResult.IsMultiViable) { return BindMemberOfType(node, right, rightName, rightArity, indexed, boundLeft, typeArgumentsSyntax, typeArgumentsWithAnnotations, lookupResult, flags, diagnostics); } if (searchExtensionMethodsIfNecessary) { var boundMethodGroup = new BoundMethodGroup( node, typeArgumentsWithAnnotations, boundLeft, rightName, lookupResult.Symbols.All(s => s.Kind == SymbolKind.Method) ? lookupResult.Symbols.SelectAsArray(s_toMethodSymbolFunc) : ImmutableArray<MethodSymbol>.Empty, lookupResult, flags); if (!boundMethodGroup.HasErrors && typeArgumentsSyntax.Any(SyntaxKind.OmittedTypeArgument)) { Error(diagnostics, ErrorCode.ERR_OmittedTypeArgument, node); } return boundMethodGroup; } this.BindMemberAccessReportError(node, right, rightName, boundLeft, lookupResult.Error, diagnostics); return BindMemberAccessBadResult(node, rightName, boundLeft, lookupResult.Error, lookupResult.Symbols.ToImmutable(), lookupResult.Kind); } finally { lookupResult.Free(); } } private void BindMemberAccessReportError(BoundMethodGroup node, BindingDiagnosticBag diagnostics) { var nameSyntax = node.NameSyntax; var syntax = node.MemberAccessExpressionSyntax ?? nameSyntax; this.BindMemberAccessReportError(syntax, nameSyntax, node.Name, node.ReceiverOpt, node.LookupError, diagnostics); } /// <summary> /// Report the error from member access lookup. Or, if there /// was no explicit error from lookup, report "no such member". /// </summary> private void BindMemberAccessReportError( SyntaxNode node, SyntaxNode name, string plainName, BoundExpression boundLeft, DiagnosticInfo lookupError, BindingDiagnosticBag diagnostics) { if (boundLeft.HasAnyErrors && boundLeft.Kind != BoundKind.TypeOrValueExpression) { return; } if (lookupError != null) { // CONSIDER: there are some cases where Dev10 uses the span of "node", // rather than "right". diagnostics.Add(new CSDiagnostic(lookupError, name.Location)); } else if (node.IsQuery()) { ReportQueryLookupFailed(node, boundLeft, plainName, ImmutableArray<Symbol>.Empty, diagnostics); } else { if ((object)boundLeft.Type == null) { Error(diagnostics, ErrorCode.ERR_NoSuchMember, name, boundLeft.Display, plainName); } else if (boundLeft.Kind == BoundKind.TypeExpression || boundLeft.Kind == BoundKind.BaseReference || node.Kind() == SyntaxKind.AwaitExpression && plainName == WellKnownMemberNames.GetResult) { Error(diagnostics, ErrorCode.ERR_NoSuchMember, name, boundLeft.Type, plainName); } else if (WouldUsingSystemFindExtension(boundLeft.Type, plainName)) { Error(diagnostics, ErrorCode.ERR_NoSuchMemberOrExtensionNeedUsing, name, boundLeft.Type, plainName, "System"); } else { Error(diagnostics, ErrorCode.ERR_NoSuchMemberOrExtension, name, boundLeft.Type, plainName); } } } private bool WouldUsingSystemFindExtension(TypeSymbol receiver, string methodName) { // we have a special case to make the diagnostic for await expressions more clear for Windows: // if the receiver type is a windows RT async interface and the method name is GetAwaiter, // then we would suggest a using directive for "System". // TODO: we should check if such a using directive would actually help, or if there is already one in scope. return methodName == WellKnownMemberNames.GetAwaiter && ImplementsWinRTAsyncInterface(receiver); } /// <summary> /// Return true if the given type is or implements a WinRTAsyncInterface. /// </summary> private bool ImplementsWinRTAsyncInterface(TypeSymbol type) { return IsWinRTAsyncInterface(type) || type.AllInterfacesNoUseSiteDiagnostics.Any(i => IsWinRTAsyncInterface(i)); } private bool IsWinRTAsyncInterface(TypeSymbol type) { if (!type.IsInterfaceType()) { return false; } var namedType = ((NamedTypeSymbol)type).ConstructedFrom; return TypeSymbol.Equals(namedType, Compilation.GetWellKnownType(WellKnownType.Windows_Foundation_IAsyncAction), TypeCompareKind.ConsiderEverything2) || TypeSymbol.Equals(namedType, Compilation.GetWellKnownType(WellKnownType.Windows_Foundation_IAsyncActionWithProgress_T), TypeCompareKind.ConsiderEverything2) || TypeSymbol.Equals(namedType, Compilation.GetWellKnownType(WellKnownType.Windows_Foundation_IAsyncOperation_T), TypeCompareKind.ConsiderEverything2) || TypeSymbol.Equals(namedType, Compilation.GetWellKnownType(WellKnownType.Windows_Foundation_IAsyncOperationWithProgress_T2), TypeCompareKind.ConsiderEverything2); } private BoundExpression BindMemberAccessBadResult(BoundMethodGroup node) { var nameSyntax = node.NameSyntax; var syntax = node.MemberAccessExpressionSyntax ?? nameSyntax; return this.BindMemberAccessBadResult(syntax, node.Name, node.ReceiverOpt, node.LookupError, StaticCast<Symbol>.From(node.Methods), node.ResultKind); } /// <summary> /// Return a BoundExpression representing the invalid member. /// </summary> private BoundExpression BindMemberAccessBadResult( SyntaxNode node, string nameString, BoundExpression boundLeft, DiagnosticInfo lookupError, ImmutableArray<Symbol> symbols, LookupResultKind lookupKind) { if (symbols.Length > 0 && symbols[0].Kind == SymbolKind.Method) { var builder = ArrayBuilder<MethodSymbol>.GetInstance(); foreach (var s in symbols) { var m = s as MethodSymbol; if ((object)m != null) builder.Add(m); } var methods = builder.ToImmutableAndFree(); // Expose the invalid methods as a BoundMethodGroup. // Since we do not want to perform further method // lookup, searchExtensionMethods is set to false. // Don't bother calling ConstructBoundMethodGroupAndReportOmittedTypeArguments - // we've reported other errors. return new BoundMethodGroup( node, default(ImmutableArray<TypeWithAnnotations>), nameString, methods, methods.Length == 1 ? methods[0] : null, lookupError, flags: BoundMethodGroupFlags.None, receiverOpt: boundLeft, resultKind: lookupKind, hasErrors: true); } var symbolOpt = symbols.Length == 1 ? symbols[0] : null; return new BoundBadExpression( node, lookupKind, (object)symbolOpt == null ? ImmutableArray<Symbol>.Empty : ImmutableArray.Create(symbolOpt), boundLeft == null ? ImmutableArray<BoundExpression>.Empty : ImmutableArray.Create(BindToTypeForErrorRecovery(boundLeft)), GetNonMethodMemberType(symbolOpt)); } private TypeSymbol GetNonMethodMemberType(Symbol symbolOpt) { TypeSymbol resultType = null; if ((object)symbolOpt != null) { switch (symbolOpt.Kind) { case SymbolKind.Field: resultType = ((FieldSymbol)symbolOpt).GetFieldType(this.FieldsBeingBound).Type; break; case SymbolKind.Property: resultType = ((PropertySymbol)symbolOpt).Type; break; case SymbolKind.Event: resultType = ((EventSymbol)symbolOpt).Type; break; } } return resultType ?? CreateErrorType(); } /// <summary> /// Combine the receiver and arguments of an extension method /// invocation into a single argument list to allow overload resolution /// to treat the invocation as a static method invocation with no receiver. /// </summary> private static void CombineExtensionMethodArguments(BoundExpression receiver, AnalyzedArguments originalArguments, AnalyzedArguments extensionMethodArguments) { Debug.Assert(receiver != null); Debug.Assert(extensionMethodArguments.Arguments.Count == 0); Debug.Assert(extensionMethodArguments.Names.Count == 0); Debug.Assert(extensionMethodArguments.RefKinds.Count == 0); extensionMethodArguments.IsExtensionMethodInvocation = true; extensionMethodArguments.Arguments.Add(receiver); extensionMethodArguments.Arguments.AddRange(originalArguments.Arguments); if (originalArguments.Names.Count > 0) { extensionMethodArguments.Names.Add(null); extensionMethodArguments.Names.AddRange(originalArguments.Names); } if (originalArguments.RefKinds.Count > 0) { extensionMethodArguments.RefKinds.Add(RefKind.None); extensionMethodArguments.RefKinds.AddRange(originalArguments.RefKinds); } } /// <summary> /// Binds a static or instance member access. /// </summary> private BoundExpression BindMemberOfType( SyntaxNode node, SyntaxNode right, string plainName, int arity, bool indexed, BoundExpression left, SeparatedSyntaxList<TypeSyntax> typeArgumentsSyntax, ImmutableArray<TypeWithAnnotations> typeArgumentsWithAnnotations, LookupResult lookupResult, BoundMethodGroupFlags methodGroupFlags, BindingDiagnosticBag diagnostics) { Debug.Assert(node != null); Debug.Assert(left != null); Debug.Assert(lookupResult.IsMultiViable); Debug.Assert(lookupResult.Symbols.Any()); var members = ArrayBuilder<Symbol>.GetInstance(); BoundExpression result; bool wasError; Symbol symbol = GetSymbolOrMethodOrPropertyGroup(lookupResult, right, plainName, arity, members, diagnostics, out wasError, qualifierOpt: left is BoundTypeExpression typeExpr ? typeExpr.Type : null); if ((object)symbol == null) { Debug.Assert(members.Count > 0); // If I identifies one or more methods, then the result is a method group with // no associated instance expression. If a type argument list was specified, it // is used in calling a generic method. // (Note that for static methods, we are stashing away the type expression in // the receiver of the method group, even though the spec notes that there is // no associated instance expression.) result = ConstructBoundMemberGroupAndReportOmittedTypeArguments( node, typeArgumentsSyntax, typeArgumentsWithAnnotations, left, plainName, members, lookupResult, methodGroupFlags, wasError, diagnostics); } else { // methods are special because of extension methods. Debug.Assert(symbol.Kind != SymbolKind.Method); left = ReplaceTypeOrValueReceiver(left, symbol.IsStatic || symbol.Kind == SymbolKind.NamedType, diagnostics); // Events are handled later as we don't know yet if we are binding to the event or it's backing field. if (symbol.Kind != SymbolKind.Event) { ReportDiagnosticsIfObsolete(diagnostics, symbol, node, hasBaseReceiver: left.Kind == BoundKind.BaseReference); } switch (symbol.Kind) { case SymbolKind.NamedType: case SymbolKind.ErrorType: if (IsInstanceReceiver(left) == true && !wasError) { // CS0572: 'B': cannot reference a type through an expression; try 'A.B' instead Error(diagnostics, ErrorCode.ERR_BadTypeReference, right, plainName, symbol); wasError = true; } // If I identifies a type, then the result is that type constructed with // the given type arguments. var type = (NamedTypeSymbol)symbol; if (!typeArgumentsWithAnnotations.IsDefault) { type = ConstructNamedTypeUnlessTypeArgumentOmitted(right, type, typeArgumentsSyntax, typeArgumentsWithAnnotations, diagnostics); } result = new BoundTypeExpression( syntax: node, aliasOpt: null, boundContainingTypeOpt: left as BoundTypeExpression, boundDimensionsOpt: ImmutableArray<BoundExpression>.Empty, typeWithAnnotations: TypeWithAnnotations.Create(type)); break; case SymbolKind.Property: // If I identifies a static property, then the result is a property // access with no associated instance expression. result = BindPropertyAccess(node, left, (PropertySymbol)symbol, diagnostics, lookupResult.Kind, hasErrors: wasError); break; case SymbolKind.Event: // If I identifies a static event, then the result is an event // access with no associated instance expression. result = BindEventAccess(node, left, (EventSymbol)symbol, diagnostics, lookupResult.Kind, hasErrors: wasError); break; case SymbolKind.Field: // If I identifies a static field: // UNDONE: If the field is readonly and the reference occurs outside the static constructor of // UNDONE: the class or struct in which the field is declared, then the result is a value, namely // UNDONE: the value of the static field I in E. // UNDONE: Otherwise, the result is a variable, namely the static field I in E. // UNDONE: Need a way to mark an expression node as "I am a variable, not a value". result = BindFieldAccess(node, left, (FieldSymbol)symbol, diagnostics, lookupResult.Kind, indexed, hasErrors: wasError); break; default: throw ExceptionUtilities.UnexpectedValue(symbol.Kind); } } members.Free(); return result; } protected MethodGroupResolution BindExtensionMethod( SyntaxNode expression, string methodName, AnalyzedArguments analyzedArguments, BoundExpression left, ImmutableArray<TypeWithAnnotations> typeArgumentsWithAnnotations, bool isMethodGroupConversion, RefKind returnRefKind, TypeSymbol returnType, bool withDependencies) { var firstResult = new MethodGroupResolution(); AnalyzedArguments actualArguments = null; foreach (var scope in new ExtensionMethodScopes(this)) { var methodGroup = MethodGroup.GetInstance(); var diagnostics = BindingDiagnosticBag.GetInstance(withDiagnostics: true, withDependencies); this.PopulateExtensionMethodsFromSingleBinder(scope, methodGroup, expression, left, methodName, typeArgumentsWithAnnotations, diagnostics); // analyzedArguments will be null if the caller is resolving for error recovery to the first method group // that can accept that receiver, regardless of arguments, when the signature cannot be inferred. // (In the error case of nameof(o.M) or the error case of o.M = null; for instance.) if (analyzedArguments == null) { if (expression == EnclosingNameofArgument) { for (int i = methodGroup.Methods.Count - 1; i >= 0; i--) { if ((object)methodGroup.Methods[i].ReduceExtensionMethod(left.Type, this.Compilation) == null) methodGroup.Methods.RemoveAt(i); } } if (methodGroup.Methods.Count != 0) { return new MethodGroupResolution(methodGroup, diagnostics.ToReadOnlyAndFree()); } } if (methodGroup.Methods.Count == 0) { methodGroup.Free(); diagnostics.Free(); continue; } if (actualArguments == null) { // Create a set of arguments for overload resolution of the // extension methods that includes the "this" parameter. actualArguments = AnalyzedArguments.GetInstance(); CombineExtensionMethodArguments(left, analyzedArguments, actualArguments); } var overloadResolutionResult = OverloadResolutionResult<MethodSymbol>.GetInstance(); bool allowRefOmittedArguments = methodGroup.Receiver.IsExpressionOfComImportType(); CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); OverloadResolution.MethodInvocationOverloadResolution( methods: methodGroup.Methods, typeArguments: methodGroup.TypeArguments, receiver: methodGroup.Receiver, arguments: actualArguments, result: overloadResolutionResult, useSiteInfo: ref useSiteInfo, isMethodGroupConversion: isMethodGroupConversion, allowRefOmittedArguments: allowRefOmittedArguments, returnRefKind: returnRefKind, returnType: returnType); diagnostics.Add(expression, useSiteInfo); var sealedDiagnostics = diagnostics.ToReadOnlyAndFree(); // Note: the MethodGroupResolution instance is responsible for freeing its copy of actual arguments var result = new MethodGroupResolution(methodGroup, null, overloadResolutionResult, AnalyzedArguments.GetInstance(actualArguments), methodGroup.ResultKind, sealedDiagnostics); // If the search in the current scope resulted in any applicable method (regardless of whether a best // applicable method could be determined) then our search is complete. Otherwise, store aside the // first non-applicable result and continue searching for an applicable result. if (result.HasAnyApplicableMethod) { if (!firstResult.IsEmpty) { firstResult.MethodGroup.Free(); firstResult.OverloadResolutionResult.Free(); } return result; } else if (firstResult.IsEmpty) { firstResult = result; } else { // Neither the first result, nor applicable. No need to save result. overloadResolutionResult.Free(); methodGroup.Free(); } } Debug.Assert((actualArguments == null) || !firstResult.IsEmpty); actualArguments?.Free(); return firstResult; } private void PopulateExtensionMethodsFromSingleBinder( ExtensionMethodScope scope, MethodGroup methodGroup, SyntaxNode node, BoundExpression left, string rightName, ImmutableArray<TypeWithAnnotations> typeArgumentsWithAnnotations, BindingDiagnosticBag diagnostics) { int arity; LookupOptions options; if (typeArgumentsWithAnnotations.IsDefault) { arity = 0; options = LookupOptions.AllMethodsOnArityZero; } else { arity = typeArgumentsWithAnnotations.Length; options = LookupOptions.Default; } var lookupResult = LookupResult.GetInstance(); CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); this.LookupExtensionMethodsInSingleBinder(scope, lookupResult, rightName, arity, options, ref useSiteInfo); diagnostics.Add(node, useSiteInfo); if (lookupResult.IsMultiViable) { Debug.Assert(lookupResult.Symbols.Any()); var members = ArrayBuilder<Symbol>.GetInstance(); bool wasError; Symbol symbol = GetSymbolOrMethodOrPropertyGroup(lookupResult, node, rightName, arity, members, diagnostics, out wasError, qualifierOpt: null); Debug.Assert((object)symbol == null); Debug.Assert(members.Count > 0); methodGroup.PopulateWithExtensionMethods(left, members, typeArgumentsWithAnnotations, lookupResult.Kind); members.Free(); } lookupResult.Free(); } protected BoundExpression BindFieldAccess( SyntaxNode node, BoundExpression receiver, FieldSymbol fieldSymbol, BindingDiagnosticBag diagnostics, LookupResultKind resultKind, bool indexed, bool hasErrors) { bool hasError = false; NamedTypeSymbol type = fieldSymbol.ContainingType; var isEnumField = (fieldSymbol.IsStatic && type.IsEnumType()); if (isEnumField && !type.IsValidEnumType()) { Error(diagnostics, ErrorCode.ERR_BindToBogus, node, fieldSymbol); hasError = true; } if (!hasError) { hasError = this.CheckInstanceOrStatic(node, receiver, fieldSymbol, ref resultKind, diagnostics); } if (!hasError && fieldSymbol.IsFixedSizeBuffer && !IsInsideNameof) { // SPEC: In a member access of the form E.I, if E is of a struct type and a member lookup of I in // that struct type identifies a fixed size member, then E.I is evaluated and classified as follows: // * If the expression E.I does not occur in an unsafe context, a compile-time error occurs. // * If E is classified as a value, a compile-time error occurs. // * Otherwise, if E is a moveable variable and the expression E.I is not a fixed_pointer_initializer, // a compile-time error occurs. // * Otherwise, E references a fixed variable and the result of the expression is a pointer to the // first element of the fixed size buffer member I in E. The result is of type S*, where S is // the element type of I, and is classified as a value. TypeSymbol receiverType = receiver.Type; // Reflect errors that have been reported elsewhere... hasError = (object)receiverType == null || !receiverType.IsValueType; if (!hasError) { var isFixedStatementExpression = SyntaxFacts.IsFixedStatementExpression(node); if (IsMoveableVariable(receiver, out Symbol accessedLocalOrParameterOpt) != isFixedStatementExpression) { if (indexed) { // SPEC C# 7.3: If the fixed size buffer access is the receiver of an element_access_expression, // E may be either fixed or moveable CheckFeatureAvailability(node, MessageID.IDS_FeatureIndexingMovableFixedBuffers, diagnostics); } else { Error(diagnostics, isFixedStatementExpression ? ErrorCode.ERR_FixedNotNeeded : ErrorCode.ERR_FixedBufferNotFixed, node); hasErrors = hasError = true; } } } if (!hasError) { hasError = !CheckValueKind(node, receiver, BindValueKind.FixedReceiver, checkingReceiver: false, diagnostics: diagnostics); } } ConstantValue constantValueOpt = null; if (fieldSymbol.IsConst && !IsInsideNameof) { constantValueOpt = fieldSymbol.GetConstantValue(this.ConstantFieldsInProgress, this.IsEarlyAttributeBinder); if (constantValueOpt == ConstantValue.Unset) { // Evaluating constant expression before dependencies // have been evaluated. Treat this as a Bad value. constantValueOpt = ConstantValue.Bad; } } if (!fieldSymbol.IsStatic) { WarnOnAccessOfOffDefault(node, receiver, diagnostics); } if (!IsBadBaseAccess(node, receiver, fieldSymbol, diagnostics)) { CheckReceiverAndRuntimeSupportForSymbolAccess(node, receiver, fieldSymbol, diagnostics); } TypeSymbol fieldType = fieldSymbol.GetFieldType(this.FieldsBeingBound).Type; BoundExpression expr = new BoundFieldAccess(node, receiver, fieldSymbol, constantValueOpt, resultKind, fieldType, hasErrors: (hasErrors || hasError)); // Spec 14.3: "Within an enum member initializer, values of other enum members are // always treated as having the type of their underlying type" if (this.InEnumMemberInitializer()) { NamedTypeSymbol enumType = null; if (isEnumField) { // This is an obvious consequence of the spec. // It is for cases like: // enum E { // A, // B = A + 1, //A is implicitly converted to int (underlying type) // } enumType = type; } else if (constantValueOpt != null && fieldType.IsEnumType()) { // This seems like a borderline SPEC VIOLATION that we're preserving for back compat. // It is for cases like: // const E e = E.A; // enum E { // A, // B = e + 1, //e is implicitly converted to int (underlying type) // } enumType = (NamedTypeSymbol)fieldType; } if ((object)enumType != null) { NamedTypeSymbol underlyingType = enumType.EnumUnderlyingType; Debug.Assert((object)underlyingType != null); expr = new BoundConversion( node, expr, Conversion.ImplicitNumeric, @checked: true, explicitCastInCode: false, conversionGroupOpt: null, constantValueOpt: expr.ConstantValue, type: underlyingType); } } return expr; } private bool InEnumMemberInitializer() { var containingType = this.ContainingType; return this.InFieldInitializer && (object)containingType != null && containingType.IsEnumType(); } private BoundExpression BindPropertyAccess( SyntaxNode node, BoundExpression receiver, PropertySymbol propertySymbol, BindingDiagnosticBag diagnostics, LookupResultKind lookupResult, bool hasErrors) { bool hasError = this.CheckInstanceOrStatic(node, receiver, propertySymbol, ref lookupResult, diagnostics); if (!propertySymbol.IsStatic) { WarnOnAccessOfOffDefault(node, receiver, diagnostics); } return new BoundPropertyAccess(node, receiver, propertySymbol, lookupResult, propertySymbol.Type, hasErrors: (hasErrors || hasError)); } private void CheckReceiverAndRuntimeSupportForSymbolAccess(SyntaxNode node, BoundExpression receiverOpt, Symbol symbol, BindingDiagnosticBag diagnostics) { if (symbol.ContainingType?.IsInterface == true) { if (symbol.IsStatic && symbol.IsAbstract) { Debug.Assert(symbol is not TypeSymbol); if (receiverOpt is BoundQueryClause { Value: var value }) { receiverOpt = value; } if (receiverOpt is not BoundTypeExpression { Type: { TypeKind: TypeKind.TypeParameter } }) { Error(diagnostics, ErrorCode.ERR_BadAbstractStaticMemberAccess, node); return; } if (!Compilation.Assembly.RuntimeSupportsStaticAbstractMembersInInterfaces && Compilation.SourceModule != symbol.ContainingModule) { Error(diagnostics, ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, node); return; } } if (!Compilation.Assembly.RuntimeSupportsDefaultInterfaceImplementation && Compilation.SourceModule != symbol.ContainingModule) { if (!symbol.IsStatic && !(symbol is TypeSymbol) && !symbol.IsImplementableInterfaceMember()) { Error(diagnostics, ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, node); } else { switch (symbol.DeclaredAccessibility) { case Accessibility.Protected: case Accessibility.ProtectedOrInternal: case Accessibility.ProtectedAndInternal: Error(diagnostics, ErrorCode.ERR_RuntimeDoesNotSupportProtectedAccessForInterfaceMember, node); break; } } } } } private BoundExpression BindEventAccess( SyntaxNode node, BoundExpression receiver, EventSymbol eventSymbol, BindingDiagnosticBag diagnostics, LookupResultKind lookupResult, bool hasErrors) { CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); bool isUsableAsField = eventSymbol.HasAssociatedField && this.IsAccessible(eventSymbol.AssociatedField, ref useSiteInfo, (receiver != null) ? receiver.Type : null); diagnostics.Add(node, useSiteInfo); bool hasError = this.CheckInstanceOrStatic(node, receiver, eventSymbol, ref lookupResult, diagnostics); if (!eventSymbol.IsStatic) { WarnOnAccessOfOffDefault(node, receiver, diagnostics); } return new BoundEventAccess(node, receiver, eventSymbol, isUsableAsField, lookupResult, eventSymbol.Type, hasErrors: (hasErrors || hasError)); } // Say if the receive is an instance or a type, or could be either (returns null). private static bool? IsInstanceReceiver(BoundExpression receiver) { if (receiver == null) { return false; } else { switch (receiver.Kind) { case BoundKind.PreviousSubmissionReference: // Could be either instance or static reference. return null; case BoundKind.TypeExpression: return false; case BoundKind.QueryClause: return IsInstanceReceiver(((BoundQueryClause)receiver).Value); default: return true; } } } private bool CheckInstanceOrStatic( SyntaxNode node, BoundExpression receiver, Symbol symbol, ref LookupResultKind resultKind, BindingDiagnosticBag diagnostics) { bool? instanceReceiver = IsInstanceReceiver(receiver); if (!symbol.RequiresInstanceReceiver()) { if (instanceReceiver == true) { ErrorCode errorCode = this.Flags.Includes(BinderFlags.ObjectInitializerMember) ? ErrorCode.ERR_StaticMemberInObjectInitializer : ErrorCode.ERR_ObjectProhibited; Error(diagnostics, errorCode, node, symbol); resultKind = LookupResultKind.StaticInstanceMismatch; return true; } } else { if (instanceReceiver == false && !IsInsideNameof) { Error(diagnostics, ErrorCode.ERR_ObjectRequired, node, symbol); resultKind = LookupResultKind.StaticInstanceMismatch; return true; } } return false; } /// <summary> /// Given a viable LookupResult, report any ambiguity errors and return either a single /// non-method symbol or a method or property group. If the result set represents a /// collection of methods or a collection of properties where at least one of the properties /// is an indexed property, then 'methodOrPropertyGroup' is populated with the method or /// property group and the method returns null. Otherwise, the method returns a single /// symbol and 'methodOrPropertyGroup' is empty. (Since the result set is viable, there /// must be at least one symbol.) If the result set is ambiguous - either containing multiple /// members of different member types, or multiple properties but no indexed properties - /// then a diagnostic is reported for the ambiguity and a single symbol is returned. /// </summary> private Symbol GetSymbolOrMethodOrPropertyGroup(LookupResult result, SyntaxNode node, string plainName, int arity, ArrayBuilder<Symbol> methodOrPropertyGroup, BindingDiagnosticBag diagnostics, out bool wasError, NamespaceOrTypeSymbol qualifierOpt) { Debug.Assert(!methodOrPropertyGroup.Any()); node = GetNameSyntax(node) ?? node; wasError = false; Debug.Assert(result.Kind != LookupResultKind.Empty); Debug.Assert(!result.Symbols.Any(s => s.IsIndexer())); Symbol other = null; // different member type from 'methodOrPropertyGroup' // Populate 'methodOrPropertyGroup' with a set of methods if any, // or a set of properties if properties but no methods. If there are // other member types, 'other' will be set to one of those members. foreach (var symbol in result.Symbols) { var kind = symbol.Kind; if (methodOrPropertyGroup.Count > 0) { var existingKind = methodOrPropertyGroup[0].Kind; if (existingKind != kind) { // Mix of different member kinds. Prefer methods over // properties and properties over other members. if ((existingKind == SymbolKind.Method) || ((existingKind == SymbolKind.Property) && (kind != SymbolKind.Method))) { other = symbol; continue; } other = methodOrPropertyGroup[0]; methodOrPropertyGroup.Clear(); } } if ((kind == SymbolKind.Method) || (kind == SymbolKind.Property)) { // SPEC VIOLATION: The spec states "Members that include an override modifier are excluded from the set" // SPEC VIOLATION: However, we are not going to do that here; we will keep the overriding member // SPEC VIOLATION: in the method group. The reason is because for features like "go to definition" // SPEC VIOLATION: we wish to go to the overriding member, not to the member of the base class. // SPEC VIOLATION: Or, for code generation of a call to Int32.ToString() we want to generate // SPEC VIOLATION: code that directly calls the Int32.ToString method with an int on the stack, // SPEC VIOLATION: rather than making a virtual call to ToString on a boxed int. methodOrPropertyGroup.Add(symbol); } else { other = symbol; } } Debug.Assert(methodOrPropertyGroup.Any() || ((object)other != null)); if ((methodOrPropertyGroup.Count > 0) && IsMethodOrPropertyGroup(methodOrPropertyGroup)) { // Ambiguities between methods and non-methods are reported here, // but all other ambiguities, including those between properties and // non-methods, are reported in ResultSymbol. if ((methodOrPropertyGroup[0].Kind == SymbolKind.Method) || ((object)other == null)) { // Result will be treated as a method or property group. Any additional // checks, such as use-site errors, must be handled by the caller when // converting to method invocation or property access. if (result.Error != null) { Error(diagnostics, result.Error, node); wasError = (result.Error.Severity == DiagnosticSeverity.Error); } return null; } } methodOrPropertyGroup.Clear(); return ResultSymbol(result, plainName, arity, node, diagnostics, false, out wasError, qualifierOpt); } private static bool IsMethodOrPropertyGroup(ArrayBuilder<Symbol> members) { Debug.Assert(members.Count > 0); var member = members[0]; // Members should be a consistent type. Debug.Assert(members.All(m => m.Kind == member.Kind)); switch (member.Kind) { case SymbolKind.Method: return true; case SymbolKind.Property: Debug.Assert(members.All(m => !m.IsIndexer())); // Do not treat a set of non-indexed properties as a property group, to // avoid the overhead of a BoundPropertyGroup node and overload // resolution for the common property access case. If there are multiple // non-indexed properties (two properties P that differ by custom attributes // for instance), the expectation is that the caller will report an ambiguity // and choose one for error recovery. foreach (PropertySymbol property in members) { if (property.IsIndexedProperty) { return true; } } return false; default: throw ExceptionUtilities.UnexpectedValue(member.Kind); } } private BoundExpression BindElementAccess(ElementAccessExpressionSyntax node, BindingDiagnosticBag diagnostics) { BoundExpression receiver = BindExpression(node.Expression, diagnostics: diagnostics, invoked: false, indexed: true); return BindElementAccess(node, receiver, node.ArgumentList, diagnostics); } private BoundExpression BindElementAccess(ExpressionSyntax node, BoundExpression receiver, BracketedArgumentListSyntax argumentList, BindingDiagnosticBag diagnostics) { AnalyzedArguments analyzedArguments = AnalyzedArguments.GetInstance(); try { BindArgumentsAndNames(argumentList, diagnostics, analyzedArguments); if (receiver.Kind == BoundKind.PropertyGroup) { var propertyGroup = (BoundPropertyGroup)receiver; return BindIndexedPropertyAccess(node, propertyGroup.ReceiverOpt, propertyGroup.Properties, analyzedArguments, diagnostics); } receiver = CheckValue(receiver, BindValueKind.RValue, diagnostics); receiver = BindToNaturalType(receiver, diagnostics); return BindElementOrIndexerAccess(node, receiver, analyzedArguments, diagnostics); } finally { analyzedArguments.Free(); } } private BoundExpression BindElementOrIndexerAccess(ExpressionSyntax node, BoundExpression expr, AnalyzedArguments analyzedArguments, BindingDiagnosticBag diagnostics) { if ((object)expr.Type == null) { return BadIndexerExpression(node, expr, analyzedArguments, null, diagnostics); } WarnOnAccessOfOffDefault(node, expr, diagnostics); // Did we have any errors? if (analyzedArguments.HasErrors || expr.HasAnyErrors) { // At this point we definitely have reported an error, but we still might be // able to get more semantic analysis of the indexing operation. We do not // want to report cascading errors. BoundExpression result = BindElementAccessCore(node, expr, analyzedArguments, BindingDiagnosticBag.Discarded); return result; } return BindElementAccessCore(node, expr, analyzedArguments, diagnostics); } private BoundExpression BadIndexerExpression(ExpressionSyntax node, BoundExpression expr, AnalyzedArguments analyzedArguments, DiagnosticInfo errorOpt, BindingDiagnosticBag diagnostics) { if (!expr.HasAnyErrors) { diagnostics.Add(errorOpt ?? new CSDiagnosticInfo(ErrorCode.ERR_BadIndexLHS, expr.Display), node.Location); } var childBoundNodes = BuildArgumentsForErrorRecovery(analyzedArguments).Add(expr); return new BoundBadExpression(node, LookupResultKind.Empty, ImmutableArray<Symbol>.Empty, childBoundNodes, CreateErrorType(), hasErrors: true); } private BoundExpression BindElementAccessCore( ExpressionSyntax node, BoundExpression expr, AnalyzedArguments arguments, BindingDiagnosticBag diagnostics) { Debug.Assert(node != null); Debug.Assert(expr != null); Debug.Assert((object)expr.Type != null); Debug.Assert(arguments != null); var exprType = expr.Type; switch (exprType.TypeKind) { case TypeKind.Array: return BindArrayAccess(node, expr, arguments, diagnostics); case TypeKind.Dynamic: return BindDynamicIndexer(node, expr, arguments, ImmutableArray<PropertySymbol>.Empty, diagnostics); case TypeKind.Pointer: return BindPointerElementAccess(node, expr, arguments, diagnostics); case TypeKind.Class: case TypeKind.Struct: case TypeKind.Interface: case TypeKind.TypeParameter: return BindIndexerAccess(node, expr, arguments, diagnostics); case TypeKind.Submission: // script class is synthesized and should not be used as a type of an indexer expression: default: return BadIndexerExpression(node, expr, arguments, null, diagnostics); } } private BoundExpression BindArrayAccess(ExpressionSyntax node, BoundExpression expr, AnalyzedArguments arguments, BindingDiagnosticBag diagnostics) { Debug.Assert(node != null); Debug.Assert(expr != null); Debug.Assert(arguments != null); // For an array access, the primary-no-array-creation-expression of the element-access // must be a value of an array-type. Furthermore, the argument-list of an array access // is not allowed to contain named arguments.The number of expressions in the // argument-list must be the same as the rank of the array-type, and each expression // must be of type int, uint, long, ulong, or must be implicitly convertible to one or // more of these types. if (arguments.Names.Count > 0) { Error(diagnostics, ErrorCode.ERR_NamedArgumentForArray, node); } bool hasErrors = ReportRefOrOutArgument(arguments, diagnostics); var arrayType = (ArrayTypeSymbol)expr.Type; // Note that the spec says to determine which of {int, uint, long, ulong} *each* index // expression is convertible to. That is not what C# 1 through 4 did; the // implementations instead determined which of those four types *all* of the index // expressions converted to. int rank = arrayType.Rank; if (arguments.Arguments.Count != rank) { Error(diagnostics, ErrorCode.ERR_BadIndexCount, node, rank); return new BoundArrayAccess(node, expr, BuildArgumentsForErrorRecovery(arguments), arrayType.ElementType, hasErrors: true); } // Convert all the arguments to the array index type. BoundExpression[] convertedArguments = new BoundExpression[arguments.Arguments.Count]; for (int i = 0; i < arguments.Arguments.Count; ++i) { BoundExpression argument = arguments.Arguments[i]; BoundExpression index = ConvertToArrayIndex(argument, diagnostics, allowIndexAndRange: rank == 1); convertedArguments[i] = index; // NOTE: Dev10 only warns if rank == 1 // Question: Why do we limit this warning to one-dimensional arrays? // Answer: Because multidimensional arrays can have nonzero lower bounds in the CLR. if (rank == 1 && !index.HasAnyErrors) { ConstantValue constant = index.ConstantValue; if (constant != null && constant.IsNegativeNumeric) { Error(diagnostics, ErrorCode.WRN_NegativeArrayIndex, index.Syntax); } } } TypeSymbol resultType = rank == 1 && TypeSymbol.Equals( convertedArguments[0].Type, Compilation.GetWellKnownType(WellKnownType.System_Range), TypeCompareKind.ConsiderEverything) ? arrayType : arrayType.ElementType; return hasErrors ? new BoundArrayAccess(node, BindToTypeForErrorRecovery(expr), convertedArguments.Select(e => BindToTypeForErrorRecovery(e)).AsImmutableOrNull(), resultType, hasErrors: true) : new BoundArrayAccess(node, expr, convertedArguments.AsImmutableOrNull(), resultType, hasErrors: false); } private BoundExpression ConvertToArrayIndex(BoundExpression index, BindingDiagnosticBag diagnostics, bool allowIndexAndRange) { Debug.Assert(index != null); if (index.Kind == BoundKind.OutVariablePendingInference) { return ((OutVariablePendingInference)index).FailInference(this, diagnostics); } else if (index.Kind == BoundKind.DiscardExpression && !index.HasExpressionType()) { return ((BoundDiscardExpression)index).FailInference(this, diagnostics); } var node = index.Syntax; var result = TryImplicitConversionToArrayIndex(index, SpecialType.System_Int32, node, diagnostics) ?? TryImplicitConversionToArrayIndex(index, SpecialType.System_UInt32, node, diagnostics) ?? TryImplicitConversionToArrayIndex(index, SpecialType.System_Int64, node, diagnostics) ?? TryImplicitConversionToArrayIndex(index, SpecialType.System_UInt64, node, diagnostics); if (result is null && allowIndexAndRange) { result = TryImplicitConversionToArrayIndex(index, WellKnownType.System_Index, node, diagnostics); if (result is null) { result = TryImplicitConversionToArrayIndex(index, WellKnownType.System_Range, node, diagnostics); if (result is object) { // This member is needed for lowering and should produce an error if not present _ = GetWellKnownTypeMember( WellKnownMember.System_Runtime_CompilerServices_RuntimeHelpers__GetSubArray_T, diagnostics, syntax: node); } } else { // This member is needed for lowering and should produce an error if not present _ = GetWellKnownTypeMember( WellKnownMember.System_Index__GetOffset, diagnostics, syntax: node); } } if (result is null) { // Give the error that would be given upon conversion to int32. NamedTypeSymbol int32 = GetSpecialType(SpecialType.System_Int32, diagnostics, node); CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); Conversion failedConversion = this.Conversions.ClassifyConversionFromExpression(index, int32, ref useSiteInfo); diagnostics.Add(node, useSiteInfo); GenerateImplicitConversionError(diagnostics, node, failedConversion, index, int32); // Suppress any additional diagnostics return CreateConversion(node, index, failedConversion, isCast: false, conversionGroupOpt: null, destination: int32, diagnostics: BindingDiagnosticBag.Discarded); } return result; } private BoundExpression TryImplicitConversionToArrayIndex(BoundExpression expr, WellKnownType wellKnownType, SyntaxNode node, BindingDiagnosticBag diagnostics) { CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); TypeSymbol type = GetWellKnownType(wellKnownType, ref useSiteInfo); if (type.IsErrorType()) { return null; } var attemptDiagnostics = BindingDiagnosticBag.GetInstance(diagnostics); var result = TryImplicitConversionToArrayIndex(expr, type, node, attemptDiagnostics); if (result is object) { diagnostics.Add(node, useSiteInfo); diagnostics.AddRange(attemptDiagnostics); } attemptDiagnostics.Free(); return result; } private BoundExpression TryImplicitConversionToArrayIndex(BoundExpression expr, SpecialType specialType, SyntaxNode node, BindingDiagnosticBag diagnostics) { var attemptDiagnostics = BindingDiagnosticBag.GetInstance(diagnostics); TypeSymbol type = GetSpecialType(specialType, attemptDiagnostics, node); var result = TryImplicitConversionToArrayIndex(expr, type, node, attemptDiagnostics); if (result is object) { diagnostics.AddRange(attemptDiagnostics); } attemptDiagnostics.Free(); return result; } private BoundExpression TryImplicitConversionToArrayIndex(BoundExpression expr, TypeSymbol targetType, SyntaxNode node, BindingDiagnosticBag diagnostics) { Debug.Assert(expr != null); Debug.Assert((object)targetType != null); CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); Conversion conversion = this.Conversions.ClassifyImplicitConversionFromExpression(expr, targetType, ref useSiteInfo); diagnostics.Add(node, useSiteInfo); if (!conversion.Exists) { return null; } if (conversion.IsDynamic) { conversion = conversion.SetArrayIndexConversionForDynamic(); } BoundExpression result = CreateConversion(expr.Syntax, expr, conversion, isCast: false, conversionGroupOpt: null, destination: targetType, diagnostics); // UNDONE: was cast? Debug.Assert(result != null); // If this ever fails (it shouldn't), then put a null-check around the diagnostics update. return result; } private BoundExpression BindPointerElementAccess(ExpressionSyntax node, BoundExpression expr, AnalyzedArguments analyzedArguments, BindingDiagnosticBag diagnostics) { Debug.Assert(node != null); Debug.Assert(expr != null); Debug.Assert(analyzedArguments != null); bool hasErrors = false; if (analyzedArguments.Names.Count > 0) { // CONSIDER: the error text for this error code mentions "arrays". It might be nice if we had // a separate error code for pointer element access. Error(diagnostics, ErrorCode.ERR_NamedArgumentForArray, node); hasErrors = true; } hasErrors = hasErrors || ReportRefOrOutArgument(analyzedArguments, diagnostics); Debug.Assert(expr.Type.IsPointerType()); PointerTypeSymbol pointerType = (PointerTypeSymbol)expr.Type; TypeSymbol pointedAtType = pointerType.PointedAtType; ArrayBuilder<BoundExpression> arguments = analyzedArguments.Arguments; if (arguments.Count != 1) { if (!hasErrors) { Error(diagnostics, ErrorCode.ERR_PtrIndexSingle, node); } return new BoundPointerElementAccess(node, expr, BadExpression(node, BuildArgumentsForErrorRecovery(analyzedArguments)).MakeCompilerGenerated(), CheckOverflowAtRuntime, pointedAtType, hasErrors: true); } if (pointedAtType.IsVoidType()) { Error(diagnostics, ErrorCode.ERR_VoidError, expr.Syntax); hasErrors = true; } BoundExpression index = arguments[0]; index = ConvertToArrayIndex(index, diagnostics, allowIndexAndRange: false); return new BoundPointerElementAccess(node, expr, index, CheckOverflowAtRuntime, pointedAtType, hasErrors); } private static bool ReportRefOrOutArgument(AnalyzedArguments analyzedArguments, BindingDiagnosticBag diagnostics) { int numArguments = analyzedArguments.Arguments.Count; for (int i = 0; i < numArguments; i++) { RefKind refKind = analyzedArguments.RefKind(i); if (refKind != RefKind.None) { Error(diagnostics, ErrorCode.ERR_BadArgExtraRef, analyzedArguments.Argument(i).Syntax, i + 1, refKind.ToArgumentDisplayString()); return true; } } return false; } private BoundExpression BindIndexerAccess(ExpressionSyntax node, BoundExpression expr, AnalyzedArguments analyzedArguments, BindingDiagnosticBag diagnostics) { Debug.Assert(node != null); Debug.Assert(expr != null); Debug.Assert((object)expr.Type != null); Debug.Assert(analyzedArguments != null); LookupResult lookupResult = LookupResult.GetInstance(); LookupOptions lookupOptions = expr.Kind == BoundKind.BaseReference ? LookupOptions.UseBaseReferenceAccessibility : LookupOptions.Default; CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); this.LookupMembersWithFallback(lookupResult, expr.Type, WellKnownMemberNames.Indexer, arity: 0, useSiteInfo: ref useSiteInfo, options: lookupOptions); diagnostics.Add(node, useSiteInfo); // Store, rather than return, so that we can release resources. BoundExpression indexerAccessExpression; if (!lookupResult.IsMultiViable) { if (TryBindIndexOrRangeIndexer( node, expr, analyzedArguments, diagnostics, out var patternIndexerAccess)) { indexerAccessExpression = patternIndexerAccess; } else { indexerAccessExpression = BadIndexerExpression(node, expr, analyzedArguments, lookupResult.Error, diagnostics); } } else { ArrayBuilder<PropertySymbol> indexerGroup = ArrayBuilder<PropertySymbol>.GetInstance(); foreach (Symbol symbol in lookupResult.Symbols) { Debug.Assert(symbol.IsIndexer()); indexerGroup.Add((PropertySymbol)symbol); } indexerAccessExpression = BindIndexerOrIndexedPropertyAccess(node, expr, indexerGroup, analyzedArguments, diagnostics); indexerGroup.Free(); } lookupResult.Free(); return indexerAccessExpression; } private static readonly Func<PropertySymbol, bool> s_isIndexedPropertyWithNonOptionalArguments = property => { if (property.IsIndexer || !property.IsIndexedProperty) { return false; } Debug.Assert(property.ParameterCount > 0); var parameter = property.Parameters[0]; return !parameter.IsOptional && !parameter.IsParams; }; private static readonly SymbolDisplayFormat s_propertyGroupFormat = new SymbolDisplayFormat( globalNamespaceStyle: SymbolDisplayGlobalNamespaceStyle.Omitted, memberOptions: SymbolDisplayMemberOptions.IncludeContainingType, miscellaneousOptions: SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers | SymbolDisplayMiscellaneousOptions.UseSpecialTypes); private BoundExpression BindIndexedPropertyAccess(BoundPropertyGroup propertyGroup, bool mustHaveAllOptionalParameters, BindingDiagnosticBag diagnostics) { var syntax = propertyGroup.Syntax; var receiverOpt = propertyGroup.ReceiverOpt; var properties = propertyGroup.Properties; if (properties.All(s_isIndexedPropertyWithNonOptionalArguments)) { Error(diagnostics, mustHaveAllOptionalParameters ? ErrorCode.ERR_IndexedPropertyMustHaveAllOptionalParams : ErrorCode.ERR_IndexedPropertyRequiresParams, syntax, properties[0].ToDisplayString(s_propertyGroupFormat)); return BoundIndexerAccess.ErrorAccess( syntax, receiverOpt, CreateErrorPropertySymbol(properties), ImmutableArray<BoundExpression>.Empty, default(ImmutableArray<string>), default(ImmutableArray<RefKind>), properties); } var arguments = AnalyzedArguments.GetInstance(); var result = BindIndexedPropertyAccess(syntax, receiverOpt, properties, arguments, diagnostics); arguments.Free(); return result; } private BoundExpression BindIndexedPropertyAccess(SyntaxNode syntax, BoundExpression receiverOpt, ImmutableArray<PropertySymbol> propertyGroup, AnalyzedArguments arguments, BindingDiagnosticBag diagnostics) { // TODO: We're creating an extra copy of the properties array in BindIndexerOrIndexedProperty // converting the ArrayBuilder to ImmutableArray. Avoid the extra copy. var properties = ArrayBuilder<PropertySymbol>.GetInstance(); properties.AddRange(propertyGroup); var result = BindIndexerOrIndexedPropertyAccess(syntax, receiverOpt, properties, arguments, diagnostics); properties.Free(); return result; } private BoundExpression BindDynamicIndexer( SyntaxNode syntax, BoundExpression receiver, AnalyzedArguments arguments, ImmutableArray<PropertySymbol> applicableProperties, BindingDiagnosticBag diagnostics) { bool hasErrors = false; BoundKind receiverKind = receiver.Kind; if (receiverKind == BoundKind.BaseReference) { Error(diagnostics, ErrorCode.ERR_NoDynamicPhantomOnBaseIndexer, syntax); hasErrors = true; } else if (receiverKind == BoundKind.TypeOrValueExpression) { var typeOrValue = (BoundTypeOrValueExpression)receiver; // Unfortunately, the runtime binder doesn't have APIs that would allow us to pass both "type or value". // Ideally the runtime binder would choose between type and value based on the result of the overload resolution. // We need to pick one or the other here. Dev11 compiler passes the type only if the value can't be accessed. bool inStaticContext; bool useType = IsInstance(typeOrValue.Data.ValueSymbol) && !HasThis(isExplicit: false, inStaticContext: out inStaticContext); receiver = ReplaceTypeOrValueReceiver(typeOrValue, useType, diagnostics); } var argArray = BuildArgumentsForDynamicInvocation(arguments, diagnostics); var refKindsArray = arguments.RefKinds.ToImmutableOrNull(); hasErrors &= ReportBadDynamicArguments(syntax, argArray, refKindsArray, diagnostics, queryClause: null); return new BoundDynamicIndexerAccess( syntax, receiver, argArray, arguments.GetNames(), refKindsArray, applicableProperties, AssemblySymbol.DynamicType, hasErrors); } private BoundExpression BindIndexerOrIndexedPropertyAccess( SyntaxNode syntax, BoundExpression receiverOpt, ArrayBuilder<PropertySymbol> propertyGroup, AnalyzedArguments analyzedArguments, BindingDiagnosticBag diagnostics) { OverloadResolutionResult<PropertySymbol> overloadResolutionResult = OverloadResolutionResult<PropertySymbol>.GetInstance(); bool allowRefOmittedArguments = receiverOpt.IsExpressionOfComImportType(); CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); this.OverloadResolution.PropertyOverloadResolution(propertyGroup, receiverOpt, analyzedArguments, overloadResolutionResult, allowRefOmittedArguments, ref useSiteInfo); diagnostics.Add(syntax, useSiteInfo); BoundExpression propertyAccess; if (analyzedArguments.HasDynamicArgument && overloadResolutionResult.HasAnyApplicableMember) { // Note that the runtime binder may consider candidates that haven't passed compile-time final validation // and an ambiguity error may be reported. Also additional checks are performed in runtime final validation // that are not performed at compile-time. // Only if the set of final applicable candidates is empty we know for sure the call will fail at runtime. var finalApplicableCandidates = GetCandidatesPassingFinalValidation(syntax, overloadResolutionResult, receiverOpt, default(ImmutableArray<TypeWithAnnotations>), diagnostics); overloadResolutionResult.Free(); return BindDynamicIndexer(syntax, receiverOpt, analyzedArguments, finalApplicableCandidates, diagnostics); } ImmutableArray<string> argumentNames = analyzedArguments.GetNames(); ImmutableArray<RefKind> argumentRefKinds = analyzedArguments.RefKinds.ToImmutableOrNull(); if (!overloadResolutionResult.Succeeded) { // If the arguments had an error reported about them then suppress further error // reporting for overload resolution. ImmutableArray<PropertySymbol> candidates = propertyGroup.ToImmutable(); if (!analyzedArguments.HasErrors) { if (TryBindIndexOrRangeIndexer( syntax, receiverOpt, analyzedArguments, diagnostics, out var patternIndexerAccess)) { return patternIndexerAccess; } else { // Dev10 uses the "this" keyword as the method name for indexers. var candidate = candidates[0]; var name = candidate.IsIndexer ? SyntaxFacts.GetText(SyntaxKind.ThisKeyword) : candidate.Name; overloadResolutionResult.ReportDiagnostics( binder: this, location: syntax.Location, nodeOpt: syntax, diagnostics: diagnostics, name: name, receiver: null, invokedExpression: null, arguments: analyzedArguments, memberGroup: candidates, typeContainingConstructor: null, delegateTypeBeingInvoked: null); } } ImmutableArray<BoundExpression> arguments = BuildArgumentsForErrorRecovery(analyzedArguments, candidates); // A bad BoundIndexerAccess containing an ErrorPropertySymbol will produce better flow analysis results than // a BoundBadExpression containing the candidate indexers. PropertySymbol property = (candidates.Length == 1) ? candidates[0] : CreateErrorPropertySymbol(candidates); propertyAccess = BoundIndexerAccess.ErrorAccess( syntax, receiverOpt, property, arguments, argumentNames, argumentRefKinds, candidates); } else { MemberResolutionResult<PropertySymbol> resolutionResult = overloadResolutionResult.ValidResult; PropertySymbol property = resolutionResult.Member; RefKind? receiverRefKind = receiverOpt?.GetRefKind(); uint receiverEscapeScope = property.RequiresInstanceReceiver && receiverOpt != null ? receiverRefKind?.IsWritableReference() == true ? GetRefEscape(receiverOpt, LocalScopeDepth) : GetValEscape(receiverOpt, LocalScopeDepth) : Binder.ExternalScope; this.CoerceArguments<PropertySymbol>(resolutionResult, analyzedArguments.Arguments, diagnostics, receiverOpt?.Type, receiverRefKind, receiverEscapeScope); var isExpanded = resolutionResult.Result.Kind == MemberResolutionKind.ApplicableInExpandedForm; var argsToParams = resolutionResult.Result.ArgsToParamsOpt; ReportDiagnosticsIfObsolete(diagnostics, property, syntax, hasBaseReceiver: receiverOpt != null && receiverOpt.Kind == BoundKind.BaseReference); // Make sure that the result of overload resolution is valid. var gotError = MemberGroupFinalValidationAccessibilityChecks(receiverOpt, property, syntax, diagnostics, invokedAsExtensionMethod: false); var receiver = ReplaceTypeOrValueReceiver(receiverOpt, property.IsStatic, diagnostics); if (!gotError && receiver != null && receiver.Kind == BoundKind.ThisReference && receiver.WasCompilerGenerated) { gotError = IsRefOrOutThisParameterCaptured(syntax, diagnostics); } var arguments = analyzedArguments.Arguments.ToImmutable(); if (!gotError) { gotError = !CheckInvocationArgMixing( syntax, property, receiver, property.Parameters, arguments, argsToParams, this.LocalScopeDepth, diagnostics); } // Note that we do not bind default arguments here, because at this point we do not know whether // the indexer is being used in a 'get', or 'set', or 'get+set' (compound assignment) context. propertyAccess = new BoundIndexerAccess( syntax, receiver, property, arguments, argumentNames, argumentRefKinds, isExpanded, argsToParams, defaultArguments: default, property.Type, gotError); } overloadResolutionResult.Free(); return propertyAccess; } private bool TryBindIndexOrRangeIndexer( SyntaxNode syntax, BoundExpression receiverOpt, AnalyzedArguments arguments, BindingDiagnosticBag diagnostics, out BoundIndexOrRangePatternIndexerAccess patternIndexerAccess) { patternIndexerAccess = null; // Verify a few things up-front, namely that we have a single argument // to this indexer that has an Index or Range type and that there is // a real receiver with a known type if (arguments.Arguments.Count != 1) { return false; } var argument = arguments.Arguments[0]; var argType = argument.Type; bool argIsIndex = TypeSymbol.Equals(argType, Compilation.GetWellKnownType(WellKnownType.System_Index), TypeCompareKind.ConsiderEverything); bool argIsRange = !argIsIndex && TypeSymbol.Equals(argType, Compilation.GetWellKnownType(WellKnownType.System_Range), TypeCompareKind.ConsiderEverything); if ((!argIsIndex && !argIsRange) || !(receiverOpt?.Type is TypeSymbol receiverType)) { return false; } // SPEC: // An indexer invocation with a single argument of System.Index or System.Range will // succeed if the receiver type conforms to an appropriate pattern, namely // 1. The receiver type's original definition has an accessible property getter that returns // an int and has the name Length or Count // 2. For Index: Has an accessible indexer with a single int parameter // For Range: Has an accessible Slice method that takes two int parameters PropertySymbol lengthOrCountProperty; var lookupResult = LookupResult.GetInstance(); var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; // Look for Length first if (!tryLookupLengthOrCount(WellKnownMemberNames.LengthPropertyName, out lengthOrCountProperty) && !tryLookupLengthOrCount(WellKnownMemberNames.CountPropertyName, out lengthOrCountProperty)) { return false; } Debug.Assert(lengthOrCountProperty is { }); if (argIsIndex) { // Look for `T this[int i]` indexer LookupMembersInType( lookupResult, receiverType, WellKnownMemberNames.Indexer, arity: 0, basesBeingResolved: null, LookupOptions.Default, originalBinder: this, diagnose: false, ref discardedUseSiteInfo); if (lookupResult.IsMultiViable) { foreach (var candidate in lookupResult.Symbols) { if (!candidate.IsStatic && candidate is PropertySymbol property && IsAccessible(property, ref discardedUseSiteInfo) && property.OriginalDefinition is { ParameterCount: 1 } original && isIntNotByRef(original.Parameters[0])) { CheckImplicitThisCopyInReadOnlyMember(receiverOpt, lengthOrCountProperty.GetMethod, diagnostics); ReportDiagnosticsIfObsolete(diagnostics, property, syntax, hasBaseReceiver: false); ReportDiagnosticsIfObsolete(diagnostics, lengthOrCountProperty, syntax, hasBaseReceiver: false); // note: implicit copy check on the indexer accessor happens in CheckPropertyValueKind patternIndexerAccess = new BoundIndexOrRangePatternIndexerAccess( syntax, receiverOpt, lengthOrCountProperty, property, BindToNaturalType(argument, diagnostics), property.Type); break; } } } } else if (receiverType.SpecialType == SpecialType.System_String) { Debug.Assert(argIsRange); // Look for Substring var substring = (MethodSymbol)Compilation.GetSpecialTypeMember(SpecialMember.System_String__Substring); if (substring is object) { patternIndexerAccess = new BoundIndexOrRangePatternIndexerAccess( syntax, receiverOpt, lengthOrCountProperty, substring, BindToNaturalType(argument, diagnostics), substring.ReturnType); checkWellKnown(WellKnownMember.System_Range__get_Start); checkWellKnown(WellKnownMember.System_Range__get_End); } } else { Debug.Assert(argIsRange); // Look for `T Slice(int, int)` indexer LookupMembersInType( lookupResult, receiverType, WellKnownMemberNames.SliceMethodName, arity: 0, basesBeingResolved: null, LookupOptions.Default, originalBinder: this, diagnose: false, ref discardedUseSiteInfo); if (lookupResult.IsMultiViable) { foreach (var candidate in lookupResult.Symbols) { if (!candidate.IsStatic && IsAccessible(candidate, ref discardedUseSiteInfo) && candidate is MethodSymbol method && method.OriginalDefinition is var original && original.ParameterCount == 2 && isIntNotByRef(original.Parameters[0]) && isIntNotByRef(original.Parameters[1])) { CheckImplicitThisCopyInReadOnlyMember(receiverOpt, lengthOrCountProperty.GetMethod, diagnostics); CheckImplicitThisCopyInReadOnlyMember(receiverOpt, method, diagnostics); ReportDiagnosticsIfObsolete(diagnostics, method, syntax, hasBaseReceiver: false); ReportDiagnosticsIfObsolete(diagnostics, lengthOrCountProperty, syntax, hasBaseReceiver: false); patternIndexerAccess = new BoundIndexOrRangePatternIndexerAccess( syntax, receiverOpt, lengthOrCountProperty, method, BindToNaturalType(argument, diagnostics), method.ReturnType); checkWellKnown(WellKnownMember.System_Range__get_Start); checkWellKnown(WellKnownMember.System_Range__get_End); break; } } } } cleanup(lookupResult); if (patternIndexerAccess is null) { return false; } _ = MessageID.IDS_FeatureIndexOperator.CheckFeatureAvailability(diagnostics, syntax); checkWellKnown(WellKnownMember.System_Index__GetOffset); if (arguments.Names.Count > 0) { diagnostics.Add( argIsRange ? ErrorCode.ERR_ImplicitRangeIndexerWithName : ErrorCode.ERR_ImplicitIndexIndexerWithName, arguments.Names[0].GetValueOrDefault().Location); } return true; static void cleanup(LookupResult lookupResult) { lookupResult.Free(); } static bool isIntNotByRef(ParameterSymbol param) => param.Type.SpecialType == SpecialType.System_Int32 && param.RefKind == RefKind.None; void checkWellKnown(WellKnownMember member) { // Check required well-known member. They may not be needed // during lowering, but it's simpler to always require them to prevent // the user from getting surprising errors when optimizations fail _ = GetWellKnownTypeMember(member, diagnostics, syntax: syntax); } bool tryLookupLengthOrCount(string propertyName, out PropertySymbol valid) { LookupMembersInType( lookupResult, receiverType, propertyName, arity: 0, basesBeingResolved: null, LookupOptions.Default, originalBinder: this, diagnose: false, useSiteInfo: ref discardedUseSiteInfo); if (lookupResult.IsSingleViable && lookupResult.Symbols[0] is PropertySymbol property && property.GetOwnOrInheritedGetMethod()?.OriginalDefinition is MethodSymbol getMethod && getMethod.ReturnType.SpecialType == SpecialType.System_Int32 && getMethod.RefKind == RefKind.None && !getMethod.IsStatic && IsAccessible(getMethod, ref discardedUseSiteInfo)) { lookupResult.Clear(); valid = property; return true; } lookupResult.Clear(); valid = null; return false; } } private ErrorPropertySymbol CreateErrorPropertySymbol(ImmutableArray<PropertySymbol> propertyGroup) { TypeSymbol propertyType = GetCommonTypeOrReturnType(propertyGroup) ?? CreateErrorType(); var candidate = propertyGroup[0]; return new ErrorPropertySymbol(candidate.ContainingType, propertyType, candidate.Name, candidate.IsIndexer, candidate.IsIndexedProperty); } /// <summary> /// Perform lookup and overload resolution on methods defined directly on the class and any /// extension methods in scope. Lookup will occur for extension methods in all nested scopes /// as necessary until an appropriate method is found. If analyzedArguments is null, the first /// method group is returned, without overload resolution being performed. That method group /// will either be the methods defined on the receiver class directly (no extension methods) /// or the first set of extension methods. /// </summary> /// <param name="node">The node associated with the method group</param> /// <param name="analyzedArguments">The arguments of the invocation (or the delegate type, if a method group conversion)</param> /// <param name="isMethodGroupConversion">True if it is a method group conversion</param> /// <param name="useSiteInfo"></param> /// <param name="inferWithDynamic"></param> /// <param name="returnRefKind">If a method group conversion, the desired ref kind of the delegate</param> /// <param name="returnType">If a method group conversion, the desired return type of the delegate. /// May be null during inference if the return type of the delegate needs to be computed.</param> internal MethodGroupResolution ResolveMethodGroup( BoundMethodGroup node, AnalyzedArguments analyzedArguments, bool isMethodGroupConversion, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, bool inferWithDynamic = false, RefKind returnRefKind = default, TypeSymbol returnType = null, bool isFunctionPointerResolution = false, in CallingConventionInfo callingConventionInfo = default) { return ResolveMethodGroup( node, node.Syntax, node.Name, analyzedArguments, isMethodGroupConversion, ref useSiteInfo, inferWithDynamic: inferWithDynamic, returnRefKind: returnRefKind, returnType: returnType, isFunctionPointerResolution: isFunctionPointerResolution, callingConventionInfo: callingConventionInfo); } internal MethodGroupResolution ResolveMethodGroup( BoundMethodGroup node, SyntaxNode expression, string methodName, AnalyzedArguments analyzedArguments, bool isMethodGroupConversion, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, bool inferWithDynamic = false, bool allowUnexpandedForm = true, RefKind returnRefKind = default, TypeSymbol returnType = null, bool isFunctionPointerResolution = false, in CallingConventionInfo callingConventionInfo = default) { var methodResolution = ResolveMethodGroupInternal( node, expression, methodName, analyzedArguments, isMethodGroupConversion, ref useSiteInfo, inferWithDynamic: inferWithDynamic, allowUnexpandedForm: allowUnexpandedForm, returnRefKind: returnRefKind, returnType: returnType, isFunctionPointerResolution: isFunctionPointerResolution, callingConvention: callingConventionInfo); if (methodResolution.IsEmpty && !methodResolution.HasAnyErrors) { Debug.Assert(node.LookupError == null); var diagnostics = BindingDiagnosticBag.GetInstance(withDiagnostics: true, useSiteInfo.AccumulatesDependencies); diagnostics.AddRange(methodResolution.Diagnostics); // Could still have use site warnings. BindMemberAccessReportError(node, diagnostics); // Note: no need to free `methodResolution`, we're transferring the pooled objects it owned return new MethodGroupResolution(methodResolution.MethodGroup, methodResolution.OtherSymbol, methodResolution.OverloadResolutionResult, methodResolution.AnalyzedArguments, methodResolution.ResultKind, diagnostics.ToReadOnlyAndFree()); } return methodResolution; } internal MethodGroupResolution ResolveMethodGroupForFunctionPointer( BoundMethodGroup methodGroup, AnalyzedArguments analyzedArguments, TypeSymbol returnType, RefKind returnRefKind, in CallingConventionInfo callingConventionInfo, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { return ResolveDefaultMethodGroup( methodGroup, analyzedArguments, isMethodGroupConversion: true, ref useSiteInfo, inferWithDynamic: false, allowUnexpandedForm: true, returnRefKind, returnType, isFunctionPointerResolution: true, callingConventionInfo); } private MethodGroupResolution ResolveMethodGroupInternal( BoundMethodGroup methodGroup, SyntaxNode expression, string methodName, AnalyzedArguments analyzedArguments, bool isMethodGroupConversion, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, bool inferWithDynamic = false, bool allowUnexpandedForm = true, RefKind returnRefKind = default, TypeSymbol returnType = null, bool isFunctionPointerResolution = false, in CallingConventionInfo callingConvention = default) { var methodResolution = ResolveDefaultMethodGroup( methodGroup, analyzedArguments, isMethodGroupConversion, ref useSiteInfo, inferWithDynamic, allowUnexpandedForm, returnRefKind, returnType, isFunctionPointerResolution, callingConvention); // If the method group's receiver is dynamic then there is no point in looking for extension methods; // it's going to be a dynamic invocation. if (!methodGroup.SearchExtensionMethods || methodResolution.HasAnyApplicableMethod || methodGroup.MethodGroupReceiverIsDynamic()) { return methodResolution; } var extensionMethodResolution = BindExtensionMethod( expression, methodName, analyzedArguments, methodGroup.ReceiverOpt, methodGroup.TypeArgumentsOpt, isMethodGroupConversion, returnRefKind: returnRefKind, returnType: returnType, withDependencies: useSiteInfo.AccumulatesDependencies); bool preferExtensionMethodResolution = false; if (extensionMethodResolution.HasAnyApplicableMethod) { preferExtensionMethodResolution = true; } else if (extensionMethodResolution.IsEmpty) { preferExtensionMethodResolution = false; } else if (methodResolution.IsEmpty) { preferExtensionMethodResolution = true; } else { // At this point, both method group resolutions are non-empty but neither contains any applicable method. // Choose the MethodGroupResolution with the better (i.e. less worse) result kind. Debug.Assert(!methodResolution.HasAnyApplicableMethod); Debug.Assert(!extensionMethodResolution.HasAnyApplicableMethod); Debug.Assert(!methodResolution.IsEmpty); Debug.Assert(!extensionMethodResolution.IsEmpty); LookupResultKind methodResultKind = methodResolution.ResultKind; LookupResultKind extensionMethodResultKind = extensionMethodResolution.ResultKind; if (methodResultKind != extensionMethodResultKind && methodResultKind == extensionMethodResultKind.WorseResultKind(methodResultKind)) { preferExtensionMethodResolution = true; } } if (preferExtensionMethodResolution) { methodResolution.Free(); Debug.Assert(!extensionMethodResolution.IsEmpty); return extensionMethodResolution; //NOTE: the first argument of this MethodGroupResolution could be a BoundTypeOrValueExpression } extensionMethodResolution.Free(); return methodResolution; } private MethodGroupResolution ResolveDefaultMethodGroup( BoundMethodGroup node, AnalyzedArguments analyzedArguments, bool isMethodGroupConversion, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, bool inferWithDynamic = false, bool allowUnexpandedForm = true, RefKind returnRefKind = default, TypeSymbol returnType = null, bool isFunctionPointerResolution = false, in CallingConventionInfo callingConvention = default) { var methods = node.Methods; if (methods.Length == 0) { var method = node.LookupSymbolOpt as MethodSymbol; if ((object)method != null) { methods = ImmutableArray.Create(method); } } var sealedDiagnostics = ImmutableBindingDiagnostic<AssemblySymbol>.Empty; if (node.LookupError != null) { var diagnostics = BindingDiagnosticBag.GetInstance(withDiagnostics: true, withDependencies: false); Error(diagnostics, node.LookupError, node.NameSyntax); sealedDiagnostics = diagnostics.ToReadOnlyAndFree(); } if (methods.Length == 0) { return new MethodGroupResolution(node.LookupSymbolOpt, node.ResultKind, sealedDiagnostics); } var methodGroup = MethodGroup.GetInstance(); // NOTE: node.ReceiverOpt could be a BoundTypeOrValueExpression - users need to check. methodGroup.PopulateWithNonExtensionMethods(node.ReceiverOpt, methods, node.TypeArgumentsOpt, node.ResultKind, node.LookupError); if (node.LookupError != null) { return new MethodGroupResolution(methodGroup, sealedDiagnostics); } // Arguments will be null if the caller is resolving to the first available // method group, regardless of arguments, when the signature cannot // be inferred. (In the error case of o.M = null; for instance.) if (analyzedArguments == null) { return new MethodGroupResolution(methodGroup, sealedDiagnostics); } else { var result = OverloadResolutionResult<MethodSymbol>.GetInstance(); bool allowRefOmittedArguments = methodGroup.Receiver.IsExpressionOfComImportType(); OverloadResolution.MethodInvocationOverloadResolution( methodGroup.Methods, methodGroup.TypeArguments, methodGroup.Receiver, analyzedArguments, result, ref useSiteInfo, isMethodGroupConversion, allowRefOmittedArguments, inferWithDynamic, allowUnexpandedForm, returnRefKind, returnType, isFunctionPointerResolution, callingConvention); // Note: the MethodGroupResolution instance is responsible for freeing its copy of analyzed arguments return new MethodGroupResolution(methodGroup, null, result, AnalyzedArguments.GetInstance(analyzedArguments), methodGroup.ResultKind, sealedDiagnostics); } } #nullable enable internal NamedTypeSymbol? GetMethodGroupDelegateType(BoundMethodGroup node, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { if (GetUniqueSignatureFromMethodGroup(node) is { } method && GetMethodGroupOrLambdaDelegateType(method.RefKind, method.ReturnsVoid ? default : method.ReturnTypeWithAnnotations, method.ParameterRefKinds, method.ParameterTypesWithAnnotations, ref useSiteInfo) is { } delegateType) { return delegateType; } return null; } /// <summary> /// Returns one of the methods from the method group if all methods in the method group /// have the same signature, ignoring parameter names and custom modifiers. The particular /// method returned is not important since the caller is interested in the signature only. /// </summary> private MethodSymbol? GetUniqueSignatureFromMethodGroup(BoundMethodGroup node) { MethodSymbol? method = null; foreach (var m in node.Methods) { switch (node.ReceiverOpt) { case BoundTypeExpression: if (!m.IsStatic) continue; break; case BoundThisReference { WasCompilerGenerated: true }: break; default: if (m.IsStatic) continue; break; } if (!isCandidateUnique(ref method, m)) { return null; } } if (node.SearchExtensionMethods) { var receiver = node.ReceiverOpt!; foreach (var scope in new ExtensionMethodScopes(this)) { var methodGroup = MethodGroup.GetInstance(); PopulateExtensionMethodsFromSingleBinder(scope, methodGroup, node.Syntax, receiver, node.Name, node.TypeArgumentsOpt, BindingDiagnosticBag.Discarded); foreach (var m in methodGroup.Methods) { if (m.ReduceExtensionMethod(receiver.Type, Compilation) is { } reduced && !isCandidateUnique(ref method, reduced)) { methodGroup.Free(); return null; } } methodGroup.Free(); } } if (method is null) { return null; } int n = node.TypeArgumentsOpt.IsDefaultOrEmpty ? 0 : node.TypeArgumentsOpt.Length; if (method.Arity != n) { return null; } else if (n > 0) { method = method.ConstructedFrom.Construct(node.TypeArgumentsOpt); } return method; static bool isCandidateUnique(ref MethodSymbol? method, MethodSymbol candidate) { if (method is null) { method = candidate; return true; } if (MemberSignatureComparer.MethodGroupSignatureComparer.Equals(method, candidate)) { return true; } method = null; return false; } } // This method was adapted from LoweredDynamicOperationFactory.GetDelegateType(). // Consider using that method directly since it also synthesizes delegates if necessary. internal NamedTypeSymbol? GetMethodGroupOrLambdaDelegateType( RefKind returnRefKind, TypeWithAnnotations returnTypeOpt, ImmutableArray<RefKind> parameterRefKinds, ImmutableArray<TypeWithAnnotations> parameterTypes, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(returnTypeOpt.Type?.IsVoidType() != true); // expecting !returnTypeOpt.HasType rather than System.Void if (returnRefKind == RefKind.None && (parameterRefKinds.IsDefault || parameterRefKinds.All(refKind => refKind == RefKind.None))) { var wkDelegateType = returnTypeOpt.HasType ? WellKnownTypes.GetWellKnownFunctionDelegate(invokeArgumentCount: parameterTypes.Length) : WellKnownTypes.GetWellKnownActionDelegate(invokeArgumentCount: parameterTypes.Length); if (wkDelegateType != WellKnownType.Unknown) { var delegateType = Compilation.GetWellKnownType(wkDelegateType); delegateType.AddUseSiteInfo(ref useSiteInfo); if (returnTypeOpt.HasType) { parameterTypes = parameterTypes.Add(returnTypeOpt); } if (parameterTypes.Length == 0) { return delegateType; } if (checkConstraints(Compilation, Conversions, delegateType, parameterTypes)) { return delegateType.Construct(parameterTypes); } } } return null; static bool checkConstraints(CSharpCompilation compilation, ConversionsBase conversions, NamedTypeSymbol delegateType, ImmutableArray<TypeWithAnnotations> typeArguments) { var diagnosticsBuilder = ArrayBuilder<TypeParameterDiagnosticInfo>.GetInstance(); var typeParameters = delegateType.TypeParameters; var substitution = new TypeMap(typeParameters, typeArguments); ArrayBuilder<TypeParameterDiagnosticInfo>? useSiteDiagnosticsBuilder = null; var result = delegateType.CheckConstraints( new ConstraintsHelper.CheckConstraintsArgs(compilation, conversions, includeNullability: false, NoLocation.Singleton, diagnostics: null, template: CompoundUseSiteInfo<AssemblySymbol>.Discarded), substitution, typeParameters, typeArguments, diagnosticsBuilder, nullabilityDiagnosticsBuilderOpt: null, ref useSiteDiagnosticsBuilder); diagnosticsBuilder.Free(); return result; } } #nullable disable internal static bool ReportDelegateInvokeUseSiteDiagnostic(BindingDiagnosticBag diagnostics, TypeSymbol possibleDelegateType, Location location = null, SyntaxNode node = null) { Debug.Assert((location == null) ^ (node == null)); if (!possibleDelegateType.IsDelegateType()) { return false; } MethodSymbol invoke = possibleDelegateType.DelegateInvokeMethod(); if ((object)invoke == null) { diagnostics.Add(new CSDiagnosticInfo(ErrorCode.ERR_InvalidDelegateType, possibleDelegateType), location ?? node.Location); return true; } UseSiteInfo<AssemblySymbol> info = invoke.GetUseSiteInfo(); diagnostics.AddDependencies(info); DiagnosticInfo diagnosticInfo = info.DiagnosticInfo; if (diagnosticInfo == null) { return false; } if (location == null) { location = node.Location; } if (diagnosticInfo.Code == (int)ErrorCode.ERR_InvalidDelegateType) { diagnostics.Add(new CSDiagnostic(new CSDiagnosticInfo(ErrorCode.ERR_InvalidDelegateType, possibleDelegateType), location)); return true; } return Symbol.ReportUseSiteDiagnostic(diagnosticInfo, diagnostics, location); } private BoundConditionalAccess BindConditionalAccessExpression(ConditionalAccessExpressionSyntax node, BindingDiagnosticBag diagnostics) { BoundExpression receiver = BindConditionalAccessReceiver(node, diagnostics); var conditionalAccessBinder = new BinderWithConditionalReceiver(this, receiver); var access = conditionalAccessBinder.BindValue(node.WhenNotNull, diagnostics, BindValueKind.RValue); if (receiver.HasAnyErrors || access.HasAnyErrors) { return new BoundConditionalAccess(node, receiver, access, CreateErrorType(), hasErrors: true); } var receiverType = receiver.Type; Debug.Assert((object)receiverType != null); // access cannot be a method group if (access.Kind == BoundKind.MethodGroup) { return GenerateBadConditionalAccessNodeError(node, receiver, access, diagnostics); } var accessType = access.Type; // access cannot have no type if ((object)accessType == null) { return GenerateBadConditionalAccessNodeError(node, receiver, access, diagnostics); } // The resulting type must be either a reference type T or Nullable<T> // Therefore we must reject cases resulting in types that are not reference types and cannot be lifted into nullable. // - access cannot have unconstrained generic type // - access cannot be a pointer // - access cannot be a restricted type if ((!accessType.IsReferenceType && !accessType.IsValueType) || accessType.IsPointerOrFunctionPointer() || accessType.IsRestrictedType()) { // Result type of the access is void when result value cannot be made nullable. // For improved diagnostics we detect the cases where the value will be used and produce a // more specific (though not technically correct) diagnostic here: // "Error CS0023: Operator '?' cannot be applied to operand of type 'T'" bool resultIsUsed = true; CSharpSyntaxNode parent = node.Parent; if (parent != null) { switch (parent.Kind()) { case SyntaxKind.ExpressionStatement: resultIsUsed = ((ExpressionStatementSyntax)parent).Expression != node; break; case SyntaxKind.SimpleLambdaExpression: resultIsUsed = (((SimpleLambdaExpressionSyntax)parent).Body != node) || MethodOrLambdaRequiresValue(ContainingMemberOrLambda, Compilation); break; case SyntaxKind.ParenthesizedLambdaExpression: resultIsUsed = (((ParenthesizedLambdaExpressionSyntax)parent).Body != node) || MethodOrLambdaRequiresValue(ContainingMemberOrLambda, Compilation); break; case SyntaxKind.ArrowExpressionClause: resultIsUsed = (((ArrowExpressionClauseSyntax)parent).Expression != node) || MethodOrLambdaRequiresValue(ContainingMemberOrLambda, Compilation); break; case SyntaxKind.ForStatement: // Incrementors and Initializers doesn't have to produce a value var loop = (ForStatementSyntax)parent; resultIsUsed = !loop.Incrementors.Contains(node) && !loop.Initializers.Contains(node); break; } } if (resultIsUsed) { return GenerateBadConditionalAccessNodeError(node, receiver, access, diagnostics); } accessType = GetSpecialType(SpecialType.System_Void, diagnostics, node); } // if access has value type, the type of the conditional access is nullable of that // https://github.com/dotnet/roslyn/issues/35075: The test `accessType.IsValueType && !accessType.IsNullableType()` // should probably be `accessType.IsNonNullableValueType()` if (accessType.IsValueType && !accessType.IsNullableType() && !accessType.IsVoidType()) { accessType = GetSpecialType(SpecialType.System_Nullable_T, diagnostics, node).Construct(accessType); } return new BoundConditionalAccess(node, receiver, access, accessType); } internal static bool MethodOrLambdaRequiresValue(Symbol symbol, CSharpCompilation compilation) { return symbol is MethodSymbol method && !method.ReturnsVoid && !method.IsAsyncEffectivelyReturningTask(compilation); } private BoundConditionalAccess GenerateBadConditionalAccessNodeError(ConditionalAccessExpressionSyntax node, BoundExpression receiver, BoundExpression access, BindingDiagnosticBag diagnostics) { var operatorToken = node.OperatorToken; // TODO: need a special ERR for this. // conditional access is not really a binary operator. DiagnosticInfo diagnosticInfo = new CSDiagnosticInfo(ErrorCode.ERR_BadUnaryOp, SyntaxFacts.GetText(operatorToken.Kind()), access.Display); diagnostics.Add(new CSDiagnostic(diagnosticInfo, operatorToken.GetLocation())); receiver = BadExpression(receiver.Syntax, receiver); return new BoundConditionalAccess(node, receiver, access, CreateErrorType(), hasErrors: true); } private BoundExpression BindMemberBindingExpression(MemberBindingExpressionSyntax node, bool invoked, bool indexed, BindingDiagnosticBag diagnostics) { BoundExpression receiver = GetReceiverForConditionalBinding(node, diagnostics); var memberAccess = BindMemberAccessWithBoundLeft(node, receiver, node.Name, node.OperatorToken, invoked, indexed, diagnostics); return memberAccess; } private BoundExpression BindElementBindingExpression(ElementBindingExpressionSyntax node, BindingDiagnosticBag diagnostics) { BoundExpression receiver = GetReceiverForConditionalBinding(node, diagnostics); var memberAccess = BindElementAccess(node, receiver, node.ArgumentList, diagnostics); return memberAccess; } private static CSharpSyntaxNode GetConditionalReceiverSyntax(ConditionalAccessExpressionSyntax node) { Debug.Assert(node != null); Debug.Assert(node.Expression != null); var receiver = node.Expression; while (receiver.IsKind(SyntaxKind.ParenthesizedExpression)) { receiver = ((ParenthesizedExpressionSyntax)receiver).Expression; Debug.Assert(receiver != null); } return receiver; } private BoundExpression GetReceiverForConditionalBinding(ExpressionSyntax binding, BindingDiagnosticBag diagnostics) { var conditionalAccessNode = SyntaxFactory.FindConditionalAccessNodeForBinding(binding); Debug.Assert(conditionalAccessNode != null); BoundExpression receiver = this.ConditionalReceiverExpression; if (receiver?.Syntax != GetConditionalReceiverSyntax(conditionalAccessNode)) { // this can happen when semantic model binds parts of a Call or a broken access expression. // We may not have receiver available in such cases. // Not a problem - we only need receiver to get its type and we can bind it here. receiver = BindConditionalAccessReceiver(conditionalAccessNode, diagnostics); } // create surrogate receiver var receiverType = receiver.Type; if (receiverType?.IsNullableType() == true) { receiverType = receiverType.GetNullableUnderlyingType(); } receiver = new BoundConditionalReceiver(receiver.Syntax, 0, receiverType ?? CreateErrorType(), hasErrors: receiver.HasErrors) { WasCompilerGenerated = true }; return receiver; } private BoundExpression BindConditionalAccessReceiver(ConditionalAccessExpressionSyntax node, BindingDiagnosticBag diagnostics) { var receiverSyntax = node.Expression; var receiver = BindRValueWithoutTargetType(receiverSyntax, diagnostics); receiver = MakeMemberAccessValue(receiver, diagnostics); if (receiver.HasAnyErrors) { return receiver; } var operatorToken = node.OperatorToken; if (receiver.Kind == BoundKind.UnboundLambda) { var msgId = ((UnboundLambda)receiver).MessageID; DiagnosticInfo diagnosticInfo = new CSDiagnosticInfo(ErrorCode.ERR_BadUnaryOp, SyntaxFacts.GetText(operatorToken.Kind()), msgId.Localize()); diagnostics.Add(new CSDiagnostic(diagnosticInfo, node.Location)); return BadExpression(receiverSyntax, receiver); } var receiverType = receiver.Type; // Can't dot into the null literal or anything that has no type if ((object)receiverType == null) { Error(diagnostics, ErrorCode.ERR_BadUnaryOp, operatorToken.GetLocation(), operatorToken.Text, receiver.Display); return BadExpression(receiverSyntax, receiver); } // No member accesses on void if (receiverType.IsVoidType()) { Error(diagnostics, ErrorCode.ERR_BadUnaryOp, operatorToken.GetLocation(), operatorToken.Text, receiverType); return BadExpression(receiverSyntax, receiver); } if (receiverType.IsValueType && !receiverType.IsNullableType()) { // must be nullable or reference type Error(diagnostics, ErrorCode.ERR_BadUnaryOp, operatorToken.GetLocation(), operatorToken.Text, receiverType); return BadExpression(receiverSyntax, receiver); } return receiver; } } }
1
dotnet/roslyn
55,132
Support lambda expressions and method groups as `var` initializers
```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
cston
2021-07-27T03:12:21Z
2021-07-27T18:26:42Z
61a565cfcd777158cb6354351436aff997ad7bf6
5840335153dcca42570a853cdacd06d660fe9596
Support lambda expressions and method groups as `var` initializers. ```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
./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, refKind, errorSyntax); } // The location where the error is reported might not be the initializer. protected BoundExpression BindInferredVariableInitializer(BindingDiagnosticBag diagnostics, ExpressionSyntax initializer, BindValueKind valueKind, RefKind refKind, 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 expression = BindToNaturalType(BindValue(initializer, diagnostics, valueKind), 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, localSymbol.RefKind, 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); 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); 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(); } } } }
1
dotnet/roslyn
55,132
Support lambda expressions and method groups as `var` initializers
```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
cston
2021-07-27T03:12:21Z
2021-07-27T18:26:42Z
61a565cfcd777158cb6354351436aff997ad7bf6
5840335153dcca42570a853cdacd06d660fe9596
Support lambda expressions and method groups as `var` initializers. ```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
./src/Compilers/CSharp/Test/IOperation/IOperation/IOperationTests_IAnonymousFunctionExpression.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.FlowAnalysis; using Microsoft.CodeAnalysis.Operations; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class IOperationTests_IAnonymousFunctionExpression : SemanticModelTestBase { [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void IAnonymousFunctionExpression_BoundLambda_HasValidLambdaExpressionTree() { string source = @" using System; class Program { static void Main(string[] args) { /*<bind>*/Action x = () => F();/*</bind>*/ } static void F() { } } "; string expectedOperationTree = @" IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'Action x = () => F();') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'Action x = () => F()') Declarators: IVariableDeclaratorOperation (Symbol: System.Action x) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'x = () => F()') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= () => F()') IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action, IsImplicit) (Syntax: '() => F()') Target: IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null) (Syntax: '() => F()') IBlockOperation (2 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'F()') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: 'F()') Expression: IInvocationOperation (void Program.F()) (OperationKind.Invocation, Type: System.Void) (Syntax: 'F()') Instance Receiver: null Arguments(0) IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'F()') ReturnedValue: null Initializer: null "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<LocalDeclarationStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void IAnonymousFunctionExpression_BoundLambda_HasValidLambdaExpressionTree_JustBindingLambdaReturnsOnlyIAnonymousFunctionExpression() { string source = @" using System; class Program { static void Main(string[] args) { Action x = /*<bind>*/() => F()/*</bind>*/; } static void F() { } } "; string expectedOperationTree = @" IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null) (Syntax: '() => F()') IBlockOperation (2 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'F()') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: 'F()') Expression: IInvocationOperation (void Program.F()) (OperationKind.Invocation, Type: System.Void) (Syntax: 'F()') Instance Receiver: null Arguments(0) IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'F()') ReturnedValue: null "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<ParenthesizedLambdaExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void IAnonymousFunctionExpression_BoundLambda_HasValidLambdaExpressionTree_ExplicitCast() { string source = @" using System; class Program { static void Main(string[] args) { /*<bind>*/Action x = (Action)(() => F());/*</bind>*/ } static void F() { } } "; string expectedOperationTree = @" IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'Action x = ... () => F());') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'Action x = ... (() => F())') Declarators: IVariableDeclaratorOperation (Symbol: System.Action x) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'x = (Action)(() => F())') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= (Action)(() => F())') IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action) (Syntax: '(Action)(() => F())') Target: IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null) (Syntax: '() => F()') IBlockOperation (2 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'F()') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: 'F()') Expression: IInvocationOperation (void Program.F()) (OperationKind.Invocation, Type: System.Void) (Syntax: 'F()') Instance Receiver: null Arguments(0) IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'F()') ReturnedValue: null Initializer: null "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<LocalDeclarationStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void IAnonymousFunctionExpression_BoundLambda_HasValidLambdaExpressionTree2() { string source = @" using System; class Program { static void Main(string[] args) { Action x = /*<bind>*/() => F()/*</bind>*/; } static void F() { } } "; string expectedOperationTree = @" IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null) (Syntax: '() => F()') IBlockOperation (2 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'F()') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: 'F()') Expression: IInvocationOperation (void Program.F()) (OperationKind.Invocation, Type: System.Void) (Syntax: 'F()') Instance Receiver: null Arguments(0) IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'F()') ReturnedValue: null "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<ParenthesizedLambdaExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void IAnonymousFunctionExpression_UnboundLambdaAsVar_HasValidLambdaExpressionTree() { string source = @" using System; class Program { static void Main(string[] args) { /*<bind>*/var x = () => F();/*</bind>*/ } static void F() { } } "; string expectedOperationTree = @" IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsInvalid) (Syntax: 'var x = () => F();') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'var x = () => F()') Declarators: IVariableDeclaratorOperation (Symbol: var x) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'x = () => F()') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: '= () => F()') IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsInvalid) (Syntax: '() => F()') IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsInvalid, IsImplicit) (Syntax: 'F()') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid, IsImplicit) (Syntax: 'F()') Expression: IInvocationOperation (void Program.F()) (OperationKind.Invocation, Type: System.Void, IsInvalid) (Syntax: 'F()') Instance Receiver: null Arguments(0) Initializer: null "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0815: Cannot assign lambda expression to an implicitly-typed variable // /*<bind>*/var x = () => F();/*</bind>*/ Diagnostic(ErrorCode.ERR_ImplicitlyTypedVariableAssignedBadValue, "x = () => F()").WithArguments("lambda expression").WithLocation(8, 23), }; VerifyOperationTreeAndDiagnosticsForTest<LocalDeclarationStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void IAnonymousFunctionExpression_UnboundLambdaAsDelegate_HasValidLambdaExpressionTree() { string source = @" using System; class Program { static void Main(string[] args) { /*<bind>*/Action<int> x = () => F();/*</bind>*/ } static void F() { } } "; string expectedOperationTree = @" IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsInvalid) (Syntax: 'Action<int> ... () => F();') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'Action<int> ... = () => F()') Declarators: IVariableDeclaratorOperation (Symbol: System.Action<System.Int32> x) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'x = () => F()') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: '= () => F()') IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action<System.Int32>, IsInvalid, IsImplicit) (Syntax: '() => F()') Target: IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsInvalid) (Syntax: '() => F()') IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsInvalid, IsImplicit) (Syntax: 'F()') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid, IsImplicit) (Syntax: 'F()') Expression: IInvocationOperation (void Program.F()) (OperationKind.Invocation, Type: System.Void, IsInvalid) (Syntax: 'F()') Instance Receiver: null Arguments(0) Initializer: null "; var expectedDiagnostics = new DiagnosticDescription[] { // CS1593: Delegate 'Action<int>' does not take 0 arguments // Action<int> x /*<bind>*/= () => F()/*</bind>*/; Diagnostic(ErrorCode.ERR_BadDelArgCount, "() => F()").WithArguments("System.Action<int>", "0").WithLocation(8, 35) }; VerifyOperationTreeAndDiagnosticsForTest<LocalDeclarationStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void IAnonymousFunctionExpression_UnboundLambdaAsDelegate_HasValidLambdaExpressionTree_ExplicitValidCast() { string source = @" using System; class Program { static void Main(string[] args) { /*<bind>*/Action<int> x = (Action)(() => F());/*</bind>*/ } static void F() { } } "; string expectedOperationTree = @" IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsInvalid) (Syntax: 'Action<int> ... () => F());') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'Action<int> ... (() => F())') Declarators: IVariableDeclaratorOperation (Symbol: System.Action<System.Int32> x) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'x = (Action)(() => F())') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: '= (Action)(() => F())') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Action<System.Int32>, IsInvalid, IsImplicit) (Syntax: '(Action)(() => F())') Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action, IsInvalid) (Syntax: '(Action)(() => F())') Target: IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsInvalid) (Syntax: '() => F()') IBlockOperation (2 statements) (OperationKind.Block, Type: null, IsInvalid, IsImplicit) (Syntax: 'F()') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid, IsImplicit) (Syntax: 'F()') Expression: IInvocationOperation (void Program.F()) (OperationKind.Invocation, Type: System.Void, IsInvalid) (Syntax: 'F()') Instance Receiver: null Arguments(0) IReturnOperation (OperationKind.Return, Type: null, IsInvalid, IsImplicit) (Syntax: 'F()') ReturnedValue: null Initializer: null "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0029: Cannot implicitly convert type 'System.Action' to 'System.Action<int>' // /*<bind>*/Action<int> x = (Action)(() => F());/*</bind>*/ Diagnostic(ErrorCode.ERR_NoImplicitConv, "(Action)(() => F())").WithArguments("System.Action", "System.Action<int>").WithLocation(8, 35) }; VerifyOperationTreeAndDiagnosticsForTest<LocalDeclarationStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void IAnonymousFunctionExpression_UnboundLambdaAsDelegate_HasValidLambdaExpressionTree_ExplicitInvalidCast() { string source = @" using System; class Program { static void Main(string[] args) { /*<bind>*/Action<int> x = (Action<int>)(() => F());/*</bind>*/ } static void F() { } } "; string expectedOperationTree = @" IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsInvalid) (Syntax: 'Action<int> ... () => F());') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'Action<int> ... (() => F())') Declarators: IVariableDeclaratorOperation (Symbol: System.Action<System.Int32> x) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'x = (Action ... (() => F())') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: '= (Action<i ... (() => F())') IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action<System.Int32>, IsInvalid) (Syntax: '(Action<int>)(() => F())') Target: IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsInvalid) (Syntax: '() => F()') IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsInvalid, IsImplicit) (Syntax: 'F()') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid, IsImplicit) (Syntax: 'F()') Expression: IInvocationOperation (void Program.F()) (OperationKind.Invocation, Type: System.Void, IsInvalid) (Syntax: 'F()') Instance Receiver: null Arguments(0) Initializer: null "; var expectedDiagnostics = new DiagnosticDescription[] { // CS1593: Delegate 'Action<int>' does not take 0 arguments // /*<bind>*/Action<int> x = (Action<int>)(() => F());/*</bind>*/ Diagnostic(ErrorCode.ERR_BadDelArgCount, "() => F()").WithArguments("System.Action<int>", "0").WithLocation(8, 49) }; VerifyOperationTreeAndDiagnosticsForTest<LocalDeclarationStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void IAnonymousFunctionExpression_UnboundLambda_ReferenceEquality() { string source = @" using System; class Program { static void Main(string[] args) { /*<bind>*/var x = () => F();/*</bind>*/ } static void F() { } } "; var compilation = CreateCompilationWithMscorlib40AndSystemCore(source); var syntaxTree = compilation.SyntaxTrees[0]; var semanticModel = compilation.GetSemanticModel(syntaxTree); var variableDeclaration = syntaxTree.GetRoot().DescendantNodes().OfType<LocalDeclarationStatementSyntax>().Single(); var lambdaSyntax = (LambdaExpressionSyntax)variableDeclaration.Declaration.Variables.Single().Initializer.Value; var variableDeclarationGroupOperation = (IVariableDeclarationGroupOperation)semanticModel.GetOperation(variableDeclaration); var variableTreeLambdaOperation = (IAnonymousFunctionOperation)variableDeclarationGroupOperation.Declarations.Single().Declarators.Single().Initializer.Value; var lambdaOperation = (IAnonymousFunctionOperation)semanticModel.GetOperation(lambdaSyntax); // Assert that both ways of getting to the lambda (requesting the lambda directly, and requesting via the lambda syntax) // return the same bound node. Assert.Same(variableTreeLambdaOperation, lambdaOperation); var variableDeclarationGroupOperationSecondRequest = (IVariableDeclarationGroupOperation)semanticModel.GetOperation(variableDeclaration); var variableTreeLambdaOperationSecondRequest = (IAnonymousFunctionOperation)variableDeclarationGroupOperation.Declarations.Single().Declarators.Single().Initializer.Value; var lambdaOperationSecondRequest = (IAnonymousFunctionOperation)semanticModel.GetOperation(lambdaSyntax); // Assert that, when request the variable declaration or the lambda for a second time, there is no rebinding of the // underlying UnboundLambda, and we get the same IAnonymousFunctionExpression as before Assert.Same(variableTreeLambdaOperation, variableTreeLambdaOperationSecondRequest); Assert.Same(lambdaOperation, lambdaOperationSecondRequest); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void IAnonymousFunctionExpression_StaticLambda() { string source = @" using System; class Program { static void Main(string[] args) { /*<bind>*/Action x = static () => F();/*</bind>*/ } static void F() { } } "; string expectedOperationTree = @" IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsInvalid) (Syntax: 'Action x = ... () => F();') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'Action x = ... c () => F()') Declarators: IVariableDeclaratorOperation (Symbol: System.Action x) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'x = static () => F()') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: '= static () => F()') IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action, IsInvalid, IsImplicit) (Syntax: 'static () => F()') Target: IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsInvalid) (Syntax: 'static () => F()') IBlockOperation (2 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'F()') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: 'F()') Expression: IInvocationOperation (void Program.F()) (OperationKind.Invocation, Type: System.Void) (Syntax: 'F()') Instance Receiver: null Arguments(0) IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'F()') ReturnedValue: null Initializer: null "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(8,30): error CS8400: Feature 'static anonymous function' is not available in C# 8.0. Please use language version 9.0 or greater. // /*<bind>*/Action x = static () => F();/*</bind>*/ Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "static").WithArguments("static anonymous function", "9.0").WithLocation(8, 30) }; VerifyOperationTreeAndDiagnosticsForTest<LocalDeclarationStatementSyntax>( source, expectedOperationTree, expectedDiagnostics, parseOptions: TestOptions.Regular8 ); var compilation = CreateCompilationWithMscorlib40AndSystemCore(source); var syntaxTree = compilation.SyntaxTrees[0]; var semanticModel = compilation.GetSemanticModel(syntaxTree); var variableDeclaration = syntaxTree.GetRoot().DescendantNodes().OfType<LocalDeclarationStatementSyntax>().Single(); var lambdaSyntax = (LambdaExpressionSyntax)variableDeclaration.Declaration.Variables.Single().Initializer.Value; var lambdaOperation = (IAnonymousFunctionOperation)semanticModel.GetOperation(lambdaSyntax); Assert.True(lambdaOperation.Symbol.IsStatic); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void LambdaFlow_01() { string source = @" struct C { void M(System.Action<bool, bool> d) /*<bind>*/{ d = (bool result, bool input) => { result = input; }; d(false, true); }/*</bind>*/ } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Block[B1] - Block Predecessors: [B0] Statements (2) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'd = (bool r ... };') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Action<System.Boolean, System.Boolean>) (Syntax: 'd = (bool r ... }') Left: IParameterReferenceOperation: d (OperationKind.ParameterReference, Type: System.Action<System.Boolean, System.Boolean>) (Syntax: 'd') Right: IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action<System.Boolean, System.Boolean>, IsImplicit) (Syntax: '(bool resul ... }') Target: IFlowAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.FlowAnonymousFunction, Type: null) (Syntax: '(bool resul ... }') { Block[B0#A0] - Entry Statements (0) Next (Regular) Block[B1#A0] Block[B1#A0] - Block Predecessors: [B0#A0] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = input;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'result = input') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result') Right: IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'input') Next (Regular) Block[B2#A0] Block[B2#A0] - Exit Predecessors: [B1#A0] Statements (0) } IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'd(false, true);') Expression: IInvocationOperation (virtual void System.Action<System.Boolean, System.Boolean>.Invoke(System.Boolean arg1, System.Boolean arg2)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'd(false, true)') Instance Receiver: IParameterReferenceOperation: d (OperationKind.ParameterReference, Type: System.Action<System.Boolean, System.Boolean>) (Syntax: 'd') Arguments(2): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: arg1) (OperationKind.Argument, Type: null) (Syntax: 'false') ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: arg2) (OperationKind.Argument, Type: null) (Syntax: 'true') ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Next (Regular) Block[B2] Block[B2] - Exit Predecessors: [B1] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void LambdaFlow_02() { string source = @" struct C { void M(System.Action<bool, bool> d1, System.Action<bool, bool> d2) /*<bind>*/{ d1 = (bool result1, bool input1) => { result1 = input1; }; d2 = (bool result2, bool input2) => result2 = input2; }/*</bind>*/ } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Block[B1] - Block Predecessors: [B0] Statements (2) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'd1 = (bool ... };') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Action<System.Boolean, System.Boolean>) (Syntax: 'd1 = (bool ... }') Left: IParameterReferenceOperation: d1 (OperationKind.ParameterReference, Type: System.Action<System.Boolean, System.Boolean>) (Syntax: 'd1') Right: IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action<System.Boolean, System.Boolean>, IsImplicit) (Syntax: '(bool resul ... }') Target: IFlowAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.FlowAnonymousFunction, Type: null) (Syntax: '(bool resul ... }') { Block[B0#A0] - Entry Statements (0) Next (Regular) Block[B1#A0] Block[B1#A0] - Block Predecessors: [B0#A0] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result1 = input1;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'result1 = input1') Left: IParameterReferenceOperation: result1 (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result1') Right: IParameterReferenceOperation: input1 (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'input1') Next (Regular) Block[B2#A0] Block[B2#A0] - Exit Predecessors: [B1#A0] Statements (0) } IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'd2 = (bool ... 2 = input2;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Action<System.Boolean, System.Boolean>) (Syntax: 'd2 = (bool ... t2 = input2') Left: IParameterReferenceOperation: d2 (OperationKind.ParameterReference, Type: System.Action<System.Boolean, System.Boolean>) (Syntax: 'd2') Right: IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action<System.Boolean, System.Boolean>, IsImplicit) (Syntax: '(bool resul ... t2 = input2') Target: IFlowAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.FlowAnonymousFunction, Type: null) (Syntax: '(bool resul ... t2 = input2') { Block[B0#A1] - Entry Statements (0) Next (Regular) Block[B1#A1] Block[B1#A1] - Block Predecessors: [B0#A1] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: 'result2 = input2') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'result2 = input2') Left: IParameterReferenceOperation: result2 (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result2') Right: IParameterReferenceOperation: input2 (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'input2') Next (Regular) Block[B2#A1] Block[B2#A1] - Exit Predecessors: [B1#A1] Statements (0) } Next (Regular) Block[B2] Block[B2] - Exit Predecessors: [B1] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void LambdaFlow_03() { string source = @" struct C { void M(System.Action<int> d1, System.Action<bool> d2) /*<bind>*/{ int i = 0; d1 = (int input1) => { input1 = 1; i++; d2 = (bool input2) => { input2 = true; i++; }; }; }/*</bind>*/ } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [System.Int32 i] Block[B1] - Block Predecessors: [B0] Statements (2) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'i = 0') Left: ILocalReferenceOperation: i (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'i = 0') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'd1 = (int i ... };') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Action<System.Int32>) (Syntax: 'd1 = (int i ... }') Left: IParameterReferenceOperation: d1 (OperationKind.ParameterReference, Type: System.Action<System.Int32>) (Syntax: 'd1') Right: IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action<System.Int32>, IsImplicit) (Syntax: '(int input1 ... }') Target: IFlowAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.FlowAnonymousFunction, Type: null) (Syntax: '(int input1 ... }') { Block[B0#A0] - Entry Statements (0) Next (Regular) Block[B1#A0] Block[B1#A0] - Block Predecessors: [B0#A0] Statements (3) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'input1 = 1;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'input1 = 1') Left: IParameterReferenceOperation: input1 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'input1') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'i++;') Expression: IIncrementOrDecrementOperation (Postfix) (OperationKind.Increment, Type: System.Int32) (Syntax: 'i++') Target: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'd2 = (bool ... };') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Action<System.Boolean>) (Syntax: 'd2 = (bool ... }') Left: IParameterReferenceOperation: d2 (OperationKind.ParameterReference, Type: System.Action<System.Boolean>) (Syntax: 'd2') Right: IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action<System.Boolean>, IsImplicit) (Syntax: '(bool input ... }') Target: IFlowAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.FlowAnonymousFunction, Type: null) (Syntax: '(bool input ... }') { Block[B0#A0#A0] - Entry Statements (0) Next (Regular) Block[B1#A0#A0] Block[B1#A0#A0] - Block Predecessors: [B0#A0#A0] Statements (2) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'input2 = true;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'input2 = true') Left: IParameterReferenceOperation: input2 (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'input2') Right: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'i++;') Expression: IIncrementOrDecrementOperation (Postfix) (OperationKind.Increment, Type: System.Int32) (Syntax: 'i++') Target: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Next (Regular) Block[B2#A0#A0] Block[B2#A0#A0] - Exit Predecessors: [B1#A0#A0] Statements (0) } Next (Regular) Block[B2#A0] Block[B2#A0] - Exit Predecessors: [B1#A0] Statements (0) } Next (Regular) Block[B2] Leaving: {R1} } Block[B2] - Exit Predecessors: [B1] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void LambdaFlow_04() { string source = @" struct C { void M(System.Action d1, System.Action<bool, bool> d2) /*<bind>*/{ d1 = () => { d2 = (bool result1, bool input1) => { result1 = input1; }; }; void local(bool result2, bool input2) => result2 = input2; }/*</bind>*/ } "; var compilation = CreateCompilation(source); var tree = compilation.SyntaxTrees.Single(); var semanticModel = compilation.GetSemanticModel(tree); var graphM = ControlFlowGraph.Create((IMethodBodyOperation)semanticModel.GetOperation(tree.GetRoot().DescendantNodes().OfType<MethodDeclarationSyntax>().Single())); Assert.NotNull(graphM); Assert.Null(graphM.Parent); IFlowAnonymousFunctionOperation lambdaD1 = getLambda(graphM); Assert.Throws<ArgumentNullException>(() => graphM.GetLocalFunctionControlFlowGraph(null)); Assert.Throws<ArgumentOutOfRangeException>(() => graphM.GetLocalFunctionControlFlowGraph(lambdaD1.Symbol)); Assert.Throws<ArgumentNullException>(() => graphM.GetLocalFunctionControlFlowGraphInScope(null)); Assert.Throws<ArgumentOutOfRangeException>(() => graphM.GetLocalFunctionControlFlowGraphInScope(lambdaD1.Symbol)); var graphD1 = graphM.GetAnonymousFunctionControlFlowGraph(lambdaD1); Assert.NotNull(graphD1); Assert.Same(graphM, graphD1.Parent); var graphD1_FromExtension = graphM.GetAnonymousFunctionControlFlowGraphInScope(lambdaD1); Assert.Same(graphD1, graphD1_FromExtension); IFlowAnonymousFunctionOperation lambdaD2 = getLambda(graphD1); var graphD2 = graphD1.GetAnonymousFunctionControlFlowGraph(lambdaD2); Assert.NotNull(graphD2); Assert.Same(graphD1, graphD2.Parent); Assert.Throws<ArgumentNullException>(() => graphM.GetAnonymousFunctionControlFlowGraph(null)); Assert.Throws<ArgumentOutOfRangeException>(() => graphM.GetAnonymousFunctionControlFlowGraph(lambdaD2)); Assert.Throws<ArgumentNullException>(() => graphM.GetAnonymousFunctionControlFlowGraphInScope(null)); Assert.Throws<ArgumentOutOfRangeException>(() => graphM.GetAnonymousFunctionControlFlowGraphInScope(lambdaD2)); IFlowAnonymousFunctionOperation getLambda(ControlFlowGraph graph) { return graph.Blocks.SelectMany(b => b.Operations.SelectMany(o => o.DescendantsAndSelf())).OfType<IFlowAnonymousFunctionOperation>().Single(); } } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void LambdaFlow_05() { string source = @" struct C { void M(System.Action d1, System.Action d2) /*<bind>*/{ d1 = () => { }; d2 = () => { d1(); }; }/*</bind>*/ } "; var compilation = CreateCompilation(source); var tree = compilation.SyntaxTrees.Single(); var semanticModel = compilation.GetSemanticModel(tree); var graphM = ControlFlowGraph.Create((IMethodBodyOperation)semanticModel.GetOperation(tree.GetRoot().DescendantNodes().OfType<MethodDeclarationSyntax>().Single())); Assert.NotNull(graphM); Assert.Null(graphM.Parent); IFlowAnonymousFunctionOperation lambdaD1 = getLambda(graphM, index: 0); Assert.NotNull(lambdaD1); IFlowAnonymousFunctionOperation lambdaD2 = getLambda(graphM, index: 1); Assert.NotNull(lambdaD2); Assert.Throws<ArgumentNullException>(() => graphM.GetLocalFunctionControlFlowGraph(null)); Assert.Throws<ArgumentOutOfRangeException>(() => graphM.GetLocalFunctionControlFlowGraph(lambdaD1.Symbol)); Assert.Throws<ArgumentNullException>(() => graphM.GetLocalFunctionControlFlowGraphInScope(null)); Assert.Throws<ArgumentOutOfRangeException>(() => graphM.GetLocalFunctionControlFlowGraphInScope(lambdaD1.Symbol)); var graphD1 = graphM.GetAnonymousFunctionControlFlowGraph(lambdaD1); Assert.NotNull(graphD1); Assert.Same(graphM, graphD1.Parent); var graphD2 = graphM.GetAnonymousFunctionControlFlowGraph(lambdaD2); Assert.NotNull(graphD2); Assert.Same(graphM, graphD2.Parent); var graphD1_FromExtension = graphM.GetAnonymousFunctionControlFlowGraphInScope(lambdaD1); Assert.Same(graphD1, graphD1_FromExtension); Assert.Throws<ArgumentOutOfRangeException>(() => graphD2.GetAnonymousFunctionControlFlowGraph(lambdaD1)); graphD1_FromExtension = graphD2.GetAnonymousFunctionControlFlowGraphInScope(lambdaD1); Assert.Same(graphD1, graphD1_FromExtension); IFlowAnonymousFunctionOperation getLambda(ControlFlowGraph graph, int index) { return graph.Blocks.SelectMany(b => b.Operations.SelectMany(o => o.DescendantsAndSelf())).OfType<IFlowAnonymousFunctionOperation>().ElementAt(index); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.FlowAnalysis; using Microsoft.CodeAnalysis.Operations; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class IOperationTests_IAnonymousFunctionExpression : SemanticModelTestBase { [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void IAnonymousFunctionExpression_BoundLambda_HasValidLambdaExpressionTree() { string source = @" using System; class Program { static void Main(string[] args) { /*<bind>*/Action x = () => F();/*</bind>*/ } static void F() { } } "; string expectedOperationTree = @" IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'Action x = () => F();') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'Action x = () => F()') Declarators: IVariableDeclaratorOperation (Symbol: System.Action x) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'x = () => F()') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= () => F()') IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action, IsImplicit) (Syntax: '() => F()') Target: IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null) (Syntax: '() => F()') IBlockOperation (2 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'F()') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: 'F()') Expression: IInvocationOperation (void Program.F()) (OperationKind.Invocation, Type: System.Void) (Syntax: 'F()') Instance Receiver: null Arguments(0) IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'F()') ReturnedValue: null Initializer: null "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<LocalDeclarationStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void IAnonymousFunctionExpression_BoundLambda_HasValidLambdaExpressionTree_JustBindingLambdaReturnsOnlyIAnonymousFunctionExpression() { string source = @" using System; class Program { static void Main(string[] args) { Action x = /*<bind>*/() => F()/*</bind>*/; } static void F() { } } "; string expectedOperationTree = @" IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null) (Syntax: '() => F()') IBlockOperation (2 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'F()') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: 'F()') Expression: IInvocationOperation (void Program.F()) (OperationKind.Invocation, Type: System.Void) (Syntax: 'F()') Instance Receiver: null Arguments(0) IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'F()') ReturnedValue: null "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<ParenthesizedLambdaExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void IAnonymousFunctionExpression_BoundLambda_HasValidLambdaExpressionTree_ExplicitCast() { string source = @" using System; class Program { static void Main(string[] args) { /*<bind>*/Action x = (Action)(() => F());/*</bind>*/ } static void F() { } } "; string expectedOperationTree = @" IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'Action x = ... () => F());') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'Action x = ... (() => F())') Declarators: IVariableDeclaratorOperation (Symbol: System.Action x) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'x = (Action)(() => F())') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= (Action)(() => F())') IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action) (Syntax: '(Action)(() => F())') Target: IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null) (Syntax: '() => F()') IBlockOperation (2 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'F()') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: 'F()') Expression: IInvocationOperation (void Program.F()) (OperationKind.Invocation, Type: System.Void) (Syntax: 'F()') Instance Receiver: null Arguments(0) IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'F()') ReturnedValue: null Initializer: null "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<LocalDeclarationStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void IAnonymousFunctionExpression_BoundLambda_HasValidLambdaExpressionTree2() { string source = @" using System; class Program { static void Main(string[] args) { Action x = /*<bind>*/() => F()/*</bind>*/; } static void F() { } } "; string expectedOperationTree = @" IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null) (Syntax: '() => F()') IBlockOperation (2 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'F()') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: 'F()') Expression: IInvocationOperation (void Program.F()) (OperationKind.Invocation, Type: System.Void) (Syntax: 'F()') Instance Receiver: null Arguments(0) IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'F()') ReturnedValue: null "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<ParenthesizedLambdaExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void IAnonymousFunctionExpression_UnboundLambdaAsVar_HasValidLambdaExpressionTree() { string source = @" using System; class Program { static void Main(string[] args) { /*<bind>*/var x = () => F();/*</bind>*/ } static void F() { } } "; string expectedOperationTree = @" IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'var x = () => F();') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'var x = () => F()') Declarators: IVariableDeclaratorOperation (Symbol: System.Action x) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'x = () => F()') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= () => F()') IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action, IsImplicit) (Syntax: '() => F()') Target: IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null) (Syntax: '() => F()') IBlockOperation (2 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'F()') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: 'F()') Expression: IInvocationOperation (void Program.F()) (OperationKind.Invocation, Type: System.Void) (Syntax: 'F()') Instance Receiver: null Arguments(0) IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'F()') ReturnedValue: null Initializer: null "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<LocalDeclarationStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void IAnonymousFunctionExpression_UnboundLambdaAsDelegate_HasValidLambdaExpressionTree() { string source = @" using System; class Program { static void Main(string[] args) { /*<bind>*/Action<int> x = () => F();/*</bind>*/ } static void F() { } } "; string expectedOperationTree = @" IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsInvalid) (Syntax: 'Action<int> ... () => F();') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'Action<int> ... = () => F()') Declarators: IVariableDeclaratorOperation (Symbol: System.Action<System.Int32> x) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'x = () => F()') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: '= () => F()') IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action<System.Int32>, IsInvalid, IsImplicit) (Syntax: '() => F()') Target: IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsInvalid) (Syntax: '() => F()') IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsInvalid, IsImplicit) (Syntax: 'F()') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid, IsImplicit) (Syntax: 'F()') Expression: IInvocationOperation (void Program.F()) (OperationKind.Invocation, Type: System.Void, IsInvalid) (Syntax: 'F()') Instance Receiver: null Arguments(0) Initializer: null "; var expectedDiagnostics = new DiagnosticDescription[] { // CS1593: Delegate 'Action<int>' does not take 0 arguments // Action<int> x /*<bind>*/= () => F()/*</bind>*/; Diagnostic(ErrorCode.ERR_BadDelArgCount, "() => F()").WithArguments("System.Action<int>", "0").WithLocation(8, 35) }; VerifyOperationTreeAndDiagnosticsForTest<LocalDeclarationStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void IAnonymousFunctionExpression_UnboundLambdaAsDelegate_HasValidLambdaExpressionTree_ExplicitValidCast() { string source = @" using System; class Program { static void Main(string[] args) { /*<bind>*/Action<int> x = (Action)(() => F());/*</bind>*/ } static void F() { } } "; string expectedOperationTree = @" IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsInvalid) (Syntax: 'Action<int> ... () => F());') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'Action<int> ... (() => F())') Declarators: IVariableDeclaratorOperation (Symbol: System.Action<System.Int32> x) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'x = (Action)(() => F())') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: '= (Action)(() => F())') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Action<System.Int32>, IsInvalid, IsImplicit) (Syntax: '(Action)(() => F())') Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action, IsInvalid) (Syntax: '(Action)(() => F())') Target: IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsInvalid) (Syntax: '() => F()') IBlockOperation (2 statements) (OperationKind.Block, Type: null, IsInvalid, IsImplicit) (Syntax: 'F()') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid, IsImplicit) (Syntax: 'F()') Expression: IInvocationOperation (void Program.F()) (OperationKind.Invocation, Type: System.Void, IsInvalid) (Syntax: 'F()') Instance Receiver: null Arguments(0) IReturnOperation (OperationKind.Return, Type: null, IsInvalid, IsImplicit) (Syntax: 'F()') ReturnedValue: null Initializer: null "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0029: Cannot implicitly convert type 'System.Action' to 'System.Action<int>' // /*<bind>*/Action<int> x = (Action)(() => F());/*</bind>*/ Diagnostic(ErrorCode.ERR_NoImplicitConv, "(Action)(() => F())").WithArguments("System.Action", "System.Action<int>").WithLocation(8, 35) }; VerifyOperationTreeAndDiagnosticsForTest<LocalDeclarationStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void IAnonymousFunctionExpression_UnboundLambdaAsDelegate_HasValidLambdaExpressionTree_ExplicitInvalidCast() { string source = @" using System; class Program { static void Main(string[] args) { /*<bind>*/Action<int> x = (Action<int>)(() => F());/*</bind>*/ } static void F() { } } "; string expectedOperationTree = @" IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsInvalid) (Syntax: 'Action<int> ... () => F());') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'Action<int> ... (() => F())') Declarators: IVariableDeclaratorOperation (Symbol: System.Action<System.Int32> x) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'x = (Action ... (() => F())') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: '= (Action<i ... (() => F())') IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action<System.Int32>, IsInvalid) (Syntax: '(Action<int>)(() => F())') Target: IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsInvalid) (Syntax: '() => F()') IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsInvalid, IsImplicit) (Syntax: 'F()') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid, IsImplicit) (Syntax: 'F()') Expression: IInvocationOperation (void Program.F()) (OperationKind.Invocation, Type: System.Void, IsInvalid) (Syntax: 'F()') Instance Receiver: null Arguments(0) Initializer: null "; var expectedDiagnostics = new DiagnosticDescription[] { // CS1593: Delegate 'Action<int>' does not take 0 arguments // /*<bind>*/Action<int> x = (Action<int>)(() => F());/*</bind>*/ Diagnostic(ErrorCode.ERR_BadDelArgCount, "() => F()").WithArguments("System.Action<int>", "0").WithLocation(8, 49) }; VerifyOperationTreeAndDiagnosticsForTest<LocalDeclarationStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void IAnonymousFunctionExpression_UnboundLambda_ReferenceEquality() { string source = @" using System; class Program { static void Main(string[] args) { /*<bind>*/var x = () => F();/*</bind>*/ } static void F() { } } "; var compilation = CreateCompilationWithMscorlib40AndSystemCore(source); var syntaxTree = compilation.SyntaxTrees[0]; var semanticModel = compilation.GetSemanticModel(syntaxTree); var variableDeclaration = syntaxTree.GetRoot().DescendantNodes().OfType<LocalDeclarationStatementSyntax>().Single(); var lambdaSyntax = (LambdaExpressionSyntax)variableDeclaration.Declaration.Variables.Single().Initializer.Value; var variableDeclarationGroupOperation = (IVariableDeclarationGroupOperation)semanticModel.GetOperation(variableDeclaration); var variableTreeLambdaOperation = ((IDelegateCreationOperation)variableDeclarationGroupOperation.Declarations.Single().Declarators.Single().Initializer.Value).Target; var lambdaOperation = (IAnonymousFunctionOperation)semanticModel.GetOperation(lambdaSyntax); // Assert that both ways of getting to the lambda (requesting the lambda directly, and requesting via the lambda syntax) // return the same bound node. Assert.Same(variableTreeLambdaOperation, lambdaOperation); var variableDeclarationGroupOperationSecondRequest = (IVariableDeclarationGroupOperation)semanticModel.GetOperation(variableDeclaration); var variableTreeLambdaOperationSecondRequest = ((IDelegateCreationOperation)variableDeclarationGroupOperationSecondRequest.Declarations.Single().Declarators.Single().Initializer.Value).Target; var lambdaOperationSecondRequest = (IAnonymousFunctionOperation)semanticModel.GetOperation(lambdaSyntax); // Assert that, when request the variable declaration or the lambda for a second time, there is no rebinding of the // underlying UnboundLambda, and we get the same IAnonymousFunctionExpression as before Assert.Same(variableTreeLambdaOperation, variableTreeLambdaOperationSecondRequest); Assert.Same(lambdaOperation, lambdaOperationSecondRequest); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void IAnonymousFunctionExpression_StaticLambda() { string source = @" using System; class Program { static void Main(string[] args) { /*<bind>*/Action x = static () => F();/*</bind>*/ } static void F() { } } "; string expectedOperationTree = @" IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsInvalid) (Syntax: 'Action x = ... () => F();') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'Action x = ... c () => F()') Declarators: IVariableDeclaratorOperation (Symbol: System.Action x) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'x = static () => F()') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: '= static () => F()') IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action, IsInvalid, IsImplicit) (Syntax: 'static () => F()') Target: IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsInvalid) (Syntax: 'static () => F()') IBlockOperation (2 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'F()') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: 'F()') Expression: IInvocationOperation (void Program.F()) (OperationKind.Invocation, Type: System.Void) (Syntax: 'F()') Instance Receiver: null Arguments(0) IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'F()') ReturnedValue: null Initializer: null "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(8,30): error CS8400: Feature 'static anonymous function' is not available in C# 8.0. Please use language version 9.0 or greater. // /*<bind>*/Action x = static () => F();/*</bind>*/ Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "static").WithArguments("static anonymous function", "9.0").WithLocation(8, 30) }; VerifyOperationTreeAndDiagnosticsForTest<LocalDeclarationStatementSyntax>( source, expectedOperationTree, expectedDiagnostics, parseOptions: TestOptions.Regular8 ); var compilation = CreateCompilationWithMscorlib40AndSystemCore(source); var syntaxTree = compilation.SyntaxTrees[0]; var semanticModel = compilation.GetSemanticModel(syntaxTree); var variableDeclaration = syntaxTree.GetRoot().DescendantNodes().OfType<LocalDeclarationStatementSyntax>().Single(); var lambdaSyntax = (LambdaExpressionSyntax)variableDeclaration.Declaration.Variables.Single().Initializer.Value; var lambdaOperation = (IAnonymousFunctionOperation)semanticModel.GetOperation(lambdaSyntax); Assert.True(lambdaOperation.Symbol.IsStatic); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void LambdaFlow_01() { string source = @" struct C { void M(System.Action<bool, bool> d) /*<bind>*/{ d = (bool result, bool input) => { result = input; }; d(false, true); }/*</bind>*/ } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Block[B1] - Block Predecessors: [B0] Statements (2) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'd = (bool r ... };') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Action<System.Boolean, System.Boolean>) (Syntax: 'd = (bool r ... }') Left: IParameterReferenceOperation: d (OperationKind.ParameterReference, Type: System.Action<System.Boolean, System.Boolean>) (Syntax: 'd') Right: IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action<System.Boolean, System.Boolean>, IsImplicit) (Syntax: '(bool resul ... }') Target: IFlowAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.FlowAnonymousFunction, Type: null) (Syntax: '(bool resul ... }') { Block[B0#A0] - Entry Statements (0) Next (Regular) Block[B1#A0] Block[B1#A0] - Block Predecessors: [B0#A0] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = input;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'result = input') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result') Right: IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'input') Next (Regular) Block[B2#A0] Block[B2#A0] - Exit Predecessors: [B1#A0] Statements (0) } IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'd(false, true);') Expression: IInvocationOperation (virtual void System.Action<System.Boolean, System.Boolean>.Invoke(System.Boolean arg1, System.Boolean arg2)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'd(false, true)') Instance Receiver: IParameterReferenceOperation: d (OperationKind.ParameterReference, Type: System.Action<System.Boolean, System.Boolean>) (Syntax: 'd') Arguments(2): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: arg1) (OperationKind.Argument, Type: null) (Syntax: 'false') ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: arg2) (OperationKind.Argument, Type: null) (Syntax: 'true') ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Next (Regular) Block[B2] Block[B2] - Exit Predecessors: [B1] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void LambdaFlow_02() { string source = @" struct C { void M(System.Action<bool, bool> d1, System.Action<bool, bool> d2) /*<bind>*/{ d1 = (bool result1, bool input1) => { result1 = input1; }; d2 = (bool result2, bool input2) => result2 = input2; }/*</bind>*/ } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Block[B1] - Block Predecessors: [B0] Statements (2) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'd1 = (bool ... };') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Action<System.Boolean, System.Boolean>) (Syntax: 'd1 = (bool ... }') Left: IParameterReferenceOperation: d1 (OperationKind.ParameterReference, Type: System.Action<System.Boolean, System.Boolean>) (Syntax: 'd1') Right: IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action<System.Boolean, System.Boolean>, IsImplicit) (Syntax: '(bool resul ... }') Target: IFlowAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.FlowAnonymousFunction, Type: null) (Syntax: '(bool resul ... }') { Block[B0#A0] - Entry Statements (0) Next (Regular) Block[B1#A0] Block[B1#A0] - Block Predecessors: [B0#A0] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result1 = input1;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'result1 = input1') Left: IParameterReferenceOperation: result1 (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result1') Right: IParameterReferenceOperation: input1 (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'input1') Next (Regular) Block[B2#A0] Block[B2#A0] - Exit Predecessors: [B1#A0] Statements (0) } IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'd2 = (bool ... 2 = input2;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Action<System.Boolean, System.Boolean>) (Syntax: 'd2 = (bool ... t2 = input2') Left: IParameterReferenceOperation: d2 (OperationKind.ParameterReference, Type: System.Action<System.Boolean, System.Boolean>) (Syntax: 'd2') Right: IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action<System.Boolean, System.Boolean>, IsImplicit) (Syntax: '(bool resul ... t2 = input2') Target: IFlowAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.FlowAnonymousFunction, Type: null) (Syntax: '(bool resul ... t2 = input2') { Block[B0#A1] - Entry Statements (0) Next (Regular) Block[B1#A1] Block[B1#A1] - Block Predecessors: [B0#A1] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: 'result2 = input2') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'result2 = input2') Left: IParameterReferenceOperation: result2 (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result2') Right: IParameterReferenceOperation: input2 (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'input2') Next (Regular) Block[B2#A1] Block[B2#A1] - Exit Predecessors: [B1#A1] Statements (0) } Next (Regular) Block[B2] Block[B2] - Exit Predecessors: [B1] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void LambdaFlow_03() { string source = @" struct C { void M(System.Action<int> d1, System.Action<bool> d2) /*<bind>*/{ int i = 0; d1 = (int input1) => { input1 = 1; i++; d2 = (bool input2) => { input2 = true; i++; }; }; }/*</bind>*/ } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [System.Int32 i] Block[B1] - Block Predecessors: [B0] Statements (2) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'i = 0') Left: ILocalReferenceOperation: i (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'i = 0') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'd1 = (int i ... };') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Action<System.Int32>) (Syntax: 'd1 = (int i ... }') Left: IParameterReferenceOperation: d1 (OperationKind.ParameterReference, Type: System.Action<System.Int32>) (Syntax: 'd1') Right: IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action<System.Int32>, IsImplicit) (Syntax: '(int input1 ... }') Target: IFlowAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.FlowAnonymousFunction, Type: null) (Syntax: '(int input1 ... }') { Block[B0#A0] - Entry Statements (0) Next (Regular) Block[B1#A0] Block[B1#A0] - Block Predecessors: [B0#A0] Statements (3) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'input1 = 1;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'input1 = 1') Left: IParameterReferenceOperation: input1 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'input1') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'i++;') Expression: IIncrementOrDecrementOperation (Postfix) (OperationKind.Increment, Type: System.Int32) (Syntax: 'i++') Target: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'd2 = (bool ... };') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Action<System.Boolean>) (Syntax: 'd2 = (bool ... }') Left: IParameterReferenceOperation: d2 (OperationKind.ParameterReference, Type: System.Action<System.Boolean>) (Syntax: 'd2') Right: IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action<System.Boolean>, IsImplicit) (Syntax: '(bool input ... }') Target: IFlowAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.FlowAnonymousFunction, Type: null) (Syntax: '(bool input ... }') { Block[B0#A0#A0] - Entry Statements (0) Next (Regular) Block[B1#A0#A0] Block[B1#A0#A0] - Block Predecessors: [B0#A0#A0] Statements (2) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'input2 = true;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'input2 = true') Left: IParameterReferenceOperation: input2 (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'input2') Right: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'i++;') Expression: IIncrementOrDecrementOperation (Postfix) (OperationKind.Increment, Type: System.Int32) (Syntax: 'i++') Target: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Next (Regular) Block[B2#A0#A0] Block[B2#A0#A0] - Exit Predecessors: [B1#A0#A0] Statements (0) } Next (Regular) Block[B2#A0] Block[B2#A0] - Exit Predecessors: [B1#A0] Statements (0) } Next (Regular) Block[B2] Leaving: {R1} } Block[B2] - Exit Predecessors: [B1] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void LambdaFlow_04() { string source = @" struct C { void M(System.Action d1, System.Action<bool, bool> d2) /*<bind>*/{ d1 = () => { d2 = (bool result1, bool input1) => { result1 = input1; }; }; void local(bool result2, bool input2) => result2 = input2; }/*</bind>*/ } "; var compilation = CreateCompilation(source); var tree = compilation.SyntaxTrees.Single(); var semanticModel = compilation.GetSemanticModel(tree); var graphM = ControlFlowGraph.Create((IMethodBodyOperation)semanticModel.GetOperation(tree.GetRoot().DescendantNodes().OfType<MethodDeclarationSyntax>().Single())); Assert.NotNull(graphM); Assert.Null(graphM.Parent); IFlowAnonymousFunctionOperation lambdaD1 = getLambda(graphM); Assert.Throws<ArgumentNullException>(() => graphM.GetLocalFunctionControlFlowGraph(null)); Assert.Throws<ArgumentOutOfRangeException>(() => graphM.GetLocalFunctionControlFlowGraph(lambdaD1.Symbol)); Assert.Throws<ArgumentNullException>(() => graphM.GetLocalFunctionControlFlowGraphInScope(null)); Assert.Throws<ArgumentOutOfRangeException>(() => graphM.GetLocalFunctionControlFlowGraphInScope(lambdaD1.Symbol)); var graphD1 = graphM.GetAnonymousFunctionControlFlowGraph(lambdaD1); Assert.NotNull(graphD1); Assert.Same(graphM, graphD1.Parent); var graphD1_FromExtension = graphM.GetAnonymousFunctionControlFlowGraphInScope(lambdaD1); Assert.Same(graphD1, graphD1_FromExtension); IFlowAnonymousFunctionOperation lambdaD2 = getLambda(graphD1); var graphD2 = graphD1.GetAnonymousFunctionControlFlowGraph(lambdaD2); Assert.NotNull(graphD2); Assert.Same(graphD1, graphD2.Parent); Assert.Throws<ArgumentNullException>(() => graphM.GetAnonymousFunctionControlFlowGraph(null)); Assert.Throws<ArgumentOutOfRangeException>(() => graphM.GetAnonymousFunctionControlFlowGraph(lambdaD2)); Assert.Throws<ArgumentNullException>(() => graphM.GetAnonymousFunctionControlFlowGraphInScope(null)); Assert.Throws<ArgumentOutOfRangeException>(() => graphM.GetAnonymousFunctionControlFlowGraphInScope(lambdaD2)); IFlowAnonymousFunctionOperation getLambda(ControlFlowGraph graph) { return graph.Blocks.SelectMany(b => b.Operations.SelectMany(o => o.DescendantsAndSelf())).OfType<IFlowAnonymousFunctionOperation>().Single(); } } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void LambdaFlow_05() { string source = @" struct C { void M(System.Action d1, System.Action d2) /*<bind>*/{ d1 = () => { }; d2 = () => { d1(); }; }/*</bind>*/ } "; var compilation = CreateCompilation(source); var tree = compilation.SyntaxTrees.Single(); var semanticModel = compilation.GetSemanticModel(tree); var graphM = ControlFlowGraph.Create((IMethodBodyOperation)semanticModel.GetOperation(tree.GetRoot().DescendantNodes().OfType<MethodDeclarationSyntax>().Single())); Assert.NotNull(graphM); Assert.Null(graphM.Parent); IFlowAnonymousFunctionOperation lambdaD1 = getLambda(graphM, index: 0); Assert.NotNull(lambdaD1); IFlowAnonymousFunctionOperation lambdaD2 = getLambda(graphM, index: 1); Assert.NotNull(lambdaD2); Assert.Throws<ArgumentNullException>(() => graphM.GetLocalFunctionControlFlowGraph(null)); Assert.Throws<ArgumentOutOfRangeException>(() => graphM.GetLocalFunctionControlFlowGraph(lambdaD1.Symbol)); Assert.Throws<ArgumentNullException>(() => graphM.GetLocalFunctionControlFlowGraphInScope(null)); Assert.Throws<ArgumentOutOfRangeException>(() => graphM.GetLocalFunctionControlFlowGraphInScope(lambdaD1.Symbol)); var graphD1 = graphM.GetAnonymousFunctionControlFlowGraph(lambdaD1); Assert.NotNull(graphD1); Assert.Same(graphM, graphD1.Parent); var graphD2 = graphM.GetAnonymousFunctionControlFlowGraph(lambdaD2); Assert.NotNull(graphD2); Assert.Same(graphM, graphD2.Parent); var graphD1_FromExtension = graphM.GetAnonymousFunctionControlFlowGraphInScope(lambdaD1); Assert.Same(graphD1, graphD1_FromExtension); Assert.Throws<ArgumentOutOfRangeException>(() => graphD2.GetAnonymousFunctionControlFlowGraph(lambdaD1)); graphD1_FromExtension = graphD2.GetAnonymousFunctionControlFlowGraphInScope(lambdaD1); Assert.Same(graphD1, graphD1_FromExtension); IFlowAnonymousFunctionOperation getLambda(ControlFlowGraph graph, int index) { return graph.Blocks.SelectMany(b => b.Operations.SelectMany(o => o.DescendantsAndSelf())).OfType<IFlowAnonymousFunctionOperation>().ElementAt(index); } } } }
1
dotnet/roslyn
55,132
Support lambda expressions and method groups as `var` initializers
```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
cston
2021-07-27T03:12:21Z
2021-07-27T18:26:42Z
61a565cfcd777158cb6354351436aff997ad7bf6
5840335153dcca42570a853cdacd06d660fe9596
Support lambda expressions and method groups as `var` initializers. ```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
./src/Compilers/CSharp/Test/IOperation/IOperation/IOperationTests_InvalidExpression.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using System.Linq; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class IOperationTests_InvalidExpression : SemanticModelTestBase { [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17598, "https://github.com/dotnet/roslyn/issues/17598")] public void InvalidInvocationExpression_BadReceiver() { string source = @" using System; class Program { static void Main(string[] args) { /*<bind>*/Console.WriteLine2()/*</bind>*/; } } "; string expectedOperationTree = @" IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'Console.WriteLine2()') Children(1): IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'Console.WriteLine2') Children(1): IOperation: (OperationKind.None, Type: null) (Syntax: 'Console') "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0117: 'Console' does not contain a definition for 'WriteLine2' // /*<bind>*/Console.WriteLine2()/*</bind>*/; Diagnostic(ErrorCode.ERR_NoSuchMember, "WriteLine2").WithArguments("System.Console", "WriteLine2").WithLocation(8, 27) }; VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17598, "https://github.com/dotnet/roslyn/issues/17598")] public void InvalidInvocationExpression_OverloadResolutionFailureBadArgument() { string source = @" using System; class Program { static void Main(string[] args) { /*<bind>*/F(string.Empty)/*</bind>*/; } void F(int x) { } } "; string expectedOperationTree = @" IInvalidOperation (OperationKind.Invalid, Type: System.Void, IsInvalid) (Syntax: 'F(string.Empty)') Children(1): IFieldReferenceOperation: System.String System.String.Empty (Static) (OperationKind.FieldReference, Type: System.String, IsInvalid) (Syntax: 'string.Empty') Instance Receiver: null "; var expectedDiagnostics = new DiagnosticDescription[] { // CS1503: Argument 1: cannot convert from 'string' to 'int' // /*<bind>*/F(string.Empty)/*</bind>*/; Diagnostic(ErrorCode.ERR_BadArgType, "string.Empty").WithArguments("1", "string", "int").WithLocation(8, 21) }; VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17598, "https://github.com/dotnet/roslyn/issues/17598")] public void InvalidInvocationExpression_OverloadResolutionFailureExtraArgument() { string source = @" using System; class Program { static void Main(string[] args) { /*<bind>*/F(string.Empty)/*</bind>*/; } void F() { } } "; string expectedOperationTree = @" IInvalidOperation (OperationKind.Invalid, Type: System.Void, IsInvalid) (Syntax: 'F(string.Empty)') Children(1): IFieldReferenceOperation: System.String System.String.Empty (Static) (OperationKind.FieldReference, Type: System.String) (Syntax: 'string.Empty') Instance Receiver: null "; var expectedDiagnostics = new DiagnosticDescription[] { // CS1501: No overload for method 'F' takes 1 arguments // /*<bind>*/F(string.Empty)/*</bind>*/; Diagnostic(ErrorCode.ERR_BadArgCount, "F").WithArguments("F", "1").WithLocation(8, 19) }; VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17598, "https://github.com/dotnet/roslyn/issues/17598")] public void InvalidFieldReferenceExpression() { string source = @" using System; class Program { static void Main(string[] args) { var x = new Program(); var /*<bind>*/y = x.MissingField/*</bind>*/; } void F() { } } "; string expectedOperationTree = @" IVariableDeclaratorOperation (Symbol: ? y) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'y = x.MissingField') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: '= x.MissingField') IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'x.MissingField') Children(1): ILocalReferenceOperation: x (OperationKind.LocalReference, Type: Program) (Syntax: 'x') "; var expectedDiagnostics = new DiagnosticDescription[] { // CS1061: 'Program' does not contain a definition for 'MissingField' and no extension method 'MissingField' accepting a first argument of type 'Program' could be found (are you missing a using directive or an assembly reference?) // var y /*<bind>*/= x.MissingField/*</bind>*/; Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "MissingField").WithArguments("Program", "MissingField").WithLocation(9, 29) }; VerifyOperationTreeAndDiagnosticsForTest<VariableDeclaratorSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17598, "https://github.com/dotnet/roslyn/issues/17598")] public void InvalidConversionExpression_ImplicitCast() { string source = @" using System; class Program { int i1; static void Main(string[] args) { var x = new Program(); /*<bind>*/string y = x.i1;/*</bind>*/ } void F() { } } "; string expectedOperationTree = @" IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsInvalid) (Syntax: 'string y = x.i1;') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'string y = x.i1') Declarators: IVariableDeclaratorOperation (Symbol: System.String y) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'y = x.i1') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: '= x.i1') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.String, IsInvalid, IsImplicit) (Syntax: 'x.i1') Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IFieldReferenceOperation: System.Int32 Program.i1 (OperationKind.FieldReference, Type: System.Int32, IsInvalid) (Syntax: 'x.i1') Instance Receiver: ILocalReferenceOperation: x (OperationKind.LocalReference, Type: Program, IsInvalid) (Syntax: 'x') Initializer: null "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0029: Cannot implicitly convert type 'int' to 'string' // string y /*<bind>*/= x.i1/*</bind>*/; Diagnostic(ErrorCode.ERR_NoImplicitConv, "x.i1").WithArguments("int", "string").WithLocation(10, 30), // CS0649: Field 'Program.i1' is never assigned to, and will always have its default value 0 // int i1; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "i1").WithArguments("Program.i1", "0").WithLocation(6, 9) }; VerifyOperationTreeAndDiagnosticsForTest<LocalDeclarationStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17598, "https://github.com/dotnet/roslyn/issues/17598")] public void InvalidConversionExpression_ExplicitCast() { string source = @" using System; class Program { int i1; static void Main(string[] args) { var x = new Program(); /*<bind>*/Program y = (Program)x.i1;/*</bind>*/ } void F() { } } "; string expectedOperationTree = @" IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsInvalid) (Syntax: 'Program y = ... ogram)x.i1;') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'Program y = ... rogram)x.i1') Declarators: IVariableDeclaratorOperation (Symbol: Program y) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'y = (Program)x.i1') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: '= (Program)x.i1') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: Program, IsInvalid) (Syntax: '(Program)x.i1') Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IFieldReferenceOperation: System.Int32 Program.i1 (OperationKind.FieldReference, Type: System.Int32, IsInvalid) (Syntax: 'x.i1') Instance Receiver: ILocalReferenceOperation: x (OperationKind.LocalReference, Type: Program, IsInvalid) (Syntax: 'x') Initializer: null "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0030: Cannot convert type 'int' to 'Program' // Program y /*<bind>*/= (Program)x.i1/*</bind>*/; Diagnostic(ErrorCode.ERR_NoExplicitConv, "(Program)x.i1").WithArguments("int", "Program").WithLocation(10, 31), // CS0649: Field 'Program.i1' is never assigned to, and will always have its default value 0 // int i1; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "i1").WithArguments("Program.i1", "0").WithLocation(6, 9) }; VerifyOperationTreeAndDiagnosticsForTest<LocalDeclarationStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17598, "https://github.com/dotnet/roslyn/issues/17598")] public void InvalidUnaryExpression() { string source = @" using System; class Program { static void Main(string[] args) { var x = new Program(); Console.Write(/*<bind>*/++x/*</bind>*/); } void F() { } } "; string expectedOperationTree = @" IIncrementOrDecrementOperation (Prefix) (OperationKind.Increment, Type: ?, IsInvalid) (Syntax: '++x') Target: ILocalReferenceOperation: x (OperationKind.LocalReference, Type: Program, IsInvalid) (Syntax: 'x') "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0023: Operator '++' cannot be applied to operand of type 'Program' // Console.Write(/*<bind>*/++x/*</bind>*/); Diagnostic(ErrorCode.ERR_BadUnaryOp, "++x").WithArguments("++", "Program").WithLocation(9, 33) }; VerifyOperationTreeAndDiagnosticsForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17598, "https://github.com/dotnet/roslyn/issues/17598")] public void InvalidBinaryExpression() { string source = @" using System; class Program { static void Main(string[] args) { var x = new Program(); Console.Write(/*<bind>*/x + (y * args.Length)/*</bind>*/); } void F() { } } "; string expectedOperationTree = @" IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: ?, IsInvalid) (Syntax: 'x + (y * args.Length)') Left: ILocalReferenceOperation: x (OperationKind.LocalReference, Type: Program) (Syntax: 'x') Right: IBinaryOperation (BinaryOperatorKind.Multiply) (OperationKind.Binary, Type: ?, IsInvalid) (Syntax: 'y * args.Length') Left: IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'y') Children(0) Right: IPropertyReferenceOperation: System.Int32 System.Array.Length { get; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'args.Length') Instance Receiver: IParameterReferenceOperation: args (OperationKind.ParameterReference, Type: System.String[]) (Syntax: 'args') "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0103: The name 'y' does not exist in the current context // Console.Write(/*<bind>*/x + (y * args.Length)/*</bind>*/); Diagnostic(ErrorCode.ERR_NameNotInContext, "y").WithArguments("y").WithLocation(9, 38) }; VerifyOperationTreeAndDiagnosticsForTest<BinaryExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17598, "https://github.com/dotnet/roslyn/issues/17598")] public void InvalidLambdaBinding_UnboundLambda() { string source = @" using System; class Program { static void Main(string[] args) { var /*<bind>*/x = () => F()/*</bind>*/; } static void F() { } } "; string expectedOperationTree = @" IVariableDeclaratorOperation (Symbol: var x) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'x = () => F()') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: '= () => F()') IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsInvalid) (Syntax: '() => F()') IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsInvalid, IsImplicit) (Syntax: 'F()') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid, IsImplicit) (Syntax: 'F()') Expression: IInvocationOperation (void Program.F()) (OperationKind.Invocation, Type: System.Void, IsInvalid) (Syntax: 'F()') Instance Receiver: null Arguments(0) "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0815: Cannot assign lambda expression to an implicitly-typed variable // var /*<bind>*/x = () => F()/*</bind>*/; Diagnostic(ErrorCode.ERR_ImplicitlyTypedVariableAssignedBadValue, "x = () => F()").WithArguments("lambda expression").WithLocation(8, 23) }; VerifyOperationTreeAndDiagnosticsForTest<VariableDeclaratorSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17598, "https://github.com/dotnet/roslyn/issues/17598")] public void InvalidLambdaBinding_LambdaExpression() { string source = @" using System; class Program { static void Main(string[] args) { var x = /*<bind>*/() => F()/*</bind>*/; } static void F() { } } "; string expectedOperationTree = @" IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsInvalid) (Syntax: '() => F()') IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsInvalid, IsImplicit) (Syntax: 'F()') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid, IsImplicit) (Syntax: 'F()') Expression: IInvocationOperation (void Program.F()) (OperationKind.Invocation, Type: System.Void, IsInvalid) (Syntax: 'F()') Instance Receiver: null Arguments(0) "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0815: Cannot assign lambda expression to an implicitly-typed variable // var x = /*<bind>*/() => F()/*</bind>*/; Diagnostic(ErrorCode.ERR_ImplicitlyTypedVariableAssignedBadValue, "x = /*<bind>*/() => F()").WithArguments("lambda expression").WithLocation(8, 13) }; VerifyOperationTreeAndDiagnosticsForTest<ParenthesizedLambdaExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17598, "https://github.com/dotnet/roslyn/issues/17598")] public void InvalidFieldInitializer() { string source = @" class Program { int x /*<bind>*/= Program/*</bind>*/; static void Main(string[] args) { var x = new Program() { x = Program }; } } "; string expectedOperationTree = @" IFieldInitializerOperation (Field: System.Int32 Program.x) (OperationKind.FieldInitializer, Type: null, IsInvalid) (Syntax: '= Program') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'Program') Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IInvalidOperation (OperationKind.Invalid, Type: Program, IsInvalid, IsImplicit) (Syntax: 'Program') Children(1): IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'Program') "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0119: 'Program' is a type, which is not valid in the given context // int x /*<bind>*/= Program/*</bind>*/; Diagnostic(ErrorCode.ERR_BadSKunknown, "Program").WithArguments("Program", "type").WithLocation(4, 23), // CS0119: 'Program' is a type, which is not valid in the given context // var x = new Program() { x = Program }; Diagnostic(ErrorCode.ERR_BadSKunknown, "Program").WithArguments("Program", "type").WithLocation(7, 37) }; VerifyOperationTreeAndDiagnosticsForTest<EqualsValueClauseSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17598, "https://github.com/dotnet/roslyn/issues/17598")] public void InvalidArrayInitializer() { string source = @" class Program { static void Main(string[] args) { var x = new int[2, 2] /*<bind>*/{ { { 1, 1 } }, { 2, 2 } }/*</bind>*/; } } "; string expectedOperationTree = @" IArrayInitializerOperation (2 elements) (OperationKind.ArrayInitializer, Type: null, IsInvalid) (Syntax: '{ { { 1, 1 ... { 2, 2 } }') Element Values(2): IArrayInitializerOperation (1 elements) (OperationKind.ArrayInitializer, Type: null, IsInvalid) (Syntax: '{ { 1, 1 } }') Element Values(1): IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: '{ 1, 1 }') Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid, IsImplicit) (Syntax: '{ 1, 1 }') Children(1): IArrayInitializerOperation (2 elements) (OperationKind.ArrayInitializer, Type: null, IsInvalid) (Syntax: '{ 1, 1 }') Element Values(2): IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsInvalid, IsImplicit) (Syntax: '1') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid) (Syntax: '1') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsInvalid, IsImplicit) (Syntax: '1') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid) (Syntax: '1') IArrayInitializerOperation (2 elements) (OperationKind.ArrayInitializer, Type: null) (Syntax: '{ 2, 2 }') Element Values(2): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0623: Array initializers can only be used in a variable or field initializer. Try using a new expression instead. // var x = new int[2, 2] /*<bind>*/{ { { 1, 1 } }, { 2, 2 } }/*</bind>*/; Diagnostic(ErrorCode.ERR_ArrayInitInBadPlace, "{ 1, 1 }").WithLocation(6, 45), // CS0847: An array initializer of length '2' is expected // var x = new int[2, 2] /*<bind>*/{ { { 1, 1 } }, { 2, 2 } }/*</bind>*/; Diagnostic(ErrorCode.ERR_ArrayInitializerIncorrectLength, "{ { 1, 1 } }").WithArguments("2").WithLocation(6, 43) }; VerifyOperationTreeAndDiagnosticsForTest<InitializerExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17598, "https://github.com/dotnet/roslyn/issues/17598")] public void InvalidArrayCreation() { string source = @" class Program { static void Main(string[] args) { var x = /*<bind>*/new X[Program] { { 1 } }/*</bind>*/; } } "; string expectedOperationTree = @" IArrayCreationOperation (OperationKind.ArrayCreation, Type: X[], IsInvalid) (Syntax: 'new X[Program] { { 1 } }') Dimension Sizes(1): IInvalidOperation (OperationKind.Invalid, Type: Program, IsInvalid, IsImplicit) (Syntax: 'Program') Children(1): IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'Program') Initializer: IArrayInitializerOperation (1 elements) (OperationKind.ArrayInitializer, Type: null, IsInvalid) (Syntax: '{ { 1 } }') Element Values(1): IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: X, IsInvalid, IsImplicit) (Syntax: '{ 1 }') Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid, IsImplicit) (Syntax: '{ 1 }') Children(1): IArrayInitializerOperation (1 elements) (OperationKind.ArrayInitializer, Type: null, IsInvalid) (Syntax: '{ 1 }') Element Values(1): IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsInvalid, IsImplicit) (Syntax: '1') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid) (Syntax: '1') "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0246: The type or namespace name 'X' could not be found (are you missing a using directive or an assembly reference?) // var x = /*<bind>*/new X[Program] { { 1 } }/*</bind>*/; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "X").WithArguments("X").WithLocation(6, 31), // CS0119: 'Program' is a type, which is not valid in the given context // var x = /*<bind>*/new X[Program] { { 1 } }/*</bind>*/; Diagnostic(ErrorCode.ERR_BadSKunknown, "Program").WithArguments("Program", "type").WithLocation(6, 33), // CS0623: Array initializers can only be used in a variable or field initializer. Try using a new expression instead. // var x = /*<bind>*/new X[Program] { { 1 } }/*</bind>*/; Diagnostic(ErrorCode.ERR_ArrayInitInBadPlace, "{ 1 }").WithLocation(6, 44) }; VerifyOperationTreeAndDiagnosticsForTest<ArrayCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17598, "https://github.com/dotnet/roslyn/issues/17598")] public void InvalidParameterDefaultValueInitializer() { string source = @" using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; class Program { static int M() { return 0; } void F(int p /*<bind>*/= M()/*</bind>*/) { } } "; string expectedOperationTree = @" IParameterInitializerOperation (Parameter: [System.Int32 p = default(System.Int32)]) (OperationKind.ParameterInitializer, Type: null, IsInvalid) (Syntax: '= M()') IInvocationOperation (System.Int32 Program.M()) (OperationKind.Invocation, Type: System.Int32, IsInvalid) (Syntax: 'M()') Instance Receiver: null Arguments(0) "; var expectedDiagnostics = new DiagnosticDescription[] { // CS1736: Default parameter value for 'p' must be a compile-time constant // void F(int p /*<bind>*/= M()/*</bind>*/) Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "M()").WithArguments("p").WithLocation(10, 30) }; VerifyOperationTreeAndDiagnosticsForTest<EqualsValueClauseSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact] [CompilerTrait(CompilerFeature.IOperation)] [WorkItem(20050, "https://github.com/dotnet/roslyn/issues/20050")] public void BuildsArgumentsOperationsForDuplicateExplicitArguments_Repro() { string source = @" public class C { void M() { /*<bind>*/string.Format(format: """", format: """")/*</bind>*/; } }"; string expectedOperationTree = @" IInvalidOperation (OperationKind.Invalid, Type: System.String, IsInvalid) (Syntax: 'string.Form ... format: """")') Children(3): IOperation: (OperationKind.None, Type: null) (Syntax: 'string') ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: """") (Syntax: '""""') ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: """") (Syntax: '""""') "; VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics: new DiagnosticDescription[] { // file.cs(6,45): error CS1740: Named argument 'format' cannot be specified multiple times // /*<bind>*/string.Format(format: "", format: "")/*</bind>*/; Diagnostic(ErrorCode.ERR_DuplicateNamedArgument, "format").WithArguments("format").WithLocation(6, 45) }); } [Fact] [CompilerTrait(CompilerFeature.IOperation)] [WorkItem(20050, "https://github.com/dotnet/roslyn/issues/20050")] public void BuildsArgumentsOperationsForDuplicateExplicitArguments_CorrectArgumentsOrder_Methods() { string source = @" public class C { void N(int a, int b, int c = 4) { } void M() { /*<bind>*/N(a: 1, a: 2, b: 3)/*</bind>*/; } }"; string expectedOperationTree = @" IInvalidOperation (OperationKind.Invalid, Type: System.Void, IsInvalid) (Syntax: 'N(a: 1, a: 2, b: 3)') Children(3): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3') "; VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics: new DiagnosticDescription[] { // file.cs(10,27): error CS1740: Named argument 'a' cannot be specified multiple times // /*<bind>*/N(a: 1, a: 2)/*</bind>*/; Diagnostic(ErrorCode.ERR_DuplicateNamedArgument, "a").WithArguments("a").WithLocation(10, 27) }); } [Fact] [CompilerTrait(CompilerFeature.IOperation)] [WorkItem(20050, "https://github.com/dotnet/roslyn/issues/20050")] public void BuildsArgumentsOperationsForDuplicateExplicitArguments_CorrectArgumentsOrder_Delegates() { string source = @" public delegate void D(int a, int b, int c = 4); public class C { void N(D lambda) { /*<bind>*/lambda(a: 1, a: 2, b: 3)/*</bind>*/; } }"; string expectedOperationTree = @" IInvalidOperation (OperationKind.Invalid, Type: System.Void, IsInvalid) (Syntax: 'lambda(a: 1, a: 2, b: 3)') Children(4): IParameterReferenceOperation: lambda (OperationKind.ParameterReference, Type: D) (Syntax: 'lambda') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3') "; VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics: new DiagnosticDescription[] { // file.cs(7,32): error CS1740: Named argument 'a' cannot be specified multiple times // /*<bind>*/lambda(a: 1, a: 2, b: 3)/*</bind>*/; Diagnostic(ErrorCode.ERR_DuplicateNamedArgument, "a").WithArguments("a").WithLocation(7, 32) }); } [Fact] [CompilerTrait(CompilerFeature.IOperation)] [WorkItem(20050, "https://github.com/dotnet/roslyn/issues/20050")] public void BuildsArgumentsOperationsForDuplicateExplicitArguments_CorrectArgumentsOrder_Indexers_Getter() { string source = @" public class C { int this[int a, int b, int c = 4] { get => 0; } void M() { var result = /*<bind>*/this[a: 1, a: 2, b: 3]/*</bind>*/; } }"; string expectedOperationTree = @" IInvalidOperation (OperationKind.Invalid, Type: System.Int32, IsInvalid) (Syntax: 'this[a: 1, a: 2, b: 3]') Children(4): IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C) (Syntax: 'this') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3') "; VerifyOperationTreeAndDiagnosticsForTest<ElementAccessExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics: new DiagnosticDescription[] { // file.cs(11,43): error CS1740: Named argument 'a' cannot be specified multiple times // var result = /*<bind>*/this[a: 1, a: 2, b: 3]/*</bind>*/; Diagnostic(ErrorCode.ERR_DuplicateNamedArgument, "a").WithArguments("a").WithLocation(11, 43) }); } [Fact] [CompilerTrait(CompilerFeature.IOperation)] [WorkItem(20050, "https://github.com/dotnet/roslyn/issues/20050")] public void BuildsArgumentsOperationsForDuplicateExplicitArguments_CorrectArgumentsOrder_Indexers_Setter() { string source = @" public class C { int this[int a, int b, int c = 4] { set {} } void M() { /*<bind>*/this[a: 1, a: 2, b: 3]/*</bind>*/ = 0; } }"; string expectedOperationTree = @" IInvalidOperation (OperationKind.Invalid, Type: System.Int32, IsInvalid) (Syntax: 'this[a: 1, a: 2, b: 3]') Children(4): IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C) (Syntax: 'this') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3') "; VerifyOperationTreeAndDiagnosticsForTest<ElementAccessExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics: new DiagnosticDescription[] { // file.cs(11,30): error CS1740: Named argument 'a' cannot be specified multiple times // /*<bind>*/this[a: 1, a: 2, b: 3]/*</bind>*/ = 0; Diagnostic(ErrorCode.ERR_DuplicateNamedArgument, "a").WithArguments("a").WithLocation(11, 30) }); } [Fact] [CompilerTrait(CompilerFeature.IOperation)] [WorkItem(20050, "https://github.com/dotnet/roslyn/issues/20050")] public void BuildsArgumentsOperationsForDuplicateExplicitArguments_IncorrectArgumentsOrder_Methods() { string source = @" public class C { void N(int a, int b, int c = 4) { } void M() { /*<bind>*/N(b: 1, a: 2, a: 3)/*</bind>*/; } }"; string expectedOperationTree = @" IInvalidOperation (OperationKind.Invalid, Type: System.Void, IsInvalid) (Syntax: 'N(b: 1, a: 2, a: 3)') Children(3): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3') "; VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics: new DiagnosticDescription[] { // file.cs(10,33): error CS1740: Named argument 'a' cannot be specified multiple times // /*<bind>*/N(b: 1, a: 2, a: 3)/*</bind>*/; Diagnostic(ErrorCode.ERR_DuplicateNamedArgument, "a").WithArguments("a").WithLocation(10, 33) }); } [Fact] [CompilerTrait(CompilerFeature.IOperation)] [WorkItem(20050, "https://github.com/dotnet/roslyn/issues/20050")] public void BuildsArgumentsOperationsForDuplicateExplicitArguments_IncorrectArgumentsOrder_Delegates() { string source = @" public delegate void D(int a, int b, int c = 4); public class C { void N(D lambda) { /*<bind>*/lambda(b: 1, a: 2, a: 3)/*</bind>*/; } }"; string expectedOperationTree = @" IInvalidOperation (OperationKind.Invalid, Type: System.Void, IsInvalid) (Syntax: 'lambda(b: 1, a: 2, a: 3)') Children(4): IParameterReferenceOperation: lambda (OperationKind.ParameterReference, Type: D) (Syntax: 'lambda') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3') "; VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics: new DiagnosticDescription[] { // file.cs(7,38): error CS1740: Named argument 'a' cannot be specified multiple times // /*<bind>*/lambda(b: 1, a: 2, a: 3)/*</bind>*/; Diagnostic(ErrorCode.ERR_DuplicateNamedArgument, "a").WithArguments("a").WithLocation(7, 38) }); } [Fact] [CompilerTrait(CompilerFeature.IOperation)] [WorkItem(20050, "https://github.com/dotnet/roslyn/issues/20050")] public void BuildsArgumentsOperationsForDuplicateExplicitArguments_IncorrectArgumentsOrder_Indexers_Getter() { string source = @" public class C { int this[int a, int b, int c = 4] { get => 0; } void M() { var result = /*<bind>*/this[b: 1, a: 2, a: 3]/*</bind>*/; } }"; string expectedOperationTree = @" IInvalidOperation (OperationKind.Invalid, Type: System.Int32, IsInvalid) (Syntax: 'this[b: 1, a: 2, a: 3]') Children(4): IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C) (Syntax: 'this') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3') "; VerifyOperationTreeAndDiagnosticsForTest<ElementAccessExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics: new DiagnosticDescription[] { // file.cs(11,49): error CS1740: Named argument 'a' cannot be specified multiple times // var result = /*<bind>*/this[b: 1, a: 2, a: 3]/*</bind>*/; Diagnostic(ErrorCode.ERR_DuplicateNamedArgument, "a").WithArguments("a").WithLocation(11, 49) }); } [Fact] [CompilerTrait(CompilerFeature.IOperation)] [WorkItem(20050, "https://github.com/dotnet/roslyn/issues/20050")] public void BuildsArgumentsOperationsForDuplicateExplicitArguments_IncorrectArgumentsOrder_Indexers_Setter() { string source = @" public class C { int this[int a, int b, int c = 4] { set {} } void M() { /*<bind>*/this[b: 1, a: 2, a: 3]/*</bind>*/ = 0; } }"; string expectedOperationTree = @" IInvalidOperation (OperationKind.Invalid, Type: System.Int32, IsInvalid) (Syntax: 'this[b: 1, a: 2, a: 3]') Children(4): IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C) (Syntax: 'this') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3') "; VerifyOperationTreeAndDiagnosticsForTest<ElementAccessExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics: new DiagnosticDescription[] { // file.cs(11,36): error CS1740: Named argument 'a' cannot be specified multiple times // /*<bind>*/this[b: 1, a: 2, a: 3]/*</bind>*/ = 0; Diagnostic(ErrorCode.ERR_DuplicateNamedArgument, "a").WithArguments("a").WithLocation(11, 36) }); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void InvalidExpressionFlow_01() { string source = @" using System; class C { static void M1(int i, int x, int y) /*<bind>*/{ i = M(1, __arglist(x, y)); }/*</bind>*/ } "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0103: The name 'M' does not exist in the current context // i = M(1, __arglist(a ? w : x, b ? y : z)); Diagnostic(ErrorCode.ERR_NameNotInContext, "M").WithArguments("M").WithLocation(7, 13) }; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Block[B1] - Block Predecessors: [B0] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'i = M(1, __ ... ist(x, y));') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsInvalid) (Syntax: 'i = M(1, __ ... list(x, y))') Left: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i') Right: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'M(1, __arglist(x, y))') Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (NoConversion) Operand: IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'M(1, __arglist(x, y))') Children(3): IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'M') Children(0) ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') IOperation: (OperationKind.None, Type: null) (Syntax: '__arglist(x, y)') Children(2): IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x') IParameterReferenceOperation: y (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'y') Next (Regular) Block[B2] Block[B2] - Exit Predecessors: [B1] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void InvalidExpressionFlow_02() { string source = @" using System; class C { static void M1(int i, bool a,int x, int y, int z) /*<bind>*/{ i = M(1, __arglist(x, a ? y : z)); }/*</bind>*/ } "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0103: The name 'M' does not exist in the current context // i = M(1, __arglist(x, a ? y : z)); Diagnostic(ErrorCode.ERR_NameNotInContext, "M").WithArguments("M").WithLocation(7, 13) }; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [1] [2] [3] [4] Block[B1] - Block Predecessors: [B0] Statements (4) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i') Value: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'M') Value: IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'M') Children(0) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '1') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'x') Value: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x') Jump if False (Regular) to Block[B3] IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'a') Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'y') Value: IParameterReferenceOperation: y (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'y') Next (Regular) Block[B4] Block[B3] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'z') Value: IParameterReferenceOperation: z (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'z') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B2] [B3] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'i = M(1, __ ... ? y : z));') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsInvalid) (Syntax: 'i = M(1, __ ... a ? y : z))') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'i') Right: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'M(1, __argl ... a ? y : z))') Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (NoConversion) Operand: IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'M(1, __argl ... a ? y : z))') Children(3): IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: ?, IsInvalid, IsImplicit) (Syntax: 'M') IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: '1') IOperation: (OperationKind.None, Type: null) (Syntax: '__arglist(x, a ? y : z)') Children(2): IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'x') IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'a ? y : z') Next (Regular) Block[B5] Leaving: {R1} } Block[B5] - Exit Predecessors: [B4] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void InvalidExpressionFlow_03() { string source = @" using System; class C { static void M1(int i, bool a, int w, int x, int y) /*<bind>*/{ i = M(1, __arglist(a ? w : x, y)); }/*</bind>*/ } "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0103: The name 'M' does not exist in the current context // i = M(1, __arglist(a ? w : x, y)); Diagnostic(ErrorCode.ERR_NameNotInContext, "M").WithArguments("M").WithLocation(7, 13) }; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [1] [2] [3] Block[B1] - Block Predecessors: [B0] Statements (3) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i') Value: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'M') Value: IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'M') Children(0) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '1') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Jump if False (Regular) to Block[B3] IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'a') Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'w') Value: IParameterReferenceOperation: w (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'w') Next (Regular) Block[B4] Block[B3] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'x') Value: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B2] [B3] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'i = M(1, __ ... w : x, y));') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsInvalid) (Syntax: 'i = M(1, __ ... w : x, y))') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'i') Right: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'M(1, __argl ... w : x, y))') Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (NoConversion) Operand: IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'M(1, __argl ... w : x, y))') Children(3): IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: ?, IsInvalid, IsImplicit) (Syntax: 'M') IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: '1') IOperation: (OperationKind.None, Type: null) (Syntax: '__arglist(a ? w : x, y)') Children(2): IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'a ? w : x') IParameterReferenceOperation: y (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'y') Next (Regular) Block[B5] Leaving: {R1} } Block[B5] - Exit Predecessors: [B4] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void InvalidExpressionFlow_04() { string source = @" using System; class C { static void M1(int i, bool a, bool b, int w, int x, int y, int z) /*<bind>*/{ i = M(1, __arglist(a ? w : x, b ? y : z)); }/*</bind>*/ } "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0103: The name 'M' does not exist in the current context // i = M(1, __arglist(a ? w : x, b ? y : z)); Diagnostic(ErrorCode.ERR_NameNotInContext, "M").WithArguments("M").WithLocation(7, 13) }; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [1] [2] [3] [4] Block[B1] - Block Predecessors: [B0] Statements (3) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i') Value: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'M') Value: IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'M') Children(0) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '1') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Jump if False (Regular) to Block[B3] IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'a') Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'w') Value: IParameterReferenceOperation: w (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'w') Next (Regular) Block[B4] Block[B3] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'x') Value: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B2] [B3] Statements (0) Jump if False (Regular) to Block[B6] IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B4] Statements (1) IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'y') Value: IParameterReferenceOperation: y (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'y') Next (Regular) Block[B7] Block[B6] - Block Predecessors: [B4] Statements (1) IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'z') Value: IParameterReferenceOperation: z (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'z') Next (Regular) Block[B7] Block[B7] - Block Predecessors: [B5] [B6] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'i = M(1, __ ... ? y : z));') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsInvalid) (Syntax: 'i = M(1, __ ... b ? y : z))') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'i') Right: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'M(1, __argl ... b ? y : z))') Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (NoConversion) Operand: IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'M(1, __argl ... b ? y : z))') Children(3): IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: ?, IsInvalid, IsImplicit) (Syntax: 'M') IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: '1') IOperation: (OperationKind.None, Type: null) (Syntax: '__arglist(a ... b ? y : z)') Children(2): IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'a ? w : x') IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'b ? y : z') Next (Regular) Block[B8] Leaving: {R1} } Block[B8] - Exit Predecessors: [B7] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using System.Linq; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class IOperationTests_InvalidExpression : SemanticModelTestBase { [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17598, "https://github.com/dotnet/roslyn/issues/17598")] public void InvalidInvocationExpression_BadReceiver() { string source = @" using System; class Program { static void Main(string[] args) { /*<bind>*/Console.WriteLine2()/*</bind>*/; } } "; string expectedOperationTree = @" IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'Console.WriteLine2()') Children(1): IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'Console.WriteLine2') Children(1): IOperation: (OperationKind.None, Type: null) (Syntax: 'Console') "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0117: 'Console' does not contain a definition for 'WriteLine2' // /*<bind>*/Console.WriteLine2()/*</bind>*/; Diagnostic(ErrorCode.ERR_NoSuchMember, "WriteLine2").WithArguments("System.Console", "WriteLine2").WithLocation(8, 27) }; VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17598, "https://github.com/dotnet/roslyn/issues/17598")] public void InvalidInvocationExpression_OverloadResolutionFailureBadArgument() { string source = @" using System; class Program { static void Main(string[] args) { /*<bind>*/F(string.Empty)/*</bind>*/; } void F(int x) { } } "; string expectedOperationTree = @" IInvalidOperation (OperationKind.Invalid, Type: System.Void, IsInvalid) (Syntax: 'F(string.Empty)') Children(1): IFieldReferenceOperation: System.String System.String.Empty (Static) (OperationKind.FieldReference, Type: System.String, IsInvalid) (Syntax: 'string.Empty') Instance Receiver: null "; var expectedDiagnostics = new DiagnosticDescription[] { // CS1503: Argument 1: cannot convert from 'string' to 'int' // /*<bind>*/F(string.Empty)/*</bind>*/; Diagnostic(ErrorCode.ERR_BadArgType, "string.Empty").WithArguments("1", "string", "int").WithLocation(8, 21) }; VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17598, "https://github.com/dotnet/roslyn/issues/17598")] public void InvalidInvocationExpression_OverloadResolutionFailureExtraArgument() { string source = @" using System; class Program { static void Main(string[] args) { /*<bind>*/F(string.Empty)/*</bind>*/; } void F() { } } "; string expectedOperationTree = @" IInvalidOperation (OperationKind.Invalid, Type: System.Void, IsInvalid) (Syntax: 'F(string.Empty)') Children(1): IFieldReferenceOperation: System.String System.String.Empty (Static) (OperationKind.FieldReference, Type: System.String) (Syntax: 'string.Empty') Instance Receiver: null "; var expectedDiagnostics = new DiagnosticDescription[] { // CS1501: No overload for method 'F' takes 1 arguments // /*<bind>*/F(string.Empty)/*</bind>*/; Diagnostic(ErrorCode.ERR_BadArgCount, "F").WithArguments("F", "1").WithLocation(8, 19) }; VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17598, "https://github.com/dotnet/roslyn/issues/17598")] public void InvalidFieldReferenceExpression() { string source = @" using System; class Program { static void Main(string[] args) { var x = new Program(); var /*<bind>*/y = x.MissingField/*</bind>*/; } void F() { } } "; string expectedOperationTree = @" IVariableDeclaratorOperation (Symbol: ? y) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'y = x.MissingField') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: '= x.MissingField') IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'x.MissingField') Children(1): ILocalReferenceOperation: x (OperationKind.LocalReference, Type: Program) (Syntax: 'x') "; var expectedDiagnostics = new DiagnosticDescription[] { // CS1061: 'Program' does not contain a definition for 'MissingField' and no extension method 'MissingField' accepting a first argument of type 'Program' could be found (are you missing a using directive or an assembly reference?) // var y /*<bind>*/= x.MissingField/*</bind>*/; Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "MissingField").WithArguments("Program", "MissingField").WithLocation(9, 29) }; VerifyOperationTreeAndDiagnosticsForTest<VariableDeclaratorSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17598, "https://github.com/dotnet/roslyn/issues/17598")] public void InvalidConversionExpression_ImplicitCast() { string source = @" using System; class Program { int i1; static void Main(string[] args) { var x = new Program(); /*<bind>*/string y = x.i1;/*</bind>*/ } void F() { } } "; string expectedOperationTree = @" IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsInvalid) (Syntax: 'string y = x.i1;') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'string y = x.i1') Declarators: IVariableDeclaratorOperation (Symbol: System.String y) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'y = x.i1') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: '= x.i1') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.String, IsInvalid, IsImplicit) (Syntax: 'x.i1') Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IFieldReferenceOperation: System.Int32 Program.i1 (OperationKind.FieldReference, Type: System.Int32, IsInvalid) (Syntax: 'x.i1') Instance Receiver: ILocalReferenceOperation: x (OperationKind.LocalReference, Type: Program, IsInvalid) (Syntax: 'x') Initializer: null "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0029: Cannot implicitly convert type 'int' to 'string' // string y /*<bind>*/= x.i1/*</bind>*/; Diagnostic(ErrorCode.ERR_NoImplicitConv, "x.i1").WithArguments("int", "string").WithLocation(10, 30), // CS0649: Field 'Program.i1' is never assigned to, and will always have its default value 0 // int i1; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "i1").WithArguments("Program.i1", "0").WithLocation(6, 9) }; VerifyOperationTreeAndDiagnosticsForTest<LocalDeclarationStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17598, "https://github.com/dotnet/roslyn/issues/17598")] public void InvalidConversionExpression_ExplicitCast() { string source = @" using System; class Program { int i1; static void Main(string[] args) { var x = new Program(); /*<bind>*/Program y = (Program)x.i1;/*</bind>*/ } void F() { } } "; string expectedOperationTree = @" IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsInvalid) (Syntax: 'Program y = ... ogram)x.i1;') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'Program y = ... rogram)x.i1') Declarators: IVariableDeclaratorOperation (Symbol: Program y) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'y = (Program)x.i1') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: '= (Program)x.i1') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: Program, IsInvalid) (Syntax: '(Program)x.i1') Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IFieldReferenceOperation: System.Int32 Program.i1 (OperationKind.FieldReference, Type: System.Int32, IsInvalid) (Syntax: 'x.i1') Instance Receiver: ILocalReferenceOperation: x (OperationKind.LocalReference, Type: Program, IsInvalid) (Syntax: 'x') Initializer: null "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0030: Cannot convert type 'int' to 'Program' // Program y /*<bind>*/= (Program)x.i1/*</bind>*/; Diagnostic(ErrorCode.ERR_NoExplicitConv, "(Program)x.i1").WithArguments("int", "Program").WithLocation(10, 31), // CS0649: Field 'Program.i1' is never assigned to, and will always have its default value 0 // int i1; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "i1").WithArguments("Program.i1", "0").WithLocation(6, 9) }; VerifyOperationTreeAndDiagnosticsForTest<LocalDeclarationStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17598, "https://github.com/dotnet/roslyn/issues/17598")] public void InvalidUnaryExpression() { string source = @" using System; class Program { static void Main(string[] args) { var x = new Program(); Console.Write(/*<bind>*/++x/*</bind>*/); } void F() { } } "; string expectedOperationTree = @" IIncrementOrDecrementOperation (Prefix) (OperationKind.Increment, Type: ?, IsInvalid) (Syntax: '++x') Target: ILocalReferenceOperation: x (OperationKind.LocalReference, Type: Program, IsInvalid) (Syntax: 'x') "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0023: Operator '++' cannot be applied to operand of type 'Program' // Console.Write(/*<bind>*/++x/*</bind>*/); Diagnostic(ErrorCode.ERR_BadUnaryOp, "++x").WithArguments("++", "Program").WithLocation(9, 33) }; VerifyOperationTreeAndDiagnosticsForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17598, "https://github.com/dotnet/roslyn/issues/17598")] public void InvalidBinaryExpression() { string source = @" using System; class Program { static void Main(string[] args) { var x = new Program(); Console.Write(/*<bind>*/x + (y * args.Length)/*</bind>*/); } void F() { } } "; string expectedOperationTree = @" IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: ?, IsInvalid) (Syntax: 'x + (y * args.Length)') Left: ILocalReferenceOperation: x (OperationKind.LocalReference, Type: Program) (Syntax: 'x') Right: IBinaryOperation (BinaryOperatorKind.Multiply) (OperationKind.Binary, Type: ?, IsInvalid) (Syntax: 'y * args.Length') Left: IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'y') Children(0) Right: IPropertyReferenceOperation: System.Int32 System.Array.Length { get; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'args.Length') Instance Receiver: IParameterReferenceOperation: args (OperationKind.ParameterReference, Type: System.String[]) (Syntax: 'args') "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0103: The name 'y' does not exist in the current context // Console.Write(/*<bind>*/x + (y * args.Length)/*</bind>*/); Diagnostic(ErrorCode.ERR_NameNotInContext, "y").WithArguments("y").WithLocation(9, 38) }; VerifyOperationTreeAndDiagnosticsForTest<BinaryExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17598, "https://github.com/dotnet/roslyn/issues/17598")] public void InvalidLambdaBinding_UnboundLambda() { string source = @" using System; class Program { static void Main(string[] args) { var /*<bind>*/x = () => F()/*</bind>*/; } static void F() { } } "; string expectedOperationTree = @" IVariableDeclaratorOperation (Symbol: System.Action x) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'x = () => F()') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= () => F()') IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action, IsImplicit) (Syntax: '() => F()') Target: IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null) (Syntax: '() => F()') IBlockOperation (2 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'F()') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: 'F()') Expression: IInvocationOperation (void Program.F()) (OperationKind.Invocation, Type: System.Void) (Syntax: 'F()') Instance Receiver: null Arguments(0) IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'F()') ReturnedValue: null "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<VariableDeclaratorSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17598, "https://github.com/dotnet/roslyn/issues/17598")] public void InvalidLambdaBinding_LambdaExpression() { string source = @" using System; class Program { static void Main(string[] args) { var x = /*<bind>*/() => F()/*</bind>*/; } static void F() { } } "; string expectedOperationTree = @" IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null) (Syntax: '() => F()') IBlockOperation (2 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'F()') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: 'F()') Expression: IInvocationOperation (void Program.F()) (OperationKind.Invocation, Type: System.Void) (Syntax: 'F()') Instance Receiver: null Arguments(0) IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'F()') ReturnedValue: null "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<ParenthesizedLambdaExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17598, "https://github.com/dotnet/roslyn/issues/17598")] public void InvalidFieldInitializer() { string source = @" class Program { int x /*<bind>*/= Program/*</bind>*/; static void Main(string[] args) { var x = new Program() { x = Program }; } } "; string expectedOperationTree = @" IFieldInitializerOperation (Field: System.Int32 Program.x) (OperationKind.FieldInitializer, Type: null, IsInvalid) (Syntax: '= Program') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'Program') Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IInvalidOperation (OperationKind.Invalid, Type: Program, IsInvalid, IsImplicit) (Syntax: 'Program') Children(1): IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'Program') "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0119: 'Program' is a type, which is not valid in the given context // int x /*<bind>*/= Program/*</bind>*/; Diagnostic(ErrorCode.ERR_BadSKunknown, "Program").WithArguments("Program", "type").WithLocation(4, 23), // CS0119: 'Program' is a type, which is not valid in the given context // var x = new Program() { x = Program }; Diagnostic(ErrorCode.ERR_BadSKunknown, "Program").WithArguments("Program", "type").WithLocation(7, 37) }; VerifyOperationTreeAndDiagnosticsForTest<EqualsValueClauseSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17598, "https://github.com/dotnet/roslyn/issues/17598")] public void InvalidArrayInitializer() { string source = @" class Program { static void Main(string[] args) { var x = new int[2, 2] /*<bind>*/{ { { 1, 1 } }, { 2, 2 } }/*</bind>*/; } } "; string expectedOperationTree = @" IArrayInitializerOperation (2 elements) (OperationKind.ArrayInitializer, Type: null, IsInvalid) (Syntax: '{ { { 1, 1 ... { 2, 2 } }') Element Values(2): IArrayInitializerOperation (1 elements) (OperationKind.ArrayInitializer, Type: null, IsInvalid) (Syntax: '{ { 1, 1 } }') Element Values(1): IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: '{ 1, 1 }') Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid, IsImplicit) (Syntax: '{ 1, 1 }') Children(1): IArrayInitializerOperation (2 elements) (OperationKind.ArrayInitializer, Type: null, IsInvalid) (Syntax: '{ 1, 1 }') Element Values(2): IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsInvalid, IsImplicit) (Syntax: '1') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid) (Syntax: '1') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsInvalid, IsImplicit) (Syntax: '1') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid) (Syntax: '1') IArrayInitializerOperation (2 elements) (OperationKind.ArrayInitializer, Type: null) (Syntax: '{ 2, 2 }') Element Values(2): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0623: Array initializers can only be used in a variable or field initializer. Try using a new expression instead. // var x = new int[2, 2] /*<bind>*/{ { { 1, 1 } }, { 2, 2 } }/*</bind>*/; Diagnostic(ErrorCode.ERR_ArrayInitInBadPlace, "{ 1, 1 }").WithLocation(6, 45), // CS0847: An array initializer of length '2' is expected // var x = new int[2, 2] /*<bind>*/{ { { 1, 1 } }, { 2, 2 } }/*</bind>*/; Diagnostic(ErrorCode.ERR_ArrayInitializerIncorrectLength, "{ { 1, 1 } }").WithArguments("2").WithLocation(6, 43) }; VerifyOperationTreeAndDiagnosticsForTest<InitializerExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17598, "https://github.com/dotnet/roslyn/issues/17598")] public void InvalidArrayCreation() { string source = @" class Program { static void Main(string[] args) { var x = /*<bind>*/new X[Program] { { 1 } }/*</bind>*/; } } "; string expectedOperationTree = @" IArrayCreationOperation (OperationKind.ArrayCreation, Type: X[], IsInvalid) (Syntax: 'new X[Program] { { 1 } }') Dimension Sizes(1): IInvalidOperation (OperationKind.Invalid, Type: Program, IsInvalid, IsImplicit) (Syntax: 'Program') Children(1): IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'Program') Initializer: IArrayInitializerOperation (1 elements) (OperationKind.ArrayInitializer, Type: null, IsInvalid) (Syntax: '{ { 1 } }') Element Values(1): IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: X, IsInvalid, IsImplicit) (Syntax: '{ 1 }') Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid, IsImplicit) (Syntax: '{ 1 }') Children(1): IArrayInitializerOperation (1 elements) (OperationKind.ArrayInitializer, Type: null, IsInvalid) (Syntax: '{ 1 }') Element Values(1): IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsInvalid, IsImplicit) (Syntax: '1') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid) (Syntax: '1') "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0246: The type or namespace name 'X' could not be found (are you missing a using directive or an assembly reference?) // var x = /*<bind>*/new X[Program] { { 1 } }/*</bind>*/; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "X").WithArguments("X").WithLocation(6, 31), // CS0119: 'Program' is a type, which is not valid in the given context // var x = /*<bind>*/new X[Program] { { 1 } }/*</bind>*/; Diagnostic(ErrorCode.ERR_BadSKunknown, "Program").WithArguments("Program", "type").WithLocation(6, 33), // CS0623: Array initializers can only be used in a variable or field initializer. Try using a new expression instead. // var x = /*<bind>*/new X[Program] { { 1 } }/*</bind>*/; Diagnostic(ErrorCode.ERR_ArrayInitInBadPlace, "{ 1 }").WithLocation(6, 44) }; VerifyOperationTreeAndDiagnosticsForTest<ArrayCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17598, "https://github.com/dotnet/roslyn/issues/17598")] public void InvalidParameterDefaultValueInitializer() { string source = @" using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; class Program { static int M() { return 0; } void F(int p /*<bind>*/= M()/*</bind>*/) { } } "; string expectedOperationTree = @" IParameterInitializerOperation (Parameter: [System.Int32 p = default(System.Int32)]) (OperationKind.ParameterInitializer, Type: null, IsInvalid) (Syntax: '= M()') IInvocationOperation (System.Int32 Program.M()) (OperationKind.Invocation, Type: System.Int32, IsInvalid) (Syntax: 'M()') Instance Receiver: null Arguments(0) "; var expectedDiagnostics = new DiagnosticDescription[] { // CS1736: Default parameter value for 'p' must be a compile-time constant // void F(int p /*<bind>*/= M()/*</bind>*/) Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "M()").WithArguments("p").WithLocation(10, 30) }; VerifyOperationTreeAndDiagnosticsForTest<EqualsValueClauseSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact] [CompilerTrait(CompilerFeature.IOperation)] [WorkItem(20050, "https://github.com/dotnet/roslyn/issues/20050")] public void BuildsArgumentsOperationsForDuplicateExplicitArguments_Repro() { string source = @" public class C { void M() { /*<bind>*/string.Format(format: """", format: """")/*</bind>*/; } }"; string expectedOperationTree = @" IInvalidOperation (OperationKind.Invalid, Type: System.String, IsInvalid) (Syntax: 'string.Form ... format: """")') Children(3): IOperation: (OperationKind.None, Type: null) (Syntax: 'string') ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: """") (Syntax: '""""') ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: """") (Syntax: '""""') "; VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics: new DiagnosticDescription[] { // file.cs(6,45): error CS1740: Named argument 'format' cannot be specified multiple times // /*<bind>*/string.Format(format: "", format: "")/*</bind>*/; Diagnostic(ErrorCode.ERR_DuplicateNamedArgument, "format").WithArguments("format").WithLocation(6, 45) }); } [Fact] [CompilerTrait(CompilerFeature.IOperation)] [WorkItem(20050, "https://github.com/dotnet/roslyn/issues/20050")] public void BuildsArgumentsOperationsForDuplicateExplicitArguments_CorrectArgumentsOrder_Methods() { string source = @" public class C { void N(int a, int b, int c = 4) { } void M() { /*<bind>*/N(a: 1, a: 2, b: 3)/*</bind>*/; } }"; string expectedOperationTree = @" IInvalidOperation (OperationKind.Invalid, Type: System.Void, IsInvalid) (Syntax: 'N(a: 1, a: 2, b: 3)') Children(3): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3') "; VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics: new DiagnosticDescription[] { // file.cs(10,27): error CS1740: Named argument 'a' cannot be specified multiple times // /*<bind>*/N(a: 1, a: 2)/*</bind>*/; Diagnostic(ErrorCode.ERR_DuplicateNamedArgument, "a").WithArguments("a").WithLocation(10, 27) }); } [Fact] [CompilerTrait(CompilerFeature.IOperation)] [WorkItem(20050, "https://github.com/dotnet/roslyn/issues/20050")] public void BuildsArgumentsOperationsForDuplicateExplicitArguments_CorrectArgumentsOrder_Delegates() { string source = @" public delegate void D(int a, int b, int c = 4); public class C { void N(D lambda) { /*<bind>*/lambda(a: 1, a: 2, b: 3)/*</bind>*/; } }"; string expectedOperationTree = @" IInvalidOperation (OperationKind.Invalid, Type: System.Void, IsInvalid) (Syntax: 'lambda(a: 1, a: 2, b: 3)') Children(4): IParameterReferenceOperation: lambda (OperationKind.ParameterReference, Type: D) (Syntax: 'lambda') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3') "; VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics: new DiagnosticDescription[] { // file.cs(7,32): error CS1740: Named argument 'a' cannot be specified multiple times // /*<bind>*/lambda(a: 1, a: 2, b: 3)/*</bind>*/; Diagnostic(ErrorCode.ERR_DuplicateNamedArgument, "a").WithArguments("a").WithLocation(7, 32) }); } [Fact] [CompilerTrait(CompilerFeature.IOperation)] [WorkItem(20050, "https://github.com/dotnet/roslyn/issues/20050")] public void BuildsArgumentsOperationsForDuplicateExplicitArguments_CorrectArgumentsOrder_Indexers_Getter() { string source = @" public class C { int this[int a, int b, int c = 4] { get => 0; } void M() { var result = /*<bind>*/this[a: 1, a: 2, b: 3]/*</bind>*/; } }"; string expectedOperationTree = @" IInvalidOperation (OperationKind.Invalid, Type: System.Int32, IsInvalid) (Syntax: 'this[a: 1, a: 2, b: 3]') Children(4): IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C) (Syntax: 'this') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3') "; VerifyOperationTreeAndDiagnosticsForTest<ElementAccessExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics: new DiagnosticDescription[] { // file.cs(11,43): error CS1740: Named argument 'a' cannot be specified multiple times // var result = /*<bind>*/this[a: 1, a: 2, b: 3]/*</bind>*/; Diagnostic(ErrorCode.ERR_DuplicateNamedArgument, "a").WithArguments("a").WithLocation(11, 43) }); } [Fact] [CompilerTrait(CompilerFeature.IOperation)] [WorkItem(20050, "https://github.com/dotnet/roslyn/issues/20050")] public void BuildsArgumentsOperationsForDuplicateExplicitArguments_CorrectArgumentsOrder_Indexers_Setter() { string source = @" public class C { int this[int a, int b, int c = 4] { set {} } void M() { /*<bind>*/this[a: 1, a: 2, b: 3]/*</bind>*/ = 0; } }"; string expectedOperationTree = @" IInvalidOperation (OperationKind.Invalid, Type: System.Int32, IsInvalid) (Syntax: 'this[a: 1, a: 2, b: 3]') Children(4): IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C) (Syntax: 'this') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3') "; VerifyOperationTreeAndDiagnosticsForTest<ElementAccessExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics: new DiagnosticDescription[] { // file.cs(11,30): error CS1740: Named argument 'a' cannot be specified multiple times // /*<bind>*/this[a: 1, a: 2, b: 3]/*</bind>*/ = 0; Diagnostic(ErrorCode.ERR_DuplicateNamedArgument, "a").WithArguments("a").WithLocation(11, 30) }); } [Fact] [CompilerTrait(CompilerFeature.IOperation)] [WorkItem(20050, "https://github.com/dotnet/roslyn/issues/20050")] public void BuildsArgumentsOperationsForDuplicateExplicitArguments_IncorrectArgumentsOrder_Methods() { string source = @" public class C { void N(int a, int b, int c = 4) { } void M() { /*<bind>*/N(b: 1, a: 2, a: 3)/*</bind>*/; } }"; string expectedOperationTree = @" IInvalidOperation (OperationKind.Invalid, Type: System.Void, IsInvalid) (Syntax: 'N(b: 1, a: 2, a: 3)') Children(3): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3') "; VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics: new DiagnosticDescription[] { // file.cs(10,33): error CS1740: Named argument 'a' cannot be specified multiple times // /*<bind>*/N(b: 1, a: 2, a: 3)/*</bind>*/; Diagnostic(ErrorCode.ERR_DuplicateNamedArgument, "a").WithArguments("a").WithLocation(10, 33) }); } [Fact] [CompilerTrait(CompilerFeature.IOperation)] [WorkItem(20050, "https://github.com/dotnet/roslyn/issues/20050")] public void BuildsArgumentsOperationsForDuplicateExplicitArguments_IncorrectArgumentsOrder_Delegates() { string source = @" public delegate void D(int a, int b, int c = 4); public class C { void N(D lambda) { /*<bind>*/lambda(b: 1, a: 2, a: 3)/*</bind>*/; } }"; string expectedOperationTree = @" IInvalidOperation (OperationKind.Invalid, Type: System.Void, IsInvalid) (Syntax: 'lambda(b: 1, a: 2, a: 3)') Children(4): IParameterReferenceOperation: lambda (OperationKind.ParameterReference, Type: D) (Syntax: 'lambda') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3') "; VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics: new DiagnosticDescription[] { // file.cs(7,38): error CS1740: Named argument 'a' cannot be specified multiple times // /*<bind>*/lambda(b: 1, a: 2, a: 3)/*</bind>*/; Diagnostic(ErrorCode.ERR_DuplicateNamedArgument, "a").WithArguments("a").WithLocation(7, 38) }); } [Fact] [CompilerTrait(CompilerFeature.IOperation)] [WorkItem(20050, "https://github.com/dotnet/roslyn/issues/20050")] public void BuildsArgumentsOperationsForDuplicateExplicitArguments_IncorrectArgumentsOrder_Indexers_Getter() { string source = @" public class C { int this[int a, int b, int c = 4] { get => 0; } void M() { var result = /*<bind>*/this[b: 1, a: 2, a: 3]/*</bind>*/; } }"; string expectedOperationTree = @" IInvalidOperation (OperationKind.Invalid, Type: System.Int32, IsInvalid) (Syntax: 'this[b: 1, a: 2, a: 3]') Children(4): IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C) (Syntax: 'this') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3') "; VerifyOperationTreeAndDiagnosticsForTest<ElementAccessExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics: new DiagnosticDescription[] { // file.cs(11,49): error CS1740: Named argument 'a' cannot be specified multiple times // var result = /*<bind>*/this[b: 1, a: 2, a: 3]/*</bind>*/; Diagnostic(ErrorCode.ERR_DuplicateNamedArgument, "a").WithArguments("a").WithLocation(11, 49) }); } [Fact] [CompilerTrait(CompilerFeature.IOperation)] [WorkItem(20050, "https://github.com/dotnet/roslyn/issues/20050")] public void BuildsArgumentsOperationsForDuplicateExplicitArguments_IncorrectArgumentsOrder_Indexers_Setter() { string source = @" public class C { int this[int a, int b, int c = 4] { set {} } void M() { /*<bind>*/this[b: 1, a: 2, a: 3]/*</bind>*/ = 0; } }"; string expectedOperationTree = @" IInvalidOperation (OperationKind.Invalid, Type: System.Int32, IsInvalid) (Syntax: 'this[b: 1, a: 2, a: 3]') Children(4): IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C) (Syntax: 'this') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3') "; VerifyOperationTreeAndDiagnosticsForTest<ElementAccessExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics: new DiagnosticDescription[] { // file.cs(11,36): error CS1740: Named argument 'a' cannot be specified multiple times // /*<bind>*/this[b: 1, a: 2, a: 3]/*</bind>*/ = 0; Diagnostic(ErrorCode.ERR_DuplicateNamedArgument, "a").WithArguments("a").WithLocation(11, 36) }); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void InvalidExpressionFlow_01() { string source = @" using System; class C { static void M1(int i, int x, int y) /*<bind>*/{ i = M(1, __arglist(x, y)); }/*</bind>*/ } "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0103: The name 'M' does not exist in the current context // i = M(1, __arglist(a ? w : x, b ? y : z)); Diagnostic(ErrorCode.ERR_NameNotInContext, "M").WithArguments("M").WithLocation(7, 13) }; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Block[B1] - Block Predecessors: [B0] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'i = M(1, __ ... ist(x, y));') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsInvalid) (Syntax: 'i = M(1, __ ... list(x, y))') Left: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i') Right: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'M(1, __arglist(x, y))') Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (NoConversion) Operand: IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'M(1, __arglist(x, y))') Children(3): IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'M') Children(0) ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') IOperation: (OperationKind.None, Type: null) (Syntax: '__arglist(x, y)') Children(2): IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x') IParameterReferenceOperation: y (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'y') Next (Regular) Block[B2] Block[B2] - Exit Predecessors: [B1] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void InvalidExpressionFlow_02() { string source = @" using System; class C { static void M1(int i, bool a,int x, int y, int z) /*<bind>*/{ i = M(1, __arglist(x, a ? y : z)); }/*</bind>*/ } "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0103: The name 'M' does not exist in the current context // i = M(1, __arglist(x, a ? y : z)); Diagnostic(ErrorCode.ERR_NameNotInContext, "M").WithArguments("M").WithLocation(7, 13) }; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [1] [2] [3] [4] Block[B1] - Block Predecessors: [B0] Statements (4) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i') Value: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'M') Value: IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'M') Children(0) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '1') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'x') Value: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x') Jump if False (Regular) to Block[B3] IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'a') Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'y') Value: IParameterReferenceOperation: y (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'y') Next (Regular) Block[B4] Block[B3] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'z') Value: IParameterReferenceOperation: z (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'z') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B2] [B3] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'i = M(1, __ ... ? y : z));') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsInvalid) (Syntax: 'i = M(1, __ ... a ? y : z))') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'i') Right: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'M(1, __argl ... a ? y : z))') Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (NoConversion) Operand: IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'M(1, __argl ... a ? y : z))') Children(3): IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: ?, IsInvalid, IsImplicit) (Syntax: 'M') IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: '1') IOperation: (OperationKind.None, Type: null) (Syntax: '__arglist(x, a ? y : z)') Children(2): IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'x') IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'a ? y : z') Next (Regular) Block[B5] Leaving: {R1} } Block[B5] - Exit Predecessors: [B4] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void InvalidExpressionFlow_03() { string source = @" using System; class C { static void M1(int i, bool a, int w, int x, int y) /*<bind>*/{ i = M(1, __arglist(a ? w : x, y)); }/*</bind>*/ } "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0103: The name 'M' does not exist in the current context // i = M(1, __arglist(a ? w : x, y)); Diagnostic(ErrorCode.ERR_NameNotInContext, "M").WithArguments("M").WithLocation(7, 13) }; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [1] [2] [3] Block[B1] - Block Predecessors: [B0] Statements (3) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i') Value: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'M') Value: IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'M') Children(0) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '1') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Jump if False (Regular) to Block[B3] IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'a') Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'w') Value: IParameterReferenceOperation: w (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'w') Next (Regular) Block[B4] Block[B3] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'x') Value: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B2] [B3] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'i = M(1, __ ... w : x, y));') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsInvalid) (Syntax: 'i = M(1, __ ... w : x, y))') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'i') Right: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'M(1, __argl ... w : x, y))') Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (NoConversion) Operand: IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'M(1, __argl ... w : x, y))') Children(3): IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: ?, IsInvalid, IsImplicit) (Syntax: 'M') IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: '1') IOperation: (OperationKind.None, Type: null) (Syntax: '__arglist(a ? w : x, y)') Children(2): IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'a ? w : x') IParameterReferenceOperation: y (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'y') Next (Regular) Block[B5] Leaving: {R1} } Block[B5] - Exit Predecessors: [B4] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void InvalidExpressionFlow_04() { string source = @" using System; class C { static void M1(int i, bool a, bool b, int w, int x, int y, int z) /*<bind>*/{ i = M(1, __arglist(a ? w : x, b ? y : z)); }/*</bind>*/ } "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0103: The name 'M' does not exist in the current context // i = M(1, __arglist(a ? w : x, b ? y : z)); Diagnostic(ErrorCode.ERR_NameNotInContext, "M").WithArguments("M").WithLocation(7, 13) }; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [1] [2] [3] [4] Block[B1] - Block Predecessors: [B0] Statements (3) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i') Value: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'M') Value: IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'M') Children(0) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '1') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Jump if False (Regular) to Block[B3] IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'a') Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'w') Value: IParameterReferenceOperation: w (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'w') Next (Regular) Block[B4] Block[B3] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'x') Value: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B2] [B3] Statements (0) Jump if False (Regular) to Block[B6] IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B4] Statements (1) IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'y') Value: IParameterReferenceOperation: y (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'y') Next (Regular) Block[B7] Block[B6] - Block Predecessors: [B4] Statements (1) IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'z') Value: IParameterReferenceOperation: z (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'z') Next (Regular) Block[B7] Block[B7] - Block Predecessors: [B5] [B6] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'i = M(1, __ ... ? y : z));') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsInvalid) (Syntax: 'i = M(1, __ ... b ? y : z))') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'i') Right: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'M(1, __argl ... b ? y : z))') Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (NoConversion) Operand: IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'M(1, __argl ... b ? y : z))') Children(3): IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: ?, IsInvalid, IsImplicit) (Syntax: 'M') IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: '1') IOperation: (OperationKind.None, Type: null) (Syntax: '__arglist(a ... b ? y : z)') Children(2): IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'a ? w : x') IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'b ? y : z') Next (Regular) Block[B8] Leaving: {R1} } Block[B8] - Exit Predecessors: [B7] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } } }
1
dotnet/roslyn
55,132
Support lambda expressions and method groups as `var` initializers
```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
cston
2021-07-27T03:12:21Z
2021-07-27T18:26:42Z
61a565cfcd777158cb6354351436aff997ad7bf6
5840335153dcca42570a853cdacd06d660fe9596
Support lambda expressions and method groups as `var` initializers. ```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
./src/Compilers/CSharp/Test/Semantic/Semantics/BindingTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; using Microsoft.CodeAnalysis.CSharp.Syntax; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Semantics { public class BindingTests : CompilingTestBase { [Fact, WorkItem(539872, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539872")] public void NoWRN_UnreachableCode() { var text = @" public class Cls { public static int Main() { goto Label2; Label1: return (1); Label2: goto Label1; } }"; CreateCompilation(text).VerifyDiagnostics(); } [Fact] public void GenericMethodName() { var source = @"class A { class B { static void M(System.Action a) { M(M1); M(M2<object>); M(M3<int>); } static void M1() { } static void M2<T>() { } } static void M3<T>() { } }"; CreateCompilation(source).VerifyDiagnostics(); } [Fact] public void GenericTypeName() { var source = @"class A { class B { static void M(System.Type t) { M(typeof(C<int>)); M(typeof(S<string, string>)); M(typeof(C<int, int>)); } class C<T> { } } struct S<T, U> { } } class C<T, U> { } "; CreateCompilation(source).VerifyDiagnostics(); } [Fact] public void GenericTypeParameterName() { var source = @"class A<T> { class B<U> { static void M<V>() { N(typeof(V)); N(typeof(U)); N(typeof(T)); } static void N(System.Type t) { } } }"; CreateCompilation(source).VerifyDiagnostics(); } [Fact] public void WrongMethodArity() { var source = @"class C { static void M1<T>() { } static void M2() { } void M3<T>() { } void M4() { } void M() { M1<object, object>(); C.M1<object, object>(); M2<int>(); C.M2<int>(); M3<object, object>(); this.M3<object, object>(); M4<int>(); this.M4<int>(); } }"; CreateCompilation(source).VerifyDiagnostics( // (9,9): error CS0305: Using the generic method 'C.M1<T>()' requires 1 type arguments Diagnostic(ErrorCode.ERR_BadArity, "M1<object, object>").WithArguments("C.M1<T>()", "method", "1").WithLocation(9, 9), // (10,11): error CS0305: Using the generic method 'C.M1<T>()' requires 1 type arguments Diagnostic(ErrorCode.ERR_BadArity, "M1<object, object>").WithArguments("C.M1<T>()", "method", "1").WithLocation(10, 11), // (11,9): error CS0308: The non-generic method 'C.M2()' cannot be used with type arguments Diagnostic(ErrorCode.ERR_HasNoTypeVars, "M2<int>").WithArguments("C.M2()", "method").WithLocation(11, 9), // (12,11): error CS0308: The non-generic method 'C.M2()' cannot be used with type arguments Diagnostic(ErrorCode.ERR_HasNoTypeVars, "M2<int>").WithArguments("C.M2()", "method").WithLocation(12, 11), // (13,9): error CS0305: Using the generic method 'C.M3<T>()' requires 1 type arguments Diagnostic(ErrorCode.ERR_BadArity, "M3<object, object>").WithArguments("C.M3<T>()", "method", "1").WithLocation(13, 9), // (14,14): error CS0305: Using the generic method 'C.M3<T>()' requires 1 type arguments Diagnostic(ErrorCode.ERR_BadArity, "M3<object, object>").WithArguments("C.M3<T>()", "method", "1").WithLocation(14, 14), // (15,9): error CS0308: The non-generic method 'C.M4()' cannot be used with type arguments Diagnostic(ErrorCode.ERR_HasNoTypeVars, "M4<int>").WithArguments("C.M4()", "method").WithLocation(15, 9), // (16,14): error CS0308: The non-generic method 'C.M4()' cannot be used with type arguments Diagnostic(ErrorCode.ERR_HasNoTypeVars, "M4<int>").WithArguments("C.M4()", "method").WithLocation(16, 14)); } [Fact] public void AmbiguousInaccessibleMethod() { var source = @"class A { protected void M1() { } protected void M1(object o) { } protected void M2(string s) { } protected void M2(object o) { } } class B { static void M(A a) { a.M1(); a.M2(); M(a.M1); M(a.M2); } static void M(System.Action<object> a) { } }"; CreateCompilation(source).VerifyDiagnostics( // (12,11): error CS0122: 'A.M1()' is inaccessible due to its protection level Diagnostic(ErrorCode.ERR_BadAccess, "M1").WithArguments("A.M1()").WithLocation(12, 11), // (13,11): error CS0122: 'A.M2(string)' is inaccessible due to its protection level Diagnostic(ErrorCode.ERR_BadAccess, "M2").WithArguments("A.M2(string)").WithLocation(13, 11), // (14,13): error CS0122: 'A.M1()' is inaccessible due to its protection level Diagnostic(ErrorCode.ERR_BadAccess, "M1").WithArguments("A.M1()").WithLocation(14, 13), // (15,13): error CS0122: 'A.M2(string)' is inaccessible due to its protection level Diagnostic(ErrorCode.ERR_BadAccess, "M2").WithArguments("A.M2(string)").WithLocation(15, 13)); } /// <summary> /// Should report inaccessible method, even when using /// method as a delegate in an invalid context. /// </summary> [Fact] public void InaccessibleMethodInvalidDelegateUse() { var source = @"class A { protected object F() { return null; } } class B { static void M(A a) { if (a.F != null) { M(a.F); a.F.ToString(); } } }"; CreateCompilation(source).VerifyDiagnostics( // (9,15): error CS0122: 'A.F()' is inaccessible due to its protection level Diagnostic(ErrorCode.ERR_BadAccess, "F").WithArguments("A.F()").WithLocation(9, 15), // (11,17): error CS0122: 'A.F()' is inaccessible due to its protection level Diagnostic(ErrorCode.ERR_BadAccess, "F").WithArguments("A.F()").WithLocation(11, 17), // (12,15): error CS0122: 'A.F()' is inaccessible due to its protection level Diagnostic(ErrorCode.ERR_BadAccess, "F").WithArguments("A.F()").WithLocation(12, 15)); } /// <summary> /// Methods should be resolved correctly even /// in cases where a method group is not allowed. /// </summary> [Fact] public void InvalidUseOfMethodGroup() { var source = @"class A { internal object E() { return null; } private object F() { return null; } } class B { static void M(A a) { object o; a.E += a.E; if (a.E != null) { M(a.E); a.E.ToString(); o = !a.E; o = a.E ?? a.F; } a.F += a.F; if (a.F != null) { M(a.F); a.F.ToString(); o = !a.F; o = (o != null) ? a.E : a.F; } } }"; CreateCompilation(source).VerifyDiagnostics( // (11,9): error CS1656: Cannot assign to 'E' because it is a 'method group' // a.E += a.E; Diagnostic(ErrorCode.ERR_AssgReadonlyLocalCause, "a.E").WithArguments("E", "method group").WithLocation(11, 9), // (14,15): error CS1503: Argument 1: cannot convert from 'method group' to 'A' // M(a.E); Diagnostic(ErrorCode.ERR_BadArgType, "a.E").WithArguments("1", "method group", "A").WithLocation(14, 15), // (15,15): error CS0119: 'A.E()' is a method, which is not valid in the given context // a.E.ToString(); Diagnostic(ErrorCode.ERR_BadSKunknown, "E").WithArguments("A.E()", "method").WithLocation(15, 15), // (16,17): error CS0023: Operator '!' cannot be applied to operand of type 'method group' // o = !a.E; Diagnostic(ErrorCode.ERR_BadUnaryOp, "!a.E").WithArguments("!", "method group").WithLocation(16, 17), // (17,26): error CS0122: 'A.F()' is inaccessible due to its protection level // o = a.E ?? a.F; Diagnostic(ErrorCode.ERR_BadAccess, "F").WithArguments("A.F()").WithLocation(17, 26), // (19,11): error CS0122: 'A.F()' is inaccessible due to its protection level // a.F += a.F; Diagnostic(ErrorCode.ERR_BadAccess, "F").WithArguments("A.F()").WithLocation(19, 11), // (19,18): error CS0122: 'A.F()' is inaccessible due to its protection level // a.F += a.F; Diagnostic(ErrorCode.ERR_BadAccess, "F").WithArguments("A.F()").WithLocation(19, 18), // (20,15): error CS0122: 'A.F()' is inaccessible due to its protection level // if (a.F != null) Diagnostic(ErrorCode.ERR_BadAccess, "F").WithArguments("A.F()").WithLocation(20, 15), // (22,17): error CS0122: 'A.F()' is inaccessible due to its protection level // M(a.F); Diagnostic(ErrorCode.ERR_BadAccess, "F").WithArguments("A.F()").WithLocation(22, 17), // (23,15): error CS0122: 'A.F()' is inaccessible due to its protection level // a.F.ToString(); Diagnostic(ErrorCode.ERR_BadAccess, "F").WithArguments("A.F()").WithLocation(23, 15), // (24,20): error CS0122: 'A.F()' is inaccessible due to its protection level // o = !a.F; Diagnostic(ErrorCode.ERR_BadAccess, "F").WithArguments("A.F()").WithLocation(24, 20), // (25,39): error CS0122: 'A.F()' is inaccessible due to its protection level // o = (o != null) ? a.E : a.F; Diagnostic(ErrorCode.ERR_BadAccess, "F").WithArguments("A.F()").WithLocation(25, 39)); } [WorkItem(528425, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528425")] [Fact(Skip = "528425")] public void InaccessibleAndAccessible() { var source = @"using System; class A { void F() { } internal void F(object o) { } static void G() { } internal static void G(object o) { } void H(object o) { } } class B : A { static void M(A a) { a.F(null); a.F(); A.G(); M1(a.F); M2(a.F); Action<object> a1 = a.F; Action a2 = a.F; } void M() { G(); } static void M1(Action<object> a) { } static void M2(Action a) { } }"; CreateCompilation(source).VerifyDiagnostics( // (15,11): error CS0122: 'A.F()' is inaccessible due to its protection level Diagnostic(ErrorCode.ERR_BadAccess, "F").WithArguments("A.F()").WithLocation(15, 11), // (16,11): error CS0122: 'A.G()' is inaccessible due to its protection level Diagnostic(ErrorCode.ERR_BadAccess, "G").WithArguments("A.G()").WithLocation(16, 11), // (18,12): error CS1503: Argument 1: cannot convert from 'method group' to 'System.Action' Diagnostic(ErrorCode.ERR_BadArgType, "a.F").WithArguments("1", "method group", "System.Action").WithLocation(18, 12), // (20,23): error CS0122: 'A.F()' is inaccessible due to its protection level Diagnostic(ErrorCode.ERR_BadAccess, "F").WithArguments("A.F()").WithLocation(20, 23), // (24,9): error CS0122: 'A.G()' is inaccessible due to its protection level Diagnostic(ErrorCode.ERR_BadAccess, "G").WithArguments("A.G()").WithLocation(24, 9)); } [Fact] public void InaccessibleAndAccessibleAndAmbiguous() { var source = @"class A { void F(string x) { } void F(string x, string y) { } internal void F(object x, string y) { } internal void F(string x, object y) { } void G(object x, string y) { } internal void G(string x, object y) { } static void M(A a, string s) { a.F(s, s); // no error } } class B { static void M(A a, string s, object o) { a.F(s, s); // accessible ambiguous a.G(s, s); // accessible and inaccessible ambiguous, no error a.G(o, o); // accessible and inaccessible invalid } }"; CreateCompilation(source).VerifyDiagnostics( // (18,9): error CS0121: The call is ambiguous between the following methods or properties: 'A.F(object, string)' and 'A.F(string, object)' Diagnostic(ErrorCode.ERR_AmbigCall, "F").WithArguments("A.F(object, string)", "A.F(string, object)").WithLocation(18, 11), // (20,13): error CS1503: Argument 1: cannot convert from 'object' to 'string' Diagnostic(ErrorCode.ERR_BadArgType, "o").WithArguments("1", "object", "string").WithLocation(20, 13)); } [Fact] public void InaccessibleAndAccessibleValid() { var source = @"class A { void F(int i) { } internal void F(long l) { } static void M(A a) { a.F(1); // no error } } class B { static void M(A a) { a.F(1); // no error } }"; CreateCompilation(source).VerifyDiagnostics(); } [Fact] public void ParenthesizedDelegate() { var source = @"class C { System.Action<object> F = null; void M() { ((this.F))(null); (new C().F)(null, null); } }"; CreateCompilation(source).VerifyDiagnostics( Diagnostic(ErrorCode.ERR_BadDelArgCount, "(new C().F)").WithArguments("System.Action<object>", "2").WithLocation(7, 9)); } /// <summary> /// Report errors for invocation expressions for non-invocable expressions, /// and bind arguments even though invocation expression was invalid. /// </summary> [Fact] public void NonMethodsWithArgs() { var source = @"namespace N { class C<T> { object F; object P { get; set; } void M() { N(a); C<string>(b); N.C<int>(c); N.D(d); T(e); (typeof(C<int>))(f); P(g) = F(h); this.F(i) = (this).P(j); null.M(k); } } }"; CreateCompilation(source).VerifyDiagnostics( // (9,15): error CS0103: The name 'a' does not exist in the current context // N(a); Diagnostic(ErrorCode.ERR_NameNotInContext, "a").WithArguments("a"), // (9,13): error CS0118: 'N' is a namespace but is used like a variable // N(a); Diagnostic(ErrorCode.ERR_BadSKknown, "N").WithArguments("N", "namespace", "variable"), // (10,23): error CS0103: The name 'b' does not exist in the current context // C<string>(b); Diagnostic(ErrorCode.ERR_NameNotInContext, "b").WithArguments("b"), // (10,13): error CS1955: Non-invocable member 'N.C<T>' cannot be used like a method. // C<string>(b); Diagnostic(ErrorCode.ERR_NonInvocableMemberCalled, "C<string>").WithArguments("N.C<T>"), // (11,22): error CS0103: The name 'c' does not exist in the current context // N.C<int>(c); Diagnostic(ErrorCode.ERR_NameNotInContext, "c").WithArguments("c"), // (11,15): error CS1955: Non-invocable member 'N.C<T>' cannot be used like a method. // N.C<int>(c); Diagnostic(ErrorCode.ERR_NonInvocableMemberCalled, "C<int>").WithArguments("N.C<T>"), // (12,17): error CS0103: The name 'd' does not exist in the current context // N.D(d); Diagnostic(ErrorCode.ERR_NameNotInContext, "d").WithArguments("d"), // (12,13): error CS0234: The type or namespace name 'D' does not exist in the namespace 'N' (are you missing an assembly reference?) // N.D(d); Diagnostic(ErrorCode.ERR_DottedTypeNameNotFoundInNS, "N.D").WithArguments("D", "N"), // (13,15): error CS0103: The name 'e' does not exist in the current context // T(e); Diagnostic(ErrorCode.ERR_NameNotInContext, "e").WithArguments("e"), // (13,13): error CS0103: The name 'T' does not exist in the current context // T(e); Diagnostic(ErrorCode.ERR_NameNotInContext, "T").WithArguments("T"), // (14,30): error CS0103: The name 'f' does not exist in the current context // (typeof(C<int>))(f); Diagnostic(ErrorCode.ERR_NameNotInContext, "f").WithArguments("f"), // (14,13): error CS0149: Method name expected // (typeof(C<int>))(f); Diagnostic(ErrorCode.ERR_MethodNameExpected, "(typeof(C<int>))"), // (15,15): error CS0103: The name 'g' does not exist in the current context // P(g) = F(h); Diagnostic(ErrorCode.ERR_NameNotInContext, "g").WithArguments("g"), // (15,13): error CS1955: Non-invocable member 'N.C<T>.P' cannot be used like a method. // P(g) = F(h); Diagnostic(ErrorCode.ERR_NonInvocableMemberCalled, "P").WithArguments("N.C<T>.P"), // (15,22): error CS0103: The name 'h' does not exist in the current context // P(g) = F(h); Diagnostic(ErrorCode.ERR_NameNotInContext, "h").WithArguments("h"), // (15,20): error CS1955: Non-invocable member 'N.C<T>.F' cannot be used like a method. // P(g) = F(h); Diagnostic(ErrorCode.ERR_NonInvocableMemberCalled, "F").WithArguments("N.C<T>.F"), // (16,20): error CS0103: The name 'i' does not exist in the current context // this.F(i) = (this).P(j); Diagnostic(ErrorCode.ERR_NameNotInContext, "i").WithArguments("i"), // (16,18): error CS1955: Non-invocable member 'N.C<T>.F' cannot be used like a method. // this.F(i) = (this).P(j); Diagnostic(ErrorCode.ERR_NonInvocableMemberCalled, "F").WithArguments("N.C<T>.F"), // (16,34): error CS0103: The name 'j' does not exist in the current context // this.F(i) = (this).P(j); Diagnostic(ErrorCode.ERR_NameNotInContext, "j").WithArguments("j"), // (16,32): error CS1955: Non-invocable member 'N.C<T>.P' cannot be used like a method. // this.F(i) = (this).P(j); Diagnostic(ErrorCode.ERR_NonInvocableMemberCalled, "P").WithArguments("N.C<T>.P"), // (17,20): error CS0103: The name 'k' does not exist in the current context // null.M(k); Diagnostic(ErrorCode.ERR_NameNotInContext, "k").WithArguments("k"), // (17,13): error CS0023: Operator '.' cannot be applied to operand of type '<null>' // null.M(k); Diagnostic(ErrorCode.ERR_BadUnaryOp, "null.M").WithArguments(".", "<null>"), // (5,16): warning CS0649: Field 'N.C<T>.F' is never assigned to, and will always have its default value null // object F; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "F").WithArguments("N.C<T>.F", "null") ); } [Fact] public void SimpleDelegates() { var source = @"static class S { public static void F(System.Action a) { } } class C { void M() { S.F(this.M); System.Action a = this.M; S.F(a); } }"; CreateCompilation(source).VerifyDiagnostics(); } [Fact] public void DelegatesFromOverloads() { var source = @"using System; class C { static void A(Action<object> a) { } static void M(C c) { A(C.F); A(c.G); Action<object> a; a = C.F; a = c.G; } static void F() { } static void F(object o) { } void G(object o) { } void G(object x, object y) { } }"; CreateCompilation(source).VerifyDiagnostics(); } [Fact] public void NonViableDelegates() { var source = @"using System; class A { static Action F = null; Action G = null; } class B { static void M(A a) { A.F(x); a.G(y); } }"; CreateCompilation(source).VerifyDiagnostics( // (11,13): error CS0103: The name 'x' does not exist in the current context // A.F(x); Diagnostic(ErrorCode.ERR_NameNotInContext, "x").WithArguments("x"), // (11,11): error CS0122: 'A.F' is inaccessible due to its protection level // A.F(x); Diagnostic(ErrorCode.ERR_BadAccess, "F").WithArguments("A.F"), // (12,13): error CS0103: The name 'y' does not exist in the current context // a.G(y); Diagnostic(ErrorCode.ERR_NameNotInContext, "y").WithArguments("y"), // (12,11): error CS0122: 'A.G' is inaccessible due to its protection level // a.G(y); Diagnostic(ErrorCode.ERR_BadAccess, "G").WithArguments("A.G"), // (4,19): warning CS0414: The field 'A.F' is assigned but its value is never used // static Action F = null; Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "F").WithArguments("A.F"), // (5,12): warning CS0414: The field 'A.G' is assigned but its value is never used // Action G = null; Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "G").WithArguments("A.G") ); } /// <summary> /// Choose one method if overloaded methods are /// equally invalid. /// </summary> [Fact] public void ChooseOneMethodIfEquallyInvalid() { var source = @"internal static class S { public static void M(double x, A y) { } public static void M(double x, B y) { } } class A { } class B { } class C { static void M() { S.M(1.0, null); // ambiguous S.M(1.0, 2.0); // equally invalid } }"; CreateCompilation(source).VerifyDiagnostics( // (12,9): error CS0121: The call is ambiguous between the following methods or properties: 'S.M(double, A)' and 'S.M(double, B)' Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("S.M(double, A)", "S.M(double, B)").WithLocation(12, 11), // (13,18): error CS1503: Argument 2: cannot convert from 'double' to 'A' Diagnostic(ErrorCode.ERR_BadArgType, "2.0").WithArguments("2", "double", "A").WithLocation(13, 18)); } [Fact] public void ChooseExpandedFormIfBadArgCountAndBadArgument() { var source = @"class C { static void M(object o) { F(); F(o); F(1, o); F(1, 2, o); } static void F(int i, params int[] args) { } }"; CreateCompilation(source).VerifyDiagnostics( // (5,9): error CS7036: There is no argument given that corresponds to the required formal parameter 'i' of 'C.F(int, params int[])' Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "F").WithArguments("i", "C.F(int, params int[])").WithLocation(5, 9), // (6,11): error CS1503: Argument 1: cannot convert from 'object' to 'int' Diagnostic(ErrorCode.ERR_BadArgType, "o").WithArguments("1", "object", "int").WithLocation(6, 11), // (7,14): error CS1503: Argument 2: cannot convert from 'object' to 'int' Diagnostic(ErrorCode.ERR_BadArgType, "o").WithArguments("2", "object", "int").WithLocation(7, 14), // (8,17): error CS1503: Argument 3: cannot convert from 'object' to 'int' Diagnostic(ErrorCode.ERR_BadArgType, "o").WithArguments("3", "object", "int").WithLocation(8, 17)); } [Fact] public void AmbiguousAndBadArgument() { var source = @"class C { static void F(int x, double y) { } static void F(double x, int y) { } static void M() { F(1, 2); F(1.0, 2.0); } }"; CreateCompilation(source).VerifyDiagnostics( // (7,9): error CS0121: The call is ambiguous between the following methods or properties: 'C.F(int, double)' and 'C.F(double, int)' Diagnostic(ErrorCode.ERR_AmbigCall, "F").WithArguments("C.F(int, double)", "C.F(double, int)").WithLocation(7, 9), // (8,11): error CS1503: Argument 1: cannot convert from 'double' to 'int' Diagnostic(ErrorCode.ERR_BadArgType, "1.0").WithArguments("1", "double", "int").WithLocation(8, 11)); } [WorkItem(541050, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541050")] [Fact] public void IncompleteDelegateDecl() { var source = @"namespace nms { delegate"; CreateCompilation(source).VerifyDiagnostics( // (3,9): error CS1031: Type expected // delegate Diagnostic(ErrorCode.ERR_TypeExpected, ""), // (3,9): error CS1001: Identifier expected // delegate Diagnostic(ErrorCode.ERR_IdentifierExpected, ""), // (3,9): error CS1003: Syntax error, '(' expected // delegate Diagnostic(ErrorCode.ERR_SyntaxError, "").WithArguments("(", ""), // (3,9): error CS1026: ) expected // delegate Diagnostic(ErrorCode.ERR_CloseParenExpected, ""), // (3,9): error CS1002: ; expected // delegate Diagnostic(ErrorCode.ERR_SemicolonExpected, ""), // (3,9): error CS1513: } expected // delegate Diagnostic(ErrorCode.ERR_RbraceExpected, "")); } [WorkItem(541213, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541213")] [Fact] public void IncompleteElsePartInIfStmt() { var source = @"public class Test { public static int Main(string [] args) { if (true) { } else "; CreateCompilation(source).VerifyDiagnostics( // (8,13): error CS1733: Expected expression // else Diagnostic(ErrorCode.ERR_ExpressionExpected, ""), // (9,1): error CS1002: ; expected // Diagnostic(ErrorCode.ERR_SemicolonExpected, ""), // (9,1): error CS1513: } expected // Diagnostic(ErrorCode.ERR_RbraceExpected, ""), // (9,1): error CS1513: } expected // Diagnostic(ErrorCode.ERR_RbraceExpected, ""), // (3,23): error CS0161: 'Test.Main(string[])': not all code paths return a value // public static int Main(string [] args) Diagnostic(ErrorCode.ERR_ReturnExpected, "Main").WithArguments("Test.Main(string[])") ); } [WorkItem(541466, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541466")] [Fact] public void UseSiteErrorViaAliasTest01() { var baseAssembly = CreateCompilation( @" namespace BaseAssembly { public class BaseClass { } } ", assemblyName: "BaseAssembly1").VerifyDiagnostics(); var derivedAssembly = CreateCompilation( @" namespace DerivedAssembly { public class DerivedClass: BaseAssembly.BaseClass { public static int IntField = 123; } } ", assemblyName: "DerivedAssembly1", references: new List<MetadataReference>() { baseAssembly.EmitToImageReference() }).VerifyDiagnostics(); var testAssembly = CreateCompilation( @" using ClassAlias = DerivedAssembly.DerivedClass; public class Test { static void Main() { int a = ClassAlias.IntField; int b = ClassAlias.IntField; } } ", references: new List<MetadataReference>() { derivedAssembly.EmitToImageReference() }) .VerifyDiagnostics(); // NOTE: Dev10 errors: // <fine-name>(7,9): error CS0012: The type 'BaseAssembly.BaseClass' is defined in an assembly that is not referenced. You must add a reference to assembly 'BaseAssembly, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'. } [WorkItem(541466, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541466")] [Fact] public void UseSiteErrorViaAliasTest02() { var baseAssembly = CreateCompilation( @" namespace BaseAssembly { public class BaseClass { } } ", assemblyName: "BaseAssembly2").VerifyDiagnostics(); var derivedAssembly = CreateCompilation( @" namespace DerivedAssembly { public class DerivedClass: BaseAssembly.BaseClass { public static int IntField = 123; } } ", assemblyName: "DerivedAssembly2", references: new List<MetadataReference>() { baseAssembly.EmitToImageReference() }).VerifyDiagnostics(); var testAssembly = CreateCompilation( @" using ClassAlias = DerivedAssembly.DerivedClass; public class Test { static void Main() { ClassAlias a = new ClassAlias(); ClassAlias b = new ClassAlias(); } } ", references: new List<MetadataReference>() { derivedAssembly.EmitToImageReference() }) .VerifyDiagnostics(); // NOTE: Dev10 errors: // <fine-name>(6,9): error CS0012: The type 'BaseAssembly.BaseClass' is defined in an assembly that is not referenced. You must add a reference to assembly 'BaseAssembly, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'. } [WorkItem(541466, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541466")] [Fact] public void UseSiteErrorViaAliasTest03() { var baseAssembly = CreateCompilation( @" namespace BaseAssembly { public class BaseClass { } } ", assemblyName: "BaseAssembly3").VerifyDiagnostics(); var derivedAssembly = CreateCompilation( @" namespace DerivedAssembly { public class DerivedClass: BaseAssembly.BaseClass { public static int IntField = 123; } } ", assemblyName: "DerivedAssembly3", references: new List<MetadataReference>() { baseAssembly.EmitToImageReference() }).VerifyDiagnostics(); var testAssembly = CreateCompilation( @" using ClassAlias = DerivedAssembly.DerivedClass; public class Test { ClassAlias a = null; ClassAlias b = null; ClassAlias m() { return null; } void m2(ClassAlias p) { } }", references: new List<MetadataReference>() { derivedAssembly.EmitToImageReference() }) .VerifyDiagnostics( // (5,16): warning CS0414: The field 'Test.a' is assigned but its value is never used // ClassAlias a = null; Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "a").WithArguments("Test.a"), // (6,16): warning CS0414: The field 'Test.b' is assigned but its value is never used // ClassAlias b = null; Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "b").WithArguments("Test.b") ); // NOTE: Dev10 errors: // <fine-name>(4,16): error CS0012: The type 'BaseAssembly.BaseClass' is defined in an assembly that is not referenced. You must add a reference to assembly 'BaseAssembly, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'. } [WorkItem(911913, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/911913")] [Fact] public void UnimplementedInterfaceSquiggleLocation_Typical() { string scenarioCode = @" public class ITT : IInterfaceBase { } public interface IInterfaceBase { void bar(); }"; var testAssembly = CreateCompilation(scenarioCode); testAssembly.VerifyDiagnostics( // (3,7): error CS0535: 'ITT' does not implement interface member 'IInterfaceBase.bar()' // : IInterfaceBase Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "IInterfaceBase").WithArguments("ITT", "IInterfaceBase.bar()").WithLocation(3, 7)); } [WorkItem(911913, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/911913")] [Fact] public void UnimplementedInterfaceSquiggleLocation_FullyQualified() { // Using fully Qualified names string scenarioCode = @" public class ITT : test.IInterfaceBase { } namespace test { public interface IInterfaceBase { void bar(); } }"; var testAssembly = CreateCompilation(scenarioCode); testAssembly.VerifyDiagnostics( // (3,7): error CS0535: 'ITT' does not implement interface member 'test.IInterfaceBase.bar()' // : test.IInterfaceBase Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "test.IInterfaceBase").WithArguments("ITT", "test.IInterfaceBase.bar()").WithLocation(3, 7)); } [WorkItem(911913, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/911913")] [Fact] public void UnimplementedInterfaceSquiggleLocation_WithAlias() { // Using Alias string scenarioCode = @" using a1 = test; public class ITT : a1.IInterfaceBase { } namespace test { public interface IInterfaceBase { void bar(); } }"; var testAssembly = CreateCompilation(scenarioCode); testAssembly.VerifyDiagnostics( // (5,7): error CS0535: 'ITT' does not implement interface member 'test.IInterfaceBase.bar()' // : a1.IInterfaceBase Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "a1.IInterfaceBase").WithArguments("ITT", "test.IInterfaceBase.bar()").WithLocation(5, 7)); } [WorkItem(911913, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/911913")] [Fact] public void UnimplementedInterfaceSquiggleLocation_InterfaceInheritanceScenario01() { // Two interfaces, neither implemented with alias - should have 2 errors each squiggling a different interface type. string scenarioCode = @" using a1 = test; public class ITT : a1.IInterfaceBase, a1.IInterfaceBase2 { } namespace test { public interface IInterfaceBase { void xyz(); } public interface IInterfaceBase2 { void xyz(); } }"; var testAssembly = CreateCompilation(scenarioCode); testAssembly.VerifyDiagnostics( // (5,7): error CS0535: 'ITT' does not implement interface member 'test.IInterfaceBase.xyz()' // : a1.IInterfaceBase, a1.IInterfaceBase2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "a1.IInterfaceBase").WithArguments("ITT", "test.IInterfaceBase.xyz()").WithLocation(5, 7), // (5,26): error CS0535: 'ITT' does not implement interface member 'test.IInterfaceBase2.xyz()' // : a1.IInterfaceBase, a1.IInterfaceBase2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "a1.IInterfaceBase2").WithArguments("ITT", "test.IInterfaceBase2.xyz()").WithLocation(5, 26)); } [WorkItem(911913, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/911913")] [Fact] public void UnimplementedInterfaceSquiggleLocation_InterfaceInheritanceScenario02() { // Two interfaces, only the second is implemented string scenarioCode = @" public class ITT : IInterfaceBase, IInterfaceBase2 { void IInterfaceBase2.abc() { } } public interface IInterfaceBase { void xyz(); } public interface IInterfaceBase2 { void abc(); }"; var testAssembly = CreateCompilation(scenarioCode); testAssembly.VerifyDiagnostics( // (3,7): error CS0535: 'ITT' does not implement interface member 'IInterfaceBase.xyz()' // : IInterfaceBase, IInterfaceBase2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "IInterfaceBase").WithArguments("ITT", "IInterfaceBase.xyz()").WithLocation(3, 7)); } [WorkItem(911913, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/911913")] [Fact] public void UnimplementedInterfaceSquiggleLocation_InterfaceInheritanceScenario03() { // Two interfaces, only the first is implemented string scenarioCode = @" public class ITT : IInterfaceBase, IInterfaceBase2 { void IInterfaceBase.xyz() { } } public interface IInterfaceBase { void xyz(); } public interface IInterfaceBase2 { void abc(); } "; var testAssembly = CreateCompilation(scenarioCode); testAssembly.VerifyDiagnostics( // (3,23): error CS0535: 'ITT' does not implement interface member 'IInterfaceBase2.abc()' // : IInterfaceBase, IInterfaceBase2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "IInterfaceBase2").WithArguments("ITT", "IInterfaceBase2.abc()").WithLocation(3, 23)); } [WorkItem(911913, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/911913")] [Fact] public void UnimplementedInterfaceSquiggleLocation_InterfaceInheritanceScenario04() { // Two interfaces, neither implemented but formatting of interfaces are on different lines string scenarioCode = @" public class ITT : IInterfaceBase, IInterfaceBase2 { } public interface IInterfaceBase { void xyz(); } public interface IInterfaceBase2 { void xyz(); } "; var testAssembly = CreateCompilation(scenarioCode); testAssembly.VerifyDiagnostics( // (3,7): error CS0535: 'ITT' does not implement interface member 'IInterfaceBase.xyz()' // : IInterfaceBase, Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "IInterfaceBase").WithArguments("ITT", "IInterfaceBase.xyz()").WithLocation(3, 7), // (4,6): error CS0535: 'ITT' does not implement interface member 'IInterfaceBase2.xyz()' // IInterfaceBase2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "IInterfaceBase2").WithArguments("ITT", "IInterfaceBase2.xyz()").WithLocation(4, 6)); } [WorkItem(911913, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/911913")] [Fact] public void UnimplementedInterfaceSquiggleLocation_InterfaceInheritanceScenario05() { // Inherited Interface scenario // With methods not implemented in both base and derived. // Should reflect 2 diagnostics but both with be squiggling the derived as we are not // explicitly implementing base. string scenarioCode = @" public class ITT: IDerived { } interface IInterfaceBase { void xyzb(); } interface IDerived : IInterfaceBase { void xyzd(); }"; var testAssembly = CreateCompilation(scenarioCode); testAssembly.VerifyDiagnostics( // (2,19): error CS0535: 'ITT' does not implement interface member 'IDerived.xyzd()' // public class ITT: IDerived Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "IDerived").WithArguments("ITT", "IDerived.xyzd()").WithLocation(2, 19), // (2,19): error CS0535: 'ITT' does not implement interface member 'IInterfaceBase.xyzb()' // public class ITT: IDerived Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "IDerived").WithArguments("ITT", "IInterfaceBase.xyzb()").WithLocation(2, 19)); } [WorkItem(911913, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/911913")] [Fact] public void UnimplementedInterfaceSquiggleLocation_InterfaceInheritanceScenario06() { // Inherited Interface scenario string scenarioCode = @" public class ITT: IDerived, IInterfaceBase { } interface IInterfaceBase { void xyz(); } interface IDerived : IInterfaceBase { void xyzd(); }"; var testAssembly = CreateCompilation(scenarioCode); testAssembly.VerifyDiagnostics( // (2,19): error CS0535: 'ITT' does not implement interface member 'IDerived.xyzd()' // public class ITT: IDerived, IInterfaceBase Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "IDerived").WithArguments("ITT", "IDerived.xyzd()").WithLocation(2, 19), // (2,29): error CS0535: 'ITT' does not implement interface member 'IInterfaceBase.xyz()' // public class ITT: IDerived, IInterfaceBase Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "IInterfaceBase").WithArguments("ITT", "IInterfaceBase.xyz()").WithLocation(2, 29)); } [WorkItem(911913, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/911913")] [Fact] public void UnimplementedInterfaceSquiggleLocation_InterfaceInheritanceScenario07() { // Inherited Interface scenario - different order. string scenarioCode = @" public class ITT: IInterfaceBase, IDerived { } interface IDerived : IInterfaceBase { void xyzd(); } interface IInterfaceBase { void xyz(); } "; var testAssembly = CreateCompilation(scenarioCode); testAssembly.VerifyDiagnostics( // (2,35): error CS0535: 'ITT' does not implement interface member 'IDerived.xyzd()' // public class ITT: IInterfaceBase, IDerived Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "IDerived").WithArguments("ITT", "IDerived.xyzd()").WithLocation(2, 35), // (2,19): error CS0535: 'ITT' does not implement interface member 'IInterfaceBase.xyz()' // public class ITT: IInterfaceBase, IDerived Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "IInterfaceBase").WithArguments("ITT", "IInterfaceBase.xyz()").WithLocation(2, 19)); } [WorkItem(911913, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/911913")] [Fact] public void UnimplementedInterfaceSquiggleLocation_InterfaceInheritanceScenario08() { // Inherited Interface scenario string scenarioCode = @" public class ITT: IDerived2 {} interface IBase { void method1(); } interface IBase2 { void Method2(); } interface IDerived2: IBase, IBase2 {}"; var testAssembly = CreateCompilation(scenarioCode); testAssembly.VerifyDiagnostics( // (2,19): error CS0535: 'ITT' does not implement interface member 'IBase.method1()' // public class ITT: IDerived2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "IDerived2").WithArguments("ITT", "IBase.method1()").WithLocation(2, 19), // (2,19): error CS0535: 'ITT' does not implement interface member 'IBase2.Method2()' // public class ITT: IDerived2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "IDerived2").WithArguments("ITT", "IBase2.Method2()").WithLocation(2, 19)); } [WorkItem(911913, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/911913")] [Fact] public void UnimplementedInterfaceSquiggleLocation13UnimplementedInterfaceSquiggleLocation_InterfaceInheritanceScenario09() { // Inherited Interface scenario. string scenarioCode = @" public class ITT : IDerived { void IBase2.method2() { } void IDerived.method3() { } } public interface IBase { void method1(); } public interface IBase2 { void method2(); } public interface IDerived : IBase, IBase2 { void method3(); }"; var testAssembly = CreateCompilation(scenarioCode); testAssembly.VerifyDiagnostics( // (2,20): error CS0535: 'ITT' does not implement interface member 'IBase.method1()' // public class ITT : IDerived Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "IDerived").WithArguments("ITT", "IBase.method1()").WithLocation(2, 20)); } [WorkItem(911913, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/911913")] [Fact] public void UnimplementedInterfaceSquiggleLocation_InterfaceInheritanceScenario10() { // Inherited Interface scenario. string scenarioCode = @" public class ITT : IDerived { void IBase2.method2() { } void IBase3.method3() { } void IDerived.method4() { } } public interface IBase { void method1(); } public interface IBase2 : IBase { void method2(); } public interface IBase3 : IBase { void method3(); } public interface IDerived : IBase2, IBase3 { void method4(); }"; var testAssembly = CreateCompilation(scenarioCode); testAssembly.VerifyDiagnostics( // (2,20): error CS0535: 'ITT' does not implement interface member 'IBase.method1()' // public class ITT : IDerived Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "IDerived").WithArguments("ITT", "IBase.method1()").WithLocation(2, 20)); } [WorkItem(911913, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/911913")] [Fact] public void UnimplementedInterfaceSquiggleLocation_InterfaceInheritanceScenario11() { // Inherited Interface scenario string scenarioCode = @" static class Module1 { public static void Main() { } } interface Ibase { void method1(); } interface Ibase2 { void method2(); } interface Iderived : Ibase { void method3(); } interface Iderived2 : Iderived { void method4(); } class foo : Iderived2, Iderived, Ibase, Ibase2 { void Ibase.method1() { } void Ibase2.method2() { } void Iderived2.method4() { } } "; var testAssembly = CreateCompilation(scenarioCode); testAssembly.VerifyDiagnostics( // (29,24): error CS0535: 'foo' does not implement interface member 'Iderived.method3()' // class foo : Iderived2, Iderived, Ibase, Ibase2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "Iderived").WithArguments("foo", "Iderived.method3()").WithLocation(29, 24)); } [WorkItem(911913, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/911913")] [Fact] public void UnimplementedInterfaceSquiggleLocation_WithPartialClass01() { // partial class - missing method. // each partial implements interface but one is missing method. string scenarioCode = @" public partial class Foo : IBase { void IBase.method1() { } void IBase2.method2() { } } public partial class Foo : IBase2 { } public partial class Foo : IBase3 { } public interface IBase { void method1(); } public interface IBase2 { void method2(); } public interface IBase3 { void method3(); }"; var testAssembly = CreateCompilation(scenarioCode); testAssembly.VerifyDiagnostics( // (15,28): error CS0535: 'Foo' does not implement interface member 'IBase3.method3()' // public partial class Foo : IBase3 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "IBase3").WithArguments("Foo", "IBase3.method3()").WithLocation(15, 28)); } [WorkItem(911913, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/911913")] [Fact] public void UnimplementedInterfaceSquiggleLocation_WithPartialClass02() { // partial class - missing method. diagnostic is reported in correct partial class // one partial class specifically does include any inherited interface string scenarioCode = @" public partial class Foo : IBase, IBase2 { void IBase.method1() { } } public partial class Foo { } public partial class Foo : IBase3 { } public interface IBase { void method1(); } public interface IBase2 { void method2(); } public interface IBase3 { void method3(); }"; var testAssembly = CreateCompilation(scenarioCode); testAssembly.VerifyDiagnostics( // (2,35): error CS0535: 'Foo' does not implement interface member 'IBase2.method2()' // public partial class Foo : IBase, IBase2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "IBase2").WithArguments("Foo", "IBase2.method2()").WithLocation(2, 35), // (13,28): error CS0535: 'Foo' does not implement interface member 'IBase3.method3()' // public partial class Foo : IBase3 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "IBase3").WithArguments("Foo", "IBase3.method3()").WithLocation(13, 28)); } [WorkItem(911913, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/911913")] [Fact] public void UnimplementedInterfaceSquiggleLocation_WithPartialClass03() { // Partial class scenario // One class implements multiple interfaces and is missing method. string scenarioCode = @" public partial class Foo : IBase, IBase2 { void IBase.method1() { } } public partial class Foo : IBase3 { } public interface IBase { void method1(); } public interface IBase2 { void method2(); } public interface IBase3 { void method3(); }"; var testAssembly = CreateCompilation(scenarioCode); testAssembly.VerifyDiagnostics( // (2,35): error CS0535: 'Foo' does not implement interface member 'IBase2.method2()' // public partial class Foo : IBase, IBase2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "IBase2").WithArguments("Foo", "IBase2.method2()").WithLocation(2, 35), // (9,28): error CS0535: 'Foo' does not implement interface member 'IBase3.method3()' // public partial class Foo : IBase3 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "IBase3").WithArguments("Foo", "IBase3.method3()").WithLocation(9, 28) ); } [WorkItem(541466, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541466")] [Fact] public void UseSiteErrorViaAliasTest04() { var testAssembly = CreateCompilation( @" using ClassAlias = Class1; public class Test { void m() { int a = ClassAlias.Class1Foo(); int b = ClassAlias.Class1Foo(); } }", references: new List<MetadataReference>() { TestReferences.SymbolsTests.NoPia.NoPIAGenericsAsm1 }) .VerifyDiagnostics( // (2,20): error CS1769: Type 'System.Collections.Generic.List<FooStruct>' from assembly 'NoPIAGenerics1-Asm1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' cannot be used across assembly boundaries because it has a generic type argument that is an embedded interop type. // using ClassAlias = Class1; Diagnostic(ErrorCode.ERR_GenericsUsedAcrossAssemblies, "Class1").WithArguments("System.Collections.Generic.List<FooStruct>", "NoPIAGenerics1-Asm1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (7,28): error CS1769: Type 'System.Collections.Generic.List<FooStruct>' from assembly 'NoPIAGenerics1-Asm1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' cannot be used across assembly boundaries because it has a generic type argument that is an embedded interop type. // int a = ClassAlias.Class1Foo(); Diagnostic(ErrorCode.ERR_GenericsUsedAcrossAssemblies, "Class1Foo").WithArguments("System.Collections.Generic.List<FooStruct>", "NoPIAGenerics1-Asm1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (8,28): error CS1769: Type 'System.Collections.Generic.List<FooStruct>' from assembly 'NoPIAGenerics1-Asm1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' cannot be used across assembly boundaries because it has a generic type argument that is an embedded interop type. // int b = ClassAlias.Class1Foo(); Diagnostic(ErrorCode.ERR_GenericsUsedAcrossAssemblies, "Class1Foo").WithArguments("System.Collections.Generic.List<FooStruct>", "NoPIAGenerics1-Asm1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null") ); // NOTE: Dev10 errors: // <fine-name>(8,28): error CS0117: 'Class1' does not contain a definition for 'Class1Foo' // <fine-name>(9,28): error CS0117: 'Class1' does not contain a definition for 'Class1Foo' } [WorkItem(541466, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541466")] [Fact] public void UseSiteErrorViaAliasTest05() { var testAssembly = CreateCompilation( @" using ClassAlias = Class1; public class Test { void m() { var a = new ClassAlias(); var b = new ClassAlias(); } }", references: new List<MetadataReference>() { TestReferences.SymbolsTests.NoPia.NoPIAGenericsAsm1 }) .VerifyDiagnostics( // (2,20): error CS1769: Type 'System.Collections.Generic.List<FooStruct>' from assembly 'NoPIAGenerics1-Asm1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' cannot be used across assembly boundaries because it has a generic type argument that is an embedded interop type. // using ClassAlias = Class1; Diagnostic(ErrorCode.ERR_GenericsUsedAcrossAssemblies, "Class1").WithArguments("System.Collections.Generic.List<FooStruct>", "NoPIAGenerics1-Asm1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null") ); // NOTE: Dev10 errors: // <fine-name>(8,17): error CS0143: The type 'Class1' has no constructors defined // <fine-name>(9,17): error CS0143: The type 'Class1' has no constructors defined } [WorkItem(541466, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541466")] [Fact] public void UseSiteErrorViaAliasTest06() { var testAssembly = CreateCompilation( @" using ClassAlias = Class1; public class Test { ClassAlias a = null; ClassAlias b = null; ClassAlias m() { return null; } void m2(ClassAlias p) { } }", references: new List<MetadataReference>() { TestReferences.SymbolsTests.NoPia.NoPIAGenericsAsm1 }) .VerifyDiagnostics( // (2,20): error CS1769: Type 'System.Collections.Generic.List<FooStruct>' from assembly 'NoPIAGenerics1-Asm1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' cannot be used across assembly boundaries because it has a generic type argument that is an embedded interop type. // using ClassAlias = Class1; Diagnostic(ErrorCode.ERR_GenericsUsedAcrossAssemblies, "Class1").WithArguments("System.Collections.Generic.List<FooStruct>", "NoPIAGenerics1-Asm1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (6,16): warning CS0414: The field 'Test.b' is assigned but its value is never used // ClassAlias b = null; Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "b").WithArguments("Test.b"), // (5,16): warning CS0414: The field 'Test.a' is assigned but its value is never used // ClassAlias a = null; Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "a").WithArguments("Test.a") ); // NOTE: Dev10 errors: // <fine-name>(4,16): error CS1772: Type 'Class1' from assembly '...\NoPIAGenerics1-Asm1.dll' cannot be used across assembly boundaries because a type in its inheritance hierarchy has a generic type parameter that is an embedded interop type. // <fine-name>(5,16): error CS1772: Type 'Class1' from assembly '...\NoPIAGenerics1-Asm1.dll' cannot be used across assembly boundaries because a type in its inheritance hierarchy has a generic type parameter that is an embedded interop type. // <fine-name>(6,16): error CS1772: Type 'Class1' from assembly '...\NoPIAGenerics1-Asm1.dll' cannot be used across assembly boundaries because a type in its inheritance hierarchy has a generic type parameter that is an embedded interop type. // <fine-name>(7,10): error CS1772: Type 'Class1' from assembly '...\NoPIAGenerics1-Asm1.dll' cannot be used across assembly boundaries because a type in its inheritance hierarchy has a generic type parameter that is an embedded interop type. } [WorkItem(541466, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541466")] [Fact] public void UseSiteErrorViaAliasTest07() { var testAssembly = CreateCompilation( @" using ClassAlias = Class1; public class Test { void m() { ClassAlias a = null; ClassAlias b = null; System.Console.WriteLine(a); System.Console.WriteLine(b); } }", references: new List<MetadataReference>() { TestReferences.SymbolsTests.NoPia.NoPIAGenericsAsm1 }) .VerifyDiagnostics( // (2,20): error CS1769: Type 'System.Collections.Generic.List<FooStruct>' from assembly 'NoPIAGenerics1-Asm1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' cannot be used across assembly boundaries because it has a generic type argument that is an embedded interop type. // using ClassAlias = Class1; Diagnostic(ErrorCode.ERR_GenericsUsedAcrossAssemblies, "Class1").WithArguments("System.Collections.Generic.List<FooStruct>", "NoPIAGenerics1-Asm1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (9,9): error CS1769: Type 'System.Collections.Generic.List<FooStruct>' from assembly 'NoPIAGenerics1-Asm1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' cannot be used across assembly boundaries because it has a generic type argument that is an embedded interop type. // System.Console.WriteLine(a); Diagnostic(ErrorCode.ERR_GenericsUsedAcrossAssemblies, "System.Console.WriteLine").WithArguments("System.Collections.Generic.List<FooStruct>", "NoPIAGenerics1-Asm1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (10,9): error CS1769: Type 'System.Collections.Generic.List<FooStruct>' from assembly 'NoPIAGenerics1-Asm1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' cannot be used across assembly boundaries because it has a generic type argument that is an embedded interop type. // System.Console.WriteLine(b); Diagnostic(ErrorCode.ERR_GenericsUsedAcrossAssemblies, "System.Console.WriteLine").WithArguments("System.Collections.Generic.List<FooStruct>", "NoPIAGenerics1-Asm1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null")); // NOTE: Dev10 reports NO ERRORS } [WorkItem(948674, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/948674")] [Fact] public void UseSiteErrorViaImplementedInterfaceMember_1() { var source1 = @" using System; using System.Runtime.InteropServices; [assembly: ImportedFromTypeLib(""GeneralPIA.dll"")] [assembly: Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")] public struct ImageMoniker { }"; CSharpCompilation comp1 = CreateCompilationWithMscorlib45(source1, assemblyName: "Pia948674_1"); var source2 = @" public interface IBar { ImageMoniker? Moniker { get; } }"; CSharpCompilation comp2 = CreateCompilationWithMscorlib45(source2, new MetadataReference[] { new CSharpCompilationReference(comp1, embedInteropTypes: true) }, assemblyName: "Bar948674_1"); var source3 = @" public class BarImpl : IBar { public ImageMoniker? Moniker { get { return null; } } }"; CSharpCompilation comp3 = CreateCompilationWithMscorlib45(source3, new MetadataReference[] { new CSharpCompilationReference(comp2), new CSharpCompilationReference(comp1, embedInteropTypes: true) }); comp3.VerifyDiagnostics( // (2,24): error CS1769: Type 'ImageMoniker?' from assembly 'Bar948674_1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' cannot be used across assembly boundaries because it has a generic type argument that is an embedded interop type. // public class BarImpl : IBar Diagnostic(ErrorCode.ERR_GenericsUsedAcrossAssemblies, "IBar").WithArguments("ImageMoniker?", "Bar948674_1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(2, 24) ); comp3 = CreateCompilationWithMscorlib45(source3, new MetadataReference[] { comp2.EmitToImageReference(), comp1.EmitToImageReference().WithEmbedInteropTypes(true) }); comp3.VerifyDiagnostics( // (2,24): error CS1769: Type 'ImageMoniker?' from assembly 'Bar948674_1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' cannot be used across assembly boundaries because it has a generic type argument that is an embedded interop type. // public class BarImpl : IBar Diagnostic(ErrorCode.ERR_GenericsUsedAcrossAssemblies, "IBar").WithArguments("ImageMoniker?", "Bar948674_1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(2, 24), // (2,24): error CS1769: Type 'ImageMoniker?' from assembly 'Bar948674_1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' cannot be used across assembly boundaries because it has a generic type argument that is an embedded interop type. // public class BarImpl : IBar Diagnostic(ErrorCode.ERR_GenericsUsedAcrossAssemblies, "IBar").WithArguments("ImageMoniker?", "Bar948674_1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(2, 24) ); } [WorkItem(948674, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/948674")] [Fact] public void UseSiteErrorViaImplementedInterfaceMember_2() { var source1 = @" using System; using System.Runtime.InteropServices; [assembly: ImportedFromTypeLib(""GeneralPIA.dll"")] [assembly: Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")] public struct ImageMoniker { }"; CSharpCompilation comp1 = CreateCompilationWithMscorlib45(source1, assemblyName: "Pia948674_2"); var source2 = @" public interface IBar { ImageMoniker? Moniker { get; } }"; CSharpCompilation comp2 = CreateCompilationWithMscorlib45(source2, new MetadataReference[] { new CSharpCompilationReference(comp1, embedInteropTypes: true) }, assemblyName: "Bar948674_2"); var source3 = @" public class BarImpl : IBar { ImageMoniker? IBar.Moniker { get { return null; } } }"; CSharpCompilation comp3 = CreateCompilationWithMscorlib45(source3, new MetadataReference[] { new CSharpCompilationReference(comp2), new CSharpCompilationReference(comp1, embedInteropTypes: true) }); comp3.VerifyDiagnostics( // (4,24): error CS0539: 'BarImpl.Moniker' in explicit interface declaration is not a member of interface // ImageMoniker? IBar.Moniker Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "Moniker").WithArguments("BarImpl.Moniker").WithLocation(4, 24), // (2,24): error CS1769: Type 'ImageMoniker?' from assembly 'Bar948674_2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' cannot be used across assembly boundaries because it has a generic type argument that is an embedded interop type. // public class BarImpl : IBar Diagnostic(ErrorCode.ERR_GenericsUsedAcrossAssemblies, "IBar").WithArguments("ImageMoniker?", "Bar948674_2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(2, 24) ); comp3 = CreateCompilationWithMscorlib45(source3, new MetadataReference[] { comp2.EmitToImageReference(), comp1.EmitToImageReference().WithEmbedInteropTypes(true) }); comp3.VerifyDiagnostics( // (4,24): error CS0539: 'BarImpl.Moniker' in explicit interface declaration is not a member of interface // ImageMoniker? IBar.Moniker Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "Moniker").WithArguments("BarImpl.Moniker").WithLocation(4, 24), // (2,24): error CS1769: Type 'ImageMoniker?' from assembly 'Bar948674_2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' cannot be used across assembly boundaries because it has a generic type argument that is an embedded interop type. // public class BarImpl : IBar Diagnostic(ErrorCode.ERR_GenericsUsedAcrossAssemblies, "IBar").WithArguments("ImageMoniker?", "Bar948674_2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(2, 24) ); } [WorkItem(948674, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/948674")] [Fact] public void UseSiteErrorViaImplementedInterfaceMember_3() { var source1 = @" using System; using System.Runtime.InteropServices; [assembly: ImportedFromTypeLib(""GeneralPIA.dll"")] [assembly: Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")] public struct ImageMoniker { }"; CSharpCompilation comp1 = CreateCompilationWithMscorlib45(source1, assemblyName: "Pia948674_3"); var source2 = @" public interface IBar { void SetMoniker(ImageMoniker? moniker); }"; CSharpCompilation comp2 = CreateCompilationWithMscorlib45(source2, new MetadataReference[] { new CSharpCompilationReference(comp1, embedInteropTypes: true) }, assemblyName: "Bar948674_3"); var source3 = @" public class BarImpl : IBar { public void SetMoniker(ImageMoniker? moniker) {} }"; CSharpCompilation comp3 = CreateCompilationWithMscorlib45(source3, new MetadataReference[] { new CSharpCompilationReference(comp2), new CSharpCompilationReference(comp1, embedInteropTypes: true) }); comp3.VerifyDiagnostics( // (2,24): error CS1769: Type 'ImageMoniker?' from assembly 'Bar948674_3, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' cannot be used across assembly boundaries because it has a generic type argument that is an embedded interop type. // public class BarImpl : IBar Diagnostic(ErrorCode.ERR_GenericsUsedAcrossAssemblies, "IBar").WithArguments("ImageMoniker?", "Bar948674_3, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(2, 24) ); comp3 = CreateCompilationWithMscorlib45(source3, new MetadataReference[] { comp2.EmitToImageReference(), comp1.EmitToImageReference().WithEmbedInteropTypes(true) }); comp3.VerifyDiagnostics( // (2,24): error CS1769: Type 'ImageMoniker?' from assembly 'Bar948674_3, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' cannot be used across assembly boundaries because it has a generic type argument that is an embedded interop type. // public class BarImpl : IBar Diagnostic(ErrorCode.ERR_GenericsUsedAcrossAssemblies, "IBar").WithArguments("ImageMoniker?", "Bar948674_3, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(2, 24) ); } [WorkItem(948674, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/948674")] [Fact] public void UseSiteErrorViaImplementedInterfaceMember_4() { var source1 = @" using System; using System.Runtime.InteropServices; [assembly: ImportedFromTypeLib(""GeneralPIA.dll"")] [assembly: Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")] public struct ImageMoniker { }"; CSharpCompilation comp1 = CreateCompilationWithMscorlib45(source1, assemblyName: "Pia948674_4"); var source2 = @" public interface IBar { void SetMoniker(ImageMoniker? moniker); }"; CSharpCompilation comp2 = CreateCompilationWithMscorlib45(source2, new MetadataReference[] { new CSharpCompilationReference(comp1, embedInteropTypes: true) }, assemblyName: "Bar948674_4"); var source3 = @" public class BarImpl : IBar { void IBar.SetMoniker(ImageMoniker? moniker) {} }"; CSharpCompilation comp3 = CreateCompilationWithMscorlib45(source3, new MetadataReference[] { new CSharpCompilationReference(comp2), new CSharpCompilationReference(comp1, embedInteropTypes: true) }); comp3.VerifyDiagnostics( // (4,15): error CS0539: 'BarImpl.SetMoniker(ImageMoniker?)' in explicit interface declaration is not a member of interface // void IBar.SetMoniker(ImageMoniker? moniker) Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "SetMoniker").WithArguments("BarImpl.SetMoniker(ImageMoniker?)").WithLocation(4, 15), // (2,24): error CS1769: Type 'ImageMoniker?' from assembly 'Bar948674_4, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' cannot be used across assembly boundaries because it has a generic type argument that is an embedded interop type. // public class BarImpl : IBar Diagnostic(ErrorCode.ERR_GenericsUsedAcrossAssemblies, "IBar").WithArguments("ImageMoniker?", "Bar948674_4, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(2, 24) ); comp3 = CreateCompilationWithMscorlib45(source3, new MetadataReference[] { comp2.EmitToImageReference(), comp1.EmitToImageReference().WithEmbedInteropTypes(true) }); comp3.VerifyDiagnostics( // (4,15): error CS0539: 'BarImpl.SetMoniker(ImageMoniker?)' in explicit interface declaration is not a member of interface // void IBar.SetMoniker(ImageMoniker? moniker) Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "SetMoniker").WithArguments("BarImpl.SetMoniker(ImageMoniker?)").WithLocation(4, 15), // (2,24): error CS1769: Type 'ImageMoniker?' from assembly 'Bar948674_4, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' cannot be used across assembly boundaries because it has a generic type argument that is an embedded interop type. // public class BarImpl : IBar Diagnostic(ErrorCode.ERR_GenericsUsedAcrossAssemblies, "IBar").WithArguments("ImageMoniker?", "Bar948674_4, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(2, 24) ); } [WorkItem(541246, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541246")] [Fact] public void NamespaceQualifiedGenericTypeName() { var source = @"namespace N { public class A<T> { public static T F; } } class B { static int G = N.A<int>.F; }"; CreateCompilation(source).VerifyDiagnostics(); } [Fact] public void NamespaceQualifiedGenericTypeNameWrongArity() { var source = @"namespace N { public class A<T> { public static T F; } public class B { public static int F; } public class B<T1, T2> { public static System.Tuple<T1, T2> F; } } class C { static int TooMany = N.A<int, int>.F; static int TooFew = N.A.F; static int TooIndecisive = N.B<int>; }"; CreateCompilation(source).VerifyDiagnostics( // (19,28): error CS0305: Using the generic type 'N.A<T>' requires '1' type arguments // Diagnostic(ErrorCode.ERR_BadArity, "A<int, int>").WithArguments("N.A<T>", "type", "1"), // (20,27): error CS0305: Using the generic type 'N.A<T>' requires '1' type arguments // Diagnostic(ErrorCode.ERR_BadArity, "A").WithArguments("N.A<T>", "type", "1"), // (21,34): error CS0308: The non-generic type 'N.B' cannot be used with type arguments // Diagnostic(ErrorCode.ERR_HasNoTypeVars, "B<int>").WithArguments("N.B", "type") ); } [WorkItem(541570, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541570")] [Fact] public void EnumNotMemberInConstructor() { var source = @"enum E { A } class C { public C(E e = E.A) { } public E E { get { return E.A; } } }"; CreateCompilation(source).VerifyDiagnostics(); } [WorkItem(541638, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541638")] [Fact] public void KeywordAsLabelIdentifier() { var source = @"class Program { static void Main(string[] args) { @int1: System.Console.WriteLine(); } }"; CreateCompilation(source).VerifyDiagnostics( // (5,5): warning CS0164: This label has not been referenced // Diagnostic(ErrorCode.WRN_UnreferencedLabel, "@int1")); } [WorkItem(541677, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541677")] [Fact] public void AssignStaticEventToLocalVariable() { var source = @"delegate void Foo(); class driver { public static event Foo e; static void Main(string[] args) { Foo x = e; } }"; CreateCompilation(source).VerifyDiagnostics(); } // Note: The locations for errors on generic methods are // name only, while Dev11 uses name + type parameters. [WorkItem(528743, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528743")] [Fact] public void GenericMethodLocation() { var source = @"interface I { void M1<T>() where T : class; } class C : I { public void M1<T>() { } void M2<T>(this object o) { } sealed void M3<T>() { } internal static virtual void M4<T>() { } }"; CreateCompilation(source).VerifyDiagnostics( // (5,7): error CS1106: Extension method must be defined in a non-generic static class // class C : I Diagnostic(ErrorCode.ERR_BadExtensionAgg, "C").WithLocation(5, 7), // (7,17): error CS0425: The constraints for type parameter 'T' of method 'C.M1<T>()' must match the constraints for type parameter 'T' of interface method 'I.M1<T>()'. Consider using an explicit interface implementation instead. // public void M1<T>() { } Diagnostic(ErrorCode.ERR_ImplBadConstraints, "M1").WithArguments("T", "C.M1<T>()", "T", "I.M1<T>()").WithLocation(7, 17), // (9,17): error CS0238: 'C.M3<T>()' cannot be sealed because it is not an override // sealed void M3<T>() { } Diagnostic(ErrorCode.ERR_SealedNonOverride, "M3").WithArguments("C.M3<T>()").WithLocation(9, 17), // (10,34): error CS0112: A static member cannot be marked as 'virtual' // internal static virtual void M4<T>() { } Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M4").WithArguments("virtual").WithLocation(10, 34) ); } [WorkItem(542391, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542391")] [Fact] public void PartialMethodOptionalParameters() { var source = @"partial class C { partial void M1(object o); partial void M1(object o = null) { } partial void M2(object o = null); partial void M2(object o) { } partial void M3(object o = null); partial void M3(object o = null) { } }"; CreateCompilation(source).VerifyDiagnostics( // (4,28): warning CS1066: The default value specified for parameter 'o' will have no effect because it applies to a member that is used in contexts that do not allow optional arguments // partial void M1(object o = null) { } Diagnostic(ErrorCode.WRN_DefaultValueForUnconsumedLocation, "o").WithArguments("o"), // (8,28): warning CS1066: The default value specified for parameter 'o' will have no effect because it applies to a member that is used in contexts that do not allow optional arguments // partial void M3(object o = null) { } Diagnostic(ErrorCode.WRN_DefaultValueForUnconsumedLocation, "o").WithArguments("o") ); } [Fact] [WorkItem(598043, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/598043")] public void PartialMethodParameterNamesFromDefinition1() { var source = @" partial class C { partial void F(int i); } partial class C { partial void F(int j) { } } "; CompileAndVerify(source, options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.All), symbolValidator: module => { var method = module.GlobalNamespace.GetMember<TypeSymbol>("C").GetMember<MethodSymbol>("F"); Assert.Equal("i", method.Parameters[0].Name); }); } [Fact] [WorkItem(598043, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/598043")] public void PartialMethodParameterNamesFromDefinition2() { var source = @" partial class C { partial void F(int j) { } } partial class C { partial void F(int i); } "; CompileAndVerify(source, options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.All), symbolValidator: module => { var method = module.GlobalNamespace.GetMember<TypeSymbol>("C").GetMember<MethodSymbol>("F"); Assert.Equal("i", method.Parameters[0].Name); }); } /// <summary> /// Handle a mix of parameter errors for default values, /// partial methods, and static parameter type. /// </summary> [Fact] public void ParameterErrorsDefaultPartialMethodStaticType() { var source = @"static class S { } partial class C { partial void M(S s = new A()); partial void M(S s = new B()) { } }"; CreateCompilation(source).VerifyDiagnostics( // (4,18): error CS0721: 'S': static types cannot be used as parameters // partial void M(S s = new A()); Diagnostic(ErrorCode.ERR_ParameterIsStaticClass, "M").WithArguments("S").WithLocation(4, 18), // (5,18): error CS0721: 'S': static types cannot be used as parameters // partial void M(S s = new B()) { } Diagnostic(ErrorCode.ERR_ParameterIsStaticClass, "M").WithArguments("S").WithLocation(5, 18), // (5,30): error CS0246: The type or namespace name 'B' could not be found (are you missing a using directive or an assembly reference?) // partial void M(S s = new B()) { } Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "B").WithArguments("B").WithLocation(5, 30), // (4,30): error CS0246: The type or namespace name 'A' could not be found (are you missing a using directive or an assembly reference?) // partial void M(S s = new A()); Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "A").WithArguments("A").WithLocation(4, 30) ); } [WorkItem(543349, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543349")] [Fact] public void Fixed() { var source = @"class C { unsafe static void M(int[] arg) { fixed (int* ptr = arg) { } fixed (int* ptr = arg) *ptr = 0; fixed (int* ptr = arg) object o = null; } }"; CreateCompilation(source, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (7,32): error CS1023: Embedded statement cannot be a declaration or labeled statement // fixed (int* ptr = arg) object o = null; Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "object o = null;").WithLocation(7, 32), // (7,39): warning CS0219: The variable 'o' is assigned but its value is never used // fixed (int* ptr = arg) object o = null; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "o").WithArguments("o").WithLocation(7, 39) ); } [WorkItem(1040171, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1040171")] [Fact] public void Bug1040171() { const string sourceCode = @" class Program { static void Main(string[] args) { bool c = true; foreach (string s in args) label: c = false; } } "; var compilation = CreateCompilation(sourceCode); compilation.VerifyDiagnostics( // (9,13): error CS1023: Embedded statement cannot be a declaration or labeled statement // label: c = false; Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "label: c = false;").WithLocation(9, 13), // (9,13): warning CS0164: This label has not been referenced // label: c = false; Diagnostic(ErrorCode.WRN_UnreferencedLabel, "label").WithLocation(9, 13), // (6,14): warning CS0219: The variable 'c' is assigned but its value is never used // bool c = true; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "c").WithArguments("c").WithLocation(6, 14)); } [Fact, WorkItem(543426, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543426")] private void NestedInterfaceImplementationWithOuterGenericType() { CompileAndVerify(@" namespace System.ServiceModel { class Pipeline<T> { interface IStage { void Process(T context); } class AsyncStage : IStage { void IStage.Process(T context) { } } } }"); } /// <summary> /// Error types should be allowed as constant types. /// </summary> [Fact] public void ErrorTypeConst() { var source = @"class C { const C1 F1 = 0; const C2 F2 = null; static void M() { const C3 c3 = 0; const C4 c4 = null; } }"; CreateCompilation(source).VerifyDiagnostics( // (3,11): error CS0246: The type or namespace name 'C1' could not be found (are you missing a using directive or an assembly reference?) Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "C1").WithArguments("C1").WithLocation(3, 11), // (4,11): error CS0246: The type or namespace name 'C2' could not be found (are you missing a using directive or an assembly reference?) Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "C2").WithArguments("C2").WithLocation(4, 11), // (7,15): error CS0246: The type or namespace name 'C3' could not be found (are you missing a using directive or an assembly reference?) Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "C3").WithArguments("C3").WithLocation(7, 15), // (8,15): error CS0246: The type or namespace name 'C4' could not be found (are you missing a using directive or an assembly reference?) Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "C4").WithArguments("C4").WithLocation(8, 15)); } [WorkItem(543777, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543777")] [Fact] public void DefaultParameterAtEndOfFile() { var source = @"class C { static void M(object o = null,"; CreateCompilation(source).VerifyDiagnostics( // (3,35): error CS1031: Type expected // static void M(object o = null, Diagnostic(ErrorCode.ERR_TypeExpected, ""), // Cascading: // (3,35): error CS1001: Identifier expected // static void M(object o = null, Diagnostic(ErrorCode.ERR_IdentifierExpected, ""), // (3,35): error CS1026: ) expected // static void M(object o = null, Diagnostic(ErrorCode.ERR_CloseParenExpected, ""), // (3,35): error CS1002: ; expected // static void M(object o = null, Diagnostic(ErrorCode.ERR_SemicolonExpected, ""), // (3,35): error CS1513: } expected // static void M(object o = null, Diagnostic(ErrorCode.ERR_RbraceExpected, ""), // (3,35): error CS1737: Optional parameters must appear after all required parameters // static void M(object o = null, Diagnostic(ErrorCode.ERR_DefaultValueBeforeRequiredValue, ""), // (3,17): error CS0501: 'C.M(object, ?)' must declare a body because it is not // marked abstract, extern, or partial static void M(object o = null, Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "M").WithArguments("C.M(object, ?)")); } [WorkItem(543814, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543814")] [Fact] public void DuplicateNamedArgumentNullLiteral() { var source = @"class C { static void M() { M("""", arg: 0, arg: null); } }"; CreateCompilation(source).VerifyDiagnostics( // (5,9): error CS1501: No overload for method 'M' takes 3 arguments // M("", Diagnostic(ErrorCode.ERR_BadArgCount, "M").WithArguments("M", "3").WithLocation(5, 9)); } [WorkItem(543820, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543820")] [Fact] public void GenericAttributeClassWithMultipleParts() { var source = @"class C<T> { } class C<T> : System.Attribute { }"; CreateCompilation(source).VerifyDiagnostics( // (2,7): error CS0101: The namespace '<global namespace>' already contains a definition for 'C' // class C<T> : System.Attribute { } Diagnostic(ErrorCode.ERR_DuplicateNameInNS, "C").WithArguments("C", "<global namespace>"), // (2,14): error CS0698: A generic type cannot derive from 'System.Attribute' because it is an attribute class // class C<T> : System.Attribute { } Diagnostic(ErrorCode.ERR_GenericDerivingFromAttribute, "System.Attribute").WithArguments("System.Attribute") ); } [WorkItem(543822, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543822")] [Fact] public void InterfaceWithPartialMethodExplicitImplementation() { var source = @"interface I { partial void I.M(); }"; CreateCompilation(source, parseOptions: TestOptions.Regular7, targetFramework: TargetFramework.NetCoreApp).VerifyDiagnostics( // (3,20): error CS0754: A partial method may not explicitly implement an interface method // partial void I.M(); Diagnostic(ErrorCode.ERR_PartialMethodNotExplicit, "M").WithLocation(3, 20), // (3,20): error CS0751: A partial method must be declared within a partial type // partial void I.M(); Diagnostic(ErrorCode.ERR_PartialMethodOnlyInPartialClass, "M").WithLocation(3, 20), // (3,20): error CS8652: The feature 'default interface implementation' is not available in C# 7.0. Please use language version 8.0 or greater. // partial void I.M(); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "M").WithArguments("default interface implementation", "8.0").WithLocation(3, 20), // (3,18): error CS0540: 'I.M()': containing type does not implement interface 'I' // partial void I.M(); Diagnostic(ErrorCode.ERR_ClassDoesntImplementInterface, "I").WithArguments("I.M()", "I").WithLocation(3, 18) ); } [WorkItem(543827, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543827")] [Fact] public void StructConstructor() { var source = @"struct S { private readonly object x; private readonly object y; S(object x, object y) { try { this.x = x; } finally { this.y = y; } } S(S o) : this(o.x, o.y) {} }"; CreateCompilation(source).VerifyDiagnostics(); } [WorkItem(543827, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543827")] [Fact] public void StructVersusTryFinally() { var source = @"struct S { private object x; private object y; static void M() { S s1; try { s1.x = null; } finally { s1.y = null; } S s2 = s1; s1.x = s1.y; s1.y = s1.x; } }"; CreateCompilation(source).VerifyDiagnostics(); } [WorkItem(544513, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544513")] [Fact()] public void AnonTypesPropSameNameDiffType() { var source = @"public class Test { public static void Main() { var p1 = new { Price = 495.00 }; var p2 = new { Price = ""36.50"" }; p1 = p2; } }"; CreateCompilation(source).VerifyDiagnostics( // (8,14): error CS0029: Cannot implicitly convert type 'AnonymousType#1' to 'AnonymousType#2' // p1 = p2; Diagnostic(ErrorCode.ERR_NoImplicitConv, "p2").WithArguments("<anonymous type: string Price>", "<anonymous type: double Price>")); } [WorkItem(545869, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545869")] [Fact] public void TestSealedOverriddenMembers() { CompileAndVerify( @"using System; internal abstract class Base { public virtual int Property { get { return 0; } protected set { } } protected virtual event EventHandler Event { add { } remove { } } protected abstract void Method(); } internal sealed class Derived : Base { public override int Property { get { return 1; } protected set { } } protected override event EventHandler Event; protected override void Method() { } void UseEvent() { Event(null, null); } } internal sealed class Derived2 : Base { public override int Property { get; protected set; } protected override event EventHandler Event { add { } remove { } } protected override void Method() { } } class Program { static void Main() { } }").VerifyDiagnostics(); } [Fact, WorkItem(1068547, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1068547")] public void Bug1068547_01() { var source = @" class Program { [System.Diagnostics.DebuggerDisplay(this)] static void Main(string[] args) { } }"; var comp = CreateCompilation(source); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var node = tree.GetRoot().DescendantNodes().Where(n => n.IsKind(SyntaxKind.ThisExpression)).Cast<ThisExpressionSyntax>().Single(); var symbolInfo = model.GetSymbolInfo(node); Assert.Null(symbolInfo.Symbol); Assert.Equal(CandidateReason.NotReferencable, symbolInfo.CandidateReason); } [Fact, WorkItem(1068547, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1068547")] public void Bug1068547_02() { var source = @" [System.Diagnostics.DebuggerDisplay(this)] "; var comp = CreateCompilation(source); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var node = tree.GetRoot().DescendantNodes().Where(n => n.IsKind(SyntaxKind.ThisExpression)).Cast<ThisExpressionSyntax>().Single(); var symbolInfo = model.GetSymbolInfo(node); Assert.Null(symbolInfo.Symbol); Assert.Equal(CandidateReason.NotReferencable, symbolInfo.CandidateReason); } [Fact] public void RefReturningDelegateCreation() { var text = @" delegate ref int D(); class C { int field = 0; ref int M() { return ref field; } void Test() { new D(M)(); } } "; CreateCompilationWithMscorlib45(text).VerifyDiagnostics(); } [Fact] public void RefReturningDelegateCreationBad() { var text = @" delegate ref int D(); class C { int field = 0; int M() { return field; } void Test() { new D(M)(); } } "; CreateCompilationWithMscorlib45(text, parseOptions: TestOptions.WithoutImprovedOverloadCandidates).VerifyDiagnostics( // (15,15): error CS8189: Ref mismatch between 'C.M()' and delegate 'D' // new D(M)(); Diagnostic(ErrorCode.ERR_DelegateRefMismatch, "M").WithArguments("C.M()", "D").WithLocation(15, 15) ); CreateCompilationWithMscorlib45(text).VerifyDiagnostics( // (15,15): error CS8189: Ref mismatch between 'C.M()' and delegate 'D' // new D(M)(); Diagnostic(ErrorCode.ERR_DelegateRefMismatch, "M").WithArguments("C.M()", "D").WithLocation(15, 15) ); } [Fact] public void RefReturningDelegateArgument() { var text = @" delegate ref int D(); class C { int field = 0; ref int M() { return ref field; } void M(D d) { } void Test() { M(M); } } "; CreateCompilationWithMscorlib45(text).VerifyDiagnostics(); } [Fact] public void RefReturningDelegateArgumentBad() { var text = @" delegate ref int D(); class C { int field = 0; int M() { return field; } void M(D d) { } void Test() { M(M); } } "; CreateCompilationWithMscorlib45(text, parseOptions: TestOptions.WithoutImprovedOverloadCandidates).VerifyDiagnostics( // (19,11): error CS8189: Ref mismatch between 'C.M()' and delegate 'D' // M(M); Diagnostic(ErrorCode.ERR_DelegateRefMismatch, "M").WithArguments("C.M()", "D").WithLocation(19, 11) ); CreateCompilationWithMscorlib45(text).VerifyDiagnostics( // (19,11): error CS8189: Ref mismatch between 'C.M()' and delegate 'D' // M(M); Diagnostic(ErrorCode.ERR_DelegateRefMismatch, "M").WithArguments("C.M()", "D").WithLocation(19, 11) ); } [Fact, WorkItem(1078958, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1078958")] public void Bug1078958() { const string source = @" class C { static void Foo<T>() { T(); } static void T() { } }"; CreateCompilation(source).VerifyDiagnostics( // (6,9): error CS0119: 'T' is a type, which is not valid in the given context // T(); Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type").WithLocation(6, 9)); } [Fact, WorkItem(1078958, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1078958")] public void Bug1078958_2() { const string source = @" class C { static void Foo<T>() { T<T>(); } static void T() { } static void T<U>() { } }"; CreateCompilation(source).VerifyDiagnostics(); } [Fact, WorkItem(1078961, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1078961")] public void Bug1078961() { const string source = @" class C { const int T = 42; static void Foo<T>(int x = T) { System.Console.Write(x); } static void Main() { Foo<object>(); } }"; CompileAndVerify(source, expectedOutput: "42"); } [Fact, WorkItem(1078961, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1078961")] public void Bug1078961_2() { const string source = @" class A : System.Attribute { public A(int i) { } } class C { const int T = 42; static void Foo<T>([A(T)] int x) { } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); var c = comp.GlobalNamespace.GetTypeMembers("C").Single(); var t = (FieldSymbol)c.GetMembers("T").Single(); var foo = (MethodSymbol)c.GetMembers("Foo").Single(); var x = foo.Parameters[0]; var a = x.GetAttributes()[0]; var i = a.ConstructorArguments.Single(); Assert.Equal((int)i.Value, (int)t.ConstantValue); } [Fact, WorkItem(1078961, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1078961")] public void Bug1078961_3() { const string source = @" class A : System.Attribute { public A(int i) { } } class C { const int T = 42; [A(T)] static void Foo<T>(int x) { } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); var c = comp.GlobalNamespace.GetTypeMembers("C").Single(); var t = (FieldSymbol)c.GetMembers("T").Single(); var foo = (MethodSymbol)c.GetMembers("Foo").Single(); var a = foo.GetAttributes()[0]; var i = a.ConstructorArguments.Single(); Assert.Equal((int)i.Value, (int)t.ConstantValue); } [Fact, WorkItem(1078961, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1078961")] public void Bug1078961_4() { const string source = @" class A : System.Attribute { public A(int i) { } } class C { const int T = 42; static void Foo<[A(T)] T>(int x) { } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); var c = comp.GlobalNamespace.GetTypeMembers("C").Single(); var t = (FieldSymbol)c.GetMembers("T").Single(); var foo = (MethodSymbol)c.GetMembers("Foo").Single(); var tt = foo.TypeParameters[0]; var a = tt.GetAttributes()[0]; var i = a.ConstructorArguments.Single(); Assert.Equal((int)i.Value, (int)t.ConstantValue); } [Fact, WorkItem(1078961, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1078961")] public void Bug1078961_5() { const string source = @" class C { class T { } static void Foo<T>(T x = default(T)) { System.Console.Write((object)x == null); } static void Main() { Foo<object>(); } }"; CompileAndVerify(source, expectedOutput: "True"); } [Fact, WorkItem(3096, "https://github.com/dotnet/roslyn/issues/3096")] public void CastToDelegate_01() { var sourceText = @"namespace NS { public static class A { public delegate void Action(); public static void M() { RunAction(A.B<string>.M0); RunAction((Action)A.B<string>.M1); } private static void RunAction(Action action) { } private class B<T> { public static void M0() { } public static void M1() { } } } }"; var compilation = CreateCompilation(sourceText, options: TestOptions.DebugDll); compilation.VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var identifierNameM0 = tree .GetRoot() .DescendantNodes() .OfType<IdentifierNameSyntax>() .First(x => x.Parent.IsKind(SyntaxKind.SimpleMemberAccessExpression) && x.Identifier.ValueText.Equals("M0")); Assert.Equal("A.B<string>.M0", identifierNameM0.Parent.ToString()); var m0Symbol = model.GetSymbolInfo(identifierNameM0); Assert.Equal("void NS.A.B<System.String>.M0()", m0Symbol.Symbol.ToTestDisplayString()); Assert.Equal(CandidateReason.None, m0Symbol.CandidateReason); var identifierNameM1 = tree .GetRoot() .DescendantNodes() .OfType<IdentifierNameSyntax>() .First(x => x.Parent.IsKind(SyntaxKind.SimpleMemberAccessExpression) && x.Identifier.ValueText.Equals("M1")); Assert.Equal("A.B<string>.M1", identifierNameM1.Parent.ToString()); var m1Symbol = model.GetSymbolInfo(identifierNameM1); Assert.Equal("void NS.A.B<System.String>.M1()", m1Symbol.Symbol.ToTestDisplayString()); Assert.Equal(CandidateReason.None, m1Symbol.CandidateReason); } [Fact, WorkItem(3096, "https://github.com/dotnet/roslyn/issues/3096")] public void CastToDelegate_02() { var sourceText = @" class A { public delegate void MyDelegate<T>(T a); public void Test() { UseMyDelegate((MyDelegate<int>)MyMethod); UseMyDelegate((MyDelegate<long>)MyMethod); UseMyDelegate((MyDelegate<float>)MyMethod); UseMyDelegate((MyDelegate<double>)MyMethod); } private void UseMyDelegate<T>(MyDelegate<T> f) { } private static void MyMethod(int a) { } private static void MyMethod(long a) { } private static void MyMethod(float a) { } private static void MyMethod(double a) { } }"; var compilation = CreateCompilation(sourceText, options: TestOptions.DebugDll); compilation.VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var identifiers = tree .GetRoot() .DescendantNodes() .OfType<IdentifierNameSyntax>() .Where(x => x.Identifier.ValueText.Equals("MyMethod")).ToArray(); Assert.Equal(4, identifiers.Length); Assert.Equal("(MyDelegate<int>)MyMethod", identifiers[0].Parent.ToString()); Assert.Equal("void A.MyMethod(System.Int32 a)", model.GetSymbolInfo(identifiers[0]).Symbol.ToTestDisplayString()); Assert.Equal("(MyDelegate<long>)MyMethod", identifiers[1].Parent.ToString()); Assert.Equal("void A.MyMethod(System.Int64 a)", model.GetSymbolInfo(identifiers[1]).Symbol.ToTestDisplayString()); Assert.Equal("(MyDelegate<float>)MyMethod", identifiers[2].Parent.ToString()); Assert.Equal("void A.MyMethod(System.Single a)", model.GetSymbolInfo(identifiers[2]).Symbol.ToTestDisplayString()); Assert.Equal("(MyDelegate<double>)MyMethod", identifiers[3].Parent.ToString()); Assert.Equal("void A.MyMethod(System.Double a)", model.GetSymbolInfo(identifiers[3]).Symbol.ToTestDisplayString()); } [Fact, WorkItem(3096, "https://github.com/dotnet/roslyn/issues/3096")] public void CastToDelegate_03() { var sourceText = @"namespace NS { public static class A { public delegate void Action(); public static void M() { var b = new A.B<string>(); RunAction(b.M0); RunAction((Action)b.M1); } private static void RunAction(Action action) { } public class B<T> { } public static void M0<T>(this B<T> x) { } public static void M1<T>(this B<T> x) { } } }"; var compilation = CreateCompilationWithMscorlib40AndSystemCore(sourceText, options: TestOptions.DebugDll); compilation.VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var identifierNameM0 = tree .GetRoot() .DescendantNodes() .OfType<IdentifierNameSyntax>() .First(x => x.Parent.IsKind(SyntaxKind.SimpleMemberAccessExpression) && x.Identifier.ValueText.Equals("M0")); Assert.Equal("b.M0", identifierNameM0.Parent.ToString()); var m0Symbol = model.GetSymbolInfo(identifierNameM0); Assert.Equal("void NS.A.B<System.String>.M0<System.String>()", m0Symbol.Symbol.ToTestDisplayString()); Assert.Equal(CandidateReason.None, m0Symbol.CandidateReason); var identifierNameM1 = tree .GetRoot() .DescendantNodes() .OfType<IdentifierNameSyntax>() .First(x => x.Parent.IsKind(SyntaxKind.SimpleMemberAccessExpression) && x.Identifier.ValueText.Equals("M1")); Assert.Equal("b.M1", identifierNameM1.Parent.ToString()); var m1Symbol = model.GetSymbolInfo(identifierNameM1); Assert.Equal("void NS.A.B<System.String>.M1<System.String>()", m1Symbol.Symbol.ToTestDisplayString()); Assert.Equal(CandidateReason.None, m1Symbol.CandidateReason); } [Fact, WorkItem(5170, "https://github.com/dotnet/roslyn/issues/5170")] public void TypeOfBinderParameter() { var sourceText = @" using System.Linq; using System.Text; public static class LazyToStringExtension { public static string LazyToString<T>(this T obj) where T : class { StringBuilder sb = new StringBuilder(); typeof(T) .GetProperties(System.Reflection.BindingFlags.Public) .Select(x => x.GetValue(obj)) } }"; var compilation = CreateCompilationWithMscorlib40(sourceText, new[] { TestMetadata.Net40.SystemCore }, options: TestOptions.DebugDll); compilation.VerifyDiagnostics( // (12,42): error CS1002: ; expected // .Select(x => x.GetValue(obj)) Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(12, 42), // (12,28): error CS1501: No overload for method 'GetValue' takes 1 arguments // .Select(x => x.GetValue(obj)) Diagnostic(ErrorCode.ERR_BadArgCount, "GetValue").WithArguments("GetValue", "1").WithLocation(12, 28), // (7,26): error CS0161: 'LazyToStringExtension.LazyToString<T>(T)': not all code paths return a value // public static string LazyToString<T>(this T obj) where T : class Diagnostic(ErrorCode.ERR_ReturnExpected, "LazyToString").WithArguments("LazyToStringExtension.LazyToString<T>(T)").WithLocation(7, 26)); var tree = compilation.SyntaxTrees[0]; var model = compilation.GetSemanticModel(tree); var node = tree.GetRoot().DescendantNodes().Where(n => n.IsKind(SyntaxKind.SimpleLambdaExpression)).Single(); var param = node.ChildNodes().Where(n => n.IsKind(SyntaxKind.Parameter)).Single(); Assert.Equal("System.Reflection.PropertyInfo x", model.GetDeclaredSymbol(param).ToTestDisplayString()); } [Fact, WorkItem(7520, "https://github.com/dotnet/roslyn/issues/7520")] public void DelegateCreationWithIncompleteLambda() { var source = @" using System; class C { public void F() { var x = new Action<int>(i => i. } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (7,40): error CS1001: Identifier expected // var x = new Action<int>(i => i. Diagnostic(ErrorCode.ERR_IdentifierExpected, "").WithLocation(7, 40), // (7,40): error CS1026: ) expected // var x = new Action<int>(i => i. Diagnostic(ErrorCode.ERR_CloseParenExpected, "").WithLocation(7, 40), // (7,40): error CS1002: ; expected // var x = new Action<int>(i => i. Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(7, 40), // (7,38): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement // var x = new Action<int>(i => i. Diagnostic(ErrorCode.ERR_IllegalStatement, @"i. ").WithLocation(7, 38) ); 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(7520, "https://github.com/dotnet/roslyn/issues/7520")] public void ImplicitDelegateCreationWithIncompleteLambda() { var source = @" using System; class C { public void F() { Action<int> x = i => i. } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (7,32): error CS1001: Identifier expected // Action<int> x = i => i. Diagnostic(ErrorCode.ERR_IdentifierExpected, "").WithLocation(7, 32), // (7,32): error CS1002: ; expected // Action<int> x = i => i. Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(7, 32), // (7,30): 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, 30) ); 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(5128, "https://github.com/dotnet/roslyn/issues/5128")] public void GetMemberGroupInsideIncompleteLambda_01() { var source = @" using System; using System.Threading.Tasks; public delegate Task RequestDelegate(HttpContext context); public class AuthenticationResult { } public abstract class AuthenticationManager { public abstract Task<AuthenticationResult> AuthenticateAsync(string authenticationScheme); } public abstract class HttpContext { public abstract AuthenticationManager Authentication { get; } } interface IApplicationBuilder { IApplicationBuilder Use(Func<RequestDelegate, RequestDelegate> middleware); } static class IApplicationBuilderExtensions { public static IApplicationBuilder Use(this IApplicationBuilder app, Func<HttpContext, Func<Task>, Task> middleware) { return app; } } class C { void M(IApplicationBuilder app) { app.Use(async (ctx, next) => { await ctx.Authentication.AuthenticateAsync(); }); } } "; var comp = CreateCompilationWithMscorlib40(source, new[] { TestMetadata.Net40.SystemCore }); comp.VerifyDiagnostics( // (41,38): error CS7036: There is no argument given that corresponds to the required formal parameter 'authenticationScheme' of 'AuthenticationManager.AuthenticateAsync(string)' // await ctx.Authentication.AuthenticateAsync(); Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "AuthenticateAsync").WithArguments("authenticationScheme", "AuthenticationManager.AuthenticateAsync(string)").WithLocation(38, 38) ); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var node1 = tree.GetRoot().DescendantNodes().Where(n => n.IsKind(SyntaxKind.IdentifierName) && ((IdentifierNameSyntax)n).Identifier.ValueText == "Use").Single().Parent; Assert.Equal("app.Use", node1.ToString()); var group1 = model.GetMemberGroup(node1); Assert.Equal(2, group1.Length); Assert.Equal("IApplicationBuilder IApplicationBuilder.Use(System.Func<RequestDelegate, RequestDelegate> middleware)", group1[0].ToTestDisplayString()); Assert.Equal("IApplicationBuilder IApplicationBuilder.Use(System.Func<HttpContext, System.Func<System.Threading.Tasks.Task>, System.Threading.Tasks.Task> middleware)", group1[1].ToTestDisplayString()); var symbolInfo1 = model.GetSymbolInfo(node1); Assert.Null(symbolInfo1.Symbol); Assert.Equal(1, symbolInfo1.CandidateSymbols.Length); Assert.Equal("IApplicationBuilder IApplicationBuilder.Use(System.Func<RequestDelegate, RequestDelegate> middleware)", symbolInfo1.CandidateSymbols.Single().ToTestDisplayString()); Assert.Equal(CandidateReason.OverloadResolutionFailure, symbolInfo1.CandidateReason); var node = tree.GetRoot().DescendantNodes().Where(n => n.IsKind(SyntaxKind.IdentifierName) && ((IdentifierNameSyntax)n).Identifier.ValueText == "AuthenticateAsync").Single().Parent; Assert.Equal("ctx.Authentication.AuthenticateAsync", node.ToString()); var group = model.GetMemberGroup(node); Assert.Equal("System.Threading.Tasks.Task<AuthenticationResult> AuthenticationManager.AuthenticateAsync(System.String authenticationScheme)", group.Single().ToTestDisplayString()); } [Fact, WorkItem(5128, "https://github.com/dotnet/roslyn/issues/5128")] public void GetMemberGroupInsideIncompleteLambda_02() { var source = @" using System; using System.Threading.Tasks; public delegate Task RequestDelegate(HttpContext context); public class AuthenticationResult { } public abstract class AuthenticationManager { public abstract Task<AuthenticationResult> AuthenticateAsync(string authenticationScheme); } public abstract class HttpContext { public abstract AuthenticationManager Authentication { get; } } interface IApplicationBuilder { IApplicationBuilder Use(Func<HttpContext, Func<Task>, Task> middleware); } static class IApplicationBuilderExtensions { public static IApplicationBuilder Use(this IApplicationBuilder app, Func<RequestDelegate, RequestDelegate> middleware) { return app; } } class C { void M(IApplicationBuilder app) { app.Use(async (ctx, next) => { await ctx.Authentication.AuthenticateAsync(); }); } } "; var comp = CreateCompilationWithMscorlib40(source, new[] { TestMetadata.Net40.SystemCore }); comp.VerifyDiagnostics( // (41,38): error CS7036: There is no argument given that corresponds to the required formal parameter 'authenticationScheme' of 'AuthenticationManager.AuthenticateAsync(string)' // await ctx.Authentication.AuthenticateAsync(); Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "AuthenticateAsync").WithArguments("authenticationScheme", "AuthenticationManager.AuthenticateAsync(string)").WithLocation(38, 38) ); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var node1 = tree.GetRoot().DescendantNodes().Where(n => n.IsKind(SyntaxKind.IdentifierName) && ((IdentifierNameSyntax)n).Identifier.ValueText == "Use").Single().Parent; Assert.Equal("app.Use", node1.ToString()); var group1 = model.GetMemberGroup(node1); Assert.Equal(2, group1.Length); Assert.Equal("IApplicationBuilder IApplicationBuilder.Use(System.Func<HttpContext, System.Func<System.Threading.Tasks.Task>, System.Threading.Tasks.Task> middleware)", group1[0].ToTestDisplayString()); Assert.Equal("IApplicationBuilder IApplicationBuilder.Use(System.Func<RequestDelegate, RequestDelegate> middleware)", group1[1].ToTestDisplayString()); var symbolInfo1 = model.GetSymbolInfo(node1); Assert.Null(symbolInfo1.Symbol); Assert.Equal(1, symbolInfo1.CandidateSymbols.Length); Assert.Equal("IApplicationBuilder IApplicationBuilder.Use(System.Func<HttpContext, System.Func<System.Threading.Tasks.Task>, System.Threading.Tasks.Task> middleware)", symbolInfo1.CandidateSymbols.Single().ToTestDisplayString()); Assert.Equal(CandidateReason.OverloadResolutionFailure, symbolInfo1.CandidateReason); var node = tree.GetRoot().DescendantNodes().Where(n => n.IsKind(SyntaxKind.IdentifierName) && ((IdentifierNameSyntax)n).Identifier.ValueText == "AuthenticateAsync").Single().Parent; Assert.Equal("ctx.Authentication.AuthenticateAsync", node.ToString()); var group = model.GetMemberGroup(node); Assert.Equal("System.Threading.Tasks.Task<AuthenticationResult> AuthenticationManager.AuthenticateAsync(System.String authenticationScheme)", group.Single().ToTestDisplayString()); } [Fact, WorkItem(5128, "https://github.com/dotnet/roslyn/issues/5128")] public void GetMemberGroupInsideIncompleteLambda_03() { var source = @" using System; using System.Threading.Tasks; public delegate Task RequestDelegate(HttpContext context); public class AuthenticationResult { } public abstract class AuthenticationManager { public abstract Task<AuthenticationResult> AuthenticateAsync(string authenticationScheme); } public abstract class HttpContext { public abstract AuthenticationManager Authentication { get; } } interface IApplicationBuilder { IApplicationBuilder Use(Func<RequestDelegate, RequestDelegate> middleware); IApplicationBuilder Use(Func<HttpContext, Func<Task>, Task> middleware); } class C { void M(IApplicationBuilder app) { app.Use(async (ctx, next) => { await ctx.Authentication.AuthenticateAsync(); }); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (41,38): error CS7036: There is no argument given that corresponds to the required formal parameter 'authenticationScheme' of 'AuthenticationManager.AuthenticateAsync(string)' // await ctx.Authentication.AuthenticateAsync(); Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "AuthenticateAsync").WithArguments("authenticationScheme", "AuthenticationManager.AuthenticateAsync(string)").WithLocation(31, 38) ); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var node1 = tree.GetRoot().DescendantNodes().Where(n => n.IsKind(SyntaxKind.IdentifierName) && ((IdentifierNameSyntax)n).Identifier.ValueText == "Use").Single().Parent; Assert.Equal("app.Use", node1.ToString()); var group1 = model.GetMemberGroup(node1); Assert.Equal(2, group1.Length); Assert.Equal("IApplicationBuilder IApplicationBuilder.Use(System.Func<RequestDelegate, RequestDelegate> middleware)", group1[0].ToTestDisplayString()); Assert.Equal("IApplicationBuilder IApplicationBuilder.Use(System.Func<HttpContext, System.Func<System.Threading.Tasks.Task>, System.Threading.Tasks.Task> middleware)", group1[1].ToTestDisplayString()); var symbolInfo1 = model.GetSymbolInfo(node1); Assert.Null(symbolInfo1.Symbol); Assert.Equal(2, symbolInfo1.CandidateSymbols.Length); Assert.Equal("IApplicationBuilder IApplicationBuilder.Use(System.Func<RequestDelegate, RequestDelegate> middleware)", symbolInfo1.CandidateSymbols[0].ToTestDisplayString()); Assert.Equal("IApplicationBuilder IApplicationBuilder.Use(System.Func<HttpContext, System.Func<System.Threading.Tasks.Task>, System.Threading.Tasks.Task> middleware)", symbolInfo1.CandidateSymbols[1].ToTestDisplayString()); Assert.Equal(CandidateReason.OverloadResolutionFailure, symbolInfo1.CandidateReason); var node = tree.GetRoot().DescendantNodes().Where(n => n.IsKind(SyntaxKind.IdentifierName) && ((IdentifierNameSyntax)n).Identifier.ValueText == "AuthenticateAsync").Single().Parent; Assert.Equal("ctx.Authentication.AuthenticateAsync", node.ToString()); var group = model.GetMemberGroup(node); Assert.Equal("System.Threading.Tasks.Task<AuthenticationResult> AuthenticationManager.AuthenticateAsync(System.String authenticationScheme)", group.Single().ToTestDisplayString()); } [Fact, WorkItem(5128, "https://github.com/dotnet/roslyn/issues/5128")] public void GetMemberGroupInsideIncompleteLambda_04() { var source = @" using System; using System.Threading.Tasks; public delegate Task RequestDelegate(HttpContext context); public class AuthenticationResult { } public abstract class AuthenticationManager { public abstract Task<AuthenticationResult> AuthenticateAsync(string authenticationScheme); } public abstract class HttpContext { public abstract AuthenticationManager Authentication { get; } } interface IApplicationBuilder { } static class IApplicationBuilderExtensions { public static IApplicationBuilder Use(this IApplicationBuilder app, Func<RequestDelegate, RequestDelegate> middleware) { return app; } public static IApplicationBuilder Use(this IApplicationBuilder app, Func<HttpContext, Func<Task>, Task> middleware) { return app; } } class C { void M(IApplicationBuilder app) { app.Use(async (ctx, next) => { await ctx.Authentication.AuthenticateAsync(); }); } } "; var comp = CreateCompilationWithMscorlib40(source, new[] { TestMetadata.Net40.SystemCore }); comp.VerifyDiagnostics( // (41,38): error CS7036: There is no argument given that corresponds to the required formal parameter 'authenticationScheme' of 'AuthenticationManager.AuthenticateAsync(string)' // await ctx.Authentication.AuthenticateAsync(); Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "AuthenticateAsync").WithArguments("authenticationScheme", "AuthenticationManager.AuthenticateAsync(string)").WithLocation(42, 38) ); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var node1 = tree.GetRoot().DescendantNodes().Where(n => n.IsKind(SyntaxKind.IdentifierName) && ((IdentifierNameSyntax)n).Identifier.ValueText == "Use").Single().Parent; Assert.Equal("app.Use", node1.ToString()); var group1 = model.GetMemberGroup(node1); Assert.Equal(2, group1.Length); Assert.Equal("IApplicationBuilder IApplicationBuilder.Use(System.Func<RequestDelegate, RequestDelegate> middleware)", group1[0].ToTestDisplayString()); Assert.Equal("IApplicationBuilder IApplicationBuilder.Use(System.Func<HttpContext, System.Func<System.Threading.Tasks.Task>, System.Threading.Tasks.Task> middleware)", group1[1].ToTestDisplayString()); var symbolInfo1 = model.GetSymbolInfo(node1); Assert.Null(symbolInfo1.Symbol); Assert.Equal(2, symbolInfo1.CandidateSymbols.Length); Assert.Equal("IApplicationBuilder IApplicationBuilder.Use(System.Func<RequestDelegate, RequestDelegate> middleware)", symbolInfo1.CandidateSymbols[0].ToTestDisplayString()); Assert.Equal("IApplicationBuilder IApplicationBuilder.Use(System.Func<HttpContext, System.Func<System.Threading.Tasks.Task>, System.Threading.Tasks.Task> middleware)", symbolInfo1.CandidateSymbols[1].ToTestDisplayString()); Assert.Equal(CandidateReason.OverloadResolutionFailure, symbolInfo1.CandidateReason); var node = tree.GetRoot().DescendantNodes().Where(n => n.IsKind(SyntaxKind.IdentifierName) && ((IdentifierNameSyntax)n).Identifier.ValueText == "AuthenticateAsync").Single().Parent; Assert.Equal("ctx.Authentication.AuthenticateAsync", node.ToString()); var group = model.GetMemberGroup(node); Assert.Equal("System.Threading.Tasks.Task<AuthenticationResult> AuthenticationManager.AuthenticateAsync(System.String authenticationScheme)", group.Single().ToTestDisplayString()); } [Fact, WorkItem(7101, "https://github.com/dotnet/roslyn/issues/7101")] public void UsingStatic_01() { var source = @" using System; using static ClassWithNonStaticMethod; using static Extension1; class Program { static void Main(string[] args) { var instance = new Program(); instance.NonStaticMethod(); } private void NonStaticMethod() { MathMin(0, 1); MathMax(0, 1); MathMax2(0, 1); int x; x = F1; x = F2; x.MathMax2(3); } } class ClassWithNonStaticMethod { public static int MathMax(int a, int b) { return Math.Max(a, b); } public int MathMin(int a, int b) { return Math.Min(a, b); } public int F2 = 0; } static class Extension1 { public static int MathMax2(this int a, int b) { return Math.Max(a, b); } public static int F1 = 0; } static class Extension2 { public static int MathMax3(this int a, int b) { return Math.Max(a, b); } } "; var comp = CreateCompilationWithMscorlib45(source); comp.VerifyDiagnostics( // (16,9): error CS0103: The name 'MathMin' does not exist in the current context // MathMin(0, 1); Diagnostic(ErrorCode.ERR_NameNotInContext, "MathMin").WithArguments("MathMin").WithLocation(16, 9), // (18,9): error CS0103: The name 'MathMax2' does not exist in the current context // MathMax2(0, 1); Diagnostic(ErrorCode.ERR_NameNotInContext, "MathMax2").WithArguments("MathMax2").WithLocation(18, 9), // (22,13): error CS0103: The name 'F2' does not exist in the current context // x = F2; Diagnostic(ErrorCode.ERR_NameNotInContext, "F2").WithArguments("F2").WithLocation(22, 13) ); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var node1 = tree.GetRoot().DescendantNodes().Where(n => n.IsKind(SyntaxKind.IdentifierName) && ((IdentifierNameSyntax)n).Identifier.ValueText == "MathMin").Single().Parent; Assert.Equal("MathMin(0, 1)", node1.ToString()); var names = model.LookupNames(node1.SpanStart); Assert.False(names.Contains("MathMin")); Assert.True(names.Contains("MathMax")); Assert.True(names.Contains("F1")); Assert.False(names.Contains("F2")); Assert.False(names.Contains("MathMax2")); Assert.False(names.Contains("MathMax3")); Assert.True(model.LookupSymbols(node1.SpanStart, name: "MathMin").IsEmpty); Assert.Equal(1, model.LookupSymbols(node1.SpanStart, name: "MathMax").Length); Assert.Equal(1, model.LookupSymbols(node1.SpanStart, name: "F1").Length); Assert.True(model.LookupSymbols(node1.SpanStart, name: "F2").IsEmpty); Assert.True(model.LookupSymbols(node1.SpanStart, name: "MathMax2").IsEmpty); Assert.True(model.LookupSymbols(node1.SpanStart, name: "MathMax3").IsEmpty); var symbols = model.LookupSymbols(node1.SpanStart); Assert.False(symbols.Where(s => s.Name == "MathMin").Any()); Assert.True(symbols.Where(s => s.Name == "MathMax").Any()); Assert.True(symbols.Where(s => s.Name == "F1").Any()); Assert.False(symbols.Where(s => s.Name == "F2").Any()); Assert.False(symbols.Where(s => s.Name == "MathMax2").Any()); Assert.False(symbols.Where(s => s.Name == "MathMax3").Any()); } [Fact, WorkItem(30726, "https://github.com/dotnet/roslyn/issues/30726")] public void UsingStaticGenericConstraint() { var code = @" using static Test<System.String>; public static class Test<T> where T : struct { } "; CreateCompilationWithMscorlib45(code).VerifyDiagnostics( // (2,1): hidden CS8019: Unnecessary using directive. // using static Test<System.String>; Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using static Test<System.String>;").WithLocation(2, 1), // (2,14): 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 'Test<T>' // using static Test<System.String>; Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "Test<System.String>").WithArguments("Test<T>", "T", "string").WithLocation(2, 14)); } [Fact, WorkItem(30726, "https://github.com/dotnet/roslyn/issues/30726")] public void UsingStaticGenericConstraintNestedType() { var code = @" using static A<A<int>[]>.B; class A<T> where T : class { internal static class B { } } "; CreateCompilationWithMscorlib45(code).VerifyDiagnostics( // (2,1): hidden CS8019: Unnecessary using directive. // using static A<A<int>[]>.B; Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using static A<A<int>[]>.B;").WithLocation(2, 1), // (2,14): error CS0452: The type 'int' must be a reference type in order to use it as parameter 'T' in the generic type or method 'A<T>' // using static A<A<int>[]>.B; Diagnostic(ErrorCode.ERR_RefConstraintNotSatisfied, "A<A<int>[]>.B").WithArguments("A<T>", "T", "int").WithLocation(2, 14)); } [Fact, WorkItem(30726, "https://github.com/dotnet/roslyn/issues/30726")] public void UsingStaticMultipleGenericConstraints() { var code = @" using static A<int, string>; static class A<T, U> where T : class where U : struct { } "; CreateCompilationWithMscorlib45(code).VerifyDiagnostics( // (2,1): hidden CS8019: Unnecessary using directive. // using static A<int, string>; Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using static A<int, string>;").WithLocation(2, 1), // (2,14): error CS0452: The type 'int' must be a reference type in order to use it as parameter 'T' in the generic type or method 'A<T, U>' // using static A<int, string>; Diagnostic(ErrorCode.ERR_RefConstraintNotSatisfied, "A<int, string>").WithArguments("A<T, U>", "T", "int").WithLocation(2, 14), // (2,14): error CS0453: The type 'string' must be a non-nullable value type in order to use it as parameter 'U' in the generic type or method 'A<T, U>' // using static A<int, string>; Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "A<int, string>").WithArguments("A<T, U>", "U", "string").WithLocation(2, 14)); } [Fact, WorkItem(8234, "https://github.com/dotnet/roslyn/issues/8234")] public void EventAccessInTypeNameContext() { var source = @" class Program { static void Main() {} event System.EventHandler E1; void Test(Program x) { System.Console.WriteLine(); x.E1.E System.Console.WriteLine(); } void Dummy() { E1 = null; var x = E1; } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (11,15): error CS1001: Identifier expected // x.E1.E Diagnostic(ErrorCode.ERR_IdentifierExpected, "").WithLocation(11, 15), // (11,15): error CS1002: ; expected // x.E1.E Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(11, 15), // (11,9): error CS0118: 'x' is a variable but is used like a type // x.E1.E Diagnostic(ErrorCode.ERR_BadSKknown, "x").WithArguments("x", "variable", "type").WithLocation(11, 9) ); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var node1 = tree.GetRoot().DescendantNodes().Where(n => n.IsKind(SyntaxKind.IdentifierName) && ((IdentifierNameSyntax)n).Identifier.ValueText == "E").Single().Parent; Assert.Equal("x.E1.E", node1.ToString()); Assert.Equal(SyntaxKind.QualifiedName, node1.Kind()); var node2 = ((QualifiedNameSyntax)node1).Left; Assert.Equal("x.E1", node2.ToString()); var symbolInfo2 = model.GetSymbolInfo(node2); Assert.Null(symbolInfo2.Symbol); Assert.Equal("event System.EventHandler Program.E1", symbolInfo2.CandidateSymbols.Single().ToTestDisplayString()); Assert.Equal(CandidateReason.NotATypeOrNamespace, symbolInfo2.CandidateReason); var symbolInfo1 = model.GetSymbolInfo(node1); Assert.Null(symbolInfo1.Symbol); Assert.True(symbolInfo1.CandidateSymbols.IsEmpty); } [Fact, WorkItem(13617, "https://github.com/dotnet/roslyn/issues/13617")] public void MissingTypeArgumentInGenericExtensionMethod() { var source = @" public static class FooExtensions { public static object ExtensionMethod0(this object obj) => default(object); public static T ExtensionMethod1<T>(this object obj) => default(T); public static T1 ExtensionMethod2<T1, T2>(this object obj) => default(T1); } public class Class1 { public void Test() { var omittedArg0 = ""string literal"".ExtensionMethod0<>(); var omittedArg1 = ""string literal"".ExtensionMethod1<>(); var omittedArg2 = ""string literal"".ExtensionMethod2<>(); var omittedArgFunc0 = ""string literal"".ExtensionMethod0<>; var omittedArgFunc1 = ""string literal"".ExtensionMethod1<>; var omittedArgFunc2 = ""string literal"".ExtensionMethod2<>; var moreArgs0 = ""string literal"".ExtensionMethod0<int>(); var moreArgs1 = ""string literal"".ExtensionMethod1<int, bool>(); var moreArgs2 = ""string literal"".ExtensionMethod2<int, bool, string>(); var lessArgs1 = ""string literal"".ExtensionMethod1(); var lessArgs2 = ""string literal"".ExtensionMethod2<int>(); var nonExistingMethod0 = ""string literal"".ExtensionMethodNotFound0(); var nonExistingMethod1 = ""string literal"".ExtensionMethodNotFound1<int>(); var nonExistingMethod2 = ""string literal"".ExtensionMethodNotFound2<int, string>(); System.Func<object> delegateConversion0 = ""string literal"".ExtensionMethod0<>; System.Func<object> delegateConversion1 = ""string literal"".ExtensionMethod1<>; System.Func<object> delegateConversion2 = ""string literal"".ExtensionMethod2<>; var exactArgs0 = ""string literal"".ExtensionMethod0(); var exactArgs1 = ""string literal"".ExtensionMethod1<int>(); var exactArgs2 = ""string literal"".ExtensionMethod2<int, bool>(); } } "; var compilation = CreateCompilationWithMscorlib40AndSystemCore(source); compilation.VerifyDiagnostics( // (13,27): error CS8389: Omitting the type argument is not allowed in the current context // var omittedArg0 = "string literal".ExtensionMethod0<>(); Diagnostic(ErrorCode.ERR_OmittedTypeArgument, @"""string literal"".ExtensionMethod0<>").WithLocation(13, 27), // (13,44): error CS1061: 'string' does not contain a definition for 'ExtensionMethod0' and no accessible extension method 'ExtensionMethod0' accepting a first argument of type 'string' could be found (are you missing a using directive or an assembly reference?) // var omittedArg0 = "string literal".ExtensionMethod0<>(); Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "ExtensionMethod0<>").WithArguments("string", "ExtensionMethod0").WithLocation(13, 44), // (14,27): error CS8389: Omitting the type argument is not allowed in the current context // var omittedArg1 = "string literal".ExtensionMethod1<>(); Diagnostic(ErrorCode.ERR_OmittedTypeArgument, @"""string literal"".ExtensionMethod1<>").WithLocation(14, 27), // (15,27): error CS8389: Omitting the type argument is not allowed in the current context // var omittedArg2 = "string literal".ExtensionMethod2<>(); Diagnostic(ErrorCode.ERR_OmittedTypeArgument, @"""string literal"".ExtensionMethod2<>").WithLocation(15, 27), // (15,44): error CS1061: 'string' does not contain a definition for 'ExtensionMethod2' and no accessible extension method 'ExtensionMethod2' accepting a first argument of type 'string' could be found (are you missing a using directive or an assembly reference?) // var omittedArg2 = "string literal".ExtensionMethod2<>(); Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "ExtensionMethod2<>").WithArguments("string", "ExtensionMethod2").WithLocation(15, 44), // (17,31): error CS8389: Omitting the type argument is not allowed in the current context // var omittedArgFunc0 = "string literal".ExtensionMethod0<>; Diagnostic(ErrorCode.ERR_OmittedTypeArgument, @"""string literal"".ExtensionMethod0<>").WithLocation(17, 31), // (17,48): error CS1061: 'string' does not contain a definition for 'ExtensionMethod0' and no accessible extension method 'ExtensionMethod0' accepting a first argument of type 'string' could be found (are you missing a using directive or an assembly reference?) // var omittedArgFunc0 = "string literal".ExtensionMethod0<>; Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "ExtensionMethod0<>").WithArguments("string", "ExtensionMethod0").WithLocation(17, 48), // (18,31): error CS8389: Omitting the type argument is not allowed in the current context // var omittedArgFunc1 = "string literal".ExtensionMethod1<>; Diagnostic(ErrorCode.ERR_OmittedTypeArgument, @"""string literal"".ExtensionMethod1<>").WithLocation(18, 31), // (18,13): error CS0815: Cannot assign method group to an implicitly-typed variable // var omittedArgFunc1 = "string literal".ExtensionMethod1<>; Diagnostic(ErrorCode.ERR_ImplicitlyTypedVariableAssignedBadValue, @"omittedArgFunc1 = ""string literal"".ExtensionMethod1<>").WithArguments("method group").WithLocation(18, 13), // (19,31): error CS8389: Omitting the type argument is not allowed in the current context // var omittedArgFunc2 = "string literal".ExtensionMethod2<>; Diagnostic(ErrorCode.ERR_OmittedTypeArgument, @"""string literal"".ExtensionMethod2<>").WithLocation(19, 31), // (19,48): error CS1061: 'string' does not contain a definition for 'ExtensionMethod2' and no accessible extension method 'ExtensionMethod2' accepting a first argument of type 'string' could be found (are you missing a using directive or an assembly reference?) // var omittedArgFunc2 = "string literal".ExtensionMethod2<>; Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "ExtensionMethod2<>").WithArguments("string", "ExtensionMethod2").WithLocation(19, 48), // (21,42): error CS1061: 'string' does not contain a definition for 'ExtensionMethod0' and no accessible extension method 'ExtensionMethod0' accepting a first argument of type 'string' could be found (are you missing a using directive or an assembly reference?) // var moreArgs0 = "string literal".ExtensionMethod0<int>(); Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "ExtensionMethod0<int>").WithArguments("string", "ExtensionMethod0").WithLocation(21, 42), // (22,42): error CS1061: 'string' does not contain a definition for 'ExtensionMethod1' and no accessible extension method 'ExtensionMethod1' accepting a first argument of type 'string' could be found (are you missing a using directive or an assembly reference?) // var moreArgs1 = "string literal".ExtensionMethod1<int, bool>(); Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "ExtensionMethod1<int, bool>").WithArguments("string", "ExtensionMethod1").WithLocation(22, 42), // (23,42): error CS1061: 'string' does not contain a definition for 'ExtensionMethod2' and no accessible extension method 'ExtensionMethod2' accepting a first argument of type 'string' could be found (are you missing a using directive or an assembly reference?) // var moreArgs2 = "string literal".ExtensionMethod2<int, bool, string>(); Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "ExtensionMethod2<int, bool, string>").WithArguments("string", "ExtensionMethod2").WithLocation(23, 42), // (25,42): error CS0411: The type arguments for method 'FooExtensions.ExtensionMethod1<T>(object)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // var lessArgs1 = "string literal".ExtensionMethod1(); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "ExtensionMethod1").WithArguments("FooExtensions.ExtensionMethod1<T>(object)").WithLocation(25, 42), // (26,42): error CS1061: 'string' does not contain a definition for 'ExtensionMethod2' and no accessible extension method 'ExtensionMethod2' accepting a first argument of type 'string' could be found (are you missing a using directive or an assembly reference?) // var lessArgs2 = "string literal".ExtensionMethod2<int>(); Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "ExtensionMethod2<int>").WithArguments("string", "ExtensionMethod2").WithLocation(26, 42), // (28,51): error CS1061: 'string' does not contain a definition for 'ExtensionMethodNotFound0' and no accessible extension method 'ExtensionMethodNotFound0' accepting a first argument of type 'string' could be found (are you missing a using directive or an assembly reference?) // var nonExistingMethod0 = "string literal".ExtensionMethodNotFound0(); Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "ExtensionMethodNotFound0").WithArguments("string", "ExtensionMethodNotFound0").WithLocation(28, 51), // (29,51): error CS1061: 'string' does not contain a definition for 'ExtensionMethodNotFound1' and no accessible extension method 'ExtensionMethodNotFound1' accepting a first argument of type 'string' could be found (are you missing a using directive or an assembly reference?) // var nonExistingMethod1 = "string literal".ExtensionMethodNotFound1<int>(); Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "ExtensionMethodNotFound1<int>").WithArguments("string", "ExtensionMethodNotFound1").WithLocation(29, 51), // (30,51): error CS1061: 'string' does not contain a definition for 'ExtensionMethodNotFound2' and no accessible extension method 'ExtensionMethodNotFound2' accepting a first argument of type 'string' could be found (are you missing a using directive or an assembly reference?) // var nonExistingMethod2 = "string literal".ExtensionMethodNotFound2<int, string>(); Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "ExtensionMethodNotFound2<int, string>").WithArguments("string", "ExtensionMethodNotFound2").WithLocation(30, 51), // (32,51): error CS8389: Omitting the type argument is not allowed in the current context // System.Func<object> delegateConversion0 = "string literal".ExtensionMethod0<>; Diagnostic(ErrorCode.ERR_OmittedTypeArgument, @"""string literal"".ExtensionMethod0<>").WithLocation(32, 51), // (32,68): error CS1061: 'string' does not contain a definition for 'ExtensionMethod0' and no accessible extension method 'ExtensionMethod0' accepting a first argument of type 'string' could be found (are you missing a using directive or an assembly reference?) // System.Func<object> delegateConversion0 = "string literal".ExtensionMethod0<>; Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "ExtensionMethod0<>").WithArguments("string", "ExtensionMethod0").WithLocation(32, 68), // (33,51): error CS8389: Omitting the type argument is not allowed in the current context // System.Func<object> delegateConversion1 = "string literal".ExtensionMethod1<>; Diagnostic(ErrorCode.ERR_OmittedTypeArgument, @"""string literal"".ExtensionMethod1<>").WithLocation(33, 51), // (33,51): error CS0407: '? FooExtensions.ExtensionMethod1<?>(object)' has the wrong return type // System.Func<object> delegateConversion1 = "string literal".ExtensionMethod1<>; Diagnostic(ErrorCode.ERR_BadRetType, @"""string literal"".ExtensionMethod1<>").WithArguments("FooExtensions.ExtensionMethod1<?>(object)", "?").WithLocation(33, 51), // (34,51): error CS8389: Omitting the type argument is not allowed in the current context // System.Func<object> delegateConversion2 = "string literal".ExtensionMethod2<>; Diagnostic(ErrorCode.ERR_OmittedTypeArgument, @"""string literal"".ExtensionMethod2<>").WithLocation(34, 51), // (34,68): error CS1061: 'string' does not contain a definition for 'ExtensionMethod2' and no accessible extension method 'ExtensionMethod2' accepting a first argument of type 'string' could be found (are you missing a using directive or an assembly reference?) // System.Func<object> delegateConversion2 = "string literal".ExtensionMethod2<>; Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "ExtensionMethod2<>").WithArguments("string", "ExtensionMethod2").WithLocation(34, 68)); } [WorkItem(22757, "https://github.com/dotnet/roslyn/issues/22757")] [Fact] public void MethodGroupConversionNoReceiver() { var source = @"using System; using System.Collections.Generic; class A { class B { void F() { IEnumerable<string> c = null; c.S(G); } } object G(string s) { return null; } } static class E { internal static IEnumerable<U> S<T, U>(this IEnumerable<T> c, Func<T, U> f) { throw new NotImplementedException(); } }"; var comp = CreateCompilationWithMscorlib40AndSystemCore(source); 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)); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var node = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(n => n.ToString() == "G").First(); var info = model.GetSymbolInfo(node); Assert.Equal("System.Object A.G(System.String s)", info.Symbol.ToTestDisplayString()); } [Fact] public void BindingLambdaArguments_DuplicateNamedArguments() { var compilation = CreateCompilation(@" using System; class X { void M<T>(T arg1, Func<T, T> arg2) { } void N() { M(arg1: 5, arg2: x => x, arg2: y => y); } }").VerifyDiagnostics( // (10,34): error CS1740: Named argument 'arg2' cannot be specified multiple times // M(arg1: 5, arg2: x => 0, arg2: y => 0); Diagnostic(ErrorCode.ERR_DuplicateNamedArgument, "arg2").WithArguments("arg2").WithLocation(10, 34)); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree, ignoreAccessibility: true); var lambda = tree.GetRoot().DescendantNodes().OfType<SimpleLambdaExpressionSyntax>().Single(s => s.Parameter.Identifier.Text == "x"); var typeInfo = model.GetTypeInfo(lambda.Body); Assert.Equal("System.Int32", typeInfo.Type.ToTestDisplayString()); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; using Microsoft.CodeAnalysis.CSharp.Syntax; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Semantics { public class BindingTests : CompilingTestBase { [Fact, WorkItem(539872, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539872")] public void NoWRN_UnreachableCode() { var text = @" public class Cls { public static int Main() { goto Label2; Label1: return (1); Label2: goto Label1; } }"; CreateCompilation(text).VerifyDiagnostics(); } [Fact] public void GenericMethodName() { var source = @"class A { class B { static void M(System.Action a) { M(M1); M(M2<object>); M(M3<int>); } static void M1() { } static void M2<T>() { } } static void M3<T>() { } }"; CreateCompilation(source).VerifyDiagnostics(); } [Fact] public void GenericTypeName() { var source = @"class A { class B { static void M(System.Type t) { M(typeof(C<int>)); M(typeof(S<string, string>)); M(typeof(C<int, int>)); } class C<T> { } } struct S<T, U> { } } class C<T, U> { } "; CreateCompilation(source).VerifyDiagnostics(); } [Fact] public void GenericTypeParameterName() { var source = @"class A<T> { class B<U> { static void M<V>() { N(typeof(V)); N(typeof(U)); N(typeof(T)); } static void N(System.Type t) { } } }"; CreateCompilation(source).VerifyDiagnostics(); } [Fact] public void WrongMethodArity() { var source = @"class C { static void M1<T>() { } static void M2() { } void M3<T>() { } void M4() { } void M() { M1<object, object>(); C.M1<object, object>(); M2<int>(); C.M2<int>(); M3<object, object>(); this.M3<object, object>(); M4<int>(); this.M4<int>(); } }"; CreateCompilation(source).VerifyDiagnostics( // (9,9): error CS0305: Using the generic method 'C.M1<T>()' requires 1 type arguments Diagnostic(ErrorCode.ERR_BadArity, "M1<object, object>").WithArguments("C.M1<T>()", "method", "1").WithLocation(9, 9), // (10,11): error CS0305: Using the generic method 'C.M1<T>()' requires 1 type arguments Diagnostic(ErrorCode.ERR_BadArity, "M1<object, object>").WithArguments("C.M1<T>()", "method", "1").WithLocation(10, 11), // (11,9): error CS0308: The non-generic method 'C.M2()' cannot be used with type arguments Diagnostic(ErrorCode.ERR_HasNoTypeVars, "M2<int>").WithArguments("C.M2()", "method").WithLocation(11, 9), // (12,11): error CS0308: The non-generic method 'C.M2()' cannot be used with type arguments Diagnostic(ErrorCode.ERR_HasNoTypeVars, "M2<int>").WithArguments("C.M2()", "method").WithLocation(12, 11), // (13,9): error CS0305: Using the generic method 'C.M3<T>()' requires 1 type arguments Diagnostic(ErrorCode.ERR_BadArity, "M3<object, object>").WithArguments("C.M3<T>()", "method", "1").WithLocation(13, 9), // (14,14): error CS0305: Using the generic method 'C.M3<T>()' requires 1 type arguments Diagnostic(ErrorCode.ERR_BadArity, "M3<object, object>").WithArguments("C.M3<T>()", "method", "1").WithLocation(14, 14), // (15,9): error CS0308: The non-generic method 'C.M4()' cannot be used with type arguments Diagnostic(ErrorCode.ERR_HasNoTypeVars, "M4<int>").WithArguments("C.M4()", "method").WithLocation(15, 9), // (16,14): error CS0308: The non-generic method 'C.M4()' cannot be used with type arguments Diagnostic(ErrorCode.ERR_HasNoTypeVars, "M4<int>").WithArguments("C.M4()", "method").WithLocation(16, 14)); } [Fact] public void AmbiguousInaccessibleMethod() { var source = @"class A { protected void M1() { } protected void M1(object o) { } protected void M2(string s) { } protected void M2(object o) { } } class B { static void M(A a) { a.M1(); a.M2(); M(a.M1); M(a.M2); } static void M(System.Action<object> a) { } }"; CreateCompilation(source).VerifyDiagnostics( // (12,11): error CS0122: 'A.M1()' is inaccessible due to its protection level Diagnostic(ErrorCode.ERR_BadAccess, "M1").WithArguments("A.M1()").WithLocation(12, 11), // (13,11): error CS0122: 'A.M2(string)' is inaccessible due to its protection level Diagnostic(ErrorCode.ERR_BadAccess, "M2").WithArguments("A.M2(string)").WithLocation(13, 11), // (14,13): error CS0122: 'A.M1()' is inaccessible due to its protection level Diagnostic(ErrorCode.ERR_BadAccess, "M1").WithArguments("A.M1()").WithLocation(14, 13), // (15,13): error CS0122: 'A.M2(string)' is inaccessible due to its protection level Diagnostic(ErrorCode.ERR_BadAccess, "M2").WithArguments("A.M2(string)").WithLocation(15, 13)); } /// <summary> /// Should report inaccessible method, even when using /// method as a delegate in an invalid context. /// </summary> [Fact] public void InaccessibleMethodInvalidDelegateUse() { var source = @"class A { protected object F() { return null; } } class B { static void M(A a) { if (a.F != null) { M(a.F); a.F.ToString(); } } }"; CreateCompilation(source).VerifyDiagnostics( // (9,15): error CS0122: 'A.F()' is inaccessible due to its protection level Diagnostic(ErrorCode.ERR_BadAccess, "F").WithArguments("A.F()").WithLocation(9, 15), // (11,17): error CS0122: 'A.F()' is inaccessible due to its protection level Diagnostic(ErrorCode.ERR_BadAccess, "F").WithArguments("A.F()").WithLocation(11, 17), // (12,15): error CS0122: 'A.F()' is inaccessible due to its protection level Diagnostic(ErrorCode.ERR_BadAccess, "F").WithArguments("A.F()").WithLocation(12, 15)); } /// <summary> /// Methods should be resolved correctly even /// in cases where a method group is not allowed. /// </summary> [Fact] public void InvalidUseOfMethodGroup() { var source = @"class A { internal object E() { return null; } private object F() { return null; } } class B { static void M(A a) { object o; a.E += a.E; if (a.E != null) { M(a.E); a.E.ToString(); o = !a.E; o = a.E ?? a.F; } a.F += a.F; if (a.F != null) { M(a.F); a.F.ToString(); o = !a.F; o = (o != null) ? a.E : a.F; } } }"; CreateCompilation(source).VerifyDiagnostics( // (11,9): error CS1656: Cannot assign to 'E' because it is a 'method group' // a.E += a.E; Diagnostic(ErrorCode.ERR_AssgReadonlyLocalCause, "a.E").WithArguments("E", "method group").WithLocation(11, 9), // (14,15): error CS1503: Argument 1: cannot convert from 'method group' to 'A' // M(a.E); Diagnostic(ErrorCode.ERR_BadArgType, "a.E").WithArguments("1", "method group", "A").WithLocation(14, 15), // (15,15): error CS0119: 'A.E()' is a method, which is not valid in the given context // a.E.ToString(); Diagnostic(ErrorCode.ERR_BadSKunknown, "E").WithArguments("A.E()", "method").WithLocation(15, 15), // (16,17): error CS0023: Operator '!' cannot be applied to operand of type 'method group' // o = !a.E; Diagnostic(ErrorCode.ERR_BadUnaryOp, "!a.E").WithArguments("!", "method group").WithLocation(16, 17), // (17,26): error CS0122: 'A.F()' is inaccessible due to its protection level // o = a.E ?? a.F; Diagnostic(ErrorCode.ERR_BadAccess, "F").WithArguments("A.F()").WithLocation(17, 26), // (19,11): error CS0122: 'A.F()' is inaccessible due to its protection level // a.F += a.F; Diagnostic(ErrorCode.ERR_BadAccess, "F").WithArguments("A.F()").WithLocation(19, 11), // (19,18): error CS0122: 'A.F()' is inaccessible due to its protection level // a.F += a.F; Diagnostic(ErrorCode.ERR_BadAccess, "F").WithArguments("A.F()").WithLocation(19, 18), // (20,15): error CS0122: 'A.F()' is inaccessible due to its protection level // if (a.F != null) Diagnostic(ErrorCode.ERR_BadAccess, "F").WithArguments("A.F()").WithLocation(20, 15), // (22,17): error CS0122: 'A.F()' is inaccessible due to its protection level // M(a.F); Diagnostic(ErrorCode.ERR_BadAccess, "F").WithArguments("A.F()").WithLocation(22, 17), // (23,15): error CS0122: 'A.F()' is inaccessible due to its protection level // a.F.ToString(); Diagnostic(ErrorCode.ERR_BadAccess, "F").WithArguments("A.F()").WithLocation(23, 15), // (24,20): error CS0122: 'A.F()' is inaccessible due to its protection level // o = !a.F; Diagnostic(ErrorCode.ERR_BadAccess, "F").WithArguments("A.F()").WithLocation(24, 20), // (25,39): error CS0122: 'A.F()' is inaccessible due to its protection level // o = (o != null) ? a.E : a.F; Diagnostic(ErrorCode.ERR_BadAccess, "F").WithArguments("A.F()").WithLocation(25, 39)); } [WorkItem(528425, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528425")] [Fact(Skip = "528425")] public void InaccessibleAndAccessible() { var source = @"using System; class A { void F() { } internal void F(object o) { } static void G() { } internal static void G(object o) { } void H(object o) { } } class B : A { static void M(A a) { a.F(null); a.F(); A.G(); M1(a.F); M2(a.F); Action<object> a1 = a.F; Action a2 = a.F; } void M() { G(); } static void M1(Action<object> a) { } static void M2(Action a) { } }"; CreateCompilation(source).VerifyDiagnostics( // (15,11): error CS0122: 'A.F()' is inaccessible due to its protection level Diagnostic(ErrorCode.ERR_BadAccess, "F").WithArguments("A.F()").WithLocation(15, 11), // (16,11): error CS0122: 'A.G()' is inaccessible due to its protection level Diagnostic(ErrorCode.ERR_BadAccess, "G").WithArguments("A.G()").WithLocation(16, 11), // (18,12): error CS1503: Argument 1: cannot convert from 'method group' to 'System.Action' Diagnostic(ErrorCode.ERR_BadArgType, "a.F").WithArguments("1", "method group", "System.Action").WithLocation(18, 12), // (20,23): error CS0122: 'A.F()' is inaccessible due to its protection level Diagnostic(ErrorCode.ERR_BadAccess, "F").WithArguments("A.F()").WithLocation(20, 23), // (24,9): error CS0122: 'A.G()' is inaccessible due to its protection level Diagnostic(ErrorCode.ERR_BadAccess, "G").WithArguments("A.G()").WithLocation(24, 9)); } [Fact] public void InaccessibleAndAccessibleAndAmbiguous() { var source = @"class A { void F(string x) { } void F(string x, string y) { } internal void F(object x, string y) { } internal void F(string x, object y) { } void G(object x, string y) { } internal void G(string x, object y) { } static void M(A a, string s) { a.F(s, s); // no error } } class B { static void M(A a, string s, object o) { a.F(s, s); // accessible ambiguous a.G(s, s); // accessible and inaccessible ambiguous, no error a.G(o, o); // accessible and inaccessible invalid } }"; CreateCompilation(source).VerifyDiagnostics( // (18,9): error CS0121: The call is ambiguous between the following methods or properties: 'A.F(object, string)' and 'A.F(string, object)' Diagnostic(ErrorCode.ERR_AmbigCall, "F").WithArguments("A.F(object, string)", "A.F(string, object)").WithLocation(18, 11), // (20,13): error CS1503: Argument 1: cannot convert from 'object' to 'string' Diagnostic(ErrorCode.ERR_BadArgType, "o").WithArguments("1", "object", "string").WithLocation(20, 13)); } [Fact] public void InaccessibleAndAccessibleValid() { var source = @"class A { void F(int i) { } internal void F(long l) { } static void M(A a) { a.F(1); // no error } } class B { static void M(A a) { a.F(1); // no error } }"; CreateCompilation(source).VerifyDiagnostics(); } [Fact] public void ParenthesizedDelegate() { var source = @"class C { System.Action<object> F = null; void M() { ((this.F))(null); (new C().F)(null, null); } }"; CreateCompilation(source).VerifyDiagnostics( Diagnostic(ErrorCode.ERR_BadDelArgCount, "(new C().F)").WithArguments("System.Action<object>", "2").WithLocation(7, 9)); } /// <summary> /// Report errors for invocation expressions for non-invocable expressions, /// and bind arguments even though invocation expression was invalid. /// </summary> [Fact] public void NonMethodsWithArgs() { var source = @"namespace N { class C<T> { object F; object P { get; set; } void M() { N(a); C<string>(b); N.C<int>(c); N.D(d); T(e); (typeof(C<int>))(f); P(g) = F(h); this.F(i) = (this).P(j); null.M(k); } } }"; CreateCompilation(source).VerifyDiagnostics( // (9,15): error CS0103: The name 'a' does not exist in the current context // N(a); Diagnostic(ErrorCode.ERR_NameNotInContext, "a").WithArguments("a"), // (9,13): error CS0118: 'N' is a namespace but is used like a variable // N(a); Diagnostic(ErrorCode.ERR_BadSKknown, "N").WithArguments("N", "namespace", "variable"), // (10,23): error CS0103: The name 'b' does not exist in the current context // C<string>(b); Diagnostic(ErrorCode.ERR_NameNotInContext, "b").WithArguments("b"), // (10,13): error CS1955: Non-invocable member 'N.C<T>' cannot be used like a method. // C<string>(b); Diagnostic(ErrorCode.ERR_NonInvocableMemberCalled, "C<string>").WithArguments("N.C<T>"), // (11,22): error CS0103: The name 'c' does not exist in the current context // N.C<int>(c); Diagnostic(ErrorCode.ERR_NameNotInContext, "c").WithArguments("c"), // (11,15): error CS1955: Non-invocable member 'N.C<T>' cannot be used like a method. // N.C<int>(c); Diagnostic(ErrorCode.ERR_NonInvocableMemberCalled, "C<int>").WithArguments("N.C<T>"), // (12,17): error CS0103: The name 'd' does not exist in the current context // N.D(d); Diagnostic(ErrorCode.ERR_NameNotInContext, "d").WithArguments("d"), // (12,13): error CS0234: The type or namespace name 'D' does not exist in the namespace 'N' (are you missing an assembly reference?) // N.D(d); Diagnostic(ErrorCode.ERR_DottedTypeNameNotFoundInNS, "N.D").WithArguments("D", "N"), // (13,15): error CS0103: The name 'e' does not exist in the current context // T(e); Diagnostic(ErrorCode.ERR_NameNotInContext, "e").WithArguments("e"), // (13,13): error CS0103: The name 'T' does not exist in the current context // T(e); Diagnostic(ErrorCode.ERR_NameNotInContext, "T").WithArguments("T"), // (14,30): error CS0103: The name 'f' does not exist in the current context // (typeof(C<int>))(f); Diagnostic(ErrorCode.ERR_NameNotInContext, "f").WithArguments("f"), // (14,13): error CS0149: Method name expected // (typeof(C<int>))(f); Diagnostic(ErrorCode.ERR_MethodNameExpected, "(typeof(C<int>))"), // (15,15): error CS0103: The name 'g' does not exist in the current context // P(g) = F(h); Diagnostic(ErrorCode.ERR_NameNotInContext, "g").WithArguments("g"), // (15,13): error CS1955: Non-invocable member 'N.C<T>.P' cannot be used like a method. // P(g) = F(h); Diagnostic(ErrorCode.ERR_NonInvocableMemberCalled, "P").WithArguments("N.C<T>.P"), // (15,22): error CS0103: The name 'h' does not exist in the current context // P(g) = F(h); Diagnostic(ErrorCode.ERR_NameNotInContext, "h").WithArguments("h"), // (15,20): error CS1955: Non-invocable member 'N.C<T>.F' cannot be used like a method. // P(g) = F(h); Diagnostic(ErrorCode.ERR_NonInvocableMemberCalled, "F").WithArguments("N.C<T>.F"), // (16,20): error CS0103: The name 'i' does not exist in the current context // this.F(i) = (this).P(j); Diagnostic(ErrorCode.ERR_NameNotInContext, "i").WithArguments("i"), // (16,18): error CS1955: Non-invocable member 'N.C<T>.F' cannot be used like a method. // this.F(i) = (this).P(j); Diagnostic(ErrorCode.ERR_NonInvocableMemberCalled, "F").WithArguments("N.C<T>.F"), // (16,34): error CS0103: The name 'j' does not exist in the current context // this.F(i) = (this).P(j); Diagnostic(ErrorCode.ERR_NameNotInContext, "j").WithArguments("j"), // (16,32): error CS1955: Non-invocable member 'N.C<T>.P' cannot be used like a method. // this.F(i) = (this).P(j); Diagnostic(ErrorCode.ERR_NonInvocableMemberCalled, "P").WithArguments("N.C<T>.P"), // (17,20): error CS0103: The name 'k' does not exist in the current context // null.M(k); Diagnostic(ErrorCode.ERR_NameNotInContext, "k").WithArguments("k"), // (17,13): error CS0023: Operator '.' cannot be applied to operand of type '<null>' // null.M(k); Diagnostic(ErrorCode.ERR_BadUnaryOp, "null.M").WithArguments(".", "<null>"), // (5,16): warning CS0649: Field 'N.C<T>.F' is never assigned to, and will always have its default value null // object F; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "F").WithArguments("N.C<T>.F", "null") ); } [Fact] public void SimpleDelegates() { var source = @"static class S { public static void F(System.Action a) { } } class C { void M() { S.F(this.M); System.Action a = this.M; S.F(a); } }"; CreateCompilation(source).VerifyDiagnostics(); } [Fact] public void DelegatesFromOverloads() { var source = @"using System; class C { static void A(Action<object> a) { } static void M(C c) { A(C.F); A(c.G); Action<object> a; a = C.F; a = c.G; } static void F() { } static void F(object o) { } void G(object o) { } void G(object x, object y) { } }"; CreateCompilation(source).VerifyDiagnostics(); } [Fact] public void NonViableDelegates() { var source = @"using System; class A { static Action F = null; Action G = null; } class B { static void M(A a) { A.F(x); a.G(y); } }"; CreateCompilation(source).VerifyDiagnostics( // (11,13): error CS0103: The name 'x' does not exist in the current context // A.F(x); Diagnostic(ErrorCode.ERR_NameNotInContext, "x").WithArguments("x"), // (11,11): error CS0122: 'A.F' is inaccessible due to its protection level // A.F(x); Diagnostic(ErrorCode.ERR_BadAccess, "F").WithArguments("A.F"), // (12,13): error CS0103: The name 'y' does not exist in the current context // a.G(y); Diagnostic(ErrorCode.ERR_NameNotInContext, "y").WithArguments("y"), // (12,11): error CS0122: 'A.G' is inaccessible due to its protection level // a.G(y); Diagnostic(ErrorCode.ERR_BadAccess, "G").WithArguments("A.G"), // (4,19): warning CS0414: The field 'A.F' is assigned but its value is never used // static Action F = null; Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "F").WithArguments("A.F"), // (5,12): warning CS0414: The field 'A.G' is assigned but its value is never used // Action G = null; Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "G").WithArguments("A.G") ); } /// <summary> /// Choose one method if overloaded methods are /// equally invalid. /// </summary> [Fact] public void ChooseOneMethodIfEquallyInvalid() { var source = @"internal static class S { public static void M(double x, A y) { } public static void M(double x, B y) { } } class A { } class B { } class C { static void M() { S.M(1.0, null); // ambiguous S.M(1.0, 2.0); // equally invalid } }"; CreateCompilation(source).VerifyDiagnostics( // (12,9): error CS0121: The call is ambiguous between the following methods or properties: 'S.M(double, A)' and 'S.M(double, B)' Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("S.M(double, A)", "S.M(double, B)").WithLocation(12, 11), // (13,18): error CS1503: Argument 2: cannot convert from 'double' to 'A' Diagnostic(ErrorCode.ERR_BadArgType, "2.0").WithArguments("2", "double", "A").WithLocation(13, 18)); } [Fact] public void ChooseExpandedFormIfBadArgCountAndBadArgument() { var source = @"class C { static void M(object o) { F(); F(o); F(1, o); F(1, 2, o); } static void F(int i, params int[] args) { } }"; CreateCompilation(source).VerifyDiagnostics( // (5,9): error CS7036: There is no argument given that corresponds to the required formal parameter 'i' of 'C.F(int, params int[])' Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "F").WithArguments("i", "C.F(int, params int[])").WithLocation(5, 9), // (6,11): error CS1503: Argument 1: cannot convert from 'object' to 'int' Diagnostic(ErrorCode.ERR_BadArgType, "o").WithArguments("1", "object", "int").WithLocation(6, 11), // (7,14): error CS1503: Argument 2: cannot convert from 'object' to 'int' Diagnostic(ErrorCode.ERR_BadArgType, "o").WithArguments("2", "object", "int").WithLocation(7, 14), // (8,17): error CS1503: Argument 3: cannot convert from 'object' to 'int' Diagnostic(ErrorCode.ERR_BadArgType, "o").WithArguments("3", "object", "int").WithLocation(8, 17)); } [Fact] public void AmbiguousAndBadArgument() { var source = @"class C { static void F(int x, double y) { } static void F(double x, int y) { } static void M() { F(1, 2); F(1.0, 2.0); } }"; CreateCompilation(source).VerifyDiagnostics( // (7,9): error CS0121: The call is ambiguous between the following methods or properties: 'C.F(int, double)' and 'C.F(double, int)' Diagnostic(ErrorCode.ERR_AmbigCall, "F").WithArguments("C.F(int, double)", "C.F(double, int)").WithLocation(7, 9), // (8,11): error CS1503: Argument 1: cannot convert from 'double' to 'int' Diagnostic(ErrorCode.ERR_BadArgType, "1.0").WithArguments("1", "double", "int").WithLocation(8, 11)); } [WorkItem(541050, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541050")] [Fact] public void IncompleteDelegateDecl() { var source = @"namespace nms { delegate"; CreateCompilation(source).VerifyDiagnostics( // (3,9): error CS1031: Type expected // delegate Diagnostic(ErrorCode.ERR_TypeExpected, ""), // (3,9): error CS1001: Identifier expected // delegate Diagnostic(ErrorCode.ERR_IdentifierExpected, ""), // (3,9): error CS1003: Syntax error, '(' expected // delegate Diagnostic(ErrorCode.ERR_SyntaxError, "").WithArguments("(", ""), // (3,9): error CS1026: ) expected // delegate Diagnostic(ErrorCode.ERR_CloseParenExpected, ""), // (3,9): error CS1002: ; expected // delegate Diagnostic(ErrorCode.ERR_SemicolonExpected, ""), // (3,9): error CS1513: } expected // delegate Diagnostic(ErrorCode.ERR_RbraceExpected, "")); } [WorkItem(541213, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541213")] [Fact] public void IncompleteElsePartInIfStmt() { var source = @"public class Test { public static int Main(string [] args) { if (true) { } else "; CreateCompilation(source).VerifyDiagnostics( // (8,13): error CS1733: Expected expression // else Diagnostic(ErrorCode.ERR_ExpressionExpected, ""), // (9,1): error CS1002: ; expected // Diagnostic(ErrorCode.ERR_SemicolonExpected, ""), // (9,1): error CS1513: } expected // Diagnostic(ErrorCode.ERR_RbraceExpected, ""), // (9,1): error CS1513: } expected // Diagnostic(ErrorCode.ERR_RbraceExpected, ""), // (3,23): error CS0161: 'Test.Main(string[])': not all code paths return a value // public static int Main(string [] args) Diagnostic(ErrorCode.ERR_ReturnExpected, "Main").WithArguments("Test.Main(string[])") ); } [WorkItem(541466, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541466")] [Fact] public void UseSiteErrorViaAliasTest01() { var baseAssembly = CreateCompilation( @" namespace BaseAssembly { public class BaseClass { } } ", assemblyName: "BaseAssembly1").VerifyDiagnostics(); var derivedAssembly = CreateCompilation( @" namespace DerivedAssembly { public class DerivedClass: BaseAssembly.BaseClass { public static int IntField = 123; } } ", assemblyName: "DerivedAssembly1", references: new List<MetadataReference>() { baseAssembly.EmitToImageReference() }).VerifyDiagnostics(); var testAssembly = CreateCompilation( @" using ClassAlias = DerivedAssembly.DerivedClass; public class Test { static void Main() { int a = ClassAlias.IntField; int b = ClassAlias.IntField; } } ", references: new List<MetadataReference>() { derivedAssembly.EmitToImageReference() }) .VerifyDiagnostics(); // NOTE: Dev10 errors: // <fine-name>(7,9): error CS0012: The type 'BaseAssembly.BaseClass' is defined in an assembly that is not referenced. You must add a reference to assembly 'BaseAssembly, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'. } [WorkItem(541466, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541466")] [Fact] public void UseSiteErrorViaAliasTest02() { var baseAssembly = CreateCompilation( @" namespace BaseAssembly { public class BaseClass { } } ", assemblyName: "BaseAssembly2").VerifyDiagnostics(); var derivedAssembly = CreateCompilation( @" namespace DerivedAssembly { public class DerivedClass: BaseAssembly.BaseClass { public static int IntField = 123; } } ", assemblyName: "DerivedAssembly2", references: new List<MetadataReference>() { baseAssembly.EmitToImageReference() }).VerifyDiagnostics(); var testAssembly = CreateCompilation( @" using ClassAlias = DerivedAssembly.DerivedClass; public class Test { static void Main() { ClassAlias a = new ClassAlias(); ClassAlias b = new ClassAlias(); } } ", references: new List<MetadataReference>() { derivedAssembly.EmitToImageReference() }) .VerifyDiagnostics(); // NOTE: Dev10 errors: // <fine-name>(6,9): error CS0012: The type 'BaseAssembly.BaseClass' is defined in an assembly that is not referenced. You must add a reference to assembly 'BaseAssembly, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'. } [WorkItem(541466, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541466")] [Fact] public void UseSiteErrorViaAliasTest03() { var baseAssembly = CreateCompilation( @" namespace BaseAssembly { public class BaseClass { } } ", assemblyName: "BaseAssembly3").VerifyDiagnostics(); var derivedAssembly = CreateCompilation( @" namespace DerivedAssembly { public class DerivedClass: BaseAssembly.BaseClass { public static int IntField = 123; } } ", assemblyName: "DerivedAssembly3", references: new List<MetadataReference>() { baseAssembly.EmitToImageReference() }).VerifyDiagnostics(); var testAssembly = CreateCompilation( @" using ClassAlias = DerivedAssembly.DerivedClass; public class Test { ClassAlias a = null; ClassAlias b = null; ClassAlias m() { return null; } void m2(ClassAlias p) { } }", references: new List<MetadataReference>() { derivedAssembly.EmitToImageReference() }) .VerifyDiagnostics( // (5,16): warning CS0414: The field 'Test.a' is assigned but its value is never used // ClassAlias a = null; Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "a").WithArguments("Test.a"), // (6,16): warning CS0414: The field 'Test.b' is assigned but its value is never used // ClassAlias b = null; Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "b").WithArguments("Test.b") ); // NOTE: Dev10 errors: // <fine-name>(4,16): error CS0012: The type 'BaseAssembly.BaseClass' is defined in an assembly that is not referenced. You must add a reference to assembly 'BaseAssembly, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'. } [WorkItem(911913, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/911913")] [Fact] public void UnimplementedInterfaceSquiggleLocation_Typical() { string scenarioCode = @" public class ITT : IInterfaceBase { } public interface IInterfaceBase { void bar(); }"; var testAssembly = CreateCompilation(scenarioCode); testAssembly.VerifyDiagnostics( // (3,7): error CS0535: 'ITT' does not implement interface member 'IInterfaceBase.bar()' // : IInterfaceBase Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "IInterfaceBase").WithArguments("ITT", "IInterfaceBase.bar()").WithLocation(3, 7)); } [WorkItem(911913, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/911913")] [Fact] public void UnimplementedInterfaceSquiggleLocation_FullyQualified() { // Using fully Qualified names string scenarioCode = @" public class ITT : test.IInterfaceBase { } namespace test { public interface IInterfaceBase { void bar(); } }"; var testAssembly = CreateCompilation(scenarioCode); testAssembly.VerifyDiagnostics( // (3,7): error CS0535: 'ITT' does not implement interface member 'test.IInterfaceBase.bar()' // : test.IInterfaceBase Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "test.IInterfaceBase").WithArguments("ITT", "test.IInterfaceBase.bar()").WithLocation(3, 7)); } [WorkItem(911913, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/911913")] [Fact] public void UnimplementedInterfaceSquiggleLocation_WithAlias() { // Using Alias string scenarioCode = @" using a1 = test; public class ITT : a1.IInterfaceBase { } namespace test { public interface IInterfaceBase { void bar(); } }"; var testAssembly = CreateCompilation(scenarioCode); testAssembly.VerifyDiagnostics( // (5,7): error CS0535: 'ITT' does not implement interface member 'test.IInterfaceBase.bar()' // : a1.IInterfaceBase Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "a1.IInterfaceBase").WithArguments("ITT", "test.IInterfaceBase.bar()").WithLocation(5, 7)); } [WorkItem(911913, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/911913")] [Fact] public void UnimplementedInterfaceSquiggleLocation_InterfaceInheritanceScenario01() { // Two interfaces, neither implemented with alias - should have 2 errors each squiggling a different interface type. string scenarioCode = @" using a1 = test; public class ITT : a1.IInterfaceBase, a1.IInterfaceBase2 { } namespace test { public interface IInterfaceBase { void xyz(); } public interface IInterfaceBase2 { void xyz(); } }"; var testAssembly = CreateCompilation(scenarioCode); testAssembly.VerifyDiagnostics( // (5,7): error CS0535: 'ITT' does not implement interface member 'test.IInterfaceBase.xyz()' // : a1.IInterfaceBase, a1.IInterfaceBase2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "a1.IInterfaceBase").WithArguments("ITT", "test.IInterfaceBase.xyz()").WithLocation(5, 7), // (5,26): error CS0535: 'ITT' does not implement interface member 'test.IInterfaceBase2.xyz()' // : a1.IInterfaceBase, a1.IInterfaceBase2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "a1.IInterfaceBase2").WithArguments("ITT", "test.IInterfaceBase2.xyz()").WithLocation(5, 26)); } [WorkItem(911913, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/911913")] [Fact] public void UnimplementedInterfaceSquiggleLocation_InterfaceInheritanceScenario02() { // Two interfaces, only the second is implemented string scenarioCode = @" public class ITT : IInterfaceBase, IInterfaceBase2 { void IInterfaceBase2.abc() { } } public interface IInterfaceBase { void xyz(); } public interface IInterfaceBase2 { void abc(); }"; var testAssembly = CreateCompilation(scenarioCode); testAssembly.VerifyDiagnostics( // (3,7): error CS0535: 'ITT' does not implement interface member 'IInterfaceBase.xyz()' // : IInterfaceBase, IInterfaceBase2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "IInterfaceBase").WithArguments("ITT", "IInterfaceBase.xyz()").WithLocation(3, 7)); } [WorkItem(911913, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/911913")] [Fact] public void UnimplementedInterfaceSquiggleLocation_InterfaceInheritanceScenario03() { // Two interfaces, only the first is implemented string scenarioCode = @" public class ITT : IInterfaceBase, IInterfaceBase2 { void IInterfaceBase.xyz() { } } public interface IInterfaceBase { void xyz(); } public interface IInterfaceBase2 { void abc(); } "; var testAssembly = CreateCompilation(scenarioCode); testAssembly.VerifyDiagnostics( // (3,23): error CS0535: 'ITT' does not implement interface member 'IInterfaceBase2.abc()' // : IInterfaceBase, IInterfaceBase2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "IInterfaceBase2").WithArguments("ITT", "IInterfaceBase2.abc()").WithLocation(3, 23)); } [WorkItem(911913, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/911913")] [Fact] public void UnimplementedInterfaceSquiggleLocation_InterfaceInheritanceScenario04() { // Two interfaces, neither implemented but formatting of interfaces are on different lines string scenarioCode = @" public class ITT : IInterfaceBase, IInterfaceBase2 { } public interface IInterfaceBase { void xyz(); } public interface IInterfaceBase2 { void xyz(); } "; var testAssembly = CreateCompilation(scenarioCode); testAssembly.VerifyDiagnostics( // (3,7): error CS0535: 'ITT' does not implement interface member 'IInterfaceBase.xyz()' // : IInterfaceBase, Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "IInterfaceBase").WithArguments("ITT", "IInterfaceBase.xyz()").WithLocation(3, 7), // (4,6): error CS0535: 'ITT' does not implement interface member 'IInterfaceBase2.xyz()' // IInterfaceBase2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "IInterfaceBase2").WithArguments("ITT", "IInterfaceBase2.xyz()").WithLocation(4, 6)); } [WorkItem(911913, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/911913")] [Fact] public void UnimplementedInterfaceSquiggleLocation_InterfaceInheritanceScenario05() { // Inherited Interface scenario // With methods not implemented in both base and derived. // Should reflect 2 diagnostics but both with be squiggling the derived as we are not // explicitly implementing base. string scenarioCode = @" public class ITT: IDerived { } interface IInterfaceBase { void xyzb(); } interface IDerived : IInterfaceBase { void xyzd(); }"; var testAssembly = CreateCompilation(scenarioCode); testAssembly.VerifyDiagnostics( // (2,19): error CS0535: 'ITT' does not implement interface member 'IDerived.xyzd()' // public class ITT: IDerived Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "IDerived").WithArguments("ITT", "IDerived.xyzd()").WithLocation(2, 19), // (2,19): error CS0535: 'ITT' does not implement interface member 'IInterfaceBase.xyzb()' // public class ITT: IDerived Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "IDerived").WithArguments("ITT", "IInterfaceBase.xyzb()").WithLocation(2, 19)); } [WorkItem(911913, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/911913")] [Fact] public void UnimplementedInterfaceSquiggleLocation_InterfaceInheritanceScenario06() { // Inherited Interface scenario string scenarioCode = @" public class ITT: IDerived, IInterfaceBase { } interface IInterfaceBase { void xyz(); } interface IDerived : IInterfaceBase { void xyzd(); }"; var testAssembly = CreateCompilation(scenarioCode); testAssembly.VerifyDiagnostics( // (2,19): error CS0535: 'ITT' does not implement interface member 'IDerived.xyzd()' // public class ITT: IDerived, IInterfaceBase Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "IDerived").WithArguments("ITT", "IDerived.xyzd()").WithLocation(2, 19), // (2,29): error CS0535: 'ITT' does not implement interface member 'IInterfaceBase.xyz()' // public class ITT: IDerived, IInterfaceBase Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "IInterfaceBase").WithArguments("ITT", "IInterfaceBase.xyz()").WithLocation(2, 29)); } [WorkItem(911913, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/911913")] [Fact] public void UnimplementedInterfaceSquiggleLocation_InterfaceInheritanceScenario07() { // Inherited Interface scenario - different order. string scenarioCode = @" public class ITT: IInterfaceBase, IDerived { } interface IDerived : IInterfaceBase { void xyzd(); } interface IInterfaceBase { void xyz(); } "; var testAssembly = CreateCompilation(scenarioCode); testAssembly.VerifyDiagnostics( // (2,35): error CS0535: 'ITT' does not implement interface member 'IDerived.xyzd()' // public class ITT: IInterfaceBase, IDerived Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "IDerived").WithArguments("ITT", "IDerived.xyzd()").WithLocation(2, 35), // (2,19): error CS0535: 'ITT' does not implement interface member 'IInterfaceBase.xyz()' // public class ITT: IInterfaceBase, IDerived Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "IInterfaceBase").WithArguments("ITT", "IInterfaceBase.xyz()").WithLocation(2, 19)); } [WorkItem(911913, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/911913")] [Fact] public void UnimplementedInterfaceSquiggleLocation_InterfaceInheritanceScenario08() { // Inherited Interface scenario string scenarioCode = @" public class ITT: IDerived2 {} interface IBase { void method1(); } interface IBase2 { void Method2(); } interface IDerived2: IBase, IBase2 {}"; var testAssembly = CreateCompilation(scenarioCode); testAssembly.VerifyDiagnostics( // (2,19): error CS0535: 'ITT' does not implement interface member 'IBase.method1()' // public class ITT: IDerived2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "IDerived2").WithArguments("ITT", "IBase.method1()").WithLocation(2, 19), // (2,19): error CS0535: 'ITT' does not implement interface member 'IBase2.Method2()' // public class ITT: IDerived2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "IDerived2").WithArguments("ITT", "IBase2.Method2()").WithLocation(2, 19)); } [WorkItem(911913, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/911913")] [Fact] public void UnimplementedInterfaceSquiggleLocation13UnimplementedInterfaceSquiggleLocation_InterfaceInheritanceScenario09() { // Inherited Interface scenario. string scenarioCode = @" public class ITT : IDerived { void IBase2.method2() { } void IDerived.method3() { } } public interface IBase { void method1(); } public interface IBase2 { void method2(); } public interface IDerived : IBase, IBase2 { void method3(); }"; var testAssembly = CreateCompilation(scenarioCode); testAssembly.VerifyDiagnostics( // (2,20): error CS0535: 'ITT' does not implement interface member 'IBase.method1()' // public class ITT : IDerived Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "IDerived").WithArguments("ITT", "IBase.method1()").WithLocation(2, 20)); } [WorkItem(911913, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/911913")] [Fact] public void UnimplementedInterfaceSquiggleLocation_InterfaceInheritanceScenario10() { // Inherited Interface scenario. string scenarioCode = @" public class ITT : IDerived { void IBase2.method2() { } void IBase3.method3() { } void IDerived.method4() { } } public interface IBase { void method1(); } public interface IBase2 : IBase { void method2(); } public interface IBase3 : IBase { void method3(); } public interface IDerived : IBase2, IBase3 { void method4(); }"; var testAssembly = CreateCompilation(scenarioCode); testAssembly.VerifyDiagnostics( // (2,20): error CS0535: 'ITT' does not implement interface member 'IBase.method1()' // public class ITT : IDerived Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "IDerived").WithArguments("ITT", "IBase.method1()").WithLocation(2, 20)); } [WorkItem(911913, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/911913")] [Fact] public void UnimplementedInterfaceSquiggleLocation_InterfaceInheritanceScenario11() { // Inherited Interface scenario string scenarioCode = @" static class Module1 { public static void Main() { } } interface Ibase { void method1(); } interface Ibase2 { void method2(); } interface Iderived : Ibase { void method3(); } interface Iderived2 : Iderived { void method4(); } class foo : Iderived2, Iderived, Ibase, Ibase2 { void Ibase.method1() { } void Ibase2.method2() { } void Iderived2.method4() { } } "; var testAssembly = CreateCompilation(scenarioCode); testAssembly.VerifyDiagnostics( // (29,24): error CS0535: 'foo' does not implement interface member 'Iderived.method3()' // class foo : Iderived2, Iderived, Ibase, Ibase2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "Iderived").WithArguments("foo", "Iderived.method3()").WithLocation(29, 24)); } [WorkItem(911913, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/911913")] [Fact] public void UnimplementedInterfaceSquiggleLocation_WithPartialClass01() { // partial class - missing method. // each partial implements interface but one is missing method. string scenarioCode = @" public partial class Foo : IBase { void IBase.method1() { } void IBase2.method2() { } } public partial class Foo : IBase2 { } public partial class Foo : IBase3 { } public interface IBase { void method1(); } public interface IBase2 { void method2(); } public interface IBase3 { void method3(); }"; var testAssembly = CreateCompilation(scenarioCode); testAssembly.VerifyDiagnostics( // (15,28): error CS0535: 'Foo' does not implement interface member 'IBase3.method3()' // public partial class Foo : IBase3 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "IBase3").WithArguments("Foo", "IBase3.method3()").WithLocation(15, 28)); } [WorkItem(911913, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/911913")] [Fact] public void UnimplementedInterfaceSquiggleLocation_WithPartialClass02() { // partial class - missing method. diagnostic is reported in correct partial class // one partial class specifically does include any inherited interface string scenarioCode = @" public partial class Foo : IBase, IBase2 { void IBase.method1() { } } public partial class Foo { } public partial class Foo : IBase3 { } public interface IBase { void method1(); } public interface IBase2 { void method2(); } public interface IBase3 { void method3(); }"; var testAssembly = CreateCompilation(scenarioCode); testAssembly.VerifyDiagnostics( // (2,35): error CS0535: 'Foo' does not implement interface member 'IBase2.method2()' // public partial class Foo : IBase, IBase2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "IBase2").WithArguments("Foo", "IBase2.method2()").WithLocation(2, 35), // (13,28): error CS0535: 'Foo' does not implement interface member 'IBase3.method3()' // public partial class Foo : IBase3 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "IBase3").WithArguments("Foo", "IBase3.method3()").WithLocation(13, 28)); } [WorkItem(911913, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/911913")] [Fact] public void UnimplementedInterfaceSquiggleLocation_WithPartialClass03() { // Partial class scenario // One class implements multiple interfaces and is missing method. string scenarioCode = @" public partial class Foo : IBase, IBase2 { void IBase.method1() { } } public partial class Foo : IBase3 { } public interface IBase { void method1(); } public interface IBase2 { void method2(); } public interface IBase3 { void method3(); }"; var testAssembly = CreateCompilation(scenarioCode); testAssembly.VerifyDiagnostics( // (2,35): error CS0535: 'Foo' does not implement interface member 'IBase2.method2()' // public partial class Foo : IBase, IBase2 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "IBase2").WithArguments("Foo", "IBase2.method2()").WithLocation(2, 35), // (9,28): error CS0535: 'Foo' does not implement interface member 'IBase3.method3()' // public partial class Foo : IBase3 Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "IBase3").WithArguments("Foo", "IBase3.method3()").WithLocation(9, 28) ); } [WorkItem(541466, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541466")] [Fact] public void UseSiteErrorViaAliasTest04() { var testAssembly = CreateCompilation( @" using ClassAlias = Class1; public class Test { void m() { int a = ClassAlias.Class1Foo(); int b = ClassAlias.Class1Foo(); } }", references: new List<MetadataReference>() { TestReferences.SymbolsTests.NoPia.NoPIAGenericsAsm1 }) .VerifyDiagnostics( // (2,20): error CS1769: Type 'System.Collections.Generic.List<FooStruct>' from assembly 'NoPIAGenerics1-Asm1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' cannot be used across assembly boundaries because it has a generic type argument that is an embedded interop type. // using ClassAlias = Class1; Diagnostic(ErrorCode.ERR_GenericsUsedAcrossAssemblies, "Class1").WithArguments("System.Collections.Generic.List<FooStruct>", "NoPIAGenerics1-Asm1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (7,28): error CS1769: Type 'System.Collections.Generic.List<FooStruct>' from assembly 'NoPIAGenerics1-Asm1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' cannot be used across assembly boundaries because it has a generic type argument that is an embedded interop type. // int a = ClassAlias.Class1Foo(); Diagnostic(ErrorCode.ERR_GenericsUsedAcrossAssemblies, "Class1Foo").WithArguments("System.Collections.Generic.List<FooStruct>", "NoPIAGenerics1-Asm1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (8,28): error CS1769: Type 'System.Collections.Generic.List<FooStruct>' from assembly 'NoPIAGenerics1-Asm1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' cannot be used across assembly boundaries because it has a generic type argument that is an embedded interop type. // int b = ClassAlias.Class1Foo(); Diagnostic(ErrorCode.ERR_GenericsUsedAcrossAssemblies, "Class1Foo").WithArguments("System.Collections.Generic.List<FooStruct>", "NoPIAGenerics1-Asm1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null") ); // NOTE: Dev10 errors: // <fine-name>(8,28): error CS0117: 'Class1' does not contain a definition for 'Class1Foo' // <fine-name>(9,28): error CS0117: 'Class1' does not contain a definition for 'Class1Foo' } [WorkItem(541466, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541466")] [Fact] public void UseSiteErrorViaAliasTest05() { var testAssembly = CreateCompilation( @" using ClassAlias = Class1; public class Test { void m() { var a = new ClassAlias(); var b = new ClassAlias(); } }", references: new List<MetadataReference>() { TestReferences.SymbolsTests.NoPia.NoPIAGenericsAsm1 }) .VerifyDiagnostics( // (2,20): error CS1769: Type 'System.Collections.Generic.List<FooStruct>' from assembly 'NoPIAGenerics1-Asm1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' cannot be used across assembly boundaries because it has a generic type argument that is an embedded interop type. // using ClassAlias = Class1; Diagnostic(ErrorCode.ERR_GenericsUsedAcrossAssemblies, "Class1").WithArguments("System.Collections.Generic.List<FooStruct>", "NoPIAGenerics1-Asm1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null") ); // NOTE: Dev10 errors: // <fine-name>(8,17): error CS0143: The type 'Class1' has no constructors defined // <fine-name>(9,17): error CS0143: The type 'Class1' has no constructors defined } [WorkItem(541466, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541466")] [Fact] public void UseSiteErrorViaAliasTest06() { var testAssembly = CreateCompilation( @" using ClassAlias = Class1; public class Test { ClassAlias a = null; ClassAlias b = null; ClassAlias m() { return null; } void m2(ClassAlias p) { } }", references: new List<MetadataReference>() { TestReferences.SymbolsTests.NoPia.NoPIAGenericsAsm1 }) .VerifyDiagnostics( // (2,20): error CS1769: Type 'System.Collections.Generic.List<FooStruct>' from assembly 'NoPIAGenerics1-Asm1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' cannot be used across assembly boundaries because it has a generic type argument that is an embedded interop type. // using ClassAlias = Class1; Diagnostic(ErrorCode.ERR_GenericsUsedAcrossAssemblies, "Class1").WithArguments("System.Collections.Generic.List<FooStruct>", "NoPIAGenerics1-Asm1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (6,16): warning CS0414: The field 'Test.b' is assigned but its value is never used // ClassAlias b = null; Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "b").WithArguments("Test.b"), // (5,16): warning CS0414: The field 'Test.a' is assigned but its value is never used // ClassAlias a = null; Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "a").WithArguments("Test.a") ); // NOTE: Dev10 errors: // <fine-name>(4,16): error CS1772: Type 'Class1' from assembly '...\NoPIAGenerics1-Asm1.dll' cannot be used across assembly boundaries because a type in its inheritance hierarchy has a generic type parameter that is an embedded interop type. // <fine-name>(5,16): error CS1772: Type 'Class1' from assembly '...\NoPIAGenerics1-Asm1.dll' cannot be used across assembly boundaries because a type in its inheritance hierarchy has a generic type parameter that is an embedded interop type. // <fine-name>(6,16): error CS1772: Type 'Class1' from assembly '...\NoPIAGenerics1-Asm1.dll' cannot be used across assembly boundaries because a type in its inheritance hierarchy has a generic type parameter that is an embedded interop type. // <fine-name>(7,10): error CS1772: Type 'Class1' from assembly '...\NoPIAGenerics1-Asm1.dll' cannot be used across assembly boundaries because a type in its inheritance hierarchy has a generic type parameter that is an embedded interop type. } [WorkItem(541466, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541466")] [Fact] public void UseSiteErrorViaAliasTest07() { var testAssembly = CreateCompilation( @" using ClassAlias = Class1; public class Test { void m() { ClassAlias a = null; ClassAlias b = null; System.Console.WriteLine(a); System.Console.WriteLine(b); } }", references: new List<MetadataReference>() { TestReferences.SymbolsTests.NoPia.NoPIAGenericsAsm1 }) .VerifyDiagnostics( // (2,20): error CS1769: Type 'System.Collections.Generic.List<FooStruct>' from assembly 'NoPIAGenerics1-Asm1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' cannot be used across assembly boundaries because it has a generic type argument that is an embedded interop type. // using ClassAlias = Class1; Diagnostic(ErrorCode.ERR_GenericsUsedAcrossAssemblies, "Class1").WithArguments("System.Collections.Generic.List<FooStruct>", "NoPIAGenerics1-Asm1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (9,9): error CS1769: Type 'System.Collections.Generic.List<FooStruct>' from assembly 'NoPIAGenerics1-Asm1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' cannot be used across assembly boundaries because it has a generic type argument that is an embedded interop type. // System.Console.WriteLine(a); Diagnostic(ErrorCode.ERR_GenericsUsedAcrossAssemblies, "System.Console.WriteLine").WithArguments("System.Collections.Generic.List<FooStruct>", "NoPIAGenerics1-Asm1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (10,9): error CS1769: Type 'System.Collections.Generic.List<FooStruct>' from assembly 'NoPIAGenerics1-Asm1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' cannot be used across assembly boundaries because it has a generic type argument that is an embedded interop type. // System.Console.WriteLine(b); Diagnostic(ErrorCode.ERR_GenericsUsedAcrossAssemblies, "System.Console.WriteLine").WithArguments("System.Collections.Generic.List<FooStruct>", "NoPIAGenerics1-Asm1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null")); // NOTE: Dev10 reports NO ERRORS } [WorkItem(948674, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/948674")] [Fact] public void UseSiteErrorViaImplementedInterfaceMember_1() { var source1 = @" using System; using System.Runtime.InteropServices; [assembly: ImportedFromTypeLib(""GeneralPIA.dll"")] [assembly: Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")] public struct ImageMoniker { }"; CSharpCompilation comp1 = CreateCompilationWithMscorlib45(source1, assemblyName: "Pia948674_1"); var source2 = @" public interface IBar { ImageMoniker? Moniker { get; } }"; CSharpCompilation comp2 = CreateCompilationWithMscorlib45(source2, new MetadataReference[] { new CSharpCompilationReference(comp1, embedInteropTypes: true) }, assemblyName: "Bar948674_1"); var source3 = @" public class BarImpl : IBar { public ImageMoniker? Moniker { get { return null; } } }"; CSharpCompilation comp3 = CreateCompilationWithMscorlib45(source3, new MetadataReference[] { new CSharpCompilationReference(comp2), new CSharpCompilationReference(comp1, embedInteropTypes: true) }); comp3.VerifyDiagnostics( // (2,24): error CS1769: Type 'ImageMoniker?' from assembly 'Bar948674_1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' cannot be used across assembly boundaries because it has a generic type argument that is an embedded interop type. // public class BarImpl : IBar Diagnostic(ErrorCode.ERR_GenericsUsedAcrossAssemblies, "IBar").WithArguments("ImageMoniker?", "Bar948674_1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(2, 24) ); comp3 = CreateCompilationWithMscorlib45(source3, new MetadataReference[] { comp2.EmitToImageReference(), comp1.EmitToImageReference().WithEmbedInteropTypes(true) }); comp3.VerifyDiagnostics( // (2,24): error CS1769: Type 'ImageMoniker?' from assembly 'Bar948674_1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' cannot be used across assembly boundaries because it has a generic type argument that is an embedded interop type. // public class BarImpl : IBar Diagnostic(ErrorCode.ERR_GenericsUsedAcrossAssemblies, "IBar").WithArguments("ImageMoniker?", "Bar948674_1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(2, 24), // (2,24): error CS1769: Type 'ImageMoniker?' from assembly 'Bar948674_1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' cannot be used across assembly boundaries because it has a generic type argument that is an embedded interop type. // public class BarImpl : IBar Diagnostic(ErrorCode.ERR_GenericsUsedAcrossAssemblies, "IBar").WithArguments("ImageMoniker?", "Bar948674_1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(2, 24) ); } [WorkItem(948674, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/948674")] [Fact] public void UseSiteErrorViaImplementedInterfaceMember_2() { var source1 = @" using System; using System.Runtime.InteropServices; [assembly: ImportedFromTypeLib(""GeneralPIA.dll"")] [assembly: Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")] public struct ImageMoniker { }"; CSharpCompilation comp1 = CreateCompilationWithMscorlib45(source1, assemblyName: "Pia948674_2"); var source2 = @" public interface IBar { ImageMoniker? Moniker { get; } }"; CSharpCompilation comp2 = CreateCompilationWithMscorlib45(source2, new MetadataReference[] { new CSharpCompilationReference(comp1, embedInteropTypes: true) }, assemblyName: "Bar948674_2"); var source3 = @" public class BarImpl : IBar { ImageMoniker? IBar.Moniker { get { return null; } } }"; CSharpCompilation comp3 = CreateCompilationWithMscorlib45(source3, new MetadataReference[] { new CSharpCompilationReference(comp2), new CSharpCompilationReference(comp1, embedInteropTypes: true) }); comp3.VerifyDiagnostics( // (4,24): error CS0539: 'BarImpl.Moniker' in explicit interface declaration is not a member of interface // ImageMoniker? IBar.Moniker Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "Moniker").WithArguments("BarImpl.Moniker").WithLocation(4, 24), // (2,24): error CS1769: Type 'ImageMoniker?' from assembly 'Bar948674_2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' cannot be used across assembly boundaries because it has a generic type argument that is an embedded interop type. // public class BarImpl : IBar Diagnostic(ErrorCode.ERR_GenericsUsedAcrossAssemblies, "IBar").WithArguments("ImageMoniker?", "Bar948674_2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(2, 24) ); comp3 = CreateCompilationWithMscorlib45(source3, new MetadataReference[] { comp2.EmitToImageReference(), comp1.EmitToImageReference().WithEmbedInteropTypes(true) }); comp3.VerifyDiagnostics( // (4,24): error CS0539: 'BarImpl.Moniker' in explicit interface declaration is not a member of interface // ImageMoniker? IBar.Moniker Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "Moniker").WithArguments("BarImpl.Moniker").WithLocation(4, 24), // (2,24): error CS1769: Type 'ImageMoniker?' from assembly 'Bar948674_2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' cannot be used across assembly boundaries because it has a generic type argument that is an embedded interop type. // public class BarImpl : IBar Diagnostic(ErrorCode.ERR_GenericsUsedAcrossAssemblies, "IBar").WithArguments("ImageMoniker?", "Bar948674_2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(2, 24) ); } [WorkItem(948674, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/948674")] [Fact] public void UseSiteErrorViaImplementedInterfaceMember_3() { var source1 = @" using System; using System.Runtime.InteropServices; [assembly: ImportedFromTypeLib(""GeneralPIA.dll"")] [assembly: Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")] public struct ImageMoniker { }"; CSharpCompilation comp1 = CreateCompilationWithMscorlib45(source1, assemblyName: "Pia948674_3"); var source2 = @" public interface IBar { void SetMoniker(ImageMoniker? moniker); }"; CSharpCompilation comp2 = CreateCompilationWithMscorlib45(source2, new MetadataReference[] { new CSharpCompilationReference(comp1, embedInteropTypes: true) }, assemblyName: "Bar948674_3"); var source3 = @" public class BarImpl : IBar { public void SetMoniker(ImageMoniker? moniker) {} }"; CSharpCompilation comp3 = CreateCompilationWithMscorlib45(source3, new MetadataReference[] { new CSharpCompilationReference(comp2), new CSharpCompilationReference(comp1, embedInteropTypes: true) }); comp3.VerifyDiagnostics( // (2,24): error CS1769: Type 'ImageMoniker?' from assembly 'Bar948674_3, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' cannot be used across assembly boundaries because it has a generic type argument that is an embedded interop type. // public class BarImpl : IBar Diagnostic(ErrorCode.ERR_GenericsUsedAcrossAssemblies, "IBar").WithArguments("ImageMoniker?", "Bar948674_3, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(2, 24) ); comp3 = CreateCompilationWithMscorlib45(source3, new MetadataReference[] { comp2.EmitToImageReference(), comp1.EmitToImageReference().WithEmbedInteropTypes(true) }); comp3.VerifyDiagnostics( // (2,24): error CS1769: Type 'ImageMoniker?' from assembly 'Bar948674_3, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' cannot be used across assembly boundaries because it has a generic type argument that is an embedded interop type. // public class BarImpl : IBar Diagnostic(ErrorCode.ERR_GenericsUsedAcrossAssemblies, "IBar").WithArguments("ImageMoniker?", "Bar948674_3, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(2, 24) ); } [WorkItem(948674, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/948674")] [Fact] public void UseSiteErrorViaImplementedInterfaceMember_4() { var source1 = @" using System; using System.Runtime.InteropServices; [assembly: ImportedFromTypeLib(""GeneralPIA.dll"")] [assembly: Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")] public struct ImageMoniker { }"; CSharpCompilation comp1 = CreateCompilationWithMscorlib45(source1, assemblyName: "Pia948674_4"); var source2 = @" public interface IBar { void SetMoniker(ImageMoniker? moniker); }"; CSharpCompilation comp2 = CreateCompilationWithMscorlib45(source2, new MetadataReference[] { new CSharpCompilationReference(comp1, embedInteropTypes: true) }, assemblyName: "Bar948674_4"); var source3 = @" public class BarImpl : IBar { void IBar.SetMoniker(ImageMoniker? moniker) {} }"; CSharpCompilation comp3 = CreateCompilationWithMscorlib45(source3, new MetadataReference[] { new CSharpCompilationReference(comp2), new CSharpCompilationReference(comp1, embedInteropTypes: true) }); comp3.VerifyDiagnostics( // (4,15): error CS0539: 'BarImpl.SetMoniker(ImageMoniker?)' in explicit interface declaration is not a member of interface // void IBar.SetMoniker(ImageMoniker? moniker) Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "SetMoniker").WithArguments("BarImpl.SetMoniker(ImageMoniker?)").WithLocation(4, 15), // (2,24): error CS1769: Type 'ImageMoniker?' from assembly 'Bar948674_4, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' cannot be used across assembly boundaries because it has a generic type argument that is an embedded interop type. // public class BarImpl : IBar Diagnostic(ErrorCode.ERR_GenericsUsedAcrossAssemblies, "IBar").WithArguments("ImageMoniker?", "Bar948674_4, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(2, 24) ); comp3 = CreateCompilationWithMscorlib45(source3, new MetadataReference[] { comp2.EmitToImageReference(), comp1.EmitToImageReference().WithEmbedInteropTypes(true) }); comp3.VerifyDiagnostics( // (4,15): error CS0539: 'BarImpl.SetMoniker(ImageMoniker?)' in explicit interface declaration is not a member of interface // void IBar.SetMoniker(ImageMoniker? moniker) Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "SetMoniker").WithArguments("BarImpl.SetMoniker(ImageMoniker?)").WithLocation(4, 15), // (2,24): error CS1769: Type 'ImageMoniker?' from assembly 'Bar948674_4, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' cannot be used across assembly boundaries because it has a generic type argument that is an embedded interop type. // public class BarImpl : IBar Diagnostic(ErrorCode.ERR_GenericsUsedAcrossAssemblies, "IBar").WithArguments("ImageMoniker?", "Bar948674_4, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(2, 24) ); } [WorkItem(541246, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541246")] [Fact] public void NamespaceQualifiedGenericTypeName() { var source = @"namespace N { public class A<T> { public static T F; } } class B { static int G = N.A<int>.F; }"; CreateCompilation(source).VerifyDiagnostics(); } [Fact] public void NamespaceQualifiedGenericTypeNameWrongArity() { var source = @"namespace N { public class A<T> { public static T F; } public class B { public static int F; } public class B<T1, T2> { public static System.Tuple<T1, T2> F; } } class C { static int TooMany = N.A<int, int>.F; static int TooFew = N.A.F; static int TooIndecisive = N.B<int>; }"; CreateCompilation(source).VerifyDiagnostics( // (19,28): error CS0305: Using the generic type 'N.A<T>' requires '1' type arguments // Diagnostic(ErrorCode.ERR_BadArity, "A<int, int>").WithArguments("N.A<T>", "type", "1"), // (20,27): error CS0305: Using the generic type 'N.A<T>' requires '1' type arguments // Diagnostic(ErrorCode.ERR_BadArity, "A").WithArguments("N.A<T>", "type", "1"), // (21,34): error CS0308: The non-generic type 'N.B' cannot be used with type arguments // Diagnostic(ErrorCode.ERR_HasNoTypeVars, "B<int>").WithArguments("N.B", "type") ); } [WorkItem(541570, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541570")] [Fact] public void EnumNotMemberInConstructor() { var source = @"enum E { A } class C { public C(E e = E.A) { } public E E { get { return E.A; } } }"; CreateCompilation(source).VerifyDiagnostics(); } [WorkItem(541638, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541638")] [Fact] public void KeywordAsLabelIdentifier() { var source = @"class Program { static void Main(string[] args) { @int1: System.Console.WriteLine(); } }"; CreateCompilation(source).VerifyDiagnostics( // (5,5): warning CS0164: This label has not been referenced // Diagnostic(ErrorCode.WRN_UnreferencedLabel, "@int1")); } [WorkItem(541677, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541677")] [Fact] public void AssignStaticEventToLocalVariable() { var source = @"delegate void Foo(); class driver { public static event Foo e; static void Main(string[] args) { Foo x = e; } }"; CreateCompilation(source).VerifyDiagnostics(); } // Note: The locations for errors on generic methods are // name only, while Dev11 uses name + type parameters. [WorkItem(528743, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528743")] [Fact] public void GenericMethodLocation() { var source = @"interface I { void M1<T>() where T : class; } class C : I { public void M1<T>() { } void M2<T>(this object o) { } sealed void M3<T>() { } internal static virtual void M4<T>() { } }"; CreateCompilation(source).VerifyDiagnostics( // (5,7): error CS1106: Extension method must be defined in a non-generic static class // class C : I Diagnostic(ErrorCode.ERR_BadExtensionAgg, "C").WithLocation(5, 7), // (7,17): error CS0425: The constraints for type parameter 'T' of method 'C.M1<T>()' must match the constraints for type parameter 'T' of interface method 'I.M1<T>()'. Consider using an explicit interface implementation instead. // public void M1<T>() { } Diagnostic(ErrorCode.ERR_ImplBadConstraints, "M1").WithArguments("T", "C.M1<T>()", "T", "I.M1<T>()").WithLocation(7, 17), // (9,17): error CS0238: 'C.M3<T>()' cannot be sealed because it is not an override // sealed void M3<T>() { } Diagnostic(ErrorCode.ERR_SealedNonOverride, "M3").WithArguments("C.M3<T>()").WithLocation(9, 17), // (10,34): error CS0112: A static member cannot be marked as 'virtual' // internal static virtual void M4<T>() { } Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M4").WithArguments("virtual").WithLocation(10, 34) ); } [WorkItem(542391, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542391")] [Fact] public void PartialMethodOptionalParameters() { var source = @"partial class C { partial void M1(object o); partial void M1(object o = null) { } partial void M2(object o = null); partial void M2(object o) { } partial void M3(object o = null); partial void M3(object o = null) { } }"; CreateCompilation(source).VerifyDiagnostics( // (4,28): warning CS1066: The default value specified for parameter 'o' will have no effect because it applies to a member that is used in contexts that do not allow optional arguments // partial void M1(object o = null) { } Diagnostic(ErrorCode.WRN_DefaultValueForUnconsumedLocation, "o").WithArguments("o"), // (8,28): warning CS1066: The default value specified for parameter 'o' will have no effect because it applies to a member that is used in contexts that do not allow optional arguments // partial void M3(object o = null) { } Diagnostic(ErrorCode.WRN_DefaultValueForUnconsumedLocation, "o").WithArguments("o") ); } [Fact] [WorkItem(598043, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/598043")] public void PartialMethodParameterNamesFromDefinition1() { var source = @" partial class C { partial void F(int i); } partial class C { partial void F(int j) { } } "; CompileAndVerify(source, options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.All), symbolValidator: module => { var method = module.GlobalNamespace.GetMember<TypeSymbol>("C").GetMember<MethodSymbol>("F"); Assert.Equal("i", method.Parameters[0].Name); }); } [Fact] [WorkItem(598043, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/598043")] public void PartialMethodParameterNamesFromDefinition2() { var source = @" partial class C { partial void F(int j) { } } partial class C { partial void F(int i); } "; CompileAndVerify(source, options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.All), symbolValidator: module => { var method = module.GlobalNamespace.GetMember<TypeSymbol>("C").GetMember<MethodSymbol>("F"); Assert.Equal("i", method.Parameters[0].Name); }); } /// <summary> /// Handle a mix of parameter errors for default values, /// partial methods, and static parameter type. /// </summary> [Fact] public void ParameterErrorsDefaultPartialMethodStaticType() { var source = @"static class S { } partial class C { partial void M(S s = new A()); partial void M(S s = new B()) { } }"; CreateCompilation(source).VerifyDiagnostics( // (4,18): error CS0721: 'S': static types cannot be used as parameters // partial void M(S s = new A()); Diagnostic(ErrorCode.ERR_ParameterIsStaticClass, "M").WithArguments("S").WithLocation(4, 18), // (5,18): error CS0721: 'S': static types cannot be used as parameters // partial void M(S s = new B()) { } Diagnostic(ErrorCode.ERR_ParameterIsStaticClass, "M").WithArguments("S").WithLocation(5, 18), // (5,30): error CS0246: The type or namespace name 'B' could not be found (are you missing a using directive or an assembly reference?) // partial void M(S s = new B()) { } Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "B").WithArguments("B").WithLocation(5, 30), // (4,30): error CS0246: The type or namespace name 'A' could not be found (are you missing a using directive or an assembly reference?) // partial void M(S s = new A()); Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "A").WithArguments("A").WithLocation(4, 30) ); } [WorkItem(543349, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543349")] [Fact] public void Fixed() { var source = @"class C { unsafe static void M(int[] arg) { fixed (int* ptr = arg) { } fixed (int* ptr = arg) *ptr = 0; fixed (int* ptr = arg) object o = null; } }"; CreateCompilation(source, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (7,32): error CS1023: Embedded statement cannot be a declaration or labeled statement // fixed (int* ptr = arg) object o = null; Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "object o = null;").WithLocation(7, 32), // (7,39): warning CS0219: The variable 'o' is assigned but its value is never used // fixed (int* ptr = arg) object o = null; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "o").WithArguments("o").WithLocation(7, 39) ); } [WorkItem(1040171, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1040171")] [Fact] public void Bug1040171() { const string sourceCode = @" class Program { static void Main(string[] args) { bool c = true; foreach (string s in args) label: c = false; } } "; var compilation = CreateCompilation(sourceCode); compilation.VerifyDiagnostics( // (9,13): error CS1023: Embedded statement cannot be a declaration or labeled statement // label: c = false; Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "label: c = false;").WithLocation(9, 13), // (9,13): warning CS0164: This label has not been referenced // label: c = false; Diagnostic(ErrorCode.WRN_UnreferencedLabel, "label").WithLocation(9, 13), // (6,14): warning CS0219: The variable 'c' is assigned but its value is never used // bool c = true; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "c").WithArguments("c").WithLocation(6, 14)); } [Fact, WorkItem(543426, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543426")] private void NestedInterfaceImplementationWithOuterGenericType() { CompileAndVerify(@" namespace System.ServiceModel { class Pipeline<T> { interface IStage { void Process(T context); } class AsyncStage : IStage { void IStage.Process(T context) { } } } }"); } /// <summary> /// Error types should be allowed as constant types. /// </summary> [Fact] public void ErrorTypeConst() { var source = @"class C { const C1 F1 = 0; const C2 F2 = null; static void M() { const C3 c3 = 0; const C4 c4 = null; } }"; CreateCompilation(source).VerifyDiagnostics( // (3,11): error CS0246: The type or namespace name 'C1' could not be found (are you missing a using directive or an assembly reference?) Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "C1").WithArguments("C1").WithLocation(3, 11), // (4,11): error CS0246: The type or namespace name 'C2' could not be found (are you missing a using directive or an assembly reference?) Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "C2").WithArguments("C2").WithLocation(4, 11), // (7,15): error CS0246: The type or namespace name 'C3' could not be found (are you missing a using directive or an assembly reference?) Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "C3").WithArguments("C3").WithLocation(7, 15), // (8,15): error CS0246: The type or namespace name 'C4' could not be found (are you missing a using directive or an assembly reference?) Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "C4").WithArguments("C4").WithLocation(8, 15)); } [WorkItem(543777, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543777")] [Fact] public void DefaultParameterAtEndOfFile() { var source = @"class C { static void M(object o = null,"; CreateCompilation(source).VerifyDiagnostics( // (3,35): error CS1031: Type expected // static void M(object o = null, Diagnostic(ErrorCode.ERR_TypeExpected, ""), // Cascading: // (3,35): error CS1001: Identifier expected // static void M(object o = null, Diagnostic(ErrorCode.ERR_IdentifierExpected, ""), // (3,35): error CS1026: ) expected // static void M(object o = null, Diagnostic(ErrorCode.ERR_CloseParenExpected, ""), // (3,35): error CS1002: ; expected // static void M(object o = null, Diagnostic(ErrorCode.ERR_SemicolonExpected, ""), // (3,35): error CS1513: } expected // static void M(object o = null, Diagnostic(ErrorCode.ERR_RbraceExpected, ""), // (3,35): error CS1737: Optional parameters must appear after all required parameters // static void M(object o = null, Diagnostic(ErrorCode.ERR_DefaultValueBeforeRequiredValue, ""), // (3,17): error CS0501: 'C.M(object, ?)' must declare a body because it is not // marked abstract, extern, or partial static void M(object o = null, Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "M").WithArguments("C.M(object, ?)")); } [WorkItem(543814, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543814")] [Fact] public void DuplicateNamedArgumentNullLiteral() { var source = @"class C { static void M() { M("""", arg: 0, arg: null); } }"; CreateCompilation(source).VerifyDiagnostics( // (5,9): error CS1501: No overload for method 'M' takes 3 arguments // M("", Diagnostic(ErrorCode.ERR_BadArgCount, "M").WithArguments("M", "3").WithLocation(5, 9)); } [WorkItem(543820, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543820")] [Fact] public void GenericAttributeClassWithMultipleParts() { var source = @"class C<T> { } class C<T> : System.Attribute { }"; CreateCompilation(source).VerifyDiagnostics( // (2,7): error CS0101: The namespace '<global namespace>' already contains a definition for 'C' // class C<T> : System.Attribute { } Diagnostic(ErrorCode.ERR_DuplicateNameInNS, "C").WithArguments("C", "<global namespace>"), // (2,14): error CS0698: A generic type cannot derive from 'System.Attribute' because it is an attribute class // class C<T> : System.Attribute { } Diagnostic(ErrorCode.ERR_GenericDerivingFromAttribute, "System.Attribute").WithArguments("System.Attribute") ); } [WorkItem(543822, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543822")] [Fact] public void InterfaceWithPartialMethodExplicitImplementation() { var source = @"interface I { partial void I.M(); }"; CreateCompilation(source, parseOptions: TestOptions.Regular7, targetFramework: TargetFramework.NetCoreApp).VerifyDiagnostics( // (3,20): error CS0754: A partial method may not explicitly implement an interface method // partial void I.M(); Diagnostic(ErrorCode.ERR_PartialMethodNotExplicit, "M").WithLocation(3, 20), // (3,20): error CS0751: A partial method must be declared within a partial type // partial void I.M(); Diagnostic(ErrorCode.ERR_PartialMethodOnlyInPartialClass, "M").WithLocation(3, 20), // (3,20): error CS8652: The feature 'default interface implementation' is not available in C# 7.0. Please use language version 8.0 or greater. // partial void I.M(); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "M").WithArguments("default interface implementation", "8.0").WithLocation(3, 20), // (3,18): error CS0540: 'I.M()': containing type does not implement interface 'I' // partial void I.M(); Diagnostic(ErrorCode.ERR_ClassDoesntImplementInterface, "I").WithArguments("I.M()", "I").WithLocation(3, 18) ); } [WorkItem(543827, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543827")] [Fact] public void StructConstructor() { var source = @"struct S { private readonly object x; private readonly object y; S(object x, object y) { try { this.x = x; } finally { this.y = y; } } S(S o) : this(o.x, o.y) {} }"; CreateCompilation(source).VerifyDiagnostics(); } [WorkItem(543827, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543827")] [Fact] public void StructVersusTryFinally() { var source = @"struct S { private object x; private object y; static void M() { S s1; try { s1.x = null; } finally { s1.y = null; } S s2 = s1; s1.x = s1.y; s1.y = s1.x; } }"; CreateCompilation(source).VerifyDiagnostics(); } [WorkItem(544513, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544513")] [Fact()] public void AnonTypesPropSameNameDiffType() { var source = @"public class Test { public static void Main() { var p1 = new { Price = 495.00 }; var p2 = new { Price = ""36.50"" }; p1 = p2; } }"; CreateCompilation(source).VerifyDiagnostics( // (8,14): error CS0029: Cannot implicitly convert type 'AnonymousType#1' to 'AnonymousType#2' // p1 = p2; Diagnostic(ErrorCode.ERR_NoImplicitConv, "p2").WithArguments("<anonymous type: string Price>", "<anonymous type: double Price>")); } [WorkItem(545869, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545869")] [Fact] public void TestSealedOverriddenMembers() { CompileAndVerify( @"using System; internal abstract class Base { public virtual int Property { get { return 0; } protected set { } } protected virtual event EventHandler Event { add { } remove { } } protected abstract void Method(); } internal sealed class Derived : Base { public override int Property { get { return 1; } protected set { } } protected override event EventHandler Event; protected override void Method() { } void UseEvent() { Event(null, null); } } internal sealed class Derived2 : Base { public override int Property { get; protected set; } protected override event EventHandler Event { add { } remove { } } protected override void Method() { } } class Program { static void Main() { } }").VerifyDiagnostics(); } [Fact, WorkItem(1068547, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1068547")] public void Bug1068547_01() { var source = @" class Program { [System.Diagnostics.DebuggerDisplay(this)] static void Main(string[] args) { } }"; var comp = CreateCompilation(source); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var node = tree.GetRoot().DescendantNodes().Where(n => n.IsKind(SyntaxKind.ThisExpression)).Cast<ThisExpressionSyntax>().Single(); var symbolInfo = model.GetSymbolInfo(node); Assert.Null(symbolInfo.Symbol); Assert.Equal(CandidateReason.NotReferencable, symbolInfo.CandidateReason); } [Fact, WorkItem(1068547, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1068547")] public void Bug1068547_02() { var source = @" [System.Diagnostics.DebuggerDisplay(this)] "; var comp = CreateCompilation(source); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var node = tree.GetRoot().DescendantNodes().Where(n => n.IsKind(SyntaxKind.ThisExpression)).Cast<ThisExpressionSyntax>().Single(); var symbolInfo = model.GetSymbolInfo(node); Assert.Null(symbolInfo.Symbol); Assert.Equal(CandidateReason.NotReferencable, symbolInfo.CandidateReason); } [Fact] public void RefReturningDelegateCreation() { var text = @" delegate ref int D(); class C { int field = 0; ref int M() { return ref field; } void Test() { new D(M)(); } } "; CreateCompilationWithMscorlib45(text).VerifyDiagnostics(); } [Fact] public void RefReturningDelegateCreationBad() { var text = @" delegate ref int D(); class C { int field = 0; int M() { return field; } void Test() { new D(M)(); } } "; CreateCompilationWithMscorlib45(text, parseOptions: TestOptions.WithoutImprovedOverloadCandidates).VerifyDiagnostics( // (15,15): error CS8189: Ref mismatch between 'C.M()' and delegate 'D' // new D(M)(); Diagnostic(ErrorCode.ERR_DelegateRefMismatch, "M").WithArguments("C.M()", "D").WithLocation(15, 15) ); CreateCompilationWithMscorlib45(text).VerifyDiagnostics( // (15,15): error CS8189: Ref mismatch between 'C.M()' and delegate 'D' // new D(M)(); Diagnostic(ErrorCode.ERR_DelegateRefMismatch, "M").WithArguments("C.M()", "D").WithLocation(15, 15) ); } [Fact] public void RefReturningDelegateArgument() { var text = @" delegate ref int D(); class C { int field = 0; ref int M() { return ref field; } void M(D d) { } void Test() { M(M); } } "; CreateCompilationWithMscorlib45(text).VerifyDiagnostics(); } [Fact] public void RefReturningDelegateArgumentBad() { var text = @" delegate ref int D(); class C { int field = 0; int M() { return field; } void M(D d) { } void Test() { M(M); } } "; CreateCompilationWithMscorlib45(text, parseOptions: TestOptions.WithoutImprovedOverloadCandidates).VerifyDiagnostics( // (19,11): error CS8189: Ref mismatch between 'C.M()' and delegate 'D' // M(M); Diagnostic(ErrorCode.ERR_DelegateRefMismatch, "M").WithArguments("C.M()", "D").WithLocation(19, 11) ); CreateCompilationWithMscorlib45(text).VerifyDiagnostics( // (19,11): error CS8189: Ref mismatch between 'C.M()' and delegate 'D' // M(M); Diagnostic(ErrorCode.ERR_DelegateRefMismatch, "M").WithArguments("C.M()", "D").WithLocation(19, 11) ); } [Fact, WorkItem(1078958, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1078958")] public void Bug1078958() { const string source = @" class C { static void Foo<T>() { T(); } static void T() { } }"; CreateCompilation(source).VerifyDiagnostics( // (6,9): error CS0119: 'T' is a type, which is not valid in the given context // T(); Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type").WithLocation(6, 9)); } [Fact, WorkItem(1078958, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1078958")] public void Bug1078958_2() { const string source = @" class C { static void Foo<T>() { T<T>(); } static void T() { } static void T<U>() { } }"; CreateCompilation(source).VerifyDiagnostics(); } [Fact, WorkItem(1078961, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1078961")] public void Bug1078961() { const string source = @" class C { const int T = 42; static void Foo<T>(int x = T) { System.Console.Write(x); } static void Main() { Foo<object>(); } }"; CompileAndVerify(source, expectedOutput: "42"); } [Fact, WorkItem(1078961, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1078961")] public void Bug1078961_2() { const string source = @" class A : System.Attribute { public A(int i) { } } class C { const int T = 42; static void Foo<T>([A(T)] int x) { } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); var c = comp.GlobalNamespace.GetTypeMembers("C").Single(); var t = (FieldSymbol)c.GetMembers("T").Single(); var foo = (MethodSymbol)c.GetMembers("Foo").Single(); var x = foo.Parameters[0]; var a = x.GetAttributes()[0]; var i = a.ConstructorArguments.Single(); Assert.Equal((int)i.Value, (int)t.ConstantValue); } [Fact, WorkItem(1078961, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1078961")] public void Bug1078961_3() { const string source = @" class A : System.Attribute { public A(int i) { } } class C { const int T = 42; [A(T)] static void Foo<T>(int x) { } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); var c = comp.GlobalNamespace.GetTypeMembers("C").Single(); var t = (FieldSymbol)c.GetMembers("T").Single(); var foo = (MethodSymbol)c.GetMembers("Foo").Single(); var a = foo.GetAttributes()[0]; var i = a.ConstructorArguments.Single(); Assert.Equal((int)i.Value, (int)t.ConstantValue); } [Fact, WorkItem(1078961, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1078961")] public void Bug1078961_4() { const string source = @" class A : System.Attribute { public A(int i) { } } class C { const int T = 42; static void Foo<[A(T)] T>(int x) { } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); var c = comp.GlobalNamespace.GetTypeMembers("C").Single(); var t = (FieldSymbol)c.GetMembers("T").Single(); var foo = (MethodSymbol)c.GetMembers("Foo").Single(); var tt = foo.TypeParameters[0]; var a = tt.GetAttributes()[0]; var i = a.ConstructorArguments.Single(); Assert.Equal((int)i.Value, (int)t.ConstantValue); } [Fact, WorkItem(1078961, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1078961")] public void Bug1078961_5() { const string source = @" class C { class T { } static void Foo<T>(T x = default(T)) { System.Console.Write((object)x == null); } static void Main() { Foo<object>(); } }"; CompileAndVerify(source, expectedOutput: "True"); } [Fact, WorkItem(3096, "https://github.com/dotnet/roslyn/issues/3096")] public void CastToDelegate_01() { var sourceText = @"namespace NS { public static class A { public delegate void Action(); public static void M() { RunAction(A.B<string>.M0); RunAction((Action)A.B<string>.M1); } private static void RunAction(Action action) { } private class B<T> { public static void M0() { } public static void M1() { } } } }"; var compilation = CreateCompilation(sourceText, options: TestOptions.DebugDll); compilation.VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var identifierNameM0 = tree .GetRoot() .DescendantNodes() .OfType<IdentifierNameSyntax>() .First(x => x.Parent.IsKind(SyntaxKind.SimpleMemberAccessExpression) && x.Identifier.ValueText.Equals("M0")); Assert.Equal("A.B<string>.M0", identifierNameM0.Parent.ToString()); var m0Symbol = model.GetSymbolInfo(identifierNameM0); Assert.Equal("void NS.A.B<System.String>.M0()", m0Symbol.Symbol.ToTestDisplayString()); Assert.Equal(CandidateReason.None, m0Symbol.CandidateReason); var identifierNameM1 = tree .GetRoot() .DescendantNodes() .OfType<IdentifierNameSyntax>() .First(x => x.Parent.IsKind(SyntaxKind.SimpleMemberAccessExpression) && x.Identifier.ValueText.Equals("M1")); Assert.Equal("A.B<string>.M1", identifierNameM1.Parent.ToString()); var m1Symbol = model.GetSymbolInfo(identifierNameM1); Assert.Equal("void NS.A.B<System.String>.M1()", m1Symbol.Symbol.ToTestDisplayString()); Assert.Equal(CandidateReason.None, m1Symbol.CandidateReason); } [Fact, WorkItem(3096, "https://github.com/dotnet/roslyn/issues/3096")] public void CastToDelegate_02() { var sourceText = @" class A { public delegate void MyDelegate<T>(T a); public void Test() { UseMyDelegate((MyDelegate<int>)MyMethod); UseMyDelegate((MyDelegate<long>)MyMethod); UseMyDelegate((MyDelegate<float>)MyMethod); UseMyDelegate((MyDelegate<double>)MyMethod); } private void UseMyDelegate<T>(MyDelegate<T> f) { } private static void MyMethod(int a) { } private static void MyMethod(long a) { } private static void MyMethod(float a) { } private static void MyMethod(double a) { } }"; var compilation = CreateCompilation(sourceText, options: TestOptions.DebugDll); compilation.VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var identifiers = tree .GetRoot() .DescendantNodes() .OfType<IdentifierNameSyntax>() .Where(x => x.Identifier.ValueText.Equals("MyMethod")).ToArray(); Assert.Equal(4, identifiers.Length); Assert.Equal("(MyDelegate<int>)MyMethod", identifiers[0].Parent.ToString()); Assert.Equal("void A.MyMethod(System.Int32 a)", model.GetSymbolInfo(identifiers[0]).Symbol.ToTestDisplayString()); Assert.Equal("(MyDelegate<long>)MyMethod", identifiers[1].Parent.ToString()); Assert.Equal("void A.MyMethod(System.Int64 a)", model.GetSymbolInfo(identifiers[1]).Symbol.ToTestDisplayString()); Assert.Equal("(MyDelegate<float>)MyMethod", identifiers[2].Parent.ToString()); Assert.Equal("void A.MyMethod(System.Single a)", model.GetSymbolInfo(identifiers[2]).Symbol.ToTestDisplayString()); Assert.Equal("(MyDelegate<double>)MyMethod", identifiers[3].Parent.ToString()); Assert.Equal("void A.MyMethod(System.Double a)", model.GetSymbolInfo(identifiers[3]).Symbol.ToTestDisplayString()); } [Fact, WorkItem(3096, "https://github.com/dotnet/roslyn/issues/3096")] public void CastToDelegate_03() { var sourceText = @"namespace NS { public static class A { public delegate void Action(); public static void M() { var b = new A.B<string>(); RunAction(b.M0); RunAction((Action)b.M1); } private static void RunAction(Action action) { } public class B<T> { } public static void M0<T>(this B<T> x) { } public static void M1<T>(this B<T> x) { } } }"; var compilation = CreateCompilationWithMscorlib40AndSystemCore(sourceText, options: TestOptions.DebugDll); compilation.VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var identifierNameM0 = tree .GetRoot() .DescendantNodes() .OfType<IdentifierNameSyntax>() .First(x => x.Parent.IsKind(SyntaxKind.SimpleMemberAccessExpression) && x.Identifier.ValueText.Equals("M0")); Assert.Equal("b.M0", identifierNameM0.Parent.ToString()); var m0Symbol = model.GetSymbolInfo(identifierNameM0); Assert.Equal("void NS.A.B<System.String>.M0<System.String>()", m0Symbol.Symbol.ToTestDisplayString()); Assert.Equal(CandidateReason.None, m0Symbol.CandidateReason); var identifierNameM1 = tree .GetRoot() .DescendantNodes() .OfType<IdentifierNameSyntax>() .First(x => x.Parent.IsKind(SyntaxKind.SimpleMemberAccessExpression) && x.Identifier.ValueText.Equals("M1")); Assert.Equal("b.M1", identifierNameM1.Parent.ToString()); var m1Symbol = model.GetSymbolInfo(identifierNameM1); Assert.Equal("void NS.A.B<System.String>.M1<System.String>()", m1Symbol.Symbol.ToTestDisplayString()); Assert.Equal(CandidateReason.None, m1Symbol.CandidateReason); } [Fact, WorkItem(5170, "https://github.com/dotnet/roslyn/issues/5170")] public void TypeOfBinderParameter() { var sourceText = @" using System.Linq; using System.Text; public static class LazyToStringExtension { public static string LazyToString<T>(this T obj) where T : class { StringBuilder sb = new StringBuilder(); typeof(T) .GetProperties(System.Reflection.BindingFlags.Public) .Select(x => x.GetValue(obj)) } }"; var compilation = CreateCompilationWithMscorlib40(sourceText, new[] { TestMetadata.Net40.SystemCore }, options: TestOptions.DebugDll); compilation.VerifyDiagnostics( // (12,42): error CS1002: ; expected // .Select(x => x.GetValue(obj)) Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(12, 42), // (12,28): error CS1501: No overload for method 'GetValue' takes 1 arguments // .Select(x => x.GetValue(obj)) Diagnostic(ErrorCode.ERR_BadArgCount, "GetValue").WithArguments("GetValue", "1").WithLocation(12, 28), // (7,26): error CS0161: 'LazyToStringExtension.LazyToString<T>(T)': not all code paths return a value // public static string LazyToString<T>(this T obj) where T : class Diagnostic(ErrorCode.ERR_ReturnExpected, "LazyToString").WithArguments("LazyToStringExtension.LazyToString<T>(T)").WithLocation(7, 26)); var tree = compilation.SyntaxTrees[0]; var model = compilation.GetSemanticModel(tree); var node = tree.GetRoot().DescendantNodes().Where(n => n.IsKind(SyntaxKind.SimpleLambdaExpression)).Single(); var param = node.ChildNodes().Where(n => n.IsKind(SyntaxKind.Parameter)).Single(); Assert.Equal("System.Reflection.PropertyInfo x", model.GetDeclaredSymbol(param).ToTestDisplayString()); } [Fact, WorkItem(7520, "https://github.com/dotnet/roslyn/issues/7520")] public void DelegateCreationWithIncompleteLambda() { var source = @" using System; class C { public void F() { var x = new Action<int>(i => i. } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (7,40): error CS1001: Identifier expected // var x = new Action<int>(i => i. Diagnostic(ErrorCode.ERR_IdentifierExpected, "").WithLocation(7, 40), // (7,40): error CS1026: ) expected // var x = new Action<int>(i => i. Diagnostic(ErrorCode.ERR_CloseParenExpected, "").WithLocation(7, 40), // (7,40): error CS1002: ; expected // var x = new Action<int>(i => i. Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(7, 40), // (7,38): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement // var x = new Action<int>(i => i. Diagnostic(ErrorCode.ERR_IllegalStatement, @"i. ").WithLocation(7, 38) ); 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(7520, "https://github.com/dotnet/roslyn/issues/7520")] public void ImplicitDelegateCreationWithIncompleteLambda() { var source = @" using System; class C { public void F() { Action<int> x = i => i. } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (7,32): error CS1001: Identifier expected // Action<int> x = i => i. Diagnostic(ErrorCode.ERR_IdentifierExpected, "").WithLocation(7, 32), // (7,32): error CS1002: ; expected // Action<int> x = i => i. Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(7, 32), // (7,30): 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, 30) ); 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(5128, "https://github.com/dotnet/roslyn/issues/5128")] public void GetMemberGroupInsideIncompleteLambda_01() { var source = @" using System; using System.Threading.Tasks; public delegate Task RequestDelegate(HttpContext context); public class AuthenticationResult { } public abstract class AuthenticationManager { public abstract Task<AuthenticationResult> AuthenticateAsync(string authenticationScheme); } public abstract class HttpContext { public abstract AuthenticationManager Authentication { get; } } interface IApplicationBuilder { IApplicationBuilder Use(Func<RequestDelegate, RequestDelegate> middleware); } static class IApplicationBuilderExtensions { public static IApplicationBuilder Use(this IApplicationBuilder app, Func<HttpContext, Func<Task>, Task> middleware) { return app; } } class C { void M(IApplicationBuilder app) { app.Use(async (ctx, next) => { await ctx.Authentication.AuthenticateAsync(); }); } } "; var comp = CreateCompilationWithMscorlib40(source, new[] { TestMetadata.Net40.SystemCore }); comp.VerifyDiagnostics( // (41,38): error CS7036: There is no argument given that corresponds to the required formal parameter 'authenticationScheme' of 'AuthenticationManager.AuthenticateAsync(string)' // await ctx.Authentication.AuthenticateAsync(); Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "AuthenticateAsync").WithArguments("authenticationScheme", "AuthenticationManager.AuthenticateAsync(string)").WithLocation(38, 38) ); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var node1 = tree.GetRoot().DescendantNodes().Where(n => n.IsKind(SyntaxKind.IdentifierName) && ((IdentifierNameSyntax)n).Identifier.ValueText == "Use").Single().Parent; Assert.Equal("app.Use", node1.ToString()); var group1 = model.GetMemberGroup(node1); Assert.Equal(2, group1.Length); Assert.Equal("IApplicationBuilder IApplicationBuilder.Use(System.Func<RequestDelegate, RequestDelegate> middleware)", group1[0].ToTestDisplayString()); Assert.Equal("IApplicationBuilder IApplicationBuilder.Use(System.Func<HttpContext, System.Func<System.Threading.Tasks.Task>, System.Threading.Tasks.Task> middleware)", group1[1].ToTestDisplayString()); var symbolInfo1 = model.GetSymbolInfo(node1); Assert.Null(symbolInfo1.Symbol); Assert.Equal(1, symbolInfo1.CandidateSymbols.Length); Assert.Equal("IApplicationBuilder IApplicationBuilder.Use(System.Func<RequestDelegate, RequestDelegate> middleware)", symbolInfo1.CandidateSymbols.Single().ToTestDisplayString()); Assert.Equal(CandidateReason.OverloadResolutionFailure, symbolInfo1.CandidateReason); var node = tree.GetRoot().DescendantNodes().Where(n => n.IsKind(SyntaxKind.IdentifierName) && ((IdentifierNameSyntax)n).Identifier.ValueText == "AuthenticateAsync").Single().Parent; Assert.Equal("ctx.Authentication.AuthenticateAsync", node.ToString()); var group = model.GetMemberGroup(node); Assert.Equal("System.Threading.Tasks.Task<AuthenticationResult> AuthenticationManager.AuthenticateAsync(System.String authenticationScheme)", group.Single().ToTestDisplayString()); } [Fact, WorkItem(5128, "https://github.com/dotnet/roslyn/issues/5128")] public void GetMemberGroupInsideIncompleteLambda_02() { var source = @" using System; using System.Threading.Tasks; public delegate Task RequestDelegate(HttpContext context); public class AuthenticationResult { } public abstract class AuthenticationManager { public abstract Task<AuthenticationResult> AuthenticateAsync(string authenticationScheme); } public abstract class HttpContext { public abstract AuthenticationManager Authentication { get; } } interface IApplicationBuilder { IApplicationBuilder Use(Func<HttpContext, Func<Task>, Task> middleware); } static class IApplicationBuilderExtensions { public static IApplicationBuilder Use(this IApplicationBuilder app, Func<RequestDelegate, RequestDelegate> middleware) { return app; } } class C { void M(IApplicationBuilder app) { app.Use(async (ctx, next) => { await ctx.Authentication.AuthenticateAsync(); }); } } "; var comp = CreateCompilationWithMscorlib40(source, new[] { TestMetadata.Net40.SystemCore }); comp.VerifyDiagnostics( // (41,38): error CS7036: There is no argument given that corresponds to the required formal parameter 'authenticationScheme' of 'AuthenticationManager.AuthenticateAsync(string)' // await ctx.Authentication.AuthenticateAsync(); Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "AuthenticateAsync").WithArguments("authenticationScheme", "AuthenticationManager.AuthenticateAsync(string)").WithLocation(38, 38) ); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var node1 = tree.GetRoot().DescendantNodes().Where(n => n.IsKind(SyntaxKind.IdentifierName) && ((IdentifierNameSyntax)n).Identifier.ValueText == "Use").Single().Parent; Assert.Equal("app.Use", node1.ToString()); var group1 = model.GetMemberGroup(node1); Assert.Equal(2, group1.Length); Assert.Equal("IApplicationBuilder IApplicationBuilder.Use(System.Func<HttpContext, System.Func<System.Threading.Tasks.Task>, System.Threading.Tasks.Task> middleware)", group1[0].ToTestDisplayString()); Assert.Equal("IApplicationBuilder IApplicationBuilder.Use(System.Func<RequestDelegate, RequestDelegate> middleware)", group1[1].ToTestDisplayString()); var symbolInfo1 = model.GetSymbolInfo(node1); Assert.Null(symbolInfo1.Symbol); Assert.Equal(1, symbolInfo1.CandidateSymbols.Length); Assert.Equal("IApplicationBuilder IApplicationBuilder.Use(System.Func<HttpContext, System.Func<System.Threading.Tasks.Task>, System.Threading.Tasks.Task> middleware)", symbolInfo1.CandidateSymbols.Single().ToTestDisplayString()); Assert.Equal(CandidateReason.OverloadResolutionFailure, symbolInfo1.CandidateReason); var node = tree.GetRoot().DescendantNodes().Where(n => n.IsKind(SyntaxKind.IdentifierName) && ((IdentifierNameSyntax)n).Identifier.ValueText == "AuthenticateAsync").Single().Parent; Assert.Equal("ctx.Authentication.AuthenticateAsync", node.ToString()); var group = model.GetMemberGroup(node); Assert.Equal("System.Threading.Tasks.Task<AuthenticationResult> AuthenticationManager.AuthenticateAsync(System.String authenticationScheme)", group.Single().ToTestDisplayString()); } [Fact, WorkItem(5128, "https://github.com/dotnet/roslyn/issues/5128")] public void GetMemberGroupInsideIncompleteLambda_03() { var source = @" using System; using System.Threading.Tasks; public delegate Task RequestDelegate(HttpContext context); public class AuthenticationResult { } public abstract class AuthenticationManager { public abstract Task<AuthenticationResult> AuthenticateAsync(string authenticationScheme); } public abstract class HttpContext { public abstract AuthenticationManager Authentication { get; } } interface IApplicationBuilder { IApplicationBuilder Use(Func<RequestDelegate, RequestDelegate> middleware); IApplicationBuilder Use(Func<HttpContext, Func<Task>, Task> middleware); } class C { void M(IApplicationBuilder app) { app.Use(async (ctx, next) => { await ctx.Authentication.AuthenticateAsync(); }); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (41,38): error CS7036: There is no argument given that corresponds to the required formal parameter 'authenticationScheme' of 'AuthenticationManager.AuthenticateAsync(string)' // await ctx.Authentication.AuthenticateAsync(); Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "AuthenticateAsync").WithArguments("authenticationScheme", "AuthenticationManager.AuthenticateAsync(string)").WithLocation(31, 38) ); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var node1 = tree.GetRoot().DescendantNodes().Where(n => n.IsKind(SyntaxKind.IdentifierName) && ((IdentifierNameSyntax)n).Identifier.ValueText == "Use").Single().Parent; Assert.Equal("app.Use", node1.ToString()); var group1 = model.GetMemberGroup(node1); Assert.Equal(2, group1.Length); Assert.Equal("IApplicationBuilder IApplicationBuilder.Use(System.Func<RequestDelegate, RequestDelegate> middleware)", group1[0].ToTestDisplayString()); Assert.Equal("IApplicationBuilder IApplicationBuilder.Use(System.Func<HttpContext, System.Func<System.Threading.Tasks.Task>, System.Threading.Tasks.Task> middleware)", group1[1].ToTestDisplayString()); var symbolInfo1 = model.GetSymbolInfo(node1); Assert.Null(symbolInfo1.Symbol); Assert.Equal(2, symbolInfo1.CandidateSymbols.Length); Assert.Equal("IApplicationBuilder IApplicationBuilder.Use(System.Func<RequestDelegate, RequestDelegate> middleware)", symbolInfo1.CandidateSymbols[0].ToTestDisplayString()); Assert.Equal("IApplicationBuilder IApplicationBuilder.Use(System.Func<HttpContext, System.Func<System.Threading.Tasks.Task>, System.Threading.Tasks.Task> middleware)", symbolInfo1.CandidateSymbols[1].ToTestDisplayString()); Assert.Equal(CandidateReason.OverloadResolutionFailure, symbolInfo1.CandidateReason); var node = tree.GetRoot().DescendantNodes().Where(n => n.IsKind(SyntaxKind.IdentifierName) && ((IdentifierNameSyntax)n).Identifier.ValueText == "AuthenticateAsync").Single().Parent; Assert.Equal("ctx.Authentication.AuthenticateAsync", node.ToString()); var group = model.GetMemberGroup(node); Assert.Equal("System.Threading.Tasks.Task<AuthenticationResult> AuthenticationManager.AuthenticateAsync(System.String authenticationScheme)", group.Single().ToTestDisplayString()); } [Fact, WorkItem(5128, "https://github.com/dotnet/roslyn/issues/5128")] public void GetMemberGroupInsideIncompleteLambda_04() { var source = @" using System; using System.Threading.Tasks; public delegate Task RequestDelegate(HttpContext context); public class AuthenticationResult { } public abstract class AuthenticationManager { public abstract Task<AuthenticationResult> AuthenticateAsync(string authenticationScheme); } public abstract class HttpContext { public abstract AuthenticationManager Authentication { get; } } interface IApplicationBuilder { } static class IApplicationBuilderExtensions { public static IApplicationBuilder Use(this IApplicationBuilder app, Func<RequestDelegate, RequestDelegate> middleware) { return app; } public static IApplicationBuilder Use(this IApplicationBuilder app, Func<HttpContext, Func<Task>, Task> middleware) { return app; } } class C { void M(IApplicationBuilder app) { app.Use(async (ctx, next) => { await ctx.Authentication.AuthenticateAsync(); }); } } "; var comp = CreateCompilationWithMscorlib40(source, new[] { TestMetadata.Net40.SystemCore }); comp.VerifyDiagnostics( // (41,38): error CS7036: There is no argument given that corresponds to the required formal parameter 'authenticationScheme' of 'AuthenticationManager.AuthenticateAsync(string)' // await ctx.Authentication.AuthenticateAsync(); Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "AuthenticateAsync").WithArguments("authenticationScheme", "AuthenticationManager.AuthenticateAsync(string)").WithLocation(42, 38) ); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var node1 = tree.GetRoot().DescendantNodes().Where(n => n.IsKind(SyntaxKind.IdentifierName) && ((IdentifierNameSyntax)n).Identifier.ValueText == "Use").Single().Parent; Assert.Equal("app.Use", node1.ToString()); var group1 = model.GetMemberGroup(node1); Assert.Equal(2, group1.Length); Assert.Equal("IApplicationBuilder IApplicationBuilder.Use(System.Func<RequestDelegate, RequestDelegate> middleware)", group1[0].ToTestDisplayString()); Assert.Equal("IApplicationBuilder IApplicationBuilder.Use(System.Func<HttpContext, System.Func<System.Threading.Tasks.Task>, System.Threading.Tasks.Task> middleware)", group1[1].ToTestDisplayString()); var symbolInfo1 = model.GetSymbolInfo(node1); Assert.Null(symbolInfo1.Symbol); Assert.Equal(2, symbolInfo1.CandidateSymbols.Length); Assert.Equal("IApplicationBuilder IApplicationBuilder.Use(System.Func<RequestDelegate, RequestDelegate> middleware)", symbolInfo1.CandidateSymbols[0].ToTestDisplayString()); Assert.Equal("IApplicationBuilder IApplicationBuilder.Use(System.Func<HttpContext, System.Func<System.Threading.Tasks.Task>, System.Threading.Tasks.Task> middleware)", symbolInfo1.CandidateSymbols[1].ToTestDisplayString()); Assert.Equal(CandidateReason.OverloadResolutionFailure, symbolInfo1.CandidateReason); var node = tree.GetRoot().DescendantNodes().Where(n => n.IsKind(SyntaxKind.IdentifierName) && ((IdentifierNameSyntax)n).Identifier.ValueText == "AuthenticateAsync").Single().Parent; Assert.Equal("ctx.Authentication.AuthenticateAsync", node.ToString()); var group = model.GetMemberGroup(node); Assert.Equal("System.Threading.Tasks.Task<AuthenticationResult> AuthenticationManager.AuthenticateAsync(System.String authenticationScheme)", group.Single().ToTestDisplayString()); } [Fact, WorkItem(7101, "https://github.com/dotnet/roslyn/issues/7101")] public void UsingStatic_01() { var source = @" using System; using static ClassWithNonStaticMethod; using static Extension1; class Program { static void Main(string[] args) { var instance = new Program(); instance.NonStaticMethod(); } private void NonStaticMethod() { MathMin(0, 1); MathMax(0, 1); MathMax2(0, 1); int x; x = F1; x = F2; x.MathMax2(3); } } class ClassWithNonStaticMethod { public static int MathMax(int a, int b) { return Math.Max(a, b); } public int MathMin(int a, int b) { return Math.Min(a, b); } public int F2 = 0; } static class Extension1 { public static int MathMax2(this int a, int b) { return Math.Max(a, b); } public static int F1 = 0; } static class Extension2 { public static int MathMax3(this int a, int b) { return Math.Max(a, b); } } "; var comp = CreateCompilationWithMscorlib45(source); comp.VerifyDiagnostics( // (16,9): error CS0103: The name 'MathMin' does not exist in the current context // MathMin(0, 1); Diagnostic(ErrorCode.ERR_NameNotInContext, "MathMin").WithArguments("MathMin").WithLocation(16, 9), // (18,9): error CS0103: The name 'MathMax2' does not exist in the current context // MathMax2(0, 1); Diagnostic(ErrorCode.ERR_NameNotInContext, "MathMax2").WithArguments("MathMax2").WithLocation(18, 9), // (22,13): error CS0103: The name 'F2' does not exist in the current context // x = F2; Diagnostic(ErrorCode.ERR_NameNotInContext, "F2").WithArguments("F2").WithLocation(22, 13) ); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var node1 = tree.GetRoot().DescendantNodes().Where(n => n.IsKind(SyntaxKind.IdentifierName) && ((IdentifierNameSyntax)n).Identifier.ValueText == "MathMin").Single().Parent; Assert.Equal("MathMin(0, 1)", node1.ToString()); var names = model.LookupNames(node1.SpanStart); Assert.False(names.Contains("MathMin")); Assert.True(names.Contains("MathMax")); Assert.True(names.Contains("F1")); Assert.False(names.Contains("F2")); Assert.False(names.Contains("MathMax2")); Assert.False(names.Contains("MathMax3")); Assert.True(model.LookupSymbols(node1.SpanStart, name: "MathMin").IsEmpty); Assert.Equal(1, model.LookupSymbols(node1.SpanStart, name: "MathMax").Length); Assert.Equal(1, model.LookupSymbols(node1.SpanStart, name: "F1").Length); Assert.True(model.LookupSymbols(node1.SpanStart, name: "F2").IsEmpty); Assert.True(model.LookupSymbols(node1.SpanStart, name: "MathMax2").IsEmpty); Assert.True(model.LookupSymbols(node1.SpanStart, name: "MathMax3").IsEmpty); var symbols = model.LookupSymbols(node1.SpanStart); Assert.False(symbols.Where(s => s.Name == "MathMin").Any()); Assert.True(symbols.Where(s => s.Name == "MathMax").Any()); Assert.True(symbols.Where(s => s.Name == "F1").Any()); Assert.False(symbols.Where(s => s.Name == "F2").Any()); Assert.False(symbols.Where(s => s.Name == "MathMax2").Any()); Assert.False(symbols.Where(s => s.Name == "MathMax3").Any()); } [Fact, WorkItem(30726, "https://github.com/dotnet/roslyn/issues/30726")] public void UsingStaticGenericConstraint() { var code = @" using static Test<System.String>; public static class Test<T> where T : struct { } "; CreateCompilationWithMscorlib45(code).VerifyDiagnostics( // (2,1): hidden CS8019: Unnecessary using directive. // using static Test<System.String>; Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using static Test<System.String>;").WithLocation(2, 1), // (2,14): 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 'Test<T>' // using static Test<System.String>; Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "Test<System.String>").WithArguments("Test<T>", "T", "string").WithLocation(2, 14)); } [Fact, WorkItem(30726, "https://github.com/dotnet/roslyn/issues/30726")] public void UsingStaticGenericConstraintNestedType() { var code = @" using static A<A<int>[]>.B; class A<T> where T : class { internal static class B { } } "; CreateCompilationWithMscorlib45(code).VerifyDiagnostics( // (2,1): hidden CS8019: Unnecessary using directive. // using static A<A<int>[]>.B; Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using static A<A<int>[]>.B;").WithLocation(2, 1), // (2,14): error CS0452: The type 'int' must be a reference type in order to use it as parameter 'T' in the generic type or method 'A<T>' // using static A<A<int>[]>.B; Diagnostic(ErrorCode.ERR_RefConstraintNotSatisfied, "A<A<int>[]>.B").WithArguments("A<T>", "T", "int").WithLocation(2, 14)); } [Fact, WorkItem(30726, "https://github.com/dotnet/roslyn/issues/30726")] public void UsingStaticMultipleGenericConstraints() { var code = @" using static A<int, string>; static class A<T, U> where T : class where U : struct { } "; CreateCompilationWithMscorlib45(code).VerifyDiagnostics( // (2,1): hidden CS8019: Unnecessary using directive. // using static A<int, string>; Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using static A<int, string>;").WithLocation(2, 1), // (2,14): error CS0452: The type 'int' must be a reference type in order to use it as parameter 'T' in the generic type or method 'A<T, U>' // using static A<int, string>; Diagnostic(ErrorCode.ERR_RefConstraintNotSatisfied, "A<int, string>").WithArguments("A<T, U>", "T", "int").WithLocation(2, 14), // (2,14): error CS0453: The type 'string' must be a non-nullable value type in order to use it as parameter 'U' in the generic type or method 'A<T, U>' // using static A<int, string>; Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "A<int, string>").WithArguments("A<T, U>", "U", "string").WithLocation(2, 14)); } [Fact, WorkItem(8234, "https://github.com/dotnet/roslyn/issues/8234")] public void EventAccessInTypeNameContext() { var source = @" class Program { static void Main() {} event System.EventHandler E1; void Test(Program x) { System.Console.WriteLine(); x.E1.E System.Console.WriteLine(); } void Dummy() { E1 = null; var x = E1; } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (11,15): error CS1001: Identifier expected // x.E1.E Diagnostic(ErrorCode.ERR_IdentifierExpected, "").WithLocation(11, 15), // (11,15): error CS1002: ; expected // x.E1.E Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(11, 15), // (11,9): error CS0118: 'x' is a variable but is used like a type // x.E1.E Diagnostic(ErrorCode.ERR_BadSKknown, "x").WithArguments("x", "variable", "type").WithLocation(11, 9) ); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var node1 = tree.GetRoot().DescendantNodes().Where(n => n.IsKind(SyntaxKind.IdentifierName) && ((IdentifierNameSyntax)n).Identifier.ValueText == "E").Single().Parent; Assert.Equal("x.E1.E", node1.ToString()); Assert.Equal(SyntaxKind.QualifiedName, node1.Kind()); var node2 = ((QualifiedNameSyntax)node1).Left; Assert.Equal("x.E1", node2.ToString()); var symbolInfo2 = model.GetSymbolInfo(node2); Assert.Null(symbolInfo2.Symbol); Assert.Equal("event System.EventHandler Program.E1", symbolInfo2.CandidateSymbols.Single().ToTestDisplayString()); Assert.Equal(CandidateReason.NotATypeOrNamespace, symbolInfo2.CandidateReason); var symbolInfo1 = model.GetSymbolInfo(node1); Assert.Null(symbolInfo1.Symbol); Assert.True(symbolInfo1.CandidateSymbols.IsEmpty); } [Fact, WorkItem(13617, "https://github.com/dotnet/roslyn/issues/13617")] public void MissingTypeArgumentInGenericExtensionMethod() { var source = @" public static class FooExtensions { public static object ExtensionMethod0(this object obj) => default(object); public static T ExtensionMethod1<T>(this object obj) => default(T); public static T1 ExtensionMethod2<T1, T2>(this object obj) => default(T1); } public class Class1 { public void Test() { var omittedArg0 = ""string literal"".ExtensionMethod0<>(); var omittedArg1 = ""string literal"".ExtensionMethod1<>(); var omittedArg2 = ""string literal"".ExtensionMethod2<>(); var omittedArgFunc0 = ""string literal"".ExtensionMethod0<>; var omittedArgFunc1 = ""string literal"".ExtensionMethod1<>; var omittedArgFunc2 = ""string literal"".ExtensionMethod2<>; var moreArgs0 = ""string literal"".ExtensionMethod0<int>(); var moreArgs1 = ""string literal"".ExtensionMethod1<int, bool>(); var moreArgs2 = ""string literal"".ExtensionMethod2<int, bool, string>(); var lessArgs1 = ""string literal"".ExtensionMethod1(); var lessArgs2 = ""string literal"".ExtensionMethod2<int>(); var nonExistingMethod0 = ""string literal"".ExtensionMethodNotFound0(); var nonExistingMethod1 = ""string literal"".ExtensionMethodNotFound1<int>(); var nonExistingMethod2 = ""string literal"".ExtensionMethodNotFound2<int, string>(); System.Func<object> delegateConversion0 = ""string literal"".ExtensionMethod0<>; System.Func<object> delegateConversion1 = ""string literal"".ExtensionMethod1<>; System.Func<object> delegateConversion2 = ""string literal"".ExtensionMethod2<>; var exactArgs0 = ""string literal"".ExtensionMethod0(); var exactArgs1 = ""string literal"".ExtensionMethod1<int>(); var exactArgs2 = ""string literal"".ExtensionMethod2<int, bool>(); } } "; var compilation = CreateCompilationWithMscorlib40AndSystemCore(source); compilation.VerifyDiagnostics( // (13,27): error CS8389: Omitting the type argument is not allowed in the current context // var omittedArg0 = "string literal".ExtensionMethod0<>(); Diagnostic(ErrorCode.ERR_OmittedTypeArgument, @"""string literal"".ExtensionMethod0<>").WithLocation(13, 27), // (13,44): error CS1061: 'string' does not contain a definition for 'ExtensionMethod0' and no accessible extension method 'ExtensionMethod0' accepting a first argument of type 'string' could be found (are you missing a using directive or an assembly reference?) // var omittedArg0 = "string literal".ExtensionMethod0<>(); Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "ExtensionMethod0<>").WithArguments("string", "ExtensionMethod0").WithLocation(13, 44), // (14,27): error CS8389: Omitting the type argument is not allowed in the current context // var omittedArg1 = "string literal".ExtensionMethod1<>(); Diagnostic(ErrorCode.ERR_OmittedTypeArgument, @"""string literal"".ExtensionMethod1<>").WithLocation(14, 27), // (15,27): error CS8389: Omitting the type argument is not allowed in the current context // var omittedArg2 = "string literal".ExtensionMethod2<>(); Diagnostic(ErrorCode.ERR_OmittedTypeArgument, @"""string literal"".ExtensionMethod2<>").WithLocation(15, 27), // (15,44): error CS1061: 'string' does not contain a definition for 'ExtensionMethod2' and no accessible extension method 'ExtensionMethod2' accepting a first argument of type 'string' could be found (are you missing a using directive or an assembly reference?) // var omittedArg2 = "string literal".ExtensionMethod2<>(); Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "ExtensionMethod2<>").WithArguments("string", "ExtensionMethod2").WithLocation(15, 44), // (17,31): error CS8389: Omitting the type argument is not allowed in the current context // var omittedArgFunc0 = "string literal".ExtensionMethod0<>; Diagnostic(ErrorCode.ERR_OmittedTypeArgument, @"""string literal"".ExtensionMethod0<>").WithLocation(17, 31), // (17,48): error CS1061: 'string' does not contain a definition for 'ExtensionMethod0' and no accessible extension method 'ExtensionMethod0' accepting a first argument of type 'string' could be found (are you missing a using directive or an assembly reference?) // var omittedArgFunc0 = "string literal".ExtensionMethod0<>; Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "ExtensionMethod0<>").WithArguments("string", "ExtensionMethod0").WithLocation(17, 48), // (18,31): error CS8389: Omitting the type argument is not allowed in the current context // var omittedArgFunc1 = "string literal".ExtensionMethod1<>; Diagnostic(ErrorCode.ERR_OmittedTypeArgument, @"""string literal"".ExtensionMethod1<>").WithLocation(18, 31), // (19,31): error CS8389: Omitting the type argument is not allowed in the current context // var omittedArgFunc2 = "string literal".ExtensionMethod2<>; Diagnostic(ErrorCode.ERR_OmittedTypeArgument, @"""string literal"".ExtensionMethod2<>").WithLocation(19, 31), // (19,48): error CS1061: 'string' does not contain a definition for 'ExtensionMethod2' and no accessible extension method 'ExtensionMethod2' accepting a first argument of type 'string' could be found (are you missing a using directive or an assembly reference?) // var omittedArgFunc2 = "string literal".ExtensionMethod2<>; Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "ExtensionMethod2<>").WithArguments("string", "ExtensionMethod2").WithLocation(19, 48), // (21,42): error CS1061: 'string' does not contain a definition for 'ExtensionMethod0' and no accessible extension method 'ExtensionMethod0' accepting a first argument of type 'string' could be found (are you missing a using directive or an assembly reference?) // var moreArgs0 = "string literal".ExtensionMethod0<int>(); Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "ExtensionMethod0<int>").WithArguments("string", "ExtensionMethod0").WithLocation(21, 42), // (22,42): error CS1061: 'string' does not contain a definition for 'ExtensionMethod1' and no accessible extension method 'ExtensionMethod1' accepting a first argument of type 'string' could be found (are you missing a using directive or an assembly reference?) // var moreArgs1 = "string literal".ExtensionMethod1<int, bool>(); Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "ExtensionMethod1<int, bool>").WithArguments("string", "ExtensionMethod1").WithLocation(22, 42), // (23,42): error CS1061: 'string' does not contain a definition for 'ExtensionMethod2' and no accessible extension method 'ExtensionMethod2' accepting a first argument of type 'string' could be found (are you missing a using directive or an assembly reference?) // var moreArgs2 = "string literal".ExtensionMethod2<int, bool, string>(); Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "ExtensionMethod2<int, bool, string>").WithArguments("string", "ExtensionMethod2").WithLocation(23, 42), // (25,42): error CS0411: The type arguments for method 'FooExtensions.ExtensionMethod1<T>(object)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // var lessArgs1 = "string literal".ExtensionMethod1(); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "ExtensionMethod1").WithArguments("FooExtensions.ExtensionMethod1<T>(object)").WithLocation(25, 42), // (26,42): error CS1061: 'string' does not contain a definition for 'ExtensionMethod2' and no accessible extension method 'ExtensionMethod2' accepting a first argument of type 'string' could be found (are you missing a using directive or an assembly reference?) // var lessArgs2 = "string literal".ExtensionMethod2<int>(); Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "ExtensionMethod2<int>").WithArguments("string", "ExtensionMethod2").WithLocation(26, 42), // (28,51): error CS1061: 'string' does not contain a definition for 'ExtensionMethodNotFound0' and no accessible extension method 'ExtensionMethodNotFound0' accepting a first argument of type 'string' could be found (are you missing a using directive or an assembly reference?) // var nonExistingMethod0 = "string literal".ExtensionMethodNotFound0(); Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "ExtensionMethodNotFound0").WithArguments("string", "ExtensionMethodNotFound0").WithLocation(28, 51), // (29,51): error CS1061: 'string' does not contain a definition for 'ExtensionMethodNotFound1' and no accessible extension method 'ExtensionMethodNotFound1' accepting a first argument of type 'string' could be found (are you missing a using directive or an assembly reference?) // var nonExistingMethod1 = "string literal".ExtensionMethodNotFound1<int>(); Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "ExtensionMethodNotFound1<int>").WithArguments("string", "ExtensionMethodNotFound1").WithLocation(29, 51), // (30,51): error CS1061: 'string' does not contain a definition for 'ExtensionMethodNotFound2' and no accessible extension method 'ExtensionMethodNotFound2' accepting a first argument of type 'string' could be found (are you missing a using directive or an assembly reference?) // var nonExistingMethod2 = "string literal".ExtensionMethodNotFound2<int, string>(); Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "ExtensionMethodNotFound2<int, string>").WithArguments("string", "ExtensionMethodNotFound2").WithLocation(30, 51), // (32,51): error CS8389: Omitting the type argument is not allowed in the current context // System.Func<object> delegateConversion0 = "string literal".ExtensionMethod0<>; Diagnostic(ErrorCode.ERR_OmittedTypeArgument, @"""string literal"".ExtensionMethod0<>").WithLocation(32, 51), // (32,68): error CS1061: 'string' does not contain a definition for 'ExtensionMethod0' and no accessible extension method 'ExtensionMethod0' accepting a first argument of type 'string' could be found (are you missing a using directive or an assembly reference?) // System.Func<object> delegateConversion0 = "string literal".ExtensionMethod0<>; Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "ExtensionMethod0<>").WithArguments("string", "ExtensionMethod0").WithLocation(32, 68), // (33,51): error CS8389: Omitting the type argument is not allowed in the current context // System.Func<object> delegateConversion1 = "string literal".ExtensionMethod1<>; Diagnostic(ErrorCode.ERR_OmittedTypeArgument, @"""string literal"".ExtensionMethod1<>").WithLocation(33, 51), // (33,51): error CS0407: '? FooExtensions.ExtensionMethod1<?>(object)' has the wrong return type // System.Func<object> delegateConversion1 = "string literal".ExtensionMethod1<>; Diagnostic(ErrorCode.ERR_BadRetType, @"""string literal"".ExtensionMethod1<>").WithArguments("FooExtensions.ExtensionMethod1<?>(object)", "?").WithLocation(33, 51), // (34,51): error CS8389: Omitting the type argument is not allowed in the current context // System.Func<object> delegateConversion2 = "string literal".ExtensionMethod2<>; Diagnostic(ErrorCode.ERR_OmittedTypeArgument, @"""string literal"".ExtensionMethod2<>").WithLocation(34, 51), // (34,68): error CS1061: 'string' does not contain a definition for 'ExtensionMethod2' and no accessible extension method 'ExtensionMethod2' accepting a first argument of type 'string' could be found (are you missing a using directive or an assembly reference?) // System.Func<object> delegateConversion2 = "string literal".ExtensionMethod2<>; Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "ExtensionMethod2<>").WithArguments("string", "ExtensionMethod2").WithLocation(34, 68)); } [WorkItem(22757, "https://github.com/dotnet/roslyn/issues/22757")] [Fact] public void MethodGroupConversionNoReceiver() { var source = @"using System; using System.Collections.Generic; class A { class B { void F() { IEnumerable<string> c = null; c.S(G); } } object G(string s) { return null; } } static class E { internal static IEnumerable<U> S<T, U>(this IEnumerable<T> c, Func<T, U> f) { throw new NotImplementedException(); } }"; var comp = CreateCompilationWithMscorlib40AndSystemCore(source); 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)); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var node = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(n => n.ToString() == "G").First(); var info = model.GetSymbolInfo(node); Assert.Equal("System.Object A.G(System.String s)", info.Symbol.ToTestDisplayString()); } [Fact] public void BindingLambdaArguments_DuplicateNamedArguments() { var compilation = CreateCompilation(@" using System; class X { void M<T>(T arg1, Func<T, T> arg2) { } void N() { M(arg1: 5, arg2: x => x, arg2: y => y); } }").VerifyDiagnostics( // (10,34): error CS1740: Named argument 'arg2' cannot be specified multiple times // M(arg1: 5, arg2: x => 0, arg2: y => 0); Diagnostic(ErrorCode.ERR_DuplicateNamedArgument, "arg2").WithArguments("arg2").WithLocation(10, 34)); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree, ignoreAccessibility: true); var lambda = tree.GetRoot().DescendantNodes().OfType<SimpleLambdaExpressionSyntax>().Single(s => s.Parameter.Identifier.Text == "x"); var typeInfo = model.GetTypeInfo(lambda.Body); Assert.Equal("System.Int32", typeInfo.Type.ToTestDisplayString()); } } }
1
dotnet/roslyn
55,132
Support lambda expressions and method groups as `var` initializers
```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
cston
2021-07-27T03:12:21Z
2021-07-27T18:26:42Z
61a565cfcd777158cb6354351436aff997ad7bf6
5840335153dcca42570a853cdacd06d660fe9596
Support lambda expressions and method groups as `var` initializers. ```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
./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)); } [Fact] public void SystemActionAndFunc_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.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 } }"; var refA = CompileIL(sourceA, prependDefaultHeader: false, autoInherit: false); 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() { var source = @"class Program { static void Main() { var d1 = Main; var d2 = () => { }; var d3 = delegate () { }; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (5,13): error CS0815: Cannot assign method group to an implicitly-typed variable // var d1 = Main; Diagnostic(ErrorCode.ERR_ImplicitlyTypedVariableAssignedBadValue, "d1 = Main").WithArguments("method group").WithLocation(5, 13), // (6,13): error CS0815: Cannot assign lambda expression to an implicitly-typed variable // var d2 = () => { }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedVariableAssignedBadValue, "d2 = () => { }").WithArguments("lambda expression").WithLocation(6, 13), // (7,13): error CS0815: Cannot assign anonymous method to an implicitly-typed variable // var d3 = delegate () { }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedVariableAssignedBadValue, "d3 = delegate () { }").WithArguments("anonymous method").WithLocation(7, 13)); } /// <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 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 }"); } } }
1
dotnet/roslyn
55,132
Support lambda expressions and method groups as `var` initializers
```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
cston
2021-07-27T03:12:21Z
2021-07-27T18:26:42Z
61a565cfcd777158cb6354351436aff997ad7bf6
5840335153dcca42570a853cdacd06d660fe9596
Support lambda expressions and method groups as `var` initializers. ```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
./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,13): error CS0815: Cannot assign lambda expression to an implicitly-typed variable // var y = x => x; Diagnostic(ErrorCode.ERR_ImplicitlyTypedVariableAssignedBadValue, "y = x => x").WithArguments("lambda expression").WithLocation(5, 13)); } [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,13): error CS0815: Cannot assign lambda expression to an implicitly-typed variable // var z = y => y ?? x.ToString(); Diagnostic(ErrorCode.ERR_ImplicitlyTypedVariableAssignedBadValue, "z = y => y ?? x.ToString()").WithArguments("lambda expression").WithLocation(5, 13), // (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 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) ); } } }
1
dotnet/roslyn
55,132
Support lambda expressions and method groups as `var` initializers
```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
cston
2021-07-27T03:12:21Z
2021-07-27T18:26:42Z
61a565cfcd777158cb6354351436aff997ad7bf6
5840335153dcca42570a853cdacd06d660fe9596
Support lambda expressions and method groups as `var` initializers. ```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
./src/Compilers/CSharp/Test/Semantic/Semantics/SemanticErrorTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Globalization; using System.Linq; using System.Threading; 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; using static Roslyn.Test.Utilities.TestMetadata; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { /// <summary> /// this place is dedicated to binding related error tests /// </summary> public class SemanticErrorTests : CompilingTestBase { #region "Targeted Error Tests - please arrange tests in the order of error code" [Fact] public void CS0019ERR_BadBinaryOps01() { var text = @" namespace x { public class b { public static void Main() { bool q = false; if (q == 1) { } } } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_BadBinaryOps, Line = 9, Column = 17 }); } [Fact] public void CS0019ERR_BadBinaryOps02() { var text = @"using System; enum E { A, B, C } enum F { X = (E.A + E.B) * DayOfWeek.Monday } // no error class C { static void M(object o) { M((E.A + E.B) * DayOfWeek.Monday); } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_BadBinaryOps, Line = 8, Column = 12 }); } [WorkItem(539906, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539906")] [Fact] public void CS0019ERR_BadBinaryOps03() { var text = @"delegate void MyDelegate1(ref int x, out float y); class Program { public void DelegatedMethod1(ref int x, out float y) { y = 1; } public void DelegatedMethod2(out int x, ref float y) { x = 1; } public void DelegatedMethod3(out int x, float y = 1) { x = 1; } static void Main(string[] args) { Program mc = new Program(); MyDelegate1 md1 = null; md1 += mc.DelegatedMethod1; md1 += mc.DelegatedMethod2; // Invalid md1 += mc.DelegatedMethod3; // Invalid md1 -= mc.DelegatedMethod1; md1 -= mc.DelegatedMethod2; // Invalid md1 -= mc.DelegatedMethod3; // Invalid } } "; CreateCompilation(text). VerifyDiagnostics( // (21,19): error CS0123: No overload for 'DelegatedMethod2' matches delegate 'MyDelegate1' // md1 += mc.DelegatedMethod2; // Invalid Diagnostic(ErrorCode.ERR_MethDelegateMismatch, "DelegatedMethod2").WithArguments("DelegatedMethod2", "MyDelegate1"), // (22,19): error CS0123: No overload for 'DelegatedMethod3' matches delegate 'MyDelegate1' // md1 += mc.DelegatedMethod3; // Invalid Diagnostic(ErrorCode.ERR_MethDelegateMismatch, "DelegatedMethod3").WithArguments("DelegatedMethod3", "MyDelegate1"), // (24,19): error CS0123: No overload for 'DelegatedMethod2' matches delegate 'MyDelegate1' // md1 -= mc.DelegatedMethod2; // Invalid Diagnostic(ErrorCode.ERR_MethDelegateMismatch, "DelegatedMethod2").WithArguments("DelegatedMethod2", "MyDelegate1"), // (25,19): error CS0123: No overload for 'DelegatedMethod3' matches delegate 'MyDelegate1' // md1 -= mc.DelegatedMethod3; // Invalid Diagnostic(ErrorCode.ERR_MethDelegateMismatch, "DelegatedMethod3").WithArguments("DelegatedMethod3", "MyDelegate1") ); } // Method List to removal or concatenation [WorkItem(539906, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539906")] [Fact] public void CS0019ERR_BadBinaryOps04() { var text = @"using System; delegate void boo(); public class abc { public void bar() { System.Console.WriteLine(""bar""); } static public void far() { System.Console.WriteLine(""far""); } } class C { static void Main(string[] args) { abc p = new abc(); boo goo = null; boo goo1 = new boo(abc.far); boo[] arrfoo = { p.bar, abc.far }; goo += arrfoo; // Invalid goo -= arrfoo; // Invalid goo += new boo[] { p.bar, abc.far }; // Invalid goo -= new boo[] { p.bar, abc.far }; // Invalid goo += Delegate.Combine(arrfoo); // Invalid goo += Delegate.Combine(goo, goo1); // Invalid } } "; CreateCompilation(text).VerifyDiagnostics( // (16,16): error CS0029: Cannot implicitly convert type 'boo[]' to 'boo' // goo += arrfoo; // Invalid Diagnostic(ErrorCode.ERR_NoImplicitConv, "arrfoo").WithArguments("boo[]", "boo"), // (17,16): error CS0029: Cannot implicitly convert type 'boo[]' to 'boo' // goo -= arrfoo; // Invalid Diagnostic(ErrorCode.ERR_NoImplicitConv, "arrfoo").WithArguments("boo[]", "boo"), // (18,16): error CS0029: Cannot implicitly convert type 'boo[]' to 'boo' // goo += new boo[] { p.bar, abc.far }; // Invalid Diagnostic(ErrorCode.ERR_NoImplicitConv, "new boo[] { p.bar, abc.far }").WithArguments("boo[]", "boo"), // (19,16): error CS0029: Cannot implicitly convert type 'boo[]' to 'boo' // goo -= new boo[] { p.bar, abc.far }; // Invalid Diagnostic(ErrorCode.ERR_NoImplicitConv, "new boo[] { p.bar, abc.far }").WithArguments("boo[]", "boo"), // (20,16): error CS0266: Cannot implicitly convert type 'System.Delegate' to 'boo'. An explicit conversion exists (are you missing a cast?) // goo += Delegate.Combine(arrfoo); // Invalid Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "Delegate.Combine(arrfoo)").WithArguments("System.Delegate", "boo"), // (21,16): error CS0266: Cannot implicitly convert type 'System.Delegate' to 'boo'. An explicit conversion exists (are you missing a cast?) // goo += Delegate.Combine(goo, goo1); // Invalid Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "Delegate.Combine(goo, goo1)").WithArguments("System.Delegate", "boo") ); } [WorkItem(539906, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539906")] [Fact] public void CS0019ERR_BadBinaryOps05() { var text = @"public delegate double MyDelegate1(ref int integerPortion, out float fraction); public delegate double MyDelegate2(ref int integerPortion, out float fraction); class C { static void Main(string[] args) { C mc = new C(); MyDelegate1 md1 = null; MyDelegate2 md2 = null; md1 += md2; // Invalid } } "; CreateCompilation(text).VerifyDiagnostics( // (10,16): error CS0029: Cannot implicitly convert type 'MyDelegate2' to 'MyDelegate1' // md1 += md2; // Invalid Diagnostic(ErrorCode.ERR_NoImplicitConv, "md2").WithArguments("MyDelegate2", "MyDelegate1") ); } // Anonymous method to removal or concatenation [WorkItem(539906, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539906")] [Fact] public void CS0019ERR_BadBinaryOps06() { var text = @"delegate void boo(int x); class C { static void Main(string[] args) { boo goo = null; goo += delegate (string x) { System.Console.WriteLine(x); };// Invalid goo -= delegate (string x) { System.Console.WriteLine(x); };// Invalid } } "; CreateCompilation(text).VerifyDiagnostics( // (7,16): error CS1661: Cannot convert anonymous method to delegate type 'boo' because the parameter types do not match the delegate parameter types // goo += delegate (string x) { System.Console.WriteLine(x); };// Invalid Diagnostic(ErrorCode.ERR_CantConvAnonMethParams, "delegate (string x) { System.Console.WriteLine(x); }").WithArguments("anonymous method", "boo"), // (7,33): error CS1678: Parameter 1 is declared as type 'string' but should be 'int' // goo += delegate (string x) { System.Console.WriteLine(x); };// Invalid Diagnostic(ErrorCode.ERR_BadParamType, "x").WithArguments("1", "", "string", "", "int"), // (8,16): error CS1661: Cannot convert anonymous method to delegate type 'boo' because the parameter types do not match the delegate parameter types // goo -= delegate (string x) { System.Console.WriteLine(x); };// Invalid Diagnostic(ErrorCode.ERR_CantConvAnonMethParams, "delegate (string x) { System.Console.WriteLine(x); }").WithArguments("anonymous method", "boo"), // (8,33): error CS1678: Parameter 1 is declared as type 'string' but should be 'int' // goo -= delegate (string x) { System.Console.WriteLine(x); };// Invalid Diagnostic(ErrorCode.ERR_BadParamType, "x").WithArguments("1", "", "string", "", "int") ); } // Lambda expression to removal or concatenation [WorkItem(539906, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539906")] [Fact] public void CS0019ERR_BadBinaryOps07() { var text = @"delegate void boo(int x); class C { static void Main(string[] args) { boo goo = null; goo += (string x) => { };// Invalid goo -= (string x) => { };// Invalid } } "; CreateCompilation(text).VerifyDiagnostics( // (7,16): error CS1661: Cannot convert lambda expression to delegate type 'boo' because the parameter types do not match the delegate parameter types // goo += (string x) => { };// Invalid Diagnostic(ErrorCode.ERR_CantConvAnonMethParams, "(string x) => { }").WithArguments("lambda expression", "boo"), // (7,24): error CS1678: Parameter 1 is declared as type 'string' but should be 'int' // goo += (string x) => { };// Invalid Diagnostic(ErrorCode.ERR_BadParamType, "x").WithArguments("1", "", "string", "", "int"), // (8,16): error CS1661: Cannot convert lambda expression to delegate type 'boo' because the parameter types do not match the delegate parameter types // goo -= (string x) => { };// Invalid Diagnostic(ErrorCode.ERR_CantConvAnonMethParams, "(string x) => { }").WithArguments("lambda expression", "boo"), // (8,24): error CS1678: Parameter 1 is declared as type 'string' but should be 'int' // goo -= (string x) => { };// Invalid Diagnostic(ErrorCode.ERR_BadParamType, "x").WithArguments("1", "", "string", "", "int") ); } // Successive operator for addition and subtraction assignment [WorkItem(539906, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539906")] [Fact] public void CS0019ERR_BadBinaryOps08() { var text = @"using System; delegate void boo(int x); class C { public void bar(int x) { Console.WriteLine("""", x); } static public void far(int x) { Console.WriteLine(""far:{0}"", x); } static void Main(string[] args) { C p = new C(); boo goo = null; goo += p.bar + far;// Invalid goo += (x) => { System.Console.WriteLine(""Lambda:{0}"", x); } + far;// Invalid goo += delegate (int x) { System.Console.WriteLine(""Anonymous:{0}"", x); } + far;// Invalid } } "; CreateCompilation(text).VerifyDiagnostics( // (11,16): error CS0019: Operator '+' cannot be applied to operands of type 'method group' and 'method group' // goo += p.bar + far;// Invalid Diagnostic(ErrorCode.ERR_BadBinaryOps, "p.bar + far").WithArguments("+", "method group", "method group").WithLocation(11, 16), // (12,16): error CS0019: Operator '+' cannot be applied to operands of type 'lambda expression' and 'method group' // goo += (x) => { System.Console.WriteLine("Lambda:{0}", x); } + far;// Invalid Diagnostic(ErrorCode.ERR_BadBinaryOps, @"(x) => { System.Console.WriteLine(""Lambda:{0}"", x); } + far").WithArguments("+", "lambda expression", "method group").WithLocation(12, 16), // (12,70): warning CS8848: Operator '+' cannot be used here due to precedence. Use parentheses to disambiguate. // goo += (x) => { System.Console.WriteLine("Lambda:{0}", x); } + far;// Invalid Diagnostic(ErrorCode.WRN_PrecedenceInversion, "+").WithArguments("+").WithLocation(12, 70), // (13,16): error CS0019: Operator '+' cannot be applied to operands of type 'anonymous method' and 'method group' // goo += delegate (int x) { System.Console.WriteLine("Anonymous:{0}", x); } + far;// Invalid Diagnostic(ErrorCode.ERR_BadBinaryOps, @"delegate (int x) { System.Console.WriteLine(""Anonymous:{0}"", x); } + far").WithArguments("+", "anonymous method", "method group").WithLocation(13, 16), // (13,83): warning CS8848: Operator '+' cannot be used here due to precedence. Use parentheses to disambiguate. // goo += delegate (int x) { System.Console.WriteLine("Anonymous:{0}", x); } + far;// Invalid Diagnostic(ErrorCode.WRN_PrecedenceInversion, "+").WithArguments("+").WithLocation(13, 83) ); } // Removal or concatenation for the delegate on Variance [WorkItem(539906, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539906")] [Fact] public void CS0019ERR_BadBinaryOps09() { var text = @"using System.Collections.Generic; delegate IList<int> Delegate1(List<int> x); delegate IEnumerable<int> Delegate2(IList<int> x); delegate IEnumerable<long> Delegate3(IList<long> x); class C { public static List<int> Method1(IList<int> x) { return null; } public static IList<long> Method1(IList<long> x) { return null; } static void Main(string[] args) { Delegate1 d1 = Method1; d1 += Method1; Delegate2 d2 = Method1; d2 += Method1; Delegate3 d3 = Method1; d1 += d2; // invalid d2 += d1; // invalid d2 += d3; // invalid } } "; CreateCompilation(text).VerifyDiagnostics( // (25,15): error CS0029: Cannot implicitly convert type 'Delegate2' to 'Delegate1' // d1 += d2; // invalid Diagnostic(ErrorCode.ERR_NoImplicitConv, "d2").WithArguments("Delegate2", "Delegate1"), // (26,15): error CS0029: Cannot implicitly convert type 'Delegate1' to 'Delegate2' // d2 += d1; // invalid Diagnostic(ErrorCode.ERR_NoImplicitConv, "d1").WithArguments("Delegate1", "Delegate2"), // (27,15): error CS0029: Cannot implicitly convert type 'Delegate3' to 'Delegate2' // d2 += d3; // invalid Diagnostic(ErrorCode.ERR_NoImplicitConv, "d3").WithArguments("Delegate3", "Delegate2") ); } // generic-delegate (goo<t>(...)) += non generic-methodgroup(bar<t>(...)) [WorkItem(539906, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539906")] [Fact] public void CS0019ERR_BadBinaryOps10() { var text = @"delegate void boo<T>(T x); class C { public void bar(int x) { System.Console.WriteLine(""bar:{0}"", x); } public void bar1(string x) { System.Console.WriteLine(""bar1:{0}"", x); } static void Main(string[] args) { C p = new C(); boo<int> goo = null; goo += p.bar;// OK goo += p.bar1;// Invalid goo += (x) => { System.Console.WriteLine(""Lambda:{0}"", x); };// OK goo += (string x) => { System.Console.WriteLine(""Lambda:{0}"", x); };// Invalid goo += delegate (int x) { System.Console.WriteLine(""Anonymous:{0}"", x); };// OK goo += delegate (string x) { System.Console.WriteLine(""Anonymous:{0}"", x); };// Invalid boo<string> goo1 = null; goo1 += p.bar;// Invalid goo1 += p.bar1;// OK goo1 += (x) => { System.Console.WriteLine(""Lambda:{0}"", x); };// OK goo1 += (int x) => { System.Console.WriteLine(""Lambda:{0}"", x); };// Invalid goo1 += delegate (int x) { System.Console.WriteLine(""Anonymous:{0}"", x); };// Invalid goo1 += delegate (string x) { System.Console.WriteLine(""Anonymous:{0}"", x); };// OK goo += goo1;// Invalid goo1 += goo;// Invalid } } "; CreateCompilation(text).VerifyDiagnostics( // (12,18): error CS0123: No overload for 'bar1' matches delegate 'boo<int>' // goo += p.bar1;// Invalid Diagnostic(ErrorCode.ERR_MethDelegateMismatch, "bar1").WithArguments("bar1", "boo<int>"), // (14,16): error CS1661: Cannot convert lambda expression to delegate type 'boo<int>' because the parameter types do not match the delegate parameter types // goo += (string x) => { System.Console.WriteLine("Lambda:{0}", x); };// Invalid Diagnostic(ErrorCode.ERR_CantConvAnonMethParams, @"(string x) => { System.Console.WriteLine(""Lambda:{0}"", x); }").WithArguments("lambda expression", "boo<int>"), // (14,24): error CS1678: Parameter 1 is declared as type 'string' but should be 'int' // goo += (string x) => { System.Console.WriteLine("Lambda:{0}", x); };// Invalid Diagnostic(ErrorCode.ERR_BadParamType, "x").WithArguments("1", "", "string", "", "int"), // (16,16): error CS1661: Cannot convert anonymous method to delegate type 'boo<int>' because the parameter types do not match the delegate parameter types // goo += delegate (string x) { System.Console.WriteLine("Anonymous:{0}", x); };// Invalid Diagnostic(ErrorCode.ERR_CantConvAnonMethParams, @"delegate (string x) { System.Console.WriteLine(""Anonymous:{0}"", x); }").WithArguments("anonymous method", "boo<int>"), // (16,33): error CS1678: Parameter 1 is declared as type 'string' but should be 'int' // goo += delegate (string x) { System.Console.WriteLine("Anonymous:{0}", x); };// Invalid Diagnostic(ErrorCode.ERR_BadParamType, "x").WithArguments("1", "", "string", "", "int"), // (19,19): error CS0123: No overload for 'bar' matches delegate 'boo<string>' // goo1 += p.bar;// Invalid Diagnostic(ErrorCode.ERR_MethDelegateMismatch, "bar").WithArguments("bar", "boo<string>"), // (22,17): error CS1661: Cannot convert lambda expression to delegate type 'boo<string>' because the parameter types do not match the delegate parameter types // goo1 += (int x) => { System.Console.WriteLine("Lambda:{0}", x); };// Invalid Diagnostic(ErrorCode.ERR_CantConvAnonMethParams, @"(int x) => { System.Console.WriteLine(""Lambda:{0}"", x); }").WithArguments("lambda expression", "boo<string>"), // (22,22): error CS1678: Parameter 1 is declared as type 'int' but should be 'string' // goo1 += (int x) => { System.Console.WriteLine("Lambda:{0}", x); };// Invalid Diagnostic(ErrorCode.ERR_BadParamType, "x").WithArguments("1", "", "int", "", "string"), // (23,17): error CS1661: Cannot convert anonymous method to delegate type 'boo<string>' because the parameter types do not match the delegate parameter types // goo1 += delegate (int x) { System.Console.WriteLine("Anonymous:{0}", x); };// Invalid Diagnostic(ErrorCode.ERR_CantConvAnonMethParams, @"delegate (int x) { System.Console.WriteLine(""Anonymous:{0}"", x); }").WithArguments("anonymous method", "boo<string>"), // (23,31): error CS1678: Parameter 1 is declared as type 'int' but should be 'string' // goo1 += delegate (int x) { System.Console.WriteLine("Anonymous:{0}", x); };// Invalid Diagnostic(ErrorCode.ERR_BadParamType, "x").WithArguments("1", "", "int", "", "string"), // (25,16): error CS0029: Cannot implicitly convert type 'boo<string>' to 'boo<int>' // goo += goo1;// Invalid Diagnostic(ErrorCode.ERR_NoImplicitConv, "goo1").WithArguments("boo<string>", "boo<int>"), // (26,17): error CS0029: Cannot implicitly convert type 'boo<int>' to 'boo<string>' // goo1 += goo;// Invalid Diagnostic(ErrorCode.ERR_NoImplicitConv, "goo").WithArguments("boo<int>", "boo<string>") ); } // generic-delegate (goo<t>(...)) += generic-methodgroup(bar<t>(...)) [WorkItem(539906, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539906")] [Fact] public void CS0019ERR_BadBinaryOps11() { var text = @"delegate void boo<T>(T x); class C { static void far<T>(T x) { } static void Main(string[] args) { C p = new C(); boo<int> goo = null; goo += far<int>;// OK goo += far<short>;// Invalid } } "; CreateCompilation(text).VerifyDiagnostics( // (10,16): error CS0123: No overload for 'far' matches delegate 'boo<int>' // goo += far<short>;// Invalid Diagnostic(ErrorCode.ERR_MethDelegateMismatch, "far<short>").WithArguments("far", "boo<int>") ); } // non generic-delegate (goo<t>(...)) += generic-methodgroup(bar<t>(...)) [WorkItem(539906, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539906")] [Fact] public void CS0019ERR_BadBinaryOps12() { var text = @"delegate void boo<T>(T x); class C { static void far<T>(T x) { } static void Main(string[] args) { C p = new C(); boo<int> goo = null; goo += far<int>;// OK goo += far<short>;// Invalid } } "; CreateCompilation(text).VerifyDiagnostics( // (10,16): error CS0123: No overload for 'far' matches delegate 'boo<int>' // goo += far<short>;// Invalid Diagnostic(ErrorCode.ERR_MethDelegateMismatch, "far<short>").WithArguments("far", "boo<int>") ); } // distinguish '|' from '||' [WorkItem(540235, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540235")] [Fact] public void CS0019ERR_BadBinaryOps13() { var text = @" class C { int a = 1 | 1; int b = 1 & 1; int c = 1 || 1; int d = 1 && 1; bool e = true | true; bool f = true & true; bool g = true || true; bool h = true && true; } "; CreateCompilation(text).VerifyDiagnostics( // (6,13): error CS0019: Operator '||' cannot be applied to operands of type 'int' and 'int' // int c = 1 || 1; Diagnostic(ErrorCode.ERR_BadBinaryOps, "1 || 1").WithArguments("||", "int", "int"), // (7,13): error CS0019: Operator '&&' cannot be applied to operands of type 'int' and 'int' // int d = 1 && 1; Diagnostic(ErrorCode.ERR_BadBinaryOps, "1 && 1").WithArguments("&&", "int", "int"), // (4,9): warning CS0414: The field 'C.a' is assigned but its value is never used // int a = 1 | 1; Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "a").WithArguments("C.a"), // (5,9): warning CS0414: The field 'C.b' is assigned but its value is never used // int b = 1 & 1; Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "b").WithArguments("C.b"), // (9,10): warning CS0414: The field 'C.e' is assigned but its value is never used // bool e = true | true; Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "e").WithArguments("C.e"), // (10,10): warning CS0414: The field 'C.f' is assigned but its value is never used // bool f = true & true; Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "f").WithArguments("C.f"), // (11,10): warning CS0414: The field 'C.g' is assigned but its value is never used // bool g = true || true; Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "g").WithArguments("C.g"), // (12,10): warning CS0414: The field 'C.h' is assigned but its value is never used // bool h = true && true; Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "h").WithArguments("C.h")); } /// <summary> /// Conversion errors for Null Coalescing operator(??) /// </summary> [Fact] public void CS0019ERR_BadBinaryOps14() { var text = @" public class D { } public class Error { public int? NonNullableValueType_a(int a) { int? b = null; int? z = a ?? b; return z; } public int? NonNullableValueType_b(char ch) { char b = ch; int? z = null ?? b; return z; } public int NonNullableValueType_const_a(char ch) { char b = ch; int z = 10 ?? b; return z; } public D NoPossibleConversionError() { D b = new D(); Error a = null; D z = a ?? b; return z; } } "; CreateCompilation(text).VerifyDiagnostics( // (7,18): error CS0019: Operator '??' cannot be applied to operands of type 'int' and 'int?' Diagnostic(ErrorCode.ERR_BadBinaryOps, "a ?? b").WithArguments("??", "int", "int?"), // (13,18): error CS0019: Operator '??' cannot be applied to operands of type '<null>' and 'char' Diagnostic(ErrorCode.ERR_BadBinaryOps, "null ?? b").WithArguments("??", "<null>", "char"), // (19,17): error CS0019: Operator '??' cannot be applied to operands of type 'int' and 'char' Diagnostic(ErrorCode.ERR_BadBinaryOps, "10 ?? b").WithArguments("??", "int", "char"), // (26,15): error CS0019: Operator '??' cannot be applied to operands of type 'Error' and 'D' Diagnostic(ErrorCode.ERR_BadBinaryOps, "a ?? b").WithArguments("??", "Error", "D")); } [WorkItem(542115, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542115")] [Fact] public void CS0019ERR_BadBinaryOps15() { var text = @"class C { static void M<T1, T2, T3, T4>(T1 t1, T2 t2, T3 t3, T4 t4, int i, C c) where T2 : class where T3 : struct where T4 : T1 { bool b; b = (t1 == t1); b = (t1 == t2); b = (t1 == t3); b = (t1 == t4); b = (t1 == i); b = (t1 == c); b = (t1 == null); b = (t2 == t1); b = (t2 == t2); b = (t2 == t3); b = (t2 == t4); b = (t2 == i); b = (t2 == c); b = (t2 == null); b = (t3 == t1); b = (t3 == t2); b = (t3 == t3); b = (t3 == t4); b = (t3 == i); b = (t3 == c); b = (t3 == null); b = (t4 != t1); b = (t4 != t2); b = (t4 != t3); b = (t4 != t4); b = (t4 != i); b = (t4 != c); b = (t4 != null); b = (i != t1); b = (i != t2); b = (i != t3); b = (i != t4); b = (i != i); b = (i != c); b = (i != null); b = (c != t1); b = (c != t2); b = (c != t3); b = (c != t4); b = (c != i); b = (c != c); b = (c != null); b = (null != t1); b = (null != t2); b = (null != t3); b = (null != t4); b = (null != i); b = (null != c); b = (null != null); } }"; CreateCompilation(text).VerifyDiagnostics( // (9,14): error CS0019: Operator '==' cannot be applied to operands of type 'T1' and 'T1' // b = (t1 == t1); Diagnostic(ErrorCode.ERR_BadBinaryOps, "t1 == t1").WithArguments("==", "T1", "T1"), // (10,14): error CS0019: Operator '==' cannot be applied to operands of type 'T1' and 'T2' // b = (t1 == t2); Diagnostic(ErrorCode.ERR_BadBinaryOps, "t1 == t2").WithArguments("==", "T1", "T2"), // (11,14): error CS0019: Operator '==' cannot be applied to operands of type 'T1' and 'T3' // b = (t1 == t3); Diagnostic(ErrorCode.ERR_BadBinaryOps, "t1 == t3").WithArguments("==", "T1", "T3"), // (12,14): error CS0019: Operator '==' cannot be applied to operands of type 'T1' and 'T4' // b = (t1 == t4); Diagnostic(ErrorCode.ERR_BadBinaryOps, "t1 == t4").WithArguments("==", "T1", "T4"), // (13,14): error CS0019: Operator '==' cannot be applied to operands of type 'T1' and 'int' // b = (t1 == i); Diagnostic(ErrorCode.ERR_BadBinaryOps, "t1 == i").WithArguments("==", "T1", "int"), // (14,14): error CS0019: Operator '==' cannot be applied to operands of type 'T1' and 'C' // b = (t1 == c); Diagnostic(ErrorCode.ERR_BadBinaryOps, "t1 == c").WithArguments("==", "T1", "C"), // (16,14): error CS0019: Operator '==' cannot be applied to operands of type 'T2' and 'T1' // b = (t2 == t1); Diagnostic(ErrorCode.ERR_BadBinaryOps, "t2 == t1").WithArguments("==", "T2", "T1"), // (18,14): error CS0019: Operator '==' cannot be applied to operands of type 'T2' and 'T3' // b = (t2 == t3); Diagnostic(ErrorCode.ERR_BadBinaryOps, "t2 == t3").WithArguments("==", "T2", "T3"), // (19,14): error CS0019: Operator '==' cannot be applied to operands of type 'T2' and 'T4' // b = (t2 == t4); Diagnostic(ErrorCode.ERR_BadBinaryOps, "t2 == t4").WithArguments("==", "T2", "T4"), // (20,14): error CS0019: Operator '==' cannot be applied to operands of type 'T2' and 'int' // b = (t2 == i); Diagnostic(ErrorCode.ERR_BadBinaryOps, "t2 == i").WithArguments("==", "T2", "int"), // (23,14): error CS0019: Operator '==' cannot be applied to operands of type 'T3' and 'T1' // b = (t3 == t1); Diagnostic(ErrorCode.ERR_BadBinaryOps, "t3 == t1").WithArguments("==", "T3", "T1"), // (24,14): error CS0019: Operator '==' cannot be applied to operands of type 'T3' and 'T2' // b = (t3 == t2); Diagnostic(ErrorCode.ERR_BadBinaryOps, "t3 == t2").WithArguments("==", "T3", "T2"), // (25,14): error CS0019: Operator '==' cannot be applied to operands of type 'T3' and 'T3' // b = (t3 == t3); Diagnostic(ErrorCode.ERR_BadBinaryOps, "t3 == t3").WithArguments("==", "T3", "T3"), // (26,14): error CS0019: Operator '==' cannot be applied to operands of type 'T3' and 'T4' // b = (t3 == t4); Diagnostic(ErrorCode.ERR_BadBinaryOps, "t3 == t4").WithArguments("==", "T3", "T4"), // (27,14): error CS0019: Operator '==' cannot be applied to operands of type 'T3' and 'int' // b = (t3 == i); Diagnostic(ErrorCode.ERR_BadBinaryOps, "t3 == i").WithArguments("==", "T3", "int"), // (28,14): error CS0019: Operator '==' cannot be applied to operands of type 'T3' and 'C' // b = (t3 == c); Diagnostic(ErrorCode.ERR_BadBinaryOps, "t3 == c").WithArguments("==", "T3", "C"), // (29,14): error CS0019: Operator '==' cannot be applied to operands of type 'T3' and '<null>' // b = (t3 == null); Diagnostic(ErrorCode.ERR_BadBinaryOps, "t3 == null").WithArguments("==", "T3", "<null>"), // (30,14): error CS0019: Operator '!=' cannot be applied to operands of type 'T4' and 'T1' // b = (t4 != t1); Diagnostic(ErrorCode.ERR_BadBinaryOps, "t4 != t1").WithArguments("!=", "T4", "T1"), // (31,14): error CS0019: Operator '!=' cannot be applied to operands of type 'T4' and 'T2' // b = (t4 != t2); Diagnostic(ErrorCode.ERR_BadBinaryOps, "t4 != t2").WithArguments("!=", "T4", "T2"), // (32,14): error CS0019: Operator '!=' cannot be applied to operands of type 'T4' and 'T3' // b = (t4 != t3); Diagnostic(ErrorCode.ERR_BadBinaryOps, "t4 != t3").WithArguments("!=", "T4", "T3"), // (33,14): error CS0019: Operator '!=' cannot be applied to operands of type 'T4' and 'T4' // b = (t4 != t4); Diagnostic(ErrorCode.ERR_BadBinaryOps, "t4 != t4").WithArguments("!=", "T4", "T4"), // (34,14): error CS0019: Operator '!=' cannot be applied to operands of type 'T4' and 'int' // b = (t4 != i); Diagnostic(ErrorCode.ERR_BadBinaryOps, "t4 != i").WithArguments("!=", "T4", "int"), // (35,14): error CS0019: Operator '!=' cannot be applied to operands of type 'T4' and 'C' // b = (t4 != c); Diagnostic(ErrorCode.ERR_BadBinaryOps, "t4 != c").WithArguments("!=", "T4", "C"), // (37,14): error CS0019: Operator '!=' cannot be applied to operands of type 'int' and 'T1' // b = (i != t1); Diagnostic(ErrorCode.ERR_BadBinaryOps, "i != t1").WithArguments("!=", "int", "T1"), // (38,14): error CS0019: Operator '!=' cannot be applied to operands of type 'int' and 'T2' // b = (i != t2); Diagnostic(ErrorCode.ERR_BadBinaryOps, "i != t2").WithArguments("!=", "int", "T2"), // (39,14): error CS0019: Operator '!=' cannot be applied to operands of type 'int' and 'T3' // b = (i != t3); Diagnostic(ErrorCode.ERR_BadBinaryOps, "i != t3").WithArguments("!=", "int", "T3"), // (40,14): error CS0019: Operator '!=' cannot be applied to operands of type 'int' and 'T4' // b = (i != t4); Diagnostic(ErrorCode.ERR_BadBinaryOps, "i != t4").WithArguments("!=", "int", "T4"), // (42,14): error CS0019: Operator '!=' cannot be applied to operands of type 'int' and 'C' // b = (i != c); Diagnostic(ErrorCode.ERR_BadBinaryOps, "i != c").WithArguments("!=", "int", "C"), // (44,14): error CS0019: Operator '!=' cannot be applied to operands of type 'C' and 'T1' // b = (c != t1); Diagnostic(ErrorCode.ERR_BadBinaryOps, "c != t1").WithArguments("!=", "C", "T1"), // (46,14): error CS0019: Operator '!=' cannot be applied to operands of type 'C' and 'T3' // b = (c != t3); Diagnostic(ErrorCode.ERR_BadBinaryOps, "c != t3").WithArguments("!=", "C", "T3"), // (47,14): error CS0019: Operator '!=' cannot be applied to operands of type 'C' and 'T4' // b = (c != t4); Diagnostic(ErrorCode.ERR_BadBinaryOps, "c != t4").WithArguments("!=", "C", "T4"), // (48,14): error CS0019: Operator '!=' cannot be applied to operands of type 'C' and 'int' // b = (c != i); Diagnostic(ErrorCode.ERR_BadBinaryOps, "c != i").WithArguments("!=", "C", "int"), // (53,14): error CS0019: Operator '!=' cannot be applied to operands of type '<null>' and 'T3' // b = (null != t3); Diagnostic(ErrorCode.ERR_BadBinaryOps, "null != t3").WithArguments("!=", "<null>", "T3"), // (17,14): warning CS1718: Comparison made to same variable; did you mean to compare something else? // b = (t2 == t2); Diagnostic(ErrorCode.WRN_ComparisonToSelf, "t2 == t2"), // (41,14): warning CS1718: Comparison made to same variable; did you mean to compare something else? // b = (i != i); Diagnostic(ErrorCode.WRN_ComparisonToSelf, "i != i"), // (43,14): warning CS0472: The result of the expression is always 'true' since a value of type 'int' is never equal to 'null' of type 'int?' // b = (i != null); Diagnostic(ErrorCode.WRN_NubExprIsConstBool, "i != null").WithArguments("true", "int", "int?"), // (49,14): warning CS1718: Comparison made to same variable; did you mean to compare something else? // b = (c != c); Diagnostic(ErrorCode.WRN_ComparisonToSelf, "c != c"), // (55,14): warning CS0472: The result of the expression is always 'true' since a value of type 'int' is never equal to 'null' of type 'int?' // b = (null != i); Diagnostic(ErrorCode.WRN_NubExprIsConstBool, "null != i").WithArguments("true", "int", "int?")); } [Fact] public void CS0019ERR_BadBinaryOps16() { var text = @"class A { } class B : A { } interface I { } class C { static void M<T, U>(T t, U u, A a, B b, C c, I i) where T : A where U : B { bool x; x = (t == t); x = (t == u); x = (t == a); x = (t == b); x = (t == c); x = (t == i); x = (u == t); x = (u == u); x = (u == a); x = (u == b); x = (u == c); x = (u == i); x = (a == t); x = (a == u); x = (a == a); x = (a == b); x = (a == c); x = (a == i); x = (b == t); x = (b == u); x = (b == a); x = (b == b); x = (b == c); x = (b == i); x = (c == t); x = (c == u); x = (c == a); x = (c == b); x = (c == c); x = (c == i); x = (i == t); x = (i == u); x = (i == a); x = (i == b); x = (i == c); x = (i == i); } }"; CreateCompilation(text).VerifyDiagnostics( // (15,14): error CS0019: Operator '==' cannot be applied to operands of type 'T' and 'C' // x = (t == c); Diagnostic(ErrorCode.ERR_BadBinaryOps, "t == c").WithArguments("==", "T", "C"), // (21,14): error CS0019: Operator '==' cannot be applied to operands of type 'U' and 'C' // x = (u == c); Diagnostic(ErrorCode.ERR_BadBinaryOps, "u == c").WithArguments("==", "U", "C"), // (27,14): error CS0019: Operator '==' cannot be applied to operands of type 'A' and 'C' // x = (a == c); Diagnostic(ErrorCode.ERR_BadBinaryOps, "a == c").WithArguments("==", "A", "C"), // (33,14): error CS0019: Operator '==' cannot be applied to operands of type 'B' and 'C' // x = (b == c); Diagnostic(ErrorCode.ERR_BadBinaryOps, "b == c").WithArguments("==", "B", "C"), // (35,14): error CS0019: Operator '==' cannot be applied to operands of type 'C' and 'T' // x = (c == t); Diagnostic(ErrorCode.ERR_BadBinaryOps, "c == t").WithArguments("==", "C", "T"), // (36,14): error CS0019: Operator '==' cannot be applied to operands of type 'C' and 'U' // x = (c == u); Diagnostic(ErrorCode.ERR_BadBinaryOps, "c == u").WithArguments("==", "C", "U"), // (37,14): error CS0019: Operator '==' cannot be applied to operands of type 'C' and 'A' // x = (c == a); Diagnostic(ErrorCode.ERR_BadBinaryOps, "c == a").WithArguments("==", "C", "A"), // (38,14): error CS0019: Operator '==' cannot be applied to operands of type 'C' and 'B' // x = (c == b); Diagnostic(ErrorCode.ERR_BadBinaryOps, "c == b").WithArguments("==", "C", "B"), // (11,14): warning CS1718: Comparison made to same variable; did you mean to compare something else? // x = (t == t); Diagnostic(ErrorCode.WRN_ComparisonToSelf, "t == t"), // (18,14): warning CS1718: Comparison made to same variable; did you mean to compare something else? // x = (u == u); Diagnostic(ErrorCode.WRN_ComparisonToSelf, "u == u"), // (25,14): warning CS1718: Comparison made to same variable; did you mean to compare something else? // x = (a == a); Diagnostic(ErrorCode.WRN_ComparisonToSelf, "a == a"), // (32,14): warning CS1718: Comparison made to same variable; did you mean to compare something else? // x = (b == b); Diagnostic(ErrorCode.WRN_ComparisonToSelf, "b == b"), // (39,14): warning CS1718: Comparison made to same variable; did you mean to compare something else? // x = (c == c); Diagnostic(ErrorCode.WRN_ComparisonToSelf, "c == c"), // (46,14): warning CS1718: Comparison made to same variable; did you mean to compare something else? // x = (i == i); Diagnostic(ErrorCode.WRN_ComparisonToSelf, "i == i")); } [Fact] public void CS0019ERR_BadBinaryOps17() { var text = @"struct S { } abstract class A<T> { internal virtual void M<U>(U u) where U : T { bool b; b = (u == null); b = (null != u); } } class B : A<S> { internal override void M<U>(U u) { bool b; b = (u == null); b = (null != u); } }"; CreateCompilation(text).VerifyDiagnostics( // (16,14): error CS0019: Operator '==' cannot be applied to operands of type 'U' and '<null>' Diagnostic(ErrorCode.ERR_BadBinaryOps, "u == null").WithArguments("==", "U", "<null>").WithLocation(16, 14), // (17,14): error CS0019: Operator '!=' cannot be applied to operands of type '<null>' and 'U' Diagnostic(ErrorCode.ERR_BadBinaryOps, "null != u").WithArguments("!=", "<null>", "U").WithLocation(17, 14)); } [Fact] public void CS0020ERR_IntDivByZero() { var text = @" namespace x { public class b { public static int Main() { int s = 1 / 0; // CS0020 return s; } } }"; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_IntDivByZero, Line = 8, Column = 21 } }); } [Fact] public void CS0020ERR_IntDivByZero_02() { var text = @" namespace x { public class b { public static void Main() { decimal x1 = 1.20M / 0; // CS0020 decimal x2 = 1.20M / decimal.Zero; // CS0020 decimal x3 = decimal.MaxValue / decimal.Zero; // CS0020 } } }"; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_IntDivByZero, Line = 8, Column = 26 }, new ErrorDescription { Code = (int)ErrorCode.ERR_IntDivByZero, Line = 9, Column = 26 }, new ErrorDescription { Code = (int)ErrorCode.ERR_IntDivByZero, Line = 10, Column = 26 } }); } [Fact] public void CS0021ERR_BadIndexLHS() { var text = @"enum E { } class C { static void M<T>() { object o; o = M[0]; o = ((System.Action)null)[0]; o = ((dynamic)o)[0]; o = default(E)[0]; o = default(T)[0]; o = (new C())[0]; } }"; CreateCompilation(text).VerifyDiagnostics( // (7,13): error CS0021: Cannot apply indexing with [] to an expression of type 'method group' Diagnostic(ErrorCode.ERR_BadIndexLHS, "M[0]").WithArguments("method group").WithLocation(7, 13), // (8,13): error CS0021: Cannot apply indexing with [] to an expression of type 'System.Action' Diagnostic(ErrorCode.ERR_BadIndexLHS, "((System.Action)null)[0]").WithArguments("System.Action").WithLocation(8, 13), // (10,13): error CS0021: Cannot apply indexing with [] to an expression of type 'E' Diagnostic(ErrorCode.ERR_BadIndexLHS, "default(E)[0]").WithArguments("E").WithLocation(10, 13), // (11,13): error CS0021: Cannot apply indexing with [] to an expression of type 'T' Diagnostic(ErrorCode.ERR_BadIndexLHS, "default(T)[0]").WithArguments("T").WithLocation(11, 13), // (12,13): error CS0021: Cannot apply indexing with [] to an expression of type 'C' Diagnostic(ErrorCode.ERR_BadIndexLHS, "(new C())[0]").WithArguments("C").WithLocation(12, 13)); } [Fact] public void CS0022ERR_BadIndexCount() { var text = @" namespace x { public class b { public static void Main() { int[,] a = new int[10,2] ; a[2] = 4; //bad index count in access } } }"; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_BadIndexCount, Line = 9, Column = 25 } }); } [WorkItem(542486, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542486")] [Fact] public void CS0022ERR_BadIndexCount02() { var text = @" class Program { static void Main(string[] args) { int[,] a = new int[1 2]; //bad index count in size specifier - no initializer } } "; CreateCompilation(text).VerifyDiagnostics( // (6,30): error CS1003: Syntax error, ',' expected Diagnostic(ErrorCode.ERR_SyntaxError, "2").WithArguments(",", "")); } [WorkItem(542486, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542486")] [Fact] public void CS0022ERR_BadIndexCount03() { var text = @" class Program { static void Main(string[] args) { int[,] a = new int[1 2] { 1 }; //bad index count in size specifier - with initializer } } "; // NOTE: Dev10 just gives a parse error on '2' CreateCompilation(text).VerifyDiagnostics( // (6,30): error CS1003: Syntax error, ',' expected Diagnostic(ErrorCode.ERR_SyntaxError, "2").WithArguments(",", ""), // (6,35): error CS0846: A nested array initializer is expected Diagnostic(ErrorCode.ERR_ArrayInitializerExpected, "1")); } [WorkItem(542486, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542486")] [Fact] public void CS0022ERR_BadIndexCount04() { var text = @" class Program { static void Main(string[] args) { int[,] a = new int[1,]; //bad index count in size specifier - no initializer } } "; CreateCompilation(text).VerifyDiagnostics( // (6,30): error CS0443: Syntax error; value expected Diagnostic(ErrorCode.ERR_ValueExpected, "")); } [WorkItem(542486, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542486")] [Fact] public void CS0022ERR_BadIndexCount05() { var text = @" class Program { static void Main(string[] args) { int[,] a = new int[1,] { { 1 } }; //bad index count in size specifier - with initializer } } "; CreateCompilation(text).VerifyDiagnostics( // (6,30): error CS0443: Syntax error; value expected Diagnostic(ErrorCode.ERR_ValueExpected, "")); } [WorkItem(539590, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539590")] [Fact] public void CS0023ERR_BadUnaryOp1() { var text = @" namespace X { class C { object M() { object q = new object(); if (!q) // CS0023 { } object obj = -null; // CS0023 obj = !null; // CS0023 obj = ~null; // CS0023 obj++; // CS0023 --obj; // CS0023 return +null; // CS0023 } } } "; CreateCompilation(text).VerifyDiagnostics( // (9,17): error CS0023: Operator '!' cannot be applied to operand of type 'object' // if (!q) // CS0023 Diagnostic(ErrorCode.ERR_BadUnaryOp, "!q").WithArguments("!", "object").WithLocation(9, 17), // (12,26): error CS8310: Operator '-' cannot be applied to operand '<null>' // object obj = -null; // CS0023 Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, "-null").WithArguments("-", "<null>").WithLocation(12, 26), // (13,19): error CS8310: Operator '!' cannot be applied to operand '<null>' // obj = !null; // CS0023 Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, "!null").WithArguments("!", "<null>").WithLocation(13, 19), // (14,19): error CS8310: Operator '~' cannot be applied to operand '<null>' // obj = ~null; // CS0023 Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, "~null").WithArguments("~", "<null>").WithLocation(14, 19), // (16,13): error CS0023: Operator '++' cannot be applied to operand of type 'object' // obj++; // CS0023 Diagnostic(ErrorCode.ERR_BadUnaryOp, "obj++").WithArguments("++", "object").WithLocation(16, 13), // (17,13): error CS0023: Operator '--' cannot be applied to operand of type 'object' // --obj; // CS0023 Diagnostic(ErrorCode.ERR_BadUnaryOp, "--obj").WithArguments("--", "object").WithLocation(17, 13), // (18,20): error CS8310: Operator '+' cannot be applied to operand '<null>' // return +null; // CS0023 Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, "+null").WithArguments("+", "<null>").WithLocation(18, 20) ); } [WorkItem(539590, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539590")] [Fact] public void CS0023ERR_BadUnaryOp_Nullable() { var text = @" public class Test { public static void Main() { bool? b = !null; // CS0023 int? n = ~null; // CS0023 float? f = +null; // CS0023 long? u = -null; // CS0023 ++n; n--; --u; u++; } } "; CreateCompilation(text).VerifyDiagnostics( // (6,19): error CS8310: Operator '!' cannot be applied to operand '<null>' // bool? b = !null; // CS0023 Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, "!null").WithArguments("!", "<null>").WithLocation(6, 19), // (7,18): error CS8310: Operator '~' cannot be applied to operand '<null>' // int? n = ~null; // CS0023 Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, "~null").WithArguments("~", "<null>").WithLocation(7, 18), // (8,20): error CS8310: Operator '+' cannot be applied to operand '<null>' // float? f = +null; // CS0023 Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, "+null").WithArguments("+", "<null>").WithLocation(8, 20), // (9,19): error CS8310: Operator '-' cannot be applied to operand '<null>' // long? u = -null; // CS0023 Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, "-null").WithArguments("-", "<null>").WithLocation(9, 19) ); } [WorkItem(539590, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539590")] [Fact] public void CS0023ERR_BadUnaryOp2() { var text = @" namespace X { class C { void M() { System.Action f = M; f = +M; // CS0023 f = +(() => { }); // CS0023 } } } "; CreateCompilation(text).VerifyDiagnostics( // (9,17): error CS0023: Operator '+' cannot be applied to operand of type 'method group' Diagnostic(ErrorCode.ERR_BadUnaryOp, "+M").WithArguments("+", "method group"), // (10,17): error CS0023: Operator '+' cannot be applied to operand of type 'lambda expression' Diagnostic(ErrorCode.ERR_BadUnaryOp, "+(() => { })").WithArguments("+", "lambda expression")); } [WorkItem(540211, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540211")] [Fact] public void CS0023ERR_BadUnaryOp_VoidMissingInstanceMethod() { var text = @"class C { void M() { M().Goo(); } } "; CreateCompilation(text).VerifyDiagnostics( // (5,12): error CS0023: Operator '.' cannot be applied to operand of type 'void' Diagnostic(ErrorCode.ERR_BadUnaryOp, ".").WithArguments(".", "void")); } [WorkItem(540211, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540211")] [Fact] public void CS0023ERR_BadUnaryOp_VoidToString() { var text = @"class C { void M() { M().ToString(); //plausible, but still wrong } } "; CreateCompilation(text).VerifyDiagnostics( // (5,12): error CS0023: Operator '.' cannot be applied to operand of type 'void' Diagnostic(ErrorCode.ERR_BadUnaryOp, ".").WithArguments(".", "void")); } [WorkItem(540329, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540329")] [Fact] public void CS0023ERR_BadUnaryOp_null() { var text = @" class X { static void Main() { int x = null.Length; } } "; CreateCompilation(text).VerifyDiagnostics( Diagnostic(ErrorCode.ERR_BadUnaryOp, "null.Length").WithArguments(".", "<null>")); } [WorkItem(540329, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540329")] [Fact] 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( Diagnostic(ErrorCode.ERR_BadUnaryOp, "arg => { arg = 2; return arg; }.ToString").WithArguments(".", "lambda expression"), Diagnostic(ErrorCode.ERR_BadUnaryOp, "delegate { }.ToString").WithArguments(".", "anonymous method")); } [Fact] public void CS0026ERR_ThisInStaticMeth() { var text = @" public class MyClass { public static int i = 0; public static void Main() { // CS0026 this.i = this.i + 1; } }"; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_ThisInStaticMeth, Line = 9, Column = 9 }, new ErrorDescription { Code = (int)ErrorCode.ERR_ObjectProhibited, Line = 9, Column = 9 }, new ErrorDescription { Code = (int)ErrorCode.ERR_ThisInStaticMeth, Line = 9, Column = 18 }, new ErrorDescription { Code = (int)ErrorCode.ERR_ObjectProhibited, Line = 9, Column = 18 } }); } [Fact] public void CS0026ERR_ThisInStaticMeth_StaticConstructor() { var text = @" public class MyClass { int f; void M() { } int P { get; set; } static MyClass() { this.f = this.P; this.M(); } }"; CreateCompilation(text).VerifyDiagnostics( // (10,9): error CS0026: Keyword 'this' is not valid in a static property, static method, or static field initializer Diagnostic(ErrorCode.ERR_ThisInStaticMeth, "this"), // (10,18): error CS0026: Keyword 'this' is not valid in a static property, static method, or static field initializer Diagnostic(ErrorCode.ERR_ThisInStaticMeth, "this"), // (11,9): error CS0026: Keyword 'this' is not valid in a static property, static method, or static field initializer Diagnostic(ErrorCode.ERR_ThisInStaticMeth, "this")); } [Fact] public void CS0026ERR_ThisInStaticMeth_Combined() { var text = @" using System; class CLS { static CLS() { var x = this.ToString(); } static object FLD = this.ToString(); static object PROP { get { return this.ToString(); } } static object METHOD() { return this.ToString(); } } class A : Attribute { public object P; } "; CreateCompilation(text).VerifyDiagnostics( // (7,25): error CS0026: Keyword 'this' is not valid in a static property, static method, or static field initializer // static object FLD = this.ToString(); Diagnostic(ErrorCode.ERR_ThisInStaticMeth, "this"), // (6,28): error CS0026: Keyword 'this' is not valid in a static property, static method, or static field initializer // static CLS() { var x = this.ToString(); } Diagnostic(ErrorCode.ERR_ThisInStaticMeth, "this"), // (8,39): error CS0026: Keyword 'this' is not valid in a static property, static method, or static field initializer // static object PROP { get { return this.ToString(); } } Diagnostic(ErrorCode.ERR_ThisInStaticMeth, "this"), // (9,37): error CS0026: Keyword 'this' is not valid in a static property, static method, or static field initializer // static object METHOD() { return this.ToString(); } Diagnostic(ErrorCode.ERR_ThisInStaticMeth, "this"), // (14,19): warning CS0649: Field 'A.P' is never assigned to, and will always have its default value null // public object P; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "P").WithArguments("A.P", "null") ); } [Fact] public void CS0027ERR_ThisInBadContext() { var text = @" namespace ConsoleApplication3 { class MyClass { int err1 = this.Fun() + 1; // CS0027 public void Fun() { } } }"; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_ThisInBadContext, Line = 6, Column = 20 } }); } [Fact] public void CS0027ERR_ThisInBadContext_2() { var text = @" using System; [assembly: A(P = this.ToString())] class A : Attribute { public object P; } "; CreateCompilation(text).VerifyDiagnostics( // (4,18): error CS0027: Keyword 'this' is not available in the current context // [assembly: A(P = this.ToString())] Diagnostic(ErrorCode.ERR_ThisInBadContext, "this")); } [Fact] public void CS0027ERR_ThisInBadContext_Interactive() { string text = @" int a; int b = a; int c = this.a; // 1 this.c = // 2 this.a; // 3 int prop { get { return 1; } set { this.a = 1;} } // 4 void goo() { this.goo(); // 5 this.a = // 6 this.b; // 7 object c = this; // 8 } this.prop = 1; // 9 class C { C() : base() { } void goo() { this.goo(); // OK } }"; var comp = CreateCompilationWithMscorlib45( new[] { SyntaxFactory.ParseSyntaxTree(text, options: TestOptions.Script) }); comp.VerifyDiagnostics( // (4,9): error CS0027: Keyword 'this' is not available in the current context // int c = this.a; // 1 Diagnostic(ErrorCode.ERR_ThisInBadContext, "this").WithLocation(4, 9), // (5,1): error CS0027: Keyword 'this' is not available in the current context // this.c = // 2 Diagnostic(ErrorCode.ERR_ThisInBadContext, "this").WithLocation(5, 1), // (6,5): error CS0027: Keyword 'this' is not available in the current context // this.a; // 3 Diagnostic(ErrorCode.ERR_ThisInBadContext, "this").WithLocation(6, 5), // (16,1): error CS0027: Keyword 'this' is not available in the current context // this.prop = 1; // 9 Diagnostic(ErrorCode.ERR_ThisInBadContext, "this").WithLocation(16, 1), // (7,36): error CS0027: Keyword 'this' is not available in the current context // int prop { get { return 1; } set { this.a = 1;} } // 4 Diagnostic(ErrorCode.ERR_ThisInBadContext, "this").WithLocation(7, 36), // (10,5): error CS0027: Keyword 'this' is not available in the current context // this.goo(); // 5 Diagnostic(ErrorCode.ERR_ThisInBadContext, "this").WithLocation(10, 5), // (11,5): error CS0027: Keyword 'this' is not available in the current context // this.a = // 6 Diagnostic(ErrorCode.ERR_ThisInBadContext, "this").WithLocation(11, 5), // (12,9): error CS0027: Keyword 'this' is not available in the current context // this.b; // 7 Diagnostic(ErrorCode.ERR_ThisInBadContext, "this").WithLocation(12, 9), // (13,16): error CS0027: Keyword 'this' is not available in the current context // object c = this; // 8 Diagnostic(ErrorCode.ERR_ThisInBadContext, "this").WithLocation(13, 16) ); } [Fact] public void CS0029ERR_NoImplicitConv01() { var text = @" namespace ConsoleApplication3 { class MyClass { int err1 = 1; public string Fun() { return err1; } public static void Main() { MyClass c = new MyClass(); } } }"; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_NoImplicitConv, Line = 11, Column = 20 } }); } [Fact] public void CS0029ERR_NoImplicitConv02() { var source = "enum E { A = new[] { 1, 2, 3 } }"; CreateCompilation(source).VerifyDiagnostics( // (1,14): error CS0029: Cannot implicitly convert type 'int[]' to 'int' // enum E { A = new[] { 1, 2, 3 } } Diagnostic(ErrorCode.ERR_NoImplicitConv, "new[] { 1, 2, 3 }").WithArguments("int[]", "int").WithLocation(1, 14)); } [Fact] public void CS0029ERR_NoImplicitConv03() { var source = @"class C { static void M() { const C d = F(); } static D F() { return null; } } class D { } "; CreateCompilation(source).VerifyDiagnostics( // (5,21): error CS0029: Cannot implicitly convert type 'D' to 'C' // const C d = F(); Diagnostic(ErrorCode.ERR_NoImplicitConv, "F()").WithArguments("D", "C").WithLocation(5, 21)); } [WorkItem(541719, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541719")] [Fact] public void CS0029ERR_NoImplicitConv04() { var text = @"class C1 { public static void Main() { bool m = true; int[] arr = new int[m]; // Invalid } } "; CreateCompilation(text).VerifyDiagnostics( // (6,29): error CS0029: Cannot implicitly convert type 'bool' to 'int' // int[] arr = new int[m]; // Invalid Diagnostic(ErrorCode.ERR_NoImplicitConv, "m").WithArguments("bool", "int").WithLocation(6, 29)); } [Fact, WorkItem(40405, "https://github.com/dotnet/roslyn/issues/40405")] public void ThrowExpression_ImplicitVoidConversion_Return() { string text = @" class C { void M1() { return true ? throw null : M2(); } void M2() { } } "; CreateCompilation(text).VerifyDiagnostics( // (6,23): error CS0029: Cannot implicitly convert type '<throw expression>' to 'void' // return true ? throw null : M2(); Diagnostic(ErrorCode.ERR_NoImplicitConv, "throw null").WithArguments("<throw expression>", "void").WithLocation(6, 23)); } [Fact, WorkItem(40405, "https://github.com/dotnet/roslyn/issues/40405")] public void ThrowExpression_ImplicitVoidConversion_Assignment() { string text = @" class C { void M1() { object obj = true ? throw null : M2(); } void M2() { } } "; CreateCompilation(text).VerifyDiagnostics( // (6,29): error CS0029: Cannot implicitly convert type '<throw expression>' to 'void' // object obj = true ? throw null : M2(); Diagnostic(ErrorCode.ERR_NoImplicitConv, "throw null").WithArguments("<throw expression>", "void").WithLocation(6, 29)); } [Fact, WorkItem(40405, "https://github.com/dotnet/roslyn/issues/40405")] public void IntLiteral_ImplicitVoidConversion_Assignment() { string text = @" class C { void M1() { var obj = true ? 0 : M2(); } void M2() { } } "; CreateCompilation(text).VerifyDiagnostics( // (6,19): error CS0173: Type of conditional expression cannot be determined because there is no implicit conversion between 'int' and 'void' // var obj = true ? 0 : M2(); Diagnostic(ErrorCode.ERR_InvalidQM, "true ? 0 : M2()").WithArguments("int", "void").WithLocation(6, 19) ); } [Fact, WorkItem(40405, "https://github.com/dotnet/roslyn/issues/40405")] public void VoidCall_ImplicitVoidConversion_Assignment() { string text = @" class C { void M1() { object obj = true ? M2() : M2(); } void M2() { } } "; CreateCompilation(text).VerifyDiagnostics( // (6,22): error CS0029: Cannot implicitly convert type 'void' to 'object' // object obj = true ? M2() : M2(); Diagnostic(ErrorCode.ERR_NoImplicitConv, "true ? M2() : M2()").WithArguments("void", "object").WithLocation(6, 22)); } [Fact, WorkItem(40405, "https://github.com/dotnet/roslyn/issues/40405")] public void VoidCall_ImplicitVoidConversion_DiscardAssignment() { string text = @" class C { void M1() { _ = true ? M2() : M2(); } void M2() { } } "; CreateCompilation(text).VerifyDiagnostics( // (6,9): error CS8209: A value of type 'void' may not be assigned. // _ = true ? M2() : M2(); Diagnostic(ErrorCode.ERR_VoidAssignment, "_").WithLocation(6, 9)); } [Fact, WorkItem(40405, "https://github.com/dotnet/roslyn/issues/40405")] public void VoidCall_Assignment() { string text = @" class C { void M1() { object obj = M2(); } void M2() { } } "; CreateCompilation(text).VerifyDiagnostics( // (6,22): error CS0029: Cannot implicitly convert type 'void' to 'object' // object obj = M2(); Diagnostic(ErrorCode.ERR_NoImplicitConv, "M2()").WithArguments("void", "object").WithLocation(6, 22)); } [Fact, WorkItem(40405, "https://github.com/dotnet/roslyn/issues/40405")] public void VoidCall_DiscardAssignment() { string text = @" class C { void M1() { _ = M2(); } void M2() { } } "; CreateCompilation(text).VerifyDiagnostics( // (6,9): error CS8209: A value of type 'void' may not be assigned. // _ = M2(); Diagnostic(ErrorCode.ERR_VoidAssignment, "_").WithLocation(6, 9)); } [Fact, WorkItem(40405, "https://github.com/dotnet/roslyn/issues/40405")] public void VoidCall_ImplicitVoidConversion_Return() { string text = @" class C { void M1() { return true ? M2() : M2(); } void M2() { } } "; CreateCompilation(text).VerifyDiagnostics( // (6,9): error CS0127: Since 'C.M1()' returns void, a return keyword must not be followed by an object expression // return true ? M2() : M2(); Diagnostic(ErrorCode.ERR_RetNoObjectRequired, "return").WithArguments("C.M1()").WithLocation(6, 9)); } [Fact] public void CS0030ERR_NoExplicitConv() { var text = @" namespace x { public class iii { public static iii operator ++(iii aa) { return (iii)0; // CS0030 } } }"; CreateCompilation(text).VerifyDiagnostics( // (8,20): error CS0030: Cannot convert type 'int' to 'x.iii' // return (iii)0; // CS0030 Diagnostic(ErrorCode.ERR_NoExplicitConv, "(iii)0").WithArguments("int", "x.iii")); } [WorkItem(528539, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528539")] [WorkItem(1119609, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1119609")] [WorkItem(920, "http://github.com/dotnet/roslyn/issues/920")] [Fact] public void CS0030ERR_NoExplicitConv02() { const string text = @" public class C { public static void Main() { decimal x = (decimal)double.PositiveInfinity; } }"; var diagnostics = CreateCompilation(text).GetDiagnostics(); var savedCurrentCulture = Thread.CurrentThread.CurrentCulture; var savedCurrentUICulture = Thread.CurrentThread.CurrentUICulture; Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture; Thread.CurrentThread.CurrentUICulture = CultureInfo.InvariantCulture; try { diagnostics.Verify( // (6,21): error CS0031: Constant value 'Infinity' cannot be converted to a 'decimal' // decimal x = (decimal)double.PositiveInfinity; Diagnostic(ErrorCode.ERR_ConstOutOfRange, "(decimal)double.PositiveInfinity").WithArguments("Infinity", "decimal"), // (6,17): warning CS0219: The variable 'x' is assigned but its value is never used // decimal x = (decimal)double.PositiveInfinity; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x").WithArguments("x")); } finally { Thread.CurrentThread.CurrentCulture = savedCurrentCulture; Thread.CurrentThread.CurrentUICulture = savedCurrentUICulture; } } [Fact] public void CS0030ERR_NoExplicitConv_Foreach() { var text = @" public class Test { static void Main(string[] args) { int[][] arr = new int[][] { new int[] { 1, 2 }, new int[] { 4, 5, 6 } }; foreach (int outer in arr) { } // invalid } }"; CreateCompilation(text).VerifyDiagnostics(Diagnostic(ErrorCode.ERR_NoExplicitConv, "foreach").WithArguments("int[]", "int")); } [Fact] public void CS0031ERR_ConstOutOfRange01() { var text = @"public class a { int num = (int)2147483648M; //CS0031 } "; CreateCompilation(text).VerifyDiagnostics( // (3,15): error CS0031: Constant value '2147483648M' cannot be converted to a 'int' // int num = (int)2147483648M; //CS0031 Diagnostic(ErrorCode.ERR_ConstOutOfRange, "(int)2147483648M").WithArguments("2147483648M", "int"), // (3,9): warning CS0414: The field 'a.num' is assigned but its value is never used // int num = (int)2147483648M; //CS0031 Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "num").WithArguments("a.num")); } [WorkItem(528539, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528539")] [Fact] public void CS0031ERR_ConstOutOfRange02() { var text = @" enum E : ushort { A = 10, B = -1 // CS0031 } enum F : sbyte { A = 0x7f, B = 0xf0, // CS0031 C, D = (A + 1) - 2, E = (A + 1), // CS0031 } class A { byte bt = 256; } "; CreateCompilation(text).VerifyDiagnostics( // (5,9): error CS0031: Constant value '-1' cannot be converted to a 'ushort' // B = -1 // CS0031 Diagnostic(ErrorCode.ERR_ConstOutOfRange, "-1").WithArguments("-1", "ushort").WithLocation(5, 9), // (10,9): error CS0031: Constant value '240' cannot be converted to a 'sbyte' // B = 0xf0, // CS0031 Diagnostic(ErrorCode.ERR_ConstOutOfRange, "0xf0").WithArguments("240", "sbyte").WithLocation(10, 9), // (13,10): error CS0031: Constant value '128' cannot be converted to a 'sbyte' // E = (A + 1), // CS0031 Diagnostic(ErrorCode.ERR_ConstOutOfRange, "A + 1").WithArguments("128", "sbyte").WithLocation(13, 10), // (17,15): error CS0031: Constant value '256' cannot be converted to a 'byte' // byte bt = 256; Diagnostic(ErrorCode.ERR_ConstOutOfRange, "256").WithArguments("256", "byte").WithLocation(17, 15), // (17,10): warning CS0414: The field 'A.bt' is assigned but its value is never used // byte bt = 256; Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "bt").WithArguments("A.bt").WithLocation(17, 10)); } [Fact] public void CS0221ERR_ConstOutOfRangeChecked04() { // Confirm that we truncate the constant value before performing the range check var template = @"public class C { void M() { System.Console.WriteLine((System.Int32)(System.Int32.MinValue - 0.9)); System.Console.WriteLine((System.Int32)(System.Int32.MinValue - 1.0)); //CS0221 System.Console.WriteLine((System.Int32)(System.Int32.MaxValue + 0.9)); System.Console.WriteLine((System.Int32)(System.Int32.MaxValue + 1.0)); //CS0221 } } "; var integralTypes = new Type[] { typeof(char), typeof(sbyte), typeof(byte), typeof(short), typeof(ushort), typeof(int), typeof(uint), }; foreach (Type t in integralTypes) { DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(template.Replace("System.Int32", t.ToString()), new ErrorDescription { Code = (int)ErrorCode.ERR_ConstOutOfRangeChecked, Line = 6, Column = 34 }, new ErrorDescription { Code = (int)ErrorCode.ERR_ConstOutOfRangeChecked, Line = 8, Column = 34 }); } } // Note that the errors for Int64 and UInt64 are not // exactly the same as for Int32, etc. above, but the // differences match the native compiler. [WorkItem(528715, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528715")] [Fact] public void CS0221ERR_ConstOutOfRangeChecked05() { // Confirm that we truncate the constant value before performing the range check var text1 = @"public class C { void M() { System.Console.WriteLine((System.Int64)(System.Int64.MinValue - 0.9)); System.Console.WriteLine((System.Int64)(System.Int64.MinValue - 1.0)); System.Console.WriteLine((System.Int64)(System.Int64.MaxValue + 0.9)); //CS0221 System.Console.WriteLine((System.Int64)(System.Int64.MaxValue + 1.0)); //CS0221 } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text1, new ErrorDescription { Code = (int)ErrorCode.ERR_ConstOutOfRangeChecked, Line = 7, Column = 34 }, new ErrorDescription { Code = (int)ErrorCode.ERR_ConstOutOfRangeChecked, Line = 8, Column = 34 }); var text2 = @"public class C { void M() { System.Console.WriteLine((System.UInt64)(System.UInt64.MinValue - 0.9)); System.Console.WriteLine((System.UInt64)(System.UInt64.MinValue - 1.0)); //CS0221 System.Console.WriteLine((System.UInt64)(System.UInt64.MaxValue + 0.9)); //CS0221 System.Console.WriteLine((System.UInt64)(System.UInt64.MaxValue + 1.0)); //CS0221 } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text2, new ErrorDescription { Code = (int)ErrorCode.ERR_ConstOutOfRangeChecked, Line = 6, Column = 34 }, new ErrorDescription { Code = (int)ErrorCode.ERR_ConstOutOfRangeChecked, Line = 7, Column = 34 }, new ErrorDescription { Code = (int)ErrorCode.ERR_ConstOutOfRangeChecked, Line = 8, Column = 34 }); var text3 = @"class C { static void Main() { System.Console.WriteLine(long.MinValue); System.Console.WriteLine((long)(double)long.MinValue); } }"; CreateCompilation(text3).VerifyDiagnostics(); } [Fact] public void CS0034ERR_AmbigBinaryOps() { #region "Source" var text = @" public class A { // allows for the conversion of A object to int public static implicit operator int(A s) { return 0; } public static implicit operator string(A i) { return null; } } public class B { public static implicit operator int(B s) // one way to resolve this CS0034 is to make one conversion explicit // public static explicit operator int (B s) { return 0; } public static implicit operator string(B i) { return null; } public static implicit operator B(string i) { return null; } public static implicit operator B(int i) { return null; } } public class C { public static void Main() { A a = new A(); B b = new B(); b = b + a; // CS0034 // another way to resolve this CS0034 is to make a cast // b = b + (int)a; } } "; #endregion CreateCompilation(text).VerifyDiagnostics( // (47,13): error CS0034: Operator '+' is ambiguous on operands of type 'B' and 'A' // b = b + a; // CS0034 Diagnostic(ErrorCode.ERR_AmbigBinaryOps, "b + a").WithArguments("+", "B", "A")); } [Fact] public void CS0035ERR_AmbigUnaryOp_RoslynCS0023() { var text = @" class MyClass { private int i; public MyClass(int i) { this.i = i; } public static implicit operator double(MyClass x) { return (double)x.i; } public static implicit operator decimal(MyClass x) { return (decimal)x.i; } } class MyClass2 { static void Main() { MyClass x = new MyClass(7); object o = -x; // CS0035 } }"; CreateCompilation(text).VerifyDiagnostics( // (27,20): error CS0035: Operator '-' is ambiguous on an operand of type 'MyClass' // object o = -x; // CS0035 Diagnostic(ErrorCode.ERR_AmbigUnaryOp, "-x").WithArguments("-", "MyClass")); } [Fact] public void CS0037ERR_ValueCantBeNull01() { var source = @"enum E { } struct S { } class C { static void M() { int i; i = null; i = (int)null; E e; e = null; e = (E)null; S s; s = null; s = (S)null; X x; x = null; x = (X)null; } }"; CreateCompilation(source).VerifyDiagnostics( // (8,13): error CS0037: Cannot convert null to 'int' because it is a non-nullable value type Diagnostic(ErrorCode.ERR_ValueCantBeNull, "null").WithArguments("int").WithLocation(8, 13), // (9,13): error CS0037: Cannot convert null to 'int' because it is a non-nullable value type Diagnostic(ErrorCode.ERR_ValueCantBeNull, "(int)null").WithArguments("int").WithLocation(9, 13), // (11,13): error CS0037: Cannot convert null to 'E' because it is a non-nullable value type Diagnostic(ErrorCode.ERR_ValueCantBeNull, "null").WithArguments("E").WithLocation(11, 13), // (12,13): error CS0037: Cannot convert null to 'E' because it is a non-nullable value type Diagnostic(ErrorCode.ERR_ValueCantBeNull, "(E)null").WithArguments("E").WithLocation(12, 13), // (14,13): error CS0037: Cannot convert null to 'S' because it is a non-nullable value type Diagnostic(ErrorCode.ERR_ValueCantBeNull, "null").WithArguments("S").WithLocation(14, 13), // (15,13): error CS0037: Cannot convert null to 'S' because it is a non-nullable value type Diagnostic(ErrorCode.ERR_ValueCantBeNull, "(S)null").WithArguments("S").WithLocation(15, 13), // (16,9): error CS0246: The type or namespace name 'X' could not be found (are you missing a using directive or an assembly reference?) Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "X").WithArguments("X").WithLocation(16, 9), // (18,14): error CS0246: The type or namespace name 'X' could not be found (are you missing a using directive or an assembly reference?) Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "X").WithArguments("X").WithLocation(18, 14)); } [Fact] public void CS0037ERR_ValueCantBeNull02() { var source = @"interface I { } class A { } class B<T1, T2, T3, T4, T5, T6, T7> where T2 : class where T3 : struct where T4 : new() where T5 : I where T6 : A where T7 : T1 { static void M(object o) { o = (T1)null; o = (T2)null; o = (T3)null; o = (T4)null; o = (T5)null; o = (T6)null; o = (T7)null; } }"; CreateCompilation(source).VerifyDiagnostics( // (13,17): error CS0037: Cannot convert null to 'T1' because it is a non-nullable value type Diagnostic(ErrorCode.ERR_ValueCantBeNull, "(T1)null").WithArguments("T1").WithLocation(13, 13), // (15,17): error CS0037: Cannot convert null to 'T3' because it is a non-nullable value type Diagnostic(ErrorCode.ERR_ValueCantBeNull, "(T3)null").WithArguments("T3").WithLocation(15, 13), // (16,17): error CS0037: Cannot convert null to 'T4' because it is a non-nullable value type Diagnostic(ErrorCode.ERR_ValueCantBeNull, "(T4)null").WithArguments("T4").WithLocation(16, 13), // (17,17): error CS0037: Cannot convert null to 'T5' because it is a non-nullable value type Diagnostic(ErrorCode.ERR_ValueCantBeNull, "(T5)null").WithArguments("T5").WithLocation(17, 13), // (19,17): error CS0037: Cannot convert null to 'T7' because it is a non-nullable value type Diagnostic(ErrorCode.ERR_ValueCantBeNull, "(T7)null").WithArguments("T7").WithLocation(19, 13)); } [WorkItem(539589, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539589")] [Fact] public void CS0037ERR_ValueCantBeNull03() { var text = @" class Program { enum MyEnum { Zero = 0, One = 1 } static int Main() { return Goo((MyEnum)null); } static int Goo(MyEnum x) { return 1; } } "; CreateCompilation(text).VerifyDiagnostics(Diagnostic(ErrorCode.ERR_ValueCantBeNull, "(MyEnum)null").WithArguments("Program.MyEnum").WithLocation(12, 20)); } [Fact(), WorkItem(528875, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528875")] public void CS0038ERR_WrongNestedThis() { var text = @" class OuterClass { public int count; // try the following line instead // public static int count; class InnerClass { void func() { // or, create an instance // OuterClass class_inst = new OuterClass(); // int count2 = class_inst.count; int count2 = count; // CS0038 } } public static void Main() { } }"; // Triage decided not to implement the more specific error (WrongNestedThis) and stick with ObjectRequired. var comp = CreateCompilation(text, options: TestOptions.ReleaseDll.WithSpecificDiagnosticOptions(new Dictionary<string, ReportDiagnostic>() { { MessageProvider.Instance.GetIdForErrorCode(649), ReportDiagnostic.Suppress } })); comp.VerifyDiagnostics(Diagnostic(ErrorCode.ERR_ObjectRequired, "count").WithArguments("OuterClass.count")); } [Fact] public void CS0039ERR_NoExplicitBuiltinConv01() { var text = @"class A { } class B: A { } class C: A { } class M { static void Main() { A a = new C(); B b = new B(); C c; // This is valid; there is a built-in reference // conversion from A to C. c = a as C; //The following generates CS0039; there is no // built-in reference conversion from B to C. c = b as C; // CS0039 } }"; CreateCompilation(text).VerifyDiagnostics( // (24,13): error CS0039: Cannot convert type 'B' to 'C' via a reference conversion, boxing conversion, unboxing conversion, wrapping conversion, or null type conversion Diagnostic(ErrorCode.ERR_NoExplicitBuiltinConv, "b as C").WithArguments("B", "C").WithLocation(24, 13)); } [Fact, WorkItem(541142, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541142")] public void CS0039ERR_NoExplicitBuiltinConv02() { var text = @"delegate void D(); class C { static void M(C c) { (F as D)(); (c.F as D)(); (G as D)(); } void F() { } static void G() { } }"; CreateCompilation(text).VerifyDiagnostics( // (6,10): 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(6, 10), // (7,10): 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(7, 10), // (8,10): 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(8, 10)); } [Fact, WorkItem(542047, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542047")] public void CS0039ERR_ConvTypeReferenceToObject() { var text = @"using System; class C { static void Main() { TypedReference a = new TypedReference(); object obj = a as object; //CS0039 } } "; CreateCompilation(text).VerifyDiagnostics( //(7,22): error CS0039: Cannot convert type 'System.TypedReference' to 'object' via a reference conversion, boxing conversion, unboxing conversion, wrapping conversion, or null type conversion Diagnostic(ErrorCode.ERR_NoExplicitBuiltinConv, "a as object").WithArguments("System.TypedReference", "object").WithLocation(7, 22)); } [Fact] public void CS0069ERR_EventPropertyInInterface() { var text = @" interface I { event System.Action E1 { add; } event System.Action E2 { remove; } event System.Action E3 { add; remove; } } "; CreateCompilation(text, parseOptions: TestOptions.Regular7, targetFramework: TargetFramework.NetCoreApp).VerifyDiagnostics( // (4,30): error CS8652: The feature 'default interface implementation' is not available in C# 7.0. Please use language version 8.0 or greater. // event System.Action E1 { add; } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "add").WithArguments("default interface implementation", "8.0").WithLocation(4, 30), // (4,33): error CS0073: An add or remove accessor must have a body // event System.Action E1 { add; } Diagnostic(ErrorCode.ERR_AddRemoveMustHaveBody, ";").WithLocation(4, 33), // (5,30): error CS8652: The feature 'default interface implementation' is not available in C# 7.0. Please use language version 8.0 or greater. // event System.Action E2 { remove; } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "remove").WithArguments("default interface implementation", "8.0").WithLocation(5, 30), // (5,36): error CS0073: An add or remove accessor must have a body // event System.Action E2 { remove; } Diagnostic(ErrorCode.ERR_AddRemoveMustHaveBody, ";").WithLocation(5, 36), // (6,30): error CS8652: The feature 'default interface implementation' is not available in C# 7.0. Please use language version 8.0 or greater. // event System.Action E3 { add; remove; } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "add").WithArguments("default interface implementation", "8.0").WithLocation(6, 30), // (6,33): error CS0073: An add or remove accessor must have a body // event System.Action E3 { add; remove; } Diagnostic(ErrorCode.ERR_AddRemoveMustHaveBody, ";").WithLocation(6, 33), // (6,35): error CS8652: The feature 'default interface implementation' is not available in C# 7.0. Please use language version 8.0 or greater. // event System.Action E3 { add; remove; } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "remove").WithArguments("default interface implementation", "8.0").WithLocation(6, 35), // (6,41): error CS0073: An add or remove accessor must have a body // event System.Action E3 { add; remove; } Diagnostic(ErrorCode.ERR_AddRemoveMustHaveBody, ";").WithLocation(6, 41), // (4,25): error CS0065: 'I.E1': event property must have both add and remove accessors // event System.Action E1 { add; } Diagnostic(ErrorCode.ERR_EventNeedsBothAccessors, "E1").WithArguments("I.E1").WithLocation(4, 25), // (5,25): error CS0065: 'I.E2': event property must have both add and remove accessors // event System.Action E2 { remove; } Diagnostic(ErrorCode.ERR_EventNeedsBothAccessors, "E2").WithArguments("I.E2").WithLocation(5, 25)); } [Fact] public void CS0070ERR_BadEventUsage() { var text = @" public delegate void EventHandler(); public class A { public event EventHandler Click; public static void OnClick() { EventHandler eh; A a = new A(); eh = a.Click; } public static void Main() { } } public class B { public int mf () { EventHandler eh = new EventHandler(A.OnClick); A a = new A(); eh = a.Click; // CS0070 // try the following line instead // a.Click += eh; return 1; } }"; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_BadEventUsage, Line = 26, Column = 14 } }); } [Fact] public void CS0079ERR_BadEventUsageNoField() { var text = @" public delegate void MyEventHandler(); public class Class1 { private MyEventHandler _e; public event MyEventHandler Pow { add { _e += value; } remove { _e -= value; } } public void Handler() { } public void Fire() { if (_e != null) { Pow(); // CS0079 // try the following line instead // _e(); } } public static void Main() { Class1 p = new Class1(); p.Pow += new MyEventHandler(p.Handler); p._e(); p.Pow += new MyEventHandler(p.Handler); p._e(); p._e -= new MyEventHandler(p.Handler); if (p._e != null) { p._e(); } p.Pow -= new MyEventHandler(p.Handler); if (p._e != null) { p._e(); } } }"; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_BadEventUsageNoField, Line = 28, Column = 13 } }); } [WorkItem(538213, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538213")] [Fact] public void CS0103ERR_NameNotInContext() { var text = @" class C { static void M() { IO.File.Exists(""test""); } } "; CreateCompilation(text).VerifyDiagnostics( Diagnostic(ErrorCode.ERR_NameNotInContext, "IO").WithArguments("IO").WithLocation(6, 9)); } [WorkItem(542574, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542574")] [Fact] public void CS0103ERR_NameNotInContextLambdaExtension() { var text = @"using System.Linq; class Test { static void Main() { int[] sourceA = { 1, 2, 3, 4, 5 }; int[] sourceB = { 3, 4, 5, 6, 7 }; var query = sourceA.Join(sourceB, a => b, b => 5, (a, b) => a + b); } }"; CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics( Diagnostic(ErrorCode.ERR_NameNotInContext, "b").WithArguments("b").WithLocation(9, 48)); } [Fact()] public void CS0103ERR_NameNotInContext_foreach() { var text = @"class C { static void Main() { foreach (var y in new[] {new {y = y }}){ } } } "; CreateCompilation(text).VerifyDiagnostics( Diagnostic(ErrorCode.ERR_NameNotInContext, "y").WithArguments("y").WithLocation(5, 43)); } [WorkItem(528780, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528780")] [Fact] public void CS0103ERR_NameNotInContext_namedAndOptional() { var text = @"using System; class NamedExample { static void Main(string[] args) { } static int CalculateBMI(int weight, int height = weight) { return (weight * 703) / (height * height); } } "; CreateCompilation(text).VerifyDiagnostics( // (7,54): error CS0103: The name 'weight' does not exist in the current context // static int CalculateBMI(int weight, int height = weight) Diagnostic(ErrorCode.ERR_NameNotInContext, "weight").WithArguments("weight").WithLocation(7, 54), // (1,1): hidden CS8019: Unnecessary using directive. // using System; Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using System;").WithLocation(1, 1) ); } [Fact] public void CS0118ERR_BadSKknown() { CreateCompilation( @"public class TestType {} public class MyClass { public static int Main() { TestType myTest = new TestType(); bool b = myTest is myTest; return 1; } }", parseOptions: TestOptions.Regular6) .VerifyDiagnostics( // (7,22): error CS0118: 'myTest' is a 'variable' but is used like a 'type' Diagnostic(ErrorCode.ERR_BadSKknown, "myTest").WithArguments("myTest", "variable", "type")); } [Fact] public void CS0118ERR_BadSKknown_02() { CreateCompilation(@" using System; public class P { public static void Main(string[] args) { #pragma warning disable 219 Action<args> a = null; Action<a> b = null; } }") .VerifyDiagnostics( // (6,16): error CS0118: 'args' is a variable but is used like a type // Action<args> a = null; Diagnostic(ErrorCode.ERR_BadSKknown, "args").WithArguments("args", "variable", "type").WithLocation(6, 16), // (7,16): error CS0118: 'a' is a variable but is used like a type // Action<a> b = null; Diagnostic(ErrorCode.ERR_BadSKknown, "a").WithArguments("a", "variable", "type").WithLocation(7, 16)); } [Fact] public void CS0118ERR_BadSKknown_CheckedUnchecked() { string source = @" using System; class Program { static void Main() { var z = 1; (Console).WriteLine(); // error (System).Console.WriteLine(); // error checked(Console).WriteLine(); // error checked(System).Console.WriteLine(); // error checked(z).ToString(); // ok checked(typeof(Console)).ToString(); // ok checked(Console.WriteLine)(); // ok checked(z) = 1; // ok } } "; CreateCompilation(source).VerifyDiagnostics( // (10,4): error CS0119: 'System.Console' is a type, which is not valid in the given context Diagnostic(ErrorCode.ERR_BadSKunknown, "Console").WithArguments("System.Console", "type"), // (11,10): error CS0118: 'System' is a namespace but is used like a variable Diagnostic(ErrorCode.ERR_BadSKknown, "System").WithArguments("System", "namespace", "variable"), // (12,17): error CS0119: 'System.Console' is a type, which is not valid in the given context Diagnostic(ErrorCode.ERR_BadSKunknown, "Console").WithArguments("System.Console", "type"), // (13,17): error CS0118: 'System' is a namespace but is used like a variable Diagnostic(ErrorCode.ERR_BadSKknown, "System").WithArguments("System", "namespace", "variable")); } [WorkItem(542773, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542773")] [Fact] public void CS0119ERR_BadSKunknown01_switch() { CreateCompilation( @"class A { public static void Main() { } void goo(color color1) { switch (color) { default: break; } } } enum color { blue, green } ") .VerifyDiagnostics(Diagnostic(ErrorCode.ERR_BadSKunknown, "color").WithArguments("color", "type")); } [Fact, WorkItem(538214, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538214"), WorkItem(528703, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528703")] public void CS0119ERR_BadSKunknown01() { var source = @"class Test { public static void M() { int x = 0; x = (global::System.Int32) + x; } }"; CreateCompilation(source).VerifyDiagnostics( // (6,14): error CS0119: 'int' is a type, which is not valid in the given context // x = (global::System.Int32) + x; Diagnostic(ErrorCode.ERR_BadSKunknown, "global::System.Int32").WithArguments("int", "type"), // (6,14): error CS0119: 'int' is a type, which is not valid in the given context // x = (global::System.Int32) + x; Diagnostic(ErrorCode.ERR_BadSKunknown, "global::System.Int32").WithArguments("int", "type")); } [Fact] public void CS0119ERR_BadSKunknown02() { var source = @"class A { internal static object F; internal static void M() { } } class B<T, U> where T : A { static void M(T t) { U.ReferenceEquals(T.F, null); T.M(); } }"; CreateCompilation(source).VerifyDiagnostics( // (10,27): error CS0119: 'T' is a type parameter, which is not valid in the given context // U.ReferenceEquals(T.F, null); Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter"), // (10,9): error CS0119: 'U' is a type parameter, which is not valid in the given context // U.ReferenceEquals(T.F, null); Diagnostic(ErrorCode.ERR_BadSKunknown, "U").WithArguments("U", "type parameter"), // (11,9): error CS0119: 'T' is a type parameter, which is not valid in the given context // T.M(); Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter"), // (3,28): warning CS0649: Field 'A.F' is never assigned to, and will always have its default value null // internal static object F; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "F").WithArguments("A.F", "null") ); } [WorkItem(541203, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541203")] [Fact] public void CS0119ERR_BadSKunknown_InThrowStmt() { CreateCompilation( @"class Test { public static void M() { throw System.Exception; } }") .VerifyDiagnostics( Diagnostic(ErrorCode.ERR_BadSKunknown, "System.Exception").WithArguments("System.Exception", "type")); } [Fact] public void CS0110ERR_CircConstValue01() { var source = @"namespace x { public class C { const int x = 1; const int a = x + b; const int b = x + c; const int c = x + d; const int d = x + e; const int e = x + a; } }"; CreateCompilation(source).VerifyDiagnostics( // (7,19): error CS0110: The evaluation of the constant value for 'x.C.a' involves a circular definition // const int a = x + b; Diagnostic(ErrorCode.ERR_CircConstValue, "a").WithArguments("x.C.a").WithLocation(7, 19)); } [Fact] public void CS0110ERR_CircConstValue02() { var source = @"enum E { A = B, B = A } enum F { X, Y = Y } "; CreateCompilation(source).VerifyDiagnostics( // (1,10): error CS0110: The evaluation of the constant value for 'E.A' involves a circular definition // enum E { A = B, B = A } Diagnostic(ErrorCode.ERR_CircConstValue, "A").WithArguments("E.A").WithLocation(1, 10), // (2,13): error CS0110: The evaluation of the constant value for 'F.Y' involves a circular definition // enum F { X, Y = Y } Diagnostic(ErrorCode.ERR_CircConstValue, "Y").WithArguments("F.Y").WithLocation(2, 13)); } [Fact] public void CS0110ERR_CircConstValue03() { var source = @"enum E { A, B = A } // no error enum F { W, X = Z, Y, Z } "; CreateCompilation(source).VerifyDiagnostics( // (2,13): error CS0110: The evaluation of the constant value for 'F.X' involves a circular definition // enum F { W, X = Z, Y, Z } Diagnostic(ErrorCode.ERR_CircConstValue, "X").WithArguments("F.X").WithLocation(2, 13)); } [Fact] public void CS0110ERR_CircConstValue04() { var source = @"enum E { A = B, B } "; CreateCompilation(source).VerifyDiagnostics( // (1,10): error CS0110: The evaluation of the constant value for 'E.A' involves a circular definition // enum E { A = B, B } Diagnostic(ErrorCode.ERR_CircConstValue, "A").WithArguments("E.A").WithLocation(1, 10)); } [Fact] public void CS0110ERR_CircConstValue05() { var source = @"enum E { A = C, B = C, C } "; CreateCompilation(source).VerifyDiagnostics( // (1,17): error CS0110: The evaluation of the constant value for 'E.B' involves a circular definition // enum E { A = C, B = C, C } Diagnostic(ErrorCode.ERR_CircConstValue, "B").WithArguments("E.B").WithLocation(1, 17)); } [Fact] public void CS0110ERR_CircConstValue06() { var source = @"class C { private const int F = (int)E.B; enum E { A = F, B } } "; CreateCompilation(source).VerifyDiagnostics( // (3,23): error CS0110: The evaluation of the constant value for 'C.F' involves a circular definition // private const int F = (int)E.B; Diagnostic(ErrorCode.ERR_CircConstValue, "F").WithArguments("C.F").WithLocation(3, 23)); } [Fact] public void CS0110ERR_CircConstValue07() { // Should report errors from other subexpressions // in addition to circular reference. var source = @"class C { const int F = (long)(F + F + G); } "; CreateCompilation(source).VerifyDiagnostics( // (3,34): error CS0103: The name 'G' does not exist in the current context // const int F = (long)(F + F + G); Diagnostic(ErrorCode.ERR_NameNotInContext, "G").WithArguments("G").WithLocation(3, 34), // (3,15): error CS0110: The evaluation of the constant value for 'C.F' involves a circular definition // const int F = (long)(F + F + G); Diagnostic(ErrorCode.ERR_CircConstValue, "F").WithArguments("C.F").WithLocation(3, 15)); } [Fact] public void CS0110ERR_CircConstValue08() { // Decimal constants are special (since they're not runtime constants). var source = @"class C { const decimal D = D; } "; CreateCompilation(source).VerifyDiagnostics( // (3,19): error CS0110: The evaluation of the constant value for 'C.D' involves a circular definition // const decimal D = D; Diagnostic(ErrorCode.ERR_CircConstValue, "D").WithArguments("C.D").WithLocation(3, 19)); } [Fact] public void CS0116ERR_NamespaceUnexpected_1() { var test = @" int x; "; CreateCompilation(test, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9).VerifyDiagnostics( // (2,5): warning CS0168: The variable 'x' is declared but never used // int x; Diagnostic(ErrorCode.WRN_UnreferencedVar, "x").WithArguments("x").WithLocation(2, 5) ); } [Fact] public void CS0116ERR_NamespaceUnexpected_2() { var test = @" namespace x { using System; void Method(string str) // CS0116 { Console.WriteLine(str); } } int AIProp { get ; set ; } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(test, new ErrorDescription { Code = (int)ErrorCode.ERR_NamespaceUnexpected, Line = 5, Column = 10 }, new ErrorDescription { Code = (int)ErrorCode.ERR_NamespaceUnexpected, Line = 10, Column = 5 }); } [Fact] public void CS0116ERR_NamespaceUnexpected_3() { var test = @" namespace ns1 { goto Labl; // Invalid const int x = 1; Lab1: const int y = 2; } "; // TODO (tomat): EOFUnexpected shouldn't be reported if we enable parsing global statements in namespaces DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(test, // (4,5): error CS1022: Type or namespace definition, or end-of-file expected // (4,10): error CS0116: A namespace does not directly contain members such as fields or methods // (4,14): error CS1022: Type or namespace definition, or end-of-file expected // (6,5): error CS0116: A namespace does not directly contain members such as fields or methods // (6,9): error CS1022: Type or namespace definition, or end-of-file expected // (5,15): error CS0116: A namespace does not directly contain members such as fields or methods // (7,15): error CS0116: A namespace does not directly contain members such as fields or methods new ErrorDescription { Code = (int)ErrorCode.ERR_EOFExpected, Line = 4, Column = 5 }, new ErrorDescription { Code = (int)ErrorCode.ERR_NamespaceUnexpected, Line = 4, Column = 10 }, new ErrorDescription { Code = (int)ErrorCode.ERR_EOFExpected, Line = 4, Column = 14 }, new ErrorDescription { Code = (int)ErrorCode.ERR_NamespaceUnexpected, Line = 6, Column = 5 }, new ErrorDescription { Code = (int)ErrorCode.ERR_EOFExpected, Line = 6, Column = 9 }, new ErrorDescription { Code = (int)ErrorCode.ERR_NamespaceUnexpected, Line = 5, Column = 15 }, new ErrorDescription { Code = (int)ErrorCode.ERR_NamespaceUnexpected, Line = 7, Column = 15 }); } [WorkItem(540091, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540091")] [Fact] public void CS0116ERR_NamespaceUnexpected_4() { var test = @" delegate int D(); D d = null; "; CreateCompilation(test, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9).VerifyDiagnostics( // (3,1): error CS8803: Top-level statements must precede namespace and type declarations. // D d = null; Diagnostic(ErrorCode.ERR_TopLevelStatementAfterNamespaceOrType, "D d = null;").WithLocation(3, 1), // (3,3): warning CS0219: The variable 'd' is assigned but its value is never used // D d = null; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "d").WithArguments("d").WithLocation(3, 3) ); } [WorkItem(540091, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540091")] [Fact] public void CS0116ERR_NamespaceUnexpected_5() { var test = @" delegate int D(); D d = {;} "; // In this case, CS0116 is suppressed because of the syntax errors CreateCompilation(test, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9).VerifyDiagnostics( // (3,1): error CS8803: Top-level statements must precede namespace and type declarations. // D d = {;} Diagnostic(ErrorCode.ERR_TopLevelStatementAfterNamespaceOrType, "D d = {;").WithLocation(3, 1), // (3,8): error CS1513: } expected Diagnostic(ErrorCode.ERR_RbraceExpected, ";"), // (3,9): error CS1022: Type or namespace definition, or end-of-file expected Diagnostic(ErrorCode.ERR_EOFExpected, "}"), // (3,7): error CS0622: Can only use array initializer expressions to assign to array types. Try using a new expression instead. Diagnostic(ErrorCode.ERR_ArrayInitToNonArrayType, "{")); } [WorkItem(539129, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539129")] [Fact] public void CS0117ERR_NoSuchMember() { CreateCompilation( @"enum E { } class C { static void M() { C.F(E.A); C.P = C.Q; } }") .VerifyDiagnostics( Diagnostic(ErrorCode.ERR_NoSuchMember, "F").WithArguments("C", "F"), Diagnostic(ErrorCode.ERR_NoSuchMember, "A").WithArguments("E", "A"), Diagnostic(ErrorCode.ERR_NoSuchMember, "P").WithArguments("C", "P"), Diagnostic(ErrorCode.ERR_NoSuchMember, "Q").WithArguments("C", "Q")); } [Fact] public void CS0120ERR_ObjectRequired01() { CreateCompilation( @"class C { object field; object Property { get; set; } void Method() { } static void M() { field = Property; C.field = C.Property; Method(); C.Method(); } } ") .VerifyDiagnostics( // (8,9): error CS0120: An object reference is required for the non-static field, method, or property 'C.field' // field = Property; Diagnostic(ErrorCode.ERR_ObjectRequired, "field").WithArguments("C.field").WithLocation(8, 9), // (8,17): error CS0120: An object reference is required for the non-static field, method, or property 'C.Property' // field = Property; Diagnostic(ErrorCode.ERR_ObjectRequired, "Property").WithArguments("C.Property").WithLocation(8, 17), // (9,9): error CS0120: An object reference is required for the non-static field, method, or property 'C.field' // C.field = C.Property; Diagnostic(ErrorCode.ERR_ObjectRequired, "C.field").WithArguments("C.field").WithLocation(9, 9), // (9,19): error CS0120: An object reference is required for the non-static field, method, or property 'C.Property' // C.field = C.Property; Diagnostic(ErrorCode.ERR_ObjectRequired, "C.Property").WithArguments("C.Property").WithLocation(9, 19), // (10,9): error CS0120: An object reference is required for the non-static field, method, or property 'C.Method()' // Method(); Diagnostic(ErrorCode.ERR_ObjectRequired, "Method").WithArguments("C.Method()").WithLocation(10, 9), // (11,9): error CS0120: An object reference is required for the non-static field, method, or property 'C.Method()' // C.Method(); Diagnostic(ErrorCode.ERR_ObjectRequired, "C.Method").WithArguments("C.Method()").WithLocation(11, 9)); } [Fact] public void CS0120ERR_ObjectRequired02() { CreateCompilation( @"using System; class Program { private readonly int v = 5; delegate int del(int i); static void Main(string[] args) { del myDelegate = (int x) => x * v; Console.Write(string.Concat(myDelegate(7), ""he"")); } }") .VerifyDiagnostics( // (9,41): error CS0120: An object reference is required for the non-static field, method, or property 'C.field' Diagnostic(ErrorCode.ERR_ObjectRequired, "v").WithArguments("Program.v")); } [Fact] public void CS0120ERR_ObjectRequired03() { var source = @"delegate int boo(); interface I { int bar(); } public struct abc : I { public int bar() { System.Console.WriteLine(""bar""); return 0x01; } } class C { static void Main(string[] args) { abc p = new abc(); boo goo = null; goo += new boo(I.bar); goo(); } }"; CreateCompilation(source, parseOptions: TestOptions.Regular7).VerifyDiagnostics( // (16,24): error CS0120: An object reference is required for the non-static field, method, or property 'I.bar()' // goo += new boo(I.bar); Diagnostic(ErrorCode.ERR_ObjectRequired, "I.bar").WithArguments("I.bar()"), // (14,13): warning CS0219: The variable 'p' is assigned but its value is never used // abc p = new abc(); Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "p").WithArguments("p") ); CreateCompilation(source, parseOptions: TestOptions.Regular).VerifyDiagnostics( // (16,24): error CS0120: An object reference is required for the non-static field, method, or property 'I.bar()' // goo += new boo(I.bar); Diagnostic(ErrorCode.ERR_ObjectRequired, "I.bar").WithArguments("I.bar()").WithLocation(16, 24), // (14,13): warning CS0219: The variable 'p' is assigned but its value is never used // abc p = new abc(); Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "p").WithArguments("p").WithLocation(14, 13) ); } [WorkItem(543950, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543950")] [Fact] public void CS0120ERR_ObjectRequired04() { CreateCompilation( @"using System; class Program { static void Main(string[] args) { var f = new Func<string>(() => ToString()); var g = new Func<int>(() => GetHashCode()); } }") .VerifyDiagnostics( // (7,40): error CS0120: An object reference is required for the non-static field, method, or property 'object.ToString()' // var f = new Func<string>(() => ToString()); Diagnostic(ErrorCode.ERR_ObjectRequired, "ToString").WithArguments("object.ToString()"), // (8,37): error CS0120: An object reference is required for the non-static field, method, or property 'object.GetHashCode()' // var g = new Func<int>(() => GetHashCode()); Diagnostic(ErrorCode.ERR_ObjectRequired, "GetHashCode").WithArguments("object.GetHashCode()") ); } [Fact] public void CS0120ERR_ObjectRequired_ConstructorInitializer() { CreateCompilation( @"class B { public B(params int[] p) { } } class C : B { int instanceField; static int staticField; int InstanceProperty { get; set; } static int StaticProperty { get; set; } int InstanceMethod() { return 0; } static int StaticMethod() { return 0; } C(int param) : base( param, instanceField, //CS0120 staticField, InstanceProperty, //CS0120 StaticProperty, InstanceMethod(), //CS0120 StaticMethod(), this.instanceField, //CS0027 C.staticField, this.InstanceProperty, //CS0027 C.StaticProperty, this.InstanceMethod(), //CS0027 C.StaticMethod()) { } } ") .VerifyDiagnostics( // (19,9): error CS0120: An object reference is required for the non-static field, method, or property 'C.instanceField' // instanceField, //CS0120 Diagnostic(ErrorCode.ERR_ObjectRequired, "instanceField").WithArguments("C.instanceField").WithLocation(19, 9), // (21,9): error CS0120: An object reference is required for the non-static field, method, or property 'C.InstanceProperty' // InstanceProperty, //CS0120 Diagnostic(ErrorCode.ERR_ObjectRequired, "InstanceProperty").WithArguments("C.InstanceProperty").WithLocation(21, 9), // (23,9): error CS0120: An object reference is required for the non-static field, method, or property 'C.InstanceMethod()' // InstanceMethod(), //CS0120 Diagnostic(ErrorCode.ERR_ObjectRequired, "InstanceMethod").WithArguments("C.InstanceMethod()").WithLocation(23, 9), // (25,9): error CS0027: Keyword 'this' is not available in the current context // this.instanceField, //CS0027 Diagnostic(ErrorCode.ERR_ThisInBadContext, "this").WithLocation(25, 9), // (27,9): error CS0027: Keyword 'this' is not available in the current context // this.InstanceProperty, //CS0027 Diagnostic(ErrorCode.ERR_ThisInBadContext, "this").WithLocation(27, 9), // (29,9): error CS0027: Keyword 'this' is not available in the current context // this.InstanceMethod(), //CS0027 Diagnostic(ErrorCode.ERR_ThisInBadContext, "this").WithLocation(29, 9), // (8,9): warning CS0649: Field 'C.instanceField' is never assigned to, and will always have its default value 0 // int instanceField; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "instanceField").WithArguments("C.instanceField", "0").WithLocation(8, 9), // (9,16): warning CS0649: Field 'C.staticField' is never assigned to, and will always have its default value 0 // static int staticField; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "staticField").WithArguments("C.staticField", "0").WithLocation(9, 16)); } [Fact] public void CS0120ERR_ObjectRequired_StaticConstructor() { CreateCompilation( @"class C { object field; object Property { get; set; } void Method() { } static C() { field = Property; C.field = C.Property; Method(); C.Method(); } } ") .VerifyDiagnostics( // (8,9): error CS0120: An object reference is required for the non-static field, method, or property 'C.field' // field = Property; Diagnostic(ErrorCode.ERR_ObjectRequired, "field").WithArguments("C.field").WithLocation(8, 9), // (8,17): error CS0120: An object reference is required for the non-static field, method, or property 'C.Property' // field = Property; Diagnostic(ErrorCode.ERR_ObjectRequired, "Property").WithArguments("C.Property").WithLocation(8, 17), // (9,9): error CS0120: An object reference is required for the non-static field, method, or property 'C.field' // C.field = C.Property; Diagnostic(ErrorCode.ERR_ObjectRequired, "C.field").WithArguments("C.field").WithLocation(9, 9), // (9,19): error CS0120: An object reference is required for the non-static field, method, or property 'C.Property' // C.field = C.Property; Diagnostic(ErrorCode.ERR_ObjectRequired, "C.Property").WithArguments("C.Property").WithLocation(9, 19), // (10,9): error CS0120: An object reference is required for the non-static field, method, or property 'C.Method()' // Method(); Diagnostic(ErrorCode.ERR_ObjectRequired, "Method").WithArguments("C.Method()").WithLocation(10, 9), // (11,9): error CS0120: An object reference is required for the non-static field, method, or property 'C.Method()' // C.Method(); Diagnostic(ErrorCode.ERR_ObjectRequired, "C.Method").WithArguments("C.Method()").WithLocation(11, 9)); } [Fact] public void CS0120ERR_ObjectRequired_NestedClass() { CreateCompilation( @" class C { object field; object Property { get; set; } void Method() { } class D { object field2; object Property2 { get; set; } public void Goo() { object f = field; object p = Property; Method(); } public static void Bar() { object f1 = field; object p1 = Property; Method(); object f2 = field2; object p2 = Property2; Goo(); } } class E : C { public void Goo() { object f3 = field; object p3 = Property; Method(); } } }") .VerifyDiagnostics( // (15,24): error CS0120: An object reference is required for the non-static field, method, or property 'C.field' // object f = field; Diagnostic(ErrorCode.ERR_ObjectRequired, "field").WithArguments("C.field"), // (16,24): error CS0120: An object reference is required for the non-static field, method, or property 'C.Property' // object p = Property; Diagnostic(ErrorCode.ERR_ObjectRequired, "Property").WithArguments("C.Property"), // (17,13): error CS0120: An object reference is required for the non-static field, method, or property 'C.Method()' // Method(); Diagnostic(ErrorCode.ERR_ObjectRequired, "Method").WithArguments("C.Method()"), // (22,25): error CS0120: An object reference is required for the non-static field, method, or property 'C.field' // object f1 = field; Diagnostic(ErrorCode.ERR_ObjectRequired, "field").WithArguments("C.field"), // (23,25): error CS0120: An object reference is required for the non-static field, method, or property 'C.Property' // object p1 = Property; Diagnostic(ErrorCode.ERR_ObjectRequired, "Property").WithArguments("C.Property"), // (24,13): error CS0120: An object reference is required for the non-static field, method, or property 'C.Method()' // Method(); Diagnostic(ErrorCode.ERR_ObjectRequired, "Method").WithArguments("C.Method()"), // (26,25): error CS0120: An object reference is required for the non-static field, method, or property 'C.D.field2' // object f2 = field2; Diagnostic(ErrorCode.ERR_ObjectRequired, "field2").WithArguments("C.D.field2"), // (27,25): error CS0120: An object reference is required for the non-static field, method, or property 'C.D.Property2' // object p2 = Property2; Diagnostic(ErrorCode.ERR_ObjectRequired, "Property2").WithArguments("C.D.Property2"), // (28,13): error CS0120: An object reference is required for the non-static field, method, or property 'C.D.Goo()' // Goo(); Diagnostic(ErrorCode.ERR_ObjectRequired, "Goo").WithArguments("C.D.Goo()"), // (4,12): warning CS0649: Field 'C.field' is never assigned to, and will always have its default value null // object field; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "field").WithArguments("C.field", "null"), // (10,16): warning CS0649: Field 'C.D.field2' is never assigned to, and will always have its default value null // object field2; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "field2").WithArguments("C.D.field2", "null")); } [Fact, WorkItem(541505, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541505")] public void CS0120ERR_ObjectRequired_Attribute() { var text = @" using System.ComponentModel; enum ProtectionLevel { Privacy = 0 } class F { [DefaultValue(Prop.Privacy)] // CS0120 ProtectionLevel Prop { get { return 0; } } } "; CreateCompilation(text).VerifyDiagnostics( // (9,17): error CS0120: An object reference is required for the non-static field, method, or property 'F.Prop' // [DefaultValue(Prop.Privacy)] // CS0120 Diagnostic(ErrorCode.ERR_ObjectRequired, "Prop").WithArguments("F.Prop"), // (9,17): error CS0176: Member 'ProtectionLevel.Privacy' cannot be accessed with an instance reference; qualify it with a type name instead // [DefaultValue(Prop.Privacy)] // CS0120 Diagnostic(ErrorCode.ERR_ObjectProhibited, "Prop.Privacy").WithArguments("ProtectionLevel.Privacy") // Extra In Roslyn ); } [Fact] public void CS0121ERR_AmbigCall() { var text = @" public class C { void f(int i, double d) { } void f(double d, int i) { } public static void Main() { new C().f(1, 1); // CS0121 } }"; CreateCompilation(text).VerifyDiagnostics( // (9,9): error CS0121: The call is ambiguous between the following methods or properties: 'C.f(int, double)' and 'C.f(double, int)' // new C().f(1, 1); // CS0121 Diagnostic(ErrorCode.ERR_AmbigCall, "f").WithArguments("C.f(int, double)", "C.f(double, int)") ); } [WorkItem(539817, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539817")] [Fact] public void CS0122ERR_BadAccess() { var text = @" class Base { private class P { int X; } } class Test : Base { void M() { object o = (P p) => 0; int x = P.X; int y = (P)null; } } "; CreateCompilation(text).VerifyDiagnostics( // (11,21): error CS0122: 'Base.P' is inaccessible due to its protection level // object o = (P p) => 0; Diagnostic(ErrorCode.ERR_BadAccess, "P").WithArguments("Base.P"), // (11,20): error CS1660: Cannot convert lambda expression to type 'object' because it is not a delegate type // object o = (P p) => 0; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "(P p) => 0").WithArguments("lambda expression", "object"), // (12,17): error CS0122: 'Base.P' is inaccessible due to its protection level // int x = P.X; Diagnostic(ErrorCode.ERR_BadAccess, "P").WithArguments("Base.P"), // (13,18): error CS0122: 'Base.P' is inaccessible due to its protection level // int y = (P)null; Diagnostic(ErrorCode.ERR_BadAccess, "P").WithArguments("Base.P"), // (4,27): warning CS0169: The field 'Base.P.X' is never used // private class P { int X; } Diagnostic(ErrorCode.WRN_UnreferencedField, "X").WithArguments("Base.P.X")); } [WorkItem(537683, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537683")] [Fact] public void CS0122ERR_BadAccess02() { var text = @"public class Outer { private class base1 { } } public class MyClass : Outer.base1 { } "; var comp = CreateCompilation(text); var type1 = comp.SourceModule.GlobalNamespace.GetMembers("MyClass").Single() as NamedTypeSymbol; var b = type1.BaseType(); var errs = comp.GetDiagnostics(); Assert.Equal(1, errs.Count()); Assert.Equal(122, errs.First().Code); } [WorkItem(539628, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539628")] [Fact] public void CS0122ERR_BadAccess03() { var text = @" class C1 { private C1() { } } class C2 { protected C2() { } private C2(short x) {} } class C3 : C2 { C3() : base(3) {} // CS0122 } class Test { public static int Main() { C1 c1 = new C1(); // CS0122 C2 c2 = new C2(); // CS0122 return 1; } } "; CreateCompilation(text).VerifyDiagnostics( // (14,12): error CS0122: 'C2.C2(short)' is inaccessible due to its protection level Diagnostic(ErrorCode.ERR_BadAccess, "base").WithArguments("C2.C2(short)"), // (21,21): error CS0122: 'C1.C1()' is inaccessible due to its protection level Diagnostic(ErrorCode.ERR_BadAccess, "C1").WithArguments("C1.C1()"), // (22,21): error CS0122: 'C2.C2()' is inaccessible due to its protection level Diagnostic(ErrorCode.ERR_BadAccess, "C2").WithArguments("C2.C2()")); } [WorkItem(539628, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539628")] [WorkItem(540336, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540336")] [Fact] public void CS0122ERR_BadAccess04() { var text = @" class A { protected class ProtectedClass { } public class B : I<ProtectedClass> { } } interface I<T> { } class Error { static void Goo<T>(I<T> i) { } static void Main() { Goo(new A.B()); } } "; var tree = Parse(text); var compilation = CreateCompilation(tree); var model = compilation.GetSemanticModel(tree); var compilationUnit = tree.GetCompilationUnitRoot(); var classError = (TypeDeclarationSyntax)compilationUnit.Members[2]; var mainMethod = (MethodDeclarationSyntax)classError.Members[1]; var callStmt = (ExpressionStatementSyntax)mainMethod.Body.Statements[0]; var callExpr = callStmt.Expression; var callPosition = callExpr.SpanStart; var boundCall = model.GetSpeculativeSymbolInfo(callPosition, callExpr, SpeculativeBindingOption.BindAsExpression); Assert.Null(boundCall.Symbol); Assert.Equal(1, boundCall.CandidateSymbols.Length); Assert.Equal(CandidateReason.OverloadResolutionFailure, boundCall.CandidateReason); var constructedMethodSymbol = (IMethodSymbol)(boundCall.CandidateSymbols[0]); Assert.Equal("void Error.Goo<A.ProtectedClass>(I<A.ProtectedClass> i)", constructedMethodSymbol.ToTestDisplayString()); var typeArgSymbol = constructedMethodSymbol.TypeArguments.Single(); Assert.Equal("A.ProtectedClass", typeArgSymbol.ToTestDisplayString()); Assert.False(model.IsAccessible(callPosition, typeArgSymbol), "Protected inner class is inaccessible"); var paramTypeSymbol = constructedMethodSymbol.Parameters.Single().Type; Assert.Equal("I<A.ProtectedClass>", paramTypeSymbol.ToTestDisplayString()); Assert.False(model.IsAccessible(callPosition, typeArgSymbol), "Type should be inaccessible since type argument is inaccessible"); // The original test attempted to verify that "Error.Goo<A.ProtectedClass>" is an // inaccessible method when inside Error.Main. The C# specification nowhere gives // a special rule for constructed generic methods; the accessibility domain of // a method depends only on its declared accessibility and the declared accessibility // of its containing type. // // We should decide whether the answer to "is this method accessible in Main?" is // yes or no, and if no, change the implementation of IsAccessible accordingly. // // Assert.False(model.IsAccessible(callPosition, constructedMethodSymbol), "Method should be inaccessible since parameter type is inaccessible"); compilation.VerifyDiagnostics( // (16,9): error CS0122: 'Error.Goo<A.ProtectedClass>(I<A.ProtectedClass>)' is inaccessible due to its protection level Diagnostic(ErrorCode.ERR_BadAccess, "Goo").WithArguments("Error.Goo<A.ProtectedClass>(I<A.ProtectedClass>)")); } [WorkItem(539628, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539628")] [Fact] public void CS0122ERR_BadAccess05() { var text = @" class Base { private Base() { } } class Derived : Base { private Derived() : this(1) { } //fine: can see own private members private Derived(int x) : base() { } //CS0122: cannot see base private members } "; CreateCompilation(text).VerifyDiagnostics( // (10,30): error CS0122: 'Base.Base()' is inaccessible due to its protection level Diagnostic(ErrorCode.ERR_BadAccess, "base").WithArguments("Base.Base()")); } [WorkItem(539628, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539628")] [Fact] public void CS0122ERR_BadAccess06() { var text = @" class Base { private Base() { } //private, but a match public Base(int x) { } //public, but not a match } class Derived : Base { private Derived() { } //implicit constructor initializer } "; CreateCompilation(text).VerifyDiagnostics( // (10,13): error CS0122: 'Base.Base()' is inaccessible due to its protection level Diagnostic(ErrorCode.ERR_BadAccess, "Derived").WithArguments("Base.Base()")); } [Fact] public void CS0123ERR_MethDelegateMismatch() { var text = @" delegate void D(); delegate void D2(int i); public class C { public static void f(int i) { } public static void Main() { D d = new D(f); // CS0123 D2 d2 = new D2(f); // OK } }"; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_MethDelegateMismatch, Line = 11, Column = 15 } }); } [WorkItem(539909, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539909")] [Fact] public void CS0123ERR_MethDelegateMismatch_01() { var text = @" delegate void boo(short x); class C { static void far<T>(T x) { } static void Main(string[] args) { C p = new C(); boo goo = null; goo += far<int>;// Invalid goo += far<short>;// OK } }"; CreateCompilation(text).VerifyDiagnostics( // (10,16): error CS0123: No overload for 'C.far<int>(int)' matches delegate 'boo' Diagnostic(ErrorCode.ERR_MethDelegateMismatch, "far<int>").WithArguments("C.far<int>(int)", "boo")); } [WorkItem(539909, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539909")] [WorkItem(540053, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540053")] [Fact] public void CS0123ERR_MethDelegateMismatch_02() { var text = @" delegate void boo(short x); class C<T> { public static void far(T x) { } public static void par<U>(U x) { System.Console.WriteLine(""par""); } public static boo goo = null; } class D { static void Main(string[] args) { C<long> p = new C<long>(); C<long>.goo += C<long>.far; C<long>.goo += C<long>.par<byte>; C<long>.goo(byte.MaxValue); C<long>.goo(long.MaxValue); C<short>.goo(long.MaxValue); } }"; CreateCompilation(text).VerifyDiagnostics( // (15,24): error CS0123: No overload for 'C<long>.far(long)' matches delegate 'boo' Diagnostic(ErrorCode.ERR_MethDelegateMismatch, "C<long>.far").WithArguments("C<long>.far(long)", "boo").WithLocation(15, 24), // (16,32): error CS0123: No overload for 'par' matches delegate 'boo' // C<long>.goo += C<long>.par<byte>; Diagnostic(ErrorCode.ERR_MethDelegateMismatch, "par<byte>").WithArguments("par", "boo").WithLocation(16, 32), // (18,21): error CS1503: Argument 1: cannot convert from 'long' to 'short' Diagnostic(ErrorCode.ERR_BadArgType, "long.MaxValue").WithArguments("1", "long", "short").WithLocation(18, 21), // (19,22): error CS1503: Argument 1: cannot convert from 'long' to 'short' Diagnostic(ErrorCode.ERR_BadArgType, "long.MaxValue").WithArguments("1", "long", "short").WithLocation(19, 22) ); } [Fact] public void CS0123ERR_MethDelegateMismatch_DelegateVariance() { var text = @" delegate TOut D<out TOut, in TIn>(TIn p); class A { } class B : A { } class C : B { } class Test { static void Main() { D<B, B> d; d = F1; //CS0407 d = F2; //CS0407 d = F3; //CS0123 d = F4; d = F5; d = F6; //CS0123 d = F7; d = F8; d = F9; //CS0123 } static A F1(A p) { return null; } static A F2(B p) { return null; } static A F3(C p) { return null; } static B F4(A p) { return null; } static B F5(B p) { return null; } static B F6(C p) { return null; } static C F7(A p) { return null; } static C F8(B p) { return null; } static C F9(C p) { return null; } }"; CreateCompilation(text).VerifyDiagnostics( // (13,13): error CS0407: 'A Test.F1(A)' has the wrong return type Diagnostic(ErrorCode.ERR_BadRetType, "F1").WithArguments("Test.F1(A)", "A"), // (14,13): error CS0407: 'A Test.F2(B)' has the wrong return type Diagnostic(ErrorCode.ERR_BadRetType, "F2").WithArguments("Test.F2(B)", "A"), // (15,13): error CS0123: No overload for 'F3' matches delegate 'D<B, B>' Diagnostic(ErrorCode.ERR_MethDelegateMismatch, "F3").WithArguments("F3", "D<B, B>"), // (18,13): error CS0123: No overload for 'F6' matches delegate 'D<B, B>' Diagnostic(ErrorCode.ERR_MethDelegateMismatch, "F6").WithArguments("F6", "D<B, B>"), // (21,13): error CS0123: No overload for 'F9' matches delegate 'D<B, B>' Diagnostic(ErrorCode.ERR_MethDelegateMismatch, "F9").WithArguments("F9", "D<B, B>")); } [Fact] public void CS0126ERR_RetObjectRequired() { var source = @"namespace N { class C { object F() { return; } X G() { return; } C P { get { return; } } Y Q { get { return; } } } } "; CreateCompilation(source).VerifyDiagnostics( // (6,9): error CS0246: The type or namespace name 'X' could not be found (are you missing a using directive or an assembly reference?) // X G() { return; } Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "X").WithArguments("X").WithLocation(6, 9), // (8,9): error CS0246: The type or namespace name 'Y' could not be found (are you missing a using directive or an assembly reference?) // Y Q { get { return; } } Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Y").WithArguments("Y").WithLocation(8, 9), // (5,22): error CS0126: An object of a type convertible to 'object' is required // object F() { return; } Diagnostic(ErrorCode.ERR_RetObjectRequired, "return").WithArguments("object").WithLocation(5, 22), // (6,17): error CS0126: An object of a type convertible to 'X' is required // X G() { return; } Diagnostic(ErrorCode.ERR_RetObjectRequired, "return").WithArguments("X").WithLocation(6, 17), // (7,21): error CS0126: An object of a type convertible to 'C' is required // C P { get { return; } } Diagnostic(ErrorCode.ERR_RetObjectRequired, "return").WithArguments("N.C").WithLocation(7, 21), // (8,21): error CS0126: An object of a type convertible to 'Y' is required // Y Q { get { return; } } Diagnostic(ErrorCode.ERR_RetObjectRequired, "return").WithArguments("Y").WithLocation(8, 21)); } [WorkItem(540115, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540115")] [Fact] public void CS0126ERR_RetObjectRequired_02() { var source = @"namespace Test { public delegate object D(); public class TestClass { public static int Test(D src) { src(); return 0; } } public class MainClass { public static int Main() { return TestClass.Test(delegate() { return; }); // The native compiler produces two errors for this code: // // CS0126: An object of a type convertible to 'object' is required // // CS1662: Cannot convert anonymous method to delegate type // 'Test.D' because some of the return types in the block are not implicitly // convertible to the delegate return type // // This is not great; the first error is right, but does not tell us anything about // the fact that overload resolution has failed on the first argument. The second // error is actually incorrect; it is not that 'some of the return types are incorrect', // it is that some of the returns do not return anything in the first place! There's // no 'type' to get wrong. // // I would like Roslyn to give two errors: // // CS1503: Argument 1: cannot convert from 'anonymous method' to 'Test.D' // CS0126: An object of a type convertible to 'object' is required // // Neal Gafter says: I'd like one error instead of two. There is an error inside the // body of the lambda. It is enough to report that specific error. This is consistent // with our design guideline to suppress errors higher in the tree when it is caused // by an error lower in the tree. } } } "; CreateCompilation(source).VerifyDiagnostics( // (18,48): error CS0126: An object of a type convertible to 'object' is required // return TestClass.Test(delegate() { return; }); Diagnostic(ErrorCode.ERR_RetObjectRequired, "return").WithArguments("object").WithLocation(18, 48)); } [Fact] public void CS0127ERR_RetNoObjectRequired() { var source = @"namespace MyNamespace { public class MyClass { public void F() { return 0; } // CS0127 public int P { get { return 0; } set { return 0; } // CS0127, set has an implicit void return type } } } "; CreateCompilation(source).VerifyDiagnostics( // (5,27): error CS0127: Since 'MyClass.F()' returns void, a return keyword must not be followed by an object expression // public void F() { return 0; } // CS0127 Diagnostic(ErrorCode.ERR_RetNoObjectRequired, "return").WithArguments("MyNamespace.MyClass.F()").WithLocation(5, 27), // (9,19): error CS0127: Since 'MyClass.P.set' returns void, a return keyword must not be followed by an object expression // set { return 0; } // CS0127, set has an implicit void return type Diagnostic(ErrorCode.ERR_RetNoObjectRequired, "return").WithArguments("MyNamespace.MyClass.P.set").WithLocation(9, 19)); } [Fact] public void CS0127ERR_RetNoObjectRequired_StaticConstructor() { string text = @" class C { static C() { return 1; } } "; CreateCompilation(text).VerifyDiagnostics( // (6,9): error CS0127: Since 'C.C()' returns void, a return keyword must not be followed by an object expression Diagnostic(ErrorCode.ERR_RetNoObjectRequired, "return").WithArguments("C.C()")); } [Fact] public void CS0128ERR_LocalDuplicate() { var text = @" namespace MyNamespace { public class MyClass { public static void Main() { char i = 'a'; int i = 2; // CS0128 if (i == 2) {} } } }"; CreateCompilation(text). VerifyDiagnostics( // (9,14): error CS0128: A local variable or function named 'i' is already defined in this scope // int i = 2; // CS0128 Diagnostic(ErrorCode.ERR_LocalDuplicate, "i").WithArguments("i").WithLocation(9, 14), // (9,14): warning CS0219: The variable 'i' is assigned but its value is never used // int i = 2; // CS0128 Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "i").WithArguments("i").WithLocation(9, 14) ); } [Fact] public void CS0131ERR_AssgLvalueExpected01() { CreateCompilation( @"class C { int i = 0; int P { get; set; } int this[int x] { get { return x; } set { } } void M() { ++P = 1; // CS0131 ++i = 1; // CS0131 ++this[0] = 1; //CS0131 } } ") .VerifyDiagnostics( // (7,9): error CS0131: The left-hand side of an assignment must be a variable, property or indexer Diagnostic(ErrorCode.ERR_AssgLvalueExpected, "++P"), // (8,9): error CS0131: The left-hand side of an assignment must be a variable, property or indexer Diagnostic(ErrorCode.ERR_AssgLvalueExpected, "++i"), // (10,9): error CS0131: The left-hand side of an assignment must be a variable, property or indexer Diagnostic(ErrorCode.ERR_AssgLvalueExpected, "++this[0]")); } [Fact] public void CS0131ERR_AssgLvalueExpected02() { var source = @"class C { const object NoObject = null; static void M() { const int i = 0; i += 1; 3 *= 1; (i + 1) -= 1; ""string"" = null; null = new object(); NoObject = ""string""; } } "; CreateCompilation(source).VerifyDiagnostics( // (7,9): error CS0131: The left-hand side of an assignment must be a variable, property or indexer // i += 1; Diagnostic(ErrorCode.ERR_AssgLvalueExpected, "i").WithLocation(7, 9), // (8,9): error CS0131: The left-hand side of an assignment must be a variable, property or indexer // 3 *= 1; Diagnostic(ErrorCode.ERR_AssgLvalueExpected, "3").WithLocation(8, 9), // (9,10): error CS0131: The left-hand side of an assignment must be a variable, property or indexer // (i + 1) -= 1; Diagnostic(ErrorCode.ERR_AssgLvalueExpected, "i + 1").WithLocation(9, 10), // (10,9): error CS0131: The left-hand side of an assignment must be a variable, property or indexer // "string" = null; Diagnostic(ErrorCode.ERR_AssgLvalueExpected, @"""string""").WithLocation(10, 9), // (11,9): error CS0131: The left-hand side of an assignment must be a variable, property or indexer // null = new object(); Diagnostic(ErrorCode.ERR_AssgLvalueExpected, "null").WithLocation(11, 9), // (12,9): error CS0131: The left-hand side of an assignment must be a variable, property or indexer // NoObject = "string"; Diagnostic(ErrorCode.ERR_AssgLvalueExpected, "NoObject").WithLocation(12, 9)); } /// <summary> /// Breaking change from Dev10. CS0131 is now reported for all value /// types, not just struct types. Specifically, CS0131 is now reported /// for type parameters constrained to "struct". (See also CS1612.) /// </summary> [WorkItem(528763, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528763")] [Fact] public void CS0131ERR_AssgLvalueExpected03() { var source = @"struct S { public object P { get; set; } public object this[object index] { get { return null; } set { } } } interface I { object P { get; set; } object this[object index] { get; set; } } class C { static void M<T>() where T : struct, I { default(S).P = null; default(T).P = null; // Dev10: no error default(S)[0] = null; default(T)[0] = null; // Dev10: no error } }"; CreateCompilation(source).VerifyDiagnostics( // (16,9): error CS0131: The left-hand side of an assignment must be a variable, property or indexer Diagnostic(ErrorCode.ERR_AssgLvalueExpected, "default(S).P").WithLocation(16, 9), // (16,9): error CS0131: The left-hand side of an assignment must be a variable, property or indexer Diagnostic(ErrorCode.ERR_AssgLvalueExpected, "default(T).P").WithLocation(17, 9), // (18,9): error CS0131: The left-hand side of an assignment must be a variable, property or indexer Diagnostic(ErrorCode.ERR_AssgLvalueExpected, "default(S)[0]").WithLocation(18, 9), // (18,9): error CS0131: The left-hand side of an assignment must be a variable, property or indexer Diagnostic(ErrorCode.ERR_AssgLvalueExpected, "default(T)[0]").WithLocation(19, 9)); } [WorkItem(538077, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538077")] [Fact] public void CS0132ERR_StaticConstParam() { var text = @" class A { static A(int z) { } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_StaticConstParam, Parameters = new string[] { "A.A(int)" } } }); } [Fact] public void CS0133ERR_NotConstantExpression01() { var source = @"class MyClass { public const int a = b; //no error since b is declared const public const int b = c; //CS0133, c is not constant public static int c = 1; //change static to const to correct program } "; CreateCompilation(source).VerifyDiagnostics( // (4,25): error CS0133: The expression being assigned to 'MyClass.b' must be constant // public const int b = c; //CS0133, c is not constant Diagnostic(ErrorCode.ERR_NotConstantExpression, "c").WithArguments("MyClass.b").WithLocation(4, 25)); } [Fact] public void CS0133ERR_NotConstantExpression02() { var source = @"enum E { X, Y = C.F(), Z = C.G() + 1, } class C { public static E F() { return E.X; } public static int G() { return 0; } } "; CreateCompilation(source).VerifyDiagnostics( // (4,9): error CS0266: Cannot implicitly convert type 'E' to 'int'. An explicit conversion exists (are you missing a cast?) // Y = C.F(), Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "C.F()").WithArguments("E", "int").WithLocation(4, 9), // (4,9): error CS0133: The expression being assigned to 'E.Y' must be constant // Y = C.F(), Diagnostic(ErrorCode.ERR_NotConstantExpression, "C.F()").WithArguments("E.Y").WithLocation(4, 9), // (5,9): error CS0133: The expression being assigned to 'E.Z' must be constant // Z = C.G() + 1, Diagnostic(ErrorCode.ERR_NotConstantExpression, "C.G() + 1").WithArguments("E.Z").WithLocation(5, 9)); } [Fact] public void CS0133ERR_NotConstantExpression03() { var source = @"class C { static void M() { int y = 1; const int x = 2 * y; } } "; CreateCompilation(source).VerifyDiagnostics( // (6,23): error CS0133: The expression being assigned to 'x' must be constant // const int x = 2 * y; Diagnostic(ErrorCode.ERR_NotConstantExpression, "2 * y").WithArguments("x").WithLocation(6, 23)); } [Fact] public void CS0133ERR_NotConstantExpression04() { var source = @"class C { static void M() { const int x = x + x; } }"; CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (5,27): error CS0110: The evaluation of the constant value for 'x' involves a circular definition // const int x = x + x; Diagnostic(ErrorCode.ERR_CircConstValue, "x").WithArguments("x").WithLocation(5, 27), // (5,23): error CS0110: The evaluation of the constant value for 'x' involves a circular definition // const int x = x + x; Diagnostic(ErrorCode.ERR_CircConstValue, "x").WithArguments("x").WithLocation(5, 23)); } [Fact] public void CS0135ERR_NameIllegallyOverrides() { // See NameCollisionTests.cs for commentary on this error. var text = @" public class MyClass2 { public static int i = 0; public static void Main() { { int i = 4; // CS0135: Roslyn reports this error here i++; } i = 0; // Native compiler reports the error here } }"; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text); } [Fact] public void CS0135ERR_NameIllegallyOverrides02() { CreateCompilationWithMscorlib40AndSystemCore(@" using System.Linq; class Test { static int x; static void Main() { int z = x; var y = from x in Enumerable.Range(1, 100) // CS1931 select x; } }").VerifyDiagnostics( // (6,16): warning CS0649: Field 'Test.x' is never assigned to, and will always have its default value 0 // static int x; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "x").WithArguments("Test.x", "0").WithLocation(6, 16) ); } [Fact] public void CS0136ERR_LocalIllegallyOverrides01() { // See comments in NameCollisionTests for thoughts on this error. string text = @"class C { static void M(object x) { string x = null; // CS0136 string y = null; if (x != null) { int y = 0; // CS0136 M(y); } M(x); M(y); } object P { get { int value = 0; // no error return value; } set { int value = 0; // CS0136 M(value); } } static void N(int q) { System.Func<int, int> f = q=>q; // 0136 } }"; var comp = CreateCompilation(text, parseOptions: TestOptions.Regular7_3); comp.VerifyDiagnostics( // (5,16): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // string x = null; // CS0136 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x").WithLocation(5, 16), // (9,17): error CS0136: A local or parameter named 'y' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // int y = 0; // CS0136 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y").WithArguments("y").WithLocation(9, 17), // (24,17): error CS0136: A local or parameter named 'value' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // int value = 0; // CS0136 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "value").WithArguments("value").WithLocation(24, 17), // (30,35): error CS0136: A local or parameter named 'q' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // System.Func<int, int> f = q=>q; // 0136 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "q").WithArguments("q").WithLocation(30, 35)); comp = CreateCompilation(text); comp.VerifyDiagnostics( // (5,16): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // string x = null; // CS0136 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x").WithLocation(5, 16), // (9,17): error CS0136: A local or parameter named 'y' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // int y = 0; // CS0136 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y").WithArguments("y").WithLocation(9, 17), // (24,17): error CS0136: A local or parameter named 'value' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // int value = 0; // CS0136 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "value").WithArguments("value").WithLocation(24, 17)); } [Fact] public void CS0136ERR_LocalIllegallyOverrides02() { // See comments in NameCollisionTests for commentary on this error. CreateCompilation( @"class C { static void M(object o) { try { } catch (System.IO.IOException e) { M(e); } catch (System.Exception e) // Legal; the two 'e' variables are in non-overlapping declaration spaces { M(e); } try { } catch (System.Exception o) // CS0136: Illegal; the two 'o' variables are in overlapping declaration spaces. { M(o); } } } ") .VerifyDiagnostics( Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "o").WithArguments("o").WithLocation(19, 33)); } [Fact] public void CS0136ERR_LocalIllegallyOverrides03() { // See comments in NameCollisionTests for commentary on this error. CreateCompilation( @"class C { int field = 0; int property { get; set; } static public void Main() { int[] ints = new int[] { 1, 2, 3 }; string[] strings = new string[] { ""1"", ""2"", ""3"" }; int conflict = 1; System.Console.WriteLine(conflict); foreach (int field in ints) { } // Legal: local hides field but name is used consistently foreach (string property in strings) { } // Legal: local hides property but name is used consistently foreach (string conflict in strings) { } // 0136: local hides another local in an enclosing local declaration space. } } ") .VerifyDiagnostics( // (14,25): error CS0136: A local or parameter named 'conflict' cannot be declared in this // scope because that name is used in an enclosing local scope to define a local or parameter // foreach (string conflict in strings) { } // 0136 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "conflict").WithArguments("conflict").WithLocation(14, 25), // (3,9): warning CS0414: The field 'C.field' is assigned but its value is never used // int field = 0; Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "field").WithArguments("C.field")); } [WorkItem(538045, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538045")] [Fact] public void CS0139ERR_NoBreakOrCont() { var text = @" namespace x { public class a { public static void Main(bool b) { if (b) continue; // CS0139 else break; // CS0139 } } }"; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_NoBreakOrCont, Line = 9, Column = 17 }, new ErrorDescription { Code = (int)ErrorCode.ERR_NoBreakOrCont, Line = 11, Column = 17 }}); } [WorkItem(542400, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542400")] [Fact] public void CS0140ERR_DuplicateLabel() { var text = @" namespace MyNamespace { public class MyClass { public static void Main() { label1: int i = M(); label1: int j = M(); // CS0140, comment this line to resolve goto label1; } static int M() { return 0; } } }"; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (9,10): error CS0140: The label 'label1' is a duplicate // label1: int j = M(); // CS0140, comment this line to resolve Diagnostic(ErrorCode.ERR_DuplicateLabel, "label1").WithArguments("label1").WithLocation(9, 10) ); } [WorkItem(542420, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542420")] [Fact] public void ErrorMeansSuccess_Attribute() { var text = @" using A; using B; using System; namespace A { class var { } class XAttribute : Attribute { } } namespace B { class var { } class XAttribute : Attribute { } class X : Attribute { } } class Xyzzy { [X] // 17.2 If an attribute class is found both with and without this suffix, an ambiguity is present and a compile-time error occurs. public static void Main(string[] args) { } static int M() { return 0; } }"; var comp = CreateCompilation(text); comp.VerifyDiagnostics(); } [WorkItem(542420, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542420")] [Fact] public void ErrorMeansSuccess_var() { var text = @" using A; using B; namespace A { class var { } } namespace B { class var { } } class Xyzzy { public static void Main(string[] args) { var x = M(); // 8.5.1 When the local-variable-type is specified as var and no type named var is in scope, ... } static int M() { return 0; } }"; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (21,9): error CS0104: 'var' is an ambiguous reference between 'A.var' and 'B.var' // var x = M(); // 8.5.1 When the local-variable-type is specified as var and no type named var is in scope, ... Diagnostic(ErrorCode.ERR_AmbigContext, "var").WithArguments("var", "A.var", "B.var") ); } [Fact] public void CS0144ERR_NoNewAbstract() { var text = @" interface ii { } abstract class aa { } public class a { public static void Main() { ii xx = new ii(); // CS0144 ii yy = new ii(Error); // CS0144, CS0103 aa zz = new aa(); // CS0144 } }"; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_NoNewAbstract, Line = 14, Column = 15 }, new ErrorDescription { Code = (int)ErrorCode.ERR_NoNewAbstract, Line = 15, Column = 15 }, new ErrorDescription { Code = (int)ErrorCode.ERR_NoNewAbstract, Line = 16, Column = 15 }, new ErrorDescription { Code = (int)ErrorCode.ERR_NameNotInContext, Line = 15, Column = 22 } }); } [WorkItem(539583, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539583")] [Fact] public void CS0150ERR_ConstantExpected() { var test = @" class C { static void Main() { byte x = 1; int[] a1 = new int[x]; int[] a2 = new int[x] { 1 }; //CS0150 const sbyte y = 1; const short z = 2; int[] b1 = new int[y + z]; int[] b2 = new int[y + z] { 1, 2, 3 }; } } "; CreateCompilation(test).VerifyDiagnostics( // (8,28): error CS0150: A constant value is expected Diagnostic(ErrorCode.ERR_ConstantExpected, "x")); } [Fact()] public void CS0151ERR_IntegralTypeValueExpected() { var text = @" public class iii { public static implicit operator int (iii aa) { return 0; } public static implicit operator long (iii aa) { return 0; } public static void Main() { iii a = new iii(); switch (a) // CS0151, compiler cannot choose between int and long { case 1: break; } } }"; var comp = CreateCompilation(text, parseOptions: TestOptions.Regular6); comp.VerifyDiagnostics( // (18,15): error CS0151: A switch expression or case label must be a bool, char, string, integral, enum, or corresponding nullable type in C# 6 and earlier. // switch (a) // CS0151, compiler cannot choose between int and long Diagnostic(ErrorCode.ERR_V6SwitchGoverningTypeValueExpected, "a").WithLocation(18, 15), // (20,15): error CS0029: Cannot implicitly convert type 'int' to 'iii' // case 1: Diagnostic(ErrorCode.ERR_NoImplicitConv, "1").WithArguments("int", "iii").WithLocation(20, 15) ); } [Fact] public void CS0152ERR_DuplicateCaseLabel() { var text = @" namespace x { public class a { public static void Main() { int i = 0; switch (i) { case 1: i++; return; case 1: // CS0152, two case 1 statements i++; return; } } } }"; CreateCompilation(text).VerifyDiagnostics( // (16,13): error CS0152: The switch statement contains multiple cases with the label value '1' // case 1: // CS0152, two case 1 statements Diagnostic(ErrorCode.ERR_DuplicateCaseLabel, "case 1:").WithArguments("1").WithLocation(16, 13) ); } [Fact] public void CS0153ERR_InvalidGotoCase() { var text = @" public class a { public static void Main() { goto case 5; // CS0153 } }"; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (6,7): error CS0153: A goto case is only valid inside a switch statement // goto case 5; // CS0153 Diagnostic(ErrorCode.ERR_InvalidGotoCase, "goto case 5;").WithLocation(6, 7)); } [Fact] public void CS0153ERR_InvalidGotoCase_2() { var text = @" class Program { static void Main(string[] args) { string Fruit = ""Apple""; switch (Fruit) { case ""Banana"": break; default: break; } goto default; } }"; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (14,9): error CS0153: A goto case is only valid inside a switch statement // goto default; Diagnostic(ErrorCode.ERR_InvalidGotoCase, "goto default;").WithLocation(14, 9)); } [Fact] public void CS0154ERR_PropertyLacksGet01() { CreateCompilation( @"class C { static object P { set { } } static int Q { set { } } static void M(object o) { C.P = null; o = C.P; // CS0154 M(P); // CS0154 ++C.Q; // CS0154 } } ") .VerifyDiagnostics( // (8,13): error CS0154: The property or indexer 'C.P' cannot be used in this context because it lacks the get accessor Diagnostic(ErrorCode.ERR_PropertyLacksGet, "C.P").WithArguments("C.P"), // (9,11): error CS0154: The property or indexer 'C.P' cannot be used in this context because it lacks the get accessor Diagnostic(ErrorCode.ERR_PropertyLacksGet, "P").WithArguments("C.P"), // (10,11): error CS0154: The property or indexer 'C.Q' cannot be used in this context because it lacks the get accessor Diagnostic(ErrorCode.ERR_PropertyLacksGet, "C.Q").WithArguments("C.Q")); } [Fact] public void CS0154ERR_PropertyLacksGet02() { var source = @"class A { public virtual A P { get; set; } public object Q { set { } } } class B : A { public override A P { set { } } void M() { M(Q); // CS0154, no get method } static void M(B b) { object o = b.P; // no error o = b.Q; // CS0154, no get method b.P.Q = null; // no error o = b.P.Q; // CS0154, no get method } static void M(object o) { } } "; CreateCompilation(source).VerifyDiagnostics( // (11,11): error CS0154: The property or indexer 'A.Q' cannot be used in this context because it lacks the get accessor // M(Q); // CS0154, no get method Diagnostic(ErrorCode.ERR_PropertyLacksGet, "Q").WithArguments("A.Q").WithLocation(11, 11), // (16,13): error CS0154: The property or indexer 'A.Q' cannot be used in this context because it lacks the get accessor // o = b.Q; // CS0154, no get method Diagnostic(ErrorCode.ERR_PropertyLacksGet, "b.Q").WithArguments("A.Q").WithLocation(16, 13), // (18,13): error CS0154: The property or indexer 'A.Q' cannot be used in this context because it lacks the get accessor // o = b.P.Q; // CS0154, no get method Diagnostic(ErrorCode.ERR_PropertyLacksGet, "b.P.Q").WithArguments("A.Q").WithLocation(18, 13)); } [Fact] public void CS0154ERR_PropertyLacksGet03() { var source = @"class C { int P { set { } } void M() { P += 1; } } "; CreateCompilation(source).VerifyDiagnostics( // (6,9): error CS0154: The property or indexer 'C.P' cannot be used in this context because it lacks the get accessor // P += 1; Diagnostic(ErrorCode.ERR_PropertyLacksGet, "P").WithArguments("C.P").WithLocation(6, 9)); } [Fact] public void CS0154ERR_PropertyLacksGet04() { var source = @"class C { object p; object P { set { p = P; } } } "; CreateCompilation(source).VerifyDiagnostics( // (4,26): error CS0154: The property or indexer 'C.P' cannot be used in this context because it lacks the get accessor // object P { set { p = P; } } Diagnostic(ErrorCode.ERR_PropertyLacksGet, "P").WithArguments("C.P").WithLocation(4, 26)); } [Fact] public void CS0154ERR_PropertyLacksGet05() { CreateCompilation( @"class C { object P { set { } } static bool Q { set { } } void M() { object o = P as string; o = P ?? Q; o = (o != null) ? P : Q; o = !Q; } }") .VerifyDiagnostics( // (7,20): error CS0154: The property or indexer 'C.P' cannot be used in this context because it lacks the get accessor Diagnostic(ErrorCode.ERR_PropertyLacksGet, "P").WithArguments("C.P").WithLocation(7, 20), // (8,13): error CS0154: The property or indexer 'C.P' cannot be used in this context because it lacks the get accessor Diagnostic(ErrorCode.ERR_PropertyLacksGet, "P").WithArguments("C.P").WithLocation(8, 13), // (8,18): error CS0154: The property or indexer 'C.Q' cannot be used in this context because it lacks the get accessor Diagnostic(ErrorCode.ERR_PropertyLacksGet, "Q").WithArguments("C.Q").WithLocation(8, 18), // (9,27): error CS0154: The property or indexer 'C.P' cannot be used in this context because it lacks the get accessor Diagnostic(ErrorCode.ERR_PropertyLacksGet, "P").WithArguments("C.P").WithLocation(9, 27), // (9,31): error CS0154: The property or indexer 'C.Q' cannot be used in this context because it lacks the get accessor Diagnostic(ErrorCode.ERR_PropertyLacksGet, "Q").WithArguments("C.Q").WithLocation(9, 31), // (10,14): error CS0154: The property or indexer 'C.Q' cannot be used in this context because it lacks the get accessor Diagnostic(ErrorCode.ERR_PropertyLacksGet, "Q").WithArguments("C.Q").WithLocation(10, 14)); } [Fact] public void CS0154ERR_PropertyLacksGet06() { CreateCompilation( @"class C { int this[int x] { set { } } void M(int b) { b = this[0]; b = 1 + this[1]; M(this[2]); this[3]++; this[4] += 1; } }") .VerifyDiagnostics( // (6,13): error CS0154: The property or indexer 'C.this[int]' cannot be used in this context because it lacks the get accessor Diagnostic(ErrorCode.ERR_PropertyLacksGet, "this[0]").WithArguments("C.this[int]"), // (7,17): error CS0154: The property or indexer 'C.this[int]' cannot be used in this context because it lacks the get accessor Diagnostic(ErrorCode.ERR_PropertyLacksGet, "this[1]").WithArguments("C.this[int]"), // (8,11): error CS0154: The property or indexer 'C.this[int]' cannot be used in this context because it lacks the get accessor Diagnostic(ErrorCode.ERR_PropertyLacksGet, "this[2]").WithArguments("C.this[int]"), // (9,9): error CS0154: The property or indexer 'C.this[int]' cannot be used in this context because it lacks the get accessor Diagnostic(ErrorCode.ERR_PropertyLacksGet, "this[3]").WithArguments("C.this[int]"), // (10,9): error CS0154: The property or indexer 'C.this[int]' cannot be used in this context because it lacks the get accessor Diagnostic(ErrorCode.ERR_PropertyLacksGet, "this[4]").WithArguments("C.this[int]")); } [Fact] public void CS0154ERR_PropertyLacksGet07() { var source1 = @"public class A { public virtual object P { private get { return null; } set { } } } public class B : A { public override object P { set { } } }"; var compilation1 = CreateCompilation(source1); compilation1.VerifyDiagnostics(); var compilationVerifier = CompileAndVerify(compilation1); var reference1 = MetadataReference.CreateFromImage(compilationVerifier.EmittedAssemblyData); var source2 = @"class C { static void M(B b) { var o = b.P; b.P = o; } }"; var compilation2 = CreateCompilation(source2, references: new[] { reference1 }); compilation2.VerifyDiagnostics( // (5,17): error CS0154: The property or indexer 'B.P' cannot be used in this context because it lacks the get accessor Diagnostic(ErrorCode.ERR_PropertyLacksGet, "b.P").WithArguments("B.P").WithLocation(5, 17)); } [Fact] public void CS0155ERR_BadExceptionType() { var text = @"interface IA { } interface IB : IA { } struct S { } class C { static void M() { try { } catch (object) { } catch (System.Exception) { } catch (System.DateTime) { } catch (System.Int32) { } catch (IA) { } catch (IB) { } catch (S) { } catch (S) { } } } "; CreateCompilation(text).VerifyDiagnostics( Diagnostic(ErrorCode.ERR_BadExceptionType, "object").WithLocation(9, 16), Diagnostic(ErrorCode.ERR_UnreachableCatch, "System.Exception").WithArguments("object").WithLocation(10, 16), Diagnostic(ErrorCode.ERR_BadExceptionType, "System.DateTime").WithLocation(11, 16), Diagnostic(ErrorCode.ERR_BadExceptionType, "System.Int32").WithLocation(12, 16), Diagnostic(ErrorCode.ERR_BadExceptionType, "IA").WithLocation(13, 16), Diagnostic(ErrorCode.ERR_BadExceptionType, "IB").WithLocation(14, 16), Diagnostic(ErrorCode.ERR_BadExceptionType, "S").WithLocation(15, 16), Diagnostic(ErrorCode.ERR_BadExceptionType, "S").WithLocation(16, 16)); } [Fact] public void CS0155ERR_BadExceptionType_Null() { var text = @"class C { static readonly bool False = false; const string T = null; static void M(object o) { const string s = null; if (False) throw null; if (False) throw (string)null; //CS0155 if (False) throw s; //CS0155 if (False) throw T; //CS0155 } } "; CreateCompilation(text).VerifyDiagnostics( // (10,26): error CS0029: Cannot implicitly convert type 'string' to 'System.Exception' // if (False) throw (string)null; //CS0155 Diagnostic(ErrorCode.ERR_NoImplicitConv, "(string)null").WithArguments("string", "System.Exception").WithLocation(10, 26), // (11,26): error CS0029: Cannot implicitly convert type 'string' to 'System.Exception' // if (False) throw s; //CS0155 Diagnostic(ErrorCode.ERR_NoImplicitConv, "s").WithArguments("string", "System.Exception").WithLocation(11, 26), // (12,26): error CS0029: Cannot implicitly convert type 'string' to 'System.Exception' // if (False) throw T; //CS0155 Diagnostic(ErrorCode.ERR_NoImplicitConv, "T").WithArguments("string", "System.Exception").WithLocation(12, 26) ); } [Fact] public void CS0155ERR_BadExceptionType_FailingAs() { var text = @" class C { static readonly bool False = false; static void M(object o) { if (False) throw new C() as D; //CS0155, though always null } } class D : C { } "; CreateCompilation(text).VerifyDiagnostics( // (8,26): error CS0029: Cannot implicitly convert type 'D' to 'System.Exception' // if (False) throw new C() as D; //CS0155, though always null Diagnostic(ErrorCode.ERR_NoImplicitConv, "new C() as D").WithArguments("D", "System.Exception").WithLocation(8, 26) ); } [Fact] public void CS0155ERR_BadExceptionType_TypeParameters() { var text = @"using System; class C { static readonly bool False = false; static void M<T, TC, TS, TE>(object o) where TC : class where TS : struct where TE : Exception, new() { if (False) throw default(T); //CS0155 if (False) throw default(TC); //CS0155 if (False) throw default(TS); //CS0155 if (False) throw default(TE); if (False) throw new TE(); } } "; CreateCompilation(text).VerifyDiagnostics( // (11,26): error CS0029: Cannot implicitly convert type 'T' to 'System.Exception' // if (False) throw default(T); //CS0155 Diagnostic(ErrorCode.ERR_NoImplicitConv, "default(T)").WithArguments("T", "System.Exception").WithLocation(11, 26), // (12,26): error CS0029: Cannot implicitly convert type 'TC' to 'System.Exception' // if (False) throw default(TC); //CS0155 Diagnostic(ErrorCode.ERR_NoImplicitConv, "default(TC)").WithArguments("TC", "System.Exception").WithLocation(12, 26), // (13,26): error CS0029: Cannot implicitly convert type 'TS' to 'System.Exception' // if (False) throw default(TS); //CS0155 Diagnostic(ErrorCode.ERR_NoImplicitConv, "default(TS)").WithArguments("TS", "System.Exception").WithLocation(13, 26) ); } [Fact()] public void CS0155ERR_BadExceptionType_UserDefinedConversions() { var text = @"using System; class C { static readonly bool False = false; static void M(object o) { if (False) throw new Implicit(); //CS0155 if (False) throw new Explicit(); //CS0155 if (False) throw (Exception)new Implicit(); if (False) throw (Exception)new Explicit(); } } class Implicit { public static implicit operator Exception(Implicit i) { return null; } } class Explicit { public static explicit operator Exception(Explicit i) { return null; } } "; CreateCompilation(text, parseOptions: TestOptions.Regular7_3).VerifyDiagnostics( // (8,20): error CS0155: The type caught or thrown must be derived from System.Exception Diagnostic(ErrorCode.ERR_BadExceptionType, "new Implicit()"), // (8,20): error CS0155: The type caught or thrown must be derived from System.Exception Diagnostic(ErrorCode.ERR_BadExceptionType, "new Explicit()") ); CreateCompilation(text).VerifyDiagnostics( // (9,26): error CS0266: Cannot implicitly convert type 'Explicit' to 'System.Exception'. An explicit conversion exists (are you missing a cast?) // if (False) throw new Explicit(); //CS0155 Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "new Explicit()").WithArguments("Explicit", "System.Exception").WithLocation(9, 26) ); } [Fact] public void CS0155ERR_BadExceptionType_Dynamic() { var text = @" class C { static readonly bool False = false; static void M(object o) { dynamic d = null; if (False) throw d; //CS0155 } } "; CreateCompilation(text, parseOptions: TestOptions.Regular7_3).VerifyDiagnostics( // (9,26): error CS0155: The type caught or thrown must be derived from System.Exception Diagnostic(ErrorCode.ERR_BadExceptionType, "d")); CreateCompilation(text).VerifyDiagnostics(); // dynamic conversion to Exception } [WorkItem(542995, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542995")] [Fact] public void CS0155ERR_BadExceptionType_Struct() { var text = @" public class Test { public static void Main(string[] args) { } private void Method() { try { } catch (s1 s) { } } } struct s1 { } "; CreateCompilation(text).VerifyDiagnostics( // (12,16): error CS0155: The type caught or thrown must be derived from System.Exception // catch (s1 s) Diagnostic(ErrorCode.ERR_BadExceptionType, "s1"), // (12,19): warning CS0168: The variable 's' is declared but never used // catch (s1 s) Diagnostic(ErrorCode.WRN_UnreferencedVar, "s").WithArguments("s") ); } [Fact] public void CS0156ERR_BadEmptyThrow() { var text = @" using System; namespace x { public class b : Exception { } public class a { public static void Main() { try { throw; // CS0156 } catch(b) { throw; // this throw is valid } } } }"; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_BadEmptyThrow, Line = 16, Column = 13 } }); } [Fact] public void CS0156ERR_BadEmptyThrow_Nesting() { var text = @" class C { void M() { bool b = System.DateTime.Now.Second > 1; //avoid unreachable code if (b) throw; //CS0156 try { if (b) throw; //CS0156 try { if (b) throw; //CS0156 } catch { if (b) throw; //fine } finally { if (b) throw; //CS0156 } } catch { if (b) throw; //fine try { if (b) throw; //fine } catch { if (b) throw; //fine } finally { if (b) throw; //CS0724 try { if (b) throw; //CS0724 } catch { if (b) throw; //fine } finally { if (b) throw; //CS0724 } } } finally { if (b) throw; //CS0156 try { if (b) throw; //CS0156 } catch { if (b) throw; //fine } finally { if (b) throw; //CS0156 } } } }"; CreateCompilation(text).VerifyDiagnostics( // (6,9): error CS0156: A throw statement with no arguments is not allowed outside of a catch clause Diagnostic(ErrorCode.ERR_BadEmptyThrow, "throw"), // (9,13): error CS0156: A throw statement with no arguments is not allowed outside of a catch clause Diagnostic(ErrorCode.ERR_BadEmptyThrow, "throw"), // (12,17): error CS0156: A throw statement with no arguments is not allowed outside of a catch clause Diagnostic(ErrorCode.ERR_BadEmptyThrow, "throw"), // (20,17): error CS0156: A throw statement with no arguments is not allowed outside of a catch clause Diagnostic(ErrorCode.ERR_BadEmptyThrow, "throw"), // (36,17): error CS0724: A throw statement with no arguments is not allowed in a finally clause that is nested inside the nearest enclosing catch clause Diagnostic(ErrorCode.ERR_BadEmptyThrowInFinally, "throw"), // (36,17): error CS0724: A throw statement with no arguments is not allowed in a finally clause that is nested inside the nearest enclosing catch clause Diagnostic(ErrorCode.ERR_BadEmptyThrowInFinally, "throw"), // (36,17): error CS0724: A throw statement with no arguments is not allowed in a finally clause that is nested inside the nearest enclosing catch clause Diagnostic(ErrorCode.ERR_BadEmptyThrowInFinally, "throw"), // (41,13): error CS0156: A throw statement with no arguments is not allowed outside of a catch clause Diagnostic(ErrorCode.ERR_BadEmptyThrow, "throw"), // (44,17): error CS0156: A throw statement with no arguments is not allowed outside of a catch clause Diagnostic(ErrorCode.ERR_BadEmptyThrow, "throw"), // (52,17): error CS0156: A throw statement with no arguments is not allowed outside of a catch clause Diagnostic(ErrorCode.ERR_BadEmptyThrow, "throw")); } [Fact] public void CS0156ERR_BadEmptyThrow_Lambdas() { var text = @" class C { void M() { bool b = System.DateTime.Now.Second > 1; // avoid unreachable code System.Action a; a = () => { throw; }; //CS0156 try { a = () => { if (b) throw; //CS0156 try { if (b) throw; //CS0156 } catch { if (b) throw; //fine } finally { if (b) throw; //CS0156 } }; } catch { a = () => { if (b) throw; //CS0156 try { if (b) throw; //CS0156 } catch { if (b) throw; //fine } finally { if (b) throw; //CS0156 } }; } finally { a = () => { if (b) throw; //CS0156 try { if (b) throw; //CS0156 } catch { if (b) throw; //fine } finally { if (b) throw; //CS0156 } }; } } }"; CreateCompilation(text).VerifyDiagnostics( // (8,21): error CS0156: A throw statement with no arguments is not allowed outside of a catch clause Diagnostic(ErrorCode.ERR_BadEmptyThrow, "throw"), // (13,24): error CS0156: A throw statement with no arguments is not allowed outside of a catch clause Diagnostic(ErrorCode.ERR_BadEmptyThrow, "throw"), // (16,28): error CS0156: A throw statement with no arguments is not allowed outside of a catch clause Diagnostic(ErrorCode.ERR_BadEmptyThrow, "throw"), // (24,28): error CS0156: A throw statement with no arguments is not allowed outside of a catch clause Diagnostic(ErrorCode.ERR_BadEmptyThrow, "throw"), // (32,24): error CS0156: A throw statement with no arguments is not allowed outside of a catch clause Diagnostic(ErrorCode.ERR_BadEmptyThrow, "throw"), // (35,28): error CS0156: A throw statement with no arguments is not allowed outside of a catch clause Diagnostic(ErrorCode.ERR_BadEmptyThrow, "throw"), // (43,28): error CS0156: A throw statement with no arguments is not allowed outside of a catch clause Diagnostic(ErrorCode.ERR_BadEmptyThrow, "throw"), // (51,24): error CS0156: A throw statement with no arguments is not allowed outside of a catch clause Diagnostic(ErrorCode.ERR_BadEmptyThrow, "throw"), // (54,28): error CS0156: A throw statement with no arguments is not allowed outside of a catch clause Diagnostic(ErrorCode.ERR_BadEmptyThrow, "throw"), // (62,28): error CS0156: A throw statement with no arguments is not allowed outside of a catch clause Diagnostic(ErrorCode.ERR_BadEmptyThrow, "throw")); } [WorkItem(540817, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540817")] [Fact] public void CS0157ERR_BadFinallyLeave01() { var text = @"class C { static int F; static void M() { if (F == 0) goto Before; else if (F == 1) goto After; Before: ; try { if (F == 0) goto Before; else if (F == 1) goto After; else if (F == 2) goto TryBlock; else if (F == 3) return; TryBlock: ; } catch (System.Exception) { if (F == 0) goto Before; else if (F == 1) goto After; else if (F == 2) goto CatchBlock; else if (F == 3) return; CatchBlock: ; } finally { if (F == 0) goto Before; else if (F == 1) goto After; else if (F == 2) goto FinallyBlock; else if (F == 3) return; FinallyBlock: ; } After: ; } }"; CreateCompilation(text).VerifyDiagnostics( // (41,17): error CS0157: Control cannot leave the body of a finally clause // goto Before; Diagnostic(ErrorCode.ERR_BadFinallyLeave, "goto"), // (43,17): error CS0157: Control cannot leave the body of a finally clause // goto After; Diagnostic(ErrorCode.ERR_BadFinallyLeave, "goto"), // (47,17): error CS0157: Control cannot leave the body of a finally clause // return; Diagnostic(ErrorCode.ERR_BadFinallyLeave, "return"), // (3,16): warning CS0649: Field 'C.F' is never assigned to, and will always have its default value 0 // static int F; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "F").WithArguments("C.F", "0") ); } [WorkItem(540817, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540817")] [Fact] public void CS0157ERR_BadFinallyLeave02() { var text = @"using System; class C { static void F(int i) { } static void M() { for (int i = 0; i < 10;) { if (i < 5) { try { F(i); } catch (Exception) { continue; } finally { break; } } else { try { F(i); } catch (Exception) { break; } finally { continue; } } } } }"; CreateCompilation(text). VerifyDiagnostics( Diagnostic(ErrorCode.ERR_BadFinallyLeave, "break").WithLocation(15, 27), Diagnostic(ErrorCode.ERR_BadFinallyLeave, "continue").WithLocation(21, 27)); } [WorkItem(540817, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540817")] [Fact] public void CS0157ERR_BadFinallyLeave03() { var text = @" class C { static void Main(string[] args) { int i = 0; try { i = 1; } catch { i = 2; } finally { i = 3; goto lab1; }// invalid lab1: return; } } "; CreateCompilation(text). VerifyDiagnostics( // (9,26): error CS0157: Control cannot leave the body of a finally clause // finally { i = 3; goto lab1; }// invalid Diagnostic(ErrorCode.ERR_BadFinallyLeave, "goto"), // (6,13): warning CS0219: The variable 'i' is assigned but its value is never used // int i = 0; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "i").WithArguments("i") ); } [WorkItem(539890, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539890")] [Fact] public void CS0158ERR_LabelShadow() { var text = @" namespace MyNamespace { public class MyClass { public static void Main() { goto lab1; lab1: { lab1: goto lab1; // CS0158 } } } }"; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_LabelShadow, Line = 11, Column = 13 } }); } [WorkItem(539890, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539890")] [Fact] public void CS0158ERR_LabelShadow_02() { var text = @" delegate int del(int i); class C { static void Main(string[] args) { del p = x => { goto label1; label1: // invalid return x * x; }; label1: return; } } "; CreateCompilation(text). VerifyDiagnostics( // (10,9): error CS0158: The label 'label1' shadows another label by the same name in a contained scope // label1: // invalid Diagnostic(ErrorCode.ERR_LabelShadow, "label1").WithArguments("label1"), // (13,5): warning CS0164: This label has not been referenced // label1: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "label1") ); } [WorkItem(539875, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539875")] [Fact] public void CS0159ERR_LabelNotFound() { var text = @" public class Cls { public static void Main() { goto Label2; } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_LabelNotFound, Line = 6, Column = 14 } }); } [WorkItem(528799, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528799")] [Fact()] public void CS0159ERR_LabelNotFound_2() { var text = @" class Program { static void Main(string[] args) { int s = 23; switch (s) { case 21: break; case 23: goto default; } } } "; CreateCompilation(text).VerifyDiagnostics( // (12,17): error CS0159: No such label 'default:' within the scope of the goto statement // goto default; Diagnostic(ErrorCode.ERR_LabelNotFound, "goto default;").WithArguments("default:"), // (11,13): error CS8070: Control cannot fall out of switch from final case label ('case 23:') // case 23: Diagnostic(ErrorCode.ERR_SwitchFallOut, "case 23:").WithArguments("case 23:")); } [WorkItem(539876, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539876")] [Fact] public void CS0159ERR_LabelNotFound_3() { var text = @" class Program { static void Main(string[] args) { goto Label; } public static void Goo() { Label: ; } } "; CreateCompilation(text). VerifyDiagnostics(Diagnostic(ErrorCode.ERR_LabelNotFound, "Label").WithArguments("Label"), Diagnostic(ErrorCode.WRN_UnreferencedLabel, "Label")); } [WorkItem(539876, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539876")] [Fact] public void CS0159ERR_LabelNotFound_4() { var text = @" class Program { static void Main(string[] args) { for (int i = 0; i < 10; i++) { Label: i++; } goto Label; } } "; CreateCompilation(text). VerifyDiagnostics(Diagnostic(ErrorCode.ERR_LabelNotFound, "Label").WithArguments("Label"), Diagnostic(ErrorCode.WRN_UnreferencedLabel, "Label")); } [WorkItem(539876, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539876")] [Fact] public void CS0159ERR_LabelNotFound_5() { var text = @" class Program { static void Main(string[] args) { if (true) { Label1: goto Label2; } else { Label2: goto Label1; } } } "; CreateCompilation(text). VerifyDiagnostics(Diagnostic(ErrorCode.ERR_LabelNotFound, "Label2").WithArguments("Label2"), Diagnostic(ErrorCode.ERR_LabelNotFound, "Label1").WithArguments("Label1"), Diagnostic(ErrorCode.WRN_UnreachableCode, "Label2"), Diagnostic(ErrorCode.WRN_UnreferencedLabel, "Label1"), Diagnostic(ErrorCode.WRN_UnreferencedLabel, "Label2")); } [WorkItem(539876, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539876")] [Fact] public void CS0159ERR_LabelNotFound_6() { var text = @" class Program { static void Main(string[] args) { { goto L; } { L: return; } } } "; CreateCompilation(text). VerifyDiagnostics(Diagnostic(ErrorCode.ERR_LabelNotFound, "L").WithArguments("L"), Diagnostic(ErrorCode.WRN_UnreferencedLabel, "L")); } [WorkItem(539876, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539876")] [Fact] public void CS0159ERR_LabelNotFound_7() { var text = @" class Program { static void Main(string[] args) { int i = 3; if (true) { label1: goto label3; if (!false) { label2: goto label5; if (i > 2) { label3: goto label2; if (i == 3) { label4: if (i < 5) { label5: if (i == 4) { } else { System.Console.WriteLine(""a""); } } } } } } } } "; CreateCompilation(text). VerifyDiagnostics(Diagnostic(ErrorCode.ERR_LabelNotFound, "label3").WithArguments("label3"), Diagnostic(ErrorCode.ERR_LabelNotFound, "label5").WithArguments("label5"), Diagnostic(ErrorCode.WRN_UnreachableCode, "if"), Diagnostic(ErrorCode.WRN_UnreachableCode, "label4"), Diagnostic(ErrorCode.WRN_UnreachableCode, "label5"), Diagnostic(ErrorCode.WRN_UnreferencedLabel, "label1"), Diagnostic(ErrorCode.WRN_UnreferencedLabel, "label3"), Diagnostic(ErrorCode.WRN_UnreferencedLabel, "label4"), Diagnostic(ErrorCode.WRN_UnreferencedLabel, "label5")); } [WorkItem(540818, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540818")] [Fact] public void CS0159ERR_LabelNotFound_8() { var text = @" delegate int del(int i); class C { static void Main(string[] args) { del q = x => { goto label2; // invalid return x * x; }; label2: return; } } "; CreateCompilation(text). VerifyDiagnostics( // (10,17): warning CS0162: Unreachable code detected // return x * x; Diagnostic(ErrorCode.WRN_UnreachableCode, "return"), // (9,17): error CS0159: No such label 'label2' within the scope of the goto statement // goto label2; // invalid Diagnostic(ErrorCode.ERR_LabelNotFound, "goto").WithArguments("label2"), // (12,5): warning CS0164: This label has not been referenced // label2: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "label2") ); } [WorkItem(539876, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539876")] [Fact] public void CS0159ERR_LabelNotFound_9() { var text = @" public class Test { static public void Main(string[] args) { string[] S = new string[] { ""ABC"", ""XYZ"" }; foreach (string x in S) { goto innerLoop; foreach (char y in x) { innerLoop: return; } } } } "; CreateCompilation(text). VerifyDiagnostics(Diagnostic(ErrorCode.ERR_LabelNotFound, "innerLoop").WithArguments("innerLoop"), Diagnostic(ErrorCode.WRN_UnreferencedLabel, "innerLoop")); } [Fact] public void CS0160ERR_UnreachableCatch() { var text = @"using System; using System.IO; class A : Exception { } class B : A { } class C : IOException { } interface I { } class D : Exception, I { } class E : IOException, I { } class F<T> : Exception { } class Program { static void M() { try { } catch (A) { } catch (D) { } catch (E) { } catch (IOException) { } catch (C) { } catch (F<bool>) { } catch (F<int>) { } catch (Exception) { } catch (B) { } catch (StackOverflowException) { } catch (F<int>) { } catch (F<float>) { } } } "; CreateCompilation(text).VerifyDiagnostics( Diagnostic(ErrorCode.ERR_UnreachableCatch, "C").WithArguments("System.IO.IOException").WithLocation(19, 16), Diagnostic(ErrorCode.ERR_UnreachableCatch, "B").WithArguments("A").WithLocation(23, 16), Diagnostic(ErrorCode.ERR_UnreachableCatch, "StackOverflowException").WithArguments("System.Exception").WithLocation(24, 16), Diagnostic(ErrorCode.ERR_UnreachableCatch, "F<int>").WithArguments("F<int>").WithLocation(25, 16), Diagnostic(ErrorCode.ERR_UnreachableCatch, "F<float>").WithArguments("System.Exception").WithLocation(26, 16)); } [Fact] public void CS0160ERR_UnreachableCatch_Filter1() { var text = @" using System; class A : Exception { } class B : A { } class Program { static void M() { int a = 1; try { } catch when (a == 1) { } catch (Exception e) when (e.Message == null) { } catch (A) { } catch (B e) when (e.Message == null) { } } } "; CreateCompilation(text).VerifyDiagnostics( // (15,16): error CS0160: A previous catch clause already catches all exceptions of this or of a super type ('A') // catch (B e) when (e.Message == null) { } Diagnostic(ErrorCode.ERR_UnreachableCatch, "B").WithArguments("A").WithLocation(15, 16)); } [Fact] public void CS8359WRN_FilterIsConstantFalse_NonBoolean() { // Non-boolean constant filters are not considered for WRN_FilterIsConstant warnings. var text = @" using System; class A : Exception { } class B : A { } class Program { static void M() { try { } catch (A) when (1) { } catch (B) when (0) { } catch (B) when (""false"") { } catch (B) when (false) { } } } "; CreateCompilation(text).VerifyDiagnostics( // (11,25): error CS0029: Cannot implicitly convert type 'int' to 'bool' // catch (A) when (1) { } Diagnostic(ErrorCode.ERR_NoImplicitConv, "1").WithArguments("int", "bool").WithLocation(11, 25), // (12,25): error CS0029: Cannot implicitly convert type 'int' to 'bool' // catch (B) when (0) { } Diagnostic(ErrorCode.ERR_NoImplicitConv, "0").WithArguments("int", "bool").WithLocation(12, 25), // (13,25): error CS0029: Cannot implicitly convert type 'string' to 'bool' // catch (B) when ("false") { } Diagnostic(ErrorCode.ERR_NoImplicitConv, @"""false""").WithArguments("string", "bool").WithLocation(13, 25), // (14,25): warning CS8359: Filter expression is a constant 'false', consider removing the catch clause // catch (B) when (false) { } Diagnostic(ErrorCode.WRN_FilterIsConstantFalse, "false").WithLocation(14, 25)); } [Fact] public void CS8359WRN_FilterIsConstantFalse1() { var text = @" using System; class A : Exception { } class B : A { } class Program { static void M() { try { } catch (A) when (false) { } catch (B) when (false) { } } } "; CreateCompilation(text).VerifyDiagnostics( // (11,25): warning CS8359: Filter expression is a constant 'false', consider removing the catch clause // catch (A) when (false) { } Diagnostic(ErrorCode.WRN_FilterIsConstantFalse, "false").WithLocation(11, 25), // (12,25): warning CS8359: Filter expression is a constant 'false', consider removing the catch clause // catch (B) when (false) { } Diagnostic(ErrorCode.WRN_FilterIsConstantFalse, "false").WithLocation(12, 25)); } [Fact] public void CS8359WRN_FilterIsConstantFalse2() { var text = @" using System; class A : Exception { } class B : A { } class Program { static void M() { try { } catch (A) when ((1+1)!=2) { } catch (B) when (false) { } } } "; CreateCompilation(text).VerifyDiagnostics( // (11,25): warning CS8359: Filter expression is a constant 'false', consider removing the catch clause // catch (A) when (false) { } Diagnostic(ErrorCode.WRN_FilterIsConstantFalse, "(1+1)!=2").WithLocation(11, 25), // (12,25): warning CS8359: Filter expression is a constant 'false', consider removing the catch clause // catch (B) when (false) { } Diagnostic(ErrorCode.WRN_FilterIsConstantFalse, "false").WithLocation(12, 25)); } [Fact] public void CS8359WRN_FilterIsConstantFalse3() { var text = @" using System; class A : Exception { } class Program { static void M() { try { } catch (A) when (false) { } finally { } } } "; CreateCompilation(text).VerifyDiagnostics( // (11,25): warning CS8359: Filter expression is a constant 'false', consider removing the catch clause // catch (A) when (false) { } Diagnostic(ErrorCode.WRN_FilterIsConstantFalse, "false").WithLocation(10, 25)); } [Fact] public void CS8360WRN_FilterIsConstantRedundantTryCatch1() { var text = @" using System; class A : Exception { } class Program { static void M() { try { } catch (A) when (false) { } } } "; CreateCompilation(text).VerifyDiagnostics( // (11,25): warning CS8360: Filter expression is a constant 'false', consider removing the try-catch block // catch (A) when (false) { } Diagnostic(ErrorCode.WRN_FilterIsConstantFalseRedundantTryCatch, "false").WithLocation(10, 25)); } [Fact] public void CS8360WRN_FilterIsConstantRedundantTryCatch2() { var text = @" using System; class A : Exception { } class Program { static void M() { try { } catch (A) when ((1+1)!=2) { } } } "; CreateCompilation(text).VerifyDiagnostics( // (11,25): warning CS8360: Filter expression is a constant 'false', consider removing the try-catch block // catch (A) when (false) { } Diagnostic(ErrorCode.WRN_FilterIsConstantFalseRedundantTryCatch, "(1+1)!=2").WithLocation(10, 25)); } [Fact] public void CS7095WRN_FilterIsConstantTrue1() { var text = @" using System; class A : Exception { } class B : A { } class Program { static void M() { try { } catch (A) when (true) { } catch (B) { } } } "; CreateCompilation(text).VerifyDiagnostics( // (11,25): warning CS7095: Filter expression is a constant 'true', consider removing the filter // catch (A) when (true) { } Diagnostic(ErrorCode.WRN_FilterIsConstantTrue, "true").WithLocation(11, 25)); } [Fact] public void CS7095WRN_FilterIsConstantTrue2() { var text = @" using System; class A : Exception { } class Program { static void M() { try { } catch when (true) { } catch (A) { } catch when (false) { } } } "; CreateCompilation(text).VerifyDiagnostics( // (10,19): warning CS7095: Filter expression is a constant 'true', consider removing the filter // catch when (true) { } Diagnostic(ErrorCode.WRN_FilterIsConstantTrue, "true").WithLocation(10, 21), // (12,19): warning CS8359: Filter expression is a constant 'false', consider removing the catch clause // catch when (false) { } Diagnostic(ErrorCode.WRN_FilterIsConstantFalse, "false").WithLocation(12, 21)); } [Fact] public void CS7095WRN_FilterIsConstantTrue3() { var text = @" using System; class A : Exception { } class Program { static void M() { try { } catch when ((1+1)==2) { } } } "; CreateCompilation(text).VerifyDiagnostics( // (10,19): warning CS7095: Filter expression is a constant 'true', consider removing the filter // catch when (true) { } Diagnostic(ErrorCode.WRN_FilterIsConstantTrue, "(1+1)==2").WithLocation(10, 21)); } [Fact] public void CS0162WRN_UnreachableCode_Filter_ConstantCondition() { var text = @" using System; class A : Exception { } class B : A { } class Program { static void M() { try { } catch (A) when (false) { Console.WriteLine(1); } catch (B) { } } } "; CreateCompilation(text).VerifyDiagnostics( // (11,25): warning CS8359: Filter expression is a constant 'false', consider removing the catch clause // catch (A) when (false) Diagnostic(ErrorCode.WRN_FilterIsConstantFalse, "false").WithLocation(11, 25), // (13,13): warning CS0162: Unreachable code detected // Console.WriteLine(1); Diagnostic(ErrorCode.WRN_UnreachableCode, "Console").WithLocation(13, 13) ); } [Fact] public void CS0162WRN_UnreachableCode_Filter_ConstantCondition2() { var text = @" using System; class Program { static void M() { int x; try { } catch (Exception) when (false) { Console.WriteLine(x); } } } "; // Unlike an unreachable code in if statement block we don't allow using // a variable that's not definitely assigned. The reason why we allow it in an if statement // is to make conditional compilation easier. Such scenario doesn't apply to filters. CreateCompilation(text).VerifyDiagnostics( // (10,33): warning CS7105: Filter expression is a constant 'false', consider removing the try-catch block // catch (Exception) when (false) Diagnostic(ErrorCode.WRN_FilterIsConstantFalseRedundantTryCatch, "false").WithLocation(10, 33), // (12,13): warning CS0162: Unreachable code detected // Console.WriteLine(x); Diagnostic(ErrorCode.WRN_UnreachableCode, "Console").WithLocation(12, 13) ); } [Fact] public void CS0162WRN_UnreachableCode_Filter_ConstantCondition3() { var text = @" using System; class Program { static void M() { int x; try { } catch (Exception) when (true) { Console.WriteLine(x); } } } "; // Unlike an unreachable code in if statement block we don't allow using // a variable that's not definitely assigned. The reason why we allow it in an if statement // is to make conditional compilation easier. Such scenario doesn't apply to filters. CreateCompilation(text).VerifyDiagnostics( // (10,33): warning CS7095: Filter expression is a constant 'true', consider removing the filter // catch (Exception) when (true) Diagnostic(ErrorCode.WRN_FilterIsConstantTrue, "true").WithLocation(10, 33), // (12,31): error CS0165: Use of unassigned local variable 'x' // Console.WriteLine(x); Diagnostic(ErrorCode.ERR_UseDefViolation, "x").WithArguments("x").WithLocation(12, 31) ); } [Fact] public void CS0160ERR_UnreachableCatch_Dynamic() { string source = @" using System; public class EG<T> : Exception { } public class A { public void M1() { try { Goo(); } catch (EG<object>) { } catch (EG<dynamic>) { } } void Goo() { } }"; CreateCompilation(source).VerifyDiagnostics( // (17,16): error CS0160: A previous catch clause already catches all exceptions of this or of a super type ('EG<object>') Diagnostic(ErrorCode.ERR_UnreachableCatch, "EG<dynamic>").WithArguments("EG<object>")); } [Fact] public void CS0160ERR_UnreachableCatch_TypeParameter() { string source = @" using System; public class EA : Exception { } public class EB : EA { } public class A<T> where T : EB { public void M1() { try { Goo(); } catch (EA) { } catch (T) { } } void Goo() { } }"; CreateCompilation(source).VerifyDiagnostics( // (18,16): error CS0160: A previous catch clause already catches all exceptions of this or of a super type ('EA') Diagnostic(ErrorCode.ERR_UnreachableCatch, "T").WithArguments("EA")); } [Fact] public void CS0160ERR_UnreachableCatch_TypeParameter_Dynamic1() { string source = @" using System; public class EG<T> : Exception { } public abstract class A<T> { public abstract void M<U>() where U : T; } public class B<V> : A<EG<dynamic>> where V : EG<object> { public override void M<U>() { try { Goo(); } catch (EG<dynamic>) { } catch (V) { } catch (U) { } } void Goo() { } } "; CreateCompilationWithMscorlib40AndSystemCore(source).VerifyDiagnostics( // (22,16): error CS0160: A previous catch clause already catches all exceptions of this or of a super type ('EG<dynamic>') Diagnostic(ErrorCode.ERR_UnreachableCatch, "V").WithArguments("EG<dynamic>"), // (25,16): error CS0160: A previous catch clause already catches all exceptions of this or of a super type ('EG<dynamic>') Diagnostic(ErrorCode.ERR_UnreachableCatch, "U").WithArguments("EG<dynamic>")); } [Fact] public void TypeParameter_DynamicConversions() { string source = @" using System; public class EG<T> : Exception { } public abstract class A<T> { public abstract void M<U>() where U : T; } public class B<V> : A<EG<dynamic>> where V : EG<object> { public override void M<U>() { V v = default(V); U u = default(U); // implicit EG<dynamic> egd = v; // implicit egd = u; //explicit v = (V)egd; //explicit u = (U)egd; //implicit array V[] va = null; EG<dynamic>[] egda = va; // explicit array va = (V[])egda; } void Goo() { } } "; CreateCompilationWithMscorlib40AndSystemCore(source).VerifyDiagnostics(); } [Fact] public void CS0160ERR_UnreachableCatch_TypeParameter_Dynamic2() { string source = @" using System; public class EG<T> : Exception { } public abstract class A<T> { public abstract void M<U>() where U : T; } public class B<V> : A<EG<dynamic>> where V : EG<object> { public override void M<U>() { try { Goo(); } catch (EG<object>) { } catch (V) { } catch (U) { } } void Goo() { } } "; CreateCompilationWithMscorlib40AndSystemCore(source).VerifyDiagnostics( // (22,16): error CS0160: A previous catch clause already catches all exceptions of this or of a super type ('EG<object>') Diagnostic(ErrorCode.ERR_UnreachableCatch, "V").WithArguments("EG<object>"), // (25,16): error CS0160: A previous catch clause already catches all exceptions of this or of a super type ('EG<object>') Diagnostic(ErrorCode.ERR_UnreachableCatch, "U").WithArguments("EG<object>")); } [Fact] public void CS0161ERR_ReturnExpected() { var text = @" public class Test { public static int Main() // CS0161 { int i = 10; if (i < 10) { return i; } else { // uncomment the following line to resolve // return 1; } } }"; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_ReturnExpected, Line = 4, Column = 22 } }); } [Fact] public void CS0163ERR_SwitchFallThrough() { var text = @" public class MyClass { public static void Main() { int i = 0; switch (i) // CS0163 { case 1: i++; // uncomment one of the following lines to resolve // return; // break; // goto case 3; case 2: i++; return; case 3: i = 0; return; } } }"; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_SwitchFallThrough, Line = 10, Column = 10 } }); } [Fact] public void CS0165ERR_UseDefViolation01() { var text = @" class MyClass { public int i; } class MyClass2 { public static void Main(string [] args) { int i, j; if (args[0] == ""test"") { i = 0; } /* // to resolve, either initialize the variables when declared // or provide for logic to initialize them, as follows: else { i = 1; } */ j = i; // CS0165, i might be uninitialized MyClass myClass; myClass.i = 0; // CS0165 // use new as follows // MyClass myClass = new MyClass(); // myClass.i = 0; i = j; } }"; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_UseDefViolation, Line = 26, Column = 11 } , new ErrorDescription { Code = (int)ErrorCode.ERR_UseDefViolation, Line = 29, Column = 7 }}); } [Fact] public void CS0165ERR_UseDefViolation02() { CreateCompilation( @"class C { static void M(int m) { int v; for (int i = 0; i < m; ++i) { v = 0; } M(v); int w; for (; ; ) { w = 0; break; } M(w); for (int x; x < 1; ++x) { } for (int y; m < 1; ++y) { } for (int z; ; ) { M(z); } } } ") .VerifyDiagnostics( Diagnostic(ErrorCode.ERR_UseDefViolation, "v").WithArguments("v").WithLocation(10, 11), Diagnostic(ErrorCode.ERR_UseDefViolation, "x").WithArguments("x").WithLocation(18, 21), Diagnostic(ErrorCode.ERR_UseDefViolation, "y").WithArguments("y").WithLocation(21, 30), Diagnostic(ErrorCode.ERR_UseDefViolation, "z").WithArguments("z").WithLocation(26, 15)); } [Fact] public void CS0165ERR_UseDefViolation03() { CreateCompilation( @"class C { static int F() { return 0; } static void M0() { int a, b, c, d; for (a = 1; (b = F()) < 2; c = 3) { d = 4; } if (a == 0) { } if (b == 0) { } if (c == 0) { } // Use of unassigned 'c' if (d == 0) { } // Use of unassigned 'd' } static void M1() { int x, y; for (x = 0; (y = x) < 10; ) { } if (y == 0) { } // no error } static void M2() { int x, y; for (x = 0; x < 10; y = x) { } if (y == 0) { } // Use of unassigned 'y' } static void M3() { int x, y; for (x = 0; x < 10; ) { y = x; } if (y == 0) { } // Use of unassigned 'y' } static void M4() { int x, y; for (y = x; (x = 0) < 10; ) { } // Use of unassigned 'x' if (y == 0) { } // no error } static void M5() { int x, y; for (; (x = 0) < 10; y = x) { } if (y == 0) { } // Use of unassigned 'y' } static void M6() { int x, y; for (; (x = 0) < 10; ) { y = x; } if (y == 0) { } // Use of unassigned 'y' } static void M7() { int x, y; for (y = x; F() < 10; x = 0) { } // Use of unassigned 'x' if (y == 0) { } // no error } static void M8() { int x, y; for (; (y = x) < 10; x = 0) { } // Use of unassigned 'x' if (y == 0) { } // no error } static void M9() { int x, y; for (; F() < 10; x = 0) { y = x; } // Use of unassigned 'x' if (y == 0) { } // no error } static void M10() { int x, y; for (y = x; F() < 10; ) { x = 0; } // Use of unassigned 'x' if (y == 0) { } // no error } static void M11() { int x, y; for (; F() < 10; y = x) { x = 0; } if (y == 0) { } // Use of unassigned 'y' } } ") .VerifyDiagnostics( Diagnostic(ErrorCode.ERR_UseDefViolation, "c").WithArguments("c").WithLocation(13, 13), Diagnostic(ErrorCode.ERR_UseDefViolation, "d").WithArguments("d").WithLocation(14, 13), Diagnostic(ErrorCode.ERR_UseDefViolation, "y").WithArguments("y").WithLocation(26, 13), Diagnostic(ErrorCode.ERR_UseDefViolation, "y").WithArguments("y").WithLocation(32, 13), Diagnostic(ErrorCode.ERR_UseDefViolation, "x").WithArguments("x").WithLocation(37, 18), Diagnostic(ErrorCode.ERR_UseDefViolation, "y").WithArguments("y").WithLocation(44, 13), Diagnostic(ErrorCode.ERR_UseDefViolation, "y").WithArguments("y").WithLocation(50, 13), Diagnostic(ErrorCode.ERR_UseDefViolation, "x").WithArguments("x").WithLocation(55, 18), Diagnostic(ErrorCode.ERR_UseDefViolation, "x").WithArguments("x").WithLocation(61, 21), Diagnostic(ErrorCode.ERR_UseDefViolation, "x").WithArguments("x").WithLocation(67, 39), Diagnostic(ErrorCode.ERR_UseDefViolation, "y").WithArguments("y").WithLocation(68, 13), Diagnostic(ErrorCode.ERR_UseDefViolation, "x").WithArguments("x").WithLocation(73, 18), Diagnostic(ErrorCode.ERR_UseDefViolation, "y").WithArguments("y").WithLocation(80, 13)); } [Fact] public void CS0165ERR_UseDefViolation04() { CreateCompilation( @"class C { static int M() { int x, y, z; try { x = 0; y = 1; } catch (System.Exception) { x = 1; } finally { z = 1; } return (x + y + z); } }") .VerifyDiagnostics( Diagnostic(ErrorCode.ERR_UseDefViolation, "y").WithArguments("y").WithLocation(19, 21)); } [Fact] public void CS0165ERR_UseDefViolation05() { // This is a "negative" test case; we should *not* be producing a "use of unassigned // local variable" error here. In an earlier revision we were doing so because we were // losing the information about the first argument being "out" when the bad call node // was created. Later flow analysis then did not know that "x" need not be assigned // before it was used, and we'd produce a wrong error. CreateCompilation( @"class C { static int N(out int q) { q = 1; return 2;} static void M() { int x = N(out x, 123); } } ") .VerifyDiagnostics( Diagnostic(ErrorCode.ERR_BadArgCount, "N").WithArguments("N", "2")); } [WorkItem(540860, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540860")] [Fact] public void CS0165ERR_UseDefViolation06() { // Should not generate "unassigned local variable" for struct. CreateCompilation( @"struct S { public void M() { } } class C { void M() { S s; s.M(); } }") .VerifyDiagnostics(); } [Fact] public void CS0165ERR_UseDefViolation07() { // Make sure flow analysis is hooked up for indexers CreateCompilation( @"struct S { public int this[int x] { get { return 0; } } } class C { public int this[int x] { get { return 0; } } } class Test { static void Main() { int unassigned1; int unassigned2; int sink; C c; sink = c[1]; //CS0165 c = new C(); sink = c[1]; //fine sink = c[unassigned1]; //CS0165 S s; sink = s[1]; //fine - struct with no fields s = new S(); sink = s[1]; //fine sink = s[unassigned2]; //CS0165 } }") .VerifyDiagnostics( // (18,16): error CS0165: Use of unassigned local variable 'c' Diagnostic(ErrorCode.ERR_UseDefViolation, "c").WithArguments("c"), // (22,18): error CS0165: Use of unassigned local variable 'unassigned1' Diagnostic(ErrorCode.ERR_UseDefViolation, "unassigned1").WithArguments("unassigned1"), // (29,18): error CS0165: Use of unassigned local variable 'unassigned2' Diagnostic(ErrorCode.ERR_UseDefViolation, "unassigned2").WithArguments("unassigned2")); } [WorkItem(3402, "DevDiv_Projects/Roslyn")] [Fact] public void CS0170ERR_UseDefViolationField() { var text = @" public struct error { public int i; } public class MyClass { public static void Main() { error e; // uncomment the next line to resolve this error // e.i = 0; System.Console.WriteLine( e.i ); // CS0170 because //e.i was never assigned } }"; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_UseDefViolationField, Line = 14, Column = 33 } }); } [Fact] public void CS0171ERR_UnassignedThis() { var text = @" struct MyStruct { MyStruct(int initField) // CS0171 { // i = initField; // uncomment this line to resolve this error } public int i; } class MyClass { public static void Main() { MyStruct aStruct = new MyStruct(); } }"; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (4,4): error CS0171: Field 'MyStruct.i' must be fully assigned before control is returned to the caller // MyStruct(int initField) // CS0171 Diagnostic(ErrorCode.ERR_UnassignedThis, "MyStruct").WithArguments("MyStruct.i"), // (15,16): warning CS0219: The variable 'aStruct' is assigned but its value is never used // MyStruct aStruct = new MyStruct(); Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "aStruct").WithArguments("aStruct"), // (8,15): warning CS0649: Field 'MyStruct.i' is never assigned to, and will always have its default value 0 // public int i; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "i").WithArguments("MyStruct.i", "0") ); } [Fact] public void FieldAssignedInReferencedConstructor() { var text = @"struct S { private readonly object _x; S(object o) { _x = o; } S(object x, object y) : this(x ?? y) { } }"; var comp = CreateCompilation(text); comp.VerifyDiagnostics(); // No CS0171 for S._x } [Fact()] public void CS0172ERR_AmbigQM() { var text = @" public class Square { public class Circle { public static implicit operator Circle(Square aa) { return null; } public static implicit operator Square(Circle aa) { return null; } } public static void Main() { Circle aa = new Circle(); Square ii = new Square(); var o1 = (1 == 1) ? aa : ii; // CS0172 object o2 = (1 == 1) ? aa : ii; // CS8652 } }"; CreateCompilation(text, parseOptions: TestOptions.Regular8).VerifyDiagnostics( // (21,16): error CS0172: Type of conditional expression cannot be determined because 'Square.Circle' and 'Square' implicitly convert to one another // var o1 = (1 == 1) ? aa : ii; // CS0172 Diagnostic(ErrorCode.ERR_AmbigQM, "(1 == 1) ? aa : ii").WithArguments("Square.Circle", "Square").WithLocation(21, 16), // (22,19): error CS8957: Conditional expression is not valid in language version 8.0 because a common type was not found between 'Square.Circle' and 'Square'. To use a target-typed conversion, upgrade to language version 9.0 or greater. // object o2 = (1 == 1) ? aa : ii; // CS8652 Diagnostic(ErrorCode.ERR_NoImplicitConvTargetTypedConditional, "(1 == 1) ? aa : ii").WithArguments("8.0", "Square.Circle", "Square", "9.0").WithLocation(22, 19) ); } [Fact] public void CS0173ERR_InvalidQM() { var text = @" public class C {} public class A {} public class MyClass { public static void F(bool b) { A a = new A(); C c = new C(); var o = b ? a : c; // CS0173 } public static void Main() { F(true); } }"; CreateCompilation(text).VerifyDiagnostics( // (11,15): error CS0173: Type of conditional expression cannot be determined because there is no implicit conversion between 'A' and 'C' // var o = b ? a : c; // CS0173 Diagnostic(ErrorCode.ERR_InvalidQM, "b ? a : c").WithArguments("A", "C").WithLocation(11, 15) ); } [WorkItem(528331, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528331")] [Fact] public void CS0173ERR_InvalidQM_FuncCall() { var text = @" class Program { static void Main(string[] args) { var s = true ? System.Console.WriteLine(0) : System.Console.WriteLine(1); } }"; CreateCompilation(text). VerifyDiagnostics(Diagnostic(ErrorCode.ERR_ImplicitlyTypedVariableAssignedBadValue, "s = true ? System.Console.WriteLine(0) : System.Console.WriteLine(1)").WithArguments("void").WithLocation(6, 13)); } [Fact] public void CS0173ERR_InvalidQM_GeneralType() { var text = @" class Program { static void Main(string[] args) { A<string> a = new A<string>(); A<int> b = new A<int>(); var o = 1 > 2 ? a : b; // Invalid, Can't implicit convert } } class A<T> { }"; CreateCompilation(text).VerifyDiagnostics( // (8,17): error CS0173: Type of conditional expression cannot be determined because there is no implicit conversion between 'A<string>' and 'A<int>' // var o = 1 > 2 ? a : b; // Invalid, Can't implicit convert Diagnostic(ErrorCode.ERR_InvalidQM, "1 > 2 ? a : b").WithArguments("A<string>", "A<int>").WithLocation(8, 17) ); } [WorkItem(540902, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540902")] [Fact] public void CS0173ERR_InvalidQM_foreach() { var text = @" public class Test { public static void Main() { S[] x = null; foreach (S x in true ? x : 1) // Dev10: CS0173 ONLY { } C[] y= null; foreach (C c in false ? 1 : y) // Dev10: CS0173 ONLY { } } } struct S { } class C { } "; CreateCompilation(text).VerifyDiagnostics( // (7,25): error CS0173: Type of conditional expression cannot be determined because there is no implicit conversion between 'S[]' and 'int' // foreach (S x in true ? x : 1) // Dev10: CS0173 ONLY Diagnostic(ErrorCode.ERR_InvalidQM, "true ? x : 1").WithArguments("S[]", "int"), // (7,20): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // foreach (S x in true ? x : 1) // Dev10: CS0173 ONLY Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x"), // (11,25): error CS0173: Type of conditional expression cannot be determined because there is no implicit conversion between 'int' and 'C[]' // foreach (C c in false ? 1 : y) // Dev10: CS0173 ONLY Diagnostic(ErrorCode.ERR_InvalidQM, "false ? 1 : y").WithArguments("int", "C[]") ); } // /// Scenarios? // [Fact] // public void CS0174ERR_NoBaseClass() // { // var text = @" // "; // CreateCompilationWithMscorlib(text).VerifyDiagnostics(Diagnostic(ErrorCode.ERR_NoBaseClass, "?")); // } [WorkItem(543360, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543360")] [Fact()] public void CS0175ERR_BaseIllegal() { var text = @" using System; class Base { public int TestInt = 0; } class MyClass : Base { public void BaseTest() { Console.WriteLine(base); // CS0175 base = 9; // CS0175 } } "; CreateCompilation(text).VerifyDiagnostics( // (11,27): error CS0175: Use of keyword 'base' is not valid in this context Diagnostic(ErrorCode.ERR_BaseIllegal, "base").WithLocation(12, 27), // (12,9): error CS0175: Use of keyword 'base' is not valid in this context Diagnostic(ErrorCode.ERR_BaseIllegal, "base").WithLocation(13, 9) ); } [WorkItem(528624, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528624")] [Fact()] public void CS0175ERR_BaseIllegal_02() { var text = @" using System.Collections.Generic; class MyClass : List<int> { public void BaseTest() { var x = from i in base select i; } } "; CreateCompilation(text).VerifyDiagnostics( // (8,27): error CS0175: Use of keyword 'base' is not valid in this context // var x = from i in base select i; Diagnostic(ErrorCode.ERR_BaseIllegal, "base") ); } [Fact] public void CS0176ERR_ObjectProhibited01() { var source = @" class A { class B { static void Method() { } void M() { this.Method(); } } }"; CreateCompilation(source).VerifyDiagnostics( // (9,13): error CS0176: Member 'A.B.Method()' cannot be accessed with an instance reference; qualify it with a type name instead // this.Method(); Diagnostic(ErrorCode.ERR_ObjectProhibited, "this.Method").WithArguments("A.B.Method()").WithLocation(9, 13) ); } [Fact] public void CS0176ERR_ObjectProhibited02() { var source = @" class C { static object field; static object Property { get; set; } void M(C c) { Property = field; // no error C.Property = C.field; // no error this.field = this.Property; c.Property = c.field; } } "; CreateCompilation(source).VerifyDiagnostics( // (9,9): error CS0176: Member 'C.field' cannot be accessed with an instance reference; qualify it with a type name instead // this.field = this.Property; Diagnostic(ErrorCode.ERR_ObjectProhibited, "this.field").WithArguments("C.field"), // (9,22): error CS0176: Member 'C.Property' cannot be accessed with an instance reference; qualify it with a type name instead // this.field = this.Property; Diagnostic(ErrorCode.ERR_ObjectProhibited, "this.Property").WithArguments("C.Property"), // (10,9): error CS0176: Member 'C.Property' cannot be accessed with an instance reference; qualify it with a type name instead // c.Property = c.field; Diagnostic(ErrorCode.ERR_ObjectProhibited, "c.Property").WithArguments("C.Property"), // (10,22): error CS0176: Member 'C.field' cannot be accessed with an instance reference; qualify it with a type name instead // c.Property = c.field; Diagnostic(ErrorCode.ERR_ObjectProhibited, "c.field").WithArguments("C.field") ); } [Fact] public void CS0176ERR_ObjectProhibited03() { var source = @"class A { internal static object F; } class B<T> where T : A { static void M(T t) { object q = t.F; t.ReferenceEquals(q, null); } }"; CreateCompilation(source).VerifyDiagnostics( // (9,20): error CS0176: Member 'A.F' cannot be accessed with an instance reference; qualify it with a type name instead // object q = t.F; Diagnostic(ErrorCode.ERR_ObjectProhibited, "t.F").WithArguments("A.F").WithLocation(9, 20), // (10,9): error CS0176: Member 'object.ReferenceEquals(object, object)' cannot be accessed with an instance reference; qualify it with a type name instead // t.ReferenceEquals(q, null); Diagnostic(ErrorCode.ERR_ObjectProhibited, "t.ReferenceEquals").WithArguments("object.ReferenceEquals(object, object)").WithLocation(10, 9), // (3,28): warning CS0649: Field 'A.F' is never assigned to, and will always have its default value null // internal static object F; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "F").WithArguments("A.F", "null").WithLocation(3, 28)); } [WorkItem(543361, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543361")] [Fact] public void CS0176ERR_ObjectProhibited04() { var source = @" public delegate void D(); class Test { public event D D; public void TestIdenticalEventName() { D.CreateDelegate(null, null, null); // CS0176 } } "; CreateCompilation(source, targetFramework: TargetFramework.Mscorlib45).VerifyDiagnostics( // (9,9): error CS0176: Member 'Delegate.CreateDelegate(Type, object, string)' cannot be accessed with an instance reference; qualify it with a type name instead // D.CreateDelegate(null, null, null); // CS0176 Diagnostic(ErrorCode.ERR_ObjectProhibited, "D.CreateDelegate").WithArguments("System.Delegate.CreateDelegate(System.Type, object, string)").WithLocation(9, 9) ); } // Identical to CS0176ERR_ObjectProhibited04, but with event keyword removed (i.e. field instead of field-like event). [WorkItem(543361, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543361")] [Fact] public void CS0176ERR_ObjectProhibited05() { var source = @" public delegate void D(); class Test { public D D; public void TestIdenticalEventName() { D.CreateDelegate(null, null, null); // CS0176 } } "; CreateCompilation(source).VerifyDiagnostics( // (5,14): warning CS0649: Field 'Test.D' is never assigned to, and will always have its default value null // public D D; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "D").WithArguments("Test.D", "null") ); } [Fact] public void CS0177ERR_ParamUnassigned01() { var text = @"class C { static void M(out int x, out int y, out int z) { try { x = 0; y = 1; } catch (System.Exception) { x = 1; } finally { z = 1; } } }"; CreateCompilation(text).VerifyDiagnostics( Diagnostic(ErrorCode.ERR_ParamUnassigned, "M").WithArguments("y").WithLocation(3, 17)); } [WorkItem(528243, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528243")] [Fact] public void CS0177ERR_ParamUnassigned02() { var text = @"class C { static bool P { get { return false; } } static object M(out object x) { if (P) { object o = P ? M(out x) : null; return o; } return P ? null : M(out x); } }"; CreateCompilation(text).VerifyDiagnostics( // (9,13): error CS0177: The out parameter 'x' must be assigned to before control leaves the current method // return o; Diagnostic(ErrorCode.ERR_ParamUnassigned, "return o;").WithArguments("x").WithLocation(9, 13), // (11,9): error CS0177: The out parameter 'x' must be assigned to before control leaves the current method // return P ? null : M(out x); Diagnostic(ErrorCode.ERR_ParamUnassigned, "return P ? null : M(out x);").WithArguments("x").WithLocation(11, 9)); } [Fact] public void CS0185ERR_LockNeedsReference() { var text = @" public class MainClass { public static void Main () { lock (1) // CS0185 // try the following lines instead // MainClass x = new MainClass(); // lock(x) { } } }"; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_LockNeedsReference, Line = 6, Column = 15 } }); } [Fact] public void CS0186ERR_NullNotValid() { var text = @" using System.Collections; class MyClass { static void Main() { // Each of the following lines generates CS0186: foreach (int i in null) { } // CS0186 foreach (int i in (IEnumerable)null) { }; // CS0186 } }"; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_NullNotValid, Line = 9, Column = 27 } , new ErrorDescription { Code = (int)ErrorCode.ERR_NullNotValid, Line = 10, Column = 27 }}); } [Fact] public void CS0186ERR_NullNotValid02() { var text = @" public class Test { public static void Main(string[] args) { foreach (var x in default(int[])) { } } } "; CreateCompilation(text). VerifyDiagnostics(Diagnostic(ErrorCode.ERR_NullNotValid, "default(int[])")); } [WorkItem(540983, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540983")] [Fact] public void CS0188ERR_UseDefViolationThis() { var text = @" namespace MyNamespace { class MyClass { struct S { public int a; void Goo() { } S(int i) { // a = i; Goo(); // CS0188 } } public static void Main() { } } }"; CreateCompilation(text). VerifyDiagnostics( // (17,17): error CS0188: The 'this' object cannot be used before all of its fields are assigned to // Goo(); // CS0188 Diagnostic(ErrorCode.ERR_UseDefViolationThis, "Goo").WithArguments("this"), // (8,24): warning CS0649: Field 'MyNamespace.MyClass.S.a' is never assigned to, and will always have its default value 0 // public int a; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "a").WithArguments("MyNamespace.MyClass.S.a", "0")); } [Fact, WorkItem(579533, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/579533"), WorkItem(864605, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/864605")] public void CS0188ERR_UseDefViolationThis_MethodGroupInIsOperator_ImplicitReceiver() { string source = @" using System; struct S { int value; public S(int v) { var b1 = F is Action; value = v; } void F() { } }"; CreateCompilationWithMscorlib40AndSystemCore(source).VerifyDiagnostics( // (10,18): error CS0837: The first operand of an 'is' or 'as' operator may not be a lambda expression, anonymous method, or method group. Diagnostic(ErrorCode.ERR_LambdaInIsAs, "F is Action").WithLocation(10, 18), // (10,18): error CS0188: The 'this' object cannot be used before all of its fields are assigned to Diagnostic(ErrorCode.ERR_UseDefViolationThis, "F").WithArguments("this")); } [Fact, WorkItem(579533, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/579533"), WorkItem(864605, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/864605")] public void CS0188ERR_UseDefViolationThis_MethodGroupInIsOperator_ExplicitReceiver() { string source = @" using System; struct S { int value; public S(int v) { var b1 = this.F is Action; value = v; } void F() { } }"; CreateCompilationWithMscorlib40AndSystemCore(source).VerifyDiagnostics( // (10,18): error CS0837: The first operand of an 'is' or 'as' operator may not be a lambda expression, anonymous method, or method group. // var b1 = this.F is Action; Diagnostic(ErrorCode.ERR_LambdaInIsAs, "this.F is Action").WithLocation(10, 18), // (10,18): error CS0188: The 'this' object cannot be used before all of its fields are assigned to // var b1 = this.F is Action; Diagnostic(ErrorCode.ERR_UseDefViolationThis, "this").WithArguments("this")); } [Fact, WorkItem(579533, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/579533")] public void CS0188ERR_UseDefViolationThis_ImplicitReceiverInDynamic() { string source = @" using System; struct S { dynamic value; public S(dynamic d) { /*this.*/ Add(d); throw new NotImplementedException(); } void Add(int value) { this.value += value; } } "; CreateCompilationWithMscorlib40AndSystemCore(source).VerifyDiagnostics( // (10,19): error CS0188: The 'this' object cannot be used before all of its fields are assigned to Diagnostic(ErrorCode.ERR_UseDefViolationThis, "Add").WithArguments("this")); } [Fact, WorkItem(579533, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/579533")] public void CS0188ERR_UseDefViolationThis_ExplicitReceiverInDynamic() { string source = @" using System; struct S { dynamic value; public S(dynamic d) { this.Add(d); throw new NotImplementedException(); } void Add(int value) { this.value += value; } } "; CreateCompilationWithMscorlib40AndSystemCore(source).VerifyDiagnostics( // (10,9): error CS0188: The 'this' object cannot be used before all of its fields are assigned to Diagnostic(ErrorCode.ERR_UseDefViolationThis, "this").WithArguments("this")); } [Fact] public void CS0190ERR_ArgsInvalid() { string source = @" using System; public class C { static void M(__arglist) { ArgIterator ai = new ArgIterator(__arglist); } static void Main() { M(__arglist); } }"; var comp = CreateCompilation(source, targetFramework: TargetFramework.Mscorlib45); comp.VerifyDiagnostics( // (11,7): error CS0190: The __arglist construct is valid only within a variable argument method // M(__arglist); Diagnostic(ErrorCode.ERR_ArgsInvalid, "__arglist") ); } [Fact] public void CS4013ERR_SpecialByRefInLambda01() { // Note that the native compiler does *not* produce an error when you illegally // use __arglist inside a lambda, oddly enough. Roslyn does. string source = @" using System; using System.Linq; public class C { delegate int D(RuntimeArgumentHandle r); static void M(__arglist) { D f = null; f = x=>f(__arglist); f = delegate { return f(__arglist); }; var q = from x in new int[10] select f(__arglist); } static void Main() { } }"; var comp = CreateCompilationWithMscorlib40AndSystemCore(source); comp.VerifyDiagnostics( // (10,14): error CS4013: Instance of type 'System.RuntimeArgumentHandle' cannot be used inside an anonymous function, query expression, iterator block or async method // f = x=>f(__arglist); Diagnostic(ErrorCode.ERR_SpecialByRefInLambda, "__arglist").WithArguments("System.RuntimeArgumentHandle"), // (11,29): error CS4013: Instance of type 'System.RuntimeArgumentHandle' cannot be used inside an anonymous function, query expression, iterator block or async method // f = delegate { return f(__arglist); }; Diagnostic(ErrorCode.ERR_SpecialByRefInLambda, "__arglist").WithArguments("System.RuntimeArgumentHandle"), // (12,44): error CS4013: Instance of type 'System.RuntimeArgumentHandle' cannot be used inside an anonymous function, query expression, iterator block or async method // var q = from x in new int[10] select f(__arglist); Diagnostic(ErrorCode.ERR_SpecialByRefInLambda, "__arglist").WithArguments("System.RuntimeArgumentHandle") ); } [Fact] public void CS4013ERR_SpecialByRefInLambda02() { string source = @" using System; public class C { static void M(__arglist) { RuntimeArgumentHandle h = __arglist; Action action = ()=> { RuntimeArgumentHandle h2 = h; // Bad use of h ArgIterator args1 = new ArgIterator(h); // Bad use of h RuntimeArgumentHandle h3 = h2; // no error; does not create field ArgIterator args2 = new ArgIterator(h2); // no error; does not create field }; } static void Main() { } }"; CreateCompilationWithMscorlib45(source).VerifyEmitDiagnostics( // (10,34): error CS4013: Instance of type 'System.RuntimeArgumentHandle' cannot be used inside an anonymous function, query expression, iterator block or async method // RuntimeArgumentHandle h2 = h; // Bad use of h Diagnostic(ErrorCode.ERR_SpecialByRefInLambda, "h").WithArguments("System.RuntimeArgumentHandle"), // (11,43): error CS4013: Instance of type 'System.RuntimeArgumentHandle' cannot be used inside an anonymous function, query expression, iterator block or async method // ArgIterator args1 = new ArgIterator(h); // Bad use of h Diagnostic(ErrorCode.ERR_SpecialByRefInLambda, "h").WithArguments("System.RuntimeArgumentHandle")); } [Fact] public void CS4013ERR_SpecialByRefInLambda03() { string source = @" using System; using System.Collections.Generic; public class C { static void N(RuntimeArgumentHandle x) {} static IEnumerable<int> M(RuntimeArgumentHandle h1) // Error: hoisted to field { N(h1); yield return 1; RuntimeArgumentHandle h2 = default(RuntimeArgumentHandle); yield return 2; N(h2); // Error: hoisted to field yield return 3; RuntimeArgumentHandle h3 = default(RuntimeArgumentHandle); N(h3); // No error; we don't need to hoist this one to a field } static void Main() { } }"; CreateCompilation(source).Emit(new System.IO.MemoryStream()).Diagnostics .Verify( // (7,51): error CS4013: Instance of type 'System.RuntimeArgumentHandle' cannot be used inside an anonymous function, query expression, iterator block or async method // static IEnumerable<int> M(RuntimeArgumentHandle h1) // Error: hoisted to field Diagnostic(ErrorCode.ERR_SpecialByRefInLambda, "h1").WithArguments("System.RuntimeArgumentHandle"), // (13,7): error CS4013: Instance of type 'System.RuntimeArgumentHandle' cannot be used inside an anonymous function, query expression, iterator block or async method // N(h2); // Error: hoisted to field Diagnostic(ErrorCode.ERR_SpecialByRefInLambda, "h2").WithArguments("System.RuntimeArgumentHandle") ); } [Fact, WorkItem(538008, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538008")] public void CS0191ERR_AssgReadonly() { var source = @"class MyClass { public readonly int TestInt = 6; // OK to assign to readonly field in declaration public MyClass() { TestInt = 11; // OK to assign to readonly field in constructor TestInt = 12; // OK to assign to readonly field multiple times in constructor this.TestInt = 13; // OK to assign with explicit this receiver MyClass t = this; t.TestInt = 14; // CS0191 - we can't be sure that the receiver is this } public void TestReadOnly() { TestInt = 19; // CS0191 } public static void Main() { } } class MyDerived : MyClass { MyDerived() { TestInt = 15; // CS0191 - not in declaring class } } "; CreateCompilation(source).VerifyDiagnostics( // (28,9): error CS0191: A readonly field cannot be assigned to (except in the constructor of the class in which the field is defined or a variable initializer)) // TestInt = 15; // CS0191 - not in declaring class Diagnostic(ErrorCode.ERR_AssgReadonly, "TestInt").WithLocation(28, 9), // (11,9): error CS0191: A readonly field cannot be assigned to (except in the constructor of the class in which the field is defined or a variable initializer)) // t.TestInt = 14; // CS0191 - we can't be sure that the receiver is this Diagnostic(ErrorCode.ERR_AssgReadonly, "t.TestInt").WithLocation(11, 9), // (16,9): error CS0191: A readonly field cannot be assigned to (except in the constructor of the class in which the field is defined or a variable initializer)) // TestInt = 19; // CS0191 Diagnostic(ErrorCode.ERR_AssgReadonly, "TestInt").WithLocation(16, 9)); } [WorkItem(538009, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538009")] [Fact] public void CS0192ERR_RefReadonly() { var text = @" class MyClass { public readonly int TestInt = 6; static void TestMethod(ref int testInt) { testInt = 0; } MyClass() { TestMethod(ref TestInt); // OK } public void PassReadOnlyRef() { TestMethod(ref TestInt); // CS0192 } public static void Main() { } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_RefReadonly, Line = 17, Column = 24 } }); } [Fact] public void CS0193ERR_PtrExpected() { var text = @" using System; public struct Age { public int AgeYears; public int AgeMonths; public int AgeDays; } public class MyClass { public static void SetAge(ref Age anAge, int years, int months, int days) { anAge->Months = 3; // CS0193, anAge is not a pointer // try the following line instead // anAge.AgeMonths = 3; } public static void Main() { Age MyAge = new Age(); Console.WriteLine(MyAge.AgeMonths); SetAge(ref MyAge, 22, 4, 15); Console.WriteLine(MyAge.AgeMonths); } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_PtrExpected, Line = 15, Column = 7 } }); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void CS0196ERR_PtrIndexSingle() { var text = @" unsafe public class MyClass { public static void Main () { int *i = null; int j = 0; j = i[1,2]; // CS0196 // try the following line instead // j = i[1]; } }"; var compilation = CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (8,11): error CS0196: A pointer must be indexed by only one value // j = i[1,2]; // CS0196 Diagnostic(ErrorCode.ERR_PtrIndexSingle, "i[1,2]")); var tree = compilation.SyntaxTrees.Single(); var node = tree.GetRoot().DescendantNodes().OfType<ElementAccessExpressionSyntax>().First(); Assert.Equal("i[1,2]", node.ToString()); compilation.VerifyOperationTree(node, expectedOperationTree: @" IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'i[1,2]') Children(2): ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32*, IsInvalid) (Syntax: 'i') IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid, IsImplicit) (Syntax: 'i[1,2]') Children(2): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid) (Syntax: '1') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2, IsInvalid) (Syntax: '2') "); } [Fact] public void CS0198ERR_AssgReadonlyStatic() { var text = @" public class MyClass { public static readonly int TestInt = 6; static MyClass() { TestInt = 7; TestInt = 8; MyClass.TestInt = 7; } public MyClass() { TestInt = 11; // CS0198, constructor is not static and readonly field is } private void InstanceMethod() { TestInt = 12; // CS0198 } private void StaticMethod() { TestInt = 13; // CS0198 } public static void Main() { } } class MyDerived : MyClass { static MyDerived() { MyClass.TestInt = 14; // CS0198, not in declaring class } }"; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_AssgReadonlyStatic, Line = 15, Column = 7 }, new ErrorDescription { Code = (int)ErrorCode.ERR_AssgReadonlyStatic, Line = 20, Column = 8 }, new ErrorDescription { Code = (int)ErrorCode.ERR_AssgReadonlyStatic, Line = 25, Column = 8 }, new ErrorDescription { Code = (int)ErrorCode.ERR_AssgReadonlyStatic, Line = 37, Column = 9 }, }); } [Fact, WorkItem(990, "https://github.com/dotnet/roslyn/issues/990")] public void WriteOfReadonlyStaticMemberOfAnotherInstantiation01() { var text = @"public static class Goo<T> { static Goo() { Goo<int>.X = 1; Goo<int>.Y = 2; Goo<T>.Y = 3; } public static readonly int X; public static int Y { get; } }"; CreateCompilation(text, options: TestOptions.ReleaseDll).VerifyDiagnostics( // (6,9): error CS0200: Property or indexer 'Goo<int>.Y' cannot be assigned to -- it is read only // Goo<int>.Y = 2; Diagnostic(ErrorCode.ERR_AssgReadonlyProp, "Goo<int>.Y").WithArguments("Goo<int>.Y").WithLocation(6, 9) ); CreateCompilation(text, options: TestOptions.ReleaseDll, parseOptions: TestOptions.Regular.WithStrictFeature()).VerifyDiagnostics( // (5,9): error CS0198: A static readonly field cannot be assigned to (except in a static constructor or a variable initializer) // Goo<int>.X = 1; Diagnostic(ErrorCode.ERR_AssgReadonlyStatic, "Goo<int>.X").WithLocation(5, 9), // (6,9): error CS0200: Property or indexer 'Goo<int>.Y' cannot be assigned to -- it is read only // Goo<int>.Y = 2; Diagnostic(ErrorCode.ERR_AssgReadonlyProp, "Goo<int>.Y").WithArguments("Goo<int>.Y").WithLocation(6, 9) ); } [Fact, WorkItem(990, "https://github.com/dotnet/roslyn/issues/990")] public void WriteOfReadonlyStaticMemberOfAnotherInstantiation02() { var text = @"using System; using System.Threading; class Program { static void Main(string[] args) { Console.WriteLine(Goo<long>.x); Console.WriteLine(Goo<int>.x); Console.WriteLine(Goo<string>.x); Console.WriteLine(Goo<int>.x); } } public static class Goo<T> { static Goo() { Console.WriteLine(""initializing for "" + typeof(T)); Goo<int>.x = typeof(T).Name; } public static readonly string x; }"; var expectedOutput = @"initializing for System.Int64 initializing for System.Int32 Int64 initializing for System.String String "; // Although we accept this nasty code, it will not verify. CompileAndVerify(text, expectedOutput: expectedOutput, verify: Verification.Fails); } [Fact] public void CS0199ERR_RefReadonlyStatic() { var text = @" class MyClass { public static readonly int TestInt = 6; static void TestMethod(ref int testInt) { testInt = 0; } MyClass() { TestMethod(ref TestInt); // CS0199, TestInt is static } public static void Main() { } }"; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_RefReadonlyStatic, Line = 13, Column = 24 } }); } [Fact] public void CS0200ERR_AssgReadonlyProp01() { var source = @"abstract class A { internal static A P { get { return null; } } internal object Q { get; set; } public abstract object R { get; } } class B : A { public override object R { get { return null; } } } class Program { static void M(B b) { B.P.Q = null; B.P = null; // CS0200 b.R = null; // CS0200 } }"; CreateCompilation(source).VerifyDiagnostics( // (16,9): error CS0200: Property or indexer 'A.P' cannot be assigned to -- it is read only Diagnostic(ErrorCode.ERR_AssgReadonlyProp, "B.P").WithArguments("A.P").WithLocation(16, 9), // (17,9): error CS0200: Property or indexer 'B.R' cannot be assigned to -- it is read only Diagnostic(ErrorCode.ERR_AssgReadonlyProp, "b.R").WithArguments("B.R").WithLocation(17, 9)); } [Fact] public void CS0200ERR_AssgReadonlyProp02() { var source = @"class A { public virtual A P { get; set; } public A Q { get { return null; } } } class B : A { public override A P { get { return null; } } } class Program { static void M(B b) { b.P = null; b.Q = null; // CS0200 b.Q.P = null; b.P.Q = null; // CS0200 } }"; CreateCompilation(source).VerifyDiagnostics( // (15,9): error CS0200: Property or indexer 'A.Q' cannot be assigned to -- it is read only Diagnostic(ErrorCode.ERR_AssgReadonlyProp, "b.Q").WithArguments("A.Q").WithLocation(15, 9), // (17,9): error CS0200: Property or indexer 'A.Q' cannot be assigned to -- it is read only Diagnostic(ErrorCode.ERR_AssgReadonlyProp, "b.P.Q").WithArguments("A.Q").WithLocation(17, 9)); } [Fact] public void CS0200ERR_AssgReadonlyProp03() { var source = @"class C { static int P { get { return 0; } } int Q { get { return 0; } } static void M(C c) { ++P; ++c.Q; } }"; CreateCompilation(source).VerifyDiagnostics( // (7,11): error CS0200: Property or indexer 'C.P' cannot be assigned to -- it is read only Diagnostic(ErrorCode.ERR_AssgReadonlyProp, "P").WithArguments("C.P").WithLocation(7, 11), // (8,11): error CS0200: Property or indexer 'C.Q' cannot be assigned to -- it is read only Diagnostic(ErrorCode.ERR_AssgReadonlyProp, "c.Q").WithArguments("C.Q").WithLocation(8, 11)); } [Fact] public void CS0200ERR_AssgReadonlyProp04() { var source = @"class C { object P { get { P = null; return null; } } }"; CreateCompilation(source).VerifyDiagnostics( // (3,22): error CS0200: Property or indexer 'C.P' cannot be assigned to -- it is read only Diagnostic(ErrorCode.ERR_AssgReadonlyProp, "P").WithArguments("C.P").WithLocation(3, 22)); } [Fact] public void CS0200ERR_AssgReadonlyProp05() { CreateCompilation( @"class C { int this[int x] { get { return x; } } void M(int b) { this[0] = b; this[1]++; this[2] += 1; } }") .VerifyDiagnostics( // (6,9): error CS0200: Property or indexer 'C.this[int]' cannot be assigned to -- it is read only Diagnostic(ErrorCode.ERR_AssgReadonlyProp, "this[0]").WithArguments("C.this[int]"), // (7,9): error CS0200: Property or indexer 'C.this[int]' cannot be assigned to -- it is read only Diagnostic(ErrorCode.ERR_AssgReadonlyProp, "this[1]").WithArguments("C.this[int]"), // (8,9): error CS0200: Property or indexer 'C.this[int]' cannot be assigned to -- it is read only Diagnostic(ErrorCode.ERR_AssgReadonlyProp, "this[2]").WithArguments("C.this[int]")); } [Fact] public void CS0200ERR_AssgReadonlyProp06() { var source1 = @"public class A { public virtual object P { get { return null; } private set { } } } public class B : A { public override object P { get { return null; } } }"; var compilation1 = CreateCompilation(source1); compilation1.VerifyDiagnostics(); var compilationVerifier = CompileAndVerify(compilation1); var reference1 = MetadataReference.CreateFromImage(compilationVerifier.EmittedAssemblyData); var source2 = @"class C { static void M(B b) { var o = b.P; b.P = o; } }"; var compilation2 = CreateCompilation(source2, references: new[] { reference1 }); compilation2.VerifyDiagnostics( // (6,9): error CS0200: Property or indexer 'B.P' cannot be assigned to -- it is read only Diagnostic(ErrorCode.ERR_AssgReadonlyProp, "b.P").WithArguments("B.P").WithLocation(6, 9)); } [Fact] public void CS0201ERR_IllegalStatement1() { var text = @" public class MyList<T> { public void Add(T x) { int i = 0; if ( (object)x == null) { checked(i++); // CS0201 // OK checked { i++; } } } }"; CreateCompilation(text).VerifyDiagnostics( // (9,10): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement Diagnostic(ErrorCode.ERR_IllegalStatement, "checked(i++)")); } [Fact, WorkItem(536863, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536863")] public void CS0201ERR_IllegalStatement2() { var text = @" class A { public static int Main() { (a) => a; (a, b) => { }; int x = 0; int y = 0; x + y; x == 1; } }"; CreateCompilation(text, parseOptions: TestOptions.Regular.WithTuplesFeature()).VerifyDiagnostics( // (6,9): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement // (a) => a; Diagnostic(ErrorCode.ERR_IllegalStatement, "(a) => a").WithLocation(6, 9), // (7,9): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement // (a, b) => { }; Diagnostic(ErrorCode.ERR_IllegalStatement, "(a, b) => { }").WithLocation(7, 9), // (9,9): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement // x + y; x == 1; Diagnostic(ErrorCode.ERR_IllegalStatement, "x + y").WithLocation(9, 9), // (9,16): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement // x + y; x == 1; Diagnostic(ErrorCode.ERR_IllegalStatement, "x == 1").WithLocation(9, 16), // (4,23): error CS0161: 'A.Main()': not all code paths return a value // public static int Main() Diagnostic(ErrorCode.ERR_ReturnExpected, "Main").WithArguments("A.Main()").WithLocation(4, 23) ); } [Fact, WorkItem(536863, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536863")] public void CS0201ERR_IllegalStatement2WithCSharp6() { var test = @" class A { public static int Main() { (a) => a; (a, b) => { }; int x = 0; int y = 0; x + y; x == 1; } }"; var comp = CreateCompilation(new[] { Parse(test, options: TestOptions.Regular6) }, new MetadataReference[] { }); comp.VerifyDiagnostics( // (6,9): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement // (a) => a; Diagnostic(ErrorCode.ERR_IllegalStatement, "(a) => a").WithLocation(6, 9), // (7,9): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement // (a, b) => { }; Diagnostic(ErrorCode.ERR_IllegalStatement, "(a, b) => { }").WithLocation(7, 9), // (9,9): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement // x + y; x == 1; Diagnostic(ErrorCode.ERR_IllegalStatement, "x + y").WithLocation(9, 9), // (9,16): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement // x + y; x == 1; Diagnostic(ErrorCode.ERR_IllegalStatement, "x == 1").WithLocation(9, 16), // (4,23): error CS0161: 'A.Main()': not all code paths return a value // public static int Main() Diagnostic(ErrorCode.ERR_ReturnExpected, "Main").WithArguments("A.Main()").WithLocation(4, 23) ); } [Fact] public void CS0202ERR_BadGetEnumerator() { var text = @" public class C1 { public int Current { get { return 0; } } public bool MoveNext () { return false; } public static implicit operator C1 (int c1) { return 0; } } public class C2 { public int Current { get { return 0; } } public bool MoveNext () { return false; } public C1[] GetEnumerator () { return null; } } public class MainClass { public static void Main () { C2 c2 = new C2(); foreach (C1 x in c2) // CS0202 { System.Console.WriteLine(x.Current); } } }"; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_BadGetEnumerator, Line = 50, Column = 24 } }); } // [Fact()] // public void CS0204ERR_TooManyLocals() // { // var text = @" //"; // DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, // new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_TooManyLocals, Line = 8, Column = 13 } } // ); // } [Fact()] public void CS0205ERR_AbstractBaseCall() { var text = @"abstract class A { abstract public void M(); abstract protected object P { get; } } class B : A { public override void M() { base.M(); // CS0205 object o = base.P; // CS0205 } protected override object P { get { return null; } } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_AbstractBaseCall, Line = 10, Column = 9 }, new ErrorDescription { Code = (int)ErrorCode.ERR_AbstractBaseCall, Line = 11, Column = 20 }); } [Fact] public void CS0205ERR_AbstractBaseCall_Override() { var text = @" public class Base1 { public virtual long Property1 { get { return 0; } set { } } } abstract public class Base2 : Base1 { public abstract override long Property1 { get; } void test1() { Property1 += 1; } } public class Derived : Base2 { public override long Property1 { get { return 1; } set { } } void test2() { base.Property1++; base.Property1 = 2; long x = base.Property1; } } "; CreateCompilation(text).VerifyDiagnostics( // (19,9): error CS0205: Cannot call an abstract base member: 'Base2.Property1' Diagnostic(ErrorCode.ERR_AbstractBaseCall, "base.Property1").WithArguments("Base2.Property1"), // (21,18): error CS0205: Cannot call an abstract base member: 'Base2.Property1' Diagnostic(ErrorCode.ERR_AbstractBaseCall, "base.Property1").WithArguments("Base2.Property1")); } [Fact] public void CS0206ERR_RefProperty() { var text = @"class C { static int P { get; set; } object Q { get; set; } static void M(ref int i) { } static void M(out object o) { o = null; } void M() { M(ref P); // CS0206 M(out this.Q); // CS0206 } } "; CreateCompilation(text).VerifyDiagnostics( // (14,15): error CS0206: A property or indexer may not be passed as an out or ref parameter Diagnostic(ErrorCode.ERR_RefProperty, "P").WithArguments("C.P"), // (15,15): error CS0206: A property or indexer may not be passed as an out or ref parameter Diagnostic(ErrorCode.ERR_RefProperty, "this.Q").WithArguments("C.Q")); } [Fact] public void CS0206ERR_RefProperty_Indexers() { var text = @"class C { int this[int x] { get { return x; } set { } } static void R(ref int i) { } static void O(out int o) { o = 0; } void M() { R(ref this[0]); // CS0206 O(out this[0]); // CS0206 } } "; CreateCompilation(text).VerifyDiagnostics( // (13,15): error CS0206: A property or indexer may not be passed as an out or ref parameter Diagnostic(ErrorCode.ERR_RefProperty, "this[0]").WithArguments("C.this[int]"), // (14,15): error CS0206: A property or indexer may not be passed as an out or ref parameter Diagnostic(ErrorCode.ERR_RefProperty, "this[0]").WithArguments("C.this[int]")); } [Fact] public void CS0208ERR_ManagedAddr01() { var text = @" class myClass { public int a = 98; } struct myProblemStruct { string s; float f; } struct myGoodStruct { int i; float f; } public class MyClass { unsafe public static void Main() { // myClass is a class, a managed type. myClass s = new myClass(); myClass* s2 = &s; // CS0208 // The struct contains a string, a managed type. int i = sizeof(myProblemStruct); //CS0208 // The struct contains only value types. i = sizeof(myGoodStruct); //OK } } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (25,9): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('myClass') // myClass* s2 = &s; // CS0208 Diagnostic(ErrorCode.ERR_ManagedAddr, "myClass*").WithArguments("myClass"), // (25,23): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('myClass') // myClass* s2 = &s; // CS0208 Diagnostic(ErrorCode.ERR_ManagedAddr, "&s").WithArguments("myClass"), // (28,17): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('myProblemStruct') // int i = sizeof(myProblemStruct); //CS0208 Diagnostic(ErrorCode.ERR_ManagedAddr, "sizeof(myProblemStruct)").WithArguments("myProblemStruct"), // (9,12): warning CS0169: The field 'myProblemStruct.s' is never used // string s; Diagnostic(ErrorCode.WRN_UnreferencedField, "s").WithArguments("myProblemStruct.s"), // (10,11): warning CS0169: The field 'myProblemStruct.f' is never used // float f; Diagnostic(ErrorCode.WRN_UnreferencedField, "f").WithArguments("myProblemStruct.f"), // (15,9): warning CS0169: The field 'myGoodStruct.i' is never used // int i; Diagnostic(ErrorCode.WRN_UnreferencedField, "i").WithArguments("myGoodStruct.i"), // (16,11): warning CS0169: The field 'myGoodStruct.f' is never used // float f; Diagnostic(ErrorCode.WRN_UnreferencedField, "f").WithArguments("myGoodStruct.f")); } [Fact] public void CS0208ERR_ManagedAddr02() { var source = @"enum E { } delegate void D(); struct S { } interface I { } unsafe class C { object* _object; void* _void; bool* _bool; char* _char; sbyte* _sbyte; byte* _byte; short* _short; ushort* _ushort; int* _int; uint* _uint; long* _long; ulong* _ulong; decimal* _decimal; float* _float; double* _double; string* _string; System.IntPtr* _intptr; System.UIntPtr* _uintptr; int** _intptr2; int?* _nullable; dynamic* _dynamic; E* e; D* d; S* s; I* i; C* c; }"; CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.UnsafeReleaseDll) .GetDiagnostics() .Where(d => d.Severity == DiagnosticSeverity.Error) .Verify( // (22,13): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('string') // string* _string; Diagnostic(ErrorCode.ERR_ManagedAddr, "_string").WithArguments("string").WithLocation(22, 13), // (27,14): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('dynamic') // dynamic* _dynamic; Diagnostic(ErrorCode.ERR_ManagedAddr, "_dynamic").WithArguments("dynamic").WithLocation(27, 14), // (29,8): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('D') // D* d; Diagnostic(ErrorCode.ERR_ManagedAddr, "d").WithArguments("D").WithLocation(29, 8), // (31,8): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('I') // I* i; Diagnostic(ErrorCode.ERR_ManagedAddr, "i").WithArguments("I").WithLocation(31, 8), // (32,8): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('C') // C* c; Diagnostic(ErrorCode.ERR_ManagedAddr, "c").WithArguments("C").WithLocation(32, 8), // (7,13): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('object') // object* _object; Diagnostic(ErrorCode.ERR_ManagedAddr, "_object").WithArguments("object").WithLocation(7, 13)); } [Fact] public void CS0209ERR_BadFixedInitType() { var text = @" class Point { public int x, y; } public class MyClass { unsafe public static void Main() { Point pt = new Point(); fixed (int i) // CS0209 { } } } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (13,18): error CS0209: The type of a local declared in a fixed statement must be a pointer type // fixed (int i) // CS0209 Diagnostic(ErrorCode.ERR_BadFixedInitType, "i"), // (13,18): error CS0210: You must provide an initializer in a fixed or using statement declaration // fixed (int i) // CS0209 Diagnostic(ErrorCode.ERR_FixedMustInit, "i"), // (4,15): warning CS0649: Field 'Point.x' is never assigned to, and will always have its default value 0 // public int x, y; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "x").WithArguments("Point.x", "0"), // (4,18): warning CS0649: Field 'Point.y' is never assigned to, and will always have its default value 0 // public int x, y; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "y").WithArguments("Point.y", "0")); } [Fact] public void CS0210ERR_FixedMustInit() { var text = @" using System.IO; class Test { static void Main() { using (StreamWriter w) // CS0210 { w.WriteLine(""Hello there""); } using (StreamWriter x, y) // CS0210, CS0210 { } } } "; CreateCompilation(text).VerifyDiagnostics( // (7,27): error CS0210: You must provide an initializer in a fixed or using statement declaration // using (StreamWriter w) // CS0210 Diagnostic(ErrorCode.ERR_FixedMustInit, "w").WithLocation(7, 27), // (12,27): error CS0210: You must provide an initializer in a fixed or using statement declaration // using (StreamWriter x, y) // CS0210, CS0210 Diagnostic(ErrorCode.ERR_FixedMustInit, "x").WithLocation(12, 27), // (12,30): error CS0210: You must provide an initializer in a fixed or using statement declaration // using (StreamWriter x, y) // CS0210, CS0210 Diagnostic(ErrorCode.ERR_FixedMustInit, "y").WithLocation(12, 30), // (9,10): error CS0165: Use of unassigned local variable 'w' // w.WriteLine("Hello there"); Diagnostic(ErrorCode.ERR_UseDefViolation, "w").WithArguments("w").WithLocation(9, 10) ); } [Fact] public void CS0211ERR_InvalidAddrOp() { var text = @" public class MyClass { unsafe public void M() { int a = 0, b = 0; int *i = &(a + b); // CS0211, the addition of two local variables // try the following line instead // int *i = &a; } public static void Main() { } } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (7,18): error CS0211: Cannot take the address of the given expression // int *i = &(a + b); // CS0211, the addition of two local variables Diagnostic(ErrorCode.ERR_InvalidAddrOp, "a + b")); } [Fact] public void CS0212ERR_FixedNeeded() { var text = @" public class A { public int iField = 5; unsafe public void M() { A a = new A(); int* ptr = &a.iField; // CS0212 } // OK unsafe public void M2() { A a = new A(); fixed (int* ptr = &a.iField) {} } } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (7,18): error CS0212: You can only take the address of an unfixed expression inside of a fixed statement initializer // int* ptr = &a.iField; // CS0212 Diagnostic(ErrorCode.ERR_FixedNeeded, "&a.iField")); } [Fact] public void CS0213ERR_FixedNotNeeded() { var text = @" public class MyClass { unsafe public static void Main() { int i = 45; fixed (int *j = &i) { } // CS0213 // try the following line instead // int* j = &i; int[] a = new int[] {1,2,3}; fixed (int *b = a) { fixed (int *c = b) { } // CS0213 // try the following line instead // int *c = b; } } } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (7,23): error CS0213: You cannot use the fixed statement to take the address of an already fixed expression // fixed (int *j = &i) { } // CS0213 Diagnostic(ErrorCode.ERR_FixedNotNeeded, "&i").WithLocation(7, 23), // (14,26): error CS9385: The given expression cannot be used in a fixed statement // fixed (int *c = b) { } // CS0213 Diagnostic(ErrorCode.ERR_ExprCannotBeFixed, "b").WithLocation(14, 26)); } [Fact] public void CS0217ERR_BadBoolOp() { // Note that the wording of this error message has changed. var text = @" public class MyClass { public static bool operator true (MyClass f) { return false; } public static bool operator false (MyClass f) { return false; } public static int operator & (MyClass f1, MyClass f2) { return 0; } public static void Main() { MyClass f = new MyClass(); int i = f && f; // CS0217 } } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (22,15): error CS0217: In order to be applicable as a short circuit operator a user-defined logical operator ('MyClass.operator &(MyClass, MyClass)') must have the same return type and parameter types // int i = f && f; // CS0217 Diagnostic(ErrorCode.ERR_BadBoolOp, "f && f").WithArguments("MyClass.operator &(MyClass, MyClass)")); } // CS0220 ERR_CheckedOverflow - see ConstantTests [Fact] public void CS0221ERR_ConstOutOfRangeChecked01() { string text = @"class MyClass { static void F(int x) { } static void M() { F((int)0xFFFFFFFF); // CS0221 F(unchecked((int)uint.MaxValue)); F(checked((int)(uint.MaxValue - 1))); // CS0221 } } "; CreateCompilation(text).VerifyDiagnostics( // (6,11): error CS0221: Constant value '4294967295' cannot be converted to a 'int' (use 'unchecked' syntax to override) Diagnostic(ErrorCode.ERR_ConstOutOfRangeChecked, "(int)0xFFFFFFFF").WithArguments("4294967295", "int"), // (8,19): error CS0221: Constant value '4294967294' cannot be converted to a 'int' (use 'unchecked' syntax to override) Diagnostic(ErrorCode.ERR_ConstOutOfRangeChecked, "(int)(uint.MaxValue - 1)").WithArguments("4294967294", "int")); } [Fact] public void CS0221ERR_ConstOutOfRangeChecked02() { string text = @"enum E : byte { A, B = 0xfe, C } class C { const int F = (int)(E.C + 1); // CS0221 const int G = (int)unchecked(1 + E.C); const int H = (int)checked(E.A - 1); // CS0221 } "; CreateCompilation(text).VerifyDiagnostics( // (4,25): error CS0031: Constant value '256' cannot be converted to a 'E' Diagnostic(ErrorCode.ERR_ConstOutOfRangeChecked, "E.C + 1").WithArguments("256", "E"), // (6,32): error CS0221: Constant value '-1' cannot be converted to a 'E' (use 'unchecked' syntax to override) Diagnostic(ErrorCode.ERR_ConstOutOfRangeChecked, "E.A - 1").WithArguments("-1", "E")); } [WorkItem(1119609, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1119609")] [Fact(Skip = "1119609")] public void CS0221ERR_ConstOutOfRangeChecked03() { var text = @"public class MyClass { decimal x1 = (decimal)double.PositiveInfinity; //CS0221 decimal x2 = (decimal)double.NegativeInfinity; //CS0221 decimal x3 = (decimal)double.NaN; //CS0221 decimal x4 = (decimal)double.MaxValue; //CS0221 public static void Main() {} } "; CreateCompilation(text).VerifyDiagnostics( // (3,18): error CS0031: Constant value 'Infinity' cannot be converted to a 'decimal' // decimal x1 = (decimal)double.PositiveInfinity; //CS0221 Diagnostic(ErrorCode.ERR_ConstOutOfRange, "(decimal)double.PositiveInfinity").WithArguments("Infinity", "decimal"), // (4,18): error CS0031: Constant value '-Infinity' cannot be converted to a 'decimal' // decimal x2 = (decimal)double.NegativeInfinity; //CS0221 Diagnostic(ErrorCode.ERR_ConstOutOfRange, "(decimal)double.NegativeInfinity").WithArguments("-Infinity", "decimal"), // (5,18): error CS0031: Constant value 'NaN' cannot be converted to a 'decimal' // decimal x3 = (decimal)double.NaN; //CS0221 Diagnostic(ErrorCode.ERR_ConstOutOfRange, "(decimal)double.NaN").WithArguments("NaN", "decimal"), // (6,18): error CS0031: Constant value '1.79769313486232E+308' cannot be converted to a 'decimal' // decimal x4 = (decimal)double.MaxValue; //CS0221 Diagnostic(ErrorCode.ERR_ConstOutOfRange, "(decimal)double.MaxValue").WithArguments("1.79769313486232E+308", "decimal"), // (3,13): warning CS0414: The field 'MyClass.x1' is assigned but its value is never used // decimal x1 = (decimal)double.PositiveInfinity; //CS0221 Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "x1").WithArguments("MyClass.x1"), // (4,13): warning CS0414: The field 'MyClass.x2' is assigned but its value is never used // decimal x2 = (decimal)double.NegativeInfinity; //CS0221 Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "x2").WithArguments("MyClass.x2"), // (5,13): warning CS0414: The field 'MyClass.x3' is assigned but its value is never used // decimal x3 = (decimal)double.NaN; //CS0221 Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "x3").WithArguments("MyClass.x3"), // (6,13): warning CS0414: The field 'MyClass.x4' is assigned but its value is never used // decimal x4 = (decimal)double.MaxValue; //CS0221 Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "x4").WithArguments("MyClass.x4")); } [Fact] public void CS0226ERR_IllegalArglist() { var text = @" public class C { public static int Main () { __arglist(1,""This is a string""); // CS0226 return 0; } } "; CreateCompilation(text).VerifyDiagnostics( Diagnostic(ErrorCode.ERR_IllegalArglist, @"__arglist(1,""This is a string"")")); } // [Fact()] // public void CS0228ERR_NoAccessibleMember() // { // var text = @" //"; // DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, // new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_NoAccessibleMember, Line = 31, Column = 17 } } // ); // } [Fact] public void CS0229ERR_AmbigMember() { var text = @" interface IList { int Count { get; set; } void Counter(); } interface Icounter { double Count { get; set; } } interface IListCounter : IList , Icounter {} class MyClass { void Test(IListCounter x) { x.Count = 1; // CS0229 // Try one of the following lines instead: // ((IList)x).Count = 1; // or // ((Icounter)x).Count = 1; } public static void Main() {} } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_AmbigMember, Line = 28, Column = 11 } }); } [Fact] public void CS0233ERR_SizeofUnsafe() { var text = @" using System; using System.Runtime.InteropServices; [StructLayout(LayoutKind.Sequential)] public struct S { public int a; } public class MyClass { public static void Main() { S myS = new S(); Console.WriteLine(sizeof(S)); // CS0233 // Try the following line instead: // Console.WriteLine(Marshal.SizeOf(myS)); } } "; CreateCompilation(text).VerifyDiagnostics( // (16,27): error CS0233: 'S' does not have a predefined size, therefore sizeof can only be used in an unsafe context (consider using System.Runtime.InteropServices.Marshal.SizeOf) // Console.WriteLine(sizeof(S)); // CS0233 Diagnostic(ErrorCode.ERR_SizeofUnsafe, "sizeof(S)").WithArguments("S"), // (15,11): warning CS0219: The variable 'myS' is assigned but its value is never used // S myS = new S(); Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "myS").WithArguments("myS")); } [Fact] public void CS0236ERR_FieldInitRefNonstatic() { var text = @" public class MyClass { int[] instanceArray; static int[] staticArray; static int staticField = 1; const int constField = 1; int a; int b = 1; int c = b; //CS0236 int d = this.b; //CS0027 int e = InstanceMethod(); //CS0236 int f = this.InstanceMethod(); //CS0027 int g = StaticMethod(); int h = MyClass.StaticMethod(); int i = GenericInstanceMethod<int>(1); //CS0236 int j = this.GenericInstanceMethod<int>(1); //CS0027 int k = GenericStaticMethod<int>(1); int l = MyClass.GenericStaticMethod<int>(1); int m = InstanceProperty; //CS0236 int n = this.InstanceProperty; //CS0027 int o = StaticProperty; int p = MyClass.StaticProperty; int q = instanceArray[0]; //CS0236 int r = this.instanceArray[0]; //CS0027 int s = staticArray[0]; int t = MyClass.staticArray[0]; int u = staticField; int v = MyClass.staticField; int w = constField; int x = MyClass.constField; MyClass() { a = b; } int InstanceMethod() { return a; } static int StaticMethod() { return 1; } T GenericInstanceMethod<T>(T t) { return t; } static T GenericStaticMethod<T>(T t) { return t; } int InstanceProperty { get { return a; } } static int StaticProperty { get { return 1; } } public static void Main() { } } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (12,13): error CS0236: A field initializer cannot reference the non-static field, method, or property 'MyClass.b' // int c = b; //CS0236 Diagnostic(ErrorCode.ERR_FieldInitRefNonstatic, "b").WithArguments("MyClass.b").WithLocation(12, 13), // (13,13): error CS0027: Keyword 'this' is not available in the current context // int d = this.b; //CS0027 Diagnostic(ErrorCode.ERR_ThisInBadContext, "this").WithLocation(13, 13), // (14,13): error CS0236: A field initializer cannot reference the non-static field, method, or property 'MyClass.InstanceMethod()' // int e = InstanceMethod(); //CS0236 Diagnostic(ErrorCode.ERR_FieldInitRefNonstatic, "InstanceMethod").WithArguments("MyClass.InstanceMethod()").WithLocation(14, 13), // (15,13): error CS0027: Keyword 'this' is not available in the current context // int f = this.InstanceMethod(); //CS0027 Diagnostic(ErrorCode.ERR_ThisInBadContext, "this").WithLocation(15, 13), // (18,13): error CS0236: A field initializer cannot reference the non-static field, method, or property 'MyClass.GenericInstanceMethod<int>(int)' // int i = GenericInstanceMethod<int>(1); //CS0236 Diagnostic(ErrorCode.ERR_FieldInitRefNonstatic, "GenericInstanceMethod<int>").WithArguments("MyClass.GenericInstanceMethod<int>(int)").WithLocation(18, 13), // (19,13): error CS0027: Keyword 'this' is not available in the current context // int j = this.GenericInstanceMethod<int>(1); //CS0027 Diagnostic(ErrorCode.ERR_ThisInBadContext, "this").WithLocation(19, 13), // (22,13): error CS0236: A field initializer cannot reference the non-static field, method, or property 'MyClass.InstanceProperty' // int m = InstanceProperty; //CS0236 Diagnostic(ErrorCode.ERR_FieldInitRefNonstatic, "InstanceProperty").WithArguments("MyClass.InstanceProperty").WithLocation(22, 13), // (23,13): error CS0027: Keyword 'this' is not available in the current context // int n = this.InstanceProperty; //CS0027 Diagnostic(ErrorCode.ERR_ThisInBadContext, "this").WithLocation(23, 13), // (26,13): error CS0236: A field initializer cannot reference the non-static field, method, or property 'MyClass.instanceArray' // int q = instanceArray[0]; //CS0236 Diagnostic(ErrorCode.ERR_FieldInitRefNonstatic, "instanceArray").WithArguments("MyClass.instanceArray").WithLocation(26, 13), // (27,13): error CS0027: Keyword 'this' is not available in the current context // int r = this.instanceArray[0]; //CS0027 Diagnostic(ErrorCode.ERR_ThisInBadContext, "this").WithLocation(27, 13), // (4,11): warning CS0649: Field 'MyClass.instanceArray' is never assigned to, and will always have its default value null // int[] instanceArray; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "instanceArray").WithArguments("MyClass.instanceArray", "null").WithLocation(4, 11), // (5,18): warning CS0649: Field 'MyClass.staticArray' is never assigned to, and will always have its default value null // static int[] staticArray; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "staticArray").WithArguments("MyClass.staticArray", "null").WithLocation(5, 18), // (33,9): warning CS0414: The field 'MyClass.x' is assigned but its value is never used // int x = MyClass.constField; Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "x").WithArguments("MyClass.x").WithLocation(33, 9), // (32,9): warning CS0414: The field 'MyClass.w' is assigned but its value is never used // int w = constField; Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "w").WithArguments("MyClass.w").WithLocation(32, 9) ); } [Fact] public void CS0236ERR_FieldInitRefNonstaticMethodGroups() { var text = @" delegate void F(); public class MyClass { F a = Static; F b = MyClass.Static; F c = Static<int>; F d = MyClass.Static<int>; F e = Instance; F f = this.Instance; F g = Instance<int>; F h = this.Instance<int>; static void Static() { } static void Static<T>() { } void Instance() { } void Instance<T>() { } public static void Main() { } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib( text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_FieldInitRefNonstatic, Line = 9, Column = 11 }, new ErrorDescription { Code = (int)ErrorCode.ERR_ThisInBadContext, Line = 10, Column = 11 }, new ErrorDescription { Code = (int)ErrorCode.ERR_FieldInitRefNonstatic, Line = 11, Column = 11 }, new ErrorDescription { Code = (int)ErrorCode.ERR_ThisInBadContext, Line = 12, Column = 11 }, }); } [WorkItem(541501, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541501")] [Fact] public void CS0236ERR_FieldInitRefNonstaticProperty() { CreateCompilation( @" enum ProtectionLevel { Privacy = 0 } class F { const ProtectionLevel p = ProtectionLevel.Privacy; // CS0236 int ProtectionLevel { get { return 0; } } } ") .VerifyDiagnostics( // (9,29): error CS0236: A field initializer cannot reference the non-static field, method, or property 'F.ProtectionLevel' // const ProtectionLevel p = ProtectionLevel.Privacy; // CS0120 Diagnostic(ErrorCode.ERR_FieldInitRefNonstatic, "ProtectionLevel").WithArguments("F.ProtectionLevel")); } [WorkItem(541501, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541501")] [Fact] public void CS0236ERR_FieldInitRefNonstatic_ObjectInitializer() { CreateCompilation( @" public class Goo { public int i; public string s; } public class MemberInitializerTest { private int i =10; private string s = ""abc""; private Goo f = new Goo{i = i, s = s}; public static void Main() { } } ") .VerifyDiagnostics( // (12,33): error CS0236: A field initializer cannot reference the non-static field, method, or property 'MemberInitializerTest.i' // private Goo f = new Goo{i = i, s = s}; Diagnostic(ErrorCode.ERR_FieldInitRefNonstatic, "i").WithArguments("MemberInitializerTest.i").WithLocation(12, 33), // (12,40): error CS0236: A field initializer cannot reference the non-static field, method, or property 'MemberInitializerTest.s' // private Goo f = new Goo{i = i, s = s}; Diagnostic(ErrorCode.ERR_FieldInitRefNonstatic, "s").WithArguments("MemberInitializerTest.s").WithLocation(12, 40)); } [Fact] public void CS0236ERR_FieldInitRefNonstatic_AnotherInitializer() { CreateCompilation( @" class TestClass { int P1 { get; } int y = (P1 = 123); int y1 { get; } = (P1 = 123); static void Main() { } } ") .VerifyDiagnostics( // (6,14): error CS0236: A field initializer cannot reference the non-static field, method, or property 'TestClass.P1' // int y = (P1 = 123); Diagnostic(ErrorCode.ERR_FieldInitRefNonstatic, "P1").WithArguments("TestClass.P1").WithLocation(6, 14), // (7,24): error CS0236: A field initializer cannot reference the non-static field, method, or property 'TestClass.P1' // int y1 { get; } = (P1 = 123); Diagnostic(ErrorCode.ERR_FieldInitRefNonstatic, "P1").WithArguments("TestClass.P1").WithLocation(7, 24) ); } [Fact] public void CS0242ERR_VoidError() { var text = @" class TestClass { public unsafe void Test() { void* p = null; p++; //CS0242 p += 2; //CS0242 void* q = p + 1; //CS0242 long diff = q - p; //CS0242 var v = *p; } } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (7,9): error CS0242: The operation in question is undefined on void pointers // p++; //CS0242 Diagnostic(ErrorCode.ERR_VoidError, "p++"), // (8,9): error CS0242: The operation in question is undefined on void pointers // p += 2; //CS0242 Diagnostic(ErrorCode.ERR_VoidError, "p += 2"), // (9,19): error CS0242: The operation in question is undefined on void pointers // void* q = p + 1; //CS0242 Diagnostic(ErrorCode.ERR_VoidError, "p + 1"), // (10,21): error CS0242: The operation in question is undefined on void pointers // long diff = q - p; //CS0242 Diagnostic(ErrorCode.ERR_VoidError, "q - p"), // (11,17): error CS0242: The operation in question is undefined on void pointers // var v = *p; Diagnostic(ErrorCode.ERR_VoidError, "*p")); } [Fact] public void CS0244ERR_PointerInAsOrIs() { var text = @" class UnsafeTest { unsafe static void SquarePtrParam (int* p) { bool b = p is object; // CS0244 p is pointer } unsafe public static void Main() { int i = 5; SquarePtrParam (&i); } } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (6,16): error CS0244: Neither 'is' nor 'as' is valid on pointer types // bool b = p is object; // CS0244 p is pointer Diagnostic(ErrorCode.ERR_PointerInAsOrIs, "p is object")); } [Fact] public void CS0245ERR_CallingFinalizeDeprecated() { var text = @" class MyClass // : IDisposable { /* public void Dispose() { // cleanup code goes here } */ void m() { this.Finalize(); // CS0245 // this.Dispose(); } public static void Main() { } } "; CreateCompilation(text).VerifyDiagnostics( // (13,7): error CS0245: Destructors and object.Finalize cannot be called directly. Consider calling IDisposable.Dispose if available. Diagnostic(ErrorCode.ERR_CallingFinalizeDeprecated, "this.Finalize()")); } [WorkItem(540722, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540722")] [Fact] public void CS0246ERR_SingleTypeNameNotFound05() { CreateCompilation(@" namespace nms { public class Mine { private static int retval = 5; public static int Main() { try { } catch (e) { } return retval; } }; } ") .VerifyDiagnostics( // (10,20): error CS0246: The type or namespace name 'e' could not be found (are you missing a using directive or an assembly reference?) Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "e").WithArguments("e")); } [WorkItem(528446, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528446")] [Fact] public void CS0246ERR_SingleTypeNameNotFoundNoCS8000() { CreateCompilation(@" class Test { void Main() { var sum = new j(); } } ") .VerifyDiagnostics( // (11,20): error CS0246: The type or namespace name 'j' could not be found (are you missing a using directive or an assembly reference?) Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "j").WithArguments("j")); } [Fact] public void CS0247ERR_NegativeStackAllocSize() { var text = @" public class MyClass { unsafe public static void Main() { int *p = stackalloc int [-30]; // CS0247 } } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (6,32): error CS0247: Cannot use a negative size with stackalloc // int *p = stackalloc int [-30]; // CS0247 Diagnostic(ErrorCode.ERR_NegativeStackAllocSize, "-30")); } [Fact] public void CS0248ERR_NegativeArraySize() { var text = @" class MyClass { public static void Main() { int[] myArray = new int[-3] {1,2,3}; // CS0248, pass a nonnegative number int[] myArray2 = new int[-5000000000]; // slightly different code path for long array sizes int[] myArray3 = new int[3000000000u]; // slightly different code path for uint array sizes var myArray4 = new object[-2, 1, -1] {{{null}},{{null}}}; var myArray5 = new object[-1L] {null}; } } "; CreateCompilation(text).VerifyDiagnostics( // (6,33): error CS0248: Cannot create an array with a negative size // int[] myArray = new int[-3] {1,2,3}; // CS0248, pass a nonnegative number Diagnostic(ErrorCode.ERR_NegativeArraySize, "-3").WithLocation(6, 33), // (7,34): error CS0248: Cannot create an array with a negative size // int[] myArray2 = new int[-5000000000]; // slightly different code path for long array sizes Diagnostic(ErrorCode.ERR_NegativeArraySize, "-5000000000").WithLocation(7, 34), // (9,35): error CS0248: Cannot create an array with a negative size // var myArray4 = new object[-2, 1, -1] {{{null}},{{null}}}; Diagnostic(ErrorCode.ERR_NegativeArraySize, "-2").WithLocation(9, 35), // (9,42): error CS0248: Cannot create an array with a negative size // var myArray4 = new object[-2, 1, -1] {{{null}},{{null}}}; Diagnostic(ErrorCode.ERR_NegativeArraySize, "-1").WithLocation(9, 42), // (10,35): error CS0248: Cannot create an array with a negative size // var myArray5 = new object[-1L] {null}; Diagnostic(ErrorCode.ERR_NegativeArraySize, "-1L").WithLocation(10, 35), // (10,35): error CS0150: A constant value is expected // var myArray5 = new object[-1L] {null}; Diagnostic(ErrorCode.ERR_ConstantExpected, "-1L").WithLocation(10, 35)); } [WorkItem(528912, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528912")] [Fact] public void CS0250ERR_CallingBaseFinalizeDeprecated() { var text = @" class B { } class C : B { ~C() { base.Finalize(); // CS0250 } public static void Main() { } } "; CreateCompilation(text).VerifyDiagnostics( // (10,7): error CS0250: Do not directly call your base type Finalize method. It is called automatically from your destructor. Diagnostic(ErrorCode.ERR_CallingBaseFinalizeDeprecated, "base.Finalize()")); } [Fact] public void CS0254ERR_BadCastInFixed() { var text = @" class Point { public uint x, y; } class FixedTest { unsafe static void SquarePtrParam (int* p) { *p *= *p; } unsafe public static void Main() { Point pt = new Point(); pt.x = 5; pt.y = 6; fixed (int* p = (int*)&pt.x) // CS0254 // try the following line instead // fixed (uint* p = &pt.x) { SquarePtrParam ((int*)p); } } } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (20,23): error CS9385: The given expression cannot be used in a fixed statement // fixed (int* p = (int*)&pt.x) // CS0254 Diagnostic(ErrorCode.ERR_ExprCannotBeFixed, "(int*)&pt.x").WithLocation(20, 23)); } [Fact] public void CS0255ERR_StackallocInFinally() { var text = @" unsafe class Test { void M() { try { // Something } finally { int* fib = stackalloc int[100]; } } }"; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (12,24): error CS0255: stackalloc may not be used in a catch or finally block // int* fib = stackalloc int[100]; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int[100]").WithLocation(12, 24)); } [Fact] public void CS0255ERR_StackallocInCatch() { var text = @" unsafe class Test { void M() { try { // Something } catch { int* fib = stackalloc int[100]; } } }"; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (12,24): error CS0255: stackalloc may not be used in a catch or finally block // int* fib = stackalloc int[100]; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int[100]").WithLocation(12, 24)); } [Fact] public void CS0266ERR_NoImplicitConvCast01() { var text = @" class MyClass { public static void Main() { object obj = ""MyString""; // Cannot implicitly convert 'object' to 'MyClass' MyClass myClass = obj; // CS0266 // Try this line instead // MyClass c = ( MyClass )obj; } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_NoImplicitConvCast, Line = 8, Column = 27 } }); } [Fact] public void CS0266ERR_NoImplicitConvCast02() { var source = @"class C { const int f = 0L; } "; CreateCompilation(source).VerifyDiagnostics( // (3,19): error CS0266: Cannot implicitly convert type 'long' to 'int'. An explicit conversion exists (are you missing a cast?) // const int f = 0L; Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "0L").WithArguments("long", "int").WithLocation(3, 19)); } [Fact] public void CS0266ERR_NoImplicitConvCast03() { var source = @"class C { static void M() { const short s = 1L; } } "; CreateCompilation(source).VerifyDiagnostics( // (5,25): error CS0266: Cannot implicitly convert type 'long' to 'short'. An explicit conversion exists (are you missing a cast?) // const short s = 1L; Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "1L").WithArguments("long", "short").WithLocation(5, 25), // (5,21): warning CS0219: The variable 's' is assigned but its value is never used // const short s = 1L; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "s").WithArguments("s").WithLocation(5, 21)); } [Fact] public void CS0266ERR_NoImplicitConvCast04() { var source = @"enum E { A = 1 } class C { E f = 2; // CS0266 E g = E.A; void M() { f = E.A; g = 'c'; // CS0266 } } "; CreateCompilation(source).VerifyDiagnostics( // (4,11): error CS0266: Cannot implicitly convert type 'int' to 'E'. An explicit conversion exists (are you missing a cast?) // E f = 2; // CS0266 Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "2").WithArguments("int", "E").WithLocation(4, 11), // (9,13): error CS0266: Cannot implicitly convert type 'char' to 'E'. An explicit conversion exists (are you missing a cast?) // g = 'c'; // CS0266 Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "'c'").WithArguments("char", "E").WithLocation(9, 13), // (4,7): warning CS0414: The field 'C.f' is assigned but its value is never used // E f = 2; // CS0266 Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "f").WithArguments("C.f").WithLocation(4, 7), // (5,7): warning CS0414: The field 'C.g' is assigned but its value is never used // E g = E.A; Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "g").WithArguments("C.g").WithLocation(5, 7)); } [Fact] public void CS0266ERR_NoImplicitConvCast05() { var source = @"enum E : byte { A = 'a', // CS0266 B = 0xff, } "; CreateCompilation(source).VerifyDiagnostics( // (3,9): error CS0266: Cannot implicitly convert type 'char' to 'byte'. An explicit conversion exists (are you missing a cast?) // A = 'a', // CS0266 Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "'a'").WithArguments("char", "byte").WithLocation(3, 9)); } [Fact] public void CS0266ERR_NoImplicitConvCast06() { var source = @"enum E { A = 1, B = 1L // CS0266 } "; CreateCompilation(source).VerifyDiagnostics( // (4,9): error CS0266: Cannot implicitly convert type 'long' to 'int'. An explicit conversion exists (are you missing a cast?) // B = 1L // CS0266 Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "1L").WithArguments("long", "int").WithLocation(4, 9)); } [Fact] public void CS0266ERR_NoImplicitConvCast07() { // No errors var source = "enum E { A, B = A }"; CreateCompilation(source).VerifyDiagnostics(); } [Fact] public void CS0266ERR_NoImplicitConvCast08() { // No errors var source = @"enum E { A = 1, B } enum F { X = E.A + 1, Y } "; CreateCompilation(source).VerifyDiagnostics(); } [Fact] public void CS0266ERR_NoImplicitConvCast09() { var source = @"enum E { A = F.A, B = F.B, C = G.A, D = G.B, } enum F : short { A = 1, B } enum G : long { A = 1, B } "; CreateCompilation(source).VerifyDiagnostics( // (5,9): error CS0266: Cannot implicitly convert type 'long' to 'int'. An explicit conversion exists (are you missing a cast?) // C = G.A, Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "G.A").WithArguments("long", "int").WithLocation(5, 9), // (6,9): error CS0266: Cannot implicitly convert type 'long' to 'int'. An explicit conversion exists (are you missing a cast?) // D = G.B, Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "G.B").WithArguments("long", "int").WithLocation(6, 9)); } [Fact] public void CS0266ERR_NoImplicitConvCast10() { var source = @"class C { public const int F = D.G + 1; } class D { public const int G = E.H + 1; } class E { public const int H = 1L; } "; CreateCompilation(source).VerifyDiagnostics( // (11,26): error CS0266: Cannot implicitly convert type 'long' to 'int'. An explicit conversion exists (are you missing a cast?) // public const int H = 1L; Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "1L").WithArguments("long", "int").WithLocation(11, 26)); } [Fact()] public void CS0266ERR_NoImplicitConvCast11() { string text = @"class Program { static void Main(string[] args) { bool? b = true; int result = b ? 0 : 1; // Compiler error } } "; CreateCompilation(text). VerifyDiagnostics(Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "b").WithArguments("bool?", "bool")); } [WorkItem(541718, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541718")] [Fact] public void CS0266ERR_NoImplicitConvCast12() { string text = @" class C1 { public static void Main() { var cube = new int[Number.One][]; } } enum Number { One, Two } "; CreateCompilation(text).VerifyDiagnostics( // (6,28): error CS0266: Cannot implicitly convert type 'Number' to 'int'. An explicit conversion exists (are you missing a cast?) // var cube = new int[Number.One][]; Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "Number.One").WithArguments("Number", "int").WithLocation(6, 28)); } [WorkItem(541718, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541718")] [Fact] public void CS0266ERR_NoImplicitConvCast13() { string text = @" class C1 { public static void Main() { double x = 5; int[] arr4 = new int[x];// Invalid float y = 5; int[] arr5 = new int[y];// Invalid decimal z = 5; int[] arr6 = new int[z];// Invalid } } "; CreateCompilation(text). VerifyDiagnostics( // (7,30): error CS0266: Cannot implicitly convert type 'double' to 'int'. An explicit conversion exists (are you missing a cast?) // int[] arr4 = new int[x];// Invalid Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "x").WithArguments("double", "int").WithLocation(7, 30), // (10,30): error CS0266: Cannot implicitly convert type 'float' to 'int'. An explicit conversion exists (are you missing a cast?) // int[] arr5 = new int[y];// Invalid Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "y").WithArguments("float", "int").WithLocation(10, 30), // (13,30): error CS0266: Cannot implicitly convert type 'decimal' to 'int'. An explicit conversion exists (are you missing a cast?) // int[] arr6 = new int[z];// Invalid Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "z").WithArguments("decimal", "int").WithLocation(13, 30)); } [Fact] public void CS0266ERR_NoImplicitConvCast14() { string source = @" class C { public unsafe void M(int* p, object o) { _ = p[o]; // error with span on 'o' _ = p[0]; // ok } } "; CreateCompilation(source, options: TestOptions.UnsafeDebugDll).VerifyDiagnostics( // (6,15): error CS0266: Cannot implicitly convert type 'object' to 'int'. An explicit conversion exists (are you missing a cast?) // _ = p[o]; // error with span on 'o' Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "o").WithArguments("object", "int").WithLocation(6, 15)); } [Fact] public void CS0266ERR_NoImplicitConvCast15() { string source = @" class C { public void M(object o) { int[o] x; } } "; CreateCompilation(source).VerifyDiagnostics( // (6,12): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression) // int[o]; Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "[o]").WithLocation(6, 12), // (6,13): error CS0266: Cannot implicitly convert type 'object' to 'int'. An explicit conversion exists (are you missing a cast?) // int[o]; Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "o").WithArguments("object", "int").WithLocation(6, 13), // (6,16): warning CS0168: The variable 'x' is declared but never used // int[o] x; Diagnostic(ErrorCode.WRN_UnreferencedVar, "x").WithArguments("x").WithLocation(6, 16)); } [Fact] public void CS0269ERR_UseDefViolationOut() { var text = @" class C { public static void F(out int i) { try { // Assignment occurs, but compiler can't verify it i = 1; } catch { } int k = i; // CS0269 i = 1; } public static void Main() { int myInt; F(out myInt); } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_UseDefViolationOut, Line = 15, Column = 17 } }); } [Fact] public void CS0271ERR_InaccessibleGetter01() { var source = @"class C { internal static object P { private get; set; } public C Q { protected get { return null; } set { } } } class P { static void M(C c) { object o = C.P; M(c.Q); } }"; CreateCompilation(source).VerifyDiagnostics( // (10,20): error CS0271: The property or indexer 'C.P' cannot be used in this context because the get accessor is inaccessible Diagnostic(ErrorCode.ERR_InaccessibleGetter, "C.P").WithArguments("C.P").WithLocation(10, 20), // (11,11): error CS0271: The property or indexer 'C.Q' cannot be used in this context because the get accessor is inaccessible Diagnostic(ErrorCode.ERR_InaccessibleGetter, "c.Q").WithArguments("C.Q").WithLocation(11, 11)); } [Fact] public void CS0271ERR_InaccessibleGetter02() { var source = @"class A { public virtual object P { protected get; set; } } class B : A { public override object P { set { } } void M() { object o = P; // no error } } class C { void M(B b) { object o = b.P; // CS0271 } }"; CreateCompilation(source).VerifyDiagnostics( // (17,20): error CS0271: The property or indexer 'B.P' cannot be used in this context because the get accessor is inaccessible Diagnostic(ErrorCode.ERR_InaccessibleGetter, "b.P").WithArguments("B.P").WithLocation(17, 20)); } [Fact] public void CS0271ERR_InaccessibleGetter03() { var source = @"namespace N1 { class A { void M(N2.B b) { object o = b.P; } } } namespace N2 { class B : N1.A { public object P { protected get; set; } } }"; CreateCompilation(source).VerifyDiagnostics( // (7,24): error CS0271: The property or indexer 'N2.B.P' cannot be used in this context because the get accessor is inaccessible Diagnostic(ErrorCode.ERR_InaccessibleGetter, "b.P").WithArguments("N2.B.P").WithLocation(7, 24)); } [Fact] public void CS0271ERR_InaccessibleGetter04() { var source = @"class A { static public object P { protected get; set; } static internal object Q { private get; set; } static void M() { object o = B.Q; // no error o = A.Q; // no error } } class B : A { static void M() { object o = B.P; // no error o = P; // no error o = Q; // CS0271 } } class C { static void M() { object o = B.P; // CS0271 o = A.Q; // CS0271 } }"; CreateCompilation(source).VerifyDiagnostics( // (17,13): error CS0271: The property or indexer 'A.Q' cannot be used in this context because the get accessor is inaccessible Diagnostic(ErrorCode.ERR_InaccessibleGetter, "Q").WithArguments("A.Q").WithLocation(17, 13), // (24,20): error CS0271: The property or indexer 'A.P' cannot be used in this context because the get accessor is inaccessible Diagnostic(ErrorCode.ERR_InaccessibleGetter, "B.P").WithArguments("A.P").WithLocation(24, 20), // (25,13): error CS0271: The property or indexer 'A.Q' cannot be used in this context because the get accessor is inaccessible Diagnostic(ErrorCode.ERR_InaccessibleGetter, "A.Q").WithArguments("A.Q").WithLocation(25, 13)); } [Fact] public void CS0271ERR_InaccessibleGetter05() { CreateCompilation( @"class A { public object this[int x] { protected get { return null; } set { } } internal object this[string s] { private get { return null; } set { } } void M() { object o = new B()[""hello""]; // no error o = new A()[""hello""]; // no error } } class B : A { void M() { object o = new B()[0]; // no error o = this[0]; // no error o = this[""hello""]; // CS0271 } } class C { void M() { object o = new B()[0]; // CS0271 o = new A()[""hello""]; // CS0271 } }") .VerifyDiagnostics( // (17,13): error CS0271: The property or indexer 'A.this[string]' cannot be used in this context because the get accessor is inaccessible Diagnostic(ErrorCode.ERR_InaccessibleGetter, @"this[""hello""]").WithArguments("A.this[string]"), // (24,20): error CS0271: The property or indexer 'A.this[int]' cannot be used in this context because the get accessor is inaccessible Diagnostic(ErrorCode.ERR_InaccessibleGetter, "new B()[0]").WithArguments("A.this[int]"), // (25,13): error CS0271: The property or indexer 'A.this[string]' cannot be used in this context because the get accessor is inaccessible Diagnostic(ErrorCode.ERR_InaccessibleGetter, @"new A()[""hello""]").WithArguments("A.this[string]")); } [Fact] public void CS0272ERR_InaccessibleSetter01() { var source = @"namespace N { class C { internal object P { get; private set; } static public C Q { get { return null; } protected set { } } } class P { static void M(C c) { c.P = c; C.Q = c; } } }"; CreateCompilation(source).VerifyDiagnostics( // (12,13): error CS0272: The property or indexer 'N.C.P' cannot be used in this context because the set accessor is inaccessible Diagnostic(ErrorCode.ERR_InaccessibleSetter, "c.P").WithArguments("N.C.P").WithLocation(12, 13), // (13,13): error CS0272: The property or indexer 'N.C.Q' cannot be used in this context because the set accessor is inaccessible Diagnostic(ErrorCode.ERR_InaccessibleSetter, "C.Q").WithArguments("N.C.Q").WithLocation(13, 13)); } [Fact] public void CS0272ERR_InaccessibleSetter02() { var source = @"namespace N1 { abstract class A { public virtual object P { get; protected set; } } } namespace N2 { class B : N1.A { public override object P { get { return null; } } void M() { P = null; // no error } } } class C { void M(N2.B b) { b.P = null; // CS0272 } }"; CreateCompilation(source).VerifyDiagnostics( // (23,9): error CS0272: The property or indexer 'N2.B.P' cannot be used in this context because the set accessor is inaccessible Diagnostic(ErrorCode.ERR_InaccessibleSetter, "b.P").WithArguments("N2.B.P").WithLocation(23, 9)); } [Fact] public void CS0272ERR_InaccessibleSetter03() { CreateCompilation( @"namespace N1 { abstract class A { public virtual object this[int x] { get { return null; } protected set { } } } } namespace N2 { class B : N1.A { public override object this[int x] { get { return null; } } void M() { this[0] = null; // no error } } } class C { void M(N2.B b) { b[0] = null; // CS0272 } } ") .VerifyDiagnostics( // (23,9): error CS0272: The property or indexer 'N2.B.this[int]' cannot be used in this context because the set accessor is inaccessible Diagnostic(ErrorCode.ERR_InaccessibleSetter, "b[0]").WithArguments("N2.B.this[int]")); } [Fact] public void CS0283ERR_BadConstType() { // Test for both ERR_BadConstType and an error for RHS to ensure // the RHS is not reported multiple times (when calculating the // constant value for the symbol and also when binding). var source = @"struct S { static void M(object o) { const S s = 2; M(s); } } "; CreateCompilation(source).VerifyDiagnostics( // (5,15): error CS0283: The type 'S' cannot be declared const // const S s = 2; Diagnostic(ErrorCode.ERR_BadConstType, "S").WithArguments("S").WithLocation(5, 15), // (5,21): error CS0029: Cannot implicitly convert type 'int' to 'S' // const S s = 2; Diagnostic(ErrorCode.ERR_NoImplicitConv, "2").WithArguments("int", "S").WithLocation(5, 21)); } [Fact] public void CS0304ERR_NoNewTyvar01() { var source = @"struct S<T, U> where U : new() { void M<V>() { object o; o = new T(); o = new U(); o = new V(); } } class C<T, U> where T : struct where U : class { void M<V, W>() where V : struct where W : class, new() { object o; o = new T(); o = new U(); o = new V(); o = new W(); } }"; CreateCompilation(source).VerifyDiagnostics( // (6,13): error CS0304: Cannot create an instance of the variable type 'T' because it does not have the new() constraint Diagnostic(ErrorCode.ERR_NoNewTyvar, "new T()").WithArguments("T").WithLocation(6, 13), // (8, 13): error CS0304: Cannot create an instance of the variable type 'V' because it does not have the new() constraint Diagnostic(ErrorCode.ERR_NoNewTyvar, "new V()").WithArguments("V").WithLocation(8, 13), // (21,13): error CS0304: Cannot create an instance of the variable type 'U' because it does not have the new() constraint Diagnostic(ErrorCode.ERR_NoNewTyvar, "new U()").WithArguments("U").WithLocation(21, 13)); } [WorkItem(542377, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542377")] [Fact] public void CS0304ERR_NoNewTyvar02() { var source = @"struct S { } class C { } abstract class A<T> { public abstract U F<U>() where U : T; } class B1 : A<int> { public override U F<U>() { return new U(); } } class B2 : A<S> { public override U F<U>() { return new U(); } } class B3 : A<C> { public override U F<U>() { return new U(); } }"; CreateCompilation(source).VerifyDiagnostics( // (17,39): error CS0304: Cannot create an instance of the variable type 'U' because it does not have the new() constraint Diagnostic(ErrorCode.ERR_NoNewTyvar, "new U()").WithArguments("U").WithLocation(17, 39)); } [WorkItem(542547, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542547")] [Fact] public void CS0305ERR_BadArity() { var text = @" public class NormalType { public static int M1<T1>(T1 p1, T1 p2) { return 0; } public static int Main() { M1<int, >(10, 11); return -1; } }"; CreateCompilation(text).VerifyDiagnostics( // (7,17): error CS1031: Type expected Diagnostic(ErrorCode.ERR_TypeExpected, ">"), // (7,9): error CS0305: Using the generic method 'NormalType.M1<T1>(T1, T1)' requires 1 type arguments Diagnostic(ErrorCode.ERR_BadArity, "M1<int, >").WithArguments("NormalType.M1<T1>(T1, T1)", "method", "1")); } [Fact] public void CS0310ERR_NewConstraintNotSatisfied01() { var text = @"class A<T> { } class B { private B() { } } delegate void D(); enum E { } struct S { } class C<T, U> where T : new() { static void M<V>() where V : new() { M<A<int>>(); M<B>(); M<D>(); M<E>(); M<object>(); M<int>(); M<S>(); M<T>(); M<U>(); M<B, B>(); M<T, U>(); M<T, V>(); M<T[]>(); M<dynamic>(); } static void M<V, W>() where V : new() where W : new() { } }"; CreateCompilation(text).VerifyDiagnostics( // (14,9): error CS0310: 'B' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'V' in the generic type or method 'C<T, U>.M<V>()' Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, "M<B>").WithArguments("C<T, U>.M<V>()", "V", "B").WithLocation(14, 9), // (15,9): error CS0310: 'D' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'V' in the generic type or method 'C<T, U>.M<V>()' Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, "M<D>").WithArguments("C<T, U>.M<V>()", "V", "D").WithLocation(15, 9), // (21,9): error CS0310: 'U' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'V' in the generic type or method 'C<T, U>.M<V>()' Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, "M<U>").WithArguments("C<T, U>.M<V>()", "V", "U").WithLocation(21, 9), // (22,9): error CS0310: 'B' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'V' in the generic type or method 'C<T, U>.M<V, W>()' Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, "M<B, B>").WithArguments("C<T, U>.M<V, W>()", "V", "B").WithLocation(22, 9), // (22,9): error CS0310: 'B' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'W' in the generic type or method 'C<T, U>.M<V, W>()' Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, "M<B, B>").WithArguments("C<T, U>.M<V, W>()", "W", "B").WithLocation(22, 9), // (23,9): error CS0310: 'U' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'W' in the generic type or method 'C<T, U>.M<V, W>()' Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, "M<T, U>").WithArguments("C<T, U>.M<V, W>()", "W", "U").WithLocation(23, 9), // (25,9): error CS0310: 'T[]' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'V' in the generic type or method 'C<T, U>.M<V>()' Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, "M<T[]>").WithArguments("C<T, U>.M<V>()", "V", "T[]").WithLocation(25, 9)); } [Fact] public void CS0310ERR_NewConstraintNotSatisfied02() { var text = @"class A { } class B { internal B() { } } class C<T> where T : new() { internal static void M<U>() where U : new() { } internal static void E<U>(D<U> d) { } // Error: missing constraint on E<U> to satisfy constraint on D<U> } delegate T D<T>() where T : new(); static class E { internal static void M<T>(this object o) where T : new() { } internal static void F<T>(D<T> d) where T : new() { } } class F<T, U> where U : new() { } abstract class G { } class H : G { } interface I { } struct S { private S(object o) { } static void M() { C<A>.M<A>(); C<A>.M<B>(); C<B>.M<A>(); C<B>.M<B>(); C<G>.M<H>(); C<H>.M<G>(); C<I>.M<S>(); E.F(S.F<A>); E.F(S.F<B>); E.F(S.F<C<A>>); E.F(S.F<C<B>>); var o = new object(); o.M<A>(); o.M<B>(); o = new F<A, B>(); o = new F<B, A>(); } static T F<T>() { return default(T); } }"; // Note that none of these errors except the first one are reported by the native compiler, because // it does not report additional errors after an error is found in a formal parameter of a method. CreateCompilationWithMscorlib40(text, references: new[] { Net40.SystemCore }).VerifyDiagnostics( // (9,36): error CS0310: 'U' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method 'D<T>' // internal static void E<U>(D<U> d) { } // Error: missing constraint on E<U> to satisfy constraint on D<U> Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, "d").WithArguments("D<T>", "T", "U").WithLocation(9, 36), // (29,14): error CS0310: 'B' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'U' in the generic type or method 'C<A>.M<U>()' // C<A>.M<B>(); Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, "M<B>").WithArguments("C<A>.M<U>()", "U", "B").WithLocation(29, 14), // (30,11): error CS0310: 'B' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method 'C<T>' // C<B>.M<A>(); Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, "B").WithArguments("C<T>", "T", "B").WithLocation(30, 11), // (31,11): error CS0310: 'B' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method 'C<T>' // C<B>.M<B>(); Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, "B").WithArguments("C<T>", "T", "B").WithLocation(31, 11), // (31,14): error CS0310: 'B' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'U' in the generic type or method 'C<B>.M<U>()' // C<B>.M<B>(); Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, "M<B>").WithArguments("C<B>.M<U>()", "U", "B").WithLocation(31, 14), // (32,11): error CS0310: 'G' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method 'C<T>' // C<G>.M<H>(); Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, "G").WithArguments("C<T>", "T", "G").WithLocation(32, 11), // (33,14): error CS0310: 'G' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'U' in the generic type or method 'C<H>.M<U>()' // C<H>.M<G>(); Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, "M<G>").WithArguments("C<H>.M<U>()", "U", "G").WithLocation(33, 14), // (34,11): error CS0310: 'I' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method 'C<T>' // C<I>.M<S>(); Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, "I").WithArguments("C<T>", "T", "I").WithLocation(34, 11), // (36,11): error CS0310: 'B' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method 'E.F<T>(D<T>)' // E.F(S.F<B>); Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, "F").WithArguments("E.F<T>(D<T>)", "T", "B").WithLocation(36, 11), // (38,19): error CS0310: 'B' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method 'C<T>' // E.F(S.F<C<B>>); Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, "B").WithArguments("C<T>", "T", "B").WithLocation(38, 19), // This invocation of E.F(S.F<C<B>>) is an extremely interesting one. // First off, obviously the type argument for S.F is prima facie wrong, so we give an error for that above. // But what about the overload resolution problem in error recovery? Even though the argument is bad we still // might want to try to get an overload resolution result. Thus we must infer a type for T in E.F<T>(D<T>). // We must do overload resolution on an invocation S.F<C<B>>(). Overload resolution succeeds; it has no reason // to fail. (Overload resolution would fail if a formal parameter type of S.F<C<B>>() did not satisfy one of its // constraints, but there are no formal parameters. Also, there are no constraints at all on T in S.F<T>.) // // Thus T in D<T> is inferred to be C<B>, and thus T in E.F<T> is inferred to be C<B>. // // Now we check to see whether E.F<C<B>>(D<C<B>>) is applicable. It is inapplicable because // B fails to meet the constraints of T in C<T>. (C<B> does not fail to meet the constraints // of T in D<T> because C<B> has a public default parameterless ctor.) // // Therefore E.F<C.B>(S.F<C<B>>) fails overload resolution. Why? Because B is not valid for T in C<T>. // (We cannot say that the constraints on T in E.F<T> is unmet because again, C<B> meets the // constraint; it has a ctor.) So that is the error we report. // // This is arguably a "cascading" error; we have already reported an error for C<B> when the // argument was bound. Normally we avoid reporting "cascading" errors in overload resolution by // saying that an erroneous argument is implicitly convertible to any formal parameter type; // thus we avoid an erroneous expression from causing overload resolution to make every // candidate method inapplicable. (Though it might cause overload resolution to fail by making // every candidate method applicable, causing an ambiguity!) But the overload resolution // error here is not caused by an argument *conversion* in the first place; the overload // resolution error is caused because *the deduced formal parameter type is illegal.* // // We might want to put some gear in place to suppress this cascading error. It is not // entirely clear what that machinery might look like. // (38,11): error CS0310: 'B' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method 'C<T>' // E.F(S.F<C<B>>); Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, "F").WithArguments("C<T>", "T", "B").WithLocation(38, 11), // (41,11): error CS0310: 'B' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method 'E.M<T>(object)' // o.M<B>(); Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, "M<B>").WithArguments("E.M<T>(object)", "T", "B").WithLocation(41, 11), // (42,22): error CS0310: 'B' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'U' in the generic type or method 'F<T, U>' // o = new F<A, B>(); Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, "B").WithArguments("F<T, U>", "U", "B").WithLocation(42, 22)); } [Fact] public void CS0310ERR_NewConstraintNotSatisfied03() { var text = @"class A { } class B { private B() { } } class C<T, U> where U : struct { internal static void M<V>(V v) where V : new() { } void M() { A a = default(A); M(a); a.E(); B b = default(B); M(b); b.E(); T t = default(T); M(t); t.E(); U u1 = default(U); M(u1); u1.E(); U? u2 = null; M(u2); u2.E(); } } static class S { internal static void E<T>(this T t) where T : new() { } }"; CreateCompilationWithMscorlib40(text, references: new[] { Net40.SystemCore }).VerifyDiagnostics( // (15,9): error CS0310: 'B' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'V' in the generic type or method 'C<T, U>.M<V>(V)' // M(b); Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, "M").WithArguments("C<T, U>.M<V>(V)", "V", "B").WithLocation(15, 9), // (16,11): error CS0310: 'B' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method 'S.E<T>(T)' // b.E(); Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, "E").WithArguments("S.E<T>(T)", "T", "B").WithLocation(16, 11), // (18,9): error CS0310: 'T' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'V' in the generic type or method 'C<T, U>.M<V>(V)' // M(t); Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, "M").WithArguments("C<T, U>.M<V>(V)", "V", "T").WithLocation(18, 9), // (19,11): error CS0310: 'T' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method 'S.E<T>(T)' // t.E(); Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, "E").WithArguments("S.E<T>(T)", "T", "T").WithLocation(19, 11) ); } /// <summary> /// Constraint errors within aliases. /// </summary> [Fact] public void CS0310ERR_NewConstraintNotSatisfied04() { var text = @"using NA = N.A; using NB = N.B; using CA = N.C<N.A>; using CB = N.C<N.B>; namespace N { using CAD = C<N.A>.D; using CBD = C<N.B>.D; class A { } // public (default) .ctor class B { private B() { } } // private .ctor class C<T> where T : new() { internal static void M<U>() where U : new() { } internal class D { private D() { } // private .ctor internal static void M<U>() where U : new() { } } } class E { static void M() { C<N.A>.M<N.B>(); C<NB>.M<NA>(); C<C<N.A>.D>.M<N.A>(); C<N.A>.D.M<N.B>(); C<N.B>.D.M<N.A>(); CA.M<N.B>(); CB.M<N.A>(); CAD.M<N.B>(); CBD.M<N.A>(); C<CAD>.M<N.A>(); C<CBD>.M<N.A>(); } } }"; CreateCompilation(text).VerifyDiagnostics( // (4,7): error CS0310: 'B' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method 'C<T>' // using CB = N.C<N.B>; Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, "CB").WithArguments("N.C<T>", "T", "N.B").WithLocation(4, 7), // (8,11): error CS0310: 'B' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method 'C<T>' // using CBD = C<N.B>.D; Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, "CBD").WithArguments("N.C<T>", "T", "N.B").WithLocation(8, 11), // (24,20): error CS0310: 'B' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'U' in the generic type or method 'C<A>.M<U>()' // C<N.A>.M<N.B>(); Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, "M<N.B>").WithArguments("N.C<N.A>.M<U>()", "U", "N.B").WithLocation(24, 20), // (25,15): error CS0310: 'B' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method 'C<T>' // C<NB>.M<NA>(); Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, "NB").WithArguments("N.C<T>", "T", "N.B").WithLocation(25, 15), // (26,15): error CS0310: 'C<A>.D' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method 'C<T>' // C<C<N.A>.D>.M<N.A>(); Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, "C<N.A>.D").WithArguments("N.C<T>", "T", "N.C<N.A>.D").WithLocation(26, 15), // (27,22): error CS0310: 'B' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'U' in the generic type or method 'C<A>.D.M<U>()' // C<N.A>.D.M<N.B>(); Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, "M<N.B>").WithArguments("N.C<N.A>.D.M<U>()", "U", "N.B").WithLocation(27, 22), // (28,15): error CS0310: 'B' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method 'C<T>' // C<N.B>.D.M<N.A>(); Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, "N.B").WithArguments("N.C<T>", "T", "N.B").WithLocation(28, 15), // (29,16): error CS0310: 'B' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'U' in the generic type or method 'C<A>.M<U>()' // CA.M<N.B>(); Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, "M<N.B>").WithArguments("N.C<N.A>.M<U>()", "U", "N.B").WithLocation(29, 16), // (31,17): error CS0310: 'B' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'U' in the generic type or method 'C<A>.D.M<U>()' // CAD.M<N.B>(); Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, "M<N.B>").WithArguments("N.C<N.A>.D.M<U>()", "U", "N.B").WithLocation(31, 17), // (33,15): error CS0310: 'C<A>.D' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method 'C<T>' // C<CAD>.M<N.A>(); Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, "CAD").WithArguments("N.C<T>", "T", "N.C<N.A>.D").WithLocation(33, 15), // (34,15): error CS0310: 'C<B>.D' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method 'C<T>' // C<CBD>.M<N.A>(); Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, "CBD").WithArguments("N.C<T>", "T", "N.C<N.B>.D").WithLocation(34, 15)); } /// <summary> /// Constructors with optional and params args /// should not be considered parameterless. /// </summary> [Fact] public void CS0310ERR_NewConstraintNotSatisfied05() { var text = @"class A { public A() { } } class B { public B(object o = null) { } } class C { public C(params object[] args) { } } class D<T> where T : new() { static void M() { D<A>.M(); D<B>.M(); D<C>.M(); } }"; CreateCompilation(text).VerifyDiagnostics( // (18,11): error CS0310: 'B' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method 'D<T>' Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, "B").WithArguments("D<T>", "T", "B").WithLocation(18, 11), // (19,11): error CS0310: 'C' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method 'D<T>' Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, "C").WithArguments("D<T>", "T", "C").WithLocation(19, 11)); } [Fact] public void CS0311ERR_GenericConstraintNotSatisfiedRefType01() { var source = @"class A { } class B { } class C<T> where T : A { } class D { static void M<T>() where T : A { } static void M() { object o = new C<B>(); M<B>(); } }"; CreateCompilation(source).VerifyDiagnostics( // (9,26): error CS0311: The type 'B' cannot be used as type parameter 'T' in the generic type or method 'C<T>'. There is no implicit reference conversion from 'B' to 'A'. Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "B").WithArguments("C<T>", "A", "T", "B").WithLocation(9, 26), // (10,9): error CS0311: The type 'B' cannot be used as type parameter 'T' in the generic type or method 'D.M<T>()'. There is no implicit reference conversion from 'B' to 'A'. Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "M<B>").WithArguments("D.M<T>()", "A", "T", "B").WithLocation(10, 9)); } [Fact] public void CS0311ERR_GenericConstraintNotSatisfiedRefType02() { var source = @"class C<T, U> where U : T { void M<V>() where V : C<T, V> { } }"; CreateCompilation(source).VerifyDiagnostics( // (3,12): error CS0311: The type 'V' cannot be used as type parameter 'U' in the generic type or method 'C<T, U>'. There is no implicit reference conversion from 'V' to 'T'. Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "V").WithArguments("C<T, U>", "T", "U", "V").WithLocation(3, 12)); } [Fact] public void CS0311ERR_GenericConstraintNotSatisfiedRefType03() { var source = @"interface I<T> where T : I<I<T>> { }"; CreateCompilation(source).VerifyDiagnostics( // (1,13): error CS0311: The type 'I<T>' cannot be used as type parameter 'T' in the generic type or method 'I<T>'. There is no implicit reference conversion from 'I<T>' to 'I<I<I<T>>>'. Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "T").WithArguments("I<T>", "I<I<I<T>>>", "T", "I<T>").WithLocation(1, 13)); } [Fact] public void CS0311ERR_GenericConstraintNotSatisfiedRefType04() { var source = @"interface IA<T> { } interface IB<T> where T : IA<T> { } class C<T1, T2, T3> where T1 : IB<object[]> where T2 : IB<T2> where T3 : IB<IB<T3>[]>, IA<T3> { }"; CreateCompilation(source).VerifyDiagnostics( // (3,9): error CS0311: The type 'object[]' cannot be used as type parameter 'T' in the generic type or method 'IB<T>'. There is no implicit reference conversion from 'object[]' to 'IA<object[]>'. Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "T1").WithArguments("IB<T>", "IA<object[]>", "T", "object[]").WithLocation(3, 9), // (3,13): error CS0311: The type 'T2' cannot be used as type parameter 'T' in the generic type or method 'IB<T>'. There is no boxing conversion or type parameter conversion from 'T2' to 'IA<T2>'. Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedTyVar, "T2").WithArguments("IB<T>", "IA<T2>", "T", "T2").WithLocation(3, 13), // (3,17): error CS0311: The type 'IB<T3>[]' cannot be used as type parameter 'T' in the generic type or method 'IB<T>'. There is no implicit reference conversion from 'IB<T3>[]' to 'IA<IB<T3>[]>'. Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "T3").WithArguments("IB<T>", "IA<IB<T3>[]>", "T", "IB<T3>[]").WithLocation(3, 17)); } [Fact] public void CS0311ERR_GenericConstraintNotSatisfiedRefType05() { var source = @"namespace N { class C<T, U> where U : T { static object F() { return null; } static object G<V>() where V : T { return null; } static void M() { object o; o = C<int, object>.F(); o = N.C<int, int>.G<string>(); } } }"; CreateCompilation(source).VerifyDiagnostics( // (16,24): error CS0311: The type 'object' cannot be used as type parameter 'U' in the generic type or method 'C<T, U>'. There is no implicit reference conversion from 'object' to 'int'. // o = C<int, object>.F(); Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "object").WithArguments("N.C<T, U>", "int", "U", "object").WithLocation(16, 24), // (17,31): error CS0311: The type 'string' cannot be used as type parameter 'V' in the generic type or method 'C<int, int>.G<V>()'. There is no implicit reference conversion from 'string' to 'int'. // o = N.C<int, int>.G<string>(); Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "G<string>").WithArguments("N.C<int, int>.G<V>()", "int", "V", "string").WithLocation(17, 31)); } [Fact] public void CS0312ERR_GenericConstraintNotSatisfiedNullableEnum() { var source = @"class A<T, U> where T : U { } class B<T> { static void M<U>() where U : T { } static void M() { object o = new A<int?, int>(); B<int>.M<int?>(); } }"; CreateCompilation(source).VerifyDiagnostics( // (7,26): error CS0312: The type 'int?' cannot be used as type parameter 'T' in the generic type or method 'A<T, U>'. The nullable type 'int?' does not satisfy the constraint of 'int'. // object o = new A<int?, int>(); Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedNullableEnum, "int?").WithArguments("A<T, U>", "int", "T", "int?").WithLocation(7, 26), // (8,16): error CS0312: The type 'int?' cannot be used as type parameter 'U' in the generic type or method 'B<int>.M<U>()'. The nullable type 'int?' does not satisfy the constraint of 'int'. // B<int>.M<int?>(); Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedNullableEnum, "M<int?>").WithArguments("B<int>.M<U>()", "int", "U", "int?").WithLocation(8, 16)); } [Fact] public void CS0313ERR_GenericConstraintNotSatisfiedNullableInterface() { var source = @"interface I { } struct S : I { } class A<T> where T : I { } class B { static void M<T>() where T : I { } static void M() { object o = new A<S?>(); M<S?>(); } }"; CreateCompilation(source).VerifyDiagnostics( // (9,26): error CS0313: The type 'S?' cannot be used as type parameter 'T' in the generic type or method 'A<T>'. The nullable type 'S?' does not satisfy the constraint of 'I'. Nullable types can not satisfy any interface constraints. Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedNullableInterface, "S?").WithArguments("A<T>", "I", "T", "S?").WithLocation(9, 26), // (10,9): error CS0313: The type 'S?' cannot be used as type parameter 'T' in the generic type or method 'B.M<T>()'. The nullable type 'S?' does not satisfy the constraint of 'I'. Nullable types can not satisfy any interface constraints. Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedNullableInterface, "M<S?>").WithArguments("B.M<T>()", "I", "T", "S?").WithLocation(10, 9)); } [Fact] public void CS0314ERR_GenericConstraintNotSatisfiedTyVar01() { var source = @"class A { } class B<T> where T : A { } class C<T> where T : struct { static void M<U>() where U : A { } static void M() { object o = new B<T>(); M<T>(); } }"; CreateCompilation(source).VerifyDiagnostics( // (8,26): error CS0314: The type 'T' cannot be used as type parameter 'T' in the generic type or method 'B<T>'. There is no boxing conversion or type parameter conversion from 'T' to 'A'. Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedTyVar, "T").WithArguments("B<T>", "A", "T", "T").WithLocation(8, 26), // (9,9): error CS0314: The type 'T' cannot be used as type parameter 'U' in the generic type or method 'C<T>.M<U>()'. There is no boxing conversion or type parameter conversion from 'T' to 'A'. Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedTyVar, "M<T>").WithArguments("C<T>.M<U>()", "A", "U", "T").WithLocation(9, 9)); } [Fact] public void CS0314ERR_GenericConstraintNotSatisfiedTyVar02() { var source = @"class C<T, U> where U : T { void M<V>() where V : C<V, U> { } }"; CreateCompilation(source).VerifyDiagnostics( // (3,12): error CS0314: The type 'U' cannot be used as type parameter 'U' in the generic type or method 'C<T, U>'. There is no boxing conversion or type parameter conversion from 'U' to 'V'. Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedTyVar, "V").WithArguments("C<T, U>", "V", "U", "U").WithLocation(3, 12)); } [Fact] public void CS0314ERR_GenericConstraintNotSatisfiedTyVar03() { var source = @"interface IA<T> where T : IB<T> { } interface IB<T> where T : IA<T> { }"; CreateCompilation(source).VerifyDiagnostics( // (1,14): error CS0314: The type 'T' cannot be used as type parameter 'T' in the generic type or method 'IB<T>'. There is no boxing conversion or type parameter conversion from 'T' to 'IA<T>'. Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedTyVar, "T").WithArguments("IB<T>", "IA<T>", "T", "T").WithLocation(1, 14), // (2,14): error CS0314: The type 'T' cannot be used as type parameter 'T' in the generic type or method 'IA<T>'. There is no boxing conversion or type parameter conversion from 'T' to 'IB<T>'. Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedTyVar, "T").WithArguments("IA<T>", "IB<T>", "T", "T").WithLocation(2, 14)); } [Fact] public void CS0315ERR_GenericConstraintNotSatisfiedValType() { var source = @"class A { } class B<T> where T : A { } struct S { } class C { static void M<T, U>() where U : A { } static void M() { object o = new B<S>(); M<int, double>(); } }"; CreateCompilation(source).VerifyDiagnostics( // (9,26): error CS0315: The type 'S' cannot be used as type parameter 'T' in the generic type or method 'B<T>'. There is no boxing conversion from 'S' to 'A'. Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedValType, "S").WithArguments("B<T>", "A", "T", "S").WithLocation(9, 26), // (10,9): error CS0315: The type 'double?' cannot be used as type parameter 'U' in the generic type or method 'C.M<T, U>()'. There is no boxing conversion from 'double?' to 'A'. Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedValType, "M<int, double>").WithArguments("C.M<T, U>()", "A", "U", "double").WithLocation(10, 9)); } [Fact] public void CS0316ERR_DuplicateGeneratedName() { var text = @" public class Test { public int this[int value] // CS0316 { get { return 1; } set { } } public int this[char @value] // CS0316 { get { return 1; } set { } } public int this[string value] // no error since no setter { get { return 1; } } } "; CreateCompilation(text).VerifyDiagnostics( // (10,26): error CS0316: The parameter name 'value' conflicts with an automatically-generated parameter name // public int this[char @value] // CS0316 Diagnostic(ErrorCode.ERR_DuplicateGeneratedName, "@value").WithArguments("value").WithLocation(10, 26), // (4,25): error CS0316: The parameter name 'value' conflicts with an automatically-generated parameter name // public int this[int value] // CS0316 Diagnostic(ErrorCode.ERR_DuplicateGeneratedName, "value").WithArguments("value").WithLocation(4, 25)); } [Fact] public void CS0403ERR_TypeVarCantBeNull() { var source = @"interface I { } class A { } class B<T1, T2, T3, T4, T5, T6, T7> where T2 : class where T3 : struct where T4 : new() where T5 : I where T6 : A where T7 : T1 { static void M() { T1 t1 = null; T2 t2 = null; T3 t3 = null; T4 t4 = null; T5 t5 = null; T6 t6 = null; T7 t7 = null; } static T1 F1() { return null; } static T2 F2() { return null; } static T3 F3() { return null; } static T4 F4() { return null; } static T5 F5() { return null; } static T6 F6() { return null; } static T7 F7() { return null; } }"; CreateCompilation(source).VerifyDiagnostics( // (13,17): error CS0403: Cannot convert null to type parameter 'T1' because it could be a non-nullable value type. Consider using 'default(T1)' instead. // T1 t1 = null; Diagnostic(ErrorCode.ERR_TypeVarCantBeNull, "null").WithArguments("T1"), // (15,17): error CS0403: Cannot convert null to type parameter 'T3' because it could be a non-nullable value type. Consider using 'default(T3)' instead. // T3 t3 = null; Diagnostic(ErrorCode.ERR_TypeVarCantBeNull, "null").WithArguments("T3"), // (16,17): error CS0403: Cannot convert null to type parameter 'T4' because it could be a non-nullable value type. Consider using 'default(T4)' instead. // T4 t4 = null; Diagnostic(ErrorCode.ERR_TypeVarCantBeNull, "null").WithArguments("T4"), // (17,17): error CS0403: Cannot convert null to type parameter 'T5' because it could be a non-nullable value type. Consider using 'default(T5)' instead. // T5 t5 = null; Diagnostic(ErrorCode.ERR_TypeVarCantBeNull, "null").WithArguments("T5"), // (19,17): error CS0403: Cannot convert null to type parameter 'T7' because it could be a non-nullable value type. Consider using 'default(T7)' instead. // T7 t7 = null; Diagnostic(ErrorCode.ERR_TypeVarCantBeNull, "null").WithArguments("T7"), // (14,12): warning CS0219: The variable 't2' is assigned but its value is never used // T2 t2 = null; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "t2").WithArguments("t2"), // (18,12): warning CS0219: The variable 't6' is assigned but its value is never used // T6 t6 = null; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "t6").WithArguments("t6"), // (21,29): error CS0403: Cannot convert null to type parameter 'T1' because it could be a non-nullable value type. Consider using 'default(T1)' instead. // static T1 F1() { return null; } Diagnostic(ErrorCode.ERR_TypeVarCantBeNull, "null").WithArguments("T1"), // (23,29): error CS0403: Cannot convert null to type parameter 'T3' because it could be a non-nullable value type. Consider using 'default(T3)' instead. // static T3 F3() { return null; } Diagnostic(ErrorCode.ERR_TypeVarCantBeNull, "null").WithArguments("T3"), // (24,29): error CS0403: Cannot convert null to type parameter 'T4' because it could be a non-nullable value type. Consider using 'default(T4)' instead. // static T4 F4() { return null; } Diagnostic(ErrorCode.ERR_TypeVarCantBeNull, "null").WithArguments("T4"), // (25,29): error CS0403: Cannot convert null to type parameter 'T5' because it could be a non-nullable value type. Consider using 'default(T5)' instead. // static T5 F5() { return null; } Diagnostic(ErrorCode.ERR_TypeVarCantBeNull, "null").WithArguments("T5"), // (27,29): error CS0403: Cannot convert null to type parameter 'T7' because it could be a non-nullable value type. Consider using 'default(T7)' instead. // static T7 F7() { return null; } Diagnostic(ErrorCode.ERR_TypeVarCantBeNull, "null").WithArguments("T7") ); } [WorkItem(539901, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539901")] [Fact] public void CS0407ERR_BadRetType_01() { var text = @" public delegate int MyDelegate(); class C { MyDelegate d; public C() { d = new MyDelegate(F); // OK: F returns int d = new MyDelegate(G); // CS0407 - G doesn't return int } public int F() { return 1; } public void G() { } public static void Main() { C c1 = new C(); } } "; CreateCompilation(text, parseOptions: TestOptions.WithoutImprovedOverloadCandidates).VerifyDiagnostics( // (11,28): error CS0407: 'void C.G()' has the wrong return type // d = new MyDelegate(G); // CS0407 - G doesn't return int Diagnostic(ErrorCode.ERR_BadRetType, "G").WithArguments("C.G()", "void").WithLocation(11, 28) ); CreateCompilation(text).VerifyDiagnostics( // (11,28): error CS0407: 'void C.G()' has the wrong return type // d = new MyDelegate(G); // CS0407 - G doesn't return int Diagnostic(ErrorCode.ERR_BadRetType, "G").WithArguments("C.G()", "void").WithLocation(11, 28) ); } [WorkItem(925899, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/925899")] [Fact] public void CS0407ERR_BadRetType_02() { var text = @" using System; class C { public static void Main() { var oo = new Func<object, object>(x => 1); var os = new Func<object, string>(oo); var ss = new Func<string, string>(oo); } } "; CreateCompilation(text, parseOptions: TestOptions.WithoutImprovedOverloadCandidates).VerifyDiagnostics( // (10,43): error CS0407: 'object System.Func<object, object>.Invoke(object)' has the wrong return type // var os = new Func<object, string>(oo); Diagnostic(ErrorCode.ERR_BadRetType, "oo").WithArguments("System.Func<object, object>.Invoke(object)", "object").WithLocation(10, 43), // (11,43): error CS0407: 'object System.Func<object, object>.Invoke(object)' has the wrong return type // var ss = new Func<string, string>(oo); Diagnostic(ErrorCode.ERR_BadRetType, "oo").WithArguments("System.Func<object, object>.Invoke(object)", "object").WithLocation(11, 43) ); CreateCompilation(text).VerifyDiagnostics( // (10,43): error CS0407: 'object Func<object, object>.Invoke(object)' has the wrong return type // var os = new Func<object, string>(oo); Diagnostic(ErrorCode.ERR_BadRetType, "oo").WithArguments("System.Func<object, object>.Invoke(object)", "object").WithLocation(10, 43), // (11,43): error CS0407: 'object Func<object, object>.Invoke(object)' has the wrong return type // var ss = new Func<string, string>(oo); Diagnostic(ErrorCode.ERR_BadRetType, "oo").WithArguments("System.Func<object, object>.Invoke(object)", "object").WithLocation(11, 43) ); } [WorkItem(539924, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539924")] [Fact] public void CS0407ERR_BadRetType_03() { var text = @" delegate DerivedClass MyDerivedDelegate(DerivedClass x); public class BaseClass { public static BaseClass DelegatedMethod(BaseClass x) { System.Console.WriteLine(""Base""); return x; } } public class DerivedClass : BaseClass { public static DerivedClass DelegatedMethod(DerivedClass x) { System.Console.WriteLine(""Derived""); return x; } static void Main(string[] args) { MyDerivedDelegate goo1 = null; goo1 += BaseClass.DelegatedMethod; goo1 += DerivedClass.DelegatedMethod; goo1(new DerivedClass()); } } "; CreateCompilation(text).VerifyDiagnostics( // (21,17): error CS0407: 'BaseClass BaseClass.DelegatedMethod(BaseClass)' has the wrong return type Diagnostic(ErrorCode.ERR_BadRetType, "BaseClass.DelegatedMethod").WithArguments("BaseClass.DelegatedMethod(BaseClass)", "BaseClass")); } [WorkItem(3401, "DevDiv_Projects/Roslyn")] [Fact] public void CS0411ERR_CantInferMethTypeArgs01() { var text = @" class C { public void F<T>(T t) where T : C { } public static void Main() { C c = new C(); c.F(null); // CS0411 } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_CantInferMethTypeArgs, Line = 11, Column = 11 } }); } [WorkItem(2099, "https://devdiv.visualstudio.com:443/defaultcollection/DevDiv/_workitems/edit/2099")] [Fact(Skip = "529560")] public void CS0411ERR_CantInferMethTypeArgs02() { var text = @" public class MemberInitializerTest { delegate void D<T>(); public static void GenericMethod<T>() { } public static void Run() { var genD = (D<int>)GenericMethod; } }"; CreateCompilation(text).VerifyDiagnostics( // (8,20): error CS0030: The type arguments for method 'MemberInitializerTest.GenericMethod<T>()' cannot be inferred from the usage. Try specifying the type arguments explicitly. // var genD = (D<int>)GenericMethod; Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "(D<int>)GenericMethod").WithArguments("MemberInitializerTest.GenericMethod<T>()") ); } [Fact] public void CS0412ERR_LocalSameNameAsTypeParam() { var text = @" using System; class C { // Parameter name is the same as method type parameter name public void G<T>(int T) // CS0412 { } public void F<T>() { // Method local variable name is the same as method type // parameter name double T = 0.0; // CS0412 Console.WriteLine(T); } public static void Main() { } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_LocalSameNameAsTypeParam, Line = 7, Column = 26 }, new ErrorDescription { Code = (int)ErrorCode.ERR_LocalSameNameAsTypeParam, Line = 14, Column = 16 } }); } [Fact] public void CS0413ERR_AsWithTypeVar() { var source = @"interface I { } class A { } class B<T1, T2, T3, T4, T5, T6, T7> where T2 : class where T3 : struct where T4 : new() where T5 : I where T6 : A where T7 : T1 { static void M(object o) { o = o as T1; o = o as T2; o = o as T3; o = o as T4; o = o as T5; o = o as T6; o = o as T7; } }"; CreateCompilation(source).VerifyDiagnostics( // (13,13): error CS0413: The type parameter 'T1' cannot be used with the 'as' operator because it does not have a class type constraint nor a 'class' constraint Diagnostic(ErrorCode.ERR_AsWithTypeVar, "o as T1").WithArguments("T1").WithLocation(13, 13), // (15,13): error CS0413: The type parameter 'T3' cannot be used with the 'as' operator because it does not have a class type constraint nor a 'class' constraint Diagnostic(ErrorCode.ERR_AsWithTypeVar, "o as T3").WithArguments("T3").WithLocation(15, 13), // (16,13): error CS0413: The type parameter 'T4' cannot be used with the 'as' operator because it does not have a class type constraint nor a 'class' constraint Diagnostic(ErrorCode.ERR_AsWithTypeVar, "o as T4").WithArguments("T4").WithLocation(16, 13), // (17,13): error CS0413: The type parameter 'T5' cannot be used with the 'as' operator because it does not have a class type constraint nor a 'class' constraint Diagnostic(ErrorCode.ERR_AsWithTypeVar, "o as T5").WithArguments("T5").WithLocation(17, 13), // (19,13): error CS0413: The type parameter 'T7' cannot be used with the 'as' operator because it does not have a class type constraint nor a 'class' constraint Diagnostic(ErrorCode.ERR_AsWithTypeVar, "o as T7").WithArguments("T7").WithLocation(19, 13)); } [Fact] public void CS0417ERR_NewTyvarWithArgs01() { var source = @"struct S<T> where T : new() { T F(object o) { return new T(o); } U G<U, V>(object o) where U : new() where V : struct { return new U(new V(o)); } }"; CreateCompilation(source).VerifyDiagnostics( // (5,16): error CS0417: 'T': cannot provide arguments when creating an instance of a variable type Diagnostic(ErrorCode.ERR_NewTyvarWithArgs, "new T(o)").WithArguments("T").WithLocation(5, 16), // (11,16): error CS0417: 'U': cannot provide arguments when creating an instance of a variable type Diagnostic(ErrorCode.ERR_NewTyvarWithArgs, "new U(new V(o))").WithArguments("U").WithLocation(11, 16), // (11,22): error CS0417: 'V': cannot provide arguments when creating an instance of a variable type Diagnostic(ErrorCode.ERR_NewTyvarWithArgs, "new V(o)").WithArguments("V").WithLocation(11, 22)); } [Fact] public void CS0417ERR_NewTyvarWithArgs02() { var source = @"class C { public C() { } public C(object o) { } static void M<T>() where T : C, new() { new T(); new T(null); } }"; CreateCompilation(source).VerifyDiagnostics( // (8,9): error CS0417: 'T': cannot provide arguments when creating an instance of a variable type Diagnostic(ErrorCode.ERR_NewTyvarWithArgs, "new T(null)").WithArguments("T").WithLocation(8, 9)); } [Fact] public void CS0428ERR_MethGrpToNonDel() { var text = @" namespace ConsoleApplication1 { class Program { delegate int Del1(); delegate object Del2(); static void Main(string[] args) { ExampleClass ec = new ExampleClass(); int i = ec.Method1; Del1 d1 = ec.Method1; i = ec.Method1(); ec = ExampleClass.Method2; Del2 d2 = ExampleClass.Method2; ec = ExampleClass.Method2(); } } public class ExampleClass { public int Method1() { return 1; } public static ExampleClass Method2() { return null; } } }"; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_MethGrpToNonDel, Line = 12, Column = 24 }, new ErrorDescription { Code = (int)ErrorCode.ERR_MethGrpToNonDel, Line = 15, Column = 31 }}); } [Fact, WorkItem(528649, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528649")] public void CS0431ERR_ColColWithTypeAlias() { var text = @" using AliasC = C; class C { public class Goo { } } class Test { class C { } static int Main() { AliasC::Goo goo = new AliasC::Goo(); return 0; } }"; CreateCompilation(text).VerifyDiagnostics( Diagnostic(ErrorCode.ERR_ColColWithTypeAlias, "AliasC").WithArguments("AliasC"), Diagnostic(ErrorCode.ERR_ColColWithTypeAlias, "AliasC").WithArguments("AliasC")); } [WorkItem(3402, "DevDiv_Projects/Roslyn")] [Fact] public void CS0445ERR_UnboxNotLValue() { var text = @" namespace ConsoleApplication1 { // CS0445.CS class UnboxingTest { public static void Main() { Point p = new Point(); p.x = 1; p.y = 5; object obj = p; // Generates CS0445: ((Point)obj).x = 2; } } public struct Point { public int x; public int y; } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_UnboxNotLValue, Line = 15, Column = 13 } }); } [Fact] public void CS0446ERR_AnonMethGrpInForEach() { var text = @" class Tester { static void Main() { int[] intArray = new int[5]; foreach (int i in M) { } // CS0446 } static void M() { } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_AnonMethGrpInForEach, Line = 7, Column = 27 } }); } [Fact] [WorkItem(36203, "https://github.com/dotnet/roslyn/issues/36203")] public void CS0452_GenericConstraintError_HasHigherPriorityThanMethodOverloadError() { var code = @" class Code { void GenericMethod<T>(int i) where T: class => throw null; void GenericMethod<T>(string s) => throw null; void IncorrectMethodCall() { GenericMethod<int>(1); } }"; CreateCompilation(code).VerifyDiagnostics( // (9,9): error CS0452: The type 'int' must be a reference type in order to use it as parameter 'T' in the generic type or method 'Code.GenericMethod<T>(int)' Diagnostic(ErrorCode.ERR_RefConstraintNotSatisfied, "GenericMethod<int>").WithArguments("Code.GenericMethod<T>(int)", "T", "int").WithLocation(9, 9)); } [Fact] public void CS0457ERR_AmbigUDConv() { var text = @" public class A { } public class G0 { } public class G1<R> : G0 { } public class H0 { public static implicit operator G0(H0 h) { return new G0(); } } public class H1<R> : H0 { public static implicit operator G1<R>(H1<R> h) { return new G1<R>(); } } public class Test { public static void F0(G0 g) { } public static void Main() { H1<A> h1a = new H1<A>(); F0(h1a); // CS0457 } } "; CreateCompilation(text).VerifyDiagnostics( // (24,10): error CS0457: Ambiguous user defined conversions 'H1<A>.implicit operator G1<A>(H1<A>)' and 'H0.implicit operator G0(H0)' when converting from 'H1<A>' to 'G0' Diagnostic(ErrorCode.ERR_AmbigUDConv, "h1a").WithArguments("H1<A>.implicit operator G1<A>(H1<A>)", "H0.implicit operator G0(H0)", "H1<A>", "G0")); } [WorkItem(22306, "https://github.com/dotnet/roslyn/issues/22306")] [Fact] public void AddrOnReadOnlyLocal() { var text = @" class A { public unsafe void M1() { int[] ints = new int[] { 1, 2, 3 }; foreach (int i in ints) { int *j = &i; } fixed (int *i = &_i) { int **j = &i; } } private int _i = 0; } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(); } [Fact] public void CS0463ERR_DecConstError() { var text = @" using System; class MyClass { public static void Main() { const decimal myDec = 79000000000000000000000000000.0m + 79000000000000000000000000000.0m; // CS0463 Console.WriteLine(myDec.ToString()); } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_DecConstError, Line = 7, Column = 31 } }); } [WorkItem(543272, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543272")] [Fact] public void CS0463ERR_DecConstError_02() { var text = @" class MyClass { public static void Main() { decimal x1 = decimal.MaxValue + 1; // CS0463 decimal x2 = decimal.MaxValue + decimal.One; // CS0463 decimal x3 = decimal.MinValue - decimal.One; // CS0463 decimal x4 = decimal.MinValue + decimal.MinusOne; // CS0463 decimal x5 = decimal.MaxValue - decimal.MinValue; // CS0463 } } "; CreateCompilation(text).VerifyDiagnostics( // (6,22): error CS0463: Evaluation of the decimal constant expression failed // decimal x1 = decimal.MaxValue + 1; // CS0463 Diagnostic(ErrorCode.ERR_DecConstError, "decimal.MaxValue + 1"), // (7,22): error CS0463: Evaluation of the decimal constant expression failed // decimal x2 = decimal.MaxValue + decimal.One; // CS0463 Diagnostic(ErrorCode.ERR_DecConstError, "decimal.MaxValue + decimal.One"), // (8,22): error CS0463: Evaluation of the decimal constant expression failed // decimal x3 = decimal.MinValue - decimal.One; // CS0463 Diagnostic(ErrorCode.ERR_DecConstError, "decimal.MinValue - decimal.One"), // (9,22): error CS0463: Evaluation of the decimal constant expression failed // decimal x4 = decimal.MinValue + decimal.MinusOne; // CS0463 Diagnostic(ErrorCode.ERR_DecConstError, "decimal.MinValue + decimal.MinusOne"), // (10,22): error CS0463: Evaluation of the decimal constant expression failed // decimal x5 = decimal.MaxValue - decimal.MinValue; // CS0463 Diagnostic(ErrorCode.ERR_DecConstError, "decimal.MaxValue - decimal.MinValue")); } [Fact()] public void CS0471ERR_TypeArgsNotAllowedAmbig() { var text = @" class Test { public void F(bool x, bool y) {} public void F1() { int a = 1, b = 2, c = 3; F(a<b, c>(3)); // CS0471 // To resolve, try the following instead: // F((a<b), c>(3)); } } "; //Dev11 used to give 'The {1} '{0}' is not a generic method. If you intended an expression list, use parentheses around the &lt; expression.' //Roslyn will be satisfied with something less helpful. var noWarns = new Dictionary<string, ReportDiagnostic>(); noWarns.Add(MessageProvider.Instance.GetIdForErrorCode(219), ReportDiagnostic.Suppress); CreateCompilation(text, options: TestOptions.ReleaseDll.WithSpecificDiagnosticOptions(noWarns)).VerifyDiagnostics( // (8,13): error CS0118: 'b' is a variable but is used like a type // F(a<b, c>(3)); // CS0471 Diagnostic(ErrorCode.ERR_BadSKknown, "b").WithArguments("b", "variable", "type"), // (8,16): error CS0118: 'c' is a variable but is used like a type // F(a<b, c>(3)); // CS0471 Diagnostic(ErrorCode.ERR_BadSKknown, "c").WithArguments("c", "variable", "type"), // (8,11): error CS0307: The variable 'a' cannot be used with type arguments // F(a<b, c>(3)); // CS0471 Diagnostic(ErrorCode.ERR_TypeArgsNotAllowed, "a<b, c>").WithArguments("a", "variable")); } [Fact] public void CS0516ERR_RecursiveConstructorCall() { var text = @" namespace x { public class clx { public clx() : this() // CS0516 { } public static void Main() { } } } "; CreateCompilation(text).VerifyDiagnostics( // (6,22): error CS0516: Constructor 'x.clx.clx()' cannot call itself Diagnostic(ErrorCode.ERR_RecursiveConstructorCall, "this").WithArguments("x.clx.clx()")); } [WorkItem(751825, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/751825")] [Fact] public void Repro751825() { var text = @" public class A : A<int> { public A() : base() { } } "; CreateCompilation(text).VerifyDiagnostics( // (2,18): error CS0308: The non-generic type 'A' cannot be used with type arguments // public class A : A<int> Diagnostic(ErrorCode.ERR_HasNoTypeVars, "A<int>").WithArguments("A", "type"), // (4,18): error CS0516: Constructor 'A.A()' cannot call itself // public A() : base() { } Diagnostic(ErrorCode.ERR_RecursiveConstructorCall, "base").WithArguments("A.A()")); } [WorkItem(366, "https://github.com/dotnet/roslyn/issues/366")] [Fact] public void IndirectConstructorCycle() { var text = @" public class A { public A() : this(1) {} public A(int x) : this(string.Empty) {} public A(string s) : this(1) {} public A(long l) : this(double.MaxValue) {} public A(double d) : this(char.MaxValue) {} public A(char c) : this(long.MaxValue) {} public A(short s) : this() {} } "; CreateCompilation(text).VerifyDiagnostics( // (6,24): error CS0768: Constructor 'A.A(string)' cannot call itself through another constructor // public A(string s) : this(1) {} Diagnostic(ErrorCode.ERR_IndirectRecursiveConstructorCall, ": this(1)").WithArguments("A.A(string)").WithLocation(6, 24), // (9,22): error CS0768: Constructor 'A.A(char)' cannot call itself through another constructor // public A(char c) : this(long.MaxValue) {} Diagnostic(ErrorCode.ERR_IndirectRecursiveConstructorCall, ": this(long.MaxValue)").WithArguments("A.A(char)").WithLocation(9, 22) ); } [Fact] public void CS0517ERR_ObjectCallingBaseConstructor() { var text = @"namespace System { public class Void { } //just need the type to be defined public class Object { public Object() : base() { } } } "; CreateEmptyCompilation(text).VerifyDiagnostics( // (7,16): error CS0517: 'object' has no base class and cannot call a base constructor Diagnostic(ErrorCode.ERR_ObjectCallingBaseConstructor, "Object").WithArguments("object")); } [Fact] public void CS0522ERR_StructWithBaseConstructorCall() { var text = @" public class clx { public clx(int i) { } public static void Main() { } } public struct cly { public cly(int i):base(0) // CS0522 // try the following line instead // public cly(int i) { } } "; CreateCompilation(text).VerifyDiagnostics( // (15,11): error CS0522: 'cly': structs cannot call base class constructors Diagnostic(ErrorCode.ERR_StructWithBaseConstructorCall, "cly").WithArguments("cly")); } [Fact] public void CS0543ERR_EnumeratorOverflow01() { var source = @"enum E { A = int.MaxValue - 1, B, C, // CS0543 D, E = C, F, G = B, H, // CS0543 I } "; CreateCompilation(source).VerifyDiagnostics( // (5,5): error CS0543: 'E.C': the enumerator value is too large to fit in its type // C, // CS0543 Diagnostic(ErrorCode.ERR_EnumeratorOverflow, "C").WithArguments("E.C").WithLocation(5, 5), // (10,5): error CS0543: 'E.H': the enumerator value is too large to fit in its type // H, // CS0543 Diagnostic(ErrorCode.ERR_EnumeratorOverflow, "H").WithArguments("E.H").WithLocation(10, 5)); } [Fact] public void CS0543ERR_EnumeratorOverflow02() { var source = @"namespace N { enum E : byte { A = 255, B, C } enum F : short { A = 0x00ff, B = 0x7f00, C = A | B, D } enum G : int { X = int.MinValue, Y = X - 1, Z } } "; CreateCompilation(source).VerifyDiagnostics( // (3,30): error CS0543: 'E.B': the enumerator value is too large to fit in its type // enum E : byte { A = 255, B, C } Diagnostic(ErrorCode.ERR_EnumeratorOverflow, "B").WithArguments("N.E.B").WithLocation(3, 30), // (5,42): error CS0220: The operation overflows at compile time in checked mode // enum G : int { X = int.MinValue, Y = X - 1, Z } Diagnostic(ErrorCode.ERR_CheckedOverflow, "X - 1").WithLocation(5, 42), // (4,57): error CS0543: 'F.D': the enumerator value is too large to fit in its type // enum F : short { A = 0x00ff, B = 0x7f00, C = A | B, D } Diagnostic(ErrorCode.ERR_EnumeratorOverflow, "D").WithArguments("N.F.D").WithLocation(4, 57)); } [Fact] public void CS0543ERR_EnumeratorOverflow03() { var source = @"enum S8 : sbyte { A = sbyte.MinValue, B, C, D = -1, E, F, G = sbyte.MaxValue - 2, H, I, J, K } enum S16 : short { A = short.MinValue, B, C, D = -1, E, F, G = short.MaxValue - 2, H, I, J, K } enum S32 : int { A = int.MinValue, B, C, D = -1, E, F, G = int.MaxValue - 2, H, I, J, K } enum S64 : long { A = long.MinValue, B, C, D = -1, E, F, G = long.MaxValue - 2, H, I, J, K } enum U8 : byte { A = 0, B, C, D = byte.MaxValue - 2, E, F, G, H } enum U16 : ushort { A = 0, B, C, D = ushort.MaxValue - 2, E, F, G, H } enum U32 : uint { A = 0, B, C, D = uint.MaxValue - 2, E, F, G, H } enum U64 : ulong { A = 0, B, C, D = ulong.MaxValue - 2, E, F, G, H } "; CreateCompilation(source).VerifyDiagnostics( // (3,84): error CS0543: 'S32.J': the enumerator value is too large to fit in its type // enum S32 : int { A = int.MinValue, B, C, D = -1, E, F, G = int.MaxValue - 2, H, I, J, K } Diagnostic(ErrorCode.ERR_EnumeratorOverflow, "J").WithArguments("S32.J").WithLocation(3, 84), // (4,87): error CS0543: 'S64.J': the enumerator value is too large to fit in its type // enum S64 : long { A = long.MinValue, B, C, D = -1, E, F, G = long.MaxValue - 2, H, I, J, K } Diagnostic(ErrorCode.ERR_EnumeratorOverflow, "J").WithArguments("S64.J").WithLocation(4, 87), // (7,61): error CS0543: 'U32.G': the enumerator value is too large to fit in its type // enum U32 : uint { A = 0, B, C, D = uint.MaxValue - 2, E, F, G, H } Diagnostic(ErrorCode.ERR_EnumeratorOverflow, "G").WithArguments("U32.G").WithLocation(7, 61), // (6,65): error CS0543: 'U16.G': the enumerator value is too large to fit in its type // enum U16 : ushort { A = 0, B, C, D = ushort.MaxValue - 2, E, F, G, H } Diagnostic(ErrorCode.ERR_EnumeratorOverflow, "G").WithArguments("U16.G").WithLocation(6, 65), // (5,60): error CS0543: 'U8.G': the enumerator value is too large to fit in its type // enum U8 : byte { A = 0, B, C, D = byte.MaxValue - 2, E, F, G, H } Diagnostic(ErrorCode.ERR_EnumeratorOverflow, "G").WithArguments("U8.G").WithLocation(5, 60), // (2,90): error CS0543: 'S16.J': the enumerator value is too large to fit in its type // enum S16 : short { A = short.MinValue, B, C, D = -1, E, F, G = short.MaxValue - 2, H, I, J, K } Diagnostic(ErrorCode.ERR_EnumeratorOverflow, "J").WithArguments("S16.J").WithLocation(2, 90), // (1,89): error CS0543: 'S8.J': the enumerator value is too large to fit in its type // enum S8 : sbyte { A = sbyte.MinValue, B, C, D = -1, E, F, G = sbyte.MaxValue - 2, H, I, J, K } Diagnostic(ErrorCode.ERR_EnumeratorOverflow, "J").WithArguments("S8.J").WithLocation(1, 89), // (8,63): error CS0543: 'U64.G': the enumerator value is too large to fit in its type // enum U64 : ulong { A = 0, B, C, D = ulong.MaxValue - 2, E, F, G, H } Diagnostic(ErrorCode.ERR_EnumeratorOverflow, "G").WithArguments("U64.G").WithLocation(8, 63)); } [Fact] public void CS0543ERR_EnumeratorOverflow04() { string source = string.Format( @"enum A {0} enum B : byte {1} enum C : byte {2} enum D : sbyte {3}", CreateEnumValues(300, "E"), CreateEnumValues(256, "E"), CreateEnumValues(300, "E"), CreateEnumValues(300, "E", sbyte.MinValue)); CreateCompilation(source).VerifyDiagnostics( // (3,1443): error CS0543: 'C.E256': the enumerator value is too large to fit in its type // enum C : byte { E0, E1, E2, E3, E4, E5, E6, E7, E8, E9, E10, E11, E12, E13, E14, E15, E16, E17, E18, E19, E20, E21, E22, E23, E24, E25, E26, E27, E28, E29, E30, E31, E32, E33, E34, E35, E36, E37, E38, E39, E40, E41, E42, E43, E44, E45, E46, E47, E48, E49, E50, E51, E52, E53, E54, E55, E56, E57, E58, E59, E60, E61, E62, E63, E64, E65, E66, E67, E68, E69, E70, E71, E72, E73, E74, E75, E76, E77, E78, E79, E80, E81, E82, E83, E84, E85, E86, E87, E88, E89, E90, E91, E92, E93, E94, E95, E96, E97, E98, E99, E100, E101, E102, E103, E104, E105, E106, E107, E108, E109, E110, E111, E112, E113, E114, E115, E116, E117, E118, E119, E120, E121, E122, E123, E124, E125, E126, E127, E128, E129, E130, E131, E132, E133, E134, E135, E136, E137, E138, E139, E140, E141, E142, E143, E144, E145, E146, E147, E148, E149, E150, E151, E152, E153, E154, E155, E156, E157, E158, E159, E160, E161, E162, E163, E164, E165, E166, E167, E168, E169, E170, E171, E172, E173, E174, E175, E176, E177, E178, E179, E180, E181, E182, E183, E184, E185, E186, E187, E188, E189, E190, E191, E192, E193, E194, E195, E196, E197, E198, E199, E200, E201, E202, E203, E204, E205, E206, E207, E208, E209, E210, E211, E212, E213, E214, E215, E216, E217, E218, E219, E220, E221, E222, E223, E224, E225, E226, E227, E228, E229, E230, E231, E232, E233, E234, E235, E236, E237, E238, E239, E240, E241, E242, E243, E244, E245, E246, E247, E248, E249, E250, E251, E252, E253, E254, E255, E256, E257, E258, E259, E260, E261, E262, E263, E264, E265, E266, E267, E268, E269, E270, E271, E272, E273, E274, E275, E276, E277, E278, E279, E280, E281, E282, E283, E284, E285, E286, E287, E288, E289, E290, E291, E292, E293, E294, E295, E296, E297, E298, E299, } Diagnostic(ErrorCode.ERR_EnumeratorOverflow, "E256").WithArguments("C.E256").WithLocation(3, 1443), // (4,1451): error CS0543: 'D.E256': the enumerator value is too large to fit in its type // enum D : sbyte { E0 = -128, E1, E2, E3, E4, E5, E6, E7, E8, E9, E10, E11, E12, E13, E14, E15, E16, E17, E18, E19, E20, E21, E22, E23, E24, E25, E26, E27, E28, E29, E30, E31, E32, E33, E34, E35, E36, E37, E38, E39, E40, E41, E42, E43, E44, E45, E46, E47, E48, E49, E50, E51, E52, E53, E54, E55, E56, E57, E58, E59, E60, E61, E62, E63, E64, E65, E66, E67, E68, E69, E70, E71, E72, E73, E74, E75, E76, E77, E78, E79, E80, E81, E82, E83, E84, E85, E86, E87, E88, E89, E90, E91, E92, E93, E94, E95, E96, E97, E98, E99, E100, E101, E102, E103, E104, E105, E106, E107, E108, E109, E110, E111, E112, E113, E114, E115, E116, E117, E118, E119, E120, E121, E122, E123, E124, E125, E126, E127, E128, E129, E130, E131, E132, E133, E134, E135, E136, E137, E138, E139, E140, E141, E142, E143, E144, E145, E146, E147, E148, E149, E150, E151, E152, E153, E154, E155, E156, E157, E158, E159, E160, E161, E162, E163, E164, E165, E166, E167, E168, E169, E170, E171, E172, E173, E174, E175, E176, E177, E178, E179, E180, E181, E182, E183, E184, E185, E186, E187, E188, E189, E190, E191, E192, E193, E194, E195, E196, E197, E198, E199, E200, E201, E202, E203, E204, E205, E206, E207, E208, E209, E210, E211, E212, E213, E214, E215, E216, E217, E218, E219, E220, E221, E222, E223, E224, E225, E226, E227, E228, E229, E230, E231, E232, E233, E234, E235, E236, E237, E238, E239, E240, E241, E242, E243, E244, E245, E246, E247, E248, E249, E250, E251, E252, E253, E254, E255, E256, E257, E258, E259, E260, E261, E262, E263, E264, E265, E266, E267, E268, E269, E270, E271, E272, E273, E274, E275, E276, E277, E278, E279, E280, E281, E282, E283, E284, E285, E286, E287, E288, E289, E290, E291, E292, E293, E294, E295, E296, E297, E298, E299, } Diagnostic(ErrorCode.ERR_EnumeratorOverflow, "E256").WithArguments("D.E256").WithLocation(4, 1451)); } // Create string "{ E0, E1, ..., En }" private static string CreateEnumValues(int count, string prefix, int? initialValue = null) { var builder = new System.Text.StringBuilder("{ "); for (int i = 0; i < count; i++) { builder.Append(prefix); builder.Append(i); if ((i == 0) && (initialValue != null)) { builder.AppendFormat(" = {0}", initialValue.Value); } builder.Append(", "); } builder.Append(" }"); return builder.ToString(); } // CS0570 --> Symbols\OverriddenOrHiddenMembersTests.cs [Fact] public void CS0571ERR_CantCallSpecialMethod01() { var source = @"class C { protected virtual object P { get; set; } static object Q { get; set; } void M(D d) { this.set_P(get_Q()); D.set_Q(d.get_P()); ((this.get_P))(); } } class D : C { protected override object P { get { return null; } set { } } } "; CreateCompilation(source).VerifyDiagnostics( // (7,20): error CS0571: 'C.Q.get': cannot explicitly call operator or accessor // this.set_P(get_Q()); Diagnostic(ErrorCode.ERR_CantCallSpecialMethod, "get_Q").WithArguments("C.Q.get").WithLocation(7, 20), // (7,14): error CS0571: 'C.P.set': cannot explicitly call operator or accessor // this.set_P(get_Q()); Diagnostic(ErrorCode.ERR_CantCallSpecialMethod, "set_P").WithArguments("C.P.set").WithLocation(7, 14), // (8,19): error CS0571: 'D.P.get': cannot explicitly call operator or accessor // D.set_Q(d.get_P()); Diagnostic(ErrorCode.ERR_CantCallSpecialMethod, "get_P").WithArguments("D.P.get").WithLocation(8, 19), // (8,11): error CS0571: 'C.Q.set': cannot explicitly call operator or accessor // D.set_Q(d.get_P()); Diagnostic(ErrorCode.ERR_CantCallSpecialMethod, "set_Q").WithArguments("C.Q.set").WithLocation(8, 11), // (9,16): error CS0571: 'C.P.get': cannot explicitly call operator or accessor // ((this.get_P))(); Diagnostic(ErrorCode.ERR_CantCallSpecialMethod, "get_P").WithArguments("C.P.get").WithLocation(9, 16)); // CONSIDER: Dev10 reports 'C.P.get' for the fourth error. Roslyn reports 'D.P.get' // because it is in the more-derived type and because Binder.LookupMembersInClass // calls MergeHidingLookups(D.P.get, C.P.get) with both arguments non-viable // (i.e. keeps current, since new value isn't better). } [Fact] public void CS0571ERR_CantCallSpecialMethod02() { var source = @"using System; namespace A.B { class C { object P { get; set; } static object Q { get { return 0; } set { } } void M(C c) { Func<object> f = get_P; f = C.get_Q; Action<object> a = c.set_P; a = set_Q; } } } "; CreateCompilation(source).VerifyDiagnostics( // (10,30): error CS0571: 'C.P.get': cannot explicitly call operator or accessor // Func<object> f = get_P; Diagnostic(ErrorCode.ERR_CantCallSpecialMethod, "get_P").WithArguments("A.B.C.P.get").WithLocation(10, 30), // (11,19): error CS0571: 'C.Q.get': cannot explicitly call operator or accessor // f = C.get_Q; Diagnostic(ErrorCode.ERR_CantCallSpecialMethod, "get_Q").WithArguments("A.B.C.Q.get").WithLocation(11, 19), // (12,34): error CS0571: 'C.P.set': cannot explicitly call operator or accessor // Action<object> a = c.set_P; Diagnostic(ErrorCode.ERR_CantCallSpecialMethod, "set_P").WithArguments("A.B.C.P.set").WithLocation(12, 34), // (13,17): error CS0571: 'C.Q.set': cannot explicitly call operator or accessor // a = set_Q; Diagnostic(ErrorCode.ERR_CantCallSpecialMethod, "set_Q").WithArguments("A.B.C.Q.set").WithLocation(13, 17)); } /// <summary> /// No errors should be reported if method with /// accessor name is defined in different class. /// </summary> [Fact] public void CS0571ERR_CantCallSpecialMethod03() { var source = @"class A { public object get_P() { return null; } } class B : A { public object P { get; set; } void M() { object o = this.P; o = this.get_P(); } } class C { void M(B b) { object o = b.P; o = b.get_P(); } } "; CreateCompilation(source).VerifyDiagnostics(); } [Fact()] public void CS0571ERR_CantCallSpecialMethod04() { var compilation = CreateCompilation( @"public class MyClass { public static MyClass operator ++(MyClass c) { return null; } public static void M() { op_Increment(null); // CS0571 } } ").VerifyDiagnostics( // (9,9): error CS0571: 'MyClass.operator ++(MyClass)': cannot explicitly call operator or accessor // op_Increment(null); // CS0571 Diagnostic(ErrorCode.ERR_CantCallSpecialMethod, "op_Increment").WithArguments("MyClass.operator ++(MyClass)")); } [Fact] public void CS0571ERR_CantCallSpecialMethod05() { var source = @" using System; public class C { public static void M() { IntPtr.op_Addition(default(IntPtr), 0); IntPtr.op_Subtraction(default(IntPtr), 0); IntPtr.op_Equality(default(IntPtr), default(IntPtr)); IntPtr.op_Inequality(default(IntPtr), default(IntPtr)); IntPtr.op_Explicit(0); } } "; CreateCompilation(source).VerifyDiagnostics( // (7,16): error CS0571: 'IntPtr.operator +(IntPtr, int)': cannot explicitly call operator or accessor // IntPtr.op_Addition(default(IntPtr), 0); Diagnostic(ErrorCode.ERR_CantCallSpecialMethod, "op_Addition").WithArguments("System.IntPtr.operator +(System.IntPtr, int)").WithLocation(7, 16), // (8,16): error CS0571: 'IntPtr.operator -(IntPtr, int)': cannot explicitly call operator or accessor // IntPtr.op_Subtraction(default(IntPtr), 0); Diagnostic(ErrorCode.ERR_CantCallSpecialMethod, "op_Subtraction").WithArguments("System.IntPtr.operator -(System.IntPtr, int)").WithLocation(8, 16), // (9,16): error CS0571: 'IntPtr.operator ==(IntPtr, IntPtr)': cannot explicitly call operator or accessor // IntPtr.op_Equality(default(IntPtr), default(IntPtr)); Diagnostic(ErrorCode.ERR_CantCallSpecialMethod, "op_Equality").WithArguments("System.IntPtr.operator ==(System.IntPtr, System.IntPtr)").WithLocation(9, 16), // (10,16): error CS0571: 'IntPtr.operator !=(IntPtr, IntPtr)': cannot explicitly call operator or accessor // IntPtr.op_Inequality(default(IntPtr), default(IntPtr)); Diagnostic(ErrorCode.ERR_CantCallSpecialMethod, "op_Inequality").WithArguments("System.IntPtr.operator !=(System.IntPtr, System.IntPtr)").WithLocation(10, 16), // (11,16): error CS0571: 'IntPtr.explicit operator IntPtr(int)': cannot explicitly call operator or accessor // IntPtr.op_Explicit(0); Diagnostic(ErrorCode.ERR_CantCallSpecialMethod, "op_Explicit").WithArguments("System.IntPtr.explicit operator System.IntPtr(int)").WithLocation(11, 16)); } [Fact] public void CS0572ERR_BadTypeReference() { var text = @" using System; class C { public class Inner { public static int v = 9; } } class D : C { public static void Main() { C cValue = new C(); Console.WriteLine(cValue.Inner.v); // CS0572 // try the following line instead // Console.WriteLine(C.Inner.v); } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_BadTypeReference, Line = 16, Column = 32 } }); } [Fact] public void CS0574ERR_BadDestructorName() { var test = @" namespace x { public class iii { ~iiii(){} public static void Main() { } } } "; CreateCompilation(test).VerifyDiagnostics( // (6,10): error CS0574: Name of destructor must match name of type // ~iiii(){} Diagnostic(ErrorCode.ERR_BadDestructorName, "iiii").WithLocation(6, 10)); } [WorkItem(541951, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541951")] [Fact] public void CS0611ERR_ArrayElementCantBeRefAny() { var text = @" public class Test { public System.TypedReference[] x; public System.RuntimeArgumentHandle[][] y; } "; var comp = CreateCompilation(text, targetFramework: TargetFramework.Mscorlib45); comp.VerifyDiagnostics( // (4,12): error CS0611: Array elements cannot be of type 'System.TypedReference' // public System.TypedReference[] x; Diagnostic(ErrorCode.ERR_ArrayElementCantBeRefAny, "System.TypedReference").WithArguments("System.TypedReference").WithLocation(4, 12), // (5,12): error CS0611: Array elements cannot be of type 'System.RuntimeArgumentHandle' // public System.RuntimeArgumentHandle[][] y; Diagnostic(ErrorCode.ERR_ArrayElementCantBeRefAny, "System.RuntimeArgumentHandle").WithArguments("System.RuntimeArgumentHandle").WithLocation(5, 12)); } [WorkItem(541951, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541951")] [Fact] public void CS0611ERR_ArrayElementCantBeRefAny_1() { var text = @"using System; class C { static void M() { var x = new[] { new ArgIterator() }; var y = new[] { new TypedReference() }; var z = new[] { new RuntimeArgumentHandle() }; } }"; var comp = CreateCompilation(text, targetFramework: TargetFramework.Mscorlib45); comp.VerifyDiagnostics( // (6,17): error CS0611: Array elements cannot be of type 'System.ArgIterator' // var x = new[] { new ArgIterator() }; Diagnostic(ErrorCode.ERR_ArrayElementCantBeRefAny, "new[] { new ArgIterator() }").WithArguments("System.ArgIterator").WithLocation(6, 17), // (7,17): error CS0611: Array elements cannot be of type 'System.TypedReference' // var y = new[] { new TypedReference() }; Diagnostic(ErrorCode.ERR_ArrayElementCantBeRefAny, "new[] { new TypedReference() }").WithArguments("System.TypedReference").WithLocation(7, 17), // (8,17): error CS0611: Array elements cannot be of type 'System.RuntimeArgumentHandle' // var z = new[] { new RuntimeArgumentHandle() }; Diagnostic(ErrorCode.ERR_ArrayElementCantBeRefAny, "new[] { new RuntimeArgumentHandle() }").WithArguments("System.RuntimeArgumentHandle").WithLocation(8, 17)); } [Fact, WorkItem(546062, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546062")] public void CS0619ERR_DeprecatedSymbolStr() { var text = @" using System; namespace a { [Obsolete] class C1 { } [Obsolete(""Obsolescence message"", true)] interface I1 { } public class CI1 : I1 { } public class MainClass { public static void Main() { } } } "; CreateCompilation(text).VerifyDiagnostics( // (11,24): error CS0619: 'a.I1' is obsolete: 'Obsolescence message' // public class CI1 : I1 { } Diagnostic(ErrorCode.ERR_DeprecatedSymbolStr, "I1").WithArguments("a.I1", "Obsolescence message") ); } [Fact] public void CS0622ERR_ArrayInitToNonArrayType() { var text = @" public class Test { public static void Main () { Test t = { new Test() }; // CS0622 } }"; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_ArrayInitToNonArrayType, Line = 6, Column = 18 } }); } [Fact] public void CS0623ERR_ArrayInitInBadPlace() { var text = @" class X { public void goo(int a) { int[] x = { { 4 } }; //CS0623 } }"; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_ArrayInitInBadPlace, Line = 6, Column = 21 } }); } [Fact] public void CS0631ERR_IllegalRefParam() { var compilation = CreateCompilation( @"interface I { object this[ref object index] { get; set; } } class C { internal object this[object x, out object y] { get { y = null; return null; } } } struct S { internal object this[out int x, out int y] { set { x = 0; y = 0; } } }"); compilation.VerifyDiagnostics( // (3,17): error CS0631: ref and out are not valid in this context Diagnostic(ErrorCode.ERR_IllegalRefParam, "ref").WithLocation(3, 17), // (7,36): error CS0631: ref and out are not valid in this context Diagnostic(ErrorCode.ERR_IllegalRefParam, "out").WithLocation(7, 36), // (11,26): error CS0631: ref and out are not valid in this context Diagnostic(ErrorCode.ERR_IllegalRefParam, "out").WithLocation(11, 26), // (11,37): error CS0631: ref and out are not valid in this context Diagnostic(ErrorCode.ERR_IllegalRefParam, "out").WithLocation(11, 37)); } [WorkItem(529305, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529305")] [Fact()] public void CS0664ERR_LiteralDoubleCast() { var text = @" class Example { static void Main() { // CS0664, because 1.0 is interpreted as a double: decimal d1 = 1.0; float f1 = 2.0; } }"; var compilation = CreateCompilation(text); compilation.VerifyDiagnostics( // (7,22): error CS0664: Literal of type double cannot be implicitly converted to type 'decimal'; use an 'M' suffix to create a literal of this type // decimal d1 = 1.0; Diagnostic(ErrorCode.ERR_LiteralDoubleCast, "1.0").WithArguments("M", "decimal").WithLocation(7, 22), // (8,20): error CS0664: Literal of type double cannot be implicitly converted to type 'float'; use an 'F' suffix to create a literal of this type // float f1 = 2.0; Diagnostic(ErrorCode.ERR_LiteralDoubleCast, "2.0").WithArguments("F", "float").WithLocation(8, 20), // (7,17): warning CS0219: The variable 'd1' is assigned but its value is never used // decimal d1 = 1.0; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "d1").WithArguments("d1").WithLocation(7, 17), // (8,15): warning CS0219: The variable 'f1' is assigned but its value is never used // float f1 = 2.0; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "f1").WithArguments("f1").WithLocation(8, 15)); } [Fact] public void CS0670ERR_FieldCantHaveVoidType() { CreateCompilation(@" class C { void x = default(void); }").VerifyDiagnostics( // (4,22): error CS1547: Keyword 'void' cannot be used in this context Diagnostic(ErrorCode.ERR_NoVoidHere, "void"), // (4,5): error CS0670: Field cannot have void type Diagnostic(ErrorCode.ERR_FieldCantHaveVoidType, "void")); } [Fact] public void CS0670ERR_FieldCantHaveVoidType_Var() { CreateCompilationWithMscorlib45(@" var x = default(void); ", parseOptions: TestOptions.Script).VerifyDiagnostics( // (2,17): error CS1547: Keyword 'void' cannot be used in this context Diagnostic(ErrorCode.ERR_NoVoidHere, "void"), // (2,1): error CS0670: Field cannot have void type Diagnostic(ErrorCode.ERR_FieldCantHaveVoidType, "var")); } [WorkItem(538016, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538016")] [Fact] public void CS0687ERR_AliasQualAsExpression() { var text = @" using M = Test; using System; public class Test { public static int x = 77; public static void Main() { Console.WriteLine(M::x); // CS0687 } }"; CreateCompilation(text).VerifyDiagnostics( Diagnostic(ErrorCode.ERR_ColColWithTypeAlias, "M").WithArguments("M") ); } [Fact] public void CS0704ERR_LookupInTypeVariable() { var text = @"using System; class A { internal class B : Attribute { } internal class C<T> { } } class D<T> where T : A { class E : T.B { } interface I<U> where U : T.B { } [T.B] static object M<U>() { T.C<object> b1 = new T.C<object>(); T<U>.B b2 = null; b1 = default(T.B); object o = typeof(T.C<A>); o = o as T.B; return b1; } }"; CreateCompilation(text).VerifyDiagnostics( // (9,15): error CS0704: Cannot do member lookup in 'T' because it is a type parameter class E : T.B { } Diagnostic(ErrorCode.ERR_LookupInTypeVariable, "T.B").WithArguments("T"), // (10,30): error CS0704: Cannot do member lookup in 'T' because it is a type parameter // interface I<U> where U : T.B { } Diagnostic(ErrorCode.ERR_LookupInTypeVariable, "T.B").WithArguments("T"), // (11,6): error CS0704: Cannot do member lookup in 'T' because it is a type parameter // [T.B] Diagnostic(ErrorCode.ERR_LookupInTypeVariable, "T.B").WithArguments("T"), // (14,9): error CS0704: Cannot do member lookup in 'T' because it is a type parameter // T.C<object> b1 = new T.C<object>(); Diagnostic(ErrorCode.ERR_LookupInTypeVariable, "T.C<object>").WithArguments("T"), // (14,30): error CS0704: Cannot do member lookup in 'T' because it is a type parameter // T.C<object> b1 = new T.C<object>(); Diagnostic(ErrorCode.ERR_LookupInTypeVariable, "T.C<object>").WithArguments("T"), // (15,9): error CS0307: The type parameter 'T' cannot be used with type arguments // T<U>.B b2 = null; Diagnostic(ErrorCode.ERR_TypeArgsNotAllowed, "T<U>").WithArguments("T", "type parameter"), // (16,22): error CS0704: Cannot do member lookup in 'T' because it is a type parameter // b1 = default(T.B); Diagnostic(ErrorCode.ERR_LookupInTypeVariable, "T.B").WithArguments("T"), // (17,27): error CS0704: Cannot do member lookup in 'T' because it is a type parameter // object o = typeof(T.C<A>); Diagnostic(ErrorCode.ERR_LookupInTypeVariable, "T.C<A>").WithArguments("T"), // (18,18): error CS0704: Cannot do member lookup in 'T' because it is a type parameter // o = o as T.B; Diagnostic(ErrorCode.ERR_LookupInTypeVariable, "T.B").WithArguments("T") ); } [Fact] public void CS0712ERR_InstantiatingStaticClass() { var text = @" public static class SC { } public class CMain { public static void Main() { SC sc = new SC(); // CS0712 } }"; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_InstantiatingStaticClass, Line = 10, Column = 17 }, new ErrorDescription { Code = (int)ErrorCode.ERR_VarDeclIsStaticClass, Line = 10, Column = 9 }}); } [Fact] public void CS0716ERR_ConvertToStaticClass() { var text = @" public static class SC { static void F() { } } public class Test { public static void Main() { object o = new object(); System.Console.WriteLine((SC)o); // CS0716 } }"; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_ConvertToStaticClass, Line = 12, Column = 34 } }); } [Fact] [WorkItem(36203, "https://github.com/dotnet/roslyn/issues/36203")] public void CS0718_StaticClassError_HasHigherPriorityThanMethodOverloadError() { var code = @" static class StaticClass { } class Code { void GenericMethod<T>(int i) => throw null; void GenericMethod<T>(string s) => throw null; void IncorrectMethodCall() { GenericMethod<StaticClass>(1); } }"; CreateCompilation(code).VerifyDiagnostics( // (11,9): error CS0718: 'StaticClass': static types cannot be used as type arguments Diagnostic(ErrorCode.ERR_GenericArgIsStaticClass, "GenericMethod<StaticClass>").WithArguments("StaticClass").WithLocation(11, 9)); } [Fact] public void CS0723ERR_VarDeclIsStaticClass_Locals() { CreateCompilation( @"static class SC { static void M() { SC sc = null; // CS0723 N(sc); var sc2 = new SC(); } static void N(object o) { } }").VerifyDiagnostics( // (5,9): error CS0723: Cannot declare a variable of static type 'SC' Diagnostic(ErrorCode.ERR_VarDeclIsStaticClass, "SC").WithArguments("SC"), // (7,19): error CS0712: Cannot create an instance of the static class 'SC' Diagnostic(ErrorCode.ERR_InstantiatingStaticClass, "new SC()").WithArguments("SC"), // (7,9): error CS0723: Cannot declare a variable of static type 'SC' Diagnostic(ErrorCode.ERR_VarDeclIsStaticClass, "var").WithArguments("SC")); } [Fact] public void CS0723ERR_VarDeclIsStaticClass_Fields() { CreateCompilationWithMscorlib45(@" static class SC {} var sc2 = new SC(); ", parseOptions: TestOptions.Script).VerifyDiagnostics( // (4,5): error CS0723: Cannot declare a variable of static type 'SC' Diagnostic(ErrorCode.ERR_VarDeclIsStaticClass, "sc2").WithArguments("SC"), // (4,11): error CS0712: Cannot create an instance of the static class 'SC' Diagnostic(ErrorCode.ERR_InstantiatingStaticClass, "new SC()").WithArguments("SC")); } [Fact] public void CS0724ERR_BadEmptyThrowInFinally() { var text = @" using System; class X { static void Test() { try { throw new Exception(); } catch { try { } finally { throw; // CS0724 } } } static void Main() { } }"; CreateCompilation(text).VerifyDiagnostics( // (19,17): error CS0724: A throw statement with no arguments is not allowed in a finally clause that is nested inside the nearest enclosing catch clause Diagnostic(ErrorCode.ERR_BadEmptyThrowInFinally, "throw").WithLocation(19, 17)); } [Fact, WorkItem(1040213, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1040213")] public void CS0724ERR_BadEmptyThrowInFinally_Nesting() { var text = @" using System; class X { static void Test(bool b) { try { throw new Exception(); } catch { try { } finally { if (b) throw; // CS0724 try { throw; // CS0724 } catch { throw; // OK } finally { throw; // CS0724 } } } } static void Main() { } }"; CreateCompilation(text).VerifyDiagnostics( // (19,17): error CS0724: A throw statement with no arguments is not allowed in a finally clause that is nested inside the nearest enclosing catch clause Diagnostic(ErrorCode.ERR_BadEmptyThrowInFinally, "throw"), // (19,17): error CS0724: A throw statement with no arguments is not allowed in a finally clause that is nested inside the nearest enclosing catch clause Diagnostic(ErrorCode.ERR_BadEmptyThrowInFinally, "throw"), // (19,17): error CS0724: A throw statement with no arguments is not allowed in a finally clause that is nested inside the nearest enclosing catch clause Diagnostic(ErrorCode.ERR_BadEmptyThrowInFinally, "throw")); } [Fact] public void CS0747ERR_InvalidInitializerElementInitializer() { var text = @" using System.Collections.Generic; public class C { public static int Main() { var t = new List<int> { Capacity = 2, 1 }; // CS0747 return 1; } }"; CreateCompilation(text).VerifyDiagnostics( Diagnostic(ErrorCode.ERR_InvalidInitializerElementInitializer, "1")); } [Fact] public void CS0762ERR_PartialMethodToDelegate() { var text = @" public delegate void TestDel(); public partial class C { partial void Part(); public static int Main() { C c = new C(); TestDel td = new TestDel(c.Part); // CS0762 return 1; } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_PartialMethodToDelegate, Line = 11, Column = 38 } }); } [Fact] public void CS0765ERR_PartialMethodInExpressionTree() { var text = @" using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Linq.Expressions; public delegate void dele(); public class ConClass { [Conditional(""CONDITION"")] public static void TestMethod() { } } public partial class PartClass : IEnumerable { List<object> list = new List<object>(); partial void Add(int x); public IEnumerator GetEnumerator() { for (int i = 0; i < list.Count; i++) yield return list[i]; } static void Main() { Expression<Func<PartClass>> testExpr1 = () => new PartClass { 1, 2 }; // CS0765 Expression<dele> testExpr2 = () => ConClass.TestMethod(); // CS0765 } }"; CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics( // (30,71): error CS0765: Partial methods with only a defining declaration or removed conditional methods cannot be used in expression trees // Expression<Func<PartClass>> testExpr1 = () => new PartClass { 1, 2 }; // CS0765 Diagnostic(ErrorCode.ERR_PartialMethodInExpressionTree, "1"), // (30,74): error CS0765: Partial methods with only a defining declaration or removed conditional methods cannot be used in expression trees // Expression<Func<PartClass>> testExpr1 = () => new PartClass { 1, 2 }; // CS0765 Diagnostic(ErrorCode.ERR_PartialMethodInExpressionTree, "2"), // (31,44): error CS0765: Partial methods with only a defining declaration or removed conditional methods cannot be used in expression trees // Expression<dele> testExpr2 = () => ConClass.TestMethod(); // CS0765 Diagnostic(ErrorCode.ERR_PartialMethodInExpressionTree, "ConClass.TestMethod()")); } [Fact] public void CS0815ERR_ImplicitlyTypedVariableAssignedBadValue_Local() { CreateCompilation(@" class Test { public static void Main() { var m = Main; // CS0815 var d = s => -1; // CS0815 var e = (string s) => 0; // CS0815 var p = null;//CS0815 var del = delegate(string a) { return -1; };// CS0815 var v = M(); // CS0815 } static void M() {} }").VerifyDiagnostics( // (6,13): error CS0815: Cannot assign method group to an implicitly-typed variable // var m = Main; // CS0815 Diagnostic(ErrorCode.ERR_ImplicitlyTypedVariableAssignedBadValue, "m = Main").WithArguments("method group"), // (7,13): error CS0815: Cannot assign lambda expression to an implicitly-typed variable // var d = s => -1; // CS0815 Diagnostic(ErrorCode.ERR_ImplicitlyTypedVariableAssignedBadValue, "d = s => -1").WithArguments("lambda expression"), // (8,13): error CS0815: Cannot assign lambda expression to an implicitly-typed variable // var e = (string s) => 0; // CS0815 Diagnostic(ErrorCode.ERR_ImplicitlyTypedVariableAssignedBadValue, "e = (string s) => 0").WithArguments("lambda expression"), // (9,13): error CS0815: Cannot assign <null> to an implicitly-typed variable // var p = null;//CS0815 Diagnostic(ErrorCode.ERR_ImplicitlyTypedVariableAssignedBadValue, "p = null").WithArguments("<null>"), // (10,13): error CS0815: Cannot assign anonymous method to an implicitly-typed variable // var del = delegate(string a) { return -1; };// CS0815 Diagnostic(ErrorCode.ERR_ImplicitlyTypedVariableAssignedBadValue, "del = delegate(string a) { return -1; }").WithArguments("anonymous method"), // (11,13): error CS0815: Cannot assign void to an implicitly-typed variable // var v = M(); // CS0815 Diagnostic(ErrorCode.ERR_ImplicitlyTypedVariableAssignedBadValue, "v = M()").WithArguments("void")); } [Fact] public void CS0815ERR_ImplicitlyTypedVariableAssignedBadValue_Field() { CreateCompilationWithMscorlib45(@" static void M() {} var m = M; var d = s => -1; var e = (string s) => 0; var p = null; var del = delegate(string a) { return -1; }; var v = M(); ", parseOptions: TestOptions.Script).VerifyDiagnostics( // (4,5): error CS0815: Cannot assign method group to an implicitly-typed variable Diagnostic(ErrorCode.ERR_ImplicitlyTypedVariableAssignedBadValue, "m = M").WithArguments("method group"), // (5,5): error CS0815: Cannot assign lambda expression to an implicitly-typed variable Diagnostic(ErrorCode.ERR_ImplicitlyTypedVariableAssignedBadValue, "d = s => -1").WithArguments("lambda expression"), // (6,5): error CS0815: Cannot assign lambda expression to an implicitly-typed variable Diagnostic(ErrorCode.ERR_ImplicitlyTypedVariableAssignedBadValue, "e = (string s) => 0").WithArguments("lambda expression"), // (7,5): error CS0815: Cannot assign <null> to an implicitly-typed variable Diagnostic(ErrorCode.ERR_ImplicitlyTypedVariableAssignedBadValue, "p = null").WithArguments("<null>"), // (8,5): error CS0815: Cannot assign anonymous method to an implicitly-typed variable Diagnostic(ErrorCode.ERR_ImplicitlyTypedVariableAssignedBadValue, "del = delegate(string a) { return -1; }").WithArguments("anonymous method"), // (9,1): error CS0670: Field cannot have void type Diagnostic(ErrorCode.ERR_FieldCantHaveVoidType, "var")); } [Fact] public void CS0818ERR_ImplicitlyTypedVariableWithNoInitializer() { var text = @" class A { public static int Main() { var a; // CS0818 return -1; } }"; // In the native compiler we skip post-initial-binding error analysis if there was // an error during the initial binding, so we report only that the "var" declaration // is bad. We do not report warnings like "variable b is assigned but never used". // In Roslyn we do flow analysis even if the initial binding pass produced an error, // so we have extra errors here. DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new[] { new ErrorDescription { Code = (int)ErrorCode.ERR_ImplicitlyTypedVariableWithNoInitializer, Line = 6, Column = 13 }, new ErrorDescription { Code = (int)ErrorCode.WRN_UnreferencedVar, Line = 6, Column = 13, IsWarning = true }}); } [Fact] public void CS0818ERR_ImplicitlyTypedVariableWithNoInitializer_Fields() { CreateCompilationWithMscorlib45(@" var a; // CS0818 ", parseOptions: TestOptions.Script).VerifyDiagnostics( // (1,5): error CS0818: Implicitly-typed variables must be initialized Diagnostic(ErrorCode.ERR_ImplicitlyTypedVariableWithNoInitializer, "a")); } [Fact] public void CS0819ERR_ImplicitlyTypedVariableMultipleDeclarator_Locals() { var text = @" class A { public static int Main() { var a = 3, b = 2; // CS0819 return -1; } } "; // In the native compiler we skip post-initial-binding error analysis if there was // an error during the initial binding, so we report only that the "var" declaration // is bad. We do not report warnings like "variable b is assigned but never used". // In Roslyn we do flow analysis even if the initial binding pass produced an error, // so we have extra errors here. DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new[] { new ErrorDescription { Code = (int)ErrorCode.ERR_ImplicitlyTypedVariableMultipleDeclarator, Line = 6, Column = 9 }, new ErrorDescription { Code = (int)ErrorCode.WRN_UnreferencedVarAssg, Line = 6, Column = 13, IsWarning = true }, new ErrorDescription { Code = (int)ErrorCode.WRN_UnreferencedVarAssg, Line = 6, Column = 20, IsWarning = true }}); } [Fact] public void CS0819ERR_ImplicitlyTypedVariableMultipleDeclarator_Fields() { CreateCompilationWithMscorlib45(@" var goo = 4, bar = 4.5; ", parseOptions: TestOptions.Script).VerifyDiagnostics( // (2,1): error CS0819: Implicitly-typed fields cannot have multiple declarators Diagnostic(ErrorCode.ERR_ImplicitlyTypedVariableMultipleDeclarator, "var")); } [Fact] public void CS0820ERR_ImplicitlyTypedVariableAssignedArrayInitializer() { var text = @" class G { public static int Main() { var a = { 1, 2, 3 }; //CS0820 return -1; } }"; // In the native compilers this code produces two errors, both // "you can't assign an array initializer to an implicitly typed local" and // "you can only use an array initializer to assign to an array type". // It seems like the first error ought to prevent the second. In Roslyn // we only produce the first error. DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new[] { new ErrorDescription { Code = (int)ErrorCode.ERR_ImplicitlyTypedVariableAssignedArrayInitializer, Line = 6, Column = 13 }}); } [Fact] public void CS0820ERR_ImplicitlyTypedVariableAssignedArrayInitializer_Fields() { CreateCompilationWithMscorlib45(@" var y = { 1, 2, 3 }; ", parseOptions: TestOptions.Script).VerifyDiagnostics( // (1,5): error CS0820: Cannot initialize an implicitly-typed variable with an array initializer Diagnostic(ErrorCode.ERR_ImplicitlyTypedVariableAssignedArrayInitializer, "y = { 1, 2, 3 }")); } [Fact] public void CS0821ERR_ImplicitlyTypedLocalCannotBeFixed() { var text = @" class A { static int x; public static int Main() { unsafe { fixed (var p = &x) { } } return -1; } }"; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (10,24): error CS0821: Implicitly-typed local variables cannot be fixed // fixed (var p = &x) { } Diagnostic(ErrorCode.ERR_ImplicitlyTypedLocalCannotBeFixed, "p = &x")); } [Fact] public void CS0822ERR_ImplicitlyTypedLocalCannotBeConst() { var text = @" class A { public static void Main() { const var x = 0; // CS0822.cs const var y = (int?)null + x; } }"; // In the dev10 compiler, the second line reports both that "const var" is illegal // and that the initializer must be a valid constant. This seems a bit odd, so // in Roslyn we just report the first error. Let the user sort out whether they // meant it to be a constant or a variable, and then we can tell them if its a // bad constant. var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (6,15): error CS0822: Implicitly-typed variables cannot be constant // const var x = 0; // CS0822.cs Diagnostic(ErrorCode.ERR_ImplicitlyTypedVariableCannotBeConst, "var x = 0").WithLocation(6, 15), // (7,15): error CS0822: Implicitly-typed variables cannot be constant // const var y = (int?)null + x; Diagnostic(ErrorCode.ERR_ImplicitlyTypedVariableCannotBeConst, "var y = (int?)null + x").WithLocation(7, 15), // (7,23): warning CS0458: The result of the expression is always 'null' of type 'int?' // const var y = (int?)null + x; Diagnostic(ErrorCode.WRN_AlwaysNull, "(int?)null + x").WithArguments("int?").WithLocation(7, 23) ); } [Fact] public void CS0822ERR_ImplicitlyTypedVariableCannotBeConst_Fields() { CreateCompilationWithMscorlib45(@" const var x = 0; // CS0822.cs ", parseOptions: TestOptions.Script).VerifyDiagnostics( // (2,7): error CS0822: Implicitly-typed variables cannot be constant Diagnostic(ErrorCode.ERR_ImplicitlyTypedVariableCannotBeConst, "var")); } [Fact] public void CS0825ERR_ImplicitlyTypedVariableCannotBeUsedAsTheTypeOfAParameter_Fields() { CreateCompilationWithMscorlib45(@" void goo(var arg) { } var goo(int arg) { return 2; } ", parseOptions: TestOptions.Script).VerifyDiagnostics( // (1,10): error CS0825: The contextual keyword 'var' may only appear within a local variable declaration or in script code Diagnostic(ErrorCode.ERR_TypeVarNotFound, "var"), // (2,1): error CS0825: The contextual keyword 'var' may only appear within a local variable declaration or in script code Diagnostic(ErrorCode.ERR_TypeVarNotFound, "var")); } [Fact] public void CS0825ERR_ImplicitlyTypedVariableCannotBeUsedAsTheTypeOfAParameter_Fields2() { CreateCompilationWithMscorlib45(@" T goo<T>() { return default(T); } goo<var>(); ", parseOptions: TestOptions.Script).VerifyDiagnostics( // (2,5): error CS0825: The contextual keyword 'var' may only appear within a local variable declaration or in script code Diagnostic(ErrorCode.ERR_TypeVarNotFound, "var")); } [Fact()] public void CS0826ERR_ImplicitlyTypedArrayNoBestType() { var text = @" public class C { delegate void D(); public static void M1() {} public static void M2(int x) {} public static int M3() { return 1; } public static int M4(int x) { return x; } public static int Main() { var z = new[] { 1, ""str"" }; // CS0826 char c = 'c'; short s1 = 0; short s2 = -0; short s3 = 1; short s4 = -1; var array1 = new[] { s1, s2, s3, s4, c, '1' }; // CS0826 var a = new [] {}; // CS0826 byte b = 3; var arr = new [] {b, c}; // CS0826 var a1 = new [] {null}; // CS0826 var a2 = new [] {null, null, null}; // CS0826 D[] l1 = new [] {x=>x+1}; // CS0826 D[] l2 = new [] {x=>x+1, x=>{return x + 1;}, (int x)=>x+1, (int x)=>{return x + 1;}, (x, y)=>x + y, ()=>{return 1;}}; // CS0826 D[] d1 = new [] {delegate {}}; // CS0826 D[] d2 = new [] {delegate {}, delegate (){}, delegate {return 1;}, delegate {return;}, delegate(int x){}, delegate(int x){return x;}, delegate(int x, int y){return x + y;}}; // CS0826 var m = new [] {M1, M2, M3, M4}; // CS0826 return 1; } }"; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, Line = 12, Column = 17 }, new ErrorDescription { Code = (int)ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, Line = 20, Column = 22 }, new ErrorDescription { Code = (int)ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, Line = 22, Column = 17 }, new ErrorDescription { Code = (int)ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, Line = 25, Column = 19 }, new ErrorDescription { Code = (int)ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, Line = 27, Column = 18 }, new ErrorDescription { Code = (int)ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, Line = 28, Column = 18 }, new ErrorDescription { Code = (int)ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, Line = 30, Column = 18 }, new ErrorDescription { Code = (int)ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, Line = 31, Column = 18 }, new ErrorDescription { Code = (int)ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, Line = 33, Column = 18 }, new ErrorDescription { Code = (int)ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, Line = 34, Column = 18 }, new ErrorDescription { Code = (int)ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, Line = 36, Column = 17 }}); } [Fact] public void CS0828ERR_AnonymousTypePropertyAssignedBadValue() { var text = @" public class C { public static int Main() { var c = new { p1 = null }; // CS0828 return 1; } }"; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_AnonymousTypePropertyAssignedBadValue, Line = 6, Column = 23 } }); } [Fact] public void CS0828ERR_AnonymousTypePropertyAssignedBadValue_2() { var text = @" public class C { public static void Main() { var c = new { p1 = Main }; // CS0828 } }"; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_AnonymousTypePropertyAssignedBadValue, Line = 6, Column = 23 } }); } [Fact] public void CS0828ERR_AnonymousTypePropertyAssignedBadValue_3() { var text = @" public class C { public static void Main() { var c = new { p1 = Main() }; // CS0828 } }"; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_AnonymousTypePropertyAssignedBadValue, Line = 6, Column = 23 } }); } [Fact] public void CS0828ERR_AnonymousTypePropertyAssignedBadValue_4() { var text = @" public class C { public static void Main() { var c = new { p1 = ()=>3 }; // CS0828 } }"; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_AnonymousTypePropertyAssignedBadValue, Line = 6, Column = 23 } }); } [Fact] public void CS0828ERR_AnonymousTypePropertyAssignedBadValue_5() { var text = @" public class C { public static void Main() { var c = new { p1 = delegate { return 1; } // CS0828 }; } }"; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_AnonymousTypePropertyAssignedBadValue, Line = 8, Column = 13 } }); } [Fact] public void CS0831ERR_ExpressionTreeContainsBaseAccess() { var text = @" using System; using System.Linq.Expressions; public class A { public virtual int BaseMethod() { return 1; } } public class C : A { public override int BaseMethod() { return 2; } public int Test(C c) { Expression<Func<int>> e = () => base.BaseMethod(); // CS0831 return 1; } }"; CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics( // (14,41): error CS0831: An expression tree may not contain a base access // Expression<Func<int>> e = () => base.BaseMethod(); // CS0831 Diagnostic(ErrorCode.ERR_ExpressionTreeContainsBaseAccess, "base") ); } [Fact] public void CS0832ERR_ExpressionTreeContainsAssignment() { var text = @" using System; using System.Linq.Expressions; public class C { public static int Main() { Expression<Func<int, int>> e1 = x => x += 5; // CS0843 Expression<Func<int, int>> e2 = x => x = 5; // CS0843 return 1; } }"; CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics( // (9,46): error CS0832: An expression tree may not contain an assignment operator // Expression<Func<int, int>> e1 = x => x += 5; // CS0843 Diagnostic(ErrorCode.ERR_ExpressionTreeContainsAssignment, "x += 5"), // (10,46): error CS0832: An expression tree may not contain an assignment operator // Expression<Func<int, int>> e2 = x => x = 5; // CS0843 Diagnostic(ErrorCode.ERR_ExpressionTreeContainsAssignment, "x = 5") ); } [Fact] public void CS0833ERR_AnonymousTypeDuplicatePropertyName() { var text = @" public class C { public static int Main() { var c = new { p1 = 1, p1 = 2 }; // CS0833 return 1; } }"; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_AnonymousTypeDuplicatePropertyName, Line = 6, Column = 31 } }); } [Fact] public void CS0833ERR_AnonymousTypeDuplicatePropertyName_2() { var text = @" public class C { public static int Main() { var c = new { C.Prop, Prop = 2 }; // CS0833 return 1; } static string Prop { get; set; } }"; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_AnonymousTypeDuplicatePropertyName, Line = 6, Column = 31 } }); } [Fact] public void CS0833ERR_AnonymousTypeDuplicatePropertyName_3() { var text = @" public class C { public static int Main() { var c = new { C.Prop, Prop = 2 }; // CS0833 + CS0828 return 1; } static string Prop() { return null; } }"; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_AnonymousTypePropertyAssignedBadValue, Line = 6, Column = 23 }, new ErrorDescription { Code = (int)ErrorCode.ERR_AnonymousTypeDuplicatePropertyName, Line = 6, Column = 31 }}); } [Fact] public void CS0834ERR_StatementLambdaToExpressionTree() { var text = @" using System; using System.Linq.Expressions; public class C { public static void Main() { Expression<Func<int, int>> e = x => { return x; }; // CS0834 } }"; CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics( // (9,40): error CS0834: A lambda expression with a statement body cannot be converted to an expression tree // Expression<Func<int, int>> e = x => { return x; }; // CS0834 Diagnostic(ErrorCode.ERR_StatementLambdaToExpressionTree, "x => { return x; }") ); } [Fact] public void CS0835ERR_ExpressionTreeMustHaveDelegate() { var text = @" using System.Linq.Expressions; public class Myclass { public static int Main() { Expression<int> e = x => x + 1; // CS0835 return 1; } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new[] { LinqAssemblyRef }, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_ExpressionTreeMustHaveDelegate, Line = 8, Column = 29 } }); } [Fact] public void CS0836ERR_AnonymousTypeNotAvailable() { var text = @" using System; [AttributeUsage(AttributeTargets.Class, AllowMultiple = true, Inherited = false)] public class MyClass : Attribute { public MyClass(object obj) { } } [MyClass(new { })] // CS0836 public class ClassGoo { } public class Test { public static int Main() { return 0; } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_AnonymousTypeNotAvailable, Line = 11, Column = 10 } }); } [Fact] public void CS0836ERR_AnonymousTypeNotAvailable2() { var text = @" public class Test { const object x = new { }; public static int Main() { return 0; } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_AnonymousTypeNotAvailable, Line = 4, Column = 22 } }); } [Fact] public void CS0836ERR_AnonymousTypeNotAvailable3() { var text = @" public class Test { static object y = new { }; private object x = new { }; public static int Main() { return 0; } } "; // NOTE: Actually we assert that #836 is NOT generated DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text); } [Fact] public void CS0836ERR_AnonymousTypeNotAvailable4() { var text = @" public class Test { public static int Main(object x = new { }) { return 0; } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_DefaultValueMustBeConstant, Line = 4, Column = 39 } }); } [Fact] public void CS0836ERR_AnonymousTypeNotAvailable5() { var text = @" using System; [AttributeUsage(AttributeTargets.All)] public class MyClass : Attribute { public MyClass(object obj) { } } public class Test { [MyClass(new { })] // CS0836 public static int Main() { return 0; } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_AnonymousTypeNotAvailable, Line = 13, Column = 14 } }); } [Fact] public void CS0836ERR_AnonymousTypeNotAvailable6() { var text = @" using System; [AttributeUsage(AttributeTargets.All)] public class MyClass : Attribute { public MyClass(object obj) { } } public class Test { [MyClass(new { })] // CS0836 static object y = new { }; public static int Main() { return 0; } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_AnonymousTypeNotAvailable, Line = 13, Column = 14 } }); } [Fact] public void CS0837ERR_LambdaInIsAs() { var text = @" namespace TestNamespace { public delegate void Del(); class Test { static int Main() { bool b1 = (() => { }) is Del; // CS0837 bool b2 = delegate() { } is Del;// CS0837 Del d1 = () => { } as Del; // CS0837 Del d2 = delegate() { } as Del; // CS0837 return 1; } } } "; CreateCompilation(text).VerifyDiagnostics( // (10,23): error CS0837: The first operand of an 'is' or 'as' operator may not be a lambda expression, anonymous method, or method group. // bool b1 = (() => { }) is Del; // CS0837 Diagnostic(ErrorCode.ERR_LambdaInIsAs, "(() => { }) is Del").WithLocation(10, 23), // (11,23): error CS0837: The first operand of an 'is' or 'as' operator may not be a lambda expression, anonymous method, or method group. // bool b2 = delegate() { } is Del;// CS0837 Diagnostic(ErrorCode.ERR_LambdaInIsAs, "delegate() { } is Del").WithLocation(11, 23), // (11,38): warning CS8848: Operator 'is' cannot be used here due to precedence. Use parentheses to disambiguate. // bool b2 = delegate() { } is Del;// CS0837 Diagnostic(ErrorCode.WRN_PrecedenceInversion, "is").WithArguments("is").WithLocation(11, 38), // (12,22): error CS0837: The first operand of an 'is' or 'as' operator may not be a lambda expression, anonymous method, or method group. // Del d1 = () => { } as Del; // CS0837 Diagnostic(ErrorCode.ERR_LambdaInIsAs, "() => { } as Del").WithLocation(12, 22), // (12,32): warning CS8848: Operator 'as' cannot be used here due to precedence. Use parentheses to disambiguate. // Del d1 = () => { } as Del; // CS0837 Diagnostic(ErrorCode.WRN_PrecedenceInversion, "as").WithArguments("as").WithLocation(12, 32), // (13,22): error CS0837: The first operand of an 'is' or 'as' operator may not be a lambda expression, anonymous method, or method group. // Del d2 = delegate() { } as Del; // CS0837 Diagnostic(ErrorCode.ERR_LambdaInIsAs, "delegate() { } as Del").WithLocation(13, 22), // (13,37): warning CS8848: Operator 'as' cannot be used here due to precedence. Use parentheses to disambiguate. // Del d2 = delegate() { } as Del; // CS0837 Diagnostic(ErrorCode.WRN_PrecedenceInversion, "as").WithArguments("as").WithLocation(13, 37) ); CreateCompilation(text, options: TestOptions.ReleaseDll.WithWarningLevel(5)).VerifyDiagnostics( // (10,23): error CS0837: The first operand of an 'is' or 'as' operator may not be a lambda expression, anonymous method, or method group. // bool b1 = (() => { }) is Del; // CS0837 Diagnostic(ErrorCode.ERR_LambdaInIsAs, "(() => { }) is Del").WithLocation(10, 23), // (11,23): error CS0837: The first operand of an 'is' or 'as' operator may not be a lambda expression, anonymous method, or method group. // bool b2 = delegate() { } is Del;// CS0837 Diagnostic(ErrorCode.ERR_LambdaInIsAs, "delegate() { } is Del").WithLocation(11, 23), // (11,38): warning CS8848: Operator 'is' cannot be used here due to precedence. Use parentheses to disambiguate. // bool b2 = delegate() { } is Del;// CS0837 Diagnostic(ErrorCode.WRN_PrecedenceInversion, "is").WithArguments("is").WithLocation(11, 38), // (12,22): error CS0837: The first operand of an 'is' or 'as' operator may not be a lambda expression, anonymous method, or method group. // Del d1 = () => { } as Del; // CS0837 Diagnostic(ErrorCode.ERR_LambdaInIsAs, "() => { } as Del").WithLocation(12, 22), // (12,32): warning CS8848: Operator 'as' cannot be used here due to precedence. Use parentheses to disambiguate. // Del d1 = () => { } as Del; // CS0837 Diagnostic(ErrorCode.WRN_PrecedenceInversion, "as").WithArguments("as").WithLocation(12, 32), // (13,22): error CS0837: The first operand of an 'is' or 'as' operator may not be a lambda expression, anonymous method, or method group. // Del d2 = delegate() { } as Del; // CS0837 Diagnostic(ErrorCode.ERR_LambdaInIsAs, "delegate() { } as Del").WithLocation(13, 22), // (13,37): warning CS8848: Operator 'as' cannot be used here due to precedence. Use parentheses to disambiguate. // Del d2 = delegate() { } as Del; // CS0837 Diagnostic(ErrorCode.WRN_PrecedenceInversion, "as").WithArguments("as").WithLocation(13, 37) ); } [Fact] public void CS0841ERR_VariableUsedBeforeDeclaration01() { CreateCompilation( @"class C { static void M() { j = 5; // CS0841 int j; // To fix, move this line up. } } ") // The native compiler just produces the "var used before decl" error; the Roslyn // compiler runs the flow checking pass even if the initial binding failed. We // might consider turning off flow checking if the initial binding failed, and // removing the warning here. .VerifyDiagnostics( Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "j").WithArguments("j"), Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "j").WithArguments("j")); } [Fact] public void CS0841ERR_VariableUsedBeforeDeclaration02() { CreateCompilation( @"class C { static void M() { int a = b, b = 0, c = a; for (int x = y, y = 0; ; ) { } } } ") .VerifyDiagnostics( Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "b").WithArguments("b"), Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "y").WithArguments("y")); } [Fact] public void CS0841ERR_VariableUsedBeforeDeclaration03() { // It is a bit unfortunate that we produce "can't use variable before decl" here // when the variable is being used after the decl. Perhaps we should generate // a better error? CreateCompilation( @"class C { static int N(out int q) { q = 1; return 2;} static void M() { var x = N(out x); } } ") .VerifyDiagnostics( Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x").WithArguments("x")); } [Fact] public void CS0841ERR_VariableUsedBeforeDeclaration04() { var systemRef = Net451.System; CreateCompilationWithMscorlib40AndSystemCore( @"using System.Collections.Generic; class Base { int i; } class Derived : Base { int j; } class C { public static void Main() { HashSet<Base> set1 = new HashSet<Base>(); foreach (Base b in set1) { Derived d = b as Derived; Base b = null; } } } ", new List<MetadataReference> { systemRef }) .VerifyDiagnostics( // (18,25): error CS0841: Cannot use local variable 'b' before it is declared // Derived d = b as Derived; Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "b").WithArguments("b"), // (19,18): error CS0136: A local or parameter named 'b' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // Base b = null; Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "b").WithArguments("b"), // (4,9): warning CS0169: The field 'Base.i' is never used // int i; Diagnostic(ErrorCode.WRN_UnreferencedField, "i").WithArguments("Base.i"), // (8,9): warning CS0169: The field 'Derived.j' is never used // int j; Diagnostic(ErrorCode.WRN_UnreferencedField, "j").WithArguments("Derived.j")); } /// <summary> /// No errors using statics before declaration. /// </summary> [Fact] public void StaticUsedBeforeDeclaration() { var text = @"class C { static int F = G + 2; static int G = F + 1; } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text); } [Fact] public void CS0843ERR_UnassignedThisAutoProperty() { var text = @" struct S { public int AIProp { get; set; } public S(int i) { } //CS0843 } class Test { static int Main() { return 1; } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_UnassignedThisAutoProperty, Line = 5, Column = 12 } }); } [Fact] public void CS0844ERR_VariableUsedBeforeDeclarationAndHidesField() { var text = @" public class MyClass { int num; public void TestMethod() { num = 5; // CS0844 int num = 6; System.Console.WriteLine(num); } } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (7,9): error CS0844: Cannot use local variable 'num' before it is declared. The declaration of the local variable hides the field 'MyClass.num'. // num = 5; // CS0844 Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclarationAndHidesField, "num").WithArguments("num", "MyClass.num"), // (4,9): warning CS0169: The field 'MyClass.num' is never used // int num; Diagnostic(ErrorCode.WRN_UnreferencedField, "num").WithArguments("MyClass.num") ); } [Fact] public void CS0845ERR_ExpressionTreeContainsBadCoalesce() { var text = @" using System; using System.Linq.Expressions; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { Expression<Func<object>> e = () => null ?? ""x""; // CS0845 } } } "; CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics( // (11,48): error CS0845: An expression tree lambda may not contain a coalescing operator with a null literal left-hand side // Expression<Func<object>> e = () => null ?? "x"; // CS0845 Diagnostic(ErrorCode.ERR_ExpressionTreeContainsBadCoalesce, "null") ); } [WorkItem(3717, "DevDiv_Projects/Roslyn")] [Fact] public void CS0846ERR_ArrayInitializerExpected() { var text = @"public class Myclass { public static void Main() { int[,] a = new int[,] { 1 }; // error } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_ArrayInitializerExpected, Line = 5, Column = 33 } }); } [Fact] public void CS0847ERR_ArrayInitializerIncorrectLength() { var text = @" public class Program { public static void Main(string[] args) { int[] ar0 = new int[0]{0}; // error CS0847: An array initializer of length `0' was expected int[] ar1 = new int[3]{}; // error CS0847: An array initializer of length `3' was expected ar0[0] = ar1[0]; } } "; CreateCompilation(text).VerifyDiagnostics( // (6,31): error CS0847: An array initializer of length '0' is expected // int[] ar0 = new int[0]{0}; // error CS0847: An array initializer of length `0' was expected Diagnostic(ErrorCode.ERR_ArrayInitializerIncorrectLength, "{0}").WithArguments("0").WithLocation(6, 31), // (7,31): error CS0847: An array initializer of length '3' is expected // int[] ar1 = new int[3]{}; // error CS0847: An array initializer of length `3' was expected Diagnostic(ErrorCode.ERR_ArrayInitializerIncorrectLength, "{}").WithArguments("3").WithLocation(7, 31)); } [Fact] public void CS0853ERR_ExpressionTreeContainsNamedArgument01() { var text = @" using System.Linq.Expressions; namespace ConsoleApplication3 { class Program { delegate string dg(int x); static void Main(string[] args) { Expression<dg> myET = x => Index(minSessions:5); } public static string Index(int minSessions = 0) { return minSessions.ToString(); } } } "; CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics( // (10,40): error CS0853: An expression tree may not contain a named argument specification // Expression<dg> myET = x => Index(minSessions:5); Diagnostic(ErrorCode.ERR_ExpressionTreeContainsNamedArgument, "Index(minSessions:5)").WithLocation(10, 40) ); } [WorkItem(545063, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545063")] [Fact] public void CS0853ERR_ExpressionTreeContainsNamedArgument02() { var text = @" using System; using System.Collections.Generic; using System.Linq.Expressions; class A { static void Main() { Expression<Func<int>> f = () => new List<int> { 1 } [index: 0]; } } "; CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics( // (10,41): error CS0853: An expression tree may not contain a named argument specification // Expression<Func<int>> f = () => new List<int> { 1 } [index: 0]; Diagnostic(ErrorCode.ERR_ExpressionTreeContainsNamedArgument, "new List<int> { 1 } [index: 0]").WithLocation(10, 41) ); } [Fact] public void CS0854ERR_ExpressionTreeContainsOptionalArgument01() { var text = @" using System.Linq.Expressions; namespace ConsoleApplication3 { class Program { delegate string dg(int x); static void Main(string[] args) { Expression<dg> myET = x => Index(); } public static string Index(int minSessions = 0) { return minSessions.ToString(); } } } "; CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics( // (10,40): error CS0854: An expression tree may not contain a call or invocation that uses optional arguments // Expression<dg> myET = x => Index(); Diagnostic(ErrorCode.ERR_ExpressionTreeContainsOptionalArgument, "Index()").WithLocation(10, 40) ); } [Fact] public void CS0854ERR_ExpressionTreeContainsOptionalArgument02() { var text = @"using System; using System.Linq.Expressions; class A { internal object this[int x, int y = 2] { get { return null; } } } class B { internal object this[int x, int y = 2] { set { } } } class C { static void M(A a, B b) { Expression<Func<object>> e1; e1 = () => a[0]; e1 = () => a[1, 2]; Expression<Action> e2; e2 = () => b[3] = null; e2 = () => b[4, 5] = null; } }"; CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics( // (22,20): error CS0854: An expression tree may not contain a call or invocation that uses optional arguments Diagnostic(ErrorCode.ERR_ExpressionTreeContainsOptionalArgument, "a[0]").WithLocation(22, 20), // (25,20): error CS0832: An expression tree may not contain an assignment operator Diagnostic(ErrorCode.ERR_ExpressionTreeContainsAssignment, "b[3] = null").WithLocation(25, 20), // (25,20): error CS0854: An expression tree may not contain a call or invocation that uses optional arguments Diagnostic(ErrorCode.ERR_ExpressionTreeContainsOptionalArgument, "b[3]").WithLocation(25, 20), // (26,20): error CS0832: An expression tree may not contain an assignment operator Diagnostic(ErrorCode.ERR_ExpressionTreeContainsAssignment, "b[4, 5] = null").WithLocation(26, 20)); } [Fact] public void CS0854ERR_ExpressionTreeContainsOptionalArgument03() { var text = @"using System; using System.Collections; using System.Linq.Expressions; public class Collection : IEnumerable { public void Add(int i, int j = 0) { } public IEnumerator GetEnumerator() { throw new NotImplementedException(); } } public class C { public void M() { Expression<Func<Collection>> expr = () => new Collection { 1 }; // 1 } }"; CreateCompilation(text).VerifyDiagnostics( // (18,36): error CS0854: An expression tree may not contain a call or invocation that uses optional arguments // () => new Collection { 1 }; // 1 Diagnostic(ErrorCode.ERR_ExpressionTreeContainsOptionalArgument, "1").WithLocation(18, 36)); } [Fact] public void CS0855ERR_ExpressionTreeContainsIndexedProperty() { 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 P(index As Object) As Integer Property Q(Optional index As Object = Nothing) As Integer End Interface"; var reference1 = BasicCompilationUtils.CompileToMetadata(source1); var source2 = @"using System; using System.Linq.Expressions; class C { static void M(I i) { Expression<Func<int>> e1; e1 = () => i.P[1]; e1 = () => i.get_P(2); // no error e1 = () => i.Q; e1 = () => i.Q[index:3]; Expression<Action> e2; e2 = () => i.P[4] = 0; e2 = () => i.set_P(5, 6); // no error } }"; var compilation2 = CreateCompilationWithMscorlib40AndSystemCore(source2, new[] { reference1 }); compilation2.VerifyDiagnostics( // (8,20): error CS0855: An expression tree may not contain an indexed property Diagnostic(ErrorCode.ERR_ExpressionTreeContainsIndexedProperty, "i.P[1]").WithLocation(8, 20), // (10,20): error CS0855: An expression tree may not contain an indexed property Diagnostic(ErrorCode.ERR_ExpressionTreeContainsIndexedProperty, "i.Q").WithLocation(10, 20), // (11,20): error CS0855: An expression tree may not contain an indexed property Diagnostic(ErrorCode.ERR_ExpressionTreeContainsIndexedProperty, "i.Q[index:3]").WithLocation(11, 20), // (13,20): error CS0832: An expression tree may not contain an assignment operator Diagnostic(ErrorCode.ERR_ExpressionTreeContainsAssignment, "i.P[4] = 0").WithLocation(13, 20), // (13,20): error CS0855: An expression tree may not contain an indexed property Diagnostic(ErrorCode.ERR_ExpressionTreeContainsIndexedProperty, "i.P[4]").WithLocation(13, 20)); } [Fact] [CompilerTrait(CompilerFeature.IOperation)] [WorkItem(23004, "https://github.com/dotnet/roslyn/issues/23004")] public void CS0856ERR_IndexedPropertyRequiresParams01() { 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 P(x As Object, Optional y As Object = Nothing) As Object Property P(Optional x As Integer = 1, Optional y As Integer = 2) As Object Property Q(Optional x As Integer = 1, Optional y As Integer = 2) As Object Property Q(x As Object, Optional y As Object = Nothing) As Object Property R(x As Integer, y As Integer, Optional z As Integer = 3) As Object Property S(ParamArray args As Integer()) As Object End Interface"; var reference1 = BasicCompilationUtils.CompileToMetadata(source1); var source2 = @"class C { static void M(I i) { object o; o = i.P; // CS0856 (Dev11) o = i.Q; i.R = o; // CS0856 i.R[1] = o; // CS1501 o = i.S; // CS0856 (Dev11) i.S = o; // CS0856 (Dev11) } }"; var compilation2 = CreateCompilation(source2, new[] { reference1 }); compilation2.VerifyDiagnostics( // (8,9): error CS0856: Indexed property 'I.R' has non-optional arguments which must be provided Diagnostic(ErrorCode.ERR_IndexedPropertyRequiresParams, "i.R").WithArguments("I.R").WithLocation(8, 9), // (9,9): error CS7036: There is no argument given that corresponds to the required formal parameter 'y' of 'I.R[int, int, int]' Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "i.R[1]").WithArguments("y", "I.R[int, int, int]").WithLocation(9, 9)); var tree = compilation2.SyntaxTrees.Single(); var node = tree.GetRoot().DescendantNodes().OfType<ElementAccessExpressionSyntax>().First(); Assert.Equal("i.R[1]", node.ToString()); compilation2.VerifyOperationTree(node, expectedOperationTree: @" IInvalidOperation (OperationKind.Invalid, Type: System.Object, IsInvalid) (Syntax: 'i.R[1]') Children(2): IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: I, IsInvalid) (Syntax: 'i') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid) (Syntax: '1') "); } [Fact] public void CS0856ERR_IndexedPropertyRequiresParams02() { 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 Class A Protected ReadOnly Property P(Optional o As Object = Nothing) As Object Get Return Nothing End Get End Property Public ReadOnly Property P(i As Integer) As Object Get Return Nothing End Get End Property End Class"; var reference1 = BasicCompilationUtils.CompileToMetadata(source1); var source2 = @"class C { static object F(A a) { return a.P; } }"; var compilation2 = CreateCompilation(source2, new[] { reference1 }); compilation2.VerifyDiagnostics( // (5,16): error CS0856: Indexed property 'A.P' has non-optional arguments which must be provided Diagnostic(ErrorCode.ERR_IndexedPropertyRequiresParams, "a.P").WithArguments("A.P").WithLocation(5, 16)); } [Fact] public void CS0857ERR_IndexedPropertyMustHaveAllOptionalParams() { 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"")> <CoClass(GetType(A))> Public Interface IA Property P(x As Object, Optional y As Object = Nothing) As Object Property P(Optional x As Integer = 1, Optional y As Integer = 2) As Object Property Q(Optional x As Integer = 1, Optional y As Integer = 2) As Object Property Q(x As Object, Optional y As Object = Nothing) As Object Property R(x As Integer, y As Integer, Optional z As Integer = 3) As Object Property S(ParamArray args As Integer()) As Object End Interface Public Class A Implements IA Property P(x As Object, Optional y As Object = Nothing) As Object Implements IA.P Get Return Nothing End Get Set(value As Object) End Set End Property Property P(Optional x As Integer = 1, Optional y As Integer = 2) As Object Implements IA.P Get Return Nothing End Get Set(value As Object) End Set End Property Property Q(Optional x As Integer = 1, Optional y As Integer = 2) As Object Implements IA.Q Get Return Nothing End Get Set(value As Object) End Set End Property Property Q(x As Object, Optional y As Object = Nothing) As Object Implements IA.Q Get Return Nothing End Get Set(value As Object) End Set End Property Property R(x As Integer, y As Integer, Optional z As Integer = 3) As Object Implements IA.R Get Return Nothing End Get Set(value As Object) End Set End Property Property S(ParamArray args As Integer()) As Object Implements IA.S Get Return Nothing End Get Set(value As Object) End Set End Property End Class"; var reference1 = BasicCompilationUtils.CompileToMetadata(source1, verify: Verification.Passes); var source2 = @"class B { static void M() { IA a; a = new IA() { P = null }; // CS0857 (Dev11) a = new IA() { Q = null }; a = new IA() { R = null }; // CS0857 a = new IA() { S = null }; // CS0857 (Dev11) } }"; var compilation2 = CreateCompilation(source2, new[] { reference1 }); compilation2.VerifyDiagnostics( // (8,24): error CS0857: Indexed property 'IA.R' must have all arguments optional Diagnostic(ErrorCode.ERR_IndexedPropertyMustHaveAllOptionalParams, "R").WithArguments("IA.R").WithLocation(8, 24)); } [Fact] public void CS1059ERR_IncrementLvalueExpected01() { var text = @"enum E { A, B } class C { static void M() { ++E.A; // CS1059 E.A++; // CS1059 } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_IncrementLvalueExpected, Line = 6, Column = 11 }, new ErrorDescription { Code = (int)ErrorCode.ERR_IncrementLvalueExpected, Line = 7, Column = 9 }); } [Fact] public void CS1059ERR_IncrementLvalueExpected02() { var text = @"class C { const int field = 0; static void M() { const int local = 0; ++local; local++; --field; field--; ++(local + 3); (local + 3)++; --2; 2--; dynamic d = null; (d + 1)++; --(d + 1); d++++; } } "; CreateCompilation(text).VerifyDiagnostics( // (7,11): error CS1059: The operand of an increment or decrement operator must be a variable, property or indexer Diagnostic(ErrorCode.ERR_IncrementLvalueExpected, "local"), // (8,9): error CS1059: The operand of an increment or decrement operator must be a variable, property or indexer Diagnostic(ErrorCode.ERR_IncrementLvalueExpected, "local"), // (9,11): error CS1059: The operand of an increment or decrement operator must be a variable, property or indexer Diagnostic(ErrorCode.ERR_IncrementLvalueExpected, "field"), // (10,9): error CS1059: The operand of an increment or decrement operator must be a variable, property or indexer Diagnostic(ErrorCode.ERR_IncrementLvalueExpected, "field"), // (11,12): error CS1059: The operand of an increment or decrement operator must be a variable, property or indexer Diagnostic(ErrorCode.ERR_IncrementLvalueExpected, "local + 3"), // (12,10): error CS1059: The operand of an increment or decrement operator must be a variable, property or indexer Diagnostic(ErrorCode.ERR_IncrementLvalueExpected, "local + 3"), // (13,11): error CS1059: The operand of an increment or decrement operator must be a variable, property or indexer Diagnostic(ErrorCode.ERR_IncrementLvalueExpected, "2"), // (14,9): error CS1059: The operand of an increment or decrement operator must be a variable, property or indexer Diagnostic(ErrorCode.ERR_IncrementLvalueExpected, "2"), // (17,10): error CS1059: The operand of an increment or decrement operator must be a variable, property or indexer Diagnostic(ErrorCode.ERR_IncrementLvalueExpected, "d + 1"), // (18,12): error CS1059: The operand of an increment or decrement operator must be a variable, property or indexer Diagnostic(ErrorCode.ERR_IncrementLvalueExpected, "d + 1"), // (19,9): error CS1059: The operand of an increment or decrement operator must be a variable, property or indexer Diagnostic(ErrorCode.ERR_IncrementLvalueExpected, "d++")); } [Fact] public void CS1059ERR_IncrementLvalueExpected03() { var text = @" class C { void M() { ++this; // CS1059 this--; // CS1059 } } "; CreateCompilation(text).VerifyDiagnostics( // (6,11): error CS1059: The operand of an increment or decrement operator must be a variable, property or indexer // ++this; // CS1059 Diagnostic(ErrorCode.ERR_IncrementLvalueExpected, "this").WithArguments("this"), // (7,9): error CS1059: The operand of an increment or decrement operator must be a variable, property or indexer // this--; // CS1059 Diagnostic(ErrorCode.ERR_IncrementLvalueExpected, "this").WithArguments("this")); } [Fact] public void CS1061ERR_NoSuchMemberOrExtension01() { var text = @" public class TestClass1 { public void WriteSomething(string s) { System.Console.WriteLine(s); } } public class TestClass2 { public void DisplaySomething(string s) { System.Console.WriteLine(s); } } public class TestTheClasses { public static void Main() { TestClass1 tc1 = new TestClass1(); TestClass2 tc2 = new TestClass2(); if (tc1 == null | tc2 == null) {} tc1.DisplaySomething(""Hello""); // CS1061 } }"; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_NoSuchMemberOrExtension, Line = 25, Column = 13 } }); } [Fact] public void CS1061ERR_NoSuchMemberOrExtension02() { var source = @"enum E { } class C { static void M(E e) { object o = e.value__; } }"; CreateCompilation(source).VerifyDiagnostics( // (6,22): error CS1061: 'E' does not contain a definition for 'value__' and no extension method 'value__' accepting a first argument of type 'E' could be found (are you missing a using directive or an assembly reference?) // object o = e.value__; Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "value__").WithArguments("E", "value__").WithLocation(6, 22)); } [Fact] public void CS1061ERR_NoSuchMemberOrExtension03() { CreateCompilation( @"class A { } class B { void M() { this.F(); this.P = this.Q; } static void M(A a) { a.F(); a.P = a.Q; } }") .VerifyDiagnostics( Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "F").WithArguments("A", "F"), Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "P").WithArguments("A", "P"), Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "Q").WithArguments("A", "Q"), Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "F").WithArguments("B", "F"), Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "P").WithArguments("B", "P"), Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "Q").WithArguments("B", "Q")); } [Fact] public void CS1061ERR_NoSuchMemberOrExtension04() { CreateCompilation( @"using System.Collections.Generic; class C { static void M(List<object> list) { object o = list.Item; list.Item = o; } }") .VerifyDiagnostics( Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "Item").WithArguments("System.Collections.Generic.List<object>", "Item").WithLocation(6, 25), Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "Item").WithArguments("System.Collections.Generic.List<object>", "Item").WithLocation(7, 14)); } [Fact] public void CS1061ERR_NoSuchMemberOrExtension05() { CreateCompilationWithMscorlib40AndSystemCore( @"using System.Linq; class Test { static void Main() { var q = 1.Select(z => z); } } ") .VerifyDiagnostics( // (7,17): error CS1061: 'int' does not contain a definition for 'Select' and no extension method 'Select' accepting a first argument of type 'int' could be found (are you missing a using directive or an assembly reference?) // var q = 1.Select(z => z); Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "Select").WithArguments("int", "Select").WithLocation(7, 19)); } [Fact] public void CS1061ERR_NoSuchMemberOrExtension06() { var source = @"interface I<T> { } static class C { static void M(object o) { o.M1(o, o); o.M2(o, o); } static void M1<T>(this I<T> o, object arg) { } static void M2<T>(this I<T> o, params object[] args) { } }"; CreateCompilationWithMscorlib40AndSystemCore(source).VerifyDiagnostics( // (6,9): error CS1501: No overload for method 'M1' takes 2 arguments Diagnostic(ErrorCode.ERR_BadArgCount, "M1").WithArguments("M1", "2").WithLocation(6, 11), // (7,9): error CS1061: 'object' does not contain a definition for 'M2' and no extension method 'M2' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?) Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "M2").WithArguments("object", "M2").WithLocation(7, 11)); } [Fact] 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[] { 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] public void CS1113ERR_ValueTypeExtDelegate02() { var source = @"delegate void D(); interface I { } struct S { } class C { static void M<T1, T2, T3, T4, T5>(int i, S s, T1 t1, T2 t2, T3 t3, T4 t4, T5 t5) where T2 : class where T3 : struct where T4 : I where T5 : C { D d; d = i.M1; d = i.M2<int, object>; d = s.M1; d = s.M2<S, object>; d = t1.M1; d = t1.M2<T1, object>; d = t2.M1; d = t2.M2<T2, object>; d = t3.M1; d = t3.M2<T3, object>; d = t4.M1; d = t4.M2<T4, object>; d = t5.M1; d = t5.M2<T5, object>; } } static class E { internal static void M1<T>(this T t) { } internal static void M2<T, U>(this T t) { } }"; CreateCompilationWithMscorlib40(source, references: new[] { Net40.SystemCore }).VerifyDiagnostics( // (13,13): error CS1113: Extension methods 'E.M1<int>(int)' defined on value type 'int' cannot be used to create delegates Diagnostic(ErrorCode.ERR_ValueTypeExtDelegate, "i.M1").WithArguments("E.M1<int>(int)", "int").WithLocation(13, 13), // (14,13): error CS1113: Extension methods 'E.M2<int, object>(int)' defined on value type 'int' cannot be used to create delegates Diagnostic(ErrorCode.ERR_ValueTypeExtDelegate, "i.M2<int, object>").WithArguments("E.M2<int, object>(int)", "int").WithLocation(14, 13), // (15,13): error CS1113: Extension methods 'E.M1<S>(S)' defined on value type 'S' cannot be used to create delegates Diagnostic(ErrorCode.ERR_ValueTypeExtDelegate, "s.M1").WithArguments("E.M1<S>(S)", "S").WithLocation(15, 13), // (16,13): error CS1113: Extension methods 'E.M2<S, object>(S)' defined on value type 'S' cannot be used to create delegates Diagnostic(ErrorCode.ERR_ValueTypeExtDelegate, "s.M2<S, object>").WithArguments("E.M2<S, object>(S)", "S").WithLocation(16, 13), // (17,13): error CS1113: Extension methods 'E.M1<T1>(T1)' defined on value type 'T1' cannot be used to create delegates Diagnostic(ErrorCode.ERR_ValueTypeExtDelegate, "t1.M1").WithArguments("E.M1<T1>(T1)", "T1").WithLocation(17, 13), // (18,13): error CS1113: Extension methods 'E.M2<T1, object>(T1)' defined on value type 'T1' cannot be used to create delegates Diagnostic(ErrorCode.ERR_ValueTypeExtDelegate, "t1.M2<T1, object>").WithArguments("E.M2<T1, object>(T1)", "T1").WithLocation(18, 13), // (21,13): error CS1113: Extension methods 'E.M1<T3>(T3)' defined on value type 'T3' cannot be used to create delegates Diagnostic(ErrorCode.ERR_ValueTypeExtDelegate, "t3.M1").WithArguments("E.M1<T3>(T3)", "T3").WithLocation(21, 13), // (22,13): error CS1113: Extension methods 'E.M2<T3, object>(T3)' defined on value type 'T3' cannot be used to create delegates Diagnostic(ErrorCode.ERR_ValueTypeExtDelegate, "t3.M2<T3, object>").WithArguments("E.M2<T3, object>(T3)", "T3").WithLocation(22, 13), // (23,13): error CS1113: Extension methods 'E.M1<T4>(T4)' defined on value type 'T4' cannot be used to create delegates Diagnostic(ErrorCode.ERR_ValueTypeExtDelegate, "t4.M1").WithArguments("E.M1<T4>(T4)", "T4").WithLocation(23, 13), // (24,13): error CS1113: Extension methods 'E.M2<T4, object>(T4)' defined on value type 'T4' cannot be used to create delegates Diagnostic(ErrorCode.ERR_ValueTypeExtDelegate, "t4.M2<T4, object>").WithArguments("E.M2<T4, object>(T4)", "T4").WithLocation(24, 13)); } [WorkItem(528758, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528758")] [Fact(Skip = "528758")] public void CS1113ERR_ValueTypeExtDelegate03() { var source = @"delegate void D(); interface I { } struct S { } class C { static void M<T1, T2, T3, T4, T5>(int i, S s, T1 t1, T2 t2, T3 t3, T4 t4, T5 t5) where T2 : class where T3 : struct where T4 : I where T5 : C { F(i.M1); F(i.M2<int, object>); F(s.M1); F(s.M2<S, object>); F(t1.M1); F(t1.M2<T1, object>); F(t2.M1); F(t2.M2<T2, object>); F(t3.M1); F(t3.M2<T3, object>); F(t4.M1); F(t4.M2<T4, object>); F(t5.M1); F(t5.M2<T5, object>); } static void F(D d) { } } static class E { internal static void M1<T>(this T t) { } internal static void M2<T, U>(this T t) { } }"; CreateCompilation(source, references: new[] { Net40.SystemCore }).VerifyDiagnostics( // (12,11): error CS1113: Extension methods 'E.M1<int>(int)' defined on value type 'int' cannot be used to create delegates Diagnostic(ErrorCode.ERR_ValueTypeExtDelegate, "i.M1").WithArguments("E.M1<int>(int)", "int").WithLocation(12, 11), // (13,11): error CS1113: Extension methods 'E.M2<int, object>(int)' defined on value type 'int' cannot be used to create delegates Diagnostic(ErrorCode.ERR_ValueTypeExtDelegate, "i.M2<int, object>").WithArguments("E.M2<int, object>(int)", "int").WithLocation(13, 11), // (14,11): error CS1113: Extension methods 'E.M1<S>(S)' defined on value type 'S' cannot be used to create delegates Diagnostic(ErrorCode.ERR_ValueTypeExtDelegate, "s.M1").WithArguments("E.M1<S>(S)", "S").WithLocation(14, 11), // (15,11): error CS1113: Extension methods 'E.M2<S, object>(S)' defined on value type 'S' cannot be used to create delegates Diagnostic(ErrorCode.ERR_ValueTypeExtDelegate, "s.M2<S, object>").WithArguments("E.M2<S, object>(S)", "S").WithLocation(15, 11), // (16,11): error CS1113: Extension methods 'E.M1<T1>(T1)' defined on value type 'T1' cannot be used to create delegates Diagnostic(ErrorCode.ERR_ValueTypeExtDelegate, "t1.M1").WithArguments("E.M1<T1>(T1)", "T1").WithLocation(16, 11), // (17,11): error CS1113: Extension methods 'E.M2<T1, object>(T1)' defined on value type 'T1' cannot be used to create delegates Diagnostic(ErrorCode.ERR_ValueTypeExtDelegate, "t1.M2<T1, object>").WithArguments("E.M2<T1, object>(T1)", "T1").WithLocation(17, 11), // (20,11): error CS1113: Extension methods 'E.M1<T3>(T3)' defined on value type 'T3' cannot be used to create delegates Diagnostic(ErrorCode.ERR_ValueTypeExtDelegate, "t3.M1").WithArguments("E.M1<T3>(T3)", "T3").WithLocation(20, 11), // (21,11): error CS1113: Extension methods 'E.M2<T3, object>(T3)' defined on value type 'T3' cannot be used to create delegates Diagnostic(ErrorCode.ERR_ValueTypeExtDelegate, "t3.M2<T3, object>").WithArguments("E.M2<T3, object>(T3)", "T3").WithLocation(21, 11), // (22,11): error CS1113: Extension methods 'E.M1<T4>(T4)' defined on value type 'T4' cannot be used to create delegates Diagnostic(ErrorCode.ERR_ValueTypeExtDelegate, "t4.M1").WithArguments("E.M1<T4>(T4)", "T4").WithLocation(22, 11), // (23,11): error CS1113: Extension methods 'E.M2<T4, object>(T4)' defined on value type 'T4' cannot be used to create delegates Diagnostic(ErrorCode.ERR_ValueTypeExtDelegate, "t4.M2<T4, object>").WithArguments("E.M2<T4, object>(T4)", "T4").WithLocation(23, 11)); } [Fact] public void CS1501ERR_BadArgCount() { var text = @" using System; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { ExampleClass ec = new ExampleClass(); ec.ExampleMethod(10, 20); } } class ExampleClass { public void ExampleMethod() { Console.WriteLine(""Zero parameters""); } } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_BadArgCount, Line = 11, Column = 16 } }); } [Fact] public void CS1502ERR_BadArgTypes() { var text = @" namespace x { public class a { public a(char i) { } public static void Main() { a aa = new a(2222); // CS1502 & CS1503 if (aa == null) {} } } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { //new ErrorDescription { Code = (int)ErrorCode.ERR_BadArgTypes, Line = 12, Column = 24 }, //specifically omitted by roslyn new ErrorDescription { Code = (int)ErrorCode.ERR_BadArgType, Line = 12, Column = 26 }}); } [Fact] public void CS1502ERR_BadArgTypes_ConstructorInitializer() { var text = @" namespace x { public class a { public a() : this(""string"") //CS1502, CS1503 { } public a(char i) { } } } "; CreateCompilation(text).VerifyDiagnostics( //// (6,22): error CS1502: The best overloaded method match for 'x.a.a(char)' has some invalid arguments //Diagnostic(ErrorCode.ERR_BadArgTypes, "this").WithArguments("x.a.a(char)"), //specifically omitted by roslyn // (6,27): error CS1503: Argument 1: cannot convert from 'string' to 'char' Diagnostic(ErrorCode.ERR_BadArgType, "\"string\"").WithArguments("1", "string", "char")); } [Fact] public void CS1503ERR_BadArgType01() { var source = @"namespace X { public class C { public C(int i, char c) { } static void M() { new C(1, 2); // CS1502 & CS1503 } } } "; CreateCompilation(source).VerifyDiagnostics( // (10,22): error CS1503: Argument 2: cannot convert from 'int' to 'char' // new C(1, 2); // CS1502 & CS1503 Diagnostic(ErrorCode.ERR_BadArgType, "2").WithArguments("2", "int", "char").WithLocation(10, 22)); } [Fact] public void CS1503ERR_BadArgType02() { var source = @"enum E1 { A, B, C } enum E2 { X, Y, Z } class C { static void F(int i) { } static void G(E1 e) { } static void M() { F(E1.A); // CS1502 & CS1503 F((E2)E1.B); // CS1502 & CS1503 F((int)E1.C); G(E2.X); // CS1502 & CS1503 G((E1)E2.Y); G((int)E2.Z); // CS1502 & CS1503 } } "; CreateCompilation(source).VerifyDiagnostics( // (9,11): error CS1503: Argument 1: cannot convert from 'E1' to 'int' // F(E1.A); // CS1502 & CS1503 Diagnostic(ErrorCode.ERR_BadArgType, "E1.A").WithArguments("1", "E1", "int").WithLocation(9, 11), // (10,11): error CS1503: Argument 1: cannot convert from 'E2' to 'int' // F((E2)E1.B); // CS1502 & CS1503 Diagnostic(ErrorCode.ERR_BadArgType, "(E2)E1.B").WithArguments("1", "E2", "int").WithLocation(10, 11), // (12,11): error CS1503: Argument 1: cannot convert from 'E2' to 'E1' // G(E2.X); // CS1502 & CS1503 Diagnostic(ErrorCode.ERR_BadArgType, "E2.X").WithArguments("1", "E2", "E1").WithLocation(12, 11), // (14,11): error CS1503: Argument 1: cannot convert from 'int' to 'E1' // G((int)E2.Z); // CS1502 & CS1503 Diagnostic(ErrorCode.ERR_BadArgType, "(int)E2.Z").WithArguments("1", "int", "E1").WithLocation(14, 11)); } [WorkItem(538939, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538939")] [Fact] public void CS1503ERR_BadArgType03() { var source = @"class C { static void F(out int i) { i = 0; } static void M(long arg) { F(out arg); // CS1503 } } "; CreateCompilation(source).VerifyDiagnostics( // (9,15): error CS1503: Argument 1: cannot convert from 'out long' to 'out int' // F(out arg); // CS1503 Diagnostic(ErrorCode.ERR_BadArgType, "arg").WithArguments("1", "out long", "out int").WithLocation(9, 15)); } [Fact] public void CS1503ERR_BadArgType_MixedMethodsAndTypes() { var text = @" class A { public static void Goo(int x) { } } class B : A { public class Goo { } } class C : B { public static void Goo(string x) { } static void Main() { ((Goo))(1); } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.WRN_NewRequired, Line = 8, Column = 16, IsWarning = true }, new ErrorDescription { Code = (int)ErrorCode.WRN_NewRequired, Line = 12, Column = 22, IsWarning = true }, //new ErrorDescription { Code = (int)ErrorCode.ERR_BadArgTypes, Line = 16, Column = 5 }, //specifically omitted by roslyn new ErrorDescription { Code = (int)ErrorCode.ERR_BadArgType, Line = 16, Column = 13 } }); } [Fact] public void CS1510ERR_RefLvalueExpected_01() { var text = @"class C { void M(ref int i) { M(ref 2); // CS1510, can't pass a number as a ref parameter } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_RefLvalueExpected, Line = 5, Column = 15 }); } [Fact] public void CS1510ERR_RefLvalueExpected_02() { var text = @"class C { void M() { var a = new System.Action<int>(ref x => x = 1); var b = new System.Action<int, int>(ref (x,y) => x = 1); var c = new System.Action<int>(ref delegate (int x) {x = 1;}); } } "; CreateCompilation(text).VerifyDiagnostics( // (5,44): error CS1510: A ref or out argument must be an assignable variable // var a = new System.Action<int>(ref x => x = 1); Diagnostic(ErrorCode.ERR_RefLvalueExpected, "x => x = 1").WithLocation(5, 44), // (6,49): error CS1510: A ref or out argument must be an assignable variable // var b = new System.Action<int, int>(ref (x,y) => x = 1); Diagnostic(ErrorCode.ERR_RefLvalueExpected, "(x,y) => x = 1").WithLocation(6, 49), // (7,44): error CS1510: A ref or out argument must be an assignable variable // var c = new System.Action<int>(ref delegate (int x) {x = 1;}); Diagnostic(ErrorCode.ERR_RefLvalueExpected, "delegate (int x) {x = 1;}").WithLocation(7, 44)); } [Fact] public void CS1510ERR_RefLvalueExpected_03() { var text = @"class C { void M() { var a = new System.Action<int>(out x => x = 1); var b = new System.Action<int, int>(out (x,y) => x = 1); var c = new System.Action<int>(out delegate (int x) {x = 1;}); } } "; CreateCompilation(text).VerifyDiagnostics( // (5,44): error CS1510: A ref or out argument must be an assignable variable // var a = new System.Action<int>(out x => x = 1); Diagnostic(ErrorCode.ERR_RefLvalueExpected, "x => x = 1").WithLocation(5, 44), // (6,49): error CS1510: A ref or out argument must be an assignable variable // var b = new System.Action<int, int>(out (x,y) => x = 1); Diagnostic(ErrorCode.ERR_RefLvalueExpected, "(x,y) => x = 1").WithLocation(6, 49), // (7,44): error CS1510: A ref or out argument must be an assignable variable // var c = new System.Action<int>(out delegate (int x) {x = 1;}); Diagnostic(ErrorCode.ERR_RefLvalueExpected, "delegate (int x) {x = 1;}").WithLocation(7, 44)); } [Fact] public void CS1510ERR_RefLvalueExpected_04() { var text = @"class C { void Goo<T>(ref System.Action<T> t) {} void Goo<T1,T2>(ref System.Action<T1,T2> t) {} void M() { Goo<int>(ref x => x = 1); Goo<int, int>(ref (x,y) => x = 1); Goo<int>(ref delegate (int x) {x = 1;}); } } "; CreateCompilation(text).VerifyDiagnostics( // (7,22): error CS1510: A ref or out argument must be an assignable variable // Goo<int>(ref x => x = 1); Diagnostic(ErrorCode.ERR_RefLvalueExpected, "x => x = 1").WithLocation(7, 22), // (8,27): error CS1510: A ref or out argument must be an assignable variable // Goo<int, int>(ref (x,y) => x = 1); Diagnostic(ErrorCode.ERR_RefLvalueExpected, "(x,y) => x = 1").WithLocation(8, 27), // (9,22): error CS1510: A ref or out argument must be an assignable variable // Goo<int>(ref delegate (int x) {x = 1;}); Diagnostic(ErrorCode.ERR_RefLvalueExpected, "delegate (int x) {x = 1;}").WithLocation(9, 22)); } [Fact] public void CS1510ERR_RefLvalueExpected_05() { var text = @"class C { void Goo<T>(out System.Action<T> t) {t = null;} void Goo<T1,T2>(out System.Action<T1,T2> t) {t = null;} void M() { Goo<int>(out x => x = 1); Goo<int, int>(out (x,y) => x = 1); Goo<int>(out delegate (int x) {x = 1;}); } } "; CreateCompilation(text).VerifyDiagnostics( // (7,22): error CS1510: A ref or out argument must be an assignable variable // Goo<int>(out x => x = 1); Diagnostic(ErrorCode.ERR_RefLvalueExpected, "x => x = 1").WithLocation(7, 22), // (8,27): error CS1510: A ref or out argument must be an assignable variable // Goo<int, int>(out (x,y) => x = 1); Diagnostic(ErrorCode.ERR_RefLvalueExpected, "(x,y) => x = 1").WithLocation(8, 27), // (9,22): error CS1510: A ref or out argument must be an assignable variable // Goo<int>(out delegate (int x) {x = 1;}); Diagnostic(ErrorCode.ERR_RefLvalueExpected, "delegate (int x) {x = 1;}").WithLocation(9, 22)); } [Fact] public void CS1510ERR_RefLvalueExpected_Strict() { var text = @"class C { void D(int i) {} void M() { System.Action<int> del = D; var a = new System.Action<int>(ref D); var b = new System.Action<int>(out D); var c = new System.Action<int>(ref del); var d = new System.Action<int>(out del); } } "; CreateCompilation(text, parseOptions: TestOptions.Regular.WithStrictFeature()).VerifyDiagnostics( // (8,44): error CS1657: Cannot pass 'D' as a ref or out argument because it is a 'method group' // var a = new System.Action<int>(ref D); Diagnostic(ErrorCode.ERR_RefReadonlyLocalCause, "D").WithArguments("D", "method group").WithLocation(8, 44), // (9,44): error CS1657: Cannot pass 'D' as a ref or out argument because it is a 'method group' // var b = new System.Action<int>(out D); Diagnostic(ErrorCode.ERR_RefReadonlyLocalCause, "D").WithArguments("D", "method group").WithLocation(9, 44), // (10,44): error CS0149: Method name expected // var c = new System.Action<int>(ref del); Diagnostic(ErrorCode.ERR_MethodNameExpected, "del").WithLocation(10, 44), // (11,44): error CS0149: Method name expected // var d = new System.Action<int>(out del); Diagnostic(ErrorCode.ERR_MethodNameExpected, "del").WithLocation(11, 44)); } [Fact] public void CS1511ERR_BaseInStaticMeth() { var text = @" public class A { public int j = 0; } class C : A { public void Method() { base.j = 3; // base allowed here } public static int StaticMethod() { base.j = 3; // CS1511 return 1; } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_BaseInStaticMeth, Line = 16, Column = 7 } }); } [Fact] public void CS1511ERR_BaseInStaticMeth_Combined() { var text = @" using System; class CLS { static CLS() { var x = base.ToString(); } static object FLD = base.ToString(); static object PROP { get { return base.ToString(); } } static object METHOD() { return base.ToString(); } } class A : Attribute { public object P; } "; CreateCompilation(text).VerifyDiagnostics( // (7,25): error CS1511: Keyword 'base' is not available in a static method // static object FLD = base.ToString(); Diagnostic(ErrorCode.ERR_BaseInStaticMeth, "base"), // (6,28): error CS1511: Keyword 'base' is not available in a static method // static CLS() { var x = base.ToString(); } Diagnostic(ErrorCode.ERR_BaseInStaticMeth, "base"), // (8,39): error CS1511: Keyword 'base' is not available in a static method // static object PROP { get { return base.ToString(); } } Diagnostic(ErrorCode.ERR_BaseInStaticMeth, "base"), // (9,37): error CS1511: Keyword 'base' is not available in a static method // static object METHOD() { return base.ToString(); } Diagnostic(ErrorCode.ERR_BaseInStaticMeth, "base"), // (14,19): warning CS0649: Field 'A.P' is never assigned to, and will always have its default value null // public object P; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "P").WithArguments("A.P", "null") ); } [Fact] public void CS1512ERR_BaseInBadContext() { var text = @" using System; class Base { } class CMyClass : Base { private String xx = base.ToString(); // CS1512 public static void Main() { CMyClass z = new CMyClass(); } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_BaseInBadContext, Line = 8, Column = 25 } }); } [Fact] public void CS1512ERR_BaseInBadContext_AttributeArgument() { var text = @" using System; [assembly: A(P = base.ToString())] public class A : Attribute { public object P; } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_BaseInBadContext, Line = 4, Column = 18 } }); } [Fact] public void CS1520ERR_MemberNeedsType_02() { CreateCompilation( @"class Program { Main() {} Helper() {} \u0050rogram(int x) {} }") .VerifyDiagnostics( // (3,5): error CS1520: Method must have a return type // Main() {} Diagnostic(ErrorCode.ERR_MemberNeedsType, "Main"), // (4,5): error CS1520: Method must have a return type // Helper() {} Diagnostic(ErrorCode.ERR_MemberNeedsType, "Helper").WithLocation(4, 5) ); } [Fact] public void CS1525ERR_InvalidExprTerm() { CreateCompilation( @"public class MyClass { public static int Main() { bool b = string is string; return 1; } }") .VerifyDiagnostics(Diagnostic(ErrorCode.ERR_InvalidExprTerm, "string").WithArguments("string")); } [WorkItem(543167, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543167")] [Fact] public void CS1525ERR_InvalidExprTerm_1() { CreateCompilation( @"class D { public static void Main() { var s = 1?; } } ") .VerifyDiagnostics( // (5,19): error CS1525: Invalid expression term ';' // var s = 1?; Diagnostic(ErrorCode.ERR_InvalidExprTerm, ";").WithArguments(";"), // (5,19): error CS1003: Syntax error, ':' expected // var s = 1?; Diagnostic(ErrorCode.ERR_SyntaxError, ";").WithArguments(":", ";"), // (5,19): error CS1525: Invalid expression term ';' // var s = 1?; Diagnostic(ErrorCode.ERR_InvalidExprTerm, ";").WithArguments(";"), // (5,17): error CS0029: Cannot implicitly convert type 'int' to 'bool' // var s = 1?; Diagnostic(ErrorCode.ERR_NoImplicitConv, "1").WithArguments("int", "bool") ); } [Fact] public void CS1525ERR_InvalidExprTerm_ConditionalOperator() { CreateCompilation( @"class Program { static void Main(string[] args) { int x = 1; int y = 1; System.Console.WriteLine(((x == y)) ?); // Invalid System.Console.WriteLine(((x == y)) ? (x++)); // Invalid System.Console.WriteLine(((x == y)) ? (x++) : (x++) : ((((y++))))); // Invalid System.Console.WriteLine(((x == y)) ? : :); // Invalid } } ") .VerifyDiagnostics(Diagnostic(ErrorCode.ERR_InvalidExprTerm, ")").WithArguments(")"), Diagnostic(ErrorCode.ERR_SyntaxError, ")").WithArguments(":", ")"), Diagnostic(ErrorCode.ERR_InvalidExprTerm, ")").WithArguments(")"), Diagnostic(ErrorCode.ERR_SyntaxError, ")").WithArguments(":", ")"), Diagnostic(ErrorCode.ERR_InvalidExprTerm, ")").WithArguments(")"), Diagnostic(ErrorCode.ERR_SyntaxError, ":").WithArguments(",", ":"), Diagnostic(ErrorCode.ERR_SyntaxError, "(").WithArguments(",", "("), Diagnostic(ErrorCode.ERR_InvalidExprTerm, ":").WithArguments(":"), Diagnostic(ErrorCode.ERR_InvalidExprTerm, ":").WithArguments(":"), Diagnostic(ErrorCode.ERR_SyntaxError, ":").WithArguments(",", ":")); } [WorkItem(528657, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528657")] [Fact] public void CS0106ERR_BadMemberFlag() { CreateCompilation( @"new class MyClass { }") .VerifyDiagnostics(Diagnostic(ErrorCode.ERR_BadMemberFlag, "MyClass").WithArguments("new")); } [Fact] public void CS1540ERR_BadProtectedAccess01() { var text = @" namespace CS1540 { class Program1 { static void Main() { Employee.PreparePayroll(); } } class Person { protected virtual void CalculatePay() { } } class Manager : Person { protected override void CalculatePay() { } } class Employee : Person { public static void PreparePayroll() { Employee emp1 = new Employee(); Person emp2 = new Manager(); Person emp3 = new Employee(); emp1.CalculatePay(); emp2.CalculatePay(); emp3.CalculatePay(); } } }"; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_BadProtectedAccess, Line = 34, Column = 18 }, new ErrorDescription { Code = (int)ErrorCode.ERR_BadProtectedAccess, Line = 35, Column = 18 }}); } [Fact] public void CS1540ERR_BadProtectedAccess02() { var text = @"class A { protected object F; protected void M() { } protected object P { get; set; } public object Q { get; protected set; } public object R { protected get; set; } public object S { private get; set; } } class B : A { void M(object o) { // base. base.M(); base.P = base.F; base.Q = null; M(base.R); M(base.S); // a. A a = new A(); a.M(); a.P = a.F; a.Q = null; M(a.R); M(a.S); // G(). G().M(); G().P = G().F; G().Q = null; M(G().R); M(G().S); // no qualifier M(); P = F; Q = null; M(R); M(S); // this. this.M(); this.P = this.F; this.Q = null; M(this.R); M(this.S); // ((A)this). ((A)this).M(); ((A)this).P = ((A)this).F; ((A)this).Q = null; M(((A)this).R); M(((A)this).S); } static A G() { return null; } } "; CreateCompilation(text).VerifyDiagnostics( // (21,11): error CS0271: The property or indexer 'A.S' cannot be used in this context because the get accessor is inaccessible // M(base.S); Diagnostic(ErrorCode.ERR_InaccessibleGetter, "base.S").WithArguments("A.S"), // (24,11): error CS1540: Cannot access protected member 'A.M()' via a qualifier of type 'A'; the qualifier must be of type 'B' (or derived from it) // a.M(); Diagnostic(ErrorCode.ERR_BadProtectedAccess, "M").WithArguments("A.M()", "A", "B"), // (25,11): error CS1540: Cannot access protected member 'A.P' via a qualifier of type 'A'; the qualifier must be of type 'B' (or derived from it) // a.P = a.F; Diagnostic(ErrorCode.ERR_BadProtectedAccess, "P").WithArguments("A.P", "A", "B"), // (25,17): error CS1540: Cannot access protected member 'A.F' via a qualifier of type 'A'; the qualifier must be of type 'B' (or derived from it) // a.P = a.F; Diagnostic(ErrorCode.ERR_BadProtectedAccess, "F").WithArguments("A.F", "A", "B"), // (26,9): error CS1540: Cannot access protected member 'A.Q' via a qualifier of type 'A'; the qualifier must be of type 'B' (or derived from it) // a.Q = null; Diagnostic(ErrorCode.ERR_BadProtectedAccess, "a.Q").WithArguments("A.Q", "A", "B"), // (27,11): error CS1540: Cannot access protected member 'A.R' via a qualifier of type 'A'; the qualifier must be of type 'B' (or derived from it) // M(a.R); Diagnostic(ErrorCode.ERR_BadProtectedAccess, "a.R").WithArguments("A.R", "A", "B"), // (28,11): error CS0271: The property or indexer 'A.S' cannot be used in this context because the get accessor is inaccessible // M(a.S); Diagnostic(ErrorCode.ERR_InaccessibleGetter, "a.S").WithArguments("A.S"), // (30,13): error CS1540: Cannot access protected member 'A.M()' via a qualifier of type 'A'; the qualifier must be of type 'B' (or derived from it) // G().M(); Diagnostic(ErrorCode.ERR_BadProtectedAccess, "M").WithArguments("A.M()", "A", "B"), // (31,13): error CS1540: Cannot access protected member 'A.P' via a qualifier of type 'A'; the qualifier must be of type 'B' (or derived from it) // G().P = G().F; Diagnostic(ErrorCode.ERR_BadProtectedAccess, "P").WithArguments("A.P", "A", "B"), // (31,21): error CS1540: Cannot access protected member 'A.F' via a qualifier of type 'A'; the qualifier must be of type 'B' (or derived from it) // G().P = G().F; Diagnostic(ErrorCode.ERR_BadProtectedAccess, "F").WithArguments("A.F", "A", "B"), // (32,9): error CS1540: Cannot access protected member 'A.Q' via a qualifier of type 'A'; the qualifier must be of type 'B' (or derived from it) // G().Q = null; Diagnostic(ErrorCode.ERR_BadProtectedAccess, "G().Q").WithArguments("A.Q", "A", "B"), // (33,11): error CS1540: Cannot access protected member 'A.R' via a qualifier of type 'A'; the qualifier must be of type 'B' (or derived from it) // M(G().R); Diagnostic(ErrorCode.ERR_BadProtectedAccess, "G().R").WithArguments("A.R", "A", "B"), // (34,11): error CS0271: The property or indexer 'A.S' cannot be used in this context because the get accessor is inaccessible // M(G().S); Diagnostic(ErrorCode.ERR_InaccessibleGetter, "G().S").WithArguments("A.S"), // (40,11): error CS0271: The property or indexer 'A.S' cannot be used in this context because the get accessor is inaccessible // M(S); Diagnostic(ErrorCode.ERR_InaccessibleGetter, "S").WithArguments("A.S"), // (46,11): error CS0271: The property or indexer 'A.S' cannot be used in this context because the get accessor is inaccessible // M(this.S); Diagnostic(ErrorCode.ERR_InaccessibleGetter, "this.S").WithArguments("A.S"), // (48,19): error CS1540: Cannot access protected member 'A.M()' via a qualifier of type 'A'; the qualifier must be of type 'B' (or derived from it) // ((A)this).M(); Diagnostic(ErrorCode.ERR_BadProtectedAccess, "M").WithArguments("A.M()", "A", "B"), // (49,19): error CS1540: Cannot access protected member 'A.P' via a qualifier of type 'A'; the qualifier must be of type 'B' (or derived from it) // ((A)this).P = ((A)this).F; Diagnostic(ErrorCode.ERR_BadProtectedAccess, "P").WithArguments("A.P", "A", "B"), // (49,33): error CS1540: Cannot access protected member 'A.F' via a qualifier of type 'A'; the qualifier must be of type 'B' (or derived from it) // ((A)this).P = ((A)this).F; Diagnostic(ErrorCode.ERR_BadProtectedAccess, "F").WithArguments("A.F", "A", "B"), // (50,9): error CS1540: Cannot access protected member 'A.Q' via a qualifier of type 'A'; the qualifier must be of type 'B' (or derived from it) // ((A)this).Q = null; Diagnostic(ErrorCode.ERR_BadProtectedAccess, "((A)this).Q").WithArguments("A.Q", "A", "B"), // (51,11): error CS1540: Cannot access protected member 'A.R' via a qualifier of type 'A'; the qualifier must be of type 'B' (or derived from it) // M(((A)this).R); Diagnostic(ErrorCode.ERR_BadProtectedAccess, "((A)this).R").WithArguments("A.R", "A", "B"), // (52,11): error CS0271: The property or indexer 'A.S' cannot be used in this context because the get accessor is inaccessible // M(((A)this).S); Diagnostic(ErrorCode.ERR_InaccessibleGetter, "((A)this).S").WithArguments("A.S"), // (3,22): warning CS0649: Field 'A.F' is never assigned to, and will always have its default value null // protected object F; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "F").WithArguments("A.F", "null") ); } [WorkItem(540271, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540271")] [Fact] public void CS0122ERR_BadAccessProtectedCtor() { // It is illegal to access any "protected" instance method with a "this" that is not of the // current class's type. Oddly enough, that includes constructors. It is legal to call // a protected ctor via ": base()" because then the "this" is of the derived type. But // in a derived class you cannot call "new MyBase()" if the ctor is protected. // // The native compiler produces the error CS1540 whether the offending method is a regular // method or a ctor: // // Cannot access protected member 'MyBase.MyBase' via a qualifier of type 'MyBase'; // the qualifier must be of type 'Derived' (or derived from it) // // Though technically correct, this is a very confusing error message for this scenario; // one does not typically think of the constructor as being a method that is // called with an implicit "this" of a particular receiver type, even though of course // that is exactly what it is. // // The better error message here is to simply say that the best possible ctor cannot // be accessed because it is not accessible. That's what Roslyn does. // // CONSIDER: We might consider making up a new error message for this situation. // // CS0122: 'Base.Base' is inaccessible due to its protection level var text = @"namespace CS0122 { public class Base { protected Base() {} } public class Derived : Base { void M() { Base b = new Base(); } } } "; CreateCompilation(text). VerifyDiagnostics(Diagnostic(ErrorCode.ERR_BadAccess, "Base").WithArguments("CS0122.Base.Base()")); } // CS1545ERR_BindToBogusProp2 --> Symbols\Source\EventTests.cs // CS1546ERR_BindToBogusProp1 --> Symbols\Source\PropertyTests.cs [WorkItem(528658, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528658")] [Fact()] public void CS1560ERR_FileNameTooLong() { var text = @" #line 1 ""ccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc"" public class C { public void Main () { } } "; //EDMAURER no need to enforce a limit here. DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text);//, //new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_FileNameTooLong, Line = 1, Column = 25 } }); } [Fact] public void CS1579ERR_ForEachMissingMember() { var text = @" using System; public class MyCollection { int[] items; public MyCollection() { items = new int[5] { 12, 44, 33, 2, 50 }; } MyEnumerator GetEnumerator() { return new MyEnumerator(this); } public class MyEnumerator { int nIndex; MyCollection collection; public MyEnumerator(MyCollection coll) { collection = coll; nIndex = -1; } public bool MoveNext() { nIndex++; return (nIndex < collection.items.GetLength(0)); } public int Current { get { return (collection.items[nIndex]); } } } public static void Main() { MyCollection col = new MyCollection(); Console.WriteLine(""Values in the collection are:""); foreach (int i in col) // CS1579 { Console.WriteLine(i); } } }"; CreateCompilation(text).VerifyDiagnostics( // (45,27): warning CS0279: 'MyCollection' does not implement the 'collection' pattern. 'MyCollection.GetEnumerator()' is not a public instance or extension method. // foreach (int i in col) // CS1579 Diagnostic(ErrorCode.WRN_PatternNotPublicOrNotInstance, "col").WithArguments("MyCollection", "collection", "MyCollection.GetEnumerator()"), // (45,27): error CS1579: foreach statement cannot operate on variables of type 'MyCollection' because 'MyCollection' does not contain a public definition for 'GetEnumerator' // foreach (int i in col) // CS1579 Diagnostic(ErrorCode.ERR_ForEachMissingMember, "col").WithArguments("MyCollection", "GetEnumerator")); } [Fact] public void CS1579ERR_ForEachMissingMember02() { var text = @" public class Test { public static void Main(string[] args) { foreach (int x in F(1)) { } } static void F(int x) { } } "; CreateCompilation(text). VerifyDiagnostics(Diagnostic(ErrorCode.ERR_ForEachMissingMember, "F(1)").WithArguments("void", "GetEnumerator")); } [Fact] public void CS1593ERR_BadDelArgCount() { var text = @" using System; delegate string func(int i); // declare delegate class a { public static void Main() { func dt = new func(z); x(dt); } public static string z(int j) { Console.WriteLine(j); return j.ToString(); } public static void x(func hello) { hello(8, 9); // CS1593 } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_BadDelArgCount, Line = 21, Column = 9 } }); } [Fact] public void CS1593ERR_BadDelArgCount_02() { var text = @" delegate void MyDelegate1(int x, float y); class Program { public void DelegatedMethod(int x, float y = 3.0f) { System.Console.WriteLine(y); } static void Main(string[] args) { Program mc = new Program(); MyDelegate1 md1 = null; md1 += mc.DelegatedMethod; md1(1); md1 -= mc.DelegatedMethod; } } "; CreateCompilation(text).VerifyDiagnostics( // (11,9): error CS7036: There is no argument given that corresponds to the required formal parameter 'y' of 'MyDelegate1' // md1(1); Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "md1").WithArguments("y", "MyDelegate1").WithLocation(11, 9)); } [Fact] public void CS1593ERR_BadDelArgCount_03() { var text = @" using System; class Program { static void Main() { new Action<int>(Console.WriteLine)(1, 1); } } "; CreateCompilation(text). VerifyDiagnostics(Diagnostic(ErrorCode.ERR_BadDelArgCount, "new Action<int>(Console.WriteLine)").WithArguments("System.Action<int>", "2")); } [Fact()] public void CS1594ERR_BadDelArgTypes() { var text = @" using System; delegate string func(int i); // declare delegate class a { public static void Main() { func dt = new func(z); x(dt); } public static string z(int j) { Console.WriteLine(j); return j.ToString(); } public static void x(func hello) { hello(""8""); // CS1594 } } "; //EDMAURER Giving errors for the individual argument problems is better than generic "delegate 'blah' has some invalid arguments" DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_BadArgType, Line = 21, Column = 15 } }); //new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_BadDelArgTypes, Line = 21, Column = 9 } }); } // TODO: change this to CS0051 in Roslyn? [Fact] public void CS1604ERR_AssgReadonlyLocal() { var text = @" class C { void M() { this = null; } }"; CreateCompilation(text).VerifyDiagnostics( // (6,9): error CS1604: Cannot assign to 'this' because it is read-only Diagnostic(ErrorCode.ERR_AssgReadonlyLocal, "this").WithArguments("this")); } [Fact] public void CS1605ERR_RefReadonlyLocal() { var text = @" class C { void Test() { Ref(ref this); //CS1605 Out(out this); //CS1605 } static void Ref(ref C c) { } static void Out(out C c) { c = null; } }"; CreateCompilation(text).VerifyDiagnostics( // (6,17): error CS1605: Cannot pass 'this' as a ref or out argument because it is read-only Diagnostic(ErrorCode.ERR_RefReadonlyLocal, "this").WithArguments("this"), // (7,17): error CS1605: Cannot pass 'this' as a ref or out argument because it is read-only Diagnostic(ErrorCode.ERR_RefReadonlyLocal, "this").WithArguments("this")); } [Fact] public void CS1612ERR_ReturnNotLValue01() { var text = @" public struct MyStruct { public int Width; } public class ListView { MyStruct ms; public MyStruct Size { get { return ms; } set { ms = value; } } } public class MyClass { public MyClass() { ListView lvi; lvi = new ListView(); lvi.Size.Width = 5; // CS1612 } public static void Main() { } }"; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_ReturnNotLValue, Line = 23, Column = 9 } }); } /// <summary> /// Breaking change from Dev10. CS1612 is now reported for all value /// types, not just struct types. Specifically, CS1612 is now reported /// for type parameters constrained to "struct". (See also CS0131.) /// </summary> [WorkItem(528821, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528821")] [Fact] public void CS1612ERR_ReturnNotLValue02() { var source = @"interface I { object P { get; set; } } struct S : I { public object P { get; set; } } class C<T, U, V> where T : struct, I where U : class, I where V : I { S F1 { get; set; } T F2 { get; set; } U F3 { get; set; } V F4 { get; set; } void M() { F1.P = null; F2.P = null; F3.P = null; F4.P = null; } }"; CreateCompilation(source).VerifyDiagnostics( // (20,9): error CS1612: Cannot modify the return value of 'C<T, U, V>.F1' because it is not a variable Diagnostic(ErrorCode.ERR_ReturnNotLValue, "F1").WithArguments("C<T, U, V>.F1").WithLocation(20, 9), // (20,9): error CS1612: Cannot modify the return value of 'C<T, U, V>.F2' because it is not a variable Diagnostic(ErrorCode.ERR_ReturnNotLValue, "F2").WithArguments("C<T, U, V>.F2").WithLocation(21, 9)); } [Fact] public void CS1615ERR_BadArgExtraRef() { var text = @" class C { public void f(int i) {} public static void Main() { int i = 1; f(ref i); // CS1615 } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { //new ErrorDescription { Code = (int)ErrorCode.ERR_BadArgTypes, Line = 8, Column = 7 }, //specifically omitted by roslyn new ErrorDescription { Code = (int)ErrorCode.ERR_BadArgExtraRef, Line = 8, Column = 13 } }); } [Fact()] public void CS1618ERR_DelegateOnConditional() { var text = @" using System.Diagnostics; delegate void del(); class MakeAnError { public static void Main() { del d = new del(ConditionalMethod); // CS1618 } [Conditional(""DEBUG"")] public static void ConditionalMethod() { } } "; CreateCompilation(text).VerifyDiagnostics( // (10,25): error CS1618: Cannot create delegate with 'MakeAnError.ConditionalMethod()' because it has a Conditional attribute // del d = new del(ConditionalMethod); // CS1618 Diagnostic(ErrorCode.ERR_DelegateOnConditional, "ConditionalMethod").WithArguments("MakeAnError.ConditionalMethod()").WithLocation(10, 25)); } [Fact()] public void CS1618ERR_DelegateOnConditional_02() { var text = @" using System; using System.Diagnostics; delegate void del(); class MakeAnError { class Goo: Attribute { public Goo(object o) {} } [Conditional(""DEBUG"")] [Goo(new del(ConditionalMethod))] // CS1618 public static void ConditionalMethod() { } } "; CreateCompilation(text).VerifyDiagnostics( // (15,18): error CS1618: Cannot create delegate with 'MakeAnError.ConditionalMethod()' because it has a Conditional attribute // [Goo(new del(ConditionalMethod))] // CS1618 Diagnostic(ErrorCode.ERR_DelegateOnConditional, "ConditionalMethod").WithArguments("MakeAnError.ConditionalMethod()").WithLocation(15, 18)); } [Fact] public void CS1620ERR_BadArgRef() { var text = @" class C { void f(ref int i) { } public static void Main() { int x = 1; f(out x); // CS1620 - f takes a ref parameter, not an out parameter } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { //new ErrorDescription { Code = (int)ErrorCode.ERR_BadArgTypes, Line = 8, Column = 9 }, //specifically omitted by roslyn new ErrorDescription { Code = (int)ErrorCode.ERR_BadArgRef, Line = 8, Column = 15 } }); } [Fact] public void CS1621ERR_YieldInAnonMeth() { var text = @" using System.Collections; delegate object MyDelegate(); class C : IEnumerable { public IEnumerator GetEnumerator() { MyDelegate d = delegate { yield return this; // CS1621 return this; }; d(); } public static void Main() { } } "; var comp = CreateCompilation(text); var expected = new DiagnosticDescription[] { // (12,13): error CS1621: The yield statement cannot be used inside an anonymous method or lambda expression // yield return this; // CS1621 Diagnostic(ErrorCode.ERR_YieldInAnonMeth, "yield"), // (8,24): error CS0161: 'C.GetEnumerator()': not all code paths return a value // public IEnumerator GetEnumerator() Diagnostic(ErrorCode.ERR_ReturnExpected, "GetEnumerator").WithArguments("C.GetEnumerator()") }; comp.VerifyDiagnostics(expected); comp.VerifyEmitDiagnostics(expected); } [Fact] public void CS1622ERR_ReturnInIterator() { var text = @" using System.Collections; class C : IEnumerable { public IEnumerator GetEnumerator() { return (IEnumerator) this; // CS1622 yield return this; // OK } } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (8,7): error CS1622: Cannot return a value from an iterator. Use the yield return statement to return a value, or yield break to end the iteration. // return (IEnumerator) this; // CS1622 Diagnostic(ErrorCode.ERR_ReturnInIterator, "return"), // (9,7): warning CS0162: Unreachable code detected // yield return this; // OK Diagnostic(ErrorCode.WRN_UnreachableCode, "yield") ); } [Fact] public void CS1623ERR_BadIteratorArgType() { var text = @" using System.Collections; class C : IEnumerable { public IEnumerator GetEnumerator() { yield return 0; } public IEnumerator GetEnumerator(ref int i) // CS1623 { yield return i; } public IEnumerator GetEnumerator(out float f) // CS1623 { f = 0.0F; yield return f; } } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (11,46): error CS1623: Iterators cannot have ref, in or out parameters // public IEnumerator GetEnumerator(ref int i) // CS1623 Diagnostic(ErrorCode.ERR_BadIteratorArgType, "i"), // (16,48): error CS1623: Iterators cannot have ref, in or out parameters // public IEnumerator GetEnumerator(out float f) // CS1623 Diagnostic(ErrorCode.ERR_BadIteratorArgType, "f") ); } [Fact] public void CS1624ERR_BadIteratorReturn() { var text = @" class C { public int Iterator { get // CS1624 { yield return 1; } } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_BadIteratorReturn, Line = 6, Column = 9 } }); } [Fact] public void CS1625ERR_BadYieldInFinally() { var text = @" using System.Collections; class C : IEnumerable { public IEnumerator GetEnumerator() { try { } finally { yield return this; // CS1625 } } } public class CMain { public static void Main() { } } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (13,9): error CS1625: Cannot yield in the body of a finally clause // yield return this; // CS1625 Diagnostic(ErrorCode.ERR_BadYieldInFinally, "yield") ); } [Fact] public void CS1626ERR_BadYieldInTryOfCatch() { var text = @" using System.Collections; class C : IEnumerable { public IEnumerator GetEnumerator() { try { yield return this; // CS1626 } catch { } } } public class CMain { public static void Main() { } } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (10,10): error CS1626: Cannot yield a value in the body of a try block with a catch clause // yield return this; // CS1626 Diagnostic(ErrorCode.ERR_BadYieldInTryOfCatch, "yield") ); } [Fact] public void CS1628ERR_AnonDelegateCantUse() { var text = @" delegate int MyDelegate(); class C { public static void F(ref int i) { MyDelegate d = delegate { return i; }; // CS1628 } public static void Main() { } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_AnonDelegateCantUse, Line = 8, Column = 42 } }); } [Fact] public void CS1629ERR_IllegalInnerUnsafe() { var text = @" using System.Collections.Generic; class C { IEnumerator<int> IteratorMeth() { int i; unsafe // CS1629 { int *p = &i; yield return *p; } } unsafe IEnumerator<int> IteratorMeth2() { // CS1629 yield break; } } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (7,7): error CS1629: Unsafe code may not appear in iterators // unsafe // CS1629 Diagnostic(ErrorCode.ERR_IllegalInnerUnsafe, "unsafe"), // (9,10): error CS1629: Unsafe code may not appear in iterators // int *p = &i; Diagnostic(ErrorCode.ERR_IllegalInnerUnsafe, "int *"), // (9,19): error CS1629: Unsafe code may not appear in iterators // int *p = &i; Diagnostic(ErrorCode.ERR_IllegalInnerUnsafe, "&i"), // (10,24): error CS1629: Unsafe code may not appear in iterators // yield return *p; Diagnostic(ErrorCode.ERR_IllegalInnerUnsafe, "p"), // (14,29): error CS1629: Unsafe code may not appear in iterators // unsafe IEnumerator<int> IteratorMeth2() { // CS1629 Diagnostic(ErrorCode.ERR_IllegalInnerUnsafe, "IteratorMeth2") ); } [Fact] public void CS1631ERR_BadYieldInCatch() { var text = @" using System; using System.Collections; public class C : IEnumerable { public IEnumerator GetEnumerator() { try { } catch(Exception e) { yield return this; // CS1631 } } public static void Main() { } } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (14,9): error CS1631: Cannot yield a value in the body of a catch clause // yield return this; // CS1631 Diagnostic(ErrorCode.ERR_BadYieldInCatch, "yield"), // (12,23): warning CS0168: The variable 'e' is declared but never used // catch(Exception e) Diagnostic(ErrorCode.WRN_UnreferencedVar, "e").WithArguments("e") ); } [Fact] public void CS1632ERR_BadDelegateLeave() { var text = @" delegate void MyDelegate(); class MyClass { public void Test() { for (int i = 0 ; i < 5 ; i++) { MyDelegate d = delegate { break; // CS1632 }; } } } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (10,13): error CS1632: Control cannot leave the body of an anonymous method or lambda expression // break; // CS1632 Diagnostic(ErrorCode.ERR_BadDelegateLeave, "break") ); } [Fact] public void CS1636ERR_VarargsIterator() { var text = @"using System.Collections; public class Test { IEnumerable Goo(__arglist) { yield return 1; } static int Main(string[] args) { return 1; } } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (5,17): error CS1636: __arglist is not allowed in the parameter list of iterators // IEnumerable Goo(__arglist) Diagnostic(ErrorCode.ERR_VarargsIterator, "Goo")); } [Fact] public void CS1637ERR_UnsafeIteratorArgType() { var text = @" using System.Collections; public unsafe class C { public IEnumerator Iterator1(int* p) // CS1637 { yield return null; } } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (6,39): error CS1637: Iterators cannot have unsafe parameters or yield types Diagnostic(ErrorCode.ERR_UnsafeIteratorArgType, "p")); } [Fact()] public void CS1639ERR_BadCoClassSig() { // BREAKING CHANGE: Dev10 allows this test to compile, even though the output assembly is not verifiable and generates a runtime exception: // BREAKING CHANGE: We disallow CoClass creation if coClassType is an unbound generic type and report a compile time error. var text = @" using System.Runtime.InteropServices; [ComImport, Guid(""00020810-0000-0000-C000-000000000046"")] [CoClass(typeof(GenericClass<>))] public interface InterfaceType {} public class GenericClass<T>: InterfaceType {} public class Program { public static void Main() { var i = new InterfaceType(); } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_BadCoClassSig, Line = 12, Column = 41 } } ); } [Fact()] public void CS1640ERR_MultipleIEnumOfT() { var text = @" using System.Collections; using System.Collections.Generic; public class C : IEnumerable, IEnumerable<int>, IEnumerable<string> { IEnumerator<int> IEnumerable<int>.GetEnumerator() { yield break; } IEnumerator<string> IEnumerable<string>.GetEnumerator() { yield break; } IEnumerator IEnumerable.GetEnumerator() { return (IEnumerator)((IEnumerable<string>)this).GetEnumerator(); } } public class Test { public static int Main() { foreach (int i in new C()) { } // CS1640 return 1; } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_MultipleIEnumOfT, Line = 27, Column = 27 } }); } [WorkItem(7389, "DevDiv_Projects/Roslyn")] [Fact] public void CS1640ERR_MultipleIEnumOfT02() { var text = @" using System.Collections.Generic; public class Test { public static void Main(string[] args) { } } public class C<T> where T : IEnumerable<int>, IEnumerable<string> { public static void TestForeach(T t) { foreach (int i in t) { } } } "; CreateCompilation(text). VerifyDiagnostics(Diagnostic(ErrorCode.WRN_PatternIsAmbiguous, "t").WithArguments("T", "collection", "System.Collections.Generic.IEnumerable<int>.GetEnumerator()", "System.Collections.Generic.IEnumerable<string>.GetEnumerator()"), Diagnostic(ErrorCode.ERR_MultipleIEnumOfT, "t").WithArguments("T", "System.Collections.Generic.IEnumerable<T>")); } [Fact] public void CS1643ERR_AnonymousReturnExpected() { var text = @" delegate int MyDelegate(); class C { static void Main() { MyDelegate d = delegate { // CS1643 int i = 0; if (i == 0) return 1; }; } } "; CreateCompilation(text).VerifyDiagnostics( // (8,24): error CS1643: Not all code paths return a value in anonymous method of type 'MyDelegate' // MyDelegate d = delegate Diagnostic(ErrorCode.ERR_AnonymousReturnExpected, "delegate").WithArguments("anonymous method", "MyDelegate").WithLocation(8, 24) ); } [Fact] public void CS1643ERR_AnonymousReturnExpected_Foreach() { var text = @" using System; public class Test { public static void Main(string[] args) { string[] arr = null; Func<int> f = () => { foreach (var x in arr) return x; }; } } "; CreateCompilation(text). VerifyDiagnostics( // (8,61): error CS0029: Cannot implicitly convert type 'string' to 'int' // Func<int> f = () => { foreach (var x in arr) return x; }; Diagnostic(ErrorCode.ERR_NoImplicitConv, "x").WithArguments("string", "int").WithLocation(8, 61), // (8,61): 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 // Func<int> f = () => { foreach (var x in arr) return x; }; Diagnostic(ErrorCode.ERR_CantConvAnonMethReturns, "x").WithArguments("lambda expression").WithLocation(8, 61), // (8,26): error CS1643: Not all code paths return a value in lambda expression of type 'Func<int>' // Func<int> f = () => { foreach (var x in arr) return x; }; Diagnostic(ErrorCode.ERR_AnonymousReturnExpected, "=>").WithArguments("lambda expression", "System.Func<int>").WithLocation(8, 26) ); } [Fact] public void CS1648ERR_AssgReadonly2() { var text = @" public struct Inner { public int i; } class Outer { public readonly Inner inner = new Inner(); } class D { static void Main() { Outer outer = new Outer(); outer.inner.i = 1; // CS1648 } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_AssgReadonly2, Line = 17, Column = 7 } }); } [Fact] public void CS1649ERR_RefReadonly2() { var text = @" public struct Inner { public int i; } class Outer { public readonly Inner inner = new Inner(); } class D { static void f(ref int iref) { } static void Main() { Outer outer = new Outer(); f(ref outer.inner.i); // CS1649 } } "; CreateCompilation(text).VerifyDiagnostics( // (21,15): error CS1649: Members of readonly field 'Outer.inner' cannot be used as a ref or out value (except in a constructor) // f(ref outer.inner.i); // CS1649 Diagnostic(ErrorCode.ERR_RefReadonly2, "outer.inner.i").WithArguments("Outer.inner").WithLocation(21, 15) ); } [Fact] public void CS1650ERR_AssgReadonlyStatic2() { string text = @"public struct Inner { public int i; } class Outer { public static readonly Inner inner = new Inner(); } class D { static void Main() { Outer.inner.i = 1; // CS1650 } } "; CreateCompilation(text).VerifyDiagnostics( // (15,9): error CS1650: Fields of static readonly field 'Outer.inner' cannot be assigned to (except in a static constructor or a variable initializer) Diagnostic(ErrorCode.ERR_AssgReadonlyStatic2, "Outer.inner.i").WithArguments("Outer.inner")); } [Fact] public void CS1651ERR_RefReadonlyStatic2() { var text = @" public struct Inner { public int i; } class Outer { public static readonly Inner inner = new Inner(); } class D { static void f(ref int iref) { } static void Main() { f(ref Outer.inner.i); // CS1651 } } "; CreateCompilation(text).VerifyDiagnostics( // (20,15): error CS1651: Fields of static readonly field 'Outer.inner' cannot be passed ref or out (except in a static constructor) Diagnostic(ErrorCode.ERR_RefReadonlyStatic2, "Outer.inner.i").WithArguments("Outer.inner")); } [Fact] public void CS1654ERR_AssgReadonlyLocal2Cause() { var text = @" using System.Collections.Generic; namespace CS1654 { struct Book { public string Title; public string Author; public double Price; public Book(string t, string a, double p) { Title = t; Author = a; Price = p; } } class Program { List<Book> list; static void Main(string[] args) { Program prog = new Program(); prog.list = new List<Book>(); foreach (Book b in prog.list) { b.Price += 9.95; // CS1654 } } } }"; CreateCompilation(text).VerifyDiagnostics( // (29,17): error CS1654: Cannot modify members of 'b' because it is a 'foreach iteration variable' Diagnostic(ErrorCode.ERR_AssgReadonlyLocal2Cause, "b.Price").WithArguments("b", "foreach iteration variable")); } [Fact] public void CS1655ERR_RefReadonlyLocal2Cause() { var text = @" struct S { public int i; } class CMain { static void f(ref int iref) { } public static void Main() { S[] sa = new S[10]; foreach(S s in sa) { CMain.f(ref s.i); // CS1655 } } } "; CreateCompilation(text).VerifyDiagnostics( // (18,21): error CS1655: Cannot pass fields of 's' as a ref or out argument because it is a 'foreach iteration variable' // CMain.f(ref s.i); // CS1655 Diagnostic(ErrorCode.ERR_RefReadonlyLocal2Cause, "s.i").WithArguments("s", "foreach iteration variable") ); } [Fact] public void CS1656ERR_AssgReadonlyLocalCause01() { var text = @" using System; class C : IDisposable { public void Dispose() { } } class CMain { unsafe public static void Main() { using (C c = new C()) { c = new C(); // CS1656 } int[] ary = new int[] { 1, 2, 3, 4 }; fixed (int* p = ary) { p = null; // CS1656 } } } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (13,13): error CS1656: Cannot assign to 'c' because it is a 'using variable' Diagnostic(ErrorCode.ERR_AssgReadonlyLocalCause, "c").WithArguments("c", "using variable").WithLocation(15, 13), // (19,13): error CS1656: Cannot assign to 'p' because it is a 'fixed variable' Diagnostic(ErrorCode.ERR_AssgReadonlyLocalCause, "p").WithArguments("p", "fixed variable").WithLocation(21, 13)); } [Fact] public void CS1656ERR_AssgReadonlyLocalCause02() { var text = @"class C { static void M() { M = null; } }"; CreateCompilation(text).VerifyDiagnostics( // (5,9): error CS1656: Cannot assign to 'M' because it is a 'method group' Diagnostic(ErrorCode.ERR_AssgReadonlyLocalCause, "M").WithArguments("M", "method group").WithLocation(5, 9)); } [Fact] public void CS1656ERR_AssgReadonlyLocalCause_NestedForeach() { var text = @" public class Test { static public void Main(string[] args) { string S = ""ABC""; string T = ""XYZ""; foreach (char x in S) { foreach (char y in T) { x = 'M'; } } } } "; CreateCompilation(text). VerifyDiagnostics(Diagnostic(ErrorCode.ERR_AssgReadonlyLocalCause, "x").WithArguments("x", "foreach iteration variable")); } [Fact] public void CS1657ERR_RefReadonlyLocalCause() { var text = @" class C { static void F(ref string s) { } static void Main(string[] args) { foreach (var a in args) { F(ref a); //CS1657 } } } "; CreateCompilation(text).VerifyDiagnostics( // (12,19): error CS1657: Cannot use 'a' as a ref or out value because it is a 'foreach iteration variable' // F(ref a); //CS1657 Diagnostic(ErrorCode.ERR_RefReadonlyLocalCause, "a").WithArguments("a", "foreach iteration variable").WithLocation(12, 19) ); } [Fact] public void CS1660ERR_AnonMethToNonDel() { var text = @" delegate int MyDelegate(); class C { static void Main() { int i = delegate { return 1; }; // CS1660 } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_AnonMethToNonDel, Line = 6, Column = 14 } }); } [Fact] public void CS1661ERR_CantConvAnonMethParams() { var text = @" delegate void MyDelegate(int i); class C { public static void Main() { MyDelegate d = delegate(string s) { }; // CS1661 } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_CantConvAnonMethParams, Line = 8, Column = 24 }, new ErrorDescription { Code = (int)ErrorCode.ERR_BadParamType, Line = 8, Column = 40 } }); } [Fact] public void CS1662ERR_CantConvAnonMethReturns() { var text = @" delegate int MyDelegate(int i); class C { delegate double D(); public static void Main() { MyDelegate d = delegate(int i) { return 1.0; }; // CS1662 D dd = () => { return ""Who knows the real sword of Gryffindor?""; }; } }"; CreateCompilation(text).VerifyDiagnostics( // (9,49): error CS0266: Cannot implicitly convert type 'double' to 'int'. An explicit conversion exists (are you missing a cast?) // MyDelegate d = delegate(int i) { return 1.0; }; // CS1662 Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "1.0").WithArguments("double", "int").WithLocation(9, 49), // (9,49): error CS1662: Cannot convert anonymous method to intended delegate type because some of the return types in the block are not implicitly convertible to the delegate return type // MyDelegate d = delegate(int i) { return 1.0; }; // CS1662 Diagnostic(ErrorCode.ERR_CantConvAnonMethReturns, "1.0").WithArguments("anonymous method").WithLocation(9, 49), // (10,31): error CS0029: Cannot implicitly convert type 'string' to 'double' // D dd = () => { return "Who knows the real sword of Gryffindor?"; }; Diagnostic(ErrorCode.ERR_NoImplicitConv, @"""Who knows the real sword of Gryffindor?""").WithArguments("string", "double").WithLocation(10, 31), // (10,31): 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 // D dd = () => { return "Who knows the real sword of Gryffindor?"; }; Diagnostic(ErrorCode.ERR_CantConvAnonMethReturns, @"""Who knows the real sword of Gryffindor?""").WithArguments("lambda expression").WithLocation(10, 31) ); } [Fact] public void CS1666ERR_FixedBufferNotFixedErr() { var text = @" unsafe struct S { public fixed int buffer[1]; } unsafe class Test { public static void Main() { var inst = new Test(); System.Console.Write(inst.example1()); System.Console.Write(inst.field.buffer[0]); System.Console.Write(inst.example2()); System.Console.Write(inst.field.buffer[0]); } S field = new S(); private int example1() { return (field.buffer[0] = 7); // OK } private int example2() { fixed (int* p = field.buffer) { return (p[0] = 8); // OK } } } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseExe, parseOptions: TestOptions.Regular7_2).VerifyDiagnostics( // (13,30): error CS8320: Feature 'indexing movable fixed buffers' is not available in C# 7.2. Please use language version 7.3 or greater. // System.Console.Write(inst.field.buffer[0]); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_2, "inst.field.buffer").WithArguments("indexing movable fixed buffers", "7.3").WithLocation(13, 30), // (15,30): error CS8320: Feature 'indexing movable fixed buffers' is not available in C# 7.2. Please use language version 7.3 or greater. // System.Console.Write(inst.field.buffer[0]); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_2, "inst.field.buffer").WithArguments("indexing movable fixed buffers", "7.3").WithLocation(15, 30), // (22,17): error CS8320: Feature 'indexing movable fixed buffers' is not available in C# 7.2. Please use language version 7.3 or greater. // return (field.buffer[0] = 7); // OK Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_2, "field.buffer").WithArguments("indexing movable fixed buffers", "7.3").WithLocation(22, 17) ); } [Fact] public void CS1666ERR_FixedBufferNotUnsafeErr() { var text = @" unsafe struct S { public fixed int buffer[1]; } class Test { public static void Main() { var inst = new Test(); System.Console.Write(inst.example1()); System.Console.Write(inst.field.buffer[0]); } S field = new S(); private int example1() { return (field.buffer[0] = 7); // OK } } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseExe).VerifyDiagnostics( // (13,30): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // System.Console.Write(inst.field.buffer[0]); Diagnostic(ErrorCode.ERR_UnsafeNeeded, "inst.field.buffer").WithLocation(13, 30), // (20,17): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // return (field.buffer[0] = 7); // OK Diagnostic(ErrorCode.ERR_UnsafeNeeded, "field.buffer").WithLocation(20, 17) ); } [Fact] public void CS1666ERR_FixedBufferNotFixed() { var text = @" unsafe struct S { public fixed int buffer[1]; } unsafe class Test { public static void Main() { var inst = new Test(); System.Console.Write(inst.example1()); System.Console.Write(inst.field.buffer[0]); System.Console.Write(inst.example2()); System.Console.Write(inst.field.buffer[0]); } S field = new S(); private int example1() { return (field.buffer[0] = 7); // OK } private int example2() { fixed (int* p = field.buffer) { return (p[0] = 8); // OK } } } "; var c = CompileAndVerify(text, expectedOutput: "7788", verify: Verification.Fails, options: TestOptions.UnsafeReleaseExe); c.VerifyIL("Test.example1()", @" { // Code size 22 (0x16) .maxstack 3 .locals init (int V_0) IL_0000: ldarg.0 IL_0001: ldflda ""S Test.field"" IL_0006: ldflda ""int* S.buffer"" IL_000b: ldflda ""int S.<buffer>e__FixedBuffer.FixedElementField"" IL_0010: ldc.i4.7 IL_0011: dup IL_0012: stloc.0 IL_0013: stind.i4 IL_0014: ldloc.0 IL_0015: ret } "); c.VerifyIL("Test.example2()", @" { // Code size 25 (0x19) .maxstack 3 .locals init (pinned int& V_0, int V_1) IL_0000: ldarg.0 IL_0001: ldflda ""S Test.field"" IL_0006: ldflda ""int* S.buffer"" IL_000b: ldflda ""int S.<buffer>e__FixedBuffer.FixedElementField"" IL_0010: stloc.0 IL_0011: ldloc.0 IL_0012: conv.u IL_0013: ldc.i4.8 IL_0014: dup IL_0015: stloc.1 IL_0016: stind.i4 IL_0017: ldloc.1 IL_0018: ret } "); } [Fact] public void CS1669ERR_IllegalVarArgs01() { var source = @"class C { delegate void D(__arglist); // CS1669 static void Main() {} }"; CreateCompilation(source).VerifyDiagnostics( // (3,21): error CS1669: __arglist is not valid in this context // delegate void D(__arglist); // CS1669 Diagnostic(ErrorCode.ERR_IllegalVarArgs, "__arglist") ); } [Fact] public void CS1669ERR_IllegalVarArgs02() { var source = @"class C { object this[object index, __arglist] { get { return null; } } public static C operator +(C c1, __arglist) { return c1; } public static implicit operator int(__arglist) { return 0; } }"; CreateCompilation(source).VerifyDiagnostics( // (3,31): error CS1669: __arglist is not valid in this context // object this[object index, __arglist] Diagnostic(ErrorCode.ERR_IllegalVarArgs, "__arglist"), // (7,38): error CS1669: __arglist is not valid in this context // public static C operator +(C c1, __arglist) { return c1; } Diagnostic(ErrorCode.ERR_IllegalVarArgs, "__arglist"), // (8,41): error CS1669: __arglist is not valid in this context // public static implicit operator int(__arglist) { return 0; } Diagnostic(ErrorCode.ERR_IllegalVarArgs, "__arglist") ); } [WorkItem(863433, "DevDiv/Personal")] [Fact] public void CS1670ERR_IllegalParams() { // TODO: extra 1670 (not check for now) var test = @" delegate int MyDelegate(params int[] paramsList); class Test { public static int Main() { MyDelegate d = delegate(params int[] paramsList) // CS1670 { return paramsList[0]; }; return 1; } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(test, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_IllegalParams, Line = 7, Column = 33 } }); } [Fact] public void CS1673ERR_ThisStructNotInAnonMeth01() { var text = @" delegate int MyDelegate(); public struct S { int member; public int F(int i) { member = i; MyDelegate d = delegate() { i = this.member; // CS1673 return i; }; return d(); } } class CMain { public static void Main() { } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_ThisStructNotInAnonMeth, Line = 13, Column = 17 } }); } [Fact] public void CS1673ERR_ThisStructNotInAnonMeth02() { var text = @" delegate int MyDelegate(); public struct S { int member; public int F(int i) { member = i; MyDelegate d = delegate() { i = member; // CS1673 return i; }; return d(); } } class CMain { public static void Main() { } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_ThisStructNotInAnonMeth, Line = 13, Column = 17 } }); } [Fact] public void CS1674ERR_NoConvToIDisp() { var text = @" class C { public static void Main() { using (int a = 0) // CS1674 using (a); //CS1674 } } "; CreateCompilation(text).VerifyDiagnostics( // (7,22): warning CS0642: Possible mistaken empty statement Diagnostic(ErrorCode.WRN_PossibleMistakenNullStatement, ";"), // (6,16): error CS1674: 'int': type used in a using statement must be implicitly convertible to 'System.IDisposable'. Diagnostic(ErrorCode.ERR_NoConvToIDisp, "int a = 0").WithArguments("int"), // (7,20): error CS1674: 'int': type used in a using statement must be implicitly convertible to 'System.IDisposable'. Diagnostic(ErrorCode.ERR_NoConvToIDisp, "a").WithArguments("int")); } [Fact] public void CS1676ERR_BadParamRef() { var text = @" delegate void E(ref int i); class Errors { static void Main() { E e = delegate(out int i) { }; // CS1676 } } "; var compilation = CreateCompilation(text); compilation.VerifyDiagnostics( // (7,13): error CS1661: Cannot convert anonymous method to delegate type 'E' because the parameter types do not match the delegate parameter types // E e = delegate(out int i) { }; // CS1676 Diagnostic(ErrorCode.ERR_CantConvAnonMethParams, "delegate(out int i) { }").WithArguments("anonymous method", "E"), // (7,22): error CS1676: Parameter 1 must be declared with the 'ref' keyword // E e = delegate(out int i) { }; // CS1676 Diagnostic(ErrorCode.ERR_BadParamRef, "i").WithArguments("1", "ref"), // (7,13): error CS0177: The out parameter 'i' must be assigned to before control leaves the current method // E e = delegate(out int i) { }; // CS1676 Diagnostic(ErrorCode.ERR_ParamUnassigned, "delegate(out int i) { }").WithArguments("i") ); } [Fact] public void CS1677ERR_BadParamExtraRef() { var text = @" delegate void D(int i); class Errors { static void Main() { D d = delegate(out int i) { }; // CS1677 D d = delegate(ref int j) { }; // CS1677 } } "; var compilation = CreateCompilation(text); compilation.VerifyDiagnostics( // (7,15): error CS1661: Cannot convert anonymous method to delegate type 'D' because the parameter types do not match the delegate parameter types // D d = delegate(out int i) { }; // CS1677 Diagnostic(ErrorCode.ERR_CantConvAnonMethParams, "delegate(out int i) { }").WithArguments("anonymous method", "D"), // (7,24): error CS1677: Parameter 1 should not be declared with the 'out' keyword // D d = delegate(out int i) { }; // CS1677 Diagnostic(ErrorCode.ERR_BadParamExtraRef, "i").WithArguments("1", "out"), // (8,15): error CS1661: Cannot convert anonymous method to delegate type 'D' because the parameter types do not match the delegate parameter types // D d = delegate(ref int j) { }; // CS1677 Diagnostic(ErrorCode.ERR_CantConvAnonMethParams, "delegate(ref int j) { }").WithArguments("anonymous method", "D"), // (8,24): error CS1677: Parameter 1 should not be declared with the 'ref' keyword // D d = delegate(ref int j) { }; // CS1677 Diagnostic(ErrorCode.ERR_BadParamExtraRef, "j").WithArguments("1", "ref"), // (8,11): error CS0128: A local variable named 'd' is already defined in this scope // D d = delegate(ref int j) { }; // CS1677 Diagnostic(ErrorCode.ERR_LocalDuplicate, "d").WithArguments("d"), // (7,15): error CS0177: The out parameter 'i' must be assigned to before control leaves the current method // D d = delegate(out int i) { }; // CS1677 Diagnostic(ErrorCode.ERR_ParamUnassigned, "delegate(out int i) { }").WithArguments("i") ); } [Fact] public void CS1678ERR_BadParamType() { var text = @" delegate void D(int i); class Errors { static void Main() { D d = delegate(string s) { }; // CS1678 } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_CantConvAnonMethParams, Line = 7, Column = 15 }, new ErrorDescription { Code = (int)ErrorCode.ERR_BadParamType, Line = 7, Column = 31 } }); } [Fact] public void CS1681ERR_GlobalExternAlias() { var text = @" extern alias global; class myClass { static int Main() { //global::otherClass oc = new global::otherClass(); return 0; } } "; CreateCompilation(text).VerifyDiagnostics( // (2,14): error CS1681: You cannot redefine the global extern alias // extern alias global; Diagnostic(ErrorCode.ERR_GlobalExternAlias, "global"), // (2,14): error CS0430: The extern alias 'global' was not specified in a /reference option // extern alias global; Diagnostic(ErrorCode.ERR_BadExternAlias, "global").WithArguments("global"), // (2,1): info CS8020: Unused extern alias. // extern alias global; Diagnostic(ErrorCode.HDN_UnusedExternAlias, "extern alias global;") ); } [Fact] public void CS1686ERR_LocalCantBeFixedAndHoisted() { var text = @" class MyClass { public unsafe delegate int* MyDelegate(); public unsafe int* Test() { int j = 0; MyDelegate d = delegate { return &j; }; // CS1686 return &j; // CS1686 } } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (9,42): error CS1686: Local 'j' or its members cannot have their address taken and be used inside an anonymous method or lambda expression // MyDelegate d = delegate { return &j; }; // CS1686 Diagnostic(ErrorCode.ERR_LocalCantBeFixedAndHoisted, "&j").WithArguments("j")); } [Fact] public void CS1686ERR_LocalCantBeFixedAndHoisted02() { var text = @"using System; unsafe struct S { public fixed int buffer[1]; public int i; } unsafe class Test { private void example1() { S data = new S(); data.i = data.i + 1; Func<S> lambda = () => data; fixed (int* p = data.buffer) // fail due to receiver being a local { } int *q = data.buffer; // fail due to lambda capture } }"; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (16,25): error CS0213: You cannot use the fixed statement to take the address of an already fixed expression // fixed (int* p = data.buffer) // fail due to receiver being a local Diagnostic(ErrorCode.ERR_FixedNotNeeded, "data.buffer"), // (19,18): error CS1686: Local 'data' or its members cannot have their address taken and be used inside an anonymous method or lambda expression // int *q = data.buffer; // fail due to lambda capture Diagnostic(ErrorCode.ERR_LocalCantBeFixedAndHoisted, "data.buffer").WithArguments("data") ); } [WorkItem(580537, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/580537")] [Fact] public void CS1686ERR_LocalCantBeFixedAndHoisted03() { var text = @"unsafe public struct Test { private delegate int D(); public fixed int i[1]; public void example() { Test t = this; t.i[0] = 5; D d = delegate { var x = t; return 0; }; } }"; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (9,9): error CS1686: Local 't' or its members cannot have their address taken and be used inside an anonymous method or lambda expression // t.i[0] = 5; Diagnostic(ErrorCode.ERR_LocalCantBeFixedAndHoisted, "t.i").WithArguments("t") ); } [Fact] public void CS1688ERR_CantConvAnonMethNoParams() { var text = @" using System; delegate void OutParam(out int i); class ErrorCS1676 { static void Main() { OutParam o; o = delegate // CS1688 { Console.WriteLine(""); }; } } "; CreateCompilation(text).VerifyDiagnostics( // (11,31): error CS1010: Newline in constant // Console.WriteLine("); Diagnostic(ErrorCode.ERR_NewlineInConst, "").WithLocation(11, 31), // (11,34): error CS1026: ) expected // Console.WriteLine("); Diagnostic(ErrorCode.ERR_CloseParenExpected, "").WithLocation(11, 34), // (11,34): error CS1002: ; expected // Console.WriteLine("); Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(11, 34), // (9,13): error CS1688: Cannot convert anonymous method block without a parameter list to delegate type 'OutParam' because it has one or more out parameters // o = delegate // CS1688 Diagnostic(ErrorCode.ERR_CantConvAnonMethNoParams, @"delegate // CS1688 { Console.WriteLine(""); }").WithArguments("OutParam").WithLocation(9, 13) ); } [Fact] public void CS1708ERR_FixedNeedsLvalue() { var text = @" unsafe public struct S { public fixed char name[10]; } public unsafe class C { public S UnsafeMethod() { S myS = new S(); return myS; } static void Main() { C myC = new C(); myC.UnsafeMethod().name[3] = 'a'; // CS1708 C._s1.name[3] = 'a'; // CS1648 myC._s2.name[3] = 'a'; // CS1648 } static readonly S _s1; public readonly S _s2; }"; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (18,9): error CS1708: Fixed size buffers can only be accessed through locals or fields // myC.UnsafeMethod().name[3] = 'a'; // CS1708 Diagnostic(ErrorCode.ERR_FixedNeedsLvalue, "myC.UnsafeMethod().name").WithLocation(18, 9), // (19,9): error CS1650: Fields of static readonly field 'C._s1' cannot be assigned to (except in a static constructor or a variable initializer) // C._s1.name[3] = 'a'; // CS1648 Diagnostic(ErrorCode.ERR_AssgReadonlyStatic2, "C._s1.name[3]").WithArguments("C._s1").WithLocation(19, 9), // (20,9): error CS1648: Members of readonly field 'C._s2' cannot be modified (except in a constructor, an init-only member or a variable initializer) // myC._s2.name[3] = 'a'; // CS1648 Diagnostic(ErrorCode.ERR_AssgReadonly2, "myC._s2.name[3]").WithArguments("C._s2").WithLocation(20, 9) ); } [Fact, WorkItem(543995, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543995"), WorkItem(544258, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544258")] public void CS1728ERR_DelegateOnNullable() { var text = @" using System; class Test { static void Main() { int? x = null; Func<string> f1 = x.ToString; // no error Func<int> f2 = x.GetHashCode; // no error Func<object, bool> f3 = x.Equals; // no error Func<Type> f4 = x.GetType; // no error Func<int> x1 = x.GetValueOrDefault; // 1728 Func<int, int> x2 = x.GetValueOrDefault; // 1728 } } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (14,24): error CS1728: Cannot bind delegate to 'int?.GetValueOrDefault()' because it is a member of 'System.Nullable<T>' // Func<int> x1 = x.GetValueOrDefault; // 1728 Diagnostic(ErrorCode.ERR_DelegateOnNullable, "x.GetValueOrDefault").WithArguments("int?.GetValueOrDefault()"), // (15,29): error CS1728: Cannot bind delegate to 'int?.GetValueOrDefault(int)' because it is a member of 'System.Nullable<T>' // Func<int, int> x2 = x.GetValueOrDefault; // 1728 Diagnostic(ErrorCode.ERR_DelegateOnNullable, "x.GetValueOrDefault").WithArguments("int?.GetValueOrDefault(int)") ); } [Fact, WorkItem(999399, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/999399")] public void CS1729ERR_BadCtorArgCount() { var text = @" class Test { static int Main() { double d = new double(4.5); // was CS0143 (Dev10) Test test1 = new Test(2); // CS1729 Test test2 = new Test(); Parent exampleParent1 = new Parent(10); // CS1729 Parent exampleParent2 = new Parent(10, 1); if (test1 == test2 & exampleParent1 == exampleParent2) {} return 1; } } public class Parent { public Parent(int i, int j) { } } public class Child : Parent { } // CS1729 public class Child2 : Parent { public Child2(int k) : base(k, 0) { } }"; var compilation = CreateCompilation(text); DiagnosticDescription[] expected = { // (21,14): error CS7036: There is no argument given that corresponds to the required formal parameter 'i' of 'Parent.Parent(int, int)' // public class Child : Parent { } // CS1729 Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "Child").WithArguments("i", "Parent.Parent(int, int)").WithLocation(21, 14), // (6,24): error CS1729: 'double' does not contain a constructor that takes 1 arguments // double d = new double(4.5); // was CS0143 (Dev10) Diagnostic(ErrorCode.ERR_BadCtorArgCount, "double").WithArguments("double", "1").WithLocation(6, 24), // (7,26): error CS1729: 'Test' does not contain a constructor that takes 1 arguments // Test test1 = new Test(2); // CS1729 Diagnostic(ErrorCode.ERR_BadCtorArgCount, "Test").WithArguments("Test", "1").WithLocation(7, 26), // (9,37): error CS7036: There is no argument given that corresponds to the required formal parameter 'j' of 'Parent.Parent(int, int)' // Parent exampleParent1 = new Parent(10); // CS1729 Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "Parent").WithArguments("j", "Parent.Parent(int, int)").WithLocation(9, 37) }; compilation.VerifyDiagnostics(expected); compilation.GetDiagnosticsForSyntaxTree(CompilationStage.Compile, compilation.SyntaxTrees.Single(), filterSpanWithinTree: null, includeEarlierStages: true).Verify(expected); } [WorkItem(539631, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539631")] [Fact] public void CS1729ERR_BadCtorArgCount02() { var text = @" class MyClass { int intI = 1; MyClass() { intI = 2; } //this constructor initializer MyClass(int intJ) : this(3, 4) // CS1729 { intI = intI * intJ; } } class MyBase { public int intI = 1; protected MyBase() { intI = 2; } protected MyBase(int intJ) { intI = intJ; } } class MyDerived : MyBase { MyDerived() : base(3, 4) // CS1729 { intI = intI * 2; } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_BadCtorArgCount, Line = 11, Column = 25 }, new ErrorDescription { Code = (int)ErrorCode.ERR_BadCtorArgCount, Line = 32, Column = 19 }); } [Fact] public void CS1737ERR_DefaultValueBeforeRequiredValue() { var text = @" class C { public void Goo(string s = null, int x) { } }"; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_DefaultValueBeforeRequiredValue, Line = 4, Column = 43 } } //sic: error on close paren ); } [WorkItem(539007, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539007")] [Fact] public void DevDiv4792_OptionalBeforeParams() { var text = @" class C { public void Goo(string s = null, params int[] ints) { } } "; //no errors var comp = CreateCompilation(text); Assert.False(comp.GetDiagnostics().Any()); } [WorkItem(527351, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527351")] [Fact] public void CS1738ERR_NamedArgumentSpecificationBeforeFixedArgument() { var text = @" public class C { public static int Main() { Test(age: 5,""""); return 0; } public static void Test(int age, string Name) { } }"; var comp = CreateCompilation(text, parseOptions: TestOptions.Regular6); comp.VerifyDiagnostics( // (6,21): error CS1738: Named argument specifications must appear after all fixed arguments have been specified. Please use language version 7.2 or greater to allow non-trailing named arguments. // Test(age: 5,""); Diagnostic(ErrorCode.ERR_NamedArgumentSpecificationBeforeFixedArgument, @"""""").WithArguments("7.2").WithLocation(6, 21) ); } [Fact] public void CS1739ERR_BadNamedArgument() { var text = @" public class C { public static int Main() { Test(5,Nam:null); return 0; } public static void Test(int age , string Name) { } }"; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = 1739, Line = 6, Column = 20 } }); } [Fact, WorkItem(866112, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/866112")] public void CS1739ERR_BadNamedArgument_1() { var text = @" public class C { public static void Main() { Test(1, 2, Name:3); } public static void Test(params int [] array) { } }"; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = 1739, Line = 6, Column = 20 } }); } [Fact] public void CS1740ERR_DuplicateNamedArgument() { var text = @" public class C { public static int Main() { Test(age: 5, Name: ""5"", Name: """"); return 0; } public static void Test(int age, string Name) { } }"; var compilation = CSharpTestBase.CreateCompilation(text); compilation.VerifyDiagnostics( // (6,33): error CS1740: Named argument 'Name' cannot be specified multiple times // Test(age: 5, Name: "5", Name: ""); Diagnostic(ErrorCode.ERR_DuplicateNamedArgument, "Name").WithArguments("Name").WithLocation(6, 33)); } [Fact] public void CS1742ERR_NamedArgumentForArray() { var text = @" public class B { static int Main() { int[] arr = { }; int s = arr[arr: 1]; s = s + 1; return 1; } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = 1742, Line = 7, Column = 17 } }); } [Fact] public void CS1744ERR_NamedArgumentUsedInPositional() { var text = @" public class C { public static int Main() { Test(5, age: 3); return 0; } public static void Test(int age , string Name) { } }"; // CS1744: Named argument 'q' specifies a parameter for which a positional argument has already been given. DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = 1744, Line = 6, Column = 21 } }); } [Fact] public void CS1744ERR_NamedArgumentUsedInPositional2() { // Unfortunately we allow "void M(params int[] x)" to be called in the expanded // form as "M(x : 123);". However, we still do not allow "M(123, x:456);". var text = @" public class C { public static void Main() { Test(5, x: 3); } public static void Test(params int[] x) { } }"; // CS1744: Named argument 'x' specifies a parameter for which a positional argument has already been given. DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = 1744, Line = 6, Column = 17 } }); } [Fact] public void CS1744ERR_NamedArgumentUsedInPositional3() { var text = @" public class C { public static void Main() { Test(5, x : 6); } public static void Test(int x, int y = 10, params int[] z) { } }"; // CS1744: Named argument 'x' specifies a parameter for which a positional argument has already been given. DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = 1744, Line = 6, Column = 17 } }); } [Fact] public void CS1744ERR_NamedArgumentUsedInPositional4() { var text = @" public class C { public static void Main() { Test(5, 6, 7, 8, 9, 10, z : 6); } public static void Test(int x, int y = 10, params int[] z) { } }"; // CS1744: Named argument 'z' specifies a parameter for which a positional argument has already been given. DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = 1744, Line = 6, Column = 33 } }); } [Fact] public void CS1746ERR_BadNamedArgumentForDelegateInvoke() { var text = @" public class C { delegate int MyDg(int age); public static int Main() { MyDg dg = new MyDg(Test); int S = dg(Ne: 3); return 0; } public static int Test(int age) { return 1; } }"; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = 1746, Line = 8, Column = 24 } }); } // [Fact()] // public void CS1752ERR_FixedNeedsLvalue() // { // var text = @" //"; // DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, // new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_FixedNeedsLvalue, Line = 20, Column = 9 } } // ); // } // CS1912 --> ObjectAndCollectionInitializerTests.cs // CS1913 --> ObjectAndCollectionInitializerTests.cs // CS1914 --> ObjectAndCollectionInitializerTests.cs // CS1917 --> ObjectAndCollectionInitializerTests.cs // CS1918 --> ObjectAndCollectionInitializerTests.cs // CS1920 --> ObjectAndCollectionInitializerTests.cs // CS1921 --> ObjectAndCollectionInitializerTests.cs // CS1922 --> ObjectAndCollectionInitializerTests.cs [Fact] public void CS1919ERR_UnsafeTypeInObjectCreation() { var text = @" unsafe public class C { public static int Main() { var col1 = new int*(); // CS1919 var col2 = new char*(); // CS1919 return 1; } } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (6,20): error CS1919: Unsafe type 'int*' cannot be used in object creation Diagnostic(ErrorCode.ERR_UnsafeTypeInObjectCreation, "new int*()").WithArguments("int*"), // (7,20): error CS1919: Unsafe type 'char*' cannot be used in object creation Diagnostic(ErrorCode.ERR_UnsafeTypeInObjectCreation, "new char*()").WithArguments("char*")); } [Fact] public void CS1928ERR_BadExtensionArgTypes() { var text = @"class C { static void M(float f) { f.F(); } } static class S { internal static void F(this double d) { } }"; var compilation = CreateCompilationWithMscorlib40(text, references: new[] { Net40.SystemCore }); // Previously ERR_BadExtensionArgTypes. compilation.VerifyDiagnostics( // (5,9): error CS1929: 'float' does not contain a definition for 'F' and the best extension method overload 'S.F(double)' requires a receiver of type 'double' // f.F(); Diagnostic(ErrorCode.ERR_BadInstanceArgType, "f").WithArguments("float", "F", "S.F(double)", "double").WithLocation(5, 9)); } [Fact] public void CS1929ERR_BadInstanceArgType() { var source = @"class A { } class B : A { static void M(A a) { a.E(); } } static class S { internal static void E(this B b) { } }"; var compilation = CreateCompilationWithMscorlib40(source, references: new[] { Net40.SystemCore }); compilation.VerifyDiagnostics( // (6,9): error CS1929: 'A' does not contain a definition for 'E' and the best extension method overload 'S.E(B)' requires a receiver of type 'B' // a.E(); Diagnostic(ErrorCode.ERR_BadInstanceArgType, "a").WithArguments("A", "E", "S.E(B)", "B").WithLocation(6, 9) ); } [Fact] public void CS1930ERR_QueryDuplicateRangeVariable() { CreateCompilationWithMscorlib40AndSystemCore(@" using System.Linq; class Program { static void Main() { int[] nums = { 0, 1, 2, 3, 4, 5 }; var query = from num in nums let num = 3 // CS1930 select num; } } ").VerifyDiagnostics( // (10,25): error CS1930: The range variable 'num' has already been declared Diagnostic(ErrorCode.ERR_QueryDuplicateRangeVariable, "num").WithArguments("num")); } [Fact] public void CS1931ERR_QueryRangeVariableOverrides01() { CreateCompilationWithMscorlib40AndSystemCore(@" using System.Linq; class Test { static void Main() { int x = 1; var y = from x in Enumerable.Range(1, 100) // CS1931 select x + 1; } } ").VerifyDiagnostics( // (9,22): error CS1931: The range variable 'x' conflicts with a previous declaration of 'x' // var y = from x in Enumerable.Range(1, 100) // CS1931 Diagnostic(ErrorCode.ERR_QueryRangeVariableOverrides, "x").WithArguments("x"), // (8,13): warning CS0219: The variable 'x' is assigned but its value is never used // int x = 1; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x").WithArguments("x") ); } [Fact] public void CS1932ERR_QueryRangeVariableAssignedBadValue() { CreateCompilationWithMscorlib40AndSystemCore(@" using System.Linq; class Test { static void Main() { var x = from i in Enumerable.Range(1, 100) let k = null select i; } } ").VerifyDiagnostics( // (8,21): error CS1932: Cannot assign <null> to a range variable // let k = null Diagnostic(ErrorCode.ERR_QueryRangeVariableAssignedBadValue, "k = null").WithArguments("<null>") ); } [Fact] public void CS1932ERR_QueryRangeVariableAssignedBadValue02() { CreateCompilationWithMscorlib40AndSystemCore(@" using System.Linq; class Test { static void Main() { var x = from i in Enumerable.Range(1, 100) let k = ()=>3 select i; } } ").VerifyDiagnostics( // (8,21): error CS1932: Cannot assign lambda expression to a range variable // let k = ()=>3 Diagnostic(ErrorCode.ERR_QueryRangeVariableAssignedBadValue, "k = ()=>3").WithArguments("lambda expression") ); } [Fact] public void CS1932ERR_QueryRangeVariableAssignedBadValue03() { CreateCompilationWithMscorlib40AndSystemCore(@" using System.Linq; class Test { static void Main() { var x = from i in Enumerable.Range(1, 100) let k = Main select i; } } ").VerifyDiagnostics( // (8,21): error CS1932: Cannot assign method group to a range variable // let k = Main Diagnostic(ErrorCode.ERR_QueryRangeVariableAssignedBadValue, "k = Main").WithArguments("method group") ); } [Fact] public void CS1932ERR_QueryRangeVariableAssignedBadValue04() { CreateCompilationWithMscorlib40AndSystemCore(@" using System.Linq; class Test { static void Main() { var x = from i in Enumerable.Range(1, 100) let k = M() select i; } static void M() {} } ").VerifyDiagnostics( // (8,21): error CS1932: Cannot assign void to a range variable // let k = M() Diagnostic(ErrorCode.ERR_QueryRangeVariableAssignedBadValue, "k = M()").WithArguments("void") ); } [WorkItem(528756, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528756")] [Fact()] public void CS1933ERR_QueryNotAllowed() { CreateCompilationWithMscorlib40AndSystemCore(@" using System.Linq; using System.Collections; class P { const IEnumerable e = from x in new int[] { 1, 2, 3 } select x; // CS1933 static int Main() { return 1; } } ").VerifyDiagnostics( // EDMAURER now giving the more generic message CS0133 // (7,27): error CS1933: Expression cannot contain query expressions // from //Diagnostic(ErrorCode.ERR_QueryNotAllowed, "from").WithArguments()); // (7,27): error CS0133: The expression being assigned to 'P.e' must be constant // const IEnumerable e = from x in new int[] { 1, 2, 3 } select x; // CS1933 Diagnostic(ErrorCode.ERR_NotConstantExpression, "from x in new int[] { 1, 2, 3 } select x").WithArguments("P.e") ); } [Fact] public void CS1934ERR_QueryNoProviderCastable() { CreateCompilationWithMscorlib40AndSystemCore(@" using System.Linq; using System.Collections; static class Test { public static void Main() { var list = new ArrayList(); var q = from x in list // CS1934 select x + 1; } } ").VerifyDiagnostics( // (9,27): error CS1934: Could not find an implementation of the query pattern for source type 'System.Collections.ArrayList'. 'Select' not found. Consider explicitly specifying the type of the range variable 'x'. // list Diagnostic(ErrorCode.ERR_QueryNoProviderCastable, "list").WithArguments("System.Collections.ArrayList", "Select", "x")); } [Fact] public void CS1935ERR_QueryNoProviderStandard() { CreateCompilationWithMscorlib40AndSystemCore(@" using System.Collections.Generic; class Test { static int Main() { int[] nums = { 0, 1, 2, 3, 4, 5 }; IEnumerable<int> e = from n in nums where n > 3 select n; return 0; } } ").VerifyDiagnostics( // (8,40): 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'? // nums Diagnostic(ErrorCode.ERR_QueryNoProviderStandard, "nums").WithArguments("int[]", "Where")); } [Fact] public void CS1936ERR_QueryNoProvider() { CreateCompilationWithMscorlib40AndSystemCore(@" using System.Collections; using System.Linq; class Test { static int Main() { object obj = null; IEnumerable e = from x in obj // CS1936 select x; return 0; } } ").VerifyDiagnostics( // (10,35): error CS1936: Could not find an implementation of the query pattern for source type 'object'. 'Select' not found. // obj Diagnostic(ErrorCode.ERR_QueryNoProvider, "obj").WithArguments("object", "Select")); } [Fact] public void CS1936ERR_QueryNoProvider01() { var program = @" class X { internal X Cast<T>() { return this; } } class Program { static void Main() { var xx = new X(); var q3 = from int x in xx select x; } }"; var comp = CreateCompilation(program); comp.VerifyDiagnostics( // (11,32): error CS1936: Could not find an implementation of the query pattern for source type 'X'. 'Select' not found. // var q3 = from int x in xx select x; Diagnostic(ErrorCode.ERR_QueryNoProvider, "xx").WithArguments("X", "Select") ); } [Fact] public void CS1937ERR_QueryOuterKey() { CreateCompilationWithMscorlib40AndSystemCore(@" using System.Linq; class Test { static void Main() { int[] sourceA = { 1, 2, 3, 4, 5 }; int[] sourceB = { 3, 4, 5, 6, 7 }; var query = from a in sourceA join b in sourceB on b equals 5 // CS1937 select a + b; } } ").VerifyDiagnostics( // (11,42): error CS1937: The name 'b' is not in scope on the left side of 'equals'. Consider swapping the expressions on either side of 'equals'. // join b in sourceB on b equals 5 // CS1937 Diagnostic(ErrorCode.ERR_QueryOuterKey, "b").WithArguments("b") ); } [Fact] public void CS1938ERR_QueryInnerKey() { CreateCompilationWithMscorlib40AndSystemCore(@" using System.Linq; class Test { static void Main() { int[] sourceA = { 1, 2, 3, 4, 5 }; int[] sourceB = { 3, 4, 5, 6, 7 }; var query = from a in sourceA join b in sourceB on 5 equals a // CS1938 select a + b; } } ").VerifyDiagnostics( // (11,51): error CS1938: The name 'a' is not in scope on the right side of 'equals'. Consider swapping the expressions on either side of 'equals'. // join b in sourceB on 5 equals a // CS1938 Diagnostic(ErrorCode.ERR_QueryInnerKey, "a").WithArguments("a") ); } [Fact] public void CS1939ERR_QueryOutRefRangeVariable() { var text = @" using System.Linq; class Test { public static int F(ref int i) { return i; } public static void Main() { var list = new int[] { 0, 1, 2, 3, 4, 5 }; var q = from x in list let k = x select Test.F(ref x); // CS1939 } } "; CreateCompilation(text).VerifyDiagnostics( // (13,35): error CS1939: Cannot pass the range variable 'x' as an out or ref parameter // select Test.F(ref x); // CS1939 Diagnostic(ErrorCode.ERR_QueryOutRefRangeVariable, "x").WithArguments("x")); } [Fact] public void CS1940ERR_QueryMultipleProviders() { var text = @"using System; class Test { public delegate int Dele(int x); int num = 0; public int Select(Func<int, int> d) { return d(this.num); } public int Select(Dele d) { return d(this.num) + 1; } public static void Main() { var q = from x in new Test() select x; // CS1940 } }"; CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics( // (18,17): error CS1940: Multiple implementations of the query pattern were found for source type 'Test'. Ambiguous call to 'Select'. // select Diagnostic(ErrorCode.ERR_QueryMultipleProviders, "select x").WithArguments("Test", "Select") ); } [Fact] public void CS1941ERR_QueryTypeInferenceFailedMulti() { CreateCompilationWithMscorlib40AndSystemCore(@" using System.Collections; using System.Linq; class Test { static int Main() { var nums = new int[] { 1, 2, 3, 4, 5, 6 }; var words = new string[] { ""lake"", ""mountain"", ""sky"" }; IEnumerable e = from n in nums join w in words on n equals w // CS1941 select w; return 0; } } ").VerifyDiagnostics( // (11,25): error CS1941: The type of one of the expressions in the join clause is incorrect. Type inference failed in the call to 'Join'. // join Diagnostic(ErrorCode.ERR_QueryTypeInferenceFailedMulti, "join").WithArguments("join", "Join")); } [Fact] public void CS1942ERR_QueryTypeInferenceFailed() { var text = @" using System; class Q { public Q Select<T,U>(Func<int, int> func) { return this; } } class Program { static void Main(string[] args) { var x = from i in new Q() select i; //CS1942 } } "; var comp = CreateCompilationWithMscorlib40AndSystemCore(text); comp.VerifyDiagnostics( // (12,17): error CS1942: The type of the expression in the select clause is incorrect. Type inference failed in the call to 'Select'. // select i; //CS1942 Diagnostic(ErrorCode.ERR_QueryTypeInferenceFailed, "select").WithArguments("select", "Select") ); } [Fact] public void CS1943ERR_QueryTypeInferenceFailedSelectMany() { CreateCompilationWithMscorlib40AndSystemCore(@" using System.Linq; class Test { class TestClass { } static void Main() { int[] nums = { 0, 1, 2, 3, 4, 5 }; TestClass tc = new TestClass(); var x = from n in nums from s in tc // CS1943 select n + s; } } ").VerifyDiagnostics( // (13,27): error CS1943: An expression of type 'Test.TestClass' is not allowed in a subsequent from clause in a query expression with source type 'int[]'. Type inference failed in the call to 'SelectMany'. // tc Diagnostic(ErrorCode.ERR_QueryTypeInferenceFailedSelectMany, "tc").WithArguments("Test.TestClass", "int[]", "SelectMany")); } [Fact] public void CS1943ERR_QueryTypeInferenceFailedSelectMany02() { CreateCompilationWithMscorlib40AndSystemCore(@" using System; class Test { class F1 { public F1 SelectMany<T, U>(Func<int, F1> func1, Func<int, int> func2) { return this; } } static void Main() { F1 f1 = new F1(); var x = from f in f1 from g in 3 select f + g; } } ").VerifyDiagnostics( // (14,23): error CS1943: An expression of type 'int' is not allowed in a subsequent from clause in a query expression with source type 'Test.F1'. Type inference failed in the call to 'SelectMany'. // from g in 3 Diagnostic(ErrorCode.ERR_QueryTypeInferenceFailedSelectMany, "3").WithArguments("int", "Test.F1", "SelectMany").WithLocation(14, 23) ); } [Fact, WorkItem(546510, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546510")] public void CS1944ERR_ExpressionTreeContainsPointerOp() { var text = @" using System; using System.Linq.Expressions; unsafe class Test { public delegate int* D(int i); static void Main() { Expression<D> tree = x => &x; // CS1944 Expression<Func<int, int*[]>> testExpr = x => new int*[] { &x }; } } "; //Assert.Equal("", text); CreateCompilationWithMscorlib40AndSystemCore(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (10,35): error CS1944: An expression tree may not contain an unsafe pointer operation // Expression<D> tree = x => &x; // CS1944 Diagnostic(ErrorCode.ERR_ExpressionTreeContainsPointerOp, "&x"), // (11,68): error CS1944: An expression tree may not contain an unsafe pointer operation // Expression<Func<int, int*[]>> testExpr = x => new int*[] { &x }; Diagnostic(ErrorCode.ERR_ExpressionTreeContainsPointerOp, "&x") ); } [Fact] public void CS1945ERR_ExpressionTreeContainsAnonymousMethod() { var text = @" using System; using System.Linq.Expressions; public delegate void D(); class Test { static void Main() { Expression<Func<int, Func<int, bool>>> tree = (x => delegate(int i) { return true; }); // CS1945 } }"; CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics( // (10,61): error CS1945: An expression tree may not contain an anonymous method expression // Expression<Func<int, Func<int, bool>>> tree = (x => delegate(int i) { return true; }); // CS1945 Diagnostic(ErrorCode.ERR_ExpressionTreeContainsAnonymousMethod, "delegate(int i) { return true; }") ); } [Fact] public void CS1946ERR_AnonymousMethodToExpressionTree() { var text = @" using System.Linq.Expressions; public delegate void D(); class Test { static void Main() { Expression<D> tree = delegate() { }; //CS1946 } } "; CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics( // (10,30): error CS1946: An anonymous method expression cannot be converted to an expression tree // Expression<D> tree = delegate() { }; //CS1946 Diagnostic(ErrorCode.ERR_AnonymousMethodToExpressionTree, "delegate() { }") ); } [Fact] public void CS1947ERR_QueryRangeVariableReadOnly() { var program = @" using System.Linq; class Test { static void Main() { int[] array = new int[] { 1, 2, 3, 4, 5 }; var x = from i in array let k = i select i = 5; // CS1947 x.ToList(); } } "; CreateCompilation(program).VerifyDiagnostics( Diagnostic(ErrorCode.ERR_QueryRangeVariableReadOnly, "i").WithArguments("i")); } [Fact] public void CS1948ERR_QueryRangeVariableSameAsTypeParam() { CreateCompilationWithMscorlib40AndSystemCore(@" using System.Linq; class Test { public void TestMethod<T>(T t) { var x = from T in Enumerable.Range(1, 100) // CS1948 select T; } public static void Main() { } } ").VerifyDiagnostics( // (8,17): error CS1948: The range variable 'T' cannot have the same name as a method type parameter // T Diagnostic(ErrorCode.ERR_QueryRangeVariableSameAsTypeParam, "T").WithArguments("T")); } [Fact] public void CS1949ERR_TypeVarNotFoundRangeVariable() { var text = @"using System.Linq; class Test { static void Main() { var x = from var i in Enumerable.Range(1, 100) // CS1949 select i; } }"; CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics( // (7,22): error CS1949: The contextual keyword 'var' cannot be used in a range variable declaration // var x = from var i in Enumerable.Range(1, 100) // CS1949 Diagnostic(ErrorCode.ERR_TypeVarNotFoundRangeVariable, "var") ); } // CS1950 --> ObjectAndCollectionInitializerTests.cs [Fact] public void CS1951ERR_ByRefParameterInExpressionTree() { var text = @" public delegate int TestDelegate(ref int i); class Test { static void Main() { System.Linq.Expressions.Expression<TestDelegate> tree1 = (ref int x) => x; // CS1951 } } "; CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics( // (7,75): error CS1951: An expression tree lambda may not contain a ref, in or out parameter // System.Linq.Expressions.Expression<TestDelegate> tree1 = (ref int x) => x; // CS1951 Diagnostic(ErrorCode.ERR_ByRefParameterInExpressionTree, "x").WithLocation(7, 75) ); } [Fact] public void CS1951ERR_InParameterInExpressionTree() { var text = @" public delegate int TestDelegate(in int i); class Test { static void Main() { System.Linq.Expressions.Expression<TestDelegate> tree1 = (in int x) => x; // CS1951 } } "; CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics( // (7,74): error CS1951: An expression tree lambda may not contain a ref, in or out parameter // System.Linq.Expressions.Expression<TestDelegate> tree1 = (in int x) => x; // CS1951 Diagnostic(ErrorCode.ERR_ByRefParameterInExpressionTree, "x").WithLocation(7, 74) ); } [Fact] public void CS1952ERR_VarArgsInExpressionTree() { var text = @" using System; using System.Linq.Expressions; class Test { public static int M(__arglist) { return 1; } static int Main() { Expression<Func<int, int>> f = x => Test.M(__arglist(x)); // CS1952 return 1; } }"; CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics( // (14,52): error CS1952: An expression tree lambda may not contain a method with variable arguments // Expression<Func<int, int>> f = x => Test.M(__arglist(x)); // CS1952 Diagnostic(ErrorCode.ERR_VarArgsInExpressionTree, "__arglist(x)") ); } [WorkItem(864605, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/864605")] [Fact] public void CS1953ERR_MemGroupInExpressionTree() { var text = @" using System; using System.Linq.Expressions; class CS1953 { public static void Main() { double num = 10; Expression<Func<bool>> testExpr = () => num.GetType is int; // CS0837 } }"; // Used to be CS1953, but now a method group in an is expression is illegal anyway. CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics( // (10,21): error CS0837: The first operand of an 'is' or 'as' operator may not be a lambda expression, anonymous method, or method group. // () => num.GetType is int; // CS1953 Diagnostic(ErrorCode.ERR_LambdaInIsAs, "num.GetType is int").WithLocation(10, 21)); } // CS1954 --> ObjectAndCollectionInitializerTests.cs [Fact] public void CS1955ERR_NonInvocableMemberCalled() { var text = @" namespace CompilerError1955 { class ClassA { public int x = 100; public int X { get { return x; } set { x = value; } } } class Test { static void Main() { ClassA a = new ClassA(); System.Console.WriteLine(a.x()); // CS1955 System.Console.WriteLine(a.X()); // CS1955 } } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_NonInvocableMemberCalled, Line = 19, Column = 40 }, new ErrorDescription { Code = (int)ErrorCode.ERR_NonInvocableMemberCalled, Line = 20, Column = 40 }}); } // CS1958 --> ObjectAndCollectionInitializerTests.cs [Fact] public void CS1959ERR_InvalidConstantDeclarationType() { var text = @" class Program { static void Test<T>() where T : class { const T x = null; // CS1959 } } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (6,25): error CS1959: 'x' is of type 'T'. The type specified in a constant declaration must be sbyte, byte, short, ushort, int, uint, long, ulong, char, float, double, decimal, bool, string, an enum-type, or a reference-type. // const T x = null; // CS1959 Diagnostic(ErrorCode.ERR_InvalidConstantDeclarationType, "null").WithArguments("x", "T") ); } /// <summary> /// Test the different contexts in which CS1961 can be seen. /// </summary> [Fact] public void CS1961ERR_UnexpectedVariance_Contexts() { var text = @" interface IContexts<in TIn, out TOut, TInv> { #region In TIn Property1In { set; } TIn Property2In { get; } //CS1961 on ""TIn"" TIn Property3In { get; set; } //CS1961 on ""TIn"" int this[TIn arg, char filler, char indexer1In] { get; } TIn this[int arg, char[] filler, char indexer2In] { get; } //CS1961 on ""TIn"" int this[TIn arg, bool filler, char indexer3In] { set; } TIn this[int arg, bool[] filler, char indexer4In] { set; } int this[TIn arg, long filler, char indexer5In] { get; set; } TIn this[int arg, long[] filler, char indexer6In] { get; set; } //CS1961 on ""TIn"" int Method1In(TIn p); TIn Method2In(); //CS1961 on ""TIn"" int Method3In(out TIn p); //CS1961 on ""TIn"" int Method4In(ref TIn p); //CS1961 on ""TIn"" event DOut<TIn> Event1In; #endregion In #region Out TOut Property1Out { set; } //CS1961 on ""TOut"" TOut Property2Out { get; } TOut Property3Out { get; set; } //CS1961 on ""TOut"" int this[TOut arg, char filler, bool indexer1Out] { get; } //CS1961 on ""TOut"" TOut this[int arg, char[] filler, bool indexer2Out] { get; } int this[TOut arg, bool filler, bool indexer3Out] { set; } //CS1961 on ""TOut"" TOut this[int arg, bool[] filler, bool indexer4Out] { set; } //CS1961 on ""TOut"" int this[TOut arg, long filler, bool indexer5Out] { get; set; } //CS1961 on ""TOut"" TOut this[int arg, long[] filler, bool indexer6Out] { get; set; } //CS1961 on ""TOut"" long Method1Out(TOut p); //CS1961 on ""TOut"" TOut Method2Out(); long Method3Out(out TOut p); //CS1961 on ""TOut"" (sic: out params have to be input-safe) long Method4Out(ref TOut p); //CS1961 on ""TOut"" event DOut<TOut> Event1Out; //CS1961 on ""TOut"" #endregion Out #region Inv TInv Property1Inv { set; } TInv Property2Inv { get; } TInv Property3Inv { get; set; } int this[TInv arg, char filler, long indexer1Inv] { get; } TInv this[int arg, char[] filler, long indexer2Inv] { get; } int this[TInv arg, bool filler, long indexer3Inv] { set; } TInv this[int arg, bool[] filler, long indexer4Inv] { set; } int this[TInv arg, long filler, long indexer5Inv] { get; set; } TInv this[int arg, long[] filler, long indexer6Inv] { get; set; } long Method1Inv(TInv p); TInv Method2Inv(); long Method3Inv(out TInv p); long Method4Inv(ref TInv p); event DOut<TInv> Event1Inv; #endregion Inv } delegate void DOut<out T>(); //for event types - should preserve the variance of the type arg "; CreateCompilation(text).VerifyDiagnostics( // (6,5): error CS1961: Invalid variance: The type parameter 'TIn' must be covariantly valid on 'IContexts<TIn, TOut, TInv>.Property2In'. 'TIn' is contravariant. // TIn Property2In { get; } //CS1961 on "TIn" Diagnostic(ErrorCode.ERR_UnexpectedVariance, "TIn").WithArguments("IContexts<TIn, TOut, TInv>.Property2In", "TIn", "contravariant", "covariantly").WithLocation(6, 5), // (7,5): error CS1961: Invalid variance: The type parameter 'TIn' must be invariantly valid on 'IContexts<TIn, TOut, TInv>.Property3In'. 'TIn' is contravariant. // TIn Property3In { get; set; } //CS1961 on "TIn" Diagnostic(ErrorCode.ERR_UnexpectedVariance, "TIn").WithArguments("IContexts<TIn, TOut, TInv>.Property3In", "TIn", "contravariant", "invariantly").WithLocation(7, 5), // (10,5): error CS1961: Invalid variance: The type parameter 'TIn' must be covariantly valid on 'IContexts<TIn, TOut, TInv>.this[int, char[], char]'. 'TIn' is contravariant. // TIn this[int arg, char[] filler, char indexer2In] { get; } //CS1961 on "TIn" Diagnostic(ErrorCode.ERR_UnexpectedVariance, "TIn").WithArguments("IContexts<TIn, TOut, TInv>.this[int, char[], char]", "TIn", "contravariant", "covariantly").WithLocation(10, 5), // (14,5): error CS1961: Invalid variance: The type parameter 'TIn' must be invariantly valid on 'IContexts<TIn, TOut, TInv>.this[int, long[], char]'. 'TIn' is contravariant. // TIn this[int arg, long[] filler, char indexer6In] { get; set; } //CS1961 on "TIn" Diagnostic(ErrorCode.ERR_UnexpectedVariance, "TIn").WithArguments("IContexts<TIn, TOut, TInv>.this[int, long[], char]", "TIn", "contravariant", "invariantly").WithLocation(14, 5), // (17,5): error CS1961: Invalid variance: The type parameter 'TIn' must be covariantly valid on 'IContexts<TIn, TOut, TInv>.Method2In()'. 'TIn' is contravariant. // TIn Method2In(); //CS1961 on "TIn" Diagnostic(ErrorCode.ERR_UnexpectedVariance, "TIn").WithArguments("IContexts<TIn, TOut, TInv>.Method2In()", "TIn", "contravariant", "covariantly").WithLocation(17, 5), // (18,23): error CS1961: Invalid variance: The type parameter 'TIn' must be invariantly valid on 'IContexts<TIn, TOut, TInv>.Method3In(out TIn)'. 'TIn' is contravariant. // int Method3In(out TIn p); //CS1961 on "TIn" Diagnostic(ErrorCode.ERR_UnexpectedVariance, "TIn").WithArguments("IContexts<TIn, TOut, TInv>.Method3In(out TIn)", "TIn", "contravariant", "invariantly").WithLocation(18, 23), // (19,23): error CS1961: Invalid variance: The type parameter 'TIn' must be invariantly valid on 'IContexts<TIn, TOut, TInv>.Method4In(ref TIn)'. 'TIn' is contravariant. // int Method4In(ref TIn p); //CS1961 on "TIn" Diagnostic(ErrorCode.ERR_UnexpectedVariance, "TIn").WithArguments("IContexts<TIn, TOut, TInv>.Method4In(ref TIn)", "TIn", "contravariant", "invariantly").WithLocation(19, 23), // (25,5): error CS1961: Invalid variance: The type parameter 'TOut' must be contravariantly valid on 'IContexts<TIn, TOut, TInv>.Property1Out'. 'TOut' is covariant. // TOut Property1Out { set; } //CS1961 on "TOut" Diagnostic(ErrorCode.ERR_UnexpectedVariance, "TOut").WithArguments("IContexts<TIn, TOut, TInv>.Property1Out", "TOut", "covariant", "contravariantly").WithLocation(25, 5), // (27,5): error CS1961: Invalid variance: The type parameter 'TOut' must be invariantly valid on 'IContexts<TIn, TOut, TInv>.Property3Out'. 'TOut' is covariant. // TOut Property3Out { get; set; } //CS1961 on "TOut" Diagnostic(ErrorCode.ERR_UnexpectedVariance, "TOut").WithArguments("IContexts<TIn, TOut, TInv>.Property3Out", "TOut", "covariant", "invariantly").WithLocation(27, 5), // (29,14): error CS1961: Invalid variance: The type parameter 'TOut' must be contravariantly valid on 'IContexts<TIn, TOut, TInv>.this[TOut, char, bool]'. 'TOut' is covariant. // int this[TOut arg, char filler, bool indexer1Out] { get; } //CS1961 on "TOut" Diagnostic(ErrorCode.ERR_UnexpectedVariance, "TOut").WithArguments("IContexts<TIn, TOut, TInv>.this[TOut, char, bool]", "TOut", "covariant", "contravariantly").WithLocation(29, 14), // (31,14): error CS1961: Invalid variance: The type parameter 'TOut' must be contravariantly valid on 'IContexts<TIn, TOut, TInv>.this[TOut, bool, bool]'. 'TOut' is covariant. // int this[TOut arg, bool filler, bool indexer3Out] { set; } //CS1961 on "TOut" Diagnostic(ErrorCode.ERR_UnexpectedVariance, "TOut").WithArguments("IContexts<TIn, TOut, TInv>.this[TOut, bool, bool]", "TOut", "covariant", "contravariantly").WithLocation(31, 14), // (32,5): error CS1961: Invalid variance: The type parameter 'TOut' must be contravariantly valid on 'IContexts<TIn, TOut, TInv>.this[int, bool[], bool]'. 'TOut' is covariant. // TOut this[int arg, bool[] filler, bool indexer4Out] { set; } //CS1961 on "TOut" Diagnostic(ErrorCode.ERR_UnexpectedVariance, "TOut").WithArguments("IContexts<TIn, TOut, TInv>.this[int, bool[], bool]", "TOut", "covariant", "contravariantly").WithLocation(32, 5), // (33,14): error CS1961: Invalid variance: The type parameter 'TOut' must be contravariantly valid on 'IContexts<TIn, TOut, TInv>.this[TOut, long, bool]'. 'TOut' is covariant. // int this[TOut arg, long filler, bool indexer5Out] { get; set; } //CS1961 on "TOut" Diagnostic(ErrorCode.ERR_UnexpectedVariance, "TOut").WithArguments("IContexts<TIn, TOut, TInv>.this[TOut, long, bool]", "TOut", "covariant", "contravariantly").WithLocation(33, 14), // (34,5): error CS1961: Invalid variance: The type parameter 'TOut' must be invariantly valid on 'IContexts<TIn, TOut, TInv>.this[int, long[], bool]'. 'TOut' is covariant. // TOut this[int arg, long[] filler, bool indexer6Out] { get; set; } //CS1961 on "TOut" Diagnostic(ErrorCode.ERR_UnexpectedVariance, "TOut").WithArguments("IContexts<TIn, TOut, TInv>.this[int, long[], bool]", "TOut", "covariant", "invariantly").WithLocation(34, 5), // (36,21): error CS1961: Invalid variance: The type parameter 'TOut' must be contravariantly valid on 'IContexts<TIn, TOut, TInv>.Method1Out(TOut)'. 'TOut' is covariant. // long Method1Out(TOut p); //CS1961 on "TOut" Diagnostic(ErrorCode.ERR_UnexpectedVariance, "TOut").WithArguments("IContexts<TIn, TOut, TInv>.Method1Out(TOut)", "TOut", "covariant", "contravariantly").WithLocation(36, 21), // (38,25): error CS1961: Invalid variance: The type parameter 'TOut' must be invariantly valid on 'IContexts<TIn, TOut, TInv>.Method3Out(out TOut)'. 'TOut' is covariant. // long Method3Out(out TOut p); //CS1961 on "TOut" (sic: out params have to be input-safe) Diagnostic(ErrorCode.ERR_UnexpectedVariance, "TOut").WithArguments("IContexts<TIn, TOut, TInv>.Method3Out(out TOut)", "TOut", "covariant", "invariantly").WithLocation(38, 25), // (39,25): error CS1961: Invalid variance: The type parameter 'TOut' must be invariantly valid on 'IContexts<TIn, TOut, TInv>.Method4Out(ref TOut)'. 'TOut' is covariant. // long Method4Out(ref TOut p); //CS1961 on "TOut" Diagnostic(ErrorCode.ERR_UnexpectedVariance, "TOut").WithArguments("IContexts<TIn, TOut, TInv>.Method4Out(ref TOut)", "TOut", "covariant", "invariantly").WithLocation(39, 25), // (41,22): error CS1961: Invalid variance: The type parameter 'TOut' must be contravariantly valid on 'IContexts<TIn, TOut, TInv>.Event1Out'. 'TOut' is covariant. // event DOut<TOut> Event1Out; //CS1961 on "TOut" Diagnostic(ErrorCode.ERR_UnexpectedVariance, "Event1Out").WithArguments("IContexts<TIn, TOut, TInv>.Event1Out", "TOut", "covariant", "contravariantly").WithLocation(41, 22)); } /// <summary> /// Test all of the contexts that require output safety. /// Note: some also require input safety. /// </summary> [Fact] public void CS1961ERR_UnexpectedVariance_OutputUnsafe() { var text = @" interface IOutputUnsafe<in TIn, out TOut, TInv> { #region Case 1: contravariant type parameter TInv Property1Good { get; } TInv this[long[] Indexer1Good] { get; } TInv Method1Good(); TIn Property1Bad { get; } TIn this[char[] Indexer1Bad] { get; } TIn Method1Bad(); #endregion Case 1 #region Case 2: array of output-unsafe TInv[] Property2Good { get; } TInv[] this[long[,] Indexer2Good] { get; } TInv[] Method2Good(); TIn[] Property2Bad { get; } TIn[] this[char[,] Indexer2Bad] { get; } TIn[] Method2Bad(); #endregion Case 2 #region Case 3: constructed with output-unsafe type arg in covariant slot IOut<TInv> Property3Good { get; } IOut<TInv> this[long[,,] Indexer3Good] { get; } IOut<TInv> Method3Good(); IOut<TIn> Property3Bad { get; } IOut<TIn> this[char[,,] Indexer3Bad] { get; } IOut<TIn> Method3Bad(); #endregion Case 3 #region Case 4: constructed with output-unsafe type arg in invariant slot IInv<TInv> Property4Good { get; } IInv<TInv> this[long[,,,] Indexer4Good] { get; } IInv<TInv> Method4Good(); IInv<TIn> Property4Bad { get; } IInv<TIn> this[char[,,,] Indexer4Bad] { get; } IInv<TIn> Method4Bad(); #endregion Case 4 #region Case 5: constructed with input-unsafe (sic) type arg in contravariant slot IIn<TInv> Property5Good { get; } IIn<TInv> this[long[,,,,] Indexer5Good] { get; } IIn<TInv> Method5Good(); IIn<TOut> Property5Bad { get; } IIn<TOut> this[char[,,,,] Indexer5Bad] { get; } IIn<TOut> Method5Bad(); #endregion Case 5 #region Case 6: constructed with input-unsafe (sic) type arg in invariant slot IInv<TInv> Property6Good { get; } IInv<TInv> this[long[,,,,,] Indexer6Good] { get; } IInv<TInv> Method6Good(); IInv<TOut> Property6Bad { get; } IInv<TOut> this[char[,,,,,] Indexer6Bad] { get; } IInv<TOut> Method6Bad(); #endregion Case 6 } interface IIn<in T> { } interface IOut<out T> { } interface IInv<T> { }"; CreateCompilation(text).VerifyDiagnostics( // (9,5): error CS1961: Invalid variance: The type parameter 'TIn' must be covariantly valid on 'IOutputUnsafe<TIn, TOut, TInv>.Property1Bad'. 'TIn' is contravariant. // TIn Property1Bad { get; } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "TIn").WithArguments("IOutputUnsafe<TIn, TOut, TInv>.Property1Bad", "TIn", "contravariant", "covariantly").WithLocation(9, 5), // (10,5): error CS1961: Invalid variance: The type parameter 'TIn' must be covariantly valid on 'IOutputUnsafe<TIn, TOut, TInv>.this[char[]]'. 'TIn' is contravariant. // TIn this[char[] Indexer1Bad] { get; } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "TIn").WithArguments("IOutputUnsafe<TIn, TOut, TInv>.this[char[]]", "TIn", "contravariant", "covariantly").WithLocation(10, 5), // (11,5): error CS1961: Invalid variance: The type parameter 'TIn' must be covariantly valid on 'IOutputUnsafe<TIn, TOut, TInv>.Method1Bad()'. 'TIn' is contravariant. // TIn Method1Bad(); Diagnostic(ErrorCode.ERR_UnexpectedVariance, "TIn").WithArguments("IOutputUnsafe<TIn, TOut, TInv>.Method1Bad()", "TIn", "contravariant", "covariantly").WithLocation(11, 5), // (19,5): error CS1961: Invalid variance: The type parameter 'TIn' must be covariantly valid on 'IOutputUnsafe<TIn, TOut, TInv>.Property2Bad'. 'TIn' is contravariant. // TIn[] Property2Bad { get; } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "TIn[]").WithArguments("IOutputUnsafe<TIn, TOut, TInv>.Property2Bad", "TIn", "contravariant", "covariantly").WithLocation(19, 5), // (20,5): error CS1961: Invalid variance: The type parameter 'TIn' must be covariantly valid on 'IOutputUnsafe<TIn, TOut, TInv>.this[char[*,*]]'. 'TIn' is contravariant. // TIn[] this[char[,] Indexer2Bad] { get; } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "TIn[]").WithArguments("IOutputUnsafe<TIn, TOut, TInv>.this[char[*,*]]", "TIn", "contravariant", "covariantly").WithLocation(20, 5), // (21,5): error CS1961: Invalid variance: The type parameter 'TIn' must be covariantly valid on 'IOutputUnsafe<TIn, TOut, TInv>.Method2Bad()'. 'TIn' is contravariant. // TIn[] Method2Bad(); Diagnostic(ErrorCode.ERR_UnexpectedVariance, "TIn[]").WithArguments("IOutputUnsafe<TIn, TOut, TInv>.Method2Bad()", "TIn", "contravariant", "covariantly").WithLocation(21, 5), // (29,5): error CS1961: Invalid variance: The type parameter 'TIn' must be covariantly valid on 'IOutputUnsafe<TIn, TOut, TInv>.Property3Bad'. 'TIn' is contravariant. // IOut<TIn> Property3Bad { get; } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "IOut<TIn>").WithArguments("IOutputUnsafe<TIn, TOut, TInv>.Property3Bad", "TIn", "contravariant", "covariantly").WithLocation(29, 5), // (30,5): error CS1961: Invalid variance: The type parameter 'TIn' must be covariantly valid on 'IOutputUnsafe<TIn, TOut, TInv>.this[char[*,*,*]]'. 'TIn' is contravariant. // IOut<TIn> this[char[,,] Indexer3Bad] { get; } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "IOut<TIn>").WithArguments("IOutputUnsafe<TIn, TOut, TInv>.this[char[*,*,*]]", "TIn", "contravariant", "covariantly").WithLocation(30, 5), // (31,5): error CS1961: Invalid variance: The type parameter 'TIn' must be covariantly valid on 'IOutputUnsafe<TIn, TOut, TInv>.Method3Bad()'. 'TIn' is contravariant. // IOut<TIn> Method3Bad(); Diagnostic(ErrorCode.ERR_UnexpectedVariance, "IOut<TIn>").WithArguments("IOutputUnsafe<TIn, TOut, TInv>.Method3Bad()", "TIn", "contravariant", "covariantly").WithLocation(31, 5), // (39,5): error CS1961: Invalid variance: The type parameter 'TIn' must be invariantly valid on 'IOutputUnsafe<TIn, TOut, TInv>.Property4Bad'. 'TIn' is contravariant. // IInv<TIn> Property4Bad { get; } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "IInv<TIn>").WithArguments("IOutputUnsafe<TIn, TOut, TInv>.Property4Bad", "TIn", "contravariant", "invariantly").WithLocation(39, 5), // (40,5): error CS1961: Invalid variance: The type parameter 'TIn' must be invariantly valid on 'IOutputUnsafe<TIn, TOut, TInv>.this[char[*,*,*,*]]'. 'TIn' is contravariant. // IInv<TIn> this[char[,,,] Indexer4Bad] { get; } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "IInv<TIn>").WithArguments("IOutputUnsafe<TIn, TOut, TInv>.this[char[*,*,*,*]]", "TIn", "contravariant", "invariantly").WithLocation(40, 5), // (41,5): error CS1961: Invalid variance: The type parameter 'TIn' must be invariantly valid on 'IOutputUnsafe<TIn, TOut, TInv>.Method4Bad()'. 'TIn' is contravariant. // IInv<TIn> Method4Bad(); Diagnostic(ErrorCode.ERR_UnexpectedVariance, "IInv<TIn>").WithArguments("IOutputUnsafe<TIn, TOut, TInv>.Method4Bad()", "TIn", "contravariant", "invariantly").WithLocation(41, 5), // (49,5): error CS1961: Invalid variance: The type parameter 'TOut' must be contravariantly valid on 'IOutputUnsafe<TIn, TOut, TInv>.Property5Bad'. 'TOut' is covariant. // IIn<TOut> Property5Bad { get; } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "IIn<TOut>").WithArguments("IOutputUnsafe<TIn, TOut, TInv>.Property5Bad", "TOut", "covariant", "contravariantly").WithLocation(49, 5), // (50,5): error CS1961: Invalid variance: The type parameter 'TOut' must be contravariantly valid on 'IOutputUnsafe<TIn, TOut, TInv>.this[char[*,*,*,*,*]]'. 'TOut' is covariant. // IIn<TOut> this[char[,,,,] Indexer5Bad] { get; } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "IIn<TOut>").WithArguments("IOutputUnsafe<TIn, TOut, TInv>.this[char[*,*,*,*,*]]", "TOut", "covariant", "contravariantly").WithLocation(50, 5), // (51,5): error CS1961: Invalid variance: The type parameter 'TOut' must be contravariantly valid on 'IOutputUnsafe<TIn, TOut, TInv>.Method5Bad()'. 'TOut' is covariant. // IIn<TOut> Method5Bad(); Diagnostic(ErrorCode.ERR_UnexpectedVariance, "IIn<TOut>").WithArguments("IOutputUnsafe<TIn, TOut, TInv>.Method5Bad()", "TOut", "covariant", "contravariantly").WithLocation(51, 5), // (59,5): error CS1961: Invalid variance: The type parameter 'TOut' must be invariantly valid on 'IOutputUnsafe<TIn, TOut, TInv>.Property6Bad'. 'TOut' is covariant. // IInv<TOut> Property6Bad { get; } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "IInv<TOut>").WithArguments("IOutputUnsafe<TIn, TOut, TInv>.Property6Bad", "TOut", "covariant", "invariantly").WithLocation(59, 5), // (60,5): error CS1961: Invalid variance: The type parameter 'TOut' must be invariantly valid on 'IOutputUnsafe<TIn, TOut, TInv>.this[char[*,*,*,*,*,*]]'. 'TOut' is covariant. // IInv<TOut> this[char[,,,,,] Indexer6Bad] { get; } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "IInv<TOut>").WithArguments("IOutputUnsafe<TIn, TOut, TInv>.this[char[*,*,*,*,*,*]]", "TOut", "covariant", "invariantly").WithLocation(60, 5), // (61,5): error CS1961: Invalid variance: The type parameter 'TOut' must be invariantly valid on 'IOutputUnsafe<TIn, TOut, TInv>.Method6Bad()'. 'TOut' is covariant. // IInv<TOut> Method6Bad(); Diagnostic(ErrorCode.ERR_UnexpectedVariance, "IInv<TOut>").WithArguments("IOutputUnsafe<TIn, TOut, TInv>.Method6Bad()", "TOut", "covariant", "invariantly").WithLocation(61, 5)); } /// <summary> /// Test all of the contexts that require input safety. /// Note: some also require output safety. /// </summary> [Fact] public void CS1961ERR_UnexpectedVariance_InputUnsafe() { var text = @" interface IInputUnsafe<in TIn, out TOut, TInv> { #region Case 1: contravariant type parameter TInv Property1Good { set; } TInv this[long[] Indexer1GoodA] { set; } long this[long[] Indexer1GoodB, TInv p] { set; } long Method1Good(TInv p); TOut Property1Bad { set; } TOut this[char[] Indexer1BadA] { set; } long this[char[] Indexer1BadB, TOut p] { set; } long Method1Bad(TOut p); #endregion Case 1 #region Case 2: array of input-unsafe TInv[] Property2Good { set; } TInv[] this[long[,] Indexer2GoodA] { set; } long this[long[,] Indexer2GoodB, TInv[] p] { set; } long Method2Good(TInv[] p); TOut[] Property2Bad { set; } TOut[] this[char[,] Indexer2BadA] { set; } long this[char[,] Indexer2BadB, TOut[] p] { set; } long Method2Bad(TOut[] p); #endregion Case 2 #region Case 3: constructed with input-unsafe type arg in covariant (sic: not flipped) slot IOut<TInv> Property3Good { set; } IOut<TInv> this[long[,,] Indexer3GoodA] { set; } long this[long[,,] Indexer3GoodB, IOut<TInv> p] { set; } long Method3Good(IOut<TInv> p); event DOut<TInv> Event3Good; IOut<TOut> Property3Bad { set; } IOut<TOut> this[char[,,] Indexer3BadA] { set; } long this[char[,,] Indexer3BadB, IOut<TOut> p] { set; } long Method3Bad(IOut<TOut> p); event DOut<TOut> Event3Bad; #endregion Case 3 #region Case 4: constructed with input-unsafe type arg in invariant slot IInv<TInv> Property4Good { set; } IInv<TInv> this[long[,,,] Indexer4GoodA] { set; } long this[long[,,,] Indexer4GoodB, IInv<TInv> p] { set; } long Method4Good(IInv<TInv> p); event DInv<TInv> Event4Good; IInv<TOut> Property4Bad { set; } IInv<TOut> this[char[,,,] Indexer4BadA] { set; } long this[char[,,,] Indexer4BadB, IInv<TOut> p] { set; } long Method4Bad(IInv<TOut> p); event DInv<TOut> Event4Bad; #endregion Case 4 #region Case 5: constructed with output-unsafe (sic) type arg in contravariant (sic: not flipped) slot IIn<TInv> Property5Good { set; } IIn<TInv> this[long[,,,,] Indexer5GoodA] { set; } long this[long[,,,,] Indexer5GoodB, IIn<TInv> p] { set; } long Method5Good(IIn<TInv> p); event DIn<TInv> Event5Good; IIn<TIn> Property5Bad { set; } IIn<TIn> this[char[,,,,] Indexer5BadA] { set; } long this[char[,,,,] Indexer5BadB, IIn<TIn> p] { set; } long Method5Bad(IIn<TIn> p); event DIn<TIn> Event5Bad; #endregion Case 5 #region Case 6: constructed with output-unsafe (sic) type arg in invariant slot IInv<TInv> Property6Good { set; } IInv<TInv> this[long[,,,,,] Indexer6GoodA] { set; } long this[long[,,,,,] Indexer6GoodB, IInv<TInv> p] { set; } long Method6Good(IInv<TInv> p); event DInv<TInv> Event6Good; IInv<TIn> Property6Bad { set; } IInv<TIn> this[char[,,,,,] Indexer6BadA] { set; } long this[char[,,,,,] Indexer6BadB, IInv<TIn> p] { set; } long Method6Bad(IInv<TIn> p); event DInv<TIn> Event6Bad; #endregion Case 6 } interface IIn<in T> { } interface IOut<out T> { } interface IInv<T> { } delegate void DIn<in T>(); delegate void DOut<out T>(); delegate void DInv<T>(); "; CreateCompilation(text).VerifyDiagnostics( // (11,5): error CS1961: Invalid variance: The type parameter 'TOut' must be contravariantly valid on 'IInputUnsafe<TIn, TOut, TInv>.this[char[]]'. 'TOut' is covariant. // TOut this[char[] Indexer1BadA] { set; } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "TOut").WithArguments("IInputUnsafe<TIn, TOut, TInv>.this[char[]]", "TOut", "covariant", "contravariantly").WithLocation(11, 5), // (12,36): error CS1961: Invalid variance: The type parameter 'TOut' must be contravariantly valid on 'IInputUnsafe<TIn, TOut, TInv>.this[char[], TOut]'. 'TOut' is covariant. // long this[char[] Indexer1BadB, TOut p] { set; } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "TOut").WithArguments("IInputUnsafe<TIn, TOut, TInv>.this[char[], TOut]", "TOut", "covariant", "contravariantly").WithLocation(12, 36), // (23,5): error CS1961: Invalid variance: The type parameter 'TOut' must be contravariantly valid on 'IInputUnsafe<TIn, TOut, TInv>.this[char[*,*]]'. 'TOut' is covariant. // TOut[] this[char[,] Indexer2BadA] { set; } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "TOut[]").WithArguments("IInputUnsafe<TIn, TOut, TInv>.this[char[*,*]]", "TOut", "covariant", "contravariantly").WithLocation(23, 5), // (24,37): error CS1961: Invalid variance: The type parameter 'TOut' must be contravariantly valid on 'IInputUnsafe<TIn, TOut, TInv>.this[char[*,*], TOut[]]'. 'TOut' is covariant. // long this[char[,] Indexer2BadB, TOut[] p] { set; } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "TOut[]").WithArguments("IInputUnsafe<TIn, TOut, TInv>.this[char[*,*], TOut[]]", "TOut", "covariant", "contravariantly").WithLocation(24, 37), // (36,5): error CS1961: Invalid variance: The type parameter 'TOut' must be contravariantly valid on 'IInputUnsafe<TIn, TOut, TInv>.this[char[*,*,*]]'. 'TOut' is covariant. // IOut<TOut> this[char[,,] Indexer3BadA] { set; } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "IOut<TOut>").WithArguments("IInputUnsafe<TIn, TOut, TInv>.this[char[*,*,*]]", "TOut", "covariant", "contravariantly").WithLocation(36, 5), // (37,38): error CS1961: Invalid variance: The type parameter 'TOut' must be contravariantly valid on 'IInputUnsafe<TIn, TOut, TInv>.this[char[*,*,*], IOut<TOut>]'. 'TOut' is covariant. // long this[char[,,] Indexer3BadB, IOut<TOut> p] { set; } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "IOut<TOut>").WithArguments("IInputUnsafe<TIn, TOut, TInv>.this[char[*,*,*], IOut<TOut>]", "TOut", "covariant", "contravariantly").WithLocation(37, 38), // (50,5): error CS1961: Invalid variance: The type parameter 'TOut' must be invariantly valid on 'IInputUnsafe<TIn, TOut, TInv>.this[char[*,*,*,*]]'. 'TOut' is covariant. // IInv<TOut> this[char[,,,] Indexer4BadA] { set; } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "IInv<TOut>").WithArguments("IInputUnsafe<TIn, TOut, TInv>.this[char[*,*,*,*]]", "TOut", "covariant", "invariantly").WithLocation(50, 5), // (51,39): error CS1961: Invalid variance: The type parameter 'TOut' must be invariantly valid on 'IInputUnsafe<TIn, TOut, TInv>.this[char[*,*,*,*], IInv<TOut>]'. 'TOut' is covariant. // long this[char[,,,] Indexer4BadB, IInv<TOut> p] { set; } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "IInv<TOut>").WithArguments("IInputUnsafe<TIn, TOut, TInv>.this[char[*,*,*,*], IInv<TOut>]", "TOut", "covariant", "invariantly").WithLocation(51, 39), // (64,5): error CS1961: Invalid variance: The type parameter 'TIn' must be covariantly valid on 'IInputUnsafe<TIn, TOut, TInv>.this[char[*,*,*,*,*]]'. 'TIn' is contravariant. // IIn<TIn> this[char[,,,,] Indexer5BadA] { set; } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "IIn<TIn>").WithArguments("IInputUnsafe<TIn, TOut, TInv>.this[char[*,*,*,*,*]]", "TIn", "contravariant", "covariantly").WithLocation(64, 5), // (65,40): error CS1961: Invalid variance: The type parameter 'TIn' must be covariantly valid on 'IInputUnsafe<TIn, TOut, TInv>.this[char[*,*,*,*,*], IIn<TIn>]'. 'TIn' is contravariant. // long this[char[,,,,] Indexer5BadB, IIn<TIn> p] { set; } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "IIn<TIn>").WithArguments("IInputUnsafe<TIn, TOut, TInv>.this[char[*,*,*,*,*], IIn<TIn>]", "TIn", "contravariant", "covariantly").WithLocation(65, 40), // (78,5): error CS1961: Invalid variance: The type parameter 'TIn' must be invariantly valid on 'IInputUnsafe<TIn, TOut, TInv>.this[char[*,*,*,*,*,*]]'. 'TIn' is contravariant. // IInv<TIn> this[char[,,,,,] Indexer6BadA] { set; } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "IInv<TIn>").WithArguments("IInputUnsafe<TIn, TOut, TInv>.this[char[*,*,*,*,*,*]]", "TIn", "contravariant", "invariantly").WithLocation(78, 5), // (79,41): error CS1961: Invalid variance: The type parameter 'TIn' must be invariantly valid on 'IInputUnsafe<TIn, TOut, TInv>.this[char[*,*,*,*,*,*], IInv<TIn>]'. 'TIn' is contravariant. // long this[char[,,,,,] Indexer6BadB, IInv<TIn> p] { set; } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "IInv<TIn>").WithArguments("IInputUnsafe<TIn, TOut, TInv>.this[char[*,*,*,*,*,*], IInv<TIn>]", "TIn", "contravariant", "invariantly").WithLocation(79, 41), // (10,5): error CS1961: Invalid variance: The type parameter 'TOut' must be contravariantly valid on 'IInputUnsafe<TIn, TOut, TInv>.Property1Bad'. 'TOut' is covariant. // TOut Property1Bad { set; } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "TOut").WithArguments("IInputUnsafe<TIn, TOut, TInv>.Property1Bad", "TOut", "covariant", "contravariantly").WithLocation(10, 5), // (13,21): error CS1961: Invalid variance: The type parameter 'TOut' must be contravariantly valid on 'IInputUnsafe<TIn, TOut, TInv>.Method1Bad(TOut)'. 'TOut' is covariant. // long Method1Bad(TOut p); Diagnostic(ErrorCode.ERR_UnexpectedVariance, "TOut").WithArguments("IInputUnsafe<TIn, TOut, TInv>.Method1Bad(TOut)", "TOut", "covariant", "contravariantly").WithLocation(13, 21), // (22,5): error CS1961: Invalid variance: The type parameter 'TOut' must be contravariantly valid on 'IInputUnsafe<TIn, TOut, TInv>.Property2Bad'. 'TOut' is covariant. // TOut[] Property2Bad { set; } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "TOut[]").WithArguments("IInputUnsafe<TIn, TOut, TInv>.Property2Bad", "TOut", "covariant", "contravariantly").WithLocation(22, 5), // (25,21): error CS1961: Invalid variance: The type parameter 'TOut' must be contravariantly valid on 'IInputUnsafe<TIn, TOut, TInv>.Method2Bad(TOut[])'. 'TOut' is covariant. // long Method2Bad(TOut[] p); Diagnostic(ErrorCode.ERR_UnexpectedVariance, "TOut[]").WithArguments("IInputUnsafe<TIn, TOut, TInv>.Method2Bad(TOut[])", "TOut", "covariant", "contravariantly").WithLocation(25, 21), // (35,5): error CS1961: Invalid variance: The type parameter 'TOut' must be contravariantly valid on 'IInputUnsafe<TIn, TOut, TInv>.Property3Bad'. 'TOut' is covariant. // IOut<TOut> Property3Bad { set; } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "IOut<TOut>").WithArguments("IInputUnsafe<TIn, TOut, TInv>.Property3Bad", "TOut", "covariant", "contravariantly").WithLocation(35, 5), // (38,21): error CS1961: Invalid variance: The type parameter 'TOut' must be contravariantly valid on 'IInputUnsafe<TIn, TOut, TInv>.Method3Bad(IOut<TOut>)'. 'TOut' is covariant. // long Method3Bad(IOut<TOut> p); Diagnostic(ErrorCode.ERR_UnexpectedVariance, "IOut<TOut>").WithArguments("IInputUnsafe<TIn, TOut, TInv>.Method3Bad(IOut<TOut>)", "TOut", "covariant", "contravariantly").WithLocation(38, 21), // (39,22): error CS1961: Invalid variance: The type parameter 'TOut' must be contravariantly valid on 'IInputUnsafe<TIn, TOut, TInv>.Event3Bad'. 'TOut' is covariant. // event DOut<TOut> Event3Bad; Diagnostic(ErrorCode.ERR_UnexpectedVariance, "Event3Bad").WithArguments("IInputUnsafe<TIn, TOut, TInv>.Event3Bad", "TOut", "covariant", "contravariantly").WithLocation(39, 22), // (49,5): error CS1961: Invalid variance: The type parameter 'TOut' must be invariantly valid on 'IInputUnsafe<TIn, TOut, TInv>.Property4Bad'. 'TOut' is covariant. // IInv<TOut> Property4Bad { set; } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "IInv<TOut>").WithArguments("IInputUnsafe<TIn, TOut, TInv>.Property4Bad", "TOut", "covariant", "invariantly").WithLocation(49, 5), // (52,21): error CS1961: Invalid variance: The type parameter 'TOut' must be invariantly valid on 'IInputUnsafe<TIn, TOut, TInv>.Method4Bad(IInv<TOut>)'. 'TOut' is covariant. // long Method4Bad(IInv<TOut> p); Diagnostic(ErrorCode.ERR_UnexpectedVariance, "IInv<TOut>").WithArguments("IInputUnsafe<TIn, TOut, TInv>.Method4Bad(IInv<TOut>)", "TOut", "covariant", "invariantly").WithLocation(52, 21), // (53,22): error CS1961: Invalid variance: The type parameter 'TOut' must be invariantly valid on 'IInputUnsafe<TIn, TOut, TInv>.Event4Bad'. 'TOut' is covariant. // event DInv<TOut> Event4Bad; Diagnostic(ErrorCode.ERR_UnexpectedVariance, "Event4Bad").WithArguments("IInputUnsafe<TIn, TOut, TInv>.Event4Bad", "TOut", "covariant", "invariantly").WithLocation(53, 22), // (63,5): error CS1961: Invalid variance: The type parameter 'TIn' must be covariantly valid on 'IInputUnsafe<TIn, TOut, TInv>.Property5Bad'. 'TIn' is contravariant. // IIn<TIn> Property5Bad { set; } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "IIn<TIn>").WithArguments("IInputUnsafe<TIn, TOut, TInv>.Property5Bad", "TIn", "contravariant", "covariantly").WithLocation(63, 5), // (66,21): error CS1961: Invalid variance: The type parameter 'TIn' must be covariantly valid on 'IInputUnsafe<TIn, TOut, TInv>.Method5Bad(IIn<TIn>)'. 'TIn' is contravariant. // long Method5Bad(IIn<TIn> p); Diagnostic(ErrorCode.ERR_UnexpectedVariance, "IIn<TIn>").WithArguments("IInputUnsafe<TIn, TOut, TInv>.Method5Bad(IIn<TIn>)", "TIn", "contravariant", "covariantly").WithLocation(66, 21), // (67,20): error CS1961: Invalid variance: The type parameter 'TIn' must be covariantly valid on 'IInputUnsafe<TIn, TOut, TInv>.Event5Bad'. 'TIn' is contravariant. // event DIn<TIn> Event5Bad; Diagnostic(ErrorCode.ERR_UnexpectedVariance, "Event5Bad").WithArguments("IInputUnsafe<TIn, TOut, TInv>.Event5Bad", "TIn", "contravariant", "covariantly").WithLocation(67, 20), // (77,5): error CS1961: Invalid variance: The type parameter 'TIn' must be invariantly valid on 'IInputUnsafe<TIn, TOut, TInv>.Property6Bad'. 'TIn' is contravariant. // IInv<TIn> Property6Bad { set; } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "IInv<TIn>").WithArguments("IInputUnsafe<TIn, TOut, TInv>.Property6Bad", "TIn", "contravariant", "invariantly").WithLocation(77, 5), // (80,21): error CS1961: Invalid variance: The type parameter 'TIn' must be invariantly valid on 'IInputUnsafe<TIn, TOut, TInv>.Method6Bad(IInv<TIn>)'. 'TIn' is contravariant. // long Method6Bad(IInv<TIn> p); Diagnostic(ErrorCode.ERR_UnexpectedVariance, "IInv<TIn>").WithArguments("IInputUnsafe<TIn, TOut, TInv>.Method6Bad(IInv<TIn>)", "TIn", "contravariant", "invariantly").WithLocation(80, 21), // (81,21): error CS1961: Invalid variance: The type parameter 'TIn' must be invariantly valid on 'IInputUnsafe<TIn, TOut, TInv>.Event6Bad'. 'TIn' is contravariant. // event DInv<TIn> Event6Bad; Diagnostic(ErrorCode.ERR_UnexpectedVariance, "Event6Bad").WithArguments("IInputUnsafe<TIn, TOut, TInv>.Event6Bad", "TIn", "contravariant", "invariantly").WithLocation(81, 21)); } /// <summary> /// Test output-safety checks on base interfaces. /// </summary> [Fact] public void CS1961ERR_UnexpectedVariance_BaseInterfaces() { var text = @" interface IBaseInterfaces<in TIn, out TOut, TInv> : IIn<TOut>, IOut<TIn>, IInv<TInv> { } interface IIn<in T> { } interface IOut<out T> { } interface IInv<T> { }"; CreateCompilation(text).VerifyDiagnostics( // (2,39): error CS1961: Invalid variance: The type parameter 'TOut' must be contravariantly valid on 'IIn<TOut>'. 'TOut' is covariant. Diagnostic(ErrorCode.ERR_UnexpectedVariance, "TOut").WithArguments("IIn<TOut>", "TOut", "covariant", "contravariantly"), // (2,30): error CS1961: Invalid variance: The type parameter 'TIn' must be covariantly valid on 'IOut<TIn>'. 'TIn' is contravariant. Diagnostic(ErrorCode.ERR_UnexpectedVariance, "TIn").WithArguments("IOut<TIn>", "TIn", "contravariant", "covariantly")); } /// <summary> /// Test all type parameter/type argument combinations. /// | Type Arg Covariant | Type Arg Contravariant | Type Arg Invariant /// -------------------------+----------------------+------------------------+-------------------- /// Type Param Covariant | Covariant | Contravariant | Invariant /// Type Param Contravariant | Contravariant | Covariant | Invariant /// Type Param Invariant | Error | Error | Invariant /// </summary> [Fact] public void CS1961ERR_UnexpectedVariance_Generics() { var text = @" interface IOutputUnsafeTable<out TInputUnsafe, in TOutputUnsafe, TInvariant> { ICovariant<TInputUnsafe> OutputUnsafe1(); ICovariant<TOutputUnsafe> OutputUnsafe2(); ICovariant<TInvariant> OutputUnsafe3(); IContravariant<TInputUnsafe> OutputUnsafe4(); IContravariant<TOutputUnsafe> OutputUnsafe5(); IContravariant<TInvariant> OutputUnsafe6(); IInvariant<TInputUnsafe> OutputUnsafe7(); IInvariant<TOutputUnsafe> OutputUnsafe8(); IInvariant<TInvariant> OutputUnsafe9(); } interface IInputUnsafeTable<out TInputUnsafe, in TOutputUnsafe, TInvariant> { void InputUnsafe1(ICovariant<TInputUnsafe> p); void InputUnsafe2(ICovariant<TOutputUnsafe> p); void InputUnsafe3(ICovariant<TInvariant> p); void InputUnsafe4(IContravariant<TInputUnsafe> p); void InputUnsafe5(IContravariant<TOutputUnsafe> p); void InputUnsafe6(IContravariant<TInvariant> p); void InputUnsafe7(IInvariant<TInputUnsafe> p); void InputUnsafe8(IInvariant<TOutputUnsafe> p); void InputUnsafe9(IInvariant<TInvariant> p); } interface IBothUnsafeTable<out TInputUnsafe, in TOutputUnsafe, TInvariant> { void InputUnsafe1(ref ICovariant<TInputUnsafe> p); void InputUnsafe2(ref ICovariant<TOutputUnsafe> p); void InputUnsafe3(ref ICovariant<TInvariant> p); void InputUnsafe4(ref IContravariant<TInputUnsafe> p); void InputUnsafe5(ref IContravariant<TOutputUnsafe> p); void InputUnsafe6(ref IContravariant<TInvariant> p); void InputUnsafe7(ref IInvariant<TInputUnsafe> p); void InputUnsafe8(ref IInvariant<TOutputUnsafe> p); void InputUnsafe9(ref IInvariant<TInvariant> p); } interface ICovariant<out T> { } interface IContravariant<in T> { } interface IInvariant<T> { }"; CreateCompilation(text).VerifyDiagnostics( // (5,5): error CS1961: Invalid variance: The type parameter 'TOutputUnsafe' must be covariantly valid on 'IOutputUnsafeTable<TInputUnsafe, TOutputUnsafe, TInvariant>.OutputUnsafe2()'. 'TOutputUnsafe' is contravariant. // ICovariant<TOutputUnsafe> OutputUnsafe2(); Diagnostic(ErrorCode.ERR_UnexpectedVariance, "ICovariant<TOutputUnsafe>").WithArguments("IOutputUnsafeTable<TInputUnsafe, TOutputUnsafe, TInvariant>.OutputUnsafe2()", "TOutputUnsafe", "contravariant", "covariantly").WithLocation(5, 5), // (8,5): error CS1961: Invalid variance: The type parameter 'TInputUnsafe' must be contravariantly valid on 'IOutputUnsafeTable<TInputUnsafe, TOutputUnsafe, TInvariant>.OutputUnsafe4()'. 'TInputUnsafe' is covariant. // IContravariant<TInputUnsafe> OutputUnsafe4(); Diagnostic(ErrorCode.ERR_UnexpectedVariance, "IContravariant<TInputUnsafe>").WithArguments("IOutputUnsafeTable<TInputUnsafe, TOutputUnsafe, TInvariant>.OutputUnsafe4()", "TInputUnsafe", "covariant", "contravariantly").WithLocation(8, 5), // (12,5): error CS1961: Invalid variance: The type parameter 'TInputUnsafe' must be invariantly valid on 'IOutputUnsafeTable<TInputUnsafe, TOutputUnsafe, TInvariant>.OutputUnsafe7()'. 'TInputUnsafe' is covariant. // IInvariant<TInputUnsafe> OutputUnsafe7(); Diagnostic(ErrorCode.ERR_UnexpectedVariance, "IInvariant<TInputUnsafe>").WithArguments("IOutputUnsafeTable<TInputUnsafe, TOutputUnsafe, TInvariant>.OutputUnsafe7()", "TInputUnsafe", "covariant", "invariantly").WithLocation(12, 5), // (13,5): error CS1961: Invalid variance: The type parameter 'TOutputUnsafe' must be invariantly valid on 'IOutputUnsafeTable<TInputUnsafe, TOutputUnsafe, TInvariant>.OutputUnsafe8()'. 'TOutputUnsafe' is contravariant. // IInvariant<TOutputUnsafe> OutputUnsafe8(); Diagnostic(ErrorCode.ERR_UnexpectedVariance, "IInvariant<TOutputUnsafe>").WithArguments("IOutputUnsafeTable<TInputUnsafe, TOutputUnsafe, TInvariant>.OutputUnsafe8()", "TOutputUnsafe", "contravariant", "invariantly").WithLocation(13, 5), // (19,23): error CS1961: Invalid variance: The type parameter 'TInputUnsafe' must be contravariantly valid on 'IInputUnsafeTable<TInputUnsafe, TOutputUnsafe, TInvariant>.InputUnsafe1(ICovariant<TInputUnsafe>)'. 'TInputUnsafe' is covariant. // void InputUnsafe1(ICovariant<TInputUnsafe> p); Diagnostic(ErrorCode.ERR_UnexpectedVariance, "ICovariant<TInputUnsafe>").WithArguments("IInputUnsafeTable<TInputUnsafe, TOutputUnsafe, TInvariant>.InputUnsafe1(ICovariant<TInputUnsafe>)", "TInputUnsafe", "covariant", "contravariantly").WithLocation(19, 23), // (24,23): error CS1961: Invalid variance: The type parameter 'TOutputUnsafe' must be covariantly valid on 'IInputUnsafeTable<TInputUnsafe, TOutputUnsafe, TInvariant>.InputUnsafe5(IContravariant<TOutputUnsafe>)'. 'TOutputUnsafe' is contravariant. // void InputUnsafe5(IContravariant<TOutputUnsafe> p); Diagnostic(ErrorCode.ERR_UnexpectedVariance, "IContravariant<TOutputUnsafe>").WithArguments("IInputUnsafeTable<TInputUnsafe, TOutputUnsafe, TInvariant>.InputUnsafe5(IContravariant<TOutputUnsafe>)", "TOutputUnsafe", "contravariant", "covariantly").WithLocation(24, 23), // (27,23): error CS1961: Invalid variance: The type parameter 'TInputUnsafe' must be invariantly valid on 'IInputUnsafeTable<TInputUnsafe, TOutputUnsafe, TInvariant>.InputUnsafe7(IInvariant<TInputUnsafe>)'. 'TInputUnsafe' is covariant. // void InputUnsafe7(IInvariant<TInputUnsafe> p); Diagnostic(ErrorCode.ERR_UnexpectedVariance, "IInvariant<TInputUnsafe>").WithArguments("IInputUnsafeTable<TInputUnsafe, TOutputUnsafe, TInvariant>.InputUnsafe7(IInvariant<TInputUnsafe>)", "TInputUnsafe", "covariant", "invariantly").WithLocation(27, 23), // (28,23): error CS1961: Invalid variance: The type parameter 'TOutputUnsafe' must be invariantly valid on 'IInputUnsafeTable<TInputUnsafe, TOutputUnsafe, TInvariant>.InputUnsafe8(IInvariant<TOutputUnsafe>)'. 'TOutputUnsafe' is contravariant. // void InputUnsafe8(IInvariant<TOutputUnsafe> p); Diagnostic(ErrorCode.ERR_UnexpectedVariance, "IInvariant<TOutputUnsafe>").WithArguments("IInputUnsafeTable<TInputUnsafe, TOutputUnsafe, TInvariant>.InputUnsafe8(IInvariant<TOutputUnsafe>)", "TOutputUnsafe", "contravariant", "invariantly").WithLocation(28, 23), // Dev10 doesn't say "must be invariantly valid" for ref params - it lists whichever check fails first. This approach seems nicer. // (34,27): error CS1961: Invalid variance: The type parameter 'TInputUnsafe' must be invariantly valid on 'IBothUnsafeTable<TInputUnsafe, TOutputUnsafe, TInvariant>.InputUnsafe1(ref ICovariant<TInputUnsafe>)'. 'TInputUnsafe' is covariant. // void InputUnsafe1(ref ICovariant<TInputUnsafe> p); Diagnostic(ErrorCode.ERR_UnexpectedVariance, "ICovariant<TInputUnsafe>").WithArguments("IBothUnsafeTable<TInputUnsafe, TOutputUnsafe, TInvariant>.InputUnsafe1(ref ICovariant<TInputUnsafe>)", "TInputUnsafe", "covariant", "invariantly").WithLocation(34, 27), // (35,27): error CS1961: Invalid variance: The type parameter 'TOutputUnsafe' must be invariantly valid on 'IBothUnsafeTable<TInputUnsafe, TOutputUnsafe, TInvariant>.InputUnsafe2(ref ICovariant<TOutputUnsafe>)'. 'TOutputUnsafe' is contravariant. // void InputUnsafe2(ref ICovariant<TOutputUnsafe> p); Diagnostic(ErrorCode.ERR_UnexpectedVariance, "ICovariant<TOutputUnsafe>").WithArguments("IBothUnsafeTable<TInputUnsafe, TOutputUnsafe, TInvariant>.InputUnsafe2(ref ICovariant<TOutputUnsafe>)", "TOutputUnsafe", "contravariant", "invariantly").WithLocation(35, 27), // (38,27): error CS1961: Invalid variance: The type parameter 'TInputUnsafe' must be invariantly valid on 'IBothUnsafeTable<TInputUnsafe, TOutputUnsafe, TInvariant>.InputUnsafe4(ref IContravariant<TInputUnsafe>)'. 'TInputUnsafe' is covariant. // void InputUnsafe4(ref IContravariant<TInputUnsafe> p); Diagnostic(ErrorCode.ERR_UnexpectedVariance, "IContravariant<TInputUnsafe>").WithArguments("IBothUnsafeTable<TInputUnsafe, TOutputUnsafe, TInvariant>.InputUnsafe4(ref IContravariant<TInputUnsafe>)", "TInputUnsafe", "covariant", "invariantly").WithLocation(38, 27), // (39,27): error CS1961: Invalid variance: The type parameter 'TOutputUnsafe' must be invariantly valid on 'IBothUnsafeTable<TInputUnsafe, TOutputUnsafe, TInvariant>.InputUnsafe5(ref IContravariant<TOutputUnsafe>)'. 'TOutputUnsafe' is contravariant. // void InputUnsafe5(ref IContravariant<TOutputUnsafe> p); Diagnostic(ErrorCode.ERR_UnexpectedVariance, "IContravariant<TOutputUnsafe>").WithArguments("IBothUnsafeTable<TInputUnsafe, TOutputUnsafe, TInvariant>.InputUnsafe5(ref IContravariant<TOutputUnsafe>)", "TOutputUnsafe", "contravariant", "invariantly").WithLocation(39, 27), // (42,27): error CS1961: Invalid variance: The type parameter 'TInputUnsafe' must be invariantly valid on 'IBothUnsafeTable<TInputUnsafe, TOutputUnsafe, TInvariant>.InputUnsafe7(ref IInvariant<TInputUnsafe>)'. 'TInputUnsafe' is covariant. // void InputUnsafe7(ref IInvariant<TInputUnsafe> p); Diagnostic(ErrorCode.ERR_UnexpectedVariance, "IInvariant<TInputUnsafe>").WithArguments("IBothUnsafeTable<TInputUnsafe, TOutputUnsafe, TInvariant>.InputUnsafe7(ref IInvariant<TInputUnsafe>)", "TInputUnsafe", "covariant", "invariantly").WithLocation(42, 27), // (43,27): error CS1961: Invalid variance: The type parameter 'TOutputUnsafe' must be invariantly valid on 'IBothUnsafeTable<TInputUnsafe, TOutputUnsafe, TInvariant>.InputUnsafe8(ref IInvariant<TOutputUnsafe>)'. 'TOutputUnsafe' is contravariant. // void InputUnsafe8(ref IInvariant<TOutputUnsafe> p); Diagnostic(ErrorCode.ERR_UnexpectedVariance, "IInvariant<TOutputUnsafe>").WithArguments("IBothUnsafeTable<TInputUnsafe, TOutputUnsafe, TInvariant>.InputUnsafe8(ref IInvariant<TOutputUnsafe>)", "TOutputUnsafe", "contravariant", "invariantly").WithLocation(43, 27)); } [Fact] public void CS1961ERR_UnexpectedVariance_DelegateInvoke() { var text = @" delegate TIn D1<in TIn>(); //CS1961 delegate TOut D2<out TOut>(); delegate T D3<T>(); delegate void D4<in TIn>(TIn p); delegate void D5<out TOut>(TOut p); //CS1961 delegate void D6<T>(T p); delegate void D7<in TIn>(ref TIn p); //CS1961 delegate void D8<out TOut>(ref TOut p); //CS1961 delegate void D9<T>(ref T p); delegate void D10<in TIn>(out TIn p); //CS1961 delegate void D11<out TOut>(out TOut p); //CS1961 delegate void D12<T>(out T p); "; CreateCompilation(text).VerifyDiagnostics( // (2,20): error CS1961: Invalid variance: The type parameter 'TIn' must be covariantly valid on 'D1<TIn>.Invoke()'. 'TIn' is contravariant. Diagnostic(ErrorCode.ERR_UnexpectedVariance, "TIn").WithArguments("D1<TIn>.Invoke()", "TIn", "contravariant", "covariantly"), // (7,22): error CS1961: Invalid variance: The type parameter 'TOut' must be contravariantly valid on 'D5<TOut>.Invoke(TOut)'. 'TOut' is covariant. Diagnostic(ErrorCode.ERR_UnexpectedVariance, "TOut").WithArguments("D5<TOut>.Invoke(TOut)", "TOut", "covariant", "contravariantly"), // (10,21): error CS1961: Invalid variance: The type parameter 'TIn' must be invariantly valid on 'D7<TIn>.Invoke(ref TIn)'. 'TIn' is contravariant. Diagnostic(ErrorCode.ERR_UnexpectedVariance, "TIn").WithArguments("D7<TIn>.Invoke(ref TIn)", "TIn", "contravariant", "invariantly"), // (11,22): error CS1961: Invalid variance: The type parameter 'TOut' must be invariantly valid on 'D8<TOut>.Invoke(ref TOut)'. 'TOut' is covariant. Diagnostic(ErrorCode.ERR_UnexpectedVariance, "TOut").WithArguments("D8<TOut>.Invoke(ref TOut)", "TOut", "covariant", "invariantly"), // (14,22): error CS1961: Invalid variance: The type parameter 'TIn' must be invariantly valid on 'D10<TIn>.Invoke(out TIn)'. 'TIn' is contravariant. Diagnostic(ErrorCode.ERR_UnexpectedVariance, "TIn").WithArguments("D10<TIn>.Invoke(out TIn)", "TIn", "contravariant", "invariantly"), // (15,23): error CS1961: Invalid variance: The type parameter 'TOut' must be invariantly valid on 'D11<TOut>.Invoke(out TOut)'. 'TOut' is covariant. Diagnostic(ErrorCode.ERR_UnexpectedVariance, "TOut").WithArguments("D11<TOut>.Invoke(out TOut)", "TOut", "covariant", "invariantly")); } [Fact] public void CS1962ERR_BadDynamicTypeof() { var text = @" public class C { public static int Main() { dynamic S = typeof(dynamic); return 0; } public static int Test(int age) { return 1; } }"; CreateCompilation(text).VerifyDiagnostics( // (6,25): error CS1962: The typeof operator cannot be used on the dynamic type Diagnostic(ErrorCode.ERR_BadDynamicTypeof, "typeof(dynamic)")); } // CS1963ERR_ExpressionTreeContainsDynamicOperation --> SyntaxBinderTests [Fact] public void CS1964ERR_BadDynamicConversion() { var text = @" class A { public static implicit operator dynamic(A a) { return a; } public static implicit operator A(dynamic a) { return a; } } "; CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics( // (9,37): error CS1964: 'A.implicit operator A(dynamic)': user-defined conversions to or from the dynamic type are not allowed Diagnostic(ErrorCode.ERR_BadDynamicConversion, "A").WithArguments("A.implicit operator A(dynamic)"), // (4,37): error CS1964: 'A.implicit operator dynamic(A)': user-defined conversions to or from the dynamic type are not allowed Diagnostic(ErrorCode.ERR_BadDynamicConversion, "dynamic").WithArguments("A.implicit operator dynamic(A)")); } // CS1969ERR_DynamicRequiredTypesMissing -> CodeGen_DynamicTests.Missing_* // CS1970ERR_ExplicitDynamicAttr --> AttributeTests_Dynamic.ExplicitDynamicAttribute [Fact] public void CS1971ERR_NoDynamicPhantomOnBase() { const string text = @" public class B { public virtual void M(object o) {} } public class D : B { public override void M(object o) {} void N(dynamic d) { base.M(d); } } "; var comp = CreateCompilationWithMscorlib40AndSystemCore(text); comp.VerifyDiagnostics( // (12,9): error CS1971: The call to method 'M' needs to be dynamically dispatched, but cannot be because it is part of a base access expression. Consider casting the dynamic arguments or eliminating the base access. // base.M(d); Diagnostic(ErrorCode.ERR_NoDynamicPhantomOnBase, "base.M(d)").WithArguments("M")); } [Fact] public void CS1972ERR_NoDynamicPhantomOnBaseIndexer() { const string text = @" public class B { public string this[int index] { get { return ""You passed "" + index; } } } public class D : B { public void M(object o) { int[] arr = { 1, 2, 3 }; int s = base[(dynamic)o]; } } "; var comp = CreateCompilationWithMscorlib40AndSystemCore(text); comp.VerifyDiagnostics( // (14,17): error CS1972: The indexer access needs to be dynamically dispatched, but cannot be because it is part of a base access expression. Consider casting the dynamic arguments or eliminating the base access. // int s = base[(dynamic)o]; Diagnostic(ErrorCode.ERR_NoDynamicPhantomOnBaseIndexer, "base[(dynamic)o]")); } [Fact] public void CS1973ERR_BadArgTypeDynamicExtension() { const string text = @" class Program { static void Main() { dynamic d = 1; B b = new B(); b.Goo(d); } } public class B { } static public class Extension { public static void Goo(this B b, int x) { } }"; var comp = CreateCompilationWithMscorlib40AndSystemCore(text); comp.VerifyDiagnostics( // (8,9): error CS1973: 'B' has no applicable method named 'Goo' but appears to have an extension method by that name. Extension methods cannot be dynamically dispatched. Consider casting the dynamic arguments or calling the extension method without the extension method syntax. // b.Goo(d); Diagnostic(ErrorCode.ERR_BadArgTypeDynamicExtension, "b.Goo(d)").WithArguments("B", "Goo")); } [Fact] public void CS1975ERR_NoDynamicPhantomOnBaseCtor_Base() { var text = @" class A { public A(int x) { } } class B : A { public B(dynamic d) : base(d) { } } "; CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics( // (12,9): error CS1975: The constructor call needs to be dynamically dispatched, but cannot be because it is part of a constructor initializer. Consider casting the dynamic arguments. Diagnostic(ErrorCode.ERR_NoDynamicPhantomOnBaseCtor, "base")); } [Fact] public void CS1975ERR_NoDynamicPhantomOnBaseCtor_This() { var text = @" class B { public B(dynamic d) : this(d, 1) { } public B(int a, int b) { } } "; CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics( // (12,9): error CS1975: The constructor call needs to be dynamically dispatched, but cannot be because it is part of a constructor initializer. Consider casting the dynamic arguments. Diagnostic(ErrorCode.ERR_NoDynamicPhantomOnBaseCtor, "this")); } [Fact] public void CS1976ERR_BadDynamicMethodArgMemgrp() { const string text = @" class Program { static void M(dynamic d) { d.Goo(M); } }"; var comp = CreateCompilationWithMscorlib40AndSystemCore(text); comp.VerifyDiagnostics( // (6,15): error CS1976: Cannot use a method group as an argument to a dynamically dispatched operation. Did you intend to invoke the method? // d.Goo(M); Diagnostic(ErrorCode.ERR_BadDynamicMethodArgMemgrp, "M")); } [Fact] public void CS1977ERR_BadDynamicMethodArgLambda() { const string text = @" class Program { static void M(dynamic d) { d.Goo(()=>{}); d.Goo(delegate () {}); } }"; var comp = CreateCompilationWithMscorlib40AndSystemCore(text); comp.VerifyDiagnostics( // (6,15): 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. // d.Goo(()=>{}); Diagnostic(ErrorCode.ERR_BadDynamicMethodArgLambda, "()=>{}"), // (7,15): 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. // d.Goo(delegate () {}); Diagnostic(ErrorCode.ERR_BadDynamicMethodArgLambda, "delegate () {}")); } [Fact, WorkItem(578352, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/578352")] public void CS1977ERR_BadDynamicMethodArgLambda_CreateObject() { string source = @" using System; class C { static void Main() { dynamic y = null; new C(delegate { }, y); } public C(Action a, Action y) { } }"; var comp = CreateCompilationWithMscorlib40AndSystemCore(source, new[] { CSharpRef }); comp.VerifyDiagnostics( // (9,15): 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, "delegate { }")); } [Fact] public void CS1660ERR_BadDynamicMethodArgLambda_CollectionInitializer() { string source = @" using System; using System.Collections; using System.Collections.Generic; unsafe class C : IEnumerable<object> { public static void M(__arglist) { int a; int* p = &a; dynamic d = null; var c = new C { { d, delegate() { } }, { d, 1, p }, { d, __arglist }, { d, GetEnumerator }, { d, SomeStaticMethod }, }; } public static void SomeStaticMethod() {} public void Add(dynamic d, int x, int* ptr) { } public void Add(dynamic d, RuntimeArgumentHandle x) { } public void Add(dynamic d, Action f) { } public void Add(dynamic d, Func<IEnumerator<object>> f) { } public IEnumerator<object> GetEnumerator() { return null; } IEnumerator IEnumerable.GetEnumerator() { return null; } }"; var comp = CreateCompilationWithMscorlib40AndSystemCore(source, new[] { CSharpRef }, options: TestOptions.UnsafeReleaseDll); comp.VerifyDiagnostics( // (16,18): 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. // { d, delegate() { } }, Diagnostic(ErrorCode.ERR_BadDynamicMethodArgLambda, "delegate() { }").WithLocation(16, 18), // (17,21): error CS1978: Cannot use an expression of type 'int*' as an argument to a dynamically dispatched operation. // { d, 1, p }, Diagnostic(ErrorCode.ERR_BadDynamicMethodArg, "p").WithArguments("int*").WithLocation(17, 21), // (18,18): error CS1978: Cannot use an expression of type 'RuntimeArgumentHandle' as an argument to a dynamically dispatched operation. // { d, __arglist }, Diagnostic(ErrorCode.ERR_BadDynamicMethodArg, "__arglist").WithArguments("System.RuntimeArgumentHandle").WithLocation(18, 18), // (19,13): error CS1950: The best overloaded Add method 'C.Add(dynamic, RuntimeArgumentHandle)' for the collection initializer has some invalid arguments // { d, GetEnumerator }, Diagnostic(ErrorCode.ERR_BadArgTypesForCollectionAdd, "{ d, GetEnumerator }").WithArguments("C.Add(dynamic, System.RuntimeArgumentHandle)").WithLocation(19, 13), // (19,18): error CS1503: Argument 2: cannot convert from 'method group' to 'RuntimeArgumentHandle' // { d, GetEnumerator }, Diagnostic(ErrorCode.ERR_BadArgType, "GetEnumerator").WithArguments("2", "method group", "System.RuntimeArgumentHandle").WithLocation(19, 18), // (20,18): error CS1976: Cannot use a method group as an argument to a dynamically dispatched operation. Did you intend to invoke the method? // { d, SomeStaticMethod }, Diagnostic(ErrorCode.ERR_BadDynamicMethodArgMemgrp, "SomeStaticMethod").WithLocation(20, 18)); } [Fact] public void CS1978ERR_BadDynamicMethodArg() { // The dev 10 compiler gives arguably wrong error here; it says that "TypedReference may not be // used as a type argument". Though that is true, and though what is happening here behind the scenes // is that TypedReference is being used as a type argument to a dynamic call site helper method, // that's giving an error about an implementation detail. A better error is to say that // TypedReference is not a legal type in a dynamic operation. // // Dev10 compiler didn't report an error for by-ref pointer argument. See Dev10 bug 819498. // The error should be reported for any pointer argument regardless of its refness. const string text = @" class Program { unsafe static void M(dynamic d, int* i, System.TypedReference tr) { d.Goo(i); d.Goo(tr); d.Goo(ref tr); d.Goo(out tr); d.Goo(out i); d.Goo(ref i); } } "; var comp = CreateCompilationWithMscorlib40AndSystemCore(text, options: TestOptions.UnsafeReleaseDll); comp.VerifyDiagnostics( // (6,15): error CS1978: Cannot use an expression of type 'int*' as an argument to a dynamically dispatched operation. Diagnostic(ErrorCode.ERR_BadDynamicMethodArg, "i").WithArguments("int*"), // (7,15): error CS1978: Cannot use an expression of type 'System.TypedReference' as an argument to a dynamically dispatched operation. Diagnostic(ErrorCode.ERR_BadDynamicMethodArg, "tr").WithArguments("System.TypedReference"), // (8,19): error CS1978: Cannot use an expression of type 'System.TypedReference' as an argument to a dynamically dispatched operation. Diagnostic(ErrorCode.ERR_BadDynamicMethodArg, "tr").WithArguments("System.TypedReference"), // (9,19): error CS1978: Cannot use an expression of type 'System.TypedReference' as an argument to a dynamically dispatched operation. Diagnostic(ErrorCode.ERR_BadDynamicMethodArg, "tr").WithArguments("System.TypedReference"), // (10,19): error CS1978: Cannot use an expression of type 'int*' as an argument to a dynamically dispatched operation. Diagnostic(ErrorCode.ERR_BadDynamicMethodArg, "i").WithArguments("int*"), // (11,19): error CS1978: Cannot use an expression of type 'int*' as an argument to a dynamically dispatched operation. Diagnostic(ErrorCode.ERR_BadDynamicMethodArg, "i").WithArguments("int*")); } // CS1979ERR_BadDynamicQuery --> DynamicTests.cs, DynamicQuery_* // Test CS1980ERR_DynamicAttributeMissing moved to AttributeTests_Dynamic.cs // CS1763 is covered for different code path by SymbolErrorTests.CS1763ERR_NotNullRefDefaultParameter() [WorkItem(528854, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528854")] [Fact] public void CS1763ERR_NotNullRefDefaultParameter02() { string text = @" class Program { public void Goo<T, U>(T t = default(U)) where U : T { } static void Main(string[] args) { } }"; CreateCompilation(text).VerifyDiagnostics( // (4,29): error CS1763: 't' is of type 'T'. A default parameter value of a reference type other than string can only be initialized with null // public void Goo<T, U>(T t = default(U)) where U : T Diagnostic(ErrorCode.ERR_NotNullRefDefaultParameter, "t").WithArguments("t", "T")); } #endregion #region "Targeted Warning Tests - please arrange tests in the order of error code" [Fact, WorkItem(542396, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542396"), WorkItem(546817, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546817")] public void CS0067WRN_UnreferencedEvent() { var text = @" delegate void MyDelegate(); class MyClass { public event MyDelegate evt; // CS0067 public static void Main() { } } "; CreateCompilation(text).VerifyDiagnostics( // (5,29): warning CS0067: The event 'MyClass.evt' is never used // public event MyDelegate evt; // CS0067 Diagnostic(ErrorCode.WRN_UnreferencedEvent, "evt").WithArguments("MyClass.evt")); } [Fact, WorkItem(542396, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542396"), WorkItem(546817, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546817")] public void CS0067WRN_UnreferencedEvent_Accessibility() { var text = @" using System; class MyClass { public event Action E1; // CS0067 internal event Action E2; // CS0067 protected internal event Action E3; // CS0067 protected event Action E4; // CS0067 private event Action E5; // CS0067 } "; CreateCompilation(text).VerifyDiagnostics( // (5,25): warning CS0067: The event 'MyClass.E1' is never used // public event Action E1; // CS0067 Diagnostic(ErrorCode.WRN_UnreferencedEvent, "E1").WithArguments("MyClass.E1"), // (6,27): warning CS0067: The event 'MyClass.E2' is never used // internal event Action E2; // CS0067 Diagnostic(ErrorCode.WRN_UnreferencedEvent, "E2").WithArguments("MyClass.E2"), // (7,37): warning CS0067: The event 'MyClass.E3' is never used // protected internal event Action E3; // CS0067 Diagnostic(ErrorCode.WRN_UnreferencedEvent, "E3").WithArguments("MyClass.E3"), // (8,28): warning CS0067: The event 'MyClass.E4' is never used // protected event Action E4; // CS0067 Diagnostic(ErrorCode.WRN_UnreferencedEvent, "E4").WithArguments("MyClass.E4"), // (9,26): warning CS0067: The event 'MyClass.E5' is never used // private event Action E5; // CS0067 Diagnostic(ErrorCode.WRN_UnreferencedEvent, "E5").WithArguments("MyClass.E5")); } [Fact, WorkItem(542396, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542396"), WorkItem(546817, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546817")] public void CS0067WRN_UnreferencedEvent_StructLayout() { var text = @" using System; using System.Runtime.InteropServices; [StructLayout(LayoutKind.Sequential)] struct S { event Action E1; } "; CreateCompilation(text).VerifyDiagnostics(); } [Fact, WorkItem(542396, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542396"), WorkItem(546817, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546817")] public void CS0067WRN_UnreferencedEvent_Kind() { var text = @" using System; class C { event Action E1; // CS0067 event Action E2 { add { } remove { } } } "; CreateCompilation(text).VerifyDiagnostics( // (6,18): warning CS0067: The event 'C.E1' is never used // event Action E1; // CS0067 Diagnostic(ErrorCode.WRN_UnreferencedEvent, "E1").WithArguments("C.E1")); } [Fact, WorkItem(542396, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542396"), WorkItem(546817, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546817")] public void CS0067WRN_UnreferencedEvent_Accessed() { var text = @" using System; class C { event Action None; // CS0067 event Action Read; event Action Write; event Action Add; // CS0067 void M(Action a) { M(Read); Write = a; Add += a; } } "; CreateCompilation(text).VerifyDiagnostics( // (9,18): warning CS0067: The event 'C.Add' is never used // event Action Add; // CS0067 Diagnostic(ErrorCode.WRN_UnreferencedEvent, "Add").WithArguments("C.Add"), // (6,18): warning CS0067: The event 'C.None' is never used // event Action None; // CS0067 Diagnostic(ErrorCode.WRN_UnreferencedEvent, "None").WithArguments("C.None")); } [Fact, WorkItem(581002, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/581002")] public void CS0067WRN_UnreferencedEvent_Virtual() { var text = @"class A { public virtual event System.EventHandler B; class C : A { public override event System.EventHandler B; } static int Main() { C c = new C(); A a = c; return 0; } } "; CreateCompilation(text).VerifyDiagnostics( // (3,46): warning CS0067: The event 'A.B' is never used // public virtual event System.EventHandler B; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "B").WithArguments("A.B"), // (6,51): warning CS0067: The event 'A.C.B' is never used // public override event System.EventHandler B; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "B").WithArguments("A.C.B")); } [Fact, WorkItem(539630, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539630")] public void CS0162WRN_UnreachableCode01() { var text = @" class MyTest { } class MyClass { const MyTest test = null; public static int Main() { goto lab1; { // The following statements cannot be reached: int i = 9; // CS0162 i++; } lab1: if (test == null) { return 0; } else { return 1; // CS0162 } } } "; CreateCompilation(text).VerifyDiagnostics( Diagnostic(ErrorCode.WRN_UnreachableCode, "int"), Diagnostic(ErrorCode.WRN_UnreachableCode, "return")); } [Fact, WorkItem(530037, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530037")] public void CS0162WRN_UnreachableCode02() { var text = @" using System; public class Test { public static void Main(string[] args) { // (1) do { for (; ; ) { } } while (args.Length > 0); // Native CS0162 // (2) for (; ; ) // Roslyn CS0162 { goto L2; Console.WriteLine(""Unreachable code""); L2: // Roslyn CS0162 break; } } } "; CreateCompilation(text).VerifyDiagnostics( // (14,5): warning CS0162: Unreachable code detected // for (; ; ) // Roslyn CS0162 Diagnostic(ErrorCode.WRN_UnreachableCode, "for"), // (18,5): warning CS0162: Unreachable code detected // L2: // Roslyn CS0162 Diagnostic(ErrorCode.WRN_UnreachableCode, "L2") ); } [Fact, WorkItem(539873, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539873"), WorkItem(539981, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539981")] public void CS0162WRN_UnreachableCode04() { var text = @" public class Cls { public static int Main() { goto Label2; return 0; Label1: return 1; Label2: goto Label1; return 2; } delegate void Sub_0(); static void M() { Sub_0 s1_3 = () => { if (2 == 1) return; else return; }; } }"; CreateCompilation(text).VerifyDiagnostics( Diagnostic(ErrorCode.WRN_UnreachableCode, "return"), Diagnostic(ErrorCode.WRN_UnreachableCode, "return"), Diagnostic(ErrorCode.WRN_UnreachableCode, "return")); } [Fact, WorkItem(540901, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540901")] public void CS0162WRN_UnreachableCode06_Loops() { var text = @" class Program { void F() { } void T() { for (int i = 0; i < 0; F(), i++) // F() is unreachable { return; } } static void Main() { string[] S = new string[] { ""ABC"", ""XYZ"" }; foreach (string x in S) { foreach (char y in x) { goto stop; System.Console.WriteLine(y); // unreachable } foreach (char y in x) { throw new System.Exception(); System.Console.WriteLine(y); // unreachable } stop: return; } } } "; CreateCompilation(text).VerifyDiagnostics( Diagnostic(ErrorCode.WRN_UnreachableCode, "F"), Diagnostic(ErrorCode.WRN_UnreachableCode, "System"), Diagnostic(ErrorCode.WRN_UnreachableCode, "System")); } [Fact] public void CS0162WRN_UnreachableCode06_Foreach03() { var text = @" public class Test { static public void Main(string[] args) { string[] S = new string[] { ""ABC"", ""XYZ"" }; foreach (string x in S) { foreach (char y in x) { return; System.Console.WriteLine(y); } } } } "; CreateCompilation(text). VerifyDiagnostics(Diagnostic(ErrorCode.WRN_UnreachableCode, "System")); } [Fact] public void CS0162WRN_UnreachableCode07_GotoInLambda() { var text = @" using System; class Program { static void Main() { Action a = () => { goto label1; Console.WriteLine(""unreachable""); label1: Console.WriteLine(""reachable""); }; } } "; CreateCompilation(text). VerifyDiagnostics(Diagnostic(ErrorCode.WRN_UnreachableCode, @"Console")); } [Fact] public void CS0164WRN_UnreferencedLabel() { var text = @" public class a { public int i = 0; public static void Main() { int i = 0; // CS0164 l1: i++; } }"; CreateCompilation(text).VerifyDiagnostics( Diagnostic(ErrorCode.WRN_UnreferencedLabel, "l1").WithLocation(9, 7)); } [Fact] public void CS0168WRN_UnreferencedVar01() { var text = @" public class clx { public int i; } public class clz { public static void Main() { int j ; // CS0168, uncomment the following line // j++; clx a; // CS0168, try the following line instead // clx a = new clx(); } }"; CreateCompilation(text).VerifyDiagnostics( Diagnostic(ErrorCode.WRN_UnreferencedVar, "j").WithArguments("j").WithLocation(11, 13), Diagnostic(ErrorCode.WRN_UnreferencedVar, "a").WithArguments("a").WithLocation(13, 13)); } [Fact] public void CS0168WRN_UnreferencedVar02() { var text = @"using System; class C { static void M() { try { } catch (InvalidOperationException e) { } catch (InvalidCastException e) { throw; } catch (Exception e) { throw e; } } }"; CreateCompilation(text).VerifyDiagnostics( Diagnostic(ErrorCode.WRN_UnreferencedVar, "e").WithArguments("e").WithLocation(7, 42), Diagnostic(ErrorCode.WRN_UnreferencedVar, "e").WithArguments("e").WithLocation(8, 37)); } [Fact] public void CS0169WRN_UnreferencedField() { var text = @" public class ClassX { int i; // CS0169, i is not used anywhere public static void Main() { } }"; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (4,8): warning CS0169: The field 'ClassX.i' is never used // int i; // CS0169, i is not used anywhere Diagnostic(ErrorCode.WRN_UnreferencedField, "i").WithArguments("ClassX.i") ); } [Fact] public void CS0169WRN_UnreferencedField02() { var text = @"[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""OtherAssembly"")] internal class InternalClass { internal int ActuallyInternal; internal int ActuallyInternalAssigned = 0; private int ActuallyPrivate; private int ActuallyPrivateAssigned = 0; public int EffectivelyInternal; public int EffectivelyInternalAssigned = 0; private class PrivateClass { public int EffectivelyPrivate; public int EffectivelyPrivateAssigned = 0; } }"; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (7,17): warning CS0169: The field 'InternalClass.ActuallyPrivate' is never used // private int ActuallyPrivate; Diagnostic(ErrorCode.WRN_UnreferencedField, "ActuallyPrivate").WithArguments("InternalClass.ActuallyPrivate"), // (8,17): warning CS0414: The field 'InternalClass.ActuallyPrivateAssigned' is assigned but its value is never used // private int ActuallyPrivateAssigned = 0; Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "ActuallyPrivateAssigned").WithArguments("InternalClass.ActuallyPrivateAssigned"), // (14,20): warning CS0649: Field 'InternalClass.PrivateClass.EffectivelyPrivate' is never assigned to, and will always have its default value 0 // public int EffectivelyPrivate; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "EffectivelyPrivate").WithArguments("InternalClass.PrivateClass.EffectivelyPrivate", "0") ); } [Fact] public void CS0169WRN_UnreferencedField03() { var text = @"internal class InternalClass { internal int ActuallyInternal; internal int ActuallyInternalAssigned = 0; private int ActuallyPrivate; private int ActuallyPrivateAssigned = 0; public int EffectivelyInternal; public int EffectivelyInternalAssigned = 0; private class PrivateClass { public int EffectivelyPrivate; public int EffectivelyPrivateAssigned = 0; } }"; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (3,18): warning CS0649: Field 'InternalClass.ActuallyInternal' is never assigned to, and will always have its default value 0 // internal int ActuallyInternal; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "ActuallyInternal").WithArguments("InternalClass.ActuallyInternal", "0"), // (5,17): warning CS0169: The field 'InternalClass.ActuallyPrivate' is never used // private int ActuallyPrivate; Diagnostic(ErrorCode.WRN_UnreferencedField, "ActuallyPrivate").WithArguments("InternalClass.ActuallyPrivate"), // (6,17): warning CS0414: The field 'InternalClass.ActuallyPrivateAssigned' is assigned but its value is never used // private int ActuallyPrivateAssigned = 0; Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "ActuallyPrivateAssigned").WithArguments("InternalClass.ActuallyPrivateAssigned"), // (7,16): warning CS0649: Field 'InternalClass.EffectivelyInternal' is never assigned to, and will always have its default value 0 // public int EffectivelyInternal; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "EffectivelyInternal").WithArguments("InternalClass.EffectivelyInternal", "0"), // (12,20): warning CS0649: Field 'InternalClass.PrivateClass.EffectivelyPrivate' is never assigned to, and will always have its default value 0 // public int EffectivelyPrivate; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "EffectivelyPrivate").WithArguments("InternalClass.PrivateClass.EffectivelyPrivate", "0") ); } [Fact] public void CS0183WRN_IsAlwaysTrue() { var text = @"using System; public class IsTest10 { public static int Main(String[] args) { Object obj3 = null; String str2 = ""Is 'is' too strict, per error CS0183?""; obj3 = str2; if (str2 is Object) // no error CS0183 Console.WriteLine(""str2 is Object""); Int32 int2 = 1; if (int2 is Object) // error CS0183 Console.WriteLine(""int2 is Object""); return 0; } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.WRN_IsAlwaysTrue, Line = 14, Column = 13, IsWarning = true }); // TODO: extra checking } // Note: CS0184 tests moved to CodeGenOperator.cs to include IL verification. [WorkItem(530361, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530361")] [Fact] public void CS0197WRN_ByRefNonAgileField() { var text = @" class X : System.MarshalByRefObject { public int i; } class M { public int i; static void AddSeventeen(ref int i) { i += 17; } static void Main() { X x = new X(); x.i = 12; AddSeventeen(ref x.i); // CS0197 // OK M m = new M(); m.i = 12; AddSeventeen(ref m.i); } } "; CreateCompilation(text).VerifyDiagnostics( // (19,24): warning CS0197: Passing 'X.i' as ref or out or taking its address may cause a runtime exception because it is a field of a marshal-by-reference class // AddSeventeen(ref x.i); // CS0197 Diagnostic(ErrorCode.WRN_ByRefNonAgileField, "x.i").WithArguments("X.i")); } [WorkItem(530361, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530361")] [Fact] public void CS0197WRN_ByRefNonAgileField_RefKind() { var text = @" class NotByRef { public int Instance; public static int Static; } class ByRef : System.MarshalByRefObject { public int Instance; public static int Static; } class Test { void M(ByRef b, NotByRef n) { None(n.Instance); Out(out n.Instance); Ref(ref n.Instance); None(NotByRef.Static); Out(out NotByRef.Static); Ref(ref NotByRef.Static); None(b.Instance); Out(out b.Instance); Ref(ref b.Instance); None(ByRef.Static); Out(out ByRef.Static); Ref(ref ByRef.Static); } void None(int x) { throw null; } void Out(out int x) { throw null; } void Ref(ref int x) { throw null; } } "; CreateCompilation(text).VerifyDiagnostics( // (27,17): warning CS0197: Passing 'ByRef.Instance' as ref or out or taking its address may cause a runtime exception because it is a field of a marshal-by-reference class // Out(out b.Instance); Diagnostic(ErrorCode.WRN_ByRefNonAgileField, "b.Instance").WithArguments("ByRef.Instance"), // (28,17): warning CS0197: Passing 'ByRef.Instance' as ref or out or taking its address may cause a runtime exception because it is a field of a marshal-by-reference class // Ref(ref b.Instance); Diagnostic(ErrorCode.WRN_ByRefNonAgileField, "b.Instance").WithArguments("ByRef.Instance")); } [WorkItem(530361, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530361")] [Fact] public void CS0197WRN_ByRefNonAgileField_Receiver() { var text = @" using System; class ByRef : MarshalByRefObject { public int F; protected void Ref(ref int x) { } void Test() { Ref(ref F); Ref(ref this.F); Ref(ref ((ByRef)this).F); } } class Derived : ByRef { void Test() { Ref(ref F); Ref(ref this.F); Ref(ref ((ByRef)this).F); Ref(ref base.F); //Ref(ref ((ByRef)base).F); } } "; CreateCompilation(text).VerifyDiagnostics( // (15,17): warning CS0197: Passing 'ByRef.F' as ref or out or taking its address may cause a runtime exception because it is a field of a marshal-by-reference class // Ref(ref ((ByRef)this).F); Diagnostic(ErrorCode.WRN_ByRefNonAgileField, "((ByRef)this).F").WithArguments("ByRef.F"), // (26,17): warning CS0197: Passing 'ByRef.F' as ref or out or taking its address may cause a runtime exception because it is a field of a marshal-by-reference class // Ref(ref ((ByRef)this).F); Diagnostic(ErrorCode.WRN_ByRefNonAgileField, "((ByRef)this).F").WithArguments("ByRef.F")); } [Fact] public void CS0219WRN_UnreferencedVarAssg01() { var text = @"public class MyClass { public static void Main() { int a = 0; // CS0219 } }"; CreateCompilation(text).VerifyDiagnostics( // (5,13): warning CS0219: The variable 'a' is assigned but its value is never used // int a = 0; // CS0219 Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "a").WithArguments("a") ); } [Fact] public void CS0219WRN_UnreferencedVarAssg02() { var text = @" public class clx { static void Main(string[] args) { int x = 1; } }"; CreateCompilation(text).VerifyDiagnostics( Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x").WithArguments("x").WithLocation(6, 13)); } [Fact] public void CS0219WRN_UnreferencedVarAssg03() { var text = @" public class clx { static void Main(string[] args) { int? x; x = null; } }"; CreateCompilation(text).VerifyDiagnostics( Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x").WithArguments("x").WithLocation(6, 14)); } [Fact, WorkItem(542473, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542473"), WorkItem(542474, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542474")] public void CS0219WRN_UnreferencedVarAssg_StructString() { var text = @" class program { static void Main(string[] args) { s1 y = new s1(); string s = """"; } } struct s1 { } "; CreateCompilation(text).VerifyDiagnostics( // (6,12): warning CS0219: The variable 'y' is assigned but its value is never used // s1 y = new s1(); Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y").WithArguments("y").WithLocation(6, 12), Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "s").WithArguments("s").WithLocation(7, 16) ); } [Fact, WorkItem(542494, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542494")] public void CS0219WRN_UnreferencedVarAssg_Default() { var text = @" class S { public int x = 5; } class C { public static void Main() { var x = default(S); } }"; CreateCompilation(text).VerifyDiagnostics( // (11,13): warning CS0219: The variable 'x' is assigned but its value is never used // var x = default(S); Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x").WithArguments("x").WithLocation(11, 13) ); } [Fact] public void CS0219WRN_UnreferencedVarAssg_For() { var text = @" class C { public static void Main() { for (int i = 1; ; ) { break; } } }"; CreateCompilation(text).VerifyDiagnostics( // (6,18): warning CS0219: The variable 'i' is assigned but its value is never used Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "i").WithArguments("i").WithLocation(6, 18) ); } [Fact, WorkItem(546619, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546619")] public void NoCS0219WRN_UnreferencedVarAssg_ObjectInitializer() { var text = @" struct S { public int X { set {} } } class C { public static void Main() { S s = new S { X = 2 }; // no error - not a constant int? i = new int? { }; // ditto - not the default value (though bitwise equal to it) } }"; CreateCompilation(text).VerifyDiagnostics(); } [Fact, WorkItem(542472, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542472")] public void CS0251WRN_NegativeArrayIndex() { var text = @" class C { static void Main() { int[] a = new int[1]; int[,] b = new int[1, 1]; a[-1] = 1; // CS0251 a[-1, -1] = 1; // Dev10 reports CS0022 and CS0251 (twice), Roslyn reports CS0022 b[-1] = 1; // CS0022 b[-1, -1] = 1; // fine } } "; CreateCompilation(text).VerifyDiagnostics( // (8,11): warning CS0251: Indexing an array with a negative index (array indices always start at zero) Diagnostic(ErrorCode.WRN_NegativeArrayIndex, "-1"), // (9,9): error CS0022: Wrong number of indices inside []; expected '1' Diagnostic(ErrorCode.ERR_BadIndexCount, "a[-1, -1]").WithArguments("1"), // (10,9): error CS0022: Wrong number of indices inside []; expected '2' Diagnostic(ErrorCode.ERR_BadIndexCount, "b[-1]").WithArguments("2")); } [WorkItem(530362, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530362"), WorkItem(670322, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/670322")] [Fact] public void CS0252WRN_BadRefCompareLeft() { var text = @"class MyClass { public static void Main() { string s = ""11""; object o = s + s; bool b = o == s; // CS0252 } }"; CreateCompilation(text).VerifyDiagnostics( // (8,16): warning CS0252: Possible unintended reference comparison; to get a value comparison, cast the left hand side to type 'string' // bool b = o == s; // CS0252 Diagnostic(ErrorCode.WRN_BadRefCompareLeft, "o == s").WithArguments("string") ); } [WorkItem(781070, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/781070")] [Fact] public void CS0252WRN_BadRefCompareLeft_02() { var text = @"using System; public class Symbol { public static bool operator ==(Symbol a, Symbol b) { return ReferenceEquals(a, null) || ReferenceEquals(b, null) || ReferenceEquals(a, b); } public static bool operator !=(Symbol a, Symbol b) { return !(a == b); } public override bool Equals(object obj) { return (obj is Symbol || obj == null) ? this == (Symbol)obj : false; } public override int GetHashCode() { return 0; } } public class MethodSymbol : Symbol { } class Program { static void Main(string[] args) { MethodSymbol a1 = null; MethodSymbol a2 = new MethodSymbol(); // In these cases the programmer explicitly inserted a cast to use object equality instead // of the user-defined equality operator. Since the programmer did this explicitly, in // Roslyn we suppress the diagnostic that was given by the native compiler suggesting casting // the object-typed operand back to type Symbol to get value equality. Console.WriteLine((object)a1 == a2); Console.WriteLine((object)a1 != a2); Console.WriteLine((object)a2 == a1); Console.WriteLine((object)a2 != a1); Console.WriteLine(a1 == (object)a2); Console.WriteLine(a1 != (object)a2); Console.WriteLine(a2 == (object)a1); Console.WriteLine(a2 != (object)a1); } }"; CreateCompilation(text).VerifyDiagnostics(); } [WorkItem(781070, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/781070")] [Fact] public void CS0252WRN_BadRefCompareLeft_03() { var text = @"using System; public class Symbol { public static bool operator ==(Symbol a, Symbol b) { return ReferenceEquals(a, null) || ReferenceEquals(b, null) || ReferenceEquals(a, b); } public static bool operator !=(Symbol a, Symbol b) { return !(a == b); } public override bool Equals(object obj) { return (obj is Symbol || obj == null) ? this == (Symbol)obj : false; } public override int GetHashCode() { return 0; } } public class MethodSymbol : Symbol { } class Program { static void Main(string[] args) { Object a1 = null; MethodSymbol a2 = new MethodSymbol(); Console.WriteLine(a1 == a2); Console.WriteLine(a1 != a2); Console.WriteLine(a2 == a1); Console.WriteLine(a2 != a1); } }"; CreateCompilation(text).VerifyDiagnostics( // (34,27): warning CS0252: Possible unintended reference comparison; to get a value comparison, cast the left hand side to type 'Symbol' // Console.WriteLine(a1 == a2); Diagnostic(ErrorCode.WRN_BadRefCompareLeft, "a1 == a2").WithArguments("Symbol"), // (35,27): warning CS0252: Possible unintended reference comparison; to get a value comparison, cast the left hand side to type 'Symbol' // Console.WriteLine(a1 != a2); Diagnostic(ErrorCode.WRN_BadRefCompareLeft, "a1 != a2").WithArguments("Symbol"), // (36,27): warning CS0253: Possible unintended reference comparison; to get a value comparison, cast the right hand side to type 'Symbol' // Console.WriteLine(a2 == a1); Diagnostic(ErrorCode.WRN_BadRefCompareRight, "a2 == a1").WithArguments("Symbol"), // (37,27): warning CS0253: Possible unintended reference comparison; to get a value comparison, cast the right hand side to type 'Symbol' // Console.WriteLine(a2 != a1); Diagnostic(ErrorCode.WRN_BadRefCompareRight, "a2 != a1").WithArguments("Symbol") ); } [WorkItem(530362, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530362"), WorkItem(670322, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/670322")] [Fact] public void CS0253WRN_BadRefCompareRight() { var text = @" class MyClass { public static void Main() { string s = ""11""; object o = s + s; bool c = s == o; // CS0253 // try the following line instead // bool c = s == (string)o; } }"; CreateCompilation(text).VerifyDiagnostics( // (9,16): warning CS0253: Possible unintended reference comparison; to get a value comparison, cast the right hand side to type 'string' // bool c = s == o; // CS0253 Diagnostic(ErrorCode.WRN_BadRefCompareRight, "s == o").WithArguments("string") ); } [WorkItem(730177, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/730177")] [Fact] public void CS0253WRN_BadRefCompare_None() { var text = @"using System; class MyClass { public static void Main() { MulticastDelegate x1 = null; bool b1 = x1 == null; bool b2 = x1 != null; bool b3 = null == x1; bool b4 = null != x1; } }"; CreateCompilation(text).VerifyDiagnostics(); } [WorkItem(542399, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542399")] [Fact] public void CS0278WRN_PatternIsAmbiguous01() { var text = @" using System.Collections.Generic; public class myTest { public static void TestForeach<W>(W w) where W: IEnumerable<int>, IEnumerable<string> { foreach (int i in w) {} // CS0278 } } "; CreateCompilation(text).VerifyDiagnostics( // (8,25): warning CS0278: 'W' does not implement the 'collection' pattern. 'System.Collections.Generic.IEnumerable<int>.GetEnumerator()' is ambiguous with 'System.Collections.Generic.IEnumerable<string>.GetEnumerator()'. // foreach (int i in w) {} // CS0278 Diagnostic(ErrorCode.WRN_PatternIsAmbiguous, "w").WithArguments("W", "collection", "System.Collections.Generic.IEnumerable<int>.GetEnumerator()", "System.Collections.Generic.IEnumerable<string>.GetEnumerator()"), // (8,25): error CS1640: foreach statement cannot operate on variables of type 'W' because it implements multiple instantiations of 'System.Collections.Generic.IEnumerable<T>'; try casting to a specific interface instantiation // foreach (int i in w) {} // CS0278 Diagnostic(ErrorCode.ERR_MultipleIEnumOfT, "w").WithArguments("W", "System.Collections.Generic.IEnumerable<T>")); } [Fact] public void CS0278WRN_PatternIsAmbiguous02() { var text = @"using System.Collections; using System.Collections.Generic; class A : IEnumerable<A> { public IEnumerator<A> GetEnumerator() { return null; } IEnumerator IEnumerable.GetEnumerator() { return null; } } class B : IEnumerable<B> { IEnumerator<B> IEnumerable<B>.GetEnumerator() { return null; } IEnumerator IEnumerable.GetEnumerator() { return null; } } class C : IEnumerable<C>, IEnumerable<string> { public IEnumerator<C> GetEnumerator() { return null; } IEnumerator<string> IEnumerable<string>.GetEnumerator() { return null; } IEnumerator IEnumerable.GetEnumerator() { return null; } } class D : IEnumerable<D>, IEnumerable<string> { IEnumerator<D> IEnumerable<D>.GetEnumerator() { return null; } IEnumerator<string> IEnumerable<string>.GetEnumerator() { return null; } IEnumerator IEnumerable.GetEnumerator() { return null; } } class E { static void M<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10>(T1 t1, T2 t2, T3 t3, T4 t4, T5 t5, T6 t6, T7 t7, T8 t8, T9 t9, T10 t10) where T1 : A, IEnumerable<A> // duplicate interfaces where T2 : B, IEnumerable<B> // duplicate interfaces where T3 : A, IEnumerable<string>, IEnumerable<int> // multiple interfaces where T4 : B, IEnumerable<string>, IEnumerable<int> // multiple interfaces where T5 : C, IEnumerable<int> // multiple interfaces where T6 : D, IEnumerable<int> // multiple interfaces where T7 : A, IEnumerable<string>, IEnumerable<A> // duplicate and multiple interfaces where T8 : B, IEnumerable<string>, IEnumerable<B> // duplicate and multiple interfaces where T9 : C, IEnumerable<C> // duplicate and multiple interfaces where T10 : D, IEnumerable<D> // duplicate and multiple interfaces { foreach (A o in t1) { } foreach (B o in t2) { } foreach (A o in t3) { } foreach (var o in t4) { } foreach (C o in t5) { } foreach (int o in t6) { } foreach (A o in t7) { } foreach (var o in t8) { } foreach (C o in t9) { } foreach (D o in t10) { } } }"; CreateCompilation(text).VerifyDiagnostics( // (42,27): warning CS0278: 'T4' does not implement the 'collection' pattern. 'System.Collections.Generic.IEnumerable<string>.GetEnumerator()' is ambiguous with 'System.Collections.Generic.IEnumerable<int>.GetEnumerator()'. Diagnostic(ErrorCode.WRN_PatternIsAmbiguous, "t4").WithArguments("T4", "collection", "System.Collections.Generic.IEnumerable<string>.GetEnumerator()", "System.Collections.Generic.IEnumerable<int>.GetEnumerator()").WithLocation(42, 27), // (42,27): error CS1640: foreach statement cannot operate on variables of type 'T4' because it implements multiple instantiations of 'System.Collections.Generic.IEnumerable<T>'; try casting to a specific interface instantiation Diagnostic(ErrorCode.ERR_MultipleIEnumOfT, "t4").WithArguments("T4", "System.Collections.Generic.IEnumerable<T>").WithLocation(42, 27), // (46,27): warning CS0278: 'T8' does not implement the 'collection' pattern. 'System.Collections.Generic.IEnumerable<string>.GetEnumerator()' is ambiguous with 'System.Collections.Generic.IEnumerable<B>.GetEnumerator()'. Diagnostic(ErrorCode.WRN_PatternIsAmbiguous, "t8").WithArguments("T8", "collection", "System.Collections.Generic.IEnumerable<string>.GetEnumerator()", "System.Collections.Generic.IEnumerable<B>.GetEnumerator()").WithLocation(46, 27), // (46,27): error CS1640: foreach statement cannot operate on variables of type 'T8' because it implements multiple instantiations of 'System.Collections.Generic.IEnumerable<T>'; try casting to a specific interface instantiation Diagnostic(ErrorCode.ERR_MultipleIEnumOfT, "t8").WithArguments("T8", "System.Collections.Generic.IEnumerable<T>").WithLocation(46, 27)); } [Fact] public void CS0279WRN_PatternStaticOrInaccessible() { var text = @" using System.Collections; public class myTest : IEnumerable { IEnumerator IEnumerable.GetEnumerator() { return null; } internal IEnumerator GetEnumerator() { return null; } public static void Main() { foreach (int i in new myTest()) {} // CS0279 } } "; CreateCompilation(text).VerifyDiagnostics( // (18,27): warning CS0279: 'myTest' does not implement the 'collection' pattern. 'myTest.GetEnumerator()' is not a public instance or extension method. Diagnostic(ErrorCode.WRN_PatternNotPublicOrNotInstance, "new myTest()").WithArguments("myTest", "collection", "myTest.GetEnumerator()")); } [Fact] public void CS0280WRN_PatternBadSignature() { var text = @" using System.Collections; public class ValidBase: IEnumerable { IEnumerator IEnumerable.GetEnumerator() { return null; } internal IEnumerator GetEnumerator() { return null; } } class Derived : ValidBase { // field, not method new public int GetEnumerator; } public class Test { public static void Main() { foreach (int i in new Derived()) {} // CS0280 } } "; CreateCompilation(text).VerifyDiagnostics( // (27,25): warning CS0280: 'Derived' does not implement the 'collection' pattern. 'Derived.GetEnumerator' has the wrong signature. // foreach (int i in new Derived()) {} // CS0280 Diagnostic(ErrorCode.WRN_PatternBadSignature, "new Derived()").WithArguments("Derived", "collection", "Derived.GetEnumerator"), // (20,19): warning CS0649: Field 'Derived.GetEnumerator' is never assigned to, and will always have its default value 0 // new public int GetEnumerator; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "GetEnumerator").WithArguments("Derived.GetEnumerator", "0") ); } [Fact] public void CS0414WRN_UnreferencedFieldAssg() { var text = @" class C { private int i = 1; // CS0414 public static void Main() { } } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (4,16): warning CS0414: The field 'C.i' is assigned but its value is never used // private int i = 1; // CS0414 Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "i").WithArguments("C.i") ); } [Fact] public void CS0414WRN_UnreferencedFieldAssg02() { var text = @"class S<T1, T2> { T1 t1_field = default(T1); }"; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (3,8): warning CS0414: The field 'S<T1, T2>.t1_field' is assigned but its value is never used // T1 t1_field = default(T1); Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "t1_field").WithArguments("S<T1, T2>.t1_field").WithLocation(3, 8) ); } [Fact] public void CS0419WRN_AmbiguousXMLReference() { var text = @" interface I { void F(); void F(int i); } public class MyClass { /// <see cref=""I.F""/> public static void MyMethod(int i) { } public static void Main () { } } "; CreateCompilationWithMscorlib40AndDocumentationComments(text).VerifyDiagnostics( // (7,14): warning CS1591: Missing XML comment for publicly visible type or member 'MyClass' // public class MyClass Diagnostic(ErrorCode.WRN_MissingXMLComment, "MyClass").WithArguments("MyClass"), // (9,19): warning CS0419: Ambiguous reference in cref attribute: 'I.F'. Assuming 'I.F()', but could have also matched other overloads including 'I.F(int)'. // /// <see cref="I.F"/> Diagnostic(ErrorCode.WRN_AmbiguousXMLReference, "I.F").WithArguments("I.F", "I.F()", "I.F(int)"), // (13,23): warning CS1591: Missing XML comment for publicly visible type or member 'MyClass.Main()' // public static void Main () Diagnostic(ErrorCode.WRN_MissingXMLComment, "Main").WithArguments("MyClass.Main()")); } [Fact] public void CS0420WRN_VolatileByRef() { var text = @" class TestClass { private volatile int i; public void TestVolatileRef(ref int ii) { } public void TestVolatileOut(out int ii) { ii = 0; } public static void Main() { TestClass x = new TestClass(); x.TestVolatileRef(ref x.i); // CS0420 x.TestVolatileOut(out x.i); // CS0420 } } "; CreateCompilation(text).VerifyDiagnostics( // (18,29): warning CS0420: 'TestClass.i': a reference to a volatile field will not be treated as volatile Diagnostic(ErrorCode.WRN_VolatileByRef, "x.i").WithArguments("TestClass.i"), // (19,29): warning CS0420: 'TestClass.i': a reference to a volatile field will not be treated as volatile Diagnostic(ErrorCode.WRN_VolatileByRef, "x.i").WithArguments("TestClass.i")); } [Fact] public void CS0420WRN_VolatileByRef_Suppressed() { var text = @" using System.Threading; class TestClass { private static volatile int x = 0; public static void TestVolatileByRef() { Interlocked.Increment(ref x); // no CS0420 Interlocked.Decrement(ref x); // no CS0420 Interlocked.Add(ref x, 0); // no CS0420 Interlocked.CompareExchange(ref x, 0, 0); // no CS0420 Interlocked.Exchange(ref x, 0); // no CS0420 // using fully qualified name System.Threading.Interlocked.Increment(ref x); // no CS0420 System.Threading.Interlocked.Decrement(ref x); // no CS0420 System.Threading.Interlocked.Add(ref x, 0); // no CS0420 System.Threading.Interlocked.CompareExchange(ref x, 0, 0); // no CS0420 System.Threading.Interlocked.Exchange(ref x, 0); // no CS0420 // passing volatile variables in a nested way Interlocked.Increment(ref Method1(ref x).y); // CS0420 for x Interlocked.Decrement(ref Method1(ref x).y); // CS0420 for x Interlocked.Add(ref Method1(ref x).y, 0); // CS0420 for x Interlocked.CompareExchange(ref Method1(ref x).y, 0, 0); // CS0420 for x Interlocked.Exchange(ref Method1(ref x).y, 0); // CS0420 for x // located as a function argument goo(Interlocked.Increment(ref x)); // no CS0420 } public static int goo(int x) { return x; } public static MyClass Method1(ref int x) { return new MyClass(); } public class MyClass { public volatile int y = 0; } } "; CreateCompilation(text).VerifyDiagnostics( // (24,45): warning CS0420: 'TestClass.i': a reference to a volatile field will not be treated as volatile Diagnostic(ErrorCode.WRN_VolatileByRef, "x").WithArguments("TestClass.x"), // (25,45): warning CS0420: 'TestClass.i': a reference to a volatile field will not be treated as volatile Diagnostic(ErrorCode.WRN_VolatileByRef, "x").WithArguments("TestClass.x"), // (26,39): warning CS0420: 'TestClass.i': a reference to a volatile field will not be treated as volatile Diagnostic(ErrorCode.WRN_VolatileByRef, "x").WithArguments("TestClass.x"), // (27,51): warning CS0420: 'TestClass.i': a reference to a volatile field will not be treated as volatile Diagnostic(ErrorCode.WRN_VolatileByRef, "x").WithArguments("TestClass.x"), // (28,44): warning CS0420: 'TestClass.i': a reference to a volatile field will not be treated as volatile Diagnostic(ErrorCode.WRN_VolatileByRef, "x").WithArguments("TestClass.x")); } [WorkItem(728380, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/728380")] [Fact] public void Repro728380() { var source = @" class Test { static volatile int x; unsafe static void goo(int* pX) { } static int Main() { unsafe { Test.goo(&x); } return 1; } } "; CreateCompilation(source, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (9,27): error CS0212: You can only take the address of an unfixed expression inside of a fixed statement initializer // unsafe { Test.goo(&x); } Diagnostic(ErrorCode.ERR_FixedNeeded, "&x"), // (9,28): warning CS0420: 'Test.x': a reference to a volatile field will not be treated as volatile // unsafe { Test.goo(&x); } Diagnostic(ErrorCode.WRN_VolatileByRef, "x").WithArguments("Test.x")); } [Fact, WorkItem(528275, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528275")] public void CS0429WRN_UnreachableExpr() { var text = @" public class cs0429 { public static void Main() { if (false && myTest()) // CS0429 // Try the following line instead: // if (true && myTest()) { } else { int i = 0; i++; } } static bool myTest() { return true; } } "; // Dev11 compiler reports WRN_UnreachableExpr, but reachability is defined for statements not for expressions. // We don't report the warning. CreateCompilation(text).VerifyDiagnostics(); } [Fact, WorkItem(528275, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528275"), WorkItem(530071, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530071")] public void CS0429WRN_UnreachableExpr_02() { var text = @" class Program { static bool b = true; const bool con = true; static void Main(string[] args) { int x = 1; int y = 1; int s = true ? x++ : y++; // y++ unreachable s = x == y ? x++ : y++; // OK s = con ? x++ : y++; // y++ unreachable bool con1 = true; s = con1 ? x++ : y++; // OK s = b ? x++ : y++; s = 1 < 2 ? x++ : y++; // y++ unreachable } } "; // Dev11 compiler reports WRN_UnreachableExpr, but reachability is defined for statements not for expressions. // We don't report the warning. CreateCompilation(text).VerifyDiagnostics(); } [Fact, WorkItem(543943, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543943")] public void CS0458WRN_AlwaysNull() { var text = @" public class Test { public static void Main() { int? x = 0; x = null + x; x = x + default(int?); x += new int?(); x = null - x; x = x - default(int?); x -= new int?(); x = null * x; x = x * default(int?); x *= new int?(); x = null / x; x = x / default(int?); x /= new int?(); x = null % x; x = x % default(int?); x %= new int?(); x = null << x; x = x << default(int?); x <<= new int?(); x = null >> x; x = x >> default(int?); x >>= new int?(); x = null & x; x = x & default(int?); x &= new int?(); x = null | x; x = x | default(int?); x |= new int?(); x = null ^ x; x = x ^ default(int?); x ^= new int?(); //The below block of code should not raise a warning bool? y = null; y = y & null; y = y |false; y = true | null; double? d = +default(double?); int? i = -default(int?); long? l = ~default(long?); bool? b = !default(bool?); } } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( Diagnostic(ErrorCode.WRN_AlwaysNull, "null + x").WithArguments("int?"), Diagnostic(ErrorCode.WRN_AlwaysNull, "x + default(int?)").WithArguments("int?"), Diagnostic(ErrorCode.WRN_AlwaysNull, "x += new int?()").WithArguments("int?"), Diagnostic(ErrorCode.WRN_AlwaysNull, "null - x").WithArguments("int?"), Diagnostic(ErrorCode.WRN_AlwaysNull, "x - default(int?)").WithArguments("int?"), Diagnostic(ErrorCode.WRN_AlwaysNull, "x -= new int?()").WithArguments("int?"), Diagnostic(ErrorCode.WRN_AlwaysNull, "null * x").WithArguments("int?"), Diagnostic(ErrorCode.WRN_AlwaysNull, "x * default(int?)").WithArguments("int?"), Diagnostic(ErrorCode.WRN_AlwaysNull, "x *= new int?()").WithArguments("int?"), Diagnostic(ErrorCode.WRN_AlwaysNull, "null / x").WithArguments("int?"), Diagnostic(ErrorCode.WRN_AlwaysNull, "x / default(int?)").WithArguments("int?"), Diagnostic(ErrorCode.WRN_AlwaysNull, "x /= new int?()").WithArguments("int?"), Diagnostic(ErrorCode.WRN_AlwaysNull, "null % x").WithArguments("int?"), Diagnostic(ErrorCode.WRN_AlwaysNull, "x % default(int?)").WithArguments("int?"), Diagnostic(ErrorCode.WRN_AlwaysNull, "x %= new int?()").WithArguments("int?"), Diagnostic(ErrorCode.WRN_AlwaysNull, "null << x").WithArguments("int?"), Diagnostic(ErrorCode.WRN_AlwaysNull, "x << default(int?)").WithArguments("int?"), Diagnostic(ErrorCode.WRN_AlwaysNull, "x <<= new int?()").WithArguments("int?"), Diagnostic(ErrorCode.WRN_AlwaysNull, "null >> x").WithArguments("int?"), Diagnostic(ErrorCode.WRN_AlwaysNull, "x >> default(int?)").WithArguments("int?"), Diagnostic(ErrorCode.WRN_AlwaysNull, "x >>= new int?()").WithArguments("int?"), Diagnostic(ErrorCode.WRN_AlwaysNull, "null & x").WithArguments("int?"), Diagnostic(ErrorCode.WRN_AlwaysNull, "x & default(int?)").WithArguments("int?"), Diagnostic(ErrorCode.WRN_AlwaysNull, "x &= new int?()").WithArguments("int?"), Diagnostic(ErrorCode.WRN_AlwaysNull, "null | x").WithArguments("int?"), Diagnostic(ErrorCode.WRN_AlwaysNull, "x | default(int?)").WithArguments("int?"), Diagnostic(ErrorCode.WRN_AlwaysNull, "x |= new int?()").WithArguments("int?"), Diagnostic(ErrorCode.WRN_AlwaysNull, "null ^ x").WithArguments("int?"), Diagnostic(ErrorCode.WRN_AlwaysNull, "x ^ default(int?)").WithArguments("int?"), Diagnostic(ErrorCode.WRN_AlwaysNull, "x ^= new int?()").WithArguments("int?"), Diagnostic(ErrorCode.WRN_AlwaysNull, "+default(double?)").WithArguments("double?"), Diagnostic(ErrorCode.WRN_AlwaysNull, "-default(int?)").WithArguments("int?"), Diagnostic(ErrorCode.WRN_AlwaysNull, "~default(long?)").WithArguments("long?"), Diagnostic(ErrorCode.WRN_AlwaysNull, "!default(bool?)").WithArguments("bool?") ); } [Fact] public void CS0464WRN_CmpAlwaysFalse() { var text = @" class MyClass { public struct S { public static bool operator <(S x, S y) { return true; } public static bool operator >(S x, S y) { return true; } public static bool operator <=(S x, S y) { return true; } public static bool operator >=(S x, S y) { return true; } } public static void W(bool b) { System.Console.Write(b ? 't' : 'f'); } public static void Main() { S s = default(S); S? t = s; int i = 0; int? n = i; W(i < null); // CS0464 W(i <= null); // CS0464 W(i > null); // CS0464 W(i >= null); // CS0464 W(n < null); // CS0464 W(n <= null); // CS0464 W(n > null); // CS0464 W(n >= null); // CS0464 W(s < null); // CS0464 W(s <= null); // CS0464 W(s > null); // CS0464 W(s >= null); // CS0464 W(t < null); // CS0464 W(t <= null); // CS0464 W(t > null); // CS0464 W(t >= null); // CS0464 W(i < default(short?)); // CS0464 W(i <= default(short?)); // CS0464 W(i > default(short?)); // CS0464 W(i >= default(short?)); // CS0464 W(n < default(short?)); // CS0464 W(n <= default(short?)); // CS0464 W(n > default(short?)); // CS0464 W(n >= default(short?)); // CS0464 W(s < default(S?)); // CS0464 W(s <= default(S?)); // CS0464 W(s > default(S?)); // CS0464 W(s >= default(S?)); // CS0464 W(t < default(S?)); // CS0464 W(t <= default(S?)); // CS0464 W(t > default(S?)); // CS0464 W(t >= default(S?)); // CS0464 W(i < new sbyte?()); // CS0464 W(i <= new sbyte?()); // CS0464 W(i > new sbyte?()); // CS0464 W(i >= new sbyte?()); // CS0464 W(n < new sbyte?()); // CS0464 W(n <= new sbyte?()); // CS0464 W(n > new sbyte?()); // CS0464 W(n >= new sbyte?()); // CS0464 W(s < new S?()); // CS0464 W(s <= new S?()); // CS0464 W(s > new S?()); // CS0464 W(s >= new S?()); // CS0464 W(t < new S?()); // CS0464 W(t <= new S?()); // CS0464 W(t > new S?()); // CS0464 W(t >= new S?()); // CS0464 System.Console.WriteLine(); W(null < i); // CS0464 W(null <= i); // CS0464 W(null > i); // CS0464 W(null >= i); // CS0464 W(null < n); // CS0464 W(null <= n); // CS0464 W(null > n); // CS0464 W(null >= n); // CS0464 W(null < s); // CS0464 W(null <= s); // CS0464 W(null > s); // CS0464 W(null >= s); // CS0464 W(null < t); // CS0464 W(null <= t); // CS0464 W(null > t); // CS0464 W(null >= t); // CS0464 W(default(short?) < i); // CS0464 W(default(short?) <= i); // CS0464 W(default(short?) > i); // CS0464 W(default(short?) >= i); // CS0464 W(default(short?) < n); // CS0464 W(default(short?) <= n); // CS0464 W(default(short?) > n); // CS0464 W(default(short?) >= n); // CS0464 W(default(S?) < s); // CS0464 W(default(S?) <= s); // CS0464 W(default(S?) > s); // CS0464 W(default(S?) >= s); // CS0464 W(default(S?) < t); // CS0464 W(default(S?) <= t); // CS0464 W(default(S?) > t); // CS0464 W(default(S?) >= t); // CS0464 W(new sbyte?() < i); // CS0464 W(new sbyte?() <= i); // CS0464 W(new sbyte?() > i); // CS0464 W(new sbyte?() >= i); // CS0464 W(new sbyte?() < n); // CS0464 W(new sbyte?() <= n); // CS0464 W(new sbyte?() > n); // CS0464 W(new sbyte?() > n); // CS0464 W(new S?() < s); // CS0464 W(new S?() <= s); // CS0464 W(new S?() > s); // CS0464 W(new S?() >= s); // CS0464 W(new S?() < t); // CS0464 W(new S?() <= t); // CS0464 W(new S?() > t); // CS0464 W(new S?() > t); // CS0464 System.Console.WriteLine(); W(null > null); // CS0464 W(null >= null); // CS0464 W(null < null); // CS0464 W(null <= null); // CS0464 } } "; var verifier = CompileAndVerify(source: text, expectedOutput: @"ffffffffffffffffffffffffffffffffffffffffffffffff ffffffffffffffffffffffffffffffffffffffffffffffff ffff"); CreateCompilation(text).VerifyDiagnostics( // (25,11): warning CS0464: Comparing with null of type 'int?' always produces 'false' // W(i < null); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "i < null").WithArguments("int?"), // (26,11): warning CS0464: Comparing with null of type 'int?' always produces 'false' // W(i <= null); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "i <= null").WithArguments("int?"), // (27,11): warning CS0464: Comparing with null of type 'int?' always produces 'false' // W(i > null); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "i > null").WithArguments("int?"), // (28,11): warning CS0464: Comparing with null of type 'int?' always produces 'false' // W(i >= null); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "i >= null").WithArguments("int?"), // (30,11): warning CS0464: Comparing with null of type 'int?' always produces 'false' // W(n < null); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "n < null").WithArguments("int?"), // (31,11): warning CS0464: Comparing with null of type 'int?' always produces 'false' // W(n <= null); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "n <= null").WithArguments("int?"), // (32,11): warning CS0464: Comparing with null of type 'int?' always produces 'false' // W(n > null); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "n > null").WithArguments("int?"), // (33,11): warning CS0464: Comparing with null of type 'int?' always produces 'false' // W(n >= null); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "n >= null").WithArguments("int?"), // (35,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false' // W(s < null); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "s < null").WithArguments("MyClass.S?"), // (36,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false' // W(s <= null); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "s <= null").WithArguments("MyClass.S?"), // (37,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false' // W(s > null); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "s > null").WithArguments("MyClass.S?"), // (38,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false' // W(s >= null); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "s >= null").WithArguments("MyClass.S?"), // (40,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false' // W(t < null); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "t < null").WithArguments("MyClass.S?"), // (41,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false' // W(t <= null); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "t <= null").WithArguments("MyClass.S?"), // (42,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false' // W(t > null); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "t > null").WithArguments("MyClass.S?"), // (43,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false' // W(t >= null); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "t >= null").WithArguments("MyClass.S?"), // (45,11): warning CS0464: Comparing with null of type 'short?' always produces 'false' // W(i < default(short?)); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "i < default(short?)").WithArguments("short?"), // (46,11): warning CS0464: Comparing with null of type 'short?' always produces 'false' // W(i <= default(short?)); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "i <= default(short?)").WithArguments("short?"), // (47,11): warning CS0464: Comparing with null of type 'short?' always produces 'false' // W(i > default(short?)); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "i > default(short?)").WithArguments("short?"), // (48,11): warning CS0464: Comparing with null of type 'short?' always produces 'false' // W(i >= default(short?)); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "i >= default(short?)").WithArguments("short?"), // (50,11): warning CS0464: Comparing with null of type 'short?' always produces 'false' // W(n < default(short?)); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "n < default(short?)").WithArguments("short?"), // (51,11): warning CS0464: Comparing with null of type 'short?' always produces 'false' // W(n <= default(short?)); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "n <= default(short?)").WithArguments("short?"), // (52,11): warning CS0464: Comparing with null of type 'short?' always produces 'false' // W(n > default(short?)); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "n > default(short?)").WithArguments("short?"), // (53,11): warning CS0464: Comparing with null of type 'short?' always produces 'false' // W(n >= default(short?)); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "n >= default(short?)").WithArguments("short?"), // (55,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false' // W(s < default(S?)); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "s < default(S?)").WithArguments("MyClass.S?"), // (56,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false' // W(s <= default(S?)); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "s <= default(S?)").WithArguments("MyClass.S?"), // (57,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false' // W(s > default(S?)); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "s > default(S?)").WithArguments("MyClass.S?"), // (58,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false' // W(s >= default(S?)); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "s >= default(S?)").WithArguments("MyClass.S?"), // (60,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false' // W(t < default(S?)); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "t < default(S?)").WithArguments("MyClass.S?"), // (61,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false' // W(t <= default(S?)); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "t <= default(S?)").WithArguments("MyClass.S?"), // (62,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false' // W(t > default(S?)); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "t > default(S?)").WithArguments("MyClass.S?"), // (63,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false' // W(t >= default(S?)); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "t >= default(S?)").WithArguments("MyClass.S?"), // (65,11): warning CS0464: Comparing with null of type 'sbyte?' always produces 'false' // W(i < new sbyte?()); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "i < new sbyte?()").WithArguments("sbyte?"), // (66,11): warning CS0464: Comparing with null of type 'sbyte?' always produces 'false' // W(i <= new sbyte?()); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "i <= new sbyte?()").WithArguments("sbyte?"), // (67,11): warning CS0464: Comparing with null of type 'sbyte?' always produces 'false' // W(i > new sbyte?()); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "i > new sbyte?()").WithArguments("sbyte?"), // (68,11): warning CS0464: Comparing with null of type 'sbyte?' always produces 'false' // W(i >= new sbyte?()); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "i >= new sbyte?()").WithArguments("sbyte?"), // (70,11): warning CS0464: Comparing with null of type 'sbyte?' always produces 'false' // W(n < new sbyte?()); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "n < new sbyte?()").WithArguments("sbyte?"), // (71,11): warning CS0464: Comparing with null of type 'sbyte?' always produces 'false' // W(n <= new sbyte?()); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "n <= new sbyte?()").WithArguments("sbyte?"), // (72,11): warning CS0464: Comparing with null of type 'sbyte?' always produces 'false' // W(n > new sbyte?()); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "n > new sbyte?()").WithArguments("sbyte?"), // (73,11): warning CS0464: Comparing with null of type 'sbyte?' always produces 'false' // W(n >= new sbyte?()); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "n >= new sbyte?()").WithArguments("sbyte?"), // (75,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false' // W(s < new S?()); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "s < new S?()").WithArguments("MyClass.S?"), // (76,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false' // W(s <= new S?()); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "s <= new S?()").WithArguments("MyClass.S?"), // (77,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false' // W(s > new S?()); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "s > new S?()").WithArguments("MyClass.S?"), // (78,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false' // W(s >= new S?()); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "s >= new S?()").WithArguments("MyClass.S?"), // (80,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false' // W(t < new S?()); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "t < new S?()").WithArguments("MyClass.S?"), // (81,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false' // W(t <= new S?()); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "t <= new S?()").WithArguments("MyClass.S?"), // (82,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false' // W(t > new S?()); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "t > new S?()").WithArguments("MyClass.S?"), // (83,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false' // W(t >= new S?()); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "t >= new S?()").WithArguments("MyClass.S?"), // (87,11): warning CS0464: Comparing with null of type 'int?' always produces 'false' // W(null < i); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "null < i").WithArguments("int?"), // (88,11): warning CS0464: Comparing with null of type 'int?' always produces 'false' // W(null <= i); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "null <= i").WithArguments("int?"), // (89,11): warning CS0464: Comparing with null of type 'int?' always produces 'false' // W(null > i); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "null > i").WithArguments("int?"), // (90,11): warning CS0464: Comparing with null of type 'int?' always produces 'false' // W(null >= i); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "null >= i").WithArguments("int?"), // (92,11): warning CS0464: Comparing with null of type 'int?' always produces 'false' // W(null < n); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "null < n").WithArguments("int?"), // (93,11): warning CS0464: Comparing with null of type 'int?' always produces 'false' // W(null <= n); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "null <= n").WithArguments("int?"), // (94,11): warning CS0464: Comparing with null of type 'int?' always produces 'false' // W(null > n); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "null > n").WithArguments("int?"), // (95,11): warning CS0464: Comparing with null of type 'int?' always produces 'false' // W(null >= n); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "null >= n").WithArguments("int?"), // (97,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false' // W(null < s); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "null < s").WithArguments("MyClass.S?"), // (98,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false' // W(null <= s); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "null <= s").WithArguments("MyClass.S?"), // (99,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false' // W(null > s); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "null > s").WithArguments("MyClass.S?"), // (100,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false' // W(null >= s); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "null >= s").WithArguments("MyClass.S?"), // (102,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false' // W(null < t); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "null < t").WithArguments("MyClass.S?"), // (103,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false' // W(null <= t); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "null <= t").WithArguments("MyClass.S?"), // (104,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false' // W(null > t); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "null > t").WithArguments("MyClass.S?"), // (105,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false' // W(null >= t); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "null >= t").WithArguments("MyClass.S?"), // (107,11): warning CS0464: Comparing with null of type 'short?' always produces 'false' // W(default(short?) < i); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "default(short?) < i").WithArguments("short?"), // (108,11): warning CS0464: Comparing with null of type 'short?' always produces 'false' // W(default(short?) <= i); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "default(short?) <= i").WithArguments("short?"), // (109,11): warning CS0464: Comparing with null of type 'short?' always produces 'false' // W(default(short?) > i); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "default(short?) > i").WithArguments("short?"), // (110,11): warning CS0464: Comparing with null of type 'short?' always produces 'false' // W(default(short?) >= i); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "default(short?) >= i").WithArguments("short?"), // (112,11): warning CS0464: Comparing with null of type 'short?' always produces 'false' // W(default(short?) < n); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "default(short?) < n").WithArguments("short?"), // (113,11): warning CS0464: Comparing with null of type 'short?' always produces 'false' // W(default(short?) <= n); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "default(short?) <= n").WithArguments("short?"), // (114,11): warning CS0464: Comparing with null of type 'short?' always produces 'false' // W(default(short?) > n); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "default(short?) > n").WithArguments("short?"), // (115,11): warning CS0464: Comparing with null of type 'short?' always produces 'false' // W(default(short?) >= n); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "default(short?) >= n").WithArguments("short?"), // (117,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false' // W(default(S?) < s); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "default(S?) < s").WithArguments("MyClass.S?"), // (118,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false' // W(default(S?) <= s); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "default(S?) <= s").WithArguments("MyClass.S?"), // (119,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false' // W(default(S?) > s); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "default(S?) > s").WithArguments("MyClass.S?"), // (120,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false' // W(default(S?) >= s); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "default(S?) >= s").WithArguments("MyClass.S?"), // (122,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false' // W(default(S?) < t); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "default(S?) < t").WithArguments("MyClass.S?"), // (123,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false' // W(default(S?) <= t); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "default(S?) <= t").WithArguments("MyClass.S?"), // (124,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false' // W(default(S?) > t); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "default(S?) > t").WithArguments("MyClass.S?"), // (125,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false' // W(default(S?) >= t); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "default(S?) >= t").WithArguments("MyClass.S?"), // (127,11): warning CS0464: Comparing with null of type 'sbyte?' always produces 'false' // W(new sbyte?() < i); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "new sbyte?() < i").WithArguments("sbyte?"), // (128,11): warning CS0464: Comparing with null of type 'sbyte?' always produces 'false' // W(new sbyte?() <= i); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "new sbyte?() <= i").WithArguments("sbyte?"), // (129,11): warning CS0464: Comparing with null of type 'sbyte?' always produces 'false' // W(new sbyte?() > i); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "new sbyte?() > i").WithArguments("sbyte?"), // (130,11): warning CS0464: Comparing with null of type 'sbyte?' always produces 'false' // W(new sbyte?() >= i); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "new sbyte?() >= i").WithArguments("sbyte?"), // (132,11): warning CS0464: Comparing with null of type 'sbyte?' always produces 'false' // W(new sbyte?() < n); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "new sbyte?() < n").WithArguments("sbyte?"), // (133,11): warning CS0464: Comparing with null of type 'sbyte?' always produces 'false' // W(new sbyte?() <= n); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "new sbyte?() <= n").WithArguments("sbyte?"), // (134,11): warning CS0464: Comparing with null of type 'sbyte?' always produces 'false' // W(new sbyte?() > n); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "new sbyte?() > n").WithArguments("sbyte?"), // (135,11): warning CS0464: Comparing with null of type 'sbyte?' always produces 'false' // W(new sbyte?() > n); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "new sbyte?() > n").WithArguments("sbyte?"), // (137,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false' // W(new S?() < s); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "new S?() < s").WithArguments("MyClass.S?"), // (138,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false' // W(new S?() <= s); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "new S?() <= s").WithArguments("MyClass.S?"), // (139,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false' // W(new S?() > s); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "new S?() > s").WithArguments("MyClass.S?"), // (140,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false' // W(new S?() >= s); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "new S?() >= s").WithArguments("MyClass.S?"), // (142,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false' // W(new S?() < t); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "new S?() < t").WithArguments("MyClass.S?"), // (143,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false' // W(new S?() <= t); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "new S?() <= t").WithArguments("MyClass.S?"), // (144,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false' // W(new S?() > t); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "new S?() > t").WithArguments("MyClass.S?"), // (145,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false' // W(new S?() > t); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "new S?() > t").WithArguments("MyClass.S?"), // (149,11): warning CS0464: Comparing with null of type 'int?' always produces 'false' // W(null > null); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "null > null").WithArguments("int?"), // (150,11): warning CS0464: Comparing with null of type 'int?' always produces 'false' // W(null >= null); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "null >= null").WithArguments("int?"), // (151,11): warning CS0464: Comparing with null of type 'int?' always produces 'false' // W(null < null); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "null < null").WithArguments("int?"), // (152,11): warning CS0464: Comparing with null of type 'int?' always produces 'false' // W(null <= null); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "null <= null").WithArguments("int?") ); } [Fact] public void CS0469WRN_GotoCaseShouldConvert() { var text = @" class Test { static void Main() { char c = (char)180; switch (c) { case (char)127: break; case (char)180: goto case 127; // CS0469 // try the following line instead // goto case (char) 127; } } } "; CreateCompilation(text).VerifyDiagnostics( // (13,13): warning CS0469: The 'goto case' value is not implicitly convertible to type 'char' // goto case 127; // CS0469 Diagnostic(ErrorCode.WRN_GotoCaseShouldConvert, "goto case 127;").WithArguments("char").WithLocation(13, 13) ); } [Fact, WorkItem(663, "https://github.com/dotnet/roslyn/issues/663")] public void CS0472WRN_NubExprIsConstBool() { // Due to a long-standing bug, the native compiler does not produce warnings for "guid == null", // but does for "int == null". Roslyn corrects this lapse and produces warnings for both built-in // and user-defined lifted equality operators, but the new warnings for user-defined types are // only given with /warn:n where n >= 5. var text = @" using System; class MyClass { public static void W(bool b) { System.Console.Write(b ? 't' : 'f'); } enum E : int { }; public static void Main() { Guid g = default(Guid); Guid? h = g; int i = 0; int? n = i; W(i == null); // CS0472 W(i != null); // CS0472 W(n == null); // no error W(n != null); // no error W(g == null); // CS0472 W(g != null); // CS0472 W(h == null); // no error W(h != null); // no error W(i == default(short?)); // CS0472 W(i != default(short?)); // CS0472 W(n == default(short?)); // no error W(n != default(short?)); // no error W(g == default(Guid?)); // CS0472 W(g != default(Guid?)); // CS0472 W(h == default(Guid?)); // no error W(h != default(Guid?)); // no error W(i == new sbyte?()); // CS0472 W(i != new sbyte?()); // CS0472 W(n == new sbyte?()); // no error W(n != new sbyte?()); // no error W(g == new Guid?()); // CS0472 W(g != new Guid?()); // CS0472 W(h == new Guid?()); // no error W(h != new Guid?()); // no error System.Console.WriteLine(); W(null == i); // CS0472 W(null != i); // CS0472 W(null == n); // no error W(null != n); // no error W(null == g); // CS0472 W(null != g); // CS0472 W(null == h); // no error W(null != h); // no error W(default(long?) == i); // CS0472 W(default(long?) != i); // CS0472 W(default(long?) == n); // no error W(default(long?) != n); // no error W(default(Guid?) == g); // CS0472 W(default(Guid?) != g); // CS0472 W(default(Guid?) == h); // no error W(default(Guid?) != h); // no error W(new double?() == i); // CS0472 W(new double?() != i); // CS0472 W(new double?() == n); // no error W(new double?() != n); // no error W(new Guid?() == g); // CS0472 W(new Guid?() != g); // CS0472 W(new Guid?() == h); // no error W(new Guid?() != h); // no error System.Console.WriteLine(); W(null == null); // No error, because both sides are nullable, but of course W(null != null); // we could give a warning here as well. System.Console.WriteLine(); //check comparisons with converted constants W((E?)1 == null); W(null != (E?)1); W((int?)1 == null); W(null != (int?)1); //check comparisons when null is converted W(0 == (int?)null); W((int?)null != 0); W(0 == (E?)null); W((E?)null != 0); } } "; string expected = @"ftftftftftftftftftftftft ftftftftftftftftftftftft tf ftftftft"; var fullExpected = new DiagnosticDescription[] { // (19,11): warning CS0472: The result of the expression is always 'false' since a value of type 'int' is never equal to 'null' of type 'int?' // W(i == null); // CS0472 Diagnostic(ErrorCode.WRN_NubExprIsConstBool, "i == null").WithArguments("false", "int", "int?").WithLocation(19, 11), // (20,11): warning CS0472: The result of the expression is always 'true' since a value of type 'int' is never equal to 'null' of type 'int?' // W(i != null); // CS0472 Diagnostic(ErrorCode.WRN_NubExprIsConstBool, "i != null").WithArguments("true", "int", "int?").WithLocation(20, 11), // (23,11): warning CS8073: The result of the expression is always 'false' since a value of type 'System.Guid' is never equal to 'null' of type 'System.Guid?' // W(g == null); // CS0472 Diagnostic(ErrorCode.WRN_NubExprIsConstBool2, "g == null").WithArguments("false", "System.Guid", "System.Guid?").WithLocation(23, 11), // (24,11): warning CS8073: The result of the expression is always 'true' since a value of type 'System.Guid' is never equal to 'null' of type 'System.Guid?' // W(g != null); // CS0472 Diagnostic(ErrorCode.WRN_NubExprIsConstBool2, "g != null").WithArguments("true", "System.Guid", "System.Guid?").WithLocation(24, 11), // (28,11): warning CS0472: The result of the expression is always 'false' since a value of type 'int' is never equal to 'null' of type 'short?' // W(i == default(short?)); // CS0472 Diagnostic(ErrorCode.WRN_NubExprIsConstBool, "i == default(short?)").WithArguments("false", "int", "short?").WithLocation(28, 11), // (29,11): warning CS0472: The result of the expression is always 'true' since a value of type 'int' is never equal to 'null' of type 'short?' // W(i != default(short?)); // CS0472 Diagnostic(ErrorCode.WRN_NubExprIsConstBool, "i != default(short?)").WithArguments("true", "int", "short?").WithLocation(29, 11), // (32,11): warning CS8073: The result of the expression is always 'false' since a value of type 'System.Guid' is never equal to 'null' of type 'System.Guid?' // W(g == default(Guid?)); // CS0472 Diagnostic(ErrorCode.WRN_NubExprIsConstBool2, "g == default(Guid?)").WithArguments("false", "System.Guid", "System.Guid?").WithLocation(32, 11), // (33,11): warning CS8073: The result of the expression is always 'true' since a value of type 'System.Guid' is never equal to 'null' of type 'System.Guid?' // W(g != default(Guid?)); // CS0472 Diagnostic(ErrorCode.WRN_NubExprIsConstBool2, "g != default(Guid?)").WithArguments("true", "System.Guid", "System.Guid?").WithLocation(33, 11), // (37,11): warning CS0472: The result of the expression is always 'false' since a value of type 'int' is never equal to 'null' of type 'sbyte?' // W(i == new sbyte?()); // CS0472 Diagnostic(ErrorCode.WRN_NubExprIsConstBool, "i == new sbyte?()").WithArguments("false", "int", "sbyte?").WithLocation(37, 11), // (38,11): warning CS0472: The result of the expression is always 'true' since a value of type 'int' is never equal to 'null' of type 'sbyte?' // W(i != new sbyte?()); // CS0472 Diagnostic(ErrorCode.WRN_NubExprIsConstBool, "i != new sbyte?()").WithArguments("true", "int", "sbyte?").WithLocation(38, 11), // (41,11): warning CS8073: The result of the expression is always 'false' since a value of type 'System.Guid' is never equal to 'null' of type 'System.Guid?' // W(g == new Guid?()); // CS0472 Diagnostic(ErrorCode.WRN_NubExprIsConstBool2, "g == new Guid?()").WithArguments("false", "System.Guid", "System.Guid?").WithLocation(41, 11), // (42,11): warning CS8073: The result of the expression is always 'true' since a value of type 'System.Guid' is never equal to 'null' of type 'System.Guid?' // W(g != new Guid?()); // CS0472 Diagnostic(ErrorCode.WRN_NubExprIsConstBool2, "g != new Guid?()").WithArguments("true", "System.Guid", "System.Guid?").WithLocation(42, 11), // (49,11): warning CS0472: The result of the expression is always 'false' since a value of type 'int' is never equal to 'null' of type 'int?' // W(null == i); // CS0472 Diagnostic(ErrorCode.WRN_NubExprIsConstBool, "null == i").WithArguments("false", "int", "int?").WithLocation(49, 11), // (50,11): warning CS0472: The result of the expression is always 'true' since a value of type 'int' is never equal to 'null' of type 'int?' // W(null != i); // CS0472 Diagnostic(ErrorCode.WRN_NubExprIsConstBool, "null != i").WithArguments("true", "int", "int?").WithLocation(50, 11), // (53,11): warning CS8073: The result of the expression is always 'false' since a value of type 'System.Guid' is never equal to 'null' of type 'System.Guid?' // W(null == g); // CS0472 Diagnostic(ErrorCode.WRN_NubExprIsConstBool2, "null == g").WithArguments("false", "System.Guid", "System.Guid?").WithLocation(53, 11), // (54,11): warning CS8073: The result of the expression is always 'true' since a value of type 'System.Guid' is never equal to 'null' of type 'System.Guid?' // W(null != g); // CS0472 Diagnostic(ErrorCode.WRN_NubExprIsConstBool2, "null != g").WithArguments("true", "System.Guid", "System.Guid?").WithLocation(54, 11), // (58,11): warning CS0472: The result of the expression is always 'false' since a value of type 'long' is never equal to 'null' of type 'long?' // W(default(long?) == i); // CS0472 Diagnostic(ErrorCode.WRN_NubExprIsConstBool, "default(long?) == i").WithArguments("false", "long", "long?").WithLocation(58, 11), // (59,11): warning CS0472: The result of the expression is always 'true' since a value of type 'long' is never equal to 'null' of type 'long?' // W(default(long?) != i); // CS0472 Diagnostic(ErrorCode.WRN_NubExprIsConstBool, "default(long?) != i").WithArguments("true", "long", "long?").WithLocation(59, 11), // (62,11): warning CS8073: The result of the expression is always 'false' since a value of type 'System.Guid' is never equal to 'null' of type 'System.Guid?' // W(default(Guid?) == g); // CS0472 Diagnostic(ErrorCode.WRN_NubExprIsConstBool2, "default(Guid?) == g").WithArguments("false", "System.Guid", "System.Guid?").WithLocation(62, 11), // (63,11): warning CS8073: The result of the expression is always 'true' since a value of type 'System.Guid' is never equal to 'null' of type 'System.Guid?' // W(default(Guid?) != g); // CS0472 Diagnostic(ErrorCode.WRN_NubExprIsConstBool2, "default(Guid?) != g").WithArguments("true", "System.Guid", "System.Guid?").WithLocation(63, 11), // (67,11): warning CS0472: The result of the expression is always 'false' since a value of type 'double' is never equal to 'null' of type 'double?' // W(new double?() == i); // CS0472 Diagnostic(ErrorCode.WRN_NubExprIsConstBool, "new double?() == i").WithArguments("false", "double", "double?").WithLocation(67, 11), // (68,11): warning CS0472: The result of the expression is always 'true' since a value of type 'double' is never equal to 'null' of type 'double?' // W(new double?() != i); // CS0472 Diagnostic(ErrorCode.WRN_NubExprIsConstBool, "new double?() != i").WithArguments("true", "double", "double?").WithLocation(68, 11), // (71,11): warning CS8073: The result of the expression is always 'false' since a value of type 'System.Guid' is never equal to 'null' of type 'System.Guid?' // W(new Guid?() == g); // CS0472 Diagnostic(ErrorCode.WRN_NubExprIsConstBool2, "new Guid?() == g").WithArguments("false", "System.Guid", "System.Guid?").WithLocation(71, 11), // (72,11): warning CS8073: The result of the expression is always 'true' since a value of type 'System.Guid' is never equal to 'null' of type 'System.Guid?' // W(new Guid?() != g); // CS0472 Diagnostic(ErrorCode.WRN_NubExprIsConstBool2, "new Guid?() != g").WithArguments("true", "System.Guid", "System.Guid?").WithLocation(72, 11), // (84,11): warning CS0472: The result of the expression is always 'false' since a value of type 'MyClass.E' is never equal to 'null' of type 'MyClass.E?' // W((E?)1 == null); Diagnostic(ErrorCode.WRN_NubExprIsConstBool, "(E?)1 == null").WithArguments("false", "MyClass.E", "MyClass.E?").WithLocation(84, 11), // (85,11): warning CS0472: The result of the expression is always 'true' since a value of type 'MyClass.E' is never equal to 'null' of type 'MyClass.E?' // W(null != (E?)1); Diagnostic(ErrorCode.WRN_NubExprIsConstBool, "null != (E?)1").WithArguments("true", "MyClass.E", "MyClass.E?").WithLocation(85, 11), // (87,11): warning CS0472: The result of the expression is always 'false' since a value of type 'int' is never equal to 'null' of type 'int?' // W((int?)1 == null); Diagnostic(ErrorCode.WRN_NubExprIsConstBool, "(int?)1 == null").WithArguments("false", "int", "int?").WithLocation(87, 11), // (88,11): warning CS0472: The result of the expression is always 'true' since a value of type 'int' is never equal to 'null' of type 'int?' // W(null != (int?)1); Diagnostic(ErrorCode.WRN_NubExprIsConstBool, "null != (int?)1").WithArguments("true", "int", "int?").WithLocation(88, 11), // (92,11): warning CS0472: The result of the expression is always 'false' since a value of type 'int' is never equal to 'null' of type 'int?' // W(0 == (int?)null); Diagnostic(ErrorCode.WRN_NubExprIsConstBool, "0 == (int?)null").WithArguments("false", "int", "int?").WithLocation(92, 11), // (93,11): warning CS0472: The result of the expression is always 'true' since a value of type 'int' is never equal to 'null' of type 'int?' // W((int?)null != 0); Diagnostic(ErrorCode.WRN_NubExprIsConstBool, "(int?)null != 0").WithArguments("true", "int", "int?").WithLocation(93, 11), // (95,11): warning CS0472: The result of the expression is always 'false' since a value of type 'MyClass.E' is never equal to 'null' of type 'MyClass.E?' // W(0 == (E?)null); Diagnostic(ErrorCode.WRN_NubExprIsConstBool, "0 == (E?)null").WithArguments("false", "MyClass.E", "MyClass.E?").WithLocation(95, 11), // (96,11): warning CS0472: The result of the expression is always 'true' since a value of type 'MyClass.E' is never equal to 'null' of type 'MyClass.E?' // W((E?)null != 0); Diagnostic(ErrorCode.WRN_NubExprIsConstBool, "(E?)null != 0").WithArguments("true", "MyClass.E", "MyClass.E?").WithLocation(96, 11) }; var compatibleExpected = fullExpected.Where(d => !d.Code.Equals((int)ErrorCode.WRN_NubExprIsConstBool2)).ToArray(); this.CompileAndVerify(source: text, expectedOutput: expected, options: TestOptions.ReleaseExe.WithWarningLevel(4)).VerifyDiagnostics(compatibleExpected); this.CompileAndVerify(source: text, expectedOutput: expected).VerifyDiagnostics(fullExpected); } [Fact] public void CS0472WRN_NubExprIsConstBool_ConstructorInitializer() { var text = @"class A { internal A(bool b) { } } class B : A { B(int i) : base(i == null) { } }"; CreateCompilation(text).VerifyDiagnostics( // (9,21): warning CS0472: The result of the expression is always 'false' since a value of type 'int' is never equal to 'null' of type 'int?' // B(int i) : base(i == null) Diagnostic(ErrorCode.WRN_NubExprIsConstBool, "i == null").WithArguments("false", "int", "int?").WithLocation(9, 21)); } [Fact] public void CS0612WRN_DeprecatedSymbol() { var text = @" using System; class MyClass { [Obsolete] public static void ObsoleteMethod() { } [Obsolete] public static int ObsoleteField; } class MainClass { static public void Main() { MyClass.ObsoleteMethod(); // CS0612 here: method is deprecated MyClass.ObsoleteField = 0; // CS0612 here: field is deprecated } } "; CreateCompilation(text). VerifyDiagnostics( // (17,7): warning CS0612: 'MyClass.ObsoleteMethod()' is obsolete // MyClass.ObsoleteMethod(); // CS0612 here: method is deprecated Diagnostic(ErrorCode.WRN_DeprecatedSymbol, "MyClass.ObsoleteMethod()").WithArguments("MyClass.ObsoleteMethod()"), // (18,7): warning CS0612: 'MyClass.ObsoleteField' is obsolete // MyClass.ObsoleteField = 0; // CS0612 here: field is deprecated Diagnostic(ErrorCode.WRN_DeprecatedSymbol, "MyClass.ObsoleteField").WithArguments("MyClass.ObsoleteField")); } [Fact, WorkItem(546062, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546062")] public void CS0618WRN_DeprecatedSymbol() { var text = @" public class ConsoleStub { public static void Main(string[] args) { System.Collections.CaseInsensitiveHashCodeProvider x; System.Console.WriteLine(x); } }"; CreateCompilation(text). VerifyDiagnostics( // (6,9): warning CS0618: 'System.Collections.CaseInsensitiveHashCodeProvider' is obsolete: 'Please use StringComparer instead.' // System.Collections.CaseInsensitiveHashCodeProvider x; Diagnostic(ErrorCode.WRN_DeprecatedSymbolStr, "System.Collections.CaseInsensitiveHashCodeProvider").WithArguments("System.Collections.CaseInsensitiveHashCodeProvider", "Please use StringComparer instead."), // (7,34): error CS0165: Use of unassigned local variable 'x' // System.Console.WriteLine(x); Diagnostic(ErrorCode.ERR_UseDefViolation, "x").WithArguments("x")); } [WorkItem(545347, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545347")] [Fact] public void CS0649WRN_UnassignedInternalField() { var text = @" using System.Collections; class MyClass { Hashtable table; // CS0649 public void Func(object o, string p) { table[p] = o; } } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (6,15): warning CS0649: Field 'MyClass.table' is never assigned to, and will always have its default value null // Hashtable table; // CS0649 Diagnostic(ErrorCode.WRN_UnassignedInternalField, "table").WithArguments("MyClass.table", "null") ); } [Fact, WorkItem(543454, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543454")] public void CS0649WRN_UnassignedInternalField_1() { var text = @" public class GenClass<T, U> { } public class Outer { internal protected class C1 { } public class C2 { } internal class Test { public GenClass<C1, C2> Fld; } public static int Main() { return 0; } }"; CreateCompilation(text).VerifyDiagnostics( Diagnostic(ErrorCode.WRN_UnassignedInternalField, "Fld").WithArguments("Outer.Test.Fld", "null")); } [WorkItem(546449, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546449")] [WorkItem(546949, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546949")] [Fact] public void CS0652WRN_VacuousIntegralComp() { var text = @" public class Class1 { private static byte i = 0; public static void Main() { const short j = 256; if (i == j) // CS0652, 256 is out of range for byte i = 0; // However, we do not give this warning if both sides of the comparison are constants. In those // cases, we are probably in machine-generated code anyways. const byte k = 0; if (k == j) {} } } "; CreateCompilation(text).VerifyDiagnostics( // (8,11): warning CS0652: Comparison to integral constant is useless; the constant is outside the range of type 'byte' // if (i == j) // CS0652, 256 is out of range for byte Diagnostic(ErrorCode.WRN_VacuousIntegralComp, "i == j").WithArguments("byte")); } [WorkItem(546790, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546790")] [Fact] public void CS0652WRN_VacuousIntegralComp_ExplicitCast() { var text = @" using System; public class Program { public static void Main() { Int16 wSuiteMask = 0; const int VER_SUITE_WH_SERVER = 0x00008000; if (VER_SUITE_WH_SERVER == (Int32)wSuiteMask) { } } } "; CreateCompilation(text).VerifyDiagnostics(); } [Fact] public void CS0665WRN_IncorrectBooleanAssg() { var text = @" class Test { public static void Main() { bool i = false; if (i = true) // CS0665 // try the following line instead // if (i == true) { } System.Console.WriteLine(i); } } "; CreateCompilation(text).VerifyDiagnostics( // (8,11): warning CS0665: Assignment in conditional expression is always constant; did you mean to use == instead of = ? Diagnostic(ErrorCode.WRN_IncorrectBooleanAssg, "i = true")); } [Fact, WorkItem(540777, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540777")] public void CS0665WRN_IncorrectBooleanAssg_ConditionalOperator() { var text = @" class Program { static int Main(string[] args) { bool a = true; System.Console.WriteLine(a); return ((a = false) ? 50 : 100); // Warning } } "; CreateCompilation(text).VerifyDiagnostics( // (8,18): warning CS0665: Assignment in conditional expression is always constant; did you mean to use == instead of = ? Diagnostic(ErrorCode.WRN_IncorrectBooleanAssg, "a = false")); } [Fact] public void CS0665WRN_IncorrectBooleanAssg_Contexts() { var text = @" class C { static void Main(string[] args) { bool b = args.Length > 1; if (b = false) { } while (b = false) { } do { } while (b = false); for (; b = false; ) { } System.Console.WriteLine((b = false) ? 1 : 2); } } "; CreateCompilation(text).VerifyDiagnostics( // (8,13): warning CS0665: Assignment in conditional expression is always constant; did you mean to use == instead of = ? // if (b = false) { } Diagnostic(ErrorCode.WRN_IncorrectBooleanAssg, "b = false"), // (9,16): warning CS0665: Assignment in conditional expression is always constant; did you mean to use == instead of = ? // while (b = false) { } Diagnostic(ErrorCode.WRN_IncorrectBooleanAssg, "b = false"), // (10,23): warning CS0665: Assignment in conditional expression is always constant; did you mean to use == instead of = ? // do { } while (b = false); Diagnostic(ErrorCode.WRN_IncorrectBooleanAssg, "b = false"), // (11,16): warning CS0665: Assignment in conditional expression is always constant; did you mean to use == instead of = ? // for (; b = false; ) { } Diagnostic(ErrorCode.WRN_IncorrectBooleanAssg, "b = false"), // (12,35): warning CS0665: Assignment in conditional expression is always constant; did you mean to use == instead of = ? // System.Console.WriteLine((b = false) ? 1 : 2); Diagnostic(ErrorCode.WRN_IncorrectBooleanAssg, "b = false")); } [Fact] public void CS0665WRN_IncorrectBooleanAssg_Nesting() { var text = @" class C { static void Main(string[] args) { bool b = args.Length > 1; if ((b = false)) { } // parens - warn if (((b = false))) { } // more parens - warn if (M(b = false)) { } // call - do not warn if ((bool)(b = false)) { } // cast - do not warn if ((b = false) || (b = true)) { } // binary operator - do not warn B bb = new B(); if (bb = false) { } // implicit conversion - do not warn } static bool M(bool b) { return b; } } class B { public static implicit operator B(bool b) { return new B(); } public static bool operator true(B b) { return true; } public static bool operator false(B b) { return false; } } "; CreateCompilation(text).VerifyDiagnostics( // (8,14): warning CS0665: Assignment in conditional expression is always constant; did you mean to use == instead of = ? // if ((b = false)) { } // parens - warn Diagnostic(ErrorCode.WRN_IncorrectBooleanAssg, "b = false"), // (9,15): warning CS0665: Assignment in conditional expression is always constant; did you mean to use == instead of = ? // if (((b = false))) { } // more parens - warn Diagnostic(ErrorCode.WRN_IncorrectBooleanAssg, "b = false")); } [Fact, WorkItem(909, "https://github.com/dotnet/roslyn/issues/909")] public void CS0675WRN_BitwiseOrSignExtend() { var text = @" public class sign { public static void Main() { int i32_hi = 1; int i32_lo = 1; ulong u64 = 1; sbyte i08 = 1; short i16 = -1; object v1 = (((long)i32_hi) << 32) | i32_lo; // CS0675 object v2 = (ulong)i32_hi | u64; // CS0675 object v3 = (ulong)i32_hi | (ulong)i32_lo; // No warning; the sign extension bits are the same on both sides. object v4 = (ulong)(uint)(ushort)i08 | (ulong)i32_lo; // CS0675 object v5 = (int)i08 | (int)i32_lo; // No warning; sign extension is considered to be 'expected' when casting. object v6 = (((ulong)i32_hi) << 32) | (uint) i32_lo; // No warning; we've cast to a smaller unsigned type first. // We suppress the warning if the bits that are going to be wiped out are known already to be all zero or all one: object v7 = 0x0000BEEFU | (uint)i16; object v8 = 0xFFFFBEEFU | (uint)i16; object v9 = 0xDEADBEEFU | (uint)i16; // CS0675 // We should do the exact same logic for nullables. int? ni32_hi = 1; int? ni32_lo = 1; ulong? nu64 = 1; sbyte? ni08 = 1; short? ni16 = -1; object v11 = (((long?)ni32_hi) << 32) | ni32_lo; // CS0675 object v12 = (ulong?)ni32_hi | nu64; // CS0675 object v13 = (ulong?)ni32_hi | (ulong?)ni32_lo; // No warning; the sign extension bits are the same on both sides. object v14 = (ulong?)(uint?)(ushort?)ni08 | (ulong?)ni32_lo; // CS0675 object v15 = (int?)ni08 | (int?)ni32_lo; // No warning; sign extension is considered to be 'expected' when casting. object v16 = (((ulong?)ni32_hi) << 32) | (uint?) ni32_lo; // No warning; we've cast to a smaller unsigned type first. // We suppress the warning if the bits that are going to be wiped out are known already to be all zero or all one: object v17 = 0x0000BEEFU | (uint?)ni16; object v18 = 0xFFFFBEEFU | (uint?)ni16; object v19 = 0xDEADBEEFU | (uint?)ni16; // CS0675 } } class Test { static void Main() { long bits = 0; for (int i = 0; i < 32; i++) { if (i % 2 == 0) { bits |= (1 << i); bits = bits | (1 << i); } } } } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (12,19): warning CS0675: Bitwise-or operator used on a sign-extended operand; consider casting to a smaller unsigned type first // object v1 = (((long)i32_hi) << 32) | i32_lo; // CS0675 Diagnostic(ErrorCode.WRN_BitwiseOrSignExtend, "(((long)i32_hi) << 32) | i32_lo"), // (13,19): warning CS0675: Bitwise-or operator used on a sign-extended operand; consider casting to a smaller unsigned type first // object v2 = (ulong)i32_hi | u64; // CS0675 Diagnostic(ErrorCode.WRN_BitwiseOrSignExtend, "(ulong)i32_hi | u64"), // (15,19): warning CS0675: Bitwise-or operator used on a sign-extended operand; consider casting to a smaller unsigned type first // object v4 = (ulong)(uint)(ushort)i08 | (ulong)i32_lo; // CS0675 Diagnostic(ErrorCode.WRN_BitwiseOrSignExtend, "(ulong)(uint)(ushort)i08 | (ulong)i32_lo"), // (21,19): warning CS0675: Bitwise-or operator used on a sign-extended operand; consider casting to a smaller unsigned type first // object v9 = 0xDEADBEEFU | (uint)i16; // CS0675 Diagnostic(ErrorCode.WRN_BitwiseOrSignExtend, "0xDEADBEEFU | (uint)i16"), // (31,20): warning CS0675: Bitwise-or operator used on a sign-extended operand; consider casting to a smaller unsigned type first // object v11 = (((long?)ni32_hi) << 32) | ni32_lo; // CS0675 Diagnostic(ErrorCode.WRN_BitwiseOrSignExtend, "(((long?)ni32_hi) << 32) | ni32_lo"), // (32,20): warning CS0675: Bitwise-or operator used on a sign-extended operand; consider casting to a smaller unsigned type first // object v12 = (ulong?)ni32_hi | nu64; // CS0675 Diagnostic(ErrorCode.WRN_BitwiseOrSignExtend, "(ulong?)ni32_hi | nu64"), // (34,20): warning CS0675: Bitwise-or operator used on a sign-extended operand; consider casting to a smaller unsigned type first // object v14 = (ulong?)(uint?)(ushort?)ni08 | (ulong?)ni32_lo; // CS0675 Diagnostic(ErrorCode.WRN_BitwiseOrSignExtend, "(ulong?)(uint?)(ushort?)ni08 | (ulong?)ni32_lo"), // (40,20): warning CS0675: Bitwise-or operator used on a sign-extended operand; consider casting to a smaller unsigned type first // object v19 = 0xDEADBEEFU | (uint?)ni16; // CS0675 Diagnostic(ErrorCode.WRN_BitwiseOrSignExtend, "0xDEADBEEFU | (uint?)ni16"), // (53,17): warning CS0675: Bitwise-or operator used on a sign-extended operand; consider casting to a smaller unsigned type first // bits |= (1 << i); Diagnostic(ErrorCode.WRN_BitwiseOrSignExtend, "bits |= (1 << i)").WithLocation(53, 17), // (54,24): warning CS0675: Bitwise-or operator used on a sign-extended operand; consider casting to a smaller unsigned type first // bits = bits | (1 << i); Diagnostic(ErrorCode.WRN_BitwiseOrSignExtend, "bits | (1 << i)").WithLocation(54, 24) ); } [Fact] public void CS0728WRN_AssignmentToLockOrDispose01() { CreateCompilation(@" using System; public class ValidBase : IDisposable { public void Dispose() { } } public class Logger { public static void dummy() { ValidBase vb = null; using (vb) { vb = null; // CS0728 } vb = null; } public static void Main() { } }") .VerifyDiagnostics( // (15,13): warning CS0728: Possibly incorrect assignment to local 'vb' which is the argument to a using or lock statement. The Dispose call or unlocking will happen on the original value of the local. Diagnostic(ErrorCode.WRN_AssignmentToLockOrDispose, "vb").WithArguments("vb")); } [Fact] public void CS0728WRN_AssignmentToLockOrDispose02() { CreateCompilation( @"class D : System.IDisposable { public void Dispose() { } } class C { static void M() { D d = new D(); using (d) { N(ref d); } lock (d) { N(ref d); } } static void N(ref D d) { } }") .VerifyDiagnostics( Diagnostic(ErrorCode.WRN_AssignmentToLockOrDispose, "d").WithArguments("d").WithLocation(12, 19), Diagnostic(ErrorCode.WRN_AssignmentToLockOrDispose, "d").WithArguments("d").WithLocation(16, 19)); } [WorkItem(543615, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543615"), WorkItem(546550, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546550")] [ConditionalFact(typeof(WindowsOnly), Reason = ConditionalSkipReason.NativePdbRequiresDesktop)] public void CS0811ERR_DebugFullNameTooLong() { var text = @" using System; using System.Collections.Generic; namespace TestNamespace { using VeryLong = List<List<List<List<List<List<List<List<List<List<List<List<List <List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<int>>>>>>>>>>>>>>>>>>>>>>>>>>>>; // CS0811 class Test { static int Main() { VeryLong goo = null; Console.WriteLine(goo); return 1; } } } "; var compilation = CreateCompilation(text, targetFramework: TargetFramework.Mscorlib45, options: TestOptions.DebugExe); var exebits = new System.IO.MemoryStream(); var pdbbits = new System.IO.MemoryStream(); var result = compilation.Emit(exebits, pdbbits, options: TestOptions.NativePdbEmit); result.Diagnostics.Verify( // (12,20): warning CS0811: The fully qualified name for 'AVeryLong TSystem.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' is too long for debug information. Compile without '/debug' option. // static int Main() Diagnostic(ErrorCode.WRN_DebugFullNameTooLong, "Main").WithArguments("AVeryLong TSystem.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089").WithLocation(12, 20)); } [Fact] public void CS1058WRN_UnreachableGeneralCatch() { var text = @"class C { static void M() { try { } catch (System.Exception) { } catch (System.IO.IOException) { } catch { } try { } catch (System.IO.IOException) { } catch (System.Exception) { } catch { } } } "; CreateCompilation(text).VerifyDiagnostics( Diagnostic(ErrorCode.ERR_UnreachableCatch, "System.IO.IOException").WithArguments("System.Exception").WithLocation(7, 16), Diagnostic(ErrorCode.WRN_UnreachableGeneralCatch, "catch").WithLocation(8, 9), Diagnostic(ErrorCode.WRN_UnreachableGeneralCatch, "catch").WithLocation(12, 9)); } // [Fact(Skip = "11486")] // public void CS1060WRN_UninitializedField() // { // var text = @" //namespace CS1060 //{ // public class U // { // public int i; // } // // public struct S // { // public U u; // } // public class Test // { // static void Main() // { // S s; // s.u.i = 5; // CS1060 // } // } //} //"; // DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, // new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.WRN_UninitializedField, Line = 18, Column = 13, IsWarning = true } }); // } // [Fact()] // public void CS1064ERR_DebugFullNameTooLong() // { // var text = @" //"; // DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, // new ErrorDescription[] { new ErrorDescription { Code = 1064, Line = 7, Column = 5, IsWarning = true } } // ); // } [Fact] public void CS1570WRN_XMLParseError() { var text = @" namespace ns { // the following line generates CS1570 /// <summary> returns true if < 5 </summary> // try this instead // /// <summary> returns true if &lt;5 </summary> public class MyClass { public static void Main () { } } } "; CreateCompilationWithMscorlib40AndDocumentationComments(text).VerifyDiagnostics( // (5,35): warning CS1570: XML comment has badly formed XML -- 'An identifier was expected.' // /// <summary> returns true if < 5 </summary> Diagnostic(ErrorCode.WRN_XMLParseError, ""), // (5,35): warning CS1570: XML comment has badly formed XML -- '5' // /// <summary> returns true if < 5 </summary> Diagnostic(ErrorCode.WRN_XMLParseError, " ").WithArguments("5"), // (11,26): warning CS1591: Missing XML comment for publicly visible type or member 'ns.MyClass.Main()' // public static void Main () Diagnostic(ErrorCode.WRN_MissingXMLComment, "Main").WithArguments("ns.MyClass.Main()")); } [Fact] public void CS1571WRN_DuplicateParamTag() { var text = @" /// <summary>help text</summary> public class MyClass { /// <param name='Int1'>Used to indicate status.</param> /// <param name='Char1'>An initial.</param> /// <param name='Int1'>Used to indicate status.</param> // CS1571 public static void MyMethod(int Int1, char Char1) { } /// <summary>help text</summary> public static void Main () { } } "; CreateCompilationWithMscorlib40AndDocumentationComments(text).VerifyDiagnostics( // (7,15): warning CS1571: XML comment has a duplicate param tag for 'Int1' // /// <param name='Int1'>Used to indicate status.</param> // CS1571 Diagnostic(ErrorCode.WRN_DuplicateParamTag, "name='Int1'").WithArguments("Int1")); } [Fact] public void CS1572WRN_UnmatchedParamTag() { var text = @" /// <summary>help text</summary> public class MyClass { /// <param name='Int1'>Used to indicate status.</param> /// <param name='Char1'>Used to indicate status.</param> /// <param name='Char2'>???</param> // CS1572 public static void MyMethod(int Int1, char Char1) { } /// <summary>help text</summary> public static void Main () { } } "; CreateCompilationWithMscorlib40AndDocumentationComments(text).VerifyDiagnostics( // (7,21): warning CS1572: XML comment has a param tag for 'Char2', but there is no parameter by that name // /// <param name='Char2'>???</param> // CS1572 Diagnostic(ErrorCode.WRN_UnmatchedParamTag, "Char2").WithArguments("Char2")); } [Fact] public void CS1573WRN_MissingParamTag() { var text = @" /// <summary> </summary> public class MyClass { /// <param name='Int1'>Used to indicate status.</param> /// enter a comment for Char1? public static void MyMethod(int Int1, char Char1) { } /// <summary> </summary> public static void Main() { } } "; CreateCompilationWithMscorlib40AndDocumentationComments(text).VerifyDiagnostics( // (7,48): warning CS1573: Parameter 'Char1' has no matching param tag in the XML comment for 'MyClass.MyMethod(int, char)' (but other parameters do) // public static void MyMethod(int Int1, char Char1) Diagnostic(ErrorCode.WRN_MissingParamTag, "Char1").WithArguments("Char1", "MyClass.MyMethod(int, char)")); } [Fact] public void CS1574WRN_BadXMLRef() { var text = @" /// <see cref=""D""/> public class C { } "; CreateCompilationWithMscorlib40AndDocumentationComments(text).VerifyDiagnostics( // (2,16): warning CS1574: XML comment has cref attribute 'D' that could not be resolved // /// <see cref="D"/> Diagnostic(ErrorCode.WRN_BadXMLRef, "D").WithArguments("D")); } [Fact] public void CS1580WRN_BadXMLRefParamType() { var text = @" /// <seealso cref=""Test(i)""/> // CS1580 public class MyClass { /// <summary>help text</summary> public static void Main() { } /// <summary>help text</summary> public void Test(int i) { } /// <summary>help text</summary> public void Test(char i) { } } "; CreateCompilationWithMscorlib40AndDocumentationComments(text).VerifyDiagnostics( // (2,20): warning CS1580: Invalid type for parameter 'i' in XML comment cref attribute: 'Test(i)' // /// <seealso cref="Test(i)"/> // CS1580 Diagnostic(ErrorCode.WRN_BadXMLRefParamType, "i").WithArguments("i", "Test(i)"), // (2,20): warning CS1574: XML comment has cref attribute 'Test(i)' that could not be resolved // /// <seealso cref="Test(i)"/> // CS1580 Diagnostic(ErrorCode.WRN_BadXMLRef, "Test(i)").WithArguments("Test(i)")); } [Fact] public void CS1581WRN_BadXMLRefReturnType() { var text = @" /// <summary>help text</summary> public class MyClass { /// <summary>help text</summary> public static void Main() { } /// <summary>help text</summary> public static explicit operator int(MyClass f) { return 0; } } /// <seealso cref=""MyClass.explicit operator intt(MyClass)""/> // CS1581 public class MyClass2 { } "; CreateCompilationWithMscorlib40AndDocumentationComments(text).VerifyDiagnostics( // (15,20): warning CS1581: Invalid return type in XML comment cref attribute // /// <seealso cref="MyClass.explicit operator intt(MyClass)"/> // CS1581 Diagnostic(ErrorCode.WRN_BadXMLRefReturnType, "intt").WithArguments("intt", "MyClass.explicit operator intt(MyClass)"), // (15,20): warning CS1574: XML comment has cref attribute 'MyClass.explicit operator intt(MyClass)' that could not be resolved // /// <seealso cref="MyClass.explicit operator intt(MyClass)"/> // CS1581 Diagnostic(ErrorCode.WRN_BadXMLRef, "MyClass.explicit operator intt(MyClass)").WithArguments("explicit operator intt(MyClass)")); } [Fact] public void CS1584WRN_BadXMLRefSyntax() { var text = @" /// public class MyClass1 { /// public static MyClass1 operator /(MyClass1 a1, MyClass1 a2) { return null; } /// <seealso cref=""MyClass1.operator@""/> public static void Main() { } } "; CreateCompilationWithMscorlib40AndDocumentationComments(text).VerifyDiagnostics( // (10,24): warning CS1584: XML comment has syntactically incorrect cref attribute 'MyClass1.operator@' // /// <seealso cref="MyClass1.operator@"/> Diagnostic(ErrorCode.WRN_BadXMLRefSyntax, "MyClass1.operator").WithArguments("MyClass1.operator@"), // (10,41): warning CS1658: Overloadable operator expected. See also error CS1037. // /// <seealso cref="MyClass1.operator@"/> Diagnostic(ErrorCode.WRN_ErrorOverride, "@").WithArguments("Overloadable operator expected", "1037"), // (10,41): error CS1646: Keyword, identifier, or string expected after verbatim specifier: @ // /// <seealso cref="MyClass1.operator@"/> Diagnostic(ErrorCode.ERR_ExpectedVerbatimLiteral, "")); } [Fact] public void CS1587WRN_UnprocessedXMLComment() { var text = @" /// <summary>test</summary> // CS1587, tag not allowed on namespace namespace MySpace { class MyClass { public static void Main() { } } } "; CreateCompilationWithMscorlib40AndDocumentationComments(text). VerifyDiagnostics(Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/")); } [Fact] public void CS1589WRN_NoResolver() { var text = @" /// <include file='CS1589.doc' path='MyDocs/MyMembers[@name=""test""]/' /> // CS1589 class Test { public static void Main() { } } "; var c = CreateCompilation( new[] { Parse(text, options: TestOptions.RegularWithDocumentationComments) }, options: TestOptions.ReleaseDll.WithXmlReferenceResolver(null)); c.VerifyDiagnostics( // (2,5): warning CS1589: Unable to include XML fragment 'MyDocs/MyMembers[@name="test"]/' of file 'CS1589.doc' -- References to XML documents are not supported. // /// <include file='CS1589.doc' path='MyDocs/MyMembers[@name="test"]/' /> // CS1589 Diagnostic(ErrorCode.WRN_FailedInclude, @"<include file='CS1589.doc' path='MyDocs/MyMembers[@name=""test""]/' />"). WithArguments("CS1589.doc", @"MyDocs/MyMembers[@name=""test""]/", "References to XML documents are not supported.")); } [Fact] public void CS1589WRN_FailedInclude() { var text = @" /// <include file='CS1589.doc' path='MyDocs/MyMembers[@name=""test""]/' /> // CS1589 class Test { public static void Main() { } } "; CreateCompilationWithMscorlib40AndDocumentationComments(text).VerifyDiagnostics( // (2,5): warning CS1589: Unable to include XML fragment 'MyDocs/MyMembers[@name="test"]/' of file 'CS1589.doc' -- Unable to find the specified file. // /// <include file='CS1589.doc' path='MyDocs/MyMembers[@name="test"]/' /> // CS1589 Diagnostic(ErrorCode.WRN_FailedInclude, @"<include file='CS1589.doc' path='MyDocs/MyMembers[@name=""test""]/' />"). WithArguments("CS1589.doc", @"MyDocs/MyMembers[@name=""test""]/", "File not found.")); } [Fact] public void CS1590WRN_InvalidInclude() { var text = @" /// <include path='MyDocs/MyMembers[@name=""test""]/*' /> // CS1590 class Test { public static void Main() { } } "; CreateCompilationWithMscorlib40AndDocumentationComments(text).VerifyDiagnostics( // (2,5): warning CS1590: Invalid XML include element -- Missing file attribute // /// <include path='MyDocs/MyMembers[@name="test"]/*' /> // CS1590 Diagnostic(ErrorCode.WRN_InvalidInclude, @"<include path='MyDocs/MyMembers[@name=""test""]/*' />").WithArguments("Missing file attribute")); } [Fact] public void CS1591WRN_MissingXMLComment() { var text = @" /// text public class Test { // /// text public static void Main() // CS1591 { } } "; CreateCompilationWithMscorlib40AndDocumentationComments(text).VerifyDiagnostics( // (6,23): warning CS1591: Missing XML comment for publicly visible type or member 'Test.Main()' // public static void Main() // CS1591 Diagnostic(ErrorCode.WRN_MissingXMLComment, "Main").WithArguments("Test.Main()")); } [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/18610")] public void CS1592WRN_XMLParseIncludeError() { var xmlFile = Temp.CreateFile(extension: ".xml").WriteAllText("&"); var sourceTemplate = @" /// <include file='{0}' path='element'/> public class Test {{ }} "; var comp = CreateCompilationWithMscorlib40AndDocumentationComments(string.Format(sourceTemplate, xmlFile.Path)); using (new EnsureEnglishUICulture()) { comp.VerifyDiagnostics( // dcf98d2ac30a.xml(1,1): warning CS1592: Badly formed XML in included comments file -- 'Data at the root level is invalid.' Diagnostic(ErrorCode.WRN_XMLParseIncludeError).WithArguments("Data at the root level is invalid.")); } } [Fact] public void CS1658WRN_ErrorOverride() { var text = @" /// <seealso cref=""""/> public class Test { /// public static int Main() { return 0; } } "; CreateCompilationWithMscorlib40AndDocumentationComments(text).VerifyDiagnostics( // (2,20): warning CS1584: XML comment has syntactically incorrect cref attribute '' // /// <seealso cref=""/> Diagnostic(ErrorCode.WRN_BadXMLRefSyntax, @"""").WithArguments(""), // (2,20): warning CS1658: Identifier expected. See also error CS1001. // /// <seealso cref=""/> Diagnostic(ErrorCode.WRN_ErrorOverride, @"""").WithArguments("Identifier expected", "1001")); } // TODO (tomat): Also fix AttributeTests.DllImport_AttributeRedefinition [Fact(Skip = "530377"), WorkItem(530377, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530377"), WorkItem(685159, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/685159")] public void CS1685WRN_MultiplePredefTypes() { var text = @" public static class C { public static void Extension(this int X) {} }"; // include both mscorlib 4.0 and System.Core 3.5, both of which contain ExtensionAttribute // These libraries are not yet in our suite CreateEmptyCompilation(text). VerifyDiagnostics(Diagnostic(ErrorCode.WRN_MultiplePredefTypes, "")); } [Fact, WorkItem(530379, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530379")] public void CS1690WRN_CallOnNonAgileField() { var text = @" using System; class WarningCS1690 : MarshalByRefObject { int i = 5; public static void Main() { WarningCS1690 e = new WarningCS1690(); e.i.ToString(); // CS1690 int i = e.i; i.ToString(); e.i = i; } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.WRN_CallOnNonAgileField, Line = 11, Column = 9, IsWarning = true } }); } [Fact, WorkItem(530379, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530379")] public void CS1690WRN_CallOnNonAgileField_Variations() { var text = @" using System; struct S { public event Action Event; public int Field; public int Property { get; set; } public int this[int x] { get { return 0; } set { } } public void M() { } class WarningCS1690 : MarshalByRefObject { S s; public static void Main() { WarningCS1690 w = new WarningCS1690(); w.s.Event = null; w.s.Event += null; w.s.Property++; w.s[0]++; w.s.M(); Action a = w.s.M; } } } "; CreateCompilation(text).VerifyDiagnostics( // (19,13): warning CS1690: Accessing a member on 'S.WarningCS1690.s' may cause a runtime exception because it is a field of a marshal-by-reference class // w.s.Event = null; Diagnostic(ErrorCode.WRN_CallOnNonAgileField, "w.s").WithArguments("S.WarningCS1690.s"), // (20,13): warning CS1690: Accessing a member on 'S.WarningCS1690.s' may cause a runtime exception because it is a field of a marshal-by-reference class // w.s.Event += null; Diagnostic(ErrorCode.WRN_CallOnNonAgileField, "w.s").WithArguments("S.WarningCS1690.s"), // (21,13): warning CS1690: Accessing a member on 'S.WarningCS1690.s' may cause a runtime exception because it is a field of a marshal-by-reference class // w.s.Property++; Diagnostic(ErrorCode.WRN_CallOnNonAgileField, "w.s").WithArguments("S.WarningCS1690.s"), // (22,13): warning CS1690: Accessing a member on 'S.WarningCS1690.s' may cause a runtime exception because it is a field of a marshal-by-reference class // w.s[0]++; Diagnostic(ErrorCode.WRN_CallOnNonAgileField, "w.s").WithArguments("S.WarningCS1690.s"), // (23,13): warning CS1690: Accessing a member on 'S.WarningCS1690.s' may cause a runtime exception because it is a field of a marshal-by-reference class // w.s.M(); Diagnostic(ErrorCode.WRN_CallOnNonAgileField, "w.s").WithArguments("S.WarningCS1690.s"), // (24,24): warning CS1690: Accessing a member on 'S.WarningCS1690.s' may cause a runtime exception because it is a field of a marshal-by-reference class // Action a = w.s.M; Diagnostic(ErrorCode.WRN_CallOnNonAgileField, "w.s").WithArguments("S.WarningCS1690.s"), // (7,16): warning CS0649: Field 'S.Field' is never assigned to, and will always have its default value 0 // public int Field; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "Field").WithArguments("S.Field", "0"), // (6,25): warning CS0414: The field 'S.Event' is assigned but its value is never used // public event Action Event; Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "Event").WithArguments("S.Event")); } [Fact, WorkItem(530379, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530379")] public void CS1690WRN_CallOnNonAgileField_Class() { var text = @" using System; class S { public event Action Event; public int Field; public int Property { get; set; } public int this[int x] { get { return 0; } set { } } public void M() { } class WarningCS1690 : MarshalByRefObject { S s; public static void Main() { WarningCS1690 w = new WarningCS1690(); w.s.Event = null; w.s.Event += null; w.s.Property++; w.s[0]++; w.s.M(); Action a = w.s.M; } } } "; CreateCompilation(text).VerifyDiagnostics( // (14,11): warning CS0649: Field 'S.WarningCS1690.s' is never assigned to, and will always have its default value null // S s; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "s").WithArguments("S.WarningCS1690.s", "null"), // (7,16): warning CS0649: Field 'S.Field' is never assigned to, and will always have its default value 0 // public int Field; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "Field").WithArguments("S.Field", "0"), // (6,25): warning CS0414: The field 'S.Event' is assigned but its value is never used // public event Action Event; Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "Event").WithArguments("S.Event")); } // [Fact()] // public void CS1707WRN_DelegateNewMethBind() // { // var text = @" //"; // DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, // new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.WRN_DelegateNewMethBind, Line = 7, Column = 5, IsWarning = true } } // ); // } [Fact(), WorkItem(530384, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530384")] public void CS1709WRN_EmptyFileName() { var text = @" class Test { static void Main() { #pragma checksum """" ""{406EA660-64CF-4C82-B6F0-42D48172A799}"" """" // CS1709 } } "; //EDMAURER no longer giving this low-value warning. CreateCompilation(text). VerifyDiagnostics(); //VerifyDiagnostics(Diagnostic(ErrorCode.WRN_EmptyFileName, @"""")); } [Fact] public void CS1710WRN_DuplicateTypeParamTag() { var text = @" class Stack<ItemType> { } /// <typeparam name=""MyType"">can be an int</typeparam> /// <typeparam name=""MyType"">can be an int</typeparam> class MyStackWrapper<MyType> { // Open constructed type Stack<MyType>. Stack<MyType> stack; public MyStackWrapper(Stack<MyType> s) { stack = s; } } class CMain { public static void Main() { } } "; CreateCompilationWithMscorlib40AndDocumentationComments(text).VerifyDiagnostics( // (6,16): warning CS1710: XML comment has a duplicate typeparam tag for 'MyType' // /// <typeparam name="MyType">can be an int</typeparam> Diagnostic(ErrorCode.WRN_DuplicateTypeParamTag, @"name=""MyType""").WithArguments("MyType")); } [Fact] public void CS1711WRN_UnmatchedTypeParamTag() { var text = @" ///<typeparam name=""WrongName"">can be an int</typeparam> class CMain { public static void Main() { } } "; CreateCompilationWithMscorlib40AndDocumentationComments(text).VerifyDiagnostics( // (2,21): warning CS1711: XML comment has a typeparam tag for 'WrongName', but there is no type parameter by that name // ///<typeparam name="WrongName">can be an int</typeparam> Diagnostic(ErrorCode.WRN_UnmatchedTypeParamTag, "WrongName").WithArguments("WrongName")); } [Fact] public void CS1712WRN_MissingTypeParamTag() { var text = @" ///<summary>A generic list delegate.</summary> ///<typeparam name=""T"">The first type stored by the list.</typeparam> public delegate void List<T,W>(); /// public class Test { /// public static void Main() { } } "; CreateCompilationWithMscorlib40AndDocumentationComments(text).VerifyDiagnostics( // (4,29): warning CS1712: Type parameter 'W' has no matching typeparam tag in the XML comment on 'List<T, W>' (but other type parameters do) // public delegate void List<T,W>(); Diagnostic(ErrorCode.WRN_MissingTypeParamTag, "W").WithArguments("W", "List<T, W>")); } [Fact] public void CS1717WRN_AssignmentToSelf() { var text = @" public class Test { public static void Main() { int x = 0; x = x; // CS1717 } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.WRN_AssignmentToSelf, Line = 7, Column = 7, IsWarning = true } }); } [WorkItem(543470, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543470")] [Fact] public void CS1717WRN_AssignmentToSelf02() { var text = @" class C { void M(object p) { object oValue = p; if (oValue is int) { //(SQL 9.0) 653716 + common sense oValue = (double) ((int) oValue); } } }"; CreateCompilation(text).VerifyDiagnostics(); } [Fact] public void CS1717WRN_AssignmentToSelf03() { var text = @" using System; class Program { int f; event Action e; void Test(int p) { int l = 0; l = l; p = p; f = f; e = e; } } "; CreateCompilation(text).VerifyDiagnostics( // (13,9): warning CS1717: Assignment made to same variable; did you mean to assign something else? // l = l; Diagnostic(ErrorCode.WRN_AssignmentToSelf, "l = l"), // (14,9): warning CS1717: Assignment made to same variable; did you mean to assign something else? // p = p; Diagnostic(ErrorCode.WRN_AssignmentToSelf, "p = p"), // (15,9): warning CS1717: Assignment made to same variable; did you mean to assign something else? // f = f; Diagnostic(ErrorCode.WRN_AssignmentToSelf, "f = f"), // (16,9): warning CS1717: Assignment made to same variable; did you mean to assign something else? // e = e; Diagnostic(ErrorCode.WRN_AssignmentToSelf, "e = e")); } [Fact] public void CS1717WRN_AssignmentToSelf04() { var text = @" using System; class Program { int f; event Action e; static int sf; static event Action se; void Test(Program other) { f = this.f; e = this.e; f = other.f; //fine e = other.e; //fine sf = sf; se = se; sf = Program.sf; se = Program.se; } } "; CreateCompilation(text).VerifyDiagnostics( // (14,9): warning CS1717: Assignment made to same variable; did you mean to assign something else? // f = this.f; Diagnostic(ErrorCode.WRN_AssignmentToSelf, "f = this.f"), // (15,9): warning CS1717: Assignment made to same variable; did you mean to assign something else? // e = this.e; Diagnostic(ErrorCode.WRN_AssignmentToSelf, "e = this.e"), // (20,9): warning CS1717: Assignment made to same variable; did you mean to assign something else? // sf = sf; Diagnostic(ErrorCode.WRN_AssignmentToSelf, "sf = sf"), // (21,9): warning CS1717: Assignment made to same variable; did you mean to assign something else? // se = se; Diagnostic(ErrorCode.WRN_AssignmentToSelf, "se = se"), // (23,9): warning CS1717: Assignment made to same variable; did you mean to assign something else? // sf = Program.sf; Diagnostic(ErrorCode.WRN_AssignmentToSelf, "sf = Program.sf"), // (24,9): warning CS1717: Assignment made to same variable; did you mean to assign something else? // se = Program.se; Diagnostic(ErrorCode.WRN_AssignmentToSelf, "se = Program.se")); } [Fact] public void CS1717WRN_AssignmentToSelf05() { var text = @" using System.Linq; class Program { static void Main(string[] args) { var unused = from x in args select x = x; } } "; // CONSIDER: dev11 reports WRN_AssignmentToSelf. CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics( // (8,44): error CS1947: Range variable 'x' cannot be assigned to -- it is read only // var unused = from x in args select x = x; Diagnostic(ErrorCode.ERR_QueryRangeVariableReadOnly, "x").WithArguments("x")); } [Fact] public void CS1717WRN_AssignmentToSelf06() { var text = @" class C { void M( byte b, sbyte sb, short s, ushort us, int i, uint ui, long l, ulong ul, float f, double d, decimal m, bool bo, object o, C cl, S st) { b = (byte)b; sb = (sbyte)sb; s = (short)s; us = (ushort)us; i = (int)i; ui = (uint)ui; l = (long)l; ul = (ulong)ul; f = (float)f; // Not reported by dev11. d = (double)d; // Not reported by dev11. m = (decimal)m; bo = (bool)bo; o = (object)o; cl = (C)cl; st = (S)st; } } struct S { } "; // CONSIDER: dev11 does not strip off float or double identity-conversions and, thus, // does not warn about those assignments. CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics( // (21,9): warning CS1717: Assignment made to same variable; did you mean to assign something else? // b = (byte)b; Diagnostic(ErrorCode.WRN_AssignmentToSelf, "b = (byte)b"), // (22,9): warning CS1717: Assignment made to same variable; did you mean to assign something else? // sb = (sbyte)sb; Diagnostic(ErrorCode.WRN_AssignmentToSelf, "sb = (sbyte)sb"), // (23,9): warning CS1717: Assignment made to same variable; did you mean to assign something else? // s = (short)s; Diagnostic(ErrorCode.WRN_AssignmentToSelf, "s = (short)s"), // (24,9): warning CS1717: Assignment made to same variable; did you mean to assign something else? // us = (ushort)us; Diagnostic(ErrorCode.WRN_AssignmentToSelf, "us = (ushort)us"), // (25,9): warning CS1717: Assignment made to same variable; did you mean to assign something else? // i = (int)i; Diagnostic(ErrorCode.WRN_AssignmentToSelf, "i = (int)i"), // (26,9): warning CS1717: Assignment made to same variable; did you mean to assign something else? // ui = (uint)ui; Diagnostic(ErrorCode.WRN_AssignmentToSelf, "ui = (uint)ui"), // (27,9): warning CS1717: Assignment made to same variable; did you mean to assign something else? // l = (long)l; Diagnostic(ErrorCode.WRN_AssignmentToSelf, "l = (long)l"), // (28,9): warning CS1717: Assignment made to same variable; did you mean to assign something else? // ul = (ulong)ul; Diagnostic(ErrorCode.WRN_AssignmentToSelf, "ul = (ulong)ul"), // (29,9): warning CS1717: Assignment made to same variable; did you mean to assign something else? // f = (float)f; // Not reported by dev11. Diagnostic(ErrorCode.WRN_AssignmentToSelf, "f = (float)f"), // (30,9): warning CS1717: Assignment made to same variable; did you mean to assign something else? // d = (double)d; // Not reported by dev11. Diagnostic(ErrorCode.WRN_AssignmentToSelf, "d = (double)d"), // (31,9): warning CS1717: Assignment made to same variable; did you mean to assign something else? // m = (decimal)m; Diagnostic(ErrorCode.WRN_AssignmentToSelf, "m = (decimal)m"), // (32,9): warning CS1717: Assignment made to same variable; did you mean to assign something else? // bo = (bool)bo; Diagnostic(ErrorCode.WRN_AssignmentToSelf, "bo = (bool)bo"), // (33,9): warning CS1717: Assignment made to same variable; did you mean to assign something else? // o = (object)o; Diagnostic(ErrorCode.WRN_AssignmentToSelf, "o = (object)o"), // (34,9): warning CS1717: Assignment made to same variable; did you mean to assign something else? // cl = (C)cl; Diagnostic(ErrorCode.WRN_AssignmentToSelf, "cl = (C)cl"), // (35,9): warning CS1717: Assignment made to same variable; did you mean to assign something else? // st = (S)st; Diagnostic(ErrorCode.WRN_AssignmentToSelf, "st = (S)st")); } [Fact, WorkItem(546493, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546493")] public void CS1718WRN_ComparisonToSelf() { var text = @" class Tester { static int j = 123; static void Main() { int i = 0; if (i == i) i++; if (j == Tester.j) j++; } } "; CreateCompilation(text).VerifyDiagnostics( // (8,13): warning CS1718: Comparison made to same variable; did you mean to compare something else? // if (i == i) i++; Diagnostic(ErrorCode.WRN_ComparisonToSelf, "i == i"), // (9,13): warning CS1718: Comparison made to same variable; did you mean to compare something else? // if (j == Tester.j) j++; Diagnostic(ErrorCode.WRN_ComparisonToSelf, "j == Tester.j")); } [Fact, WorkItem(580501, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/580501")] public void CS1718WRN_ComparisonToSelf2() { var text = @" using System.Linq; class Tester { static void Main() { var q = from int x1 in new[] { 2, 9, 1, 8, } where x1 > x1 // CS1718 select x1; } } "; CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics( // (8,15): warning CS1718: Comparison made to same variable; did you mean to compare something else? // where x1 > x1 // CS1718 Diagnostic(ErrorCode.WRN_ComparisonToSelf, "x1 > x1")); } [Fact] public void CS1720WRN_DotOnDefault01() { var source = @"class A { internal object P { get; set; } } interface I { object P { get; set; } } static class C { static void M<T1, T2, T3, T4, T5, T6, T7>() where T2 : new() where T3 : struct where T4 : class where T5 : T1 where T6 : A where T7 : I { default(int).GetHashCode(); default(object).GetHashCode(); default(T1).GetHashCode(); default(T2).GetHashCode(); default(T3).GetHashCode(); default(T4).GetHashCode(); default(T5).GetHashCode(); default(T6).GetHashCode(); default(T7).GetHashCode(); default(T6).P = null; default(T7).P = null; default(int).E(); default(object).E(); default(T1).E(); default(T2).E(); default(T3).E(); default(T4).E(); default(T5).E(); default(T6).E(); // Dev10 (incorrectly) reports CS1720 default(T7).E(); } static void E(this object o) { } }"; CreateCompilationWithMscorlib40(source, references: new[] { Net40.SystemCore }, parseOptions: TestOptions.Regular7_3).VerifyDiagnostics( // (20,9): warning CS1720: Expression will always cause a System.NullReferenceException because the default value of 'object' is null // default(object).GetHashCode(); Diagnostic(ErrorCode.WRN_DotOnDefault, "default(object).GetHashCode").WithArguments("object").WithLocation(20, 9), // (24,9): warning CS1720: Expression will always cause a System.NullReferenceException because the default value of 'T4' is null // default(T4).GetHashCode(); Diagnostic(ErrorCode.WRN_DotOnDefault, "default(T4).GetHashCode").WithArguments("T4").WithLocation(24, 9), // (26,9): warning CS1720: Expression will always cause a System.NullReferenceException because the default value of 'T6' is null // default(T6).GetHashCode(); Diagnostic(ErrorCode.WRN_DotOnDefault, "default(T6).GetHashCode").WithArguments("T6").WithLocation(26, 9), // (28,9): warning CS1720: Expression will always cause a System.NullReferenceException because the default value of 'T6' is null // default(T6).P = null; Diagnostic(ErrorCode.WRN_DotOnDefault, "default(T6).P").WithArguments("T6").WithLocation(28, 9)); CreateCompilationWithMscorlib40(source, references: new[] { Net40.SystemCore }, options: TestOptions.ReleaseDll.WithNullableContextOptions(NullableContextOptions.Disable)).VerifyDiagnostics( ); } [Fact] public void CS1720WRN_DotOnDefault02() { var source = @"class A { internal object this[object index] { get { return null; } set { } } } struct S { internal object this[object index] { get { return null; } set { } } } interface I { object this[object index] { get; set; } } class C { unsafe static void M<T1, T2, T3, T4>() where T1 : A where T2 : I where T3 : struct, I where T4 : class, I { object o; o = default(int*)[0]; o = default(A)[0]; o = default(S)[0]; o = default(I)[0]; o = default(object[])[0]; o = default(T1)[0]; o = default(T2)[0]; o = default(T3)[0]; o = default(T4)[0]; default(int*)[1] = 1; default(A)[1] = o; default(I)[1] = o; default(object[])[1] = o; default(T1)[1] = o; default(T2)[1] = o; default(T3)[1] = o; default(T4)[1] = o; } }"; CreateCompilation(source, options: TestOptions.UnsafeReleaseDll, parseOptions: TestOptions.Regular7_3).VerifyDiagnostics( // (23,13): warning CS1720: Expression will always cause a System.NullReferenceException because the default value of 'A' is null Diagnostic(ErrorCode.WRN_DotOnDefault, "default(A)[0]").WithArguments("A").WithLocation(23, 13), // (25,13): warning CS1720: Expression will always cause a System.NullReferenceException because the default value of 'I' is null Diagnostic(ErrorCode.WRN_DotOnDefault, "default(I)[0]").WithArguments("I").WithLocation(25, 13), // (26,13): warning CS1720: Expression will always cause a System.NullReferenceException because the default value of 'object[]' is null Diagnostic(ErrorCode.WRN_DotOnDefault, "default(object[])[0]").WithArguments("object[]").WithLocation(26, 13), // (27,13): warning CS1720: Expression will always cause a System.NullReferenceException because the default value of 'T1' is null Diagnostic(ErrorCode.WRN_DotOnDefault, "default(T1)[0]").WithArguments("T1").WithLocation(27, 13), // (30,13): warning CS1720: Expression will always cause a System.NullReferenceException because the default value of 'T4' is null Diagnostic(ErrorCode.WRN_DotOnDefault, "default(T4)[0]").WithArguments("T4").WithLocation(30, 13), // (32,9): warning CS1720: Expression will always cause a System.NullReferenceException because the default value of 'A' is null Diagnostic(ErrorCode.WRN_DotOnDefault, "default(A)[1]").WithArguments("A").WithLocation(32, 9), // (33,9): warning CS1720: Expression will always cause a System.NullReferenceException because the default value of 'I' is null Diagnostic(ErrorCode.WRN_DotOnDefault, "default(I)[1]").WithArguments("I").WithLocation(33, 9), // (34,9): warning CS1720: Expression will always cause a System.NullReferenceException because the default value of 'object[]' is null Diagnostic(ErrorCode.WRN_DotOnDefault, "default(object[])[1]").WithArguments("object[]").WithLocation(34, 9), // (35,9): warning CS1720: Expression will always cause a System.NullReferenceException because the default value of 'T1' is null Diagnostic(ErrorCode.WRN_DotOnDefault, "default(T1)[1]").WithArguments("T1").WithLocation(35, 9), // (37,9): error CS0131: The left-hand side of an assignment must be a variable, property or indexer Diagnostic(ErrorCode.ERR_AssgLvalueExpected, "default(T3)[1]").WithLocation(37, 9), // Incorrect? See CS0131ERR_AssgLvalueExpected03 unit test. // (38,9): warning CS1720: Expression will always cause a System.NullReferenceException because the default value of 'T4' is null Diagnostic(ErrorCode.WRN_DotOnDefault, "default(T4)[1]").WithArguments("T4").WithLocation(38, 9)); CreateCompilation(source, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (37,9): error CS0131: The left-hand side of an assignment must be a variable, property or indexer // default(T3)[1] = o; Diagnostic(ErrorCode.ERR_AssgLvalueExpected, "default(T3)[1]").WithLocation(37, 9)); } [Fact] public void CS1720WRN_DotOnDefault03() { var source = @"static class A { static void Main() { System.Console.WriteLine(default(string).IsNull()); } internal static bool IsNull(this string val) { return (object)val == null; } } "; CompileAndVerifyWithMscorlib40(source, expectedOutput: "True", references: new[] { Net40.SystemCore }, parseOptions: TestOptions.Regular7_3).VerifyDiagnostics( // Do not report the following warning: // (5,34): warning CS1720: Expression will always cause a System.NullReferenceException because the default value of 'string' is null // System.Console.WriteLine(default(string).IsNull()); // Diagnostic(ErrorCode.WRN_DotOnDefault, "default(string).IsNull").WithArguments("string").WithLocation(5, 34) ); CompileAndVerifyWithMscorlib40(source, expectedOutput: "True", references: new[] { Net40.SystemCore }).VerifyDiagnostics(); } [Fact] public void CS1723WRN_BadXMLRefTypeVar() { var text = @" ///<summary>A generic list class.</summary> ///<see cref=""T"" /> // CS1723 public class List<T> { } "; CreateCompilationWithMscorlib40AndDocumentationComments(text).VerifyDiagnostics( // (3,15): warning CS1723: XML comment has cref attribute 'T' that refers to a type parameter // ///<see cref="T" /> // CS1723 Diagnostic(ErrorCode.WRN_BadXMLRefTypeVar, "T").WithArguments("T")); } [Fact] public void CS1974WRN_DynamicDispatchToConditionalMethod() { var text = @" using System.Diagnostics; class Myclass { static void Main() { dynamic d = null; // Warning because Goo might be conditional. Goo(d); // No warning; only the two-parameter Bar is conditional. Bar(d); } [Conditional(""DEBUG"")] static void Goo(string d) {} [Conditional(""DEBUG"")] static void Bar(int x, int y) {} static void Bar(string x) {} }"; var comp = CreateCompilationWithMscorlib40AndSystemCore(text); comp.VerifyDiagnostics( // (9,9): warning CS1974: The dynamically dispatched call to method 'Goo' may fail at runtime because one or more applicable overloads are conditional methods. // Goo(d); Diagnostic(ErrorCode.WRN_DynamicDispatchToConditionalMethod, "Goo(d)").WithArguments("Goo")); } [Fact] public void CS1981WRN_IsDynamicIsConfusing() { var text = @" public class D : C { } public class C { public static int Main() { // is dynamic bool bi = 123 is dynamic; // dynamicType is valueType dynamic i2 = 123; bi = i2 is int; // dynamicType is refType dynamic c = new D(); bi = c is C; dynamic c2 = new C(); bi = c is C; // valueType as dynamic int i = 123 as dynamic; // refType as dynamic dynamic c3 = new D() as dynamic; // dynamicType as dynamic dynamic s = ""asd""; string s2 = s as dynamic; // default(dynamic) dynamic d = default(dynamic); // dynamicType as valueType : generate error int k = i2 as int; // dynamicType as refType C c4 = c3 as C; return 0; } }"; CreateCompilation(text).VerifyDiagnostics( // (7,19): 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 Diagnostic(ErrorCode.WRN_IsDynamicIsConfusing, "123 is dynamic").WithArguments("is", "dynamic", "Object"), // (7,19): warning CS0183: The given expression is always of the provided ('dynamic') type Diagnostic(ErrorCode.WRN_IsAlwaysTrue, "123 is dynamic").WithArguments("dynamic"), // (27,17): error CS0077: The as operator must be used with a reference type // or nullable type ('int' is a non-nullable value type) Diagnostic(ErrorCode.ERR_AsMustHaveReferenceType, "i2 as int").WithArguments("int"), // (26,17): warning CS0219: The variable 'd' is assigned but its value is never used Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "d").WithArguments("d")); } [Fact] public void CS7003ERR_UnexpectedUnboundGenericName() { var text = @" class C<T> { void M(System.Type t) { M(typeof(C<C<>>)); //unbound inside bound M(typeof(C<>[])); //array of unbound M(typeof(C<>.D<int>)); //unbound containing bound M(typeof(C<int>.D<>)); //bound containing unbound M(typeof(D<,>[])); //multiple type parameters } class D<U> { } } class D<T, U> {}"; // NOTE: Dev10 reports CS1031 (type expected) - CS7003 is new. CreateCompilation(text).VerifyDiagnostics( // (6,20): error CS7003: Unexpected use of an unbound generic name Diagnostic(ErrorCode.ERR_UnexpectedUnboundGenericName, "C<>"), // (7,18): error CS7003: Unexpected use of an unbound generic name Diagnostic(ErrorCode.ERR_UnexpectedUnboundGenericName, "C<>"), // (8,18): error CS7003: Unexpected use of an unbound generic name Diagnostic(ErrorCode.ERR_UnexpectedUnboundGenericName, "C<>"), // (9,25): error CS7003: Unexpected use of an unbound generic name Diagnostic(ErrorCode.ERR_UnexpectedUnboundGenericName, "D<>"), // (10,18): error CS7003: Unexpected use of an unbound generic name Diagnostic(ErrorCode.ERR_UnexpectedUnboundGenericName, "D<,>")); } [Fact] public void CS7003ERR_UnexpectedUnboundGenericName_Nested() { var text = @" class Outer<T> { public static void Print() { System.Console.WriteLine(typeof(Inner<>)); System.Console.WriteLine(typeof(Inner<T>)); System.Console.WriteLine(typeof(Inner<int>)); System.Console.WriteLine(typeof(Outer<>.Inner<>)); System.Console.WriteLine(typeof(Outer<>.Inner<T>)); //CS7003 System.Console.WriteLine(typeof(Outer<>.Inner<int>)); //CS7003 System.Console.WriteLine(typeof(Outer<T>.Inner<>)); //CS7003 System.Console.WriteLine(typeof(Outer<T>.Inner<T>)); System.Console.WriteLine(typeof(Outer<T>.Inner<int>)); System.Console.WriteLine(typeof(Outer<int>.Inner<>)); //CS7003 System.Console.WriteLine(typeof(Outer<int>.Inner<T>)); System.Console.WriteLine(typeof(Outer<int>.Inner<int>)); } class Inner<U> { } }"; // NOTE: Dev10 reports CS1031 (type expected) - CS7003 is new. CreateCompilation(text).VerifyDiagnostics( // (11,41): error CS7003: Unexpected use of an unbound generic name Diagnostic(ErrorCode.ERR_UnexpectedUnboundGenericName, "Outer<>"), // (12,41): error CS7003: Unexpected use of an unbound generic name Diagnostic(ErrorCode.ERR_UnexpectedUnboundGenericName, "Outer<>"), // (14,50): error CS7003: Unexpected use of an unbound generic name Diagnostic(ErrorCode.ERR_UnexpectedUnboundGenericName, "Inner<>"), // (18,52): error CS7003: Unexpected use of an unbound generic name Diagnostic(ErrorCode.ERR_UnexpectedUnboundGenericName, "Inner<>")); } [Fact(), WorkItem(529583, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529583")] public void CS7003ERR_UnexpectedUnboundGenericName_Attributes() { var text = @" using System; class Outer<T> { public class Inner<U> { } } [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] class Attr : Attribute { public Attr(Type t) { } } [Attr(typeof(Outer<>.Inner<>))] [Attr(typeof(Outer<int>.Inner<>))] [Attr(typeof(Outer<>.Inner<int>))] [Attr(typeof(Outer<int>.Inner<int>))] public class Test { public static void Main() { } }"; // NOTE: Dev10 reports CS1031 (type expected) - CS7003 is new. CreateCompilation(text).VerifyDiagnostics( // (21,25): error CS7003: Unexpected use of an unbound generic name // [Attr(typeof(Outer<int>.Inner<>))] Diagnostic(ErrorCode.ERR_UnexpectedUnboundGenericName, "Inner<>"), // (22,14): error CS7003: Unexpected use of an unbound generic name // [Attr(typeof(Outer<>.Inner<int>))] Diagnostic(ErrorCode.ERR_UnexpectedUnboundGenericName, "Outer<>")); } [Fact] public void CS7013WRN_MetadataNameTooLong() { var text = @" namespace Namespace1.Namespace2 { public interface I<T> { void Goo(); } public class OuterGenericClass<T, S> { public class NestedClass : OuterGenericClass<NestedClass, NestedClass> { } public class C : I<NestedClass.NestedClass.NestedClass.NestedClass.NestedClass> { void I<NestedClass.NestedClass.NestedClass.NestedClass.NestedClass>.Goo() { } } } } "; // This error will necessarily have a very long error string. CreateCompilation(text).VerifyEmitDiagnostics( Diagnostic(ErrorCode.ERR_MetadataNameTooLong, "Goo").WithArguments("Namespace1.Namespace2.I<Namespace1.Namespace2.OuterGenericClass<Namespace1.Namespace2.OuterGenericClass<Namespace1.Namespace2.OuterGenericClass<Namespace1.Namespace2.OuterGenericClass<Namespace1.Namespace2.OuterGenericClass<T,S>.NestedClass,Namespace1.Namespace2.OuterGenericClass<T,S>.NestedClass>.NestedClass,Namespace1.Namespace2.OuterGenericClass<Namespace1.Namespace2.OuterGenericClass<T,S>.NestedClass,Namespace1.Namespace2.OuterGenericClass<T,S>.NestedClass>.NestedClass>.NestedClass,Namespace1.Namespace2.OuterGenericClass<Namespace1.Namespace2.OuterGenericClass<Namespace1.Namespace2.OuterGenericClass<T,S>.NestedClass,Namespace1.Namespace2.OuterGenericClass<T,S>.NestedClass>.NestedClass,Namespace1.Namespace2.OuterGenericClass<Namespace1.Namespace2.OuterGenericClass<T,S>.NestedClass,Namespace1.Namespace2.OuterGenericClass<T,S>.NestedClass>.NestedClass>.NestedClass>.NestedClass,Namespace1.Namespace2.OuterGenericClass<Namespace1.Namespace2.OuterGenericClass<Namespace1.Namespace2.OuterGenericClass<Namespace1.Namespace2.OuterGenericClass<T,S>.NestedClass,Namespace1.Namespace2.OuterGenericClass<T,S>.NestedClass>.NestedClass,Namespace1.Namespace2.OuterGenericClass<Namespace1.Namespace2.OuterGenericClass<T,S>.NestedClass,Namespace1.Namespace2.OuterGenericClass<T,S>.NestedClass>.NestedClass>.NestedClass,Namespace1.Namespace2.OuterGenericClass<Namespace1.Namespace2.OuterGenericClass<Namespace1.Namespace2.OuterGenericClass<T,S>.NestedClass,Namespace1.Namespace2.OuterGenericClass<T,S>.NestedClass>.NestedClass,Namespace1.Namespace2.OuterGenericClass<Namespace1.Namespace2.OuterGenericClass<T,S>.NestedClass,Namespace1.Namespace2.OuterGenericClass<T,S>.NestedClass>.NestedClass>.NestedClass>.NestedClass>.NestedClass>.Goo")); } #endregion #region shotgun tests [Fact] public void DelegateCreationBad() { var text = @" namespace CSSample { class Program { static void Main(string[] args) { } delegate void D1(); delegate void D2(); delegate int D3(int x); static D1 d1; static D2 d2; static D3 d3; internal virtual void V() { } void M() { } static void S() { } static int M2(int x) { return x; } static void F(Program p) { // Error cases d1 = new D1(2 + 2); d1 = new D1(d3); d1 = new D1(2, 3); d1 = new D1(x: 3); d1 = new D1(M2); } } } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (28,25): error CS0149: Method name expected // d1 = new D1(2 + 2); Diagnostic(ErrorCode.ERR_MethodNameExpected, "2 + 2").WithLocation(28, 25), // (29,18): error CS0123: No overload for 'Program.D3.Invoke(int)' matches delegate 'Program.D1' // d1 = new D1(d3); Diagnostic(ErrorCode.ERR_MethDelegateMismatch, "new D1(d3)").WithArguments("CSSample.Program.D3.Invoke(int)", "CSSample.Program.D1").WithLocation(29, 18), // (30,25): error CS0149: Method name expected // d1 = new D1(2, 3); Diagnostic(ErrorCode.ERR_MethodNameExpected, "2, 3").WithLocation(30, 25), // (31,28): error CS0149: Method name expected // d1 = new D1(x: 3); Diagnostic(ErrorCode.ERR_MethodNameExpected, "3").WithLocation(31, 28), // (32,18): error CS0123: No overload for 'M2' matches delegate 'Program.D1' // d1 = new D1(M2); Diagnostic(ErrorCode.ERR_MethDelegateMismatch, "new D1(M2)").WithArguments("M2", "CSSample.Program.D1").WithLocation(32, 18), // (16,19): warning CS0169: The field 'Program.d2' is never used // static D2 d2; Diagnostic(ErrorCode.WRN_UnreferencedField, "d2").WithArguments("CSSample.Program.d2").WithLocation(16, 19), // (17,19): warning CS0649: Field 'Program.d3' is never assigned to, and will always have its default value null // static D3 d3; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "d3").WithArguments("CSSample.Program.d3", "null").WithLocation(17, 19)); } [Fact, WorkItem(7359, "https://github.com/dotnet/roslyn/issues/7359")] public void DelegateCreationWithRefOut() { var source = @" using System; public class Program { static Func<T, T> Goo<T>(Func<T, T> t) { return t; } static Func<string, string> Bar = Goo<string>(x => x); static Func<string, string> BarP => Goo<string>(x => x); static T Id<T>(T id) => id; static void Test(Func<string, string> Baz) { var k = Bar; var z1 = new Func<string, string>(ref Bar); // compat var z2 = new Func<string, string>(ref Baz); // compat var z3 = new Func<string, string>(ref k); // compat var z4 = new Func<string, string>(ref x => x); var z5 = new Func<string, string>(ref Goo<string>(x => x)); var z6 = new Func<string, string>(ref BarP); var z7 = new Func<string, string>(ref new Func<string, string>(x => x)); var z8 = new Func<string, string>(ref Program.BarP); var z9 = new Func<string, string>(ref Program.Goo<string>(x => x)); var z10 = new Func<string, string>(ref Id); // compat var z11 = new Func<string, string>(ref new(x => x)); } }"; CreateCompilation(source).VerifyDiagnostics( // (16,47): error CS1510: A ref or out argument must be an assignable variable // var z4 = new Func<string, string>(ref x => x); Diagnostic(ErrorCode.ERR_RefLvalueExpected, "x => x").WithLocation(16, 47), // (17,47): error CS1510: A ref or out argument must be an assignable variable // var z5 = new Func<string, string>(ref Goo<string>(x => x)); Diagnostic(ErrorCode.ERR_RefLvalueExpected, "Goo<string>(x => x)").WithLocation(17, 47), // (18,43): error CS0206: A property or indexer may not be passed as an out or ref parameter // var z6 = new Func<string, string>(ref BarP); Diagnostic(ErrorCode.ERR_RefProperty, "ref BarP").WithArguments("Program.BarP").WithLocation(18, 43), // (19,47): error CS1510: A ref or out argument must be an assignable variable // var z7 = new Func<string, string>(ref new Func<string, string>(x => x)); Diagnostic(ErrorCode.ERR_RefLvalueExpected, "new Func<string, string>(x => x)").WithLocation(19, 47), // (20,43): error CS0206: A property or indexer may not be passed as an out or ref parameter // var z8 = new Func<string, string>(ref Program.BarP); Diagnostic(ErrorCode.ERR_RefProperty, "ref Program.BarP").WithArguments("Program.BarP").WithLocation(20, 43), // (21,47): error CS1510: A ref or out argument must be an assignable variable // var z9 = new Func<string, string>(ref Program.Goo<string>(x => x)); Diagnostic(ErrorCode.ERR_RefLvalueExpected, "Program.Goo<string>(x => x)").WithLocation(21, 47), // (23,48): error CS1510: A ref or out value must be an assignable variable // var z11 = new Func<string, string>(ref new(x => x)); Diagnostic(ErrorCode.ERR_RefLvalueExpected, "new(x => x)").WithLocation(23, 48) ); CreateCompilation(source, parseOptions: TestOptions.Regular.WithStrictFeature()).VerifyDiagnostics( // (13,47): error CS0149: Method name expected // var z1 = new Func<string, string>(ref Bar); // compat Diagnostic(ErrorCode.ERR_MethodNameExpected, "Bar").WithLocation(13, 47), // (14,47): error CS0149: Method name expected // var z2 = new Func<string, string>(ref Baz); // compat Diagnostic(ErrorCode.ERR_MethodNameExpected, "Baz").WithLocation(14, 47), // (15,47): error CS0149: Method name expected // var z3 = new Func<string, string>(ref k); // compat Diagnostic(ErrorCode.ERR_MethodNameExpected, "k").WithLocation(15, 47), // (16,47): error CS1510: A ref or out argument must be an assignable variable // var z4 = new Func<string, string>(ref x => x); Diagnostic(ErrorCode.ERR_RefLvalueExpected, "x => x").WithLocation(16, 47), // (17,47): error CS1510: A ref or out argument must be an assignable variable // var z5 = new Func<string, string>(ref Goo<string>(x => x)); Diagnostic(ErrorCode.ERR_RefLvalueExpected, "Goo<string>(x => x)").WithLocation(17, 47), // (18,47): error CS0206: A property or indexer may not be passed as an out or ref parameter // var z6 = new Func<string, string>(ref BarP); Diagnostic(ErrorCode.ERR_RefProperty, "BarP").WithArguments("Program.BarP").WithLocation(18, 47), // (19,47): error CS1510: A ref or out argument must be an assignable variable // var z7 = new Func<string, string>(ref new Func<string, string>(x => x)); Diagnostic(ErrorCode.ERR_RefLvalueExpected, "new Func<string, string>(x => x)").WithLocation(19, 47), // (20,47): error CS0206: A property or indexer may not be passed as an out or ref parameter // var z8 = new Func<string, string>(ref Program.BarP); Diagnostic(ErrorCode.ERR_RefProperty, "Program.BarP").WithArguments("Program.BarP").WithLocation(20, 47), // (21,47): error CS1510: A ref or out argument must be an assignable variable // var z9 = new Func<string, string>(ref Program.Goo<string>(x => x)); Diagnostic(ErrorCode.ERR_RefLvalueExpected, "Program.Goo<string>(x => x)").WithLocation(21, 47), // (22,48): error CS1657: Cannot pass 'Id' as a ref or out argument because it is a 'method group' // var z10 = new Func<string, string>(ref Id); // compat Diagnostic(ErrorCode.ERR_RefReadonlyLocalCause, "Id").WithArguments("Id", "method group").WithLocation(22, 48), // (23,48): error CS1510: A ref or out value must be an assignable variable // var z11 = new Func<string, string>(ref new(x => x)); Diagnostic(ErrorCode.ERR_RefLvalueExpected, "new(x => x)").WithLocation(23, 48) ); } [Fact, WorkItem(7359, "https://github.com/dotnet/roslyn/issues/7359")] public void DelegateCreationWithRefOut_Parens() { // these are allowed in compat mode without the parenthesis // with parenthesis, it behaves like strict mode var source = @" using System; public class Program { static Func<T, T> Goo<T>(Func<T, T> t) { return t; } static Func<string, string> Bar = Goo<string>(x => x); static T Id<T>(T id) => id; static void Test(Func<string, string> Baz) { var k = Bar; var z1 = new Func<string, string>(ref (Bar)); var z2 = new Func<string, string>(ref (Baz)); var z3 = new Func<string, string>(ref (k)); var z10 = new Func<string, string>(ref (Id)); // these all are still valid for compat mode, no errors should be reported for compat mode var z4 = new Func<string, string>(ref Bar); var z5 = new Func<string, string>(ref Baz); var z6 = new Func<string, string>(ref k); var z7 = new Func<string, string>(ref Id); } }"; CreateCompilation(source).VerifyDiagnostics( // (13,48): error CS0149: Method name expected // var z1 = new Func<string, string>(ref (Bar)); Diagnostic(ErrorCode.ERR_MethodNameExpected, "Bar").WithLocation(13, 48), // (14,48): error CS0149: Method name expected // var z2 = new Func<string, string>(ref (Baz)); Diagnostic(ErrorCode.ERR_MethodNameExpected, "Baz").WithLocation(14, 48), // (15,48): error CS0149: Method name expected // var z3 = new Func<string, string>(ref (k)); Diagnostic(ErrorCode.ERR_MethodNameExpected, "k").WithLocation(15, 48), // (16,49): error CS1657: Cannot pass 'Id' as a ref or out argument because it is a 'method group' // var z10 = new Func<string, string>(ref (Id)); Diagnostic(ErrorCode.ERR_RefReadonlyLocalCause, "Id").WithArguments("Id", "method group").WithLocation(16, 49)); CreateCompilation(source, parseOptions: TestOptions.Regular.WithStrictFeature()).VerifyDiagnostics( // (13,48): error CS0149: Method name expected // var z1 = new Func<string, string>(ref (Bar)); Diagnostic(ErrorCode.ERR_MethodNameExpected, "Bar").WithLocation(13, 48), // (14,48): error CS0149: Method name expected // var z2 = new Func<string, string>(ref (Baz)); Diagnostic(ErrorCode.ERR_MethodNameExpected, "Baz").WithLocation(14, 48), // (15,48): error CS0149: Method name expected // var z3 = new Func<string, string>(ref (k)); Diagnostic(ErrorCode.ERR_MethodNameExpected, "k").WithLocation(15, 48), // (16,49): error CS1657: Cannot pass 'Id' as a ref or out argument because it is a 'method group' // var z10 = new Func<string, string>(ref (Id)); Diagnostic(ErrorCode.ERR_RefReadonlyLocalCause, "Id").WithArguments("Id", "method group").WithLocation(16, 49), // (18,47): error CS0149: Method name expected // var z4 = new Func<string, string>(ref Bar); Diagnostic(ErrorCode.ERR_MethodNameExpected, "Bar").WithLocation(18, 47), // (19,47): error CS0149: Method name expected // var z5 = new Func<string, string>(ref Baz); Diagnostic(ErrorCode.ERR_MethodNameExpected, "Baz").WithLocation(19, 47), // (20,47): error CS0149: Method name expected // var z6 = new Func<string, string>(ref k); Diagnostic(ErrorCode.ERR_MethodNameExpected, "k").WithLocation(20, 47), // (21,47): error CS1657: Cannot pass 'Id' as a ref or out argument because it is a 'method group' // var z7 = new Func<string, string>(ref Id); Diagnostic(ErrorCode.ERR_RefReadonlyLocalCause, "Id").WithArguments("Id", "method group").WithLocation(21, 47)); } [Fact, WorkItem(7359, "https://github.com/dotnet/roslyn/issues/7359")] public void DelegateCreationWithRefOut_MultipleArgs() { var source = @" using System; public class Program { static Func<string, string> BarP => null; static void Test(Func<string, string> Baz) { var a = new Func<string, string>(ref Baz, Baz.Invoke); var b = new Func<string, string>(Baz, ref Baz.Invoke); var c = new Func<string, string>(ref Baz, ref Baz.Invoke); var d = new Func<string, string>(ref BarP, BarP.Invoke); var e = new Func<string, string>(BarP, ref BarP.Invoke); var f = new Func<string, string>(ref BarP, ref BarP.Invoke); } }"; CreateCompilation(source).VerifyDiagnostics( // (8,46): error CS0149: Method name expected // var a = new Func<string, string>(ref Baz, Baz.Invoke); Diagnostic(ErrorCode.ERR_MethodNameExpected, "Baz, Baz.Invoke").WithLocation(8, 46), // (9,42): error CS0149: Method name expected // var b = new Func<string, string>(Baz, ref Baz.Invoke); Diagnostic(ErrorCode.ERR_MethodNameExpected, "Baz, ref Baz.Invoke").WithLocation(9, 42), // (10,46): error CS0149: Method name expected // var c = new Func<string, string>(ref Baz, ref Baz.Invoke); Diagnostic(ErrorCode.ERR_MethodNameExpected, "Baz, ref Baz.Invoke").WithLocation(10, 46), // (11,42): error CS0206: A property or indexer may not be passed as an out or ref parameter // var d = new Func<string, string>(ref BarP, BarP.Invoke); Diagnostic(ErrorCode.ERR_RefProperty, "ref BarP").WithArguments("Program.BarP").WithLocation(11, 42), // (11,46): error CS0149: Method name expected // var d = new Func<string, string>(ref BarP, BarP.Invoke); Diagnostic(ErrorCode.ERR_MethodNameExpected, "BarP, BarP.Invoke").WithLocation(11, 46), // (12,42): error CS0149: Method name expected // var e = new Func<string, string>(BarP, ref BarP.Invoke); Diagnostic(ErrorCode.ERR_MethodNameExpected, "BarP, ref BarP.Invoke").WithLocation(12, 42), // (13,42): error CS0206: A property or indexer may not be passed as an out or ref parameter // var f = new Func<string, string>(ref BarP, ref BarP.Invoke); Diagnostic(ErrorCode.ERR_RefProperty, "ref BarP").WithArguments("Program.BarP").WithLocation(13, 42), // (13,46): error CS0149: Method name expected // var f = new Func<string, string>(ref BarP, ref BarP.Invoke); Diagnostic(ErrorCode.ERR_MethodNameExpected, "BarP, ref BarP.Invoke").WithLocation(13, 46) ); } [WorkItem(538430, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538430")] [Fact] public void NestedGenericAccessibility() { var text = @" public class C<T> { } public class E { class D : C<D> { } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { }); } [WorkItem(542419, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542419")] [Fact] public void EmptyAngleBrackets() { var text = @" class Program { int f; int P { get; set; } int M() { return 0; } interface I { } class C { } struct S { } delegate void D(); void Test(object p) { int l = 0; Test(l<>); Test(p<>); Test(f<>); Test(P<>); Test(M<>()); Test(this.f<>); Test(this.P<>); Test(this.M<>()); System.Func<int> m; m = M<>; m = this.M<>; I<> i1 = null; C<> c1 = new C(); C c2 = new C<>(); S<> s1 = new S(); S s2 = new S<>(); D<> d1 = null; Program.I<> i2 = null; Program.C<> c3 = new Program.C(); Program.C c4 = new Program.C<>(); Program.S<> s3 = new Program.S(); Program.S s4 = new Program.S<>(); Program.D<> d2 = null; Test(default(I<>)); Test(default(C<>)); Test(default(S<>)); Test(default(Program.I<>)); Test(default(Program.C<>)); Test(default(Program.S<>)); string s; s = typeof(I<>).Name; s = typeof(C<>).Name; s = typeof(S<>).Name; s = typeof(Program.I<>).Name; s = typeof(Program.C<>).Name; s = typeof(Program.S<>).Name; } } "; CreateCompilation(text).VerifyDiagnostics( // (16,14): error CS0307: The variable 'l' cannot be used with type arguments // Test(l<>); Diagnostic(ErrorCode.ERR_TypeArgsNotAllowed, "l<>").WithArguments("l", "variable").WithLocation(16, 14), // (17,14): error CS0307: The variable 'object' cannot be used with type arguments // Test(p<>); Diagnostic(ErrorCode.ERR_TypeArgsNotAllowed, "p<>").WithArguments("object", "variable").WithLocation(17, 14), // (19,14): error CS0307: The field 'Program.f' cannot be used with type arguments // Test(f<>); Diagnostic(ErrorCode.ERR_TypeArgsNotAllowed, "f<>").WithArguments("Program.f", "field").WithLocation(19, 14), // (20,14): error CS0307: The property 'Program.P' cannot be used with type arguments // Test(P<>); Diagnostic(ErrorCode.ERR_TypeArgsNotAllowed, "P<>").WithArguments("Program.P", "property").WithLocation(20, 14), // (21,14): error CS0308: The non-generic method 'Program.M()' cannot be used with type arguments // Test(M<>()); Diagnostic(ErrorCode.ERR_HasNoTypeVars, "M<>").WithArguments("Program.M()", "method").WithLocation(21, 14), // (23,14): error CS8389: Omitting the type argument is not allowed in the current context // Test(this.f<>); Diagnostic(ErrorCode.ERR_OmittedTypeArgument, "this.f<>").WithLocation(23, 14), // (23,19): error CS0307: The field 'Program.f' cannot be used with type arguments // Test(this.f<>); Diagnostic(ErrorCode.ERR_TypeArgsNotAllowed, "f<>").WithArguments("Program.f", "field").WithLocation(23, 19), // (24,14): error CS8389: Omitting the type argument is not allowed in the current context // Test(this.P<>); Diagnostic(ErrorCode.ERR_OmittedTypeArgument, "this.P<>").WithLocation(24, 14), // (24,19): error CS0307: The property 'Program.P' cannot be used with type arguments // Test(this.P<>); Diagnostic(ErrorCode.ERR_TypeArgsNotAllowed, "P<>").WithArguments("Program.P", "property").WithLocation(24, 19), // (25,14): error CS8389: Omitting the type argument is not allowed in the current context // Test(this.M<>()); Diagnostic(ErrorCode.ERR_OmittedTypeArgument, "this.M<>").WithLocation(25, 14), // (25,19): error CS0308: The non-generic method 'Program.M()' cannot be used with type arguments // Test(this.M<>()); Diagnostic(ErrorCode.ERR_HasNoTypeVars, "M<>").WithArguments("Program.M()", "method").WithLocation(25, 19), // (29,13): error CS0308: The non-generic method 'Program.M()' cannot be used with type arguments // m = M<>; Diagnostic(ErrorCode.ERR_HasNoTypeVars, "M<>").WithArguments("Program.M()", "method").WithLocation(29, 13), // (30,13): error CS8389: Omitting the type argument is not allowed in the current context // m = this.M<>; Diagnostic(ErrorCode.ERR_OmittedTypeArgument, "this.M<>").WithLocation(30, 13), // (30,18): error CS0308: The non-generic method 'Program.M()' cannot be used with type arguments // m = this.M<>; Diagnostic(ErrorCode.ERR_HasNoTypeVars, "M<>").WithArguments("Program.M()", "method").WithLocation(30, 18), // (32,9): error CS0308: The non-generic type 'Program.I' cannot be used with type arguments // I<> i1 = null; Diagnostic(ErrorCode.ERR_HasNoTypeVars, "I<>").WithArguments("Program.I", "type").WithLocation(32, 9), // (33,9): error CS0308: The non-generic type 'Program.C' cannot be used with type arguments // C<> c1 = new C(); Diagnostic(ErrorCode.ERR_HasNoTypeVars, "C<>").WithArguments("Program.C", "type").WithLocation(33, 9), // (34,20): error CS0308: The non-generic type 'Program.C' cannot be used with type arguments // C c2 = new C<>(); Diagnostic(ErrorCode.ERR_HasNoTypeVars, "C<>").WithArguments("Program.C", "type").WithLocation(34, 20), // (35,9): error CS0308: The non-generic type 'Program.S' cannot be used with type arguments // S<> s1 = new S(); Diagnostic(ErrorCode.ERR_HasNoTypeVars, "S<>").WithArguments("Program.S", "type").WithLocation(35, 9), // (36,20): error CS0308: The non-generic type 'Program.S' cannot be used with type arguments // S s2 = new S<>(); Diagnostic(ErrorCode.ERR_HasNoTypeVars, "S<>").WithArguments("Program.S", "type").WithLocation(36, 20), // (37,9): error CS0308: The non-generic type 'Program.D' cannot be used with type arguments // D<> d1 = null; Diagnostic(ErrorCode.ERR_HasNoTypeVars, "D<>").WithArguments("Program.D", "type").WithLocation(37, 9), // (39,17): error CS0308: The non-generic type 'Program.I' cannot be used with type arguments // Program.I<> i2 = null; Diagnostic(ErrorCode.ERR_HasNoTypeVars, "I<>").WithArguments("Program.I", "type").WithLocation(39, 17), // (40,17): error CS0308: The non-generic type 'Program.C' cannot be used with type arguments // Program.C<> c3 = new Program.C(); Diagnostic(ErrorCode.ERR_HasNoTypeVars, "C<>").WithArguments("Program.C", "type").WithLocation(40, 17), // (41,36): error CS0308: The non-generic type 'Program.C' cannot be used with type arguments // Program.C c4 = new Program.C<>(); Diagnostic(ErrorCode.ERR_HasNoTypeVars, "C<>").WithArguments("Program.C", "type").WithLocation(41, 36), // (42,17): error CS0308: The non-generic type 'Program.S' cannot be used with type arguments // Program.S<> s3 = new Program.S(); Diagnostic(ErrorCode.ERR_HasNoTypeVars, "S<>").WithArguments("Program.S", "type").WithLocation(42, 17), // (43,36): error CS0308: The non-generic type 'Program.S' cannot be used with type arguments // Program.S s4 = new Program.S<>(); Diagnostic(ErrorCode.ERR_HasNoTypeVars, "S<>").WithArguments("Program.S", "type").WithLocation(43, 36), // (44,17): error CS0308: The non-generic type 'Program.D' cannot be used with type arguments // Program.D<> d2 = null; Diagnostic(ErrorCode.ERR_HasNoTypeVars, "D<>").WithArguments("Program.D", "type").WithLocation(44, 17), // (46,22): error CS0308: The non-generic type 'Program.I' cannot be used with type arguments // Test(default(I<>)); Diagnostic(ErrorCode.ERR_HasNoTypeVars, "I<>").WithArguments("Program.I", "type").WithLocation(46, 22), // (47,22): error CS0308: The non-generic type 'Program.C' cannot be used with type arguments // Test(default(C<>)); Diagnostic(ErrorCode.ERR_HasNoTypeVars, "C<>").WithArguments("Program.C", "type").WithLocation(47, 22), // (48,22): error CS0308: The non-generic type 'Program.S' cannot be used with type arguments // Test(default(S<>)); Diagnostic(ErrorCode.ERR_HasNoTypeVars, "S<>").WithArguments("Program.S", "type").WithLocation(48, 22), // (50,30): error CS0308: The non-generic type 'Program.I' cannot be used with type arguments // Test(default(Program.I<>)); Diagnostic(ErrorCode.ERR_HasNoTypeVars, "I<>").WithArguments("Program.I", "type").WithLocation(50, 30), // (51,30): error CS0308: The non-generic type 'Program.C' cannot be used with type arguments // Test(default(Program.C<>)); Diagnostic(ErrorCode.ERR_HasNoTypeVars, "C<>").WithArguments("Program.C", "type").WithLocation(51, 30), // (52,30): error CS0308: The non-generic type 'Program.S' cannot be used with type arguments // Test(default(Program.S<>)); Diagnostic(ErrorCode.ERR_HasNoTypeVars, "S<>").WithArguments("Program.S", "type").WithLocation(52, 30), // (56,20): error CS0308: The non-generic type 'Program.I' cannot be used with type arguments // s = typeof(I<>).Name; Diagnostic(ErrorCode.ERR_HasNoTypeVars, "I<>").WithArguments("Program.I", "type").WithLocation(56, 20), // (57,20): error CS0308: The non-generic type 'Program.C' cannot be used with type arguments // s = typeof(C<>).Name; Diagnostic(ErrorCode.ERR_HasNoTypeVars, "C<>").WithArguments("Program.C", "type").WithLocation(57, 20), // (58,20): error CS0308: The non-generic type 'Program.S' cannot be used with type arguments // s = typeof(S<>).Name; Diagnostic(ErrorCode.ERR_HasNoTypeVars, "S<>").WithArguments("Program.S", "type").WithLocation(58, 20), // (60,28): error CS0308: The non-generic type 'Program.I' cannot be used with type arguments // s = typeof(Program.I<>).Name; Diagnostic(ErrorCode.ERR_HasNoTypeVars, "I<>").WithArguments("Program.I", "type").WithLocation(60, 28), // (61,28): error CS0308: The non-generic type 'Program.C' cannot be used with type arguments // s = typeof(Program.C<>).Name; Diagnostic(ErrorCode.ERR_HasNoTypeVars, "C<>").WithArguments("Program.C", "type").WithLocation(61, 28), // (62,28): error CS0308: The non-generic type 'Program.S' cannot be used with type arguments // s = typeof(Program.S<>).Name; Diagnostic(ErrorCode.ERR_HasNoTypeVars, "S<>").WithArguments("Program.S", "type").WithLocation(62, 28), // (4,9): warning CS0649: Field 'Program.f' is never assigned to, and will always have its default value 0 // int f; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "f").WithArguments("Program.f", "0").WithLocation(4, 9) ); } [WorkItem(542419, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542419")] [Fact] public void EmptyAngleBrackets_Events() { var text = @" class Program { event System.Action E; event System.Action F { add { } remove { } } void Test<T>(T p) { Test(E<>); Test(this.E<>); E<> += null; //parse error F<> += null; //parse error this.E<> += null; //parse error this.F<> += null; //parse error } } "; CreateCompilation(text).VerifyDiagnostics( // Parser // (12,11): error CS1525: Invalid expression term '>' // E<> += null; //parse error Diagnostic(ErrorCode.ERR_InvalidExprTerm, ">").WithArguments(">").WithLocation(12, 11), // (12,13): error CS1525: Invalid expression term '+=' // E<> += null; //parse error Diagnostic(ErrorCode.ERR_InvalidExprTerm, "+=").WithArguments("+=").WithLocation(12, 13), // (13,11): error CS1525: Invalid expression term '>' // F<> += null; //parse error Diagnostic(ErrorCode.ERR_InvalidExprTerm, ">").WithArguments(">").WithLocation(13, 11), // (13,13): error CS1525: Invalid expression term '+=' // F<> += null; //parse error Diagnostic(ErrorCode.ERR_InvalidExprTerm, "+=").WithArguments("+=").WithLocation(13, 13), // (15,16): error CS1525: Invalid expression term '>' // this.E<> += null; //parse error Diagnostic(ErrorCode.ERR_InvalidExprTerm, ">").WithArguments(">").WithLocation(15, 16), // (15,18): error CS1525: Invalid expression term '+=' // this.E<> += null; //parse error Diagnostic(ErrorCode.ERR_InvalidExprTerm, "+=").WithArguments("+=").WithLocation(15, 18), // (16,16): error CS1525: Invalid expression term '>' // this.F<> += null; //parse error Diagnostic(ErrorCode.ERR_InvalidExprTerm, ">").WithArguments(">").WithLocation(16, 16), // (16,18): error CS1525: Invalid expression term '+=' // this.F<> += null; //parse error Diagnostic(ErrorCode.ERR_InvalidExprTerm, "+=").WithArguments("+=").WithLocation(16, 18), // Binder // (9,14): error CS0307: The event 'Program.E' cannot be used with type arguments // Test(E<>); Diagnostic(ErrorCode.ERR_TypeArgsNotAllowed, "E<>").WithArguments("Program.E", "event").WithLocation(9, 14), // (10,14): error CS8389: Omitting the type argument is not allowed in the current context // Test(this.E<>); Diagnostic(ErrorCode.ERR_OmittedTypeArgument, "this.E<>").WithLocation(10, 14), // (10,19): error CS0307: The event 'Program.E' cannot be used with type arguments // Test(this.E<>); Diagnostic(ErrorCode.ERR_TypeArgsNotAllowed, "E<>").WithArguments("Program.E", "event").WithLocation(10, 19), // (13,9): error CS0079: The event 'Program.F' can only appear on the left hand side of += or -= // F<> += null; //parse error Diagnostic(ErrorCode.ERR_BadEventUsageNoField, "F").WithArguments("Program.F").WithLocation(13, 9), // (16,14): error CS0079: The event 'Program.F' can only appear on the left hand side of += or -= // this.F<> += null; //parse error Diagnostic(ErrorCode.ERR_BadEventUsageNoField, "F").WithArguments("Program.F").WithLocation(16, 14)); } [WorkItem(542419, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542419")] [WorkItem(542679, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542679")] [Fact] public void EmptyAngleBrackets_TypeParameters() { var text = @" class Program { void Test<T>(T p) { Test(default(T<>)); string s = typeof(T<>).Name; } } "; CreateCompilation(text).VerifyDiagnostics( // (6, 24): error CS0307: The type parameter 'T' cannot be used with type arguments Diagnostic(ErrorCode.ERR_TypeArgsNotAllowed, "T<>").WithArguments("T", "type parameter"), // (7,27): error CS0307: The type parameter 'T' cannot be used with type arguments Diagnostic(ErrorCode.ERR_TypeArgsNotAllowed, "T<>").WithArguments("T", "type parameter")); } [Fact, WorkItem(542796, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542796")] public void EmptyAngleBrackets_TypeWithCorrectArity() { var text = @" class C<T> { static void M() { C<>.M(); } } "; CreateCompilation(text).VerifyDiagnostics( // (6,9): error CS0305: Using the generic type 'C<T>' requires 1 type arguments Diagnostic(ErrorCode.ERR_BadArity, "C<>").WithArguments("C<T>", "type", "1")); } [Fact, WorkItem(542796, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542796")] public void EmptyAngleBrackets_MethodWithCorrectArity() { var text = @" class C { static void M<T>() { M<>(); } } "; CreateCompilation(text).VerifyDiagnostics( // (6,9): error CS0305: Using the generic method group 'M' requires 1 type arguments Diagnostic(ErrorCode.ERR_BadArity, "M<>").WithArguments("M", "method group", "1")); } [Fact, WorkItem(542796, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542796")] public void EmptyAngleBrackets_QualifiedTypeWithCorrectArity() { var text = @" class A { class C<T> { static void M() { A.C<>.M(); } } } "; CreateCompilation(text).VerifyDiagnostics( // (8,15): error CS0305: Using the generic type 'A.C<T>' requires 1 type arguments Diagnostic(ErrorCode.ERR_BadArity, "C<>").WithArguments("A.C<T>", "type", "1")); } [Fact, WorkItem(542796, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542796")] public void EmptyAngleBrackets_QualifiedMethodWithCorrectArity() { var text = @" class C { static void M<T>() { C.M<>(); } } "; CreateCompilation(text).VerifyDiagnostics( // (6,9): error CS0305: Using the generic method group 'M' requires 1 type arguments Diagnostic(ErrorCode.ERR_BadArity, "C.M<>").WithArguments("M", "method group", "1")); } [Fact] public void NamesTooLong() { var longE = new String('e', 1024); var builder = new System.Text.StringBuilder(); builder.Append(@" class C { "); builder.AppendFormat("int {0}1;\n", longE); builder.AppendFormat("event System.Action {0}2;\n", longE); builder.AppendFormat("public void {0}3() {{ }}\n", longE); builder.AppendFormat("public void goo(int {0}4) {{ }}\n", longE); builder.AppendFormat("public string {0}5 {{ get; set; }}\n", longE); builder.AppendLine(@" } "); CreateCompilation(builder.ToString(), null, TestOptions.ReleaseDll.WithGeneralDiagnosticOption(ReportDiagnostic.Suppress)).VerifyEmitDiagnostics( Diagnostic(ErrorCode.ERR_MetadataNameTooLong, longE + 2).WithArguments(longE + 2), //event Diagnostic(ErrorCode.ERR_MetadataNameTooLong, longE + 2).WithArguments(longE + 2), //backing field Diagnostic(ErrorCode.ERR_MetadataNameTooLong, longE + 2).WithArguments("add_" + longE + 2), //accessor Diagnostic(ErrorCode.ERR_MetadataNameTooLong, longE + 2).WithArguments("remove_" + longE + 2), //accessor Diagnostic(ErrorCode.ERR_MetadataNameTooLong, longE + 3).WithArguments(longE + 3), Diagnostic(ErrorCode.ERR_MetadataNameTooLong, longE + 4).WithArguments(longE + 4), Diagnostic(ErrorCode.ERR_MetadataNameTooLong, longE + 5).WithArguments(longE + 5), Diagnostic(ErrorCode.ERR_MetadataNameTooLong, longE + 5).WithArguments("<" + longE + 5 + ">k__BackingField"), Diagnostic(ErrorCode.ERR_MetadataNameTooLong, "get").WithArguments("get_" + longE + 5), Diagnostic(ErrorCode.ERR_MetadataNameTooLong, "set").WithArguments("set_" + longE + 5), Diagnostic(ErrorCode.ERR_MetadataNameTooLong, longE + 1).WithArguments(longE + 1) ); } #endregion #region regression tests [WorkItem(541605, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541605")] [Fact] public void CS0019ERR_ImplicitlyTypedVariableAssignedNullCoalesceExpr() { CreateCompilation(@" class Test { public static void Main() { var p = null ?? null; //CS0019 } } ").VerifyDiagnostics( // error CS0019: Operator '??' cannot be applied to operands of type '<null>' and '<null>' Diagnostic(ErrorCode.ERR_BadBinaryOps, "null ?? null").WithArguments("??", "<null>", "<null>")); } [WorkItem(528577, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528577")] [Fact(Skip = "528577")] public void CS0122ERR_InaccessibleGenericType() { CreateCompilation(@" public class Top<T> { class Outer<U> { } } public class MyClass { public static void Main() { var test = new Top<int>.Outer<string>(); } } ").VerifyDiagnostics( // (13,33): error CS0122: 'Top<int>.Outer<string>' is inaccessible due to its protection level // var test = new Top<int>.Outer<string>(); Diagnostic(ErrorCode.ERR_BadAccess, "new Top<int>.Outer<string>()").WithArguments("Top<int>.Outer<string>")); } [WorkItem(528591, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528591")] [Fact] public void CS0121ERR_IncorrectErrorSpan1() { CreateCompilation(@" class Test { public static void Method1(int a, long b) { } public static void Method1(long a, int b) { } public static void Main() { Method1(10, 20); //CS0121 } } ").VerifyDiagnostics( // (14,9): error CS0121: The call is ambiguous between the following methods or properties: 'Test.Method1(int, long)' and 'Test.Method1(long, int)' // Method1(10, 20) Diagnostic(ErrorCode.ERR_AmbigCall, "Method1").WithArguments("Test.Method1(int, long)", "Test.Method1(long, int)")); } [WorkItem(528592, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528592")] [Fact] public void CS0121ERR_IncorrectErrorSpan2() { CreateCompilation(@" public class Class1 { public Class1(int a, long b) { } public Class1(long a, int b) { } } class Test { public static void Main() { var i1 = new Class1(10, 20); //CS0121 } } ").VerifyDiagnostics( // (17,18): error CS0121: The call is ambiguous between the following methods or properties: 'Class1.Class1(int, long)' and 'Class1.Class1(long, int)' // new Class1(10, 20) Diagnostic(ErrorCode.ERR_AmbigCall, "Class1").WithArguments("Class1.Class1(int, long)", "Class1.Class1(long, int)")); } [WorkItem(542468, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542468")] [Fact] public void CS1513ERR_RbraceExpected_DevDiv9741() { var text = @" class Program { private delegate string D(); static void Main(string[] args) { D d = delegate { .ToString(); }; } } "; // Used to assert. CreateCompilation(text).VerifyDiagnostics( // (8,10): error CS1513: } expected // { Diagnostic(ErrorCode.ERR_RbraceExpected, "").WithLocation(8, 10), // (9,14): error CS0120: An object reference is required for the non-static field, method, or property 'object.ToString()' // .ToString(); Diagnostic(ErrorCode.ERR_ObjectRequired, "ToString").WithArguments("object.ToString()").WithLocation(9, 14), // (7,15): error CS1643: Not all code paths return a value in anonymous method of type 'Program.D' // D d = delegate Diagnostic(ErrorCode.ERR_AnonymousReturnExpected, "delegate").WithArguments("anonymous method", "Program.D").WithLocation(7, 15) ); } [WorkItem(543473, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543473")] [Fact] public void CS0815ERR_CannotAssignLambdaExpressionToAnImplicitlyTypedLocalVariable() { var text = @"class Program { static void Main(string[] args) { var a1 = checked((a) => a); } }"; CreateCompilation(text).VerifyDiagnostics( // (5,13): error CS0815: Cannot assign lambda expression to an implicitly-typed variable // var a1 = checked((a) => a); Diagnostic(ErrorCode.ERR_ImplicitlyTypedVariableAssignedBadValue, "a1 = checked((a) => a)").WithArguments("lambda expression")); } [Fact, WorkItem(543665, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543665")] public void CS0246ERR_SingleTypeNameNotFound_UndefinedTypeInDelegateSignature() { var text = @" using System; class Test { static void Main() { var d = (Action<List<int>>)delegate(List<int> t) {}; } }"; CreateCompilation(text).VerifyDiagnostics( // (7,41): error CS0246: The type or namespace name 'List<>' could not be found (are you missing a using directive or an assembly reference?) // var d = (Action<List<int>>)delegate(List<int> t) {}; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "List<int>").WithArguments("List<>").WithLocation(7, 41), // (7,21): error CS0246: The type or namespace name 'List<>' could not be found (are you missing a using directive or an assembly reference?) // var d = (Action<List<int>>)delegate(List<int> t) {}; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "List<int>").WithArguments("List<>").WithLocation(7, 21) ); } [Fact] [WorkItem(633183, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/633183")] public void CS0199ERR_RefReadonlyStatic_StaticFieldInitializer() { var source = @" class Program { Program(ref string s) { } static readonly Program Field1 = new Program(ref Program.Field2); static readonly string Field2 = """"; static void Main() { } } "; CreateCompilation(source).VerifyDiagnostics(); } [Fact] [WorkItem(633183, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/633183")] public void CS0199ERR_RefReadonlyStatic_NestedStaticFieldInitializer() { var source = @" class Program { Program(ref string s) { } static readonly Program Field1 = new Program(ref Program.Field2); static readonly string Field2 = """"; static void Main() { } class Inner { static readonly Program Field3 = new Program(ref Program.Field2); } } "; CreateCompilation(source).VerifyDiagnostics( // (11,58): error CS0199: A static readonly field cannot be used as a ref or out value (except in a static constructor) // static readonly Program Field3 = new Program(ref Program.Field2); Diagnostic(ErrorCode.ERR_RefReadonlyStatic, "Program.Field2").WithLocation(11, 58) ); } [Fact] public void BadYield_MultipleReasons() { var source = @" using System.Collections.Generic; class Program { IEnumerable<int> Test() { try { try { yield return 11; // CS1626 } catch { yield return 12; // CS1626 } finally { yield return 13; // CS1625 } } catch { try { yield return 21; // CS1626 } catch { yield return 22; // CS1631 } finally { yield return 23; // CS1625 } } finally { try { yield return 31; // CS1625 } catch { yield return 32; // CS1625 } finally { yield return 33; // CS1625 } } } } "; CreateCompilation(source).VerifyDiagnostics( // (12,17): error CS1626: Cannot yield a value in the body of a try block with a catch clause // yield return 11; // CS1626 Diagnostic(ErrorCode.ERR_BadYieldInTryOfCatch, "yield"), // (16,17): error CS1626: Cannot yield a value in the body of a try block with a catch clause // yield return 12; // CS1626 Diagnostic(ErrorCode.ERR_BadYieldInTryOfCatch, "yield"), // (20,17): error CS1625: Cannot yield in the body of a finally clause // yield return 13; // CS1625 Diagnostic(ErrorCode.ERR_BadYieldInFinally, "yield"), // (27,17): error CS1626: Cannot yield a value in the body of a try block with a catch clause // yield return 21; // CS1626 Diagnostic(ErrorCode.ERR_BadYieldInTryOfCatch, "yield"), // (31,17): error CS1631: Cannot yield a value in the body of a catch clause // yield return 22; // CS1631 Diagnostic(ErrorCode.ERR_BadYieldInCatch, "yield"), // (35,17): error CS1625: Cannot yield in the body of a finally clause // yield return 23; // CS1625 Diagnostic(ErrorCode.ERR_BadYieldInFinally, "yield"), // (42,17): error CS1625: Cannot yield in the body of a finally clause // yield return 31; // CS1625 Diagnostic(ErrorCode.ERR_BadYieldInFinally, "yield"), // (46,17): error CS1625: Cannot yield in the body of a finally clause // yield return 32; // CS1625 Diagnostic(ErrorCode.ERR_BadYieldInFinally, "yield"), // (50,17): error CS1625: Cannot yield in the body of a finally clause // yield return 33; // CS1625 Diagnostic(ErrorCode.ERR_BadYieldInFinally, "yield")); } [Fact] public void BadYield_Lambda() { var source = @" using System; using System.Collections.Generic; class Program { IEnumerable<int> Test() { try { } finally { Action a = () => { yield break; }; Action b = () => { try { } finally { yield break; } }; } yield break; } } "; CreateCompilation(source).VerifyDiagnostics( // (14,32): error CS1621: The yield statement cannot be used inside an anonymous method or lambda expression // Action a = () => { yield break; }; Diagnostic(ErrorCode.ERR_YieldInAnonMeth, "yield"), // CONSIDER: ERR_BadYieldInFinally is redundant, but matches dev11. // (22,21): error CS1625: Cannot yield in the body of a finally clause // yield break; Diagnostic(ErrorCode.ERR_BadYieldInFinally, "yield"), // (22,21): error CS1621: The yield statement cannot be used inside an anonymous method or lambda expression // yield break; Diagnostic(ErrorCode.ERR_YieldInAnonMeth, "yield")); } #endregion [Fact] public void Bug528147() { var text = @" using System; interface I<T> { } class A { private class B { } public class C : I<B> { } } class Program { delegate void D(A.C x); static void M<T>(I<T> c) { Console.WriteLine(""I""); } static void Main() { D d = M; d(null); } } "; CreateCompilation(text).VerifyDiagnostics( // (25,15): error CS0122: 'Program.M<A.B>(I<A.B>)' is inaccessible due to its protection level // D d = M; Diagnostic(ErrorCode.ERR_BadAccess, "M").WithArguments("Program.M<A.B>(I<A.B>)") ); } [WorkItem(630799, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/630799")] [Fact] public void Bug630799() { var text = @" using System; class Program { static void Goo<T,S>() where T : S where S : Exception { try { } catch(S e) { } catch(T e) { } } } "; CreateCompilation(text).VerifyDiagnostics( // (14,15): error CS0160: A previous catch clause already catches all exceptions of this or of a super type ('S') // catch(T e) Diagnostic(ErrorCode.ERR_UnreachableCatch, "T").WithArguments("S").WithLocation(14, 15), // (11,17): warning CS0168: The variable 'e' is declared but never used // catch(S e) Diagnostic(ErrorCode.WRN_UnreferencedVar, "e").WithArguments("e").WithLocation(11, 17), // (14,17): warning CS0168: The variable 'e' is declared but never used // catch(T e) Diagnostic(ErrorCode.WRN_UnreferencedVar, "e").WithArguments("e").WithLocation(14, 17) ); } [Fact] public void ConditionalMemberAccess001() { var text = @" class Program { public int P1 { set { } } public void V() { } static void Main(string[] args) { var x = 123 ?.ToString(); var p = new Program(); var x1 = p.P1 ?.ToString(); var x2 = p.V() ?.ToString(); var x3 = p.V ?.ToString(); var x4 = ()=> { return 1; } ?.ToString(); } } "; CreateCompilationWithMscorlib45(text).VerifyDiagnostics( // (13,21): error CS0023: Operator '?' cannot be applied to operand of type 'int' // var x = 123 ?.ToString(); Diagnostic(ErrorCode.ERR_BadUnaryOp, "?").WithArguments("?", "int").WithLocation(13, 21), // (16,18): error CS0154: The property or indexer 'Program.P1' cannot be used in this context because it lacks the get accessor // var x1 = p.P1 ?.ToString(); Diagnostic(ErrorCode.ERR_PropertyLacksGet, "p.P1").WithArguments("Program.P1").WithLocation(16, 18), // (17,24): error CS0023: Operator '?' cannot be applied to operand of type 'void' // var x2 = p.V() ?.ToString(); Diagnostic(ErrorCode.ERR_BadUnaryOp, "?").WithArguments("?", "void").WithLocation(17, 24), // (18,20): error CS0119: 'Program.V()' is a method, which is not valid in the given context // var x3 = p.V ?.ToString(); Diagnostic(ErrorCode.ERR_BadSKunknown, "V").WithArguments("Program.V()", "method").WithLocation(18, 20), // (19,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(19, 18) ); } [Fact] public void ConditionalMemberAccess002_notIn5() { var text = @" class Program { public int? P1 { get { return null; } } public void V() { } static void Main(string[] args) { var p = new Program(); var x1 = p.P1 ?.ToString; } } "; CreateCompilation(text, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp5)).VerifyDiagnostics( // (14,18): error CS8026: Feature 'null propagation operator' is not available in C# 5. Please use language version 6 or greater. // var x1 = p.P1 ?.ToString; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion5, "p.P1 ?.ToString").WithArguments("null propagating operator", "6").WithLocation(14, 18), // (14,23): error CS0023: Operator '?' cannot be applied to operand of type 'method group' // var x1 = p.P1 ?.ToString; Diagnostic(ErrorCode.ERR_BadUnaryOp, "?").WithArguments("?", "method group").WithLocation(14, 23) ); } [Fact] public void ConditionalMemberAccess002() { var text = @" class Program { public int? P1 { get { return null; } } public void V() { } static void Main(string[] args) { var p = new Program(); var x1 = p.P1 ?.ToString; } } "; CreateCompilationWithMscorlib45(text).VerifyDiagnostics( // (14,23): error CS0023: Operator '?' cannot be applied to operand of type 'method group' // var x1 = p.P1 ?.ToString; Diagnostic(ErrorCode.ERR_BadUnaryOp, "?").WithArguments("?", "method group").WithLocation(14, 23) ); } [Fact] [CompilerTrait(CompilerFeature.IOperation)] [WorkItem(23009, "https://github.com/dotnet/roslyn/issues/23009")] public void ConditionalElementAccess001() { var text = @" class Program { public int P1 { set { } } public void V() { var x6 = base?.ToString(); } static void Main(string[] args) { var x = 123 ?[1,2]; var p = new Program(); var x1 = p.P1 ?[1,2]; var x2 = p.V() ?[1,2]; var x3 = p.V ?[1,2]; var x4 = ()=> { return 1; } ?[1,2]; var x5 = null?.ToString(); } } "; var compilation = CreateCompilationWithMscorlib45(text).VerifyDiagnostics( // (11,18): error CS0175: Use of keyword 'base' is not valid in this context // var x6 = base?.ToString(); Diagnostic(ErrorCode.ERR_BaseIllegal, "base").WithLocation(11, 18), // (16,21): error CS0023: Operator '?' cannot be applied to operand of type 'int' // var x = 123 ?[1,2]; Diagnostic(ErrorCode.ERR_BadUnaryOp, "?").WithArguments("?", "int").WithLocation(16, 21), // (19,18): error CS0154: The property or indexer 'Program.P1' cannot be used in this context because it lacks the get accessor // var x1 = p.P1 ?[1,2]; Diagnostic(ErrorCode.ERR_PropertyLacksGet, "p.P1").WithArguments("Program.P1").WithLocation(19, 18), // (20,24): error CS0023: Operator '?' cannot be applied to operand of type 'void' // var x2 = p.V() ?[1,2]; Diagnostic(ErrorCode.ERR_BadUnaryOp, "?").WithArguments("?", "void").WithLocation(20, 24), // (21,20): error CS0119: 'Program.V()' is a method, which is not valid in the given context // var x3 = p.V ?[1,2]; Diagnostic(ErrorCode.ERR_BadSKunknown, "V").WithArguments("Program.V()", "method").WithLocation(21, 20), // (22,18): error CS0023: Operator '?' cannot be applied to operand of type 'lambda expression' // var x4 = ()=> { return 1; } ?[1,2]; Diagnostic(ErrorCode.ERR_BadUnaryOp, "()=> { return 1; } ?[1,2]").WithArguments("?", "lambda expression").WithLocation(22, 18), // (24,22): error CS0023: Operator '?' cannot be applied to operand of type '<null>' // var x5 = null?.ToString(); Diagnostic(ErrorCode.ERR_BadUnaryOp, "?").WithArguments("?", "<null>").WithLocation(24, 22) ); var tree = compilation.SyntaxTrees.Single(); var node = tree.GetRoot().DescendantNodes().OfType<ConditionalAccessExpressionSyntax>().First(); Assert.Equal("base?.ToString()", node.ToString()); compilation.VerifyOperationTree(node, expectedOperationTree: @" IConditionalAccessOperation (OperationKind.ConditionalAccess, Type: ?, IsInvalid) (Syntax: 'base?.ToString()') Operation: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: System.Object, IsInvalid) (Syntax: 'base') WhenNotNull: IInvocationOperation (virtual System.String System.Object.ToString()) (OperationKind.Invocation, Type: System.String) (Syntax: '.ToString()') Instance Receiver: IConditionalAccessInstanceOperation (OperationKind.ConditionalAccessInstance, Type: System.Object, IsInvalid, IsImplicit) (Syntax: 'base') Arguments(0) "); } [Fact] [WorkItem(976765, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/976765")] public void ConditionalMemberAccessPtr() { var text = @" using System; class Program { unsafe static void Main() { IntPtr? intPtr = null; var p = intPtr?.ToPointer(); } } "; CreateCompilationWithMscorlib45(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (9,23): error CS0023: Operator '?' cannot be applied to operand of type 'void*' // var p = intPtr?.ToPointer(); Diagnostic(ErrorCode.ERR_BadUnaryOp, "?").WithArguments("?", "void*").WithLocation(9, 23) ); } [Fact] [WorkItem(991490, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/991490")] public void ConditionalMemberAccessExprLambda() { var text = @" using System; using System.Linq.Expressions; class Program { static void M<T>(T x) { Expression<Func<string>> s = () => x?.ToString(); Expression<Func<char?>> c = () => x.ToString()?[0]; Expression<Func<int?>> c1 = () => x.ToString()?.Length; Expression<Func<int?>> c2 = () => x?.ToString()?.Length; } static void Main() { M((string)null); } } "; CreateCompilationWithMscorlib45(text, new[] { Net451.System, Net451.SystemCore, Net451.MicrosoftCSharp }, options: TestOptions.ReleaseDll).VerifyDiagnostics( // (9,44): error CS8072: An expression tree lambda may not contain a null propagating operator. // Expression<Func<string>> s = () => x?.ToString(); Diagnostic(ErrorCode.ERR_NullPropagatingOpInExpressionTree, "x?.ToString()").WithLocation(9, 44), // (10,43): error CS8072: An expression tree lambda may not contain a null propagating operator. // Expression<Func<char?>> c = () => x.ToString()?[0]; Diagnostic(ErrorCode.ERR_NullPropagatingOpInExpressionTree, "x.ToString()?[0]").WithLocation(10, 43), // (11,43): error CS8072: An expression tree lambda may not contain a null propagating operator. // Expression<Func<int?>> c1 = () => x.ToString()?.Length; Diagnostic(ErrorCode.ERR_NullPropagatingOpInExpressionTree, "x.ToString()?.Length").WithLocation(11, 43), // (13,43): error CS8072: An expression tree lambda may not contain a null propagating operator. // Expression<Func<int?>> c2 = () => x?.ToString()?.Length; Diagnostic(ErrorCode.ERR_NullPropagatingOpInExpressionTree, "x?.ToString()?.Length").WithLocation(13, 43), // (13,45): error CS8072: An expression tree lambda may not contain a null propagating operator. // Expression<Func<int?>> c2 = () => x?.ToString()?.Length; Diagnostic(ErrorCode.ERR_NullPropagatingOpInExpressionTree, ".ToString()?.Length").WithLocation(13, 45) ); } [Fact] [WorkItem(915609, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/915609")] public void DictionaryInitializerInExprLambda() { var text = @" using System; using System.Linq.Expressions; using System.Collections.Generic; class Program { static void M<T>(T x) { Expression<Func<Dictionary<int, int>>> s = () => new Dictionary<int, int> () {[1] = 2}; } static void Main() { M((string)null); } } "; CreateCompilationWithMscorlib45(text, new[] { Net451.System, Net451.SystemCore, Net451.MicrosoftCSharp }).VerifyDiagnostics( // (10,87): error CS8073: An expression tree lambda may not contain a dictionary initializer. // Expression<Func<Dictionary<int, int>>> s = () => new Dictionary<int, int> () {[1] = 2}; Diagnostic(ErrorCode.ERR_DictionaryInitializerInExpressionTree, "[1]").WithLocation(10, 87) ); } [Fact] [WorkItem(915609, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/915609")] public void DictionaryInitializerInExprLambda1() { var text = @" using System; using System.Collections.Generic; using System.Linq.Expressions; namespace ConsoleApplication31 { class Program { static void Main(string[] args) { var o = new Goo(); var x = o.E.Compile()().Pop(); System.Console.WriteLine(x); } } static class StackExtensions { public static void Add<T>(this Stack<T> s, T x) => s.Push(x); } class Goo { public Expression<Func<Stack<int>>> E = () => new Stack<int> { 42 }; } } "; CreateCompilationWithMscorlib45(text, new[] { Net451.System, Net451.SystemCore, Net451.MicrosoftCSharp }).VerifyDiagnostics( // (25,72): error CS8075: An expression tree lambda may not contain an extension collection element initializer. // public Expression<Func<Stack<int>>> E = () => new Stack<int> { 42 }; Diagnostic(ErrorCode.ERR_ExtensionCollectionElementInitializerInExpressionTree, "42").WithLocation(25, 72) ); } [WorkItem(310, "https://github.com/dotnet/roslyn/issues/310")] [Fact] public void ExtensionElementInitializerInExpressionLambda() { var text = @" using System; using System.Collections; using System.Linq.Expressions; class C { static void Main() { Expression<Func<C>> e = () => new C { H = { [""Key""] = ""Value"" } }; Console.WriteLine(e); var c = e.Compile().Invoke(); Console.WriteLine(c.H[""Key""]); } readonly Hashtable H = new Hashtable(); } "; CreateCompilationWithMscorlib45(text, new[] { Net451.System, Net451.SystemCore, Net451.MicrosoftCSharp }).VerifyDiagnostics( // (9,53): error CS8073: An expression tree lambda may not contain a dictionary initializer. // Expression<Func<C>> e = () => new C { H = { ["Key"] = "Value" } }; Diagnostic(ErrorCode.ERR_DictionaryInitializerInExpressionTree, @"[""Key""]").WithLocation(9, 53) ); } [WorkItem(12900, "https://github.com/dotnet/roslyn/issues/12900")] [WorkItem(17138, "https://github.com/dotnet/roslyn/issues/17138")] [Fact] public void CSharp7FeaturesInExprTrees() { var source = @" using System; //using System.Collections; using System.Linq.Expressions; class C { static void Main() { // out variable declarations Expression<Func<bool>> e1 = () => TryGetThree(out int x) && x == 3; // ERROR 1 // pattern matching object o = 3; Expression<Func<bool>> e2 = () => o is int y && y == 3; // ERROR 2 // direct tuple creation could be OK, as it is just a constructor invocation, // not for long tuples the generated code is more complex, and we would // prefer custom expression trees to express the semantics. Expression<Func<object>> e3 = () => (1, o); // ERROR 3: tuple literal Expression<Func<(int, int)>> e4 = () => (1, 2); // ERROR 4: tuple literal // tuple conversions (byte, byte) t1 = (1, 2); Expression<Func<(byte a, byte b)>> e5 = () => t1; // OK, identity conversion Expression<Func<(int, int)>> e6 = () => t1; // ERROR 5: tuple conversion Expression<Func<int>> e7 = () => TakeRef(ref GetRefThree()); // ERROR 6: calling ref-returning method // discard Expression<Func<bool>> e8 = () => TryGetThree(out int _); Expression<Func<bool>> e9 = () => TryGetThree(out var _); Expression<Func<bool>> e10 = () => _ = (bool)o; Expression<Func<object>> e11 = () => _ = (_, _) = GetTuple(); Expression<Func<object>> e12 = () => _ = var (a, _) = GetTuple(); Expression<Func<object>> e13 = () => _ = (var a, var _) = GetTuple(); Expression<Func<bool>> e14 = () => TryGetThree(out _); } static bool TryGetThree(out int three) { three = 3; return true; } static int three = 3; static ref int GetRefThree() { return ref three; } static int TakeRef(ref int x) { Console.WriteLine(""wow""); return x; } static (object, object) GetTuple() { return (null, null); } } namespace System { struct ValueTuple<T1, T2> { public T1 Item1; public T2 Item2; public ValueTuple(T1 item1, T2 item2) { Item1 = item1; Item2 = item2; } } } namespace System.Runtime.CompilerServices { /// <summary> /// Indicates that the use of <see cref=""System.ValueTuple""/> on a member is meant to be treated as a tuple with element names. /// </summary> [AttributeUsage(AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.Property | AttributeTargets.ReturnValue | AttributeTargets.Class | AttributeTargets.Struct )] public sealed class TupleElementNamesAttribute : Attribute { public TupleElementNamesAttribute(string[] transformNames) { } } } "; var compilation = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugExe); compilation.VerifyDiagnostics( // (34,50): error CS8185: A declaration is not allowed in this context. // Expression<Func<object>> e12 = () => _ = var (a, _) = GetTuple(); Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "var (a, _)").WithLocation(34, 50), // (35,51): error CS8185: A declaration is not allowed in this context. // Expression<Func<object>> e13 = () => _ = (var a, var _) = GetTuple(); Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "var a").WithLocation(35, 51), // (10,59): error CS8198: An expression tree may not contain an out argument variable declaration. // Expression<Func<bool>> e1 = () => TryGetThree(out int x) && x == 3; // ERROR 1 Diagnostic(ErrorCode.ERR_ExpressionTreeContainsOutVariable, "int x").WithLocation(10, 59), // (14,43): error CS8122: An expression tree may not contain an 'is' pattern-matching operator. // Expression<Func<bool>> e2 = () => o is int y && y == 3; // ERROR 2 Diagnostic(ErrorCode.ERR_ExpressionTreeContainsIsMatch, "o is int y").WithLocation(14, 43), // (19,45): error CS8143: An expression tree may not contain a tuple literal. // Expression<Func<object>> e3 = () => (1, o); // ERROR 3: tuple literal Diagnostic(ErrorCode.ERR_ExpressionTreeContainsTupleLiteral, "(1, o)").WithLocation(19, 45), // (20,49): error CS8143: An expression tree may not contain a tuple literal. // Expression<Func<(int, int)>> e4 = () => (1, 2); // ERROR 4: tuple literal Diagnostic(ErrorCode.ERR_ExpressionTreeContainsTupleLiteral, "(1, 2)").WithLocation(20, 49), // (25,49): error CS8144: An expression tree may not contain a tuple conversion. // Expression<Func<(int, int)>> e6 = () => t1; // ERROR 5: tuple conversion Diagnostic(ErrorCode.ERR_ExpressionTreeContainsTupleConversion, "t1").WithLocation(25, 49), // (27,54): error CS8156: An expression tree lambda may not contain a call to a method, property, or indexer that returns by reference // Expression<Func<int>> e7 = () => TakeRef(ref GetRefThree()); // ERROR 6: calling ref-returning method Diagnostic(ErrorCode.ERR_RefReturningCallInExpressionTree, "GetRefThree()").WithLocation(27, 54), // (30,59): error CS8205: An expression tree may not contain a discard. // Expression<Func<bool>> e8 = () => TryGetThree(out int _); Diagnostic(ErrorCode.ERR_ExpressionTreeContainsDiscard, "int _").WithLocation(30, 59), // (31,59): error CS8205: An expression tree may not contain a discard. // Expression<Func<bool>> e9 = () => TryGetThree(out var _); Diagnostic(ErrorCode.ERR_ExpressionTreeContainsDiscard, "var _").WithLocation(31, 59), // (32,44): error CS0832: An expression tree may not contain an assignment operator // Expression<Func<bool>> e10 = () => _ = (bool)o; Diagnostic(ErrorCode.ERR_ExpressionTreeContainsAssignment, "_ = (bool)o").WithLocation(32, 44), // (33,46): error CS0832: An expression tree may not contain an assignment operator // Expression<Func<object>> e11 = () => _ = (_, _) = GetTuple(); Diagnostic(ErrorCode.ERR_ExpressionTreeContainsAssignment, "_ = (_, _) = GetTuple()").WithLocation(33, 46), // (33,50): error CS8143: An expression tree may not contain a tuple literal. // Expression<Func<object>> e11 = () => _ = (_, _) = GetTuple(); Diagnostic(ErrorCode.ERR_ExpressionTreeContainsTupleLiteral, "(_, _)").WithLocation(33, 50), // (36,60): error CS8205: An expression tree may not contain a discard. // Expression<Func<bool>> e14 = () => TryGetThree(out _); Diagnostic(ErrorCode.ERR_ExpressionTreeContainsDiscard, "_").WithLocation(36, 60) ); } [Fact] public void DictionaryInitializerInCS5() { var text = @" using System.Collections.Generic; class Program { static void Main() { var s = new Dictionary<int, int> () {[1] = 2}; } } "; CreateCompilationWithMscorlib45(text, new[] { SystemRef_v4_0_30319_17929, SystemCoreRef_v4_0_30319_17929, CSharpRef }, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp5)).VerifyDiagnostics( // (8,46): error CS8026: Feature 'dictionary initializer' is not available in C# 5. Please use language version 6 or greater. // var s = new Dictionary<int, int> () {[1] = 2}; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion5, "[1] = 2").WithArguments("dictionary initializer", "6").WithLocation(8, 46) ); } [Fact] public void DictionaryInitializerDataFlow() { var text = @" using System.Collections.Generic; class Program { static void Main() { int i; var s = new Dictionary<int, int> () {[i] = 2}; i = 1; System.Console.WriteLine(i); } static void Goo() { int i; var s = new Dictionary<int, int> () {[i = 1] = 2}; System.Console.WriteLine(i); } } "; CreateCompilationWithMscorlib45(text, new[] { SystemRef_v4_0_30319_17929, SystemCoreRef_v4_0_30319_17929, CSharpRef }, parseOptions: TestOptions.Regular).VerifyDiagnostics( // (9,47): error CS0165: Use of unassigned local variable 'i' // var s = new Dictionary<int, int> () {[i] = 2}; Diagnostic(ErrorCode.ERR_UseDefViolation, "i").WithArguments("i").WithLocation(9, 47) ); } [Fact] public void ConditionalMemberAccessNotStatement() { var text = @" class Program { static void Main() { var x = new int[10]; x?.Length; x?[1]; x?.ToString()[1]; } } "; CreateCompilationWithMscorlib45(text, options: TestOptions.ReleaseDll).VerifyDiagnostics( // (8,9): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement // x?.Length; Diagnostic(ErrorCode.ERR_IllegalStatement, "x?.Length").WithLocation(8, 9), // (9,9): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement // x?[1]; Diagnostic(ErrorCode.ERR_IllegalStatement, "x?[1]").WithLocation(9, 9), // (10,9): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement // x?.ToString()[1]; Diagnostic(ErrorCode.ERR_IllegalStatement, "x?.ToString()[1]").WithLocation(10, 9) ); } [WorkItem(23422, "https://github.com/dotnet/roslyn/issues/23422")] [Fact] public void ConditionalMemberAccessRefLike() { var text = @" class Program { static void Main(string[] args) { var o = new Program(); o?.F(); // this is ok var x = o?.F(); var y = o?.F() ?? default; var z = o?.F().field ?? default; } S2 F() => throw null; } public ref struct S1 { } public ref struct S2 { public S1 field; } "; CreateCompilationWithMscorlib45(text, options: TestOptions.ReleaseDll).VerifyDiagnostics( // (10,18): error CS0023: Operator '?' cannot be applied to operand of type 'S2' // var x = o?.F(); Diagnostic(ErrorCode.ERR_BadUnaryOp, "?").WithArguments("?", "S2").WithLocation(10, 18), // (12,18): error CS0023: Operator '?' cannot be applied to operand of type 'S2' // var y = o?.F() ?? default; Diagnostic(ErrorCode.ERR_BadUnaryOp, "?").WithArguments("?", "S2").WithLocation(12, 18), // (14,18): error CS0023: Operator '?' cannot be applied to operand of type 'S1' // var z = o?.F().field ?? default; Diagnostic(ErrorCode.ERR_BadUnaryOp, "?").WithArguments("?", "S1").WithLocation(14, 18) ); } [Fact] [WorkItem(1179322, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1179322")] public void LabelSameNameAsParameter() { var text = @" class Program { static object M(object obj, object value) { if (((string)obj).Length == 0) value: new Program(); } } "; var compilation = CreateCompilation(text); compilation.GetParseDiagnostics().Verify(); // Make sure the compiler can handle producing method body diagnostics for this pattern when // queried via an API (command line compile would exit after parse errors were reported). compilation.GetMethodBodyDiagnostics().Verify( // (6,41): error CS1023: Embedded statement cannot be a declaration or labeled statement // if (((string)obj).Length == 0) value: new Program(); Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "value: new Program();").WithLocation(6, 41), // (6,41): warning CS0164: This label has not been referenced // if (((string)obj).Length == 0) value: new Program(); Diagnostic(ErrorCode.WRN_UnreferencedLabel, "value").WithLocation(6, 41), // (4,19): error CS0161: 'Program.M(object, object)': not all code paths return a value // static object M(object obj, object value) Diagnostic(ErrorCode.ERR_ReturnExpected, "M").WithArguments("Program.M(object, object)").WithLocation(4, 19)); } [Fact] public void ThrowInExpressionTree() { var text = @" using System; using System.Linq.Expressions; namespace ConsoleApplication1 { class Program { static bool b = true; static object o = string.Empty; static void Main(string[] args) { Expression<Func<object>> e1 = () => o ?? throw null; Expression<Func<object>> e2 = () => b ? throw null : o; Expression<Func<object>> e3 = () => b ? o : throw null; Expression<Func<object>> e4 = () => throw null; } } } "; CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics( // (13,54): error CS8188: An expression tree may not contain a throw-expression. // Expression<Func<object>> e1 = () => o ?? throw null; Diagnostic(ErrorCode.ERR_ExpressionTreeContainsThrowExpression, "throw null").WithLocation(13, 54), // (14,53): error CS8188: An expression tree may not contain a throw-expression. // Expression<Func<object>> e2 = () => b ? throw null : o; Diagnostic(ErrorCode.ERR_ExpressionTreeContainsThrowExpression, "throw null").WithLocation(14, 53), // (15,57): error CS8188: An expression tree may not contain a throw-expression. // Expression<Func<object>> e3 = () => b ? o : throw null; Diagnostic(ErrorCode.ERR_ExpressionTreeContainsThrowExpression, "throw null").WithLocation(15, 57), // (16,49): error CS8188: An expression tree may not contain a throw-expression. // Expression<Func<object>> e4 = () => throw null; Diagnostic(ErrorCode.ERR_ExpressionTreeContainsThrowExpression, "throw null").WithLocation(16, 49) ); } [Fact, WorkItem(17674, "https://github.com/dotnet/roslyn/issues/17674")] public void VoidDiscardAssignment() { var text = @" class Program { public static void Main(string[] args) { _ = M(); } static void M() { } } "; CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics( // (6,9): error CS8209: A value of type 'void' may not be assigned. // _ = M(); Diagnostic(ErrorCode.ERR_VoidAssignment, "_").WithLocation(6, 9) ); } [Fact, WorkItem(22880, "https://github.com/dotnet/roslyn/issues/22880")] public void AttributeCtorInParam() { var text = @" [A(1)] class A : System.Attribute { A(in int x) { } } [B()] class B : System.Attribute { B(in int x = 1) { } } "; CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics( // (2,2): error CS8358: Cannot use attribute constructor 'A.A(in int)' because it has 'in' parameters. // [A(1)] Diagnostic(ErrorCode.ERR_AttributeCtorInParameter, "A(1)").WithArguments("A.A(in int)").WithLocation(2, 2), // (7,2): error CS8358: Cannot use attribute constructor 'B.B(in int)' because it has 'in' parameters. // [B()] Diagnostic(ErrorCode.ERR_AttributeCtorInParameter, "B()").WithArguments("B.B(in int)").WithLocation(7, 2) ); } [Fact] public void ERR_ExpressionTreeContainsSwitchExpression() { var text = @" using System; using System.Linq.Expressions; public class C { public int Test() { Expression<Func<int, int>> e = a => a switch { 0 => 1, _ => 2 }; // CS8411 return 1; } }"; CreateCompilationWithMscorlib40AndSystemCore(text, parseOptions: TestOptions.RegularWithRecursivePatterns).VerifyDiagnostics( // (9,45): error CS8411: An expression tree may not contain a switch expression. // Expression<Func<int, int>> e = a => a switch { 0 => 1, _ => 2 }; // CS8411 Diagnostic(ErrorCode.ERR_ExpressionTreeContainsSwitchExpression, "a switch { 0 => 1, _ => 2 }").WithLocation(9, 45) ); } [Fact] public void PointerGenericConstraintTypes() { var source = @" namespace A { class D {} } class B {} unsafe class C<T, U, V, X, Y, Z> where T : byte* where U : unmanaged where V : U* where X : object* where Y : B* where Z : A.D* { void M1<A>() where A : byte* {} void M2<A, B>() where A : unmanaged where B : A* {} void M3<A>() where A : object* {} void M4<A>() where A : B* {} void M5<A>() where A : T {} }"; var comp = CreateCompilation(source, options: TestOptions.UnsafeDebugDll); comp.VerifyDiagnostics( // (9,44): error CS0706: Invalid constraint type. A type used as a constraint must be an interface, a non-sealed class or a type parameter. // unsafe class C<T, U, V, X, Y, Z> where T : byte* Diagnostic(ErrorCode.ERR_BadConstraintType, "byte*").WithLocation(9, 44), // (11,44): error CS0706: Invalid constraint type. A type used as a constraint must be an interface, a non-sealed class or a type parameter. // where V : U* Diagnostic(ErrorCode.ERR_BadConstraintType, "U*").WithLocation(11, 44), // (12,44): error CS0706: Invalid constraint type. A type used as a constraint must be an interface, a non-sealed class or a type parameter. // where X : object* Diagnostic(ErrorCode.ERR_BadConstraintType, "object*").WithLocation(12, 44), // (13,44): error CS0706: Invalid constraint type. A type used as a constraint must be an interface, a non-sealed class or a type parameter. // where Y : B* Diagnostic(ErrorCode.ERR_BadConstraintType, "B*").WithLocation(13, 44), // (14,44): error CS0706: Invalid constraint type. A type used as a constraint must be an interface, a non-sealed class or a type parameter. // where Z : A.D* Diagnostic(ErrorCode.ERR_BadConstraintType, "A.D*").WithLocation(14, 44), // (16,28): error CS0706: Invalid constraint type. A type used as a constraint must be an interface, a non-sealed class or a type parameter. // void M1<A>() where A : byte* {} Diagnostic(ErrorCode.ERR_BadConstraintType, "byte*").WithLocation(16, 28), // (18,31): error CS0706: Invalid constraint type. A type used as a constraint must be an interface, a non-sealed class or a type parameter. // where B : A* {} Diagnostic(ErrorCode.ERR_BadConstraintType, "A*").WithLocation(18, 31), // (19,28): error CS0706: Invalid constraint type. A type used as a constraint must be an interface, a non-sealed class or a type parameter. // void M3<A>() where A : object* {} Diagnostic(ErrorCode.ERR_BadConstraintType, "object*").WithLocation(19, 28), // (20,28): error CS0706: Invalid constraint type. A type used as a constraint must be an interface, a non-sealed class or a type parameter. // void M4<A>() where A : B* {} Diagnostic(ErrorCode.ERR_BadConstraintType, "B*").WithLocation(20, 28) ); } [Fact] public void ArrayGenericConstraintTypes() { var source = @"class A<T> where T : object[] {}"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (1,22): error CS0706: Invalid constraint type. A type used as a constraint must be an interface, a non-sealed class or a type parameter. // class A<T> where T : object[] {} Diagnostic(ErrorCode.ERR_BadConstraintType, "object[]").WithLocation(1, 22)); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Globalization; using System.Linq; using System.Threading; 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; using static Roslyn.Test.Utilities.TestMetadata; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { /// <summary> /// this place is dedicated to binding related error tests /// </summary> public class SemanticErrorTests : CompilingTestBase { #region "Targeted Error Tests - please arrange tests in the order of error code" [Fact] public void CS0019ERR_BadBinaryOps01() { var text = @" namespace x { public class b { public static void Main() { bool q = false; if (q == 1) { } } } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_BadBinaryOps, Line = 9, Column = 17 }); } [Fact] public void CS0019ERR_BadBinaryOps02() { var text = @"using System; enum E { A, B, C } enum F { X = (E.A + E.B) * DayOfWeek.Monday } // no error class C { static void M(object o) { M((E.A + E.B) * DayOfWeek.Monday); } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_BadBinaryOps, Line = 8, Column = 12 }); } [WorkItem(539906, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539906")] [Fact] public void CS0019ERR_BadBinaryOps03() { var text = @"delegate void MyDelegate1(ref int x, out float y); class Program { public void DelegatedMethod1(ref int x, out float y) { y = 1; } public void DelegatedMethod2(out int x, ref float y) { x = 1; } public void DelegatedMethod3(out int x, float y = 1) { x = 1; } static void Main(string[] args) { Program mc = new Program(); MyDelegate1 md1 = null; md1 += mc.DelegatedMethod1; md1 += mc.DelegatedMethod2; // Invalid md1 += mc.DelegatedMethod3; // Invalid md1 -= mc.DelegatedMethod1; md1 -= mc.DelegatedMethod2; // Invalid md1 -= mc.DelegatedMethod3; // Invalid } } "; CreateCompilation(text). VerifyDiagnostics( // (21,19): error CS0123: No overload for 'DelegatedMethod2' matches delegate 'MyDelegate1' // md1 += mc.DelegatedMethod2; // Invalid Diagnostic(ErrorCode.ERR_MethDelegateMismatch, "DelegatedMethod2").WithArguments("DelegatedMethod2", "MyDelegate1"), // (22,19): error CS0123: No overload for 'DelegatedMethod3' matches delegate 'MyDelegate1' // md1 += mc.DelegatedMethod3; // Invalid Diagnostic(ErrorCode.ERR_MethDelegateMismatch, "DelegatedMethod3").WithArguments("DelegatedMethod3", "MyDelegate1"), // (24,19): error CS0123: No overload for 'DelegatedMethod2' matches delegate 'MyDelegate1' // md1 -= mc.DelegatedMethod2; // Invalid Diagnostic(ErrorCode.ERR_MethDelegateMismatch, "DelegatedMethod2").WithArguments("DelegatedMethod2", "MyDelegate1"), // (25,19): error CS0123: No overload for 'DelegatedMethod3' matches delegate 'MyDelegate1' // md1 -= mc.DelegatedMethod3; // Invalid Diagnostic(ErrorCode.ERR_MethDelegateMismatch, "DelegatedMethod3").WithArguments("DelegatedMethod3", "MyDelegate1") ); } // Method List to removal or concatenation [WorkItem(539906, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539906")] [Fact] public void CS0019ERR_BadBinaryOps04() { var text = @"using System; delegate void boo(); public class abc { public void bar() { System.Console.WriteLine(""bar""); } static public void far() { System.Console.WriteLine(""far""); } } class C { static void Main(string[] args) { abc p = new abc(); boo goo = null; boo goo1 = new boo(abc.far); boo[] arrfoo = { p.bar, abc.far }; goo += arrfoo; // Invalid goo -= arrfoo; // Invalid goo += new boo[] { p.bar, abc.far }; // Invalid goo -= new boo[] { p.bar, abc.far }; // Invalid goo += Delegate.Combine(arrfoo); // Invalid goo += Delegate.Combine(goo, goo1); // Invalid } } "; CreateCompilation(text).VerifyDiagnostics( // (16,16): error CS0029: Cannot implicitly convert type 'boo[]' to 'boo' // goo += arrfoo; // Invalid Diagnostic(ErrorCode.ERR_NoImplicitConv, "arrfoo").WithArguments("boo[]", "boo"), // (17,16): error CS0029: Cannot implicitly convert type 'boo[]' to 'boo' // goo -= arrfoo; // Invalid Diagnostic(ErrorCode.ERR_NoImplicitConv, "arrfoo").WithArguments("boo[]", "boo"), // (18,16): error CS0029: Cannot implicitly convert type 'boo[]' to 'boo' // goo += new boo[] { p.bar, abc.far }; // Invalid Diagnostic(ErrorCode.ERR_NoImplicitConv, "new boo[] { p.bar, abc.far }").WithArguments("boo[]", "boo"), // (19,16): error CS0029: Cannot implicitly convert type 'boo[]' to 'boo' // goo -= new boo[] { p.bar, abc.far }; // Invalid Diagnostic(ErrorCode.ERR_NoImplicitConv, "new boo[] { p.bar, abc.far }").WithArguments("boo[]", "boo"), // (20,16): error CS0266: Cannot implicitly convert type 'System.Delegate' to 'boo'. An explicit conversion exists (are you missing a cast?) // goo += Delegate.Combine(arrfoo); // Invalid Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "Delegate.Combine(arrfoo)").WithArguments("System.Delegate", "boo"), // (21,16): error CS0266: Cannot implicitly convert type 'System.Delegate' to 'boo'. An explicit conversion exists (are you missing a cast?) // goo += Delegate.Combine(goo, goo1); // Invalid Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "Delegate.Combine(goo, goo1)").WithArguments("System.Delegate", "boo") ); } [WorkItem(539906, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539906")] [Fact] public void CS0019ERR_BadBinaryOps05() { var text = @"public delegate double MyDelegate1(ref int integerPortion, out float fraction); public delegate double MyDelegate2(ref int integerPortion, out float fraction); class C { static void Main(string[] args) { C mc = new C(); MyDelegate1 md1 = null; MyDelegate2 md2 = null; md1 += md2; // Invalid } } "; CreateCompilation(text).VerifyDiagnostics( // (10,16): error CS0029: Cannot implicitly convert type 'MyDelegate2' to 'MyDelegate1' // md1 += md2; // Invalid Diagnostic(ErrorCode.ERR_NoImplicitConv, "md2").WithArguments("MyDelegate2", "MyDelegate1") ); } // Anonymous method to removal or concatenation [WorkItem(539906, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539906")] [Fact] public void CS0019ERR_BadBinaryOps06() { var text = @"delegate void boo(int x); class C { static void Main(string[] args) { boo goo = null; goo += delegate (string x) { System.Console.WriteLine(x); };// Invalid goo -= delegate (string x) { System.Console.WriteLine(x); };// Invalid } } "; CreateCompilation(text).VerifyDiagnostics( // (7,16): error CS1661: Cannot convert anonymous method to delegate type 'boo' because the parameter types do not match the delegate parameter types // goo += delegate (string x) { System.Console.WriteLine(x); };// Invalid Diagnostic(ErrorCode.ERR_CantConvAnonMethParams, "delegate (string x) { System.Console.WriteLine(x); }").WithArguments("anonymous method", "boo"), // (7,33): error CS1678: Parameter 1 is declared as type 'string' but should be 'int' // goo += delegate (string x) { System.Console.WriteLine(x); };// Invalid Diagnostic(ErrorCode.ERR_BadParamType, "x").WithArguments("1", "", "string", "", "int"), // (8,16): error CS1661: Cannot convert anonymous method to delegate type 'boo' because the parameter types do not match the delegate parameter types // goo -= delegate (string x) { System.Console.WriteLine(x); };// Invalid Diagnostic(ErrorCode.ERR_CantConvAnonMethParams, "delegate (string x) { System.Console.WriteLine(x); }").WithArguments("anonymous method", "boo"), // (8,33): error CS1678: Parameter 1 is declared as type 'string' but should be 'int' // goo -= delegate (string x) { System.Console.WriteLine(x); };// Invalid Diagnostic(ErrorCode.ERR_BadParamType, "x").WithArguments("1", "", "string", "", "int") ); } // Lambda expression to removal or concatenation [WorkItem(539906, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539906")] [Fact] public void CS0019ERR_BadBinaryOps07() { var text = @"delegate void boo(int x); class C { static void Main(string[] args) { boo goo = null; goo += (string x) => { };// Invalid goo -= (string x) => { };// Invalid } } "; CreateCompilation(text).VerifyDiagnostics( // (7,16): error CS1661: Cannot convert lambda expression to delegate type 'boo' because the parameter types do not match the delegate parameter types // goo += (string x) => { };// Invalid Diagnostic(ErrorCode.ERR_CantConvAnonMethParams, "(string x) => { }").WithArguments("lambda expression", "boo"), // (7,24): error CS1678: Parameter 1 is declared as type 'string' but should be 'int' // goo += (string x) => { };// Invalid Diagnostic(ErrorCode.ERR_BadParamType, "x").WithArguments("1", "", "string", "", "int"), // (8,16): error CS1661: Cannot convert lambda expression to delegate type 'boo' because the parameter types do not match the delegate parameter types // goo -= (string x) => { };// Invalid Diagnostic(ErrorCode.ERR_CantConvAnonMethParams, "(string x) => { }").WithArguments("lambda expression", "boo"), // (8,24): error CS1678: Parameter 1 is declared as type 'string' but should be 'int' // goo -= (string x) => { };// Invalid Diagnostic(ErrorCode.ERR_BadParamType, "x").WithArguments("1", "", "string", "", "int") ); } // Successive operator for addition and subtraction assignment [WorkItem(539906, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539906")] [Fact] public void CS0019ERR_BadBinaryOps08() { var text = @"using System; delegate void boo(int x); class C { public void bar(int x) { Console.WriteLine("""", x); } static public void far(int x) { Console.WriteLine(""far:{0}"", x); } static void Main(string[] args) { C p = new C(); boo goo = null; goo += p.bar + far;// Invalid goo += (x) => { System.Console.WriteLine(""Lambda:{0}"", x); } + far;// Invalid goo += delegate (int x) { System.Console.WriteLine(""Anonymous:{0}"", x); } + far;// Invalid } } "; CreateCompilation(text).VerifyDiagnostics( // (11,16): error CS0019: Operator '+' cannot be applied to operands of type 'method group' and 'method group' // goo += p.bar + far;// Invalid Diagnostic(ErrorCode.ERR_BadBinaryOps, "p.bar + far").WithArguments("+", "method group", "method group").WithLocation(11, 16), // (12,16): error CS0019: Operator '+' cannot be applied to operands of type 'lambda expression' and 'method group' // goo += (x) => { System.Console.WriteLine("Lambda:{0}", x); } + far;// Invalid Diagnostic(ErrorCode.ERR_BadBinaryOps, @"(x) => { System.Console.WriteLine(""Lambda:{0}"", x); } + far").WithArguments("+", "lambda expression", "method group").WithLocation(12, 16), // (12,70): warning CS8848: Operator '+' cannot be used here due to precedence. Use parentheses to disambiguate. // goo += (x) => { System.Console.WriteLine("Lambda:{0}", x); } + far;// Invalid Diagnostic(ErrorCode.WRN_PrecedenceInversion, "+").WithArguments("+").WithLocation(12, 70), // (13,16): error CS0019: Operator '+' cannot be applied to operands of type 'anonymous method' and 'method group' // goo += delegate (int x) { System.Console.WriteLine("Anonymous:{0}", x); } + far;// Invalid Diagnostic(ErrorCode.ERR_BadBinaryOps, @"delegate (int x) { System.Console.WriteLine(""Anonymous:{0}"", x); } + far").WithArguments("+", "anonymous method", "method group").WithLocation(13, 16), // (13,83): warning CS8848: Operator '+' cannot be used here due to precedence. Use parentheses to disambiguate. // goo += delegate (int x) { System.Console.WriteLine("Anonymous:{0}", x); } + far;// Invalid Diagnostic(ErrorCode.WRN_PrecedenceInversion, "+").WithArguments("+").WithLocation(13, 83) ); } // Removal or concatenation for the delegate on Variance [WorkItem(539906, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539906")] [Fact] public void CS0019ERR_BadBinaryOps09() { var text = @"using System.Collections.Generic; delegate IList<int> Delegate1(List<int> x); delegate IEnumerable<int> Delegate2(IList<int> x); delegate IEnumerable<long> Delegate3(IList<long> x); class C { public static List<int> Method1(IList<int> x) { return null; } public static IList<long> Method1(IList<long> x) { return null; } static void Main(string[] args) { Delegate1 d1 = Method1; d1 += Method1; Delegate2 d2 = Method1; d2 += Method1; Delegate3 d3 = Method1; d1 += d2; // invalid d2 += d1; // invalid d2 += d3; // invalid } } "; CreateCompilation(text).VerifyDiagnostics( // (25,15): error CS0029: Cannot implicitly convert type 'Delegate2' to 'Delegate1' // d1 += d2; // invalid Diagnostic(ErrorCode.ERR_NoImplicitConv, "d2").WithArguments("Delegate2", "Delegate1"), // (26,15): error CS0029: Cannot implicitly convert type 'Delegate1' to 'Delegate2' // d2 += d1; // invalid Diagnostic(ErrorCode.ERR_NoImplicitConv, "d1").WithArguments("Delegate1", "Delegate2"), // (27,15): error CS0029: Cannot implicitly convert type 'Delegate3' to 'Delegate2' // d2 += d3; // invalid Diagnostic(ErrorCode.ERR_NoImplicitConv, "d3").WithArguments("Delegate3", "Delegate2") ); } // generic-delegate (goo<t>(...)) += non generic-methodgroup(bar<t>(...)) [WorkItem(539906, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539906")] [Fact] public void CS0019ERR_BadBinaryOps10() { var text = @"delegate void boo<T>(T x); class C { public void bar(int x) { System.Console.WriteLine(""bar:{0}"", x); } public void bar1(string x) { System.Console.WriteLine(""bar1:{0}"", x); } static void Main(string[] args) { C p = new C(); boo<int> goo = null; goo += p.bar;// OK goo += p.bar1;// Invalid goo += (x) => { System.Console.WriteLine(""Lambda:{0}"", x); };// OK goo += (string x) => { System.Console.WriteLine(""Lambda:{0}"", x); };// Invalid goo += delegate (int x) { System.Console.WriteLine(""Anonymous:{0}"", x); };// OK goo += delegate (string x) { System.Console.WriteLine(""Anonymous:{0}"", x); };// Invalid boo<string> goo1 = null; goo1 += p.bar;// Invalid goo1 += p.bar1;// OK goo1 += (x) => { System.Console.WriteLine(""Lambda:{0}"", x); };// OK goo1 += (int x) => { System.Console.WriteLine(""Lambda:{0}"", x); };// Invalid goo1 += delegate (int x) { System.Console.WriteLine(""Anonymous:{0}"", x); };// Invalid goo1 += delegate (string x) { System.Console.WriteLine(""Anonymous:{0}"", x); };// OK goo += goo1;// Invalid goo1 += goo;// Invalid } } "; CreateCompilation(text).VerifyDiagnostics( // (12,18): error CS0123: No overload for 'bar1' matches delegate 'boo<int>' // goo += p.bar1;// Invalid Diagnostic(ErrorCode.ERR_MethDelegateMismatch, "bar1").WithArguments("bar1", "boo<int>"), // (14,16): error CS1661: Cannot convert lambda expression to delegate type 'boo<int>' because the parameter types do not match the delegate parameter types // goo += (string x) => { System.Console.WriteLine("Lambda:{0}", x); };// Invalid Diagnostic(ErrorCode.ERR_CantConvAnonMethParams, @"(string x) => { System.Console.WriteLine(""Lambda:{0}"", x); }").WithArguments("lambda expression", "boo<int>"), // (14,24): error CS1678: Parameter 1 is declared as type 'string' but should be 'int' // goo += (string x) => { System.Console.WriteLine("Lambda:{0}", x); };// Invalid Diagnostic(ErrorCode.ERR_BadParamType, "x").WithArguments("1", "", "string", "", "int"), // (16,16): error CS1661: Cannot convert anonymous method to delegate type 'boo<int>' because the parameter types do not match the delegate parameter types // goo += delegate (string x) { System.Console.WriteLine("Anonymous:{0}", x); };// Invalid Diagnostic(ErrorCode.ERR_CantConvAnonMethParams, @"delegate (string x) { System.Console.WriteLine(""Anonymous:{0}"", x); }").WithArguments("anonymous method", "boo<int>"), // (16,33): error CS1678: Parameter 1 is declared as type 'string' but should be 'int' // goo += delegate (string x) { System.Console.WriteLine("Anonymous:{0}", x); };// Invalid Diagnostic(ErrorCode.ERR_BadParamType, "x").WithArguments("1", "", "string", "", "int"), // (19,19): error CS0123: No overload for 'bar' matches delegate 'boo<string>' // goo1 += p.bar;// Invalid Diagnostic(ErrorCode.ERR_MethDelegateMismatch, "bar").WithArguments("bar", "boo<string>"), // (22,17): error CS1661: Cannot convert lambda expression to delegate type 'boo<string>' because the parameter types do not match the delegate parameter types // goo1 += (int x) => { System.Console.WriteLine("Lambda:{0}", x); };// Invalid Diagnostic(ErrorCode.ERR_CantConvAnonMethParams, @"(int x) => { System.Console.WriteLine(""Lambda:{0}"", x); }").WithArguments("lambda expression", "boo<string>"), // (22,22): error CS1678: Parameter 1 is declared as type 'int' but should be 'string' // goo1 += (int x) => { System.Console.WriteLine("Lambda:{0}", x); };// Invalid Diagnostic(ErrorCode.ERR_BadParamType, "x").WithArguments("1", "", "int", "", "string"), // (23,17): error CS1661: Cannot convert anonymous method to delegate type 'boo<string>' because the parameter types do not match the delegate parameter types // goo1 += delegate (int x) { System.Console.WriteLine("Anonymous:{0}", x); };// Invalid Diagnostic(ErrorCode.ERR_CantConvAnonMethParams, @"delegate (int x) { System.Console.WriteLine(""Anonymous:{0}"", x); }").WithArguments("anonymous method", "boo<string>"), // (23,31): error CS1678: Parameter 1 is declared as type 'int' but should be 'string' // goo1 += delegate (int x) { System.Console.WriteLine("Anonymous:{0}", x); };// Invalid Diagnostic(ErrorCode.ERR_BadParamType, "x").WithArguments("1", "", "int", "", "string"), // (25,16): error CS0029: Cannot implicitly convert type 'boo<string>' to 'boo<int>' // goo += goo1;// Invalid Diagnostic(ErrorCode.ERR_NoImplicitConv, "goo1").WithArguments("boo<string>", "boo<int>"), // (26,17): error CS0029: Cannot implicitly convert type 'boo<int>' to 'boo<string>' // goo1 += goo;// Invalid Diagnostic(ErrorCode.ERR_NoImplicitConv, "goo").WithArguments("boo<int>", "boo<string>") ); } // generic-delegate (goo<t>(...)) += generic-methodgroup(bar<t>(...)) [WorkItem(539906, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539906")] [Fact] public void CS0019ERR_BadBinaryOps11() { var text = @"delegate void boo<T>(T x); class C { static void far<T>(T x) { } static void Main(string[] args) { C p = new C(); boo<int> goo = null; goo += far<int>;// OK goo += far<short>;// Invalid } } "; CreateCompilation(text).VerifyDiagnostics( // (10,16): error CS0123: No overload for 'far' matches delegate 'boo<int>' // goo += far<short>;// Invalid Diagnostic(ErrorCode.ERR_MethDelegateMismatch, "far<short>").WithArguments("far", "boo<int>") ); } // non generic-delegate (goo<t>(...)) += generic-methodgroup(bar<t>(...)) [WorkItem(539906, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539906")] [Fact] public void CS0019ERR_BadBinaryOps12() { var text = @"delegate void boo<T>(T x); class C { static void far<T>(T x) { } static void Main(string[] args) { C p = new C(); boo<int> goo = null; goo += far<int>;// OK goo += far<short>;// Invalid } } "; CreateCompilation(text).VerifyDiagnostics( // (10,16): error CS0123: No overload for 'far' matches delegate 'boo<int>' // goo += far<short>;// Invalid Diagnostic(ErrorCode.ERR_MethDelegateMismatch, "far<short>").WithArguments("far", "boo<int>") ); } // distinguish '|' from '||' [WorkItem(540235, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540235")] [Fact] public void CS0019ERR_BadBinaryOps13() { var text = @" class C { int a = 1 | 1; int b = 1 & 1; int c = 1 || 1; int d = 1 && 1; bool e = true | true; bool f = true & true; bool g = true || true; bool h = true && true; } "; CreateCompilation(text).VerifyDiagnostics( // (6,13): error CS0019: Operator '||' cannot be applied to operands of type 'int' and 'int' // int c = 1 || 1; Diagnostic(ErrorCode.ERR_BadBinaryOps, "1 || 1").WithArguments("||", "int", "int"), // (7,13): error CS0019: Operator '&&' cannot be applied to operands of type 'int' and 'int' // int d = 1 && 1; Diagnostic(ErrorCode.ERR_BadBinaryOps, "1 && 1").WithArguments("&&", "int", "int"), // (4,9): warning CS0414: The field 'C.a' is assigned but its value is never used // int a = 1 | 1; Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "a").WithArguments("C.a"), // (5,9): warning CS0414: The field 'C.b' is assigned but its value is never used // int b = 1 & 1; Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "b").WithArguments("C.b"), // (9,10): warning CS0414: The field 'C.e' is assigned but its value is never used // bool e = true | true; Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "e").WithArguments("C.e"), // (10,10): warning CS0414: The field 'C.f' is assigned but its value is never used // bool f = true & true; Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "f").WithArguments("C.f"), // (11,10): warning CS0414: The field 'C.g' is assigned but its value is never used // bool g = true || true; Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "g").WithArguments("C.g"), // (12,10): warning CS0414: The field 'C.h' is assigned but its value is never used // bool h = true && true; Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "h").WithArguments("C.h")); } /// <summary> /// Conversion errors for Null Coalescing operator(??) /// </summary> [Fact] public void CS0019ERR_BadBinaryOps14() { var text = @" public class D { } public class Error { public int? NonNullableValueType_a(int a) { int? b = null; int? z = a ?? b; return z; } public int? NonNullableValueType_b(char ch) { char b = ch; int? z = null ?? b; return z; } public int NonNullableValueType_const_a(char ch) { char b = ch; int z = 10 ?? b; return z; } public D NoPossibleConversionError() { D b = new D(); Error a = null; D z = a ?? b; return z; } } "; CreateCompilation(text).VerifyDiagnostics( // (7,18): error CS0019: Operator '??' cannot be applied to operands of type 'int' and 'int?' Diagnostic(ErrorCode.ERR_BadBinaryOps, "a ?? b").WithArguments("??", "int", "int?"), // (13,18): error CS0019: Operator '??' cannot be applied to operands of type '<null>' and 'char' Diagnostic(ErrorCode.ERR_BadBinaryOps, "null ?? b").WithArguments("??", "<null>", "char"), // (19,17): error CS0019: Operator '??' cannot be applied to operands of type 'int' and 'char' Diagnostic(ErrorCode.ERR_BadBinaryOps, "10 ?? b").WithArguments("??", "int", "char"), // (26,15): error CS0019: Operator '??' cannot be applied to operands of type 'Error' and 'D' Diagnostic(ErrorCode.ERR_BadBinaryOps, "a ?? b").WithArguments("??", "Error", "D")); } [WorkItem(542115, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542115")] [Fact] public void CS0019ERR_BadBinaryOps15() { var text = @"class C { static void M<T1, T2, T3, T4>(T1 t1, T2 t2, T3 t3, T4 t4, int i, C c) where T2 : class where T3 : struct where T4 : T1 { bool b; b = (t1 == t1); b = (t1 == t2); b = (t1 == t3); b = (t1 == t4); b = (t1 == i); b = (t1 == c); b = (t1 == null); b = (t2 == t1); b = (t2 == t2); b = (t2 == t3); b = (t2 == t4); b = (t2 == i); b = (t2 == c); b = (t2 == null); b = (t3 == t1); b = (t3 == t2); b = (t3 == t3); b = (t3 == t4); b = (t3 == i); b = (t3 == c); b = (t3 == null); b = (t4 != t1); b = (t4 != t2); b = (t4 != t3); b = (t4 != t4); b = (t4 != i); b = (t4 != c); b = (t4 != null); b = (i != t1); b = (i != t2); b = (i != t3); b = (i != t4); b = (i != i); b = (i != c); b = (i != null); b = (c != t1); b = (c != t2); b = (c != t3); b = (c != t4); b = (c != i); b = (c != c); b = (c != null); b = (null != t1); b = (null != t2); b = (null != t3); b = (null != t4); b = (null != i); b = (null != c); b = (null != null); } }"; CreateCompilation(text).VerifyDiagnostics( // (9,14): error CS0019: Operator '==' cannot be applied to operands of type 'T1' and 'T1' // b = (t1 == t1); Diagnostic(ErrorCode.ERR_BadBinaryOps, "t1 == t1").WithArguments("==", "T1", "T1"), // (10,14): error CS0019: Operator '==' cannot be applied to operands of type 'T1' and 'T2' // b = (t1 == t2); Diagnostic(ErrorCode.ERR_BadBinaryOps, "t1 == t2").WithArguments("==", "T1", "T2"), // (11,14): error CS0019: Operator '==' cannot be applied to operands of type 'T1' and 'T3' // b = (t1 == t3); Diagnostic(ErrorCode.ERR_BadBinaryOps, "t1 == t3").WithArguments("==", "T1", "T3"), // (12,14): error CS0019: Operator '==' cannot be applied to operands of type 'T1' and 'T4' // b = (t1 == t4); Diagnostic(ErrorCode.ERR_BadBinaryOps, "t1 == t4").WithArguments("==", "T1", "T4"), // (13,14): error CS0019: Operator '==' cannot be applied to operands of type 'T1' and 'int' // b = (t1 == i); Diagnostic(ErrorCode.ERR_BadBinaryOps, "t1 == i").WithArguments("==", "T1", "int"), // (14,14): error CS0019: Operator '==' cannot be applied to operands of type 'T1' and 'C' // b = (t1 == c); Diagnostic(ErrorCode.ERR_BadBinaryOps, "t1 == c").WithArguments("==", "T1", "C"), // (16,14): error CS0019: Operator '==' cannot be applied to operands of type 'T2' and 'T1' // b = (t2 == t1); Diagnostic(ErrorCode.ERR_BadBinaryOps, "t2 == t1").WithArguments("==", "T2", "T1"), // (18,14): error CS0019: Operator '==' cannot be applied to operands of type 'T2' and 'T3' // b = (t2 == t3); Diagnostic(ErrorCode.ERR_BadBinaryOps, "t2 == t3").WithArguments("==", "T2", "T3"), // (19,14): error CS0019: Operator '==' cannot be applied to operands of type 'T2' and 'T4' // b = (t2 == t4); Diagnostic(ErrorCode.ERR_BadBinaryOps, "t2 == t4").WithArguments("==", "T2", "T4"), // (20,14): error CS0019: Operator '==' cannot be applied to operands of type 'T2' and 'int' // b = (t2 == i); Diagnostic(ErrorCode.ERR_BadBinaryOps, "t2 == i").WithArguments("==", "T2", "int"), // (23,14): error CS0019: Operator '==' cannot be applied to operands of type 'T3' and 'T1' // b = (t3 == t1); Diagnostic(ErrorCode.ERR_BadBinaryOps, "t3 == t1").WithArguments("==", "T3", "T1"), // (24,14): error CS0019: Operator '==' cannot be applied to operands of type 'T3' and 'T2' // b = (t3 == t2); Diagnostic(ErrorCode.ERR_BadBinaryOps, "t3 == t2").WithArguments("==", "T3", "T2"), // (25,14): error CS0019: Operator '==' cannot be applied to operands of type 'T3' and 'T3' // b = (t3 == t3); Diagnostic(ErrorCode.ERR_BadBinaryOps, "t3 == t3").WithArguments("==", "T3", "T3"), // (26,14): error CS0019: Operator '==' cannot be applied to operands of type 'T3' and 'T4' // b = (t3 == t4); Diagnostic(ErrorCode.ERR_BadBinaryOps, "t3 == t4").WithArguments("==", "T3", "T4"), // (27,14): error CS0019: Operator '==' cannot be applied to operands of type 'T3' and 'int' // b = (t3 == i); Diagnostic(ErrorCode.ERR_BadBinaryOps, "t3 == i").WithArguments("==", "T3", "int"), // (28,14): error CS0019: Operator '==' cannot be applied to operands of type 'T3' and 'C' // b = (t3 == c); Diagnostic(ErrorCode.ERR_BadBinaryOps, "t3 == c").WithArguments("==", "T3", "C"), // (29,14): error CS0019: Operator '==' cannot be applied to operands of type 'T3' and '<null>' // b = (t3 == null); Diagnostic(ErrorCode.ERR_BadBinaryOps, "t3 == null").WithArguments("==", "T3", "<null>"), // (30,14): error CS0019: Operator '!=' cannot be applied to operands of type 'T4' and 'T1' // b = (t4 != t1); Diagnostic(ErrorCode.ERR_BadBinaryOps, "t4 != t1").WithArguments("!=", "T4", "T1"), // (31,14): error CS0019: Operator '!=' cannot be applied to operands of type 'T4' and 'T2' // b = (t4 != t2); Diagnostic(ErrorCode.ERR_BadBinaryOps, "t4 != t2").WithArguments("!=", "T4", "T2"), // (32,14): error CS0019: Operator '!=' cannot be applied to operands of type 'T4' and 'T3' // b = (t4 != t3); Diagnostic(ErrorCode.ERR_BadBinaryOps, "t4 != t3").WithArguments("!=", "T4", "T3"), // (33,14): error CS0019: Operator '!=' cannot be applied to operands of type 'T4' and 'T4' // b = (t4 != t4); Diagnostic(ErrorCode.ERR_BadBinaryOps, "t4 != t4").WithArguments("!=", "T4", "T4"), // (34,14): error CS0019: Operator '!=' cannot be applied to operands of type 'T4' and 'int' // b = (t4 != i); Diagnostic(ErrorCode.ERR_BadBinaryOps, "t4 != i").WithArguments("!=", "T4", "int"), // (35,14): error CS0019: Operator '!=' cannot be applied to operands of type 'T4' and 'C' // b = (t4 != c); Diagnostic(ErrorCode.ERR_BadBinaryOps, "t4 != c").WithArguments("!=", "T4", "C"), // (37,14): error CS0019: Operator '!=' cannot be applied to operands of type 'int' and 'T1' // b = (i != t1); Diagnostic(ErrorCode.ERR_BadBinaryOps, "i != t1").WithArguments("!=", "int", "T1"), // (38,14): error CS0019: Operator '!=' cannot be applied to operands of type 'int' and 'T2' // b = (i != t2); Diagnostic(ErrorCode.ERR_BadBinaryOps, "i != t2").WithArguments("!=", "int", "T2"), // (39,14): error CS0019: Operator '!=' cannot be applied to operands of type 'int' and 'T3' // b = (i != t3); Diagnostic(ErrorCode.ERR_BadBinaryOps, "i != t3").WithArguments("!=", "int", "T3"), // (40,14): error CS0019: Operator '!=' cannot be applied to operands of type 'int' and 'T4' // b = (i != t4); Diagnostic(ErrorCode.ERR_BadBinaryOps, "i != t4").WithArguments("!=", "int", "T4"), // (42,14): error CS0019: Operator '!=' cannot be applied to operands of type 'int' and 'C' // b = (i != c); Diagnostic(ErrorCode.ERR_BadBinaryOps, "i != c").WithArguments("!=", "int", "C"), // (44,14): error CS0019: Operator '!=' cannot be applied to operands of type 'C' and 'T1' // b = (c != t1); Diagnostic(ErrorCode.ERR_BadBinaryOps, "c != t1").WithArguments("!=", "C", "T1"), // (46,14): error CS0019: Operator '!=' cannot be applied to operands of type 'C' and 'T3' // b = (c != t3); Diagnostic(ErrorCode.ERR_BadBinaryOps, "c != t3").WithArguments("!=", "C", "T3"), // (47,14): error CS0019: Operator '!=' cannot be applied to operands of type 'C' and 'T4' // b = (c != t4); Diagnostic(ErrorCode.ERR_BadBinaryOps, "c != t4").WithArguments("!=", "C", "T4"), // (48,14): error CS0019: Operator '!=' cannot be applied to operands of type 'C' and 'int' // b = (c != i); Diagnostic(ErrorCode.ERR_BadBinaryOps, "c != i").WithArguments("!=", "C", "int"), // (53,14): error CS0019: Operator '!=' cannot be applied to operands of type '<null>' and 'T3' // b = (null != t3); Diagnostic(ErrorCode.ERR_BadBinaryOps, "null != t3").WithArguments("!=", "<null>", "T3"), // (17,14): warning CS1718: Comparison made to same variable; did you mean to compare something else? // b = (t2 == t2); Diagnostic(ErrorCode.WRN_ComparisonToSelf, "t2 == t2"), // (41,14): warning CS1718: Comparison made to same variable; did you mean to compare something else? // b = (i != i); Diagnostic(ErrorCode.WRN_ComparisonToSelf, "i != i"), // (43,14): warning CS0472: The result of the expression is always 'true' since a value of type 'int' is never equal to 'null' of type 'int?' // b = (i != null); Diagnostic(ErrorCode.WRN_NubExprIsConstBool, "i != null").WithArguments("true", "int", "int?"), // (49,14): warning CS1718: Comparison made to same variable; did you mean to compare something else? // b = (c != c); Diagnostic(ErrorCode.WRN_ComparisonToSelf, "c != c"), // (55,14): warning CS0472: The result of the expression is always 'true' since a value of type 'int' is never equal to 'null' of type 'int?' // b = (null != i); Diagnostic(ErrorCode.WRN_NubExprIsConstBool, "null != i").WithArguments("true", "int", "int?")); } [Fact] public void CS0019ERR_BadBinaryOps16() { var text = @"class A { } class B : A { } interface I { } class C { static void M<T, U>(T t, U u, A a, B b, C c, I i) where T : A where U : B { bool x; x = (t == t); x = (t == u); x = (t == a); x = (t == b); x = (t == c); x = (t == i); x = (u == t); x = (u == u); x = (u == a); x = (u == b); x = (u == c); x = (u == i); x = (a == t); x = (a == u); x = (a == a); x = (a == b); x = (a == c); x = (a == i); x = (b == t); x = (b == u); x = (b == a); x = (b == b); x = (b == c); x = (b == i); x = (c == t); x = (c == u); x = (c == a); x = (c == b); x = (c == c); x = (c == i); x = (i == t); x = (i == u); x = (i == a); x = (i == b); x = (i == c); x = (i == i); } }"; CreateCompilation(text).VerifyDiagnostics( // (15,14): error CS0019: Operator '==' cannot be applied to operands of type 'T' and 'C' // x = (t == c); Diagnostic(ErrorCode.ERR_BadBinaryOps, "t == c").WithArguments("==", "T", "C"), // (21,14): error CS0019: Operator '==' cannot be applied to operands of type 'U' and 'C' // x = (u == c); Diagnostic(ErrorCode.ERR_BadBinaryOps, "u == c").WithArguments("==", "U", "C"), // (27,14): error CS0019: Operator '==' cannot be applied to operands of type 'A' and 'C' // x = (a == c); Diagnostic(ErrorCode.ERR_BadBinaryOps, "a == c").WithArguments("==", "A", "C"), // (33,14): error CS0019: Operator '==' cannot be applied to operands of type 'B' and 'C' // x = (b == c); Diagnostic(ErrorCode.ERR_BadBinaryOps, "b == c").WithArguments("==", "B", "C"), // (35,14): error CS0019: Operator '==' cannot be applied to operands of type 'C' and 'T' // x = (c == t); Diagnostic(ErrorCode.ERR_BadBinaryOps, "c == t").WithArguments("==", "C", "T"), // (36,14): error CS0019: Operator '==' cannot be applied to operands of type 'C' and 'U' // x = (c == u); Diagnostic(ErrorCode.ERR_BadBinaryOps, "c == u").WithArguments("==", "C", "U"), // (37,14): error CS0019: Operator '==' cannot be applied to operands of type 'C' and 'A' // x = (c == a); Diagnostic(ErrorCode.ERR_BadBinaryOps, "c == a").WithArguments("==", "C", "A"), // (38,14): error CS0019: Operator '==' cannot be applied to operands of type 'C' and 'B' // x = (c == b); Diagnostic(ErrorCode.ERR_BadBinaryOps, "c == b").WithArguments("==", "C", "B"), // (11,14): warning CS1718: Comparison made to same variable; did you mean to compare something else? // x = (t == t); Diagnostic(ErrorCode.WRN_ComparisonToSelf, "t == t"), // (18,14): warning CS1718: Comparison made to same variable; did you mean to compare something else? // x = (u == u); Diagnostic(ErrorCode.WRN_ComparisonToSelf, "u == u"), // (25,14): warning CS1718: Comparison made to same variable; did you mean to compare something else? // x = (a == a); Diagnostic(ErrorCode.WRN_ComparisonToSelf, "a == a"), // (32,14): warning CS1718: Comparison made to same variable; did you mean to compare something else? // x = (b == b); Diagnostic(ErrorCode.WRN_ComparisonToSelf, "b == b"), // (39,14): warning CS1718: Comparison made to same variable; did you mean to compare something else? // x = (c == c); Diagnostic(ErrorCode.WRN_ComparisonToSelf, "c == c"), // (46,14): warning CS1718: Comparison made to same variable; did you mean to compare something else? // x = (i == i); Diagnostic(ErrorCode.WRN_ComparisonToSelf, "i == i")); } [Fact] public void CS0019ERR_BadBinaryOps17() { var text = @"struct S { } abstract class A<T> { internal virtual void M<U>(U u) where U : T { bool b; b = (u == null); b = (null != u); } } class B : A<S> { internal override void M<U>(U u) { bool b; b = (u == null); b = (null != u); } }"; CreateCompilation(text).VerifyDiagnostics( // (16,14): error CS0019: Operator '==' cannot be applied to operands of type 'U' and '<null>' Diagnostic(ErrorCode.ERR_BadBinaryOps, "u == null").WithArguments("==", "U", "<null>").WithLocation(16, 14), // (17,14): error CS0019: Operator '!=' cannot be applied to operands of type '<null>' and 'U' Diagnostic(ErrorCode.ERR_BadBinaryOps, "null != u").WithArguments("!=", "<null>", "U").WithLocation(17, 14)); } [Fact] public void CS0020ERR_IntDivByZero() { var text = @" namespace x { public class b { public static int Main() { int s = 1 / 0; // CS0020 return s; } } }"; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_IntDivByZero, Line = 8, Column = 21 } }); } [Fact] public void CS0020ERR_IntDivByZero_02() { var text = @" namespace x { public class b { public static void Main() { decimal x1 = 1.20M / 0; // CS0020 decimal x2 = 1.20M / decimal.Zero; // CS0020 decimal x3 = decimal.MaxValue / decimal.Zero; // CS0020 } } }"; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_IntDivByZero, Line = 8, Column = 26 }, new ErrorDescription { Code = (int)ErrorCode.ERR_IntDivByZero, Line = 9, Column = 26 }, new ErrorDescription { Code = (int)ErrorCode.ERR_IntDivByZero, Line = 10, Column = 26 } }); } [Fact] public void CS0021ERR_BadIndexLHS() { var text = @"enum E { } class C { static void M<T>() { object o; o = M[0]; o = ((System.Action)null)[0]; o = ((dynamic)o)[0]; o = default(E)[0]; o = default(T)[0]; o = (new C())[0]; } }"; CreateCompilation(text).VerifyDiagnostics( // (7,13): error CS0021: Cannot apply indexing with [] to an expression of type 'method group' Diagnostic(ErrorCode.ERR_BadIndexLHS, "M[0]").WithArguments("method group").WithLocation(7, 13), // (8,13): error CS0021: Cannot apply indexing with [] to an expression of type 'System.Action' Diagnostic(ErrorCode.ERR_BadIndexLHS, "((System.Action)null)[0]").WithArguments("System.Action").WithLocation(8, 13), // (10,13): error CS0021: Cannot apply indexing with [] to an expression of type 'E' Diagnostic(ErrorCode.ERR_BadIndexLHS, "default(E)[0]").WithArguments("E").WithLocation(10, 13), // (11,13): error CS0021: Cannot apply indexing with [] to an expression of type 'T' Diagnostic(ErrorCode.ERR_BadIndexLHS, "default(T)[0]").WithArguments("T").WithLocation(11, 13), // (12,13): error CS0021: Cannot apply indexing with [] to an expression of type 'C' Diagnostic(ErrorCode.ERR_BadIndexLHS, "(new C())[0]").WithArguments("C").WithLocation(12, 13)); } [Fact] public void CS0022ERR_BadIndexCount() { var text = @" namespace x { public class b { public static void Main() { int[,] a = new int[10,2] ; a[2] = 4; //bad index count in access } } }"; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_BadIndexCount, Line = 9, Column = 25 } }); } [WorkItem(542486, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542486")] [Fact] public void CS0022ERR_BadIndexCount02() { var text = @" class Program { static void Main(string[] args) { int[,] a = new int[1 2]; //bad index count in size specifier - no initializer } } "; CreateCompilation(text).VerifyDiagnostics( // (6,30): error CS1003: Syntax error, ',' expected Diagnostic(ErrorCode.ERR_SyntaxError, "2").WithArguments(",", "")); } [WorkItem(542486, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542486")] [Fact] public void CS0022ERR_BadIndexCount03() { var text = @" class Program { static void Main(string[] args) { int[,] a = new int[1 2] { 1 }; //bad index count in size specifier - with initializer } } "; // NOTE: Dev10 just gives a parse error on '2' CreateCompilation(text).VerifyDiagnostics( // (6,30): error CS1003: Syntax error, ',' expected Diagnostic(ErrorCode.ERR_SyntaxError, "2").WithArguments(",", ""), // (6,35): error CS0846: A nested array initializer is expected Diagnostic(ErrorCode.ERR_ArrayInitializerExpected, "1")); } [WorkItem(542486, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542486")] [Fact] public void CS0022ERR_BadIndexCount04() { var text = @" class Program { static void Main(string[] args) { int[,] a = new int[1,]; //bad index count in size specifier - no initializer } } "; CreateCompilation(text).VerifyDiagnostics( // (6,30): error CS0443: Syntax error; value expected Diagnostic(ErrorCode.ERR_ValueExpected, "")); } [WorkItem(542486, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542486")] [Fact] public void CS0022ERR_BadIndexCount05() { var text = @" class Program { static void Main(string[] args) { int[,] a = new int[1,] { { 1 } }; //bad index count in size specifier - with initializer } } "; CreateCompilation(text).VerifyDiagnostics( // (6,30): error CS0443: Syntax error; value expected Diagnostic(ErrorCode.ERR_ValueExpected, "")); } [WorkItem(539590, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539590")] [Fact] public void CS0023ERR_BadUnaryOp1() { var text = @" namespace X { class C { object M() { object q = new object(); if (!q) // CS0023 { } object obj = -null; // CS0023 obj = !null; // CS0023 obj = ~null; // CS0023 obj++; // CS0023 --obj; // CS0023 return +null; // CS0023 } } } "; CreateCompilation(text).VerifyDiagnostics( // (9,17): error CS0023: Operator '!' cannot be applied to operand of type 'object' // if (!q) // CS0023 Diagnostic(ErrorCode.ERR_BadUnaryOp, "!q").WithArguments("!", "object").WithLocation(9, 17), // (12,26): error CS8310: Operator '-' cannot be applied to operand '<null>' // object obj = -null; // CS0023 Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, "-null").WithArguments("-", "<null>").WithLocation(12, 26), // (13,19): error CS8310: Operator '!' cannot be applied to operand '<null>' // obj = !null; // CS0023 Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, "!null").WithArguments("!", "<null>").WithLocation(13, 19), // (14,19): error CS8310: Operator '~' cannot be applied to operand '<null>' // obj = ~null; // CS0023 Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, "~null").WithArguments("~", "<null>").WithLocation(14, 19), // (16,13): error CS0023: Operator '++' cannot be applied to operand of type 'object' // obj++; // CS0023 Diagnostic(ErrorCode.ERR_BadUnaryOp, "obj++").WithArguments("++", "object").WithLocation(16, 13), // (17,13): error CS0023: Operator '--' cannot be applied to operand of type 'object' // --obj; // CS0023 Diagnostic(ErrorCode.ERR_BadUnaryOp, "--obj").WithArguments("--", "object").WithLocation(17, 13), // (18,20): error CS8310: Operator '+' cannot be applied to operand '<null>' // return +null; // CS0023 Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, "+null").WithArguments("+", "<null>").WithLocation(18, 20) ); } [WorkItem(539590, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539590")] [Fact] public void CS0023ERR_BadUnaryOp_Nullable() { var text = @" public class Test { public static void Main() { bool? b = !null; // CS0023 int? n = ~null; // CS0023 float? f = +null; // CS0023 long? u = -null; // CS0023 ++n; n--; --u; u++; } } "; CreateCompilation(text).VerifyDiagnostics( // (6,19): error CS8310: Operator '!' cannot be applied to operand '<null>' // bool? b = !null; // CS0023 Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, "!null").WithArguments("!", "<null>").WithLocation(6, 19), // (7,18): error CS8310: Operator '~' cannot be applied to operand '<null>' // int? n = ~null; // CS0023 Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, "~null").WithArguments("~", "<null>").WithLocation(7, 18), // (8,20): error CS8310: Operator '+' cannot be applied to operand '<null>' // float? f = +null; // CS0023 Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, "+null").WithArguments("+", "<null>").WithLocation(8, 20), // (9,19): error CS8310: Operator '-' cannot be applied to operand '<null>' // long? u = -null; // CS0023 Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, "-null").WithArguments("-", "<null>").WithLocation(9, 19) ); } [WorkItem(539590, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539590")] [Fact] public void CS0023ERR_BadUnaryOp2() { var text = @" namespace X { class C { void M() { System.Action f = M; f = +M; // CS0023 f = +(() => { }); // CS0023 } } } "; CreateCompilation(text).VerifyDiagnostics( // (9,17): error CS0023: Operator '+' cannot be applied to operand of type 'method group' Diagnostic(ErrorCode.ERR_BadUnaryOp, "+M").WithArguments("+", "method group"), // (10,17): error CS0023: Operator '+' cannot be applied to operand of type 'lambda expression' Diagnostic(ErrorCode.ERR_BadUnaryOp, "+(() => { })").WithArguments("+", "lambda expression")); } [WorkItem(540211, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540211")] [Fact] public void CS0023ERR_BadUnaryOp_VoidMissingInstanceMethod() { var text = @"class C { void M() { M().Goo(); } } "; CreateCompilation(text).VerifyDiagnostics( // (5,12): error CS0023: Operator '.' cannot be applied to operand of type 'void' Diagnostic(ErrorCode.ERR_BadUnaryOp, ".").WithArguments(".", "void")); } [WorkItem(540211, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540211")] [Fact] public void CS0023ERR_BadUnaryOp_VoidToString() { var text = @"class C { void M() { M().ToString(); //plausible, but still wrong } } "; CreateCompilation(text).VerifyDiagnostics( // (5,12): error CS0023: Operator '.' cannot be applied to operand of type 'void' Diagnostic(ErrorCode.ERR_BadUnaryOp, ".").WithArguments(".", "void")); } [WorkItem(540329, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540329")] [Fact] public void CS0023ERR_BadUnaryOp_null() { var text = @" class X { static void Main() { int x = null.Length; } } "; CreateCompilation(text).VerifyDiagnostics( Diagnostic(ErrorCode.ERR_BadUnaryOp, "null.Length").WithArguments(".", "<null>")); } [WorkItem(540329, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540329")] [Fact] 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( Diagnostic(ErrorCode.ERR_BadUnaryOp, "arg => { arg = 2; return arg; }.ToString").WithArguments(".", "lambda expression"), Diagnostic(ErrorCode.ERR_BadUnaryOp, "delegate { }.ToString").WithArguments(".", "anonymous method")); } [Fact] public void CS0026ERR_ThisInStaticMeth() { var text = @" public class MyClass { public static int i = 0; public static void Main() { // CS0026 this.i = this.i + 1; } }"; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_ThisInStaticMeth, Line = 9, Column = 9 }, new ErrorDescription { Code = (int)ErrorCode.ERR_ObjectProhibited, Line = 9, Column = 9 }, new ErrorDescription { Code = (int)ErrorCode.ERR_ThisInStaticMeth, Line = 9, Column = 18 }, new ErrorDescription { Code = (int)ErrorCode.ERR_ObjectProhibited, Line = 9, Column = 18 } }); } [Fact] public void CS0026ERR_ThisInStaticMeth_StaticConstructor() { var text = @" public class MyClass { int f; void M() { } int P { get; set; } static MyClass() { this.f = this.P; this.M(); } }"; CreateCompilation(text).VerifyDiagnostics( // (10,9): error CS0026: Keyword 'this' is not valid in a static property, static method, or static field initializer Diagnostic(ErrorCode.ERR_ThisInStaticMeth, "this"), // (10,18): error CS0026: Keyword 'this' is not valid in a static property, static method, or static field initializer Diagnostic(ErrorCode.ERR_ThisInStaticMeth, "this"), // (11,9): error CS0026: Keyword 'this' is not valid in a static property, static method, or static field initializer Diagnostic(ErrorCode.ERR_ThisInStaticMeth, "this")); } [Fact] public void CS0026ERR_ThisInStaticMeth_Combined() { var text = @" using System; class CLS { static CLS() { var x = this.ToString(); } static object FLD = this.ToString(); static object PROP { get { return this.ToString(); } } static object METHOD() { return this.ToString(); } } class A : Attribute { public object P; } "; CreateCompilation(text).VerifyDiagnostics( // (7,25): error CS0026: Keyword 'this' is not valid in a static property, static method, or static field initializer // static object FLD = this.ToString(); Diagnostic(ErrorCode.ERR_ThisInStaticMeth, "this"), // (6,28): error CS0026: Keyword 'this' is not valid in a static property, static method, or static field initializer // static CLS() { var x = this.ToString(); } Diagnostic(ErrorCode.ERR_ThisInStaticMeth, "this"), // (8,39): error CS0026: Keyword 'this' is not valid in a static property, static method, or static field initializer // static object PROP { get { return this.ToString(); } } Diagnostic(ErrorCode.ERR_ThisInStaticMeth, "this"), // (9,37): error CS0026: Keyword 'this' is not valid in a static property, static method, or static field initializer // static object METHOD() { return this.ToString(); } Diagnostic(ErrorCode.ERR_ThisInStaticMeth, "this"), // (14,19): warning CS0649: Field 'A.P' is never assigned to, and will always have its default value null // public object P; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "P").WithArguments("A.P", "null") ); } [Fact] public void CS0027ERR_ThisInBadContext() { var text = @" namespace ConsoleApplication3 { class MyClass { int err1 = this.Fun() + 1; // CS0027 public void Fun() { } } }"; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_ThisInBadContext, Line = 6, Column = 20 } }); } [Fact] public void CS0027ERR_ThisInBadContext_2() { var text = @" using System; [assembly: A(P = this.ToString())] class A : Attribute { public object P; } "; CreateCompilation(text).VerifyDiagnostics( // (4,18): error CS0027: Keyword 'this' is not available in the current context // [assembly: A(P = this.ToString())] Diagnostic(ErrorCode.ERR_ThisInBadContext, "this")); } [Fact] public void CS0027ERR_ThisInBadContext_Interactive() { string text = @" int a; int b = a; int c = this.a; // 1 this.c = // 2 this.a; // 3 int prop { get { return 1; } set { this.a = 1;} } // 4 void goo() { this.goo(); // 5 this.a = // 6 this.b; // 7 object c = this; // 8 } this.prop = 1; // 9 class C { C() : base() { } void goo() { this.goo(); // OK } }"; var comp = CreateCompilationWithMscorlib45( new[] { SyntaxFactory.ParseSyntaxTree(text, options: TestOptions.Script) }); comp.VerifyDiagnostics( // (4,9): error CS0027: Keyword 'this' is not available in the current context // int c = this.a; // 1 Diagnostic(ErrorCode.ERR_ThisInBadContext, "this").WithLocation(4, 9), // (5,1): error CS0027: Keyword 'this' is not available in the current context // this.c = // 2 Diagnostic(ErrorCode.ERR_ThisInBadContext, "this").WithLocation(5, 1), // (6,5): error CS0027: Keyword 'this' is not available in the current context // this.a; // 3 Diagnostic(ErrorCode.ERR_ThisInBadContext, "this").WithLocation(6, 5), // (16,1): error CS0027: Keyword 'this' is not available in the current context // this.prop = 1; // 9 Diagnostic(ErrorCode.ERR_ThisInBadContext, "this").WithLocation(16, 1), // (7,36): error CS0027: Keyword 'this' is not available in the current context // int prop { get { return 1; } set { this.a = 1;} } // 4 Diagnostic(ErrorCode.ERR_ThisInBadContext, "this").WithLocation(7, 36), // (10,5): error CS0027: Keyword 'this' is not available in the current context // this.goo(); // 5 Diagnostic(ErrorCode.ERR_ThisInBadContext, "this").WithLocation(10, 5), // (11,5): error CS0027: Keyword 'this' is not available in the current context // this.a = // 6 Diagnostic(ErrorCode.ERR_ThisInBadContext, "this").WithLocation(11, 5), // (12,9): error CS0027: Keyword 'this' is not available in the current context // this.b; // 7 Diagnostic(ErrorCode.ERR_ThisInBadContext, "this").WithLocation(12, 9), // (13,16): error CS0027: Keyword 'this' is not available in the current context // object c = this; // 8 Diagnostic(ErrorCode.ERR_ThisInBadContext, "this").WithLocation(13, 16) ); } [Fact] public void CS0029ERR_NoImplicitConv01() { var text = @" namespace ConsoleApplication3 { class MyClass { int err1 = 1; public string Fun() { return err1; } public static void Main() { MyClass c = new MyClass(); } } }"; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_NoImplicitConv, Line = 11, Column = 20 } }); } [Fact] public void CS0029ERR_NoImplicitConv02() { var source = "enum E { A = new[] { 1, 2, 3 } }"; CreateCompilation(source).VerifyDiagnostics( // (1,14): error CS0029: Cannot implicitly convert type 'int[]' to 'int' // enum E { A = new[] { 1, 2, 3 } } Diagnostic(ErrorCode.ERR_NoImplicitConv, "new[] { 1, 2, 3 }").WithArguments("int[]", "int").WithLocation(1, 14)); } [Fact] public void CS0029ERR_NoImplicitConv03() { var source = @"class C { static void M() { const C d = F(); } static D F() { return null; } } class D { } "; CreateCompilation(source).VerifyDiagnostics( // (5,21): error CS0029: Cannot implicitly convert type 'D' to 'C' // const C d = F(); Diagnostic(ErrorCode.ERR_NoImplicitConv, "F()").WithArguments("D", "C").WithLocation(5, 21)); } [WorkItem(541719, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541719")] [Fact] public void CS0029ERR_NoImplicitConv04() { var text = @"class C1 { public static void Main() { bool m = true; int[] arr = new int[m]; // Invalid } } "; CreateCompilation(text).VerifyDiagnostics( // (6,29): error CS0029: Cannot implicitly convert type 'bool' to 'int' // int[] arr = new int[m]; // Invalid Diagnostic(ErrorCode.ERR_NoImplicitConv, "m").WithArguments("bool", "int").WithLocation(6, 29)); } [Fact, WorkItem(40405, "https://github.com/dotnet/roslyn/issues/40405")] public void ThrowExpression_ImplicitVoidConversion_Return() { string text = @" class C { void M1() { return true ? throw null : M2(); } void M2() { } } "; CreateCompilation(text).VerifyDiagnostics( // (6,23): error CS0029: Cannot implicitly convert type '<throw expression>' to 'void' // return true ? throw null : M2(); Diagnostic(ErrorCode.ERR_NoImplicitConv, "throw null").WithArguments("<throw expression>", "void").WithLocation(6, 23)); } [Fact, WorkItem(40405, "https://github.com/dotnet/roslyn/issues/40405")] public void ThrowExpression_ImplicitVoidConversion_Assignment() { string text = @" class C { void M1() { object obj = true ? throw null : M2(); } void M2() { } } "; CreateCompilation(text).VerifyDiagnostics( // (6,29): error CS0029: Cannot implicitly convert type '<throw expression>' to 'void' // object obj = true ? throw null : M2(); Diagnostic(ErrorCode.ERR_NoImplicitConv, "throw null").WithArguments("<throw expression>", "void").WithLocation(6, 29)); } [Fact, WorkItem(40405, "https://github.com/dotnet/roslyn/issues/40405")] public void IntLiteral_ImplicitVoidConversion_Assignment() { string text = @" class C { void M1() { var obj = true ? 0 : M2(); } void M2() { } } "; CreateCompilation(text).VerifyDiagnostics( // (6,19): error CS0173: Type of conditional expression cannot be determined because there is no implicit conversion between 'int' and 'void' // var obj = true ? 0 : M2(); Diagnostic(ErrorCode.ERR_InvalidQM, "true ? 0 : M2()").WithArguments("int", "void").WithLocation(6, 19) ); } [Fact, WorkItem(40405, "https://github.com/dotnet/roslyn/issues/40405")] public void VoidCall_ImplicitVoidConversion_Assignment() { string text = @" class C { void M1() { object obj = true ? M2() : M2(); } void M2() { } } "; CreateCompilation(text).VerifyDiagnostics( // (6,22): error CS0029: Cannot implicitly convert type 'void' to 'object' // object obj = true ? M2() : M2(); Diagnostic(ErrorCode.ERR_NoImplicitConv, "true ? M2() : M2()").WithArguments("void", "object").WithLocation(6, 22)); } [Fact, WorkItem(40405, "https://github.com/dotnet/roslyn/issues/40405")] public void VoidCall_ImplicitVoidConversion_DiscardAssignment() { string text = @" class C { void M1() { _ = true ? M2() : M2(); } void M2() { } } "; CreateCompilation(text).VerifyDiagnostics( // (6,9): error CS8209: A value of type 'void' may not be assigned. // _ = true ? M2() : M2(); Diagnostic(ErrorCode.ERR_VoidAssignment, "_").WithLocation(6, 9)); } [Fact, WorkItem(40405, "https://github.com/dotnet/roslyn/issues/40405")] public void VoidCall_Assignment() { string text = @" class C { void M1() { object obj = M2(); } void M2() { } } "; CreateCompilation(text).VerifyDiagnostics( // (6,22): error CS0029: Cannot implicitly convert type 'void' to 'object' // object obj = M2(); Diagnostic(ErrorCode.ERR_NoImplicitConv, "M2()").WithArguments("void", "object").WithLocation(6, 22)); } [Fact, WorkItem(40405, "https://github.com/dotnet/roslyn/issues/40405")] public void VoidCall_DiscardAssignment() { string text = @" class C { void M1() { _ = M2(); } void M2() { } } "; CreateCompilation(text).VerifyDiagnostics( // (6,9): error CS8209: A value of type 'void' may not be assigned. // _ = M2(); Diagnostic(ErrorCode.ERR_VoidAssignment, "_").WithLocation(6, 9)); } [Fact, WorkItem(40405, "https://github.com/dotnet/roslyn/issues/40405")] public void VoidCall_ImplicitVoidConversion_Return() { string text = @" class C { void M1() { return true ? M2() : M2(); } void M2() { } } "; CreateCompilation(text).VerifyDiagnostics( // (6,9): error CS0127: Since 'C.M1()' returns void, a return keyword must not be followed by an object expression // return true ? M2() : M2(); Diagnostic(ErrorCode.ERR_RetNoObjectRequired, "return").WithArguments("C.M1()").WithLocation(6, 9)); } [Fact] public void CS0030ERR_NoExplicitConv() { var text = @" namespace x { public class iii { public static iii operator ++(iii aa) { return (iii)0; // CS0030 } } }"; CreateCompilation(text).VerifyDiagnostics( // (8,20): error CS0030: Cannot convert type 'int' to 'x.iii' // return (iii)0; // CS0030 Diagnostic(ErrorCode.ERR_NoExplicitConv, "(iii)0").WithArguments("int", "x.iii")); } [WorkItem(528539, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528539")] [WorkItem(1119609, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1119609")] [WorkItem(920, "http://github.com/dotnet/roslyn/issues/920")] [Fact] public void CS0030ERR_NoExplicitConv02() { const string text = @" public class C { public static void Main() { decimal x = (decimal)double.PositiveInfinity; } }"; var diagnostics = CreateCompilation(text).GetDiagnostics(); var savedCurrentCulture = Thread.CurrentThread.CurrentCulture; var savedCurrentUICulture = Thread.CurrentThread.CurrentUICulture; Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture; Thread.CurrentThread.CurrentUICulture = CultureInfo.InvariantCulture; try { diagnostics.Verify( // (6,21): error CS0031: Constant value 'Infinity' cannot be converted to a 'decimal' // decimal x = (decimal)double.PositiveInfinity; Diagnostic(ErrorCode.ERR_ConstOutOfRange, "(decimal)double.PositiveInfinity").WithArguments("Infinity", "decimal"), // (6,17): warning CS0219: The variable 'x' is assigned but its value is never used // decimal x = (decimal)double.PositiveInfinity; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x").WithArguments("x")); } finally { Thread.CurrentThread.CurrentCulture = savedCurrentCulture; Thread.CurrentThread.CurrentUICulture = savedCurrentUICulture; } } [Fact] public void CS0030ERR_NoExplicitConv_Foreach() { var text = @" public class Test { static void Main(string[] args) { int[][] arr = new int[][] { new int[] { 1, 2 }, new int[] { 4, 5, 6 } }; foreach (int outer in arr) { } // invalid } }"; CreateCompilation(text).VerifyDiagnostics(Diagnostic(ErrorCode.ERR_NoExplicitConv, "foreach").WithArguments("int[]", "int")); } [Fact] public void CS0031ERR_ConstOutOfRange01() { var text = @"public class a { int num = (int)2147483648M; //CS0031 } "; CreateCompilation(text).VerifyDiagnostics( // (3,15): error CS0031: Constant value '2147483648M' cannot be converted to a 'int' // int num = (int)2147483648M; //CS0031 Diagnostic(ErrorCode.ERR_ConstOutOfRange, "(int)2147483648M").WithArguments("2147483648M", "int"), // (3,9): warning CS0414: The field 'a.num' is assigned but its value is never used // int num = (int)2147483648M; //CS0031 Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "num").WithArguments("a.num")); } [WorkItem(528539, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528539")] [Fact] public void CS0031ERR_ConstOutOfRange02() { var text = @" enum E : ushort { A = 10, B = -1 // CS0031 } enum F : sbyte { A = 0x7f, B = 0xf0, // CS0031 C, D = (A + 1) - 2, E = (A + 1), // CS0031 } class A { byte bt = 256; } "; CreateCompilation(text).VerifyDiagnostics( // (5,9): error CS0031: Constant value '-1' cannot be converted to a 'ushort' // B = -1 // CS0031 Diagnostic(ErrorCode.ERR_ConstOutOfRange, "-1").WithArguments("-1", "ushort").WithLocation(5, 9), // (10,9): error CS0031: Constant value '240' cannot be converted to a 'sbyte' // B = 0xf0, // CS0031 Diagnostic(ErrorCode.ERR_ConstOutOfRange, "0xf0").WithArguments("240", "sbyte").WithLocation(10, 9), // (13,10): error CS0031: Constant value '128' cannot be converted to a 'sbyte' // E = (A + 1), // CS0031 Diagnostic(ErrorCode.ERR_ConstOutOfRange, "A + 1").WithArguments("128", "sbyte").WithLocation(13, 10), // (17,15): error CS0031: Constant value '256' cannot be converted to a 'byte' // byte bt = 256; Diagnostic(ErrorCode.ERR_ConstOutOfRange, "256").WithArguments("256", "byte").WithLocation(17, 15), // (17,10): warning CS0414: The field 'A.bt' is assigned but its value is never used // byte bt = 256; Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "bt").WithArguments("A.bt").WithLocation(17, 10)); } [Fact] public void CS0221ERR_ConstOutOfRangeChecked04() { // Confirm that we truncate the constant value before performing the range check var template = @"public class C { void M() { System.Console.WriteLine((System.Int32)(System.Int32.MinValue - 0.9)); System.Console.WriteLine((System.Int32)(System.Int32.MinValue - 1.0)); //CS0221 System.Console.WriteLine((System.Int32)(System.Int32.MaxValue + 0.9)); System.Console.WriteLine((System.Int32)(System.Int32.MaxValue + 1.0)); //CS0221 } } "; var integralTypes = new Type[] { typeof(char), typeof(sbyte), typeof(byte), typeof(short), typeof(ushort), typeof(int), typeof(uint), }; foreach (Type t in integralTypes) { DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(template.Replace("System.Int32", t.ToString()), new ErrorDescription { Code = (int)ErrorCode.ERR_ConstOutOfRangeChecked, Line = 6, Column = 34 }, new ErrorDescription { Code = (int)ErrorCode.ERR_ConstOutOfRangeChecked, Line = 8, Column = 34 }); } } // Note that the errors for Int64 and UInt64 are not // exactly the same as for Int32, etc. above, but the // differences match the native compiler. [WorkItem(528715, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528715")] [Fact] public void CS0221ERR_ConstOutOfRangeChecked05() { // Confirm that we truncate the constant value before performing the range check var text1 = @"public class C { void M() { System.Console.WriteLine((System.Int64)(System.Int64.MinValue - 0.9)); System.Console.WriteLine((System.Int64)(System.Int64.MinValue - 1.0)); System.Console.WriteLine((System.Int64)(System.Int64.MaxValue + 0.9)); //CS0221 System.Console.WriteLine((System.Int64)(System.Int64.MaxValue + 1.0)); //CS0221 } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text1, new ErrorDescription { Code = (int)ErrorCode.ERR_ConstOutOfRangeChecked, Line = 7, Column = 34 }, new ErrorDescription { Code = (int)ErrorCode.ERR_ConstOutOfRangeChecked, Line = 8, Column = 34 }); var text2 = @"public class C { void M() { System.Console.WriteLine((System.UInt64)(System.UInt64.MinValue - 0.9)); System.Console.WriteLine((System.UInt64)(System.UInt64.MinValue - 1.0)); //CS0221 System.Console.WriteLine((System.UInt64)(System.UInt64.MaxValue + 0.9)); //CS0221 System.Console.WriteLine((System.UInt64)(System.UInt64.MaxValue + 1.0)); //CS0221 } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text2, new ErrorDescription { Code = (int)ErrorCode.ERR_ConstOutOfRangeChecked, Line = 6, Column = 34 }, new ErrorDescription { Code = (int)ErrorCode.ERR_ConstOutOfRangeChecked, Line = 7, Column = 34 }, new ErrorDescription { Code = (int)ErrorCode.ERR_ConstOutOfRangeChecked, Line = 8, Column = 34 }); var text3 = @"class C { static void Main() { System.Console.WriteLine(long.MinValue); System.Console.WriteLine((long)(double)long.MinValue); } }"; CreateCompilation(text3).VerifyDiagnostics(); } [Fact] public void CS0034ERR_AmbigBinaryOps() { #region "Source" var text = @" public class A { // allows for the conversion of A object to int public static implicit operator int(A s) { return 0; } public static implicit operator string(A i) { return null; } } public class B { public static implicit operator int(B s) // one way to resolve this CS0034 is to make one conversion explicit // public static explicit operator int (B s) { return 0; } public static implicit operator string(B i) { return null; } public static implicit operator B(string i) { return null; } public static implicit operator B(int i) { return null; } } public class C { public static void Main() { A a = new A(); B b = new B(); b = b + a; // CS0034 // another way to resolve this CS0034 is to make a cast // b = b + (int)a; } } "; #endregion CreateCompilation(text).VerifyDiagnostics( // (47,13): error CS0034: Operator '+' is ambiguous on operands of type 'B' and 'A' // b = b + a; // CS0034 Diagnostic(ErrorCode.ERR_AmbigBinaryOps, "b + a").WithArguments("+", "B", "A")); } [Fact] public void CS0035ERR_AmbigUnaryOp_RoslynCS0023() { var text = @" class MyClass { private int i; public MyClass(int i) { this.i = i; } public static implicit operator double(MyClass x) { return (double)x.i; } public static implicit operator decimal(MyClass x) { return (decimal)x.i; } } class MyClass2 { static void Main() { MyClass x = new MyClass(7); object o = -x; // CS0035 } }"; CreateCompilation(text).VerifyDiagnostics( // (27,20): error CS0035: Operator '-' is ambiguous on an operand of type 'MyClass' // object o = -x; // CS0035 Diagnostic(ErrorCode.ERR_AmbigUnaryOp, "-x").WithArguments("-", "MyClass")); } [Fact] public void CS0037ERR_ValueCantBeNull01() { var source = @"enum E { } struct S { } class C { static void M() { int i; i = null; i = (int)null; E e; e = null; e = (E)null; S s; s = null; s = (S)null; X x; x = null; x = (X)null; } }"; CreateCompilation(source).VerifyDiagnostics( // (8,13): error CS0037: Cannot convert null to 'int' because it is a non-nullable value type Diagnostic(ErrorCode.ERR_ValueCantBeNull, "null").WithArguments("int").WithLocation(8, 13), // (9,13): error CS0037: Cannot convert null to 'int' because it is a non-nullable value type Diagnostic(ErrorCode.ERR_ValueCantBeNull, "(int)null").WithArguments("int").WithLocation(9, 13), // (11,13): error CS0037: Cannot convert null to 'E' because it is a non-nullable value type Diagnostic(ErrorCode.ERR_ValueCantBeNull, "null").WithArguments("E").WithLocation(11, 13), // (12,13): error CS0037: Cannot convert null to 'E' because it is a non-nullable value type Diagnostic(ErrorCode.ERR_ValueCantBeNull, "(E)null").WithArguments("E").WithLocation(12, 13), // (14,13): error CS0037: Cannot convert null to 'S' because it is a non-nullable value type Diagnostic(ErrorCode.ERR_ValueCantBeNull, "null").WithArguments("S").WithLocation(14, 13), // (15,13): error CS0037: Cannot convert null to 'S' because it is a non-nullable value type Diagnostic(ErrorCode.ERR_ValueCantBeNull, "(S)null").WithArguments("S").WithLocation(15, 13), // (16,9): error CS0246: The type or namespace name 'X' could not be found (are you missing a using directive or an assembly reference?) Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "X").WithArguments("X").WithLocation(16, 9), // (18,14): error CS0246: The type or namespace name 'X' could not be found (are you missing a using directive or an assembly reference?) Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "X").WithArguments("X").WithLocation(18, 14)); } [Fact] public void CS0037ERR_ValueCantBeNull02() { var source = @"interface I { } class A { } class B<T1, T2, T3, T4, T5, T6, T7> where T2 : class where T3 : struct where T4 : new() where T5 : I where T6 : A where T7 : T1 { static void M(object o) { o = (T1)null; o = (T2)null; o = (T3)null; o = (T4)null; o = (T5)null; o = (T6)null; o = (T7)null; } }"; CreateCompilation(source).VerifyDiagnostics( // (13,17): error CS0037: Cannot convert null to 'T1' because it is a non-nullable value type Diagnostic(ErrorCode.ERR_ValueCantBeNull, "(T1)null").WithArguments("T1").WithLocation(13, 13), // (15,17): error CS0037: Cannot convert null to 'T3' because it is a non-nullable value type Diagnostic(ErrorCode.ERR_ValueCantBeNull, "(T3)null").WithArguments("T3").WithLocation(15, 13), // (16,17): error CS0037: Cannot convert null to 'T4' because it is a non-nullable value type Diagnostic(ErrorCode.ERR_ValueCantBeNull, "(T4)null").WithArguments("T4").WithLocation(16, 13), // (17,17): error CS0037: Cannot convert null to 'T5' because it is a non-nullable value type Diagnostic(ErrorCode.ERR_ValueCantBeNull, "(T5)null").WithArguments("T5").WithLocation(17, 13), // (19,17): error CS0037: Cannot convert null to 'T7' because it is a non-nullable value type Diagnostic(ErrorCode.ERR_ValueCantBeNull, "(T7)null").WithArguments("T7").WithLocation(19, 13)); } [WorkItem(539589, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539589")] [Fact] public void CS0037ERR_ValueCantBeNull03() { var text = @" class Program { enum MyEnum { Zero = 0, One = 1 } static int Main() { return Goo((MyEnum)null); } static int Goo(MyEnum x) { return 1; } } "; CreateCompilation(text).VerifyDiagnostics(Diagnostic(ErrorCode.ERR_ValueCantBeNull, "(MyEnum)null").WithArguments("Program.MyEnum").WithLocation(12, 20)); } [Fact(), WorkItem(528875, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528875")] public void CS0038ERR_WrongNestedThis() { var text = @" class OuterClass { public int count; // try the following line instead // public static int count; class InnerClass { void func() { // or, create an instance // OuterClass class_inst = new OuterClass(); // int count2 = class_inst.count; int count2 = count; // CS0038 } } public static void Main() { } }"; // Triage decided not to implement the more specific error (WrongNestedThis) and stick with ObjectRequired. var comp = CreateCompilation(text, options: TestOptions.ReleaseDll.WithSpecificDiagnosticOptions(new Dictionary<string, ReportDiagnostic>() { { MessageProvider.Instance.GetIdForErrorCode(649), ReportDiagnostic.Suppress } })); comp.VerifyDiagnostics(Diagnostic(ErrorCode.ERR_ObjectRequired, "count").WithArguments("OuterClass.count")); } [Fact] public void CS0039ERR_NoExplicitBuiltinConv01() { var text = @"class A { } class B: A { } class C: A { } class M { static void Main() { A a = new C(); B b = new B(); C c; // This is valid; there is a built-in reference // conversion from A to C. c = a as C; //The following generates CS0039; there is no // built-in reference conversion from B to C. c = b as C; // CS0039 } }"; CreateCompilation(text).VerifyDiagnostics( // (24,13): error CS0039: Cannot convert type 'B' to 'C' via a reference conversion, boxing conversion, unboxing conversion, wrapping conversion, or null type conversion Diagnostic(ErrorCode.ERR_NoExplicitBuiltinConv, "b as C").WithArguments("B", "C").WithLocation(24, 13)); } [Fact, WorkItem(541142, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541142")] public void CS0039ERR_NoExplicitBuiltinConv02() { var text = @"delegate void D(); class C { static void M(C c) { (F as D)(); (c.F as D)(); (G as D)(); } void F() { } static void G() { } }"; CreateCompilation(text).VerifyDiagnostics( // (6,10): 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(6, 10), // (7,10): 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(7, 10), // (8,10): 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(8, 10)); } [Fact, WorkItem(542047, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542047")] public void CS0039ERR_ConvTypeReferenceToObject() { var text = @"using System; class C { static void Main() { TypedReference a = new TypedReference(); object obj = a as object; //CS0039 } } "; CreateCompilation(text).VerifyDiagnostics( //(7,22): error CS0039: Cannot convert type 'System.TypedReference' to 'object' via a reference conversion, boxing conversion, unboxing conversion, wrapping conversion, or null type conversion Diagnostic(ErrorCode.ERR_NoExplicitBuiltinConv, "a as object").WithArguments("System.TypedReference", "object").WithLocation(7, 22)); } [Fact] public void CS0069ERR_EventPropertyInInterface() { var text = @" interface I { event System.Action E1 { add; } event System.Action E2 { remove; } event System.Action E3 { add; remove; } } "; CreateCompilation(text, parseOptions: TestOptions.Regular7, targetFramework: TargetFramework.NetCoreApp).VerifyDiagnostics( // (4,30): error CS8652: The feature 'default interface implementation' is not available in C# 7.0. Please use language version 8.0 or greater. // event System.Action E1 { add; } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "add").WithArguments("default interface implementation", "8.0").WithLocation(4, 30), // (4,33): error CS0073: An add or remove accessor must have a body // event System.Action E1 { add; } Diagnostic(ErrorCode.ERR_AddRemoveMustHaveBody, ";").WithLocation(4, 33), // (5,30): error CS8652: The feature 'default interface implementation' is not available in C# 7.0. Please use language version 8.0 or greater. // event System.Action E2 { remove; } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "remove").WithArguments("default interface implementation", "8.0").WithLocation(5, 30), // (5,36): error CS0073: An add or remove accessor must have a body // event System.Action E2 { remove; } Diagnostic(ErrorCode.ERR_AddRemoveMustHaveBody, ";").WithLocation(5, 36), // (6,30): error CS8652: The feature 'default interface implementation' is not available in C# 7.0. Please use language version 8.0 or greater. // event System.Action E3 { add; remove; } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "add").WithArguments("default interface implementation", "8.0").WithLocation(6, 30), // (6,33): error CS0073: An add or remove accessor must have a body // event System.Action E3 { add; remove; } Diagnostic(ErrorCode.ERR_AddRemoveMustHaveBody, ";").WithLocation(6, 33), // (6,35): error CS8652: The feature 'default interface implementation' is not available in C# 7.0. Please use language version 8.0 or greater. // event System.Action E3 { add; remove; } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "remove").WithArguments("default interface implementation", "8.0").WithLocation(6, 35), // (6,41): error CS0073: An add or remove accessor must have a body // event System.Action E3 { add; remove; } Diagnostic(ErrorCode.ERR_AddRemoveMustHaveBody, ";").WithLocation(6, 41), // (4,25): error CS0065: 'I.E1': event property must have both add and remove accessors // event System.Action E1 { add; } Diagnostic(ErrorCode.ERR_EventNeedsBothAccessors, "E1").WithArguments("I.E1").WithLocation(4, 25), // (5,25): error CS0065: 'I.E2': event property must have both add and remove accessors // event System.Action E2 { remove; } Diagnostic(ErrorCode.ERR_EventNeedsBothAccessors, "E2").WithArguments("I.E2").WithLocation(5, 25)); } [Fact] public void CS0070ERR_BadEventUsage() { var text = @" public delegate void EventHandler(); public class A { public event EventHandler Click; public static void OnClick() { EventHandler eh; A a = new A(); eh = a.Click; } public static void Main() { } } public class B { public int mf () { EventHandler eh = new EventHandler(A.OnClick); A a = new A(); eh = a.Click; // CS0070 // try the following line instead // a.Click += eh; return 1; } }"; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_BadEventUsage, Line = 26, Column = 14 } }); } [Fact] public void CS0079ERR_BadEventUsageNoField() { var text = @" public delegate void MyEventHandler(); public class Class1 { private MyEventHandler _e; public event MyEventHandler Pow { add { _e += value; } remove { _e -= value; } } public void Handler() { } public void Fire() { if (_e != null) { Pow(); // CS0079 // try the following line instead // _e(); } } public static void Main() { Class1 p = new Class1(); p.Pow += new MyEventHandler(p.Handler); p._e(); p.Pow += new MyEventHandler(p.Handler); p._e(); p._e -= new MyEventHandler(p.Handler); if (p._e != null) { p._e(); } p.Pow -= new MyEventHandler(p.Handler); if (p._e != null) { p._e(); } } }"; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_BadEventUsageNoField, Line = 28, Column = 13 } }); } [WorkItem(538213, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538213")] [Fact] public void CS0103ERR_NameNotInContext() { var text = @" class C { static void M() { IO.File.Exists(""test""); } } "; CreateCompilation(text).VerifyDiagnostics( Diagnostic(ErrorCode.ERR_NameNotInContext, "IO").WithArguments("IO").WithLocation(6, 9)); } [WorkItem(542574, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542574")] [Fact] public void CS0103ERR_NameNotInContextLambdaExtension() { var text = @"using System.Linq; class Test { static void Main() { int[] sourceA = { 1, 2, 3, 4, 5 }; int[] sourceB = { 3, 4, 5, 6, 7 }; var query = sourceA.Join(sourceB, a => b, b => 5, (a, b) => a + b); } }"; CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics( Diagnostic(ErrorCode.ERR_NameNotInContext, "b").WithArguments("b").WithLocation(9, 48)); } [Fact()] public void CS0103ERR_NameNotInContext_foreach() { var text = @"class C { static void Main() { foreach (var y in new[] {new {y = y }}){ } } } "; CreateCompilation(text).VerifyDiagnostics( Diagnostic(ErrorCode.ERR_NameNotInContext, "y").WithArguments("y").WithLocation(5, 43)); } [WorkItem(528780, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528780")] [Fact] public void CS0103ERR_NameNotInContext_namedAndOptional() { var text = @"using System; class NamedExample { static void Main(string[] args) { } static int CalculateBMI(int weight, int height = weight) { return (weight * 703) / (height * height); } } "; CreateCompilation(text).VerifyDiagnostics( // (7,54): error CS0103: The name 'weight' does not exist in the current context // static int CalculateBMI(int weight, int height = weight) Diagnostic(ErrorCode.ERR_NameNotInContext, "weight").WithArguments("weight").WithLocation(7, 54), // (1,1): hidden CS8019: Unnecessary using directive. // using System; Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using System;").WithLocation(1, 1) ); } [Fact] public void CS0118ERR_BadSKknown() { CreateCompilation( @"public class TestType {} public class MyClass { public static int Main() { TestType myTest = new TestType(); bool b = myTest is myTest; return 1; } }", parseOptions: TestOptions.Regular6) .VerifyDiagnostics( // (7,22): error CS0118: 'myTest' is a 'variable' but is used like a 'type' Diagnostic(ErrorCode.ERR_BadSKknown, "myTest").WithArguments("myTest", "variable", "type")); } [Fact] public void CS0118ERR_BadSKknown_02() { CreateCompilation(@" using System; public class P { public static void Main(string[] args) { #pragma warning disable 219 Action<args> a = null; Action<a> b = null; } }") .VerifyDiagnostics( // (6,16): error CS0118: 'args' is a variable but is used like a type // Action<args> a = null; Diagnostic(ErrorCode.ERR_BadSKknown, "args").WithArguments("args", "variable", "type").WithLocation(6, 16), // (7,16): error CS0118: 'a' is a variable but is used like a type // Action<a> b = null; Diagnostic(ErrorCode.ERR_BadSKknown, "a").WithArguments("a", "variable", "type").WithLocation(7, 16)); } [Fact] public void CS0118ERR_BadSKknown_CheckedUnchecked() { string source = @" using System; class Program { static void Main() { var z = 1; (Console).WriteLine(); // error (System).Console.WriteLine(); // error checked(Console).WriteLine(); // error checked(System).Console.WriteLine(); // error checked(z).ToString(); // ok checked(typeof(Console)).ToString(); // ok checked(Console.WriteLine)(); // ok checked(z) = 1; // ok } } "; CreateCompilation(source).VerifyDiagnostics( // (10,4): error CS0119: 'System.Console' is a type, which is not valid in the given context Diagnostic(ErrorCode.ERR_BadSKunknown, "Console").WithArguments("System.Console", "type"), // (11,10): error CS0118: 'System' is a namespace but is used like a variable Diagnostic(ErrorCode.ERR_BadSKknown, "System").WithArguments("System", "namespace", "variable"), // (12,17): error CS0119: 'System.Console' is a type, which is not valid in the given context Diagnostic(ErrorCode.ERR_BadSKunknown, "Console").WithArguments("System.Console", "type"), // (13,17): error CS0118: 'System' is a namespace but is used like a variable Diagnostic(ErrorCode.ERR_BadSKknown, "System").WithArguments("System", "namespace", "variable")); } [WorkItem(542773, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542773")] [Fact] public void CS0119ERR_BadSKunknown01_switch() { CreateCompilation( @"class A { public static void Main() { } void goo(color color1) { switch (color) { default: break; } } } enum color { blue, green } ") .VerifyDiagnostics(Diagnostic(ErrorCode.ERR_BadSKunknown, "color").WithArguments("color", "type")); } [Fact, WorkItem(538214, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538214"), WorkItem(528703, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528703")] public void CS0119ERR_BadSKunknown01() { var source = @"class Test { public static void M() { int x = 0; x = (global::System.Int32) + x; } }"; CreateCompilation(source).VerifyDiagnostics( // (6,14): error CS0119: 'int' is a type, which is not valid in the given context // x = (global::System.Int32) + x; Diagnostic(ErrorCode.ERR_BadSKunknown, "global::System.Int32").WithArguments("int", "type"), // (6,14): error CS0119: 'int' is a type, which is not valid in the given context // x = (global::System.Int32) + x; Diagnostic(ErrorCode.ERR_BadSKunknown, "global::System.Int32").WithArguments("int", "type")); } [Fact] public void CS0119ERR_BadSKunknown02() { var source = @"class A { internal static object F; internal static void M() { } } class B<T, U> where T : A { static void M(T t) { U.ReferenceEquals(T.F, null); T.M(); } }"; CreateCompilation(source).VerifyDiagnostics( // (10,27): error CS0119: 'T' is a type parameter, which is not valid in the given context // U.ReferenceEquals(T.F, null); Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter"), // (10,9): error CS0119: 'U' is a type parameter, which is not valid in the given context // U.ReferenceEquals(T.F, null); Diagnostic(ErrorCode.ERR_BadSKunknown, "U").WithArguments("U", "type parameter"), // (11,9): error CS0119: 'T' is a type parameter, which is not valid in the given context // T.M(); Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter"), // (3,28): warning CS0649: Field 'A.F' is never assigned to, and will always have its default value null // internal static object F; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "F").WithArguments("A.F", "null") ); } [WorkItem(541203, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541203")] [Fact] public void CS0119ERR_BadSKunknown_InThrowStmt() { CreateCompilation( @"class Test { public static void M() { throw System.Exception; } }") .VerifyDiagnostics( Diagnostic(ErrorCode.ERR_BadSKunknown, "System.Exception").WithArguments("System.Exception", "type")); } [Fact] public void CS0110ERR_CircConstValue01() { var source = @"namespace x { public class C { const int x = 1; const int a = x + b; const int b = x + c; const int c = x + d; const int d = x + e; const int e = x + a; } }"; CreateCompilation(source).VerifyDiagnostics( // (7,19): error CS0110: The evaluation of the constant value for 'x.C.a' involves a circular definition // const int a = x + b; Diagnostic(ErrorCode.ERR_CircConstValue, "a").WithArguments("x.C.a").WithLocation(7, 19)); } [Fact] public void CS0110ERR_CircConstValue02() { var source = @"enum E { A = B, B = A } enum F { X, Y = Y } "; CreateCompilation(source).VerifyDiagnostics( // (1,10): error CS0110: The evaluation of the constant value for 'E.A' involves a circular definition // enum E { A = B, B = A } Diagnostic(ErrorCode.ERR_CircConstValue, "A").WithArguments("E.A").WithLocation(1, 10), // (2,13): error CS0110: The evaluation of the constant value for 'F.Y' involves a circular definition // enum F { X, Y = Y } Diagnostic(ErrorCode.ERR_CircConstValue, "Y").WithArguments("F.Y").WithLocation(2, 13)); } [Fact] public void CS0110ERR_CircConstValue03() { var source = @"enum E { A, B = A } // no error enum F { W, X = Z, Y, Z } "; CreateCompilation(source).VerifyDiagnostics( // (2,13): error CS0110: The evaluation of the constant value for 'F.X' involves a circular definition // enum F { W, X = Z, Y, Z } Diagnostic(ErrorCode.ERR_CircConstValue, "X").WithArguments("F.X").WithLocation(2, 13)); } [Fact] public void CS0110ERR_CircConstValue04() { var source = @"enum E { A = B, B } "; CreateCompilation(source).VerifyDiagnostics( // (1,10): error CS0110: The evaluation of the constant value for 'E.A' involves a circular definition // enum E { A = B, B } Diagnostic(ErrorCode.ERR_CircConstValue, "A").WithArguments("E.A").WithLocation(1, 10)); } [Fact] public void CS0110ERR_CircConstValue05() { var source = @"enum E { A = C, B = C, C } "; CreateCompilation(source).VerifyDiagnostics( // (1,17): error CS0110: The evaluation of the constant value for 'E.B' involves a circular definition // enum E { A = C, B = C, C } Diagnostic(ErrorCode.ERR_CircConstValue, "B").WithArguments("E.B").WithLocation(1, 17)); } [Fact] public void CS0110ERR_CircConstValue06() { var source = @"class C { private const int F = (int)E.B; enum E { A = F, B } } "; CreateCompilation(source).VerifyDiagnostics( // (3,23): error CS0110: The evaluation of the constant value for 'C.F' involves a circular definition // private const int F = (int)E.B; Diagnostic(ErrorCode.ERR_CircConstValue, "F").WithArguments("C.F").WithLocation(3, 23)); } [Fact] public void CS0110ERR_CircConstValue07() { // Should report errors from other subexpressions // in addition to circular reference. var source = @"class C { const int F = (long)(F + F + G); } "; CreateCompilation(source).VerifyDiagnostics( // (3,34): error CS0103: The name 'G' does not exist in the current context // const int F = (long)(F + F + G); Diagnostic(ErrorCode.ERR_NameNotInContext, "G").WithArguments("G").WithLocation(3, 34), // (3,15): error CS0110: The evaluation of the constant value for 'C.F' involves a circular definition // const int F = (long)(F + F + G); Diagnostic(ErrorCode.ERR_CircConstValue, "F").WithArguments("C.F").WithLocation(3, 15)); } [Fact] public void CS0110ERR_CircConstValue08() { // Decimal constants are special (since they're not runtime constants). var source = @"class C { const decimal D = D; } "; CreateCompilation(source).VerifyDiagnostics( // (3,19): error CS0110: The evaluation of the constant value for 'C.D' involves a circular definition // const decimal D = D; Diagnostic(ErrorCode.ERR_CircConstValue, "D").WithArguments("C.D").WithLocation(3, 19)); } [Fact] public void CS0116ERR_NamespaceUnexpected_1() { var test = @" int x; "; CreateCompilation(test, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9).VerifyDiagnostics( // (2,5): warning CS0168: The variable 'x' is declared but never used // int x; Diagnostic(ErrorCode.WRN_UnreferencedVar, "x").WithArguments("x").WithLocation(2, 5) ); } [Fact] public void CS0116ERR_NamespaceUnexpected_2() { var test = @" namespace x { using System; void Method(string str) // CS0116 { Console.WriteLine(str); } } int AIProp { get ; set ; } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(test, new ErrorDescription { Code = (int)ErrorCode.ERR_NamespaceUnexpected, Line = 5, Column = 10 }, new ErrorDescription { Code = (int)ErrorCode.ERR_NamespaceUnexpected, Line = 10, Column = 5 }); } [Fact] public void CS0116ERR_NamespaceUnexpected_3() { var test = @" namespace ns1 { goto Labl; // Invalid const int x = 1; Lab1: const int y = 2; } "; // TODO (tomat): EOFUnexpected shouldn't be reported if we enable parsing global statements in namespaces DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(test, // (4,5): error CS1022: Type or namespace definition, or end-of-file expected // (4,10): error CS0116: A namespace does not directly contain members such as fields or methods // (4,14): error CS1022: Type or namespace definition, or end-of-file expected // (6,5): error CS0116: A namespace does not directly contain members such as fields or methods // (6,9): error CS1022: Type or namespace definition, or end-of-file expected // (5,15): error CS0116: A namespace does not directly contain members such as fields or methods // (7,15): error CS0116: A namespace does not directly contain members such as fields or methods new ErrorDescription { Code = (int)ErrorCode.ERR_EOFExpected, Line = 4, Column = 5 }, new ErrorDescription { Code = (int)ErrorCode.ERR_NamespaceUnexpected, Line = 4, Column = 10 }, new ErrorDescription { Code = (int)ErrorCode.ERR_EOFExpected, Line = 4, Column = 14 }, new ErrorDescription { Code = (int)ErrorCode.ERR_NamespaceUnexpected, Line = 6, Column = 5 }, new ErrorDescription { Code = (int)ErrorCode.ERR_EOFExpected, Line = 6, Column = 9 }, new ErrorDescription { Code = (int)ErrorCode.ERR_NamespaceUnexpected, Line = 5, Column = 15 }, new ErrorDescription { Code = (int)ErrorCode.ERR_NamespaceUnexpected, Line = 7, Column = 15 }); } [WorkItem(540091, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540091")] [Fact] public void CS0116ERR_NamespaceUnexpected_4() { var test = @" delegate int D(); D d = null; "; CreateCompilation(test, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9).VerifyDiagnostics( // (3,1): error CS8803: Top-level statements must precede namespace and type declarations. // D d = null; Diagnostic(ErrorCode.ERR_TopLevelStatementAfterNamespaceOrType, "D d = null;").WithLocation(3, 1), // (3,3): warning CS0219: The variable 'd' is assigned but its value is never used // D d = null; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "d").WithArguments("d").WithLocation(3, 3) ); } [WorkItem(540091, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540091")] [Fact] public void CS0116ERR_NamespaceUnexpected_5() { var test = @" delegate int D(); D d = {;} "; // In this case, CS0116 is suppressed because of the syntax errors CreateCompilation(test, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9).VerifyDiagnostics( // (3,1): error CS8803: Top-level statements must precede namespace and type declarations. // D d = {;} Diagnostic(ErrorCode.ERR_TopLevelStatementAfterNamespaceOrType, "D d = {;").WithLocation(3, 1), // (3,8): error CS1513: } expected Diagnostic(ErrorCode.ERR_RbraceExpected, ";"), // (3,9): error CS1022: Type or namespace definition, or end-of-file expected Diagnostic(ErrorCode.ERR_EOFExpected, "}"), // (3,7): error CS0622: Can only use array initializer expressions to assign to array types. Try using a new expression instead. Diagnostic(ErrorCode.ERR_ArrayInitToNonArrayType, "{")); } [WorkItem(539129, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539129")] [Fact] public void CS0117ERR_NoSuchMember() { CreateCompilation( @"enum E { } class C { static void M() { C.F(E.A); C.P = C.Q; } }") .VerifyDiagnostics( Diagnostic(ErrorCode.ERR_NoSuchMember, "F").WithArguments("C", "F"), Diagnostic(ErrorCode.ERR_NoSuchMember, "A").WithArguments("E", "A"), Diagnostic(ErrorCode.ERR_NoSuchMember, "P").WithArguments("C", "P"), Diagnostic(ErrorCode.ERR_NoSuchMember, "Q").WithArguments("C", "Q")); } [Fact] public void CS0120ERR_ObjectRequired01() { CreateCompilation( @"class C { object field; object Property { get; set; } void Method() { } static void M() { field = Property; C.field = C.Property; Method(); C.Method(); } } ") .VerifyDiagnostics( // (8,9): error CS0120: An object reference is required for the non-static field, method, or property 'C.field' // field = Property; Diagnostic(ErrorCode.ERR_ObjectRequired, "field").WithArguments("C.field").WithLocation(8, 9), // (8,17): error CS0120: An object reference is required for the non-static field, method, or property 'C.Property' // field = Property; Diagnostic(ErrorCode.ERR_ObjectRequired, "Property").WithArguments("C.Property").WithLocation(8, 17), // (9,9): error CS0120: An object reference is required for the non-static field, method, or property 'C.field' // C.field = C.Property; Diagnostic(ErrorCode.ERR_ObjectRequired, "C.field").WithArguments("C.field").WithLocation(9, 9), // (9,19): error CS0120: An object reference is required for the non-static field, method, or property 'C.Property' // C.field = C.Property; Diagnostic(ErrorCode.ERR_ObjectRequired, "C.Property").WithArguments("C.Property").WithLocation(9, 19), // (10,9): error CS0120: An object reference is required for the non-static field, method, or property 'C.Method()' // Method(); Diagnostic(ErrorCode.ERR_ObjectRequired, "Method").WithArguments("C.Method()").WithLocation(10, 9), // (11,9): error CS0120: An object reference is required for the non-static field, method, or property 'C.Method()' // C.Method(); Diagnostic(ErrorCode.ERR_ObjectRequired, "C.Method").WithArguments("C.Method()").WithLocation(11, 9)); } [Fact] public void CS0120ERR_ObjectRequired02() { CreateCompilation( @"using System; class Program { private readonly int v = 5; delegate int del(int i); static void Main(string[] args) { del myDelegate = (int x) => x * v; Console.Write(string.Concat(myDelegate(7), ""he"")); } }") .VerifyDiagnostics( // (9,41): error CS0120: An object reference is required for the non-static field, method, or property 'C.field' Diagnostic(ErrorCode.ERR_ObjectRequired, "v").WithArguments("Program.v")); } [Fact] public void CS0120ERR_ObjectRequired03() { var source = @"delegate int boo(); interface I { int bar(); } public struct abc : I { public int bar() { System.Console.WriteLine(""bar""); return 0x01; } } class C { static void Main(string[] args) { abc p = new abc(); boo goo = null; goo += new boo(I.bar); goo(); } }"; CreateCompilation(source, parseOptions: TestOptions.Regular7).VerifyDiagnostics( // (16,24): error CS0120: An object reference is required for the non-static field, method, or property 'I.bar()' // goo += new boo(I.bar); Diagnostic(ErrorCode.ERR_ObjectRequired, "I.bar").WithArguments("I.bar()"), // (14,13): warning CS0219: The variable 'p' is assigned but its value is never used // abc p = new abc(); Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "p").WithArguments("p") ); CreateCompilation(source, parseOptions: TestOptions.Regular).VerifyDiagnostics( // (16,24): error CS0120: An object reference is required for the non-static field, method, or property 'I.bar()' // goo += new boo(I.bar); Diagnostic(ErrorCode.ERR_ObjectRequired, "I.bar").WithArguments("I.bar()").WithLocation(16, 24), // (14,13): warning CS0219: The variable 'p' is assigned but its value is never used // abc p = new abc(); Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "p").WithArguments("p").WithLocation(14, 13) ); } [WorkItem(543950, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543950")] [Fact] public void CS0120ERR_ObjectRequired04() { CreateCompilation( @"using System; class Program { static void Main(string[] args) { var f = new Func<string>(() => ToString()); var g = new Func<int>(() => GetHashCode()); } }") .VerifyDiagnostics( // (7,40): error CS0120: An object reference is required for the non-static field, method, or property 'object.ToString()' // var f = new Func<string>(() => ToString()); Diagnostic(ErrorCode.ERR_ObjectRequired, "ToString").WithArguments("object.ToString()"), // (8,37): error CS0120: An object reference is required for the non-static field, method, or property 'object.GetHashCode()' // var g = new Func<int>(() => GetHashCode()); Diagnostic(ErrorCode.ERR_ObjectRequired, "GetHashCode").WithArguments("object.GetHashCode()") ); } [Fact] public void CS0120ERR_ObjectRequired_ConstructorInitializer() { CreateCompilation( @"class B { public B(params int[] p) { } } class C : B { int instanceField; static int staticField; int InstanceProperty { get; set; } static int StaticProperty { get; set; } int InstanceMethod() { return 0; } static int StaticMethod() { return 0; } C(int param) : base( param, instanceField, //CS0120 staticField, InstanceProperty, //CS0120 StaticProperty, InstanceMethod(), //CS0120 StaticMethod(), this.instanceField, //CS0027 C.staticField, this.InstanceProperty, //CS0027 C.StaticProperty, this.InstanceMethod(), //CS0027 C.StaticMethod()) { } } ") .VerifyDiagnostics( // (19,9): error CS0120: An object reference is required for the non-static field, method, or property 'C.instanceField' // instanceField, //CS0120 Diagnostic(ErrorCode.ERR_ObjectRequired, "instanceField").WithArguments("C.instanceField").WithLocation(19, 9), // (21,9): error CS0120: An object reference is required for the non-static field, method, or property 'C.InstanceProperty' // InstanceProperty, //CS0120 Diagnostic(ErrorCode.ERR_ObjectRequired, "InstanceProperty").WithArguments("C.InstanceProperty").WithLocation(21, 9), // (23,9): error CS0120: An object reference is required for the non-static field, method, or property 'C.InstanceMethod()' // InstanceMethod(), //CS0120 Diagnostic(ErrorCode.ERR_ObjectRequired, "InstanceMethod").WithArguments("C.InstanceMethod()").WithLocation(23, 9), // (25,9): error CS0027: Keyword 'this' is not available in the current context // this.instanceField, //CS0027 Diagnostic(ErrorCode.ERR_ThisInBadContext, "this").WithLocation(25, 9), // (27,9): error CS0027: Keyword 'this' is not available in the current context // this.InstanceProperty, //CS0027 Diagnostic(ErrorCode.ERR_ThisInBadContext, "this").WithLocation(27, 9), // (29,9): error CS0027: Keyword 'this' is not available in the current context // this.InstanceMethod(), //CS0027 Diagnostic(ErrorCode.ERR_ThisInBadContext, "this").WithLocation(29, 9), // (8,9): warning CS0649: Field 'C.instanceField' is never assigned to, and will always have its default value 0 // int instanceField; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "instanceField").WithArguments("C.instanceField", "0").WithLocation(8, 9), // (9,16): warning CS0649: Field 'C.staticField' is never assigned to, and will always have its default value 0 // static int staticField; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "staticField").WithArguments("C.staticField", "0").WithLocation(9, 16)); } [Fact] public void CS0120ERR_ObjectRequired_StaticConstructor() { CreateCompilation( @"class C { object field; object Property { get; set; } void Method() { } static C() { field = Property; C.field = C.Property; Method(); C.Method(); } } ") .VerifyDiagnostics( // (8,9): error CS0120: An object reference is required for the non-static field, method, or property 'C.field' // field = Property; Diagnostic(ErrorCode.ERR_ObjectRequired, "field").WithArguments("C.field").WithLocation(8, 9), // (8,17): error CS0120: An object reference is required for the non-static field, method, or property 'C.Property' // field = Property; Diagnostic(ErrorCode.ERR_ObjectRequired, "Property").WithArguments("C.Property").WithLocation(8, 17), // (9,9): error CS0120: An object reference is required for the non-static field, method, or property 'C.field' // C.field = C.Property; Diagnostic(ErrorCode.ERR_ObjectRequired, "C.field").WithArguments("C.field").WithLocation(9, 9), // (9,19): error CS0120: An object reference is required for the non-static field, method, or property 'C.Property' // C.field = C.Property; Diagnostic(ErrorCode.ERR_ObjectRequired, "C.Property").WithArguments("C.Property").WithLocation(9, 19), // (10,9): error CS0120: An object reference is required for the non-static field, method, or property 'C.Method()' // Method(); Diagnostic(ErrorCode.ERR_ObjectRequired, "Method").WithArguments("C.Method()").WithLocation(10, 9), // (11,9): error CS0120: An object reference is required for the non-static field, method, or property 'C.Method()' // C.Method(); Diagnostic(ErrorCode.ERR_ObjectRequired, "C.Method").WithArguments("C.Method()").WithLocation(11, 9)); } [Fact] public void CS0120ERR_ObjectRequired_NestedClass() { CreateCompilation( @" class C { object field; object Property { get; set; } void Method() { } class D { object field2; object Property2 { get; set; } public void Goo() { object f = field; object p = Property; Method(); } public static void Bar() { object f1 = field; object p1 = Property; Method(); object f2 = field2; object p2 = Property2; Goo(); } } class E : C { public void Goo() { object f3 = field; object p3 = Property; Method(); } } }") .VerifyDiagnostics( // (15,24): error CS0120: An object reference is required for the non-static field, method, or property 'C.field' // object f = field; Diagnostic(ErrorCode.ERR_ObjectRequired, "field").WithArguments("C.field"), // (16,24): error CS0120: An object reference is required for the non-static field, method, or property 'C.Property' // object p = Property; Diagnostic(ErrorCode.ERR_ObjectRequired, "Property").WithArguments("C.Property"), // (17,13): error CS0120: An object reference is required for the non-static field, method, or property 'C.Method()' // Method(); Diagnostic(ErrorCode.ERR_ObjectRequired, "Method").WithArguments("C.Method()"), // (22,25): error CS0120: An object reference is required for the non-static field, method, or property 'C.field' // object f1 = field; Diagnostic(ErrorCode.ERR_ObjectRequired, "field").WithArguments("C.field"), // (23,25): error CS0120: An object reference is required for the non-static field, method, or property 'C.Property' // object p1 = Property; Diagnostic(ErrorCode.ERR_ObjectRequired, "Property").WithArguments("C.Property"), // (24,13): error CS0120: An object reference is required for the non-static field, method, or property 'C.Method()' // Method(); Diagnostic(ErrorCode.ERR_ObjectRequired, "Method").WithArguments("C.Method()"), // (26,25): error CS0120: An object reference is required for the non-static field, method, or property 'C.D.field2' // object f2 = field2; Diagnostic(ErrorCode.ERR_ObjectRequired, "field2").WithArguments("C.D.field2"), // (27,25): error CS0120: An object reference is required for the non-static field, method, or property 'C.D.Property2' // object p2 = Property2; Diagnostic(ErrorCode.ERR_ObjectRequired, "Property2").WithArguments("C.D.Property2"), // (28,13): error CS0120: An object reference is required for the non-static field, method, or property 'C.D.Goo()' // Goo(); Diagnostic(ErrorCode.ERR_ObjectRequired, "Goo").WithArguments("C.D.Goo()"), // (4,12): warning CS0649: Field 'C.field' is never assigned to, and will always have its default value null // object field; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "field").WithArguments("C.field", "null"), // (10,16): warning CS0649: Field 'C.D.field2' is never assigned to, and will always have its default value null // object field2; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "field2").WithArguments("C.D.field2", "null")); } [Fact, WorkItem(541505, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541505")] public void CS0120ERR_ObjectRequired_Attribute() { var text = @" using System.ComponentModel; enum ProtectionLevel { Privacy = 0 } class F { [DefaultValue(Prop.Privacy)] // CS0120 ProtectionLevel Prop { get { return 0; } } } "; CreateCompilation(text).VerifyDiagnostics( // (9,17): error CS0120: An object reference is required for the non-static field, method, or property 'F.Prop' // [DefaultValue(Prop.Privacy)] // CS0120 Diagnostic(ErrorCode.ERR_ObjectRequired, "Prop").WithArguments("F.Prop"), // (9,17): error CS0176: Member 'ProtectionLevel.Privacy' cannot be accessed with an instance reference; qualify it with a type name instead // [DefaultValue(Prop.Privacy)] // CS0120 Diagnostic(ErrorCode.ERR_ObjectProhibited, "Prop.Privacy").WithArguments("ProtectionLevel.Privacy") // Extra In Roslyn ); } [Fact] public void CS0121ERR_AmbigCall() { var text = @" public class C { void f(int i, double d) { } void f(double d, int i) { } public static void Main() { new C().f(1, 1); // CS0121 } }"; CreateCompilation(text).VerifyDiagnostics( // (9,9): error CS0121: The call is ambiguous between the following methods or properties: 'C.f(int, double)' and 'C.f(double, int)' // new C().f(1, 1); // CS0121 Diagnostic(ErrorCode.ERR_AmbigCall, "f").WithArguments("C.f(int, double)", "C.f(double, int)") ); } [WorkItem(539817, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539817")] [Fact] public void CS0122ERR_BadAccess() { var text = @" class Base { private class P { int X; } } class Test : Base { void M() { object o = (P p) => 0; int x = P.X; int y = (P)null; } } "; CreateCompilation(text).VerifyDiagnostics( // (11,21): error CS0122: 'Base.P' is inaccessible due to its protection level // object o = (P p) => 0; Diagnostic(ErrorCode.ERR_BadAccess, "P").WithArguments("Base.P"), // (11,20): error CS1660: Cannot convert lambda expression to type 'object' because it is not a delegate type // object o = (P p) => 0; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "(P p) => 0").WithArguments("lambda expression", "object"), // (12,17): error CS0122: 'Base.P' is inaccessible due to its protection level // int x = P.X; Diagnostic(ErrorCode.ERR_BadAccess, "P").WithArguments("Base.P"), // (13,18): error CS0122: 'Base.P' is inaccessible due to its protection level // int y = (P)null; Diagnostic(ErrorCode.ERR_BadAccess, "P").WithArguments("Base.P"), // (4,27): warning CS0169: The field 'Base.P.X' is never used // private class P { int X; } Diagnostic(ErrorCode.WRN_UnreferencedField, "X").WithArguments("Base.P.X")); } [WorkItem(537683, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537683")] [Fact] public void CS0122ERR_BadAccess02() { var text = @"public class Outer { private class base1 { } } public class MyClass : Outer.base1 { } "; var comp = CreateCompilation(text); var type1 = comp.SourceModule.GlobalNamespace.GetMembers("MyClass").Single() as NamedTypeSymbol; var b = type1.BaseType(); var errs = comp.GetDiagnostics(); Assert.Equal(1, errs.Count()); Assert.Equal(122, errs.First().Code); } [WorkItem(539628, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539628")] [Fact] public void CS0122ERR_BadAccess03() { var text = @" class C1 { private C1() { } } class C2 { protected C2() { } private C2(short x) {} } class C3 : C2 { C3() : base(3) {} // CS0122 } class Test { public static int Main() { C1 c1 = new C1(); // CS0122 C2 c2 = new C2(); // CS0122 return 1; } } "; CreateCompilation(text).VerifyDiagnostics( // (14,12): error CS0122: 'C2.C2(short)' is inaccessible due to its protection level Diagnostic(ErrorCode.ERR_BadAccess, "base").WithArguments("C2.C2(short)"), // (21,21): error CS0122: 'C1.C1()' is inaccessible due to its protection level Diagnostic(ErrorCode.ERR_BadAccess, "C1").WithArguments("C1.C1()"), // (22,21): error CS0122: 'C2.C2()' is inaccessible due to its protection level Diagnostic(ErrorCode.ERR_BadAccess, "C2").WithArguments("C2.C2()")); } [WorkItem(539628, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539628")] [WorkItem(540336, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540336")] [Fact] public void CS0122ERR_BadAccess04() { var text = @" class A { protected class ProtectedClass { } public class B : I<ProtectedClass> { } } interface I<T> { } class Error { static void Goo<T>(I<T> i) { } static void Main() { Goo(new A.B()); } } "; var tree = Parse(text); var compilation = CreateCompilation(tree); var model = compilation.GetSemanticModel(tree); var compilationUnit = tree.GetCompilationUnitRoot(); var classError = (TypeDeclarationSyntax)compilationUnit.Members[2]; var mainMethod = (MethodDeclarationSyntax)classError.Members[1]; var callStmt = (ExpressionStatementSyntax)mainMethod.Body.Statements[0]; var callExpr = callStmt.Expression; var callPosition = callExpr.SpanStart; var boundCall = model.GetSpeculativeSymbolInfo(callPosition, callExpr, SpeculativeBindingOption.BindAsExpression); Assert.Null(boundCall.Symbol); Assert.Equal(1, boundCall.CandidateSymbols.Length); Assert.Equal(CandidateReason.OverloadResolutionFailure, boundCall.CandidateReason); var constructedMethodSymbol = (IMethodSymbol)(boundCall.CandidateSymbols[0]); Assert.Equal("void Error.Goo<A.ProtectedClass>(I<A.ProtectedClass> i)", constructedMethodSymbol.ToTestDisplayString()); var typeArgSymbol = constructedMethodSymbol.TypeArguments.Single(); Assert.Equal("A.ProtectedClass", typeArgSymbol.ToTestDisplayString()); Assert.False(model.IsAccessible(callPosition, typeArgSymbol), "Protected inner class is inaccessible"); var paramTypeSymbol = constructedMethodSymbol.Parameters.Single().Type; Assert.Equal("I<A.ProtectedClass>", paramTypeSymbol.ToTestDisplayString()); Assert.False(model.IsAccessible(callPosition, typeArgSymbol), "Type should be inaccessible since type argument is inaccessible"); // The original test attempted to verify that "Error.Goo<A.ProtectedClass>" is an // inaccessible method when inside Error.Main. The C# specification nowhere gives // a special rule for constructed generic methods; the accessibility domain of // a method depends only on its declared accessibility and the declared accessibility // of its containing type. // // We should decide whether the answer to "is this method accessible in Main?" is // yes or no, and if no, change the implementation of IsAccessible accordingly. // // Assert.False(model.IsAccessible(callPosition, constructedMethodSymbol), "Method should be inaccessible since parameter type is inaccessible"); compilation.VerifyDiagnostics( // (16,9): error CS0122: 'Error.Goo<A.ProtectedClass>(I<A.ProtectedClass>)' is inaccessible due to its protection level Diagnostic(ErrorCode.ERR_BadAccess, "Goo").WithArguments("Error.Goo<A.ProtectedClass>(I<A.ProtectedClass>)")); } [WorkItem(539628, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539628")] [Fact] public void CS0122ERR_BadAccess05() { var text = @" class Base { private Base() { } } class Derived : Base { private Derived() : this(1) { } //fine: can see own private members private Derived(int x) : base() { } //CS0122: cannot see base private members } "; CreateCompilation(text).VerifyDiagnostics( // (10,30): error CS0122: 'Base.Base()' is inaccessible due to its protection level Diagnostic(ErrorCode.ERR_BadAccess, "base").WithArguments("Base.Base()")); } [WorkItem(539628, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539628")] [Fact] public void CS0122ERR_BadAccess06() { var text = @" class Base { private Base() { } //private, but a match public Base(int x) { } //public, but not a match } class Derived : Base { private Derived() { } //implicit constructor initializer } "; CreateCompilation(text).VerifyDiagnostics( // (10,13): error CS0122: 'Base.Base()' is inaccessible due to its protection level Diagnostic(ErrorCode.ERR_BadAccess, "Derived").WithArguments("Base.Base()")); } [Fact] public void CS0123ERR_MethDelegateMismatch() { var text = @" delegate void D(); delegate void D2(int i); public class C { public static void f(int i) { } public static void Main() { D d = new D(f); // CS0123 D2 d2 = new D2(f); // OK } }"; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_MethDelegateMismatch, Line = 11, Column = 15 } }); } [WorkItem(539909, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539909")] [Fact] public void CS0123ERR_MethDelegateMismatch_01() { var text = @" delegate void boo(short x); class C { static void far<T>(T x) { } static void Main(string[] args) { C p = new C(); boo goo = null; goo += far<int>;// Invalid goo += far<short>;// OK } }"; CreateCompilation(text).VerifyDiagnostics( // (10,16): error CS0123: No overload for 'C.far<int>(int)' matches delegate 'boo' Diagnostic(ErrorCode.ERR_MethDelegateMismatch, "far<int>").WithArguments("C.far<int>(int)", "boo")); } [WorkItem(539909, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539909")] [WorkItem(540053, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540053")] [Fact] public void CS0123ERR_MethDelegateMismatch_02() { var text = @" delegate void boo(short x); class C<T> { public static void far(T x) { } public static void par<U>(U x) { System.Console.WriteLine(""par""); } public static boo goo = null; } class D { static void Main(string[] args) { C<long> p = new C<long>(); C<long>.goo += C<long>.far; C<long>.goo += C<long>.par<byte>; C<long>.goo(byte.MaxValue); C<long>.goo(long.MaxValue); C<short>.goo(long.MaxValue); } }"; CreateCompilation(text).VerifyDiagnostics( // (15,24): error CS0123: No overload for 'C<long>.far(long)' matches delegate 'boo' Diagnostic(ErrorCode.ERR_MethDelegateMismatch, "C<long>.far").WithArguments("C<long>.far(long)", "boo").WithLocation(15, 24), // (16,32): error CS0123: No overload for 'par' matches delegate 'boo' // C<long>.goo += C<long>.par<byte>; Diagnostic(ErrorCode.ERR_MethDelegateMismatch, "par<byte>").WithArguments("par", "boo").WithLocation(16, 32), // (18,21): error CS1503: Argument 1: cannot convert from 'long' to 'short' Diagnostic(ErrorCode.ERR_BadArgType, "long.MaxValue").WithArguments("1", "long", "short").WithLocation(18, 21), // (19,22): error CS1503: Argument 1: cannot convert from 'long' to 'short' Diagnostic(ErrorCode.ERR_BadArgType, "long.MaxValue").WithArguments("1", "long", "short").WithLocation(19, 22) ); } [Fact] public void CS0123ERR_MethDelegateMismatch_DelegateVariance() { var text = @" delegate TOut D<out TOut, in TIn>(TIn p); class A { } class B : A { } class C : B { } class Test { static void Main() { D<B, B> d; d = F1; //CS0407 d = F2; //CS0407 d = F3; //CS0123 d = F4; d = F5; d = F6; //CS0123 d = F7; d = F8; d = F9; //CS0123 } static A F1(A p) { return null; } static A F2(B p) { return null; } static A F3(C p) { return null; } static B F4(A p) { return null; } static B F5(B p) { return null; } static B F6(C p) { return null; } static C F7(A p) { return null; } static C F8(B p) { return null; } static C F9(C p) { return null; } }"; CreateCompilation(text).VerifyDiagnostics( // (13,13): error CS0407: 'A Test.F1(A)' has the wrong return type Diagnostic(ErrorCode.ERR_BadRetType, "F1").WithArguments("Test.F1(A)", "A"), // (14,13): error CS0407: 'A Test.F2(B)' has the wrong return type Diagnostic(ErrorCode.ERR_BadRetType, "F2").WithArguments("Test.F2(B)", "A"), // (15,13): error CS0123: No overload for 'F3' matches delegate 'D<B, B>' Diagnostic(ErrorCode.ERR_MethDelegateMismatch, "F3").WithArguments("F3", "D<B, B>"), // (18,13): error CS0123: No overload for 'F6' matches delegate 'D<B, B>' Diagnostic(ErrorCode.ERR_MethDelegateMismatch, "F6").WithArguments("F6", "D<B, B>"), // (21,13): error CS0123: No overload for 'F9' matches delegate 'D<B, B>' Diagnostic(ErrorCode.ERR_MethDelegateMismatch, "F9").WithArguments("F9", "D<B, B>")); } [Fact] public void CS0126ERR_RetObjectRequired() { var source = @"namespace N { class C { object F() { return; } X G() { return; } C P { get { return; } } Y Q { get { return; } } } } "; CreateCompilation(source).VerifyDiagnostics( // (6,9): error CS0246: The type or namespace name 'X' could not be found (are you missing a using directive or an assembly reference?) // X G() { return; } Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "X").WithArguments("X").WithLocation(6, 9), // (8,9): error CS0246: The type or namespace name 'Y' could not be found (are you missing a using directive or an assembly reference?) // Y Q { get { return; } } Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Y").WithArguments("Y").WithLocation(8, 9), // (5,22): error CS0126: An object of a type convertible to 'object' is required // object F() { return; } Diagnostic(ErrorCode.ERR_RetObjectRequired, "return").WithArguments("object").WithLocation(5, 22), // (6,17): error CS0126: An object of a type convertible to 'X' is required // X G() { return; } Diagnostic(ErrorCode.ERR_RetObjectRequired, "return").WithArguments("X").WithLocation(6, 17), // (7,21): error CS0126: An object of a type convertible to 'C' is required // C P { get { return; } } Diagnostic(ErrorCode.ERR_RetObjectRequired, "return").WithArguments("N.C").WithLocation(7, 21), // (8,21): error CS0126: An object of a type convertible to 'Y' is required // Y Q { get { return; } } Diagnostic(ErrorCode.ERR_RetObjectRequired, "return").WithArguments("Y").WithLocation(8, 21)); } [WorkItem(540115, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540115")] [Fact] public void CS0126ERR_RetObjectRequired_02() { var source = @"namespace Test { public delegate object D(); public class TestClass { public static int Test(D src) { src(); return 0; } } public class MainClass { public static int Main() { return TestClass.Test(delegate() { return; }); // The native compiler produces two errors for this code: // // CS0126: An object of a type convertible to 'object' is required // // CS1662: Cannot convert anonymous method to delegate type // 'Test.D' because some of the return types in the block are not implicitly // convertible to the delegate return type // // This is not great; the first error is right, but does not tell us anything about // the fact that overload resolution has failed on the first argument. The second // error is actually incorrect; it is not that 'some of the return types are incorrect', // it is that some of the returns do not return anything in the first place! There's // no 'type' to get wrong. // // I would like Roslyn to give two errors: // // CS1503: Argument 1: cannot convert from 'anonymous method' to 'Test.D' // CS0126: An object of a type convertible to 'object' is required // // Neal Gafter says: I'd like one error instead of two. There is an error inside the // body of the lambda. It is enough to report that specific error. This is consistent // with our design guideline to suppress errors higher in the tree when it is caused // by an error lower in the tree. } } } "; CreateCompilation(source).VerifyDiagnostics( // (18,48): error CS0126: An object of a type convertible to 'object' is required // return TestClass.Test(delegate() { return; }); Diagnostic(ErrorCode.ERR_RetObjectRequired, "return").WithArguments("object").WithLocation(18, 48)); } [Fact] public void CS0127ERR_RetNoObjectRequired() { var source = @"namespace MyNamespace { public class MyClass { public void F() { return 0; } // CS0127 public int P { get { return 0; } set { return 0; } // CS0127, set has an implicit void return type } } } "; CreateCompilation(source).VerifyDiagnostics( // (5,27): error CS0127: Since 'MyClass.F()' returns void, a return keyword must not be followed by an object expression // public void F() { return 0; } // CS0127 Diagnostic(ErrorCode.ERR_RetNoObjectRequired, "return").WithArguments("MyNamespace.MyClass.F()").WithLocation(5, 27), // (9,19): error CS0127: Since 'MyClass.P.set' returns void, a return keyword must not be followed by an object expression // set { return 0; } // CS0127, set has an implicit void return type Diagnostic(ErrorCode.ERR_RetNoObjectRequired, "return").WithArguments("MyNamespace.MyClass.P.set").WithLocation(9, 19)); } [Fact] public void CS0127ERR_RetNoObjectRequired_StaticConstructor() { string text = @" class C { static C() { return 1; } } "; CreateCompilation(text).VerifyDiagnostics( // (6,9): error CS0127: Since 'C.C()' returns void, a return keyword must not be followed by an object expression Diagnostic(ErrorCode.ERR_RetNoObjectRequired, "return").WithArguments("C.C()")); } [Fact] public void CS0128ERR_LocalDuplicate() { var text = @" namespace MyNamespace { public class MyClass { public static void Main() { char i = 'a'; int i = 2; // CS0128 if (i == 2) {} } } }"; CreateCompilation(text). VerifyDiagnostics( // (9,14): error CS0128: A local variable or function named 'i' is already defined in this scope // int i = 2; // CS0128 Diagnostic(ErrorCode.ERR_LocalDuplicate, "i").WithArguments("i").WithLocation(9, 14), // (9,14): warning CS0219: The variable 'i' is assigned but its value is never used // int i = 2; // CS0128 Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "i").WithArguments("i").WithLocation(9, 14) ); } [Fact] public void CS0131ERR_AssgLvalueExpected01() { CreateCompilation( @"class C { int i = 0; int P { get; set; } int this[int x] { get { return x; } set { } } void M() { ++P = 1; // CS0131 ++i = 1; // CS0131 ++this[0] = 1; //CS0131 } } ") .VerifyDiagnostics( // (7,9): error CS0131: The left-hand side of an assignment must be a variable, property or indexer Diagnostic(ErrorCode.ERR_AssgLvalueExpected, "++P"), // (8,9): error CS0131: The left-hand side of an assignment must be a variable, property or indexer Diagnostic(ErrorCode.ERR_AssgLvalueExpected, "++i"), // (10,9): error CS0131: The left-hand side of an assignment must be a variable, property or indexer Diagnostic(ErrorCode.ERR_AssgLvalueExpected, "++this[0]")); } [Fact] public void CS0131ERR_AssgLvalueExpected02() { var source = @"class C { const object NoObject = null; static void M() { const int i = 0; i += 1; 3 *= 1; (i + 1) -= 1; ""string"" = null; null = new object(); NoObject = ""string""; } } "; CreateCompilation(source).VerifyDiagnostics( // (7,9): error CS0131: The left-hand side of an assignment must be a variable, property or indexer // i += 1; Diagnostic(ErrorCode.ERR_AssgLvalueExpected, "i").WithLocation(7, 9), // (8,9): error CS0131: The left-hand side of an assignment must be a variable, property or indexer // 3 *= 1; Diagnostic(ErrorCode.ERR_AssgLvalueExpected, "3").WithLocation(8, 9), // (9,10): error CS0131: The left-hand side of an assignment must be a variable, property or indexer // (i + 1) -= 1; Diagnostic(ErrorCode.ERR_AssgLvalueExpected, "i + 1").WithLocation(9, 10), // (10,9): error CS0131: The left-hand side of an assignment must be a variable, property or indexer // "string" = null; Diagnostic(ErrorCode.ERR_AssgLvalueExpected, @"""string""").WithLocation(10, 9), // (11,9): error CS0131: The left-hand side of an assignment must be a variable, property or indexer // null = new object(); Diagnostic(ErrorCode.ERR_AssgLvalueExpected, "null").WithLocation(11, 9), // (12,9): error CS0131: The left-hand side of an assignment must be a variable, property or indexer // NoObject = "string"; Diagnostic(ErrorCode.ERR_AssgLvalueExpected, "NoObject").WithLocation(12, 9)); } /// <summary> /// Breaking change from Dev10. CS0131 is now reported for all value /// types, not just struct types. Specifically, CS0131 is now reported /// for type parameters constrained to "struct". (See also CS1612.) /// </summary> [WorkItem(528763, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528763")] [Fact] public void CS0131ERR_AssgLvalueExpected03() { var source = @"struct S { public object P { get; set; } public object this[object index] { get { return null; } set { } } } interface I { object P { get; set; } object this[object index] { get; set; } } class C { static void M<T>() where T : struct, I { default(S).P = null; default(T).P = null; // Dev10: no error default(S)[0] = null; default(T)[0] = null; // Dev10: no error } }"; CreateCompilation(source).VerifyDiagnostics( // (16,9): error CS0131: The left-hand side of an assignment must be a variable, property or indexer Diagnostic(ErrorCode.ERR_AssgLvalueExpected, "default(S).P").WithLocation(16, 9), // (16,9): error CS0131: The left-hand side of an assignment must be a variable, property or indexer Diagnostic(ErrorCode.ERR_AssgLvalueExpected, "default(T).P").WithLocation(17, 9), // (18,9): error CS0131: The left-hand side of an assignment must be a variable, property or indexer Diagnostic(ErrorCode.ERR_AssgLvalueExpected, "default(S)[0]").WithLocation(18, 9), // (18,9): error CS0131: The left-hand side of an assignment must be a variable, property or indexer Diagnostic(ErrorCode.ERR_AssgLvalueExpected, "default(T)[0]").WithLocation(19, 9)); } [WorkItem(538077, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538077")] [Fact] public void CS0132ERR_StaticConstParam() { var text = @" class A { static A(int z) { } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_StaticConstParam, Parameters = new string[] { "A.A(int)" } } }); } [Fact] public void CS0133ERR_NotConstantExpression01() { var source = @"class MyClass { public const int a = b; //no error since b is declared const public const int b = c; //CS0133, c is not constant public static int c = 1; //change static to const to correct program } "; CreateCompilation(source).VerifyDiagnostics( // (4,25): error CS0133: The expression being assigned to 'MyClass.b' must be constant // public const int b = c; //CS0133, c is not constant Diagnostic(ErrorCode.ERR_NotConstantExpression, "c").WithArguments("MyClass.b").WithLocation(4, 25)); } [Fact] public void CS0133ERR_NotConstantExpression02() { var source = @"enum E { X, Y = C.F(), Z = C.G() + 1, } class C { public static E F() { return E.X; } public static int G() { return 0; } } "; CreateCompilation(source).VerifyDiagnostics( // (4,9): error CS0266: Cannot implicitly convert type 'E' to 'int'. An explicit conversion exists (are you missing a cast?) // Y = C.F(), Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "C.F()").WithArguments("E", "int").WithLocation(4, 9), // (4,9): error CS0133: The expression being assigned to 'E.Y' must be constant // Y = C.F(), Diagnostic(ErrorCode.ERR_NotConstantExpression, "C.F()").WithArguments("E.Y").WithLocation(4, 9), // (5,9): error CS0133: The expression being assigned to 'E.Z' must be constant // Z = C.G() + 1, Diagnostic(ErrorCode.ERR_NotConstantExpression, "C.G() + 1").WithArguments("E.Z").WithLocation(5, 9)); } [Fact] public void CS0133ERR_NotConstantExpression03() { var source = @"class C { static void M() { int y = 1; const int x = 2 * y; } } "; CreateCompilation(source).VerifyDiagnostics( // (6,23): error CS0133: The expression being assigned to 'x' must be constant // const int x = 2 * y; Diagnostic(ErrorCode.ERR_NotConstantExpression, "2 * y").WithArguments("x").WithLocation(6, 23)); } [Fact] public void CS0133ERR_NotConstantExpression04() { var source = @"class C { static void M() { const int x = x + x; } }"; CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (5,27): error CS0110: The evaluation of the constant value for 'x' involves a circular definition // const int x = x + x; Diagnostic(ErrorCode.ERR_CircConstValue, "x").WithArguments("x").WithLocation(5, 27), // (5,23): error CS0110: The evaluation of the constant value for 'x' involves a circular definition // const int x = x + x; Diagnostic(ErrorCode.ERR_CircConstValue, "x").WithArguments("x").WithLocation(5, 23)); } [Fact] public void CS0135ERR_NameIllegallyOverrides() { // See NameCollisionTests.cs for commentary on this error. var text = @" public class MyClass2 { public static int i = 0; public static void Main() { { int i = 4; // CS0135: Roslyn reports this error here i++; } i = 0; // Native compiler reports the error here } }"; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text); } [Fact] public void CS0135ERR_NameIllegallyOverrides02() { CreateCompilationWithMscorlib40AndSystemCore(@" using System.Linq; class Test { static int x; static void Main() { int z = x; var y = from x in Enumerable.Range(1, 100) // CS1931 select x; } }").VerifyDiagnostics( // (6,16): warning CS0649: Field 'Test.x' is never assigned to, and will always have its default value 0 // static int x; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "x").WithArguments("Test.x", "0").WithLocation(6, 16) ); } [Fact] public void CS0136ERR_LocalIllegallyOverrides01() { // See comments in NameCollisionTests for thoughts on this error. string text = @"class C { static void M(object x) { string x = null; // CS0136 string y = null; if (x != null) { int y = 0; // CS0136 M(y); } M(x); M(y); } object P { get { int value = 0; // no error return value; } set { int value = 0; // CS0136 M(value); } } static void N(int q) { System.Func<int, int> f = q=>q; // 0136 } }"; var comp = CreateCompilation(text, parseOptions: TestOptions.Regular7_3); comp.VerifyDiagnostics( // (5,16): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // string x = null; // CS0136 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x").WithLocation(5, 16), // (9,17): error CS0136: A local or parameter named 'y' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // int y = 0; // CS0136 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y").WithArguments("y").WithLocation(9, 17), // (24,17): error CS0136: A local or parameter named 'value' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // int value = 0; // CS0136 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "value").WithArguments("value").WithLocation(24, 17), // (30,35): error CS0136: A local or parameter named 'q' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // System.Func<int, int> f = q=>q; // 0136 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "q").WithArguments("q").WithLocation(30, 35)); comp = CreateCompilation(text); comp.VerifyDiagnostics( // (5,16): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // string x = null; // CS0136 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x").WithLocation(5, 16), // (9,17): error CS0136: A local or parameter named 'y' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // int y = 0; // CS0136 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y").WithArguments("y").WithLocation(9, 17), // (24,17): error CS0136: A local or parameter named 'value' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // int value = 0; // CS0136 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "value").WithArguments("value").WithLocation(24, 17)); } [Fact] public void CS0136ERR_LocalIllegallyOverrides02() { // See comments in NameCollisionTests for commentary on this error. CreateCompilation( @"class C { static void M(object o) { try { } catch (System.IO.IOException e) { M(e); } catch (System.Exception e) // Legal; the two 'e' variables are in non-overlapping declaration spaces { M(e); } try { } catch (System.Exception o) // CS0136: Illegal; the two 'o' variables are in overlapping declaration spaces. { M(o); } } } ") .VerifyDiagnostics( Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "o").WithArguments("o").WithLocation(19, 33)); } [Fact] public void CS0136ERR_LocalIllegallyOverrides03() { // See comments in NameCollisionTests for commentary on this error. CreateCompilation( @"class C { int field = 0; int property { get; set; } static public void Main() { int[] ints = new int[] { 1, 2, 3 }; string[] strings = new string[] { ""1"", ""2"", ""3"" }; int conflict = 1; System.Console.WriteLine(conflict); foreach (int field in ints) { } // Legal: local hides field but name is used consistently foreach (string property in strings) { } // Legal: local hides property but name is used consistently foreach (string conflict in strings) { } // 0136: local hides another local in an enclosing local declaration space. } } ") .VerifyDiagnostics( // (14,25): error CS0136: A local or parameter named 'conflict' cannot be declared in this // scope because that name is used in an enclosing local scope to define a local or parameter // foreach (string conflict in strings) { } // 0136 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "conflict").WithArguments("conflict").WithLocation(14, 25), // (3,9): warning CS0414: The field 'C.field' is assigned but its value is never used // int field = 0; Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "field").WithArguments("C.field")); } [WorkItem(538045, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538045")] [Fact] public void CS0139ERR_NoBreakOrCont() { var text = @" namespace x { public class a { public static void Main(bool b) { if (b) continue; // CS0139 else break; // CS0139 } } }"; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_NoBreakOrCont, Line = 9, Column = 17 }, new ErrorDescription { Code = (int)ErrorCode.ERR_NoBreakOrCont, Line = 11, Column = 17 }}); } [WorkItem(542400, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542400")] [Fact] public void CS0140ERR_DuplicateLabel() { var text = @" namespace MyNamespace { public class MyClass { public static void Main() { label1: int i = M(); label1: int j = M(); // CS0140, comment this line to resolve goto label1; } static int M() { return 0; } } }"; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (9,10): error CS0140: The label 'label1' is a duplicate // label1: int j = M(); // CS0140, comment this line to resolve Diagnostic(ErrorCode.ERR_DuplicateLabel, "label1").WithArguments("label1").WithLocation(9, 10) ); } [WorkItem(542420, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542420")] [Fact] public void ErrorMeansSuccess_Attribute() { var text = @" using A; using B; using System; namespace A { class var { } class XAttribute : Attribute { } } namespace B { class var { } class XAttribute : Attribute { } class X : Attribute { } } class Xyzzy { [X] // 17.2 If an attribute class is found both with and without this suffix, an ambiguity is present and a compile-time error occurs. public static void Main(string[] args) { } static int M() { return 0; } }"; var comp = CreateCompilation(text); comp.VerifyDiagnostics(); } [WorkItem(542420, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542420")] [Fact] public void ErrorMeansSuccess_var() { var text = @" using A; using B; namespace A { class var { } } namespace B { class var { } } class Xyzzy { public static void Main(string[] args) { var x = M(); // 8.5.1 When the local-variable-type is specified as var and no type named var is in scope, ... } static int M() { return 0; } }"; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (21,9): error CS0104: 'var' is an ambiguous reference between 'A.var' and 'B.var' // var x = M(); // 8.5.1 When the local-variable-type is specified as var and no type named var is in scope, ... Diagnostic(ErrorCode.ERR_AmbigContext, "var").WithArguments("var", "A.var", "B.var") ); } [Fact] public void CS0144ERR_NoNewAbstract() { var text = @" interface ii { } abstract class aa { } public class a { public static void Main() { ii xx = new ii(); // CS0144 ii yy = new ii(Error); // CS0144, CS0103 aa zz = new aa(); // CS0144 } }"; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_NoNewAbstract, Line = 14, Column = 15 }, new ErrorDescription { Code = (int)ErrorCode.ERR_NoNewAbstract, Line = 15, Column = 15 }, new ErrorDescription { Code = (int)ErrorCode.ERR_NoNewAbstract, Line = 16, Column = 15 }, new ErrorDescription { Code = (int)ErrorCode.ERR_NameNotInContext, Line = 15, Column = 22 } }); } [WorkItem(539583, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539583")] [Fact] public void CS0150ERR_ConstantExpected() { var test = @" class C { static void Main() { byte x = 1; int[] a1 = new int[x]; int[] a2 = new int[x] { 1 }; //CS0150 const sbyte y = 1; const short z = 2; int[] b1 = new int[y + z]; int[] b2 = new int[y + z] { 1, 2, 3 }; } } "; CreateCompilation(test).VerifyDiagnostics( // (8,28): error CS0150: A constant value is expected Diagnostic(ErrorCode.ERR_ConstantExpected, "x")); } [Fact()] public void CS0151ERR_IntegralTypeValueExpected() { var text = @" public class iii { public static implicit operator int (iii aa) { return 0; } public static implicit operator long (iii aa) { return 0; } public static void Main() { iii a = new iii(); switch (a) // CS0151, compiler cannot choose between int and long { case 1: break; } } }"; var comp = CreateCompilation(text, parseOptions: TestOptions.Regular6); comp.VerifyDiagnostics( // (18,15): error CS0151: A switch expression or case label must be a bool, char, string, integral, enum, or corresponding nullable type in C# 6 and earlier. // switch (a) // CS0151, compiler cannot choose between int and long Diagnostic(ErrorCode.ERR_V6SwitchGoverningTypeValueExpected, "a").WithLocation(18, 15), // (20,15): error CS0029: Cannot implicitly convert type 'int' to 'iii' // case 1: Diagnostic(ErrorCode.ERR_NoImplicitConv, "1").WithArguments("int", "iii").WithLocation(20, 15) ); } [Fact] public void CS0152ERR_DuplicateCaseLabel() { var text = @" namespace x { public class a { public static void Main() { int i = 0; switch (i) { case 1: i++; return; case 1: // CS0152, two case 1 statements i++; return; } } } }"; CreateCompilation(text).VerifyDiagnostics( // (16,13): error CS0152: The switch statement contains multiple cases with the label value '1' // case 1: // CS0152, two case 1 statements Diagnostic(ErrorCode.ERR_DuplicateCaseLabel, "case 1:").WithArguments("1").WithLocation(16, 13) ); } [Fact] public void CS0153ERR_InvalidGotoCase() { var text = @" public class a { public static void Main() { goto case 5; // CS0153 } }"; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (6,7): error CS0153: A goto case is only valid inside a switch statement // goto case 5; // CS0153 Diagnostic(ErrorCode.ERR_InvalidGotoCase, "goto case 5;").WithLocation(6, 7)); } [Fact] public void CS0153ERR_InvalidGotoCase_2() { var text = @" class Program { static void Main(string[] args) { string Fruit = ""Apple""; switch (Fruit) { case ""Banana"": break; default: break; } goto default; } }"; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (14,9): error CS0153: A goto case is only valid inside a switch statement // goto default; Diagnostic(ErrorCode.ERR_InvalidGotoCase, "goto default;").WithLocation(14, 9)); } [Fact] public void CS0154ERR_PropertyLacksGet01() { CreateCompilation( @"class C { static object P { set { } } static int Q { set { } } static void M(object o) { C.P = null; o = C.P; // CS0154 M(P); // CS0154 ++C.Q; // CS0154 } } ") .VerifyDiagnostics( // (8,13): error CS0154: The property or indexer 'C.P' cannot be used in this context because it lacks the get accessor Diagnostic(ErrorCode.ERR_PropertyLacksGet, "C.P").WithArguments("C.P"), // (9,11): error CS0154: The property or indexer 'C.P' cannot be used in this context because it lacks the get accessor Diagnostic(ErrorCode.ERR_PropertyLacksGet, "P").WithArguments("C.P"), // (10,11): error CS0154: The property or indexer 'C.Q' cannot be used in this context because it lacks the get accessor Diagnostic(ErrorCode.ERR_PropertyLacksGet, "C.Q").WithArguments("C.Q")); } [Fact] public void CS0154ERR_PropertyLacksGet02() { var source = @"class A { public virtual A P { get; set; } public object Q { set { } } } class B : A { public override A P { set { } } void M() { M(Q); // CS0154, no get method } static void M(B b) { object o = b.P; // no error o = b.Q; // CS0154, no get method b.P.Q = null; // no error o = b.P.Q; // CS0154, no get method } static void M(object o) { } } "; CreateCompilation(source).VerifyDiagnostics( // (11,11): error CS0154: The property or indexer 'A.Q' cannot be used in this context because it lacks the get accessor // M(Q); // CS0154, no get method Diagnostic(ErrorCode.ERR_PropertyLacksGet, "Q").WithArguments("A.Q").WithLocation(11, 11), // (16,13): error CS0154: The property or indexer 'A.Q' cannot be used in this context because it lacks the get accessor // o = b.Q; // CS0154, no get method Diagnostic(ErrorCode.ERR_PropertyLacksGet, "b.Q").WithArguments("A.Q").WithLocation(16, 13), // (18,13): error CS0154: The property or indexer 'A.Q' cannot be used in this context because it lacks the get accessor // o = b.P.Q; // CS0154, no get method Diagnostic(ErrorCode.ERR_PropertyLacksGet, "b.P.Q").WithArguments("A.Q").WithLocation(18, 13)); } [Fact] public void CS0154ERR_PropertyLacksGet03() { var source = @"class C { int P { set { } } void M() { P += 1; } } "; CreateCompilation(source).VerifyDiagnostics( // (6,9): error CS0154: The property or indexer 'C.P' cannot be used in this context because it lacks the get accessor // P += 1; Diagnostic(ErrorCode.ERR_PropertyLacksGet, "P").WithArguments("C.P").WithLocation(6, 9)); } [Fact] public void CS0154ERR_PropertyLacksGet04() { var source = @"class C { object p; object P { set { p = P; } } } "; CreateCompilation(source).VerifyDiagnostics( // (4,26): error CS0154: The property or indexer 'C.P' cannot be used in this context because it lacks the get accessor // object P { set { p = P; } } Diagnostic(ErrorCode.ERR_PropertyLacksGet, "P").WithArguments("C.P").WithLocation(4, 26)); } [Fact] public void CS0154ERR_PropertyLacksGet05() { CreateCompilation( @"class C { object P { set { } } static bool Q { set { } } void M() { object o = P as string; o = P ?? Q; o = (o != null) ? P : Q; o = !Q; } }") .VerifyDiagnostics( // (7,20): error CS0154: The property or indexer 'C.P' cannot be used in this context because it lacks the get accessor Diagnostic(ErrorCode.ERR_PropertyLacksGet, "P").WithArguments("C.P").WithLocation(7, 20), // (8,13): error CS0154: The property or indexer 'C.P' cannot be used in this context because it lacks the get accessor Diagnostic(ErrorCode.ERR_PropertyLacksGet, "P").WithArguments("C.P").WithLocation(8, 13), // (8,18): error CS0154: The property or indexer 'C.Q' cannot be used in this context because it lacks the get accessor Diagnostic(ErrorCode.ERR_PropertyLacksGet, "Q").WithArguments("C.Q").WithLocation(8, 18), // (9,27): error CS0154: The property or indexer 'C.P' cannot be used in this context because it lacks the get accessor Diagnostic(ErrorCode.ERR_PropertyLacksGet, "P").WithArguments("C.P").WithLocation(9, 27), // (9,31): error CS0154: The property or indexer 'C.Q' cannot be used in this context because it lacks the get accessor Diagnostic(ErrorCode.ERR_PropertyLacksGet, "Q").WithArguments("C.Q").WithLocation(9, 31), // (10,14): error CS0154: The property or indexer 'C.Q' cannot be used in this context because it lacks the get accessor Diagnostic(ErrorCode.ERR_PropertyLacksGet, "Q").WithArguments("C.Q").WithLocation(10, 14)); } [Fact] public void CS0154ERR_PropertyLacksGet06() { CreateCompilation( @"class C { int this[int x] { set { } } void M(int b) { b = this[0]; b = 1 + this[1]; M(this[2]); this[3]++; this[4] += 1; } }") .VerifyDiagnostics( // (6,13): error CS0154: The property or indexer 'C.this[int]' cannot be used in this context because it lacks the get accessor Diagnostic(ErrorCode.ERR_PropertyLacksGet, "this[0]").WithArguments("C.this[int]"), // (7,17): error CS0154: The property or indexer 'C.this[int]' cannot be used in this context because it lacks the get accessor Diagnostic(ErrorCode.ERR_PropertyLacksGet, "this[1]").WithArguments("C.this[int]"), // (8,11): error CS0154: The property or indexer 'C.this[int]' cannot be used in this context because it lacks the get accessor Diagnostic(ErrorCode.ERR_PropertyLacksGet, "this[2]").WithArguments("C.this[int]"), // (9,9): error CS0154: The property or indexer 'C.this[int]' cannot be used in this context because it lacks the get accessor Diagnostic(ErrorCode.ERR_PropertyLacksGet, "this[3]").WithArguments("C.this[int]"), // (10,9): error CS0154: The property or indexer 'C.this[int]' cannot be used in this context because it lacks the get accessor Diagnostic(ErrorCode.ERR_PropertyLacksGet, "this[4]").WithArguments("C.this[int]")); } [Fact] public void CS0154ERR_PropertyLacksGet07() { var source1 = @"public class A { public virtual object P { private get { return null; } set { } } } public class B : A { public override object P { set { } } }"; var compilation1 = CreateCompilation(source1); compilation1.VerifyDiagnostics(); var compilationVerifier = CompileAndVerify(compilation1); var reference1 = MetadataReference.CreateFromImage(compilationVerifier.EmittedAssemblyData); var source2 = @"class C { static void M(B b) { var o = b.P; b.P = o; } }"; var compilation2 = CreateCompilation(source2, references: new[] { reference1 }); compilation2.VerifyDiagnostics( // (5,17): error CS0154: The property or indexer 'B.P' cannot be used in this context because it lacks the get accessor Diagnostic(ErrorCode.ERR_PropertyLacksGet, "b.P").WithArguments("B.P").WithLocation(5, 17)); } [Fact] public void CS0155ERR_BadExceptionType() { var text = @"interface IA { } interface IB : IA { } struct S { } class C { static void M() { try { } catch (object) { } catch (System.Exception) { } catch (System.DateTime) { } catch (System.Int32) { } catch (IA) { } catch (IB) { } catch (S) { } catch (S) { } } } "; CreateCompilation(text).VerifyDiagnostics( Diagnostic(ErrorCode.ERR_BadExceptionType, "object").WithLocation(9, 16), Diagnostic(ErrorCode.ERR_UnreachableCatch, "System.Exception").WithArguments("object").WithLocation(10, 16), Diagnostic(ErrorCode.ERR_BadExceptionType, "System.DateTime").WithLocation(11, 16), Diagnostic(ErrorCode.ERR_BadExceptionType, "System.Int32").WithLocation(12, 16), Diagnostic(ErrorCode.ERR_BadExceptionType, "IA").WithLocation(13, 16), Diagnostic(ErrorCode.ERR_BadExceptionType, "IB").WithLocation(14, 16), Diagnostic(ErrorCode.ERR_BadExceptionType, "S").WithLocation(15, 16), Diagnostic(ErrorCode.ERR_BadExceptionType, "S").WithLocation(16, 16)); } [Fact] public void CS0155ERR_BadExceptionType_Null() { var text = @"class C { static readonly bool False = false; const string T = null; static void M(object o) { const string s = null; if (False) throw null; if (False) throw (string)null; //CS0155 if (False) throw s; //CS0155 if (False) throw T; //CS0155 } } "; CreateCompilation(text).VerifyDiagnostics( // (10,26): error CS0029: Cannot implicitly convert type 'string' to 'System.Exception' // if (False) throw (string)null; //CS0155 Diagnostic(ErrorCode.ERR_NoImplicitConv, "(string)null").WithArguments("string", "System.Exception").WithLocation(10, 26), // (11,26): error CS0029: Cannot implicitly convert type 'string' to 'System.Exception' // if (False) throw s; //CS0155 Diagnostic(ErrorCode.ERR_NoImplicitConv, "s").WithArguments("string", "System.Exception").WithLocation(11, 26), // (12,26): error CS0029: Cannot implicitly convert type 'string' to 'System.Exception' // if (False) throw T; //CS0155 Diagnostic(ErrorCode.ERR_NoImplicitConv, "T").WithArguments("string", "System.Exception").WithLocation(12, 26) ); } [Fact] public void CS0155ERR_BadExceptionType_FailingAs() { var text = @" class C { static readonly bool False = false; static void M(object o) { if (False) throw new C() as D; //CS0155, though always null } } class D : C { } "; CreateCompilation(text).VerifyDiagnostics( // (8,26): error CS0029: Cannot implicitly convert type 'D' to 'System.Exception' // if (False) throw new C() as D; //CS0155, though always null Diagnostic(ErrorCode.ERR_NoImplicitConv, "new C() as D").WithArguments("D", "System.Exception").WithLocation(8, 26) ); } [Fact] public void CS0155ERR_BadExceptionType_TypeParameters() { var text = @"using System; class C { static readonly bool False = false; static void M<T, TC, TS, TE>(object o) where TC : class where TS : struct where TE : Exception, new() { if (False) throw default(T); //CS0155 if (False) throw default(TC); //CS0155 if (False) throw default(TS); //CS0155 if (False) throw default(TE); if (False) throw new TE(); } } "; CreateCompilation(text).VerifyDiagnostics( // (11,26): error CS0029: Cannot implicitly convert type 'T' to 'System.Exception' // if (False) throw default(T); //CS0155 Diagnostic(ErrorCode.ERR_NoImplicitConv, "default(T)").WithArguments("T", "System.Exception").WithLocation(11, 26), // (12,26): error CS0029: Cannot implicitly convert type 'TC' to 'System.Exception' // if (False) throw default(TC); //CS0155 Diagnostic(ErrorCode.ERR_NoImplicitConv, "default(TC)").WithArguments("TC", "System.Exception").WithLocation(12, 26), // (13,26): error CS0029: Cannot implicitly convert type 'TS' to 'System.Exception' // if (False) throw default(TS); //CS0155 Diagnostic(ErrorCode.ERR_NoImplicitConv, "default(TS)").WithArguments("TS", "System.Exception").WithLocation(13, 26) ); } [Fact()] public void CS0155ERR_BadExceptionType_UserDefinedConversions() { var text = @"using System; class C { static readonly bool False = false; static void M(object o) { if (False) throw new Implicit(); //CS0155 if (False) throw new Explicit(); //CS0155 if (False) throw (Exception)new Implicit(); if (False) throw (Exception)new Explicit(); } } class Implicit { public static implicit operator Exception(Implicit i) { return null; } } class Explicit { public static explicit operator Exception(Explicit i) { return null; } } "; CreateCompilation(text, parseOptions: TestOptions.Regular7_3).VerifyDiagnostics( // (8,20): error CS0155: The type caught or thrown must be derived from System.Exception Diagnostic(ErrorCode.ERR_BadExceptionType, "new Implicit()"), // (8,20): error CS0155: The type caught or thrown must be derived from System.Exception Diagnostic(ErrorCode.ERR_BadExceptionType, "new Explicit()") ); CreateCompilation(text).VerifyDiagnostics( // (9,26): error CS0266: Cannot implicitly convert type 'Explicit' to 'System.Exception'. An explicit conversion exists (are you missing a cast?) // if (False) throw new Explicit(); //CS0155 Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "new Explicit()").WithArguments("Explicit", "System.Exception").WithLocation(9, 26) ); } [Fact] public void CS0155ERR_BadExceptionType_Dynamic() { var text = @" class C { static readonly bool False = false; static void M(object o) { dynamic d = null; if (False) throw d; //CS0155 } } "; CreateCompilation(text, parseOptions: TestOptions.Regular7_3).VerifyDiagnostics( // (9,26): error CS0155: The type caught or thrown must be derived from System.Exception Diagnostic(ErrorCode.ERR_BadExceptionType, "d")); CreateCompilation(text).VerifyDiagnostics(); // dynamic conversion to Exception } [WorkItem(542995, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542995")] [Fact] public void CS0155ERR_BadExceptionType_Struct() { var text = @" public class Test { public static void Main(string[] args) { } private void Method() { try { } catch (s1 s) { } } } struct s1 { } "; CreateCompilation(text).VerifyDiagnostics( // (12,16): error CS0155: The type caught or thrown must be derived from System.Exception // catch (s1 s) Diagnostic(ErrorCode.ERR_BadExceptionType, "s1"), // (12,19): warning CS0168: The variable 's' is declared but never used // catch (s1 s) Diagnostic(ErrorCode.WRN_UnreferencedVar, "s").WithArguments("s") ); } [Fact] public void CS0156ERR_BadEmptyThrow() { var text = @" using System; namespace x { public class b : Exception { } public class a { public static void Main() { try { throw; // CS0156 } catch(b) { throw; // this throw is valid } } } }"; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_BadEmptyThrow, Line = 16, Column = 13 } }); } [Fact] public void CS0156ERR_BadEmptyThrow_Nesting() { var text = @" class C { void M() { bool b = System.DateTime.Now.Second > 1; //avoid unreachable code if (b) throw; //CS0156 try { if (b) throw; //CS0156 try { if (b) throw; //CS0156 } catch { if (b) throw; //fine } finally { if (b) throw; //CS0156 } } catch { if (b) throw; //fine try { if (b) throw; //fine } catch { if (b) throw; //fine } finally { if (b) throw; //CS0724 try { if (b) throw; //CS0724 } catch { if (b) throw; //fine } finally { if (b) throw; //CS0724 } } } finally { if (b) throw; //CS0156 try { if (b) throw; //CS0156 } catch { if (b) throw; //fine } finally { if (b) throw; //CS0156 } } } }"; CreateCompilation(text).VerifyDiagnostics( // (6,9): error CS0156: A throw statement with no arguments is not allowed outside of a catch clause Diagnostic(ErrorCode.ERR_BadEmptyThrow, "throw"), // (9,13): error CS0156: A throw statement with no arguments is not allowed outside of a catch clause Diagnostic(ErrorCode.ERR_BadEmptyThrow, "throw"), // (12,17): error CS0156: A throw statement with no arguments is not allowed outside of a catch clause Diagnostic(ErrorCode.ERR_BadEmptyThrow, "throw"), // (20,17): error CS0156: A throw statement with no arguments is not allowed outside of a catch clause Diagnostic(ErrorCode.ERR_BadEmptyThrow, "throw"), // (36,17): error CS0724: A throw statement with no arguments is not allowed in a finally clause that is nested inside the nearest enclosing catch clause Diagnostic(ErrorCode.ERR_BadEmptyThrowInFinally, "throw"), // (36,17): error CS0724: A throw statement with no arguments is not allowed in a finally clause that is nested inside the nearest enclosing catch clause Diagnostic(ErrorCode.ERR_BadEmptyThrowInFinally, "throw"), // (36,17): error CS0724: A throw statement with no arguments is not allowed in a finally clause that is nested inside the nearest enclosing catch clause Diagnostic(ErrorCode.ERR_BadEmptyThrowInFinally, "throw"), // (41,13): error CS0156: A throw statement with no arguments is not allowed outside of a catch clause Diagnostic(ErrorCode.ERR_BadEmptyThrow, "throw"), // (44,17): error CS0156: A throw statement with no arguments is not allowed outside of a catch clause Diagnostic(ErrorCode.ERR_BadEmptyThrow, "throw"), // (52,17): error CS0156: A throw statement with no arguments is not allowed outside of a catch clause Diagnostic(ErrorCode.ERR_BadEmptyThrow, "throw")); } [Fact] public void CS0156ERR_BadEmptyThrow_Lambdas() { var text = @" class C { void M() { bool b = System.DateTime.Now.Second > 1; // avoid unreachable code System.Action a; a = () => { throw; }; //CS0156 try { a = () => { if (b) throw; //CS0156 try { if (b) throw; //CS0156 } catch { if (b) throw; //fine } finally { if (b) throw; //CS0156 } }; } catch { a = () => { if (b) throw; //CS0156 try { if (b) throw; //CS0156 } catch { if (b) throw; //fine } finally { if (b) throw; //CS0156 } }; } finally { a = () => { if (b) throw; //CS0156 try { if (b) throw; //CS0156 } catch { if (b) throw; //fine } finally { if (b) throw; //CS0156 } }; } } }"; CreateCompilation(text).VerifyDiagnostics( // (8,21): error CS0156: A throw statement with no arguments is not allowed outside of a catch clause Diagnostic(ErrorCode.ERR_BadEmptyThrow, "throw"), // (13,24): error CS0156: A throw statement with no arguments is not allowed outside of a catch clause Diagnostic(ErrorCode.ERR_BadEmptyThrow, "throw"), // (16,28): error CS0156: A throw statement with no arguments is not allowed outside of a catch clause Diagnostic(ErrorCode.ERR_BadEmptyThrow, "throw"), // (24,28): error CS0156: A throw statement with no arguments is not allowed outside of a catch clause Diagnostic(ErrorCode.ERR_BadEmptyThrow, "throw"), // (32,24): error CS0156: A throw statement with no arguments is not allowed outside of a catch clause Diagnostic(ErrorCode.ERR_BadEmptyThrow, "throw"), // (35,28): error CS0156: A throw statement with no arguments is not allowed outside of a catch clause Diagnostic(ErrorCode.ERR_BadEmptyThrow, "throw"), // (43,28): error CS0156: A throw statement with no arguments is not allowed outside of a catch clause Diagnostic(ErrorCode.ERR_BadEmptyThrow, "throw"), // (51,24): error CS0156: A throw statement with no arguments is not allowed outside of a catch clause Diagnostic(ErrorCode.ERR_BadEmptyThrow, "throw"), // (54,28): error CS0156: A throw statement with no arguments is not allowed outside of a catch clause Diagnostic(ErrorCode.ERR_BadEmptyThrow, "throw"), // (62,28): error CS0156: A throw statement with no arguments is not allowed outside of a catch clause Diagnostic(ErrorCode.ERR_BadEmptyThrow, "throw")); } [WorkItem(540817, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540817")] [Fact] public void CS0157ERR_BadFinallyLeave01() { var text = @"class C { static int F; static void M() { if (F == 0) goto Before; else if (F == 1) goto After; Before: ; try { if (F == 0) goto Before; else if (F == 1) goto After; else if (F == 2) goto TryBlock; else if (F == 3) return; TryBlock: ; } catch (System.Exception) { if (F == 0) goto Before; else if (F == 1) goto After; else if (F == 2) goto CatchBlock; else if (F == 3) return; CatchBlock: ; } finally { if (F == 0) goto Before; else if (F == 1) goto After; else if (F == 2) goto FinallyBlock; else if (F == 3) return; FinallyBlock: ; } After: ; } }"; CreateCompilation(text).VerifyDiagnostics( // (41,17): error CS0157: Control cannot leave the body of a finally clause // goto Before; Diagnostic(ErrorCode.ERR_BadFinallyLeave, "goto"), // (43,17): error CS0157: Control cannot leave the body of a finally clause // goto After; Diagnostic(ErrorCode.ERR_BadFinallyLeave, "goto"), // (47,17): error CS0157: Control cannot leave the body of a finally clause // return; Diagnostic(ErrorCode.ERR_BadFinallyLeave, "return"), // (3,16): warning CS0649: Field 'C.F' is never assigned to, and will always have its default value 0 // static int F; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "F").WithArguments("C.F", "0") ); } [WorkItem(540817, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540817")] [Fact] public void CS0157ERR_BadFinallyLeave02() { var text = @"using System; class C { static void F(int i) { } static void M() { for (int i = 0; i < 10;) { if (i < 5) { try { F(i); } catch (Exception) { continue; } finally { break; } } else { try { F(i); } catch (Exception) { break; } finally { continue; } } } } }"; CreateCompilation(text). VerifyDiagnostics( Diagnostic(ErrorCode.ERR_BadFinallyLeave, "break").WithLocation(15, 27), Diagnostic(ErrorCode.ERR_BadFinallyLeave, "continue").WithLocation(21, 27)); } [WorkItem(540817, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540817")] [Fact] public void CS0157ERR_BadFinallyLeave03() { var text = @" class C { static void Main(string[] args) { int i = 0; try { i = 1; } catch { i = 2; } finally { i = 3; goto lab1; }// invalid lab1: return; } } "; CreateCompilation(text). VerifyDiagnostics( // (9,26): error CS0157: Control cannot leave the body of a finally clause // finally { i = 3; goto lab1; }// invalid Diagnostic(ErrorCode.ERR_BadFinallyLeave, "goto"), // (6,13): warning CS0219: The variable 'i' is assigned but its value is never used // int i = 0; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "i").WithArguments("i") ); } [WorkItem(539890, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539890")] [Fact] public void CS0158ERR_LabelShadow() { var text = @" namespace MyNamespace { public class MyClass { public static void Main() { goto lab1; lab1: { lab1: goto lab1; // CS0158 } } } }"; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_LabelShadow, Line = 11, Column = 13 } }); } [WorkItem(539890, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539890")] [Fact] public void CS0158ERR_LabelShadow_02() { var text = @" delegate int del(int i); class C { static void Main(string[] args) { del p = x => { goto label1; label1: // invalid return x * x; }; label1: return; } } "; CreateCompilation(text). VerifyDiagnostics( // (10,9): error CS0158: The label 'label1' shadows another label by the same name in a contained scope // label1: // invalid Diagnostic(ErrorCode.ERR_LabelShadow, "label1").WithArguments("label1"), // (13,5): warning CS0164: This label has not been referenced // label1: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "label1") ); } [WorkItem(539875, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539875")] [Fact] public void CS0159ERR_LabelNotFound() { var text = @" public class Cls { public static void Main() { goto Label2; } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_LabelNotFound, Line = 6, Column = 14 } }); } [WorkItem(528799, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528799")] [Fact()] public void CS0159ERR_LabelNotFound_2() { var text = @" class Program { static void Main(string[] args) { int s = 23; switch (s) { case 21: break; case 23: goto default; } } } "; CreateCompilation(text).VerifyDiagnostics( // (12,17): error CS0159: No such label 'default:' within the scope of the goto statement // goto default; Diagnostic(ErrorCode.ERR_LabelNotFound, "goto default;").WithArguments("default:"), // (11,13): error CS8070: Control cannot fall out of switch from final case label ('case 23:') // case 23: Diagnostic(ErrorCode.ERR_SwitchFallOut, "case 23:").WithArguments("case 23:")); } [WorkItem(539876, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539876")] [Fact] public void CS0159ERR_LabelNotFound_3() { var text = @" class Program { static void Main(string[] args) { goto Label; } public static void Goo() { Label: ; } } "; CreateCompilation(text). VerifyDiagnostics(Diagnostic(ErrorCode.ERR_LabelNotFound, "Label").WithArguments("Label"), Diagnostic(ErrorCode.WRN_UnreferencedLabel, "Label")); } [WorkItem(539876, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539876")] [Fact] public void CS0159ERR_LabelNotFound_4() { var text = @" class Program { static void Main(string[] args) { for (int i = 0; i < 10; i++) { Label: i++; } goto Label; } } "; CreateCompilation(text). VerifyDiagnostics(Diagnostic(ErrorCode.ERR_LabelNotFound, "Label").WithArguments("Label"), Diagnostic(ErrorCode.WRN_UnreferencedLabel, "Label")); } [WorkItem(539876, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539876")] [Fact] public void CS0159ERR_LabelNotFound_5() { var text = @" class Program { static void Main(string[] args) { if (true) { Label1: goto Label2; } else { Label2: goto Label1; } } } "; CreateCompilation(text). VerifyDiagnostics(Diagnostic(ErrorCode.ERR_LabelNotFound, "Label2").WithArguments("Label2"), Diagnostic(ErrorCode.ERR_LabelNotFound, "Label1").WithArguments("Label1"), Diagnostic(ErrorCode.WRN_UnreachableCode, "Label2"), Diagnostic(ErrorCode.WRN_UnreferencedLabel, "Label1"), Diagnostic(ErrorCode.WRN_UnreferencedLabel, "Label2")); } [WorkItem(539876, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539876")] [Fact] public void CS0159ERR_LabelNotFound_6() { var text = @" class Program { static void Main(string[] args) { { goto L; } { L: return; } } } "; CreateCompilation(text). VerifyDiagnostics(Diagnostic(ErrorCode.ERR_LabelNotFound, "L").WithArguments("L"), Diagnostic(ErrorCode.WRN_UnreferencedLabel, "L")); } [WorkItem(539876, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539876")] [Fact] public void CS0159ERR_LabelNotFound_7() { var text = @" class Program { static void Main(string[] args) { int i = 3; if (true) { label1: goto label3; if (!false) { label2: goto label5; if (i > 2) { label3: goto label2; if (i == 3) { label4: if (i < 5) { label5: if (i == 4) { } else { System.Console.WriteLine(""a""); } } } } } } } } "; CreateCompilation(text). VerifyDiagnostics(Diagnostic(ErrorCode.ERR_LabelNotFound, "label3").WithArguments("label3"), Diagnostic(ErrorCode.ERR_LabelNotFound, "label5").WithArguments("label5"), Diagnostic(ErrorCode.WRN_UnreachableCode, "if"), Diagnostic(ErrorCode.WRN_UnreachableCode, "label4"), Diagnostic(ErrorCode.WRN_UnreachableCode, "label5"), Diagnostic(ErrorCode.WRN_UnreferencedLabel, "label1"), Diagnostic(ErrorCode.WRN_UnreferencedLabel, "label3"), Diagnostic(ErrorCode.WRN_UnreferencedLabel, "label4"), Diagnostic(ErrorCode.WRN_UnreferencedLabel, "label5")); } [WorkItem(540818, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540818")] [Fact] public void CS0159ERR_LabelNotFound_8() { var text = @" delegate int del(int i); class C { static void Main(string[] args) { del q = x => { goto label2; // invalid return x * x; }; label2: return; } } "; CreateCompilation(text). VerifyDiagnostics( // (10,17): warning CS0162: Unreachable code detected // return x * x; Diagnostic(ErrorCode.WRN_UnreachableCode, "return"), // (9,17): error CS0159: No such label 'label2' within the scope of the goto statement // goto label2; // invalid Diagnostic(ErrorCode.ERR_LabelNotFound, "goto").WithArguments("label2"), // (12,5): warning CS0164: This label has not been referenced // label2: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "label2") ); } [WorkItem(539876, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539876")] [Fact] public void CS0159ERR_LabelNotFound_9() { var text = @" public class Test { static public void Main(string[] args) { string[] S = new string[] { ""ABC"", ""XYZ"" }; foreach (string x in S) { goto innerLoop; foreach (char y in x) { innerLoop: return; } } } } "; CreateCompilation(text). VerifyDiagnostics(Diagnostic(ErrorCode.ERR_LabelNotFound, "innerLoop").WithArguments("innerLoop"), Diagnostic(ErrorCode.WRN_UnreferencedLabel, "innerLoop")); } [Fact] public void CS0160ERR_UnreachableCatch() { var text = @"using System; using System.IO; class A : Exception { } class B : A { } class C : IOException { } interface I { } class D : Exception, I { } class E : IOException, I { } class F<T> : Exception { } class Program { static void M() { try { } catch (A) { } catch (D) { } catch (E) { } catch (IOException) { } catch (C) { } catch (F<bool>) { } catch (F<int>) { } catch (Exception) { } catch (B) { } catch (StackOverflowException) { } catch (F<int>) { } catch (F<float>) { } } } "; CreateCompilation(text).VerifyDiagnostics( Diagnostic(ErrorCode.ERR_UnreachableCatch, "C").WithArguments("System.IO.IOException").WithLocation(19, 16), Diagnostic(ErrorCode.ERR_UnreachableCatch, "B").WithArguments("A").WithLocation(23, 16), Diagnostic(ErrorCode.ERR_UnreachableCatch, "StackOverflowException").WithArguments("System.Exception").WithLocation(24, 16), Diagnostic(ErrorCode.ERR_UnreachableCatch, "F<int>").WithArguments("F<int>").WithLocation(25, 16), Diagnostic(ErrorCode.ERR_UnreachableCatch, "F<float>").WithArguments("System.Exception").WithLocation(26, 16)); } [Fact] public void CS0160ERR_UnreachableCatch_Filter1() { var text = @" using System; class A : Exception { } class B : A { } class Program { static void M() { int a = 1; try { } catch when (a == 1) { } catch (Exception e) when (e.Message == null) { } catch (A) { } catch (B e) when (e.Message == null) { } } } "; CreateCompilation(text).VerifyDiagnostics( // (15,16): error CS0160: A previous catch clause already catches all exceptions of this or of a super type ('A') // catch (B e) when (e.Message == null) { } Diagnostic(ErrorCode.ERR_UnreachableCatch, "B").WithArguments("A").WithLocation(15, 16)); } [Fact] public void CS8359WRN_FilterIsConstantFalse_NonBoolean() { // Non-boolean constant filters are not considered for WRN_FilterIsConstant warnings. var text = @" using System; class A : Exception { } class B : A { } class Program { static void M() { try { } catch (A) when (1) { } catch (B) when (0) { } catch (B) when (""false"") { } catch (B) when (false) { } } } "; CreateCompilation(text).VerifyDiagnostics( // (11,25): error CS0029: Cannot implicitly convert type 'int' to 'bool' // catch (A) when (1) { } Diagnostic(ErrorCode.ERR_NoImplicitConv, "1").WithArguments("int", "bool").WithLocation(11, 25), // (12,25): error CS0029: Cannot implicitly convert type 'int' to 'bool' // catch (B) when (0) { } Diagnostic(ErrorCode.ERR_NoImplicitConv, "0").WithArguments("int", "bool").WithLocation(12, 25), // (13,25): error CS0029: Cannot implicitly convert type 'string' to 'bool' // catch (B) when ("false") { } Diagnostic(ErrorCode.ERR_NoImplicitConv, @"""false""").WithArguments("string", "bool").WithLocation(13, 25), // (14,25): warning CS8359: Filter expression is a constant 'false', consider removing the catch clause // catch (B) when (false) { } Diagnostic(ErrorCode.WRN_FilterIsConstantFalse, "false").WithLocation(14, 25)); } [Fact] public void CS8359WRN_FilterIsConstantFalse1() { var text = @" using System; class A : Exception { } class B : A { } class Program { static void M() { try { } catch (A) when (false) { } catch (B) when (false) { } } } "; CreateCompilation(text).VerifyDiagnostics( // (11,25): warning CS8359: Filter expression is a constant 'false', consider removing the catch clause // catch (A) when (false) { } Diagnostic(ErrorCode.WRN_FilterIsConstantFalse, "false").WithLocation(11, 25), // (12,25): warning CS8359: Filter expression is a constant 'false', consider removing the catch clause // catch (B) when (false) { } Diagnostic(ErrorCode.WRN_FilterIsConstantFalse, "false").WithLocation(12, 25)); } [Fact] public void CS8359WRN_FilterIsConstantFalse2() { var text = @" using System; class A : Exception { } class B : A { } class Program { static void M() { try { } catch (A) when ((1+1)!=2) { } catch (B) when (false) { } } } "; CreateCompilation(text).VerifyDiagnostics( // (11,25): warning CS8359: Filter expression is a constant 'false', consider removing the catch clause // catch (A) when (false) { } Diagnostic(ErrorCode.WRN_FilterIsConstantFalse, "(1+1)!=2").WithLocation(11, 25), // (12,25): warning CS8359: Filter expression is a constant 'false', consider removing the catch clause // catch (B) when (false) { } Diagnostic(ErrorCode.WRN_FilterIsConstantFalse, "false").WithLocation(12, 25)); } [Fact] public void CS8359WRN_FilterIsConstantFalse3() { var text = @" using System; class A : Exception { } class Program { static void M() { try { } catch (A) when (false) { } finally { } } } "; CreateCompilation(text).VerifyDiagnostics( // (11,25): warning CS8359: Filter expression is a constant 'false', consider removing the catch clause // catch (A) when (false) { } Diagnostic(ErrorCode.WRN_FilterIsConstantFalse, "false").WithLocation(10, 25)); } [Fact] public void CS8360WRN_FilterIsConstantRedundantTryCatch1() { var text = @" using System; class A : Exception { } class Program { static void M() { try { } catch (A) when (false) { } } } "; CreateCompilation(text).VerifyDiagnostics( // (11,25): warning CS8360: Filter expression is a constant 'false', consider removing the try-catch block // catch (A) when (false) { } Diagnostic(ErrorCode.WRN_FilterIsConstantFalseRedundantTryCatch, "false").WithLocation(10, 25)); } [Fact] public void CS8360WRN_FilterIsConstantRedundantTryCatch2() { var text = @" using System; class A : Exception { } class Program { static void M() { try { } catch (A) when ((1+1)!=2) { } } } "; CreateCompilation(text).VerifyDiagnostics( // (11,25): warning CS8360: Filter expression is a constant 'false', consider removing the try-catch block // catch (A) when (false) { } Diagnostic(ErrorCode.WRN_FilterIsConstantFalseRedundantTryCatch, "(1+1)!=2").WithLocation(10, 25)); } [Fact] public void CS7095WRN_FilterIsConstantTrue1() { var text = @" using System; class A : Exception { } class B : A { } class Program { static void M() { try { } catch (A) when (true) { } catch (B) { } } } "; CreateCompilation(text).VerifyDiagnostics( // (11,25): warning CS7095: Filter expression is a constant 'true', consider removing the filter // catch (A) when (true) { } Diagnostic(ErrorCode.WRN_FilterIsConstantTrue, "true").WithLocation(11, 25)); } [Fact] public void CS7095WRN_FilterIsConstantTrue2() { var text = @" using System; class A : Exception { } class Program { static void M() { try { } catch when (true) { } catch (A) { } catch when (false) { } } } "; CreateCompilation(text).VerifyDiagnostics( // (10,19): warning CS7095: Filter expression is a constant 'true', consider removing the filter // catch when (true) { } Diagnostic(ErrorCode.WRN_FilterIsConstantTrue, "true").WithLocation(10, 21), // (12,19): warning CS8359: Filter expression is a constant 'false', consider removing the catch clause // catch when (false) { } Diagnostic(ErrorCode.WRN_FilterIsConstantFalse, "false").WithLocation(12, 21)); } [Fact] public void CS7095WRN_FilterIsConstantTrue3() { var text = @" using System; class A : Exception { } class Program { static void M() { try { } catch when ((1+1)==2) { } } } "; CreateCompilation(text).VerifyDiagnostics( // (10,19): warning CS7095: Filter expression is a constant 'true', consider removing the filter // catch when (true) { } Diagnostic(ErrorCode.WRN_FilterIsConstantTrue, "(1+1)==2").WithLocation(10, 21)); } [Fact] public void CS0162WRN_UnreachableCode_Filter_ConstantCondition() { var text = @" using System; class A : Exception { } class B : A { } class Program { static void M() { try { } catch (A) when (false) { Console.WriteLine(1); } catch (B) { } } } "; CreateCompilation(text).VerifyDiagnostics( // (11,25): warning CS8359: Filter expression is a constant 'false', consider removing the catch clause // catch (A) when (false) Diagnostic(ErrorCode.WRN_FilterIsConstantFalse, "false").WithLocation(11, 25), // (13,13): warning CS0162: Unreachable code detected // Console.WriteLine(1); Diagnostic(ErrorCode.WRN_UnreachableCode, "Console").WithLocation(13, 13) ); } [Fact] public void CS0162WRN_UnreachableCode_Filter_ConstantCondition2() { var text = @" using System; class Program { static void M() { int x; try { } catch (Exception) when (false) { Console.WriteLine(x); } } } "; // Unlike an unreachable code in if statement block we don't allow using // a variable that's not definitely assigned. The reason why we allow it in an if statement // is to make conditional compilation easier. Such scenario doesn't apply to filters. CreateCompilation(text).VerifyDiagnostics( // (10,33): warning CS7105: Filter expression is a constant 'false', consider removing the try-catch block // catch (Exception) when (false) Diagnostic(ErrorCode.WRN_FilterIsConstantFalseRedundantTryCatch, "false").WithLocation(10, 33), // (12,13): warning CS0162: Unreachable code detected // Console.WriteLine(x); Diagnostic(ErrorCode.WRN_UnreachableCode, "Console").WithLocation(12, 13) ); } [Fact] public void CS0162WRN_UnreachableCode_Filter_ConstantCondition3() { var text = @" using System; class Program { static void M() { int x; try { } catch (Exception) when (true) { Console.WriteLine(x); } } } "; // Unlike an unreachable code in if statement block we don't allow using // a variable that's not definitely assigned. The reason why we allow it in an if statement // is to make conditional compilation easier. Such scenario doesn't apply to filters. CreateCompilation(text).VerifyDiagnostics( // (10,33): warning CS7095: Filter expression is a constant 'true', consider removing the filter // catch (Exception) when (true) Diagnostic(ErrorCode.WRN_FilterIsConstantTrue, "true").WithLocation(10, 33), // (12,31): error CS0165: Use of unassigned local variable 'x' // Console.WriteLine(x); Diagnostic(ErrorCode.ERR_UseDefViolation, "x").WithArguments("x").WithLocation(12, 31) ); } [Fact] public void CS0160ERR_UnreachableCatch_Dynamic() { string source = @" using System; public class EG<T> : Exception { } public class A { public void M1() { try { Goo(); } catch (EG<object>) { } catch (EG<dynamic>) { } } void Goo() { } }"; CreateCompilation(source).VerifyDiagnostics( // (17,16): error CS0160: A previous catch clause already catches all exceptions of this or of a super type ('EG<object>') Diagnostic(ErrorCode.ERR_UnreachableCatch, "EG<dynamic>").WithArguments("EG<object>")); } [Fact] public void CS0160ERR_UnreachableCatch_TypeParameter() { string source = @" using System; public class EA : Exception { } public class EB : EA { } public class A<T> where T : EB { public void M1() { try { Goo(); } catch (EA) { } catch (T) { } } void Goo() { } }"; CreateCompilation(source).VerifyDiagnostics( // (18,16): error CS0160: A previous catch clause already catches all exceptions of this or of a super type ('EA') Diagnostic(ErrorCode.ERR_UnreachableCatch, "T").WithArguments("EA")); } [Fact] public void CS0160ERR_UnreachableCatch_TypeParameter_Dynamic1() { string source = @" using System; public class EG<T> : Exception { } public abstract class A<T> { public abstract void M<U>() where U : T; } public class B<V> : A<EG<dynamic>> where V : EG<object> { public override void M<U>() { try { Goo(); } catch (EG<dynamic>) { } catch (V) { } catch (U) { } } void Goo() { } } "; CreateCompilationWithMscorlib40AndSystemCore(source).VerifyDiagnostics( // (22,16): error CS0160: A previous catch clause already catches all exceptions of this or of a super type ('EG<dynamic>') Diagnostic(ErrorCode.ERR_UnreachableCatch, "V").WithArguments("EG<dynamic>"), // (25,16): error CS0160: A previous catch clause already catches all exceptions of this or of a super type ('EG<dynamic>') Diagnostic(ErrorCode.ERR_UnreachableCatch, "U").WithArguments("EG<dynamic>")); } [Fact] public void TypeParameter_DynamicConversions() { string source = @" using System; public class EG<T> : Exception { } public abstract class A<T> { public abstract void M<U>() where U : T; } public class B<V> : A<EG<dynamic>> where V : EG<object> { public override void M<U>() { V v = default(V); U u = default(U); // implicit EG<dynamic> egd = v; // implicit egd = u; //explicit v = (V)egd; //explicit u = (U)egd; //implicit array V[] va = null; EG<dynamic>[] egda = va; // explicit array va = (V[])egda; } void Goo() { } } "; CreateCompilationWithMscorlib40AndSystemCore(source).VerifyDiagnostics(); } [Fact] public void CS0160ERR_UnreachableCatch_TypeParameter_Dynamic2() { string source = @" using System; public class EG<T> : Exception { } public abstract class A<T> { public abstract void M<U>() where U : T; } public class B<V> : A<EG<dynamic>> where V : EG<object> { public override void M<U>() { try { Goo(); } catch (EG<object>) { } catch (V) { } catch (U) { } } void Goo() { } } "; CreateCompilationWithMscorlib40AndSystemCore(source).VerifyDiagnostics( // (22,16): error CS0160: A previous catch clause already catches all exceptions of this or of a super type ('EG<object>') Diagnostic(ErrorCode.ERR_UnreachableCatch, "V").WithArguments("EG<object>"), // (25,16): error CS0160: A previous catch clause already catches all exceptions of this or of a super type ('EG<object>') Diagnostic(ErrorCode.ERR_UnreachableCatch, "U").WithArguments("EG<object>")); } [Fact] public void CS0161ERR_ReturnExpected() { var text = @" public class Test { public static int Main() // CS0161 { int i = 10; if (i < 10) { return i; } else { // uncomment the following line to resolve // return 1; } } }"; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_ReturnExpected, Line = 4, Column = 22 } }); } [Fact] public void CS0163ERR_SwitchFallThrough() { var text = @" public class MyClass { public static void Main() { int i = 0; switch (i) // CS0163 { case 1: i++; // uncomment one of the following lines to resolve // return; // break; // goto case 3; case 2: i++; return; case 3: i = 0; return; } } }"; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_SwitchFallThrough, Line = 10, Column = 10 } }); } [Fact] public void CS0165ERR_UseDefViolation01() { var text = @" class MyClass { public int i; } class MyClass2 { public static void Main(string [] args) { int i, j; if (args[0] == ""test"") { i = 0; } /* // to resolve, either initialize the variables when declared // or provide for logic to initialize them, as follows: else { i = 1; } */ j = i; // CS0165, i might be uninitialized MyClass myClass; myClass.i = 0; // CS0165 // use new as follows // MyClass myClass = new MyClass(); // myClass.i = 0; i = j; } }"; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_UseDefViolation, Line = 26, Column = 11 } , new ErrorDescription { Code = (int)ErrorCode.ERR_UseDefViolation, Line = 29, Column = 7 }}); } [Fact] public void CS0165ERR_UseDefViolation02() { CreateCompilation( @"class C { static void M(int m) { int v; for (int i = 0; i < m; ++i) { v = 0; } M(v); int w; for (; ; ) { w = 0; break; } M(w); for (int x; x < 1; ++x) { } for (int y; m < 1; ++y) { } for (int z; ; ) { M(z); } } } ") .VerifyDiagnostics( Diagnostic(ErrorCode.ERR_UseDefViolation, "v").WithArguments("v").WithLocation(10, 11), Diagnostic(ErrorCode.ERR_UseDefViolation, "x").WithArguments("x").WithLocation(18, 21), Diagnostic(ErrorCode.ERR_UseDefViolation, "y").WithArguments("y").WithLocation(21, 30), Diagnostic(ErrorCode.ERR_UseDefViolation, "z").WithArguments("z").WithLocation(26, 15)); } [Fact] public void CS0165ERR_UseDefViolation03() { CreateCompilation( @"class C { static int F() { return 0; } static void M0() { int a, b, c, d; for (a = 1; (b = F()) < 2; c = 3) { d = 4; } if (a == 0) { } if (b == 0) { } if (c == 0) { } // Use of unassigned 'c' if (d == 0) { } // Use of unassigned 'd' } static void M1() { int x, y; for (x = 0; (y = x) < 10; ) { } if (y == 0) { } // no error } static void M2() { int x, y; for (x = 0; x < 10; y = x) { } if (y == 0) { } // Use of unassigned 'y' } static void M3() { int x, y; for (x = 0; x < 10; ) { y = x; } if (y == 0) { } // Use of unassigned 'y' } static void M4() { int x, y; for (y = x; (x = 0) < 10; ) { } // Use of unassigned 'x' if (y == 0) { } // no error } static void M5() { int x, y; for (; (x = 0) < 10; y = x) { } if (y == 0) { } // Use of unassigned 'y' } static void M6() { int x, y; for (; (x = 0) < 10; ) { y = x; } if (y == 0) { } // Use of unassigned 'y' } static void M7() { int x, y; for (y = x; F() < 10; x = 0) { } // Use of unassigned 'x' if (y == 0) { } // no error } static void M8() { int x, y; for (; (y = x) < 10; x = 0) { } // Use of unassigned 'x' if (y == 0) { } // no error } static void M9() { int x, y; for (; F() < 10; x = 0) { y = x; } // Use of unassigned 'x' if (y == 0) { } // no error } static void M10() { int x, y; for (y = x; F() < 10; ) { x = 0; } // Use of unassigned 'x' if (y == 0) { } // no error } static void M11() { int x, y; for (; F() < 10; y = x) { x = 0; } if (y == 0) { } // Use of unassigned 'y' } } ") .VerifyDiagnostics( Diagnostic(ErrorCode.ERR_UseDefViolation, "c").WithArguments("c").WithLocation(13, 13), Diagnostic(ErrorCode.ERR_UseDefViolation, "d").WithArguments("d").WithLocation(14, 13), Diagnostic(ErrorCode.ERR_UseDefViolation, "y").WithArguments("y").WithLocation(26, 13), Diagnostic(ErrorCode.ERR_UseDefViolation, "y").WithArguments("y").WithLocation(32, 13), Diagnostic(ErrorCode.ERR_UseDefViolation, "x").WithArguments("x").WithLocation(37, 18), Diagnostic(ErrorCode.ERR_UseDefViolation, "y").WithArguments("y").WithLocation(44, 13), Diagnostic(ErrorCode.ERR_UseDefViolation, "y").WithArguments("y").WithLocation(50, 13), Diagnostic(ErrorCode.ERR_UseDefViolation, "x").WithArguments("x").WithLocation(55, 18), Diagnostic(ErrorCode.ERR_UseDefViolation, "x").WithArguments("x").WithLocation(61, 21), Diagnostic(ErrorCode.ERR_UseDefViolation, "x").WithArguments("x").WithLocation(67, 39), Diagnostic(ErrorCode.ERR_UseDefViolation, "y").WithArguments("y").WithLocation(68, 13), Diagnostic(ErrorCode.ERR_UseDefViolation, "x").WithArguments("x").WithLocation(73, 18), Diagnostic(ErrorCode.ERR_UseDefViolation, "y").WithArguments("y").WithLocation(80, 13)); } [Fact] public void CS0165ERR_UseDefViolation04() { CreateCompilation( @"class C { static int M() { int x, y, z; try { x = 0; y = 1; } catch (System.Exception) { x = 1; } finally { z = 1; } return (x + y + z); } }") .VerifyDiagnostics( Diagnostic(ErrorCode.ERR_UseDefViolation, "y").WithArguments("y").WithLocation(19, 21)); } [Fact] public void CS0165ERR_UseDefViolation05() { // This is a "negative" test case; we should *not* be producing a "use of unassigned // local variable" error here. In an earlier revision we were doing so because we were // losing the information about the first argument being "out" when the bad call node // was created. Later flow analysis then did not know that "x" need not be assigned // before it was used, and we'd produce a wrong error. CreateCompilation( @"class C { static int N(out int q) { q = 1; return 2;} static void M() { int x = N(out x, 123); } } ") .VerifyDiagnostics( Diagnostic(ErrorCode.ERR_BadArgCount, "N").WithArguments("N", "2")); } [WorkItem(540860, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540860")] [Fact] public void CS0165ERR_UseDefViolation06() { // Should not generate "unassigned local variable" for struct. CreateCompilation( @"struct S { public void M() { } } class C { void M() { S s; s.M(); } }") .VerifyDiagnostics(); } [Fact] public void CS0165ERR_UseDefViolation07() { // Make sure flow analysis is hooked up for indexers CreateCompilation( @"struct S { public int this[int x] { get { return 0; } } } class C { public int this[int x] { get { return 0; } } } class Test { static void Main() { int unassigned1; int unassigned2; int sink; C c; sink = c[1]; //CS0165 c = new C(); sink = c[1]; //fine sink = c[unassigned1]; //CS0165 S s; sink = s[1]; //fine - struct with no fields s = new S(); sink = s[1]; //fine sink = s[unassigned2]; //CS0165 } }") .VerifyDiagnostics( // (18,16): error CS0165: Use of unassigned local variable 'c' Diagnostic(ErrorCode.ERR_UseDefViolation, "c").WithArguments("c"), // (22,18): error CS0165: Use of unassigned local variable 'unassigned1' Diagnostic(ErrorCode.ERR_UseDefViolation, "unassigned1").WithArguments("unassigned1"), // (29,18): error CS0165: Use of unassigned local variable 'unassigned2' Diagnostic(ErrorCode.ERR_UseDefViolation, "unassigned2").WithArguments("unassigned2")); } [WorkItem(3402, "DevDiv_Projects/Roslyn")] [Fact] public void CS0170ERR_UseDefViolationField() { var text = @" public struct error { public int i; } public class MyClass { public static void Main() { error e; // uncomment the next line to resolve this error // e.i = 0; System.Console.WriteLine( e.i ); // CS0170 because //e.i was never assigned } }"; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_UseDefViolationField, Line = 14, Column = 33 } }); } [Fact] public void CS0171ERR_UnassignedThis() { var text = @" struct MyStruct { MyStruct(int initField) // CS0171 { // i = initField; // uncomment this line to resolve this error } public int i; } class MyClass { public static void Main() { MyStruct aStruct = new MyStruct(); } }"; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (4,4): error CS0171: Field 'MyStruct.i' must be fully assigned before control is returned to the caller // MyStruct(int initField) // CS0171 Diagnostic(ErrorCode.ERR_UnassignedThis, "MyStruct").WithArguments("MyStruct.i"), // (15,16): warning CS0219: The variable 'aStruct' is assigned but its value is never used // MyStruct aStruct = new MyStruct(); Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "aStruct").WithArguments("aStruct"), // (8,15): warning CS0649: Field 'MyStruct.i' is never assigned to, and will always have its default value 0 // public int i; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "i").WithArguments("MyStruct.i", "0") ); } [Fact] public void FieldAssignedInReferencedConstructor() { var text = @"struct S { private readonly object _x; S(object o) { _x = o; } S(object x, object y) : this(x ?? y) { } }"; var comp = CreateCompilation(text); comp.VerifyDiagnostics(); // No CS0171 for S._x } [Fact()] public void CS0172ERR_AmbigQM() { var text = @" public class Square { public class Circle { public static implicit operator Circle(Square aa) { return null; } public static implicit operator Square(Circle aa) { return null; } } public static void Main() { Circle aa = new Circle(); Square ii = new Square(); var o1 = (1 == 1) ? aa : ii; // CS0172 object o2 = (1 == 1) ? aa : ii; // CS8652 } }"; CreateCompilation(text, parseOptions: TestOptions.Regular8).VerifyDiagnostics( // (21,16): error CS0172: Type of conditional expression cannot be determined because 'Square.Circle' and 'Square' implicitly convert to one another // var o1 = (1 == 1) ? aa : ii; // CS0172 Diagnostic(ErrorCode.ERR_AmbigQM, "(1 == 1) ? aa : ii").WithArguments("Square.Circle", "Square").WithLocation(21, 16), // (22,19): error CS8957: Conditional expression is not valid in language version 8.0 because a common type was not found between 'Square.Circle' and 'Square'. To use a target-typed conversion, upgrade to language version 9.0 or greater. // object o2 = (1 == 1) ? aa : ii; // CS8652 Diagnostic(ErrorCode.ERR_NoImplicitConvTargetTypedConditional, "(1 == 1) ? aa : ii").WithArguments("8.0", "Square.Circle", "Square", "9.0").WithLocation(22, 19) ); } [Fact] public void CS0173ERR_InvalidQM() { var text = @" public class C {} public class A {} public class MyClass { public static void F(bool b) { A a = new A(); C c = new C(); var o = b ? a : c; // CS0173 } public static void Main() { F(true); } }"; CreateCompilation(text).VerifyDiagnostics( // (11,15): error CS0173: Type of conditional expression cannot be determined because there is no implicit conversion between 'A' and 'C' // var o = b ? a : c; // CS0173 Diagnostic(ErrorCode.ERR_InvalidQM, "b ? a : c").WithArguments("A", "C").WithLocation(11, 15) ); } [WorkItem(528331, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528331")] [Fact] public void CS0173ERR_InvalidQM_FuncCall() { var text = @" class Program { static void Main(string[] args) { var s = true ? System.Console.WriteLine(0) : System.Console.WriteLine(1); } }"; CreateCompilation(text). VerifyDiagnostics(Diagnostic(ErrorCode.ERR_ImplicitlyTypedVariableAssignedBadValue, "s = true ? System.Console.WriteLine(0) : System.Console.WriteLine(1)").WithArguments("void").WithLocation(6, 13)); } [Fact] public void CS0173ERR_InvalidQM_GeneralType() { var text = @" class Program { static void Main(string[] args) { A<string> a = new A<string>(); A<int> b = new A<int>(); var o = 1 > 2 ? a : b; // Invalid, Can't implicit convert } } class A<T> { }"; CreateCompilation(text).VerifyDiagnostics( // (8,17): error CS0173: Type of conditional expression cannot be determined because there is no implicit conversion between 'A<string>' and 'A<int>' // var o = 1 > 2 ? a : b; // Invalid, Can't implicit convert Diagnostic(ErrorCode.ERR_InvalidQM, "1 > 2 ? a : b").WithArguments("A<string>", "A<int>").WithLocation(8, 17) ); } [WorkItem(540902, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540902")] [Fact] public void CS0173ERR_InvalidQM_foreach() { var text = @" public class Test { public static void Main() { S[] x = null; foreach (S x in true ? x : 1) // Dev10: CS0173 ONLY { } C[] y= null; foreach (C c in false ? 1 : y) // Dev10: CS0173 ONLY { } } } struct S { } class C { } "; CreateCompilation(text).VerifyDiagnostics( // (7,25): error CS0173: Type of conditional expression cannot be determined because there is no implicit conversion between 'S[]' and 'int' // foreach (S x in true ? x : 1) // Dev10: CS0173 ONLY Diagnostic(ErrorCode.ERR_InvalidQM, "true ? x : 1").WithArguments("S[]", "int"), // (7,20): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // foreach (S x in true ? x : 1) // Dev10: CS0173 ONLY Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x"), // (11,25): error CS0173: Type of conditional expression cannot be determined because there is no implicit conversion between 'int' and 'C[]' // foreach (C c in false ? 1 : y) // Dev10: CS0173 ONLY Diagnostic(ErrorCode.ERR_InvalidQM, "false ? 1 : y").WithArguments("int", "C[]") ); } // /// Scenarios? // [Fact] // public void CS0174ERR_NoBaseClass() // { // var text = @" // "; // CreateCompilationWithMscorlib(text).VerifyDiagnostics(Diagnostic(ErrorCode.ERR_NoBaseClass, "?")); // } [WorkItem(543360, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543360")] [Fact()] public void CS0175ERR_BaseIllegal() { var text = @" using System; class Base { public int TestInt = 0; } class MyClass : Base { public void BaseTest() { Console.WriteLine(base); // CS0175 base = 9; // CS0175 } } "; CreateCompilation(text).VerifyDiagnostics( // (11,27): error CS0175: Use of keyword 'base' is not valid in this context Diagnostic(ErrorCode.ERR_BaseIllegal, "base").WithLocation(12, 27), // (12,9): error CS0175: Use of keyword 'base' is not valid in this context Diagnostic(ErrorCode.ERR_BaseIllegal, "base").WithLocation(13, 9) ); } [WorkItem(528624, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528624")] [Fact()] public void CS0175ERR_BaseIllegal_02() { var text = @" using System.Collections.Generic; class MyClass : List<int> { public void BaseTest() { var x = from i in base select i; } } "; CreateCompilation(text).VerifyDiagnostics( // (8,27): error CS0175: Use of keyword 'base' is not valid in this context // var x = from i in base select i; Diagnostic(ErrorCode.ERR_BaseIllegal, "base") ); } [Fact] public void CS0176ERR_ObjectProhibited01() { var source = @" class A { class B { static void Method() { } void M() { this.Method(); } } }"; CreateCompilation(source).VerifyDiagnostics( // (9,13): error CS0176: Member 'A.B.Method()' cannot be accessed with an instance reference; qualify it with a type name instead // this.Method(); Diagnostic(ErrorCode.ERR_ObjectProhibited, "this.Method").WithArguments("A.B.Method()").WithLocation(9, 13) ); } [Fact] public void CS0176ERR_ObjectProhibited02() { var source = @" class C { static object field; static object Property { get; set; } void M(C c) { Property = field; // no error C.Property = C.field; // no error this.field = this.Property; c.Property = c.field; } } "; CreateCompilation(source).VerifyDiagnostics( // (9,9): error CS0176: Member 'C.field' cannot be accessed with an instance reference; qualify it with a type name instead // this.field = this.Property; Diagnostic(ErrorCode.ERR_ObjectProhibited, "this.field").WithArguments("C.field"), // (9,22): error CS0176: Member 'C.Property' cannot be accessed with an instance reference; qualify it with a type name instead // this.field = this.Property; Diagnostic(ErrorCode.ERR_ObjectProhibited, "this.Property").WithArguments("C.Property"), // (10,9): error CS0176: Member 'C.Property' cannot be accessed with an instance reference; qualify it with a type name instead // c.Property = c.field; Diagnostic(ErrorCode.ERR_ObjectProhibited, "c.Property").WithArguments("C.Property"), // (10,22): error CS0176: Member 'C.field' cannot be accessed with an instance reference; qualify it with a type name instead // c.Property = c.field; Diagnostic(ErrorCode.ERR_ObjectProhibited, "c.field").WithArguments("C.field") ); } [Fact] public void CS0176ERR_ObjectProhibited03() { var source = @"class A { internal static object F; } class B<T> where T : A { static void M(T t) { object q = t.F; t.ReferenceEquals(q, null); } }"; CreateCompilation(source).VerifyDiagnostics( // (9,20): error CS0176: Member 'A.F' cannot be accessed with an instance reference; qualify it with a type name instead // object q = t.F; Diagnostic(ErrorCode.ERR_ObjectProhibited, "t.F").WithArguments("A.F").WithLocation(9, 20), // (10,9): error CS0176: Member 'object.ReferenceEquals(object, object)' cannot be accessed with an instance reference; qualify it with a type name instead // t.ReferenceEquals(q, null); Diagnostic(ErrorCode.ERR_ObjectProhibited, "t.ReferenceEquals").WithArguments("object.ReferenceEquals(object, object)").WithLocation(10, 9), // (3,28): warning CS0649: Field 'A.F' is never assigned to, and will always have its default value null // internal static object F; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "F").WithArguments("A.F", "null").WithLocation(3, 28)); } [WorkItem(543361, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543361")] [Fact] public void CS0176ERR_ObjectProhibited04() { var source = @" public delegate void D(); class Test { public event D D; public void TestIdenticalEventName() { D.CreateDelegate(null, null, null); // CS0176 } } "; CreateCompilation(source, targetFramework: TargetFramework.Mscorlib45).VerifyDiagnostics( // (9,9): error CS0176: Member 'Delegate.CreateDelegate(Type, object, string)' cannot be accessed with an instance reference; qualify it with a type name instead // D.CreateDelegate(null, null, null); // CS0176 Diagnostic(ErrorCode.ERR_ObjectProhibited, "D.CreateDelegate").WithArguments("System.Delegate.CreateDelegate(System.Type, object, string)").WithLocation(9, 9) ); } // Identical to CS0176ERR_ObjectProhibited04, but with event keyword removed (i.e. field instead of field-like event). [WorkItem(543361, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543361")] [Fact] public void CS0176ERR_ObjectProhibited05() { var source = @" public delegate void D(); class Test { public D D; public void TestIdenticalEventName() { D.CreateDelegate(null, null, null); // CS0176 } } "; CreateCompilation(source).VerifyDiagnostics( // (5,14): warning CS0649: Field 'Test.D' is never assigned to, and will always have its default value null // public D D; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "D").WithArguments("Test.D", "null") ); } [Fact] public void CS0177ERR_ParamUnassigned01() { var text = @"class C { static void M(out int x, out int y, out int z) { try { x = 0; y = 1; } catch (System.Exception) { x = 1; } finally { z = 1; } } }"; CreateCompilation(text).VerifyDiagnostics( Diagnostic(ErrorCode.ERR_ParamUnassigned, "M").WithArguments("y").WithLocation(3, 17)); } [WorkItem(528243, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528243")] [Fact] public void CS0177ERR_ParamUnassigned02() { var text = @"class C { static bool P { get { return false; } } static object M(out object x) { if (P) { object o = P ? M(out x) : null; return o; } return P ? null : M(out x); } }"; CreateCompilation(text).VerifyDiagnostics( // (9,13): error CS0177: The out parameter 'x' must be assigned to before control leaves the current method // return o; Diagnostic(ErrorCode.ERR_ParamUnassigned, "return o;").WithArguments("x").WithLocation(9, 13), // (11,9): error CS0177: The out parameter 'x' must be assigned to before control leaves the current method // return P ? null : M(out x); Diagnostic(ErrorCode.ERR_ParamUnassigned, "return P ? null : M(out x);").WithArguments("x").WithLocation(11, 9)); } [Fact] public void CS0185ERR_LockNeedsReference() { var text = @" public class MainClass { public static void Main () { lock (1) // CS0185 // try the following lines instead // MainClass x = new MainClass(); // lock(x) { } } }"; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_LockNeedsReference, Line = 6, Column = 15 } }); } [Fact] public void CS0186ERR_NullNotValid() { var text = @" using System.Collections; class MyClass { static void Main() { // Each of the following lines generates CS0186: foreach (int i in null) { } // CS0186 foreach (int i in (IEnumerable)null) { }; // CS0186 } }"; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_NullNotValid, Line = 9, Column = 27 } , new ErrorDescription { Code = (int)ErrorCode.ERR_NullNotValid, Line = 10, Column = 27 }}); } [Fact] public void CS0186ERR_NullNotValid02() { var text = @" public class Test { public static void Main(string[] args) { foreach (var x in default(int[])) { } } } "; CreateCompilation(text). VerifyDiagnostics(Diagnostic(ErrorCode.ERR_NullNotValid, "default(int[])")); } [WorkItem(540983, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540983")] [Fact] public void CS0188ERR_UseDefViolationThis() { var text = @" namespace MyNamespace { class MyClass { struct S { public int a; void Goo() { } S(int i) { // a = i; Goo(); // CS0188 } } public static void Main() { } } }"; CreateCompilation(text). VerifyDiagnostics( // (17,17): error CS0188: The 'this' object cannot be used before all of its fields are assigned to // Goo(); // CS0188 Diagnostic(ErrorCode.ERR_UseDefViolationThis, "Goo").WithArguments("this"), // (8,24): warning CS0649: Field 'MyNamespace.MyClass.S.a' is never assigned to, and will always have its default value 0 // public int a; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "a").WithArguments("MyNamespace.MyClass.S.a", "0")); } [Fact, WorkItem(579533, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/579533"), WorkItem(864605, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/864605")] public void CS0188ERR_UseDefViolationThis_MethodGroupInIsOperator_ImplicitReceiver() { string source = @" using System; struct S { int value; public S(int v) { var b1 = F is Action; value = v; } void F() { } }"; CreateCompilationWithMscorlib40AndSystemCore(source).VerifyDiagnostics( // (10,18): error CS0837: The first operand of an 'is' or 'as' operator may not be a lambda expression, anonymous method, or method group. Diagnostic(ErrorCode.ERR_LambdaInIsAs, "F is Action").WithLocation(10, 18), // (10,18): error CS0188: The 'this' object cannot be used before all of its fields are assigned to Diagnostic(ErrorCode.ERR_UseDefViolationThis, "F").WithArguments("this")); } [Fact, WorkItem(579533, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/579533"), WorkItem(864605, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/864605")] public void CS0188ERR_UseDefViolationThis_MethodGroupInIsOperator_ExplicitReceiver() { string source = @" using System; struct S { int value; public S(int v) { var b1 = this.F is Action; value = v; } void F() { } }"; CreateCompilationWithMscorlib40AndSystemCore(source).VerifyDiagnostics( // (10,18): error CS0837: The first operand of an 'is' or 'as' operator may not be a lambda expression, anonymous method, or method group. // var b1 = this.F is Action; Diagnostic(ErrorCode.ERR_LambdaInIsAs, "this.F is Action").WithLocation(10, 18), // (10,18): error CS0188: The 'this' object cannot be used before all of its fields are assigned to // var b1 = this.F is Action; Diagnostic(ErrorCode.ERR_UseDefViolationThis, "this").WithArguments("this")); } [Fact, WorkItem(579533, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/579533")] public void CS0188ERR_UseDefViolationThis_ImplicitReceiverInDynamic() { string source = @" using System; struct S { dynamic value; public S(dynamic d) { /*this.*/ Add(d); throw new NotImplementedException(); } void Add(int value) { this.value += value; } } "; CreateCompilationWithMscorlib40AndSystemCore(source).VerifyDiagnostics( // (10,19): error CS0188: The 'this' object cannot be used before all of its fields are assigned to Diagnostic(ErrorCode.ERR_UseDefViolationThis, "Add").WithArguments("this")); } [Fact, WorkItem(579533, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/579533")] public void CS0188ERR_UseDefViolationThis_ExplicitReceiverInDynamic() { string source = @" using System; struct S { dynamic value; public S(dynamic d) { this.Add(d); throw new NotImplementedException(); } void Add(int value) { this.value += value; } } "; CreateCompilationWithMscorlib40AndSystemCore(source).VerifyDiagnostics( // (10,9): error CS0188: The 'this' object cannot be used before all of its fields are assigned to Diagnostic(ErrorCode.ERR_UseDefViolationThis, "this").WithArguments("this")); } [Fact] public void CS0190ERR_ArgsInvalid() { string source = @" using System; public class C { static void M(__arglist) { ArgIterator ai = new ArgIterator(__arglist); } static void Main() { M(__arglist); } }"; var comp = CreateCompilation(source, targetFramework: TargetFramework.Mscorlib45); comp.VerifyDiagnostics( // (11,7): error CS0190: The __arglist construct is valid only within a variable argument method // M(__arglist); Diagnostic(ErrorCode.ERR_ArgsInvalid, "__arglist") ); } [Fact] public void CS4013ERR_SpecialByRefInLambda01() { // Note that the native compiler does *not* produce an error when you illegally // use __arglist inside a lambda, oddly enough. Roslyn does. string source = @" using System; using System.Linq; public class C { delegate int D(RuntimeArgumentHandle r); static void M(__arglist) { D f = null; f = x=>f(__arglist); f = delegate { return f(__arglist); }; var q = from x in new int[10] select f(__arglist); } static void Main() { } }"; var comp = CreateCompilationWithMscorlib40AndSystemCore(source); comp.VerifyDiagnostics( // (10,14): error CS4013: Instance of type 'System.RuntimeArgumentHandle' cannot be used inside an anonymous function, query expression, iterator block or async method // f = x=>f(__arglist); Diagnostic(ErrorCode.ERR_SpecialByRefInLambda, "__arglist").WithArguments("System.RuntimeArgumentHandle"), // (11,29): error CS4013: Instance of type 'System.RuntimeArgumentHandle' cannot be used inside an anonymous function, query expression, iterator block or async method // f = delegate { return f(__arglist); }; Diagnostic(ErrorCode.ERR_SpecialByRefInLambda, "__arglist").WithArguments("System.RuntimeArgumentHandle"), // (12,44): error CS4013: Instance of type 'System.RuntimeArgumentHandle' cannot be used inside an anonymous function, query expression, iterator block or async method // var q = from x in new int[10] select f(__arglist); Diagnostic(ErrorCode.ERR_SpecialByRefInLambda, "__arglist").WithArguments("System.RuntimeArgumentHandle") ); } [Fact] public void CS4013ERR_SpecialByRefInLambda02() { string source = @" using System; public class C { static void M(__arglist) { RuntimeArgumentHandle h = __arglist; Action action = ()=> { RuntimeArgumentHandle h2 = h; // Bad use of h ArgIterator args1 = new ArgIterator(h); // Bad use of h RuntimeArgumentHandle h3 = h2; // no error; does not create field ArgIterator args2 = new ArgIterator(h2); // no error; does not create field }; } static void Main() { } }"; CreateCompilationWithMscorlib45(source).VerifyEmitDiagnostics( // (10,34): error CS4013: Instance of type 'System.RuntimeArgumentHandle' cannot be used inside an anonymous function, query expression, iterator block or async method // RuntimeArgumentHandle h2 = h; // Bad use of h Diagnostic(ErrorCode.ERR_SpecialByRefInLambda, "h").WithArguments("System.RuntimeArgumentHandle"), // (11,43): error CS4013: Instance of type 'System.RuntimeArgumentHandle' cannot be used inside an anonymous function, query expression, iterator block or async method // ArgIterator args1 = new ArgIterator(h); // Bad use of h Diagnostic(ErrorCode.ERR_SpecialByRefInLambda, "h").WithArguments("System.RuntimeArgumentHandle")); } [Fact] public void CS4013ERR_SpecialByRefInLambda03() { string source = @" using System; using System.Collections.Generic; public class C { static void N(RuntimeArgumentHandle x) {} static IEnumerable<int> M(RuntimeArgumentHandle h1) // Error: hoisted to field { N(h1); yield return 1; RuntimeArgumentHandle h2 = default(RuntimeArgumentHandle); yield return 2; N(h2); // Error: hoisted to field yield return 3; RuntimeArgumentHandle h3 = default(RuntimeArgumentHandle); N(h3); // No error; we don't need to hoist this one to a field } static void Main() { } }"; CreateCompilation(source).Emit(new System.IO.MemoryStream()).Diagnostics .Verify( // (7,51): error CS4013: Instance of type 'System.RuntimeArgumentHandle' cannot be used inside an anonymous function, query expression, iterator block or async method // static IEnumerable<int> M(RuntimeArgumentHandle h1) // Error: hoisted to field Diagnostic(ErrorCode.ERR_SpecialByRefInLambda, "h1").WithArguments("System.RuntimeArgumentHandle"), // (13,7): error CS4013: Instance of type 'System.RuntimeArgumentHandle' cannot be used inside an anonymous function, query expression, iterator block or async method // N(h2); // Error: hoisted to field Diagnostic(ErrorCode.ERR_SpecialByRefInLambda, "h2").WithArguments("System.RuntimeArgumentHandle") ); } [Fact, WorkItem(538008, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538008")] public void CS0191ERR_AssgReadonly() { var source = @"class MyClass { public readonly int TestInt = 6; // OK to assign to readonly field in declaration public MyClass() { TestInt = 11; // OK to assign to readonly field in constructor TestInt = 12; // OK to assign to readonly field multiple times in constructor this.TestInt = 13; // OK to assign with explicit this receiver MyClass t = this; t.TestInt = 14; // CS0191 - we can't be sure that the receiver is this } public void TestReadOnly() { TestInt = 19; // CS0191 } public static void Main() { } } class MyDerived : MyClass { MyDerived() { TestInt = 15; // CS0191 - not in declaring class } } "; CreateCompilation(source).VerifyDiagnostics( // (28,9): error CS0191: A readonly field cannot be assigned to (except in the constructor of the class in which the field is defined or a variable initializer)) // TestInt = 15; // CS0191 - not in declaring class Diagnostic(ErrorCode.ERR_AssgReadonly, "TestInt").WithLocation(28, 9), // (11,9): error CS0191: A readonly field cannot be assigned to (except in the constructor of the class in which the field is defined or a variable initializer)) // t.TestInt = 14; // CS0191 - we can't be sure that the receiver is this Diagnostic(ErrorCode.ERR_AssgReadonly, "t.TestInt").WithLocation(11, 9), // (16,9): error CS0191: A readonly field cannot be assigned to (except in the constructor of the class in which the field is defined or a variable initializer)) // TestInt = 19; // CS0191 Diagnostic(ErrorCode.ERR_AssgReadonly, "TestInt").WithLocation(16, 9)); } [WorkItem(538009, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538009")] [Fact] public void CS0192ERR_RefReadonly() { var text = @" class MyClass { public readonly int TestInt = 6; static void TestMethod(ref int testInt) { testInt = 0; } MyClass() { TestMethod(ref TestInt); // OK } public void PassReadOnlyRef() { TestMethod(ref TestInt); // CS0192 } public static void Main() { } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_RefReadonly, Line = 17, Column = 24 } }); } [Fact] public void CS0193ERR_PtrExpected() { var text = @" using System; public struct Age { public int AgeYears; public int AgeMonths; public int AgeDays; } public class MyClass { public static void SetAge(ref Age anAge, int years, int months, int days) { anAge->Months = 3; // CS0193, anAge is not a pointer // try the following line instead // anAge.AgeMonths = 3; } public static void Main() { Age MyAge = new Age(); Console.WriteLine(MyAge.AgeMonths); SetAge(ref MyAge, 22, 4, 15); Console.WriteLine(MyAge.AgeMonths); } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_PtrExpected, Line = 15, Column = 7 } }); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void CS0196ERR_PtrIndexSingle() { var text = @" unsafe public class MyClass { public static void Main () { int *i = null; int j = 0; j = i[1,2]; // CS0196 // try the following line instead // j = i[1]; } }"; var compilation = CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (8,11): error CS0196: A pointer must be indexed by only one value // j = i[1,2]; // CS0196 Diagnostic(ErrorCode.ERR_PtrIndexSingle, "i[1,2]")); var tree = compilation.SyntaxTrees.Single(); var node = tree.GetRoot().DescendantNodes().OfType<ElementAccessExpressionSyntax>().First(); Assert.Equal("i[1,2]", node.ToString()); compilation.VerifyOperationTree(node, expectedOperationTree: @" IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'i[1,2]') Children(2): ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32*, IsInvalid) (Syntax: 'i') IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid, IsImplicit) (Syntax: 'i[1,2]') Children(2): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid) (Syntax: '1') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2, IsInvalid) (Syntax: '2') "); } [Fact] public void CS0198ERR_AssgReadonlyStatic() { var text = @" public class MyClass { public static readonly int TestInt = 6; static MyClass() { TestInt = 7; TestInt = 8; MyClass.TestInt = 7; } public MyClass() { TestInt = 11; // CS0198, constructor is not static and readonly field is } private void InstanceMethod() { TestInt = 12; // CS0198 } private void StaticMethod() { TestInt = 13; // CS0198 } public static void Main() { } } class MyDerived : MyClass { static MyDerived() { MyClass.TestInt = 14; // CS0198, not in declaring class } }"; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_AssgReadonlyStatic, Line = 15, Column = 7 }, new ErrorDescription { Code = (int)ErrorCode.ERR_AssgReadonlyStatic, Line = 20, Column = 8 }, new ErrorDescription { Code = (int)ErrorCode.ERR_AssgReadonlyStatic, Line = 25, Column = 8 }, new ErrorDescription { Code = (int)ErrorCode.ERR_AssgReadonlyStatic, Line = 37, Column = 9 }, }); } [Fact, WorkItem(990, "https://github.com/dotnet/roslyn/issues/990")] public void WriteOfReadonlyStaticMemberOfAnotherInstantiation01() { var text = @"public static class Goo<T> { static Goo() { Goo<int>.X = 1; Goo<int>.Y = 2; Goo<T>.Y = 3; } public static readonly int X; public static int Y { get; } }"; CreateCompilation(text, options: TestOptions.ReleaseDll).VerifyDiagnostics( // (6,9): error CS0200: Property or indexer 'Goo<int>.Y' cannot be assigned to -- it is read only // Goo<int>.Y = 2; Diagnostic(ErrorCode.ERR_AssgReadonlyProp, "Goo<int>.Y").WithArguments("Goo<int>.Y").WithLocation(6, 9) ); CreateCompilation(text, options: TestOptions.ReleaseDll, parseOptions: TestOptions.Regular.WithStrictFeature()).VerifyDiagnostics( // (5,9): error CS0198: A static readonly field cannot be assigned to (except in a static constructor or a variable initializer) // Goo<int>.X = 1; Diagnostic(ErrorCode.ERR_AssgReadonlyStatic, "Goo<int>.X").WithLocation(5, 9), // (6,9): error CS0200: Property or indexer 'Goo<int>.Y' cannot be assigned to -- it is read only // Goo<int>.Y = 2; Diagnostic(ErrorCode.ERR_AssgReadonlyProp, "Goo<int>.Y").WithArguments("Goo<int>.Y").WithLocation(6, 9) ); } [Fact, WorkItem(990, "https://github.com/dotnet/roslyn/issues/990")] public void WriteOfReadonlyStaticMemberOfAnotherInstantiation02() { var text = @"using System; using System.Threading; class Program { static void Main(string[] args) { Console.WriteLine(Goo<long>.x); Console.WriteLine(Goo<int>.x); Console.WriteLine(Goo<string>.x); Console.WriteLine(Goo<int>.x); } } public static class Goo<T> { static Goo() { Console.WriteLine(""initializing for "" + typeof(T)); Goo<int>.x = typeof(T).Name; } public static readonly string x; }"; var expectedOutput = @"initializing for System.Int64 initializing for System.Int32 Int64 initializing for System.String String "; // Although we accept this nasty code, it will not verify. CompileAndVerify(text, expectedOutput: expectedOutput, verify: Verification.Fails); } [Fact] public void CS0199ERR_RefReadonlyStatic() { var text = @" class MyClass { public static readonly int TestInt = 6; static void TestMethod(ref int testInt) { testInt = 0; } MyClass() { TestMethod(ref TestInt); // CS0199, TestInt is static } public static void Main() { } }"; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_RefReadonlyStatic, Line = 13, Column = 24 } }); } [Fact] public void CS0200ERR_AssgReadonlyProp01() { var source = @"abstract class A { internal static A P { get { return null; } } internal object Q { get; set; } public abstract object R { get; } } class B : A { public override object R { get { return null; } } } class Program { static void M(B b) { B.P.Q = null; B.P = null; // CS0200 b.R = null; // CS0200 } }"; CreateCompilation(source).VerifyDiagnostics( // (16,9): error CS0200: Property or indexer 'A.P' cannot be assigned to -- it is read only Diagnostic(ErrorCode.ERR_AssgReadonlyProp, "B.P").WithArguments("A.P").WithLocation(16, 9), // (17,9): error CS0200: Property or indexer 'B.R' cannot be assigned to -- it is read only Diagnostic(ErrorCode.ERR_AssgReadonlyProp, "b.R").WithArguments("B.R").WithLocation(17, 9)); } [Fact] public void CS0200ERR_AssgReadonlyProp02() { var source = @"class A { public virtual A P { get; set; } public A Q { get { return null; } } } class B : A { public override A P { get { return null; } } } class Program { static void M(B b) { b.P = null; b.Q = null; // CS0200 b.Q.P = null; b.P.Q = null; // CS0200 } }"; CreateCompilation(source).VerifyDiagnostics( // (15,9): error CS0200: Property or indexer 'A.Q' cannot be assigned to -- it is read only Diagnostic(ErrorCode.ERR_AssgReadonlyProp, "b.Q").WithArguments("A.Q").WithLocation(15, 9), // (17,9): error CS0200: Property or indexer 'A.Q' cannot be assigned to -- it is read only Diagnostic(ErrorCode.ERR_AssgReadonlyProp, "b.P.Q").WithArguments("A.Q").WithLocation(17, 9)); } [Fact] public void CS0200ERR_AssgReadonlyProp03() { var source = @"class C { static int P { get { return 0; } } int Q { get { return 0; } } static void M(C c) { ++P; ++c.Q; } }"; CreateCompilation(source).VerifyDiagnostics( // (7,11): error CS0200: Property or indexer 'C.P' cannot be assigned to -- it is read only Diagnostic(ErrorCode.ERR_AssgReadonlyProp, "P").WithArguments("C.P").WithLocation(7, 11), // (8,11): error CS0200: Property or indexer 'C.Q' cannot be assigned to -- it is read only Diagnostic(ErrorCode.ERR_AssgReadonlyProp, "c.Q").WithArguments("C.Q").WithLocation(8, 11)); } [Fact] public void CS0200ERR_AssgReadonlyProp04() { var source = @"class C { object P { get { P = null; return null; } } }"; CreateCompilation(source).VerifyDiagnostics( // (3,22): error CS0200: Property or indexer 'C.P' cannot be assigned to -- it is read only Diagnostic(ErrorCode.ERR_AssgReadonlyProp, "P").WithArguments("C.P").WithLocation(3, 22)); } [Fact] public void CS0200ERR_AssgReadonlyProp05() { CreateCompilation( @"class C { int this[int x] { get { return x; } } void M(int b) { this[0] = b; this[1]++; this[2] += 1; } }") .VerifyDiagnostics( // (6,9): error CS0200: Property or indexer 'C.this[int]' cannot be assigned to -- it is read only Diagnostic(ErrorCode.ERR_AssgReadonlyProp, "this[0]").WithArguments("C.this[int]"), // (7,9): error CS0200: Property or indexer 'C.this[int]' cannot be assigned to -- it is read only Diagnostic(ErrorCode.ERR_AssgReadonlyProp, "this[1]").WithArguments("C.this[int]"), // (8,9): error CS0200: Property or indexer 'C.this[int]' cannot be assigned to -- it is read only Diagnostic(ErrorCode.ERR_AssgReadonlyProp, "this[2]").WithArguments("C.this[int]")); } [Fact] public void CS0200ERR_AssgReadonlyProp06() { var source1 = @"public class A { public virtual object P { get { return null; } private set { } } } public class B : A { public override object P { get { return null; } } }"; var compilation1 = CreateCompilation(source1); compilation1.VerifyDiagnostics(); var compilationVerifier = CompileAndVerify(compilation1); var reference1 = MetadataReference.CreateFromImage(compilationVerifier.EmittedAssemblyData); var source2 = @"class C { static void M(B b) { var o = b.P; b.P = o; } }"; var compilation2 = CreateCompilation(source2, references: new[] { reference1 }); compilation2.VerifyDiagnostics( // (6,9): error CS0200: Property or indexer 'B.P' cannot be assigned to -- it is read only Diagnostic(ErrorCode.ERR_AssgReadonlyProp, "b.P").WithArguments("B.P").WithLocation(6, 9)); } [Fact] public void CS0201ERR_IllegalStatement1() { var text = @" public class MyList<T> { public void Add(T x) { int i = 0; if ( (object)x == null) { checked(i++); // CS0201 // OK checked { i++; } } } }"; CreateCompilation(text).VerifyDiagnostics( // (9,10): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement Diagnostic(ErrorCode.ERR_IllegalStatement, "checked(i++)")); } [Fact, WorkItem(536863, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536863")] public void CS0201ERR_IllegalStatement2() { var text = @" class A { public static int Main() { (a) => a; (a, b) => { }; int x = 0; int y = 0; x + y; x == 1; } }"; CreateCompilation(text, parseOptions: TestOptions.Regular.WithTuplesFeature()).VerifyDiagnostics( // (6,9): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement // (a) => a; Diagnostic(ErrorCode.ERR_IllegalStatement, "(a) => a").WithLocation(6, 9), // (7,9): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement // (a, b) => { }; Diagnostic(ErrorCode.ERR_IllegalStatement, "(a, b) => { }").WithLocation(7, 9), // (9,9): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement // x + y; x == 1; Diagnostic(ErrorCode.ERR_IllegalStatement, "x + y").WithLocation(9, 9), // (9,16): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement // x + y; x == 1; Diagnostic(ErrorCode.ERR_IllegalStatement, "x == 1").WithLocation(9, 16), // (4,23): error CS0161: 'A.Main()': not all code paths return a value // public static int Main() Diagnostic(ErrorCode.ERR_ReturnExpected, "Main").WithArguments("A.Main()").WithLocation(4, 23) ); } [Fact, WorkItem(536863, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536863")] public void CS0201ERR_IllegalStatement2WithCSharp6() { var test = @" class A { public static int Main() { (a) => a; (a, b) => { }; int x = 0; int y = 0; x + y; x == 1; } }"; var comp = CreateCompilation(new[] { Parse(test, options: TestOptions.Regular6) }, new MetadataReference[] { }); comp.VerifyDiagnostics( // (6,9): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement // (a) => a; Diagnostic(ErrorCode.ERR_IllegalStatement, "(a) => a").WithLocation(6, 9), // (7,9): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement // (a, b) => { }; Diagnostic(ErrorCode.ERR_IllegalStatement, "(a, b) => { }").WithLocation(7, 9), // (9,9): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement // x + y; x == 1; Diagnostic(ErrorCode.ERR_IllegalStatement, "x + y").WithLocation(9, 9), // (9,16): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement // x + y; x == 1; Diagnostic(ErrorCode.ERR_IllegalStatement, "x == 1").WithLocation(9, 16), // (4,23): error CS0161: 'A.Main()': not all code paths return a value // public static int Main() Diagnostic(ErrorCode.ERR_ReturnExpected, "Main").WithArguments("A.Main()").WithLocation(4, 23) ); } [Fact] public void CS0202ERR_BadGetEnumerator() { var text = @" public class C1 { public int Current { get { return 0; } } public bool MoveNext () { return false; } public static implicit operator C1 (int c1) { return 0; } } public class C2 { public int Current { get { return 0; } } public bool MoveNext () { return false; } public C1[] GetEnumerator () { return null; } } public class MainClass { public static void Main () { C2 c2 = new C2(); foreach (C1 x in c2) // CS0202 { System.Console.WriteLine(x.Current); } } }"; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_BadGetEnumerator, Line = 50, Column = 24 } }); } // [Fact()] // public void CS0204ERR_TooManyLocals() // { // var text = @" //"; // DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, // new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_TooManyLocals, Line = 8, Column = 13 } } // ); // } [Fact()] public void CS0205ERR_AbstractBaseCall() { var text = @"abstract class A { abstract public void M(); abstract protected object P { get; } } class B : A { public override void M() { base.M(); // CS0205 object o = base.P; // CS0205 } protected override object P { get { return null; } } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_AbstractBaseCall, Line = 10, Column = 9 }, new ErrorDescription { Code = (int)ErrorCode.ERR_AbstractBaseCall, Line = 11, Column = 20 }); } [Fact] public void CS0205ERR_AbstractBaseCall_Override() { var text = @" public class Base1 { public virtual long Property1 { get { return 0; } set { } } } abstract public class Base2 : Base1 { public abstract override long Property1 { get; } void test1() { Property1 += 1; } } public class Derived : Base2 { public override long Property1 { get { return 1; } set { } } void test2() { base.Property1++; base.Property1 = 2; long x = base.Property1; } } "; CreateCompilation(text).VerifyDiagnostics( // (19,9): error CS0205: Cannot call an abstract base member: 'Base2.Property1' Diagnostic(ErrorCode.ERR_AbstractBaseCall, "base.Property1").WithArguments("Base2.Property1"), // (21,18): error CS0205: Cannot call an abstract base member: 'Base2.Property1' Diagnostic(ErrorCode.ERR_AbstractBaseCall, "base.Property1").WithArguments("Base2.Property1")); } [Fact] public void CS0206ERR_RefProperty() { var text = @"class C { static int P { get; set; } object Q { get; set; } static void M(ref int i) { } static void M(out object o) { o = null; } void M() { M(ref P); // CS0206 M(out this.Q); // CS0206 } } "; CreateCompilation(text).VerifyDiagnostics( // (14,15): error CS0206: A property or indexer may not be passed as an out or ref parameter Diagnostic(ErrorCode.ERR_RefProperty, "P").WithArguments("C.P"), // (15,15): error CS0206: A property or indexer may not be passed as an out or ref parameter Diagnostic(ErrorCode.ERR_RefProperty, "this.Q").WithArguments("C.Q")); } [Fact] public void CS0206ERR_RefProperty_Indexers() { var text = @"class C { int this[int x] { get { return x; } set { } } static void R(ref int i) { } static void O(out int o) { o = 0; } void M() { R(ref this[0]); // CS0206 O(out this[0]); // CS0206 } } "; CreateCompilation(text).VerifyDiagnostics( // (13,15): error CS0206: A property or indexer may not be passed as an out or ref parameter Diagnostic(ErrorCode.ERR_RefProperty, "this[0]").WithArguments("C.this[int]"), // (14,15): error CS0206: A property or indexer may not be passed as an out or ref parameter Diagnostic(ErrorCode.ERR_RefProperty, "this[0]").WithArguments("C.this[int]")); } [Fact] public void CS0208ERR_ManagedAddr01() { var text = @" class myClass { public int a = 98; } struct myProblemStruct { string s; float f; } struct myGoodStruct { int i; float f; } public class MyClass { unsafe public static void Main() { // myClass is a class, a managed type. myClass s = new myClass(); myClass* s2 = &s; // CS0208 // The struct contains a string, a managed type. int i = sizeof(myProblemStruct); //CS0208 // The struct contains only value types. i = sizeof(myGoodStruct); //OK } } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (25,9): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('myClass') // myClass* s2 = &s; // CS0208 Diagnostic(ErrorCode.ERR_ManagedAddr, "myClass*").WithArguments("myClass"), // (25,23): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('myClass') // myClass* s2 = &s; // CS0208 Diagnostic(ErrorCode.ERR_ManagedAddr, "&s").WithArguments("myClass"), // (28,17): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('myProblemStruct') // int i = sizeof(myProblemStruct); //CS0208 Diagnostic(ErrorCode.ERR_ManagedAddr, "sizeof(myProblemStruct)").WithArguments("myProblemStruct"), // (9,12): warning CS0169: The field 'myProblemStruct.s' is never used // string s; Diagnostic(ErrorCode.WRN_UnreferencedField, "s").WithArguments("myProblemStruct.s"), // (10,11): warning CS0169: The field 'myProblemStruct.f' is never used // float f; Diagnostic(ErrorCode.WRN_UnreferencedField, "f").WithArguments("myProblemStruct.f"), // (15,9): warning CS0169: The field 'myGoodStruct.i' is never used // int i; Diagnostic(ErrorCode.WRN_UnreferencedField, "i").WithArguments("myGoodStruct.i"), // (16,11): warning CS0169: The field 'myGoodStruct.f' is never used // float f; Diagnostic(ErrorCode.WRN_UnreferencedField, "f").WithArguments("myGoodStruct.f")); } [Fact] public void CS0208ERR_ManagedAddr02() { var source = @"enum E { } delegate void D(); struct S { } interface I { } unsafe class C { object* _object; void* _void; bool* _bool; char* _char; sbyte* _sbyte; byte* _byte; short* _short; ushort* _ushort; int* _int; uint* _uint; long* _long; ulong* _ulong; decimal* _decimal; float* _float; double* _double; string* _string; System.IntPtr* _intptr; System.UIntPtr* _uintptr; int** _intptr2; int?* _nullable; dynamic* _dynamic; E* e; D* d; S* s; I* i; C* c; }"; CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.UnsafeReleaseDll) .GetDiagnostics() .Where(d => d.Severity == DiagnosticSeverity.Error) .Verify( // (22,13): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('string') // string* _string; Diagnostic(ErrorCode.ERR_ManagedAddr, "_string").WithArguments("string").WithLocation(22, 13), // (27,14): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('dynamic') // dynamic* _dynamic; Diagnostic(ErrorCode.ERR_ManagedAddr, "_dynamic").WithArguments("dynamic").WithLocation(27, 14), // (29,8): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('D') // D* d; Diagnostic(ErrorCode.ERR_ManagedAddr, "d").WithArguments("D").WithLocation(29, 8), // (31,8): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('I') // I* i; Diagnostic(ErrorCode.ERR_ManagedAddr, "i").WithArguments("I").WithLocation(31, 8), // (32,8): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('C') // C* c; Diagnostic(ErrorCode.ERR_ManagedAddr, "c").WithArguments("C").WithLocation(32, 8), // (7,13): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('object') // object* _object; Diagnostic(ErrorCode.ERR_ManagedAddr, "_object").WithArguments("object").WithLocation(7, 13)); } [Fact] public void CS0209ERR_BadFixedInitType() { var text = @" class Point { public int x, y; } public class MyClass { unsafe public static void Main() { Point pt = new Point(); fixed (int i) // CS0209 { } } } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (13,18): error CS0209: The type of a local declared in a fixed statement must be a pointer type // fixed (int i) // CS0209 Diagnostic(ErrorCode.ERR_BadFixedInitType, "i"), // (13,18): error CS0210: You must provide an initializer in a fixed or using statement declaration // fixed (int i) // CS0209 Diagnostic(ErrorCode.ERR_FixedMustInit, "i"), // (4,15): warning CS0649: Field 'Point.x' is never assigned to, and will always have its default value 0 // public int x, y; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "x").WithArguments("Point.x", "0"), // (4,18): warning CS0649: Field 'Point.y' is never assigned to, and will always have its default value 0 // public int x, y; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "y").WithArguments("Point.y", "0")); } [Fact] public void CS0210ERR_FixedMustInit() { var text = @" using System.IO; class Test { static void Main() { using (StreamWriter w) // CS0210 { w.WriteLine(""Hello there""); } using (StreamWriter x, y) // CS0210, CS0210 { } } } "; CreateCompilation(text).VerifyDiagnostics( // (7,27): error CS0210: You must provide an initializer in a fixed or using statement declaration // using (StreamWriter w) // CS0210 Diagnostic(ErrorCode.ERR_FixedMustInit, "w").WithLocation(7, 27), // (12,27): error CS0210: You must provide an initializer in a fixed or using statement declaration // using (StreamWriter x, y) // CS0210, CS0210 Diagnostic(ErrorCode.ERR_FixedMustInit, "x").WithLocation(12, 27), // (12,30): error CS0210: You must provide an initializer in a fixed or using statement declaration // using (StreamWriter x, y) // CS0210, CS0210 Diagnostic(ErrorCode.ERR_FixedMustInit, "y").WithLocation(12, 30), // (9,10): error CS0165: Use of unassigned local variable 'w' // w.WriteLine("Hello there"); Diagnostic(ErrorCode.ERR_UseDefViolation, "w").WithArguments("w").WithLocation(9, 10) ); } [Fact] public void CS0211ERR_InvalidAddrOp() { var text = @" public class MyClass { unsafe public void M() { int a = 0, b = 0; int *i = &(a + b); // CS0211, the addition of two local variables // try the following line instead // int *i = &a; } public static void Main() { } } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (7,18): error CS0211: Cannot take the address of the given expression // int *i = &(a + b); // CS0211, the addition of two local variables Diagnostic(ErrorCode.ERR_InvalidAddrOp, "a + b")); } [Fact] public void CS0212ERR_FixedNeeded() { var text = @" public class A { public int iField = 5; unsafe public void M() { A a = new A(); int* ptr = &a.iField; // CS0212 } // OK unsafe public void M2() { A a = new A(); fixed (int* ptr = &a.iField) {} } } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (7,18): error CS0212: You can only take the address of an unfixed expression inside of a fixed statement initializer // int* ptr = &a.iField; // CS0212 Diagnostic(ErrorCode.ERR_FixedNeeded, "&a.iField")); } [Fact] public void CS0213ERR_FixedNotNeeded() { var text = @" public class MyClass { unsafe public static void Main() { int i = 45; fixed (int *j = &i) { } // CS0213 // try the following line instead // int* j = &i; int[] a = new int[] {1,2,3}; fixed (int *b = a) { fixed (int *c = b) { } // CS0213 // try the following line instead // int *c = b; } } } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (7,23): error CS0213: You cannot use the fixed statement to take the address of an already fixed expression // fixed (int *j = &i) { } // CS0213 Diagnostic(ErrorCode.ERR_FixedNotNeeded, "&i").WithLocation(7, 23), // (14,26): error CS9385: The given expression cannot be used in a fixed statement // fixed (int *c = b) { } // CS0213 Diagnostic(ErrorCode.ERR_ExprCannotBeFixed, "b").WithLocation(14, 26)); } [Fact] public void CS0217ERR_BadBoolOp() { // Note that the wording of this error message has changed. var text = @" public class MyClass { public static bool operator true (MyClass f) { return false; } public static bool operator false (MyClass f) { return false; } public static int operator & (MyClass f1, MyClass f2) { return 0; } public static void Main() { MyClass f = new MyClass(); int i = f && f; // CS0217 } } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (22,15): error CS0217: In order to be applicable as a short circuit operator a user-defined logical operator ('MyClass.operator &(MyClass, MyClass)') must have the same return type and parameter types // int i = f && f; // CS0217 Diagnostic(ErrorCode.ERR_BadBoolOp, "f && f").WithArguments("MyClass.operator &(MyClass, MyClass)")); } // CS0220 ERR_CheckedOverflow - see ConstantTests [Fact] public void CS0221ERR_ConstOutOfRangeChecked01() { string text = @"class MyClass { static void F(int x) { } static void M() { F((int)0xFFFFFFFF); // CS0221 F(unchecked((int)uint.MaxValue)); F(checked((int)(uint.MaxValue - 1))); // CS0221 } } "; CreateCompilation(text).VerifyDiagnostics( // (6,11): error CS0221: Constant value '4294967295' cannot be converted to a 'int' (use 'unchecked' syntax to override) Diagnostic(ErrorCode.ERR_ConstOutOfRangeChecked, "(int)0xFFFFFFFF").WithArguments("4294967295", "int"), // (8,19): error CS0221: Constant value '4294967294' cannot be converted to a 'int' (use 'unchecked' syntax to override) Diagnostic(ErrorCode.ERR_ConstOutOfRangeChecked, "(int)(uint.MaxValue - 1)").WithArguments("4294967294", "int")); } [Fact] public void CS0221ERR_ConstOutOfRangeChecked02() { string text = @"enum E : byte { A, B = 0xfe, C } class C { const int F = (int)(E.C + 1); // CS0221 const int G = (int)unchecked(1 + E.C); const int H = (int)checked(E.A - 1); // CS0221 } "; CreateCompilation(text).VerifyDiagnostics( // (4,25): error CS0031: Constant value '256' cannot be converted to a 'E' Diagnostic(ErrorCode.ERR_ConstOutOfRangeChecked, "E.C + 1").WithArguments("256", "E"), // (6,32): error CS0221: Constant value '-1' cannot be converted to a 'E' (use 'unchecked' syntax to override) Diagnostic(ErrorCode.ERR_ConstOutOfRangeChecked, "E.A - 1").WithArguments("-1", "E")); } [WorkItem(1119609, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1119609")] [Fact(Skip = "1119609")] public void CS0221ERR_ConstOutOfRangeChecked03() { var text = @"public class MyClass { decimal x1 = (decimal)double.PositiveInfinity; //CS0221 decimal x2 = (decimal)double.NegativeInfinity; //CS0221 decimal x3 = (decimal)double.NaN; //CS0221 decimal x4 = (decimal)double.MaxValue; //CS0221 public static void Main() {} } "; CreateCompilation(text).VerifyDiagnostics( // (3,18): error CS0031: Constant value 'Infinity' cannot be converted to a 'decimal' // decimal x1 = (decimal)double.PositiveInfinity; //CS0221 Diagnostic(ErrorCode.ERR_ConstOutOfRange, "(decimal)double.PositiveInfinity").WithArguments("Infinity", "decimal"), // (4,18): error CS0031: Constant value '-Infinity' cannot be converted to a 'decimal' // decimal x2 = (decimal)double.NegativeInfinity; //CS0221 Diagnostic(ErrorCode.ERR_ConstOutOfRange, "(decimal)double.NegativeInfinity").WithArguments("-Infinity", "decimal"), // (5,18): error CS0031: Constant value 'NaN' cannot be converted to a 'decimal' // decimal x3 = (decimal)double.NaN; //CS0221 Diagnostic(ErrorCode.ERR_ConstOutOfRange, "(decimal)double.NaN").WithArguments("NaN", "decimal"), // (6,18): error CS0031: Constant value '1.79769313486232E+308' cannot be converted to a 'decimal' // decimal x4 = (decimal)double.MaxValue; //CS0221 Diagnostic(ErrorCode.ERR_ConstOutOfRange, "(decimal)double.MaxValue").WithArguments("1.79769313486232E+308", "decimal"), // (3,13): warning CS0414: The field 'MyClass.x1' is assigned but its value is never used // decimal x1 = (decimal)double.PositiveInfinity; //CS0221 Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "x1").WithArguments("MyClass.x1"), // (4,13): warning CS0414: The field 'MyClass.x2' is assigned but its value is never used // decimal x2 = (decimal)double.NegativeInfinity; //CS0221 Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "x2").WithArguments("MyClass.x2"), // (5,13): warning CS0414: The field 'MyClass.x3' is assigned but its value is never used // decimal x3 = (decimal)double.NaN; //CS0221 Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "x3").WithArguments("MyClass.x3"), // (6,13): warning CS0414: The field 'MyClass.x4' is assigned but its value is never used // decimal x4 = (decimal)double.MaxValue; //CS0221 Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "x4").WithArguments("MyClass.x4")); } [Fact] public void CS0226ERR_IllegalArglist() { var text = @" public class C { public static int Main () { __arglist(1,""This is a string""); // CS0226 return 0; } } "; CreateCompilation(text).VerifyDiagnostics( Diagnostic(ErrorCode.ERR_IllegalArglist, @"__arglist(1,""This is a string"")")); } // [Fact()] // public void CS0228ERR_NoAccessibleMember() // { // var text = @" //"; // DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, // new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_NoAccessibleMember, Line = 31, Column = 17 } } // ); // } [Fact] public void CS0229ERR_AmbigMember() { var text = @" interface IList { int Count { get; set; } void Counter(); } interface Icounter { double Count { get; set; } } interface IListCounter : IList , Icounter {} class MyClass { void Test(IListCounter x) { x.Count = 1; // CS0229 // Try one of the following lines instead: // ((IList)x).Count = 1; // or // ((Icounter)x).Count = 1; } public static void Main() {} } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_AmbigMember, Line = 28, Column = 11 } }); } [Fact] public void CS0233ERR_SizeofUnsafe() { var text = @" using System; using System.Runtime.InteropServices; [StructLayout(LayoutKind.Sequential)] public struct S { public int a; } public class MyClass { public static void Main() { S myS = new S(); Console.WriteLine(sizeof(S)); // CS0233 // Try the following line instead: // Console.WriteLine(Marshal.SizeOf(myS)); } } "; CreateCompilation(text).VerifyDiagnostics( // (16,27): error CS0233: 'S' does not have a predefined size, therefore sizeof can only be used in an unsafe context (consider using System.Runtime.InteropServices.Marshal.SizeOf) // Console.WriteLine(sizeof(S)); // CS0233 Diagnostic(ErrorCode.ERR_SizeofUnsafe, "sizeof(S)").WithArguments("S"), // (15,11): warning CS0219: The variable 'myS' is assigned but its value is never used // S myS = new S(); Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "myS").WithArguments("myS")); } [Fact] public void CS0236ERR_FieldInitRefNonstatic() { var text = @" public class MyClass { int[] instanceArray; static int[] staticArray; static int staticField = 1; const int constField = 1; int a; int b = 1; int c = b; //CS0236 int d = this.b; //CS0027 int e = InstanceMethod(); //CS0236 int f = this.InstanceMethod(); //CS0027 int g = StaticMethod(); int h = MyClass.StaticMethod(); int i = GenericInstanceMethod<int>(1); //CS0236 int j = this.GenericInstanceMethod<int>(1); //CS0027 int k = GenericStaticMethod<int>(1); int l = MyClass.GenericStaticMethod<int>(1); int m = InstanceProperty; //CS0236 int n = this.InstanceProperty; //CS0027 int o = StaticProperty; int p = MyClass.StaticProperty; int q = instanceArray[0]; //CS0236 int r = this.instanceArray[0]; //CS0027 int s = staticArray[0]; int t = MyClass.staticArray[0]; int u = staticField; int v = MyClass.staticField; int w = constField; int x = MyClass.constField; MyClass() { a = b; } int InstanceMethod() { return a; } static int StaticMethod() { return 1; } T GenericInstanceMethod<T>(T t) { return t; } static T GenericStaticMethod<T>(T t) { return t; } int InstanceProperty { get { return a; } } static int StaticProperty { get { return 1; } } public static void Main() { } } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (12,13): error CS0236: A field initializer cannot reference the non-static field, method, or property 'MyClass.b' // int c = b; //CS0236 Diagnostic(ErrorCode.ERR_FieldInitRefNonstatic, "b").WithArguments("MyClass.b").WithLocation(12, 13), // (13,13): error CS0027: Keyword 'this' is not available in the current context // int d = this.b; //CS0027 Diagnostic(ErrorCode.ERR_ThisInBadContext, "this").WithLocation(13, 13), // (14,13): error CS0236: A field initializer cannot reference the non-static field, method, or property 'MyClass.InstanceMethod()' // int e = InstanceMethod(); //CS0236 Diagnostic(ErrorCode.ERR_FieldInitRefNonstatic, "InstanceMethod").WithArguments("MyClass.InstanceMethod()").WithLocation(14, 13), // (15,13): error CS0027: Keyword 'this' is not available in the current context // int f = this.InstanceMethod(); //CS0027 Diagnostic(ErrorCode.ERR_ThisInBadContext, "this").WithLocation(15, 13), // (18,13): error CS0236: A field initializer cannot reference the non-static field, method, or property 'MyClass.GenericInstanceMethod<int>(int)' // int i = GenericInstanceMethod<int>(1); //CS0236 Diagnostic(ErrorCode.ERR_FieldInitRefNonstatic, "GenericInstanceMethod<int>").WithArguments("MyClass.GenericInstanceMethod<int>(int)").WithLocation(18, 13), // (19,13): error CS0027: Keyword 'this' is not available in the current context // int j = this.GenericInstanceMethod<int>(1); //CS0027 Diagnostic(ErrorCode.ERR_ThisInBadContext, "this").WithLocation(19, 13), // (22,13): error CS0236: A field initializer cannot reference the non-static field, method, or property 'MyClass.InstanceProperty' // int m = InstanceProperty; //CS0236 Diagnostic(ErrorCode.ERR_FieldInitRefNonstatic, "InstanceProperty").WithArguments("MyClass.InstanceProperty").WithLocation(22, 13), // (23,13): error CS0027: Keyword 'this' is not available in the current context // int n = this.InstanceProperty; //CS0027 Diagnostic(ErrorCode.ERR_ThisInBadContext, "this").WithLocation(23, 13), // (26,13): error CS0236: A field initializer cannot reference the non-static field, method, or property 'MyClass.instanceArray' // int q = instanceArray[0]; //CS0236 Diagnostic(ErrorCode.ERR_FieldInitRefNonstatic, "instanceArray").WithArguments("MyClass.instanceArray").WithLocation(26, 13), // (27,13): error CS0027: Keyword 'this' is not available in the current context // int r = this.instanceArray[0]; //CS0027 Diagnostic(ErrorCode.ERR_ThisInBadContext, "this").WithLocation(27, 13), // (4,11): warning CS0649: Field 'MyClass.instanceArray' is never assigned to, and will always have its default value null // int[] instanceArray; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "instanceArray").WithArguments("MyClass.instanceArray", "null").WithLocation(4, 11), // (5,18): warning CS0649: Field 'MyClass.staticArray' is never assigned to, and will always have its default value null // static int[] staticArray; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "staticArray").WithArguments("MyClass.staticArray", "null").WithLocation(5, 18), // (33,9): warning CS0414: The field 'MyClass.x' is assigned but its value is never used // int x = MyClass.constField; Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "x").WithArguments("MyClass.x").WithLocation(33, 9), // (32,9): warning CS0414: The field 'MyClass.w' is assigned but its value is never used // int w = constField; Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "w").WithArguments("MyClass.w").WithLocation(32, 9) ); } [Fact] public void CS0236ERR_FieldInitRefNonstaticMethodGroups() { var text = @" delegate void F(); public class MyClass { F a = Static; F b = MyClass.Static; F c = Static<int>; F d = MyClass.Static<int>; F e = Instance; F f = this.Instance; F g = Instance<int>; F h = this.Instance<int>; static void Static() { } static void Static<T>() { } void Instance() { } void Instance<T>() { } public static void Main() { } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib( text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_FieldInitRefNonstatic, Line = 9, Column = 11 }, new ErrorDescription { Code = (int)ErrorCode.ERR_ThisInBadContext, Line = 10, Column = 11 }, new ErrorDescription { Code = (int)ErrorCode.ERR_FieldInitRefNonstatic, Line = 11, Column = 11 }, new ErrorDescription { Code = (int)ErrorCode.ERR_ThisInBadContext, Line = 12, Column = 11 }, }); } [WorkItem(541501, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541501")] [Fact] public void CS0236ERR_FieldInitRefNonstaticProperty() { CreateCompilation( @" enum ProtectionLevel { Privacy = 0 } class F { const ProtectionLevel p = ProtectionLevel.Privacy; // CS0236 int ProtectionLevel { get { return 0; } } } ") .VerifyDiagnostics( // (9,29): error CS0236: A field initializer cannot reference the non-static field, method, or property 'F.ProtectionLevel' // const ProtectionLevel p = ProtectionLevel.Privacy; // CS0120 Diagnostic(ErrorCode.ERR_FieldInitRefNonstatic, "ProtectionLevel").WithArguments("F.ProtectionLevel")); } [WorkItem(541501, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541501")] [Fact] public void CS0236ERR_FieldInitRefNonstatic_ObjectInitializer() { CreateCompilation( @" public class Goo { public int i; public string s; } public class MemberInitializerTest { private int i =10; private string s = ""abc""; private Goo f = new Goo{i = i, s = s}; public static void Main() { } } ") .VerifyDiagnostics( // (12,33): error CS0236: A field initializer cannot reference the non-static field, method, or property 'MemberInitializerTest.i' // private Goo f = new Goo{i = i, s = s}; Diagnostic(ErrorCode.ERR_FieldInitRefNonstatic, "i").WithArguments("MemberInitializerTest.i").WithLocation(12, 33), // (12,40): error CS0236: A field initializer cannot reference the non-static field, method, or property 'MemberInitializerTest.s' // private Goo f = new Goo{i = i, s = s}; Diagnostic(ErrorCode.ERR_FieldInitRefNonstatic, "s").WithArguments("MemberInitializerTest.s").WithLocation(12, 40)); } [Fact] public void CS0236ERR_FieldInitRefNonstatic_AnotherInitializer() { CreateCompilation( @" class TestClass { int P1 { get; } int y = (P1 = 123); int y1 { get; } = (P1 = 123); static void Main() { } } ") .VerifyDiagnostics( // (6,14): error CS0236: A field initializer cannot reference the non-static field, method, or property 'TestClass.P1' // int y = (P1 = 123); Diagnostic(ErrorCode.ERR_FieldInitRefNonstatic, "P1").WithArguments("TestClass.P1").WithLocation(6, 14), // (7,24): error CS0236: A field initializer cannot reference the non-static field, method, or property 'TestClass.P1' // int y1 { get; } = (P1 = 123); Diagnostic(ErrorCode.ERR_FieldInitRefNonstatic, "P1").WithArguments("TestClass.P1").WithLocation(7, 24) ); } [Fact] public void CS0242ERR_VoidError() { var text = @" class TestClass { public unsafe void Test() { void* p = null; p++; //CS0242 p += 2; //CS0242 void* q = p + 1; //CS0242 long diff = q - p; //CS0242 var v = *p; } } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (7,9): error CS0242: The operation in question is undefined on void pointers // p++; //CS0242 Diagnostic(ErrorCode.ERR_VoidError, "p++"), // (8,9): error CS0242: The operation in question is undefined on void pointers // p += 2; //CS0242 Diagnostic(ErrorCode.ERR_VoidError, "p += 2"), // (9,19): error CS0242: The operation in question is undefined on void pointers // void* q = p + 1; //CS0242 Diagnostic(ErrorCode.ERR_VoidError, "p + 1"), // (10,21): error CS0242: The operation in question is undefined on void pointers // long diff = q - p; //CS0242 Diagnostic(ErrorCode.ERR_VoidError, "q - p"), // (11,17): error CS0242: The operation in question is undefined on void pointers // var v = *p; Diagnostic(ErrorCode.ERR_VoidError, "*p")); } [Fact] public void CS0244ERR_PointerInAsOrIs() { var text = @" class UnsafeTest { unsafe static void SquarePtrParam (int* p) { bool b = p is object; // CS0244 p is pointer } unsafe public static void Main() { int i = 5; SquarePtrParam (&i); } } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (6,16): error CS0244: Neither 'is' nor 'as' is valid on pointer types // bool b = p is object; // CS0244 p is pointer Diagnostic(ErrorCode.ERR_PointerInAsOrIs, "p is object")); } [Fact] public void CS0245ERR_CallingFinalizeDeprecated() { var text = @" class MyClass // : IDisposable { /* public void Dispose() { // cleanup code goes here } */ void m() { this.Finalize(); // CS0245 // this.Dispose(); } public static void Main() { } } "; CreateCompilation(text).VerifyDiagnostics( // (13,7): error CS0245: Destructors and object.Finalize cannot be called directly. Consider calling IDisposable.Dispose if available. Diagnostic(ErrorCode.ERR_CallingFinalizeDeprecated, "this.Finalize()")); } [WorkItem(540722, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540722")] [Fact] public void CS0246ERR_SingleTypeNameNotFound05() { CreateCompilation(@" namespace nms { public class Mine { private static int retval = 5; public static int Main() { try { } catch (e) { } return retval; } }; } ") .VerifyDiagnostics( // (10,20): error CS0246: The type or namespace name 'e' could not be found (are you missing a using directive or an assembly reference?) Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "e").WithArguments("e")); } [WorkItem(528446, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528446")] [Fact] public void CS0246ERR_SingleTypeNameNotFoundNoCS8000() { CreateCompilation(@" class Test { void Main() { var sum = new j(); } } ") .VerifyDiagnostics( // (11,20): error CS0246: The type or namespace name 'j' could not be found (are you missing a using directive or an assembly reference?) Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "j").WithArguments("j")); } [Fact] public void CS0247ERR_NegativeStackAllocSize() { var text = @" public class MyClass { unsafe public static void Main() { int *p = stackalloc int [-30]; // CS0247 } } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (6,32): error CS0247: Cannot use a negative size with stackalloc // int *p = stackalloc int [-30]; // CS0247 Diagnostic(ErrorCode.ERR_NegativeStackAllocSize, "-30")); } [Fact] public void CS0248ERR_NegativeArraySize() { var text = @" class MyClass { public static void Main() { int[] myArray = new int[-3] {1,2,3}; // CS0248, pass a nonnegative number int[] myArray2 = new int[-5000000000]; // slightly different code path for long array sizes int[] myArray3 = new int[3000000000u]; // slightly different code path for uint array sizes var myArray4 = new object[-2, 1, -1] {{{null}},{{null}}}; var myArray5 = new object[-1L] {null}; } } "; CreateCompilation(text).VerifyDiagnostics( // (6,33): error CS0248: Cannot create an array with a negative size // int[] myArray = new int[-3] {1,2,3}; // CS0248, pass a nonnegative number Diagnostic(ErrorCode.ERR_NegativeArraySize, "-3").WithLocation(6, 33), // (7,34): error CS0248: Cannot create an array with a negative size // int[] myArray2 = new int[-5000000000]; // slightly different code path for long array sizes Diagnostic(ErrorCode.ERR_NegativeArraySize, "-5000000000").WithLocation(7, 34), // (9,35): error CS0248: Cannot create an array with a negative size // var myArray4 = new object[-2, 1, -1] {{{null}},{{null}}}; Diagnostic(ErrorCode.ERR_NegativeArraySize, "-2").WithLocation(9, 35), // (9,42): error CS0248: Cannot create an array with a negative size // var myArray4 = new object[-2, 1, -1] {{{null}},{{null}}}; Diagnostic(ErrorCode.ERR_NegativeArraySize, "-1").WithLocation(9, 42), // (10,35): error CS0248: Cannot create an array with a negative size // var myArray5 = new object[-1L] {null}; Diagnostic(ErrorCode.ERR_NegativeArraySize, "-1L").WithLocation(10, 35), // (10,35): error CS0150: A constant value is expected // var myArray5 = new object[-1L] {null}; Diagnostic(ErrorCode.ERR_ConstantExpected, "-1L").WithLocation(10, 35)); } [WorkItem(528912, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528912")] [Fact] public void CS0250ERR_CallingBaseFinalizeDeprecated() { var text = @" class B { } class C : B { ~C() { base.Finalize(); // CS0250 } public static void Main() { } } "; CreateCompilation(text).VerifyDiagnostics( // (10,7): error CS0250: Do not directly call your base type Finalize method. It is called automatically from your destructor. Diagnostic(ErrorCode.ERR_CallingBaseFinalizeDeprecated, "base.Finalize()")); } [Fact] public void CS0254ERR_BadCastInFixed() { var text = @" class Point { public uint x, y; } class FixedTest { unsafe static void SquarePtrParam (int* p) { *p *= *p; } unsafe public static void Main() { Point pt = new Point(); pt.x = 5; pt.y = 6; fixed (int* p = (int*)&pt.x) // CS0254 // try the following line instead // fixed (uint* p = &pt.x) { SquarePtrParam ((int*)p); } } } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (20,23): error CS9385: The given expression cannot be used in a fixed statement // fixed (int* p = (int*)&pt.x) // CS0254 Diagnostic(ErrorCode.ERR_ExprCannotBeFixed, "(int*)&pt.x").WithLocation(20, 23)); } [Fact] public void CS0255ERR_StackallocInFinally() { var text = @" unsafe class Test { void M() { try { // Something } finally { int* fib = stackalloc int[100]; } } }"; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (12,24): error CS0255: stackalloc may not be used in a catch or finally block // int* fib = stackalloc int[100]; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int[100]").WithLocation(12, 24)); } [Fact] public void CS0255ERR_StackallocInCatch() { var text = @" unsafe class Test { void M() { try { // Something } catch { int* fib = stackalloc int[100]; } } }"; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (12,24): error CS0255: stackalloc may not be used in a catch or finally block // int* fib = stackalloc int[100]; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int[100]").WithLocation(12, 24)); } [Fact] public void CS0266ERR_NoImplicitConvCast01() { var text = @" class MyClass { public static void Main() { object obj = ""MyString""; // Cannot implicitly convert 'object' to 'MyClass' MyClass myClass = obj; // CS0266 // Try this line instead // MyClass c = ( MyClass )obj; } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_NoImplicitConvCast, Line = 8, Column = 27 } }); } [Fact] public void CS0266ERR_NoImplicitConvCast02() { var source = @"class C { const int f = 0L; } "; CreateCompilation(source).VerifyDiagnostics( // (3,19): error CS0266: Cannot implicitly convert type 'long' to 'int'. An explicit conversion exists (are you missing a cast?) // const int f = 0L; Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "0L").WithArguments("long", "int").WithLocation(3, 19)); } [Fact] public void CS0266ERR_NoImplicitConvCast03() { var source = @"class C { static void M() { const short s = 1L; } } "; CreateCompilation(source).VerifyDiagnostics( // (5,25): error CS0266: Cannot implicitly convert type 'long' to 'short'. An explicit conversion exists (are you missing a cast?) // const short s = 1L; Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "1L").WithArguments("long", "short").WithLocation(5, 25), // (5,21): warning CS0219: The variable 's' is assigned but its value is never used // const short s = 1L; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "s").WithArguments("s").WithLocation(5, 21)); } [Fact] public void CS0266ERR_NoImplicitConvCast04() { var source = @"enum E { A = 1 } class C { E f = 2; // CS0266 E g = E.A; void M() { f = E.A; g = 'c'; // CS0266 } } "; CreateCompilation(source).VerifyDiagnostics( // (4,11): error CS0266: Cannot implicitly convert type 'int' to 'E'. An explicit conversion exists (are you missing a cast?) // E f = 2; // CS0266 Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "2").WithArguments("int", "E").WithLocation(4, 11), // (9,13): error CS0266: Cannot implicitly convert type 'char' to 'E'. An explicit conversion exists (are you missing a cast?) // g = 'c'; // CS0266 Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "'c'").WithArguments("char", "E").WithLocation(9, 13), // (4,7): warning CS0414: The field 'C.f' is assigned but its value is never used // E f = 2; // CS0266 Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "f").WithArguments("C.f").WithLocation(4, 7), // (5,7): warning CS0414: The field 'C.g' is assigned but its value is never used // E g = E.A; Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "g").WithArguments("C.g").WithLocation(5, 7)); } [Fact] public void CS0266ERR_NoImplicitConvCast05() { var source = @"enum E : byte { A = 'a', // CS0266 B = 0xff, } "; CreateCompilation(source).VerifyDiagnostics( // (3,9): error CS0266: Cannot implicitly convert type 'char' to 'byte'. An explicit conversion exists (are you missing a cast?) // A = 'a', // CS0266 Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "'a'").WithArguments("char", "byte").WithLocation(3, 9)); } [Fact] public void CS0266ERR_NoImplicitConvCast06() { var source = @"enum E { A = 1, B = 1L // CS0266 } "; CreateCompilation(source).VerifyDiagnostics( // (4,9): error CS0266: Cannot implicitly convert type 'long' to 'int'. An explicit conversion exists (are you missing a cast?) // B = 1L // CS0266 Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "1L").WithArguments("long", "int").WithLocation(4, 9)); } [Fact] public void CS0266ERR_NoImplicitConvCast07() { // No errors var source = "enum E { A, B = A }"; CreateCompilation(source).VerifyDiagnostics(); } [Fact] public void CS0266ERR_NoImplicitConvCast08() { // No errors var source = @"enum E { A = 1, B } enum F { X = E.A + 1, Y } "; CreateCompilation(source).VerifyDiagnostics(); } [Fact] public void CS0266ERR_NoImplicitConvCast09() { var source = @"enum E { A = F.A, B = F.B, C = G.A, D = G.B, } enum F : short { A = 1, B } enum G : long { A = 1, B } "; CreateCompilation(source).VerifyDiagnostics( // (5,9): error CS0266: Cannot implicitly convert type 'long' to 'int'. An explicit conversion exists (are you missing a cast?) // C = G.A, Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "G.A").WithArguments("long", "int").WithLocation(5, 9), // (6,9): error CS0266: Cannot implicitly convert type 'long' to 'int'. An explicit conversion exists (are you missing a cast?) // D = G.B, Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "G.B").WithArguments("long", "int").WithLocation(6, 9)); } [Fact] public void CS0266ERR_NoImplicitConvCast10() { var source = @"class C { public const int F = D.G + 1; } class D { public const int G = E.H + 1; } class E { public const int H = 1L; } "; CreateCompilation(source).VerifyDiagnostics( // (11,26): error CS0266: Cannot implicitly convert type 'long' to 'int'. An explicit conversion exists (are you missing a cast?) // public const int H = 1L; Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "1L").WithArguments("long", "int").WithLocation(11, 26)); } [Fact()] public void CS0266ERR_NoImplicitConvCast11() { string text = @"class Program { static void Main(string[] args) { bool? b = true; int result = b ? 0 : 1; // Compiler error } } "; CreateCompilation(text). VerifyDiagnostics(Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "b").WithArguments("bool?", "bool")); } [WorkItem(541718, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541718")] [Fact] public void CS0266ERR_NoImplicitConvCast12() { string text = @" class C1 { public static void Main() { var cube = new int[Number.One][]; } } enum Number { One, Two } "; CreateCompilation(text).VerifyDiagnostics( // (6,28): error CS0266: Cannot implicitly convert type 'Number' to 'int'. An explicit conversion exists (are you missing a cast?) // var cube = new int[Number.One][]; Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "Number.One").WithArguments("Number", "int").WithLocation(6, 28)); } [WorkItem(541718, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541718")] [Fact] public void CS0266ERR_NoImplicitConvCast13() { string text = @" class C1 { public static void Main() { double x = 5; int[] arr4 = new int[x];// Invalid float y = 5; int[] arr5 = new int[y];// Invalid decimal z = 5; int[] arr6 = new int[z];// Invalid } } "; CreateCompilation(text). VerifyDiagnostics( // (7,30): error CS0266: Cannot implicitly convert type 'double' to 'int'. An explicit conversion exists (are you missing a cast?) // int[] arr4 = new int[x];// Invalid Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "x").WithArguments("double", "int").WithLocation(7, 30), // (10,30): error CS0266: Cannot implicitly convert type 'float' to 'int'. An explicit conversion exists (are you missing a cast?) // int[] arr5 = new int[y];// Invalid Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "y").WithArguments("float", "int").WithLocation(10, 30), // (13,30): error CS0266: Cannot implicitly convert type 'decimal' to 'int'. An explicit conversion exists (are you missing a cast?) // int[] arr6 = new int[z];// Invalid Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "z").WithArguments("decimal", "int").WithLocation(13, 30)); } [Fact] public void CS0266ERR_NoImplicitConvCast14() { string source = @" class C { public unsafe void M(int* p, object o) { _ = p[o]; // error with span on 'o' _ = p[0]; // ok } } "; CreateCompilation(source, options: TestOptions.UnsafeDebugDll).VerifyDiagnostics( // (6,15): error CS0266: Cannot implicitly convert type 'object' to 'int'. An explicit conversion exists (are you missing a cast?) // _ = p[o]; // error with span on 'o' Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "o").WithArguments("object", "int").WithLocation(6, 15)); } [Fact] public void CS0266ERR_NoImplicitConvCast15() { string source = @" class C { public void M(object o) { int[o] x; } } "; CreateCompilation(source).VerifyDiagnostics( // (6,12): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression) // int[o]; Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "[o]").WithLocation(6, 12), // (6,13): error CS0266: Cannot implicitly convert type 'object' to 'int'. An explicit conversion exists (are you missing a cast?) // int[o]; Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "o").WithArguments("object", "int").WithLocation(6, 13), // (6,16): warning CS0168: The variable 'x' is declared but never used // int[o] x; Diagnostic(ErrorCode.WRN_UnreferencedVar, "x").WithArguments("x").WithLocation(6, 16)); } [Fact] public void CS0269ERR_UseDefViolationOut() { var text = @" class C { public static void F(out int i) { try { // Assignment occurs, but compiler can't verify it i = 1; } catch { } int k = i; // CS0269 i = 1; } public static void Main() { int myInt; F(out myInt); } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_UseDefViolationOut, Line = 15, Column = 17 } }); } [Fact] public void CS0271ERR_InaccessibleGetter01() { var source = @"class C { internal static object P { private get; set; } public C Q { protected get { return null; } set { } } } class P { static void M(C c) { object o = C.P; M(c.Q); } }"; CreateCompilation(source).VerifyDiagnostics( // (10,20): error CS0271: The property or indexer 'C.P' cannot be used in this context because the get accessor is inaccessible Diagnostic(ErrorCode.ERR_InaccessibleGetter, "C.P").WithArguments("C.P").WithLocation(10, 20), // (11,11): error CS0271: The property or indexer 'C.Q' cannot be used in this context because the get accessor is inaccessible Diagnostic(ErrorCode.ERR_InaccessibleGetter, "c.Q").WithArguments("C.Q").WithLocation(11, 11)); } [Fact] public void CS0271ERR_InaccessibleGetter02() { var source = @"class A { public virtual object P { protected get; set; } } class B : A { public override object P { set { } } void M() { object o = P; // no error } } class C { void M(B b) { object o = b.P; // CS0271 } }"; CreateCompilation(source).VerifyDiagnostics( // (17,20): error CS0271: The property or indexer 'B.P' cannot be used in this context because the get accessor is inaccessible Diagnostic(ErrorCode.ERR_InaccessibleGetter, "b.P").WithArguments("B.P").WithLocation(17, 20)); } [Fact] public void CS0271ERR_InaccessibleGetter03() { var source = @"namespace N1 { class A { void M(N2.B b) { object o = b.P; } } } namespace N2 { class B : N1.A { public object P { protected get; set; } } }"; CreateCompilation(source).VerifyDiagnostics( // (7,24): error CS0271: The property or indexer 'N2.B.P' cannot be used in this context because the get accessor is inaccessible Diagnostic(ErrorCode.ERR_InaccessibleGetter, "b.P").WithArguments("N2.B.P").WithLocation(7, 24)); } [Fact] public void CS0271ERR_InaccessibleGetter04() { var source = @"class A { static public object P { protected get; set; } static internal object Q { private get; set; } static void M() { object o = B.Q; // no error o = A.Q; // no error } } class B : A { static void M() { object o = B.P; // no error o = P; // no error o = Q; // CS0271 } } class C { static void M() { object o = B.P; // CS0271 o = A.Q; // CS0271 } }"; CreateCompilation(source).VerifyDiagnostics( // (17,13): error CS0271: The property or indexer 'A.Q' cannot be used in this context because the get accessor is inaccessible Diagnostic(ErrorCode.ERR_InaccessibleGetter, "Q").WithArguments("A.Q").WithLocation(17, 13), // (24,20): error CS0271: The property or indexer 'A.P' cannot be used in this context because the get accessor is inaccessible Diagnostic(ErrorCode.ERR_InaccessibleGetter, "B.P").WithArguments("A.P").WithLocation(24, 20), // (25,13): error CS0271: The property or indexer 'A.Q' cannot be used in this context because the get accessor is inaccessible Diagnostic(ErrorCode.ERR_InaccessibleGetter, "A.Q").WithArguments("A.Q").WithLocation(25, 13)); } [Fact] public void CS0271ERR_InaccessibleGetter05() { CreateCompilation( @"class A { public object this[int x] { protected get { return null; } set { } } internal object this[string s] { private get { return null; } set { } } void M() { object o = new B()[""hello""]; // no error o = new A()[""hello""]; // no error } } class B : A { void M() { object o = new B()[0]; // no error o = this[0]; // no error o = this[""hello""]; // CS0271 } } class C { void M() { object o = new B()[0]; // CS0271 o = new A()[""hello""]; // CS0271 } }") .VerifyDiagnostics( // (17,13): error CS0271: The property or indexer 'A.this[string]' cannot be used in this context because the get accessor is inaccessible Diagnostic(ErrorCode.ERR_InaccessibleGetter, @"this[""hello""]").WithArguments("A.this[string]"), // (24,20): error CS0271: The property or indexer 'A.this[int]' cannot be used in this context because the get accessor is inaccessible Diagnostic(ErrorCode.ERR_InaccessibleGetter, "new B()[0]").WithArguments("A.this[int]"), // (25,13): error CS0271: The property or indexer 'A.this[string]' cannot be used in this context because the get accessor is inaccessible Diagnostic(ErrorCode.ERR_InaccessibleGetter, @"new A()[""hello""]").WithArguments("A.this[string]")); } [Fact] public void CS0272ERR_InaccessibleSetter01() { var source = @"namespace N { class C { internal object P { get; private set; } static public C Q { get { return null; } protected set { } } } class P { static void M(C c) { c.P = c; C.Q = c; } } }"; CreateCompilation(source).VerifyDiagnostics( // (12,13): error CS0272: The property or indexer 'N.C.P' cannot be used in this context because the set accessor is inaccessible Diagnostic(ErrorCode.ERR_InaccessibleSetter, "c.P").WithArguments("N.C.P").WithLocation(12, 13), // (13,13): error CS0272: The property or indexer 'N.C.Q' cannot be used in this context because the set accessor is inaccessible Diagnostic(ErrorCode.ERR_InaccessibleSetter, "C.Q").WithArguments("N.C.Q").WithLocation(13, 13)); } [Fact] public void CS0272ERR_InaccessibleSetter02() { var source = @"namespace N1 { abstract class A { public virtual object P { get; protected set; } } } namespace N2 { class B : N1.A { public override object P { get { return null; } } void M() { P = null; // no error } } } class C { void M(N2.B b) { b.P = null; // CS0272 } }"; CreateCompilation(source).VerifyDiagnostics( // (23,9): error CS0272: The property or indexer 'N2.B.P' cannot be used in this context because the set accessor is inaccessible Diagnostic(ErrorCode.ERR_InaccessibleSetter, "b.P").WithArguments("N2.B.P").WithLocation(23, 9)); } [Fact] public void CS0272ERR_InaccessibleSetter03() { CreateCompilation( @"namespace N1 { abstract class A { public virtual object this[int x] { get { return null; } protected set { } } } } namespace N2 { class B : N1.A { public override object this[int x] { get { return null; } } void M() { this[0] = null; // no error } } } class C { void M(N2.B b) { b[0] = null; // CS0272 } } ") .VerifyDiagnostics( // (23,9): error CS0272: The property or indexer 'N2.B.this[int]' cannot be used in this context because the set accessor is inaccessible Diagnostic(ErrorCode.ERR_InaccessibleSetter, "b[0]").WithArguments("N2.B.this[int]")); } [Fact] public void CS0283ERR_BadConstType() { // Test for both ERR_BadConstType and an error for RHS to ensure // the RHS is not reported multiple times (when calculating the // constant value for the symbol and also when binding). var source = @"struct S { static void M(object o) { const S s = 2; M(s); } } "; CreateCompilation(source).VerifyDiagnostics( // (5,15): error CS0283: The type 'S' cannot be declared const // const S s = 2; Diagnostic(ErrorCode.ERR_BadConstType, "S").WithArguments("S").WithLocation(5, 15), // (5,21): error CS0029: Cannot implicitly convert type 'int' to 'S' // const S s = 2; Diagnostic(ErrorCode.ERR_NoImplicitConv, "2").WithArguments("int", "S").WithLocation(5, 21)); } [Fact] public void CS0304ERR_NoNewTyvar01() { var source = @"struct S<T, U> where U : new() { void M<V>() { object o; o = new T(); o = new U(); o = new V(); } } class C<T, U> where T : struct where U : class { void M<V, W>() where V : struct where W : class, new() { object o; o = new T(); o = new U(); o = new V(); o = new W(); } }"; CreateCompilation(source).VerifyDiagnostics( // (6,13): error CS0304: Cannot create an instance of the variable type 'T' because it does not have the new() constraint Diagnostic(ErrorCode.ERR_NoNewTyvar, "new T()").WithArguments("T").WithLocation(6, 13), // (8, 13): error CS0304: Cannot create an instance of the variable type 'V' because it does not have the new() constraint Diagnostic(ErrorCode.ERR_NoNewTyvar, "new V()").WithArguments("V").WithLocation(8, 13), // (21,13): error CS0304: Cannot create an instance of the variable type 'U' because it does not have the new() constraint Diagnostic(ErrorCode.ERR_NoNewTyvar, "new U()").WithArguments("U").WithLocation(21, 13)); } [WorkItem(542377, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542377")] [Fact] public void CS0304ERR_NoNewTyvar02() { var source = @"struct S { } class C { } abstract class A<T> { public abstract U F<U>() where U : T; } class B1 : A<int> { public override U F<U>() { return new U(); } } class B2 : A<S> { public override U F<U>() { return new U(); } } class B3 : A<C> { public override U F<U>() { return new U(); } }"; CreateCompilation(source).VerifyDiagnostics( // (17,39): error CS0304: Cannot create an instance of the variable type 'U' because it does not have the new() constraint Diagnostic(ErrorCode.ERR_NoNewTyvar, "new U()").WithArguments("U").WithLocation(17, 39)); } [WorkItem(542547, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542547")] [Fact] public void CS0305ERR_BadArity() { var text = @" public class NormalType { public static int M1<T1>(T1 p1, T1 p2) { return 0; } public static int Main() { M1<int, >(10, 11); return -1; } }"; CreateCompilation(text).VerifyDiagnostics( // (7,17): error CS1031: Type expected Diagnostic(ErrorCode.ERR_TypeExpected, ">"), // (7,9): error CS0305: Using the generic method 'NormalType.M1<T1>(T1, T1)' requires 1 type arguments Diagnostic(ErrorCode.ERR_BadArity, "M1<int, >").WithArguments("NormalType.M1<T1>(T1, T1)", "method", "1")); } [Fact] public void CS0310ERR_NewConstraintNotSatisfied01() { var text = @"class A<T> { } class B { private B() { } } delegate void D(); enum E { } struct S { } class C<T, U> where T : new() { static void M<V>() where V : new() { M<A<int>>(); M<B>(); M<D>(); M<E>(); M<object>(); M<int>(); M<S>(); M<T>(); M<U>(); M<B, B>(); M<T, U>(); M<T, V>(); M<T[]>(); M<dynamic>(); } static void M<V, W>() where V : new() where W : new() { } }"; CreateCompilation(text).VerifyDiagnostics( // (14,9): error CS0310: 'B' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'V' in the generic type or method 'C<T, U>.M<V>()' Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, "M<B>").WithArguments("C<T, U>.M<V>()", "V", "B").WithLocation(14, 9), // (15,9): error CS0310: 'D' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'V' in the generic type or method 'C<T, U>.M<V>()' Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, "M<D>").WithArguments("C<T, U>.M<V>()", "V", "D").WithLocation(15, 9), // (21,9): error CS0310: 'U' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'V' in the generic type or method 'C<T, U>.M<V>()' Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, "M<U>").WithArguments("C<T, U>.M<V>()", "V", "U").WithLocation(21, 9), // (22,9): error CS0310: 'B' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'V' in the generic type or method 'C<T, U>.M<V, W>()' Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, "M<B, B>").WithArguments("C<T, U>.M<V, W>()", "V", "B").WithLocation(22, 9), // (22,9): error CS0310: 'B' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'W' in the generic type or method 'C<T, U>.M<V, W>()' Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, "M<B, B>").WithArguments("C<T, U>.M<V, W>()", "W", "B").WithLocation(22, 9), // (23,9): error CS0310: 'U' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'W' in the generic type or method 'C<T, U>.M<V, W>()' Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, "M<T, U>").WithArguments("C<T, U>.M<V, W>()", "W", "U").WithLocation(23, 9), // (25,9): error CS0310: 'T[]' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'V' in the generic type or method 'C<T, U>.M<V>()' Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, "M<T[]>").WithArguments("C<T, U>.M<V>()", "V", "T[]").WithLocation(25, 9)); } [Fact] public void CS0310ERR_NewConstraintNotSatisfied02() { var text = @"class A { } class B { internal B() { } } class C<T> where T : new() { internal static void M<U>() where U : new() { } internal static void E<U>(D<U> d) { } // Error: missing constraint on E<U> to satisfy constraint on D<U> } delegate T D<T>() where T : new(); static class E { internal static void M<T>(this object o) where T : new() { } internal static void F<T>(D<T> d) where T : new() { } } class F<T, U> where U : new() { } abstract class G { } class H : G { } interface I { } struct S { private S(object o) { } static void M() { C<A>.M<A>(); C<A>.M<B>(); C<B>.M<A>(); C<B>.M<B>(); C<G>.M<H>(); C<H>.M<G>(); C<I>.M<S>(); E.F(S.F<A>); E.F(S.F<B>); E.F(S.F<C<A>>); E.F(S.F<C<B>>); var o = new object(); o.M<A>(); o.M<B>(); o = new F<A, B>(); o = new F<B, A>(); } static T F<T>() { return default(T); } }"; // Note that none of these errors except the first one are reported by the native compiler, because // it does not report additional errors after an error is found in a formal parameter of a method. CreateCompilationWithMscorlib40(text, references: new[] { Net40.SystemCore }).VerifyDiagnostics( // (9,36): error CS0310: 'U' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method 'D<T>' // internal static void E<U>(D<U> d) { } // Error: missing constraint on E<U> to satisfy constraint on D<U> Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, "d").WithArguments("D<T>", "T", "U").WithLocation(9, 36), // (29,14): error CS0310: 'B' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'U' in the generic type or method 'C<A>.M<U>()' // C<A>.M<B>(); Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, "M<B>").WithArguments("C<A>.M<U>()", "U", "B").WithLocation(29, 14), // (30,11): error CS0310: 'B' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method 'C<T>' // C<B>.M<A>(); Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, "B").WithArguments("C<T>", "T", "B").WithLocation(30, 11), // (31,11): error CS0310: 'B' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method 'C<T>' // C<B>.M<B>(); Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, "B").WithArguments("C<T>", "T", "B").WithLocation(31, 11), // (31,14): error CS0310: 'B' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'U' in the generic type or method 'C<B>.M<U>()' // C<B>.M<B>(); Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, "M<B>").WithArguments("C<B>.M<U>()", "U", "B").WithLocation(31, 14), // (32,11): error CS0310: 'G' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method 'C<T>' // C<G>.M<H>(); Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, "G").WithArguments("C<T>", "T", "G").WithLocation(32, 11), // (33,14): error CS0310: 'G' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'U' in the generic type or method 'C<H>.M<U>()' // C<H>.M<G>(); Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, "M<G>").WithArguments("C<H>.M<U>()", "U", "G").WithLocation(33, 14), // (34,11): error CS0310: 'I' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method 'C<T>' // C<I>.M<S>(); Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, "I").WithArguments("C<T>", "T", "I").WithLocation(34, 11), // (36,11): error CS0310: 'B' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method 'E.F<T>(D<T>)' // E.F(S.F<B>); Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, "F").WithArguments("E.F<T>(D<T>)", "T", "B").WithLocation(36, 11), // (38,19): error CS0310: 'B' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method 'C<T>' // E.F(S.F<C<B>>); Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, "B").WithArguments("C<T>", "T", "B").WithLocation(38, 19), // This invocation of E.F(S.F<C<B>>) is an extremely interesting one. // First off, obviously the type argument for S.F is prima facie wrong, so we give an error for that above. // But what about the overload resolution problem in error recovery? Even though the argument is bad we still // might want to try to get an overload resolution result. Thus we must infer a type for T in E.F<T>(D<T>). // We must do overload resolution on an invocation S.F<C<B>>(). Overload resolution succeeds; it has no reason // to fail. (Overload resolution would fail if a formal parameter type of S.F<C<B>>() did not satisfy one of its // constraints, but there are no formal parameters. Also, there are no constraints at all on T in S.F<T>.) // // Thus T in D<T> is inferred to be C<B>, and thus T in E.F<T> is inferred to be C<B>. // // Now we check to see whether E.F<C<B>>(D<C<B>>) is applicable. It is inapplicable because // B fails to meet the constraints of T in C<T>. (C<B> does not fail to meet the constraints // of T in D<T> because C<B> has a public default parameterless ctor.) // // Therefore E.F<C.B>(S.F<C<B>>) fails overload resolution. Why? Because B is not valid for T in C<T>. // (We cannot say that the constraints on T in E.F<T> is unmet because again, C<B> meets the // constraint; it has a ctor.) So that is the error we report. // // This is arguably a "cascading" error; we have already reported an error for C<B> when the // argument was bound. Normally we avoid reporting "cascading" errors in overload resolution by // saying that an erroneous argument is implicitly convertible to any formal parameter type; // thus we avoid an erroneous expression from causing overload resolution to make every // candidate method inapplicable. (Though it might cause overload resolution to fail by making // every candidate method applicable, causing an ambiguity!) But the overload resolution // error here is not caused by an argument *conversion* in the first place; the overload // resolution error is caused because *the deduced formal parameter type is illegal.* // // We might want to put some gear in place to suppress this cascading error. It is not // entirely clear what that machinery might look like. // (38,11): error CS0310: 'B' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method 'C<T>' // E.F(S.F<C<B>>); Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, "F").WithArguments("C<T>", "T", "B").WithLocation(38, 11), // (41,11): error CS0310: 'B' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method 'E.M<T>(object)' // o.M<B>(); Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, "M<B>").WithArguments("E.M<T>(object)", "T", "B").WithLocation(41, 11), // (42,22): error CS0310: 'B' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'U' in the generic type or method 'F<T, U>' // o = new F<A, B>(); Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, "B").WithArguments("F<T, U>", "U", "B").WithLocation(42, 22)); } [Fact] public void CS0310ERR_NewConstraintNotSatisfied03() { var text = @"class A { } class B { private B() { } } class C<T, U> where U : struct { internal static void M<V>(V v) where V : new() { } void M() { A a = default(A); M(a); a.E(); B b = default(B); M(b); b.E(); T t = default(T); M(t); t.E(); U u1 = default(U); M(u1); u1.E(); U? u2 = null; M(u2); u2.E(); } } static class S { internal static void E<T>(this T t) where T : new() { } }"; CreateCompilationWithMscorlib40(text, references: new[] { Net40.SystemCore }).VerifyDiagnostics( // (15,9): error CS0310: 'B' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'V' in the generic type or method 'C<T, U>.M<V>(V)' // M(b); Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, "M").WithArguments("C<T, U>.M<V>(V)", "V", "B").WithLocation(15, 9), // (16,11): error CS0310: 'B' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method 'S.E<T>(T)' // b.E(); Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, "E").WithArguments("S.E<T>(T)", "T", "B").WithLocation(16, 11), // (18,9): error CS0310: 'T' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'V' in the generic type or method 'C<T, U>.M<V>(V)' // M(t); Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, "M").WithArguments("C<T, U>.M<V>(V)", "V", "T").WithLocation(18, 9), // (19,11): error CS0310: 'T' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method 'S.E<T>(T)' // t.E(); Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, "E").WithArguments("S.E<T>(T)", "T", "T").WithLocation(19, 11) ); } /// <summary> /// Constraint errors within aliases. /// </summary> [Fact] public void CS0310ERR_NewConstraintNotSatisfied04() { var text = @"using NA = N.A; using NB = N.B; using CA = N.C<N.A>; using CB = N.C<N.B>; namespace N { using CAD = C<N.A>.D; using CBD = C<N.B>.D; class A { } // public (default) .ctor class B { private B() { } } // private .ctor class C<T> where T : new() { internal static void M<U>() where U : new() { } internal class D { private D() { } // private .ctor internal static void M<U>() where U : new() { } } } class E { static void M() { C<N.A>.M<N.B>(); C<NB>.M<NA>(); C<C<N.A>.D>.M<N.A>(); C<N.A>.D.M<N.B>(); C<N.B>.D.M<N.A>(); CA.M<N.B>(); CB.M<N.A>(); CAD.M<N.B>(); CBD.M<N.A>(); C<CAD>.M<N.A>(); C<CBD>.M<N.A>(); } } }"; CreateCompilation(text).VerifyDiagnostics( // (4,7): error CS0310: 'B' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method 'C<T>' // using CB = N.C<N.B>; Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, "CB").WithArguments("N.C<T>", "T", "N.B").WithLocation(4, 7), // (8,11): error CS0310: 'B' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method 'C<T>' // using CBD = C<N.B>.D; Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, "CBD").WithArguments("N.C<T>", "T", "N.B").WithLocation(8, 11), // (24,20): error CS0310: 'B' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'U' in the generic type or method 'C<A>.M<U>()' // C<N.A>.M<N.B>(); Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, "M<N.B>").WithArguments("N.C<N.A>.M<U>()", "U", "N.B").WithLocation(24, 20), // (25,15): error CS0310: 'B' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method 'C<T>' // C<NB>.M<NA>(); Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, "NB").WithArguments("N.C<T>", "T", "N.B").WithLocation(25, 15), // (26,15): error CS0310: 'C<A>.D' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method 'C<T>' // C<C<N.A>.D>.M<N.A>(); Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, "C<N.A>.D").WithArguments("N.C<T>", "T", "N.C<N.A>.D").WithLocation(26, 15), // (27,22): error CS0310: 'B' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'U' in the generic type or method 'C<A>.D.M<U>()' // C<N.A>.D.M<N.B>(); Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, "M<N.B>").WithArguments("N.C<N.A>.D.M<U>()", "U", "N.B").WithLocation(27, 22), // (28,15): error CS0310: 'B' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method 'C<T>' // C<N.B>.D.M<N.A>(); Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, "N.B").WithArguments("N.C<T>", "T", "N.B").WithLocation(28, 15), // (29,16): error CS0310: 'B' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'U' in the generic type or method 'C<A>.M<U>()' // CA.M<N.B>(); Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, "M<N.B>").WithArguments("N.C<N.A>.M<U>()", "U", "N.B").WithLocation(29, 16), // (31,17): error CS0310: 'B' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'U' in the generic type or method 'C<A>.D.M<U>()' // CAD.M<N.B>(); Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, "M<N.B>").WithArguments("N.C<N.A>.D.M<U>()", "U", "N.B").WithLocation(31, 17), // (33,15): error CS0310: 'C<A>.D' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method 'C<T>' // C<CAD>.M<N.A>(); Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, "CAD").WithArguments("N.C<T>", "T", "N.C<N.A>.D").WithLocation(33, 15), // (34,15): error CS0310: 'C<B>.D' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method 'C<T>' // C<CBD>.M<N.A>(); Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, "CBD").WithArguments("N.C<T>", "T", "N.C<N.B>.D").WithLocation(34, 15)); } /// <summary> /// Constructors with optional and params args /// should not be considered parameterless. /// </summary> [Fact] public void CS0310ERR_NewConstraintNotSatisfied05() { var text = @"class A { public A() { } } class B { public B(object o = null) { } } class C { public C(params object[] args) { } } class D<T> where T : new() { static void M() { D<A>.M(); D<B>.M(); D<C>.M(); } }"; CreateCompilation(text).VerifyDiagnostics( // (18,11): error CS0310: 'B' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method 'D<T>' Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, "B").WithArguments("D<T>", "T", "B").WithLocation(18, 11), // (19,11): error CS0310: 'C' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method 'D<T>' Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, "C").WithArguments("D<T>", "T", "C").WithLocation(19, 11)); } [Fact] public void CS0311ERR_GenericConstraintNotSatisfiedRefType01() { var source = @"class A { } class B { } class C<T> where T : A { } class D { static void M<T>() where T : A { } static void M() { object o = new C<B>(); M<B>(); } }"; CreateCompilation(source).VerifyDiagnostics( // (9,26): error CS0311: The type 'B' cannot be used as type parameter 'T' in the generic type or method 'C<T>'. There is no implicit reference conversion from 'B' to 'A'. Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "B").WithArguments("C<T>", "A", "T", "B").WithLocation(9, 26), // (10,9): error CS0311: The type 'B' cannot be used as type parameter 'T' in the generic type or method 'D.M<T>()'. There is no implicit reference conversion from 'B' to 'A'. Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "M<B>").WithArguments("D.M<T>()", "A", "T", "B").WithLocation(10, 9)); } [Fact] public void CS0311ERR_GenericConstraintNotSatisfiedRefType02() { var source = @"class C<T, U> where U : T { void M<V>() where V : C<T, V> { } }"; CreateCompilation(source).VerifyDiagnostics( // (3,12): error CS0311: The type 'V' cannot be used as type parameter 'U' in the generic type or method 'C<T, U>'. There is no implicit reference conversion from 'V' to 'T'. Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "V").WithArguments("C<T, U>", "T", "U", "V").WithLocation(3, 12)); } [Fact] public void CS0311ERR_GenericConstraintNotSatisfiedRefType03() { var source = @"interface I<T> where T : I<I<T>> { }"; CreateCompilation(source).VerifyDiagnostics( // (1,13): error CS0311: The type 'I<T>' cannot be used as type parameter 'T' in the generic type or method 'I<T>'. There is no implicit reference conversion from 'I<T>' to 'I<I<I<T>>>'. Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "T").WithArguments("I<T>", "I<I<I<T>>>", "T", "I<T>").WithLocation(1, 13)); } [Fact] public void CS0311ERR_GenericConstraintNotSatisfiedRefType04() { var source = @"interface IA<T> { } interface IB<T> where T : IA<T> { } class C<T1, T2, T3> where T1 : IB<object[]> where T2 : IB<T2> where T3 : IB<IB<T3>[]>, IA<T3> { }"; CreateCompilation(source).VerifyDiagnostics( // (3,9): error CS0311: The type 'object[]' cannot be used as type parameter 'T' in the generic type or method 'IB<T>'. There is no implicit reference conversion from 'object[]' to 'IA<object[]>'. Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "T1").WithArguments("IB<T>", "IA<object[]>", "T", "object[]").WithLocation(3, 9), // (3,13): error CS0311: The type 'T2' cannot be used as type parameter 'T' in the generic type or method 'IB<T>'. There is no boxing conversion or type parameter conversion from 'T2' to 'IA<T2>'. Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedTyVar, "T2").WithArguments("IB<T>", "IA<T2>", "T", "T2").WithLocation(3, 13), // (3,17): error CS0311: The type 'IB<T3>[]' cannot be used as type parameter 'T' in the generic type or method 'IB<T>'. There is no implicit reference conversion from 'IB<T3>[]' to 'IA<IB<T3>[]>'. Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "T3").WithArguments("IB<T>", "IA<IB<T3>[]>", "T", "IB<T3>[]").WithLocation(3, 17)); } [Fact] public void CS0311ERR_GenericConstraintNotSatisfiedRefType05() { var source = @"namespace N { class C<T, U> where U : T { static object F() { return null; } static object G<V>() where V : T { return null; } static void M() { object o; o = C<int, object>.F(); o = N.C<int, int>.G<string>(); } } }"; CreateCompilation(source).VerifyDiagnostics( // (16,24): error CS0311: The type 'object' cannot be used as type parameter 'U' in the generic type or method 'C<T, U>'. There is no implicit reference conversion from 'object' to 'int'. // o = C<int, object>.F(); Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "object").WithArguments("N.C<T, U>", "int", "U", "object").WithLocation(16, 24), // (17,31): error CS0311: The type 'string' cannot be used as type parameter 'V' in the generic type or method 'C<int, int>.G<V>()'. There is no implicit reference conversion from 'string' to 'int'. // o = N.C<int, int>.G<string>(); Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "G<string>").WithArguments("N.C<int, int>.G<V>()", "int", "V", "string").WithLocation(17, 31)); } [Fact] public void CS0312ERR_GenericConstraintNotSatisfiedNullableEnum() { var source = @"class A<T, U> where T : U { } class B<T> { static void M<U>() where U : T { } static void M() { object o = new A<int?, int>(); B<int>.M<int?>(); } }"; CreateCompilation(source).VerifyDiagnostics( // (7,26): error CS0312: The type 'int?' cannot be used as type parameter 'T' in the generic type or method 'A<T, U>'. The nullable type 'int?' does not satisfy the constraint of 'int'. // object o = new A<int?, int>(); Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedNullableEnum, "int?").WithArguments("A<T, U>", "int", "T", "int?").WithLocation(7, 26), // (8,16): error CS0312: The type 'int?' cannot be used as type parameter 'U' in the generic type or method 'B<int>.M<U>()'. The nullable type 'int?' does not satisfy the constraint of 'int'. // B<int>.M<int?>(); Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedNullableEnum, "M<int?>").WithArguments("B<int>.M<U>()", "int", "U", "int?").WithLocation(8, 16)); } [Fact] public void CS0313ERR_GenericConstraintNotSatisfiedNullableInterface() { var source = @"interface I { } struct S : I { } class A<T> where T : I { } class B { static void M<T>() where T : I { } static void M() { object o = new A<S?>(); M<S?>(); } }"; CreateCompilation(source).VerifyDiagnostics( // (9,26): error CS0313: The type 'S?' cannot be used as type parameter 'T' in the generic type or method 'A<T>'. The nullable type 'S?' does not satisfy the constraint of 'I'. Nullable types can not satisfy any interface constraints. Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedNullableInterface, "S?").WithArguments("A<T>", "I", "T", "S?").WithLocation(9, 26), // (10,9): error CS0313: The type 'S?' cannot be used as type parameter 'T' in the generic type or method 'B.M<T>()'. The nullable type 'S?' does not satisfy the constraint of 'I'. Nullable types can not satisfy any interface constraints. Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedNullableInterface, "M<S?>").WithArguments("B.M<T>()", "I", "T", "S?").WithLocation(10, 9)); } [Fact] public void CS0314ERR_GenericConstraintNotSatisfiedTyVar01() { var source = @"class A { } class B<T> where T : A { } class C<T> where T : struct { static void M<U>() where U : A { } static void M() { object o = new B<T>(); M<T>(); } }"; CreateCompilation(source).VerifyDiagnostics( // (8,26): error CS0314: The type 'T' cannot be used as type parameter 'T' in the generic type or method 'B<T>'. There is no boxing conversion or type parameter conversion from 'T' to 'A'. Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedTyVar, "T").WithArguments("B<T>", "A", "T", "T").WithLocation(8, 26), // (9,9): error CS0314: The type 'T' cannot be used as type parameter 'U' in the generic type or method 'C<T>.M<U>()'. There is no boxing conversion or type parameter conversion from 'T' to 'A'. Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedTyVar, "M<T>").WithArguments("C<T>.M<U>()", "A", "U", "T").WithLocation(9, 9)); } [Fact] public void CS0314ERR_GenericConstraintNotSatisfiedTyVar02() { var source = @"class C<T, U> where U : T { void M<V>() where V : C<V, U> { } }"; CreateCompilation(source).VerifyDiagnostics( // (3,12): error CS0314: The type 'U' cannot be used as type parameter 'U' in the generic type or method 'C<T, U>'. There is no boxing conversion or type parameter conversion from 'U' to 'V'. Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedTyVar, "V").WithArguments("C<T, U>", "V", "U", "U").WithLocation(3, 12)); } [Fact] public void CS0314ERR_GenericConstraintNotSatisfiedTyVar03() { var source = @"interface IA<T> where T : IB<T> { } interface IB<T> where T : IA<T> { }"; CreateCompilation(source).VerifyDiagnostics( // (1,14): error CS0314: The type 'T' cannot be used as type parameter 'T' in the generic type or method 'IB<T>'. There is no boxing conversion or type parameter conversion from 'T' to 'IA<T>'. Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedTyVar, "T").WithArguments("IB<T>", "IA<T>", "T", "T").WithLocation(1, 14), // (2,14): error CS0314: The type 'T' cannot be used as type parameter 'T' in the generic type or method 'IA<T>'. There is no boxing conversion or type parameter conversion from 'T' to 'IB<T>'. Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedTyVar, "T").WithArguments("IA<T>", "IB<T>", "T", "T").WithLocation(2, 14)); } [Fact] public void CS0315ERR_GenericConstraintNotSatisfiedValType() { var source = @"class A { } class B<T> where T : A { } struct S { } class C { static void M<T, U>() where U : A { } static void M() { object o = new B<S>(); M<int, double>(); } }"; CreateCompilation(source).VerifyDiagnostics( // (9,26): error CS0315: The type 'S' cannot be used as type parameter 'T' in the generic type or method 'B<T>'. There is no boxing conversion from 'S' to 'A'. Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedValType, "S").WithArguments("B<T>", "A", "T", "S").WithLocation(9, 26), // (10,9): error CS0315: The type 'double?' cannot be used as type parameter 'U' in the generic type or method 'C.M<T, U>()'. There is no boxing conversion from 'double?' to 'A'. Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedValType, "M<int, double>").WithArguments("C.M<T, U>()", "A", "U", "double").WithLocation(10, 9)); } [Fact] public void CS0316ERR_DuplicateGeneratedName() { var text = @" public class Test { public int this[int value] // CS0316 { get { return 1; } set { } } public int this[char @value] // CS0316 { get { return 1; } set { } } public int this[string value] // no error since no setter { get { return 1; } } } "; CreateCompilation(text).VerifyDiagnostics( // (10,26): error CS0316: The parameter name 'value' conflicts with an automatically-generated parameter name // public int this[char @value] // CS0316 Diagnostic(ErrorCode.ERR_DuplicateGeneratedName, "@value").WithArguments("value").WithLocation(10, 26), // (4,25): error CS0316: The parameter name 'value' conflicts with an automatically-generated parameter name // public int this[int value] // CS0316 Diagnostic(ErrorCode.ERR_DuplicateGeneratedName, "value").WithArguments("value").WithLocation(4, 25)); } [Fact] public void CS0403ERR_TypeVarCantBeNull() { var source = @"interface I { } class A { } class B<T1, T2, T3, T4, T5, T6, T7> where T2 : class where T3 : struct where T4 : new() where T5 : I where T6 : A where T7 : T1 { static void M() { T1 t1 = null; T2 t2 = null; T3 t3 = null; T4 t4 = null; T5 t5 = null; T6 t6 = null; T7 t7 = null; } static T1 F1() { return null; } static T2 F2() { return null; } static T3 F3() { return null; } static T4 F4() { return null; } static T5 F5() { return null; } static T6 F6() { return null; } static T7 F7() { return null; } }"; CreateCompilation(source).VerifyDiagnostics( // (13,17): error CS0403: Cannot convert null to type parameter 'T1' because it could be a non-nullable value type. Consider using 'default(T1)' instead. // T1 t1 = null; Diagnostic(ErrorCode.ERR_TypeVarCantBeNull, "null").WithArguments("T1"), // (15,17): error CS0403: Cannot convert null to type parameter 'T3' because it could be a non-nullable value type. Consider using 'default(T3)' instead. // T3 t3 = null; Diagnostic(ErrorCode.ERR_TypeVarCantBeNull, "null").WithArguments("T3"), // (16,17): error CS0403: Cannot convert null to type parameter 'T4' because it could be a non-nullable value type. Consider using 'default(T4)' instead. // T4 t4 = null; Diagnostic(ErrorCode.ERR_TypeVarCantBeNull, "null").WithArguments("T4"), // (17,17): error CS0403: Cannot convert null to type parameter 'T5' because it could be a non-nullable value type. Consider using 'default(T5)' instead. // T5 t5 = null; Diagnostic(ErrorCode.ERR_TypeVarCantBeNull, "null").WithArguments("T5"), // (19,17): error CS0403: Cannot convert null to type parameter 'T7' because it could be a non-nullable value type. Consider using 'default(T7)' instead. // T7 t7 = null; Diagnostic(ErrorCode.ERR_TypeVarCantBeNull, "null").WithArguments("T7"), // (14,12): warning CS0219: The variable 't2' is assigned but its value is never used // T2 t2 = null; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "t2").WithArguments("t2"), // (18,12): warning CS0219: The variable 't6' is assigned but its value is never used // T6 t6 = null; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "t6").WithArguments("t6"), // (21,29): error CS0403: Cannot convert null to type parameter 'T1' because it could be a non-nullable value type. Consider using 'default(T1)' instead. // static T1 F1() { return null; } Diagnostic(ErrorCode.ERR_TypeVarCantBeNull, "null").WithArguments("T1"), // (23,29): error CS0403: Cannot convert null to type parameter 'T3' because it could be a non-nullable value type. Consider using 'default(T3)' instead. // static T3 F3() { return null; } Diagnostic(ErrorCode.ERR_TypeVarCantBeNull, "null").WithArguments("T3"), // (24,29): error CS0403: Cannot convert null to type parameter 'T4' because it could be a non-nullable value type. Consider using 'default(T4)' instead. // static T4 F4() { return null; } Diagnostic(ErrorCode.ERR_TypeVarCantBeNull, "null").WithArguments("T4"), // (25,29): error CS0403: Cannot convert null to type parameter 'T5' because it could be a non-nullable value type. Consider using 'default(T5)' instead. // static T5 F5() { return null; } Diagnostic(ErrorCode.ERR_TypeVarCantBeNull, "null").WithArguments("T5"), // (27,29): error CS0403: Cannot convert null to type parameter 'T7' because it could be a non-nullable value type. Consider using 'default(T7)' instead. // static T7 F7() { return null; } Diagnostic(ErrorCode.ERR_TypeVarCantBeNull, "null").WithArguments("T7") ); } [WorkItem(539901, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539901")] [Fact] public void CS0407ERR_BadRetType_01() { var text = @" public delegate int MyDelegate(); class C { MyDelegate d; public C() { d = new MyDelegate(F); // OK: F returns int d = new MyDelegate(G); // CS0407 - G doesn't return int } public int F() { return 1; } public void G() { } public static void Main() { C c1 = new C(); } } "; CreateCompilation(text, parseOptions: TestOptions.WithoutImprovedOverloadCandidates).VerifyDiagnostics( // (11,28): error CS0407: 'void C.G()' has the wrong return type // d = new MyDelegate(G); // CS0407 - G doesn't return int Diagnostic(ErrorCode.ERR_BadRetType, "G").WithArguments("C.G()", "void").WithLocation(11, 28) ); CreateCompilation(text).VerifyDiagnostics( // (11,28): error CS0407: 'void C.G()' has the wrong return type // d = new MyDelegate(G); // CS0407 - G doesn't return int Diagnostic(ErrorCode.ERR_BadRetType, "G").WithArguments("C.G()", "void").WithLocation(11, 28) ); } [WorkItem(925899, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/925899")] [Fact] public void CS0407ERR_BadRetType_02() { var text = @" using System; class C { public static void Main() { var oo = new Func<object, object>(x => 1); var os = new Func<object, string>(oo); var ss = new Func<string, string>(oo); } } "; CreateCompilation(text, parseOptions: TestOptions.WithoutImprovedOverloadCandidates).VerifyDiagnostics( // (10,43): error CS0407: 'object System.Func<object, object>.Invoke(object)' has the wrong return type // var os = new Func<object, string>(oo); Diagnostic(ErrorCode.ERR_BadRetType, "oo").WithArguments("System.Func<object, object>.Invoke(object)", "object").WithLocation(10, 43), // (11,43): error CS0407: 'object System.Func<object, object>.Invoke(object)' has the wrong return type // var ss = new Func<string, string>(oo); Diagnostic(ErrorCode.ERR_BadRetType, "oo").WithArguments("System.Func<object, object>.Invoke(object)", "object").WithLocation(11, 43) ); CreateCompilation(text).VerifyDiagnostics( // (10,43): error CS0407: 'object Func<object, object>.Invoke(object)' has the wrong return type // var os = new Func<object, string>(oo); Diagnostic(ErrorCode.ERR_BadRetType, "oo").WithArguments("System.Func<object, object>.Invoke(object)", "object").WithLocation(10, 43), // (11,43): error CS0407: 'object Func<object, object>.Invoke(object)' has the wrong return type // var ss = new Func<string, string>(oo); Diagnostic(ErrorCode.ERR_BadRetType, "oo").WithArguments("System.Func<object, object>.Invoke(object)", "object").WithLocation(11, 43) ); } [WorkItem(539924, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539924")] [Fact] public void CS0407ERR_BadRetType_03() { var text = @" delegate DerivedClass MyDerivedDelegate(DerivedClass x); public class BaseClass { public static BaseClass DelegatedMethod(BaseClass x) { System.Console.WriteLine(""Base""); return x; } } public class DerivedClass : BaseClass { public static DerivedClass DelegatedMethod(DerivedClass x) { System.Console.WriteLine(""Derived""); return x; } static void Main(string[] args) { MyDerivedDelegate goo1 = null; goo1 += BaseClass.DelegatedMethod; goo1 += DerivedClass.DelegatedMethod; goo1(new DerivedClass()); } } "; CreateCompilation(text).VerifyDiagnostics( // (21,17): error CS0407: 'BaseClass BaseClass.DelegatedMethod(BaseClass)' has the wrong return type Diagnostic(ErrorCode.ERR_BadRetType, "BaseClass.DelegatedMethod").WithArguments("BaseClass.DelegatedMethod(BaseClass)", "BaseClass")); } [WorkItem(3401, "DevDiv_Projects/Roslyn")] [Fact] public void CS0411ERR_CantInferMethTypeArgs01() { var text = @" class C { public void F<T>(T t) where T : C { } public static void Main() { C c = new C(); c.F(null); // CS0411 } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_CantInferMethTypeArgs, Line = 11, Column = 11 } }); } [WorkItem(2099, "https://devdiv.visualstudio.com:443/defaultcollection/DevDiv/_workitems/edit/2099")] [Fact(Skip = "529560")] public void CS0411ERR_CantInferMethTypeArgs02() { var text = @" public class MemberInitializerTest { delegate void D<T>(); public static void GenericMethod<T>() { } public static void Run() { var genD = (D<int>)GenericMethod; } }"; CreateCompilation(text).VerifyDiagnostics( // (8,20): error CS0030: The type arguments for method 'MemberInitializerTest.GenericMethod<T>()' cannot be inferred from the usage. Try specifying the type arguments explicitly. // var genD = (D<int>)GenericMethod; Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "(D<int>)GenericMethod").WithArguments("MemberInitializerTest.GenericMethod<T>()") ); } [Fact] public void CS0412ERR_LocalSameNameAsTypeParam() { var text = @" using System; class C { // Parameter name is the same as method type parameter name public void G<T>(int T) // CS0412 { } public void F<T>() { // Method local variable name is the same as method type // parameter name double T = 0.0; // CS0412 Console.WriteLine(T); } public static void Main() { } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_LocalSameNameAsTypeParam, Line = 7, Column = 26 }, new ErrorDescription { Code = (int)ErrorCode.ERR_LocalSameNameAsTypeParam, Line = 14, Column = 16 } }); } [Fact] public void CS0413ERR_AsWithTypeVar() { var source = @"interface I { } class A { } class B<T1, T2, T3, T4, T5, T6, T7> where T2 : class where T3 : struct where T4 : new() where T5 : I where T6 : A where T7 : T1 { static void M(object o) { o = o as T1; o = o as T2; o = o as T3; o = o as T4; o = o as T5; o = o as T6; o = o as T7; } }"; CreateCompilation(source).VerifyDiagnostics( // (13,13): error CS0413: The type parameter 'T1' cannot be used with the 'as' operator because it does not have a class type constraint nor a 'class' constraint Diagnostic(ErrorCode.ERR_AsWithTypeVar, "o as T1").WithArguments("T1").WithLocation(13, 13), // (15,13): error CS0413: The type parameter 'T3' cannot be used with the 'as' operator because it does not have a class type constraint nor a 'class' constraint Diagnostic(ErrorCode.ERR_AsWithTypeVar, "o as T3").WithArguments("T3").WithLocation(15, 13), // (16,13): error CS0413: The type parameter 'T4' cannot be used with the 'as' operator because it does not have a class type constraint nor a 'class' constraint Diagnostic(ErrorCode.ERR_AsWithTypeVar, "o as T4").WithArguments("T4").WithLocation(16, 13), // (17,13): error CS0413: The type parameter 'T5' cannot be used with the 'as' operator because it does not have a class type constraint nor a 'class' constraint Diagnostic(ErrorCode.ERR_AsWithTypeVar, "o as T5").WithArguments("T5").WithLocation(17, 13), // (19,13): error CS0413: The type parameter 'T7' cannot be used with the 'as' operator because it does not have a class type constraint nor a 'class' constraint Diagnostic(ErrorCode.ERR_AsWithTypeVar, "o as T7").WithArguments("T7").WithLocation(19, 13)); } [Fact] public void CS0417ERR_NewTyvarWithArgs01() { var source = @"struct S<T> where T : new() { T F(object o) { return new T(o); } U G<U, V>(object o) where U : new() where V : struct { return new U(new V(o)); } }"; CreateCompilation(source).VerifyDiagnostics( // (5,16): error CS0417: 'T': cannot provide arguments when creating an instance of a variable type Diagnostic(ErrorCode.ERR_NewTyvarWithArgs, "new T(o)").WithArguments("T").WithLocation(5, 16), // (11,16): error CS0417: 'U': cannot provide arguments when creating an instance of a variable type Diagnostic(ErrorCode.ERR_NewTyvarWithArgs, "new U(new V(o))").WithArguments("U").WithLocation(11, 16), // (11,22): error CS0417: 'V': cannot provide arguments when creating an instance of a variable type Diagnostic(ErrorCode.ERR_NewTyvarWithArgs, "new V(o)").WithArguments("V").WithLocation(11, 22)); } [Fact] public void CS0417ERR_NewTyvarWithArgs02() { var source = @"class C { public C() { } public C(object o) { } static void M<T>() where T : C, new() { new T(); new T(null); } }"; CreateCompilation(source).VerifyDiagnostics( // (8,9): error CS0417: 'T': cannot provide arguments when creating an instance of a variable type Diagnostic(ErrorCode.ERR_NewTyvarWithArgs, "new T(null)").WithArguments("T").WithLocation(8, 9)); } [Fact] public void CS0428ERR_MethGrpToNonDel() { var text = @" namespace ConsoleApplication1 { class Program { delegate int Del1(); delegate object Del2(); static void Main(string[] args) { ExampleClass ec = new ExampleClass(); int i = ec.Method1; Del1 d1 = ec.Method1; i = ec.Method1(); ec = ExampleClass.Method2; Del2 d2 = ExampleClass.Method2; ec = ExampleClass.Method2(); } } public class ExampleClass { public int Method1() { return 1; } public static ExampleClass Method2() { return null; } } }"; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_MethGrpToNonDel, Line = 12, Column = 24 }, new ErrorDescription { Code = (int)ErrorCode.ERR_MethGrpToNonDel, Line = 15, Column = 31 }}); } [Fact, WorkItem(528649, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528649")] public void CS0431ERR_ColColWithTypeAlias() { var text = @" using AliasC = C; class C { public class Goo { } } class Test { class C { } static int Main() { AliasC::Goo goo = new AliasC::Goo(); return 0; } }"; CreateCompilation(text).VerifyDiagnostics( Diagnostic(ErrorCode.ERR_ColColWithTypeAlias, "AliasC").WithArguments("AliasC"), Diagnostic(ErrorCode.ERR_ColColWithTypeAlias, "AliasC").WithArguments("AliasC")); } [WorkItem(3402, "DevDiv_Projects/Roslyn")] [Fact] public void CS0445ERR_UnboxNotLValue() { var text = @" namespace ConsoleApplication1 { // CS0445.CS class UnboxingTest { public static void Main() { Point p = new Point(); p.x = 1; p.y = 5; object obj = p; // Generates CS0445: ((Point)obj).x = 2; } } public struct Point { public int x; public int y; } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_UnboxNotLValue, Line = 15, Column = 13 } }); } [Fact] public void CS0446ERR_AnonMethGrpInForEach() { var text = @" class Tester { static void Main() { int[] intArray = new int[5]; foreach (int i in M) { } // CS0446 } static void M() { } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_AnonMethGrpInForEach, Line = 7, Column = 27 } }); } [Fact] [WorkItem(36203, "https://github.com/dotnet/roslyn/issues/36203")] public void CS0452_GenericConstraintError_HasHigherPriorityThanMethodOverloadError() { var code = @" class Code { void GenericMethod<T>(int i) where T: class => throw null; void GenericMethod<T>(string s) => throw null; void IncorrectMethodCall() { GenericMethod<int>(1); } }"; CreateCompilation(code).VerifyDiagnostics( // (9,9): error CS0452: The type 'int' must be a reference type in order to use it as parameter 'T' in the generic type or method 'Code.GenericMethod<T>(int)' Diagnostic(ErrorCode.ERR_RefConstraintNotSatisfied, "GenericMethod<int>").WithArguments("Code.GenericMethod<T>(int)", "T", "int").WithLocation(9, 9)); } [Fact] public void CS0457ERR_AmbigUDConv() { var text = @" public class A { } public class G0 { } public class G1<R> : G0 { } public class H0 { public static implicit operator G0(H0 h) { return new G0(); } } public class H1<R> : H0 { public static implicit operator G1<R>(H1<R> h) { return new G1<R>(); } } public class Test { public static void F0(G0 g) { } public static void Main() { H1<A> h1a = new H1<A>(); F0(h1a); // CS0457 } } "; CreateCompilation(text).VerifyDiagnostics( // (24,10): error CS0457: Ambiguous user defined conversions 'H1<A>.implicit operator G1<A>(H1<A>)' and 'H0.implicit operator G0(H0)' when converting from 'H1<A>' to 'G0' Diagnostic(ErrorCode.ERR_AmbigUDConv, "h1a").WithArguments("H1<A>.implicit operator G1<A>(H1<A>)", "H0.implicit operator G0(H0)", "H1<A>", "G0")); } [WorkItem(22306, "https://github.com/dotnet/roslyn/issues/22306")] [Fact] public void AddrOnReadOnlyLocal() { var text = @" class A { public unsafe void M1() { int[] ints = new int[] { 1, 2, 3 }; foreach (int i in ints) { int *j = &i; } fixed (int *i = &_i) { int **j = &i; } } private int _i = 0; } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(); } [Fact] public void CS0463ERR_DecConstError() { var text = @" using System; class MyClass { public static void Main() { const decimal myDec = 79000000000000000000000000000.0m + 79000000000000000000000000000.0m; // CS0463 Console.WriteLine(myDec.ToString()); } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_DecConstError, Line = 7, Column = 31 } }); } [WorkItem(543272, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543272")] [Fact] public void CS0463ERR_DecConstError_02() { var text = @" class MyClass { public static void Main() { decimal x1 = decimal.MaxValue + 1; // CS0463 decimal x2 = decimal.MaxValue + decimal.One; // CS0463 decimal x3 = decimal.MinValue - decimal.One; // CS0463 decimal x4 = decimal.MinValue + decimal.MinusOne; // CS0463 decimal x5 = decimal.MaxValue - decimal.MinValue; // CS0463 } } "; CreateCompilation(text).VerifyDiagnostics( // (6,22): error CS0463: Evaluation of the decimal constant expression failed // decimal x1 = decimal.MaxValue + 1; // CS0463 Diagnostic(ErrorCode.ERR_DecConstError, "decimal.MaxValue + 1"), // (7,22): error CS0463: Evaluation of the decimal constant expression failed // decimal x2 = decimal.MaxValue + decimal.One; // CS0463 Diagnostic(ErrorCode.ERR_DecConstError, "decimal.MaxValue + decimal.One"), // (8,22): error CS0463: Evaluation of the decimal constant expression failed // decimal x3 = decimal.MinValue - decimal.One; // CS0463 Diagnostic(ErrorCode.ERR_DecConstError, "decimal.MinValue - decimal.One"), // (9,22): error CS0463: Evaluation of the decimal constant expression failed // decimal x4 = decimal.MinValue + decimal.MinusOne; // CS0463 Diagnostic(ErrorCode.ERR_DecConstError, "decimal.MinValue + decimal.MinusOne"), // (10,22): error CS0463: Evaluation of the decimal constant expression failed // decimal x5 = decimal.MaxValue - decimal.MinValue; // CS0463 Diagnostic(ErrorCode.ERR_DecConstError, "decimal.MaxValue - decimal.MinValue")); } [Fact()] public void CS0471ERR_TypeArgsNotAllowedAmbig() { var text = @" class Test { public void F(bool x, bool y) {} public void F1() { int a = 1, b = 2, c = 3; F(a<b, c>(3)); // CS0471 // To resolve, try the following instead: // F((a<b), c>(3)); } } "; //Dev11 used to give 'The {1} '{0}' is not a generic method. If you intended an expression list, use parentheses around the &lt; expression.' //Roslyn will be satisfied with something less helpful. var noWarns = new Dictionary<string, ReportDiagnostic>(); noWarns.Add(MessageProvider.Instance.GetIdForErrorCode(219), ReportDiagnostic.Suppress); CreateCompilation(text, options: TestOptions.ReleaseDll.WithSpecificDiagnosticOptions(noWarns)).VerifyDiagnostics( // (8,13): error CS0118: 'b' is a variable but is used like a type // F(a<b, c>(3)); // CS0471 Diagnostic(ErrorCode.ERR_BadSKknown, "b").WithArguments("b", "variable", "type"), // (8,16): error CS0118: 'c' is a variable but is used like a type // F(a<b, c>(3)); // CS0471 Diagnostic(ErrorCode.ERR_BadSKknown, "c").WithArguments("c", "variable", "type"), // (8,11): error CS0307: The variable 'a' cannot be used with type arguments // F(a<b, c>(3)); // CS0471 Diagnostic(ErrorCode.ERR_TypeArgsNotAllowed, "a<b, c>").WithArguments("a", "variable")); } [Fact] public void CS0516ERR_RecursiveConstructorCall() { var text = @" namespace x { public class clx { public clx() : this() // CS0516 { } public static void Main() { } } } "; CreateCompilation(text).VerifyDiagnostics( // (6,22): error CS0516: Constructor 'x.clx.clx()' cannot call itself Diagnostic(ErrorCode.ERR_RecursiveConstructorCall, "this").WithArguments("x.clx.clx()")); } [WorkItem(751825, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/751825")] [Fact] public void Repro751825() { var text = @" public class A : A<int> { public A() : base() { } } "; CreateCompilation(text).VerifyDiagnostics( // (2,18): error CS0308: The non-generic type 'A' cannot be used with type arguments // public class A : A<int> Diagnostic(ErrorCode.ERR_HasNoTypeVars, "A<int>").WithArguments("A", "type"), // (4,18): error CS0516: Constructor 'A.A()' cannot call itself // public A() : base() { } Diagnostic(ErrorCode.ERR_RecursiveConstructorCall, "base").WithArguments("A.A()")); } [WorkItem(366, "https://github.com/dotnet/roslyn/issues/366")] [Fact] public void IndirectConstructorCycle() { var text = @" public class A { public A() : this(1) {} public A(int x) : this(string.Empty) {} public A(string s) : this(1) {} public A(long l) : this(double.MaxValue) {} public A(double d) : this(char.MaxValue) {} public A(char c) : this(long.MaxValue) {} public A(short s) : this() {} } "; CreateCompilation(text).VerifyDiagnostics( // (6,24): error CS0768: Constructor 'A.A(string)' cannot call itself through another constructor // public A(string s) : this(1) {} Diagnostic(ErrorCode.ERR_IndirectRecursiveConstructorCall, ": this(1)").WithArguments("A.A(string)").WithLocation(6, 24), // (9,22): error CS0768: Constructor 'A.A(char)' cannot call itself through another constructor // public A(char c) : this(long.MaxValue) {} Diagnostic(ErrorCode.ERR_IndirectRecursiveConstructorCall, ": this(long.MaxValue)").WithArguments("A.A(char)").WithLocation(9, 22) ); } [Fact] public void CS0517ERR_ObjectCallingBaseConstructor() { var text = @"namespace System { public class Void { } //just need the type to be defined public class Object { public Object() : base() { } } } "; CreateEmptyCompilation(text).VerifyDiagnostics( // (7,16): error CS0517: 'object' has no base class and cannot call a base constructor Diagnostic(ErrorCode.ERR_ObjectCallingBaseConstructor, "Object").WithArguments("object")); } [Fact] public void CS0522ERR_StructWithBaseConstructorCall() { var text = @" public class clx { public clx(int i) { } public static void Main() { } } public struct cly { public cly(int i):base(0) // CS0522 // try the following line instead // public cly(int i) { } } "; CreateCompilation(text).VerifyDiagnostics( // (15,11): error CS0522: 'cly': structs cannot call base class constructors Diagnostic(ErrorCode.ERR_StructWithBaseConstructorCall, "cly").WithArguments("cly")); } [Fact] public void CS0543ERR_EnumeratorOverflow01() { var source = @"enum E { A = int.MaxValue - 1, B, C, // CS0543 D, E = C, F, G = B, H, // CS0543 I } "; CreateCompilation(source).VerifyDiagnostics( // (5,5): error CS0543: 'E.C': the enumerator value is too large to fit in its type // C, // CS0543 Diagnostic(ErrorCode.ERR_EnumeratorOverflow, "C").WithArguments("E.C").WithLocation(5, 5), // (10,5): error CS0543: 'E.H': the enumerator value is too large to fit in its type // H, // CS0543 Diagnostic(ErrorCode.ERR_EnumeratorOverflow, "H").WithArguments("E.H").WithLocation(10, 5)); } [Fact] public void CS0543ERR_EnumeratorOverflow02() { var source = @"namespace N { enum E : byte { A = 255, B, C } enum F : short { A = 0x00ff, B = 0x7f00, C = A | B, D } enum G : int { X = int.MinValue, Y = X - 1, Z } } "; CreateCompilation(source).VerifyDiagnostics( // (3,30): error CS0543: 'E.B': the enumerator value is too large to fit in its type // enum E : byte { A = 255, B, C } Diagnostic(ErrorCode.ERR_EnumeratorOverflow, "B").WithArguments("N.E.B").WithLocation(3, 30), // (5,42): error CS0220: The operation overflows at compile time in checked mode // enum G : int { X = int.MinValue, Y = X - 1, Z } Diagnostic(ErrorCode.ERR_CheckedOverflow, "X - 1").WithLocation(5, 42), // (4,57): error CS0543: 'F.D': the enumerator value is too large to fit in its type // enum F : short { A = 0x00ff, B = 0x7f00, C = A | B, D } Diagnostic(ErrorCode.ERR_EnumeratorOverflow, "D").WithArguments("N.F.D").WithLocation(4, 57)); } [Fact] public void CS0543ERR_EnumeratorOverflow03() { var source = @"enum S8 : sbyte { A = sbyte.MinValue, B, C, D = -1, E, F, G = sbyte.MaxValue - 2, H, I, J, K } enum S16 : short { A = short.MinValue, B, C, D = -1, E, F, G = short.MaxValue - 2, H, I, J, K } enum S32 : int { A = int.MinValue, B, C, D = -1, E, F, G = int.MaxValue - 2, H, I, J, K } enum S64 : long { A = long.MinValue, B, C, D = -1, E, F, G = long.MaxValue - 2, H, I, J, K } enum U8 : byte { A = 0, B, C, D = byte.MaxValue - 2, E, F, G, H } enum U16 : ushort { A = 0, B, C, D = ushort.MaxValue - 2, E, F, G, H } enum U32 : uint { A = 0, B, C, D = uint.MaxValue - 2, E, F, G, H } enum U64 : ulong { A = 0, B, C, D = ulong.MaxValue - 2, E, F, G, H } "; CreateCompilation(source).VerifyDiagnostics( // (3,84): error CS0543: 'S32.J': the enumerator value is too large to fit in its type // enum S32 : int { A = int.MinValue, B, C, D = -1, E, F, G = int.MaxValue - 2, H, I, J, K } Diagnostic(ErrorCode.ERR_EnumeratorOverflow, "J").WithArguments("S32.J").WithLocation(3, 84), // (4,87): error CS0543: 'S64.J': the enumerator value is too large to fit in its type // enum S64 : long { A = long.MinValue, B, C, D = -1, E, F, G = long.MaxValue - 2, H, I, J, K } Diagnostic(ErrorCode.ERR_EnumeratorOverflow, "J").WithArguments("S64.J").WithLocation(4, 87), // (7,61): error CS0543: 'U32.G': the enumerator value is too large to fit in its type // enum U32 : uint { A = 0, B, C, D = uint.MaxValue - 2, E, F, G, H } Diagnostic(ErrorCode.ERR_EnumeratorOverflow, "G").WithArguments("U32.G").WithLocation(7, 61), // (6,65): error CS0543: 'U16.G': the enumerator value is too large to fit in its type // enum U16 : ushort { A = 0, B, C, D = ushort.MaxValue - 2, E, F, G, H } Diagnostic(ErrorCode.ERR_EnumeratorOverflow, "G").WithArguments("U16.G").WithLocation(6, 65), // (5,60): error CS0543: 'U8.G': the enumerator value is too large to fit in its type // enum U8 : byte { A = 0, B, C, D = byte.MaxValue - 2, E, F, G, H } Diagnostic(ErrorCode.ERR_EnumeratorOverflow, "G").WithArguments("U8.G").WithLocation(5, 60), // (2,90): error CS0543: 'S16.J': the enumerator value is too large to fit in its type // enum S16 : short { A = short.MinValue, B, C, D = -1, E, F, G = short.MaxValue - 2, H, I, J, K } Diagnostic(ErrorCode.ERR_EnumeratorOverflow, "J").WithArguments("S16.J").WithLocation(2, 90), // (1,89): error CS0543: 'S8.J': the enumerator value is too large to fit in its type // enum S8 : sbyte { A = sbyte.MinValue, B, C, D = -1, E, F, G = sbyte.MaxValue - 2, H, I, J, K } Diagnostic(ErrorCode.ERR_EnumeratorOverflow, "J").WithArguments("S8.J").WithLocation(1, 89), // (8,63): error CS0543: 'U64.G': the enumerator value is too large to fit in its type // enum U64 : ulong { A = 0, B, C, D = ulong.MaxValue - 2, E, F, G, H } Diagnostic(ErrorCode.ERR_EnumeratorOverflow, "G").WithArguments("U64.G").WithLocation(8, 63)); } [Fact] public void CS0543ERR_EnumeratorOverflow04() { string source = string.Format( @"enum A {0} enum B : byte {1} enum C : byte {2} enum D : sbyte {3}", CreateEnumValues(300, "E"), CreateEnumValues(256, "E"), CreateEnumValues(300, "E"), CreateEnumValues(300, "E", sbyte.MinValue)); CreateCompilation(source).VerifyDiagnostics( // (3,1443): error CS0543: 'C.E256': the enumerator value is too large to fit in its type // enum C : byte { E0, E1, E2, E3, E4, E5, E6, E7, E8, E9, E10, E11, E12, E13, E14, E15, E16, E17, E18, E19, E20, E21, E22, E23, E24, E25, E26, E27, E28, E29, E30, E31, E32, E33, E34, E35, E36, E37, E38, E39, E40, E41, E42, E43, E44, E45, E46, E47, E48, E49, E50, E51, E52, E53, E54, E55, E56, E57, E58, E59, E60, E61, E62, E63, E64, E65, E66, E67, E68, E69, E70, E71, E72, E73, E74, E75, E76, E77, E78, E79, E80, E81, E82, E83, E84, E85, E86, E87, E88, E89, E90, E91, E92, E93, E94, E95, E96, E97, E98, E99, E100, E101, E102, E103, E104, E105, E106, E107, E108, E109, E110, E111, E112, E113, E114, E115, E116, E117, E118, E119, E120, E121, E122, E123, E124, E125, E126, E127, E128, E129, E130, E131, E132, E133, E134, E135, E136, E137, E138, E139, E140, E141, E142, E143, E144, E145, E146, E147, E148, E149, E150, E151, E152, E153, E154, E155, E156, E157, E158, E159, E160, E161, E162, E163, E164, E165, E166, E167, E168, E169, E170, E171, E172, E173, E174, E175, E176, E177, E178, E179, E180, E181, E182, E183, E184, E185, E186, E187, E188, E189, E190, E191, E192, E193, E194, E195, E196, E197, E198, E199, E200, E201, E202, E203, E204, E205, E206, E207, E208, E209, E210, E211, E212, E213, E214, E215, E216, E217, E218, E219, E220, E221, E222, E223, E224, E225, E226, E227, E228, E229, E230, E231, E232, E233, E234, E235, E236, E237, E238, E239, E240, E241, E242, E243, E244, E245, E246, E247, E248, E249, E250, E251, E252, E253, E254, E255, E256, E257, E258, E259, E260, E261, E262, E263, E264, E265, E266, E267, E268, E269, E270, E271, E272, E273, E274, E275, E276, E277, E278, E279, E280, E281, E282, E283, E284, E285, E286, E287, E288, E289, E290, E291, E292, E293, E294, E295, E296, E297, E298, E299, } Diagnostic(ErrorCode.ERR_EnumeratorOverflow, "E256").WithArguments("C.E256").WithLocation(3, 1443), // (4,1451): error CS0543: 'D.E256': the enumerator value is too large to fit in its type // enum D : sbyte { E0 = -128, E1, E2, E3, E4, E5, E6, E7, E8, E9, E10, E11, E12, E13, E14, E15, E16, E17, E18, E19, E20, E21, E22, E23, E24, E25, E26, E27, E28, E29, E30, E31, E32, E33, E34, E35, E36, E37, E38, E39, E40, E41, E42, E43, E44, E45, E46, E47, E48, E49, E50, E51, E52, E53, E54, E55, E56, E57, E58, E59, E60, E61, E62, E63, E64, E65, E66, E67, E68, E69, E70, E71, E72, E73, E74, E75, E76, E77, E78, E79, E80, E81, E82, E83, E84, E85, E86, E87, E88, E89, E90, E91, E92, E93, E94, E95, E96, E97, E98, E99, E100, E101, E102, E103, E104, E105, E106, E107, E108, E109, E110, E111, E112, E113, E114, E115, E116, E117, E118, E119, E120, E121, E122, E123, E124, E125, E126, E127, E128, E129, E130, E131, E132, E133, E134, E135, E136, E137, E138, E139, E140, E141, E142, E143, E144, E145, E146, E147, E148, E149, E150, E151, E152, E153, E154, E155, E156, E157, E158, E159, E160, E161, E162, E163, E164, E165, E166, E167, E168, E169, E170, E171, E172, E173, E174, E175, E176, E177, E178, E179, E180, E181, E182, E183, E184, E185, E186, E187, E188, E189, E190, E191, E192, E193, E194, E195, E196, E197, E198, E199, E200, E201, E202, E203, E204, E205, E206, E207, E208, E209, E210, E211, E212, E213, E214, E215, E216, E217, E218, E219, E220, E221, E222, E223, E224, E225, E226, E227, E228, E229, E230, E231, E232, E233, E234, E235, E236, E237, E238, E239, E240, E241, E242, E243, E244, E245, E246, E247, E248, E249, E250, E251, E252, E253, E254, E255, E256, E257, E258, E259, E260, E261, E262, E263, E264, E265, E266, E267, E268, E269, E270, E271, E272, E273, E274, E275, E276, E277, E278, E279, E280, E281, E282, E283, E284, E285, E286, E287, E288, E289, E290, E291, E292, E293, E294, E295, E296, E297, E298, E299, } Diagnostic(ErrorCode.ERR_EnumeratorOverflow, "E256").WithArguments("D.E256").WithLocation(4, 1451)); } // Create string "{ E0, E1, ..., En }" private static string CreateEnumValues(int count, string prefix, int? initialValue = null) { var builder = new System.Text.StringBuilder("{ "); for (int i = 0; i < count; i++) { builder.Append(prefix); builder.Append(i); if ((i == 0) && (initialValue != null)) { builder.AppendFormat(" = {0}", initialValue.Value); } builder.Append(", "); } builder.Append(" }"); return builder.ToString(); } // CS0570 --> Symbols\OverriddenOrHiddenMembersTests.cs [Fact] public void CS0571ERR_CantCallSpecialMethod01() { var source = @"class C { protected virtual object P { get; set; } static object Q { get; set; } void M(D d) { this.set_P(get_Q()); D.set_Q(d.get_P()); ((this.get_P))(); } } class D : C { protected override object P { get { return null; } set { } } } "; CreateCompilation(source).VerifyDiagnostics( // (7,20): error CS0571: 'C.Q.get': cannot explicitly call operator or accessor // this.set_P(get_Q()); Diagnostic(ErrorCode.ERR_CantCallSpecialMethod, "get_Q").WithArguments("C.Q.get").WithLocation(7, 20), // (7,14): error CS0571: 'C.P.set': cannot explicitly call operator or accessor // this.set_P(get_Q()); Diagnostic(ErrorCode.ERR_CantCallSpecialMethod, "set_P").WithArguments("C.P.set").WithLocation(7, 14), // (8,19): error CS0571: 'D.P.get': cannot explicitly call operator or accessor // D.set_Q(d.get_P()); Diagnostic(ErrorCode.ERR_CantCallSpecialMethod, "get_P").WithArguments("D.P.get").WithLocation(8, 19), // (8,11): error CS0571: 'C.Q.set': cannot explicitly call operator or accessor // D.set_Q(d.get_P()); Diagnostic(ErrorCode.ERR_CantCallSpecialMethod, "set_Q").WithArguments("C.Q.set").WithLocation(8, 11), // (9,16): error CS0571: 'C.P.get': cannot explicitly call operator or accessor // ((this.get_P))(); Diagnostic(ErrorCode.ERR_CantCallSpecialMethod, "get_P").WithArguments("C.P.get").WithLocation(9, 16)); // CONSIDER: Dev10 reports 'C.P.get' for the fourth error. Roslyn reports 'D.P.get' // because it is in the more-derived type and because Binder.LookupMembersInClass // calls MergeHidingLookups(D.P.get, C.P.get) with both arguments non-viable // (i.e. keeps current, since new value isn't better). } [Fact] public void CS0571ERR_CantCallSpecialMethod02() { var source = @"using System; namespace A.B { class C { object P { get; set; } static object Q { get { return 0; } set { } } void M(C c) { Func<object> f = get_P; f = C.get_Q; Action<object> a = c.set_P; a = set_Q; } } } "; CreateCompilation(source).VerifyDiagnostics( // (10,30): error CS0571: 'C.P.get': cannot explicitly call operator or accessor // Func<object> f = get_P; Diagnostic(ErrorCode.ERR_CantCallSpecialMethod, "get_P").WithArguments("A.B.C.P.get").WithLocation(10, 30), // (11,19): error CS0571: 'C.Q.get': cannot explicitly call operator or accessor // f = C.get_Q; Diagnostic(ErrorCode.ERR_CantCallSpecialMethod, "get_Q").WithArguments("A.B.C.Q.get").WithLocation(11, 19), // (12,34): error CS0571: 'C.P.set': cannot explicitly call operator or accessor // Action<object> a = c.set_P; Diagnostic(ErrorCode.ERR_CantCallSpecialMethod, "set_P").WithArguments("A.B.C.P.set").WithLocation(12, 34), // (13,17): error CS0571: 'C.Q.set': cannot explicitly call operator or accessor // a = set_Q; Diagnostic(ErrorCode.ERR_CantCallSpecialMethod, "set_Q").WithArguments("A.B.C.Q.set").WithLocation(13, 17)); } /// <summary> /// No errors should be reported if method with /// accessor name is defined in different class. /// </summary> [Fact] public void CS0571ERR_CantCallSpecialMethod03() { var source = @"class A { public object get_P() { return null; } } class B : A { public object P { get; set; } void M() { object o = this.P; o = this.get_P(); } } class C { void M(B b) { object o = b.P; o = b.get_P(); } } "; CreateCompilation(source).VerifyDiagnostics(); } [Fact()] public void CS0571ERR_CantCallSpecialMethod04() { var compilation = CreateCompilation( @"public class MyClass { public static MyClass operator ++(MyClass c) { return null; } public static void M() { op_Increment(null); // CS0571 } } ").VerifyDiagnostics( // (9,9): error CS0571: 'MyClass.operator ++(MyClass)': cannot explicitly call operator or accessor // op_Increment(null); // CS0571 Diagnostic(ErrorCode.ERR_CantCallSpecialMethod, "op_Increment").WithArguments("MyClass.operator ++(MyClass)")); } [Fact] public void CS0571ERR_CantCallSpecialMethod05() { var source = @" using System; public class C { public static void M() { IntPtr.op_Addition(default(IntPtr), 0); IntPtr.op_Subtraction(default(IntPtr), 0); IntPtr.op_Equality(default(IntPtr), default(IntPtr)); IntPtr.op_Inequality(default(IntPtr), default(IntPtr)); IntPtr.op_Explicit(0); } } "; CreateCompilation(source).VerifyDiagnostics( // (7,16): error CS0571: 'IntPtr.operator +(IntPtr, int)': cannot explicitly call operator or accessor // IntPtr.op_Addition(default(IntPtr), 0); Diagnostic(ErrorCode.ERR_CantCallSpecialMethod, "op_Addition").WithArguments("System.IntPtr.operator +(System.IntPtr, int)").WithLocation(7, 16), // (8,16): error CS0571: 'IntPtr.operator -(IntPtr, int)': cannot explicitly call operator or accessor // IntPtr.op_Subtraction(default(IntPtr), 0); Diagnostic(ErrorCode.ERR_CantCallSpecialMethod, "op_Subtraction").WithArguments("System.IntPtr.operator -(System.IntPtr, int)").WithLocation(8, 16), // (9,16): error CS0571: 'IntPtr.operator ==(IntPtr, IntPtr)': cannot explicitly call operator or accessor // IntPtr.op_Equality(default(IntPtr), default(IntPtr)); Diagnostic(ErrorCode.ERR_CantCallSpecialMethod, "op_Equality").WithArguments("System.IntPtr.operator ==(System.IntPtr, System.IntPtr)").WithLocation(9, 16), // (10,16): error CS0571: 'IntPtr.operator !=(IntPtr, IntPtr)': cannot explicitly call operator or accessor // IntPtr.op_Inequality(default(IntPtr), default(IntPtr)); Diagnostic(ErrorCode.ERR_CantCallSpecialMethod, "op_Inequality").WithArguments("System.IntPtr.operator !=(System.IntPtr, System.IntPtr)").WithLocation(10, 16), // (11,16): error CS0571: 'IntPtr.explicit operator IntPtr(int)': cannot explicitly call operator or accessor // IntPtr.op_Explicit(0); Diagnostic(ErrorCode.ERR_CantCallSpecialMethod, "op_Explicit").WithArguments("System.IntPtr.explicit operator System.IntPtr(int)").WithLocation(11, 16)); } [Fact] public void CS0572ERR_BadTypeReference() { var text = @" using System; class C { public class Inner { public static int v = 9; } } class D : C { public static void Main() { C cValue = new C(); Console.WriteLine(cValue.Inner.v); // CS0572 // try the following line instead // Console.WriteLine(C.Inner.v); } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_BadTypeReference, Line = 16, Column = 32 } }); } [Fact] public void CS0574ERR_BadDestructorName() { var test = @" namespace x { public class iii { ~iiii(){} public static void Main() { } } } "; CreateCompilation(test).VerifyDiagnostics( // (6,10): error CS0574: Name of destructor must match name of type // ~iiii(){} Diagnostic(ErrorCode.ERR_BadDestructorName, "iiii").WithLocation(6, 10)); } [WorkItem(541951, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541951")] [Fact] public void CS0611ERR_ArrayElementCantBeRefAny() { var text = @" public class Test { public System.TypedReference[] x; public System.RuntimeArgumentHandle[][] y; } "; var comp = CreateCompilation(text, targetFramework: TargetFramework.Mscorlib45); comp.VerifyDiagnostics( // (4,12): error CS0611: Array elements cannot be of type 'System.TypedReference' // public System.TypedReference[] x; Diagnostic(ErrorCode.ERR_ArrayElementCantBeRefAny, "System.TypedReference").WithArguments("System.TypedReference").WithLocation(4, 12), // (5,12): error CS0611: Array elements cannot be of type 'System.RuntimeArgumentHandle' // public System.RuntimeArgumentHandle[][] y; Diagnostic(ErrorCode.ERR_ArrayElementCantBeRefAny, "System.RuntimeArgumentHandle").WithArguments("System.RuntimeArgumentHandle").WithLocation(5, 12)); } [WorkItem(541951, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541951")] [Fact] public void CS0611ERR_ArrayElementCantBeRefAny_1() { var text = @"using System; class C { static void M() { var x = new[] { new ArgIterator() }; var y = new[] { new TypedReference() }; var z = new[] { new RuntimeArgumentHandle() }; } }"; var comp = CreateCompilation(text, targetFramework: TargetFramework.Mscorlib45); comp.VerifyDiagnostics( // (6,17): error CS0611: Array elements cannot be of type 'System.ArgIterator' // var x = new[] { new ArgIterator() }; Diagnostic(ErrorCode.ERR_ArrayElementCantBeRefAny, "new[] { new ArgIterator() }").WithArguments("System.ArgIterator").WithLocation(6, 17), // (7,17): error CS0611: Array elements cannot be of type 'System.TypedReference' // var y = new[] { new TypedReference() }; Diagnostic(ErrorCode.ERR_ArrayElementCantBeRefAny, "new[] { new TypedReference() }").WithArguments("System.TypedReference").WithLocation(7, 17), // (8,17): error CS0611: Array elements cannot be of type 'System.RuntimeArgumentHandle' // var z = new[] { new RuntimeArgumentHandle() }; Diagnostic(ErrorCode.ERR_ArrayElementCantBeRefAny, "new[] { new RuntimeArgumentHandle() }").WithArguments("System.RuntimeArgumentHandle").WithLocation(8, 17)); } [Fact, WorkItem(546062, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546062")] public void CS0619ERR_DeprecatedSymbolStr() { var text = @" using System; namespace a { [Obsolete] class C1 { } [Obsolete(""Obsolescence message"", true)] interface I1 { } public class CI1 : I1 { } public class MainClass { public static void Main() { } } } "; CreateCompilation(text).VerifyDiagnostics( // (11,24): error CS0619: 'a.I1' is obsolete: 'Obsolescence message' // public class CI1 : I1 { } Diagnostic(ErrorCode.ERR_DeprecatedSymbolStr, "I1").WithArguments("a.I1", "Obsolescence message") ); } [Fact] public void CS0622ERR_ArrayInitToNonArrayType() { var text = @" public class Test { public static void Main () { Test t = { new Test() }; // CS0622 } }"; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_ArrayInitToNonArrayType, Line = 6, Column = 18 } }); } [Fact] public void CS0623ERR_ArrayInitInBadPlace() { var text = @" class X { public void goo(int a) { int[] x = { { 4 } }; //CS0623 } }"; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_ArrayInitInBadPlace, Line = 6, Column = 21 } }); } [Fact] public void CS0631ERR_IllegalRefParam() { var compilation = CreateCompilation( @"interface I { object this[ref object index] { get; set; } } class C { internal object this[object x, out object y] { get { y = null; return null; } } } struct S { internal object this[out int x, out int y] { set { x = 0; y = 0; } } }"); compilation.VerifyDiagnostics( // (3,17): error CS0631: ref and out are not valid in this context Diagnostic(ErrorCode.ERR_IllegalRefParam, "ref").WithLocation(3, 17), // (7,36): error CS0631: ref and out are not valid in this context Diagnostic(ErrorCode.ERR_IllegalRefParam, "out").WithLocation(7, 36), // (11,26): error CS0631: ref and out are not valid in this context Diagnostic(ErrorCode.ERR_IllegalRefParam, "out").WithLocation(11, 26), // (11,37): error CS0631: ref and out are not valid in this context Diagnostic(ErrorCode.ERR_IllegalRefParam, "out").WithLocation(11, 37)); } [WorkItem(529305, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529305")] [Fact()] public void CS0664ERR_LiteralDoubleCast() { var text = @" class Example { static void Main() { // CS0664, because 1.0 is interpreted as a double: decimal d1 = 1.0; float f1 = 2.0; } }"; var compilation = CreateCompilation(text); compilation.VerifyDiagnostics( // (7,22): error CS0664: Literal of type double cannot be implicitly converted to type 'decimal'; use an 'M' suffix to create a literal of this type // decimal d1 = 1.0; Diagnostic(ErrorCode.ERR_LiteralDoubleCast, "1.0").WithArguments("M", "decimal").WithLocation(7, 22), // (8,20): error CS0664: Literal of type double cannot be implicitly converted to type 'float'; use an 'F' suffix to create a literal of this type // float f1 = 2.0; Diagnostic(ErrorCode.ERR_LiteralDoubleCast, "2.0").WithArguments("F", "float").WithLocation(8, 20), // (7,17): warning CS0219: The variable 'd1' is assigned but its value is never used // decimal d1 = 1.0; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "d1").WithArguments("d1").WithLocation(7, 17), // (8,15): warning CS0219: The variable 'f1' is assigned but its value is never used // float f1 = 2.0; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "f1").WithArguments("f1").WithLocation(8, 15)); } [Fact] public void CS0670ERR_FieldCantHaveVoidType() { CreateCompilation(@" class C { void x = default(void); }").VerifyDiagnostics( // (4,22): error CS1547: Keyword 'void' cannot be used in this context Diagnostic(ErrorCode.ERR_NoVoidHere, "void"), // (4,5): error CS0670: Field cannot have void type Diagnostic(ErrorCode.ERR_FieldCantHaveVoidType, "void")); } [Fact] public void CS0670ERR_FieldCantHaveVoidType_Var() { CreateCompilationWithMscorlib45(@" var x = default(void); ", parseOptions: TestOptions.Script).VerifyDiagnostics( // (2,17): error CS1547: Keyword 'void' cannot be used in this context Diagnostic(ErrorCode.ERR_NoVoidHere, "void"), // (2,1): error CS0670: Field cannot have void type Diagnostic(ErrorCode.ERR_FieldCantHaveVoidType, "var")); } [WorkItem(538016, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538016")] [Fact] public void CS0687ERR_AliasQualAsExpression() { var text = @" using M = Test; using System; public class Test { public static int x = 77; public static void Main() { Console.WriteLine(M::x); // CS0687 } }"; CreateCompilation(text).VerifyDiagnostics( Diagnostic(ErrorCode.ERR_ColColWithTypeAlias, "M").WithArguments("M") ); } [Fact] public void CS0704ERR_LookupInTypeVariable() { var text = @"using System; class A { internal class B : Attribute { } internal class C<T> { } } class D<T> where T : A { class E : T.B { } interface I<U> where U : T.B { } [T.B] static object M<U>() { T.C<object> b1 = new T.C<object>(); T<U>.B b2 = null; b1 = default(T.B); object o = typeof(T.C<A>); o = o as T.B; return b1; } }"; CreateCompilation(text).VerifyDiagnostics( // (9,15): error CS0704: Cannot do member lookup in 'T' because it is a type parameter class E : T.B { } Diagnostic(ErrorCode.ERR_LookupInTypeVariable, "T.B").WithArguments("T"), // (10,30): error CS0704: Cannot do member lookup in 'T' because it is a type parameter // interface I<U> where U : T.B { } Diagnostic(ErrorCode.ERR_LookupInTypeVariable, "T.B").WithArguments("T"), // (11,6): error CS0704: Cannot do member lookup in 'T' because it is a type parameter // [T.B] Diagnostic(ErrorCode.ERR_LookupInTypeVariable, "T.B").WithArguments("T"), // (14,9): error CS0704: Cannot do member lookup in 'T' because it is a type parameter // T.C<object> b1 = new T.C<object>(); Diagnostic(ErrorCode.ERR_LookupInTypeVariable, "T.C<object>").WithArguments("T"), // (14,30): error CS0704: Cannot do member lookup in 'T' because it is a type parameter // T.C<object> b1 = new T.C<object>(); Diagnostic(ErrorCode.ERR_LookupInTypeVariable, "T.C<object>").WithArguments("T"), // (15,9): error CS0307: The type parameter 'T' cannot be used with type arguments // T<U>.B b2 = null; Diagnostic(ErrorCode.ERR_TypeArgsNotAllowed, "T<U>").WithArguments("T", "type parameter"), // (16,22): error CS0704: Cannot do member lookup in 'T' because it is a type parameter // b1 = default(T.B); Diagnostic(ErrorCode.ERR_LookupInTypeVariable, "T.B").WithArguments("T"), // (17,27): error CS0704: Cannot do member lookup in 'T' because it is a type parameter // object o = typeof(T.C<A>); Diagnostic(ErrorCode.ERR_LookupInTypeVariable, "T.C<A>").WithArguments("T"), // (18,18): error CS0704: Cannot do member lookup in 'T' because it is a type parameter // o = o as T.B; Diagnostic(ErrorCode.ERR_LookupInTypeVariable, "T.B").WithArguments("T") ); } [Fact] public void CS0712ERR_InstantiatingStaticClass() { var text = @" public static class SC { } public class CMain { public static void Main() { SC sc = new SC(); // CS0712 } }"; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_InstantiatingStaticClass, Line = 10, Column = 17 }, new ErrorDescription { Code = (int)ErrorCode.ERR_VarDeclIsStaticClass, Line = 10, Column = 9 }}); } [Fact] public void CS0716ERR_ConvertToStaticClass() { var text = @" public static class SC { static void F() { } } public class Test { public static void Main() { object o = new object(); System.Console.WriteLine((SC)o); // CS0716 } }"; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_ConvertToStaticClass, Line = 12, Column = 34 } }); } [Fact] [WorkItem(36203, "https://github.com/dotnet/roslyn/issues/36203")] public void CS0718_StaticClassError_HasHigherPriorityThanMethodOverloadError() { var code = @" static class StaticClass { } class Code { void GenericMethod<T>(int i) => throw null; void GenericMethod<T>(string s) => throw null; void IncorrectMethodCall() { GenericMethod<StaticClass>(1); } }"; CreateCompilation(code).VerifyDiagnostics( // (11,9): error CS0718: 'StaticClass': static types cannot be used as type arguments Diagnostic(ErrorCode.ERR_GenericArgIsStaticClass, "GenericMethod<StaticClass>").WithArguments("StaticClass").WithLocation(11, 9)); } [Fact] public void CS0723ERR_VarDeclIsStaticClass_Locals() { CreateCompilation( @"static class SC { static void M() { SC sc = null; // CS0723 N(sc); var sc2 = new SC(); } static void N(object o) { } }").VerifyDiagnostics( // (5,9): error CS0723: Cannot declare a variable of static type 'SC' Diagnostic(ErrorCode.ERR_VarDeclIsStaticClass, "SC").WithArguments("SC"), // (7,19): error CS0712: Cannot create an instance of the static class 'SC' Diagnostic(ErrorCode.ERR_InstantiatingStaticClass, "new SC()").WithArguments("SC"), // (7,9): error CS0723: Cannot declare a variable of static type 'SC' Diagnostic(ErrorCode.ERR_VarDeclIsStaticClass, "var").WithArguments("SC")); } [Fact] public void CS0723ERR_VarDeclIsStaticClass_Fields() { CreateCompilationWithMscorlib45(@" static class SC {} var sc2 = new SC(); ", parseOptions: TestOptions.Script).VerifyDiagnostics( // (4,5): error CS0723: Cannot declare a variable of static type 'SC' Diagnostic(ErrorCode.ERR_VarDeclIsStaticClass, "sc2").WithArguments("SC"), // (4,11): error CS0712: Cannot create an instance of the static class 'SC' Diagnostic(ErrorCode.ERR_InstantiatingStaticClass, "new SC()").WithArguments("SC")); } [Fact] public void CS0724ERR_BadEmptyThrowInFinally() { var text = @" using System; class X { static void Test() { try { throw new Exception(); } catch { try { } finally { throw; // CS0724 } } } static void Main() { } }"; CreateCompilation(text).VerifyDiagnostics( // (19,17): error CS0724: A throw statement with no arguments is not allowed in a finally clause that is nested inside the nearest enclosing catch clause Diagnostic(ErrorCode.ERR_BadEmptyThrowInFinally, "throw").WithLocation(19, 17)); } [Fact, WorkItem(1040213, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1040213")] public void CS0724ERR_BadEmptyThrowInFinally_Nesting() { var text = @" using System; class X { static void Test(bool b) { try { throw new Exception(); } catch { try { } finally { if (b) throw; // CS0724 try { throw; // CS0724 } catch { throw; // OK } finally { throw; // CS0724 } } } } static void Main() { } }"; CreateCompilation(text).VerifyDiagnostics( // (19,17): error CS0724: A throw statement with no arguments is not allowed in a finally clause that is nested inside the nearest enclosing catch clause Diagnostic(ErrorCode.ERR_BadEmptyThrowInFinally, "throw"), // (19,17): error CS0724: A throw statement with no arguments is not allowed in a finally clause that is nested inside the nearest enclosing catch clause Diagnostic(ErrorCode.ERR_BadEmptyThrowInFinally, "throw"), // (19,17): error CS0724: A throw statement with no arguments is not allowed in a finally clause that is nested inside the nearest enclosing catch clause Diagnostic(ErrorCode.ERR_BadEmptyThrowInFinally, "throw")); } [Fact] public void CS0747ERR_InvalidInitializerElementInitializer() { var text = @" using System.Collections.Generic; public class C { public static int Main() { var t = new List<int> { Capacity = 2, 1 }; // CS0747 return 1; } }"; CreateCompilation(text).VerifyDiagnostics( Diagnostic(ErrorCode.ERR_InvalidInitializerElementInitializer, "1")); } [Fact] public void CS0762ERR_PartialMethodToDelegate() { var text = @" public delegate void TestDel(); public partial class C { partial void Part(); public static int Main() { C c = new C(); TestDel td = new TestDel(c.Part); // CS0762 return 1; } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_PartialMethodToDelegate, Line = 11, Column = 38 } }); } [Fact] public void CS0765ERR_PartialMethodInExpressionTree() { var text = @" using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Linq.Expressions; public delegate void dele(); public class ConClass { [Conditional(""CONDITION"")] public static void TestMethod() { } } public partial class PartClass : IEnumerable { List<object> list = new List<object>(); partial void Add(int x); public IEnumerator GetEnumerator() { for (int i = 0; i < list.Count; i++) yield return list[i]; } static void Main() { Expression<Func<PartClass>> testExpr1 = () => new PartClass { 1, 2 }; // CS0765 Expression<dele> testExpr2 = () => ConClass.TestMethod(); // CS0765 } }"; CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics( // (30,71): error CS0765: Partial methods with only a defining declaration or removed conditional methods cannot be used in expression trees // Expression<Func<PartClass>> testExpr1 = () => new PartClass { 1, 2 }; // CS0765 Diagnostic(ErrorCode.ERR_PartialMethodInExpressionTree, "1"), // (30,74): error CS0765: Partial methods with only a defining declaration or removed conditional methods cannot be used in expression trees // Expression<Func<PartClass>> testExpr1 = () => new PartClass { 1, 2 }; // CS0765 Diagnostic(ErrorCode.ERR_PartialMethodInExpressionTree, "2"), // (31,44): error CS0765: Partial methods with only a defining declaration or removed conditional methods cannot be used in expression trees // Expression<dele> testExpr2 = () => ConClass.TestMethod(); // CS0765 Diagnostic(ErrorCode.ERR_PartialMethodInExpressionTree, "ConClass.TestMethod()")); } [Fact] public void CS0815ERR_ImplicitlyTypedVariableAssignedBadValue_Local() { CreateCompilation(@" class Test { public static void Main() { var m = Main; var d = s => -1; // CS8917 var e = (string s) => 0; var p = null;//CS0815 var del = delegate(string a) { return -1; }; var v = M(); // CS0815 } static void M() {} }").VerifyDiagnostics( // (7,17): error CS8917: The delegate type could not be inferred. // var d = s => -1; // CS8917 Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "s => -1").WithLocation(7, 17), // (9,13): error CS0815: Cannot assign <null> to an implicitly-typed variable // var p = null;//CS0815 Diagnostic(ErrorCode.ERR_ImplicitlyTypedVariableAssignedBadValue, "p = null").WithArguments("<null>").WithLocation(9, 13), // (11,13): error CS0815: Cannot assign void to an implicitly-typed variable // var v = M(); // CS0815 Diagnostic(ErrorCode.ERR_ImplicitlyTypedVariableAssignedBadValue, "v = M()").WithArguments("void").WithLocation(11, 13)); } [Fact] public void CS0815ERR_ImplicitlyTypedVariableAssignedBadValue_Field() { CreateCompilationWithMscorlib45(@" static void M() {} var m = M; var d = s => -1; var e = (string s) => 0; var p = null; var del = delegate(string a) { return -1; }; var v = M(); ", parseOptions: TestOptions.Script).VerifyDiagnostics( // (5,9): error CS8917: The delegate type could not be inferred. // var d = s => -1; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "s => -1").WithLocation(5, 9), // (7,5): error CS0815: Cannot assign <null> to an implicitly-typed variable // var p = null; Diagnostic(ErrorCode.ERR_ImplicitlyTypedVariableAssignedBadValue, "p = null").WithArguments("<null>").WithLocation(7, 5), // (9,1): error CS0670: Field cannot have void type // var v = M(); Diagnostic(ErrorCode.ERR_FieldCantHaveVoidType, "var").WithLocation(9, 1)); } [Fact] public void CS0818ERR_ImplicitlyTypedVariableWithNoInitializer() { var text = @" class A { public static int Main() { var a; // CS0818 return -1; } }"; // In the native compiler we skip post-initial-binding error analysis if there was // an error during the initial binding, so we report only that the "var" declaration // is bad. We do not report warnings like "variable b is assigned but never used". // In Roslyn we do flow analysis even if the initial binding pass produced an error, // so we have extra errors here. DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new[] { new ErrorDescription { Code = (int)ErrorCode.ERR_ImplicitlyTypedVariableWithNoInitializer, Line = 6, Column = 13 }, new ErrorDescription { Code = (int)ErrorCode.WRN_UnreferencedVar, Line = 6, Column = 13, IsWarning = true }}); } [Fact] public void CS0818ERR_ImplicitlyTypedVariableWithNoInitializer_Fields() { CreateCompilationWithMscorlib45(@" var a; // CS0818 ", parseOptions: TestOptions.Script).VerifyDiagnostics( // (1,5): error CS0818: Implicitly-typed variables must be initialized Diagnostic(ErrorCode.ERR_ImplicitlyTypedVariableWithNoInitializer, "a")); } [Fact] public void CS0819ERR_ImplicitlyTypedVariableMultipleDeclarator_Locals() { var text = @" class A { public static int Main() { var a = 3, b = 2; // CS0819 return -1; } } "; // In the native compiler we skip post-initial-binding error analysis if there was // an error during the initial binding, so we report only that the "var" declaration // is bad. We do not report warnings like "variable b is assigned but never used". // In Roslyn we do flow analysis even if the initial binding pass produced an error, // so we have extra errors here. DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new[] { new ErrorDescription { Code = (int)ErrorCode.ERR_ImplicitlyTypedVariableMultipleDeclarator, Line = 6, Column = 9 }, new ErrorDescription { Code = (int)ErrorCode.WRN_UnreferencedVarAssg, Line = 6, Column = 13, IsWarning = true }, new ErrorDescription { Code = (int)ErrorCode.WRN_UnreferencedVarAssg, Line = 6, Column = 20, IsWarning = true }}); } [Fact] public void CS0819ERR_ImplicitlyTypedVariableMultipleDeclarator_Fields() { CreateCompilationWithMscorlib45(@" var goo = 4, bar = 4.5; ", parseOptions: TestOptions.Script).VerifyDiagnostics( // (2,1): error CS0819: Implicitly-typed fields cannot have multiple declarators Diagnostic(ErrorCode.ERR_ImplicitlyTypedVariableMultipleDeclarator, "var")); } [Fact] public void CS0820ERR_ImplicitlyTypedVariableAssignedArrayInitializer() { var text = @" class G { public static int Main() { var a = { 1, 2, 3 }; //CS0820 return -1; } }"; // In the native compilers this code produces two errors, both // "you can't assign an array initializer to an implicitly typed local" and // "you can only use an array initializer to assign to an array type". // It seems like the first error ought to prevent the second. In Roslyn // we only produce the first error. DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new[] { new ErrorDescription { Code = (int)ErrorCode.ERR_ImplicitlyTypedVariableAssignedArrayInitializer, Line = 6, Column = 13 }}); } [Fact] public void CS0820ERR_ImplicitlyTypedVariableAssignedArrayInitializer_Fields() { CreateCompilationWithMscorlib45(@" var y = { 1, 2, 3 }; ", parseOptions: TestOptions.Script).VerifyDiagnostics( // (1,5): error CS0820: Cannot initialize an implicitly-typed variable with an array initializer Diagnostic(ErrorCode.ERR_ImplicitlyTypedVariableAssignedArrayInitializer, "y = { 1, 2, 3 }")); } [Fact] public void CS0821ERR_ImplicitlyTypedLocalCannotBeFixed() { var text = @" class A { static int x; public static int Main() { unsafe { fixed (var p = &x) { } } return -1; } }"; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (10,24): error CS0821: Implicitly-typed local variables cannot be fixed // fixed (var p = &x) { } Diagnostic(ErrorCode.ERR_ImplicitlyTypedLocalCannotBeFixed, "p = &x")); } [Fact] public void CS0822ERR_ImplicitlyTypedLocalCannotBeConst() { var text = @" class A { public static void Main() { const var x = 0; // CS0822.cs const var y = (int?)null + x; } }"; // In the dev10 compiler, the second line reports both that "const var" is illegal // and that the initializer must be a valid constant. This seems a bit odd, so // in Roslyn we just report the first error. Let the user sort out whether they // meant it to be a constant or a variable, and then we can tell them if its a // bad constant. var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (6,15): error CS0822: Implicitly-typed variables cannot be constant // const var x = 0; // CS0822.cs Diagnostic(ErrorCode.ERR_ImplicitlyTypedVariableCannotBeConst, "var x = 0").WithLocation(6, 15), // (7,15): error CS0822: Implicitly-typed variables cannot be constant // const var y = (int?)null + x; Diagnostic(ErrorCode.ERR_ImplicitlyTypedVariableCannotBeConst, "var y = (int?)null + x").WithLocation(7, 15), // (7,23): warning CS0458: The result of the expression is always 'null' of type 'int?' // const var y = (int?)null + x; Diagnostic(ErrorCode.WRN_AlwaysNull, "(int?)null + x").WithArguments("int?").WithLocation(7, 23) ); } [Fact] public void CS0822ERR_ImplicitlyTypedVariableCannotBeConst_Fields() { CreateCompilationWithMscorlib45(@" const var x = 0; // CS0822.cs ", parseOptions: TestOptions.Script).VerifyDiagnostics( // (2,7): error CS0822: Implicitly-typed variables cannot be constant Diagnostic(ErrorCode.ERR_ImplicitlyTypedVariableCannotBeConst, "var")); } [Fact] public void CS0825ERR_ImplicitlyTypedVariableCannotBeUsedAsTheTypeOfAParameter_Fields() { CreateCompilationWithMscorlib45(@" void goo(var arg) { } var goo(int arg) { return 2; } ", parseOptions: TestOptions.Script).VerifyDiagnostics( // (1,10): error CS0825: The contextual keyword 'var' may only appear within a local variable declaration or in script code Diagnostic(ErrorCode.ERR_TypeVarNotFound, "var"), // (2,1): error CS0825: The contextual keyword 'var' may only appear within a local variable declaration or in script code Diagnostic(ErrorCode.ERR_TypeVarNotFound, "var")); } [Fact] public void CS0825ERR_ImplicitlyTypedVariableCannotBeUsedAsTheTypeOfAParameter_Fields2() { CreateCompilationWithMscorlib45(@" T goo<T>() { return default(T); } goo<var>(); ", parseOptions: TestOptions.Script).VerifyDiagnostics( // (2,5): error CS0825: The contextual keyword 'var' may only appear within a local variable declaration or in script code Diagnostic(ErrorCode.ERR_TypeVarNotFound, "var")); } [Fact()] public void CS0826ERR_ImplicitlyTypedArrayNoBestType() { var text = @" public class C { delegate void D(); public static void M1() {} public static void M2(int x) {} public static int M3() { return 1; } public static int M4(int x) { return x; } public static int Main() { var z = new[] { 1, ""str"" }; // CS0826 char c = 'c'; short s1 = 0; short s2 = -0; short s3 = 1; short s4 = -1; var array1 = new[] { s1, s2, s3, s4, c, '1' }; // CS0826 var a = new [] {}; // CS0826 byte b = 3; var arr = new [] {b, c}; // CS0826 var a1 = new [] {null}; // CS0826 var a2 = new [] {null, null, null}; // CS0826 D[] l1 = new [] {x=>x+1}; // CS0826 D[] l2 = new [] {x=>x+1, x=>{return x + 1;}, (int x)=>x+1, (int x)=>{return x + 1;}, (x, y)=>x + y, ()=>{return 1;}}; // CS0826 D[] d1 = new [] {delegate {}}; // CS0826 D[] d2 = new [] {delegate {}, delegate (){}, delegate {return 1;}, delegate {return;}, delegate(int x){}, delegate(int x){return x;}, delegate(int x, int y){return x + y;}}; // CS0826 var m = new [] {M1, M2, M3, M4}; // CS0826 return 1; } }"; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, Line = 12, Column = 17 }, new ErrorDescription { Code = (int)ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, Line = 20, Column = 22 }, new ErrorDescription { Code = (int)ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, Line = 22, Column = 17 }, new ErrorDescription { Code = (int)ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, Line = 25, Column = 19 }, new ErrorDescription { Code = (int)ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, Line = 27, Column = 18 }, new ErrorDescription { Code = (int)ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, Line = 28, Column = 18 }, new ErrorDescription { Code = (int)ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, Line = 30, Column = 18 }, new ErrorDescription { Code = (int)ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, Line = 31, Column = 18 }, new ErrorDescription { Code = (int)ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, Line = 33, Column = 18 }, new ErrorDescription { Code = (int)ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, Line = 34, Column = 18 }, new ErrorDescription { Code = (int)ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, Line = 36, Column = 17 }}); } [Fact] public void CS0828ERR_AnonymousTypePropertyAssignedBadValue() { var text = @" public class C { public static int Main() { var c = new { p1 = null }; // CS0828 return 1; } }"; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_AnonymousTypePropertyAssignedBadValue, Line = 6, Column = 23 } }); } [Fact] public void CS0828ERR_AnonymousTypePropertyAssignedBadValue_2() { var text = @" public class C { public static void Main() { var c = new { p1 = Main }; // CS0828 } }"; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_AnonymousTypePropertyAssignedBadValue, Line = 6, Column = 23 } }); } [Fact] public void CS0828ERR_AnonymousTypePropertyAssignedBadValue_3() { var text = @" public class C { public static void Main() { var c = new { p1 = Main() }; // CS0828 } }"; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_AnonymousTypePropertyAssignedBadValue, Line = 6, Column = 23 } }); } [Fact] public void CS0828ERR_AnonymousTypePropertyAssignedBadValue_4() { var text = @" public class C { public static void Main() { var c = new { p1 = ()=>3 }; // CS0828 } }"; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_AnonymousTypePropertyAssignedBadValue, Line = 6, Column = 23 } }); } [Fact] public void CS0828ERR_AnonymousTypePropertyAssignedBadValue_5() { var text = @" public class C { public static void Main() { var c = new { p1 = delegate { return 1; } // CS0828 }; } }"; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_AnonymousTypePropertyAssignedBadValue, Line = 8, Column = 13 } }); } [Fact] public void CS0831ERR_ExpressionTreeContainsBaseAccess() { var text = @" using System; using System.Linq.Expressions; public class A { public virtual int BaseMethod() { return 1; } } public class C : A { public override int BaseMethod() { return 2; } public int Test(C c) { Expression<Func<int>> e = () => base.BaseMethod(); // CS0831 return 1; } }"; CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics( // (14,41): error CS0831: An expression tree may not contain a base access // Expression<Func<int>> e = () => base.BaseMethod(); // CS0831 Diagnostic(ErrorCode.ERR_ExpressionTreeContainsBaseAccess, "base") ); } [Fact] public void CS0832ERR_ExpressionTreeContainsAssignment() { var text = @" using System; using System.Linq.Expressions; public class C { public static int Main() { Expression<Func<int, int>> e1 = x => x += 5; // CS0843 Expression<Func<int, int>> e2 = x => x = 5; // CS0843 return 1; } }"; CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics( // (9,46): error CS0832: An expression tree may not contain an assignment operator // Expression<Func<int, int>> e1 = x => x += 5; // CS0843 Diagnostic(ErrorCode.ERR_ExpressionTreeContainsAssignment, "x += 5"), // (10,46): error CS0832: An expression tree may not contain an assignment operator // Expression<Func<int, int>> e2 = x => x = 5; // CS0843 Diagnostic(ErrorCode.ERR_ExpressionTreeContainsAssignment, "x = 5") ); } [Fact] public void CS0833ERR_AnonymousTypeDuplicatePropertyName() { var text = @" public class C { public static int Main() { var c = new { p1 = 1, p1 = 2 }; // CS0833 return 1; } }"; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_AnonymousTypeDuplicatePropertyName, Line = 6, Column = 31 } }); } [Fact] public void CS0833ERR_AnonymousTypeDuplicatePropertyName_2() { var text = @" public class C { public static int Main() { var c = new { C.Prop, Prop = 2 }; // CS0833 return 1; } static string Prop { get; set; } }"; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_AnonymousTypeDuplicatePropertyName, Line = 6, Column = 31 } }); } [Fact] public void CS0833ERR_AnonymousTypeDuplicatePropertyName_3() { var text = @" public class C { public static int Main() { var c = new { C.Prop, Prop = 2 }; // CS0833 + CS0828 return 1; } static string Prop() { return null; } }"; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_AnonymousTypePropertyAssignedBadValue, Line = 6, Column = 23 }, new ErrorDescription { Code = (int)ErrorCode.ERR_AnonymousTypeDuplicatePropertyName, Line = 6, Column = 31 }}); } [Fact] public void CS0834ERR_StatementLambdaToExpressionTree() { var text = @" using System; using System.Linq.Expressions; public class C { public static void Main() { Expression<Func<int, int>> e = x => { return x; }; // CS0834 } }"; CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics( // (9,40): error CS0834: A lambda expression with a statement body cannot be converted to an expression tree // Expression<Func<int, int>> e = x => { return x; }; // CS0834 Diagnostic(ErrorCode.ERR_StatementLambdaToExpressionTree, "x => { return x; }") ); } [Fact] public void CS0835ERR_ExpressionTreeMustHaveDelegate() { var text = @" using System.Linq.Expressions; public class Myclass { public static int Main() { Expression<int> e = x => x + 1; // CS0835 return 1; } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new[] { LinqAssemblyRef }, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_ExpressionTreeMustHaveDelegate, Line = 8, Column = 29 } }); } [Fact] public void CS0836ERR_AnonymousTypeNotAvailable() { var text = @" using System; [AttributeUsage(AttributeTargets.Class, AllowMultiple = true, Inherited = false)] public class MyClass : Attribute { public MyClass(object obj) { } } [MyClass(new { })] // CS0836 public class ClassGoo { } public class Test { public static int Main() { return 0; } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_AnonymousTypeNotAvailable, Line = 11, Column = 10 } }); } [Fact] public void CS0836ERR_AnonymousTypeNotAvailable2() { var text = @" public class Test { const object x = new { }; public static int Main() { return 0; } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_AnonymousTypeNotAvailable, Line = 4, Column = 22 } }); } [Fact] public void CS0836ERR_AnonymousTypeNotAvailable3() { var text = @" public class Test { static object y = new { }; private object x = new { }; public static int Main() { return 0; } } "; // NOTE: Actually we assert that #836 is NOT generated DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text); } [Fact] public void CS0836ERR_AnonymousTypeNotAvailable4() { var text = @" public class Test { public static int Main(object x = new { }) { return 0; } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_DefaultValueMustBeConstant, Line = 4, Column = 39 } }); } [Fact] public void CS0836ERR_AnonymousTypeNotAvailable5() { var text = @" using System; [AttributeUsage(AttributeTargets.All)] public class MyClass : Attribute { public MyClass(object obj) { } } public class Test { [MyClass(new { })] // CS0836 public static int Main() { return 0; } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_AnonymousTypeNotAvailable, Line = 13, Column = 14 } }); } [Fact] public void CS0836ERR_AnonymousTypeNotAvailable6() { var text = @" using System; [AttributeUsage(AttributeTargets.All)] public class MyClass : Attribute { public MyClass(object obj) { } } public class Test { [MyClass(new { })] // CS0836 static object y = new { }; public static int Main() { return 0; } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_AnonymousTypeNotAvailable, Line = 13, Column = 14 } }); } [Fact] public void CS0837ERR_LambdaInIsAs() { var text = @" namespace TestNamespace { public delegate void Del(); class Test { static int Main() { bool b1 = (() => { }) is Del; // CS0837 bool b2 = delegate() { } is Del;// CS0837 Del d1 = () => { } as Del; // CS0837 Del d2 = delegate() { } as Del; // CS0837 return 1; } } } "; CreateCompilation(text).VerifyDiagnostics( // (10,23): error CS0837: The first operand of an 'is' or 'as' operator may not be a lambda expression, anonymous method, or method group. // bool b1 = (() => { }) is Del; // CS0837 Diagnostic(ErrorCode.ERR_LambdaInIsAs, "(() => { }) is Del").WithLocation(10, 23), // (11,23): error CS0837: The first operand of an 'is' or 'as' operator may not be a lambda expression, anonymous method, or method group. // bool b2 = delegate() { } is Del;// CS0837 Diagnostic(ErrorCode.ERR_LambdaInIsAs, "delegate() { } is Del").WithLocation(11, 23), // (11,38): warning CS8848: Operator 'is' cannot be used here due to precedence. Use parentheses to disambiguate. // bool b2 = delegate() { } is Del;// CS0837 Diagnostic(ErrorCode.WRN_PrecedenceInversion, "is").WithArguments("is").WithLocation(11, 38), // (12,22): error CS0837: The first operand of an 'is' or 'as' operator may not be a lambda expression, anonymous method, or method group. // Del d1 = () => { } as Del; // CS0837 Diagnostic(ErrorCode.ERR_LambdaInIsAs, "() => { } as Del").WithLocation(12, 22), // (12,32): warning CS8848: Operator 'as' cannot be used here due to precedence. Use parentheses to disambiguate. // Del d1 = () => { } as Del; // CS0837 Diagnostic(ErrorCode.WRN_PrecedenceInversion, "as").WithArguments("as").WithLocation(12, 32), // (13,22): error CS0837: The first operand of an 'is' or 'as' operator may not be a lambda expression, anonymous method, or method group. // Del d2 = delegate() { } as Del; // CS0837 Diagnostic(ErrorCode.ERR_LambdaInIsAs, "delegate() { } as Del").WithLocation(13, 22), // (13,37): warning CS8848: Operator 'as' cannot be used here due to precedence. Use parentheses to disambiguate. // Del d2 = delegate() { } as Del; // CS0837 Diagnostic(ErrorCode.WRN_PrecedenceInversion, "as").WithArguments("as").WithLocation(13, 37) ); CreateCompilation(text, options: TestOptions.ReleaseDll.WithWarningLevel(5)).VerifyDiagnostics( // (10,23): error CS0837: The first operand of an 'is' or 'as' operator may not be a lambda expression, anonymous method, or method group. // bool b1 = (() => { }) is Del; // CS0837 Diagnostic(ErrorCode.ERR_LambdaInIsAs, "(() => { }) is Del").WithLocation(10, 23), // (11,23): error CS0837: The first operand of an 'is' or 'as' operator may not be a lambda expression, anonymous method, or method group. // bool b2 = delegate() { } is Del;// CS0837 Diagnostic(ErrorCode.ERR_LambdaInIsAs, "delegate() { } is Del").WithLocation(11, 23), // (11,38): warning CS8848: Operator 'is' cannot be used here due to precedence. Use parentheses to disambiguate. // bool b2 = delegate() { } is Del;// CS0837 Diagnostic(ErrorCode.WRN_PrecedenceInversion, "is").WithArguments("is").WithLocation(11, 38), // (12,22): error CS0837: The first operand of an 'is' or 'as' operator may not be a lambda expression, anonymous method, or method group. // Del d1 = () => { } as Del; // CS0837 Diagnostic(ErrorCode.ERR_LambdaInIsAs, "() => { } as Del").WithLocation(12, 22), // (12,32): warning CS8848: Operator 'as' cannot be used here due to precedence. Use parentheses to disambiguate. // Del d1 = () => { } as Del; // CS0837 Diagnostic(ErrorCode.WRN_PrecedenceInversion, "as").WithArguments("as").WithLocation(12, 32), // (13,22): error CS0837: The first operand of an 'is' or 'as' operator may not be a lambda expression, anonymous method, or method group. // Del d2 = delegate() { } as Del; // CS0837 Diagnostic(ErrorCode.ERR_LambdaInIsAs, "delegate() { } as Del").WithLocation(13, 22), // (13,37): warning CS8848: Operator 'as' cannot be used here due to precedence. Use parentheses to disambiguate. // Del d2 = delegate() { } as Del; // CS0837 Diagnostic(ErrorCode.WRN_PrecedenceInversion, "as").WithArguments("as").WithLocation(13, 37) ); } [Fact] public void CS0841ERR_VariableUsedBeforeDeclaration01() { CreateCompilation( @"class C { static void M() { j = 5; // CS0841 int j; // To fix, move this line up. } } ") // The native compiler just produces the "var used before decl" error; the Roslyn // compiler runs the flow checking pass even if the initial binding failed. We // might consider turning off flow checking if the initial binding failed, and // removing the warning here. .VerifyDiagnostics( Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "j").WithArguments("j"), Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "j").WithArguments("j")); } [Fact] public void CS0841ERR_VariableUsedBeforeDeclaration02() { CreateCompilation( @"class C { static void M() { int a = b, b = 0, c = a; for (int x = y, y = 0; ; ) { } } } ") .VerifyDiagnostics( Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "b").WithArguments("b"), Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "y").WithArguments("y")); } [Fact] public void CS0841ERR_VariableUsedBeforeDeclaration03() { // It is a bit unfortunate that we produce "can't use variable before decl" here // when the variable is being used after the decl. Perhaps we should generate // a better error? CreateCompilation( @"class C { static int N(out int q) { q = 1; return 2;} static void M() { var x = N(out x); } } ") .VerifyDiagnostics( Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x").WithArguments("x")); } [Fact] public void CS0841ERR_VariableUsedBeforeDeclaration04() { var systemRef = Net451.System; CreateCompilationWithMscorlib40AndSystemCore( @"using System.Collections.Generic; class Base { int i; } class Derived : Base { int j; } class C { public static void Main() { HashSet<Base> set1 = new HashSet<Base>(); foreach (Base b in set1) { Derived d = b as Derived; Base b = null; } } } ", new List<MetadataReference> { systemRef }) .VerifyDiagnostics( // (18,25): error CS0841: Cannot use local variable 'b' before it is declared // Derived d = b as Derived; Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "b").WithArguments("b"), // (19,18): error CS0136: A local or parameter named 'b' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // Base b = null; Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "b").WithArguments("b"), // (4,9): warning CS0169: The field 'Base.i' is never used // int i; Diagnostic(ErrorCode.WRN_UnreferencedField, "i").WithArguments("Base.i"), // (8,9): warning CS0169: The field 'Derived.j' is never used // int j; Diagnostic(ErrorCode.WRN_UnreferencedField, "j").WithArguments("Derived.j")); } /// <summary> /// No errors using statics before declaration. /// </summary> [Fact] public void StaticUsedBeforeDeclaration() { var text = @"class C { static int F = G + 2; static int G = F + 1; } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text); } [Fact] public void CS0843ERR_UnassignedThisAutoProperty() { var text = @" struct S { public int AIProp { get; set; } public S(int i) { } //CS0843 } class Test { static int Main() { return 1; } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_UnassignedThisAutoProperty, Line = 5, Column = 12 } }); } [Fact] public void CS0844ERR_VariableUsedBeforeDeclarationAndHidesField() { var text = @" public class MyClass { int num; public void TestMethod() { num = 5; // CS0844 int num = 6; System.Console.WriteLine(num); } } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (7,9): error CS0844: Cannot use local variable 'num' before it is declared. The declaration of the local variable hides the field 'MyClass.num'. // num = 5; // CS0844 Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclarationAndHidesField, "num").WithArguments("num", "MyClass.num"), // (4,9): warning CS0169: The field 'MyClass.num' is never used // int num; Diagnostic(ErrorCode.WRN_UnreferencedField, "num").WithArguments("MyClass.num") ); } [Fact] public void CS0845ERR_ExpressionTreeContainsBadCoalesce() { var text = @" using System; using System.Linq.Expressions; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { Expression<Func<object>> e = () => null ?? ""x""; // CS0845 } } } "; CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics( // (11,48): error CS0845: An expression tree lambda may not contain a coalescing operator with a null literal left-hand side // Expression<Func<object>> e = () => null ?? "x"; // CS0845 Diagnostic(ErrorCode.ERR_ExpressionTreeContainsBadCoalesce, "null") ); } [WorkItem(3717, "DevDiv_Projects/Roslyn")] [Fact] public void CS0846ERR_ArrayInitializerExpected() { var text = @"public class Myclass { public static void Main() { int[,] a = new int[,] { 1 }; // error } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_ArrayInitializerExpected, Line = 5, Column = 33 } }); } [Fact] public void CS0847ERR_ArrayInitializerIncorrectLength() { var text = @" public class Program { public static void Main(string[] args) { int[] ar0 = new int[0]{0}; // error CS0847: An array initializer of length `0' was expected int[] ar1 = new int[3]{}; // error CS0847: An array initializer of length `3' was expected ar0[0] = ar1[0]; } } "; CreateCompilation(text).VerifyDiagnostics( // (6,31): error CS0847: An array initializer of length '0' is expected // int[] ar0 = new int[0]{0}; // error CS0847: An array initializer of length `0' was expected Diagnostic(ErrorCode.ERR_ArrayInitializerIncorrectLength, "{0}").WithArguments("0").WithLocation(6, 31), // (7,31): error CS0847: An array initializer of length '3' is expected // int[] ar1 = new int[3]{}; // error CS0847: An array initializer of length `3' was expected Diagnostic(ErrorCode.ERR_ArrayInitializerIncorrectLength, "{}").WithArguments("3").WithLocation(7, 31)); } [Fact] public void CS0853ERR_ExpressionTreeContainsNamedArgument01() { var text = @" using System.Linq.Expressions; namespace ConsoleApplication3 { class Program { delegate string dg(int x); static void Main(string[] args) { Expression<dg> myET = x => Index(minSessions:5); } public static string Index(int minSessions = 0) { return minSessions.ToString(); } } } "; CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics( // (10,40): error CS0853: An expression tree may not contain a named argument specification // Expression<dg> myET = x => Index(minSessions:5); Diagnostic(ErrorCode.ERR_ExpressionTreeContainsNamedArgument, "Index(minSessions:5)").WithLocation(10, 40) ); } [WorkItem(545063, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545063")] [Fact] public void CS0853ERR_ExpressionTreeContainsNamedArgument02() { var text = @" using System; using System.Collections.Generic; using System.Linq.Expressions; class A { static void Main() { Expression<Func<int>> f = () => new List<int> { 1 } [index: 0]; } } "; CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics( // (10,41): error CS0853: An expression tree may not contain a named argument specification // Expression<Func<int>> f = () => new List<int> { 1 } [index: 0]; Diagnostic(ErrorCode.ERR_ExpressionTreeContainsNamedArgument, "new List<int> { 1 } [index: 0]").WithLocation(10, 41) ); } [Fact] public void CS0854ERR_ExpressionTreeContainsOptionalArgument01() { var text = @" using System.Linq.Expressions; namespace ConsoleApplication3 { class Program { delegate string dg(int x); static void Main(string[] args) { Expression<dg> myET = x => Index(); } public static string Index(int minSessions = 0) { return minSessions.ToString(); } } } "; CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics( // (10,40): error CS0854: An expression tree may not contain a call or invocation that uses optional arguments // Expression<dg> myET = x => Index(); Diagnostic(ErrorCode.ERR_ExpressionTreeContainsOptionalArgument, "Index()").WithLocation(10, 40) ); } [Fact] public void CS0854ERR_ExpressionTreeContainsOptionalArgument02() { var text = @"using System; using System.Linq.Expressions; class A { internal object this[int x, int y = 2] { get { return null; } } } class B { internal object this[int x, int y = 2] { set { } } } class C { static void M(A a, B b) { Expression<Func<object>> e1; e1 = () => a[0]; e1 = () => a[1, 2]; Expression<Action> e2; e2 = () => b[3] = null; e2 = () => b[4, 5] = null; } }"; CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics( // (22,20): error CS0854: An expression tree may not contain a call or invocation that uses optional arguments Diagnostic(ErrorCode.ERR_ExpressionTreeContainsOptionalArgument, "a[0]").WithLocation(22, 20), // (25,20): error CS0832: An expression tree may not contain an assignment operator Diagnostic(ErrorCode.ERR_ExpressionTreeContainsAssignment, "b[3] = null").WithLocation(25, 20), // (25,20): error CS0854: An expression tree may not contain a call or invocation that uses optional arguments Diagnostic(ErrorCode.ERR_ExpressionTreeContainsOptionalArgument, "b[3]").WithLocation(25, 20), // (26,20): error CS0832: An expression tree may not contain an assignment operator Diagnostic(ErrorCode.ERR_ExpressionTreeContainsAssignment, "b[4, 5] = null").WithLocation(26, 20)); } [Fact] public void CS0854ERR_ExpressionTreeContainsOptionalArgument03() { var text = @"using System; using System.Collections; using System.Linq.Expressions; public class Collection : IEnumerable { public void Add(int i, int j = 0) { } public IEnumerator GetEnumerator() { throw new NotImplementedException(); } } public class C { public void M() { Expression<Func<Collection>> expr = () => new Collection { 1 }; // 1 } }"; CreateCompilation(text).VerifyDiagnostics( // (18,36): error CS0854: An expression tree may not contain a call or invocation that uses optional arguments // () => new Collection { 1 }; // 1 Diagnostic(ErrorCode.ERR_ExpressionTreeContainsOptionalArgument, "1").WithLocation(18, 36)); } [Fact] public void CS0855ERR_ExpressionTreeContainsIndexedProperty() { 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 P(index As Object) As Integer Property Q(Optional index As Object = Nothing) As Integer End Interface"; var reference1 = BasicCompilationUtils.CompileToMetadata(source1); var source2 = @"using System; using System.Linq.Expressions; class C { static void M(I i) { Expression<Func<int>> e1; e1 = () => i.P[1]; e1 = () => i.get_P(2); // no error e1 = () => i.Q; e1 = () => i.Q[index:3]; Expression<Action> e2; e2 = () => i.P[4] = 0; e2 = () => i.set_P(5, 6); // no error } }"; var compilation2 = CreateCompilationWithMscorlib40AndSystemCore(source2, new[] { reference1 }); compilation2.VerifyDiagnostics( // (8,20): error CS0855: An expression tree may not contain an indexed property Diagnostic(ErrorCode.ERR_ExpressionTreeContainsIndexedProperty, "i.P[1]").WithLocation(8, 20), // (10,20): error CS0855: An expression tree may not contain an indexed property Diagnostic(ErrorCode.ERR_ExpressionTreeContainsIndexedProperty, "i.Q").WithLocation(10, 20), // (11,20): error CS0855: An expression tree may not contain an indexed property Diagnostic(ErrorCode.ERR_ExpressionTreeContainsIndexedProperty, "i.Q[index:3]").WithLocation(11, 20), // (13,20): error CS0832: An expression tree may not contain an assignment operator Diagnostic(ErrorCode.ERR_ExpressionTreeContainsAssignment, "i.P[4] = 0").WithLocation(13, 20), // (13,20): error CS0855: An expression tree may not contain an indexed property Diagnostic(ErrorCode.ERR_ExpressionTreeContainsIndexedProperty, "i.P[4]").WithLocation(13, 20)); } [Fact] [CompilerTrait(CompilerFeature.IOperation)] [WorkItem(23004, "https://github.com/dotnet/roslyn/issues/23004")] public void CS0856ERR_IndexedPropertyRequiresParams01() { 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 P(x As Object, Optional y As Object = Nothing) As Object Property P(Optional x As Integer = 1, Optional y As Integer = 2) As Object Property Q(Optional x As Integer = 1, Optional y As Integer = 2) As Object Property Q(x As Object, Optional y As Object = Nothing) As Object Property R(x As Integer, y As Integer, Optional z As Integer = 3) As Object Property S(ParamArray args As Integer()) As Object End Interface"; var reference1 = BasicCompilationUtils.CompileToMetadata(source1); var source2 = @"class C { static void M(I i) { object o; o = i.P; // CS0856 (Dev11) o = i.Q; i.R = o; // CS0856 i.R[1] = o; // CS1501 o = i.S; // CS0856 (Dev11) i.S = o; // CS0856 (Dev11) } }"; var compilation2 = CreateCompilation(source2, new[] { reference1 }); compilation2.VerifyDiagnostics( // (8,9): error CS0856: Indexed property 'I.R' has non-optional arguments which must be provided Diagnostic(ErrorCode.ERR_IndexedPropertyRequiresParams, "i.R").WithArguments("I.R").WithLocation(8, 9), // (9,9): error CS7036: There is no argument given that corresponds to the required formal parameter 'y' of 'I.R[int, int, int]' Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "i.R[1]").WithArguments("y", "I.R[int, int, int]").WithLocation(9, 9)); var tree = compilation2.SyntaxTrees.Single(); var node = tree.GetRoot().DescendantNodes().OfType<ElementAccessExpressionSyntax>().First(); Assert.Equal("i.R[1]", node.ToString()); compilation2.VerifyOperationTree(node, expectedOperationTree: @" IInvalidOperation (OperationKind.Invalid, Type: System.Object, IsInvalid) (Syntax: 'i.R[1]') Children(2): IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: I, IsInvalid) (Syntax: 'i') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid) (Syntax: '1') "); } [Fact] public void CS0856ERR_IndexedPropertyRequiresParams02() { 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 Class A Protected ReadOnly Property P(Optional o As Object = Nothing) As Object Get Return Nothing End Get End Property Public ReadOnly Property P(i As Integer) As Object Get Return Nothing End Get End Property End Class"; var reference1 = BasicCompilationUtils.CompileToMetadata(source1); var source2 = @"class C { static object F(A a) { return a.P; } }"; var compilation2 = CreateCompilation(source2, new[] { reference1 }); compilation2.VerifyDiagnostics( // (5,16): error CS0856: Indexed property 'A.P' has non-optional arguments which must be provided Diagnostic(ErrorCode.ERR_IndexedPropertyRequiresParams, "a.P").WithArguments("A.P").WithLocation(5, 16)); } [Fact] public void CS0857ERR_IndexedPropertyMustHaveAllOptionalParams() { 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"")> <CoClass(GetType(A))> Public Interface IA Property P(x As Object, Optional y As Object = Nothing) As Object Property P(Optional x As Integer = 1, Optional y As Integer = 2) As Object Property Q(Optional x As Integer = 1, Optional y As Integer = 2) As Object Property Q(x As Object, Optional y As Object = Nothing) As Object Property R(x As Integer, y As Integer, Optional z As Integer = 3) As Object Property S(ParamArray args As Integer()) As Object End Interface Public Class A Implements IA Property P(x As Object, Optional y As Object = Nothing) As Object Implements IA.P Get Return Nothing End Get Set(value As Object) End Set End Property Property P(Optional x As Integer = 1, Optional y As Integer = 2) As Object Implements IA.P Get Return Nothing End Get Set(value As Object) End Set End Property Property Q(Optional x As Integer = 1, Optional y As Integer = 2) As Object Implements IA.Q Get Return Nothing End Get Set(value As Object) End Set End Property Property Q(x As Object, Optional y As Object = Nothing) As Object Implements IA.Q Get Return Nothing End Get Set(value As Object) End Set End Property Property R(x As Integer, y As Integer, Optional z As Integer = 3) As Object Implements IA.R Get Return Nothing End Get Set(value As Object) End Set End Property Property S(ParamArray args As Integer()) As Object Implements IA.S Get Return Nothing End Get Set(value As Object) End Set End Property End Class"; var reference1 = BasicCompilationUtils.CompileToMetadata(source1, verify: Verification.Passes); var source2 = @"class B { static void M() { IA a; a = new IA() { P = null }; // CS0857 (Dev11) a = new IA() { Q = null }; a = new IA() { R = null }; // CS0857 a = new IA() { S = null }; // CS0857 (Dev11) } }"; var compilation2 = CreateCompilation(source2, new[] { reference1 }); compilation2.VerifyDiagnostics( // (8,24): error CS0857: Indexed property 'IA.R' must have all arguments optional Diagnostic(ErrorCode.ERR_IndexedPropertyMustHaveAllOptionalParams, "R").WithArguments("IA.R").WithLocation(8, 24)); } [Fact] public void CS1059ERR_IncrementLvalueExpected01() { var text = @"enum E { A, B } class C { static void M() { ++E.A; // CS1059 E.A++; // CS1059 } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_IncrementLvalueExpected, Line = 6, Column = 11 }, new ErrorDescription { Code = (int)ErrorCode.ERR_IncrementLvalueExpected, Line = 7, Column = 9 }); } [Fact] public void CS1059ERR_IncrementLvalueExpected02() { var text = @"class C { const int field = 0; static void M() { const int local = 0; ++local; local++; --field; field--; ++(local + 3); (local + 3)++; --2; 2--; dynamic d = null; (d + 1)++; --(d + 1); d++++; } } "; CreateCompilation(text).VerifyDiagnostics( // (7,11): error CS1059: The operand of an increment or decrement operator must be a variable, property or indexer Diagnostic(ErrorCode.ERR_IncrementLvalueExpected, "local"), // (8,9): error CS1059: The operand of an increment or decrement operator must be a variable, property or indexer Diagnostic(ErrorCode.ERR_IncrementLvalueExpected, "local"), // (9,11): error CS1059: The operand of an increment or decrement operator must be a variable, property or indexer Diagnostic(ErrorCode.ERR_IncrementLvalueExpected, "field"), // (10,9): error CS1059: The operand of an increment or decrement operator must be a variable, property or indexer Diagnostic(ErrorCode.ERR_IncrementLvalueExpected, "field"), // (11,12): error CS1059: The operand of an increment or decrement operator must be a variable, property or indexer Diagnostic(ErrorCode.ERR_IncrementLvalueExpected, "local + 3"), // (12,10): error CS1059: The operand of an increment or decrement operator must be a variable, property or indexer Diagnostic(ErrorCode.ERR_IncrementLvalueExpected, "local + 3"), // (13,11): error CS1059: The operand of an increment or decrement operator must be a variable, property or indexer Diagnostic(ErrorCode.ERR_IncrementLvalueExpected, "2"), // (14,9): error CS1059: The operand of an increment or decrement operator must be a variable, property or indexer Diagnostic(ErrorCode.ERR_IncrementLvalueExpected, "2"), // (17,10): error CS1059: The operand of an increment or decrement operator must be a variable, property or indexer Diagnostic(ErrorCode.ERR_IncrementLvalueExpected, "d + 1"), // (18,12): error CS1059: The operand of an increment or decrement operator must be a variable, property or indexer Diagnostic(ErrorCode.ERR_IncrementLvalueExpected, "d + 1"), // (19,9): error CS1059: The operand of an increment or decrement operator must be a variable, property or indexer Diagnostic(ErrorCode.ERR_IncrementLvalueExpected, "d++")); } [Fact] public void CS1059ERR_IncrementLvalueExpected03() { var text = @" class C { void M() { ++this; // CS1059 this--; // CS1059 } } "; CreateCompilation(text).VerifyDiagnostics( // (6,11): error CS1059: The operand of an increment or decrement operator must be a variable, property or indexer // ++this; // CS1059 Diagnostic(ErrorCode.ERR_IncrementLvalueExpected, "this").WithArguments("this"), // (7,9): error CS1059: The operand of an increment or decrement operator must be a variable, property or indexer // this--; // CS1059 Diagnostic(ErrorCode.ERR_IncrementLvalueExpected, "this").WithArguments("this")); } [Fact] public void CS1061ERR_NoSuchMemberOrExtension01() { var text = @" public class TestClass1 { public void WriteSomething(string s) { System.Console.WriteLine(s); } } public class TestClass2 { public void DisplaySomething(string s) { System.Console.WriteLine(s); } } public class TestTheClasses { public static void Main() { TestClass1 tc1 = new TestClass1(); TestClass2 tc2 = new TestClass2(); if (tc1 == null | tc2 == null) {} tc1.DisplaySomething(""Hello""); // CS1061 } }"; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_NoSuchMemberOrExtension, Line = 25, Column = 13 } }); } [Fact] public void CS1061ERR_NoSuchMemberOrExtension02() { var source = @"enum E { } class C { static void M(E e) { object o = e.value__; } }"; CreateCompilation(source).VerifyDiagnostics( // (6,22): error CS1061: 'E' does not contain a definition for 'value__' and no extension method 'value__' accepting a first argument of type 'E' could be found (are you missing a using directive or an assembly reference?) // object o = e.value__; Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "value__").WithArguments("E", "value__").WithLocation(6, 22)); } [Fact] public void CS1061ERR_NoSuchMemberOrExtension03() { CreateCompilation( @"class A { } class B { void M() { this.F(); this.P = this.Q; } static void M(A a) { a.F(); a.P = a.Q; } }") .VerifyDiagnostics( Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "F").WithArguments("A", "F"), Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "P").WithArguments("A", "P"), Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "Q").WithArguments("A", "Q"), Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "F").WithArguments("B", "F"), Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "P").WithArguments("B", "P"), Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "Q").WithArguments("B", "Q")); } [Fact] public void CS1061ERR_NoSuchMemberOrExtension04() { CreateCompilation( @"using System.Collections.Generic; class C { static void M(List<object> list) { object o = list.Item; list.Item = o; } }") .VerifyDiagnostics( Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "Item").WithArguments("System.Collections.Generic.List<object>", "Item").WithLocation(6, 25), Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "Item").WithArguments("System.Collections.Generic.List<object>", "Item").WithLocation(7, 14)); } [Fact] public void CS1061ERR_NoSuchMemberOrExtension05() { CreateCompilationWithMscorlib40AndSystemCore( @"using System.Linq; class Test { static void Main() { var q = 1.Select(z => z); } } ") .VerifyDiagnostics( // (7,17): error CS1061: 'int' does not contain a definition for 'Select' and no extension method 'Select' accepting a first argument of type 'int' could be found (are you missing a using directive or an assembly reference?) // var q = 1.Select(z => z); Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "Select").WithArguments("int", "Select").WithLocation(7, 19)); } [Fact] public void CS1061ERR_NoSuchMemberOrExtension06() { var source = @"interface I<T> { } static class C { static void M(object o) { o.M1(o, o); o.M2(o, o); } static void M1<T>(this I<T> o, object arg) { } static void M2<T>(this I<T> o, params object[] args) { } }"; CreateCompilationWithMscorlib40AndSystemCore(source).VerifyDiagnostics( // (6,9): error CS1501: No overload for method 'M1' takes 2 arguments Diagnostic(ErrorCode.ERR_BadArgCount, "M1").WithArguments("M1", "2").WithLocation(6, 11), // (7,9): error CS1061: 'object' does not contain a definition for 'M2' and no extension method 'M2' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?) Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "M2").WithArguments("object", "M2").WithLocation(7, 11)); } [Fact] 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[] { 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] public void CS1113ERR_ValueTypeExtDelegate02() { var source = @"delegate void D(); interface I { } struct S { } class C { static void M<T1, T2, T3, T4, T5>(int i, S s, T1 t1, T2 t2, T3 t3, T4 t4, T5 t5) where T2 : class where T3 : struct where T4 : I where T5 : C { D d; d = i.M1; d = i.M2<int, object>; d = s.M1; d = s.M2<S, object>; d = t1.M1; d = t1.M2<T1, object>; d = t2.M1; d = t2.M2<T2, object>; d = t3.M1; d = t3.M2<T3, object>; d = t4.M1; d = t4.M2<T4, object>; d = t5.M1; d = t5.M2<T5, object>; } } static class E { internal static void M1<T>(this T t) { } internal static void M2<T, U>(this T t) { } }"; CreateCompilationWithMscorlib40(source, references: new[] { Net40.SystemCore }).VerifyDiagnostics( // (13,13): error CS1113: Extension methods 'E.M1<int>(int)' defined on value type 'int' cannot be used to create delegates Diagnostic(ErrorCode.ERR_ValueTypeExtDelegate, "i.M1").WithArguments("E.M1<int>(int)", "int").WithLocation(13, 13), // (14,13): error CS1113: Extension methods 'E.M2<int, object>(int)' defined on value type 'int' cannot be used to create delegates Diagnostic(ErrorCode.ERR_ValueTypeExtDelegate, "i.M2<int, object>").WithArguments("E.M2<int, object>(int)", "int").WithLocation(14, 13), // (15,13): error CS1113: Extension methods 'E.M1<S>(S)' defined on value type 'S' cannot be used to create delegates Diagnostic(ErrorCode.ERR_ValueTypeExtDelegate, "s.M1").WithArguments("E.M1<S>(S)", "S").WithLocation(15, 13), // (16,13): error CS1113: Extension methods 'E.M2<S, object>(S)' defined on value type 'S' cannot be used to create delegates Diagnostic(ErrorCode.ERR_ValueTypeExtDelegate, "s.M2<S, object>").WithArguments("E.M2<S, object>(S)", "S").WithLocation(16, 13), // (17,13): error CS1113: Extension methods 'E.M1<T1>(T1)' defined on value type 'T1' cannot be used to create delegates Diagnostic(ErrorCode.ERR_ValueTypeExtDelegate, "t1.M1").WithArguments("E.M1<T1>(T1)", "T1").WithLocation(17, 13), // (18,13): error CS1113: Extension methods 'E.M2<T1, object>(T1)' defined on value type 'T1' cannot be used to create delegates Diagnostic(ErrorCode.ERR_ValueTypeExtDelegate, "t1.M2<T1, object>").WithArguments("E.M2<T1, object>(T1)", "T1").WithLocation(18, 13), // (21,13): error CS1113: Extension methods 'E.M1<T3>(T3)' defined on value type 'T3' cannot be used to create delegates Diagnostic(ErrorCode.ERR_ValueTypeExtDelegate, "t3.M1").WithArguments("E.M1<T3>(T3)", "T3").WithLocation(21, 13), // (22,13): error CS1113: Extension methods 'E.M2<T3, object>(T3)' defined on value type 'T3' cannot be used to create delegates Diagnostic(ErrorCode.ERR_ValueTypeExtDelegate, "t3.M2<T3, object>").WithArguments("E.M2<T3, object>(T3)", "T3").WithLocation(22, 13), // (23,13): error CS1113: Extension methods 'E.M1<T4>(T4)' defined on value type 'T4' cannot be used to create delegates Diagnostic(ErrorCode.ERR_ValueTypeExtDelegate, "t4.M1").WithArguments("E.M1<T4>(T4)", "T4").WithLocation(23, 13), // (24,13): error CS1113: Extension methods 'E.M2<T4, object>(T4)' defined on value type 'T4' cannot be used to create delegates Diagnostic(ErrorCode.ERR_ValueTypeExtDelegate, "t4.M2<T4, object>").WithArguments("E.M2<T4, object>(T4)", "T4").WithLocation(24, 13)); } [WorkItem(528758, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528758")] [Fact(Skip = "528758")] public void CS1113ERR_ValueTypeExtDelegate03() { var source = @"delegate void D(); interface I { } struct S { } class C { static void M<T1, T2, T3, T4, T5>(int i, S s, T1 t1, T2 t2, T3 t3, T4 t4, T5 t5) where T2 : class where T3 : struct where T4 : I where T5 : C { F(i.M1); F(i.M2<int, object>); F(s.M1); F(s.M2<S, object>); F(t1.M1); F(t1.M2<T1, object>); F(t2.M1); F(t2.M2<T2, object>); F(t3.M1); F(t3.M2<T3, object>); F(t4.M1); F(t4.M2<T4, object>); F(t5.M1); F(t5.M2<T5, object>); } static void F(D d) { } } static class E { internal static void M1<T>(this T t) { } internal static void M2<T, U>(this T t) { } }"; CreateCompilation(source, references: new[] { Net40.SystemCore }).VerifyDiagnostics( // (12,11): error CS1113: Extension methods 'E.M1<int>(int)' defined on value type 'int' cannot be used to create delegates Diagnostic(ErrorCode.ERR_ValueTypeExtDelegate, "i.M1").WithArguments("E.M1<int>(int)", "int").WithLocation(12, 11), // (13,11): error CS1113: Extension methods 'E.M2<int, object>(int)' defined on value type 'int' cannot be used to create delegates Diagnostic(ErrorCode.ERR_ValueTypeExtDelegate, "i.M2<int, object>").WithArguments("E.M2<int, object>(int)", "int").WithLocation(13, 11), // (14,11): error CS1113: Extension methods 'E.M1<S>(S)' defined on value type 'S' cannot be used to create delegates Diagnostic(ErrorCode.ERR_ValueTypeExtDelegate, "s.M1").WithArguments("E.M1<S>(S)", "S").WithLocation(14, 11), // (15,11): error CS1113: Extension methods 'E.M2<S, object>(S)' defined on value type 'S' cannot be used to create delegates Diagnostic(ErrorCode.ERR_ValueTypeExtDelegate, "s.M2<S, object>").WithArguments("E.M2<S, object>(S)", "S").WithLocation(15, 11), // (16,11): error CS1113: Extension methods 'E.M1<T1>(T1)' defined on value type 'T1' cannot be used to create delegates Diagnostic(ErrorCode.ERR_ValueTypeExtDelegate, "t1.M1").WithArguments("E.M1<T1>(T1)", "T1").WithLocation(16, 11), // (17,11): error CS1113: Extension methods 'E.M2<T1, object>(T1)' defined on value type 'T1' cannot be used to create delegates Diagnostic(ErrorCode.ERR_ValueTypeExtDelegate, "t1.M2<T1, object>").WithArguments("E.M2<T1, object>(T1)", "T1").WithLocation(17, 11), // (20,11): error CS1113: Extension methods 'E.M1<T3>(T3)' defined on value type 'T3' cannot be used to create delegates Diagnostic(ErrorCode.ERR_ValueTypeExtDelegate, "t3.M1").WithArguments("E.M1<T3>(T3)", "T3").WithLocation(20, 11), // (21,11): error CS1113: Extension methods 'E.M2<T3, object>(T3)' defined on value type 'T3' cannot be used to create delegates Diagnostic(ErrorCode.ERR_ValueTypeExtDelegate, "t3.M2<T3, object>").WithArguments("E.M2<T3, object>(T3)", "T3").WithLocation(21, 11), // (22,11): error CS1113: Extension methods 'E.M1<T4>(T4)' defined on value type 'T4' cannot be used to create delegates Diagnostic(ErrorCode.ERR_ValueTypeExtDelegate, "t4.M1").WithArguments("E.M1<T4>(T4)", "T4").WithLocation(22, 11), // (23,11): error CS1113: Extension methods 'E.M2<T4, object>(T4)' defined on value type 'T4' cannot be used to create delegates Diagnostic(ErrorCode.ERR_ValueTypeExtDelegate, "t4.M2<T4, object>").WithArguments("E.M2<T4, object>(T4)", "T4").WithLocation(23, 11)); } [Fact] public void CS1501ERR_BadArgCount() { var text = @" using System; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { ExampleClass ec = new ExampleClass(); ec.ExampleMethod(10, 20); } } class ExampleClass { public void ExampleMethod() { Console.WriteLine(""Zero parameters""); } } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_BadArgCount, Line = 11, Column = 16 } }); } [Fact] public void CS1502ERR_BadArgTypes() { var text = @" namespace x { public class a { public a(char i) { } public static void Main() { a aa = new a(2222); // CS1502 & CS1503 if (aa == null) {} } } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { //new ErrorDescription { Code = (int)ErrorCode.ERR_BadArgTypes, Line = 12, Column = 24 }, //specifically omitted by roslyn new ErrorDescription { Code = (int)ErrorCode.ERR_BadArgType, Line = 12, Column = 26 }}); } [Fact] public void CS1502ERR_BadArgTypes_ConstructorInitializer() { var text = @" namespace x { public class a { public a() : this(""string"") //CS1502, CS1503 { } public a(char i) { } } } "; CreateCompilation(text).VerifyDiagnostics( //// (6,22): error CS1502: The best overloaded method match for 'x.a.a(char)' has some invalid arguments //Diagnostic(ErrorCode.ERR_BadArgTypes, "this").WithArguments("x.a.a(char)"), //specifically omitted by roslyn // (6,27): error CS1503: Argument 1: cannot convert from 'string' to 'char' Diagnostic(ErrorCode.ERR_BadArgType, "\"string\"").WithArguments("1", "string", "char")); } [Fact] public void CS1503ERR_BadArgType01() { var source = @"namespace X { public class C { public C(int i, char c) { } static void M() { new C(1, 2); // CS1502 & CS1503 } } } "; CreateCompilation(source).VerifyDiagnostics( // (10,22): error CS1503: Argument 2: cannot convert from 'int' to 'char' // new C(1, 2); // CS1502 & CS1503 Diagnostic(ErrorCode.ERR_BadArgType, "2").WithArguments("2", "int", "char").WithLocation(10, 22)); } [Fact] public void CS1503ERR_BadArgType02() { var source = @"enum E1 { A, B, C } enum E2 { X, Y, Z } class C { static void F(int i) { } static void G(E1 e) { } static void M() { F(E1.A); // CS1502 & CS1503 F((E2)E1.B); // CS1502 & CS1503 F((int)E1.C); G(E2.X); // CS1502 & CS1503 G((E1)E2.Y); G((int)E2.Z); // CS1502 & CS1503 } } "; CreateCompilation(source).VerifyDiagnostics( // (9,11): error CS1503: Argument 1: cannot convert from 'E1' to 'int' // F(E1.A); // CS1502 & CS1503 Diagnostic(ErrorCode.ERR_BadArgType, "E1.A").WithArguments("1", "E1", "int").WithLocation(9, 11), // (10,11): error CS1503: Argument 1: cannot convert from 'E2' to 'int' // F((E2)E1.B); // CS1502 & CS1503 Diagnostic(ErrorCode.ERR_BadArgType, "(E2)E1.B").WithArguments("1", "E2", "int").WithLocation(10, 11), // (12,11): error CS1503: Argument 1: cannot convert from 'E2' to 'E1' // G(E2.X); // CS1502 & CS1503 Diagnostic(ErrorCode.ERR_BadArgType, "E2.X").WithArguments("1", "E2", "E1").WithLocation(12, 11), // (14,11): error CS1503: Argument 1: cannot convert from 'int' to 'E1' // G((int)E2.Z); // CS1502 & CS1503 Diagnostic(ErrorCode.ERR_BadArgType, "(int)E2.Z").WithArguments("1", "int", "E1").WithLocation(14, 11)); } [WorkItem(538939, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538939")] [Fact] public void CS1503ERR_BadArgType03() { var source = @"class C { static void F(out int i) { i = 0; } static void M(long arg) { F(out arg); // CS1503 } } "; CreateCompilation(source).VerifyDiagnostics( // (9,15): error CS1503: Argument 1: cannot convert from 'out long' to 'out int' // F(out arg); // CS1503 Diagnostic(ErrorCode.ERR_BadArgType, "arg").WithArguments("1", "out long", "out int").WithLocation(9, 15)); } [Fact] public void CS1503ERR_BadArgType_MixedMethodsAndTypes() { var text = @" class A { public static void Goo(int x) { } } class B : A { public class Goo { } } class C : B { public static void Goo(string x) { } static void Main() { ((Goo))(1); } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.WRN_NewRequired, Line = 8, Column = 16, IsWarning = true }, new ErrorDescription { Code = (int)ErrorCode.WRN_NewRequired, Line = 12, Column = 22, IsWarning = true }, //new ErrorDescription { Code = (int)ErrorCode.ERR_BadArgTypes, Line = 16, Column = 5 }, //specifically omitted by roslyn new ErrorDescription { Code = (int)ErrorCode.ERR_BadArgType, Line = 16, Column = 13 } }); } [Fact] public void CS1510ERR_RefLvalueExpected_01() { var text = @"class C { void M(ref int i) { M(ref 2); // CS1510, can't pass a number as a ref parameter } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_RefLvalueExpected, Line = 5, Column = 15 }); } [Fact] public void CS1510ERR_RefLvalueExpected_02() { var text = @"class C { void M() { var a = new System.Action<int>(ref x => x = 1); var b = new System.Action<int, int>(ref (x,y) => x = 1); var c = new System.Action<int>(ref delegate (int x) {x = 1;}); } } "; CreateCompilation(text).VerifyDiagnostics( // (5,44): error CS1510: A ref or out argument must be an assignable variable // var a = new System.Action<int>(ref x => x = 1); Diagnostic(ErrorCode.ERR_RefLvalueExpected, "x => x = 1").WithLocation(5, 44), // (6,49): error CS1510: A ref or out argument must be an assignable variable // var b = new System.Action<int, int>(ref (x,y) => x = 1); Diagnostic(ErrorCode.ERR_RefLvalueExpected, "(x,y) => x = 1").WithLocation(6, 49), // (7,44): error CS1510: A ref or out argument must be an assignable variable // var c = new System.Action<int>(ref delegate (int x) {x = 1;}); Diagnostic(ErrorCode.ERR_RefLvalueExpected, "delegate (int x) {x = 1;}").WithLocation(7, 44)); } [Fact] public void CS1510ERR_RefLvalueExpected_03() { var text = @"class C { void M() { var a = new System.Action<int>(out x => x = 1); var b = new System.Action<int, int>(out (x,y) => x = 1); var c = new System.Action<int>(out delegate (int x) {x = 1;}); } } "; CreateCompilation(text).VerifyDiagnostics( // (5,44): error CS1510: A ref or out argument must be an assignable variable // var a = new System.Action<int>(out x => x = 1); Diagnostic(ErrorCode.ERR_RefLvalueExpected, "x => x = 1").WithLocation(5, 44), // (6,49): error CS1510: A ref or out argument must be an assignable variable // var b = new System.Action<int, int>(out (x,y) => x = 1); Diagnostic(ErrorCode.ERR_RefLvalueExpected, "(x,y) => x = 1").WithLocation(6, 49), // (7,44): error CS1510: A ref or out argument must be an assignable variable // var c = new System.Action<int>(out delegate (int x) {x = 1;}); Diagnostic(ErrorCode.ERR_RefLvalueExpected, "delegate (int x) {x = 1;}").WithLocation(7, 44)); } [Fact] public void CS1510ERR_RefLvalueExpected_04() { var text = @"class C { void Goo<T>(ref System.Action<T> t) {} void Goo<T1,T2>(ref System.Action<T1,T2> t) {} void M() { Goo<int>(ref x => x = 1); Goo<int, int>(ref (x,y) => x = 1); Goo<int>(ref delegate (int x) {x = 1;}); } } "; CreateCompilation(text).VerifyDiagnostics( // (7,22): error CS1510: A ref or out argument must be an assignable variable // Goo<int>(ref x => x = 1); Diagnostic(ErrorCode.ERR_RefLvalueExpected, "x => x = 1").WithLocation(7, 22), // (8,27): error CS1510: A ref or out argument must be an assignable variable // Goo<int, int>(ref (x,y) => x = 1); Diagnostic(ErrorCode.ERR_RefLvalueExpected, "(x,y) => x = 1").WithLocation(8, 27), // (9,22): error CS1510: A ref or out argument must be an assignable variable // Goo<int>(ref delegate (int x) {x = 1;}); Diagnostic(ErrorCode.ERR_RefLvalueExpected, "delegate (int x) {x = 1;}").WithLocation(9, 22)); } [Fact] public void CS1510ERR_RefLvalueExpected_05() { var text = @"class C { void Goo<T>(out System.Action<T> t) {t = null;} void Goo<T1,T2>(out System.Action<T1,T2> t) {t = null;} void M() { Goo<int>(out x => x = 1); Goo<int, int>(out (x,y) => x = 1); Goo<int>(out delegate (int x) {x = 1;}); } } "; CreateCompilation(text).VerifyDiagnostics( // (7,22): error CS1510: A ref or out argument must be an assignable variable // Goo<int>(out x => x = 1); Diagnostic(ErrorCode.ERR_RefLvalueExpected, "x => x = 1").WithLocation(7, 22), // (8,27): error CS1510: A ref or out argument must be an assignable variable // Goo<int, int>(out (x,y) => x = 1); Diagnostic(ErrorCode.ERR_RefLvalueExpected, "(x,y) => x = 1").WithLocation(8, 27), // (9,22): error CS1510: A ref or out argument must be an assignable variable // Goo<int>(out delegate (int x) {x = 1;}); Diagnostic(ErrorCode.ERR_RefLvalueExpected, "delegate (int x) {x = 1;}").WithLocation(9, 22)); } [Fact] public void CS1510ERR_RefLvalueExpected_Strict() { var text = @"class C { void D(int i) {} void M() { System.Action<int> del = D; var a = new System.Action<int>(ref D); var b = new System.Action<int>(out D); var c = new System.Action<int>(ref del); var d = new System.Action<int>(out del); } } "; CreateCompilation(text, parseOptions: TestOptions.Regular.WithStrictFeature()).VerifyDiagnostics( // (8,44): error CS1657: Cannot pass 'D' as a ref or out argument because it is a 'method group' // var a = new System.Action<int>(ref D); Diagnostic(ErrorCode.ERR_RefReadonlyLocalCause, "D").WithArguments("D", "method group").WithLocation(8, 44), // (9,44): error CS1657: Cannot pass 'D' as a ref or out argument because it is a 'method group' // var b = new System.Action<int>(out D); Diagnostic(ErrorCode.ERR_RefReadonlyLocalCause, "D").WithArguments("D", "method group").WithLocation(9, 44), // (10,44): error CS0149: Method name expected // var c = new System.Action<int>(ref del); Diagnostic(ErrorCode.ERR_MethodNameExpected, "del").WithLocation(10, 44), // (11,44): error CS0149: Method name expected // var d = new System.Action<int>(out del); Diagnostic(ErrorCode.ERR_MethodNameExpected, "del").WithLocation(11, 44)); } [Fact] public void CS1511ERR_BaseInStaticMeth() { var text = @" public class A { public int j = 0; } class C : A { public void Method() { base.j = 3; // base allowed here } public static int StaticMethod() { base.j = 3; // CS1511 return 1; } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_BaseInStaticMeth, Line = 16, Column = 7 } }); } [Fact] public void CS1511ERR_BaseInStaticMeth_Combined() { var text = @" using System; class CLS { static CLS() { var x = base.ToString(); } static object FLD = base.ToString(); static object PROP { get { return base.ToString(); } } static object METHOD() { return base.ToString(); } } class A : Attribute { public object P; } "; CreateCompilation(text).VerifyDiagnostics( // (7,25): error CS1511: Keyword 'base' is not available in a static method // static object FLD = base.ToString(); Diagnostic(ErrorCode.ERR_BaseInStaticMeth, "base"), // (6,28): error CS1511: Keyword 'base' is not available in a static method // static CLS() { var x = base.ToString(); } Diagnostic(ErrorCode.ERR_BaseInStaticMeth, "base"), // (8,39): error CS1511: Keyword 'base' is not available in a static method // static object PROP { get { return base.ToString(); } } Diagnostic(ErrorCode.ERR_BaseInStaticMeth, "base"), // (9,37): error CS1511: Keyword 'base' is not available in a static method // static object METHOD() { return base.ToString(); } Diagnostic(ErrorCode.ERR_BaseInStaticMeth, "base"), // (14,19): warning CS0649: Field 'A.P' is never assigned to, and will always have its default value null // public object P; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "P").WithArguments("A.P", "null") ); } [Fact] public void CS1512ERR_BaseInBadContext() { var text = @" using System; class Base { } class CMyClass : Base { private String xx = base.ToString(); // CS1512 public static void Main() { CMyClass z = new CMyClass(); } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_BaseInBadContext, Line = 8, Column = 25 } }); } [Fact] public void CS1512ERR_BaseInBadContext_AttributeArgument() { var text = @" using System; [assembly: A(P = base.ToString())] public class A : Attribute { public object P; } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_BaseInBadContext, Line = 4, Column = 18 } }); } [Fact] public void CS1520ERR_MemberNeedsType_02() { CreateCompilation( @"class Program { Main() {} Helper() {} \u0050rogram(int x) {} }") .VerifyDiagnostics( // (3,5): error CS1520: Method must have a return type // Main() {} Diagnostic(ErrorCode.ERR_MemberNeedsType, "Main"), // (4,5): error CS1520: Method must have a return type // Helper() {} Diagnostic(ErrorCode.ERR_MemberNeedsType, "Helper").WithLocation(4, 5) ); } [Fact] public void CS1525ERR_InvalidExprTerm() { CreateCompilation( @"public class MyClass { public static int Main() { bool b = string is string; return 1; } }") .VerifyDiagnostics(Diagnostic(ErrorCode.ERR_InvalidExprTerm, "string").WithArguments("string")); } [WorkItem(543167, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543167")] [Fact] public void CS1525ERR_InvalidExprTerm_1() { CreateCompilation( @"class D { public static void Main() { var s = 1?; } } ") .VerifyDiagnostics( // (5,19): error CS1525: Invalid expression term ';' // var s = 1?; Diagnostic(ErrorCode.ERR_InvalidExprTerm, ";").WithArguments(";"), // (5,19): error CS1003: Syntax error, ':' expected // var s = 1?; Diagnostic(ErrorCode.ERR_SyntaxError, ";").WithArguments(":", ";"), // (5,19): error CS1525: Invalid expression term ';' // var s = 1?; Diagnostic(ErrorCode.ERR_InvalidExprTerm, ";").WithArguments(";"), // (5,17): error CS0029: Cannot implicitly convert type 'int' to 'bool' // var s = 1?; Diagnostic(ErrorCode.ERR_NoImplicitConv, "1").WithArguments("int", "bool") ); } [Fact] public void CS1525ERR_InvalidExprTerm_ConditionalOperator() { CreateCompilation( @"class Program { static void Main(string[] args) { int x = 1; int y = 1; System.Console.WriteLine(((x == y)) ?); // Invalid System.Console.WriteLine(((x == y)) ? (x++)); // Invalid System.Console.WriteLine(((x == y)) ? (x++) : (x++) : ((((y++))))); // Invalid System.Console.WriteLine(((x == y)) ? : :); // Invalid } } ") .VerifyDiagnostics(Diagnostic(ErrorCode.ERR_InvalidExprTerm, ")").WithArguments(")"), Diagnostic(ErrorCode.ERR_SyntaxError, ")").WithArguments(":", ")"), Diagnostic(ErrorCode.ERR_InvalidExprTerm, ")").WithArguments(")"), Diagnostic(ErrorCode.ERR_SyntaxError, ")").WithArguments(":", ")"), Diagnostic(ErrorCode.ERR_InvalidExprTerm, ")").WithArguments(")"), Diagnostic(ErrorCode.ERR_SyntaxError, ":").WithArguments(",", ":"), Diagnostic(ErrorCode.ERR_SyntaxError, "(").WithArguments(",", "("), Diagnostic(ErrorCode.ERR_InvalidExprTerm, ":").WithArguments(":"), Diagnostic(ErrorCode.ERR_InvalidExprTerm, ":").WithArguments(":"), Diagnostic(ErrorCode.ERR_SyntaxError, ":").WithArguments(",", ":")); } [WorkItem(528657, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528657")] [Fact] public void CS0106ERR_BadMemberFlag() { CreateCompilation( @"new class MyClass { }") .VerifyDiagnostics(Diagnostic(ErrorCode.ERR_BadMemberFlag, "MyClass").WithArguments("new")); } [Fact] public void CS1540ERR_BadProtectedAccess01() { var text = @" namespace CS1540 { class Program1 { static void Main() { Employee.PreparePayroll(); } } class Person { protected virtual void CalculatePay() { } } class Manager : Person { protected override void CalculatePay() { } } class Employee : Person { public static void PreparePayroll() { Employee emp1 = new Employee(); Person emp2 = new Manager(); Person emp3 = new Employee(); emp1.CalculatePay(); emp2.CalculatePay(); emp3.CalculatePay(); } } }"; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_BadProtectedAccess, Line = 34, Column = 18 }, new ErrorDescription { Code = (int)ErrorCode.ERR_BadProtectedAccess, Line = 35, Column = 18 }}); } [Fact] public void CS1540ERR_BadProtectedAccess02() { var text = @"class A { protected object F; protected void M() { } protected object P { get; set; } public object Q { get; protected set; } public object R { protected get; set; } public object S { private get; set; } } class B : A { void M(object o) { // base. base.M(); base.P = base.F; base.Q = null; M(base.R); M(base.S); // a. A a = new A(); a.M(); a.P = a.F; a.Q = null; M(a.R); M(a.S); // G(). G().M(); G().P = G().F; G().Q = null; M(G().R); M(G().S); // no qualifier M(); P = F; Q = null; M(R); M(S); // this. this.M(); this.P = this.F; this.Q = null; M(this.R); M(this.S); // ((A)this). ((A)this).M(); ((A)this).P = ((A)this).F; ((A)this).Q = null; M(((A)this).R); M(((A)this).S); } static A G() { return null; } } "; CreateCompilation(text).VerifyDiagnostics( // (21,11): error CS0271: The property or indexer 'A.S' cannot be used in this context because the get accessor is inaccessible // M(base.S); Diagnostic(ErrorCode.ERR_InaccessibleGetter, "base.S").WithArguments("A.S"), // (24,11): error CS1540: Cannot access protected member 'A.M()' via a qualifier of type 'A'; the qualifier must be of type 'B' (or derived from it) // a.M(); Diagnostic(ErrorCode.ERR_BadProtectedAccess, "M").WithArguments("A.M()", "A", "B"), // (25,11): error CS1540: Cannot access protected member 'A.P' via a qualifier of type 'A'; the qualifier must be of type 'B' (or derived from it) // a.P = a.F; Diagnostic(ErrorCode.ERR_BadProtectedAccess, "P").WithArguments("A.P", "A", "B"), // (25,17): error CS1540: Cannot access protected member 'A.F' via a qualifier of type 'A'; the qualifier must be of type 'B' (or derived from it) // a.P = a.F; Diagnostic(ErrorCode.ERR_BadProtectedAccess, "F").WithArguments("A.F", "A", "B"), // (26,9): error CS1540: Cannot access protected member 'A.Q' via a qualifier of type 'A'; the qualifier must be of type 'B' (or derived from it) // a.Q = null; Diagnostic(ErrorCode.ERR_BadProtectedAccess, "a.Q").WithArguments("A.Q", "A", "B"), // (27,11): error CS1540: Cannot access protected member 'A.R' via a qualifier of type 'A'; the qualifier must be of type 'B' (or derived from it) // M(a.R); Diagnostic(ErrorCode.ERR_BadProtectedAccess, "a.R").WithArguments("A.R", "A", "B"), // (28,11): error CS0271: The property or indexer 'A.S' cannot be used in this context because the get accessor is inaccessible // M(a.S); Diagnostic(ErrorCode.ERR_InaccessibleGetter, "a.S").WithArguments("A.S"), // (30,13): error CS1540: Cannot access protected member 'A.M()' via a qualifier of type 'A'; the qualifier must be of type 'B' (or derived from it) // G().M(); Diagnostic(ErrorCode.ERR_BadProtectedAccess, "M").WithArguments("A.M()", "A", "B"), // (31,13): error CS1540: Cannot access protected member 'A.P' via a qualifier of type 'A'; the qualifier must be of type 'B' (or derived from it) // G().P = G().F; Diagnostic(ErrorCode.ERR_BadProtectedAccess, "P").WithArguments("A.P", "A", "B"), // (31,21): error CS1540: Cannot access protected member 'A.F' via a qualifier of type 'A'; the qualifier must be of type 'B' (or derived from it) // G().P = G().F; Diagnostic(ErrorCode.ERR_BadProtectedAccess, "F").WithArguments("A.F", "A", "B"), // (32,9): error CS1540: Cannot access protected member 'A.Q' via a qualifier of type 'A'; the qualifier must be of type 'B' (or derived from it) // G().Q = null; Diagnostic(ErrorCode.ERR_BadProtectedAccess, "G().Q").WithArguments("A.Q", "A", "B"), // (33,11): error CS1540: Cannot access protected member 'A.R' via a qualifier of type 'A'; the qualifier must be of type 'B' (or derived from it) // M(G().R); Diagnostic(ErrorCode.ERR_BadProtectedAccess, "G().R").WithArguments("A.R", "A", "B"), // (34,11): error CS0271: The property or indexer 'A.S' cannot be used in this context because the get accessor is inaccessible // M(G().S); Diagnostic(ErrorCode.ERR_InaccessibleGetter, "G().S").WithArguments("A.S"), // (40,11): error CS0271: The property or indexer 'A.S' cannot be used in this context because the get accessor is inaccessible // M(S); Diagnostic(ErrorCode.ERR_InaccessibleGetter, "S").WithArguments("A.S"), // (46,11): error CS0271: The property or indexer 'A.S' cannot be used in this context because the get accessor is inaccessible // M(this.S); Diagnostic(ErrorCode.ERR_InaccessibleGetter, "this.S").WithArguments("A.S"), // (48,19): error CS1540: Cannot access protected member 'A.M()' via a qualifier of type 'A'; the qualifier must be of type 'B' (or derived from it) // ((A)this).M(); Diagnostic(ErrorCode.ERR_BadProtectedAccess, "M").WithArguments("A.M()", "A", "B"), // (49,19): error CS1540: Cannot access protected member 'A.P' via a qualifier of type 'A'; the qualifier must be of type 'B' (or derived from it) // ((A)this).P = ((A)this).F; Diagnostic(ErrorCode.ERR_BadProtectedAccess, "P").WithArguments("A.P", "A", "B"), // (49,33): error CS1540: Cannot access protected member 'A.F' via a qualifier of type 'A'; the qualifier must be of type 'B' (or derived from it) // ((A)this).P = ((A)this).F; Diagnostic(ErrorCode.ERR_BadProtectedAccess, "F").WithArguments("A.F", "A", "B"), // (50,9): error CS1540: Cannot access protected member 'A.Q' via a qualifier of type 'A'; the qualifier must be of type 'B' (or derived from it) // ((A)this).Q = null; Diagnostic(ErrorCode.ERR_BadProtectedAccess, "((A)this).Q").WithArguments("A.Q", "A", "B"), // (51,11): error CS1540: Cannot access protected member 'A.R' via a qualifier of type 'A'; the qualifier must be of type 'B' (or derived from it) // M(((A)this).R); Diagnostic(ErrorCode.ERR_BadProtectedAccess, "((A)this).R").WithArguments("A.R", "A", "B"), // (52,11): error CS0271: The property or indexer 'A.S' cannot be used in this context because the get accessor is inaccessible // M(((A)this).S); Diagnostic(ErrorCode.ERR_InaccessibleGetter, "((A)this).S").WithArguments("A.S"), // (3,22): warning CS0649: Field 'A.F' is never assigned to, and will always have its default value null // protected object F; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "F").WithArguments("A.F", "null") ); } [WorkItem(540271, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540271")] [Fact] public void CS0122ERR_BadAccessProtectedCtor() { // It is illegal to access any "protected" instance method with a "this" that is not of the // current class's type. Oddly enough, that includes constructors. It is legal to call // a protected ctor via ": base()" because then the "this" is of the derived type. But // in a derived class you cannot call "new MyBase()" if the ctor is protected. // // The native compiler produces the error CS1540 whether the offending method is a regular // method or a ctor: // // Cannot access protected member 'MyBase.MyBase' via a qualifier of type 'MyBase'; // the qualifier must be of type 'Derived' (or derived from it) // // Though technically correct, this is a very confusing error message for this scenario; // one does not typically think of the constructor as being a method that is // called with an implicit "this" of a particular receiver type, even though of course // that is exactly what it is. // // The better error message here is to simply say that the best possible ctor cannot // be accessed because it is not accessible. That's what Roslyn does. // // CONSIDER: We might consider making up a new error message for this situation. // // CS0122: 'Base.Base' is inaccessible due to its protection level var text = @"namespace CS0122 { public class Base { protected Base() {} } public class Derived : Base { void M() { Base b = new Base(); } } } "; CreateCompilation(text). VerifyDiagnostics(Diagnostic(ErrorCode.ERR_BadAccess, "Base").WithArguments("CS0122.Base.Base()")); } // CS1545ERR_BindToBogusProp2 --> Symbols\Source\EventTests.cs // CS1546ERR_BindToBogusProp1 --> Symbols\Source\PropertyTests.cs [WorkItem(528658, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528658")] [Fact()] public void CS1560ERR_FileNameTooLong() { var text = @" #line 1 ""ccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc"" public class C { public void Main () { } } "; //EDMAURER no need to enforce a limit here. DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text);//, //new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_FileNameTooLong, Line = 1, Column = 25 } }); } [Fact] public void CS1579ERR_ForEachMissingMember() { var text = @" using System; public class MyCollection { int[] items; public MyCollection() { items = new int[5] { 12, 44, 33, 2, 50 }; } MyEnumerator GetEnumerator() { return new MyEnumerator(this); } public class MyEnumerator { int nIndex; MyCollection collection; public MyEnumerator(MyCollection coll) { collection = coll; nIndex = -1; } public bool MoveNext() { nIndex++; return (nIndex < collection.items.GetLength(0)); } public int Current { get { return (collection.items[nIndex]); } } } public static void Main() { MyCollection col = new MyCollection(); Console.WriteLine(""Values in the collection are:""); foreach (int i in col) // CS1579 { Console.WriteLine(i); } } }"; CreateCompilation(text).VerifyDiagnostics( // (45,27): warning CS0279: 'MyCollection' does not implement the 'collection' pattern. 'MyCollection.GetEnumerator()' is not a public instance or extension method. // foreach (int i in col) // CS1579 Diagnostic(ErrorCode.WRN_PatternNotPublicOrNotInstance, "col").WithArguments("MyCollection", "collection", "MyCollection.GetEnumerator()"), // (45,27): error CS1579: foreach statement cannot operate on variables of type 'MyCollection' because 'MyCollection' does not contain a public definition for 'GetEnumerator' // foreach (int i in col) // CS1579 Diagnostic(ErrorCode.ERR_ForEachMissingMember, "col").WithArguments("MyCollection", "GetEnumerator")); } [Fact] public void CS1579ERR_ForEachMissingMember02() { var text = @" public class Test { public static void Main(string[] args) { foreach (int x in F(1)) { } } static void F(int x) { } } "; CreateCompilation(text). VerifyDiagnostics(Diagnostic(ErrorCode.ERR_ForEachMissingMember, "F(1)").WithArguments("void", "GetEnumerator")); } [Fact] public void CS1593ERR_BadDelArgCount() { var text = @" using System; delegate string func(int i); // declare delegate class a { public static void Main() { func dt = new func(z); x(dt); } public static string z(int j) { Console.WriteLine(j); return j.ToString(); } public static void x(func hello) { hello(8, 9); // CS1593 } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_BadDelArgCount, Line = 21, Column = 9 } }); } [Fact] public void CS1593ERR_BadDelArgCount_02() { var text = @" delegate void MyDelegate1(int x, float y); class Program { public void DelegatedMethod(int x, float y = 3.0f) { System.Console.WriteLine(y); } static void Main(string[] args) { Program mc = new Program(); MyDelegate1 md1 = null; md1 += mc.DelegatedMethod; md1(1); md1 -= mc.DelegatedMethod; } } "; CreateCompilation(text).VerifyDiagnostics( // (11,9): error CS7036: There is no argument given that corresponds to the required formal parameter 'y' of 'MyDelegate1' // md1(1); Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "md1").WithArguments("y", "MyDelegate1").WithLocation(11, 9)); } [Fact] public void CS1593ERR_BadDelArgCount_03() { var text = @" using System; class Program { static void Main() { new Action<int>(Console.WriteLine)(1, 1); } } "; CreateCompilation(text). VerifyDiagnostics(Diagnostic(ErrorCode.ERR_BadDelArgCount, "new Action<int>(Console.WriteLine)").WithArguments("System.Action<int>", "2")); } [Fact()] public void CS1594ERR_BadDelArgTypes() { var text = @" using System; delegate string func(int i); // declare delegate class a { public static void Main() { func dt = new func(z); x(dt); } public static string z(int j) { Console.WriteLine(j); return j.ToString(); } public static void x(func hello) { hello(""8""); // CS1594 } } "; //EDMAURER Giving errors for the individual argument problems is better than generic "delegate 'blah' has some invalid arguments" DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_BadArgType, Line = 21, Column = 15 } }); //new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_BadDelArgTypes, Line = 21, Column = 9 } }); } // TODO: change this to CS0051 in Roslyn? [Fact] public void CS1604ERR_AssgReadonlyLocal() { var text = @" class C { void M() { this = null; } }"; CreateCompilation(text).VerifyDiagnostics( // (6,9): error CS1604: Cannot assign to 'this' because it is read-only Diagnostic(ErrorCode.ERR_AssgReadonlyLocal, "this").WithArguments("this")); } [Fact] public void CS1605ERR_RefReadonlyLocal() { var text = @" class C { void Test() { Ref(ref this); //CS1605 Out(out this); //CS1605 } static void Ref(ref C c) { } static void Out(out C c) { c = null; } }"; CreateCompilation(text).VerifyDiagnostics( // (6,17): error CS1605: Cannot pass 'this' as a ref or out argument because it is read-only Diagnostic(ErrorCode.ERR_RefReadonlyLocal, "this").WithArguments("this"), // (7,17): error CS1605: Cannot pass 'this' as a ref or out argument because it is read-only Diagnostic(ErrorCode.ERR_RefReadonlyLocal, "this").WithArguments("this")); } [Fact] public void CS1612ERR_ReturnNotLValue01() { var text = @" public struct MyStruct { public int Width; } public class ListView { MyStruct ms; public MyStruct Size { get { return ms; } set { ms = value; } } } public class MyClass { public MyClass() { ListView lvi; lvi = new ListView(); lvi.Size.Width = 5; // CS1612 } public static void Main() { } }"; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_ReturnNotLValue, Line = 23, Column = 9 } }); } /// <summary> /// Breaking change from Dev10. CS1612 is now reported for all value /// types, not just struct types. Specifically, CS1612 is now reported /// for type parameters constrained to "struct". (See also CS0131.) /// </summary> [WorkItem(528821, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528821")] [Fact] public void CS1612ERR_ReturnNotLValue02() { var source = @"interface I { object P { get; set; } } struct S : I { public object P { get; set; } } class C<T, U, V> where T : struct, I where U : class, I where V : I { S F1 { get; set; } T F2 { get; set; } U F3 { get; set; } V F4 { get; set; } void M() { F1.P = null; F2.P = null; F3.P = null; F4.P = null; } }"; CreateCompilation(source).VerifyDiagnostics( // (20,9): error CS1612: Cannot modify the return value of 'C<T, U, V>.F1' because it is not a variable Diagnostic(ErrorCode.ERR_ReturnNotLValue, "F1").WithArguments("C<T, U, V>.F1").WithLocation(20, 9), // (20,9): error CS1612: Cannot modify the return value of 'C<T, U, V>.F2' because it is not a variable Diagnostic(ErrorCode.ERR_ReturnNotLValue, "F2").WithArguments("C<T, U, V>.F2").WithLocation(21, 9)); } [Fact] public void CS1615ERR_BadArgExtraRef() { var text = @" class C { public void f(int i) {} public static void Main() { int i = 1; f(ref i); // CS1615 } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { //new ErrorDescription { Code = (int)ErrorCode.ERR_BadArgTypes, Line = 8, Column = 7 }, //specifically omitted by roslyn new ErrorDescription { Code = (int)ErrorCode.ERR_BadArgExtraRef, Line = 8, Column = 13 } }); } [Fact()] public void CS1618ERR_DelegateOnConditional() { var text = @" using System.Diagnostics; delegate void del(); class MakeAnError { public static void Main() { del d = new del(ConditionalMethod); // CS1618 } [Conditional(""DEBUG"")] public static void ConditionalMethod() { } } "; CreateCompilation(text).VerifyDiagnostics( // (10,25): error CS1618: Cannot create delegate with 'MakeAnError.ConditionalMethod()' because it has a Conditional attribute // del d = new del(ConditionalMethod); // CS1618 Diagnostic(ErrorCode.ERR_DelegateOnConditional, "ConditionalMethod").WithArguments("MakeAnError.ConditionalMethod()").WithLocation(10, 25)); } [Fact()] public void CS1618ERR_DelegateOnConditional_02() { var text = @" using System; using System.Diagnostics; delegate void del(); class MakeAnError { class Goo: Attribute { public Goo(object o) {} } [Conditional(""DEBUG"")] [Goo(new del(ConditionalMethod))] // CS1618 public static void ConditionalMethod() { } } "; CreateCompilation(text).VerifyDiagnostics( // (15,18): error CS1618: Cannot create delegate with 'MakeAnError.ConditionalMethod()' because it has a Conditional attribute // [Goo(new del(ConditionalMethod))] // CS1618 Diagnostic(ErrorCode.ERR_DelegateOnConditional, "ConditionalMethod").WithArguments("MakeAnError.ConditionalMethod()").WithLocation(15, 18)); } [Fact] public void CS1620ERR_BadArgRef() { var text = @" class C { void f(ref int i) { } public static void Main() { int x = 1; f(out x); // CS1620 - f takes a ref parameter, not an out parameter } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { //new ErrorDescription { Code = (int)ErrorCode.ERR_BadArgTypes, Line = 8, Column = 9 }, //specifically omitted by roslyn new ErrorDescription { Code = (int)ErrorCode.ERR_BadArgRef, Line = 8, Column = 15 } }); } [Fact] public void CS1621ERR_YieldInAnonMeth() { var text = @" using System.Collections; delegate object MyDelegate(); class C : IEnumerable { public IEnumerator GetEnumerator() { MyDelegate d = delegate { yield return this; // CS1621 return this; }; d(); } public static void Main() { } } "; var comp = CreateCompilation(text); var expected = new DiagnosticDescription[] { // (12,13): error CS1621: The yield statement cannot be used inside an anonymous method or lambda expression // yield return this; // CS1621 Diagnostic(ErrorCode.ERR_YieldInAnonMeth, "yield"), // (8,24): error CS0161: 'C.GetEnumerator()': not all code paths return a value // public IEnumerator GetEnumerator() Diagnostic(ErrorCode.ERR_ReturnExpected, "GetEnumerator").WithArguments("C.GetEnumerator()") }; comp.VerifyDiagnostics(expected); comp.VerifyEmitDiagnostics(expected); } [Fact] public void CS1622ERR_ReturnInIterator() { var text = @" using System.Collections; class C : IEnumerable { public IEnumerator GetEnumerator() { return (IEnumerator) this; // CS1622 yield return this; // OK } } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (8,7): error CS1622: Cannot return a value from an iterator. Use the yield return statement to return a value, or yield break to end the iteration. // return (IEnumerator) this; // CS1622 Diagnostic(ErrorCode.ERR_ReturnInIterator, "return"), // (9,7): warning CS0162: Unreachable code detected // yield return this; // OK Diagnostic(ErrorCode.WRN_UnreachableCode, "yield") ); } [Fact] public void CS1623ERR_BadIteratorArgType() { var text = @" using System.Collections; class C : IEnumerable { public IEnumerator GetEnumerator() { yield return 0; } public IEnumerator GetEnumerator(ref int i) // CS1623 { yield return i; } public IEnumerator GetEnumerator(out float f) // CS1623 { f = 0.0F; yield return f; } } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (11,46): error CS1623: Iterators cannot have ref, in or out parameters // public IEnumerator GetEnumerator(ref int i) // CS1623 Diagnostic(ErrorCode.ERR_BadIteratorArgType, "i"), // (16,48): error CS1623: Iterators cannot have ref, in or out parameters // public IEnumerator GetEnumerator(out float f) // CS1623 Diagnostic(ErrorCode.ERR_BadIteratorArgType, "f") ); } [Fact] public void CS1624ERR_BadIteratorReturn() { var text = @" class C { public int Iterator { get // CS1624 { yield return 1; } } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_BadIteratorReturn, Line = 6, Column = 9 } }); } [Fact] public void CS1625ERR_BadYieldInFinally() { var text = @" using System.Collections; class C : IEnumerable { public IEnumerator GetEnumerator() { try { } finally { yield return this; // CS1625 } } } public class CMain { public static void Main() { } } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (13,9): error CS1625: Cannot yield in the body of a finally clause // yield return this; // CS1625 Diagnostic(ErrorCode.ERR_BadYieldInFinally, "yield") ); } [Fact] public void CS1626ERR_BadYieldInTryOfCatch() { var text = @" using System.Collections; class C : IEnumerable { public IEnumerator GetEnumerator() { try { yield return this; // CS1626 } catch { } } } public class CMain { public static void Main() { } } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (10,10): error CS1626: Cannot yield a value in the body of a try block with a catch clause // yield return this; // CS1626 Diagnostic(ErrorCode.ERR_BadYieldInTryOfCatch, "yield") ); } [Fact] public void CS1628ERR_AnonDelegateCantUse() { var text = @" delegate int MyDelegate(); class C { public static void F(ref int i) { MyDelegate d = delegate { return i; }; // CS1628 } public static void Main() { } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_AnonDelegateCantUse, Line = 8, Column = 42 } }); } [Fact] public void CS1629ERR_IllegalInnerUnsafe() { var text = @" using System.Collections.Generic; class C { IEnumerator<int> IteratorMeth() { int i; unsafe // CS1629 { int *p = &i; yield return *p; } } unsafe IEnumerator<int> IteratorMeth2() { // CS1629 yield break; } } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (7,7): error CS1629: Unsafe code may not appear in iterators // unsafe // CS1629 Diagnostic(ErrorCode.ERR_IllegalInnerUnsafe, "unsafe"), // (9,10): error CS1629: Unsafe code may not appear in iterators // int *p = &i; Diagnostic(ErrorCode.ERR_IllegalInnerUnsafe, "int *"), // (9,19): error CS1629: Unsafe code may not appear in iterators // int *p = &i; Diagnostic(ErrorCode.ERR_IllegalInnerUnsafe, "&i"), // (10,24): error CS1629: Unsafe code may not appear in iterators // yield return *p; Diagnostic(ErrorCode.ERR_IllegalInnerUnsafe, "p"), // (14,29): error CS1629: Unsafe code may not appear in iterators // unsafe IEnumerator<int> IteratorMeth2() { // CS1629 Diagnostic(ErrorCode.ERR_IllegalInnerUnsafe, "IteratorMeth2") ); } [Fact] public void CS1631ERR_BadYieldInCatch() { var text = @" using System; using System.Collections; public class C : IEnumerable { public IEnumerator GetEnumerator() { try { } catch(Exception e) { yield return this; // CS1631 } } public static void Main() { } } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (14,9): error CS1631: Cannot yield a value in the body of a catch clause // yield return this; // CS1631 Diagnostic(ErrorCode.ERR_BadYieldInCatch, "yield"), // (12,23): warning CS0168: The variable 'e' is declared but never used // catch(Exception e) Diagnostic(ErrorCode.WRN_UnreferencedVar, "e").WithArguments("e") ); } [Fact] public void CS1632ERR_BadDelegateLeave() { var text = @" delegate void MyDelegate(); class MyClass { public void Test() { for (int i = 0 ; i < 5 ; i++) { MyDelegate d = delegate { break; // CS1632 }; } } } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (10,13): error CS1632: Control cannot leave the body of an anonymous method or lambda expression // break; // CS1632 Diagnostic(ErrorCode.ERR_BadDelegateLeave, "break") ); } [Fact] public void CS1636ERR_VarargsIterator() { var text = @"using System.Collections; public class Test { IEnumerable Goo(__arglist) { yield return 1; } static int Main(string[] args) { return 1; } } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (5,17): error CS1636: __arglist is not allowed in the parameter list of iterators // IEnumerable Goo(__arglist) Diagnostic(ErrorCode.ERR_VarargsIterator, "Goo")); } [Fact] public void CS1637ERR_UnsafeIteratorArgType() { var text = @" using System.Collections; public unsafe class C { public IEnumerator Iterator1(int* p) // CS1637 { yield return null; } } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (6,39): error CS1637: Iterators cannot have unsafe parameters or yield types Diagnostic(ErrorCode.ERR_UnsafeIteratorArgType, "p")); } [Fact()] public void CS1639ERR_BadCoClassSig() { // BREAKING CHANGE: Dev10 allows this test to compile, even though the output assembly is not verifiable and generates a runtime exception: // BREAKING CHANGE: We disallow CoClass creation if coClassType is an unbound generic type and report a compile time error. var text = @" using System.Runtime.InteropServices; [ComImport, Guid(""00020810-0000-0000-C000-000000000046"")] [CoClass(typeof(GenericClass<>))] public interface InterfaceType {} public class GenericClass<T>: InterfaceType {} public class Program { public static void Main() { var i = new InterfaceType(); } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_BadCoClassSig, Line = 12, Column = 41 } } ); } [Fact()] public void CS1640ERR_MultipleIEnumOfT() { var text = @" using System.Collections; using System.Collections.Generic; public class C : IEnumerable, IEnumerable<int>, IEnumerable<string> { IEnumerator<int> IEnumerable<int>.GetEnumerator() { yield break; } IEnumerator<string> IEnumerable<string>.GetEnumerator() { yield break; } IEnumerator IEnumerable.GetEnumerator() { return (IEnumerator)((IEnumerable<string>)this).GetEnumerator(); } } public class Test { public static int Main() { foreach (int i in new C()) { } // CS1640 return 1; } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_MultipleIEnumOfT, Line = 27, Column = 27 } }); } [WorkItem(7389, "DevDiv_Projects/Roslyn")] [Fact] public void CS1640ERR_MultipleIEnumOfT02() { var text = @" using System.Collections.Generic; public class Test { public static void Main(string[] args) { } } public class C<T> where T : IEnumerable<int>, IEnumerable<string> { public static void TestForeach(T t) { foreach (int i in t) { } } } "; CreateCompilation(text). VerifyDiagnostics(Diagnostic(ErrorCode.WRN_PatternIsAmbiguous, "t").WithArguments("T", "collection", "System.Collections.Generic.IEnumerable<int>.GetEnumerator()", "System.Collections.Generic.IEnumerable<string>.GetEnumerator()"), Diagnostic(ErrorCode.ERR_MultipleIEnumOfT, "t").WithArguments("T", "System.Collections.Generic.IEnumerable<T>")); } [Fact] public void CS1643ERR_AnonymousReturnExpected() { var text = @" delegate int MyDelegate(); class C { static void Main() { MyDelegate d = delegate { // CS1643 int i = 0; if (i == 0) return 1; }; } } "; CreateCompilation(text).VerifyDiagnostics( // (8,24): error CS1643: Not all code paths return a value in anonymous method of type 'MyDelegate' // MyDelegate d = delegate Diagnostic(ErrorCode.ERR_AnonymousReturnExpected, "delegate").WithArguments("anonymous method", "MyDelegate").WithLocation(8, 24) ); } [Fact] public void CS1643ERR_AnonymousReturnExpected_Foreach() { var text = @" using System; public class Test { public static void Main(string[] args) { string[] arr = null; Func<int> f = () => { foreach (var x in arr) return x; }; } } "; CreateCompilation(text). VerifyDiagnostics( // (8,61): error CS0029: Cannot implicitly convert type 'string' to 'int' // Func<int> f = () => { foreach (var x in arr) return x; }; Diagnostic(ErrorCode.ERR_NoImplicitConv, "x").WithArguments("string", "int").WithLocation(8, 61), // (8,61): 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 // Func<int> f = () => { foreach (var x in arr) return x; }; Diagnostic(ErrorCode.ERR_CantConvAnonMethReturns, "x").WithArguments("lambda expression").WithLocation(8, 61), // (8,26): error CS1643: Not all code paths return a value in lambda expression of type 'Func<int>' // Func<int> f = () => { foreach (var x in arr) return x; }; Diagnostic(ErrorCode.ERR_AnonymousReturnExpected, "=>").WithArguments("lambda expression", "System.Func<int>").WithLocation(8, 26) ); } [Fact] public void CS1648ERR_AssgReadonly2() { var text = @" public struct Inner { public int i; } class Outer { public readonly Inner inner = new Inner(); } class D { static void Main() { Outer outer = new Outer(); outer.inner.i = 1; // CS1648 } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_AssgReadonly2, Line = 17, Column = 7 } }); } [Fact] public void CS1649ERR_RefReadonly2() { var text = @" public struct Inner { public int i; } class Outer { public readonly Inner inner = new Inner(); } class D { static void f(ref int iref) { } static void Main() { Outer outer = new Outer(); f(ref outer.inner.i); // CS1649 } } "; CreateCompilation(text).VerifyDiagnostics( // (21,15): error CS1649: Members of readonly field 'Outer.inner' cannot be used as a ref or out value (except in a constructor) // f(ref outer.inner.i); // CS1649 Diagnostic(ErrorCode.ERR_RefReadonly2, "outer.inner.i").WithArguments("Outer.inner").WithLocation(21, 15) ); } [Fact] public void CS1650ERR_AssgReadonlyStatic2() { string text = @"public struct Inner { public int i; } class Outer { public static readonly Inner inner = new Inner(); } class D { static void Main() { Outer.inner.i = 1; // CS1650 } } "; CreateCompilation(text).VerifyDiagnostics( // (15,9): error CS1650: Fields of static readonly field 'Outer.inner' cannot be assigned to (except in a static constructor or a variable initializer) Diagnostic(ErrorCode.ERR_AssgReadonlyStatic2, "Outer.inner.i").WithArguments("Outer.inner")); } [Fact] public void CS1651ERR_RefReadonlyStatic2() { var text = @" public struct Inner { public int i; } class Outer { public static readonly Inner inner = new Inner(); } class D { static void f(ref int iref) { } static void Main() { f(ref Outer.inner.i); // CS1651 } } "; CreateCompilation(text).VerifyDiagnostics( // (20,15): error CS1651: Fields of static readonly field 'Outer.inner' cannot be passed ref or out (except in a static constructor) Diagnostic(ErrorCode.ERR_RefReadonlyStatic2, "Outer.inner.i").WithArguments("Outer.inner")); } [Fact] public void CS1654ERR_AssgReadonlyLocal2Cause() { var text = @" using System.Collections.Generic; namespace CS1654 { struct Book { public string Title; public string Author; public double Price; public Book(string t, string a, double p) { Title = t; Author = a; Price = p; } } class Program { List<Book> list; static void Main(string[] args) { Program prog = new Program(); prog.list = new List<Book>(); foreach (Book b in prog.list) { b.Price += 9.95; // CS1654 } } } }"; CreateCompilation(text).VerifyDiagnostics( // (29,17): error CS1654: Cannot modify members of 'b' because it is a 'foreach iteration variable' Diagnostic(ErrorCode.ERR_AssgReadonlyLocal2Cause, "b.Price").WithArguments("b", "foreach iteration variable")); } [Fact] public void CS1655ERR_RefReadonlyLocal2Cause() { var text = @" struct S { public int i; } class CMain { static void f(ref int iref) { } public static void Main() { S[] sa = new S[10]; foreach(S s in sa) { CMain.f(ref s.i); // CS1655 } } } "; CreateCompilation(text).VerifyDiagnostics( // (18,21): error CS1655: Cannot pass fields of 's' as a ref or out argument because it is a 'foreach iteration variable' // CMain.f(ref s.i); // CS1655 Diagnostic(ErrorCode.ERR_RefReadonlyLocal2Cause, "s.i").WithArguments("s", "foreach iteration variable") ); } [Fact] public void CS1656ERR_AssgReadonlyLocalCause01() { var text = @" using System; class C : IDisposable { public void Dispose() { } } class CMain { unsafe public static void Main() { using (C c = new C()) { c = new C(); // CS1656 } int[] ary = new int[] { 1, 2, 3, 4 }; fixed (int* p = ary) { p = null; // CS1656 } } } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (13,13): error CS1656: Cannot assign to 'c' because it is a 'using variable' Diagnostic(ErrorCode.ERR_AssgReadonlyLocalCause, "c").WithArguments("c", "using variable").WithLocation(15, 13), // (19,13): error CS1656: Cannot assign to 'p' because it is a 'fixed variable' Diagnostic(ErrorCode.ERR_AssgReadonlyLocalCause, "p").WithArguments("p", "fixed variable").WithLocation(21, 13)); } [Fact] public void CS1656ERR_AssgReadonlyLocalCause02() { var text = @"class C { static void M() { M = null; } }"; CreateCompilation(text).VerifyDiagnostics( // (5,9): error CS1656: Cannot assign to 'M' because it is a 'method group' Diagnostic(ErrorCode.ERR_AssgReadonlyLocalCause, "M").WithArguments("M", "method group").WithLocation(5, 9)); } [Fact] public void CS1656ERR_AssgReadonlyLocalCause_NestedForeach() { var text = @" public class Test { static public void Main(string[] args) { string S = ""ABC""; string T = ""XYZ""; foreach (char x in S) { foreach (char y in T) { x = 'M'; } } } } "; CreateCompilation(text). VerifyDiagnostics(Diagnostic(ErrorCode.ERR_AssgReadonlyLocalCause, "x").WithArguments("x", "foreach iteration variable")); } [Fact] public void CS1657ERR_RefReadonlyLocalCause() { var text = @" class C { static void F(ref string s) { } static void Main(string[] args) { foreach (var a in args) { F(ref a); //CS1657 } } } "; CreateCompilation(text).VerifyDiagnostics( // (12,19): error CS1657: Cannot use 'a' as a ref or out value because it is a 'foreach iteration variable' // F(ref a); //CS1657 Diagnostic(ErrorCode.ERR_RefReadonlyLocalCause, "a").WithArguments("a", "foreach iteration variable").WithLocation(12, 19) ); } [Fact] public void CS1660ERR_AnonMethToNonDel() { var text = @" delegate int MyDelegate(); class C { static void Main() { int i = delegate { return 1; }; // CS1660 } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_AnonMethToNonDel, Line = 6, Column = 14 } }); } [Fact] public void CS1661ERR_CantConvAnonMethParams() { var text = @" delegate void MyDelegate(int i); class C { public static void Main() { MyDelegate d = delegate(string s) { }; // CS1661 } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_CantConvAnonMethParams, Line = 8, Column = 24 }, new ErrorDescription { Code = (int)ErrorCode.ERR_BadParamType, Line = 8, Column = 40 } }); } [Fact] public void CS1662ERR_CantConvAnonMethReturns() { var text = @" delegate int MyDelegate(int i); class C { delegate double D(); public static void Main() { MyDelegate d = delegate(int i) { return 1.0; }; // CS1662 D dd = () => { return ""Who knows the real sword of Gryffindor?""; }; } }"; CreateCompilation(text).VerifyDiagnostics( // (9,49): error CS0266: Cannot implicitly convert type 'double' to 'int'. An explicit conversion exists (are you missing a cast?) // MyDelegate d = delegate(int i) { return 1.0; }; // CS1662 Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "1.0").WithArguments("double", "int").WithLocation(9, 49), // (9,49): error CS1662: Cannot convert anonymous method to intended delegate type because some of the return types in the block are not implicitly convertible to the delegate return type // MyDelegate d = delegate(int i) { return 1.0; }; // CS1662 Diagnostic(ErrorCode.ERR_CantConvAnonMethReturns, "1.0").WithArguments("anonymous method").WithLocation(9, 49), // (10,31): error CS0029: Cannot implicitly convert type 'string' to 'double' // D dd = () => { return "Who knows the real sword of Gryffindor?"; }; Diagnostic(ErrorCode.ERR_NoImplicitConv, @"""Who knows the real sword of Gryffindor?""").WithArguments("string", "double").WithLocation(10, 31), // (10,31): 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 // D dd = () => { return "Who knows the real sword of Gryffindor?"; }; Diagnostic(ErrorCode.ERR_CantConvAnonMethReturns, @"""Who knows the real sword of Gryffindor?""").WithArguments("lambda expression").WithLocation(10, 31) ); } [Fact] public void CS1666ERR_FixedBufferNotFixedErr() { var text = @" unsafe struct S { public fixed int buffer[1]; } unsafe class Test { public static void Main() { var inst = new Test(); System.Console.Write(inst.example1()); System.Console.Write(inst.field.buffer[0]); System.Console.Write(inst.example2()); System.Console.Write(inst.field.buffer[0]); } S field = new S(); private int example1() { return (field.buffer[0] = 7); // OK } private int example2() { fixed (int* p = field.buffer) { return (p[0] = 8); // OK } } } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseExe, parseOptions: TestOptions.Regular7_2).VerifyDiagnostics( // (13,30): error CS8320: Feature 'indexing movable fixed buffers' is not available in C# 7.2. Please use language version 7.3 or greater. // System.Console.Write(inst.field.buffer[0]); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_2, "inst.field.buffer").WithArguments("indexing movable fixed buffers", "7.3").WithLocation(13, 30), // (15,30): error CS8320: Feature 'indexing movable fixed buffers' is not available in C# 7.2. Please use language version 7.3 or greater. // System.Console.Write(inst.field.buffer[0]); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_2, "inst.field.buffer").WithArguments("indexing movable fixed buffers", "7.3").WithLocation(15, 30), // (22,17): error CS8320: Feature 'indexing movable fixed buffers' is not available in C# 7.2. Please use language version 7.3 or greater. // return (field.buffer[0] = 7); // OK Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_2, "field.buffer").WithArguments("indexing movable fixed buffers", "7.3").WithLocation(22, 17) ); } [Fact] public void CS1666ERR_FixedBufferNotUnsafeErr() { var text = @" unsafe struct S { public fixed int buffer[1]; } class Test { public static void Main() { var inst = new Test(); System.Console.Write(inst.example1()); System.Console.Write(inst.field.buffer[0]); } S field = new S(); private int example1() { return (field.buffer[0] = 7); // OK } } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseExe).VerifyDiagnostics( // (13,30): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // System.Console.Write(inst.field.buffer[0]); Diagnostic(ErrorCode.ERR_UnsafeNeeded, "inst.field.buffer").WithLocation(13, 30), // (20,17): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // return (field.buffer[0] = 7); // OK Diagnostic(ErrorCode.ERR_UnsafeNeeded, "field.buffer").WithLocation(20, 17) ); } [Fact] public void CS1666ERR_FixedBufferNotFixed() { var text = @" unsafe struct S { public fixed int buffer[1]; } unsafe class Test { public static void Main() { var inst = new Test(); System.Console.Write(inst.example1()); System.Console.Write(inst.field.buffer[0]); System.Console.Write(inst.example2()); System.Console.Write(inst.field.buffer[0]); } S field = new S(); private int example1() { return (field.buffer[0] = 7); // OK } private int example2() { fixed (int* p = field.buffer) { return (p[0] = 8); // OK } } } "; var c = CompileAndVerify(text, expectedOutput: "7788", verify: Verification.Fails, options: TestOptions.UnsafeReleaseExe); c.VerifyIL("Test.example1()", @" { // Code size 22 (0x16) .maxstack 3 .locals init (int V_0) IL_0000: ldarg.0 IL_0001: ldflda ""S Test.field"" IL_0006: ldflda ""int* S.buffer"" IL_000b: ldflda ""int S.<buffer>e__FixedBuffer.FixedElementField"" IL_0010: ldc.i4.7 IL_0011: dup IL_0012: stloc.0 IL_0013: stind.i4 IL_0014: ldloc.0 IL_0015: ret } "); c.VerifyIL("Test.example2()", @" { // Code size 25 (0x19) .maxstack 3 .locals init (pinned int& V_0, int V_1) IL_0000: ldarg.0 IL_0001: ldflda ""S Test.field"" IL_0006: ldflda ""int* S.buffer"" IL_000b: ldflda ""int S.<buffer>e__FixedBuffer.FixedElementField"" IL_0010: stloc.0 IL_0011: ldloc.0 IL_0012: conv.u IL_0013: ldc.i4.8 IL_0014: dup IL_0015: stloc.1 IL_0016: stind.i4 IL_0017: ldloc.1 IL_0018: ret } "); } [Fact] public void CS1669ERR_IllegalVarArgs01() { var source = @"class C { delegate void D(__arglist); // CS1669 static void Main() {} }"; CreateCompilation(source).VerifyDiagnostics( // (3,21): error CS1669: __arglist is not valid in this context // delegate void D(__arglist); // CS1669 Diagnostic(ErrorCode.ERR_IllegalVarArgs, "__arglist") ); } [Fact] public void CS1669ERR_IllegalVarArgs02() { var source = @"class C { object this[object index, __arglist] { get { return null; } } public static C operator +(C c1, __arglist) { return c1; } public static implicit operator int(__arglist) { return 0; } }"; CreateCompilation(source).VerifyDiagnostics( // (3,31): error CS1669: __arglist is not valid in this context // object this[object index, __arglist] Diagnostic(ErrorCode.ERR_IllegalVarArgs, "__arglist"), // (7,38): error CS1669: __arglist is not valid in this context // public static C operator +(C c1, __arglist) { return c1; } Diagnostic(ErrorCode.ERR_IllegalVarArgs, "__arglist"), // (8,41): error CS1669: __arglist is not valid in this context // public static implicit operator int(__arglist) { return 0; } Diagnostic(ErrorCode.ERR_IllegalVarArgs, "__arglist") ); } [WorkItem(863433, "DevDiv/Personal")] [Fact] public void CS1670ERR_IllegalParams() { // TODO: extra 1670 (not check for now) var test = @" delegate int MyDelegate(params int[] paramsList); class Test { public static int Main() { MyDelegate d = delegate(params int[] paramsList) // CS1670 { return paramsList[0]; }; return 1; } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(test, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_IllegalParams, Line = 7, Column = 33 } }); } [Fact] public void CS1673ERR_ThisStructNotInAnonMeth01() { var text = @" delegate int MyDelegate(); public struct S { int member; public int F(int i) { member = i; MyDelegate d = delegate() { i = this.member; // CS1673 return i; }; return d(); } } class CMain { public static void Main() { } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_ThisStructNotInAnonMeth, Line = 13, Column = 17 } }); } [Fact] public void CS1673ERR_ThisStructNotInAnonMeth02() { var text = @" delegate int MyDelegate(); public struct S { int member; public int F(int i) { member = i; MyDelegate d = delegate() { i = member; // CS1673 return i; }; return d(); } } class CMain { public static void Main() { } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_ThisStructNotInAnonMeth, Line = 13, Column = 17 } }); } [Fact] public void CS1674ERR_NoConvToIDisp() { var text = @" class C { public static void Main() { using (int a = 0) // CS1674 using (a); //CS1674 } } "; CreateCompilation(text).VerifyDiagnostics( // (7,22): warning CS0642: Possible mistaken empty statement Diagnostic(ErrorCode.WRN_PossibleMistakenNullStatement, ";"), // (6,16): error CS1674: 'int': type used in a using statement must be implicitly convertible to 'System.IDisposable'. Diagnostic(ErrorCode.ERR_NoConvToIDisp, "int a = 0").WithArguments("int"), // (7,20): error CS1674: 'int': type used in a using statement must be implicitly convertible to 'System.IDisposable'. Diagnostic(ErrorCode.ERR_NoConvToIDisp, "a").WithArguments("int")); } [Fact] public void CS1676ERR_BadParamRef() { var text = @" delegate void E(ref int i); class Errors { static void Main() { E e = delegate(out int i) { }; // CS1676 } } "; var compilation = CreateCompilation(text); compilation.VerifyDiagnostics( // (7,13): error CS1661: Cannot convert anonymous method to delegate type 'E' because the parameter types do not match the delegate parameter types // E e = delegate(out int i) { }; // CS1676 Diagnostic(ErrorCode.ERR_CantConvAnonMethParams, "delegate(out int i) { }").WithArguments("anonymous method", "E"), // (7,22): error CS1676: Parameter 1 must be declared with the 'ref' keyword // E e = delegate(out int i) { }; // CS1676 Diagnostic(ErrorCode.ERR_BadParamRef, "i").WithArguments("1", "ref"), // (7,13): error CS0177: The out parameter 'i' must be assigned to before control leaves the current method // E e = delegate(out int i) { }; // CS1676 Diagnostic(ErrorCode.ERR_ParamUnassigned, "delegate(out int i) { }").WithArguments("i") ); } [Fact] public void CS1677ERR_BadParamExtraRef() { var text = @" delegate void D(int i); class Errors { static void Main() { D d = delegate(out int i) { }; // CS1677 D d = delegate(ref int j) { }; // CS1677 } } "; var compilation = CreateCompilation(text); compilation.VerifyDiagnostics( // (7,15): error CS1661: Cannot convert anonymous method to delegate type 'D' because the parameter types do not match the delegate parameter types // D d = delegate(out int i) { }; // CS1677 Diagnostic(ErrorCode.ERR_CantConvAnonMethParams, "delegate(out int i) { }").WithArguments("anonymous method", "D"), // (7,24): error CS1677: Parameter 1 should not be declared with the 'out' keyword // D d = delegate(out int i) { }; // CS1677 Diagnostic(ErrorCode.ERR_BadParamExtraRef, "i").WithArguments("1", "out"), // (8,15): error CS1661: Cannot convert anonymous method to delegate type 'D' because the parameter types do not match the delegate parameter types // D d = delegate(ref int j) { }; // CS1677 Diagnostic(ErrorCode.ERR_CantConvAnonMethParams, "delegate(ref int j) { }").WithArguments("anonymous method", "D"), // (8,24): error CS1677: Parameter 1 should not be declared with the 'ref' keyword // D d = delegate(ref int j) { }; // CS1677 Diagnostic(ErrorCode.ERR_BadParamExtraRef, "j").WithArguments("1", "ref"), // (8,11): error CS0128: A local variable named 'd' is already defined in this scope // D d = delegate(ref int j) { }; // CS1677 Diagnostic(ErrorCode.ERR_LocalDuplicate, "d").WithArguments("d"), // (7,15): error CS0177: The out parameter 'i' must be assigned to before control leaves the current method // D d = delegate(out int i) { }; // CS1677 Diagnostic(ErrorCode.ERR_ParamUnassigned, "delegate(out int i) { }").WithArguments("i") ); } [Fact] public void CS1678ERR_BadParamType() { var text = @" delegate void D(int i); class Errors { static void Main() { D d = delegate(string s) { }; // CS1678 } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_CantConvAnonMethParams, Line = 7, Column = 15 }, new ErrorDescription { Code = (int)ErrorCode.ERR_BadParamType, Line = 7, Column = 31 } }); } [Fact] public void CS1681ERR_GlobalExternAlias() { var text = @" extern alias global; class myClass { static int Main() { //global::otherClass oc = new global::otherClass(); return 0; } } "; CreateCompilation(text).VerifyDiagnostics( // (2,14): error CS1681: You cannot redefine the global extern alias // extern alias global; Diagnostic(ErrorCode.ERR_GlobalExternAlias, "global"), // (2,14): error CS0430: The extern alias 'global' was not specified in a /reference option // extern alias global; Diagnostic(ErrorCode.ERR_BadExternAlias, "global").WithArguments("global"), // (2,1): info CS8020: Unused extern alias. // extern alias global; Diagnostic(ErrorCode.HDN_UnusedExternAlias, "extern alias global;") ); } [Fact] public void CS1686ERR_LocalCantBeFixedAndHoisted() { var text = @" class MyClass { public unsafe delegate int* MyDelegate(); public unsafe int* Test() { int j = 0; MyDelegate d = delegate { return &j; }; // CS1686 return &j; // CS1686 } } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (9,42): error CS1686: Local 'j' or its members cannot have their address taken and be used inside an anonymous method or lambda expression // MyDelegate d = delegate { return &j; }; // CS1686 Diagnostic(ErrorCode.ERR_LocalCantBeFixedAndHoisted, "&j").WithArguments("j")); } [Fact] public void CS1686ERR_LocalCantBeFixedAndHoisted02() { var text = @"using System; unsafe struct S { public fixed int buffer[1]; public int i; } unsafe class Test { private void example1() { S data = new S(); data.i = data.i + 1; Func<S> lambda = () => data; fixed (int* p = data.buffer) // fail due to receiver being a local { } int *q = data.buffer; // fail due to lambda capture } }"; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (16,25): error CS0213: You cannot use the fixed statement to take the address of an already fixed expression // fixed (int* p = data.buffer) // fail due to receiver being a local Diagnostic(ErrorCode.ERR_FixedNotNeeded, "data.buffer"), // (19,18): error CS1686: Local 'data' or its members cannot have their address taken and be used inside an anonymous method or lambda expression // int *q = data.buffer; // fail due to lambda capture Diagnostic(ErrorCode.ERR_LocalCantBeFixedAndHoisted, "data.buffer").WithArguments("data") ); } [WorkItem(580537, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/580537")] [Fact] public void CS1686ERR_LocalCantBeFixedAndHoisted03() { var text = @"unsafe public struct Test { private delegate int D(); public fixed int i[1]; public void example() { Test t = this; t.i[0] = 5; D d = delegate { var x = t; return 0; }; } }"; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (9,9): error CS1686: Local 't' or its members cannot have their address taken and be used inside an anonymous method or lambda expression // t.i[0] = 5; Diagnostic(ErrorCode.ERR_LocalCantBeFixedAndHoisted, "t.i").WithArguments("t") ); } [Fact] public void CS1688ERR_CantConvAnonMethNoParams() { var text = @" using System; delegate void OutParam(out int i); class ErrorCS1676 { static void Main() { OutParam o; o = delegate // CS1688 { Console.WriteLine(""); }; } } "; CreateCompilation(text).VerifyDiagnostics( // (11,31): error CS1010: Newline in constant // Console.WriteLine("); Diagnostic(ErrorCode.ERR_NewlineInConst, "").WithLocation(11, 31), // (11,34): error CS1026: ) expected // Console.WriteLine("); Diagnostic(ErrorCode.ERR_CloseParenExpected, "").WithLocation(11, 34), // (11,34): error CS1002: ; expected // Console.WriteLine("); Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(11, 34), // (9,13): error CS1688: Cannot convert anonymous method block without a parameter list to delegate type 'OutParam' because it has one or more out parameters // o = delegate // CS1688 Diagnostic(ErrorCode.ERR_CantConvAnonMethNoParams, @"delegate // CS1688 { Console.WriteLine(""); }").WithArguments("OutParam").WithLocation(9, 13) ); } [Fact] public void CS1708ERR_FixedNeedsLvalue() { var text = @" unsafe public struct S { public fixed char name[10]; } public unsafe class C { public S UnsafeMethod() { S myS = new S(); return myS; } static void Main() { C myC = new C(); myC.UnsafeMethod().name[3] = 'a'; // CS1708 C._s1.name[3] = 'a'; // CS1648 myC._s2.name[3] = 'a'; // CS1648 } static readonly S _s1; public readonly S _s2; }"; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (18,9): error CS1708: Fixed size buffers can only be accessed through locals or fields // myC.UnsafeMethod().name[3] = 'a'; // CS1708 Diagnostic(ErrorCode.ERR_FixedNeedsLvalue, "myC.UnsafeMethod().name").WithLocation(18, 9), // (19,9): error CS1650: Fields of static readonly field 'C._s1' cannot be assigned to (except in a static constructor or a variable initializer) // C._s1.name[3] = 'a'; // CS1648 Diagnostic(ErrorCode.ERR_AssgReadonlyStatic2, "C._s1.name[3]").WithArguments("C._s1").WithLocation(19, 9), // (20,9): error CS1648: Members of readonly field 'C._s2' cannot be modified (except in a constructor, an init-only member or a variable initializer) // myC._s2.name[3] = 'a'; // CS1648 Diagnostic(ErrorCode.ERR_AssgReadonly2, "myC._s2.name[3]").WithArguments("C._s2").WithLocation(20, 9) ); } [Fact, WorkItem(543995, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543995"), WorkItem(544258, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544258")] public void CS1728ERR_DelegateOnNullable() { var text = @" using System; class Test { static void Main() { int? x = null; Func<string> f1 = x.ToString; // no error Func<int> f2 = x.GetHashCode; // no error Func<object, bool> f3 = x.Equals; // no error Func<Type> f4 = x.GetType; // no error Func<int> x1 = x.GetValueOrDefault; // 1728 Func<int, int> x2 = x.GetValueOrDefault; // 1728 } } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (14,24): error CS1728: Cannot bind delegate to 'int?.GetValueOrDefault()' because it is a member of 'System.Nullable<T>' // Func<int> x1 = x.GetValueOrDefault; // 1728 Diagnostic(ErrorCode.ERR_DelegateOnNullable, "x.GetValueOrDefault").WithArguments("int?.GetValueOrDefault()"), // (15,29): error CS1728: Cannot bind delegate to 'int?.GetValueOrDefault(int)' because it is a member of 'System.Nullable<T>' // Func<int, int> x2 = x.GetValueOrDefault; // 1728 Diagnostic(ErrorCode.ERR_DelegateOnNullable, "x.GetValueOrDefault").WithArguments("int?.GetValueOrDefault(int)") ); } [Fact, WorkItem(999399, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/999399")] public void CS1729ERR_BadCtorArgCount() { var text = @" class Test { static int Main() { double d = new double(4.5); // was CS0143 (Dev10) Test test1 = new Test(2); // CS1729 Test test2 = new Test(); Parent exampleParent1 = new Parent(10); // CS1729 Parent exampleParent2 = new Parent(10, 1); if (test1 == test2 & exampleParent1 == exampleParent2) {} return 1; } } public class Parent { public Parent(int i, int j) { } } public class Child : Parent { } // CS1729 public class Child2 : Parent { public Child2(int k) : base(k, 0) { } }"; var compilation = CreateCompilation(text); DiagnosticDescription[] expected = { // (21,14): error CS7036: There is no argument given that corresponds to the required formal parameter 'i' of 'Parent.Parent(int, int)' // public class Child : Parent { } // CS1729 Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "Child").WithArguments("i", "Parent.Parent(int, int)").WithLocation(21, 14), // (6,24): error CS1729: 'double' does not contain a constructor that takes 1 arguments // double d = new double(4.5); // was CS0143 (Dev10) Diagnostic(ErrorCode.ERR_BadCtorArgCount, "double").WithArguments("double", "1").WithLocation(6, 24), // (7,26): error CS1729: 'Test' does not contain a constructor that takes 1 arguments // Test test1 = new Test(2); // CS1729 Diagnostic(ErrorCode.ERR_BadCtorArgCount, "Test").WithArguments("Test", "1").WithLocation(7, 26), // (9,37): error CS7036: There is no argument given that corresponds to the required formal parameter 'j' of 'Parent.Parent(int, int)' // Parent exampleParent1 = new Parent(10); // CS1729 Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "Parent").WithArguments("j", "Parent.Parent(int, int)").WithLocation(9, 37) }; compilation.VerifyDiagnostics(expected); compilation.GetDiagnosticsForSyntaxTree(CompilationStage.Compile, compilation.SyntaxTrees.Single(), filterSpanWithinTree: null, includeEarlierStages: true).Verify(expected); } [WorkItem(539631, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539631")] [Fact] public void CS1729ERR_BadCtorArgCount02() { var text = @" class MyClass { int intI = 1; MyClass() { intI = 2; } //this constructor initializer MyClass(int intJ) : this(3, 4) // CS1729 { intI = intI * intJ; } } class MyBase { public int intI = 1; protected MyBase() { intI = 2; } protected MyBase(int intJ) { intI = intJ; } } class MyDerived : MyBase { MyDerived() : base(3, 4) // CS1729 { intI = intI * 2; } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_BadCtorArgCount, Line = 11, Column = 25 }, new ErrorDescription { Code = (int)ErrorCode.ERR_BadCtorArgCount, Line = 32, Column = 19 }); } [Fact] public void CS1737ERR_DefaultValueBeforeRequiredValue() { var text = @" class C { public void Goo(string s = null, int x) { } }"; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_DefaultValueBeforeRequiredValue, Line = 4, Column = 43 } } //sic: error on close paren ); } [WorkItem(539007, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539007")] [Fact] public void DevDiv4792_OptionalBeforeParams() { var text = @" class C { public void Goo(string s = null, params int[] ints) { } } "; //no errors var comp = CreateCompilation(text); Assert.False(comp.GetDiagnostics().Any()); } [WorkItem(527351, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527351")] [Fact] public void CS1738ERR_NamedArgumentSpecificationBeforeFixedArgument() { var text = @" public class C { public static int Main() { Test(age: 5,""""); return 0; } public static void Test(int age, string Name) { } }"; var comp = CreateCompilation(text, parseOptions: TestOptions.Regular6); comp.VerifyDiagnostics( // (6,21): error CS1738: Named argument specifications must appear after all fixed arguments have been specified. Please use language version 7.2 or greater to allow non-trailing named arguments. // Test(age: 5,""); Diagnostic(ErrorCode.ERR_NamedArgumentSpecificationBeforeFixedArgument, @"""""").WithArguments("7.2").WithLocation(6, 21) ); } [Fact] public void CS1739ERR_BadNamedArgument() { var text = @" public class C { public static int Main() { Test(5,Nam:null); return 0; } public static void Test(int age , string Name) { } }"; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = 1739, Line = 6, Column = 20 } }); } [Fact, WorkItem(866112, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/866112")] public void CS1739ERR_BadNamedArgument_1() { var text = @" public class C { public static void Main() { Test(1, 2, Name:3); } public static void Test(params int [] array) { } }"; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = 1739, Line = 6, Column = 20 } }); } [Fact] public void CS1740ERR_DuplicateNamedArgument() { var text = @" public class C { public static int Main() { Test(age: 5, Name: ""5"", Name: """"); return 0; } public static void Test(int age, string Name) { } }"; var compilation = CSharpTestBase.CreateCompilation(text); compilation.VerifyDiagnostics( // (6,33): error CS1740: Named argument 'Name' cannot be specified multiple times // Test(age: 5, Name: "5", Name: ""); Diagnostic(ErrorCode.ERR_DuplicateNamedArgument, "Name").WithArguments("Name").WithLocation(6, 33)); } [Fact] public void CS1742ERR_NamedArgumentForArray() { var text = @" public class B { static int Main() { int[] arr = { }; int s = arr[arr: 1]; s = s + 1; return 1; } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = 1742, Line = 7, Column = 17 } }); } [Fact] public void CS1744ERR_NamedArgumentUsedInPositional() { var text = @" public class C { public static int Main() { Test(5, age: 3); return 0; } public static void Test(int age , string Name) { } }"; // CS1744: Named argument 'q' specifies a parameter for which a positional argument has already been given. DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = 1744, Line = 6, Column = 21 } }); } [Fact] public void CS1744ERR_NamedArgumentUsedInPositional2() { // Unfortunately we allow "void M(params int[] x)" to be called in the expanded // form as "M(x : 123);". However, we still do not allow "M(123, x:456);". var text = @" public class C { public static void Main() { Test(5, x: 3); } public static void Test(params int[] x) { } }"; // CS1744: Named argument 'x' specifies a parameter for which a positional argument has already been given. DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = 1744, Line = 6, Column = 17 } }); } [Fact] public void CS1744ERR_NamedArgumentUsedInPositional3() { var text = @" public class C { public static void Main() { Test(5, x : 6); } public static void Test(int x, int y = 10, params int[] z) { } }"; // CS1744: Named argument 'x' specifies a parameter for which a positional argument has already been given. DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = 1744, Line = 6, Column = 17 } }); } [Fact] public void CS1744ERR_NamedArgumentUsedInPositional4() { var text = @" public class C { public static void Main() { Test(5, 6, 7, 8, 9, 10, z : 6); } public static void Test(int x, int y = 10, params int[] z) { } }"; // CS1744: Named argument 'z' specifies a parameter for which a positional argument has already been given. DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = 1744, Line = 6, Column = 33 } }); } [Fact] public void CS1746ERR_BadNamedArgumentForDelegateInvoke() { var text = @" public class C { delegate int MyDg(int age); public static int Main() { MyDg dg = new MyDg(Test); int S = dg(Ne: 3); return 0; } public static int Test(int age) { return 1; } }"; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = 1746, Line = 8, Column = 24 } }); } // [Fact()] // public void CS1752ERR_FixedNeedsLvalue() // { // var text = @" //"; // DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, // new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_FixedNeedsLvalue, Line = 20, Column = 9 } } // ); // } // CS1912 --> ObjectAndCollectionInitializerTests.cs // CS1913 --> ObjectAndCollectionInitializerTests.cs // CS1914 --> ObjectAndCollectionInitializerTests.cs // CS1917 --> ObjectAndCollectionInitializerTests.cs // CS1918 --> ObjectAndCollectionInitializerTests.cs // CS1920 --> ObjectAndCollectionInitializerTests.cs // CS1921 --> ObjectAndCollectionInitializerTests.cs // CS1922 --> ObjectAndCollectionInitializerTests.cs [Fact] public void CS1919ERR_UnsafeTypeInObjectCreation() { var text = @" unsafe public class C { public static int Main() { var col1 = new int*(); // CS1919 var col2 = new char*(); // CS1919 return 1; } } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (6,20): error CS1919: Unsafe type 'int*' cannot be used in object creation Diagnostic(ErrorCode.ERR_UnsafeTypeInObjectCreation, "new int*()").WithArguments("int*"), // (7,20): error CS1919: Unsafe type 'char*' cannot be used in object creation Diagnostic(ErrorCode.ERR_UnsafeTypeInObjectCreation, "new char*()").WithArguments("char*")); } [Fact] public void CS1928ERR_BadExtensionArgTypes() { var text = @"class C { static void M(float f) { f.F(); } } static class S { internal static void F(this double d) { } }"; var compilation = CreateCompilationWithMscorlib40(text, references: new[] { Net40.SystemCore }); // Previously ERR_BadExtensionArgTypes. compilation.VerifyDiagnostics( // (5,9): error CS1929: 'float' does not contain a definition for 'F' and the best extension method overload 'S.F(double)' requires a receiver of type 'double' // f.F(); Diagnostic(ErrorCode.ERR_BadInstanceArgType, "f").WithArguments("float", "F", "S.F(double)", "double").WithLocation(5, 9)); } [Fact] public void CS1929ERR_BadInstanceArgType() { var source = @"class A { } class B : A { static void M(A a) { a.E(); } } static class S { internal static void E(this B b) { } }"; var compilation = CreateCompilationWithMscorlib40(source, references: new[] { Net40.SystemCore }); compilation.VerifyDiagnostics( // (6,9): error CS1929: 'A' does not contain a definition for 'E' and the best extension method overload 'S.E(B)' requires a receiver of type 'B' // a.E(); Diagnostic(ErrorCode.ERR_BadInstanceArgType, "a").WithArguments("A", "E", "S.E(B)", "B").WithLocation(6, 9) ); } [Fact] public void CS1930ERR_QueryDuplicateRangeVariable() { CreateCompilationWithMscorlib40AndSystemCore(@" using System.Linq; class Program { static void Main() { int[] nums = { 0, 1, 2, 3, 4, 5 }; var query = from num in nums let num = 3 // CS1930 select num; } } ").VerifyDiagnostics( // (10,25): error CS1930: The range variable 'num' has already been declared Diagnostic(ErrorCode.ERR_QueryDuplicateRangeVariable, "num").WithArguments("num")); } [Fact] public void CS1931ERR_QueryRangeVariableOverrides01() { CreateCompilationWithMscorlib40AndSystemCore(@" using System.Linq; class Test { static void Main() { int x = 1; var y = from x in Enumerable.Range(1, 100) // CS1931 select x + 1; } } ").VerifyDiagnostics( // (9,22): error CS1931: The range variable 'x' conflicts with a previous declaration of 'x' // var y = from x in Enumerable.Range(1, 100) // CS1931 Diagnostic(ErrorCode.ERR_QueryRangeVariableOverrides, "x").WithArguments("x"), // (8,13): warning CS0219: The variable 'x' is assigned but its value is never used // int x = 1; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x").WithArguments("x") ); } [Fact] public void CS1932ERR_QueryRangeVariableAssignedBadValue() { CreateCompilationWithMscorlib40AndSystemCore(@" using System.Linq; class Test { static void Main() { var x = from i in Enumerable.Range(1, 100) let k = null select i; } } ").VerifyDiagnostics( // (8,21): error CS1932: Cannot assign <null> to a range variable // let k = null Diagnostic(ErrorCode.ERR_QueryRangeVariableAssignedBadValue, "k = null").WithArguments("<null>") ); } [Fact] public void CS1932ERR_QueryRangeVariableAssignedBadValue02() { CreateCompilationWithMscorlib40AndSystemCore(@" using System.Linq; class Test { static void Main() { var x = from i in Enumerable.Range(1, 100) let k = ()=>3 select i; } } ").VerifyDiagnostics( // (8,21): error CS1932: Cannot assign lambda expression to a range variable // let k = ()=>3 Diagnostic(ErrorCode.ERR_QueryRangeVariableAssignedBadValue, "k = ()=>3").WithArguments("lambda expression") ); } [Fact] public void CS1932ERR_QueryRangeVariableAssignedBadValue03() { CreateCompilationWithMscorlib40AndSystemCore(@" using System.Linq; class Test { static void Main() { var x = from i in Enumerable.Range(1, 100) let k = Main select i; } } ").VerifyDiagnostics( // (8,21): error CS1932: Cannot assign method group to a range variable // let k = Main Diagnostic(ErrorCode.ERR_QueryRangeVariableAssignedBadValue, "k = Main").WithArguments("method group") ); } [Fact] public void CS1932ERR_QueryRangeVariableAssignedBadValue04() { CreateCompilationWithMscorlib40AndSystemCore(@" using System.Linq; class Test { static void Main() { var x = from i in Enumerable.Range(1, 100) let k = M() select i; } static void M() {} } ").VerifyDiagnostics( // (8,21): error CS1932: Cannot assign void to a range variable // let k = M() Diagnostic(ErrorCode.ERR_QueryRangeVariableAssignedBadValue, "k = M()").WithArguments("void") ); } [WorkItem(528756, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528756")] [Fact()] public void CS1933ERR_QueryNotAllowed() { CreateCompilationWithMscorlib40AndSystemCore(@" using System.Linq; using System.Collections; class P { const IEnumerable e = from x in new int[] { 1, 2, 3 } select x; // CS1933 static int Main() { return 1; } } ").VerifyDiagnostics( // EDMAURER now giving the more generic message CS0133 // (7,27): error CS1933: Expression cannot contain query expressions // from //Diagnostic(ErrorCode.ERR_QueryNotAllowed, "from").WithArguments()); // (7,27): error CS0133: The expression being assigned to 'P.e' must be constant // const IEnumerable e = from x in new int[] { 1, 2, 3 } select x; // CS1933 Diagnostic(ErrorCode.ERR_NotConstantExpression, "from x in new int[] { 1, 2, 3 } select x").WithArguments("P.e") ); } [Fact] public void CS1934ERR_QueryNoProviderCastable() { CreateCompilationWithMscorlib40AndSystemCore(@" using System.Linq; using System.Collections; static class Test { public static void Main() { var list = new ArrayList(); var q = from x in list // CS1934 select x + 1; } } ").VerifyDiagnostics( // (9,27): error CS1934: Could not find an implementation of the query pattern for source type 'System.Collections.ArrayList'. 'Select' not found. Consider explicitly specifying the type of the range variable 'x'. // list Diagnostic(ErrorCode.ERR_QueryNoProviderCastable, "list").WithArguments("System.Collections.ArrayList", "Select", "x")); } [Fact] public void CS1935ERR_QueryNoProviderStandard() { CreateCompilationWithMscorlib40AndSystemCore(@" using System.Collections.Generic; class Test { static int Main() { int[] nums = { 0, 1, 2, 3, 4, 5 }; IEnumerable<int> e = from n in nums where n > 3 select n; return 0; } } ").VerifyDiagnostics( // (8,40): 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'? // nums Diagnostic(ErrorCode.ERR_QueryNoProviderStandard, "nums").WithArguments("int[]", "Where")); } [Fact] public void CS1936ERR_QueryNoProvider() { CreateCompilationWithMscorlib40AndSystemCore(@" using System.Collections; using System.Linq; class Test { static int Main() { object obj = null; IEnumerable e = from x in obj // CS1936 select x; return 0; } } ").VerifyDiagnostics( // (10,35): error CS1936: Could not find an implementation of the query pattern for source type 'object'. 'Select' not found. // obj Diagnostic(ErrorCode.ERR_QueryNoProvider, "obj").WithArguments("object", "Select")); } [Fact] public void CS1936ERR_QueryNoProvider01() { var program = @" class X { internal X Cast<T>() { return this; } } class Program { static void Main() { var xx = new X(); var q3 = from int x in xx select x; } }"; var comp = CreateCompilation(program); comp.VerifyDiagnostics( // (11,32): error CS1936: Could not find an implementation of the query pattern for source type 'X'. 'Select' not found. // var q3 = from int x in xx select x; Diagnostic(ErrorCode.ERR_QueryNoProvider, "xx").WithArguments("X", "Select") ); } [Fact] public void CS1937ERR_QueryOuterKey() { CreateCompilationWithMscorlib40AndSystemCore(@" using System.Linq; class Test { static void Main() { int[] sourceA = { 1, 2, 3, 4, 5 }; int[] sourceB = { 3, 4, 5, 6, 7 }; var query = from a in sourceA join b in sourceB on b equals 5 // CS1937 select a + b; } } ").VerifyDiagnostics( // (11,42): error CS1937: The name 'b' is not in scope on the left side of 'equals'. Consider swapping the expressions on either side of 'equals'. // join b in sourceB on b equals 5 // CS1937 Diagnostic(ErrorCode.ERR_QueryOuterKey, "b").WithArguments("b") ); } [Fact] public void CS1938ERR_QueryInnerKey() { CreateCompilationWithMscorlib40AndSystemCore(@" using System.Linq; class Test { static void Main() { int[] sourceA = { 1, 2, 3, 4, 5 }; int[] sourceB = { 3, 4, 5, 6, 7 }; var query = from a in sourceA join b in sourceB on 5 equals a // CS1938 select a + b; } } ").VerifyDiagnostics( // (11,51): error CS1938: The name 'a' is not in scope on the right side of 'equals'. Consider swapping the expressions on either side of 'equals'. // join b in sourceB on 5 equals a // CS1938 Diagnostic(ErrorCode.ERR_QueryInnerKey, "a").WithArguments("a") ); } [Fact] public void CS1939ERR_QueryOutRefRangeVariable() { var text = @" using System.Linq; class Test { public static int F(ref int i) { return i; } public static void Main() { var list = new int[] { 0, 1, 2, 3, 4, 5 }; var q = from x in list let k = x select Test.F(ref x); // CS1939 } } "; CreateCompilation(text).VerifyDiagnostics( // (13,35): error CS1939: Cannot pass the range variable 'x' as an out or ref parameter // select Test.F(ref x); // CS1939 Diagnostic(ErrorCode.ERR_QueryOutRefRangeVariable, "x").WithArguments("x")); } [Fact] public void CS1940ERR_QueryMultipleProviders() { var text = @"using System; class Test { public delegate int Dele(int x); int num = 0; public int Select(Func<int, int> d) { return d(this.num); } public int Select(Dele d) { return d(this.num) + 1; } public static void Main() { var q = from x in new Test() select x; // CS1940 } }"; CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics( // (18,17): error CS1940: Multiple implementations of the query pattern were found for source type 'Test'. Ambiguous call to 'Select'. // select Diagnostic(ErrorCode.ERR_QueryMultipleProviders, "select x").WithArguments("Test", "Select") ); } [Fact] public void CS1941ERR_QueryTypeInferenceFailedMulti() { CreateCompilationWithMscorlib40AndSystemCore(@" using System.Collections; using System.Linq; class Test { static int Main() { var nums = new int[] { 1, 2, 3, 4, 5, 6 }; var words = new string[] { ""lake"", ""mountain"", ""sky"" }; IEnumerable e = from n in nums join w in words on n equals w // CS1941 select w; return 0; } } ").VerifyDiagnostics( // (11,25): error CS1941: The type of one of the expressions in the join clause is incorrect. Type inference failed in the call to 'Join'. // join Diagnostic(ErrorCode.ERR_QueryTypeInferenceFailedMulti, "join").WithArguments("join", "Join")); } [Fact] public void CS1942ERR_QueryTypeInferenceFailed() { var text = @" using System; class Q { public Q Select<T,U>(Func<int, int> func) { return this; } } class Program { static void Main(string[] args) { var x = from i in new Q() select i; //CS1942 } } "; var comp = CreateCompilationWithMscorlib40AndSystemCore(text); comp.VerifyDiagnostics( // (12,17): error CS1942: The type of the expression in the select clause is incorrect. Type inference failed in the call to 'Select'. // select i; //CS1942 Diagnostic(ErrorCode.ERR_QueryTypeInferenceFailed, "select").WithArguments("select", "Select") ); } [Fact] public void CS1943ERR_QueryTypeInferenceFailedSelectMany() { CreateCompilationWithMscorlib40AndSystemCore(@" using System.Linq; class Test { class TestClass { } static void Main() { int[] nums = { 0, 1, 2, 3, 4, 5 }; TestClass tc = new TestClass(); var x = from n in nums from s in tc // CS1943 select n + s; } } ").VerifyDiagnostics( // (13,27): error CS1943: An expression of type 'Test.TestClass' is not allowed in a subsequent from clause in a query expression with source type 'int[]'. Type inference failed in the call to 'SelectMany'. // tc Diagnostic(ErrorCode.ERR_QueryTypeInferenceFailedSelectMany, "tc").WithArguments("Test.TestClass", "int[]", "SelectMany")); } [Fact] public void CS1943ERR_QueryTypeInferenceFailedSelectMany02() { CreateCompilationWithMscorlib40AndSystemCore(@" using System; class Test { class F1 { public F1 SelectMany<T, U>(Func<int, F1> func1, Func<int, int> func2) { return this; } } static void Main() { F1 f1 = new F1(); var x = from f in f1 from g in 3 select f + g; } } ").VerifyDiagnostics( // (14,23): error CS1943: An expression of type 'int' is not allowed in a subsequent from clause in a query expression with source type 'Test.F1'. Type inference failed in the call to 'SelectMany'. // from g in 3 Diagnostic(ErrorCode.ERR_QueryTypeInferenceFailedSelectMany, "3").WithArguments("int", "Test.F1", "SelectMany").WithLocation(14, 23) ); } [Fact, WorkItem(546510, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546510")] public void CS1944ERR_ExpressionTreeContainsPointerOp() { var text = @" using System; using System.Linq.Expressions; unsafe class Test { public delegate int* D(int i); static void Main() { Expression<D> tree = x => &x; // CS1944 Expression<Func<int, int*[]>> testExpr = x => new int*[] { &x }; } } "; //Assert.Equal("", text); CreateCompilationWithMscorlib40AndSystemCore(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (10,35): error CS1944: An expression tree may not contain an unsafe pointer operation // Expression<D> tree = x => &x; // CS1944 Diagnostic(ErrorCode.ERR_ExpressionTreeContainsPointerOp, "&x"), // (11,68): error CS1944: An expression tree may not contain an unsafe pointer operation // Expression<Func<int, int*[]>> testExpr = x => new int*[] { &x }; Diagnostic(ErrorCode.ERR_ExpressionTreeContainsPointerOp, "&x") ); } [Fact] public void CS1945ERR_ExpressionTreeContainsAnonymousMethod() { var text = @" using System; using System.Linq.Expressions; public delegate void D(); class Test { static void Main() { Expression<Func<int, Func<int, bool>>> tree = (x => delegate(int i) { return true; }); // CS1945 } }"; CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics( // (10,61): error CS1945: An expression tree may not contain an anonymous method expression // Expression<Func<int, Func<int, bool>>> tree = (x => delegate(int i) { return true; }); // CS1945 Diagnostic(ErrorCode.ERR_ExpressionTreeContainsAnonymousMethod, "delegate(int i) { return true; }") ); } [Fact] public void CS1946ERR_AnonymousMethodToExpressionTree() { var text = @" using System.Linq.Expressions; public delegate void D(); class Test { static void Main() { Expression<D> tree = delegate() { }; //CS1946 } } "; CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics( // (10,30): error CS1946: An anonymous method expression cannot be converted to an expression tree // Expression<D> tree = delegate() { }; //CS1946 Diagnostic(ErrorCode.ERR_AnonymousMethodToExpressionTree, "delegate() { }") ); } [Fact] public void CS1947ERR_QueryRangeVariableReadOnly() { var program = @" using System.Linq; class Test { static void Main() { int[] array = new int[] { 1, 2, 3, 4, 5 }; var x = from i in array let k = i select i = 5; // CS1947 x.ToList(); } } "; CreateCompilation(program).VerifyDiagnostics( Diagnostic(ErrorCode.ERR_QueryRangeVariableReadOnly, "i").WithArguments("i")); } [Fact] public void CS1948ERR_QueryRangeVariableSameAsTypeParam() { CreateCompilationWithMscorlib40AndSystemCore(@" using System.Linq; class Test { public void TestMethod<T>(T t) { var x = from T in Enumerable.Range(1, 100) // CS1948 select T; } public static void Main() { } } ").VerifyDiagnostics( // (8,17): error CS1948: The range variable 'T' cannot have the same name as a method type parameter // T Diagnostic(ErrorCode.ERR_QueryRangeVariableSameAsTypeParam, "T").WithArguments("T")); } [Fact] public void CS1949ERR_TypeVarNotFoundRangeVariable() { var text = @"using System.Linq; class Test { static void Main() { var x = from var i in Enumerable.Range(1, 100) // CS1949 select i; } }"; CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics( // (7,22): error CS1949: The contextual keyword 'var' cannot be used in a range variable declaration // var x = from var i in Enumerable.Range(1, 100) // CS1949 Diagnostic(ErrorCode.ERR_TypeVarNotFoundRangeVariable, "var") ); } // CS1950 --> ObjectAndCollectionInitializerTests.cs [Fact] public void CS1951ERR_ByRefParameterInExpressionTree() { var text = @" public delegate int TestDelegate(ref int i); class Test { static void Main() { System.Linq.Expressions.Expression<TestDelegate> tree1 = (ref int x) => x; // CS1951 } } "; CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics( // (7,75): error CS1951: An expression tree lambda may not contain a ref, in or out parameter // System.Linq.Expressions.Expression<TestDelegate> tree1 = (ref int x) => x; // CS1951 Diagnostic(ErrorCode.ERR_ByRefParameterInExpressionTree, "x").WithLocation(7, 75) ); } [Fact] public void CS1951ERR_InParameterInExpressionTree() { var text = @" public delegate int TestDelegate(in int i); class Test { static void Main() { System.Linq.Expressions.Expression<TestDelegate> tree1 = (in int x) => x; // CS1951 } } "; CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics( // (7,74): error CS1951: An expression tree lambda may not contain a ref, in or out parameter // System.Linq.Expressions.Expression<TestDelegate> tree1 = (in int x) => x; // CS1951 Diagnostic(ErrorCode.ERR_ByRefParameterInExpressionTree, "x").WithLocation(7, 74) ); } [Fact] public void CS1952ERR_VarArgsInExpressionTree() { var text = @" using System; using System.Linq.Expressions; class Test { public static int M(__arglist) { return 1; } static int Main() { Expression<Func<int, int>> f = x => Test.M(__arglist(x)); // CS1952 return 1; } }"; CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics( // (14,52): error CS1952: An expression tree lambda may not contain a method with variable arguments // Expression<Func<int, int>> f = x => Test.M(__arglist(x)); // CS1952 Diagnostic(ErrorCode.ERR_VarArgsInExpressionTree, "__arglist(x)") ); } [WorkItem(864605, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/864605")] [Fact] public void CS1953ERR_MemGroupInExpressionTree() { var text = @" using System; using System.Linq.Expressions; class CS1953 { public static void Main() { double num = 10; Expression<Func<bool>> testExpr = () => num.GetType is int; // CS0837 } }"; // Used to be CS1953, but now a method group in an is expression is illegal anyway. CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics( // (10,21): error CS0837: The first operand of an 'is' or 'as' operator may not be a lambda expression, anonymous method, or method group. // () => num.GetType is int; // CS1953 Diagnostic(ErrorCode.ERR_LambdaInIsAs, "num.GetType is int").WithLocation(10, 21)); } // CS1954 --> ObjectAndCollectionInitializerTests.cs [Fact] public void CS1955ERR_NonInvocableMemberCalled() { var text = @" namespace CompilerError1955 { class ClassA { public int x = 100; public int X { get { return x; } set { x = value; } } } class Test { static void Main() { ClassA a = new ClassA(); System.Console.WriteLine(a.x()); // CS1955 System.Console.WriteLine(a.X()); // CS1955 } } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_NonInvocableMemberCalled, Line = 19, Column = 40 }, new ErrorDescription { Code = (int)ErrorCode.ERR_NonInvocableMemberCalled, Line = 20, Column = 40 }}); } // CS1958 --> ObjectAndCollectionInitializerTests.cs [Fact] public void CS1959ERR_InvalidConstantDeclarationType() { var text = @" class Program { static void Test<T>() where T : class { const T x = null; // CS1959 } } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (6,25): error CS1959: 'x' is of type 'T'. The type specified in a constant declaration must be sbyte, byte, short, ushort, int, uint, long, ulong, char, float, double, decimal, bool, string, an enum-type, or a reference-type. // const T x = null; // CS1959 Diagnostic(ErrorCode.ERR_InvalidConstantDeclarationType, "null").WithArguments("x", "T") ); } /// <summary> /// Test the different contexts in which CS1961 can be seen. /// </summary> [Fact] public void CS1961ERR_UnexpectedVariance_Contexts() { var text = @" interface IContexts<in TIn, out TOut, TInv> { #region In TIn Property1In { set; } TIn Property2In { get; } //CS1961 on ""TIn"" TIn Property3In { get; set; } //CS1961 on ""TIn"" int this[TIn arg, char filler, char indexer1In] { get; } TIn this[int arg, char[] filler, char indexer2In] { get; } //CS1961 on ""TIn"" int this[TIn arg, bool filler, char indexer3In] { set; } TIn this[int arg, bool[] filler, char indexer4In] { set; } int this[TIn arg, long filler, char indexer5In] { get; set; } TIn this[int arg, long[] filler, char indexer6In] { get; set; } //CS1961 on ""TIn"" int Method1In(TIn p); TIn Method2In(); //CS1961 on ""TIn"" int Method3In(out TIn p); //CS1961 on ""TIn"" int Method4In(ref TIn p); //CS1961 on ""TIn"" event DOut<TIn> Event1In; #endregion In #region Out TOut Property1Out { set; } //CS1961 on ""TOut"" TOut Property2Out { get; } TOut Property3Out { get; set; } //CS1961 on ""TOut"" int this[TOut arg, char filler, bool indexer1Out] { get; } //CS1961 on ""TOut"" TOut this[int arg, char[] filler, bool indexer2Out] { get; } int this[TOut arg, bool filler, bool indexer3Out] { set; } //CS1961 on ""TOut"" TOut this[int arg, bool[] filler, bool indexer4Out] { set; } //CS1961 on ""TOut"" int this[TOut arg, long filler, bool indexer5Out] { get; set; } //CS1961 on ""TOut"" TOut this[int arg, long[] filler, bool indexer6Out] { get; set; } //CS1961 on ""TOut"" long Method1Out(TOut p); //CS1961 on ""TOut"" TOut Method2Out(); long Method3Out(out TOut p); //CS1961 on ""TOut"" (sic: out params have to be input-safe) long Method4Out(ref TOut p); //CS1961 on ""TOut"" event DOut<TOut> Event1Out; //CS1961 on ""TOut"" #endregion Out #region Inv TInv Property1Inv { set; } TInv Property2Inv { get; } TInv Property3Inv { get; set; } int this[TInv arg, char filler, long indexer1Inv] { get; } TInv this[int arg, char[] filler, long indexer2Inv] { get; } int this[TInv arg, bool filler, long indexer3Inv] { set; } TInv this[int arg, bool[] filler, long indexer4Inv] { set; } int this[TInv arg, long filler, long indexer5Inv] { get; set; } TInv this[int arg, long[] filler, long indexer6Inv] { get; set; } long Method1Inv(TInv p); TInv Method2Inv(); long Method3Inv(out TInv p); long Method4Inv(ref TInv p); event DOut<TInv> Event1Inv; #endregion Inv } delegate void DOut<out T>(); //for event types - should preserve the variance of the type arg "; CreateCompilation(text).VerifyDiagnostics( // (6,5): error CS1961: Invalid variance: The type parameter 'TIn' must be covariantly valid on 'IContexts<TIn, TOut, TInv>.Property2In'. 'TIn' is contravariant. // TIn Property2In { get; } //CS1961 on "TIn" Diagnostic(ErrorCode.ERR_UnexpectedVariance, "TIn").WithArguments("IContexts<TIn, TOut, TInv>.Property2In", "TIn", "contravariant", "covariantly").WithLocation(6, 5), // (7,5): error CS1961: Invalid variance: The type parameter 'TIn' must be invariantly valid on 'IContexts<TIn, TOut, TInv>.Property3In'. 'TIn' is contravariant. // TIn Property3In { get; set; } //CS1961 on "TIn" Diagnostic(ErrorCode.ERR_UnexpectedVariance, "TIn").WithArguments("IContexts<TIn, TOut, TInv>.Property3In", "TIn", "contravariant", "invariantly").WithLocation(7, 5), // (10,5): error CS1961: Invalid variance: The type parameter 'TIn' must be covariantly valid on 'IContexts<TIn, TOut, TInv>.this[int, char[], char]'. 'TIn' is contravariant. // TIn this[int arg, char[] filler, char indexer2In] { get; } //CS1961 on "TIn" Diagnostic(ErrorCode.ERR_UnexpectedVariance, "TIn").WithArguments("IContexts<TIn, TOut, TInv>.this[int, char[], char]", "TIn", "contravariant", "covariantly").WithLocation(10, 5), // (14,5): error CS1961: Invalid variance: The type parameter 'TIn' must be invariantly valid on 'IContexts<TIn, TOut, TInv>.this[int, long[], char]'. 'TIn' is contravariant. // TIn this[int arg, long[] filler, char indexer6In] { get; set; } //CS1961 on "TIn" Diagnostic(ErrorCode.ERR_UnexpectedVariance, "TIn").WithArguments("IContexts<TIn, TOut, TInv>.this[int, long[], char]", "TIn", "contravariant", "invariantly").WithLocation(14, 5), // (17,5): error CS1961: Invalid variance: The type parameter 'TIn' must be covariantly valid on 'IContexts<TIn, TOut, TInv>.Method2In()'. 'TIn' is contravariant. // TIn Method2In(); //CS1961 on "TIn" Diagnostic(ErrorCode.ERR_UnexpectedVariance, "TIn").WithArguments("IContexts<TIn, TOut, TInv>.Method2In()", "TIn", "contravariant", "covariantly").WithLocation(17, 5), // (18,23): error CS1961: Invalid variance: The type parameter 'TIn' must be invariantly valid on 'IContexts<TIn, TOut, TInv>.Method3In(out TIn)'. 'TIn' is contravariant. // int Method3In(out TIn p); //CS1961 on "TIn" Diagnostic(ErrorCode.ERR_UnexpectedVariance, "TIn").WithArguments("IContexts<TIn, TOut, TInv>.Method3In(out TIn)", "TIn", "contravariant", "invariantly").WithLocation(18, 23), // (19,23): error CS1961: Invalid variance: The type parameter 'TIn' must be invariantly valid on 'IContexts<TIn, TOut, TInv>.Method4In(ref TIn)'. 'TIn' is contravariant. // int Method4In(ref TIn p); //CS1961 on "TIn" Diagnostic(ErrorCode.ERR_UnexpectedVariance, "TIn").WithArguments("IContexts<TIn, TOut, TInv>.Method4In(ref TIn)", "TIn", "contravariant", "invariantly").WithLocation(19, 23), // (25,5): error CS1961: Invalid variance: The type parameter 'TOut' must be contravariantly valid on 'IContexts<TIn, TOut, TInv>.Property1Out'. 'TOut' is covariant. // TOut Property1Out { set; } //CS1961 on "TOut" Diagnostic(ErrorCode.ERR_UnexpectedVariance, "TOut").WithArguments("IContexts<TIn, TOut, TInv>.Property1Out", "TOut", "covariant", "contravariantly").WithLocation(25, 5), // (27,5): error CS1961: Invalid variance: The type parameter 'TOut' must be invariantly valid on 'IContexts<TIn, TOut, TInv>.Property3Out'. 'TOut' is covariant. // TOut Property3Out { get; set; } //CS1961 on "TOut" Diagnostic(ErrorCode.ERR_UnexpectedVariance, "TOut").WithArguments("IContexts<TIn, TOut, TInv>.Property3Out", "TOut", "covariant", "invariantly").WithLocation(27, 5), // (29,14): error CS1961: Invalid variance: The type parameter 'TOut' must be contravariantly valid on 'IContexts<TIn, TOut, TInv>.this[TOut, char, bool]'. 'TOut' is covariant. // int this[TOut arg, char filler, bool indexer1Out] { get; } //CS1961 on "TOut" Diagnostic(ErrorCode.ERR_UnexpectedVariance, "TOut").WithArguments("IContexts<TIn, TOut, TInv>.this[TOut, char, bool]", "TOut", "covariant", "contravariantly").WithLocation(29, 14), // (31,14): error CS1961: Invalid variance: The type parameter 'TOut' must be contravariantly valid on 'IContexts<TIn, TOut, TInv>.this[TOut, bool, bool]'. 'TOut' is covariant. // int this[TOut arg, bool filler, bool indexer3Out] { set; } //CS1961 on "TOut" Diagnostic(ErrorCode.ERR_UnexpectedVariance, "TOut").WithArguments("IContexts<TIn, TOut, TInv>.this[TOut, bool, bool]", "TOut", "covariant", "contravariantly").WithLocation(31, 14), // (32,5): error CS1961: Invalid variance: The type parameter 'TOut' must be contravariantly valid on 'IContexts<TIn, TOut, TInv>.this[int, bool[], bool]'. 'TOut' is covariant. // TOut this[int arg, bool[] filler, bool indexer4Out] { set; } //CS1961 on "TOut" Diagnostic(ErrorCode.ERR_UnexpectedVariance, "TOut").WithArguments("IContexts<TIn, TOut, TInv>.this[int, bool[], bool]", "TOut", "covariant", "contravariantly").WithLocation(32, 5), // (33,14): error CS1961: Invalid variance: The type parameter 'TOut' must be contravariantly valid on 'IContexts<TIn, TOut, TInv>.this[TOut, long, bool]'. 'TOut' is covariant. // int this[TOut arg, long filler, bool indexer5Out] { get; set; } //CS1961 on "TOut" Diagnostic(ErrorCode.ERR_UnexpectedVariance, "TOut").WithArguments("IContexts<TIn, TOut, TInv>.this[TOut, long, bool]", "TOut", "covariant", "contravariantly").WithLocation(33, 14), // (34,5): error CS1961: Invalid variance: The type parameter 'TOut' must be invariantly valid on 'IContexts<TIn, TOut, TInv>.this[int, long[], bool]'. 'TOut' is covariant. // TOut this[int arg, long[] filler, bool indexer6Out] { get; set; } //CS1961 on "TOut" Diagnostic(ErrorCode.ERR_UnexpectedVariance, "TOut").WithArguments("IContexts<TIn, TOut, TInv>.this[int, long[], bool]", "TOut", "covariant", "invariantly").WithLocation(34, 5), // (36,21): error CS1961: Invalid variance: The type parameter 'TOut' must be contravariantly valid on 'IContexts<TIn, TOut, TInv>.Method1Out(TOut)'. 'TOut' is covariant. // long Method1Out(TOut p); //CS1961 on "TOut" Diagnostic(ErrorCode.ERR_UnexpectedVariance, "TOut").WithArguments("IContexts<TIn, TOut, TInv>.Method1Out(TOut)", "TOut", "covariant", "contravariantly").WithLocation(36, 21), // (38,25): error CS1961: Invalid variance: The type parameter 'TOut' must be invariantly valid on 'IContexts<TIn, TOut, TInv>.Method3Out(out TOut)'. 'TOut' is covariant. // long Method3Out(out TOut p); //CS1961 on "TOut" (sic: out params have to be input-safe) Diagnostic(ErrorCode.ERR_UnexpectedVariance, "TOut").WithArguments("IContexts<TIn, TOut, TInv>.Method3Out(out TOut)", "TOut", "covariant", "invariantly").WithLocation(38, 25), // (39,25): error CS1961: Invalid variance: The type parameter 'TOut' must be invariantly valid on 'IContexts<TIn, TOut, TInv>.Method4Out(ref TOut)'. 'TOut' is covariant. // long Method4Out(ref TOut p); //CS1961 on "TOut" Diagnostic(ErrorCode.ERR_UnexpectedVariance, "TOut").WithArguments("IContexts<TIn, TOut, TInv>.Method4Out(ref TOut)", "TOut", "covariant", "invariantly").WithLocation(39, 25), // (41,22): error CS1961: Invalid variance: The type parameter 'TOut' must be contravariantly valid on 'IContexts<TIn, TOut, TInv>.Event1Out'. 'TOut' is covariant. // event DOut<TOut> Event1Out; //CS1961 on "TOut" Diagnostic(ErrorCode.ERR_UnexpectedVariance, "Event1Out").WithArguments("IContexts<TIn, TOut, TInv>.Event1Out", "TOut", "covariant", "contravariantly").WithLocation(41, 22)); } /// <summary> /// Test all of the contexts that require output safety. /// Note: some also require input safety. /// </summary> [Fact] public void CS1961ERR_UnexpectedVariance_OutputUnsafe() { var text = @" interface IOutputUnsafe<in TIn, out TOut, TInv> { #region Case 1: contravariant type parameter TInv Property1Good { get; } TInv this[long[] Indexer1Good] { get; } TInv Method1Good(); TIn Property1Bad { get; } TIn this[char[] Indexer1Bad] { get; } TIn Method1Bad(); #endregion Case 1 #region Case 2: array of output-unsafe TInv[] Property2Good { get; } TInv[] this[long[,] Indexer2Good] { get; } TInv[] Method2Good(); TIn[] Property2Bad { get; } TIn[] this[char[,] Indexer2Bad] { get; } TIn[] Method2Bad(); #endregion Case 2 #region Case 3: constructed with output-unsafe type arg in covariant slot IOut<TInv> Property3Good { get; } IOut<TInv> this[long[,,] Indexer3Good] { get; } IOut<TInv> Method3Good(); IOut<TIn> Property3Bad { get; } IOut<TIn> this[char[,,] Indexer3Bad] { get; } IOut<TIn> Method3Bad(); #endregion Case 3 #region Case 4: constructed with output-unsafe type arg in invariant slot IInv<TInv> Property4Good { get; } IInv<TInv> this[long[,,,] Indexer4Good] { get; } IInv<TInv> Method4Good(); IInv<TIn> Property4Bad { get; } IInv<TIn> this[char[,,,] Indexer4Bad] { get; } IInv<TIn> Method4Bad(); #endregion Case 4 #region Case 5: constructed with input-unsafe (sic) type arg in contravariant slot IIn<TInv> Property5Good { get; } IIn<TInv> this[long[,,,,] Indexer5Good] { get; } IIn<TInv> Method5Good(); IIn<TOut> Property5Bad { get; } IIn<TOut> this[char[,,,,] Indexer5Bad] { get; } IIn<TOut> Method5Bad(); #endregion Case 5 #region Case 6: constructed with input-unsafe (sic) type arg in invariant slot IInv<TInv> Property6Good { get; } IInv<TInv> this[long[,,,,,] Indexer6Good] { get; } IInv<TInv> Method6Good(); IInv<TOut> Property6Bad { get; } IInv<TOut> this[char[,,,,,] Indexer6Bad] { get; } IInv<TOut> Method6Bad(); #endregion Case 6 } interface IIn<in T> { } interface IOut<out T> { } interface IInv<T> { }"; CreateCompilation(text).VerifyDiagnostics( // (9,5): error CS1961: Invalid variance: The type parameter 'TIn' must be covariantly valid on 'IOutputUnsafe<TIn, TOut, TInv>.Property1Bad'. 'TIn' is contravariant. // TIn Property1Bad { get; } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "TIn").WithArguments("IOutputUnsafe<TIn, TOut, TInv>.Property1Bad", "TIn", "contravariant", "covariantly").WithLocation(9, 5), // (10,5): error CS1961: Invalid variance: The type parameter 'TIn' must be covariantly valid on 'IOutputUnsafe<TIn, TOut, TInv>.this[char[]]'. 'TIn' is contravariant. // TIn this[char[] Indexer1Bad] { get; } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "TIn").WithArguments("IOutputUnsafe<TIn, TOut, TInv>.this[char[]]", "TIn", "contravariant", "covariantly").WithLocation(10, 5), // (11,5): error CS1961: Invalid variance: The type parameter 'TIn' must be covariantly valid on 'IOutputUnsafe<TIn, TOut, TInv>.Method1Bad()'. 'TIn' is contravariant. // TIn Method1Bad(); Diagnostic(ErrorCode.ERR_UnexpectedVariance, "TIn").WithArguments("IOutputUnsafe<TIn, TOut, TInv>.Method1Bad()", "TIn", "contravariant", "covariantly").WithLocation(11, 5), // (19,5): error CS1961: Invalid variance: The type parameter 'TIn' must be covariantly valid on 'IOutputUnsafe<TIn, TOut, TInv>.Property2Bad'. 'TIn' is contravariant. // TIn[] Property2Bad { get; } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "TIn[]").WithArguments("IOutputUnsafe<TIn, TOut, TInv>.Property2Bad", "TIn", "contravariant", "covariantly").WithLocation(19, 5), // (20,5): error CS1961: Invalid variance: The type parameter 'TIn' must be covariantly valid on 'IOutputUnsafe<TIn, TOut, TInv>.this[char[*,*]]'. 'TIn' is contravariant. // TIn[] this[char[,] Indexer2Bad] { get; } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "TIn[]").WithArguments("IOutputUnsafe<TIn, TOut, TInv>.this[char[*,*]]", "TIn", "contravariant", "covariantly").WithLocation(20, 5), // (21,5): error CS1961: Invalid variance: The type parameter 'TIn' must be covariantly valid on 'IOutputUnsafe<TIn, TOut, TInv>.Method2Bad()'. 'TIn' is contravariant. // TIn[] Method2Bad(); Diagnostic(ErrorCode.ERR_UnexpectedVariance, "TIn[]").WithArguments("IOutputUnsafe<TIn, TOut, TInv>.Method2Bad()", "TIn", "contravariant", "covariantly").WithLocation(21, 5), // (29,5): error CS1961: Invalid variance: The type parameter 'TIn' must be covariantly valid on 'IOutputUnsafe<TIn, TOut, TInv>.Property3Bad'. 'TIn' is contravariant. // IOut<TIn> Property3Bad { get; } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "IOut<TIn>").WithArguments("IOutputUnsafe<TIn, TOut, TInv>.Property3Bad", "TIn", "contravariant", "covariantly").WithLocation(29, 5), // (30,5): error CS1961: Invalid variance: The type parameter 'TIn' must be covariantly valid on 'IOutputUnsafe<TIn, TOut, TInv>.this[char[*,*,*]]'. 'TIn' is contravariant. // IOut<TIn> this[char[,,] Indexer3Bad] { get; } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "IOut<TIn>").WithArguments("IOutputUnsafe<TIn, TOut, TInv>.this[char[*,*,*]]", "TIn", "contravariant", "covariantly").WithLocation(30, 5), // (31,5): error CS1961: Invalid variance: The type parameter 'TIn' must be covariantly valid on 'IOutputUnsafe<TIn, TOut, TInv>.Method3Bad()'. 'TIn' is contravariant. // IOut<TIn> Method3Bad(); Diagnostic(ErrorCode.ERR_UnexpectedVariance, "IOut<TIn>").WithArguments("IOutputUnsafe<TIn, TOut, TInv>.Method3Bad()", "TIn", "contravariant", "covariantly").WithLocation(31, 5), // (39,5): error CS1961: Invalid variance: The type parameter 'TIn' must be invariantly valid on 'IOutputUnsafe<TIn, TOut, TInv>.Property4Bad'. 'TIn' is contravariant. // IInv<TIn> Property4Bad { get; } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "IInv<TIn>").WithArguments("IOutputUnsafe<TIn, TOut, TInv>.Property4Bad", "TIn", "contravariant", "invariantly").WithLocation(39, 5), // (40,5): error CS1961: Invalid variance: The type parameter 'TIn' must be invariantly valid on 'IOutputUnsafe<TIn, TOut, TInv>.this[char[*,*,*,*]]'. 'TIn' is contravariant. // IInv<TIn> this[char[,,,] Indexer4Bad] { get; } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "IInv<TIn>").WithArguments("IOutputUnsafe<TIn, TOut, TInv>.this[char[*,*,*,*]]", "TIn", "contravariant", "invariantly").WithLocation(40, 5), // (41,5): error CS1961: Invalid variance: The type parameter 'TIn' must be invariantly valid on 'IOutputUnsafe<TIn, TOut, TInv>.Method4Bad()'. 'TIn' is contravariant. // IInv<TIn> Method4Bad(); Diagnostic(ErrorCode.ERR_UnexpectedVariance, "IInv<TIn>").WithArguments("IOutputUnsafe<TIn, TOut, TInv>.Method4Bad()", "TIn", "contravariant", "invariantly").WithLocation(41, 5), // (49,5): error CS1961: Invalid variance: The type parameter 'TOut' must be contravariantly valid on 'IOutputUnsafe<TIn, TOut, TInv>.Property5Bad'. 'TOut' is covariant. // IIn<TOut> Property5Bad { get; } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "IIn<TOut>").WithArguments("IOutputUnsafe<TIn, TOut, TInv>.Property5Bad", "TOut", "covariant", "contravariantly").WithLocation(49, 5), // (50,5): error CS1961: Invalid variance: The type parameter 'TOut' must be contravariantly valid on 'IOutputUnsafe<TIn, TOut, TInv>.this[char[*,*,*,*,*]]'. 'TOut' is covariant. // IIn<TOut> this[char[,,,,] Indexer5Bad] { get; } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "IIn<TOut>").WithArguments("IOutputUnsafe<TIn, TOut, TInv>.this[char[*,*,*,*,*]]", "TOut", "covariant", "contravariantly").WithLocation(50, 5), // (51,5): error CS1961: Invalid variance: The type parameter 'TOut' must be contravariantly valid on 'IOutputUnsafe<TIn, TOut, TInv>.Method5Bad()'. 'TOut' is covariant. // IIn<TOut> Method5Bad(); Diagnostic(ErrorCode.ERR_UnexpectedVariance, "IIn<TOut>").WithArguments("IOutputUnsafe<TIn, TOut, TInv>.Method5Bad()", "TOut", "covariant", "contravariantly").WithLocation(51, 5), // (59,5): error CS1961: Invalid variance: The type parameter 'TOut' must be invariantly valid on 'IOutputUnsafe<TIn, TOut, TInv>.Property6Bad'. 'TOut' is covariant. // IInv<TOut> Property6Bad { get; } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "IInv<TOut>").WithArguments("IOutputUnsafe<TIn, TOut, TInv>.Property6Bad", "TOut", "covariant", "invariantly").WithLocation(59, 5), // (60,5): error CS1961: Invalid variance: The type parameter 'TOut' must be invariantly valid on 'IOutputUnsafe<TIn, TOut, TInv>.this[char[*,*,*,*,*,*]]'. 'TOut' is covariant. // IInv<TOut> this[char[,,,,,] Indexer6Bad] { get; } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "IInv<TOut>").WithArguments("IOutputUnsafe<TIn, TOut, TInv>.this[char[*,*,*,*,*,*]]", "TOut", "covariant", "invariantly").WithLocation(60, 5), // (61,5): error CS1961: Invalid variance: The type parameter 'TOut' must be invariantly valid on 'IOutputUnsafe<TIn, TOut, TInv>.Method6Bad()'. 'TOut' is covariant. // IInv<TOut> Method6Bad(); Diagnostic(ErrorCode.ERR_UnexpectedVariance, "IInv<TOut>").WithArguments("IOutputUnsafe<TIn, TOut, TInv>.Method6Bad()", "TOut", "covariant", "invariantly").WithLocation(61, 5)); } /// <summary> /// Test all of the contexts that require input safety. /// Note: some also require output safety. /// </summary> [Fact] public void CS1961ERR_UnexpectedVariance_InputUnsafe() { var text = @" interface IInputUnsafe<in TIn, out TOut, TInv> { #region Case 1: contravariant type parameter TInv Property1Good { set; } TInv this[long[] Indexer1GoodA] { set; } long this[long[] Indexer1GoodB, TInv p] { set; } long Method1Good(TInv p); TOut Property1Bad { set; } TOut this[char[] Indexer1BadA] { set; } long this[char[] Indexer1BadB, TOut p] { set; } long Method1Bad(TOut p); #endregion Case 1 #region Case 2: array of input-unsafe TInv[] Property2Good { set; } TInv[] this[long[,] Indexer2GoodA] { set; } long this[long[,] Indexer2GoodB, TInv[] p] { set; } long Method2Good(TInv[] p); TOut[] Property2Bad { set; } TOut[] this[char[,] Indexer2BadA] { set; } long this[char[,] Indexer2BadB, TOut[] p] { set; } long Method2Bad(TOut[] p); #endregion Case 2 #region Case 3: constructed with input-unsafe type arg in covariant (sic: not flipped) slot IOut<TInv> Property3Good { set; } IOut<TInv> this[long[,,] Indexer3GoodA] { set; } long this[long[,,] Indexer3GoodB, IOut<TInv> p] { set; } long Method3Good(IOut<TInv> p); event DOut<TInv> Event3Good; IOut<TOut> Property3Bad { set; } IOut<TOut> this[char[,,] Indexer3BadA] { set; } long this[char[,,] Indexer3BadB, IOut<TOut> p] { set; } long Method3Bad(IOut<TOut> p); event DOut<TOut> Event3Bad; #endregion Case 3 #region Case 4: constructed with input-unsafe type arg in invariant slot IInv<TInv> Property4Good { set; } IInv<TInv> this[long[,,,] Indexer4GoodA] { set; } long this[long[,,,] Indexer4GoodB, IInv<TInv> p] { set; } long Method4Good(IInv<TInv> p); event DInv<TInv> Event4Good; IInv<TOut> Property4Bad { set; } IInv<TOut> this[char[,,,] Indexer4BadA] { set; } long this[char[,,,] Indexer4BadB, IInv<TOut> p] { set; } long Method4Bad(IInv<TOut> p); event DInv<TOut> Event4Bad; #endregion Case 4 #region Case 5: constructed with output-unsafe (sic) type arg in contravariant (sic: not flipped) slot IIn<TInv> Property5Good { set; } IIn<TInv> this[long[,,,,] Indexer5GoodA] { set; } long this[long[,,,,] Indexer5GoodB, IIn<TInv> p] { set; } long Method5Good(IIn<TInv> p); event DIn<TInv> Event5Good; IIn<TIn> Property5Bad { set; } IIn<TIn> this[char[,,,,] Indexer5BadA] { set; } long this[char[,,,,] Indexer5BadB, IIn<TIn> p] { set; } long Method5Bad(IIn<TIn> p); event DIn<TIn> Event5Bad; #endregion Case 5 #region Case 6: constructed with output-unsafe (sic) type arg in invariant slot IInv<TInv> Property6Good { set; } IInv<TInv> this[long[,,,,,] Indexer6GoodA] { set; } long this[long[,,,,,] Indexer6GoodB, IInv<TInv> p] { set; } long Method6Good(IInv<TInv> p); event DInv<TInv> Event6Good; IInv<TIn> Property6Bad { set; } IInv<TIn> this[char[,,,,,] Indexer6BadA] { set; } long this[char[,,,,,] Indexer6BadB, IInv<TIn> p] { set; } long Method6Bad(IInv<TIn> p); event DInv<TIn> Event6Bad; #endregion Case 6 } interface IIn<in T> { } interface IOut<out T> { } interface IInv<T> { } delegate void DIn<in T>(); delegate void DOut<out T>(); delegate void DInv<T>(); "; CreateCompilation(text).VerifyDiagnostics( // (11,5): error CS1961: Invalid variance: The type parameter 'TOut' must be contravariantly valid on 'IInputUnsafe<TIn, TOut, TInv>.this[char[]]'. 'TOut' is covariant. // TOut this[char[] Indexer1BadA] { set; } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "TOut").WithArguments("IInputUnsafe<TIn, TOut, TInv>.this[char[]]", "TOut", "covariant", "contravariantly").WithLocation(11, 5), // (12,36): error CS1961: Invalid variance: The type parameter 'TOut' must be contravariantly valid on 'IInputUnsafe<TIn, TOut, TInv>.this[char[], TOut]'. 'TOut' is covariant. // long this[char[] Indexer1BadB, TOut p] { set; } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "TOut").WithArguments("IInputUnsafe<TIn, TOut, TInv>.this[char[], TOut]", "TOut", "covariant", "contravariantly").WithLocation(12, 36), // (23,5): error CS1961: Invalid variance: The type parameter 'TOut' must be contravariantly valid on 'IInputUnsafe<TIn, TOut, TInv>.this[char[*,*]]'. 'TOut' is covariant. // TOut[] this[char[,] Indexer2BadA] { set; } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "TOut[]").WithArguments("IInputUnsafe<TIn, TOut, TInv>.this[char[*,*]]", "TOut", "covariant", "contravariantly").WithLocation(23, 5), // (24,37): error CS1961: Invalid variance: The type parameter 'TOut' must be contravariantly valid on 'IInputUnsafe<TIn, TOut, TInv>.this[char[*,*], TOut[]]'. 'TOut' is covariant. // long this[char[,] Indexer2BadB, TOut[] p] { set; } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "TOut[]").WithArguments("IInputUnsafe<TIn, TOut, TInv>.this[char[*,*], TOut[]]", "TOut", "covariant", "contravariantly").WithLocation(24, 37), // (36,5): error CS1961: Invalid variance: The type parameter 'TOut' must be contravariantly valid on 'IInputUnsafe<TIn, TOut, TInv>.this[char[*,*,*]]'. 'TOut' is covariant. // IOut<TOut> this[char[,,] Indexer3BadA] { set; } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "IOut<TOut>").WithArguments("IInputUnsafe<TIn, TOut, TInv>.this[char[*,*,*]]", "TOut", "covariant", "contravariantly").WithLocation(36, 5), // (37,38): error CS1961: Invalid variance: The type parameter 'TOut' must be contravariantly valid on 'IInputUnsafe<TIn, TOut, TInv>.this[char[*,*,*], IOut<TOut>]'. 'TOut' is covariant. // long this[char[,,] Indexer3BadB, IOut<TOut> p] { set; } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "IOut<TOut>").WithArguments("IInputUnsafe<TIn, TOut, TInv>.this[char[*,*,*], IOut<TOut>]", "TOut", "covariant", "contravariantly").WithLocation(37, 38), // (50,5): error CS1961: Invalid variance: The type parameter 'TOut' must be invariantly valid on 'IInputUnsafe<TIn, TOut, TInv>.this[char[*,*,*,*]]'. 'TOut' is covariant. // IInv<TOut> this[char[,,,] Indexer4BadA] { set; } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "IInv<TOut>").WithArguments("IInputUnsafe<TIn, TOut, TInv>.this[char[*,*,*,*]]", "TOut", "covariant", "invariantly").WithLocation(50, 5), // (51,39): error CS1961: Invalid variance: The type parameter 'TOut' must be invariantly valid on 'IInputUnsafe<TIn, TOut, TInv>.this[char[*,*,*,*], IInv<TOut>]'. 'TOut' is covariant. // long this[char[,,,] Indexer4BadB, IInv<TOut> p] { set; } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "IInv<TOut>").WithArguments("IInputUnsafe<TIn, TOut, TInv>.this[char[*,*,*,*], IInv<TOut>]", "TOut", "covariant", "invariantly").WithLocation(51, 39), // (64,5): error CS1961: Invalid variance: The type parameter 'TIn' must be covariantly valid on 'IInputUnsafe<TIn, TOut, TInv>.this[char[*,*,*,*,*]]'. 'TIn' is contravariant. // IIn<TIn> this[char[,,,,] Indexer5BadA] { set; } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "IIn<TIn>").WithArguments("IInputUnsafe<TIn, TOut, TInv>.this[char[*,*,*,*,*]]", "TIn", "contravariant", "covariantly").WithLocation(64, 5), // (65,40): error CS1961: Invalid variance: The type parameter 'TIn' must be covariantly valid on 'IInputUnsafe<TIn, TOut, TInv>.this[char[*,*,*,*,*], IIn<TIn>]'. 'TIn' is contravariant. // long this[char[,,,,] Indexer5BadB, IIn<TIn> p] { set; } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "IIn<TIn>").WithArguments("IInputUnsafe<TIn, TOut, TInv>.this[char[*,*,*,*,*], IIn<TIn>]", "TIn", "contravariant", "covariantly").WithLocation(65, 40), // (78,5): error CS1961: Invalid variance: The type parameter 'TIn' must be invariantly valid on 'IInputUnsafe<TIn, TOut, TInv>.this[char[*,*,*,*,*,*]]'. 'TIn' is contravariant. // IInv<TIn> this[char[,,,,,] Indexer6BadA] { set; } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "IInv<TIn>").WithArguments("IInputUnsafe<TIn, TOut, TInv>.this[char[*,*,*,*,*,*]]", "TIn", "contravariant", "invariantly").WithLocation(78, 5), // (79,41): error CS1961: Invalid variance: The type parameter 'TIn' must be invariantly valid on 'IInputUnsafe<TIn, TOut, TInv>.this[char[*,*,*,*,*,*], IInv<TIn>]'. 'TIn' is contravariant. // long this[char[,,,,,] Indexer6BadB, IInv<TIn> p] { set; } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "IInv<TIn>").WithArguments("IInputUnsafe<TIn, TOut, TInv>.this[char[*,*,*,*,*,*], IInv<TIn>]", "TIn", "contravariant", "invariantly").WithLocation(79, 41), // (10,5): error CS1961: Invalid variance: The type parameter 'TOut' must be contravariantly valid on 'IInputUnsafe<TIn, TOut, TInv>.Property1Bad'. 'TOut' is covariant. // TOut Property1Bad { set; } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "TOut").WithArguments("IInputUnsafe<TIn, TOut, TInv>.Property1Bad", "TOut", "covariant", "contravariantly").WithLocation(10, 5), // (13,21): error CS1961: Invalid variance: The type parameter 'TOut' must be contravariantly valid on 'IInputUnsafe<TIn, TOut, TInv>.Method1Bad(TOut)'. 'TOut' is covariant. // long Method1Bad(TOut p); Diagnostic(ErrorCode.ERR_UnexpectedVariance, "TOut").WithArguments("IInputUnsafe<TIn, TOut, TInv>.Method1Bad(TOut)", "TOut", "covariant", "contravariantly").WithLocation(13, 21), // (22,5): error CS1961: Invalid variance: The type parameter 'TOut' must be contravariantly valid on 'IInputUnsafe<TIn, TOut, TInv>.Property2Bad'. 'TOut' is covariant. // TOut[] Property2Bad { set; } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "TOut[]").WithArguments("IInputUnsafe<TIn, TOut, TInv>.Property2Bad", "TOut", "covariant", "contravariantly").WithLocation(22, 5), // (25,21): error CS1961: Invalid variance: The type parameter 'TOut' must be contravariantly valid on 'IInputUnsafe<TIn, TOut, TInv>.Method2Bad(TOut[])'. 'TOut' is covariant. // long Method2Bad(TOut[] p); Diagnostic(ErrorCode.ERR_UnexpectedVariance, "TOut[]").WithArguments("IInputUnsafe<TIn, TOut, TInv>.Method2Bad(TOut[])", "TOut", "covariant", "contravariantly").WithLocation(25, 21), // (35,5): error CS1961: Invalid variance: The type parameter 'TOut' must be contravariantly valid on 'IInputUnsafe<TIn, TOut, TInv>.Property3Bad'. 'TOut' is covariant. // IOut<TOut> Property3Bad { set; } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "IOut<TOut>").WithArguments("IInputUnsafe<TIn, TOut, TInv>.Property3Bad", "TOut", "covariant", "contravariantly").WithLocation(35, 5), // (38,21): error CS1961: Invalid variance: The type parameter 'TOut' must be contravariantly valid on 'IInputUnsafe<TIn, TOut, TInv>.Method3Bad(IOut<TOut>)'. 'TOut' is covariant. // long Method3Bad(IOut<TOut> p); Diagnostic(ErrorCode.ERR_UnexpectedVariance, "IOut<TOut>").WithArguments("IInputUnsafe<TIn, TOut, TInv>.Method3Bad(IOut<TOut>)", "TOut", "covariant", "contravariantly").WithLocation(38, 21), // (39,22): error CS1961: Invalid variance: The type parameter 'TOut' must be contravariantly valid on 'IInputUnsafe<TIn, TOut, TInv>.Event3Bad'. 'TOut' is covariant. // event DOut<TOut> Event3Bad; Diagnostic(ErrorCode.ERR_UnexpectedVariance, "Event3Bad").WithArguments("IInputUnsafe<TIn, TOut, TInv>.Event3Bad", "TOut", "covariant", "contravariantly").WithLocation(39, 22), // (49,5): error CS1961: Invalid variance: The type parameter 'TOut' must be invariantly valid on 'IInputUnsafe<TIn, TOut, TInv>.Property4Bad'. 'TOut' is covariant. // IInv<TOut> Property4Bad { set; } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "IInv<TOut>").WithArguments("IInputUnsafe<TIn, TOut, TInv>.Property4Bad", "TOut", "covariant", "invariantly").WithLocation(49, 5), // (52,21): error CS1961: Invalid variance: The type parameter 'TOut' must be invariantly valid on 'IInputUnsafe<TIn, TOut, TInv>.Method4Bad(IInv<TOut>)'. 'TOut' is covariant. // long Method4Bad(IInv<TOut> p); Diagnostic(ErrorCode.ERR_UnexpectedVariance, "IInv<TOut>").WithArguments("IInputUnsafe<TIn, TOut, TInv>.Method4Bad(IInv<TOut>)", "TOut", "covariant", "invariantly").WithLocation(52, 21), // (53,22): error CS1961: Invalid variance: The type parameter 'TOut' must be invariantly valid on 'IInputUnsafe<TIn, TOut, TInv>.Event4Bad'. 'TOut' is covariant. // event DInv<TOut> Event4Bad; Diagnostic(ErrorCode.ERR_UnexpectedVariance, "Event4Bad").WithArguments("IInputUnsafe<TIn, TOut, TInv>.Event4Bad", "TOut", "covariant", "invariantly").WithLocation(53, 22), // (63,5): error CS1961: Invalid variance: The type parameter 'TIn' must be covariantly valid on 'IInputUnsafe<TIn, TOut, TInv>.Property5Bad'. 'TIn' is contravariant. // IIn<TIn> Property5Bad { set; } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "IIn<TIn>").WithArguments("IInputUnsafe<TIn, TOut, TInv>.Property5Bad", "TIn", "contravariant", "covariantly").WithLocation(63, 5), // (66,21): error CS1961: Invalid variance: The type parameter 'TIn' must be covariantly valid on 'IInputUnsafe<TIn, TOut, TInv>.Method5Bad(IIn<TIn>)'. 'TIn' is contravariant. // long Method5Bad(IIn<TIn> p); Diagnostic(ErrorCode.ERR_UnexpectedVariance, "IIn<TIn>").WithArguments("IInputUnsafe<TIn, TOut, TInv>.Method5Bad(IIn<TIn>)", "TIn", "contravariant", "covariantly").WithLocation(66, 21), // (67,20): error CS1961: Invalid variance: The type parameter 'TIn' must be covariantly valid on 'IInputUnsafe<TIn, TOut, TInv>.Event5Bad'. 'TIn' is contravariant. // event DIn<TIn> Event5Bad; Diagnostic(ErrorCode.ERR_UnexpectedVariance, "Event5Bad").WithArguments("IInputUnsafe<TIn, TOut, TInv>.Event5Bad", "TIn", "contravariant", "covariantly").WithLocation(67, 20), // (77,5): error CS1961: Invalid variance: The type parameter 'TIn' must be invariantly valid on 'IInputUnsafe<TIn, TOut, TInv>.Property6Bad'. 'TIn' is contravariant. // IInv<TIn> Property6Bad { set; } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "IInv<TIn>").WithArguments("IInputUnsafe<TIn, TOut, TInv>.Property6Bad", "TIn", "contravariant", "invariantly").WithLocation(77, 5), // (80,21): error CS1961: Invalid variance: The type parameter 'TIn' must be invariantly valid on 'IInputUnsafe<TIn, TOut, TInv>.Method6Bad(IInv<TIn>)'. 'TIn' is contravariant. // long Method6Bad(IInv<TIn> p); Diagnostic(ErrorCode.ERR_UnexpectedVariance, "IInv<TIn>").WithArguments("IInputUnsafe<TIn, TOut, TInv>.Method6Bad(IInv<TIn>)", "TIn", "contravariant", "invariantly").WithLocation(80, 21), // (81,21): error CS1961: Invalid variance: The type parameter 'TIn' must be invariantly valid on 'IInputUnsafe<TIn, TOut, TInv>.Event6Bad'. 'TIn' is contravariant. // event DInv<TIn> Event6Bad; Diagnostic(ErrorCode.ERR_UnexpectedVariance, "Event6Bad").WithArguments("IInputUnsafe<TIn, TOut, TInv>.Event6Bad", "TIn", "contravariant", "invariantly").WithLocation(81, 21)); } /// <summary> /// Test output-safety checks on base interfaces. /// </summary> [Fact] public void CS1961ERR_UnexpectedVariance_BaseInterfaces() { var text = @" interface IBaseInterfaces<in TIn, out TOut, TInv> : IIn<TOut>, IOut<TIn>, IInv<TInv> { } interface IIn<in T> { } interface IOut<out T> { } interface IInv<T> { }"; CreateCompilation(text).VerifyDiagnostics( // (2,39): error CS1961: Invalid variance: The type parameter 'TOut' must be contravariantly valid on 'IIn<TOut>'. 'TOut' is covariant. Diagnostic(ErrorCode.ERR_UnexpectedVariance, "TOut").WithArguments("IIn<TOut>", "TOut", "covariant", "contravariantly"), // (2,30): error CS1961: Invalid variance: The type parameter 'TIn' must be covariantly valid on 'IOut<TIn>'. 'TIn' is contravariant. Diagnostic(ErrorCode.ERR_UnexpectedVariance, "TIn").WithArguments("IOut<TIn>", "TIn", "contravariant", "covariantly")); } /// <summary> /// Test all type parameter/type argument combinations. /// | Type Arg Covariant | Type Arg Contravariant | Type Arg Invariant /// -------------------------+----------------------+------------------------+-------------------- /// Type Param Covariant | Covariant | Contravariant | Invariant /// Type Param Contravariant | Contravariant | Covariant | Invariant /// Type Param Invariant | Error | Error | Invariant /// </summary> [Fact] public void CS1961ERR_UnexpectedVariance_Generics() { var text = @" interface IOutputUnsafeTable<out TInputUnsafe, in TOutputUnsafe, TInvariant> { ICovariant<TInputUnsafe> OutputUnsafe1(); ICovariant<TOutputUnsafe> OutputUnsafe2(); ICovariant<TInvariant> OutputUnsafe3(); IContravariant<TInputUnsafe> OutputUnsafe4(); IContravariant<TOutputUnsafe> OutputUnsafe5(); IContravariant<TInvariant> OutputUnsafe6(); IInvariant<TInputUnsafe> OutputUnsafe7(); IInvariant<TOutputUnsafe> OutputUnsafe8(); IInvariant<TInvariant> OutputUnsafe9(); } interface IInputUnsafeTable<out TInputUnsafe, in TOutputUnsafe, TInvariant> { void InputUnsafe1(ICovariant<TInputUnsafe> p); void InputUnsafe2(ICovariant<TOutputUnsafe> p); void InputUnsafe3(ICovariant<TInvariant> p); void InputUnsafe4(IContravariant<TInputUnsafe> p); void InputUnsafe5(IContravariant<TOutputUnsafe> p); void InputUnsafe6(IContravariant<TInvariant> p); void InputUnsafe7(IInvariant<TInputUnsafe> p); void InputUnsafe8(IInvariant<TOutputUnsafe> p); void InputUnsafe9(IInvariant<TInvariant> p); } interface IBothUnsafeTable<out TInputUnsafe, in TOutputUnsafe, TInvariant> { void InputUnsafe1(ref ICovariant<TInputUnsafe> p); void InputUnsafe2(ref ICovariant<TOutputUnsafe> p); void InputUnsafe3(ref ICovariant<TInvariant> p); void InputUnsafe4(ref IContravariant<TInputUnsafe> p); void InputUnsafe5(ref IContravariant<TOutputUnsafe> p); void InputUnsafe6(ref IContravariant<TInvariant> p); void InputUnsafe7(ref IInvariant<TInputUnsafe> p); void InputUnsafe8(ref IInvariant<TOutputUnsafe> p); void InputUnsafe9(ref IInvariant<TInvariant> p); } interface ICovariant<out T> { } interface IContravariant<in T> { } interface IInvariant<T> { }"; CreateCompilation(text).VerifyDiagnostics( // (5,5): error CS1961: Invalid variance: The type parameter 'TOutputUnsafe' must be covariantly valid on 'IOutputUnsafeTable<TInputUnsafe, TOutputUnsafe, TInvariant>.OutputUnsafe2()'. 'TOutputUnsafe' is contravariant. // ICovariant<TOutputUnsafe> OutputUnsafe2(); Diagnostic(ErrorCode.ERR_UnexpectedVariance, "ICovariant<TOutputUnsafe>").WithArguments("IOutputUnsafeTable<TInputUnsafe, TOutputUnsafe, TInvariant>.OutputUnsafe2()", "TOutputUnsafe", "contravariant", "covariantly").WithLocation(5, 5), // (8,5): error CS1961: Invalid variance: The type parameter 'TInputUnsafe' must be contravariantly valid on 'IOutputUnsafeTable<TInputUnsafe, TOutputUnsafe, TInvariant>.OutputUnsafe4()'. 'TInputUnsafe' is covariant. // IContravariant<TInputUnsafe> OutputUnsafe4(); Diagnostic(ErrorCode.ERR_UnexpectedVariance, "IContravariant<TInputUnsafe>").WithArguments("IOutputUnsafeTable<TInputUnsafe, TOutputUnsafe, TInvariant>.OutputUnsafe4()", "TInputUnsafe", "covariant", "contravariantly").WithLocation(8, 5), // (12,5): error CS1961: Invalid variance: The type parameter 'TInputUnsafe' must be invariantly valid on 'IOutputUnsafeTable<TInputUnsafe, TOutputUnsafe, TInvariant>.OutputUnsafe7()'. 'TInputUnsafe' is covariant. // IInvariant<TInputUnsafe> OutputUnsafe7(); Diagnostic(ErrorCode.ERR_UnexpectedVariance, "IInvariant<TInputUnsafe>").WithArguments("IOutputUnsafeTable<TInputUnsafe, TOutputUnsafe, TInvariant>.OutputUnsafe7()", "TInputUnsafe", "covariant", "invariantly").WithLocation(12, 5), // (13,5): error CS1961: Invalid variance: The type parameter 'TOutputUnsafe' must be invariantly valid on 'IOutputUnsafeTable<TInputUnsafe, TOutputUnsafe, TInvariant>.OutputUnsafe8()'. 'TOutputUnsafe' is contravariant. // IInvariant<TOutputUnsafe> OutputUnsafe8(); Diagnostic(ErrorCode.ERR_UnexpectedVariance, "IInvariant<TOutputUnsafe>").WithArguments("IOutputUnsafeTable<TInputUnsafe, TOutputUnsafe, TInvariant>.OutputUnsafe8()", "TOutputUnsafe", "contravariant", "invariantly").WithLocation(13, 5), // (19,23): error CS1961: Invalid variance: The type parameter 'TInputUnsafe' must be contravariantly valid on 'IInputUnsafeTable<TInputUnsafe, TOutputUnsafe, TInvariant>.InputUnsafe1(ICovariant<TInputUnsafe>)'. 'TInputUnsafe' is covariant. // void InputUnsafe1(ICovariant<TInputUnsafe> p); Diagnostic(ErrorCode.ERR_UnexpectedVariance, "ICovariant<TInputUnsafe>").WithArguments("IInputUnsafeTable<TInputUnsafe, TOutputUnsafe, TInvariant>.InputUnsafe1(ICovariant<TInputUnsafe>)", "TInputUnsafe", "covariant", "contravariantly").WithLocation(19, 23), // (24,23): error CS1961: Invalid variance: The type parameter 'TOutputUnsafe' must be covariantly valid on 'IInputUnsafeTable<TInputUnsafe, TOutputUnsafe, TInvariant>.InputUnsafe5(IContravariant<TOutputUnsafe>)'. 'TOutputUnsafe' is contravariant. // void InputUnsafe5(IContravariant<TOutputUnsafe> p); Diagnostic(ErrorCode.ERR_UnexpectedVariance, "IContravariant<TOutputUnsafe>").WithArguments("IInputUnsafeTable<TInputUnsafe, TOutputUnsafe, TInvariant>.InputUnsafe5(IContravariant<TOutputUnsafe>)", "TOutputUnsafe", "contravariant", "covariantly").WithLocation(24, 23), // (27,23): error CS1961: Invalid variance: The type parameter 'TInputUnsafe' must be invariantly valid on 'IInputUnsafeTable<TInputUnsafe, TOutputUnsafe, TInvariant>.InputUnsafe7(IInvariant<TInputUnsafe>)'. 'TInputUnsafe' is covariant. // void InputUnsafe7(IInvariant<TInputUnsafe> p); Diagnostic(ErrorCode.ERR_UnexpectedVariance, "IInvariant<TInputUnsafe>").WithArguments("IInputUnsafeTable<TInputUnsafe, TOutputUnsafe, TInvariant>.InputUnsafe7(IInvariant<TInputUnsafe>)", "TInputUnsafe", "covariant", "invariantly").WithLocation(27, 23), // (28,23): error CS1961: Invalid variance: The type parameter 'TOutputUnsafe' must be invariantly valid on 'IInputUnsafeTable<TInputUnsafe, TOutputUnsafe, TInvariant>.InputUnsafe8(IInvariant<TOutputUnsafe>)'. 'TOutputUnsafe' is contravariant. // void InputUnsafe8(IInvariant<TOutputUnsafe> p); Diagnostic(ErrorCode.ERR_UnexpectedVariance, "IInvariant<TOutputUnsafe>").WithArguments("IInputUnsafeTable<TInputUnsafe, TOutputUnsafe, TInvariant>.InputUnsafe8(IInvariant<TOutputUnsafe>)", "TOutputUnsafe", "contravariant", "invariantly").WithLocation(28, 23), // Dev10 doesn't say "must be invariantly valid" for ref params - it lists whichever check fails first. This approach seems nicer. // (34,27): error CS1961: Invalid variance: The type parameter 'TInputUnsafe' must be invariantly valid on 'IBothUnsafeTable<TInputUnsafe, TOutputUnsafe, TInvariant>.InputUnsafe1(ref ICovariant<TInputUnsafe>)'. 'TInputUnsafe' is covariant. // void InputUnsafe1(ref ICovariant<TInputUnsafe> p); Diagnostic(ErrorCode.ERR_UnexpectedVariance, "ICovariant<TInputUnsafe>").WithArguments("IBothUnsafeTable<TInputUnsafe, TOutputUnsafe, TInvariant>.InputUnsafe1(ref ICovariant<TInputUnsafe>)", "TInputUnsafe", "covariant", "invariantly").WithLocation(34, 27), // (35,27): error CS1961: Invalid variance: The type parameter 'TOutputUnsafe' must be invariantly valid on 'IBothUnsafeTable<TInputUnsafe, TOutputUnsafe, TInvariant>.InputUnsafe2(ref ICovariant<TOutputUnsafe>)'. 'TOutputUnsafe' is contravariant. // void InputUnsafe2(ref ICovariant<TOutputUnsafe> p); Diagnostic(ErrorCode.ERR_UnexpectedVariance, "ICovariant<TOutputUnsafe>").WithArguments("IBothUnsafeTable<TInputUnsafe, TOutputUnsafe, TInvariant>.InputUnsafe2(ref ICovariant<TOutputUnsafe>)", "TOutputUnsafe", "contravariant", "invariantly").WithLocation(35, 27), // (38,27): error CS1961: Invalid variance: The type parameter 'TInputUnsafe' must be invariantly valid on 'IBothUnsafeTable<TInputUnsafe, TOutputUnsafe, TInvariant>.InputUnsafe4(ref IContravariant<TInputUnsafe>)'. 'TInputUnsafe' is covariant. // void InputUnsafe4(ref IContravariant<TInputUnsafe> p); Diagnostic(ErrorCode.ERR_UnexpectedVariance, "IContravariant<TInputUnsafe>").WithArguments("IBothUnsafeTable<TInputUnsafe, TOutputUnsafe, TInvariant>.InputUnsafe4(ref IContravariant<TInputUnsafe>)", "TInputUnsafe", "covariant", "invariantly").WithLocation(38, 27), // (39,27): error CS1961: Invalid variance: The type parameter 'TOutputUnsafe' must be invariantly valid on 'IBothUnsafeTable<TInputUnsafe, TOutputUnsafe, TInvariant>.InputUnsafe5(ref IContravariant<TOutputUnsafe>)'. 'TOutputUnsafe' is contravariant. // void InputUnsafe5(ref IContravariant<TOutputUnsafe> p); Diagnostic(ErrorCode.ERR_UnexpectedVariance, "IContravariant<TOutputUnsafe>").WithArguments("IBothUnsafeTable<TInputUnsafe, TOutputUnsafe, TInvariant>.InputUnsafe5(ref IContravariant<TOutputUnsafe>)", "TOutputUnsafe", "contravariant", "invariantly").WithLocation(39, 27), // (42,27): error CS1961: Invalid variance: The type parameter 'TInputUnsafe' must be invariantly valid on 'IBothUnsafeTable<TInputUnsafe, TOutputUnsafe, TInvariant>.InputUnsafe7(ref IInvariant<TInputUnsafe>)'. 'TInputUnsafe' is covariant. // void InputUnsafe7(ref IInvariant<TInputUnsafe> p); Diagnostic(ErrorCode.ERR_UnexpectedVariance, "IInvariant<TInputUnsafe>").WithArguments("IBothUnsafeTable<TInputUnsafe, TOutputUnsafe, TInvariant>.InputUnsafe7(ref IInvariant<TInputUnsafe>)", "TInputUnsafe", "covariant", "invariantly").WithLocation(42, 27), // (43,27): error CS1961: Invalid variance: The type parameter 'TOutputUnsafe' must be invariantly valid on 'IBothUnsafeTable<TInputUnsafe, TOutputUnsafe, TInvariant>.InputUnsafe8(ref IInvariant<TOutputUnsafe>)'. 'TOutputUnsafe' is contravariant. // void InputUnsafe8(ref IInvariant<TOutputUnsafe> p); Diagnostic(ErrorCode.ERR_UnexpectedVariance, "IInvariant<TOutputUnsafe>").WithArguments("IBothUnsafeTable<TInputUnsafe, TOutputUnsafe, TInvariant>.InputUnsafe8(ref IInvariant<TOutputUnsafe>)", "TOutputUnsafe", "contravariant", "invariantly").WithLocation(43, 27)); } [Fact] public void CS1961ERR_UnexpectedVariance_DelegateInvoke() { var text = @" delegate TIn D1<in TIn>(); //CS1961 delegate TOut D2<out TOut>(); delegate T D3<T>(); delegate void D4<in TIn>(TIn p); delegate void D5<out TOut>(TOut p); //CS1961 delegate void D6<T>(T p); delegate void D7<in TIn>(ref TIn p); //CS1961 delegate void D8<out TOut>(ref TOut p); //CS1961 delegate void D9<T>(ref T p); delegate void D10<in TIn>(out TIn p); //CS1961 delegate void D11<out TOut>(out TOut p); //CS1961 delegate void D12<T>(out T p); "; CreateCompilation(text).VerifyDiagnostics( // (2,20): error CS1961: Invalid variance: The type parameter 'TIn' must be covariantly valid on 'D1<TIn>.Invoke()'. 'TIn' is contravariant. Diagnostic(ErrorCode.ERR_UnexpectedVariance, "TIn").WithArguments("D1<TIn>.Invoke()", "TIn", "contravariant", "covariantly"), // (7,22): error CS1961: Invalid variance: The type parameter 'TOut' must be contravariantly valid on 'D5<TOut>.Invoke(TOut)'. 'TOut' is covariant. Diagnostic(ErrorCode.ERR_UnexpectedVariance, "TOut").WithArguments("D5<TOut>.Invoke(TOut)", "TOut", "covariant", "contravariantly"), // (10,21): error CS1961: Invalid variance: The type parameter 'TIn' must be invariantly valid on 'D7<TIn>.Invoke(ref TIn)'. 'TIn' is contravariant. Diagnostic(ErrorCode.ERR_UnexpectedVariance, "TIn").WithArguments("D7<TIn>.Invoke(ref TIn)", "TIn", "contravariant", "invariantly"), // (11,22): error CS1961: Invalid variance: The type parameter 'TOut' must be invariantly valid on 'D8<TOut>.Invoke(ref TOut)'. 'TOut' is covariant. Diagnostic(ErrorCode.ERR_UnexpectedVariance, "TOut").WithArguments("D8<TOut>.Invoke(ref TOut)", "TOut", "covariant", "invariantly"), // (14,22): error CS1961: Invalid variance: The type parameter 'TIn' must be invariantly valid on 'D10<TIn>.Invoke(out TIn)'. 'TIn' is contravariant. Diagnostic(ErrorCode.ERR_UnexpectedVariance, "TIn").WithArguments("D10<TIn>.Invoke(out TIn)", "TIn", "contravariant", "invariantly"), // (15,23): error CS1961: Invalid variance: The type parameter 'TOut' must be invariantly valid on 'D11<TOut>.Invoke(out TOut)'. 'TOut' is covariant. Diagnostic(ErrorCode.ERR_UnexpectedVariance, "TOut").WithArguments("D11<TOut>.Invoke(out TOut)", "TOut", "covariant", "invariantly")); } [Fact] public void CS1962ERR_BadDynamicTypeof() { var text = @" public class C { public static int Main() { dynamic S = typeof(dynamic); return 0; } public static int Test(int age) { return 1; } }"; CreateCompilation(text).VerifyDiagnostics( // (6,25): error CS1962: The typeof operator cannot be used on the dynamic type Diagnostic(ErrorCode.ERR_BadDynamicTypeof, "typeof(dynamic)")); } // CS1963ERR_ExpressionTreeContainsDynamicOperation --> SyntaxBinderTests [Fact] public void CS1964ERR_BadDynamicConversion() { var text = @" class A { public static implicit operator dynamic(A a) { return a; } public static implicit operator A(dynamic a) { return a; } } "; CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics( // (9,37): error CS1964: 'A.implicit operator A(dynamic)': user-defined conversions to or from the dynamic type are not allowed Diagnostic(ErrorCode.ERR_BadDynamicConversion, "A").WithArguments("A.implicit operator A(dynamic)"), // (4,37): error CS1964: 'A.implicit operator dynamic(A)': user-defined conversions to or from the dynamic type are not allowed Diagnostic(ErrorCode.ERR_BadDynamicConversion, "dynamic").WithArguments("A.implicit operator dynamic(A)")); } // CS1969ERR_DynamicRequiredTypesMissing -> CodeGen_DynamicTests.Missing_* // CS1970ERR_ExplicitDynamicAttr --> AttributeTests_Dynamic.ExplicitDynamicAttribute [Fact] public void CS1971ERR_NoDynamicPhantomOnBase() { const string text = @" public class B { public virtual void M(object o) {} } public class D : B { public override void M(object o) {} void N(dynamic d) { base.M(d); } } "; var comp = CreateCompilationWithMscorlib40AndSystemCore(text); comp.VerifyDiagnostics( // (12,9): error CS1971: The call to method 'M' needs to be dynamically dispatched, but cannot be because it is part of a base access expression. Consider casting the dynamic arguments or eliminating the base access. // base.M(d); Diagnostic(ErrorCode.ERR_NoDynamicPhantomOnBase, "base.M(d)").WithArguments("M")); } [Fact] public void CS1972ERR_NoDynamicPhantomOnBaseIndexer() { const string text = @" public class B { public string this[int index] { get { return ""You passed "" + index; } } } public class D : B { public void M(object o) { int[] arr = { 1, 2, 3 }; int s = base[(dynamic)o]; } } "; var comp = CreateCompilationWithMscorlib40AndSystemCore(text); comp.VerifyDiagnostics( // (14,17): error CS1972: The indexer access needs to be dynamically dispatched, but cannot be because it is part of a base access expression. Consider casting the dynamic arguments or eliminating the base access. // int s = base[(dynamic)o]; Diagnostic(ErrorCode.ERR_NoDynamicPhantomOnBaseIndexer, "base[(dynamic)o]")); } [Fact] public void CS1973ERR_BadArgTypeDynamicExtension() { const string text = @" class Program { static void Main() { dynamic d = 1; B b = new B(); b.Goo(d); } } public class B { } static public class Extension { public static void Goo(this B b, int x) { } }"; var comp = CreateCompilationWithMscorlib40AndSystemCore(text); comp.VerifyDiagnostics( // (8,9): error CS1973: 'B' has no applicable method named 'Goo' but appears to have an extension method by that name. Extension methods cannot be dynamically dispatched. Consider casting the dynamic arguments or calling the extension method without the extension method syntax. // b.Goo(d); Diagnostic(ErrorCode.ERR_BadArgTypeDynamicExtension, "b.Goo(d)").WithArguments("B", "Goo")); } [Fact] public void CS1975ERR_NoDynamicPhantomOnBaseCtor_Base() { var text = @" class A { public A(int x) { } } class B : A { public B(dynamic d) : base(d) { } } "; CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics( // (12,9): error CS1975: The constructor call needs to be dynamically dispatched, but cannot be because it is part of a constructor initializer. Consider casting the dynamic arguments. Diagnostic(ErrorCode.ERR_NoDynamicPhantomOnBaseCtor, "base")); } [Fact] public void CS1975ERR_NoDynamicPhantomOnBaseCtor_This() { var text = @" class B { public B(dynamic d) : this(d, 1) { } public B(int a, int b) { } } "; CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics( // (12,9): error CS1975: The constructor call needs to be dynamically dispatched, but cannot be because it is part of a constructor initializer. Consider casting the dynamic arguments. Diagnostic(ErrorCode.ERR_NoDynamicPhantomOnBaseCtor, "this")); } [Fact] public void CS1976ERR_BadDynamicMethodArgMemgrp() { const string text = @" class Program { static void M(dynamic d) { d.Goo(M); } }"; var comp = CreateCompilationWithMscorlib40AndSystemCore(text); comp.VerifyDiagnostics( // (6,15): error CS1976: Cannot use a method group as an argument to a dynamically dispatched operation. Did you intend to invoke the method? // d.Goo(M); Diagnostic(ErrorCode.ERR_BadDynamicMethodArgMemgrp, "M")); } [Fact] public void CS1977ERR_BadDynamicMethodArgLambda() { const string text = @" class Program { static void M(dynamic d) { d.Goo(()=>{}); d.Goo(delegate () {}); } }"; var comp = CreateCompilationWithMscorlib40AndSystemCore(text); comp.VerifyDiagnostics( // (6,15): 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. // d.Goo(()=>{}); Diagnostic(ErrorCode.ERR_BadDynamicMethodArgLambda, "()=>{}"), // (7,15): 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. // d.Goo(delegate () {}); Diagnostic(ErrorCode.ERR_BadDynamicMethodArgLambda, "delegate () {}")); } [Fact, WorkItem(578352, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/578352")] public void CS1977ERR_BadDynamicMethodArgLambda_CreateObject() { string source = @" using System; class C { static void Main() { dynamic y = null; new C(delegate { }, y); } public C(Action a, Action y) { } }"; var comp = CreateCompilationWithMscorlib40AndSystemCore(source, new[] { CSharpRef }); comp.VerifyDiagnostics( // (9,15): 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, "delegate { }")); } [Fact] public void CS1660ERR_BadDynamicMethodArgLambda_CollectionInitializer() { string source = @" using System; using System.Collections; using System.Collections.Generic; unsafe class C : IEnumerable<object> { public static void M(__arglist) { int a; int* p = &a; dynamic d = null; var c = new C { { d, delegate() { } }, { d, 1, p }, { d, __arglist }, { d, GetEnumerator }, { d, SomeStaticMethod }, }; } public static void SomeStaticMethod() {} public void Add(dynamic d, int x, int* ptr) { } public void Add(dynamic d, RuntimeArgumentHandle x) { } public void Add(dynamic d, Action f) { } public void Add(dynamic d, Func<IEnumerator<object>> f) { } public IEnumerator<object> GetEnumerator() { return null; } IEnumerator IEnumerable.GetEnumerator() { return null; } }"; var comp = CreateCompilationWithMscorlib40AndSystemCore(source, new[] { CSharpRef }, options: TestOptions.UnsafeReleaseDll); comp.VerifyDiagnostics( // (16,18): 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. // { d, delegate() { } }, Diagnostic(ErrorCode.ERR_BadDynamicMethodArgLambda, "delegate() { }").WithLocation(16, 18), // (17,21): error CS1978: Cannot use an expression of type 'int*' as an argument to a dynamically dispatched operation. // { d, 1, p }, Diagnostic(ErrorCode.ERR_BadDynamicMethodArg, "p").WithArguments("int*").WithLocation(17, 21), // (18,18): error CS1978: Cannot use an expression of type 'RuntimeArgumentHandle' as an argument to a dynamically dispatched operation. // { d, __arglist }, Diagnostic(ErrorCode.ERR_BadDynamicMethodArg, "__arglist").WithArguments("System.RuntimeArgumentHandle").WithLocation(18, 18), // (19,13): error CS1950: The best overloaded Add method 'C.Add(dynamic, RuntimeArgumentHandle)' for the collection initializer has some invalid arguments // { d, GetEnumerator }, Diagnostic(ErrorCode.ERR_BadArgTypesForCollectionAdd, "{ d, GetEnumerator }").WithArguments("C.Add(dynamic, System.RuntimeArgumentHandle)").WithLocation(19, 13), // (19,18): error CS1503: Argument 2: cannot convert from 'method group' to 'RuntimeArgumentHandle' // { d, GetEnumerator }, Diagnostic(ErrorCode.ERR_BadArgType, "GetEnumerator").WithArguments("2", "method group", "System.RuntimeArgumentHandle").WithLocation(19, 18), // (20,18): error CS1976: Cannot use a method group as an argument to a dynamically dispatched operation. Did you intend to invoke the method? // { d, SomeStaticMethod }, Diagnostic(ErrorCode.ERR_BadDynamicMethodArgMemgrp, "SomeStaticMethod").WithLocation(20, 18)); } [Fact] public void CS1978ERR_BadDynamicMethodArg() { // The dev 10 compiler gives arguably wrong error here; it says that "TypedReference may not be // used as a type argument". Though that is true, and though what is happening here behind the scenes // is that TypedReference is being used as a type argument to a dynamic call site helper method, // that's giving an error about an implementation detail. A better error is to say that // TypedReference is not a legal type in a dynamic operation. // // Dev10 compiler didn't report an error for by-ref pointer argument. See Dev10 bug 819498. // The error should be reported for any pointer argument regardless of its refness. const string text = @" class Program { unsafe static void M(dynamic d, int* i, System.TypedReference tr) { d.Goo(i); d.Goo(tr); d.Goo(ref tr); d.Goo(out tr); d.Goo(out i); d.Goo(ref i); } } "; var comp = CreateCompilationWithMscorlib40AndSystemCore(text, options: TestOptions.UnsafeReleaseDll); comp.VerifyDiagnostics( // (6,15): error CS1978: Cannot use an expression of type 'int*' as an argument to a dynamically dispatched operation. Diagnostic(ErrorCode.ERR_BadDynamicMethodArg, "i").WithArguments("int*"), // (7,15): error CS1978: Cannot use an expression of type 'System.TypedReference' as an argument to a dynamically dispatched operation. Diagnostic(ErrorCode.ERR_BadDynamicMethodArg, "tr").WithArguments("System.TypedReference"), // (8,19): error CS1978: Cannot use an expression of type 'System.TypedReference' as an argument to a dynamically dispatched operation. Diagnostic(ErrorCode.ERR_BadDynamicMethodArg, "tr").WithArguments("System.TypedReference"), // (9,19): error CS1978: Cannot use an expression of type 'System.TypedReference' as an argument to a dynamically dispatched operation. Diagnostic(ErrorCode.ERR_BadDynamicMethodArg, "tr").WithArguments("System.TypedReference"), // (10,19): error CS1978: Cannot use an expression of type 'int*' as an argument to a dynamically dispatched operation. Diagnostic(ErrorCode.ERR_BadDynamicMethodArg, "i").WithArguments("int*"), // (11,19): error CS1978: Cannot use an expression of type 'int*' as an argument to a dynamically dispatched operation. Diagnostic(ErrorCode.ERR_BadDynamicMethodArg, "i").WithArguments("int*")); } // CS1979ERR_BadDynamicQuery --> DynamicTests.cs, DynamicQuery_* // Test CS1980ERR_DynamicAttributeMissing moved to AttributeTests_Dynamic.cs // CS1763 is covered for different code path by SymbolErrorTests.CS1763ERR_NotNullRefDefaultParameter() [WorkItem(528854, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528854")] [Fact] public void CS1763ERR_NotNullRefDefaultParameter02() { string text = @" class Program { public void Goo<T, U>(T t = default(U)) where U : T { } static void Main(string[] args) { } }"; CreateCompilation(text).VerifyDiagnostics( // (4,29): error CS1763: 't' is of type 'T'. A default parameter value of a reference type other than string can only be initialized with null // public void Goo<T, U>(T t = default(U)) where U : T Diagnostic(ErrorCode.ERR_NotNullRefDefaultParameter, "t").WithArguments("t", "T")); } #endregion #region "Targeted Warning Tests - please arrange tests in the order of error code" [Fact, WorkItem(542396, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542396"), WorkItem(546817, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546817")] public void CS0067WRN_UnreferencedEvent() { var text = @" delegate void MyDelegate(); class MyClass { public event MyDelegate evt; // CS0067 public static void Main() { } } "; CreateCompilation(text).VerifyDiagnostics( // (5,29): warning CS0067: The event 'MyClass.evt' is never used // public event MyDelegate evt; // CS0067 Diagnostic(ErrorCode.WRN_UnreferencedEvent, "evt").WithArguments("MyClass.evt")); } [Fact, WorkItem(542396, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542396"), WorkItem(546817, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546817")] public void CS0067WRN_UnreferencedEvent_Accessibility() { var text = @" using System; class MyClass { public event Action E1; // CS0067 internal event Action E2; // CS0067 protected internal event Action E3; // CS0067 protected event Action E4; // CS0067 private event Action E5; // CS0067 } "; CreateCompilation(text).VerifyDiagnostics( // (5,25): warning CS0067: The event 'MyClass.E1' is never used // public event Action E1; // CS0067 Diagnostic(ErrorCode.WRN_UnreferencedEvent, "E1").WithArguments("MyClass.E1"), // (6,27): warning CS0067: The event 'MyClass.E2' is never used // internal event Action E2; // CS0067 Diagnostic(ErrorCode.WRN_UnreferencedEvent, "E2").WithArguments("MyClass.E2"), // (7,37): warning CS0067: The event 'MyClass.E3' is never used // protected internal event Action E3; // CS0067 Diagnostic(ErrorCode.WRN_UnreferencedEvent, "E3").WithArguments("MyClass.E3"), // (8,28): warning CS0067: The event 'MyClass.E4' is never used // protected event Action E4; // CS0067 Diagnostic(ErrorCode.WRN_UnreferencedEvent, "E4").WithArguments("MyClass.E4"), // (9,26): warning CS0067: The event 'MyClass.E5' is never used // private event Action E5; // CS0067 Diagnostic(ErrorCode.WRN_UnreferencedEvent, "E5").WithArguments("MyClass.E5")); } [Fact, WorkItem(542396, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542396"), WorkItem(546817, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546817")] public void CS0067WRN_UnreferencedEvent_StructLayout() { var text = @" using System; using System.Runtime.InteropServices; [StructLayout(LayoutKind.Sequential)] struct S { event Action E1; } "; CreateCompilation(text).VerifyDiagnostics(); } [Fact, WorkItem(542396, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542396"), WorkItem(546817, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546817")] public void CS0067WRN_UnreferencedEvent_Kind() { var text = @" using System; class C { event Action E1; // CS0067 event Action E2 { add { } remove { } } } "; CreateCompilation(text).VerifyDiagnostics( // (6,18): warning CS0067: The event 'C.E1' is never used // event Action E1; // CS0067 Diagnostic(ErrorCode.WRN_UnreferencedEvent, "E1").WithArguments("C.E1")); } [Fact, WorkItem(542396, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542396"), WorkItem(546817, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546817")] public void CS0067WRN_UnreferencedEvent_Accessed() { var text = @" using System; class C { event Action None; // CS0067 event Action Read; event Action Write; event Action Add; // CS0067 void M(Action a) { M(Read); Write = a; Add += a; } } "; CreateCompilation(text).VerifyDiagnostics( // (9,18): warning CS0067: The event 'C.Add' is never used // event Action Add; // CS0067 Diagnostic(ErrorCode.WRN_UnreferencedEvent, "Add").WithArguments("C.Add"), // (6,18): warning CS0067: The event 'C.None' is never used // event Action None; // CS0067 Diagnostic(ErrorCode.WRN_UnreferencedEvent, "None").WithArguments("C.None")); } [Fact, WorkItem(581002, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/581002")] public void CS0067WRN_UnreferencedEvent_Virtual() { var text = @"class A { public virtual event System.EventHandler B; class C : A { public override event System.EventHandler B; } static int Main() { C c = new C(); A a = c; return 0; } } "; CreateCompilation(text).VerifyDiagnostics( // (3,46): warning CS0067: The event 'A.B' is never used // public virtual event System.EventHandler B; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "B").WithArguments("A.B"), // (6,51): warning CS0067: The event 'A.C.B' is never used // public override event System.EventHandler B; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "B").WithArguments("A.C.B")); } [Fact, WorkItem(539630, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539630")] public void CS0162WRN_UnreachableCode01() { var text = @" class MyTest { } class MyClass { const MyTest test = null; public static int Main() { goto lab1; { // The following statements cannot be reached: int i = 9; // CS0162 i++; } lab1: if (test == null) { return 0; } else { return 1; // CS0162 } } } "; CreateCompilation(text).VerifyDiagnostics( Diagnostic(ErrorCode.WRN_UnreachableCode, "int"), Diagnostic(ErrorCode.WRN_UnreachableCode, "return")); } [Fact, WorkItem(530037, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530037")] public void CS0162WRN_UnreachableCode02() { var text = @" using System; public class Test { public static void Main(string[] args) { // (1) do { for (; ; ) { } } while (args.Length > 0); // Native CS0162 // (2) for (; ; ) // Roslyn CS0162 { goto L2; Console.WriteLine(""Unreachable code""); L2: // Roslyn CS0162 break; } } } "; CreateCompilation(text).VerifyDiagnostics( // (14,5): warning CS0162: Unreachable code detected // for (; ; ) // Roslyn CS0162 Diagnostic(ErrorCode.WRN_UnreachableCode, "for"), // (18,5): warning CS0162: Unreachable code detected // L2: // Roslyn CS0162 Diagnostic(ErrorCode.WRN_UnreachableCode, "L2") ); } [Fact, WorkItem(539873, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539873"), WorkItem(539981, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539981")] public void CS0162WRN_UnreachableCode04() { var text = @" public class Cls { public static int Main() { goto Label2; return 0; Label1: return 1; Label2: goto Label1; return 2; } delegate void Sub_0(); static void M() { Sub_0 s1_3 = () => { if (2 == 1) return; else return; }; } }"; CreateCompilation(text).VerifyDiagnostics( Diagnostic(ErrorCode.WRN_UnreachableCode, "return"), Diagnostic(ErrorCode.WRN_UnreachableCode, "return"), Diagnostic(ErrorCode.WRN_UnreachableCode, "return")); } [Fact, WorkItem(540901, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540901")] public void CS0162WRN_UnreachableCode06_Loops() { var text = @" class Program { void F() { } void T() { for (int i = 0; i < 0; F(), i++) // F() is unreachable { return; } } static void Main() { string[] S = new string[] { ""ABC"", ""XYZ"" }; foreach (string x in S) { foreach (char y in x) { goto stop; System.Console.WriteLine(y); // unreachable } foreach (char y in x) { throw new System.Exception(); System.Console.WriteLine(y); // unreachable } stop: return; } } } "; CreateCompilation(text).VerifyDiagnostics( Diagnostic(ErrorCode.WRN_UnreachableCode, "F"), Diagnostic(ErrorCode.WRN_UnreachableCode, "System"), Diagnostic(ErrorCode.WRN_UnreachableCode, "System")); } [Fact] public void CS0162WRN_UnreachableCode06_Foreach03() { var text = @" public class Test { static public void Main(string[] args) { string[] S = new string[] { ""ABC"", ""XYZ"" }; foreach (string x in S) { foreach (char y in x) { return; System.Console.WriteLine(y); } } } } "; CreateCompilation(text). VerifyDiagnostics(Diagnostic(ErrorCode.WRN_UnreachableCode, "System")); } [Fact] public void CS0162WRN_UnreachableCode07_GotoInLambda() { var text = @" using System; class Program { static void Main() { Action a = () => { goto label1; Console.WriteLine(""unreachable""); label1: Console.WriteLine(""reachable""); }; } } "; CreateCompilation(text). VerifyDiagnostics(Diagnostic(ErrorCode.WRN_UnreachableCode, @"Console")); } [Fact] public void CS0164WRN_UnreferencedLabel() { var text = @" public class a { public int i = 0; public static void Main() { int i = 0; // CS0164 l1: i++; } }"; CreateCompilation(text).VerifyDiagnostics( Diagnostic(ErrorCode.WRN_UnreferencedLabel, "l1").WithLocation(9, 7)); } [Fact] public void CS0168WRN_UnreferencedVar01() { var text = @" public class clx { public int i; } public class clz { public static void Main() { int j ; // CS0168, uncomment the following line // j++; clx a; // CS0168, try the following line instead // clx a = new clx(); } }"; CreateCompilation(text).VerifyDiagnostics( Diagnostic(ErrorCode.WRN_UnreferencedVar, "j").WithArguments("j").WithLocation(11, 13), Diagnostic(ErrorCode.WRN_UnreferencedVar, "a").WithArguments("a").WithLocation(13, 13)); } [Fact] public void CS0168WRN_UnreferencedVar02() { var text = @"using System; class C { static void M() { try { } catch (InvalidOperationException e) { } catch (InvalidCastException e) { throw; } catch (Exception e) { throw e; } } }"; CreateCompilation(text).VerifyDiagnostics( Diagnostic(ErrorCode.WRN_UnreferencedVar, "e").WithArguments("e").WithLocation(7, 42), Diagnostic(ErrorCode.WRN_UnreferencedVar, "e").WithArguments("e").WithLocation(8, 37)); } [Fact] public void CS0169WRN_UnreferencedField() { var text = @" public class ClassX { int i; // CS0169, i is not used anywhere public static void Main() { } }"; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (4,8): warning CS0169: The field 'ClassX.i' is never used // int i; // CS0169, i is not used anywhere Diagnostic(ErrorCode.WRN_UnreferencedField, "i").WithArguments("ClassX.i") ); } [Fact] public void CS0169WRN_UnreferencedField02() { var text = @"[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""OtherAssembly"")] internal class InternalClass { internal int ActuallyInternal; internal int ActuallyInternalAssigned = 0; private int ActuallyPrivate; private int ActuallyPrivateAssigned = 0; public int EffectivelyInternal; public int EffectivelyInternalAssigned = 0; private class PrivateClass { public int EffectivelyPrivate; public int EffectivelyPrivateAssigned = 0; } }"; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (7,17): warning CS0169: The field 'InternalClass.ActuallyPrivate' is never used // private int ActuallyPrivate; Diagnostic(ErrorCode.WRN_UnreferencedField, "ActuallyPrivate").WithArguments("InternalClass.ActuallyPrivate"), // (8,17): warning CS0414: The field 'InternalClass.ActuallyPrivateAssigned' is assigned but its value is never used // private int ActuallyPrivateAssigned = 0; Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "ActuallyPrivateAssigned").WithArguments("InternalClass.ActuallyPrivateAssigned"), // (14,20): warning CS0649: Field 'InternalClass.PrivateClass.EffectivelyPrivate' is never assigned to, and will always have its default value 0 // public int EffectivelyPrivate; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "EffectivelyPrivate").WithArguments("InternalClass.PrivateClass.EffectivelyPrivate", "0") ); } [Fact] public void CS0169WRN_UnreferencedField03() { var text = @"internal class InternalClass { internal int ActuallyInternal; internal int ActuallyInternalAssigned = 0; private int ActuallyPrivate; private int ActuallyPrivateAssigned = 0; public int EffectivelyInternal; public int EffectivelyInternalAssigned = 0; private class PrivateClass { public int EffectivelyPrivate; public int EffectivelyPrivateAssigned = 0; } }"; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (3,18): warning CS0649: Field 'InternalClass.ActuallyInternal' is never assigned to, and will always have its default value 0 // internal int ActuallyInternal; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "ActuallyInternal").WithArguments("InternalClass.ActuallyInternal", "0"), // (5,17): warning CS0169: The field 'InternalClass.ActuallyPrivate' is never used // private int ActuallyPrivate; Diagnostic(ErrorCode.WRN_UnreferencedField, "ActuallyPrivate").WithArguments("InternalClass.ActuallyPrivate"), // (6,17): warning CS0414: The field 'InternalClass.ActuallyPrivateAssigned' is assigned but its value is never used // private int ActuallyPrivateAssigned = 0; Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "ActuallyPrivateAssigned").WithArguments("InternalClass.ActuallyPrivateAssigned"), // (7,16): warning CS0649: Field 'InternalClass.EffectivelyInternal' is never assigned to, and will always have its default value 0 // public int EffectivelyInternal; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "EffectivelyInternal").WithArguments("InternalClass.EffectivelyInternal", "0"), // (12,20): warning CS0649: Field 'InternalClass.PrivateClass.EffectivelyPrivate' is never assigned to, and will always have its default value 0 // public int EffectivelyPrivate; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "EffectivelyPrivate").WithArguments("InternalClass.PrivateClass.EffectivelyPrivate", "0") ); } [Fact] public void CS0183WRN_IsAlwaysTrue() { var text = @"using System; public class IsTest10 { public static int Main(String[] args) { Object obj3 = null; String str2 = ""Is 'is' too strict, per error CS0183?""; obj3 = str2; if (str2 is Object) // no error CS0183 Console.WriteLine(""str2 is Object""); Int32 int2 = 1; if (int2 is Object) // error CS0183 Console.WriteLine(""int2 is Object""); return 0; } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.WRN_IsAlwaysTrue, Line = 14, Column = 13, IsWarning = true }); // TODO: extra checking } // Note: CS0184 tests moved to CodeGenOperator.cs to include IL verification. [WorkItem(530361, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530361")] [Fact] public void CS0197WRN_ByRefNonAgileField() { var text = @" class X : System.MarshalByRefObject { public int i; } class M { public int i; static void AddSeventeen(ref int i) { i += 17; } static void Main() { X x = new X(); x.i = 12; AddSeventeen(ref x.i); // CS0197 // OK M m = new M(); m.i = 12; AddSeventeen(ref m.i); } } "; CreateCompilation(text).VerifyDiagnostics( // (19,24): warning CS0197: Passing 'X.i' as ref or out or taking its address may cause a runtime exception because it is a field of a marshal-by-reference class // AddSeventeen(ref x.i); // CS0197 Diagnostic(ErrorCode.WRN_ByRefNonAgileField, "x.i").WithArguments("X.i")); } [WorkItem(530361, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530361")] [Fact] public void CS0197WRN_ByRefNonAgileField_RefKind() { var text = @" class NotByRef { public int Instance; public static int Static; } class ByRef : System.MarshalByRefObject { public int Instance; public static int Static; } class Test { void M(ByRef b, NotByRef n) { None(n.Instance); Out(out n.Instance); Ref(ref n.Instance); None(NotByRef.Static); Out(out NotByRef.Static); Ref(ref NotByRef.Static); None(b.Instance); Out(out b.Instance); Ref(ref b.Instance); None(ByRef.Static); Out(out ByRef.Static); Ref(ref ByRef.Static); } void None(int x) { throw null; } void Out(out int x) { throw null; } void Ref(ref int x) { throw null; } } "; CreateCompilation(text).VerifyDiagnostics( // (27,17): warning CS0197: Passing 'ByRef.Instance' as ref or out or taking its address may cause a runtime exception because it is a field of a marshal-by-reference class // Out(out b.Instance); Diagnostic(ErrorCode.WRN_ByRefNonAgileField, "b.Instance").WithArguments("ByRef.Instance"), // (28,17): warning CS0197: Passing 'ByRef.Instance' as ref or out or taking its address may cause a runtime exception because it is a field of a marshal-by-reference class // Ref(ref b.Instance); Diagnostic(ErrorCode.WRN_ByRefNonAgileField, "b.Instance").WithArguments("ByRef.Instance")); } [WorkItem(530361, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530361")] [Fact] public void CS0197WRN_ByRefNonAgileField_Receiver() { var text = @" using System; class ByRef : MarshalByRefObject { public int F; protected void Ref(ref int x) { } void Test() { Ref(ref F); Ref(ref this.F); Ref(ref ((ByRef)this).F); } } class Derived : ByRef { void Test() { Ref(ref F); Ref(ref this.F); Ref(ref ((ByRef)this).F); Ref(ref base.F); //Ref(ref ((ByRef)base).F); } } "; CreateCompilation(text).VerifyDiagnostics( // (15,17): warning CS0197: Passing 'ByRef.F' as ref or out or taking its address may cause a runtime exception because it is a field of a marshal-by-reference class // Ref(ref ((ByRef)this).F); Diagnostic(ErrorCode.WRN_ByRefNonAgileField, "((ByRef)this).F").WithArguments("ByRef.F"), // (26,17): warning CS0197: Passing 'ByRef.F' as ref or out or taking its address may cause a runtime exception because it is a field of a marshal-by-reference class // Ref(ref ((ByRef)this).F); Diagnostic(ErrorCode.WRN_ByRefNonAgileField, "((ByRef)this).F").WithArguments("ByRef.F")); } [Fact] public void CS0219WRN_UnreferencedVarAssg01() { var text = @"public class MyClass { public static void Main() { int a = 0; // CS0219 } }"; CreateCompilation(text).VerifyDiagnostics( // (5,13): warning CS0219: The variable 'a' is assigned but its value is never used // int a = 0; // CS0219 Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "a").WithArguments("a") ); } [Fact] public void CS0219WRN_UnreferencedVarAssg02() { var text = @" public class clx { static void Main(string[] args) { int x = 1; } }"; CreateCompilation(text).VerifyDiagnostics( Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x").WithArguments("x").WithLocation(6, 13)); } [Fact] public void CS0219WRN_UnreferencedVarAssg03() { var text = @" public class clx { static void Main(string[] args) { int? x; x = null; } }"; CreateCompilation(text).VerifyDiagnostics( Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x").WithArguments("x").WithLocation(6, 14)); } [Fact, WorkItem(542473, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542473"), WorkItem(542474, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542474")] public void CS0219WRN_UnreferencedVarAssg_StructString() { var text = @" class program { static void Main(string[] args) { s1 y = new s1(); string s = """"; } } struct s1 { } "; CreateCompilation(text).VerifyDiagnostics( // (6,12): warning CS0219: The variable 'y' is assigned but its value is never used // s1 y = new s1(); Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y").WithArguments("y").WithLocation(6, 12), Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "s").WithArguments("s").WithLocation(7, 16) ); } [Fact, WorkItem(542494, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542494")] public void CS0219WRN_UnreferencedVarAssg_Default() { var text = @" class S { public int x = 5; } class C { public static void Main() { var x = default(S); } }"; CreateCompilation(text).VerifyDiagnostics( // (11,13): warning CS0219: The variable 'x' is assigned but its value is never used // var x = default(S); Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x").WithArguments("x").WithLocation(11, 13) ); } [Fact] public void CS0219WRN_UnreferencedVarAssg_For() { var text = @" class C { public static void Main() { for (int i = 1; ; ) { break; } } }"; CreateCompilation(text).VerifyDiagnostics( // (6,18): warning CS0219: The variable 'i' is assigned but its value is never used Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "i").WithArguments("i").WithLocation(6, 18) ); } [Fact, WorkItem(546619, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546619")] public void NoCS0219WRN_UnreferencedVarAssg_ObjectInitializer() { var text = @" struct S { public int X { set {} } } class C { public static void Main() { S s = new S { X = 2 }; // no error - not a constant int? i = new int? { }; // ditto - not the default value (though bitwise equal to it) } }"; CreateCompilation(text).VerifyDiagnostics(); } [Fact, WorkItem(542472, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542472")] public void CS0251WRN_NegativeArrayIndex() { var text = @" class C { static void Main() { int[] a = new int[1]; int[,] b = new int[1, 1]; a[-1] = 1; // CS0251 a[-1, -1] = 1; // Dev10 reports CS0022 and CS0251 (twice), Roslyn reports CS0022 b[-1] = 1; // CS0022 b[-1, -1] = 1; // fine } } "; CreateCompilation(text).VerifyDiagnostics( // (8,11): warning CS0251: Indexing an array with a negative index (array indices always start at zero) Diagnostic(ErrorCode.WRN_NegativeArrayIndex, "-1"), // (9,9): error CS0022: Wrong number of indices inside []; expected '1' Diagnostic(ErrorCode.ERR_BadIndexCount, "a[-1, -1]").WithArguments("1"), // (10,9): error CS0022: Wrong number of indices inside []; expected '2' Diagnostic(ErrorCode.ERR_BadIndexCount, "b[-1]").WithArguments("2")); } [WorkItem(530362, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530362"), WorkItem(670322, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/670322")] [Fact] public void CS0252WRN_BadRefCompareLeft() { var text = @"class MyClass { public static void Main() { string s = ""11""; object o = s + s; bool b = o == s; // CS0252 } }"; CreateCompilation(text).VerifyDiagnostics( // (8,16): warning CS0252: Possible unintended reference comparison; to get a value comparison, cast the left hand side to type 'string' // bool b = o == s; // CS0252 Diagnostic(ErrorCode.WRN_BadRefCompareLeft, "o == s").WithArguments("string") ); } [WorkItem(781070, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/781070")] [Fact] public void CS0252WRN_BadRefCompareLeft_02() { var text = @"using System; public class Symbol { public static bool operator ==(Symbol a, Symbol b) { return ReferenceEquals(a, null) || ReferenceEquals(b, null) || ReferenceEquals(a, b); } public static bool operator !=(Symbol a, Symbol b) { return !(a == b); } public override bool Equals(object obj) { return (obj is Symbol || obj == null) ? this == (Symbol)obj : false; } public override int GetHashCode() { return 0; } } public class MethodSymbol : Symbol { } class Program { static void Main(string[] args) { MethodSymbol a1 = null; MethodSymbol a2 = new MethodSymbol(); // In these cases the programmer explicitly inserted a cast to use object equality instead // of the user-defined equality operator. Since the programmer did this explicitly, in // Roslyn we suppress the diagnostic that was given by the native compiler suggesting casting // the object-typed operand back to type Symbol to get value equality. Console.WriteLine((object)a1 == a2); Console.WriteLine((object)a1 != a2); Console.WriteLine((object)a2 == a1); Console.WriteLine((object)a2 != a1); Console.WriteLine(a1 == (object)a2); Console.WriteLine(a1 != (object)a2); Console.WriteLine(a2 == (object)a1); Console.WriteLine(a2 != (object)a1); } }"; CreateCompilation(text).VerifyDiagnostics(); } [WorkItem(781070, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/781070")] [Fact] public void CS0252WRN_BadRefCompareLeft_03() { var text = @"using System; public class Symbol { public static bool operator ==(Symbol a, Symbol b) { return ReferenceEquals(a, null) || ReferenceEquals(b, null) || ReferenceEquals(a, b); } public static bool operator !=(Symbol a, Symbol b) { return !(a == b); } public override bool Equals(object obj) { return (obj is Symbol || obj == null) ? this == (Symbol)obj : false; } public override int GetHashCode() { return 0; } } public class MethodSymbol : Symbol { } class Program { static void Main(string[] args) { Object a1 = null; MethodSymbol a2 = new MethodSymbol(); Console.WriteLine(a1 == a2); Console.WriteLine(a1 != a2); Console.WriteLine(a2 == a1); Console.WriteLine(a2 != a1); } }"; CreateCompilation(text).VerifyDiagnostics( // (34,27): warning CS0252: Possible unintended reference comparison; to get a value comparison, cast the left hand side to type 'Symbol' // Console.WriteLine(a1 == a2); Diagnostic(ErrorCode.WRN_BadRefCompareLeft, "a1 == a2").WithArguments("Symbol"), // (35,27): warning CS0252: Possible unintended reference comparison; to get a value comparison, cast the left hand side to type 'Symbol' // Console.WriteLine(a1 != a2); Diagnostic(ErrorCode.WRN_BadRefCompareLeft, "a1 != a2").WithArguments("Symbol"), // (36,27): warning CS0253: Possible unintended reference comparison; to get a value comparison, cast the right hand side to type 'Symbol' // Console.WriteLine(a2 == a1); Diagnostic(ErrorCode.WRN_BadRefCompareRight, "a2 == a1").WithArguments("Symbol"), // (37,27): warning CS0253: Possible unintended reference comparison; to get a value comparison, cast the right hand side to type 'Symbol' // Console.WriteLine(a2 != a1); Diagnostic(ErrorCode.WRN_BadRefCompareRight, "a2 != a1").WithArguments("Symbol") ); } [WorkItem(530362, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530362"), WorkItem(670322, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/670322")] [Fact] public void CS0253WRN_BadRefCompareRight() { var text = @" class MyClass { public static void Main() { string s = ""11""; object o = s + s; bool c = s == o; // CS0253 // try the following line instead // bool c = s == (string)o; } }"; CreateCompilation(text).VerifyDiagnostics( // (9,16): warning CS0253: Possible unintended reference comparison; to get a value comparison, cast the right hand side to type 'string' // bool c = s == o; // CS0253 Diagnostic(ErrorCode.WRN_BadRefCompareRight, "s == o").WithArguments("string") ); } [WorkItem(730177, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/730177")] [Fact] public void CS0253WRN_BadRefCompare_None() { var text = @"using System; class MyClass { public static void Main() { MulticastDelegate x1 = null; bool b1 = x1 == null; bool b2 = x1 != null; bool b3 = null == x1; bool b4 = null != x1; } }"; CreateCompilation(text).VerifyDiagnostics(); } [WorkItem(542399, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542399")] [Fact] public void CS0278WRN_PatternIsAmbiguous01() { var text = @" using System.Collections.Generic; public class myTest { public static void TestForeach<W>(W w) where W: IEnumerable<int>, IEnumerable<string> { foreach (int i in w) {} // CS0278 } } "; CreateCompilation(text).VerifyDiagnostics( // (8,25): warning CS0278: 'W' does not implement the 'collection' pattern. 'System.Collections.Generic.IEnumerable<int>.GetEnumerator()' is ambiguous with 'System.Collections.Generic.IEnumerable<string>.GetEnumerator()'. // foreach (int i in w) {} // CS0278 Diagnostic(ErrorCode.WRN_PatternIsAmbiguous, "w").WithArguments("W", "collection", "System.Collections.Generic.IEnumerable<int>.GetEnumerator()", "System.Collections.Generic.IEnumerable<string>.GetEnumerator()"), // (8,25): error CS1640: foreach statement cannot operate on variables of type 'W' because it implements multiple instantiations of 'System.Collections.Generic.IEnumerable<T>'; try casting to a specific interface instantiation // foreach (int i in w) {} // CS0278 Diagnostic(ErrorCode.ERR_MultipleIEnumOfT, "w").WithArguments("W", "System.Collections.Generic.IEnumerable<T>")); } [Fact] public void CS0278WRN_PatternIsAmbiguous02() { var text = @"using System.Collections; using System.Collections.Generic; class A : IEnumerable<A> { public IEnumerator<A> GetEnumerator() { return null; } IEnumerator IEnumerable.GetEnumerator() { return null; } } class B : IEnumerable<B> { IEnumerator<B> IEnumerable<B>.GetEnumerator() { return null; } IEnumerator IEnumerable.GetEnumerator() { return null; } } class C : IEnumerable<C>, IEnumerable<string> { public IEnumerator<C> GetEnumerator() { return null; } IEnumerator<string> IEnumerable<string>.GetEnumerator() { return null; } IEnumerator IEnumerable.GetEnumerator() { return null; } } class D : IEnumerable<D>, IEnumerable<string> { IEnumerator<D> IEnumerable<D>.GetEnumerator() { return null; } IEnumerator<string> IEnumerable<string>.GetEnumerator() { return null; } IEnumerator IEnumerable.GetEnumerator() { return null; } } class E { static void M<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10>(T1 t1, T2 t2, T3 t3, T4 t4, T5 t5, T6 t6, T7 t7, T8 t8, T9 t9, T10 t10) where T1 : A, IEnumerable<A> // duplicate interfaces where T2 : B, IEnumerable<B> // duplicate interfaces where T3 : A, IEnumerable<string>, IEnumerable<int> // multiple interfaces where T4 : B, IEnumerable<string>, IEnumerable<int> // multiple interfaces where T5 : C, IEnumerable<int> // multiple interfaces where T6 : D, IEnumerable<int> // multiple interfaces where T7 : A, IEnumerable<string>, IEnumerable<A> // duplicate and multiple interfaces where T8 : B, IEnumerable<string>, IEnumerable<B> // duplicate and multiple interfaces where T9 : C, IEnumerable<C> // duplicate and multiple interfaces where T10 : D, IEnumerable<D> // duplicate and multiple interfaces { foreach (A o in t1) { } foreach (B o in t2) { } foreach (A o in t3) { } foreach (var o in t4) { } foreach (C o in t5) { } foreach (int o in t6) { } foreach (A o in t7) { } foreach (var o in t8) { } foreach (C o in t9) { } foreach (D o in t10) { } } }"; CreateCompilation(text).VerifyDiagnostics( // (42,27): warning CS0278: 'T4' does not implement the 'collection' pattern. 'System.Collections.Generic.IEnumerable<string>.GetEnumerator()' is ambiguous with 'System.Collections.Generic.IEnumerable<int>.GetEnumerator()'. Diagnostic(ErrorCode.WRN_PatternIsAmbiguous, "t4").WithArguments("T4", "collection", "System.Collections.Generic.IEnumerable<string>.GetEnumerator()", "System.Collections.Generic.IEnumerable<int>.GetEnumerator()").WithLocation(42, 27), // (42,27): error CS1640: foreach statement cannot operate on variables of type 'T4' because it implements multiple instantiations of 'System.Collections.Generic.IEnumerable<T>'; try casting to a specific interface instantiation Diagnostic(ErrorCode.ERR_MultipleIEnumOfT, "t4").WithArguments("T4", "System.Collections.Generic.IEnumerable<T>").WithLocation(42, 27), // (46,27): warning CS0278: 'T8' does not implement the 'collection' pattern. 'System.Collections.Generic.IEnumerable<string>.GetEnumerator()' is ambiguous with 'System.Collections.Generic.IEnumerable<B>.GetEnumerator()'. Diagnostic(ErrorCode.WRN_PatternIsAmbiguous, "t8").WithArguments("T8", "collection", "System.Collections.Generic.IEnumerable<string>.GetEnumerator()", "System.Collections.Generic.IEnumerable<B>.GetEnumerator()").WithLocation(46, 27), // (46,27): error CS1640: foreach statement cannot operate on variables of type 'T8' because it implements multiple instantiations of 'System.Collections.Generic.IEnumerable<T>'; try casting to a specific interface instantiation Diagnostic(ErrorCode.ERR_MultipleIEnumOfT, "t8").WithArguments("T8", "System.Collections.Generic.IEnumerable<T>").WithLocation(46, 27)); } [Fact] public void CS0279WRN_PatternStaticOrInaccessible() { var text = @" using System.Collections; public class myTest : IEnumerable { IEnumerator IEnumerable.GetEnumerator() { return null; } internal IEnumerator GetEnumerator() { return null; } public static void Main() { foreach (int i in new myTest()) {} // CS0279 } } "; CreateCompilation(text).VerifyDiagnostics( // (18,27): warning CS0279: 'myTest' does not implement the 'collection' pattern. 'myTest.GetEnumerator()' is not a public instance or extension method. Diagnostic(ErrorCode.WRN_PatternNotPublicOrNotInstance, "new myTest()").WithArguments("myTest", "collection", "myTest.GetEnumerator()")); } [Fact] public void CS0280WRN_PatternBadSignature() { var text = @" using System.Collections; public class ValidBase: IEnumerable { IEnumerator IEnumerable.GetEnumerator() { return null; } internal IEnumerator GetEnumerator() { return null; } } class Derived : ValidBase { // field, not method new public int GetEnumerator; } public class Test { public static void Main() { foreach (int i in new Derived()) {} // CS0280 } } "; CreateCompilation(text).VerifyDiagnostics( // (27,25): warning CS0280: 'Derived' does not implement the 'collection' pattern. 'Derived.GetEnumerator' has the wrong signature. // foreach (int i in new Derived()) {} // CS0280 Diagnostic(ErrorCode.WRN_PatternBadSignature, "new Derived()").WithArguments("Derived", "collection", "Derived.GetEnumerator"), // (20,19): warning CS0649: Field 'Derived.GetEnumerator' is never assigned to, and will always have its default value 0 // new public int GetEnumerator; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "GetEnumerator").WithArguments("Derived.GetEnumerator", "0") ); } [Fact] public void CS0414WRN_UnreferencedFieldAssg() { var text = @" class C { private int i = 1; // CS0414 public static void Main() { } } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (4,16): warning CS0414: The field 'C.i' is assigned but its value is never used // private int i = 1; // CS0414 Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "i").WithArguments("C.i") ); } [Fact] public void CS0414WRN_UnreferencedFieldAssg02() { var text = @"class S<T1, T2> { T1 t1_field = default(T1); }"; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (3,8): warning CS0414: The field 'S<T1, T2>.t1_field' is assigned but its value is never used // T1 t1_field = default(T1); Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "t1_field").WithArguments("S<T1, T2>.t1_field").WithLocation(3, 8) ); } [Fact] public void CS0419WRN_AmbiguousXMLReference() { var text = @" interface I { void F(); void F(int i); } public class MyClass { /// <see cref=""I.F""/> public static void MyMethod(int i) { } public static void Main () { } } "; CreateCompilationWithMscorlib40AndDocumentationComments(text).VerifyDiagnostics( // (7,14): warning CS1591: Missing XML comment for publicly visible type or member 'MyClass' // public class MyClass Diagnostic(ErrorCode.WRN_MissingXMLComment, "MyClass").WithArguments("MyClass"), // (9,19): warning CS0419: Ambiguous reference in cref attribute: 'I.F'. Assuming 'I.F()', but could have also matched other overloads including 'I.F(int)'. // /// <see cref="I.F"/> Diagnostic(ErrorCode.WRN_AmbiguousXMLReference, "I.F").WithArguments("I.F", "I.F()", "I.F(int)"), // (13,23): warning CS1591: Missing XML comment for publicly visible type or member 'MyClass.Main()' // public static void Main () Diagnostic(ErrorCode.WRN_MissingXMLComment, "Main").WithArguments("MyClass.Main()")); } [Fact] public void CS0420WRN_VolatileByRef() { var text = @" class TestClass { private volatile int i; public void TestVolatileRef(ref int ii) { } public void TestVolatileOut(out int ii) { ii = 0; } public static void Main() { TestClass x = new TestClass(); x.TestVolatileRef(ref x.i); // CS0420 x.TestVolatileOut(out x.i); // CS0420 } } "; CreateCompilation(text).VerifyDiagnostics( // (18,29): warning CS0420: 'TestClass.i': a reference to a volatile field will not be treated as volatile Diagnostic(ErrorCode.WRN_VolatileByRef, "x.i").WithArguments("TestClass.i"), // (19,29): warning CS0420: 'TestClass.i': a reference to a volatile field will not be treated as volatile Diagnostic(ErrorCode.WRN_VolatileByRef, "x.i").WithArguments("TestClass.i")); } [Fact] public void CS0420WRN_VolatileByRef_Suppressed() { var text = @" using System.Threading; class TestClass { private static volatile int x = 0; public static void TestVolatileByRef() { Interlocked.Increment(ref x); // no CS0420 Interlocked.Decrement(ref x); // no CS0420 Interlocked.Add(ref x, 0); // no CS0420 Interlocked.CompareExchange(ref x, 0, 0); // no CS0420 Interlocked.Exchange(ref x, 0); // no CS0420 // using fully qualified name System.Threading.Interlocked.Increment(ref x); // no CS0420 System.Threading.Interlocked.Decrement(ref x); // no CS0420 System.Threading.Interlocked.Add(ref x, 0); // no CS0420 System.Threading.Interlocked.CompareExchange(ref x, 0, 0); // no CS0420 System.Threading.Interlocked.Exchange(ref x, 0); // no CS0420 // passing volatile variables in a nested way Interlocked.Increment(ref Method1(ref x).y); // CS0420 for x Interlocked.Decrement(ref Method1(ref x).y); // CS0420 for x Interlocked.Add(ref Method1(ref x).y, 0); // CS0420 for x Interlocked.CompareExchange(ref Method1(ref x).y, 0, 0); // CS0420 for x Interlocked.Exchange(ref Method1(ref x).y, 0); // CS0420 for x // located as a function argument goo(Interlocked.Increment(ref x)); // no CS0420 } public static int goo(int x) { return x; } public static MyClass Method1(ref int x) { return new MyClass(); } public class MyClass { public volatile int y = 0; } } "; CreateCompilation(text).VerifyDiagnostics( // (24,45): warning CS0420: 'TestClass.i': a reference to a volatile field will not be treated as volatile Diagnostic(ErrorCode.WRN_VolatileByRef, "x").WithArguments("TestClass.x"), // (25,45): warning CS0420: 'TestClass.i': a reference to a volatile field will not be treated as volatile Diagnostic(ErrorCode.WRN_VolatileByRef, "x").WithArguments("TestClass.x"), // (26,39): warning CS0420: 'TestClass.i': a reference to a volatile field will not be treated as volatile Diagnostic(ErrorCode.WRN_VolatileByRef, "x").WithArguments("TestClass.x"), // (27,51): warning CS0420: 'TestClass.i': a reference to a volatile field will not be treated as volatile Diagnostic(ErrorCode.WRN_VolatileByRef, "x").WithArguments("TestClass.x"), // (28,44): warning CS0420: 'TestClass.i': a reference to a volatile field will not be treated as volatile Diagnostic(ErrorCode.WRN_VolatileByRef, "x").WithArguments("TestClass.x")); } [WorkItem(728380, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/728380")] [Fact] public void Repro728380() { var source = @" class Test { static volatile int x; unsafe static void goo(int* pX) { } static int Main() { unsafe { Test.goo(&x); } return 1; } } "; CreateCompilation(source, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (9,27): error CS0212: You can only take the address of an unfixed expression inside of a fixed statement initializer // unsafe { Test.goo(&x); } Diagnostic(ErrorCode.ERR_FixedNeeded, "&x"), // (9,28): warning CS0420: 'Test.x': a reference to a volatile field will not be treated as volatile // unsafe { Test.goo(&x); } Diagnostic(ErrorCode.WRN_VolatileByRef, "x").WithArguments("Test.x")); } [Fact, WorkItem(528275, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528275")] public void CS0429WRN_UnreachableExpr() { var text = @" public class cs0429 { public static void Main() { if (false && myTest()) // CS0429 // Try the following line instead: // if (true && myTest()) { } else { int i = 0; i++; } } static bool myTest() { return true; } } "; // Dev11 compiler reports WRN_UnreachableExpr, but reachability is defined for statements not for expressions. // We don't report the warning. CreateCompilation(text).VerifyDiagnostics(); } [Fact, WorkItem(528275, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528275"), WorkItem(530071, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530071")] public void CS0429WRN_UnreachableExpr_02() { var text = @" class Program { static bool b = true; const bool con = true; static void Main(string[] args) { int x = 1; int y = 1; int s = true ? x++ : y++; // y++ unreachable s = x == y ? x++ : y++; // OK s = con ? x++ : y++; // y++ unreachable bool con1 = true; s = con1 ? x++ : y++; // OK s = b ? x++ : y++; s = 1 < 2 ? x++ : y++; // y++ unreachable } } "; // Dev11 compiler reports WRN_UnreachableExpr, but reachability is defined for statements not for expressions. // We don't report the warning. CreateCompilation(text).VerifyDiagnostics(); } [Fact, WorkItem(543943, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543943")] public void CS0458WRN_AlwaysNull() { var text = @" public class Test { public static void Main() { int? x = 0; x = null + x; x = x + default(int?); x += new int?(); x = null - x; x = x - default(int?); x -= new int?(); x = null * x; x = x * default(int?); x *= new int?(); x = null / x; x = x / default(int?); x /= new int?(); x = null % x; x = x % default(int?); x %= new int?(); x = null << x; x = x << default(int?); x <<= new int?(); x = null >> x; x = x >> default(int?); x >>= new int?(); x = null & x; x = x & default(int?); x &= new int?(); x = null | x; x = x | default(int?); x |= new int?(); x = null ^ x; x = x ^ default(int?); x ^= new int?(); //The below block of code should not raise a warning bool? y = null; y = y & null; y = y |false; y = true | null; double? d = +default(double?); int? i = -default(int?); long? l = ~default(long?); bool? b = !default(bool?); } } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( Diagnostic(ErrorCode.WRN_AlwaysNull, "null + x").WithArguments("int?"), Diagnostic(ErrorCode.WRN_AlwaysNull, "x + default(int?)").WithArguments("int?"), Diagnostic(ErrorCode.WRN_AlwaysNull, "x += new int?()").WithArguments("int?"), Diagnostic(ErrorCode.WRN_AlwaysNull, "null - x").WithArguments("int?"), Diagnostic(ErrorCode.WRN_AlwaysNull, "x - default(int?)").WithArguments("int?"), Diagnostic(ErrorCode.WRN_AlwaysNull, "x -= new int?()").WithArguments("int?"), Diagnostic(ErrorCode.WRN_AlwaysNull, "null * x").WithArguments("int?"), Diagnostic(ErrorCode.WRN_AlwaysNull, "x * default(int?)").WithArguments("int?"), Diagnostic(ErrorCode.WRN_AlwaysNull, "x *= new int?()").WithArguments("int?"), Diagnostic(ErrorCode.WRN_AlwaysNull, "null / x").WithArguments("int?"), Diagnostic(ErrorCode.WRN_AlwaysNull, "x / default(int?)").WithArguments("int?"), Diagnostic(ErrorCode.WRN_AlwaysNull, "x /= new int?()").WithArguments("int?"), Diagnostic(ErrorCode.WRN_AlwaysNull, "null % x").WithArguments("int?"), Diagnostic(ErrorCode.WRN_AlwaysNull, "x % default(int?)").WithArguments("int?"), Diagnostic(ErrorCode.WRN_AlwaysNull, "x %= new int?()").WithArguments("int?"), Diagnostic(ErrorCode.WRN_AlwaysNull, "null << x").WithArguments("int?"), Diagnostic(ErrorCode.WRN_AlwaysNull, "x << default(int?)").WithArguments("int?"), Diagnostic(ErrorCode.WRN_AlwaysNull, "x <<= new int?()").WithArguments("int?"), Diagnostic(ErrorCode.WRN_AlwaysNull, "null >> x").WithArguments("int?"), Diagnostic(ErrorCode.WRN_AlwaysNull, "x >> default(int?)").WithArguments("int?"), Diagnostic(ErrorCode.WRN_AlwaysNull, "x >>= new int?()").WithArguments("int?"), Diagnostic(ErrorCode.WRN_AlwaysNull, "null & x").WithArguments("int?"), Diagnostic(ErrorCode.WRN_AlwaysNull, "x & default(int?)").WithArguments("int?"), Diagnostic(ErrorCode.WRN_AlwaysNull, "x &= new int?()").WithArguments("int?"), Diagnostic(ErrorCode.WRN_AlwaysNull, "null | x").WithArguments("int?"), Diagnostic(ErrorCode.WRN_AlwaysNull, "x | default(int?)").WithArguments("int?"), Diagnostic(ErrorCode.WRN_AlwaysNull, "x |= new int?()").WithArguments("int?"), Diagnostic(ErrorCode.WRN_AlwaysNull, "null ^ x").WithArguments("int?"), Diagnostic(ErrorCode.WRN_AlwaysNull, "x ^ default(int?)").WithArguments("int?"), Diagnostic(ErrorCode.WRN_AlwaysNull, "x ^= new int?()").WithArguments("int?"), Diagnostic(ErrorCode.WRN_AlwaysNull, "+default(double?)").WithArguments("double?"), Diagnostic(ErrorCode.WRN_AlwaysNull, "-default(int?)").WithArguments("int?"), Diagnostic(ErrorCode.WRN_AlwaysNull, "~default(long?)").WithArguments("long?"), Diagnostic(ErrorCode.WRN_AlwaysNull, "!default(bool?)").WithArguments("bool?") ); } [Fact] public void CS0464WRN_CmpAlwaysFalse() { var text = @" class MyClass { public struct S { public static bool operator <(S x, S y) { return true; } public static bool operator >(S x, S y) { return true; } public static bool operator <=(S x, S y) { return true; } public static bool operator >=(S x, S y) { return true; } } public static void W(bool b) { System.Console.Write(b ? 't' : 'f'); } public static void Main() { S s = default(S); S? t = s; int i = 0; int? n = i; W(i < null); // CS0464 W(i <= null); // CS0464 W(i > null); // CS0464 W(i >= null); // CS0464 W(n < null); // CS0464 W(n <= null); // CS0464 W(n > null); // CS0464 W(n >= null); // CS0464 W(s < null); // CS0464 W(s <= null); // CS0464 W(s > null); // CS0464 W(s >= null); // CS0464 W(t < null); // CS0464 W(t <= null); // CS0464 W(t > null); // CS0464 W(t >= null); // CS0464 W(i < default(short?)); // CS0464 W(i <= default(short?)); // CS0464 W(i > default(short?)); // CS0464 W(i >= default(short?)); // CS0464 W(n < default(short?)); // CS0464 W(n <= default(short?)); // CS0464 W(n > default(short?)); // CS0464 W(n >= default(short?)); // CS0464 W(s < default(S?)); // CS0464 W(s <= default(S?)); // CS0464 W(s > default(S?)); // CS0464 W(s >= default(S?)); // CS0464 W(t < default(S?)); // CS0464 W(t <= default(S?)); // CS0464 W(t > default(S?)); // CS0464 W(t >= default(S?)); // CS0464 W(i < new sbyte?()); // CS0464 W(i <= new sbyte?()); // CS0464 W(i > new sbyte?()); // CS0464 W(i >= new sbyte?()); // CS0464 W(n < new sbyte?()); // CS0464 W(n <= new sbyte?()); // CS0464 W(n > new sbyte?()); // CS0464 W(n >= new sbyte?()); // CS0464 W(s < new S?()); // CS0464 W(s <= new S?()); // CS0464 W(s > new S?()); // CS0464 W(s >= new S?()); // CS0464 W(t < new S?()); // CS0464 W(t <= new S?()); // CS0464 W(t > new S?()); // CS0464 W(t >= new S?()); // CS0464 System.Console.WriteLine(); W(null < i); // CS0464 W(null <= i); // CS0464 W(null > i); // CS0464 W(null >= i); // CS0464 W(null < n); // CS0464 W(null <= n); // CS0464 W(null > n); // CS0464 W(null >= n); // CS0464 W(null < s); // CS0464 W(null <= s); // CS0464 W(null > s); // CS0464 W(null >= s); // CS0464 W(null < t); // CS0464 W(null <= t); // CS0464 W(null > t); // CS0464 W(null >= t); // CS0464 W(default(short?) < i); // CS0464 W(default(short?) <= i); // CS0464 W(default(short?) > i); // CS0464 W(default(short?) >= i); // CS0464 W(default(short?) < n); // CS0464 W(default(short?) <= n); // CS0464 W(default(short?) > n); // CS0464 W(default(short?) >= n); // CS0464 W(default(S?) < s); // CS0464 W(default(S?) <= s); // CS0464 W(default(S?) > s); // CS0464 W(default(S?) >= s); // CS0464 W(default(S?) < t); // CS0464 W(default(S?) <= t); // CS0464 W(default(S?) > t); // CS0464 W(default(S?) >= t); // CS0464 W(new sbyte?() < i); // CS0464 W(new sbyte?() <= i); // CS0464 W(new sbyte?() > i); // CS0464 W(new sbyte?() >= i); // CS0464 W(new sbyte?() < n); // CS0464 W(new sbyte?() <= n); // CS0464 W(new sbyte?() > n); // CS0464 W(new sbyte?() > n); // CS0464 W(new S?() < s); // CS0464 W(new S?() <= s); // CS0464 W(new S?() > s); // CS0464 W(new S?() >= s); // CS0464 W(new S?() < t); // CS0464 W(new S?() <= t); // CS0464 W(new S?() > t); // CS0464 W(new S?() > t); // CS0464 System.Console.WriteLine(); W(null > null); // CS0464 W(null >= null); // CS0464 W(null < null); // CS0464 W(null <= null); // CS0464 } } "; var verifier = CompileAndVerify(source: text, expectedOutput: @"ffffffffffffffffffffffffffffffffffffffffffffffff ffffffffffffffffffffffffffffffffffffffffffffffff ffff"); CreateCompilation(text).VerifyDiagnostics( // (25,11): warning CS0464: Comparing with null of type 'int?' always produces 'false' // W(i < null); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "i < null").WithArguments("int?"), // (26,11): warning CS0464: Comparing with null of type 'int?' always produces 'false' // W(i <= null); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "i <= null").WithArguments("int?"), // (27,11): warning CS0464: Comparing with null of type 'int?' always produces 'false' // W(i > null); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "i > null").WithArguments("int?"), // (28,11): warning CS0464: Comparing with null of type 'int?' always produces 'false' // W(i >= null); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "i >= null").WithArguments("int?"), // (30,11): warning CS0464: Comparing with null of type 'int?' always produces 'false' // W(n < null); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "n < null").WithArguments("int?"), // (31,11): warning CS0464: Comparing with null of type 'int?' always produces 'false' // W(n <= null); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "n <= null").WithArguments("int?"), // (32,11): warning CS0464: Comparing with null of type 'int?' always produces 'false' // W(n > null); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "n > null").WithArguments("int?"), // (33,11): warning CS0464: Comparing with null of type 'int?' always produces 'false' // W(n >= null); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "n >= null").WithArguments("int?"), // (35,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false' // W(s < null); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "s < null").WithArguments("MyClass.S?"), // (36,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false' // W(s <= null); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "s <= null").WithArguments("MyClass.S?"), // (37,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false' // W(s > null); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "s > null").WithArguments("MyClass.S?"), // (38,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false' // W(s >= null); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "s >= null").WithArguments("MyClass.S?"), // (40,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false' // W(t < null); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "t < null").WithArguments("MyClass.S?"), // (41,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false' // W(t <= null); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "t <= null").WithArguments("MyClass.S?"), // (42,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false' // W(t > null); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "t > null").WithArguments("MyClass.S?"), // (43,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false' // W(t >= null); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "t >= null").WithArguments("MyClass.S?"), // (45,11): warning CS0464: Comparing with null of type 'short?' always produces 'false' // W(i < default(short?)); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "i < default(short?)").WithArguments("short?"), // (46,11): warning CS0464: Comparing with null of type 'short?' always produces 'false' // W(i <= default(short?)); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "i <= default(short?)").WithArguments("short?"), // (47,11): warning CS0464: Comparing with null of type 'short?' always produces 'false' // W(i > default(short?)); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "i > default(short?)").WithArguments("short?"), // (48,11): warning CS0464: Comparing with null of type 'short?' always produces 'false' // W(i >= default(short?)); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "i >= default(short?)").WithArguments("short?"), // (50,11): warning CS0464: Comparing with null of type 'short?' always produces 'false' // W(n < default(short?)); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "n < default(short?)").WithArguments("short?"), // (51,11): warning CS0464: Comparing with null of type 'short?' always produces 'false' // W(n <= default(short?)); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "n <= default(short?)").WithArguments("short?"), // (52,11): warning CS0464: Comparing with null of type 'short?' always produces 'false' // W(n > default(short?)); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "n > default(short?)").WithArguments("short?"), // (53,11): warning CS0464: Comparing with null of type 'short?' always produces 'false' // W(n >= default(short?)); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "n >= default(short?)").WithArguments("short?"), // (55,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false' // W(s < default(S?)); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "s < default(S?)").WithArguments("MyClass.S?"), // (56,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false' // W(s <= default(S?)); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "s <= default(S?)").WithArguments("MyClass.S?"), // (57,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false' // W(s > default(S?)); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "s > default(S?)").WithArguments("MyClass.S?"), // (58,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false' // W(s >= default(S?)); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "s >= default(S?)").WithArguments("MyClass.S?"), // (60,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false' // W(t < default(S?)); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "t < default(S?)").WithArguments("MyClass.S?"), // (61,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false' // W(t <= default(S?)); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "t <= default(S?)").WithArguments("MyClass.S?"), // (62,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false' // W(t > default(S?)); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "t > default(S?)").WithArguments("MyClass.S?"), // (63,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false' // W(t >= default(S?)); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "t >= default(S?)").WithArguments("MyClass.S?"), // (65,11): warning CS0464: Comparing with null of type 'sbyte?' always produces 'false' // W(i < new sbyte?()); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "i < new sbyte?()").WithArguments("sbyte?"), // (66,11): warning CS0464: Comparing with null of type 'sbyte?' always produces 'false' // W(i <= new sbyte?()); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "i <= new sbyte?()").WithArguments("sbyte?"), // (67,11): warning CS0464: Comparing with null of type 'sbyte?' always produces 'false' // W(i > new sbyte?()); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "i > new sbyte?()").WithArguments("sbyte?"), // (68,11): warning CS0464: Comparing with null of type 'sbyte?' always produces 'false' // W(i >= new sbyte?()); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "i >= new sbyte?()").WithArguments("sbyte?"), // (70,11): warning CS0464: Comparing with null of type 'sbyte?' always produces 'false' // W(n < new sbyte?()); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "n < new sbyte?()").WithArguments("sbyte?"), // (71,11): warning CS0464: Comparing with null of type 'sbyte?' always produces 'false' // W(n <= new sbyte?()); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "n <= new sbyte?()").WithArguments("sbyte?"), // (72,11): warning CS0464: Comparing with null of type 'sbyte?' always produces 'false' // W(n > new sbyte?()); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "n > new sbyte?()").WithArguments("sbyte?"), // (73,11): warning CS0464: Comparing with null of type 'sbyte?' always produces 'false' // W(n >= new sbyte?()); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "n >= new sbyte?()").WithArguments("sbyte?"), // (75,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false' // W(s < new S?()); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "s < new S?()").WithArguments("MyClass.S?"), // (76,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false' // W(s <= new S?()); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "s <= new S?()").WithArguments("MyClass.S?"), // (77,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false' // W(s > new S?()); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "s > new S?()").WithArguments("MyClass.S?"), // (78,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false' // W(s >= new S?()); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "s >= new S?()").WithArguments("MyClass.S?"), // (80,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false' // W(t < new S?()); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "t < new S?()").WithArguments("MyClass.S?"), // (81,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false' // W(t <= new S?()); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "t <= new S?()").WithArguments("MyClass.S?"), // (82,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false' // W(t > new S?()); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "t > new S?()").WithArguments("MyClass.S?"), // (83,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false' // W(t >= new S?()); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "t >= new S?()").WithArguments("MyClass.S?"), // (87,11): warning CS0464: Comparing with null of type 'int?' always produces 'false' // W(null < i); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "null < i").WithArguments("int?"), // (88,11): warning CS0464: Comparing with null of type 'int?' always produces 'false' // W(null <= i); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "null <= i").WithArguments("int?"), // (89,11): warning CS0464: Comparing with null of type 'int?' always produces 'false' // W(null > i); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "null > i").WithArguments("int?"), // (90,11): warning CS0464: Comparing with null of type 'int?' always produces 'false' // W(null >= i); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "null >= i").WithArguments("int?"), // (92,11): warning CS0464: Comparing with null of type 'int?' always produces 'false' // W(null < n); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "null < n").WithArguments("int?"), // (93,11): warning CS0464: Comparing with null of type 'int?' always produces 'false' // W(null <= n); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "null <= n").WithArguments("int?"), // (94,11): warning CS0464: Comparing with null of type 'int?' always produces 'false' // W(null > n); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "null > n").WithArguments("int?"), // (95,11): warning CS0464: Comparing with null of type 'int?' always produces 'false' // W(null >= n); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "null >= n").WithArguments("int?"), // (97,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false' // W(null < s); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "null < s").WithArguments("MyClass.S?"), // (98,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false' // W(null <= s); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "null <= s").WithArguments("MyClass.S?"), // (99,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false' // W(null > s); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "null > s").WithArguments("MyClass.S?"), // (100,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false' // W(null >= s); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "null >= s").WithArguments("MyClass.S?"), // (102,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false' // W(null < t); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "null < t").WithArguments("MyClass.S?"), // (103,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false' // W(null <= t); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "null <= t").WithArguments("MyClass.S?"), // (104,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false' // W(null > t); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "null > t").WithArguments("MyClass.S?"), // (105,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false' // W(null >= t); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "null >= t").WithArguments("MyClass.S?"), // (107,11): warning CS0464: Comparing with null of type 'short?' always produces 'false' // W(default(short?) < i); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "default(short?) < i").WithArguments("short?"), // (108,11): warning CS0464: Comparing with null of type 'short?' always produces 'false' // W(default(short?) <= i); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "default(short?) <= i").WithArguments("short?"), // (109,11): warning CS0464: Comparing with null of type 'short?' always produces 'false' // W(default(short?) > i); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "default(short?) > i").WithArguments("short?"), // (110,11): warning CS0464: Comparing with null of type 'short?' always produces 'false' // W(default(short?) >= i); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "default(short?) >= i").WithArguments("short?"), // (112,11): warning CS0464: Comparing with null of type 'short?' always produces 'false' // W(default(short?) < n); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "default(short?) < n").WithArguments("short?"), // (113,11): warning CS0464: Comparing with null of type 'short?' always produces 'false' // W(default(short?) <= n); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "default(short?) <= n").WithArguments("short?"), // (114,11): warning CS0464: Comparing with null of type 'short?' always produces 'false' // W(default(short?) > n); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "default(short?) > n").WithArguments("short?"), // (115,11): warning CS0464: Comparing with null of type 'short?' always produces 'false' // W(default(short?) >= n); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "default(short?) >= n").WithArguments("short?"), // (117,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false' // W(default(S?) < s); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "default(S?) < s").WithArguments("MyClass.S?"), // (118,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false' // W(default(S?) <= s); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "default(S?) <= s").WithArguments("MyClass.S?"), // (119,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false' // W(default(S?) > s); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "default(S?) > s").WithArguments("MyClass.S?"), // (120,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false' // W(default(S?) >= s); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "default(S?) >= s").WithArguments("MyClass.S?"), // (122,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false' // W(default(S?) < t); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "default(S?) < t").WithArguments("MyClass.S?"), // (123,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false' // W(default(S?) <= t); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "default(S?) <= t").WithArguments("MyClass.S?"), // (124,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false' // W(default(S?) > t); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "default(S?) > t").WithArguments("MyClass.S?"), // (125,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false' // W(default(S?) >= t); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "default(S?) >= t").WithArguments("MyClass.S?"), // (127,11): warning CS0464: Comparing with null of type 'sbyte?' always produces 'false' // W(new sbyte?() < i); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "new sbyte?() < i").WithArguments("sbyte?"), // (128,11): warning CS0464: Comparing with null of type 'sbyte?' always produces 'false' // W(new sbyte?() <= i); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "new sbyte?() <= i").WithArguments("sbyte?"), // (129,11): warning CS0464: Comparing with null of type 'sbyte?' always produces 'false' // W(new sbyte?() > i); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "new sbyte?() > i").WithArguments("sbyte?"), // (130,11): warning CS0464: Comparing with null of type 'sbyte?' always produces 'false' // W(new sbyte?() >= i); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "new sbyte?() >= i").WithArguments("sbyte?"), // (132,11): warning CS0464: Comparing with null of type 'sbyte?' always produces 'false' // W(new sbyte?() < n); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "new sbyte?() < n").WithArguments("sbyte?"), // (133,11): warning CS0464: Comparing with null of type 'sbyte?' always produces 'false' // W(new sbyte?() <= n); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "new sbyte?() <= n").WithArguments("sbyte?"), // (134,11): warning CS0464: Comparing with null of type 'sbyte?' always produces 'false' // W(new sbyte?() > n); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "new sbyte?() > n").WithArguments("sbyte?"), // (135,11): warning CS0464: Comparing with null of type 'sbyte?' always produces 'false' // W(new sbyte?() > n); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "new sbyte?() > n").WithArguments("sbyte?"), // (137,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false' // W(new S?() < s); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "new S?() < s").WithArguments("MyClass.S?"), // (138,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false' // W(new S?() <= s); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "new S?() <= s").WithArguments("MyClass.S?"), // (139,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false' // W(new S?() > s); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "new S?() > s").WithArguments("MyClass.S?"), // (140,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false' // W(new S?() >= s); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "new S?() >= s").WithArguments("MyClass.S?"), // (142,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false' // W(new S?() < t); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "new S?() < t").WithArguments("MyClass.S?"), // (143,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false' // W(new S?() <= t); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "new S?() <= t").WithArguments("MyClass.S?"), // (144,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false' // W(new S?() > t); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "new S?() > t").WithArguments("MyClass.S?"), // (145,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false' // W(new S?() > t); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "new S?() > t").WithArguments("MyClass.S?"), // (149,11): warning CS0464: Comparing with null of type 'int?' always produces 'false' // W(null > null); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "null > null").WithArguments("int?"), // (150,11): warning CS0464: Comparing with null of type 'int?' always produces 'false' // W(null >= null); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "null >= null").WithArguments("int?"), // (151,11): warning CS0464: Comparing with null of type 'int?' always produces 'false' // W(null < null); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "null < null").WithArguments("int?"), // (152,11): warning CS0464: Comparing with null of type 'int?' always produces 'false' // W(null <= null); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "null <= null").WithArguments("int?") ); } [Fact] public void CS0469WRN_GotoCaseShouldConvert() { var text = @" class Test { static void Main() { char c = (char)180; switch (c) { case (char)127: break; case (char)180: goto case 127; // CS0469 // try the following line instead // goto case (char) 127; } } } "; CreateCompilation(text).VerifyDiagnostics( // (13,13): warning CS0469: The 'goto case' value is not implicitly convertible to type 'char' // goto case 127; // CS0469 Diagnostic(ErrorCode.WRN_GotoCaseShouldConvert, "goto case 127;").WithArguments("char").WithLocation(13, 13) ); } [Fact, WorkItem(663, "https://github.com/dotnet/roslyn/issues/663")] public void CS0472WRN_NubExprIsConstBool() { // Due to a long-standing bug, the native compiler does not produce warnings for "guid == null", // but does for "int == null". Roslyn corrects this lapse and produces warnings for both built-in // and user-defined lifted equality operators, but the new warnings for user-defined types are // only given with /warn:n where n >= 5. var text = @" using System; class MyClass { public static void W(bool b) { System.Console.Write(b ? 't' : 'f'); } enum E : int { }; public static void Main() { Guid g = default(Guid); Guid? h = g; int i = 0; int? n = i; W(i == null); // CS0472 W(i != null); // CS0472 W(n == null); // no error W(n != null); // no error W(g == null); // CS0472 W(g != null); // CS0472 W(h == null); // no error W(h != null); // no error W(i == default(short?)); // CS0472 W(i != default(short?)); // CS0472 W(n == default(short?)); // no error W(n != default(short?)); // no error W(g == default(Guid?)); // CS0472 W(g != default(Guid?)); // CS0472 W(h == default(Guid?)); // no error W(h != default(Guid?)); // no error W(i == new sbyte?()); // CS0472 W(i != new sbyte?()); // CS0472 W(n == new sbyte?()); // no error W(n != new sbyte?()); // no error W(g == new Guid?()); // CS0472 W(g != new Guid?()); // CS0472 W(h == new Guid?()); // no error W(h != new Guid?()); // no error System.Console.WriteLine(); W(null == i); // CS0472 W(null != i); // CS0472 W(null == n); // no error W(null != n); // no error W(null == g); // CS0472 W(null != g); // CS0472 W(null == h); // no error W(null != h); // no error W(default(long?) == i); // CS0472 W(default(long?) != i); // CS0472 W(default(long?) == n); // no error W(default(long?) != n); // no error W(default(Guid?) == g); // CS0472 W(default(Guid?) != g); // CS0472 W(default(Guid?) == h); // no error W(default(Guid?) != h); // no error W(new double?() == i); // CS0472 W(new double?() != i); // CS0472 W(new double?() == n); // no error W(new double?() != n); // no error W(new Guid?() == g); // CS0472 W(new Guid?() != g); // CS0472 W(new Guid?() == h); // no error W(new Guid?() != h); // no error System.Console.WriteLine(); W(null == null); // No error, because both sides are nullable, but of course W(null != null); // we could give a warning here as well. System.Console.WriteLine(); //check comparisons with converted constants W((E?)1 == null); W(null != (E?)1); W((int?)1 == null); W(null != (int?)1); //check comparisons when null is converted W(0 == (int?)null); W((int?)null != 0); W(0 == (E?)null); W((E?)null != 0); } } "; string expected = @"ftftftftftftftftftftftft ftftftftftftftftftftftft tf ftftftft"; var fullExpected = new DiagnosticDescription[] { // (19,11): warning CS0472: The result of the expression is always 'false' since a value of type 'int' is never equal to 'null' of type 'int?' // W(i == null); // CS0472 Diagnostic(ErrorCode.WRN_NubExprIsConstBool, "i == null").WithArguments("false", "int", "int?").WithLocation(19, 11), // (20,11): warning CS0472: The result of the expression is always 'true' since a value of type 'int' is never equal to 'null' of type 'int?' // W(i != null); // CS0472 Diagnostic(ErrorCode.WRN_NubExprIsConstBool, "i != null").WithArguments("true", "int", "int?").WithLocation(20, 11), // (23,11): warning CS8073: The result of the expression is always 'false' since a value of type 'System.Guid' is never equal to 'null' of type 'System.Guid?' // W(g == null); // CS0472 Diagnostic(ErrorCode.WRN_NubExprIsConstBool2, "g == null").WithArguments("false", "System.Guid", "System.Guid?").WithLocation(23, 11), // (24,11): warning CS8073: The result of the expression is always 'true' since a value of type 'System.Guid' is never equal to 'null' of type 'System.Guid?' // W(g != null); // CS0472 Diagnostic(ErrorCode.WRN_NubExprIsConstBool2, "g != null").WithArguments("true", "System.Guid", "System.Guid?").WithLocation(24, 11), // (28,11): warning CS0472: The result of the expression is always 'false' since a value of type 'int' is never equal to 'null' of type 'short?' // W(i == default(short?)); // CS0472 Diagnostic(ErrorCode.WRN_NubExprIsConstBool, "i == default(short?)").WithArguments("false", "int", "short?").WithLocation(28, 11), // (29,11): warning CS0472: The result of the expression is always 'true' since a value of type 'int' is never equal to 'null' of type 'short?' // W(i != default(short?)); // CS0472 Diagnostic(ErrorCode.WRN_NubExprIsConstBool, "i != default(short?)").WithArguments("true", "int", "short?").WithLocation(29, 11), // (32,11): warning CS8073: The result of the expression is always 'false' since a value of type 'System.Guid' is never equal to 'null' of type 'System.Guid?' // W(g == default(Guid?)); // CS0472 Diagnostic(ErrorCode.WRN_NubExprIsConstBool2, "g == default(Guid?)").WithArguments("false", "System.Guid", "System.Guid?").WithLocation(32, 11), // (33,11): warning CS8073: The result of the expression is always 'true' since a value of type 'System.Guid' is never equal to 'null' of type 'System.Guid?' // W(g != default(Guid?)); // CS0472 Diagnostic(ErrorCode.WRN_NubExprIsConstBool2, "g != default(Guid?)").WithArguments("true", "System.Guid", "System.Guid?").WithLocation(33, 11), // (37,11): warning CS0472: The result of the expression is always 'false' since a value of type 'int' is never equal to 'null' of type 'sbyte?' // W(i == new sbyte?()); // CS0472 Diagnostic(ErrorCode.WRN_NubExprIsConstBool, "i == new sbyte?()").WithArguments("false", "int", "sbyte?").WithLocation(37, 11), // (38,11): warning CS0472: The result of the expression is always 'true' since a value of type 'int' is never equal to 'null' of type 'sbyte?' // W(i != new sbyte?()); // CS0472 Diagnostic(ErrorCode.WRN_NubExprIsConstBool, "i != new sbyte?()").WithArguments("true", "int", "sbyte?").WithLocation(38, 11), // (41,11): warning CS8073: The result of the expression is always 'false' since a value of type 'System.Guid' is never equal to 'null' of type 'System.Guid?' // W(g == new Guid?()); // CS0472 Diagnostic(ErrorCode.WRN_NubExprIsConstBool2, "g == new Guid?()").WithArguments("false", "System.Guid", "System.Guid?").WithLocation(41, 11), // (42,11): warning CS8073: The result of the expression is always 'true' since a value of type 'System.Guid' is never equal to 'null' of type 'System.Guid?' // W(g != new Guid?()); // CS0472 Diagnostic(ErrorCode.WRN_NubExprIsConstBool2, "g != new Guid?()").WithArguments("true", "System.Guid", "System.Guid?").WithLocation(42, 11), // (49,11): warning CS0472: The result of the expression is always 'false' since a value of type 'int' is never equal to 'null' of type 'int?' // W(null == i); // CS0472 Diagnostic(ErrorCode.WRN_NubExprIsConstBool, "null == i").WithArguments("false", "int", "int?").WithLocation(49, 11), // (50,11): warning CS0472: The result of the expression is always 'true' since a value of type 'int' is never equal to 'null' of type 'int?' // W(null != i); // CS0472 Diagnostic(ErrorCode.WRN_NubExprIsConstBool, "null != i").WithArguments("true", "int", "int?").WithLocation(50, 11), // (53,11): warning CS8073: The result of the expression is always 'false' since a value of type 'System.Guid' is never equal to 'null' of type 'System.Guid?' // W(null == g); // CS0472 Diagnostic(ErrorCode.WRN_NubExprIsConstBool2, "null == g").WithArguments("false", "System.Guid", "System.Guid?").WithLocation(53, 11), // (54,11): warning CS8073: The result of the expression is always 'true' since a value of type 'System.Guid' is never equal to 'null' of type 'System.Guid?' // W(null != g); // CS0472 Diagnostic(ErrorCode.WRN_NubExprIsConstBool2, "null != g").WithArguments("true", "System.Guid", "System.Guid?").WithLocation(54, 11), // (58,11): warning CS0472: The result of the expression is always 'false' since a value of type 'long' is never equal to 'null' of type 'long?' // W(default(long?) == i); // CS0472 Diagnostic(ErrorCode.WRN_NubExprIsConstBool, "default(long?) == i").WithArguments("false", "long", "long?").WithLocation(58, 11), // (59,11): warning CS0472: The result of the expression is always 'true' since a value of type 'long' is never equal to 'null' of type 'long?' // W(default(long?) != i); // CS0472 Diagnostic(ErrorCode.WRN_NubExprIsConstBool, "default(long?) != i").WithArguments("true", "long", "long?").WithLocation(59, 11), // (62,11): warning CS8073: The result of the expression is always 'false' since a value of type 'System.Guid' is never equal to 'null' of type 'System.Guid?' // W(default(Guid?) == g); // CS0472 Diagnostic(ErrorCode.WRN_NubExprIsConstBool2, "default(Guid?) == g").WithArguments("false", "System.Guid", "System.Guid?").WithLocation(62, 11), // (63,11): warning CS8073: The result of the expression is always 'true' since a value of type 'System.Guid' is never equal to 'null' of type 'System.Guid?' // W(default(Guid?) != g); // CS0472 Diagnostic(ErrorCode.WRN_NubExprIsConstBool2, "default(Guid?) != g").WithArguments("true", "System.Guid", "System.Guid?").WithLocation(63, 11), // (67,11): warning CS0472: The result of the expression is always 'false' since a value of type 'double' is never equal to 'null' of type 'double?' // W(new double?() == i); // CS0472 Diagnostic(ErrorCode.WRN_NubExprIsConstBool, "new double?() == i").WithArguments("false", "double", "double?").WithLocation(67, 11), // (68,11): warning CS0472: The result of the expression is always 'true' since a value of type 'double' is never equal to 'null' of type 'double?' // W(new double?() != i); // CS0472 Diagnostic(ErrorCode.WRN_NubExprIsConstBool, "new double?() != i").WithArguments("true", "double", "double?").WithLocation(68, 11), // (71,11): warning CS8073: The result of the expression is always 'false' since a value of type 'System.Guid' is never equal to 'null' of type 'System.Guid?' // W(new Guid?() == g); // CS0472 Diagnostic(ErrorCode.WRN_NubExprIsConstBool2, "new Guid?() == g").WithArguments("false", "System.Guid", "System.Guid?").WithLocation(71, 11), // (72,11): warning CS8073: The result of the expression is always 'true' since a value of type 'System.Guid' is never equal to 'null' of type 'System.Guid?' // W(new Guid?() != g); // CS0472 Diagnostic(ErrorCode.WRN_NubExprIsConstBool2, "new Guid?() != g").WithArguments("true", "System.Guid", "System.Guid?").WithLocation(72, 11), // (84,11): warning CS0472: The result of the expression is always 'false' since a value of type 'MyClass.E' is never equal to 'null' of type 'MyClass.E?' // W((E?)1 == null); Diagnostic(ErrorCode.WRN_NubExprIsConstBool, "(E?)1 == null").WithArguments("false", "MyClass.E", "MyClass.E?").WithLocation(84, 11), // (85,11): warning CS0472: The result of the expression is always 'true' since a value of type 'MyClass.E' is never equal to 'null' of type 'MyClass.E?' // W(null != (E?)1); Diagnostic(ErrorCode.WRN_NubExprIsConstBool, "null != (E?)1").WithArguments("true", "MyClass.E", "MyClass.E?").WithLocation(85, 11), // (87,11): warning CS0472: The result of the expression is always 'false' since a value of type 'int' is never equal to 'null' of type 'int?' // W((int?)1 == null); Diagnostic(ErrorCode.WRN_NubExprIsConstBool, "(int?)1 == null").WithArguments("false", "int", "int?").WithLocation(87, 11), // (88,11): warning CS0472: The result of the expression is always 'true' since a value of type 'int' is never equal to 'null' of type 'int?' // W(null != (int?)1); Diagnostic(ErrorCode.WRN_NubExprIsConstBool, "null != (int?)1").WithArguments("true", "int", "int?").WithLocation(88, 11), // (92,11): warning CS0472: The result of the expression is always 'false' since a value of type 'int' is never equal to 'null' of type 'int?' // W(0 == (int?)null); Diagnostic(ErrorCode.WRN_NubExprIsConstBool, "0 == (int?)null").WithArguments("false", "int", "int?").WithLocation(92, 11), // (93,11): warning CS0472: The result of the expression is always 'true' since a value of type 'int' is never equal to 'null' of type 'int?' // W((int?)null != 0); Diagnostic(ErrorCode.WRN_NubExprIsConstBool, "(int?)null != 0").WithArguments("true", "int", "int?").WithLocation(93, 11), // (95,11): warning CS0472: The result of the expression is always 'false' since a value of type 'MyClass.E' is never equal to 'null' of type 'MyClass.E?' // W(0 == (E?)null); Diagnostic(ErrorCode.WRN_NubExprIsConstBool, "0 == (E?)null").WithArguments("false", "MyClass.E", "MyClass.E?").WithLocation(95, 11), // (96,11): warning CS0472: The result of the expression is always 'true' since a value of type 'MyClass.E' is never equal to 'null' of type 'MyClass.E?' // W((E?)null != 0); Diagnostic(ErrorCode.WRN_NubExprIsConstBool, "(E?)null != 0").WithArguments("true", "MyClass.E", "MyClass.E?").WithLocation(96, 11) }; var compatibleExpected = fullExpected.Where(d => !d.Code.Equals((int)ErrorCode.WRN_NubExprIsConstBool2)).ToArray(); this.CompileAndVerify(source: text, expectedOutput: expected, options: TestOptions.ReleaseExe.WithWarningLevel(4)).VerifyDiagnostics(compatibleExpected); this.CompileAndVerify(source: text, expectedOutput: expected).VerifyDiagnostics(fullExpected); } [Fact] public void CS0472WRN_NubExprIsConstBool_ConstructorInitializer() { var text = @"class A { internal A(bool b) { } } class B : A { B(int i) : base(i == null) { } }"; CreateCompilation(text).VerifyDiagnostics( // (9,21): warning CS0472: The result of the expression is always 'false' since a value of type 'int' is never equal to 'null' of type 'int?' // B(int i) : base(i == null) Diagnostic(ErrorCode.WRN_NubExprIsConstBool, "i == null").WithArguments("false", "int", "int?").WithLocation(9, 21)); } [Fact] public void CS0612WRN_DeprecatedSymbol() { var text = @" using System; class MyClass { [Obsolete] public static void ObsoleteMethod() { } [Obsolete] public static int ObsoleteField; } class MainClass { static public void Main() { MyClass.ObsoleteMethod(); // CS0612 here: method is deprecated MyClass.ObsoleteField = 0; // CS0612 here: field is deprecated } } "; CreateCompilation(text). VerifyDiagnostics( // (17,7): warning CS0612: 'MyClass.ObsoleteMethod()' is obsolete // MyClass.ObsoleteMethod(); // CS0612 here: method is deprecated Diagnostic(ErrorCode.WRN_DeprecatedSymbol, "MyClass.ObsoleteMethod()").WithArguments("MyClass.ObsoleteMethod()"), // (18,7): warning CS0612: 'MyClass.ObsoleteField' is obsolete // MyClass.ObsoleteField = 0; // CS0612 here: field is deprecated Diagnostic(ErrorCode.WRN_DeprecatedSymbol, "MyClass.ObsoleteField").WithArguments("MyClass.ObsoleteField")); } [Fact, WorkItem(546062, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546062")] public void CS0618WRN_DeprecatedSymbol() { var text = @" public class ConsoleStub { public static void Main(string[] args) { System.Collections.CaseInsensitiveHashCodeProvider x; System.Console.WriteLine(x); } }"; CreateCompilation(text). VerifyDiagnostics( // (6,9): warning CS0618: 'System.Collections.CaseInsensitiveHashCodeProvider' is obsolete: 'Please use StringComparer instead.' // System.Collections.CaseInsensitiveHashCodeProvider x; Diagnostic(ErrorCode.WRN_DeprecatedSymbolStr, "System.Collections.CaseInsensitiveHashCodeProvider").WithArguments("System.Collections.CaseInsensitiveHashCodeProvider", "Please use StringComparer instead."), // (7,34): error CS0165: Use of unassigned local variable 'x' // System.Console.WriteLine(x); Diagnostic(ErrorCode.ERR_UseDefViolation, "x").WithArguments("x")); } [WorkItem(545347, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545347")] [Fact] public void CS0649WRN_UnassignedInternalField() { var text = @" using System.Collections; class MyClass { Hashtable table; // CS0649 public void Func(object o, string p) { table[p] = o; } } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (6,15): warning CS0649: Field 'MyClass.table' is never assigned to, and will always have its default value null // Hashtable table; // CS0649 Diagnostic(ErrorCode.WRN_UnassignedInternalField, "table").WithArguments("MyClass.table", "null") ); } [Fact, WorkItem(543454, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543454")] public void CS0649WRN_UnassignedInternalField_1() { var text = @" public class GenClass<T, U> { } public class Outer { internal protected class C1 { } public class C2 { } internal class Test { public GenClass<C1, C2> Fld; } public static int Main() { return 0; } }"; CreateCompilation(text).VerifyDiagnostics( Diagnostic(ErrorCode.WRN_UnassignedInternalField, "Fld").WithArguments("Outer.Test.Fld", "null")); } [WorkItem(546449, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546449")] [WorkItem(546949, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546949")] [Fact] public void CS0652WRN_VacuousIntegralComp() { var text = @" public class Class1 { private static byte i = 0; public static void Main() { const short j = 256; if (i == j) // CS0652, 256 is out of range for byte i = 0; // However, we do not give this warning if both sides of the comparison are constants. In those // cases, we are probably in machine-generated code anyways. const byte k = 0; if (k == j) {} } } "; CreateCompilation(text).VerifyDiagnostics( // (8,11): warning CS0652: Comparison to integral constant is useless; the constant is outside the range of type 'byte' // if (i == j) // CS0652, 256 is out of range for byte Diagnostic(ErrorCode.WRN_VacuousIntegralComp, "i == j").WithArguments("byte")); } [WorkItem(546790, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546790")] [Fact] public void CS0652WRN_VacuousIntegralComp_ExplicitCast() { var text = @" using System; public class Program { public static void Main() { Int16 wSuiteMask = 0; const int VER_SUITE_WH_SERVER = 0x00008000; if (VER_SUITE_WH_SERVER == (Int32)wSuiteMask) { } } } "; CreateCompilation(text).VerifyDiagnostics(); } [Fact] public void CS0665WRN_IncorrectBooleanAssg() { var text = @" class Test { public static void Main() { bool i = false; if (i = true) // CS0665 // try the following line instead // if (i == true) { } System.Console.WriteLine(i); } } "; CreateCompilation(text).VerifyDiagnostics( // (8,11): warning CS0665: Assignment in conditional expression is always constant; did you mean to use == instead of = ? Diagnostic(ErrorCode.WRN_IncorrectBooleanAssg, "i = true")); } [Fact, WorkItem(540777, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540777")] public void CS0665WRN_IncorrectBooleanAssg_ConditionalOperator() { var text = @" class Program { static int Main(string[] args) { bool a = true; System.Console.WriteLine(a); return ((a = false) ? 50 : 100); // Warning } } "; CreateCompilation(text).VerifyDiagnostics( // (8,18): warning CS0665: Assignment in conditional expression is always constant; did you mean to use == instead of = ? Diagnostic(ErrorCode.WRN_IncorrectBooleanAssg, "a = false")); } [Fact] public void CS0665WRN_IncorrectBooleanAssg_Contexts() { var text = @" class C { static void Main(string[] args) { bool b = args.Length > 1; if (b = false) { } while (b = false) { } do { } while (b = false); for (; b = false; ) { } System.Console.WriteLine((b = false) ? 1 : 2); } } "; CreateCompilation(text).VerifyDiagnostics( // (8,13): warning CS0665: Assignment in conditional expression is always constant; did you mean to use == instead of = ? // if (b = false) { } Diagnostic(ErrorCode.WRN_IncorrectBooleanAssg, "b = false"), // (9,16): warning CS0665: Assignment in conditional expression is always constant; did you mean to use == instead of = ? // while (b = false) { } Diagnostic(ErrorCode.WRN_IncorrectBooleanAssg, "b = false"), // (10,23): warning CS0665: Assignment in conditional expression is always constant; did you mean to use == instead of = ? // do { } while (b = false); Diagnostic(ErrorCode.WRN_IncorrectBooleanAssg, "b = false"), // (11,16): warning CS0665: Assignment in conditional expression is always constant; did you mean to use == instead of = ? // for (; b = false; ) { } Diagnostic(ErrorCode.WRN_IncorrectBooleanAssg, "b = false"), // (12,35): warning CS0665: Assignment in conditional expression is always constant; did you mean to use == instead of = ? // System.Console.WriteLine((b = false) ? 1 : 2); Diagnostic(ErrorCode.WRN_IncorrectBooleanAssg, "b = false")); } [Fact] public void CS0665WRN_IncorrectBooleanAssg_Nesting() { var text = @" class C { static void Main(string[] args) { bool b = args.Length > 1; if ((b = false)) { } // parens - warn if (((b = false))) { } // more parens - warn if (M(b = false)) { } // call - do not warn if ((bool)(b = false)) { } // cast - do not warn if ((b = false) || (b = true)) { } // binary operator - do not warn B bb = new B(); if (bb = false) { } // implicit conversion - do not warn } static bool M(bool b) { return b; } } class B { public static implicit operator B(bool b) { return new B(); } public static bool operator true(B b) { return true; } public static bool operator false(B b) { return false; } } "; CreateCompilation(text).VerifyDiagnostics( // (8,14): warning CS0665: Assignment in conditional expression is always constant; did you mean to use == instead of = ? // if ((b = false)) { } // parens - warn Diagnostic(ErrorCode.WRN_IncorrectBooleanAssg, "b = false"), // (9,15): warning CS0665: Assignment in conditional expression is always constant; did you mean to use == instead of = ? // if (((b = false))) { } // more parens - warn Diagnostic(ErrorCode.WRN_IncorrectBooleanAssg, "b = false")); } [Fact, WorkItem(909, "https://github.com/dotnet/roslyn/issues/909")] public void CS0675WRN_BitwiseOrSignExtend() { var text = @" public class sign { public static void Main() { int i32_hi = 1; int i32_lo = 1; ulong u64 = 1; sbyte i08 = 1; short i16 = -1; object v1 = (((long)i32_hi) << 32) | i32_lo; // CS0675 object v2 = (ulong)i32_hi | u64; // CS0675 object v3 = (ulong)i32_hi | (ulong)i32_lo; // No warning; the sign extension bits are the same on both sides. object v4 = (ulong)(uint)(ushort)i08 | (ulong)i32_lo; // CS0675 object v5 = (int)i08 | (int)i32_lo; // No warning; sign extension is considered to be 'expected' when casting. object v6 = (((ulong)i32_hi) << 32) | (uint) i32_lo; // No warning; we've cast to a smaller unsigned type first. // We suppress the warning if the bits that are going to be wiped out are known already to be all zero or all one: object v7 = 0x0000BEEFU | (uint)i16; object v8 = 0xFFFFBEEFU | (uint)i16; object v9 = 0xDEADBEEFU | (uint)i16; // CS0675 // We should do the exact same logic for nullables. int? ni32_hi = 1; int? ni32_lo = 1; ulong? nu64 = 1; sbyte? ni08 = 1; short? ni16 = -1; object v11 = (((long?)ni32_hi) << 32) | ni32_lo; // CS0675 object v12 = (ulong?)ni32_hi | nu64; // CS0675 object v13 = (ulong?)ni32_hi | (ulong?)ni32_lo; // No warning; the sign extension bits are the same on both sides. object v14 = (ulong?)(uint?)(ushort?)ni08 | (ulong?)ni32_lo; // CS0675 object v15 = (int?)ni08 | (int?)ni32_lo; // No warning; sign extension is considered to be 'expected' when casting. object v16 = (((ulong?)ni32_hi) << 32) | (uint?) ni32_lo; // No warning; we've cast to a smaller unsigned type first. // We suppress the warning if the bits that are going to be wiped out are known already to be all zero or all one: object v17 = 0x0000BEEFU | (uint?)ni16; object v18 = 0xFFFFBEEFU | (uint?)ni16; object v19 = 0xDEADBEEFU | (uint?)ni16; // CS0675 } } class Test { static void Main() { long bits = 0; for (int i = 0; i < 32; i++) { if (i % 2 == 0) { bits |= (1 << i); bits = bits | (1 << i); } } } } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (12,19): warning CS0675: Bitwise-or operator used on a sign-extended operand; consider casting to a smaller unsigned type first // object v1 = (((long)i32_hi) << 32) | i32_lo; // CS0675 Diagnostic(ErrorCode.WRN_BitwiseOrSignExtend, "(((long)i32_hi) << 32) | i32_lo"), // (13,19): warning CS0675: Bitwise-or operator used on a sign-extended operand; consider casting to a smaller unsigned type first // object v2 = (ulong)i32_hi | u64; // CS0675 Diagnostic(ErrorCode.WRN_BitwiseOrSignExtend, "(ulong)i32_hi | u64"), // (15,19): warning CS0675: Bitwise-or operator used on a sign-extended operand; consider casting to a smaller unsigned type first // object v4 = (ulong)(uint)(ushort)i08 | (ulong)i32_lo; // CS0675 Diagnostic(ErrorCode.WRN_BitwiseOrSignExtend, "(ulong)(uint)(ushort)i08 | (ulong)i32_lo"), // (21,19): warning CS0675: Bitwise-or operator used on a sign-extended operand; consider casting to a smaller unsigned type first // object v9 = 0xDEADBEEFU | (uint)i16; // CS0675 Diagnostic(ErrorCode.WRN_BitwiseOrSignExtend, "0xDEADBEEFU | (uint)i16"), // (31,20): warning CS0675: Bitwise-or operator used on a sign-extended operand; consider casting to a smaller unsigned type first // object v11 = (((long?)ni32_hi) << 32) | ni32_lo; // CS0675 Diagnostic(ErrorCode.WRN_BitwiseOrSignExtend, "(((long?)ni32_hi) << 32) | ni32_lo"), // (32,20): warning CS0675: Bitwise-or operator used on a sign-extended operand; consider casting to a smaller unsigned type first // object v12 = (ulong?)ni32_hi | nu64; // CS0675 Diagnostic(ErrorCode.WRN_BitwiseOrSignExtend, "(ulong?)ni32_hi | nu64"), // (34,20): warning CS0675: Bitwise-or operator used on a sign-extended operand; consider casting to a smaller unsigned type first // object v14 = (ulong?)(uint?)(ushort?)ni08 | (ulong?)ni32_lo; // CS0675 Diagnostic(ErrorCode.WRN_BitwiseOrSignExtend, "(ulong?)(uint?)(ushort?)ni08 | (ulong?)ni32_lo"), // (40,20): warning CS0675: Bitwise-or operator used on a sign-extended operand; consider casting to a smaller unsigned type first // object v19 = 0xDEADBEEFU | (uint?)ni16; // CS0675 Diagnostic(ErrorCode.WRN_BitwiseOrSignExtend, "0xDEADBEEFU | (uint?)ni16"), // (53,17): warning CS0675: Bitwise-or operator used on a sign-extended operand; consider casting to a smaller unsigned type first // bits |= (1 << i); Diagnostic(ErrorCode.WRN_BitwiseOrSignExtend, "bits |= (1 << i)").WithLocation(53, 17), // (54,24): warning CS0675: Bitwise-or operator used on a sign-extended operand; consider casting to a smaller unsigned type first // bits = bits | (1 << i); Diagnostic(ErrorCode.WRN_BitwiseOrSignExtend, "bits | (1 << i)").WithLocation(54, 24) ); } [Fact] public void CS0728WRN_AssignmentToLockOrDispose01() { CreateCompilation(@" using System; public class ValidBase : IDisposable { public void Dispose() { } } public class Logger { public static void dummy() { ValidBase vb = null; using (vb) { vb = null; // CS0728 } vb = null; } public static void Main() { } }") .VerifyDiagnostics( // (15,13): warning CS0728: Possibly incorrect assignment to local 'vb' which is the argument to a using or lock statement. The Dispose call or unlocking will happen on the original value of the local. Diagnostic(ErrorCode.WRN_AssignmentToLockOrDispose, "vb").WithArguments("vb")); } [Fact] public void CS0728WRN_AssignmentToLockOrDispose02() { CreateCompilation( @"class D : System.IDisposable { public void Dispose() { } } class C { static void M() { D d = new D(); using (d) { N(ref d); } lock (d) { N(ref d); } } static void N(ref D d) { } }") .VerifyDiagnostics( Diagnostic(ErrorCode.WRN_AssignmentToLockOrDispose, "d").WithArguments("d").WithLocation(12, 19), Diagnostic(ErrorCode.WRN_AssignmentToLockOrDispose, "d").WithArguments("d").WithLocation(16, 19)); } [WorkItem(543615, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543615"), WorkItem(546550, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546550")] [ConditionalFact(typeof(WindowsOnly), Reason = ConditionalSkipReason.NativePdbRequiresDesktop)] public void CS0811ERR_DebugFullNameTooLong() { var text = @" using System; using System.Collections.Generic; namespace TestNamespace { using VeryLong = List<List<List<List<List<List<List<List<List<List<List<List<List <List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<int>>>>>>>>>>>>>>>>>>>>>>>>>>>>; // CS0811 class Test { static int Main() { VeryLong goo = null; Console.WriteLine(goo); return 1; } } } "; var compilation = CreateCompilation(text, targetFramework: TargetFramework.Mscorlib45, options: TestOptions.DebugExe); var exebits = new System.IO.MemoryStream(); var pdbbits = new System.IO.MemoryStream(); var result = compilation.Emit(exebits, pdbbits, options: TestOptions.NativePdbEmit); result.Diagnostics.Verify( // (12,20): warning CS0811: The fully qualified name for 'AVeryLong TSystem.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' is too long for debug information. Compile without '/debug' option. // static int Main() Diagnostic(ErrorCode.WRN_DebugFullNameTooLong, "Main").WithArguments("AVeryLong TSystem.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089").WithLocation(12, 20)); } [Fact] public void CS1058WRN_UnreachableGeneralCatch() { var text = @"class C { static void M() { try { } catch (System.Exception) { } catch (System.IO.IOException) { } catch { } try { } catch (System.IO.IOException) { } catch (System.Exception) { } catch { } } } "; CreateCompilation(text).VerifyDiagnostics( Diagnostic(ErrorCode.ERR_UnreachableCatch, "System.IO.IOException").WithArguments("System.Exception").WithLocation(7, 16), Diagnostic(ErrorCode.WRN_UnreachableGeneralCatch, "catch").WithLocation(8, 9), Diagnostic(ErrorCode.WRN_UnreachableGeneralCatch, "catch").WithLocation(12, 9)); } // [Fact(Skip = "11486")] // public void CS1060WRN_UninitializedField() // { // var text = @" //namespace CS1060 //{ // public class U // { // public int i; // } // // public struct S // { // public U u; // } // public class Test // { // static void Main() // { // S s; // s.u.i = 5; // CS1060 // } // } //} //"; // DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, // new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.WRN_UninitializedField, Line = 18, Column = 13, IsWarning = true } }); // } // [Fact()] // public void CS1064ERR_DebugFullNameTooLong() // { // var text = @" //"; // DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, // new ErrorDescription[] { new ErrorDescription { Code = 1064, Line = 7, Column = 5, IsWarning = true } } // ); // } [Fact] public void CS1570WRN_XMLParseError() { var text = @" namespace ns { // the following line generates CS1570 /// <summary> returns true if < 5 </summary> // try this instead // /// <summary> returns true if &lt;5 </summary> public class MyClass { public static void Main () { } } } "; CreateCompilationWithMscorlib40AndDocumentationComments(text).VerifyDiagnostics( // (5,35): warning CS1570: XML comment has badly formed XML -- 'An identifier was expected.' // /// <summary> returns true if < 5 </summary> Diagnostic(ErrorCode.WRN_XMLParseError, ""), // (5,35): warning CS1570: XML comment has badly formed XML -- '5' // /// <summary> returns true if < 5 </summary> Diagnostic(ErrorCode.WRN_XMLParseError, " ").WithArguments("5"), // (11,26): warning CS1591: Missing XML comment for publicly visible type or member 'ns.MyClass.Main()' // public static void Main () Diagnostic(ErrorCode.WRN_MissingXMLComment, "Main").WithArguments("ns.MyClass.Main()")); } [Fact] public void CS1571WRN_DuplicateParamTag() { var text = @" /// <summary>help text</summary> public class MyClass { /// <param name='Int1'>Used to indicate status.</param> /// <param name='Char1'>An initial.</param> /// <param name='Int1'>Used to indicate status.</param> // CS1571 public static void MyMethod(int Int1, char Char1) { } /// <summary>help text</summary> public static void Main () { } } "; CreateCompilationWithMscorlib40AndDocumentationComments(text).VerifyDiagnostics( // (7,15): warning CS1571: XML comment has a duplicate param tag for 'Int1' // /// <param name='Int1'>Used to indicate status.</param> // CS1571 Diagnostic(ErrorCode.WRN_DuplicateParamTag, "name='Int1'").WithArguments("Int1")); } [Fact] public void CS1572WRN_UnmatchedParamTag() { var text = @" /// <summary>help text</summary> public class MyClass { /// <param name='Int1'>Used to indicate status.</param> /// <param name='Char1'>Used to indicate status.</param> /// <param name='Char2'>???</param> // CS1572 public static void MyMethod(int Int1, char Char1) { } /// <summary>help text</summary> public static void Main () { } } "; CreateCompilationWithMscorlib40AndDocumentationComments(text).VerifyDiagnostics( // (7,21): warning CS1572: XML comment has a param tag for 'Char2', but there is no parameter by that name // /// <param name='Char2'>???</param> // CS1572 Diagnostic(ErrorCode.WRN_UnmatchedParamTag, "Char2").WithArguments("Char2")); } [Fact] public void CS1573WRN_MissingParamTag() { var text = @" /// <summary> </summary> public class MyClass { /// <param name='Int1'>Used to indicate status.</param> /// enter a comment for Char1? public static void MyMethod(int Int1, char Char1) { } /// <summary> </summary> public static void Main() { } } "; CreateCompilationWithMscorlib40AndDocumentationComments(text).VerifyDiagnostics( // (7,48): warning CS1573: Parameter 'Char1' has no matching param tag in the XML comment for 'MyClass.MyMethod(int, char)' (but other parameters do) // public static void MyMethod(int Int1, char Char1) Diagnostic(ErrorCode.WRN_MissingParamTag, "Char1").WithArguments("Char1", "MyClass.MyMethod(int, char)")); } [Fact] public void CS1574WRN_BadXMLRef() { var text = @" /// <see cref=""D""/> public class C { } "; CreateCompilationWithMscorlib40AndDocumentationComments(text).VerifyDiagnostics( // (2,16): warning CS1574: XML comment has cref attribute 'D' that could not be resolved // /// <see cref="D"/> Diagnostic(ErrorCode.WRN_BadXMLRef, "D").WithArguments("D")); } [Fact] public void CS1580WRN_BadXMLRefParamType() { var text = @" /// <seealso cref=""Test(i)""/> // CS1580 public class MyClass { /// <summary>help text</summary> public static void Main() { } /// <summary>help text</summary> public void Test(int i) { } /// <summary>help text</summary> public void Test(char i) { } } "; CreateCompilationWithMscorlib40AndDocumentationComments(text).VerifyDiagnostics( // (2,20): warning CS1580: Invalid type for parameter 'i' in XML comment cref attribute: 'Test(i)' // /// <seealso cref="Test(i)"/> // CS1580 Diagnostic(ErrorCode.WRN_BadXMLRefParamType, "i").WithArguments("i", "Test(i)"), // (2,20): warning CS1574: XML comment has cref attribute 'Test(i)' that could not be resolved // /// <seealso cref="Test(i)"/> // CS1580 Diagnostic(ErrorCode.WRN_BadXMLRef, "Test(i)").WithArguments("Test(i)")); } [Fact] public void CS1581WRN_BadXMLRefReturnType() { var text = @" /// <summary>help text</summary> public class MyClass { /// <summary>help text</summary> public static void Main() { } /// <summary>help text</summary> public static explicit operator int(MyClass f) { return 0; } } /// <seealso cref=""MyClass.explicit operator intt(MyClass)""/> // CS1581 public class MyClass2 { } "; CreateCompilationWithMscorlib40AndDocumentationComments(text).VerifyDiagnostics( // (15,20): warning CS1581: Invalid return type in XML comment cref attribute // /// <seealso cref="MyClass.explicit operator intt(MyClass)"/> // CS1581 Diagnostic(ErrorCode.WRN_BadXMLRefReturnType, "intt").WithArguments("intt", "MyClass.explicit operator intt(MyClass)"), // (15,20): warning CS1574: XML comment has cref attribute 'MyClass.explicit operator intt(MyClass)' that could not be resolved // /// <seealso cref="MyClass.explicit operator intt(MyClass)"/> // CS1581 Diagnostic(ErrorCode.WRN_BadXMLRef, "MyClass.explicit operator intt(MyClass)").WithArguments("explicit operator intt(MyClass)")); } [Fact] public void CS1584WRN_BadXMLRefSyntax() { var text = @" /// public class MyClass1 { /// public static MyClass1 operator /(MyClass1 a1, MyClass1 a2) { return null; } /// <seealso cref=""MyClass1.operator@""/> public static void Main() { } } "; CreateCompilationWithMscorlib40AndDocumentationComments(text).VerifyDiagnostics( // (10,24): warning CS1584: XML comment has syntactically incorrect cref attribute 'MyClass1.operator@' // /// <seealso cref="MyClass1.operator@"/> Diagnostic(ErrorCode.WRN_BadXMLRefSyntax, "MyClass1.operator").WithArguments("MyClass1.operator@"), // (10,41): warning CS1658: Overloadable operator expected. See also error CS1037. // /// <seealso cref="MyClass1.operator@"/> Diagnostic(ErrorCode.WRN_ErrorOverride, "@").WithArguments("Overloadable operator expected", "1037"), // (10,41): error CS1646: Keyword, identifier, or string expected after verbatim specifier: @ // /// <seealso cref="MyClass1.operator@"/> Diagnostic(ErrorCode.ERR_ExpectedVerbatimLiteral, "")); } [Fact] public void CS1587WRN_UnprocessedXMLComment() { var text = @" /// <summary>test</summary> // CS1587, tag not allowed on namespace namespace MySpace { class MyClass { public static void Main() { } } } "; CreateCompilationWithMscorlib40AndDocumentationComments(text). VerifyDiagnostics(Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/")); } [Fact] public void CS1589WRN_NoResolver() { var text = @" /// <include file='CS1589.doc' path='MyDocs/MyMembers[@name=""test""]/' /> // CS1589 class Test { public static void Main() { } } "; var c = CreateCompilation( new[] { Parse(text, options: TestOptions.RegularWithDocumentationComments) }, options: TestOptions.ReleaseDll.WithXmlReferenceResolver(null)); c.VerifyDiagnostics( // (2,5): warning CS1589: Unable to include XML fragment 'MyDocs/MyMembers[@name="test"]/' of file 'CS1589.doc' -- References to XML documents are not supported. // /// <include file='CS1589.doc' path='MyDocs/MyMembers[@name="test"]/' /> // CS1589 Diagnostic(ErrorCode.WRN_FailedInclude, @"<include file='CS1589.doc' path='MyDocs/MyMembers[@name=""test""]/' />"). WithArguments("CS1589.doc", @"MyDocs/MyMembers[@name=""test""]/", "References to XML documents are not supported.")); } [Fact] public void CS1589WRN_FailedInclude() { var text = @" /// <include file='CS1589.doc' path='MyDocs/MyMembers[@name=""test""]/' /> // CS1589 class Test { public static void Main() { } } "; CreateCompilationWithMscorlib40AndDocumentationComments(text).VerifyDiagnostics( // (2,5): warning CS1589: Unable to include XML fragment 'MyDocs/MyMembers[@name="test"]/' of file 'CS1589.doc' -- Unable to find the specified file. // /// <include file='CS1589.doc' path='MyDocs/MyMembers[@name="test"]/' /> // CS1589 Diagnostic(ErrorCode.WRN_FailedInclude, @"<include file='CS1589.doc' path='MyDocs/MyMembers[@name=""test""]/' />"). WithArguments("CS1589.doc", @"MyDocs/MyMembers[@name=""test""]/", "File not found.")); } [Fact] public void CS1590WRN_InvalidInclude() { var text = @" /// <include path='MyDocs/MyMembers[@name=""test""]/*' /> // CS1590 class Test { public static void Main() { } } "; CreateCompilationWithMscorlib40AndDocumentationComments(text).VerifyDiagnostics( // (2,5): warning CS1590: Invalid XML include element -- Missing file attribute // /// <include path='MyDocs/MyMembers[@name="test"]/*' /> // CS1590 Diagnostic(ErrorCode.WRN_InvalidInclude, @"<include path='MyDocs/MyMembers[@name=""test""]/*' />").WithArguments("Missing file attribute")); } [Fact] public void CS1591WRN_MissingXMLComment() { var text = @" /// text public class Test { // /// text public static void Main() // CS1591 { } } "; CreateCompilationWithMscorlib40AndDocumentationComments(text).VerifyDiagnostics( // (6,23): warning CS1591: Missing XML comment for publicly visible type or member 'Test.Main()' // public static void Main() // CS1591 Diagnostic(ErrorCode.WRN_MissingXMLComment, "Main").WithArguments("Test.Main()")); } [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/18610")] public void CS1592WRN_XMLParseIncludeError() { var xmlFile = Temp.CreateFile(extension: ".xml").WriteAllText("&"); var sourceTemplate = @" /// <include file='{0}' path='element'/> public class Test {{ }} "; var comp = CreateCompilationWithMscorlib40AndDocumentationComments(string.Format(sourceTemplate, xmlFile.Path)); using (new EnsureEnglishUICulture()) { comp.VerifyDiagnostics( // dcf98d2ac30a.xml(1,1): warning CS1592: Badly formed XML in included comments file -- 'Data at the root level is invalid.' Diagnostic(ErrorCode.WRN_XMLParseIncludeError).WithArguments("Data at the root level is invalid.")); } } [Fact] public void CS1658WRN_ErrorOverride() { var text = @" /// <seealso cref=""""/> public class Test { /// public static int Main() { return 0; } } "; CreateCompilationWithMscorlib40AndDocumentationComments(text).VerifyDiagnostics( // (2,20): warning CS1584: XML comment has syntactically incorrect cref attribute '' // /// <seealso cref=""/> Diagnostic(ErrorCode.WRN_BadXMLRefSyntax, @"""").WithArguments(""), // (2,20): warning CS1658: Identifier expected. See also error CS1001. // /// <seealso cref=""/> Diagnostic(ErrorCode.WRN_ErrorOverride, @"""").WithArguments("Identifier expected", "1001")); } // TODO (tomat): Also fix AttributeTests.DllImport_AttributeRedefinition [Fact(Skip = "530377"), WorkItem(530377, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530377"), WorkItem(685159, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/685159")] public void CS1685WRN_MultiplePredefTypes() { var text = @" public static class C { public static void Extension(this int X) {} }"; // include both mscorlib 4.0 and System.Core 3.5, both of which contain ExtensionAttribute // These libraries are not yet in our suite CreateEmptyCompilation(text). VerifyDiagnostics(Diagnostic(ErrorCode.WRN_MultiplePredefTypes, "")); } [Fact, WorkItem(530379, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530379")] public void CS1690WRN_CallOnNonAgileField() { var text = @" using System; class WarningCS1690 : MarshalByRefObject { int i = 5; public static void Main() { WarningCS1690 e = new WarningCS1690(); e.i.ToString(); // CS1690 int i = e.i; i.ToString(); e.i = i; } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.WRN_CallOnNonAgileField, Line = 11, Column = 9, IsWarning = true } }); } [Fact, WorkItem(530379, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530379")] public void CS1690WRN_CallOnNonAgileField_Variations() { var text = @" using System; struct S { public event Action Event; public int Field; public int Property { get; set; } public int this[int x] { get { return 0; } set { } } public void M() { } class WarningCS1690 : MarshalByRefObject { S s; public static void Main() { WarningCS1690 w = new WarningCS1690(); w.s.Event = null; w.s.Event += null; w.s.Property++; w.s[0]++; w.s.M(); Action a = w.s.M; } } } "; CreateCompilation(text).VerifyDiagnostics( // (19,13): warning CS1690: Accessing a member on 'S.WarningCS1690.s' may cause a runtime exception because it is a field of a marshal-by-reference class // w.s.Event = null; Diagnostic(ErrorCode.WRN_CallOnNonAgileField, "w.s").WithArguments("S.WarningCS1690.s"), // (20,13): warning CS1690: Accessing a member on 'S.WarningCS1690.s' may cause a runtime exception because it is a field of a marshal-by-reference class // w.s.Event += null; Diagnostic(ErrorCode.WRN_CallOnNonAgileField, "w.s").WithArguments("S.WarningCS1690.s"), // (21,13): warning CS1690: Accessing a member on 'S.WarningCS1690.s' may cause a runtime exception because it is a field of a marshal-by-reference class // w.s.Property++; Diagnostic(ErrorCode.WRN_CallOnNonAgileField, "w.s").WithArguments("S.WarningCS1690.s"), // (22,13): warning CS1690: Accessing a member on 'S.WarningCS1690.s' may cause a runtime exception because it is a field of a marshal-by-reference class // w.s[0]++; Diagnostic(ErrorCode.WRN_CallOnNonAgileField, "w.s").WithArguments("S.WarningCS1690.s"), // (23,13): warning CS1690: Accessing a member on 'S.WarningCS1690.s' may cause a runtime exception because it is a field of a marshal-by-reference class // w.s.M(); Diagnostic(ErrorCode.WRN_CallOnNonAgileField, "w.s").WithArguments("S.WarningCS1690.s"), // (24,24): warning CS1690: Accessing a member on 'S.WarningCS1690.s' may cause a runtime exception because it is a field of a marshal-by-reference class // Action a = w.s.M; Diagnostic(ErrorCode.WRN_CallOnNonAgileField, "w.s").WithArguments("S.WarningCS1690.s"), // (7,16): warning CS0649: Field 'S.Field' is never assigned to, and will always have its default value 0 // public int Field; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "Field").WithArguments("S.Field", "0"), // (6,25): warning CS0414: The field 'S.Event' is assigned but its value is never used // public event Action Event; Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "Event").WithArguments("S.Event")); } [Fact, WorkItem(530379, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530379")] public void CS1690WRN_CallOnNonAgileField_Class() { var text = @" using System; class S { public event Action Event; public int Field; public int Property { get; set; } public int this[int x] { get { return 0; } set { } } public void M() { } class WarningCS1690 : MarshalByRefObject { S s; public static void Main() { WarningCS1690 w = new WarningCS1690(); w.s.Event = null; w.s.Event += null; w.s.Property++; w.s[0]++; w.s.M(); Action a = w.s.M; } } } "; CreateCompilation(text).VerifyDiagnostics( // (14,11): warning CS0649: Field 'S.WarningCS1690.s' is never assigned to, and will always have its default value null // S s; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "s").WithArguments("S.WarningCS1690.s", "null"), // (7,16): warning CS0649: Field 'S.Field' is never assigned to, and will always have its default value 0 // public int Field; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "Field").WithArguments("S.Field", "0"), // (6,25): warning CS0414: The field 'S.Event' is assigned but its value is never used // public event Action Event; Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "Event").WithArguments("S.Event")); } // [Fact()] // public void CS1707WRN_DelegateNewMethBind() // { // var text = @" //"; // DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, // new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.WRN_DelegateNewMethBind, Line = 7, Column = 5, IsWarning = true } } // ); // } [Fact(), WorkItem(530384, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530384")] public void CS1709WRN_EmptyFileName() { var text = @" class Test { static void Main() { #pragma checksum """" ""{406EA660-64CF-4C82-B6F0-42D48172A799}"" """" // CS1709 } } "; //EDMAURER no longer giving this low-value warning. CreateCompilation(text). VerifyDiagnostics(); //VerifyDiagnostics(Diagnostic(ErrorCode.WRN_EmptyFileName, @"""")); } [Fact] public void CS1710WRN_DuplicateTypeParamTag() { var text = @" class Stack<ItemType> { } /// <typeparam name=""MyType"">can be an int</typeparam> /// <typeparam name=""MyType"">can be an int</typeparam> class MyStackWrapper<MyType> { // Open constructed type Stack<MyType>. Stack<MyType> stack; public MyStackWrapper(Stack<MyType> s) { stack = s; } } class CMain { public static void Main() { } } "; CreateCompilationWithMscorlib40AndDocumentationComments(text).VerifyDiagnostics( // (6,16): warning CS1710: XML comment has a duplicate typeparam tag for 'MyType' // /// <typeparam name="MyType">can be an int</typeparam> Diagnostic(ErrorCode.WRN_DuplicateTypeParamTag, @"name=""MyType""").WithArguments("MyType")); } [Fact] public void CS1711WRN_UnmatchedTypeParamTag() { var text = @" ///<typeparam name=""WrongName"">can be an int</typeparam> class CMain { public static void Main() { } } "; CreateCompilationWithMscorlib40AndDocumentationComments(text).VerifyDiagnostics( // (2,21): warning CS1711: XML comment has a typeparam tag for 'WrongName', but there is no type parameter by that name // ///<typeparam name="WrongName">can be an int</typeparam> Diagnostic(ErrorCode.WRN_UnmatchedTypeParamTag, "WrongName").WithArguments("WrongName")); } [Fact] public void CS1712WRN_MissingTypeParamTag() { var text = @" ///<summary>A generic list delegate.</summary> ///<typeparam name=""T"">The first type stored by the list.</typeparam> public delegate void List<T,W>(); /// public class Test { /// public static void Main() { } } "; CreateCompilationWithMscorlib40AndDocumentationComments(text).VerifyDiagnostics( // (4,29): warning CS1712: Type parameter 'W' has no matching typeparam tag in the XML comment on 'List<T, W>' (but other type parameters do) // public delegate void List<T,W>(); Diagnostic(ErrorCode.WRN_MissingTypeParamTag, "W").WithArguments("W", "List<T, W>")); } [Fact] public void CS1717WRN_AssignmentToSelf() { var text = @" public class Test { public static void Main() { int x = 0; x = x; // CS1717 } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.WRN_AssignmentToSelf, Line = 7, Column = 7, IsWarning = true } }); } [WorkItem(543470, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543470")] [Fact] public void CS1717WRN_AssignmentToSelf02() { var text = @" class C { void M(object p) { object oValue = p; if (oValue is int) { //(SQL 9.0) 653716 + common sense oValue = (double) ((int) oValue); } } }"; CreateCompilation(text).VerifyDiagnostics(); } [Fact] public void CS1717WRN_AssignmentToSelf03() { var text = @" using System; class Program { int f; event Action e; void Test(int p) { int l = 0; l = l; p = p; f = f; e = e; } } "; CreateCompilation(text).VerifyDiagnostics( // (13,9): warning CS1717: Assignment made to same variable; did you mean to assign something else? // l = l; Diagnostic(ErrorCode.WRN_AssignmentToSelf, "l = l"), // (14,9): warning CS1717: Assignment made to same variable; did you mean to assign something else? // p = p; Diagnostic(ErrorCode.WRN_AssignmentToSelf, "p = p"), // (15,9): warning CS1717: Assignment made to same variable; did you mean to assign something else? // f = f; Diagnostic(ErrorCode.WRN_AssignmentToSelf, "f = f"), // (16,9): warning CS1717: Assignment made to same variable; did you mean to assign something else? // e = e; Diagnostic(ErrorCode.WRN_AssignmentToSelf, "e = e")); } [Fact] public void CS1717WRN_AssignmentToSelf04() { var text = @" using System; class Program { int f; event Action e; static int sf; static event Action se; void Test(Program other) { f = this.f; e = this.e; f = other.f; //fine e = other.e; //fine sf = sf; se = se; sf = Program.sf; se = Program.se; } } "; CreateCompilation(text).VerifyDiagnostics( // (14,9): warning CS1717: Assignment made to same variable; did you mean to assign something else? // f = this.f; Diagnostic(ErrorCode.WRN_AssignmentToSelf, "f = this.f"), // (15,9): warning CS1717: Assignment made to same variable; did you mean to assign something else? // e = this.e; Diagnostic(ErrorCode.WRN_AssignmentToSelf, "e = this.e"), // (20,9): warning CS1717: Assignment made to same variable; did you mean to assign something else? // sf = sf; Diagnostic(ErrorCode.WRN_AssignmentToSelf, "sf = sf"), // (21,9): warning CS1717: Assignment made to same variable; did you mean to assign something else? // se = se; Diagnostic(ErrorCode.WRN_AssignmentToSelf, "se = se"), // (23,9): warning CS1717: Assignment made to same variable; did you mean to assign something else? // sf = Program.sf; Diagnostic(ErrorCode.WRN_AssignmentToSelf, "sf = Program.sf"), // (24,9): warning CS1717: Assignment made to same variable; did you mean to assign something else? // se = Program.se; Diagnostic(ErrorCode.WRN_AssignmentToSelf, "se = Program.se")); } [Fact] public void CS1717WRN_AssignmentToSelf05() { var text = @" using System.Linq; class Program { static void Main(string[] args) { var unused = from x in args select x = x; } } "; // CONSIDER: dev11 reports WRN_AssignmentToSelf. CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics( // (8,44): error CS1947: Range variable 'x' cannot be assigned to -- it is read only // var unused = from x in args select x = x; Diagnostic(ErrorCode.ERR_QueryRangeVariableReadOnly, "x").WithArguments("x")); } [Fact] public void CS1717WRN_AssignmentToSelf06() { var text = @" class C { void M( byte b, sbyte sb, short s, ushort us, int i, uint ui, long l, ulong ul, float f, double d, decimal m, bool bo, object o, C cl, S st) { b = (byte)b; sb = (sbyte)sb; s = (short)s; us = (ushort)us; i = (int)i; ui = (uint)ui; l = (long)l; ul = (ulong)ul; f = (float)f; // Not reported by dev11. d = (double)d; // Not reported by dev11. m = (decimal)m; bo = (bool)bo; o = (object)o; cl = (C)cl; st = (S)st; } } struct S { } "; // CONSIDER: dev11 does not strip off float or double identity-conversions and, thus, // does not warn about those assignments. CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics( // (21,9): warning CS1717: Assignment made to same variable; did you mean to assign something else? // b = (byte)b; Diagnostic(ErrorCode.WRN_AssignmentToSelf, "b = (byte)b"), // (22,9): warning CS1717: Assignment made to same variable; did you mean to assign something else? // sb = (sbyte)sb; Diagnostic(ErrorCode.WRN_AssignmentToSelf, "sb = (sbyte)sb"), // (23,9): warning CS1717: Assignment made to same variable; did you mean to assign something else? // s = (short)s; Diagnostic(ErrorCode.WRN_AssignmentToSelf, "s = (short)s"), // (24,9): warning CS1717: Assignment made to same variable; did you mean to assign something else? // us = (ushort)us; Diagnostic(ErrorCode.WRN_AssignmentToSelf, "us = (ushort)us"), // (25,9): warning CS1717: Assignment made to same variable; did you mean to assign something else? // i = (int)i; Diagnostic(ErrorCode.WRN_AssignmentToSelf, "i = (int)i"), // (26,9): warning CS1717: Assignment made to same variable; did you mean to assign something else? // ui = (uint)ui; Diagnostic(ErrorCode.WRN_AssignmentToSelf, "ui = (uint)ui"), // (27,9): warning CS1717: Assignment made to same variable; did you mean to assign something else? // l = (long)l; Diagnostic(ErrorCode.WRN_AssignmentToSelf, "l = (long)l"), // (28,9): warning CS1717: Assignment made to same variable; did you mean to assign something else? // ul = (ulong)ul; Diagnostic(ErrorCode.WRN_AssignmentToSelf, "ul = (ulong)ul"), // (29,9): warning CS1717: Assignment made to same variable; did you mean to assign something else? // f = (float)f; // Not reported by dev11. Diagnostic(ErrorCode.WRN_AssignmentToSelf, "f = (float)f"), // (30,9): warning CS1717: Assignment made to same variable; did you mean to assign something else? // d = (double)d; // Not reported by dev11. Diagnostic(ErrorCode.WRN_AssignmentToSelf, "d = (double)d"), // (31,9): warning CS1717: Assignment made to same variable; did you mean to assign something else? // m = (decimal)m; Diagnostic(ErrorCode.WRN_AssignmentToSelf, "m = (decimal)m"), // (32,9): warning CS1717: Assignment made to same variable; did you mean to assign something else? // bo = (bool)bo; Diagnostic(ErrorCode.WRN_AssignmentToSelf, "bo = (bool)bo"), // (33,9): warning CS1717: Assignment made to same variable; did you mean to assign something else? // o = (object)o; Diagnostic(ErrorCode.WRN_AssignmentToSelf, "o = (object)o"), // (34,9): warning CS1717: Assignment made to same variable; did you mean to assign something else? // cl = (C)cl; Diagnostic(ErrorCode.WRN_AssignmentToSelf, "cl = (C)cl"), // (35,9): warning CS1717: Assignment made to same variable; did you mean to assign something else? // st = (S)st; Diagnostic(ErrorCode.WRN_AssignmentToSelf, "st = (S)st")); } [Fact, WorkItem(546493, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546493")] public void CS1718WRN_ComparisonToSelf() { var text = @" class Tester { static int j = 123; static void Main() { int i = 0; if (i == i) i++; if (j == Tester.j) j++; } } "; CreateCompilation(text).VerifyDiagnostics( // (8,13): warning CS1718: Comparison made to same variable; did you mean to compare something else? // if (i == i) i++; Diagnostic(ErrorCode.WRN_ComparisonToSelf, "i == i"), // (9,13): warning CS1718: Comparison made to same variable; did you mean to compare something else? // if (j == Tester.j) j++; Diagnostic(ErrorCode.WRN_ComparisonToSelf, "j == Tester.j")); } [Fact, WorkItem(580501, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/580501")] public void CS1718WRN_ComparisonToSelf2() { var text = @" using System.Linq; class Tester { static void Main() { var q = from int x1 in new[] { 2, 9, 1, 8, } where x1 > x1 // CS1718 select x1; } } "; CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics( // (8,15): warning CS1718: Comparison made to same variable; did you mean to compare something else? // where x1 > x1 // CS1718 Diagnostic(ErrorCode.WRN_ComparisonToSelf, "x1 > x1")); } [Fact] public void CS1720WRN_DotOnDefault01() { var source = @"class A { internal object P { get; set; } } interface I { object P { get; set; } } static class C { static void M<T1, T2, T3, T4, T5, T6, T7>() where T2 : new() where T3 : struct where T4 : class where T5 : T1 where T6 : A where T7 : I { default(int).GetHashCode(); default(object).GetHashCode(); default(T1).GetHashCode(); default(T2).GetHashCode(); default(T3).GetHashCode(); default(T4).GetHashCode(); default(T5).GetHashCode(); default(T6).GetHashCode(); default(T7).GetHashCode(); default(T6).P = null; default(T7).P = null; default(int).E(); default(object).E(); default(T1).E(); default(T2).E(); default(T3).E(); default(T4).E(); default(T5).E(); default(T6).E(); // Dev10 (incorrectly) reports CS1720 default(T7).E(); } static void E(this object o) { } }"; CreateCompilationWithMscorlib40(source, references: new[] { Net40.SystemCore }, parseOptions: TestOptions.Regular7_3).VerifyDiagnostics( // (20,9): warning CS1720: Expression will always cause a System.NullReferenceException because the default value of 'object' is null // default(object).GetHashCode(); Diagnostic(ErrorCode.WRN_DotOnDefault, "default(object).GetHashCode").WithArguments("object").WithLocation(20, 9), // (24,9): warning CS1720: Expression will always cause a System.NullReferenceException because the default value of 'T4' is null // default(T4).GetHashCode(); Diagnostic(ErrorCode.WRN_DotOnDefault, "default(T4).GetHashCode").WithArguments("T4").WithLocation(24, 9), // (26,9): warning CS1720: Expression will always cause a System.NullReferenceException because the default value of 'T6' is null // default(T6).GetHashCode(); Diagnostic(ErrorCode.WRN_DotOnDefault, "default(T6).GetHashCode").WithArguments("T6").WithLocation(26, 9), // (28,9): warning CS1720: Expression will always cause a System.NullReferenceException because the default value of 'T6' is null // default(T6).P = null; Diagnostic(ErrorCode.WRN_DotOnDefault, "default(T6).P").WithArguments("T6").WithLocation(28, 9)); CreateCompilationWithMscorlib40(source, references: new[] { Net40.SystemCore }, options: TestOptions.ReleaseDll.WithNullableContextOptions(NullableContextOptions.Disable)).VerifyDiagnostics( ); } [Fact] public void CS1720WRN_DotOnDefault02() { var source = @"class A { internal object this[object index] { get { return null; } set { } } } struct S { internal object this[object index] { get { return null; } set { } } } interface I { object this[object index] { get; set; } } class C { unsafe static void M<T1, T2, T3, T4>() where T1 : A where T2 : I where T3 : struct, I where T4 : class, I { object o; o = default(int*)[0]; o = default(A)[0]; o = default(S)[0]; o = default(I)[0]; o = default(object[])[0]; o = default(T1)[0]; o = default(T2)[0]; o = default(T3)[0]; o = default(T4)[0]; default(int*)[1] = 1; default(A)[1] = o; default(I)[1] = o; default(object[])[1] = o; default(T1)[1] = o; default(T2)[1] = o; default(T3)[1] = o; default(T4)[1] = o; } }"; CreateCompilation(source, options: TestOptions.UnsafeReleaseDll, parseOptions: TestOptions.Regular7_3).VerifyDiagnostics( // (23,13): warning CS1720: Expression will always cause a System.NullReferenceException because the default value of 'A' is null Diagnostic(ErrorCode.WRN_DotOnDefault, "default(A)[0]").WithArguments("A").WithLocation(23, 13), // (25,13): warning CS1720: Expression will always cause a System.NullReferenceException because the default value of 'I' is null Diagnostic(ErrorCode.WRN_DotOnDefault, "default(I)[0]").WithArguments("I").WithLocation(25, 13), // (26,13): warning CS1720: Expression will always cause a System.NullReferenceException because the default value of 'object[]' is null Diagnostic(ErrorCode.WRN_DotOnDefault, "default(object[])[0]").WithArguments("object[]").WithLocation(26, 13), // (27,13): warning CS1720: Expression will always cause a System.NullReferenceException because the default value of 'T1' is null Diagnostic(ErrorCode.WRN_DotOnDefault, "default(T1)[0]").WithArguments("T1").WithLocation(27, 13), // (30,13): warning CS1720: Expression will always cause a System.NullReferenceException because the default value of 'T4' is null Diagnostic(ErrorCode.WRN_DotOnDefault, "default(T4)[0]").WithArguments("T4").WithLocation(30, 13), // (32,9): warning CS1720: Expression will always cause a System.NullReferenceException because the default value of 'A' is null Diagnostic(ErrorCode.WRN_DotOnDefault, "default(A)[1]").WithArguments("A").WithLocation(32, 9), // (33,9): warning CS1720: Expression will always cause a System.NullReferenceException because the default value of 'I' is null Diagnostic(ErrorCode.WRN_DotOnDefault, "default(I)[1]").WithArguments("I").WithLocation(33, 9), // (34,9): warning CS1720: Expression will always cause a System.NullReferenceException because the default value of 'object[]' is null Diagnostic(ErrorCode.WRN_DotOnDefault, "default(object[])[1]").WithArguments("object[]").WithLocation(34, 9), // (35,9): warning CS1720: Expression will always cause a System.NullReferenceException because the default value of 'T1' is null Diagnostic(ErrorCode.WRN_DotOnDefault, "default(T1)[1]").WithArguments("T1").WithLocation(35, 9), // (37,9): error CS0131: The left-hand side of an assignment must be a variable, property or indexer Diagnostic(ErrorCode.ERR_AssgLvalueExpected, "default(T3)[1]").WithLocation(37, 9), // Incorrect? See CS0131ERR_AssgLvalueExpected03 unit test. // (38,9): warning CS1720: Expression will always cause a System.NullReferenceException because the default value of 'T4' is null Diagnostic(ErrorCode.WRN_DotOnDefault, "default(T4)[1]").WithArguments("T4").WithLocation(38, 9)); CreateCompilation(source, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (37,9): error CS0131: The left-hand side of an assignment must be a variable, property or indexer // default(T3)[1] = o; Diagnostic(ErrorCode.ERR_AssgLvalueExpected, "default(T3)[1]").WithLocation(37, 9)); } [Fact] public void CS1720WRN_DotOnDefault03() { var source = @"static class A { static void Main() { System.Console.WriteLine(default(string).IsNull()); } internal static bool IsNull(this string val) { return (object)val == null; } } "; CompileAndVerifyWithMscorlib40(source, expectedOutput: "True", references: new[] { Net40.SystemCore }, parseOptions: TestOptions.Regular7_3).VerifyDiagnostics( // Do not report the following warning: // (5,34): warning CS1720: Expression will always cause a System.NullReferenceException because the default value of 'string' is null // System.Console.WriteLine(default(string).IsNull()); // Diagnostic(ErrorCode.WRN_DotOnDefault, "default(string).IsNull").WithArguments("string").WithLocation(5, 34) ); CompileAndVerifyWithMscorlib40(source, expectedOutput: "True", references: new[] { Net40.SystemCore }).VerifyDiagnostics(); } [Fact] public void CS1723WRN_BadXMLRefTypeVar() { var text = @" ///<summary>A generic list class.</summary> ///<see cref=""T"" /> // CS1723 public class List<T> { } "; CreateCompilationWithMscorlib40AndDocumentationComments(text).VerifyDiagnostics( // (3,15): warning CS1723: XML comment has cref attribute 'T' that refers to a type parameter // ///<see cref="T" /> // CS1723 Diagnostic(ErrorCode.WRN_BadXMLRefTypeVar, "T").WithArguments("T")); } [Fact] public void CS1974WRN_DynamicDispatchToConditionalMethod() { var text = @" using System.Diagnostics; class Myclass { static void Main() { dynamic d = null; // Warning because Goo might be conditional. Goo(d); // No warning; only the two-parameter Bar is conditional. Bar(d); } [Conditional(""DEBUG"")] static void Goo(string d) {} [Conditional(""DEBUG"")] static void Bar(int x, int y) {} static void Bar(string x) {} }"; var comp = CreateCompilationWithMscorlib40AndSystemCore(text); comp.VerifyDiagnostics( // (9,9): warning CS1974: The dynamically dispatched call to method 'Goo' may fail at runtime because one or more applicable overloads are conditional methods. // Goo(d); Diagnostic(ErrorCode.WRN_DynamicDispatchToConditionalMethod, "Goo(d)").WithArguments("Goo")); } [Fact] public void CS1981WRN_IsDynamicIsConfusing() { var text = @" public class D : C { } public class C { public static int Main() { // is dynamic bool bi = 123 is dynamic; // dynamicType is valueType dynamic i2 = 123; bi = i2 is int; // dynamicType is refType dynamic c = new D(); bi = c is C; dynamic c2 = new C(); bi = c is C; // valueType as dynamic int i = 123 as dynamic; // refType as dynamic dynamic c3 = new D() as dynamic; // dynamicType as dynamic dynamic s = ""asd""; string s2 = s as dynamic; // default(dynamic) dynamic d = default(dynamic); // dynamicType as valueType : generate error int k = i2 as int; // dynamicType as refType C c4 = c3 as C; return 0; } }"; CreateCompilation(text).VerifyDiagnostics( // (7,19): 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 Diagnostic(ErrorCode.WRN_IsDynamicIsConfusing, "123 is dynamic").WithArguments("is", "dynamic", "Object"), // (7,19): warning CS0183: The given expression is always of the provided ('dynamic') type Diagnostic(ErrorCode.WRN_IsAlwaysTrue, "123 is dynamic").WithArguments("dynamic"), // (27,17): error CS0077: The as operator must be used with a reference type // or nullable type ('int' is a non-nullable value type) Diagnostic(ErrorCode.ERR_AsMustHaveReferenceType, "i2 as int").WithArguments("int"), // (26,17): warning CS0219: The variable 'd' is assigned but its value is never used Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "d").WithArguments("d")); } [Fact] public void CS7003ERR_UnexpectedUnboundGenericName() { var text = @" class C<T> { void M(System.Type t) { M(typeof(C<C<>>)); //unbound inside bound M(typeof(C<>[])); //array of unbound M(typeof(C<>.D<int>)); //unbound containing bound M(typeof(C<int>.D<>)); //bound containing unbound M(typeof(D<,>[])); //multiple type parameters } class D<U> { } } class D<T, U> {}"; // NOTE: Dev10 reports CS1031 (type expected) - CS7003 is new. CreateCompilation(text).VerifyDiagnostics( // (6,20): error CS7003: Unexpected use of an unbound generic name Diagnostic(ErrorCode.ERR_UnexpectedUnboundGenericName, "C<>"), // (7,18): error CS7003: Unexpected use of an unbound generic name Diagnostic(ErrorCode.ERR_UnexpectedUnboundGenericName, "C<>"), // (8,18): error CS7003: Unexpected use of an unbound generic name Diagnostic(ErrorCode.ERR_UnexpectedUnboundGenericName, "C<>"), // (9,25): error CS7003: Unexpected use of an unbound generic name Diagnostic(ErrorCode.ERR_UnexpectedUnboundGenericName, "D<>"), // (10,18): error CS7003: Unexpected use of an unbound generic name Diagnostic(ErrorCode.ERR_UnexpectedUnboundGenericName, "D<,>")); } [Fact] public void CS7003ERR_UnexpectedUnboundGenericName_Nested() { var text = @" class Outer<T> { public static void Print() { System.Console.WriteLine(typeof(Inner<>)); System.Console.WriteLine(typeof(Inner<T>)); System.Console.WriteLine(typeof(Inner<int>)); System.Console.WriteLine(typeof(Outer<>.Inner<>)); System.Console.WriteLine(typeof(Outer<>.Inner<T>)); //CS7003 System.Console.WriteLine(typeof(Outer<>.Inner<int>)); //CS7003 System.Console.WriteLine(typeof(Outer<T>.Inner<>)); //CS7003 System.Console.WriteLine(typeof(Outer<T>.Inner<T>)); System.Console.WriteLine(typeof(Outer<T>.Inner<int>)); System.Console.WriteLine(typeof(Outer<int>.Inner<>)); //CS7003 System.Console.WriteLine(typeof(Outer<int>.Inner<T>)); System.Console.WriteLine(typeof(Outer<int>.Inner<int>)); } class Inner<U> { } }"; // NOTE: Dev10 reports CS1031 (type expected) - CS7003 is new. CreateCompilation(text).VerifyDiagnostics( // (11,41): error CS7003: Unexpected use of an unbound generic name Diagnostic(ErrorCode.ERR_UnexpectedUnboundGenericName, "Outer<>"), // (12,41): error CS7003: Unexpected use of an unbound generic name Diagnostic(ErrorCode.ERR_UnexpectedUnboundGenericName, "Outer<>"), // (14,50): error CS7003: Unexpected use of an unbound generic name Diagnostic(ErrorCode.ERR_UnexpectedUnboundGenericName, "Inner<>"), // (18,52): error CS7003: Unexpected use of an unbound generic name Diagnostic(ErrorCode.ERR_UnexpectedUnboundGenericName, "Inner<>")); } [Fact(), WorkItem(529583, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529583")] public void CS7003ERR_UnexpectedUnboundGenericName_Attributes() { var text = @" using System; class Outer<T> { public class Inner<U> { } } [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] class Attr : Attribute { public Attr(Type t) { } } [Attr(typeof(Outer<>.Inner<>))] [Attr(typeof(Outer<int>.Inner<>))] [Attr(typeof(Outer<>.Inner<int>))] [Attr(typeof(Outer<int>.Inner<int>))] public class Test { public static void Main() { } }"; // NOTE: Dev10 reports CS1031 (type expected) - CS7003 is new. CreateCompilation(text).VerifyDiagnostics( // (21,25): error CS7003: Unexpected use of an unbound generic name // [Attr(typeof(Outer<int>.Inner<>))] Diagnostic(ErrorCode.ERR_UnexpectedUnboundGenericName, "Inner<>"), // (22,14): error CS7003: Unexpected use of an unbound generic name // [Attr(typeof(Outer<>.Inner<int>))] Diagnostic(ErrorCode.ERR_UnexpectedUnboundGenericName, "Outer<>")); } [Fact] public void CS7013WRN_MetadataNameTooLong() { var text = @" namespace Namespace1.Namespace2 { public interface I<T> { void Goo(); } public class OuterGenericClass<T, S> { public class NestedClass : OuterGenericClass<NestedClass, NestedClass> { } public class C : I<NestedClass.NestedClass.NestedClass.NestedClass.NestedClass> { void I<NestedClass.NestedClass.NestedClass.NestedClass.NestedClass>.Goo() { } } } } "; // This error will necessarily have a very long error string. CreateCompilation(text).VerifyEmitDiagnostics( Diagnostic(ErrorCode.ERR_MetadataNameTooLong, "Goo").WithArguments("Namespace1.Namespace2.I<Namespace1.Namespace2.OuterGenericClass<Namespace1.Namespace2.OuterGenericClass<Namespace1.Namespace2.OuterGenericClass<Namespace1.Namespace2.OuterGenericClass<Namespace1.Namespace2.OuterGenericClass<T,S>.NestedClass,Namespace1.Namespace2.OuterGenericClass<T,S>.NestedClass>.NestedClass,Namespace1.Namespace2.OuterGenericClass<Namespace1.Namespace2.OuterGenericClass<T,S>.NestedClass,Namespace1.Namespace2.OuterGenericClass<T,S>.NestedClass>.NestedClass>.NestedClass,Namespace1.Namespace2.OuterGenericClass<Namespace1.Namespace2.OuterGenericClass<Namespace1.Namespace2.OuterGenericClass<T,S>.NestedClass,Namespace1.Namespace2.OuterGenericClass<T,S>.NestedClass>.NestedClass,Namespace1.Namespace2.OuterGenericClass<Namespace1.Namespace2.OuterGenericClass<T,S>.NestedClass,Namespace1.Namespace2.OuterGenericClass<T,S>.NestedClass>.NestedClass>.NestedClass>.NestedClass,Namespace1.Namespace2.OuterGenericClass<Namespace1.Namespace2.OuterGenericClass<Namespace1.Namespace2.OuterGenericClass<Namespace1.Namespace2.OuterGenericClass<T,S>.NestedClass,Namespace1.Namespace2.OuterGenericClass<T,S>.NestedClass>.NestedClass,Namespace1.Namespace2.OuterGenericClass<Namespace1.Namespace2.OuterGenericClass<T,S>.NestedClass,Namespace1.Namespace2.OuterGenericClass<T,S>.NestedClass>.NestedClass>.NestedClass,Namespace1.Namespace2.OuterGenericClass<Namespace1.Namespace2.OuterGenericClass<Namespace1.Namespace2.OuterGenericClass<T,S>.NestedClass,Namespace1.Namespace2.OuterGenericClass<T,S>.NestedClass>.NestedClass,Namespace1.Namespace2.OuterGenericClass<Namespace1.Namespace2.OuterGenericClass<T,S>.NestedClass,Namespace1.Namespace2.OuterGenericClass<T,S>.NestedClass>.NestedClass>.NestedClass>.NestedClass>.NestedClass>.Goo")); } #endregion #region shotgun tests [Fact] public void DelegateCreationBad() { var text = @" namespace CSSample { class Program { static void Main(string[] args) { } delegate void D1(); delegate void D2(); delegate int D3(int x); static D1 d1; static D2 d2; static D3 d3; internal virtual void V() { } void M() { } static void S() { } static int M2(int x) { return x; } static void F(Program p) { // Error cases d1 = new D1(2 + 2); d1 = new D1(d3); d1 = new D1(2, 3); d1 = new D1(x: 3); d1 = new D1(M2); } } } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (28,25): error CS0149: Method name expected // d1 = new D1(2 + 2); Diagnostic(ErrorCode.ERR_MethodNameExpected, "2 + 2").WithLocation(28, 25), // (29,18): error CS0123: No overload for 'Program.D3.Invoke(int)' matches delegate 'Program.D1' // d1 = new D1(d3); Diagnostic(ErrorCode.ERR_MethDelegateMismatch, "new D1(d3)").WithArguments("CSSample.Program.D3.Invoke(int)", "CSSample.Program.D1").WithLocation(29, 18), // (30,25): error CS0149: Method name expected // d1 = new D1(2, 3); Diagnostic(ErrorCode.ERR_MethodNameExpected, "2, 3").WithLocation(30, 25), // (31,28): error CS0149: Method name expected // d1 = new D1(x: 3); Diagnostic(ErrorCode.ERR_MethodNameExpected, "3").WithLocation(31, 28), // (32,18): error CS0123: No overload for 'M2' matches delegate 'Program.D1' // d1 = new D1(M2); Diagnostic(ErrorCode.ERR_MethDelegateMismatch, "new D1(M2)").WithArguments("M2", "CSSample.Program.D1").WithLocation(32, 18), // (16,19): warning CS0169: The field 'Program.d2' is never used // static D2 d2; Diagnostic(ErrorCode.WRN_UnreferencedField, "d2").WithArguments("CSSample.Program.d2").WithLocation(16, 19), // (17,19): warning CS0649: Field 'Program.d3' is never assigned to, and will always have its default value null // static D3 d3; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "d3").WithArguments("CSSample.Program.d3", "null").WithLocation(17, 19)); } [Fact, WorkItem(7359, "https://github.com/dotnet/roslyn/issues/7359")] public void DelegateCreationWithRefOut() { var source = @" using System; public class Program { static Func<T, T> Goo<T>(Func<T, T> t) { return t; } static Func<string, string> Bar = Goo<string>(x => x); static Func<string, string> BarP => Goo<string>(x => x); static T Id<T>(T id) => id; static void Test(Func<string, string> Baz) { var k = Bar; var z1 = new Func<string, string>(ref Bar); // compat var z2 = new Func<string, string>(ref Baz); // compat var z3 = new Func<string, string>(ref k); // compat var z4 = new Func<string, string>(ref x => x); var z5 = new Func<string, string>(ref Goo<string>(x => x)); var z6 = new Func<string, string>(ref BarP); var z7 = new Func<string, string>(ref new Func<string, string>(x => x)); var z8 = new Func<string, string>(ref Program.BarP); var z9 = new Func<string, string>(ref Program.Goo<string>(x => x)); var z10 = new Func<string, string>(ref Id); // compat var z11 = new Func<string, string>(ref new(x => x)); } }"; CreateCompilation(source).VerifyDiagnostics( // (16,47): error CS1510: A ref or out argument must be an assignable variable // var z4 = new Func<string, string>(ref x => x); Diagnostic(ErrorCode.ERR_RefLvalueExpected, "x => x").WithLocation(16, 47), // (17,47): error CS1510: A ref or out argument must be an assignable variable // var z5 = new Func<string, string>(ref Goo<string>(x => x)); Diagnostic(ErrorCode.ERR_RefLvalueExpected, "Goo<string>(x => x)").WithLocation(17, 47), // (18,43): error CS0206: A property or indexer may not be passed as an out or ref parameter // var z6 = new Func<string, string>(ref BarP); Diagnostic(ErrorCode.ERR_RefProperty, "ref BarP").WithArguments("Program.BarP").WithLocation(18, 43), // (19,47): error CS1510: A ref or out argument must be an assignable variable // var z7 = new Func<string, string>(ref new Func<string, string>(x => x)); Diagnostic(ErrorCode.ERR_RefLvalueExpected, "new Func<string, string>(x => x)").WithLocation(19, 47), // (20,43): error CS0206: A property or indexer may not be passed as an out or ref parameter // var z8 = new Func<string, string>(ref Program.BarP); Diagnostic(ErrorCode.ERR_RefProperty, "ref Program.BarP").WithArguments("Program.BarP").WithLocation(20, 43), // (21,47): error CS1510: A ref or out argument must be an assignable variable // var z9 = new Func<string, string>(ref Program.Goo<string>(x => x)); Diagnostic(ErrorCode.ERR_RefLvalueExpected, "Program.Goo<string>(x => x)").WithLocation(21, 47), // (23,48): error CS1510: A ref or out value must be an assignable variable // var z11 = new Func<string, string>(ref new(x => x)); Diagnostic(ErrorCode.ERR_RefLvalueExpected, "new(x => x)").WithLocation(23, 48) ); CreateCompilation(source, parseOptions: TestOptions.Regular.WithStrictFeature()).VerifyDiagnostics( // (13,47): error CS0149: Method name expected // var z1 = new Func<string, string>(ref Bar); // compat Diagnostic(ErrorCode.ERR_MethodNameExpected, "Bar").WithLocation(13, 47), // (14,47): error CS0149: Method name expected // var z2 = new Func<string, string>(ref Baz); // compat Diagnostic(ErrorCode.ERR_MethodNameExpected, "Baz").WithLocation(14, 47), // (15,47): error CS0149: Method name expected // var z3 = new Func<string, string>(ref k); // compat Diagnostic(ErrorCode.ERR_MethodNameExpected, "k").WithLocation(15, 47), // (16,47): error CS1510: A ref or out argument must be an assignable variable // var z4 = new Func<string, string>(ref x => x); Diagnostic(ErrorCode.ERR_RefLvalueExpected, "x => x").WithLocation(16, 47), // (17,47): error CS1510: A ref or out argument must be an assignable variable // var z5 = new Func<string, string>(ref Goo<string>(x => x)); Diagnostic(ErrorCode.ERR_RefLvalueExpected, "Goo<string>(x => x)").WithLocation(17, 47), // (18,47): error CS0206: A property or indexer may not be passed as an out or ref parameter // var z6 = new Func<string, string>(ref BarP); Diagnostic(ErrorCode.ERR_RefProperty, "BarP").WithArguments("Program.BarP").WithLocation(18, 47), // (19,47): error CS1510: A ref or out argument must be an assignable variable // var z7 = new Func<string, string>(ref new Func<string, string>(x => x)); Diagnostic(ErrorCode.ERR_RefLvalueExpected, "new Func<string, string>(x => x)").WithLocation(19, 47), // (20,47): error CS0206: A property or indexer may not be passed as an out or ref parameter // var z8 = new Func<string, string>(ref Program.BarP); Diagnostic(ErrorCode.ERR_RefProperty, "Program.BarP").WithArguments("Program.BarP").WithLocation(20, 47), // (21,47): error CS1510: A ref or out argument must be an assignable variable // var z9 = new Func<string, string>(ref Program.Goo<string>(x => x)); Diagnostic(ErrorCode.ERR_RefLvalueExpected, "Program.Goo<string>(x => x)").WithLocation(21, 47), // (22,48): error CS1657: Cannot pass 'Id' as a ref or out argument because it is a 'method group' // var z10 = new Func<string, string>(ref Id); // compat Diagnostic(ErrorCode.ERR_RefReadonlyLocalCause, "Id").WithArguments("Id", "method group").WithLocation(22, 48), // (23,48): error CS1510: A ref or out value must be an assignable variable // var z11 = new Func<string, string>(ref new(x => x)); Diagnostic(ErrorCode.ERR_RefLvalueExpected, "new(x => x)").WithLocation(23, 48) ); } [Fact, WorkItem(7359, "https://github.com/dotnet/roslyn/issues/7359")] public void DelegateCreationWithRefOut_Parens() { // these are allowed in compat mode without the parenthesis // with parenthesis, it behaves like strict mode var source = @" using System; public class Program { static Func<T, T> Goo<T>(Func<T, T> t) { return t; } static Func<string, string> Bar = Goo<string>(x => x); static T Id<T>(T id) => id; static void Test(Func<string, string> Baz) { var k = Bar; var z1 = new Func<string, string>(ref (Bar)); var z2 = new Func<string, string>(ref (Baz)); var z3 = new Func<string, string>(ref (k)); var z10 = new Func<string, string>(ref (Id)); // these all are still valid for compat mode, no errors should be reported for compat mode var z4 = new Func<string, string>(ref Bar); var z5 = new Func<string, string>(ref Baz); var z6 = new Func<string, string>(ref k); var z7 = new Func<string, string>(ref Id); } }"; CreateCompilation(source).VerifyDiagnostics( // (13,48): error CS0149: Method name expected // var z1 = new Func<string, string>(ref (Bar)); Diagnostic(ErrorCode.ERR_MethodNameExpected, "Bar").WithLocation(13, 48), // (14,48): error CS0149: Method name expected // var z2 = new Func<string, string>(ref (Baz)); Diagnostic(ErrorCode.ERR_MethodNameExpected, "Baz").WithLocation(14, 48), // (15,48): error CS0149: Method name expected // var z3 = new Func<string, string>(ref (k)); Diagnostic(ErrorCode.ERR_MethodNameExpected, "k").WithLocation(15, 48), // (16,49): error CS1657: Cannot pass 'Id' as a ref or out argument because it is a 'method group' // var z10 = new Func<string, string>(ref (Id)); Diagnostic(ErrorCode.ERR_RefReadonlyLocalCause, "Id").WithArguments("Id", "method group").WithLocation(16, 49)); CreateCompilation(source, parseOptions: TestOptions.Regular.WithStrictFeature()).VerifyDiagnostics( // (13,48): error CS0149: Method name expected // var z1 = new Func<string, string>(ref (Bar)); Diagnostic(ErrorCode.ERR_MethodNameExpected, "Bar").WithLocation(13, 48), // (14,48): error CS0149: Method name expected // var z2 = new Func<string, string>(ref (Baz)); Diagnostic(ErrorCode.ERR_MethodNameExpected, "Baz").WithLocation(14, 48), // (15,48): error CS0149: Method name expected // var z3 = new Func<string, string>(ref (k)); Diagnostic(ErrorCode.ERR_MethodNameExpected, "k").WithLocation(15, 48), // (16,49): error CS1657: Cannot pass 'Id' as a ref or out argument because it is a 'method group' // var z10 = new Func<string, string>(ref (Id)); Diagnostic(ErrorCode.ERR_RefReadonlyLocalCause, "Id").WithArguments("Id", "method group").WithLocation(16, 49), // (18,47): error CS0149: Method name expected // var z4 = new Func<string, string>(ref Bar); Diagnostic(ErrorCode.ERR_MethodNameExpected, "Bar").WithLocation(18, 47), // (19,47): error CS0149: Method name expected // var z5 = new Func<string, string>(ref Baz); Diagnostic(ErrorCode.ERR_MethodNameExpected, "Baz").WithLocation(19, 47), // (20,47): error CS0149: Method name expected // var z6 = new Func<string, string>(ref k); Diagnostic(ErrorCode.ERR_MethodNameExpected, "k").WithLocation(20, 47), // (21,47): error CS1657: Cannot pass 'Id' as a ref or out argument because it is a 'method group' // var z7 = new Func<string, string>(ref Id); Diagnostic(ErrorCode.ERR_RefReadonlyLocalCause, "Id").WithArguments("Id", "method group").WithLocation(21, 47)); } [Fact, WorkItem(7359, "https://github.com/dotnet/roslyn/issues/7359")] public void DelegateCreationWithRefOut_MultipleArgs() { var source = @" using System; public class Program { static Func<string, string> BarP => null; static void Test(Func<string, string> Baz) { var a = new Func<string, string>(ref Baz, Baz.Invoke); var b = new Func<string, string>(Baz, ref Baz.Invoke); var c = new Func<string, string>(ref Baz, ref Baz.Invoke); var d = new Func<string, string>(ref BarP, BarP.Invoke); var e = new Func<string, string>(BarP, ref BarP.Invoke); var f = new Func<string, string>(ref BarP, ref BarP.Invoke); } }"; CreateCompilation(source).VerifyDiagnostics( // (8,46): error CS0149: Method name expected // var a = new Func<string, string>(ref Baz, Baz.Invoke); Diagnostic(ErrorCode.ERR_MethodNameExpected, "Baz, Baz.Invoke").WithLocation(8, 46), // (9,42): error CS0149: Method name expected // var b = new Func<string, string>(Baz, ref Baz.Invoke); Diagnostic(ErrorCode.ERR_MethodNameExpected, "Baz, ref Baz.Invoke").WithLocation(9, 42), // (10,46): error CS0149: Method name expected // var c = new Func<string, string>(ref Baz, ref Baz.Invoke); Diagnostic(ErrorCode.ERR_MethodNameExpected, "Baz, ref Baz.Invoke").WithLocation(10, 46), // (11,42): error CS0206: A property or indexer may not be passed as an out or ref parameter // var d = new Func<string, string>(ref BarP, BarP.Invoke); Diagnostic(ErrorCode.ERR_RefProperty, "ref BarP").WithArguments("Program.BarP").WithLocation(11, 42), // (11,46): error CS0149: Method name expected // var d = new Func<string, string>(ref BarP, BarP.Invoke); Diagnostic(ErrorCode.ERR_MethodNameExpected, "BarP, BarP.Invoke").WithLocation(11, 46), // (12,42): error CS0149: Method name expected // var e = new Func<string, string>(BarP, ref BarP.Invoke); Diagnostic(ErrorCode.ERR_MethodNameExpected, "BarP, ref BarP.Invoke").WithLocation(12, 42), // (13,42): error CS0206: A property or indexer may not be passed as an out or ref parameter // var f = new Func<string, string>(ref BarP, ref BarP.Invoke); Diagnostic(ErrorCode.ERR_RefProperty, "ref BarP").WithArguments("Program.BarP").WithLocation(13, 42), // (13,46): error CS0149: Method name expected // var f = new Func<string, string>(ref BarP, ref BarP.Invoke); Diagnostic(ErrorCode.ERR_MethodNameExpected, "BarP, ref BarP.Invoke").WithLocation(13, 46) ); } [WorkItem(538430, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538430")] [Fact] public void NestedGenericAccessibility() { var text = @" public class C<T> { } public class E { class D : C<D> { } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { }); } [WorkItem(542419, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542419")] [Fact] public void EmptyAngleBrackets() { var text = @" class Program { int f; int P { get; set; } int M() { return 0; } interface I { } class C { } struct S { } delegate void D(); void Test(object p) { int l = 0; Test(l<>); Test(p<>); Test(f<>); Test(P<>); Test(M<>()); Test(this.f<>); Test(this.P<>); Test(this.M<>()); System.Func<int> m; m = M<>; m = this.M<>; I<> i1 = null; C<> c1 = new C(); C c2 = new C<>(); S<> s1 = new S(); S s2 = new S<>(); D<> d1 = null; Program.I<> i2 = null; Program.C<> c3 = new Program.C(); Program.C c4 = new Program.C<>(); Program.S<> s3 = new Program.S(); Program.S s4 = new Program.S<>(); Program.D<> d2 = null; Test(default(I<>)); Test(default(C<>)); Test(default(S<>)); Test(default(Program.I<>)); Test(default(Program.C<>)); Test(default(Program.S<>)); string s; s = typeof(I<>).Name; s = typeof(C<>).Name; s = typeof(S<>).Name; s = typeof(Program.I<>).Name; s = typeof(Program.C<>).Name; s = typeof(Program.S<>).Name; } } "; CreateCompilation(text).VerifyDiagnostics( // (16,14): error CS0307: The variable 'l' cannot be used with type arguments // Test(l<>); Diagnostic(ErrorCode.ERR_TypeArgsNotAllowed, "l<>").WithArguments("l", "variable").WithLocation(16, 14), // (17,14): error CS0307: The variable 'object' cannot be used with type arguments // Test(p<>); Diagnostic(ErrorCode.ERR_TypeArgsNotAllowed, "p<>").WithArguments("object", "variable").WithLocation(17, 14), // (19,14): error CS0307: The field 'Program.f' cannot be used with type arguments // Test(f<>); Diagnostic(ErrorCode.ERR_TypeArgsNotAllowed, "f<>").WithArguments("Program.f", "field").WithLocation(19, 14), // (20,14): error CS0307: The property 'Program.P' cannot be used with type arguments // Test(P<>); Diagnostic(ErrorCode.ERR_TypeArgsNotAllowed, "P<>").WithArguments("Program.P", "property").WithLocation(20, 14), // (21,14): error CS0308: The non-generic method 'Program.M()' cannot be used with type arguments // Test(M<>()); Diagnostic(ErrorCode.ERR_HasNoTypeVars, "M<>").WithArguments("Program.M()", "method").WithLocation(21, 14), // (23,14): error CS8389: Omitting the type argument is not allowed in the current context // Test(this.f<>); Diagnostic(ErrorCode.ERR_OmittedTypeArgument, "this.f<>").WithLocation(23, 14), // (23,19): error CS0307: The field 'Program.f' cannot be used with type arguments // Test(this.f<>); Diagnostic(ErrorCode.ERR_TypeArgsNotAllowed, "f<>").WithArguments("Program.f", "field").WithLocation(23, 19), // (24,14): error CS8389: Omitting the type argument is not allowed in the current context // Test(this.P<>); Diagnostic(ErrorCode.ERR_OmittedTypeArgument, "this.P<>").WithLocation(24, 14), // (24,19): error CS0307: The property 'Program.P' cannot be used with type arguments // Test(this.P<>); Diagnostic(ErrorCode.ERR_TypeArgsNotAllowed, "P<>").WithArguments("Program.P", "property").WithLocation(24, 19), // (25,14): error CS8389: Omitting the type argument is not allowed in the current context // Test(this.M<>()); Diagnostic(ErrorCode.ERR_OmittedTypeArgument, "this.M<>").WithLocation(25, 14), // (25,19): error CS0308: The non-generic method 'Program.M()' cannot be used with type arguments // Test(this.M<>()); Diagnostic(ErrorCode.ERR_HasNoTypeVars, "M<>").WithArguments("Program.M()", "method").WithLocation(25, 19), // (29,13): error CS0308: The non-generic method 'Program.M()' cannot be used with type arguments // m = M<>; Diagnostic(ErrorCode.ERR_HasNoTypeVars, "M<>").WithArguments("Program.M()", "method").WithLocation(29, 13), // (30,13): error CS8389: Omitting the type argument is not allowed in the current context // m = this.M<>; Diagnostic(ErrorCode.ERR_OmittedTypeArgument, "this.M<>").WithLocation(30, 13), // (30,18): error CS0308: The non-generic method 'Program.M()' cannot be used with type arguments // m = this.M<>; Diagnostic(ErrorCode.ERR_HasNoTypeVars, "M<>").WithArguments("Program.M()", "method").WithLocation(30, 18), // (32,9): error CS0308: The non-generic type 'Program.I' cannot be used with type arguments // I<> i1 = null; Diagnostic(ErrorCode.ERR_HasNoTypeVars, "I<>").WithArguments("Program.I", "type").WithLocation(32, 9), // (33,9): error CS0308: The non-generic type 'Program.C' cannot be used with type arguments // C<> c1 = new C(); Diagnostic(ErrorCode.ERR_HasNoTypeVars, "C<>").WithArguments("Program.C", "type").WithLocation(33, 9), // (34,20): error CS0308: The non-generic type 'Program.C' cannot be used with type arguments // C c2 = new C<>(); Diagnostic(ErrorCode.ERR_HasNoTypeVars, "C<>").WithArguments("Program.C", "type").WithLocation(34, 20), // (35,9): error CS0308: The non-generic type 'Program.S' cannot be used with type arguments // S<> s1 = new S(); Diagnostic(ErrorCode.ERR_HasNoTypeVars, "S<>").WithArguments("Program.S", "type").WithLocation(35, 9), // (36,20): error CS0308: The non-generic type 'Program.S' cannot be used with type arguments // S s2 = new S<>(); Diagnostic(ErrorCode.ERR_HasNoTypeVars, "S<>").WithArguments("Program.S", "type").WithLocation(36, 20), // (37,9): error CS0308: The non-generic type 'Program.D' cannot be used with type arguments // D<> d1 = null; Diagnostic(ErrorCode.ERR_HasNoTypeVars, "D<>").WithArguments("Program.D", "type").WithLocation(37, 9), // (39,17): error CS0308: The non-generic type 'Program.I' cannot be used with type arguments // Program.I<> i2 = null; Diagnostic(ErrorCode.ERR_HasNoTypeVars, "I<>").WithArguments("Program.I", "type").WithLocation(39, 17), // (40,17): error CS0308: The non-generic type 'Program.C' cannot be used with type arguments // Program.C<> c3 = new Program.C(); Diagnostic(ErrorCode.ERR_HasNoTypeVars, "C<>").WithArguments("Program.C", "type").WithLocation(40, 17), // (41,36): error CS0308: The non-generic type 'Program.C' cannot be used with type arguments // Program.C c4 = new Program.C<>(); Diagnostic(ErrorCode.ERR_HasNoTypeVars, "C<>").WithArguments("Program.C", "type").WithLocation(41, 36), // (42,17): error CS0308: The non-generic type 'Program.S' cannot be used with type arguments // Program.S<> s3 = new Program.S(); Diagnostic(ErrorCode.ERR_HasNoTypeVars, "S<>").WithArguments("Program.S", "type").WithLocation(42, 17), // (43,36): error CS0308: The non-generic type 'Program.S' cannot be used with type arguments // Program.S s4 = new Program.S<>(); Diagnostic(ErrorCode.ERR_HasNoTypeVars, "S<>").WithArguments("Program.S", "type").WithLocation(43, 36), // (44,17): error CS0308: The non-generic type 'Program.D' cannot be used with type arguments // Program.D<> d2 = null; Diagnostic(ErrorCode.ERR_HasNoTypeVars, "D<>").WithArguments("Program.D", "type").WithLocation(44, 17), // (46,22): error CS0308: The non-generic type 'Program.I' cannot be used with type arguments // Test(default(I<>)); Diagnostic(ErrorCode.ERR_HasNoTypeVars, "I<>").WithArguments("Program.I", "type").WithLocation(46, 22), // (47,22): error CS0308: The non-generic type 'Program.C' cannot be used with type arguments // Test(default(C<>)); Diagnostic(ErrorCode.ERR_HasNoTypeVars, "C<>").WithArguments("Program.C", "type").WithLocation(47, 22), // (48,22): error CS0308: The non-generic type 'Program.S' cannot be used with type arguments // Test(default(S<>)); Diagnostic(ErrorCode.ERR_HasNoTypeVars, "S<>").WithArguments("Program.S", "type").WithLocation(48, 22), // (50,30): error CS0308: The non-generic type 'Program.I' cannot be used with type arguments // Test(default(Program.I<>)); Diagnostic(ErrorCode.ERR_HasNoTypeVars, "I<>").WithArguments("Program.I", "type").WithLocation(50, 30), // (51,30): error CS0308: The non-generic type 'Program.C' cannot be used with type arguments // Test(default(Program.C<>)); Diagnostic(ErrorCode.ERR_HasNoTypeVars, "C<>").WithArguments("Program.C", "type").WithLocation(51, 30), // (52,30): error CS0308: The non-generic type 'Program.S' cannot be used with type arguments // Test(default(Program.S<>)); Diagnostic(ErrorCode.ERR_HasNoTypeVars, "S<>").WithArguments("Program.S", "type").WithLocation(52, 30), // (56,20): error CS0308: The non-generic type 'Program.I' cannot be used with type arguments // s = typeof(I<>).Name; Diagnostic(ErrorCode.ERR_HasNoTypeVars, "I<>").WithArguments("Program.I", "type").WithLocation(56, 20), // (57,20): error CS0308: The non-generic type 'Program.C' cannot be used with type arguments // s = typeof(C<>).Name; Diagnostic(ErrorCode.ERR_HasNoTypeVars, "C<>").WithArguments("Program.C", "type").WithLocation(57, 20), // (58,20): error CS0308: The non-generic type 'Program.S' cannot be used with type arguments // s = typeof(S<>).Name; Diagnostic(ErrorCode.ERR_HasNoTypeVars, "S<>").WithArguments("Program.S", "type").WithLocation(58, 20), // (60,28): error CS0308: The non-generic type 'Program.I' cannot be used with type arguments // s = typeof(Program.I<>).Name; Diagnostic(ErrorCode.ERR_HasNoTypeVars, "I<>").WithArguments("Program.I", "type").WithLocation(60, 28), // (61,28): error CS0308: The non-generic type 'Program.C' cannot be used with type arguments // s = typeof(Program.C<>).Name; Diagnostic(ErrorCode.ERR_HasNoTypeVars, "C<>").WithArguments("Program.C", "type").WithLocation(61, 28), // (62,28): error CS0308: The non-generic type 'Program.S' cannot be used with type arguments // s = typeof(Program.S<>).Name; Diagnostic(ErrorCode.ERR_HasNoTypeVars, "S<>").WithArguments("Program.S", "type").WithLocation(62, 28), // (4,9): warning CS0649: Field 'Program.f' is never assigned to, and will always have its default value 0 // int f; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "f").WithArguments("Program.f", "0").WithLocation(4, 9) ); } [WorkItem(542419, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542419")] [Fact] public void EmptyAngleBrackets_Events() { var text = @" class Program { event System.Action E; event System.Action F { add { } remove { } } void Test<T>(T p) { Test(E<>); Test(this.E<>); E<> += null; //parse error F<> += null; //parse error this.E<> += null; //parse error this.F<> += null; //parse error } } "; CreateCompilation(text).VerifyDiagnostics( // Parser // (12,11): error CS1525: Invalid expression term '>' // E<> += null; //parse error Diagnostic(ErrorCode.ERR_InvalidExprTerm, ">").WithArguments(">").WithLocation(12, 11), // (12,13): error CS1525: Invalid expression term '+=' // E<> += null; //parse error Diagnostic(ErrorCode.ERR_InvalidExprTerm, "+=").WithArguments("+=").WithLocation(12, 13), // (13,11): error CS1525: Invalid expression term '>' // F<> += null; //parse error Diagnostic(ErrorCode.ERR_InvalidExprTerm, ">").WithArguments(">").WithLocation(13, 11), // (13,13): error CS1525: Invalid expression term '+=' // F<> += null; //parse error Diagnostic(ErrorCode.ERR_InvalidExprTerm, "+=").WithArguments("+=").WithLocation(13, 13), // (15,16): error CS1525: Invalid expression term '>' // this.E<> += null; //parse error Diagnostic(ErrorCode.ERR_InvalidExprTerm, ">").WithArguments(">").WithLocation(15, 16), // (15,18): error CS1525: Invalid expression term '+=' // this.E<> += null; //parse error Diagnostic(ErrorCode.ERR_InvalidExprTerm, "+=").WithArguments("+=").WithLocation(15, 18), // (16,16): error CS1525: Invalid expression term '>' // this.F<> += null; //parse error Diagnostic(ErrorCode.ERR_InvalidExprTerm, ">").WithArguments(">").WithLocation(16, 16), // (16,18): error CS1525: Invalid expression term '+=' // this.F<> += null; //parse error Diagnostic(ErrorCode.ERR_InvalidExprTerm, "+=").WithArguments("+=").WithLocation(16, 18), // Binder // (9,14): error CS0307: The event 'Program.E' cannot be used with type arguments // Test(E<>); Diagnostic(ErrorCode.ERR_TypeArgsNotAllowed, "E<>").WithArguments("Program.E", "event").WithLocation(9, 14), // (10,14): error CS8389: Omitting the type argument is not allowed in the current context // Test(this.E<>); Diagnostic(ErrorCode.ERR_OmittedTypeArgument, "this.E<>").WithLocation(10, 14), // (10,19): error CS0307: The event 'Program.E' cannot be used with type arguments // Test(this.E<>); Diagnostic(ErrorCode.ERR_TypeArgsNotAllowed, "E<>").WithArguments("Program.E", "event").WithLocation(10, 19), // (13,9): error CS0079: The event 'Program.F' can only appear on the left hand side of += or -= // F<> += null; //parse error Diagnostic(ErrorCode.ERR_BadEventUsageNoField, "F").WithArguments("Program.F").WithLocation(13, 9), // (16,14): error CS0079: The event 'Program.F' can only appear on the left hand side of += or -= // this.F<> += null; //parse error Diagnostic(ErrorCode.ERR_BadEventUsageNoField, "F").WithArguments("Program.F").WithLocation(16, 14)); } [WorkItem(542419, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542419")] [WorkItem(542679, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542679")] [Fact] public void EmptyAngleBrackets_TypeParameters() { var text = @" class Program { void Test<T>(T p) { Test(default(T<>)); string s = typeof(T<>).Name; } } "; CreateCompilation(text).VerifyDiagnostics( // (6, 24): error CS0307: The type parameter 'T' cannot be used with type arguments Diagnostic(ErrorCode.ERR_TypeArgsNotAllowed, "T<>").WithArguments("T", "type parameter"), // (7,27): error CS0307: The type parameter 'T' cannot be used with type arguments Diagnostic(ErrorCode.ERR_TypeArgsNotAllowed, "T<>").WithArguments("T", "type parameter")); } [Fact, WorkItem(542796, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542796")] public void EmptyAngleBrackets_TypeWithCorrectArity() { var text = @" class C<T> { static void M() { C<>.M(); } } "; CreateCompilation(text).VerifyDiagnostics( // (6,9): error CS0305: Using the generic type 'C<T>' requires 1 type arguments Diagnostic(ErrorCode.ERR_BadArity, "C<>").WithArguments("C<T>", "type", "1")); } [Fact, WorkItem(542796, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542796")] public void EmptyAngleBrackets_MethodWithCorrectArity() { var text = @" class C { static void M<T>() { M<>(); } } "; CreateCompilation(text).VerifyDiagnostics( // (6,9): error CS0305: Using the generic method group 'M' requires 1 type arguments Diagnostic(ErrorCode.ERR_BadArity, "M<>").WithArguments("M", "method group", "1")); } [Fact, WorkItem(542796, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542796")] public void EmptyAngleBrackets_QualifiedTypeWithCorrectArity() { var text = @" class A { class C<T> { static void M() { A.C<>.M(); } } } "; CreateCompilation(text).VerifyDiagnostics( // (8,15): error CS0305: Using the generic type 'A.C<T>' requires 1 type arguments Diagnostic(ErrorCode.ERR_BadArity, "C<>").WithArguments("A.C<T>", "type", "1")); } [Fact, WorkItem(542796, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542796")] public void EmptyAngleBrackets_QualifiedMethodWithCorrectArity() { var text = @" class C { static void M<T>() { C.M<>(); } } "; CreateCompilation(text).VerifyDiagnostics( // (6,9): error CS0305: Using the generic method group 'M' requires 1 type arguments Diagnostic(ErrorCode.ERR_BadArity, "C.M<>").WithArguments("M", "method group", "1")); } [Fact] public void NamesTooLong() { var longE = new String('e', 1024); var builder = new System.Text.StringBuilder(); builder.Append(@" class C { "); builder.AppendFormat("int {0}1;\n", longE); builder.AppendFormat("event System.Action {0}2;\n", longE); builder.AppendFormat("public void {0}3() {{ }}\n", longE); builder.AppendFormat("public void goo(int {0}4) {{ }}\n", longE); builder.AppendFormat("public string {0}5 {{ get; set; }}\n", longE); builder.AppendLine(@" } "); CreateCompilation(builder.ToString(), null, TestOptions.ReleaseDll.WithGeneralDiagnosticOption(ReportDiagnostic.Suppress)).VerifyEmitDiagnostics( Diagnostic(ErrorCode.ERR_MetadataNameTooLong, longE + 2).WithArguments(longE + 2), //event Diagnostic(ErrorCode.ERR_MetadataNameTooLong, longE + 2).WithArguments(longE + 2), //backing field Diagnostic(ErrorCode.ERR_MetadataNameTooLong, longE + 2).WithArguments("add_" + longE + 2), //accessor Diagnostic(ErrorCode.ERR_MetadataNameTooLong, longE + 2).WithArguments("remove_" + longE + 2), //accessor Diagnostic(ErrorCode.ERR_MetadataNameTooLong, longE + 3).WithArguments(longE + 3), Diagnostic(ErrorCode.ERR_MetadataNameTooLong, longE + 4).WithArguments(longE + 4), Diagnostic(ErrorCode.ERR_MetadataNameTooLong, longE + 5).WithArguments(longE + 5), Diagnostic(ErrorCode.ERR_MetadataNameTooLong, longE + 5).WithArguments("<" + longE + 5 + ">k__BackingField"), Diagnostic(ErrorCode.ERR_MetadataNameTooLong, "get").WithArguments("get_" + longE + 5), Diagnostic(ErrorCode.ERR_MetadataNameTooLong, "set").WithArguments("set_" + longE + 5), Diagnostic(ErrorCode.ERR_MetadataNameTooLong, longE + 1).WithArguments(longE + 1) ); } #endregion #region regression tests [WorkItem(541605, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541605")] [Fact] public void CS0019ERR_ImplicitlyTypedVariableAssignedNullCoalesceExpr() { CreateCompilation(@" class Test { public static void Main() { var p = null ?? null; //CS0019 } } ").VerifyDiagnostics( // error CS0019: Operator '??' cannot be applied to operands of type '<null>' and '<null>' Diagnostic(ErrorCode.ERR_BadBinaryOps, "null ?? null").WithArguments("??", "<null>", "<null>")); } [WorkItem(528577, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528577")] [Fact(Skip = "528577")] public void CS0122ERR_InaccessibleGenericType() { CreateCompilation(@" public class Top<T> { class Outer<U> { } } public class MyClass { public static void Main() { var test = new Top<int>.Outer<string>(); } } ").VerifyDiagnostics( // (13,33): error CS0122: 'Top<int>.Outer<string>' is inaccessible due to its protection level // var test = new Top<int>.Outer<string>(); Diagnostic(ErrorCode.ERR_BadAccess, "new Top<int>.Outer<string>()").WithArguments("Top<int>.Outer<string>")); } [WorkItem(528591, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528591")] [Fact] public void CS0121ERR_IncorrectErrorSpan1() { CreateCompilation(@" class Test { public static void Method1(int a, long b) { } public static void Method1(long a, int b) { } public static void Main() { Method1(10, 20); //CS0121 } } ").VerifyDiagnostics( // (14,9): error CS0121: The call is ambiguous between the following methods or properties: 'Test.Method1(int, long)' and 'Test.Method1(long, int)' // Method1(10, 20) Diagnostic(ErrorCode.ERR_AmbigCall, "Method1").WithArguments("Test.Method1(int, long)", "Test.Method1(long, int)")); } [WorkItem(528592, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528592")] [Fact] public void CS0121ERR_IncorrectErrorSpan2() { CreateCompilation(@" public class Class1 { public Class1(int a, long b) { } public Class1(long a, int b) { } } class Test { public static void Main() { var i1 = new Class1(10, 20); //CS0121 } } ").VerifyDiagnostics( // (17,18): error CS0121: The call is ambiguous between the following methods or properties: 'Class1.Class1(int, long)' and 'Class1.Class1(long, int)' // new Class1(10, 20) Diagnostic(ErrorCode.ERR_AmbigCall, "Class1").WithArguments("Class1.Class1(int, long)", "Class1.Class1(long, int)")); } [WorkItem(542468, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542468")] [Fact] public void CS1513ERR_RbraceExpected_DevDiv9741() { var text = @" class Program { private delegate string D(); static void Main(string[] args) { D d = delegate { .ToString(); }; } } "; // Used to assert. CreateCompilation(text).VerifyDiagnostics( // (8,10): error CS1513: } expected // { Diagnostic(ErrorCode.ERR_RbraceExpected, "").WithLocation(8, 10), // (9,14): error CS0120: An object reference is required for the non-static field, method, or property 'object.ToString()' // .ToString(); Diagnostic(ErrorCode.ERR_ObjectRequired, "ToString").WithArguments("object.ToString()").WithLocation(9, 14), // (7,15): error CS1643: Not all code paths return a value in anonymous method of type 'Program.D' // D d = delegate Diagnostic(ErrorCode.ERR_AnonymousReturnExpected, "delegate").WithArguments("anonymous method", "Program.D").WithLocation(7, 15) ); } [WorkItem(543473, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543473")] [Fact] public void CS0815ERR_CannotAssignLambdaExpressionToAnImplicitlyTypedLocalVariable() { var text = @"class Program { static void Main(string[] args) { var a1 = checked((a) => a); } }"; CreateCompilation(text).VerifyDiagnostics( // (5,26): error CS8917: The delegate type could not be inferred. // var a1 = checked((a) => a); Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "(a) => a").WithLocation(5, 26)); } [Fact, WorkItem(543665, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543665")] public void CS0246ERR_SingleTypeNameNotFound_UndefinedTypeInDelegateSignature() { var text = @" using System; class Test { static void Main() { var d = (Action<List<int>>)delegate(List<int> t) {}; } }"; CreateCompilation(text).VerifyDiagnostics( // (7,41): error CS0246: The type or namespace name 'List<>' could not be found (are you missing a using directive or an assembly reference?) // var d = (Action<List<int>>)delegate(List<int> t) {}; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "List<int>").WithArguments("List<>").WithLocation(7, 41), // (7,21): error CS0246: The type or namespace name 'List<>' could not be found (are you missing a using directive or an assembly reference?) // var d = (Action<List<int>>)delegate(List<int> t) {}; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "List<int>").WithArguments("List<>").WithLocation(7, 21) ); } [Fact] [WorkItem(633183, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/633183")] public void CS0199ERR_RefReadonlyStatic_StaticFieldInitializer() { var source = @" class Program { Program(ref string s) { } static readonly Program Field1 = new Program(ref Program.Field2); static readonly string Field2 = """"; static void Main() { } } "; CreateCompilation(source).VerifyDiagnostics(); } [Fact] [WorkItem(633183, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/633183")] public void CS0199ERR_RefReadonlyStatic_NestedStaticFieldInitializer() { var source = @" class Program { Program(ref string s) { } static readonly Program Field1 = new Program(ref Program.Field2); static readonly string Field2 = """"; static void Main() { } class Inner { static readonly Program Field3 = new Program(ref Program.Field2); } } "; CreateCompilation(source).VerifyDiagnostics( // (11,58): error CS0199: A static readonly field cannot be used as a ref or out value (except in a static constructor) // static readonly Program Field3 = new Program(ref Program.Field2); Diagnostic(ErrorCode.ERR_RefReadonlyStatic, "Program.Field2").WithLocation(11, 58) ); } [Fact] public void BadYield_MultipleReasons() { var source = @" using System.Collections.Generic; class Program { IEnumerable<int> Test() { try { try { yield return 11; // CS1626 } catch { yield return 12; // CS1626 } finally { yield return 13; // CS1625 } } catch { try { yield return 21; // CS1626 } catch { yield return 22; // CS1631 } finally { yield return 23; // CS1625 } } finally { try { yield return 31; // CS1625 } catch { yield return 32; // CS1625 } finally { yield return 33; // CS1625 } } } } "; CreateCompilation(source).VerifyDiagnostics( // (12,17): error CS1626: Cannot yield a value in the body of a try block with a catch clause // yield return 11; // CS1626 Diagnostic(ErrorCode.ERR_BadYieldInTryOfCatch, "yield"), // (16,17): error CS1626: Cannot yield a value in the body of a try block with a catch clause // yield return 12; // CS1626 Diagnostic(ErrorCode.ERR_BadYieldInTryOfCatch, "yield"), // (20,17): error CS1625: Cannot yield in the body of a finally clause // yield return 13; // CS1625 Diagnostic(ErrorCode.ERR_BadYieldInFinally, "yield"), // (27,17): error CS1626: Cannot yield a value in the body of a try block with a catch clause // yield return 21; // CS1626 Diagnostic(ErrorCode.ERR_BadYieldInTryOfCatch, "yield"), // (31,17): error CS1631: Cannot yield a value in the body of a catch clause // yield return 22; // CS1631 Diagnostic(ErrorCode.ERR_BadYieldInCatch, "yield"), // (35,17): error CS1625: Cannot yield in the body of a finally clause // yield return 23; // CS1625 Diagnostic(ErrorCode.ERR_BadYieldInFinally, "yield"), // (42,17): error CS1625: Cannot yield in the body of a finally clause // yield return 31; // CS1625 Diagnostic(ErrorCode.ERR_BadYieldInFinally, "yield"), // (46,17): error CS1625: Cannot yield in the body of a finally clause // yield return 32; // CS1625 Diagnostic(ErrorCode.ERR_BadYieldInFinally, "yield"), // (50,17): error CS1625: Cannot yield in the body of a finally clause // yield return 33; // CS1625 Diagnostic(ErrorCode.ERR_BadYieldInFinally, "yield")); } [Fact] public void BadYield_Lambda() { var source = @" using System; using System.Collections.Generic; class Program { IEnumerable<int> Test() { try { } finally { Action a = () => { yield break; }; Action b = () => { try { } finally { yield break; } }; } yield break; } } "; CreateCompilation(source).VerifyDiagnostics( // (14,32): error CS1621: The yield statement cannot be used inside an anonymous method or lambda expression // Action a = () => { yield break; }; Diagnostic(ErrorCode.ERR_YieldInAnonMeth, "yield"), // CONSIDER: ERR_BadYieldInFinally is redundant, but matches dev11. // (22,21): error CS1625: Cannot yield in the body of a finally clause // yield break; Diagnostic(ErrorCode.ERR_BadYieldInFinally, "yield"), // (22,21): error CS1621: The yield statement cannot be used inside an anonymous method or lambda expression // yield break; Diagnostic(ErrorCode.ERR_YieldInAnonMeth, "yield")); } #endregion [Fact] public void Bug528147() { var text = @" using System; interface I<T> { } class A { private class B { } public class C : I<B> { } } class Program { delegate void D(A.C x); static void M<T>(I<T> c) { Console.WriteLine(""I""); } static void Main() { D d = M; d(null); } } "; CreateCompilation(text).VerifyDiagnostics( // (25,15): error CS0122: 'Program.M<A.B>(I<A.B>)' is inaccessible due to its protection level // D d = M; Diagnostic(ErrorCode.ERR_BadAccess, "M").WithArguments("Program.M<A.B>(I<A.B>)") ); } [WorkItem(630799, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/630799")] [Fact] public void Bug630799() { var text = @" using System; class Program { static void Goo<T,S>() where T : S where S : Exception { try { } catch(S e) { } catch(T e) { } } } "; CreateCompilation(text).VerifyDiagnostics( // (14,15): error CS0160: A previous catch clause already catches all exceptions of this or of a super type ('S') // catch(T e) Diagnostic(ErrorCode.ERR_UnreachableCatch, "T").WithArguments("S").WithLocation(14, 15), // (11,17): warning CS0168: The variable 'e' is declared but never used // catch(S e) Diagnostic(ErrorCode.WRN_UnreferencedVar, "e").WithArguments("e").WithLocation(11, 17), // (14,17): warning CS0168: The variable 'e' is declared but never used // catch(T e) Diagnostic(ErrorCode.WRN_UnreferencedVar, "e").WithArguments("e").WithLocation(14, 17) ); } [Fact] public void ConditionalMemberAccess001() { var text = @" class Program { public int P1 { set { } } public void V() { } static void Main(string[] args) { var x = 123 ?.ToString(); var p = new Program(); var x1 = p.P1 ?.ToString(); var x2 = p.V() ?.ToString(); var x3 = p.V ?.ToString(); var x4 = ()=> { return 1; } ?.ToString(); } } "; CreateCompilationWithMscorlib45(text).VerifyDiagnostics( // (13,21): error CS0023: Operator '?' cannot be applied to operand of type 'int' // var x = 123 ?.ToString(); Diagnostic(ErrorCode.ERR_BadUnaryOp, "?").WithArguments("?", "int").WithLocation(13, 21), // (16,18): error CS0154: The property or indexer 'Program.P1' cannot be used in this context because it lacks the get accessor // var x1 = p.P1 ?.ToString(); Diagnostic(ErrorCode.ERR_PropertyLacksGet, "p.P1").WithArguments("Program.P1").WithLocation(16, 18), // (17,24): error CS0023: Operator '?' cannot be applied to operand of type 'void' // var x2 = p.V() ?.ToString(); Diagnostic(ErrorCode.ERR_BadUnaryOp, "?").WithArguments("?", "void").WithLocation(17, 24), // (18,20): error CS0119: 'Program.V()' is a method, which is not valid in the given context // var x3 = p.V ?.ToString(); Diagnostic(ErrorCode.ERR_BadSKunknown, "V").WithArguments("Program.V()", "method").WithLocation(18, 20), // (19,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(19, 18) ); } [Fact] public void ConditionalMemberAccess002_notIn5() { var text = @" class Program { public int? P1 { get { return null; } } public void V() { } static void Main(string[] args) { var p = new Program(); var x1 = p.P1 ?.ToString; } } "; CreateCompilation(text, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp5)).VerifyDiagnostics( // (14,18): error CS8026: Feature 'null propagation operator' is not available in C# 5. Please use language version 6 or greater. // var x1 = p.P1 ?.ToString; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion5, "p.P1 ?.ToString").WithArguments("null propagating operator", "6").WithLocation(14, 18), // (14,23): error CS0023: Operator '?' cannot be applied to operand of type 'method group' // var x1 = p.P1 ?.ToString; Diagnostic(ErrorCode.ERR_BadUnaryOp, "?").WithArguments("?", "method group").WithLocation(14, 23) ); } [Fact] public void ConditionalMemberAccess002() { var text = @" class Program { public int? P1 { get { return null; } } public void V() { } static void Main(string[] args) { var p = new Program(); var x1 = p.P1 ?.ToString; } } "; CreateCompilationWithMscorlib45(text).VerifyDiagnostics( // (14,23): error CS0023: Operator '?' cannot be applied to operand of type 'method group' // var x1 = p.P1 ?.ToString; Diagnostic(ErrorCode.ERR_BadUnaryOp, "?").WithArguments("?", "method group").WithLocation(14, 23) ); } [Fact] [CompilerTrait(CompilerFeature.IOperation)] [WorkItem(23009, "https://github.com/dotnet/roslyn/issues/23009")] public void ConditionalElementAccess001() { var text = @" class Program { public int P1 { set { } } public void V() { var x6 = base?.ToString(); } static void Main(string[] args) { var x = 123 ?[1,2]; var p = new Program(); var x1 = p.P1 ?[1,2]; var x2 = p.V() ?[1,2]; var x3 = p.V ?[1,2]; var x4 = ()=> { return 1; } ?[1,2]; var x5 = null?.ToString(); } } "; var compilation = CreateCompilationWithMscorlib45(text).VerifyDiagnostics( // (11,18): error CS0175: Use of keyword 'base' is not valid in this context // var x6 = base?.ToString(); Diagnostic(ErrorCode.ERR_BaseIllegal, "base").WithLocation(11, 18), // (16,21): error CS0023: Operator '?' cannot be applied to operand of type 'int' // var x = 123 ?[1,2]; Diagnostic(ErrorCode.ERR_BadUnaryOp, "?").WithArguments("?", "int").WithLocation(16, 21), // (19,18): error CS0154: The property or indexer 'Program.P1' cannot be used in this context because it lacks the get accessor // var x1 = p.P1 ?[1,2]; Diagnostic(ErrorCode.ERR_PropertyLacksGet, "p.P1").WithArguments("Program.P1").WithLocation(19, 18), // (20,24): error CS0023: Operator '?' cannot be applied to operand of type 'void' // var x2 = p.V() ?[1,2]; Diagnostic(ErrorCode.ERR_BadUnaryOp, "?").WithArguments("?", "void").WithLocation(20, 24), // (21,20): error CS0119: 'Program.V()' is a method, which is not valid in the given context // var x3 = p.V ?[1,2]; Diagnostic(ErrorCode.ERR_BadSKunknown, "V").WithArguments("Program.V()", "method").WithLocation(21, 20), // (22,18): error CS0023: Operator '?' cannot be applied to operand of type 'lambda expression' // var x4 = ()=> { return 1; } ?[1,2]; Diagnostic(ErrorCode.ERR_BadUnaryOp, "()=> { return 1; } ?[1,2]").WithArguments("?", "lambda expression").WithLocation(22, 18), // (24,22): error CS0023: Operator '?' cannot be applied to operand of type '<null>' // var x5 = null?.ToString(); Diagnostic(ErrorCode.ERR_BadUnaryOp, "?").WithArguments("?", "<null>").WithLocation(24, 22) ); var tree = compilation.SyntaxTrees.Single(); var node = tree.GetRoot().DescendantNodes().OfType<ConditionalAccessExpressionSyntax>().First(); Assert.Equal("base?.ToString()", node.ToString()); compilation.VerifyOperationTree(node, expectedOperationTree: @" IConditionalAccessOperation (OperationKind.ConditionalAccess, Type: ?, IsInvalid) (Syntax: 'base?.ToString()') Operation: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: System.Object, IsInvalid) (Syntax: 'base') WhenNotNull: IInvocationOperation (virtual System.String System.Object.ToString()) (OperationKind.Invocation, Type: System.String) (Syntax: '.ToString()') Instance Receiver: IConditionalAccessInstanceOperation (OperationKind.ConditionalAccessInstance, Type: System.Object, IsInvalid, IsImplicit) (Syntax: 'base') Arguments(0) "); } [Fact] [WorkItem(976765, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/976765")] public void ConditionalMemberAccessPtr() { var text = @" using System; class Program { unsafe static void Main() { IntPtr? intPtr = null; var p = intPtr?.ToPointer(); } } "; CreateCompilationWithMscorlib45(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (9,23): error CS0023: Operator '?' cannot be applied to operand of type 'void*' // var p = intPtr?.ToPointer(); Diagnostic(ErrorCode.ERR_BadUnaryOp, "?").WithArguments("?", "void*").WithLocation(9, 23) ); } [Fact] [WorkItem(991490, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/991490")] public void ConditionalMemberAccessExprLambda() { var text = @" using System; using System.Linq.Expressions; class Program { static void M<T>(T x) { Expression<Func<string>> s = () => x?.ToString(); Expression<Func<char?>> c = () => x.ToString()?[0]; Expression<Func<int?>> c1 = () => x.ToString()?.Length; Expression<Func<int?>> c2 = () => x?.ToString()?.Length; } static void Main() { M((string)null); } } "; CreateCompilationWithMscorlib45(text, new[] { Net451.System, Net451.SystemCore, Net451.MicrosoftCSharp }, options: TestOptions.ReleaseDll).VerifyDiagnostics( // (9,44): error CS8072: An expression tree lambda may not contain a null propagating operator. // Expression<Func<string>> s = () => x?.ToString(); Diagnostic(ErrorCode.ERR_NullPropagatingOpInExpressionTree, "x?.ToString()").WithLocation(9, 44), // (10,43): error CS8072: An expression tree lambda may not contain a null propagating operator. // Expression<Func<char?>> c = () => x.ToString()?[0]; Diagnostic(ErrorCode.ERR_NullPropagatingOpInExpressionTree, "x.ToString()?[0]").WithLocation(10, 43), // (11,43): error CS8072: An expression tree lambda may not contain a null propagating operator. // Expression<Func<int?>> c1 = () => x.ToString()?.Length; Diagnostic(ErrorCode.ERR_NullPropagatingOpInExpressionTree, "x.ToString()?.Length").WithLocation(11, 43), // (13,43): error CS8072: An expression tree lambda may not contain a null propagating operator. // Expression<Func<int?>> c2 = () => x?.ToString()?.Length; Diagnostic(ErrorCode.ERR_NullPropagatingOpInExpressionTree, "x?.ToString()?.Length").WithLocation(13, 43), // (13,45): error CS8072: An expression tree lambda may not contain a null propagating operator. // Expression<Func<int?>> c2 = () => x?.ToString()?.Length; Diagnostic(ErrorCode.ERR_NullPropagatingOpInExpressionTree, ".ToString()?.Length").WithLocation(13, 45) ); } [Fact] [WorkItem(915609, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/915609")] public void DictionaryInitializerInExprLambda() { var text = @" using System; using System.Linq.Expressions; using System.Collections.Generic; class Program { static void M<T>(T x) { Expression<Func<Dictionary<int, int>>> s = () => new Dictionary<int, int> () {[1] = 2}; } static void Main() { M((string)null); } } "; CreateCompilationWithMscorlib45(text, new[] { Net451.System, Net451.SystemCore, Net451.MicrosoftCSharp }).VerifyDiagnostics( // (10,87): error CS8073: An expression tree lambda may not contain a dictionary initializer. // Expression<Func<Dictionary<int, int>>> s = () => new Dictionary<int, int> () {[1] = 2}; Diagnostic(ErrorCode.ERR_DictionaryInitializerInExpressionTree, "[1]").WithLocation(10, 87) ); } [Fact] [WorkItem(915609, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/915609")] public void DictionaryInitializerInExprLambda1() { var text = @" using System; using System.Collections.Generic; using System.Linq.Expressions; namespace ConsoleApplication31 { class Program { static void Main(string[] args) { var o = new Goo(); var x = o.E.Compile()().Pop(); System.Console.WriteLine(x); } } static class StackExtensions { public static void Add<T>(this Stack<T> s, T x) => s.Push(x); } class Goo { public Expression<Func<Stack<int>>> E = () => new Stack<int> { 42 }; } } "; CreateCompilationWithMscorlib45(text, new[] { Net451.System, Net451.SystemCore, Net451.MicrosoftCSharp }).VerifyDiagnostics( // (25,72): error CS8075: An expression tree lambda may not contain an extension collection element initializer. // public Expression<Func<Stack<int>>> E = () => new Stack<int> { 42 }; Diagnostic(ErrorCode.ERR_ExtensionCollectionElementInitializerInExpressionTree, "42").WithLocation(25, 72) ); } [WorkItem(310, "https://github.com/dotnet/roslyn/issues/310")] [Fact] public void ExtensionElementInitializerInExpressionLambda() { var text = @" using System; using System.Collections; using System.Linq.Expressions; class C { static void Main() { Expression<Func<C>> e = () => new C { H = { [""Key""] = ""Value"" } }; Console.WriteLine(e); var c = e.Compile().Invoke(); Console.WriteLine(c.H[""Key""]); } readonly Hashtable H = new Hashtable(); } "; CreateCompilationWithMscorlib45(text, new[] { Net451.System, Net451.SystemCore, Net451.MicrosoftCSharp }).VerifyDiagnostics( // (9,53): error CS8073: An expression tree lambda may not contain a dictionary initializer. // Expression<Func<C>> e = () => new C { H = { ["Key"] = "Value" } }; Diagnostic(ErrorCode.ERR_DictionaryInitializerInExpressionTree, @"[""Key""]").WithLocation(9, 53) ); } [WorkItem(12900, "https://github.com/dotnet/roslyn/issues/12900")] [WorkItem(17138, "https://github.com/dotnet/roslyn/issues/17138")] [Fact] public void CSharp7FeaturesInExprTrees() { var source = @" using System; //using System.Collections; using System.Linq.Expressions; class C { static void Main() { // out variable declarations Expression<Func<bool>> e1 = () => TryGetThree(out int x) && x == 3; // ERROR 1 // pattern matching object o = 3; Expression<Func<bool>> e2 = () => o is int y && y == 3; // ERROR 2 // direct tuple creation could be OK, as it is just a constructor invocation, // not for long tuples the generated code is more complex, and we would // prefer custom expression trees to express the semantics. Expression<Func<object>> e3 = () => (1, o); // ERROR 3: tuple literal Expression<Func<(int, int)>> e4 = () => (1, 2); // ERROR 4: tuple literal // tuple conversions (byte, byte) t1 = (1, 2); Expression<Func<(byte a, byte b)>> e5 = () => t1; // OK, identity conversion Expression<Func<(int, int)>> e6 = () => t1; // ERROR 5: tuple conversion Expression<Func<int>> e7 = () => TakeRef(ref GetRefThree()); // ERROR 6: calling ref-returning method // discard Expression<Func<bool>> e8 = () => TryGetThree(out int _); Expression<Func<bool>> e9 = () => TryGetThree(out var _); Expression<Func<bool>> e10 = () => _ = (bool)o; Expression<Func<object>> e11 = () => _ = (_, _) = GetTuple(); Expression<Func<object>> e12 = () => _ = var (a, _) = GetTuple(); Expression<Func<object>> e13 = () => _ = (var a, var _) = GetTuple(); Expression<Func<bool>> e14 = () => TryGetThree(out _); } static bool TryGetThree(out int three) { three = 3; return true; } static int three = 3; static ref int GetRefThree() { return ref three; } static int TakeRef(ref int x) { Console.WriteLine(""wow""); return x; } static (object, object) GetTuple() { return (null, null); } } namespace System { struct ValueTuple<T1, T2> { public T1 Item1; public T2 Item2; public ValueTuple(T1 item1, T2 item2) { Item1 = item1; Item2 = item2; } } } namespace System.Runtime.CompilerServices { /// <summary> /// Indicates that the use of <see cref=""System.ValueTuple""/> on a member is meant to be treated as a tuple with element names. /// </summary> [AttributeUsage(AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.Property | AttributeTargets.ReturnValue | AttributeTargets.Class | AttributeTargets.Struct )] public sealed class TupleElementNamesAttribute : Attribute { public TupleElementNamesAttribute(string[] transformNames) { } } } "; var compilation = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugExe); compilation.VerifyDiagnostics( // (34,50): error CS8185: A declaration is not allowed in this context. // Expression<Func<object>> e12 = () => _ = var (a, _) = GetTuple(); Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "var (a, _)").WithLocation(34, 50), // (35,51): error CS8185: A declaration is not allowed in this context. // Expression<Func<object>> e13 = () => _ = (var a, var _) = GetTuple(); Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "var a").WithLocation(35, 51), // (10,59): error CS8198: An expression tree may not contain an out argument variable declaration. // Expression<Func<bool>> e1 = () => TryGetThree(out int x) && x == 3; // ERROR 1 Diagnostic(ErrorCode.ERR_ExpressionTreeContainsOutVariable, "int x").WithLocation(10, 59), // (14,43): error CS8122: An expression tree may not contain an 'is' pattern-matching operator. // Expression<Func<bool>> e2 = () => o is int y && y == 3; // ERROR 2 Diagnostic(ErrorCode.ERR_ExpressionTreeContainsIsMatch, "o is int y").WithLocation(14, 43), // (19,45): error CS8143: An expression tree may not contain a tuple literal. // Expression<Func<object>> e3 = () => (1, o); // ERROR 3: tuple literal Diagnostic(ErrorCode.ERR_ExpressionTreeContainsTupleLiteral, "(1, o)").WithLocation(19, 45), // (20,49): error CS8143: An expression tree may not contain a tuple literal. // Expression<Func<(int, int)>> e4 = () => (1, 2); // ERROR 4: tuple literal Diagnostic(ErrorCode.ERR_ExpressionTreeContainsTupleLiteral, "(1, 2)").WithLocation(20, 49), // (25,49): error CS8144: An expression tree may not contain a tuple conversion. // Expression<Func<(int, int)>> e6 = () => t1; // ERROR 5: tuple conversion Diagnostic(ErrorCode.ERR_ExpressionTreeContainsTupleConversion, "t1").WithLocation(25, 49), // (27,54): error CS8156: An expression tree lambda may not contain a call to a method, property, or indexer that returns by reference // Expression<Func<int>> e7 = () => TakeRef(ref GetRefThree()); // ERROR 6: calling ref-returning method Diagnostic(ErrorCode.ERR_RefReturningCallInExpressionTree, "GetRefThree()").WithLocation(27, 54), // (30,59): error CS8205: An expression tree may not contain a discard. // Expression<Func<bool>> e8 = () => TryGetThree(out int _); Diagnostic(ErrorCode.ERR_ExpressionTreeContainsDiscard, "int _").WithLocation(30, 59), // (31,59): error CS8205: An expression tree may not contain a discard. // Expression<Func<bool>> e9 = () => TryGetThree(out var _); Diagnostic(ErrorCode.ERR_ExpressionTreeContainsDiscard, "var _").WithLocation(31, 59), // (32,44): error CS0832: An expression tree may not contain an assignment operator // Expression<Func<bool>> e10 = () => _ = (bool)o; Diagnostic(ErrorCode.ERR_ExpressionTreeContainsAssignment, "_ = (bool)o").WithLocation(32, 44), // (33,46): error CS0832: An expression tree may not contain an assignment operator // Expression<Func<object>> e11 = () => _ = (_, _) = GetTuple(); Diagnostic(ErrorCode.ERR_ExpressionTreeContainsAssignment, "_ = (_, _) = GetTuple()").WithLocation(33, 46), // (33,50): error CS8143: An expression tree may not contain a tuple literal. // Expression<Func<object>> e11 = () => _ = (_, _) = GetTuple(); Diagnostic(ErrorCode.ERR_ExpressionTreeContainsTupleLiteral, "(_, _)").WithLocation(33, 50), // (36,60): error CS8205: An expression tree may not contain a discard. // Expression<Func<bool>> e14 = () => TryGetThree(out _); Diagnostic(ErrorCode.ERR_ExpressionTreeContainsDiscard, "_").WithLocation(36, 60) ); } [Fact] public void DictionaryInitializerInCS5() { var text = @" using System.Collections.Generic; class Program { static void Main() { var s = new Dictionary<int, int> () {[1] = 2}; } } "; CreateCompilationWithMscorlib45(text, new[] { SystemRef_v4_0_30319_17929, SystemCoreRef_v4_0_30319_17929, CSharpRef }, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp5)).VerifyDiagnostics( // (8,46): error CS8026: Feature 'dictionary initializer' is not available in C# 5. Please use language version 6 or greater. // var s = new Dictionary<int, int> () {[1] = 2}; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion5, "[1] = 2").WithArguments("dictionary initializer", "6").WithLocation(8, 46) ); } [Fact] public void DictionaryInitializerDataFlow() { var text = @" using System.Collections.Generic; class Program { static void Main() { int i; var s = new Dictionary<int, int> () {[i] = 2}; i = 1; System.Console.WriteLine(i); } static void Goo() { int i; var s = new Dictionary<int, int> () {[i = 1] = 2}; System.Console.WriteLine(i); } } "; CreateCompilationWithMscorlib45(text, new[] { SystemRef_v4_0_30319_17929, SystemCoreRef_v4_0_30319_17929, CSharpRef }, parseOptions: TestOptions.Regular).VerifyDiagnostics( // (9,47): error CS0165: Use of unassigned local variable 'i' // var s = new Dictionary<int, int> () {[i] = 2}; Diagnostic(ErrorCode.ERR_UseDefViolation, "i").WithArguments("i").WithLocation(9, 47) ); } [Fact] public void ConditionalMemberAccessNotStatement() { var text = @" class Program { static void Main() { var x = new int[10]; x?.Length; x?[1]; x?.ToString()[1]; } } "; CreateCompilationWithMscorlib45(text, options: TestOptions.ReleaseDll).VerifyDiagnostics( // (8,9): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement // x?.Length; Diagnostic(ErrorCode.ERR_IllegalStatement, "x?.Length").WithLocation(8, 9), // (9,9): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement // x?[1]; Diagnostic(ErrorCode.ERR_IllegalStatement, "x?[1]").WithLocation(9, 9), // (10,9): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement // x?.ToString()[1]; Diagnostic(ErrorCode.ERR_IllegalStatement, "x?.ToString()[1]").WithLocation(10, 9) ); } [WorkItem(23422, "https://github.com/dotnet/roslyn/issues/23422")] [Fact] public void ConditionalMemberAccessRefLike() { var text = @" class Program { static void Main(string[] args) { var o = new Program(); o?.F(); // this is ok var x = o?.F(); var y = o?.F() ?? default; var z = o?.F().field ?? default; } S2 F() => throw null; } public ref struct S1 { } public ref struct S2 { public S1 field; } "; CreateCompilationWithMscorlib45(text, options: TestOptions.ReleaseDll).VerifyDiagnostics( // (10,18): error CS0023: Operator '?' cannot be applied to operand of type 'S2' // var x = o?.F(); Diagnostic(ErrorCode.ERR_BadUnaryOp, "?").WithArguments("?", "S2").WithLocation(10, 18), // (12,18): error CS0023: Operator '?' cannot be applied to operand of type 'S2' // var y = o?.F() ?? default; Diagnostic(ErrorCode.ERR_BadUnaryOp, "?").WithArguments("?", "S2").WithLocation(12, 18), // (14,18): error CS0023: Operator '?' cannot be applied to operand of type 'S1' // var z = o?.F().field ?? default; Diagnostic(ErrorCode.ERR_BadUnaryOp, "?").WithArguments("?", "S1").WithLocation(14, 18) ); } [Fact] [WorkItem(1179322, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1179322")] public void LabelSameNameAsParameter() { var text = @" class Program { static object M(object obj, object value) { if (((string)obj).Length == 0) value: new Program(); } } "; var compilation = CreateCompilation(text); compilation.GetParseDiagnostics().Verify(); // Make sure the compiler can handle producing method body diagnostics for this pattern when // queried via an API (command line compile would exit after parse errors were reported). compilation.GetMethodBodyDiagnostics().Verify( // (6,41): error CS1023: Embedded statement cannot be a declaration or labeled statement // if (((string)obj).Length == 0) value: new Program(); Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "value: new Program();").WithLocation(6, 41), // (6,41): warning CS0164: This label has not been referenced // if (((string)obj).Length == 0) value: new Program(); Diagnostic(ErrorCode.WRN_UnreferencedLabel, "value").WithLocation(6, 41), // (4,19): error CS0161: 'Program.M(object, object)': not all code paths return a value // static object M(object obj, object value) Diagnostic(ErrorCode.ERR_ReturnExpected, "M").WithArguments("Program.M(object, object)").WithLocation(4, 19)); } [Fact] public void ThrowInExpressionTree() { var text = @" using System; using System.Linq.Expressions; namespace ConsoleApplication1 { class Program { static bool b = true; static object o = string.Empty; static void Main(string[] args) { Expression<Func<object>> e1 = () => o ?? throw null; Expression<Func<object>> e2 = () => b ? throw null : o; Expression<Func<object>> e3 = () => b ? o : throw null; Expression<Func<object>> e4 = () => throw null; } } } "; CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics( // (13,54): error CS8188: An expression tree may not contain a throw-expression. // Expression<Func<object>> e1 = () => o ?? throw null; Diagnostic(ErrorCode.ERR_ExpressionTreeContainsThrowExpression, "throw null").WithLocation(13, 54), // (14,53): error CS8188: An expression tree may not contain a throw-expression. // Expression<Func<object>> e2 = () => b ? throw null : o; Diagnostic(ErrorCode.ERR_ExpressionTreeContainsThrowExpression, "throw null").WithLocation(14, 53), // (15,57): error CS8188: An expression tree may not contain a throw-expression. // Expression<Func<object>> e3 = () => b ? o : throw null; Diagnostic(ErrorCode.ERR_ExpressionTreeContainsThrowExpression, "throw null").WithLocation(15, 57), // (16,49): error CS8188: An expression tree may not contain a throw-expression. // Expression<Func<object>> e4 = () => throw null; Diagnostic(ErrorCode.ERR_ExpressionTreeContainsThrowExpression, "throw null").WithLocation(16, 49) ); } [Fact, WorkItem(17674, "https://github.com/dotnet/roslyn/issues/17674")] public void VoidDiscardAssignment() { var text = @" class Program { public static void Main(string[] args) { _ = M(); } static void M() { } } "; CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics( // (6,9): error CS8209: A value of type 'void' may not be assigned. // _ = M(); Diagnostic(ErrorCode.ERR_VoidAssignment, "_").WithLocation(6, 9) ); } [Fact, WorkItem(22880, "https://github.com/dotnet/roslyn/issues/22880")] public void AttributeCtorInParam() { var text = @" [A(1)] class A : System.Attribute { A(in int x) { } } [B()] class B : System.Attribute { B(in int x = 1) { } } "; CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics( // (2,2): error CS8358: Cannot use attribute constructor 'A.A(in int)' because it has 'in' parameters. // [A(1)] Diagnostic(ErrorCode.ERR_AttributeCtorInParameter, "A(1)").WithArguments("A.A(in int)").WithLocation(2, 2), // (7,2): error CS8358: Cannot use attribute constructor 'B.B(in int)' because it has 'in' parameters. // [B()] Diagnostic(ErrorCode.ERR_AttributeCtorInParameter, "B()").WithArguments("B.B(in int)").WithLocation(7, 2) ); } [Fact] public void ERR_ExpressionTreeContainsSwitchExpression() { var text = @" using System; using System.Linq.Expressions; public class C { public int Test() { Expression<Func<int, int>> e = a => a switch { 0 => 1, _ => 2 }; // CS8411 return 1; } }"; CreateCompilationWithMscorlib40AndSystemCore(text, parseOptions: TestOptions.RegularWithRecursivePatterns).VerifyDiagnostics( // (9,45): error CS8411: An expression tree may not contain a switch expression. // Expression<Func<int, int>> e = a => a switch { 0 => 1, _ => 2 }; // CS8411 Diagnostic(ErrorCode.ERR_ExpressionTreeContainsSwitchExpression, "a switch { 0 => 1, _ => 2 }").WithLocation(9, 45) ); } [Fact] public void PointerGenericConstraintTypes() { var source = @" namespace A { class D {} } class B {} unsafe class C<T, U, V, X, Y, Z> where T : byte* where U : unmanaged where V : U* where X : object* where Y : B* where Z : A.D* { void M1<A>() where A : byte* {} void M2<A, B>() where A : unmanaged where B : A* {} void M3<A>() where A : object* {} void M4<A>() where A : B* {} void M5<A>() where A : T {} }"; var comp = CreateCompilation(source, options: TestOptions.UnsafeDebugDll); comp.VerifyDiagnostics( // (9,44): error CS0706: Invalid constraint type. A type used as a constraint must be an interface, a non-sealed class or a type parameter. // unsafe class C<T, U, V, X, Y, Z> where T : byte* Diagnostic(ErrorCode.ERR_BadConstraintType, "byte*").WithLocation(9, 44), // (11,44): error CS0706: Invalid constraint type. A type used as a constraint must be an interface, a non-sealed class or a type parameter. // where V : U* Diagnostic(ErrorCode.ERR_BadConstraintType, "U*").WithLocation(11, 44), // (12,44): error CS0706: Invalid constraint type. A type used as a constraint must be an interface, a non-sealed class or a type parameter. // where X : object* Diagnostic(ErrorCode.ERR_BadConstraintType, "object*").WithLocation(12, 44), // (13,44): error CS0706: Invalid constraint type. A type used as a constraint must be an interface, a non-sealed class or a type parameter. // where Y : B* Diagnostic(ErrorCode.ERR_BadConstraintType, "B*").WithLocation(13, 44), // (14,44): error CS0706: Invalid constraint type. A type used as a constraint must be an interface, a non-sealed class or a type parameter. // where Z : A.D* Diagnostic(ErrorCode.ERR_BadConstraintType, "A.D*").WithLocation(14, 44), // (16,28): error CS0706: Invalid constraint type. A type used as a constraint must be an interface, a non-sealed class or a type parameter. // void M1<A>() where A : byte* {} Diagnostic(ErrorCode.ERR_BadConstraintType, "byte*").WithLocation(16, 28), // (18,31): error CS0706: Invalid constraint type. A type used as a constraint must be an interface, a non-sealed class or a type parameter. // where B : A* {} Diagnostic(ErrorCode.ERR_BadConstraintType, "A*").WithLocation(18, 31), // (19,28): error CS0706: Invalid constraint type. A type used as a constraint must be an interface, a non-sealed class or a type parameter. // void M3<A>() where A : object* {} Diagnostic(ErrorCode.ERR_BadConstraintType, "object*").WithLocation(19, 28), // (20,28): error CS0706: Invalid constraint type. A type used as a constraint must be an interface, a non-sealed class or a type parameter. // void M4<A>() where A : B* {} Diagnostic(ErrorCode.ERR_BadConstraintType, "B*").WithLocation(20, 28) ); } [Fact] public void ArrayGenericConstraintTypes() { var source = @"class A<T> where T : object[] {}"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (1,22): error CS0706: Invalid constraint type. A type used as a constraint must be an interface, a non-sealed class or a type parameter. // class A<T> where T : object[] {} Diagnostic(ErrorCode.ERR_BadConstraintType, "object[]").WithLocation(1, 22)); } } }
1
dotnet/roslyn
55,132
Support lambda expressions and method groups as `var` initializers
```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
cston
2021-07-27T03:12:21Z
2021-07-27T18:26:42Z
61a565cfcd777158cb6354351436aff997ad7bf6
5840335153dcca42570a853cdacd06d660fe9596
Support lambda expressions and method groups as `var` initializers. ```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
./src/EditorFeatures/CSharpTest/ReplaceDefaultLiteral/ReplaceDefaultLiteralTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.CodeFixes; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.ReplaceDefaultLiteral; 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.ReplaceDefaultLiteral { [Trait(Traits.Feature, Traits.Features.CodeActionsReplaceDefaultLiteral)] public sealed class ReplaceDefaultLiteralTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest { public ReplaceDefaultLiteralTests(ITestOutputHelper logger) : base(logger) { } internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace) => (null, new CSharpReplaceDefaultLiteralCodeFixProvider()); private static readonly ImmutableArray<LanguageVersion> s_csharp7_1above = ImmutableArray.Create( LanguageVersion.CSharp7_1, LanguageVersion.Latest); private static readonly ImmutableArray<LanguageVersion> s_csharp7below = ImmutableArray.Create( LanguageVersion.CSharp7, LanguageVersion.CSharp6, LanguageVersion.CSharp5, LanguageVersion.CSharp4, LanguageVersion.CSharp3, LanguageVersion.CSharp2, LanguageVersion.CSharp1); private async Task TestWithLanguageVersionsAsync(string initialMarkup, string expectedMarkup, ImmutableArray<LanguageVersion> versions) { foreach (var version in versions) { await TestInRegularAndScriptAsync(initialMarkup, expectedMarkup, parseOptions: CSharpParseOptions.Default.WithLanguageVersion(version)); } } private async Task TestMissingWithLanguageVersionsAsync(string initialMarkup, ImmutableArray<LanguageVersion> versions) { foreach (var version in versions) { await TestMissingInRegularAndScriptAsync(initialMarkup, new TestParameters(CSharpParseOptions.Default.WithLanguageVersion(version))); } } [Fact] public async Task TestCSharp7_1_InCaseSwitchLabel_Int() { await TestWithLanguageVersionsAsync( @"class C { void M() { switch (1) { case [||]default: } } }", @"class C { void M() { switch (1) { case 0: } } }", s_csharp7_1above); } [Fact] public async Task TestCSharp7_1_InCaseSwitchLabel_Int_InParentheses() { await TestWithLanguageVersionsAsync( @"class C { void M() { switch (1) { case ([||]default): } } }", @"class C { void M() { switch (1) { case (0): } } }", s_csharp7_1above); } [Fact] public async Task TestCSharp7_1_InCaseSwitchLabel_Int_NotInsideCast() { await TestMissingWithLanguageVersionsAsync( @"class C { void M() { switch (1) { case (int)[||]default: } } }", s_csharp7_1above); } [Fact] public async Task TestCSharp7_1_InCaseSwitchLabel_Int_NotOnDefaultExpression() { await TestMissingWithLanguageVersionsAsync( @"class C { void M() { switch (1) { case [||]default(int): } } }", s_csharp7_1above); } [Fact] public async Task TestCSharp7_1_InCaseSwitchLabel_Int_NotOnNumericLiteral() { await TestMissingWithLanguageVersionsAsync( @"class C { void M() { switch (1) { case [||]0: } } }", s_csharp7_1above); } [Fact] public async Task TestCSharp7_1_InCaseSwitchLabel_DateTime() { // Note that the default value of a struct type is not a constant, so this code is incorrect. await TestWithLanguageVersionsAsync( @"class C { void M() { switch (System.DateTime.Now) { case [||]default: } } }", @"class C { void M() { switch (System.DateTime.Now) { case default(System.DateTime): } } }", s_csharp7_1above); } [Fact] public async Task TestCSharp7_1_InCaseSwitchLabel_TupleType() { // Note that the default value of a tuple type is not a constant, so this code is incorrect. await TestWithLanguageVersionsAsync( @"class C { void M() { switch ((0, true)) { case [||]default: } } }", @"class C { void M() { switch ((0, true)) { case default((int, bool)): } } }", s_csharp7_1above); } [Theory] [InlineData("value")] [InlineData("null")] [InlineData("default")] [InlineData("() => { }")] [InlineData("")] public async Task TestCSharp7_1_InCaseSwitchLabel_NotForInvalidType(string expression) { await TestMissingWithLanguageVersionsAsync( $@"class C {{ void M() {{ switch ({expression}) {{ case [||]default: }} }} }}", s_csharp7_1above); } [Fact] public async Task TestCSharp7_1_InCasePatternSwitchLabel_Int() { await TestWithLanguageVersionsAsync( @"class C { void M() { switch (1) { case [||]default when true: } } }", @"class C { void M() { switch (1) { case 0 when true: } } }", s_csharp7_1above); } [Fact] public async Task TestCSharp7_1_InCasePatternSwitchLabel_Int_InParentheses() { await TestWithLanguageVersionsAsync( @"class C { void M() { switch (1) { case ([||]default) when true: } } }", @"class C { void M() { switch (1) { case (0) when true: } } }", s_csharp7_1above); } [Fact] public async Task TestCSharp7_1_InCasePatternSwitchLabel_Int_NotInsideCast() { await TestMissingWithLanguageVersionsAsync( @"class C { void M() { switch (1) { case (int)[||]default when true: } } }", s_csharp7_1above); } [Fact] public async Task TestCSharp7_1_InCasePatternSwitchLabel_Int_NotOnDefaultExpression() { await TestMissingWithLanguageVersionsAsync( @"class C { void M() { switch (1) { case [||]default(int) when true: } } }", s_csharp7_1above); } [Fact] public async Task TestCSharp7_1_InCasePatternSwitchLabel_Int_NotOnNumericLiteral() { await TestMissingWithLanguageVersionsAsync( @"class C { void M() { switch (1) { case [||]0 when true: } } }", s_csharp7_1above); } [Fact] public async Task TestCSharp7_1_InCasePatternSwitchLabel_DateTime() { // Note that the default value of a struct type is not a constant, so this code is incorrect. await TestWithLanguageVersionsAsync( @"class C { void M() { switch (System.DateTime.Now) { case [||]default when true: } } }", @"class C { void M() { switch (System.DateTime.Now) { case default(System.DateTime) when true: } } }", s_csharp7_1above); } [Fact] public async Task TestCSharp7_1_InCasePatternSwitchLabel_TupleType() { // Note that the default value of a tuple type is not a constant, so this code is incorrect. await TestWithLanguageVersionsAsync( @"class C { void M() { switch ((0, true)) { case [||]default when true: } } }", @"class C { void M() { switch ((0, true)) { case default((int, bool)) when true: } } }", s_csharp7_1above); } [Theory] [InlineData("value")] [InlineData("null")] [InlineData("default")] [InlineData("() => { }")] [InlineData("")] public async Task TestCSharp7_1_InCasePatternSwitchLabel_NotForInvalidType(string expression) { await TestMissingWithLanguageVersionsAsync( $@"class C {{ void M() {{ switch ({expression}) {{ case [||]default when true: }} }} }}", s_csharp7_1above); } [Fact] public async Task TestCSharp7_1_InIsPattern_Bool() { await TestWithLanguageVersionsAsync( @"class C { void M() { if (true is [||]default) { } } }", @"class C { void M() { if (true is false) { } } }", s_csharp7_1above); } [Fact] public async Task TestCSharp7_1_InIsPattern_Bool_InParentheses() { await TestWithLanguageVersionsAsync( @"class C { void M() { if (true is ([||]default)) { } } }", @"class C { void M() { if (true is (false)) { } } }", s_csharp7_1above); } [Fact] public async Task TestCSharp7_1_InIsPattern_Bool_NotInsideCast() { await TestMissingWithLanguageVersionsAsync( @"class C { void M() { if (true is (bool)[||]default) { } } }", s_csharp7_1above); } [Fact] public async Task TestCSharp7_1_InIsPattern_Bool_NotOnDefaultExpression() { await TestMissingWithLanguageVersionsAsync( @"class C { void M() { if (true is [||]default(bool)) { } } }", s_csharp7_1above); } [Fact] public async Task TestCSharp7_1_InIsPattern_Bool_NotOnFalseLiteral() { await TestMissingWithLanguageVersionsAsync( @"class C { void M() { if (true is [||]false) { } } }", s_csharp7_1above); } [Theory] [InlineData("int", "0")] [InlineData("uint", "0U")] [InlineData("byte", "0")] [InlineData("sbyte", "0")] [InlineData("short", "0")] [InlineData("ushort", "0")] [InlineData("long", "0L")] [InlineData("ulong", "0UL")] [InlineData("float", "0F")] [InlineData("double", "0D")] [InlineData("decimal", "0M")] [InlineData("char", "'\\0'")] [InlineData("string", "null")] [InlineData("object", "null")] public async Task TestCSharp7_1_InIsPattern_BuiltInType(string type, string expectedLiteral) { await TestWithLanguageVersionsAsync( $@"class C {{ void M({type} value) {{ if (value is [||]default) {{ }} }} }}", $@"class C {{ void M({type} value) {{ if (value is {expectedLiteral}) {{ }} }} }}", s_csharp7_1above); } [Fact] public async Task TestCSharp7_1_InIsPattern_DateTime() { // Note that the default value of a struct type is not a constant, so this code is incorrect. await TestWithLanguageVersionsAsync( @"class C { void M() { if (System.DateTime.Now is [||]default) { } } }", @"class C { void M() { if (System.DateTime.Now is default(System.DateTime)) { } } }", s_csharp7_1above); } [Fact] public async Task TestCSharp7_1_InIsPattern_TupleType() { // Note that the default value of a tuple type is not a constant, so this code is incorrect. await TestWithLanguageVersionsAsync( @"class C { void M() { if ((0, true) is [||]default) { } } }", @"class C { void M() { if ((0, true) is default((int, bool))) { } } }", s_csharp7_1above); } [Theory] [InlineData("class Type { }")] [InlineData("interface Type { }")] [InlineData("delegate void Type();")] public async Task TestCSharp7_1_InIsPattern_CustomReferenceType(string typeDeclaration) { await TestWithLanguageVersionsAsync( $@"class C {{ {typeDeclaration} void M() {{ if (new Type() is [||]default) {{ }} }} }}", $@"class C {{ {typeDeclaration} void M() {{ if (new Type() is null) {{ }} }} }}", s_csharp7_1above); } [Theory] [InlineData("enum Enum { }")] [InlineData("enum Enum { None = 0 }")] [InlineData("[Flags] enum Enum { None = 0 }")] [InlineData("[System.Flags] enum Enum { None = 1 }")] [InlineData("[System.Flags] enum Enum { None = 1, None = 0 }")] [InlineData("[System.Flags] enum Enum { Some = 0 }")] public async Task TestCSharp7_1_InIsPattern_CustomEnum_WithoutSpecialMember(string enumDeclaration) { await TestWithLanguageVersionsAsync( $@"class C {{ {enumDeclaration} void M() {{ if (new Enum() is [||]default) {{ }} }} }}", $@"class C {{ {enumDeclaration} void M() {{ if (new Enum() is 0) {{ }} }} }}", s_csharp7_1above); } [Theory] [InlineData("[System.Flags] enum Enum : int { None = 0 }")] [InlineData("[System.Flags] enum Enum : uint { None = 0 }")] [InlineData("[System.Flags] enum Enum : byte { None = 0 }")] [InlineData("[System.Flags] enum Enum : sbyte { None = 0 }")] [InlineData("[System.Flags] enum Enum : short { None = 0 }")] [InlineData("[System.Flags] enum Enum : ushort { None = 0 }")] [InlineData("[System.Flags] enum Enum : long { None = 0 }")] [InlineData("[System.Flags] enum Enum : ulong { None = 0 }")] [InlineData("[System.Flags] enum Enum { None = default }")] [InlineData("[System.Flags] enum Enum { Some = 1, None = 0 }")] [InlineData("[System.FlagsAttribute] enum Enum { None = 0, Some = 1 }")] public async Task TestCSharp7_1_InIsPattern_CustomEnum_WithSpecialMember(string enumDeclaration) { await TestWithLanguageVersionsAsync( $@"class C {{ {enumDeclaration} void M() {{ if (new Enum() is [||]default) {{ }} }} }}", $@"class C {{ {enumDeclaration} void M() {{ if (new Enum() is Enum.None) {{ }} }} }}", s_csharp7_1above); } [Fact] public async Task TestCSharp7_1_InIsPattern_CustomStruct() { // Note that the default value of a struct type is not a constant, so this code is incorrect. await TestWithLanguageVersionsAsync( @"class C { struct Struct { } void M() { if (new Struct() is [||]default) { } } }", @"class C { struct Struct { } void M() { if (new Struct() is default(Struct)) { } } }", s_csharp7_1above); } [Fact] public async Task TestCSharp7_1_InIsPattern_AnonymousType() { await TestWithLanguageVersionsAsync( @"class C { void M() { if (new { a = 0 } is [||]default) { } } }", @"class C { void M() { if (new { a = 0 } is null) { } } }", s_csharp7_1above); } [Theory] [InlineData("class Container<T> { }")] [InlineData("interface Container<T> { }")] [InlineData("delegate void Container<T>();")] public async Task TestCSharp7_1_InIsPattern_CustomReferenceTypeOfAnonymousType(string typeDeclaration) { await TestWithLanguageVersionsAsync( $@"class C {{ {typeDeclaration} Container<T> ToContainer<T>(T value) => new Container<T>(); void M() {{ if (ToContainer(new {{ x = 0 }}) is [||]default) {{ }} }} }}", $@"class C {{ {typeDeclaration} Container<T> ToContainer<T>(T value) => new Container<T>(); void M() {{ if (ToContainer(new {{ x = 0 }}) is null) {{ }} }} }}", s_csharp7_1above); } [Fact] public async Task TestCSharp7_1_InIsPattern_NotForCustomStructOfAnonymousType() { await TestMissingWithLanguageVersionsAsync( @"class C { struct Container<T> { } Container<T> ToContainer<T>(T value) => new Container<T>(); void M() { if (ToContainer(new { x = 0 }) is [||]default) { } } }", s_csharp7_1above); } [Theory] [InlineData("System.Threading", "CancellationToken", "None")] [InlineData("System", "IntPtr", "Zero")] [InlineData("System", "UIntPtr", "Zero")] public async Task TestCSharp7_1_InIsPattern_SpecialTypeQualified(string @namespace, string type, string member) { await TestWithLanguageVersionsAsync( $@"class C {{ void M() {{ if (default({@namespace}.{type}) is [||]default) {{ }} }} }}", $@"class C {{ void M() {{ if (default({@namespace}.{type}) is {@namespace}.{type}.{member}) {{ }} }} }}", s_csharp7_1above); } [Theory] [InlineData("System.Threading", "CancellationToken", "None")] [InlineData("System", "IntPtr", "Zero")] [InlineData("System", "UIntPtr", "Zero")] public async Task TestCSharp7_1_InIsPattern_SpecialTypeUnqualifiedWithUsing(string @namespace, string type, string member) { await TestWithLanguageVersionsAsync( $@"using {@namespace}; class C {{ void M() {{ if (default({type}) is [||]default) {{ }} }} }}", $@"using {@namespace}; class C {{ void M() {{ if (default({type}) is {type}.{member}) {{ }} }} }}", s_csharp7_1above); } [Theory] [InlineData("CancellationToken")] [InlineData("IntPtr")] [InlineData("UIntPtr")] public async Task TestCSharp7_1_InIsPattern_NotForSpecialTypeUnqualifiedWithoutUsing(string type) { await TestMissingWithLanguageVersionsAsync( $@"class C {{ void M() {{ if (default({type}) is [||]default) {{ }} }} }}", s_csharp7_1above); } [Fact] public async Task TestCSharp7_1_InIsPattern_NotForInvalidType1() { await TestMissingWithLanguageVersionsAsync( @"class C { void M() { var value; if (value is [||]default) { } } }", s_csharp7_1above); } [Theory] [InlineData("value")] [InlineData("null")] [InlineData("default")] [InlineData("() => { }")] [InlineData("")] public async Task TestCSharp7_1_InIsPattern_NotForInvalidType2(string expression) { await TestMissingWithLanguageVersionsAsync( $@"class C {{ void M() {{ var value = {expression}; if (value is [||]default) {{ }} }} }}", s_csharp7_1above); } [Theory] [InlineData("value")] [InlineData("null")] [InlineData("default")] [InlineData("() => { }")] [InlineData("")] public async Task TestCSharp7_1_InIsPattern_NotForInvalidType3(string expression) { await TestMissingWithLanguageVersionsAsync( $@"class C {{ void M() {{ if ({expression} is [||]default) {{ }} }} }}", s_csharp7_1above); } [Fact] public async Task TestCSharp7_1_InIsPattern_Bool_Trivia() { await TestWithLanguageVersionsAsync( @"class C { void M() { if (true is /*a*/ [||]default /*b*/) { } } }", @"class C { void M() { if (true is /*a*/ false /*b*/) { } } }", s_csharp7_1above); } [Fact] public async Task TestCSharp7_1_InIsPattern_DateTime_Trivia() { await TestWithLanguageVersionsAsync( @"class C { void M() { if (System.DateTime.Now is /*a*/ [||]default /*b*/) { } } }", @"class C { void M() { if (System.DateTime.Now is /*a*/ default(System.DateTime) /*b*/) { } } }", s_csharp7_1above); } [Fact] public async Task TestCSharp7_1_NotInsideExpression() { await TestMissingWithLanguageVersionsAsync( @"class C { void M() { int i = [||]default; } }", s_csharp7_1above); } [Fact] public async Task TestCSharp7_1_NotInsideExpression_InvalidType() { await TestMissingWithLanguageVersionsAsync( @"class C { void M() { var v = [||]default; } }", s_csharp7_1above); } [Fact] public async Task TestCSharp7Lower_NotInsideExpression() { await TestMissingWithLanguageVersionsAsync( @"class C { void M() { int i = [||]default; } }", s_csharp7below); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.CodeFixes; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.ReplaceDefaultLiteral; 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.ReplaceDefaultLiteral { [Trait(Traits.Feature, Traits.Features.CodeActionsReplaceDefaultLiteral)] public sealed class ReplaceDefaultLiteralTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest { public ReplaceDefaultLiteralTests(ITestOutputHelper logger) : base(logger) { } internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace) => (null, new CSharpReplaceDefaultLiteralCodeFixProvider()); private static readonly ImmutableArray<LanguageVersion> s_csharp7_1above = ImmutableArray.Create( LanguageVersion.CSharp7_1, LanguageVersion.Latest); private static readonly ImmutableArray<LanguageVersion> s_csharp7below = ImmutableArray.Create( LanguageVersion.CSharp7, LanguageVersion.CSharp6, LanguageVersion.CSharp5, LanguageVersion.CSharp4, LanguageVersion.CSharp3, LanguageVersion.CSharp2, LanguageVersion.CSharp1); private async Task TestWithLanguageVersionsAsync(string initialMarkup, string expectedMarkup, ImmutableArray<LanguageVersion> versions) { foreach (var version in versions) { await TestInRegularAndScriptAsync(initialMarkup, expectedMarkup, parseOptions: CSharpParseOptions.Default.WithLanguageVersion(version)); } } private async Task TestMissingWithLanguageVersionsAsync(string initialMarkup, ImmutableArray<LanguageVersion> versions) { foreach (var version in versions) { await TestMissingInRegularAndScriptAsync(initialMarkup, new TestParameters(CSharpParseOptions.Default.WithLanguageVersion(version))); } } [Fact] public async Task TestCSharp7_1_InCaseSwitchLabel_Int() { await TestWithLanguageVersionsAsync( @"class C { void M() { switch (1) { case [||]default: } } }", @"class C { void M() { switch (1) { case 0: } } }", s_csharp7_1above); } [Fact] public async Task TestCSharp7_1_InCaseSwitchLabel_Int_InParentheses() { await TestWithLanguageVersionsAsync( @"class C { void M() { switch (1) { case ([||]default): } } }", @"class C { void M() { switch (1) { case (0): } } }", s_csharp7_1above); } [Fact] public async Task TestCSharp7_1_InCaseSwitchLabel_Int_NotInsideCast() { await TestMissingWithLanguageVersionsAsync( @"class C { void M() { switch (1) { case (int)[||]default: } } }", s_csharp7_1above); } [Fact] public async Task TestCSharp7_1_InCaseSwitchLabel_Int_NotOnDefaultExpression() { await TestMissingWithLanguageVersionsAsync( @"class C { void M() { switch (1) { case [||]default(int): } } }", s_csharp7_1above); } [Fact] public async Task TestCSharp7_1_InCaseSwitchLabel_Int_NotOnNumericLiteral() { await TestMissingWithLanguageVersionsAsync( @"class C { void M() { switch (1) { case [||]0: } } }", s_csharp7_1above); } [Fact] public async Task TestCSharp7_1_InCaseSwitchLabel_DateTime() { // Note that the default value of a struct type is not a constant, so this code is incorrect. await TestWithLanguageVersionsAsync( @"class C { void M() { switch (System.DateTime.Now) { case [||]default: } } }", @"class C { void M() { switch (System.DateTime.Now) { case default(System.DateTime): } } }", s_csharp7_1above); } [Fact] public async Task TestCSharp7_1_InCaseSwitchLabel_TupleType() { // Note that the default value of a tuple type is not a constant, so this code is incorrect. await TestWithLanguageVersionsAsync( @"class C { void M() { switch ((0, true)) { case [||]default: } } }", @"class C { void M() { switch ((0, true)) { case default((int, bool)): } } }", s_csharp7_1above); } [Theory] [InlineData("value")] [InlineData("null")] [InlineData("default")] [InlineData("() => { }")] [InlineData("")] public async Task TestCSharp7_1_InCaseSwitchLabel_NotForInvalidType(string expression) { await TestMissingWithLanguageVersionsAsync( $@"class C {{ void M() {{ switch ({expression}) {{ case [||]default: }} }} }}", s_csharp7_1above); } [Fact] public async Task TestCSharp7_1_InCasePatternSwitchLabel_Int() { await TestWithLanguageVersionsAsync( @"class C { void M() { switch (1) { case [||]default when true: } } }", @"class C { void M() { switch (1) { case 0 when true: } } }", s_csharp7_1above); } [Fact] public async Task TestCSharp7_1_InCasePatternSwitchLabel_Int_InParentheses() { await TestWithLanguageVersionsAsync( @"class C { void M() { switch (1) { case ([||]default) when true: } } }", @"class C { void M() { switch (1) { case (0) when true: } } }", s_csharp7_1above); } [Fact] public async Task TestCSharp7_1_InCasePatternSwitchLabel_Int_NotInsideCast() { await TestMissingWithLanguageVersionsAsync( @"class C { void M() { switch (1) { case (int)[||]default when true: } } }", s_csharp7_1above); } [Fact] public async Task TestCSharp7_1_InCasePatternSwitchLabel_Int_NotOnDefaultExpression() { await TestMissingWithLanguageVersionsAsync( @"class C { void M() { switch (1) { case [||]default(int) when true: } } }", s_csharp7_1above); } [Fact] public async Task TestCSharp7_1_InCasePatternSwitchLabel_Int_NotOnNumericLiteral() { await TestMissingWithLanguageVersionsAsync( @"class C { void M() { switch (1) { case [||]0 when true: } } }", s_csharp7_1above); } [Fact] public async Task TestCSharp7_1_InCasePatternSwitchLabel_DateTime() { // Note that the default value of a struct type is not a constant, so this code is incorrect. await TestWithLanguageVersionsAsync( @"class C { void M() { switch (System.DateTime.Now) { case [||]default when true: } } }", @"class C { void M() { switch (System.DateTime.Now) { case default(System.DateTime) when true: } } }", s_csharp7_1above); } [Fact] public async Task TestCSharp7_1_InCasePatternSwitchLabel_TupleType() { // Note that the default value of a tuple type is not a constant, so this code is incorrect. await TestWithLanguageVersionsAsync( @"class C { void M() { switch ((0, true)) { case [||]default when true: } } }", @"class C { void M() { switch ((0, true)) { case default((int, bool)) when true: } } }", s_csharp7_1above); } [Theory] [InlineData("value")] [InlineData("null")] [InlineData("default")] [InlineData("() => { }")] [InlineData("")] public async Task TestCSharp7_1_InCasePatternSwitchLabel_NotForInvalidType(string expression) { await TestMissingWithLanguageVersionsAsync( $@"class C {{ void M() {{ switch ({expression}) {{ case [||]default when true: }} }} }}", s_csharp7_1above); } [Fact] public async Task TestCSharp7_1_InIsPattern_Bool() { await TestWithLanguageVersionsAsync( @"class C { void M() { if (true is [||]default) { } } }", @"class C { void M() { if (true is false) { } } }", s_csharp7_1above); } [Fact] public async Task TestCSharp7_1_InIsPattern_Bool_InParentheses() { await TestWithLanguageVersionsAsync( @"class C { void M() { if (true is ([||]default)) { } } }", @"class C { void M() { if (true is (false)) { } } }", s_csharp7_1above); } [Fact] public async Task TestCSharp7_1_InIsPattern_Bool_NotInsideCast() { await TestMissingWithLanguageVersionsAsync( @"class C { void M() { if (true is (bool)[||]default) { } } }", s_csharp7_1above); } [Fact] public async Task TestCSharp7_1_InIsPattern_Bool_NotOnDefaultExpression() { await TestMissingWithLanguageVersionsAsync( @"class C { void M() { if (true is [||]default(bool)) { } } }", s_csharp7_1above); } [Fact] public async Task TestCSharp7_1_InIsPattern_Bool_NotOnFalseLiteral() { await TestMissingWithLanguageVersionsAsync( @"class C { void M() { if (true is [||]false) { } } }", s_csharp7_1above); } [Theory] [InlineData("int", "0")] [InlineData("uint", "0U")] [InlineData("byte", "0")] [InlineData("sbyte", "0")] [InlineData("short", "0")] [InlineData("ushort", "0")] [InlineData("long", "0L")] [InlineData("ulong", "0UL")] [InlineData("float", "0F")] [InlineData("double", "0D")] [InlineData("decimal", "0M")] [InlineData("char", "'\\0'")] [InlineData("string", "null")] [InlineData("object", "null")] public async Task TestCSharp7_1_InIsPattern_BuiltInType(string type, string expectedLiteral) { await TestWithLanguageVersionsAsync( $@"class C {{ void M({type} value) {{ if (value is [||]default) {{ }} }} }}", $@"class C {{ void M({type} value) {{ if (value is {expectedLiteral}) {{ }} }} }}", s_csharp7_1above); } [Fact] public async Task TestCSharp7_1_InIsPattern_DateTime() { // Note that the default value of a struct type is not a constant, so this code is incorrect. await TestWithLanguageVersionsAsync( @"class C { void M() { if (System.DateTime.Now is [||]default) { } } }", @"class C { void M() { if (System.DateTime.Now is default(System.DateTime)) { } } }", s_csharp7_1above); } [Fact] public async Task TestCSharp7_1_InIsPattern_TupleType() { // Note that the default value of a tuple type is not a constant, so this code is incorrect. await TestWithLanguageVersionsAsync( @"class C { void M() { if ((0, true) is [||]default) { } } }", @"class C { void M() { if ((0, true) is default((int, bool))) { } } }", s_csharp7_1above); } [Theory] [InlineData("class Type { }")] [InlineData("interface Type { }")] [InlineData("delegate void Type();")] public async Task TestCSharp7_1_InIsPattern_CustomReferenceType(string typeDeclaration) { await TestWithLanguageVersionsAsync( $@"class C {{ {typeDeclaration} void M() {{ if (new Type() is [||]default) {{ }} }} }}", $@"class C {{ {typeDeclaration} void M() {{ if (new Type() is null) {{ }} }} }}", s_csharp7_1above); } [Theory] [InlineData("enum Enum { }")] [InlineData("enum Enum { None = 0 }")] [InlineData("[Flags] enum Enum { None = 0 }")] [InlineData("[System.Flags] enum Enum { None = 1 }")] [InlineData("[System.Flags] enum Enum { None = 1, None = 0 }")] [InlineData("[System.Flags] enum Enum { Some = 0 }")] public async Task TestCSharp7_1_InIsPattern_CustomEnum_WithoutSpecialMember(string enumDeclaration) { await TestWithLanguageVersionsAsync( $@"class C {{ {enumDeclaration} void M() {{ if (new Enum() is [||]default) {{ }} }} }}", $@"class C {{ {enumDeclaration} void M() {{ if (new Enum() is 0) {{ }} }} }}", s_csharp7_1above); } [Theory] [InlineData("[System.Flags] enum Enum : int { None = 0 }")] [InlineData("[System.Flags] enum Enum : uint { None = 0 }")] [InlineData("[System.Flags] enum Enum : byte { None = 0 }")] [InlineData("[System.Flags] enum Enum : sbyte { None = 0 }")] [InlineData("[System.Flags] enum Enum : short { None = 0 }")] [InlineData("[System.Flags] enum Enum : ushort { None = 0 }")] [InlineData("[System.Flags] enum Enum : long { None = 0 }")] [InlineData("[System.Flags] enum Enum : ulong { None = 0 }")] [InlineData("[System.Flags] enum Enum { None = default }")] [InlineData("[System.Flags] enum Enum { Some = 1, None = 0 }")] [InlineData("[System.FlagsAttribute] enum Enum { None = 0, Some = 1 }")] public async Task TestCSharp7_1_InIsPattern_CustomEnum_WithSpecialMember(string enumDeclaration) { await TestWithLanguageVersionsAsync( $@"class C {{ {enumDeclaration} void M() {{ if (new Enum() is [||]default) {{ }} }} }}", $@"class C {{ {enumDeclaration} void M() {{ if (new Enum() is Enum.None) {{ }} }} }}", s_csharp7_1above); } [Fact] public async Task TestCSharp7_1_InIsPattern_CustomStruct() { // Note that the default value of a struct type is not a constant, so this code is incorrect. await TestWithLanguageVersionsAsync( @"class C { struct Struct { } void M() { if (new Struct() is [||]default) { } } }", @"class C { struct Struct { } void M() { if (new Struct() is default(Struct)) { } } }", s_csharp7_1above); } [Fact] public async Task TestCSharp7_1_InIsPattern_AnonymousType() { await TestWithLanguageVersionsAsync( @"class C { void M() { if (new { a = 0 } is [||]default) { } } }", @"class C { void M() { if (new { a = 0 } is null) { } } }", s_csharp7_1above); } [Theory] [InlineData("class Container<T> { }")] [InlineData("interface Container<T> { }")] [InlineData("delegate void Container<T>();")] public async Task TestCSharp7_1_InIsPattern_CustomReferenceTypeOfAnonymousType(string typeDeclaration) { await TestWithLanguageVersionsAsync( $@"class C {{ {typeDeclaration} Container<T> ToContainer<T>(T value) => new Container<T>(); void M() {{ if (ToContainer(new {{ x = 0 }}) is [||]default) {{ }} }} }}", $@"class C {{ {typeDeclaration} Container<T> ToContainer<T>(T value) => new Container<T>(); void M() {{ if (ToContainer(new {{ x = 0 }}) is null) {{ }} }} }}", s_csharp7_1above); } [Fact] public async Task TestCSharp7_1_InIsPattern_NotForCustomStructOfAnonymousType() { await TestMissingWithLanguageVersionsAsync( @"class C { struct Container<T> { } Container<T> ToContainer<T>(T value) => new Container<T>(); void M() { if (ToContainer(new { x = 0 }) is [||]default) { } } }", s_csharp7_1above); } [Theory] [InlineData("System.Threading", "CancellationToken", "None")] [InlineData("System", "IntPtr", "Zero")] [InlineData("System", "UIntPtr", "Zero")] public async Task TestCSharp7_1_InIsPattern_SpecialTypeQualified(string @namespace, string type, string member) { await TestWithLanguageVersionsAsync( $@"class C {{ void M() {{ if (default({@namespace}.{type}) is [||]default) {{ }} }} }}", $@"class C {{ void M() {{ if (default({@namespace}.{type}) is {@namespace}.{type}.{member}) {{ }} }} }}", s_csharp7_1above); } [Theory] [InlineData("System.Threading", "CancellationToken", "None")] [InlineData("System", "IntPtr", "Zero")] [InlineData("System", "UIntPtr", "Zero")] public async Task TestCSharp7_1_InIsPattern_SpecialTypeUnqualifiedWithUsing(string @namespace, string type, string member) { await TestWithLanguageVersionsAsync( $@"using {@namespace}; class C {{ void M() {{ if (default({type}) is [||]default) {{ }} }} }}", $@"using {@namespace}; class C {{ void M() {{ if (default({type}) is {type}.{member}) {{ }} }} }}", s_csharp7_1above); } [Theory] [InlineData("CancellationToken")] [InlineData("IntPtr")] [InlineData("UIntPtr")] public async Task TestCSharp7_1_InIsPattern_NotForSpecialTypeUnqualifiedWithoutUsing(string type) { await TestMissingWithLanguageVersionsAsync( $@"class C {{ void M() {{ if (default({type}) is [||]default) {{ }} }} }}", s_csharp7_1above); } [Fact] public async Task TestCSharp7_1_InIsPattern_NotForInvalidType1() { await TestMissingWithLanguageVersionsAsync( @"class C { void M() { var value; if (value is [||]default) { } } }", s_csharp7_1above); } [Theory] [InlineData("value")] [InlineData("null")] [InlineData("default")] [InlineData("")] public async Task TestCSharp7_1_InIsPattern_NotForInvalidType2(string expression) { await TestMissingWithLanguageVersionsAsync( $@"class C {{ void M() {{ var value = {expression}; if (value is [||]default) {{ }} }} }}", s_csharp7_1above); } [Theory] [InlineData("value")] [InlineData("null")] [InlineData("default")] [InlineData("() => { }")] [InlineData("")] public async Task TestCSharp7_1_InIsPattern_NotForInvalidType3(string expression) { await TestMissingWithLanguageVersionsAsync( $@"class C {{ void M() {{ if ({expression} is [||]default) {{ }} }} }}", s_csharp7_1above); } [Fact] public async Task TestCSharp7_1_InIsPattern_Lambda() { await TestWithLanguageVersionsAsync( $@"class C {{ void M() {{ var value = () => {{ }}; if (value is [||]default) {{ }} }} }}", $@"class C {{ void M() {{ var value = () => {{ }}; if (value is null) {{ }} }} }}", s_csharp7_1above); } [Fact] public async Task TestCSharp7_1_InIsPattern_Bool_Trivia() { await TestWithLanguageVersionsAsync( @"class C { void M() { if (true is /*a*/ [||]default /*b*/) { } } }", @"class C { void M() { if (true is /*a*/ false /*b*/) { } } }", s_csharp7_1above); } [Fact] public async Task TestCSharp7_1_InIsPattern_DateTime_Trivia() { await TestWithLanguageVersionsAsync( @"class C { void M() { if (System.DateTime.Now is /*a*/ [||]default /*b*/) { } } }", @"class C { void M() { if (System.DateTime.Now is /*a*/ default(System.DateTime) /*b*/) { } } }", s_csharp7_1above); } [Fact] public async Task TestCSharp7_1_NotInsideExpression() { await TestMissingWithLanguageVersionsAsync( @"class C { void M() { int i = [||]default; } }", s_csharp7_1above); } [Fact] public async Task TestCSharp7_1_NotInsideExpression_InvalidType() { await TestMissingWithLanguageVersionsAsync( @"class C { void M() { var v = [||]default; } }", s_csharp7_1above); } [Fact] public async Task TestCSharp7Lower_NotInsideExpression() { await TestMissingWithLanguageVersionsAsync( @"class C { void M() { int i = [||]default; } }", s_csharp7below); } } }
1
dotnet/roslyn
55,132
Support lambda expressions and method groups as `var` initializers
```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
cston
2021-07-27T03:12:21Z
2021-07-27T18:26:42Z
61a565cfcd777158cb6354351436aff997ad7bf6
5840335153dcca42570a853cdacd06d660fe9596
Support lambda expressions and method groups as `var` initializers. ```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
./src/EditorFeatures/CSharpTest/UseExplicitTypeForConst/UseExplicitTypeForConstTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.UseExplicitTypeForConst; 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.UseExplicitTypeForConst { [Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitTypeForConst)] public sealed class UseExplicitTypeForConstTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest { public UseExplicitTypeForConstTests(ITestOutputHelper logger) : base(logger) { } internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace) => (null, new UseExplicitTypeForConstCodeFixProvider()); [Fact] public async Task TestWithIntLiteral() { await TestInRegularAndScriptAsync( @"class C { void M() { const [|var|] v = 0; } }", @"class C { void M() { const int v = 0; } }"); } [Fact] public async Task TestWithStringConstant() { await TestInRegularAndScriptAsync( @"class C { const string s = null; void M() { const [|var|] v = s; } }", @"class C { const string s = null; void M() { const string v = s; } }"); } [Fact] public async Task TestWithQualifiedType() { await TestInRegularAndScriptAsync( @"class C { void M() { const [|var|] v = default(System.Action); } }", @"class C { void M() { const System.Action v = default(System.Action); } }"); } [Fact] public async Task TestWithNonConstantInitializer() { await TestInRegularAndScriptAsync( @"class C { void M() { const [|var|] v = System.Console.ReadLine(); } }", @"class C { void M() { const string v = System.Console.ReadLine(); } }"); } [Fact] public async Task TestWithNonConstantTupleType() { await TestInRegularAndScriptAsync( @"class C { void M() { const [|var|] v = (0, true); } }", @"class C { void M() { const (int, bool) v = (0, true); } }"); } [Fact] public async Task TestNotWithNullLiteral() { await TestMissingInRegularAndScriptAsync( @"class C { void M() { const [|var|] v = null; } }"); } [Fact] public async Task TestNotWithDefaultLiteral() { await TestMissingInRegularAndScriptAsync( @"class C { void M() { const [|var|] v = default; } }"); } [Fact] public async Task TestNotWithLambda() { await TestMissingInRegularAndScriptAsync( @"class C { void M() { const [|var|] v = () => { }; } }"); } [Fact] public async Task TestNotWithAnonymousType() { await TestMissingInRegularAndScriptAsync( @"class C { void M() { const [|var|] v = new { a = 0 }; } }"); } [Fact] public async Task TestNotWithArrayInitializer() { await TestMissingInRegularAndScriptAsync( @"class C { void M() { const [|var|] v = { 0, 1 }; } }"); } [Fact] public async Task TestNotWithMissingInitializer() { await TestMissingInRegularAndScriptAsync( @"class C { void M() { const [|var|] v = } }"); } [Fact] public async Task TestNotWithClassVar() { await TestMissingInRegularAndScriptAsync( @"class C { class var { } void M() { const [|var|] v = 0; } }"); } [Fact] public async Task TestNotOnField() { await TestMissingInRegularAndScriptAsync( @"class C { const [|var|] v = 0; }"); } [Fact] public async Task TestNotWithMultipleDeclarators() { await TestMissingInRegularAndScriptAsync( @"class C { void M() { const [|var|] a = 0, b = 0; } }"); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CSharp.UseExplicitTypeForConst; 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.UseExplicitTypeForConst { [Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitTypeForConst)] public sealed class UseExplicitTypeForConstTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest { public UseExplicitTypeForConstTests(ITestOutputHelper logger) : base(logger) { } internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace) => (null, new UseExplicitTypeForConstCodeFixProvider()); [Fact] public async Task TestWithIntLiteral() { await TestInRegularAndScriptAsync( @"class C { void M() { const [|var|] v = 0; } }", @"class C { void M() { const int v = 0; } }"); } [Fact] public async Task TestWithStringConstant() { await TestInRegularAndScriptAsync( @"class C { const string s = null; void M() { const [|var|] v = s; } }", @"class C { const string s = null; void M() { const string v = s; } }"); } [Fact] public async Task TestWithQualifiedType() { await TestInRegularAndScriptAsync( @"class C { void M() { const [|var|] v = default(System.Action); } }", @"class C { void M() { const System.Action v = default(System.Action); } }"); } [Fact] public async Task TestWithNonConstantInitializer() { await TestInRegularAndScriptAsync( @"class C { void M() { const [|var|] v = System.Console.ReadLine(); } }", @"class C { void M() { const string v = System.Console.ReadLine(); } }"); } [Fact] public async Task TestWithNonConstantTupleType() { await TestInRegularAndScriptAsync( @"class C { void M() { const [|var|] v = (0, true); } }", @"class C { void M() { const (int, bool) v = (0, true); } }"); } [Fact] public async Task TestNotWithNullLiteral() { await TestMissingInRegularAndScriptAsync( @"class C { void M() { const [|var|] v = null; } }"); } [Fact] public async Task TestNotWithDefaultLiteral() { await TestMissingInRegularAndScriptAsync( @"class C { void M() { const [|var|] v = default; } }"); } [Fact] public async Task TestWithLambda() { await TestInRegularAndScriptAsync( @"class C { void M() { const [|var|] v = () => { }; } }", @"class C { void M() { const System.Action v = () => { }; } }"); } [Fact] public async Task TestNotWithAnonymousType() { await TestMissingInRegularAndScriptAsync( @"class C { void M() { const [|var|] v = new { a = 0 }; } }"); } [Fact] public async Task TestNotWithArrayInitializer() { await TestMissingInRegularAndScriptAsync( @"class C { void M() { const [|var|] v = { 0, 1 }; } }"); } [Fact] public async Task TestNotWithMissingInitializer() { await TestMissingInRegularAndScriptAsync( @"class C { void M() { const [|var|] v = } }"); } [Fact] public async Task TestNotWithClassVar() { await TestMissingInRegularAndScriptAsync( @"class C { class var { } void M() { const [|var|] v = 0; } }"); } [Fact] public async Task TestNotOnField() { await TestMissingInRegularAndScriptAsync( @"class C { const [|var|] v = 0; }"); } [Fact] public async Task TestNotWithMultipleDeclarators() { await TestMissingInRegularAndScriptAsync( @"class C { void M() { const [|var|] a = 0, b = 0; } }"); } } }
1
dotnet/roslyn
55,132
Support lambda expressions and method groups as `var` initializers
```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
cston
2021-07-27T03:12:21Z
2021-07-27T18:26:42Z
61a565cfcd777158cb6354351436aff997ad7bf6
5840335153dcca42570a853cdacd06d660fe9596
Support lambda expressions and method groups as `var` initializers. ```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
./src/EditorFeatures/Core/Implementation/Interactive/InteractiveSession.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. extern alias InteractiveHost; extern alias Scripting; using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Scripting.Hosting; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.Interactive { using InteractiveHost::Microsoft.CodeAnalysis.Interactive; using RelativePathResolver = Scripting::Microsoft.CodeAnalysis.RelativePathResolver; internal sealed class InteractiveSession : IDisposable { public InteractiveHost Host { get; } private readonly IThreadingContext _threadingContext; private readonly InteractiveEvaluatorLanguageInfoProvider _languageInfo; private readonly InteractiveWorkspace _workspace; private readonly CancellationTokenSource _shutdownCancellationSource; private readonly string _hostDirectory; #region State only accessible by queued tasks // Use to serialize InteractiveHost process initialization and code execution. // The process may restart any time and we need to react to that by clearing // the current solution and setting up the first submission project. // At the same time a code submission might be in progress. // If we left these operations run in parallel we might get into a state // inconsistent with the state of the host. private readonly TaskQueue _taskQueue; private ProjectId? _lastSuccessfulSubmissionProjectId; private ProjectId? _currentSubmissionProjectId; public int SubmissionCount { get; private set; } private RemoteInitializationResult? _initializationResult; private InteractiveHostPlatformInfo _platformInfo; private ImmutableArray<string> _referenceSearchPaths; private ImmutableArray<string> _sourceSearchPaths; private string _workingDirectory; /// <summary> /// Buffers that need to be associated with a submission project once the process initialization completes. /// </summary> private readonly List<(ITextBuffer buffer, string name)> _pendingBuffers = new(); #endregion public InteractiveSession( InteractiveWorkspace workspace, IThreadingContext threadingContext, IAsynchronousOperationListener listener, InteractiveEvaluatorLanguageInfoProvider languageInfo, string initialWorkingDirectory) { _workspace = workspace; _threadingContext = threadingContext; _languageInfo = languageInfo; _taskQueue = new TaskQueue(listener, TaskScheduler.Default); _shutdownCancellationSource = new CancellationTokenSource(); // The following settings will apply when the REPL starts without .rsp file. // They are discarded once the REPL is reset. _referenceSearchPaths = ImmutableArray<string>.Empty; _sourceSearchPaths = ImmutableArray<string>.Empty; _workingDirectory = initialWorkingDirectory; _hostDirectory = Path.Combine(Path.GetDirectoryName(typeof(InteractiveSession).Assembly.Location)!, "InteractiveHost"); Host = new InteractiveHost(languageInfo.ReplServiceProviderType, initialWorkingDirectory); Host.ProcessInitialized += ProcessInitialized; } public void Dispose() { _shutdownCancellationSource.Cancel(); _shutdownCancellationSource.Dispose(); Host.Dispose(); } /// <summary> /// Invoked by <see cref="InteractiveHost"/> when a new process initialization completes. /// </summary> private void ProcessInitialized(InteractiveHostPlatformInfo platformInfo, InteractiveHostOptions options, RemoteExecutionResult result) { Contract.ThrowIfFalse(result.InitializationResult != null); _ = _taskQueue.ScheduleTask(nameof(ProcessInitialized), () => { _workspace.ResetSolution(); _currentSubmissionProjectId = null; _lastSuccessfulSubmissionProjectId = null; // update host state: _platformInfo = platformInfo; _initializationResult = result.InitializationResult; UpdatePathsNoLock(result); // Create submission projects for buffers that were added by the Interactive Window // before the process initialization completed. foreach (var (buffer, languageName) in _pendingBuffers) { AddSubmissionProjectNoLock(buffer, languageName); } _pendingBuffers.Clear(); }, _shutdownCancellationSource.Token); } /// <summary> /// Invoked on UI thread when a new language buffer is created and before it is added to the projection. /// </summary> internal void AddSubmissionProject(ITextBuffer submissionBuffer) { _taskQueue.ScheduleTask( nameof(AddSubmissionProject), () => AddSubmissionProjectNoLock(submissionBuffer, _languageInfo.LanguageName), _shutdownCancellationSource.Token); } private void AddSubmissionProjectNoLock(ITextBuffer submissionBuffer, string languageName) { var initResult = _initializationResult; var imports = ImmutableArray<string>.Empty; var references = ImmutableArray<MetadataReference>.Empty; var initializationScriptImports = ImmutableArray<string>.Empty; var initializationScriptReferences = ImmutableArray<MetadataReference>.Empty; ProjectId? initializationScriptProjectId = null; string? initializationScriptPath = null; if (_currentSubmissionProjectId == null) { Debug.Assert(_lastSuccessfulSubmissionProjectId == null); // The Interactive Window may have added the first language buffer before // the host initialization has completed. Do not create a submission project // for the buffer in such case. It will be created when the initialization completes. if (initResult == null) { _pendingBuffers.Add((submissionBuffer, languageName)); return; } imports = initResult.Imports.ToImmutableArrayOrEmpty(); var metadataService = _workspace.Services.GetRequiredService<IMetadataService>(); references = initResult.MetadataReferencePaths.ToImmutableArrayOrEmpty().SelectAsArray( (path, metadataService) => (MetadataReference)metadataService.GetReference(path, MetadataReferenceProperties.Assembly), metadataService); // if a script was specified in .rps file insert a project with a document that represents it: initializationScriptPath = initResult!.ScriptPath; if (initializationScriptPath != null) { initializationScriptProjectId = ProjectId.CreateNewId(CreateNewSubmissionName()); _lastSuccessfulSubmissionProjectId = initializationScriptProjectId; // imports and references will be inherited: initializationScriptImports = imports; initializationScriptReferences = references; imports = ImmutableArray<string>.Empty; references = ImmutableArray<MetadataReference>.Empty; } } var newSubmissionProjectName = CreateNewSubmissionName(); var newSubmissionText = submissionBuffer.CurrentSnapshot.AsText(); _currentSubmissionProjectId = ProjectId.CreateNewId(newSubmissionProjectName); var newSubmissionDocumentId = DocumentId.CreateNewId(_currentSubmissionProjectId, newSubmissionProjectName); // Chain projects to the the last submission that successfully executed. _workspace.SetCurrentSolution(solution => { if (initializationScriptProjectId != null) { RoslynDebug.AssertNotNull(initializationScriptPath); var initProject = CreateSubmissionProjectNoLock(solution, initializationScriptProjectId, previousSubmissionProjectId: null, languageName, initializationScriptImports, initializationScriptReferences); solution = initProject.Solution.AddDocument( DocumentId.CreateNewId(initializationScriptProjectId, debugName: initializationScriptPath), Path.GetFileName(initializationScriptPath), new FileTextLoader(initializationScriptPath, defaultEncoding: null)); } var newSubmissionProject = CreateSubmissionProjectNoLock(solution, _currentSubmissionProjectId, _lastSuccessfulSubmissionProjectId, languageName, imports, references); solution = newSubmissionProject.Solution.AddDocument( newSubmissionDocumentId, newSubmissionProjectName, newSubmissionText); return solution; }, WorkspaceChangeKind.SolutionChanged); // opening document will start workspace listening to changes in this text container _workspace.OpenDocument(newSubmissionDocumentId, submissionBuffer.AsTextContainer()); } private string CreateNewSubmissionName() => "Submission#" + SubmissionCount++; private Project CreateSubmissionProjectNoLock(Solution solution, ProjectId newSubmissionProjectId, ProjectId? previousSubmissionProjectId, string languageName, ImmutableArray<string> imports, ImmutableArray<MetadataReference> references) { var name = newSubmissionProjectId.DebugName; RoslynDebug.AssertNotNull(name); CompilationOptions compilationOptions; if (previousSubmissionProjectId != null) { compilationOptions = solution.GetRequiredProject(previousSubmissionProjectId).CompilationOptions!; var metadataResolver = (RuntimeMetadataReferenceResolver)compilationOptions.MetadataReferenceResolver!; if (metadataResolver.PathResolver.BaseDirectory != _workingDirectory || !metadataResolver.PathResolver.SearchPaths.SequenceEqual(_referenceSearchPaths)) { compilationOptions = compilationOptions.WithMetadataReferenceResolver(metadataResolver.WithRelativePathResolver(new RelativePathResolver(_referenceSearchPaths, _workingDirectory))); } var sourceResolver = (SourceFileResolver)compilationOptions.SourceReferenceResolver!; if (sourceResolver.BaseDirectory != _workingDirectory || !sourceResolver.SearchPaths.SequenceEqual(_sourceSearchPaths)) { compilationOptions = compilationOptions.WithSourceReferenceResolver(CreateSourceReferenceResolver(sourceResolver.SearchPaths, _workingDirectory)); } } else { var metadataService = _workspace.Services.GetRequiredService<IMetadataService>(); compilationOptions = _languageInfo.GetSubmissionCompilationOptions( name, CreateMetadataReferenceResolver(metadataService, _platformInfo, _referenceSearchPaths, _workingDirectory), CreateSourceReferenceResolver(_sourceSearchPaths, _workingDirectory), imports); } solution = solution.AddProject( ProjectInfo.Create( newSubmissionProjectId, VersionStamp.Create(), name: name, assemblyName: name, language: languageName, compilationOptions: compilationOptions, parseOptions: _languageInfo.ParseOptions, documents: null, projectReferences: null, metadataReferences: references, hostObjectType: typeof(InteractiveScriptGlobals), isSubmission: true)); if (previousSubmissionProjectId != null) { solution = solution.AddProjectReference(newSubmissionProjectId, new ProjectReference(previousSubmissionProjectId)); } return solution.GetRequiredProject(newSubmissionProjectId); } /// <summary> /// Called once a code snippet is submitted. /// Followed by creation of a new language buffer and call to <see cref="AddSubmissionProject(ITextBuffer)"/>. /// </summary> internal Task<bool> ExecuteCodeAsync(string text) { return _taskQueue.ScheduleTask(nameof(ExecuteCodeAsync), async () => { var result = await Host.ExecuteAsync(text).ConfigureAwait(false); if (result.Success) { _lastSuccessfulSubmissionProjectId = _currentSubmissionProjectId; // update local search paths - remote paths has already been updated UpdatePathsNoLock(result); } return result.Success; }, _shutdownCancellationSource.Token); } internal async Task<bool> ResetAsync(InteractiveHostOptions options) { try { // Do not queue reset operation - invoke it directly. // Code execution might be in progress when the user requests reset (via a reset button, or process terminating on its own). // We need the execution to be interrupted and the process restarted, not wait for it to complete. var result = await Host.ResetAsync(options).ConfigureAwait(false); // Note: Not calling UpdatePathsNoLock here. The paths will be updated by ProcessInitialized // which is executed once the new host process finishes its initialization. return result.Success; } catch (Exception e) when (FatalError.ReportAndPropagate(e)) { throw ExceptionUtilities.Unreachable; } } public InteractiveHostOptions GetHostOptions(bool initialize, InteractiveHostPlatform? platform) => InteractiveHostOptions.CreateFromDirectory( _hostDirectory, initialize ? _languageInfo.InteractiveResponseFileName : null, CultureInfo.CurrentUICulture, platform ?? Host.OptionsOpt?.Platform ?? InteractiveHost.DefaultPlatform); private static RuntimeMetadataReferenceResolver CreateMetadataReferenceResolver(IMetadataService metadataService, InteractiveHostPlatformInfo platformInfo, ImmutableArray<string> searchPaths, string baseDirectory) { return new RuntimeMetadataReferenceResolver( searchPaths, baseDirectory, gacFileResolver: platformInfo.HasGlobalAssemblyCache ? new GacFileResolver(preferredCulture: CultureInfo.CurrentCulture) : null, platformAssemblyPaths: platformInfo.PlatformAssemblyPaths, fileReferenceProvider: (path, properties) => metadataService.GetReference(path, properties)); } private static SourceReferenceResolver CreateSourceReferenceResolver(ImmutableArray<string> searchPaths, string baseDirectory) => new SourceFileResolver(searchPaths, baseDirectory); public Task SetPathsAsync(ImmutableArray<string> referenceSearchPaths, ImmutableArray<string> sourceSearchPaths, string workingDirectory) { return _taskQueue.ScheduleTask(nameof(ExecuteCodeAsync), async () => { var result = await Host.SetPathsAsync(referenceSearchPaths, sourceSearchPaths, workingDirectory).ConfigureAwait(false); UpdatePathsNoLock(result); }, _shutdownCancellationSource.Token); } private void UpdatePathsNoLock(RemoteExecutionResult result) { _workingDirectory = result.WorkingDirectory; _referenceSearchPaths = result.ReferencePaths; _sourceSearchPaths = result.SourcePaths; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. extern alias InteractiveHost; extern alias Scripting; using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Scripting.Hosting; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.Interactive { using InteractiveHost::Microsoft.CodeAnalysis.Interactive; using RelativePathResolver = Scripting::Microsoft.CodeAnalysis.RelativePathResolver; internal sealed class InteractiveSession : IDisposable { public InteractiveHost Host { get; } private readonly IThreadingContext _threadingContext; private readonly InteractiveEvaluatorLanguageInfoProvider _languageInfo; private readonly InteractiveWorkspace _workspace; private readonly CancellationTokenSource _shutdownCancellationSource; private readonly string _hostDirectory; #region State only accessible by queued tasks // Use to serialize InteractiveHost process initialization and code execution. // The process may restart any time and we need to react to that by clearing // the current solution and setting up the first submission project. // At the same time a code submission might be in progress. // If we left these operations run in parallel we might get into a state // inconsistent with the state of the host. private readonly TaskQueue _taskQueue; private ProjectId? _lastSuccessfulSubmissionProjectId; private ProjectId? _currentSubmissionProjectId; public int SubmissionCount { get; private set; } private RemoteInitializationResult? _initializationResult; private InteractiveHostPlatformInfo _platformInfo; private ImmutableArray<string> _referenceSearchPaths; private ImmutableArray<string> _sourceSearchPaths; private string _workingDirectory; /// <summary> /// Buffers that need to be associated with a submission project once the process initialization completes. /// </summary> private readonly List<(ITextBuffer buffer, string name)> _pendingBuffers = new(); #endregion public InteractiveSession( InteractiveWorkspace workspace, IThreadingContext threadingContext, IAsynchronousOperationListener listener, InteractiveEvaluatorLanguageInfoProvider languageInfo, string initialWorkingDirectory) { _workspace = workspace; _threadingContext = threadingContext; _languageInfo = languageInfo; _taskQueue = new TaskQueue(listener, TaskScheduler.Default); _shutdownCancellationSource = new CancellationTokenSource(); // The following settings will apply when the REPL starts without .rsp file. // They are discarded once the REPL is reset. _referenceSearchPaths = ImmutableArray<string>.Empty; _sourceSearchPaths = ImmutableArray<string>.Empty; _workingDirectory = initialWorkingDirectory; _hostDirectory = Path.Combine(Path.GetDirectoryName(typeof(InteractiveSession).Assembly.Location)!, "InteractiveHost"); Host = new InteractiveHost(languageInfo.ReplServiceProviderType, initialWorkingDirectory); Host.ProcessInitialized += ProcessInitialized; } public void Dispose() { _shutdownCancellationSource.Cancel(); _shutdownCancellationSource.Dispose(); Host.Dispose(); } /// <summary> /// Invoked by <see cref="InteractiveHost"/> when a new process initialization completes. /// </summary> private void ProcessInitialized(InteractiveHostPlatformInfo platformInfo, InteractiveHostOptions options, RemoteExecutionResult result) { Contract.ThrowIfFalse(result.InitializationResult != null); _ = _taskQueue.ScheduleTask(nameof(ProcessInitialized), () => { _workspace.ResetSolution(); _currentSubmissionProjectId = null; _lastSuccessfulSubmissionProjectId = null; // update host state: _platformInfo = platformInfo; _initializationResult = result.InitializationResult; UpdatePathsNoLock(result); // Create submission projects for buffers that were added by the Interactive Window // before the process initialization completed. foreach (var (buffer, languageName) in _pendingBuffers) { AddSubmissionProjectNoLock(buffer, languageName); } _pendingBuffers.Clear(); }, _shutdownCancellationSource.Token); } /// <summary> /// Invoked on UI thread when a new language buffer is created and before it is added to the projection. /// </summary> internal void AddSubmissionProject(ITextBuffer submissionBuffer) { _taskQueue.ScheduleTask( nameof(AddSubmissionProject), () => AddSubmissionProjectNoLock(submissionBuffer, _languageInfo.LanguageName), _shutdownCancellationSource.Token); } private void AddSubmissionProjectNoLock(ITextBuffer submissionBuffer, string languageName) { var initResult = _initializationResult; var imports = ImmutableArray<string>.Empty; var references = ImmutableArray<MetadataReference>.Empty; var initializationScriptImports = ImmutableArray<string>.Empty; var initializationScriptReferences = ImmutableArray<MetadataReference>.Empty; ProjectId? initializationScriptProjectId = null; string? initializationScriptPath = null; if (_currentSubmissionProjectId == null) { Debug.Assert(_lastSuccessfulSubmissionProjectId == null); // The Interactive Window may have added the first language buffer before // the host initialization has completed. Do not create a submission project // for the buffer in such case. It will be created when the initialization completes. if (initResult == null) { _pendingBuffers.Add((submissionBuffer, languageName)); return; } imports = initResult.Imports.ToImmutableArrayOrEmpty(); var metadataService = _workspace.Services.GetRequiredService<IMetadataService>(); references = initResult.MetadataReferencePaths.ToImmutableArrayOrEmpty().SelectAsArray( (path, metadataService) => (MetadataReference)metadataService.GetReference(path, MetadataReferenceProperties.Assembly), metadataService); // if a script was specified in .rps file insert a project with a document that represents it: initializationScriptPath = initResult!.ScriptPath; if (initializationScriptPath != null) { initializationScriptProjectId = ProjectId.CreateNewId(CreateNewSubmissionName()); _lastSuccessfulSubmissionProjectId = initializationScriptProjectId; // imports and references will be inherited: initializationScriptImports = imports; initializationScriptReferences = references; imports = ImmutableArray<string>.Empty; references = ImmutableArray<MetadataReference>.Empty; } } var newSubmissionProjectName = CreateNewSubmissionName(); var newSubmissionText = submissionBuffer.CurrentSnapshot.AsText(); _currentSubmissionProjectId = ProjectId.CreateNewId(newSubmissionProjectName); var newSubmissionDocumentId = DocumentId.CreateNewId(_currentSubmissionProjectId, newSubmissionProjectName); // Chain projects to the the last submission that successfully executed. _workspace.SetCurrentSolution(solution => { if (initializationScriptProjectId != null) { RoslynDebug.AssertNotNull(initializationScriptPath); var initProject = CreateSubmissionProjectNoLock(solution, initializationScriptProjectId, previousSubmissionProjectId: null, languageName, initializationScriptImports, initializationScriptReferences); solution = initProject.Solution.AddDocument( DocumentId.CreateNewId(initializationScriptProjectId, debugName: initializationScriptPath), Path.GetFileName(initializationScriptPath), new FileTextLoader(initializationScriptPath, defaultEncoding: null)); } var newSubmissionProject = CreateSubmissionProjectNoLock(solution, _currentSubmissionProjectId, _lastSuccessfulSubmissionProjectId, languageName, imports, references); solution = newSubmissionProject.Solution.AddDocument( newSubmissionDocumentId, newSubmissionProjectName, newSubmissionText); return solution; }, WorkspaceChangeKind.SolutionChanged); // opening document will start workspace listening to changes in this text container _workspace.OpenDocument(newSubmissionDocumentId, submissionBuffer.AsTextContainer()); } private string CreateNewSubmissionName() => "Submission#" + SubmissionCount++; private Project CreateSubmissionProjectNoLock(Solution solution, ProjectId newSubmissionProjectId, ProjectId? previousSubmissionProjectId, string languageName, ImmutableArray<string> imports, ImmutableArray<MetadataReference> references) { var name = newSubmissionProjectId.DebugName; RoslynDebug.AssertNotNull(name); CompilationOptions compilationOptions; if (previousSubmissionProjectId != null) { compilationOptions = solution.GetRequiredProject(previousSubmissionProjectId).CompilationOptions!; var metadataResolver = (RuntimeMetadataReferenceResolver)compilationOptions.MetadataReferenceResolver!; if (metadataResolver.PathResolver.BaseDirectory != _workingDirectory || !metadataResolver.PathResolver.SearchPaths.SequenceEqual(_referenceSearchPaths)) { compilationOptions = compilationOptions.WithMetadataReferenceResolver(metadataResolver.WithRelativePathResolver(new RelativePathResolver(_referenceSearchPaths, _workingDirectory))); } var sourceResolver = (SourceFileResolver)compilationOptions.SourceReferenceResolver!; if (sourceResolver.BaseDirectory != _workingDirectory || !sourceResolver.SearchPaths.SequenceEqual(_sourceSearchPaths)) { compilationOptions = compilationOptions.WithSourceReferenceResolver(CreateSourceReferenceResolver(sourceResolver.SearchPaths, _workingDirectory)); } } else { var metadataService = _workspace.Services.GetRequiredService<IMetadataService>(); compilationOptions = _languageInfo.GetSubmissionCompilationOptions( name, CreateMetadataReferenceResolver(metadataService, _platformInfo, _referenceSearchPaths, _workingDirectory), CreateSourceReferenceResolver(_sourceSearchPaths, _workingDirectory), imports); } solution = solution.AddProject( ProjectInfo.Create( newSubmissionProjectId, VersionStamp.Create(), name: name, assemblyName: name, language: languageName, compilationOptions: compilationOptions, parseOptions: _languageInfo.ParseOptions, documents: null, projectReferences: null, metadataReferences: references, hostObjectType: typeof(InteractiveScriptGlobals), isSubmission: true)); if (previousSubmissionProjectId != null) { solution = solution.AddProjectReference(newSubmissionProjectId, new ProjectReference(previousSubmissionProjectId)); } return solution.GetRequiredProject(newSubmissionProjectId); } /// <summary> /// Called once a code snippet is submitted. /// Followed by creation of a new language buffer and call to <see cref="AddSubmissionProject(ITextBuffer)"/>. /// </summary> internal Task<bool> ExecuteCodeAsync(string text) { return _taskQueue.ScheduleTask(nameof(ExecuteCodeAsync), async () => { var result = await Host.ExecuteAsync(text).ConfigureAwait(false); if (result.Success) { _lastSuccessfulSubmissionProjectId = _currentSubmissionProjectId; // update local search paths - remote paths has already been updated UpdatePathsNoLock(result); } return result.Success; }, _shutdownCancellationSource.Token); } internal async Task<bool> ResetAsync(InteractiveHostOptions options) { try { // Do not queue reset operation - invoke it directly. // Code execution might be in progress when the user requests reset (via a reset button, or process terminating on its own). // We need the execution to be interrupted and the process restarted, not wait for it to complete. var result = await Host.ResetAsync(options).ConfigureAwait(false); // Note: Not calling UpdatePathsNoLock here. The paths will be updated by ProcessInitialized // which is executed once the new host process finishes its initialization. return result.Success; } catch (Exception e) when (FatalError.ReportAndPropagate(e)) { throw ExceptionUtilities.Unreachable; } } public InteractiveHostOptions GetHostOptions(bool initialize, InteractiveHostPlatform? platform) => InteractiveHostOptions.CreateFromDirectory( _hostDirectory, initialize ? _languageInfo.InteractiveResponseFileName : null, CultureInfo.CurrentUICulture, platform ?? Host.OptionsOpt?.Platform ?? InteractiveHost.DefaultPlatform); private static RuntimeMetadataReferenceResolver CreateMetadataReferenceResolver(IMetadataService metadataService, InteractiveHostPlatformInfo platformInfo, ImmutableArray<string> searchPaths, string baseDirectory) { return new RuntimeMetadataReferenceResolver( searchPaths, baseDirectory, gacFileResolver: platformInfo.HasGlobalAssemblyCache ? new GacFileResolver(preferredCulture: CultureInfo.CurrentCulture) : null, platformAssemblyPaths: platformInfo.PlatformAssemblyPaths, fileReferenceProvider: (path, properties) => metadataService.GetReference(path, properties)); } private static SourceReferenceResolver CreateSourceReferenceResolver(ImmutableArray<string> searchPaths, string baseDirectory) => new SourceFileResolver(searchPaths, baseDirectory); public Task SetPathsAsync(ImmutableArray<string> referenceSearchPaths, ImmutableArray<string> sourceSearchPaths, string workingDirectory) { return _taskQueue.ScheduleTask(nameof(ExecuteCodeAsync), async () => { var result = await Host.SetPathsAsync(referenceSearchPaths, sourceSearchPaths, workingDirectory).ConfigureAwait(false); UpdatePathsNoLock(result); }, _shutdownCancellationSource.Token); } private void UpdatePathsNoLock(RemoteExecutionResult result) { _workingDirectory = result.WorkingDirectory; _referenceSearchPaths = result.ReferencePaths; _sourceSearchPaths = result.SourcePaths; } } }
-1
dotnet/roslyn
55,132
Support lambda expressions and method groups as `var` initializers
```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
cston
2021-07-27T03:12:21Z
2021-07-27T18:26:42Z
61a565cfcd777158cb6354351436aff997ad7bf6
5840335153dcca42570a853cdacd06d660fe9596
Support lambda expressions and method groups as `var` initializers. ```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
./src/Features/Core/Portable/CodeLens/ReferenceLocationDescriptor.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Runtime.Serialization; namespace Microsoft.CodeAnalysis.CodeLens { /// <summary> /// Holds information required to display and navigate to individual references /// </summary> [DataContract] internal sealed class ReferenceLocationDescriptor { /// <summary> /// Fully qualified name of the symbol containing the reference location /// </summary> [DataMember(Order = 0)] public string LongDescription { get; } /// <summary> /// Language of the reference location /// </summary> [DataMember(Order = 1)] public string Language { get; } /// <summary> /// The kind of symbol containing the reference location (such as type, method, property, etc.) /// </summary> [DataMember(Order = 2)] public Glyph? Glyph { get; } /// <summary> /// Reference's span start based on the document content /// </summary> [DataMember(Order = 3)] public int SpanStart { get; } /// <summary> /// Reference's span length based on the document content /// </summary> [DataMember(Order = 4)] public int SpanLength { get; } /// <summary> /// Reference's line based on the document content /// </summary> [DataMember(Order = 5)] public int LineNumber { get; } /// <summary> /// Reference's character based on the document content /// </summary> [DataMember(Order = 6)] public int ColumnNumber { get; } [DataMember(Order = 7)] public Guid ProjectGuid { get; } [DataMember(Order = 8)] public Guid DocumentGuid { get; } /// <summary> /// Document's file path /// </summary> [DataMember(Order = 9)] public string FilePath { get; } /// <summary> /// the full line of source that contained the reference /// </summary> [DataMember(Order = 10)] public string ReferenceLineText { get; } /// <summary> /// the beginning of the span within reference text that was the use of the reference /// </summary> [DataMember(Order = 11)] public int ReferenceStart { get; } /// <summary> /// the length of the span of the reference /// </summary> [DataMember(Order = 12)] public int ReferenceLength { get; } /// <summary> /// Text above the line with the reference /// </summary> [DataMember(Order = 13)] public string BeforeReferenceText1 { get; } /// <summary> /// Text above the line with the reference /// </summary> [DataMember(Order = 14)] public string BeforeReferenceText2 { get; } /// <summary> /// Text below the line with the reference /// </summary> [DataMember(Order = 15)] public string AfterReferenceText1 { get; } /// <summary> /// Text below the line with the reference /// </summary> [DataMember(Order = 16)] public string AfterReferenceText2 { get; } public ReferenceLocationDescriptor( string longDescription, string language, Glyph? glyph, int spanStart, int spanLength, int lineNumber, int columnNumber, Guid projectGuid, Guid documentGuid, string filePath, string referenceLineText, int referenceStart, int referenceLength, string beforeReferenceText1, string beforeReferenceText2, string afterReferenceText1, string afterReferenceText2) { LongDescription = longDescription; Language = language; Glyph = glyph; SpanStart = spanStart; SpanLength = spanLength; LineNumber = lineNumber; ColumnNumber = columnNumber; // We want to keep track of the location's document if it comes from a file in your solution. ProjectGuid = projectGuid; DocumentGuid = documentGuid; FilePath = filePath; ReferenceLineText = referenceLineText; ReferenceStart = referenceStart; ReferenceLength = referenceLength; BeforeReferenceText1 = beforeReferenceText1; BeforeReferenceText2 = beforeReferenceText2; AfterReferenceText1 = afterReferenceText1; AfterReferenceText2 = afterReferenceText2; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Runtime.Serialization; namespace Microsoft.CodeAnalysis.CodeLens { /// <summary> /// Holds information required to display and navigate to individual references /// </summary> [DataContract] internal sealed class ReferenceLocationDescriptor { /// <summary> /// Fully qualified name of the symbol containing the reference location /// </summary> [DataMember(Order = 0)] public string LongDescription { get; } /// <summary> /// Language of the reference location /// </summary> [DataMember(Order = 1)] public string Language { get; } /// <summary> /// The kind of symbol containing the reference location (such as type, method, property, etc.) /// </summary> [DataMember(Order = 2)] public Glyph? Glyph { get; } /// <summary> /// Reference's span start based on the document content /// </summary> [DataMember(Order = 3)] public int SpanStart { get; } /// <summary> /// Reference's span length based on the document content /// </summary> [DataMember(Order = 4)] public int SpanLength { get; } /// <summary> /// Reference's line based on the document content /// </summary> [DataMember(Order = 5)] public int LineNumber { get; } /// <summary> /// Reference's character based on the document content /// </summary> [DataMember(Order = 6)] public int ColumnNumber { get; } [DataMember(Order = 7)] public Guid ProjectGuid { get; } [DataMember(Order = 8)] public Guid DocumentGuid { get; } /// <summary> /// Document's file path /// </summary> [DataMember(Order = 9)] public string FilePath { get; } /// <summary> /// the full line of source that contained the reference /// </summary> [DataMember(Order = 10)] public string ReferenceLineText { get; } /// <summary> /// the beginning of the span within reference text that was the use of the reference /// </summary> [DataMember(Order = 11)] public int ReferenceStart { get; } /// <summary> /// the length of the span of the reference /// </summary> [DataMember(Order = 12)] public int ReferenceLength { get; } /// <summary> /// Text above the line with the reference /// </summary> [DataMember(Order = 13)] public string BeforeReferenceText1 { get; } /// <summary> /// Text above the line with the reference /// </summary> [DataMember(Order = 14)] public string BeforeReferenceText2 { get; } /// <summary> /// Text below the line with the reference /// </summary> [DataMember(Order = 15)] public string AfterReferenceText1 { get; } /// <summary> /// Text below the line with the reference /// </summary> [DataMember(Order = 16)] public string AfterReferenceText2 { get; } public ReferenceLocationDescriptor( string longDescription, string language, Glyph? glyph, int spanStart, int spanLength, int lineNumber, int columnNumber, Guid projectGuid, Guid documentGuid, string filePath, string referenceLineText, int referenceStart, int referenceLength, string beforeReferenceText1, string beforeReferenceText2, string afterReferenceText1, string afterReferenceText2) { LongDescription = longDescription; Language = language; Glyph = glyph; SpanStart = spanStart; SpanLength = spanLength; LineNumber = lineNumber; ColumnNumber = columnNumber; // We want to keep track of the location's document if it comes from a file in your solution. ProjectGuid = projectGuid; DocumentGuid = documentGuid; FilePath = filePath; ReferenceLineText = referenceLineText; ReferenceStart = referenceStart; ReferenceLength = referenceLength; BeforeReferenceText1 = beforeReferenceText1; BeforeReferenceText2 = beforeReferenceText2; AfterReferenceText1 = afterReferenceText1; AfterReferenceText2 = afterReferenceText2; } } }
-1
dotnet/roslyn
55,132
Support lambda expressions and method groups as `var` initializers
```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
cston
2021-07-27T03:12:21Z
2021-07-27T18:26:42Z
61a565cfcd777158cb6354351436aff997ad7bf6
5840335153dcca42570a853cdacd06d660fe9596
Support lambda expressions and method groups as `var` initializers. ```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
./src/Compilers/Test/Resources/Core/SymbolsTests/Metadata/DynamicAttribute.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. // csc /t:library /unsafe DynamicAttribute.cs public class Base0 { } public class Base1<T> { } public class Base2<T, U> { } public class Outer<T> : Base1<dynamic> { public class Inner<U, V> : Base2<dynamic, V> { public class InnerInner<W> : Base1<dynamic> { } } } public class Outer2<T> : Base1<dynamic> { public class Inner2<U, V> : Base0 { public class InnerInner2<W> : Base0 { } } } public class Outer3 { public class Inner3<U> { public static Outer3.Inner3<dynamic> field1 = null; } } public class Derived<T> : Outer<dynamic>.Inner<Outer<dynamic>.Inner<T[], dynamic>.InnerInner<int>[], dynamic>.InnerInner<dynamic> where T : Derived<T> { public static dynamic field1; public static dynamic[] field2; public static dynamic[][] field3; public const dynamic field4 = null; public const dynamic[] field5 = null; public const dynamic[][] field6 = null; public const dynamic[][] field7 = null; public Outer<T>.Inner<int, T>.InnerInner<Outer<dynamic>> field8 = null; public Outer<dynamic>.Inner<T, T>.InnerInner<T> field9 = null; public Outer<Outer<dynamic>.Inner<T, dynamic>>.Inner<dynamic, T>.InnerInner<T> field10 = null; public Outer<T>.Inner<dynamic, dynamic>.InnerInner<T> field11 = null; public Outer<T>.Inner<T, T>.InnerInner<Outer<dynamic>.Inner<T, dynamic>.InnerInner<int>> field12 = null; public Outer<dynamic>.Inner<Outer<T>, T>.InnerInner<dynamic> field13 = null; public Outer<dynamic>.Inner<dynamic, dynamic>.InnerInner<dynamic> field14 = null; public Outer<dynamic>.Inner<Outer<dynamic>, T>.InnerInner<dynamic>[] field15 = null; public Outer<dynamic>.Inner<Outer<dynamic>.Inner<T, dynamic>.InnerInner<int>, dynamic[]>.InnerInner<dynamic>[][] field16 = null; public static Outer<dynamic>.Inner<Outer<dynamic>.Inner<T[], dynamic>.InnerInner<int>[], dynamic>.InnerInner<dynamic>[][] field17 = null; public static dynamic F1(dynamic x) { return x; } public static dynamic F2(ref dynamic x) { return x; } public static dynamic[] F3(dynamic[] x) { return x; } public static Outer<dynamic>.Inner<Outer<dynamic>.Inner<T[], dynamic>.InnerInner<int>[], dynamic>.InnerInner<dynamic>[][] F4(Outer<dynamic>.Inner<Outer<dynamic>.Inner<T[], dynamic>.InnerInner<int>[], dynamic>.InnerInner<dynamic>[][] x) { return x; } public static dynamic Prop1 { get { return field1; } } public static Outer<dynamic>.Inner<Outer<dynamic>.Inner<T[], dynamic>.InnerInner<int>[], dynamic>.InnerInner<dynamic>[][] Prop2 { get { return field17; } set { field17 = value; } } } public unsafe class UnsafeClass<T> : Base2<int*[], Outer<dynamic>.Inner<Outer<dynamic>.Inner<T[], dynamic>.InnerInner<int*[][]>[], dynamic>.InnerInner<dynamic>[][]> { } public struct Struct { public static Outer<dynamic>.Inner<dynamic, Struct?> nullableField; }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. // csc /t:library /unsafe DynamicAttribute.cs public class Base0 { } public class Base1<T> { } public class Base2<T, U> { } public class Outer<T> : Base1<dynamic> { public class Inner<U, V> : Base2<dynamic, V> { public class InnerInner<W> : Base1<dynamic> { } } } public class Outer2<T> : Base1<dynamic> { public class Inner2<U, V> : Base0 { public class InnerInner2<W> : Base0 { } } } public class Outer3 { public class Inner3<U> { public static Outer3.Inner3<dynamic> field1 = null; } } public class Derived<T> : Outer<dynamic>.Inner<Outer<dynamic>.Inner<T[], dynamic>.InnerInner<int>[], dynamic>.InnerInner<dynamic> where T : Derived<T> { public static dynamic field1; public static dynamic[] field2; public static dynamic[][] field3; public const dynamic field4 = null; public const dynamic[] field5 = null; public const dynamic[][] field6 = null; public const dynamic[][] field7 = null; public Outer<T>.Inner<int, T>.InnerInner<Outer<dynamic>> field8 = null; public Outer<dynamic>.Inner<T, T>.InnerInner<T> field9 = null; public Outer<Outer<dynamic>.Inner<T, dynamic>>.Inner<dynamic, T>.InnerInner<T> field10 = null; public Outer<T>.Inner<dynamic, dynamic>.InnerInner<T> field11 = null; public Outer<T>.Inner<T, T>.InnerInner<Outer<dynamic>.Inner<T, dynamic>.InnerInner<int>> field12 = null; public Outer<dynamic>.Inner<Outer<T>, T>.InnerInner<dynamic> field13 = null; public Outer<dynamic>.Inner<dynamic, dynamic>.InnerInner<dynamic> field14 = null; public Outer<dynamic>.Inner<Outer<dynamic>, T>.InnerInner<dynamic>[] field15 = null; public Outer<dynamic>.Inner<Outer<dynamic>.Inner<T, dynamic>.InnerInner<int>, dynamic[]>.InnerInner<dynamic>[][] field16 = null; public static Outer<dynamic>.Inner<Outer<dynamic>.Inner<T[], dynamic>.InnerInner<int>[], dynamic>.InnerInner<dynamic>[][] field17 = null; public static dynamic F1(dynamic x) { return x; } public static dynamic F2(ref dynamic x) { return x; } public static dynamic[] F3(dynamic[] x) { return x; } public static Outer<dynamic>.Inner<Outer<dynamic>.Inner<T[], dynamic>.InnerInner<int>[], dynamic>.InnerInner<dynamic>[][] F4(Outer<dynamic>.Inner<Outer<dynamic>.Inner<T[], dynamic>.InnerInner<int>[], dynamic>.InnerInner<dynamic>[][] x) { return x; } public static dynamic Prop1 { get { return field1; } } public static Outer<dynamic>.Inner<Outer<dynamic>.Inner<T[], dynamic>.InnerInner<int>[], dynamic>.InnerInner<dynamic>[][] Prop2 { get { return field17; } set { field17 = value; } } } public unsafe class UnsafeClass<T> : Base2<int*[], Outer<dynamic>.Inner<Outer<dynamic>.Inner<T[], dynamic>.InnerInner<int*[][]>[], dynamic>.InnerInner<dynamic>[][]> { } public struct Struct { public static Outer<dynamic>.Inner<dynamic, Struct?> nullableField; }
-1
dotnet/roslyn
55,132
Support lambda expressions and method groups as `var` initializers
```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
cston
2021-07-27T03:12:21Z
2021-07-27T18:26:42Z
61a565cfcd777158cb6354351436aff997ad7bf6
5840335153dcca42570a853cdacd06d660fe9596
Support lambda expressions and method groups as `var` initializers. ```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
./src/VisualStudio/IntegrationTest/TestSetup/IntegrationTestServicePackage.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Runtime.InteropServices; using System.Threading; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; using Task = System.Threading.Tasks.Task; namespace Microsoft.VisualStudio.IntegrationTest.Setup { [Guid("D02DAC01-DDD0-4ECC-8687-79A554852B14")] public sealed class IntegrationTestServicePackage : AsyncPackage { private static readonly Guid s_compilerPackage = new Guid("31C0675E-87A4-4061-A0DD-A4E510FCCF97"); protected override async Task InitializeAsync(CancellationToken cancellationToken, IProgress<ServiceProgressData> progress) { await base.InitializeAsync(cancellationToken, progress).ConfigureAwait(true); await JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken); var shell = (IVsShell)await GetServiceAsync(typeof(SVsShell)); ErrorHandler.ThrowOnFailure(shell.IsPackageInstalled(s_compilerPackage, out var installed)); if (installed != 0) { await ((IVsShell7)shell).LoadPackageAsync(s_compilerPackage); } IntegrationTestServiceCommands.Initialize(this); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Runtime.InteropServices; using System.Threading; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; using Task = System.Threading.Tasks.Task; namespace Microsoft.VisualStudio.IntegrationTest.Setup { [Guid("D02DAC01-DDD0-4ECC-8687-79A554852B14")] public sealed class IntegrationTestServicePackage : AsyncPackage { private static readonly Guid s_compilerPackage = new Guid("31C0675E-87A4-4061-A0DD-A4E510FCCF97"); protected override async Task InitializeAsync(CancellationToken cancellationToken, IProgress<ServiceProgressData> progress) { await base.InitializeAsync(cancellationToken, progress).ConfigureAwait(true); await JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken); var shell = (IVsShell)await GetServiceAsync(typeof(SVsShell)); ErrorHandler.ThrowOnFailure(shell.IsPackageInstalled(s_compilerPackage, out var installed)); if (installed != 0) { await ((IVsShell7)shell).LoadPackageAsync(s_compilerPackage); } IntegrationTestServiceCommands.Initialize(this); } } }
-1
dotnet/roslyn
55,132
Support lambda expressions and method groups as `var` initializers
```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
cston
2021-07-27T03:12:21Z
2021-07-27T18:26:42Z
61a565cfcd777158cb6354351436aff997ad7bf6
5840335153dcca42570a853cdacd06d660fe9596
Support lambda expressions and method groups as `var` initializers. ```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
./src/EditorFeatures/Core/Options/NavigationBarOptions.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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 Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Options.Providers; namespace Microsoft.CodeAnalysis.Editor.Options { internal static class NavigationBarOptions { public static readonly PerLanguageOption<bool> ShowNavigationBar = new(nameof(NavigationBarOptions), nameof(ShowNavigationBar), defaultValue: true); } [ExportOptionProvider, Shared] internal class NavigationBarOptionsProvider : IOptionProvider { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public NavigationBarOptionsProvider() { } public ImmutableArray<IOption> Options { get; } = ImmutableArray.Create<IOption>( NavigationBarOptions.ShowNavigationBar); } }
// Licensed to the .NET Foundation under one or more agreements. // The .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 Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Options.Providers; namespace Microsoft.CodeAnalysis.Editor.Options { internal static class NavigationBarOptions { public static readonly PerLanguageOption<bool> ShowNavigationBar = new(nameof(NavigationBarOptions), nameof(ShowNavigationBar), defaultValue: true); } [ExportOptionProvider, Shared] internal class NavigationBarOptionsProvider : IOptionProvider { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public NavigationBarOptionsProvider() { } public ImmutableArray<IOption> Options { get; } = ImmutableArray.Create<IOption>( NavigationBarOptions.ShowNavigationBar); } }
-1
dotnet/roslyn
55,132
Support lambda expressions and method groups as `var` initializers
```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
cston
2021-07-27T03:12:21Z
2021-07-27T18:26:42Z
61a565cfcd777158cb6354351436aff997ad7bf6
5840335153dcca42570a853cdacd06d660fe9596
Support lambda expressions and method groups as `var` initializers. ```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
./src/Compilers/CSharp/Portable/Lowering/LocalRewriter/LocalRewriter_LockStatement.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.CSharp.Syntax; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CSharp { internal sealed partial class LocalRewriter { /// <summary> /// Lowers a lock statement to a try-finally block that calls Monitor.Enter and Monitor.Exit /// before and after the body, respectively. /// </summary> public override BoundNode VisitLockStatement(BoundLockStatement node) { LockStatementSyntax lockSyntax = (LockStatementSyntax)node.Syntax; BoundExpression rewrittenArgument = VisitExpression(node.Argument); BoundStatement? rewrittenBody = VisitStatement(node.Body); Debug.Assert(rewrittenBody is { }); TypeSymbol? argumentType = rewrittenArgument.Type; if (argumentType is null) { // This isn't particularly elegant, but hopefully locking on null is // not very common. Debug.Assert(rewrittenArgument.ConstantValue == ConstantValue.Null); argumentType = _compilation.GetSpecialType(SpecialType.System_Object); rewrittenArgument = MakeLiteral( rewrittenArgument.Syntax, rewrittenArgument.ConstantValue, argumentType); //need to have a non-null type here for TempHelpers.StoreToTemp. } if (argumentType.Kind == SymbolKind.TypeParameter) { // If the argument has a type parameter type, then we'll box it right away // so that the same object is passed to both Monitor.Enter and Monitor.Exit. argumentType = _compilation.GetSpecialType(SpecialType.System_Object); rewrittenArgument = MakeConversionNode( rewrittenArgument.Syntax, rewrittenArgument, Conversion.Boxing, argumentType, @checked: false, constantValueOpt: rewrittenArgument.ConstantValue); } BoundAssignmentOperator assignmentToLockTemp; BoundLocal boundLockTemp = _factory.StoreToTemp(rewrittenArgument, out assignmentToLockTemp, syntaxOpt: lockSyntax, kind: SynthesizedLocalKind.Lock); BoundStatement boundLockTempInit = new BoundExpressionStatement(lockSyntax, assignmentToLockTemp); BoundExpression exitCallExpr; MethodSymbol exitMethod; if (TryGetWellKnownTypeMember(lockSyntax, WellKnownMember.System_Threading_Monitor__Exit, out exitMethod)) { exitCallExpr = BoundCall.Synthesized( lockSyntax, receiverOpt: null, exitMethod, boundLockTemp); } else { exitCallExpr = new BoundBadExpression(lockSyntax, LookupResultKind.NotInvocable, ImmutableArray<Symbol?>.Empty, ImmutableArray.Create<BoundExpression>(boundLockTemp), ErrorTypeSymbol.UnknownResultType); } BoundStatement exitCall = new BoundExpressionStatement(lockSyntax, exitCallExpr); MethodSymbol enterMethod; if ((TryGetWellKnownTypeMember(lockSyntax, WellKnownMember.System_Threading_Monitor__Enter2, out enterMethod, isOptional: true) || TryGetWellKnownTypeMember(lockSyntax, WellKnownMember.System_Threading_Monitor__Enter, out enterMethod)) && // If we didn't find the overload introduced in .NET 4.0, then use the older one. enterMethod.ParameterCount == 2) { // C# 4.0+ version // L $lock = `argument`; // sequence point // bool $lockTaken = false; // try // { // Monitor.Enter($lock, ref $lockTaken); // `body` // sequence point // } // finally // { // hidden sequence point // if ($lockTaken) Monitor.Exit($lock); // } TypeSymbol boolType = _compilation.GetSpecialType(SpecialType.System_Boolean); BoundAssignmentOperator assignmentToLockTakenTemp; BoundLocal boundLockTakenTemp = _factory.StoreToTemp( MakeLiteral(rewrittenArgument.Syntax, ConstantValue.False, boolType), store: out assignmentToLockTakenTemp, syntaxOpt: lockSyntax, kind: SynthesizedLocalKind.LockTaken); BoundStatement boundLockTakenTempInit = new BoundExpressionStatement(lockSyntax, assignmentToLockTakenTemp); BoundStatement enterCall = new BoundExpressionStatement( lockSyntax, BoundCall.Synthesized( lockSyntax, receiverOpt: null, enterMethod, boundLockTemp, boundLockTakenTemp)); exitCall = RewriteIfStatement( lockSyntax, boundLockTakenTemp, exitCall, null, node.HasErrors); return new BoundBlock( lockSyntax, ImmutableArray.Create(boundLockTemp.LocalSymbol, boundLockTakenTemp.LocalSymbol), ImmutableArray.Create( InstrumentLockTargetCapture(node, boundLockTempInit), boundLockTakenTempInit, new BoundTryStatement( lockSyntax, BoundBlock.SynthesizedNoLocals(lockSyntax, ImmutableArray.Create<BoundStatement>( enterCall, rewrittenBody)), ImmutableArray<BoundCatchBlock>.Empty, BoundBlock.SynthesizedNoLocals(lockSyntax, exitCall)))); } else { // Pre-4.0 version // L $lock = `argument`; // sequence point // Monitor.Enter($lock); // NB: before try-finally so we don't Exit if an exception prevents us from acquiring the lock. // try // { // `body` // sequence point // } // finally // { // Monitor.Exit($lock); // hidden sequence point // } BoundExpression enterCallExpr; if ((object)enterMethod != null) { Debug.Assert(enterMethod.ParameterCount == 1); enterCallExpr = BoundCall.Synthesized( lockSyntax, receiverOpt: null, enterMethod, boundLockTemp); } else { enterCallExpr = new BoundBadExpression(lockSyntax, LookupResultKind.NotInvocable, ImmutableArray<Symbol?>.Empty, ImmutableArray.Create<BoundExpression>(boundLockTemp), ErrorTypeSymbol.UnknownResultType); } BoundStatement enterCall = new BoundExpressionStatement( lockSyntax, enterCallExpr); return new BoundBlock( lockSyntax, ImmutableArray.Create(boundLockTemp.LocalSymbol), ImmutableArray.Create( InstrumentLockTargetCapture(node, boundLockTempInit), enterCall, new BoundTryStatement( lockSyntax, BoundBlock.SynthesizedNoLocals(lockSyntax, rewrittenBody), ImmutableArray<BoundCatchBlock>.Empty, BoundBlock.SynthesizedNoLocals(lockSyntax, exitCall)))); } } private BoundStatement InstrumentLockTargetCapture(BoundLockStatement original, BoundStatement lockTargetCapture) { return this.Instrument ? _instrumenter.InstrumentLockTargetCapture(original, lockTargetCapture) : lockTargetCapture; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .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.CSharp.Syntax; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CSharp { internal sealed partial class LocalRewriter { /// <summary> /// Lowers a lock statement to a try-finally block that calls Monitor.Enter and Monitor.Exit /// before and after the body, respectively. /// </summary> public override BoundNode VisitLockStatement(BoundLockStatement node) { LockStatementSyntax lockSyntax = (LockStatementSyntax)node.Syntax; BoundExpression rewrittenArgument = VisitExpression(node.Argument); BoundStatement? rewrittenBody = VisitStatement(node.Body); Debug.Assert(rewrittenBody is { }); TypeSymbol? argumentType = rewrittenArgument.Type; if (argumentType is null) { // This isn't particularly elegant, but hopefully locking on null is // not very common. Debug.Assert(rewrittenArgument.ConstantValue == ConstantValue.Null); argumentType = _compilation.GetSpecialType(SpecialType.System_Object); rewrittenArgument = MakeLiteral( rewrittenArgument.Syntax, rewrittenArgument.ConstantValue, argumentType); //need to have a non-null type here for TempHelpers.StoreToTemp. } if (argumentType.Kind == SymbolKind.TypeParameter) { // If the argument has a type parameter type, then we'll box it right away // so that the same object is passed to both Monitor.Enter and Monitor.Exit. argumentType = _compilation.GetSpecialType(SpecialType.System_Object); rewrittenArgument = MakeConversionNode( rewrittenArgument.Syntax, rewrittenArgument, Conversion.Boxing, argumentType, @checked: false, constantValueOpt: rewrittenArgument.ConstantValue); } BoundAssignmentOperator assignmentToLockTemp; BoundLocal boundLockTemp = _factory.StoreToTemp(rewrittenArgument, out assignmentToLockTemp, syntaxOpt: lockSyntax, kind: SynthesizedLocalKind.Lock); BoundStatement boundLockTempInit = new BoundExpressionStatement(lockSyntax, assignmentToLockTemp); BoundExpression exitCallExpr; MethodSymbol exitMethod; if (TryGetWellKnownTypeMember(lockSyntax, WellKnownMember.System_Threading_Monitor__Exit, out exitMethod)) { exitCallExpr = BoundCall.Synthesized( lockSyntax, receiverOpt: null, exitMethod, boundLockTemp); } else { exitCallExpr = new BoundBadExpression(lockSyntax, LookupResultKind.NotInvocable, ImmutableArray<Symbol?>.Empty, ImmutableArray.Create<BoundExpression>(boundLockTemp), ErrorTypeSymbol.UnknownResultType); } BoundStatement exitCall = new BoundExpressionStatement(lockSyntax, exitCallExpr); MethodSymbol enterMethod; if ((TryGetWellKnownTypeMember(lockSyntax, WellKnownMember.System_Threading_Monitor__Enter2, out enterMethod, isOptional: true) || TryGetWellKnownTypeMember(lockSyntax, WellKnownMember.System_Threading_Monitor__Enter, out enterMethod)) && // If we didn't find the overload introduced in .NET 4.0, then use the older one. enterMethod.ParameterCount == 2) { // C# 4.0+ version // L $lock = `argument`; // sequence point // bool $lockTaken = false; // try // { // Monitor.Enter($lock, ref $lockTaken); // `body` // sequence point // } // finally // { // hidden sequence point // if ($lockTaken) Monitor.Exit($lock); // } TypeSymbol boolType = _compilation.GetSpecialType(SpecialType.System_Boolean); BoundAssignmentOperator assignmentToLockTakenTemp; BoundLocal boundLockTakenTemp = _factory.StoreToTemp( MakeLiteral(rewrittenArgument.Syntax, ConstantValue.False, boolType), store: out assignmentToLockTakenTemp, syntaxOpt: lockSyntax, kind: SynthesizedLocalKind.LockTaken); BoundStatement boundLockTakenTempInit = new BoundExpressionStatement(lockSyntax, assignmentToLockTakenTemp); BoundStatement enterCall = new BoundExpressionStatement( lockSyntax, BoundCall.Synthesized( lockSyntax, receiverOpt: null, enterMethod, boundLockTemp, boundLockTakenTemp)); exitCall = RewriteIfStatement( lockSyntax, boundLockTakenTemp, exitCall, null, node.HasErrors); return new BoundBlock( lockSyntax, ImmutableArray.Create(boundLockTemp.LocalSymbol, boundLockTakenTemp.LocalSymbol), ImmutableArray.Create( InstrumentLockTargetCapture(node, boundLockTempInit), boundLockTakenTempInit, new BoundTryStatement( lockSyntax, BoundBlock.SynthesizedNoLocals(lockSyntax, ImmutableArray.Create<BoundStatement>( enterCall, rewrittenBody)), ImmutableArray<BoundCatchBlock>.Empty, BoundBlock.SynthesizedNoLocals(lockSyntax, exitCall)))); } else { // Pre-4.0 version // L $lock = `argument`; // sequence point // Monitor.Enter($lock); // NB: before try-finally so we don't Exit if an exception prevents us from acquiring the lock. // try // { // `body` // sequence point // } // finally // { // Monitor.Exit($lock); // hidden sequence point // } BoundExpression enterCallExpr; if ((object)enterMethod != null) { Debug.Assert(enterMethod.ParameterCount == 1); enterCallExpr = BoundCall.Synthesized( lockSyntax, receiverOpt: null, enterMethod, boundLockTemp); } else { enterCallExpr = new BoundBadExpression(lockSyntax, LookupResultKind.NotInvocable, ImmutableArray<Symbol?>.Empty, ImmutableArray.Create<BoundExpression>(boundLockTemp), ErrorTypeSymbol.UnknownResultType); } BoundStatement enterCall = new BoundExpressionStatement( lockSyntax, enterCallExpr); return new BoundBlock( lockSyntax, ImmutableArray.Create(boundLockTemp.LocalSymbol), ImmutableArray.Create( InstrumentLockTargetCapture(node, boundLockTempInit), enterCall, new BoundTryStatement( lockSyntax, BoundBlock.SynthesizedNoLocals(lockSyntax, rewrittenBody), ImmutableArray<BoundCatchBlock>.Empty, BoundBlock.SynthesizedNoLocals(lockSyntax, exitCall)))); } } private BoundStatement InstrumentLockTargetCapture(BoundLockStatement original, BoundStatement lockTargetCapture) { return this.Instrument ? _instrumenter.InstrumentLockTargetCapture(original, lockTargetCapture) : lockTargetCapture; } } }
-1
dotnet/roslyn
55,132
Support lambda expressions and method groups as `var` initializers
```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
cston
2021-07-27T03:12:21Z
2021-07-27T18:26:42Z
61a565cfcd777158cb6354351436aff997ad7bf6
5840335153dcca42570a853cdacd06d660fe9596
Support lambda expressions and method groups as `var` initializers. ```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
./src/EditorFeatures/CSharpTest/Structure/ParenthesizedLambdaStructureTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp.Structure; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Structure; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Structure { public class ParenthesizedLambdaStructureTests : AbstractCSharpSyntaxNodeStructureTests<ParenthesizedLambdaExpressionSyntax> { internal override AbstractSyntaxStructureProvider CreateProvider() => new ParenthesizedLambdaExpressionStructureProvider(); [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] public async Task TestLambda() { const string code = @" class C { void M() { {|hint:$$() => {|textspan:{ x(); };|}|} } }"; await VerifyBlockSpansAsync(code, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: false)); } [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] public async Task TestLambdaInForLoop() { const string code = @" class C { void M() { for (Action a = $$() => { }; true; a()) { } } }"; await VerifyNoBlockSpansAsync(code); } [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] public async Task TestLambdaInMethodCall1() { const string code = @" class C { void M() { someMethod(42, ""test"", false, {|hint:$$(x, y, z) => {|textspan:{ return x + y + z; }|}|}, ""other arguments""); } }"; await VerifyBlockSpansAsync(code, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: false)); } [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] public async Task TestLambdaInMethodCall2() { const string code = @" class C { void M() { someMethod(42, ""test"", false, {|hint:$$(x, y, z) => {|textspan:{ return x + y + z; }|}|}); } }"; await VerifyBlockSpansAsync(code, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: 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.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp.Structure; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Structure; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Structure { public class ParenthesizedLambdaStructureTests : AbstractCSharpSyntaxNodeStructureTests<ParenthesizedLambdaExpressionSyntax> { internal override AbstractSyntaxStructureProvider CreateProvider() => new ParenthesizedLambdaExpressionStructureProvider(); [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] public async Task TestLambda() { const string code = @" class C { void M() { {|hint:$$() => {|textspan:{ x(); };|}|} } }"; await VerifyBlockSpansAsync(code, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: false)); } [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] public async Task TestLambdaInForLoop() { const string code = @" class C { void M() { for (Action a = $$() => { }; true; a()) { } } }"; await VerifyNoBlockSpansAsync(code); } [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] public async Task TestLambdaInMethodCall1() { const string code = @" class C { void M() { someMethod(42, ""test"", false, {|hint:$$(x, y, z) => {|textspan:{ return x + y + z; }|}|}, ""other arguments""); } }"; await VerifyBlockSpansAsync(code, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: false)); } [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] public async Task TestLambdaInMethodCall2() { const string code = @" class C { void M() { someMethod(42, ""test"", false, {|hint:$$(x, y, z) => {|textspan:{ return x + y + z; }|}|}); } }"; await VerifyBlockSpansAsync(code, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: false)); } } }
-1
dotnet/roslyn
55,132
Support lambda expressions and method groups as `var` initializers
```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
cston
2021-07-27T03:12:21Z
2021-07-27T18:26:42Z
61a565cfcd777158cb6354351436aff997ad7bf6
5840335153dcca42570a853cdacd06d660fe9596
Support lambda expressions and method groups as `var` initializers. ```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
./src/CodeStyle/CSharp/Analyzers/CSharpFormattingAnalyzer.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET 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.Formatting; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Formatting; namespace Microsoft.CodeAnalysis.CodeStyle { [DiagnosticAnalyzer(LanguageNames.CSharp)] internal class CSharpFormattingAnalyzer : AbstractFormattingAnalyzer { protected override ISyntaxFormattingService SyntaxFormattingService => CSharpSyntaxFormattingService.Instance; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.CSharp.Formatting; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Formatting; namespace Microsoft.CodeAnalysis.CodeStyle { [DiagnosticAnalyzer(LanguageNames.CSharp)] internal class CSharpFormattingAnalyzer : AbstractFormattingAnalyzer { protected override ISyntaxFormattingService SyntaxFormattingService => CSharpSyntaxFormattingService.Instance; } }
-1
dotnet/roslyn
55,132
Support lambda expressions and method groups as `var` initializers
```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
cston
2021-07-27T03:12:21Z
2021-07-27T18:26:42Z
61a565cfcd777158cb6354351436aff997ad7bf6
5840335153dcca42570a853cdacd06d660fe9596
Support lambda expressions and method groups as `var` initializers. ```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
./src/Scripting/Core/Hosting/ObjectFormatter/CommonObjectFormatter.Visitor.FormattedMember.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Diagnostics; namespace Microsoft.CodeAnalysis.Scripting.Hosting { internal abstract partial class CommonObjectFormatter { private sealed partial class Visitor { private struct FormattedMember { // Non-negative if the member is an inlined element of an array (DebuggerBrowsableState.RootHidden applied on a member of array type). public readonly int Index; // Formatted name of the member or null if it doesn't have a name (Index is >=0 then). public readonly string Name; // Formatted value of the member. public readonly string Value; public FormattedMember(int index, string name, string value) { Debug.Assert((name != null) || (index >= 0)); Name = name; Index = index; Value = value; } /// <remarks> /// Doesn't (and doesn't need to) reflect the number of digits in <see cref="Index"/> since /// it's only used for a conservative approximation (shorter is more conservative when trying /// to determine the minimum number of members that will fill the output). /// </remarks> public int MinimalLength { get { return (Name != null ? Name.Length : "[0]".Length) + Value.Length; } } public string GetDisplayName() { return Name ?? "[" + Index.ToString() + "]"; } public bool HasKeyName() { return Index >= 0 && Name != null && Name.Length >= 2 && Name[0] == '[' && Name[Name.Length - 1] == ']'; } public bool AppendAsCollectionEntry(Builder result) { // Some BCL collections use [{key.ToString()}]: {value.ToString()} pattern to display collection entries. // We want them to be printed initializer-style, i.e. { <key>, <value> } if (HasKeyName()) { result.AppendGroupOpening(); result.AppendCollectionItemSeparator(isFirst: true, inline: true); result.Append(Name, 1, Name.Length - 2); result.AppendCollectionItemSeparator(isFirst: false, inline: true); result.Append(Value); result.AppendGroupClosing(inline: true); } else { result.Append(Value); } return true; } public bool Append(Builder result, string separator) { result.Append(GetDisplayName()); result.Append(separator); result.Append(Value); 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.Diagnostics; namespace Microsoft.CodeAnalysis.Scripting.Hosting { internal abstract partial class CommonObjectFormatter { private sealed partial class Visitor { private struct FormattedMember { // Non-negative if the member is an inlined element of an array (DebuggerBrowsableState.RootHidden applied on a member of array type). public readonly int Index; // Formatted name of the member or null if it doesn't have a name (Index is >=0 then). public readonly string Name; // Formatted value of the member. public readonly string Value; public FormattedMember(int index, string name, string value) { Debug.Assert((name != null) || (index >= 0)); Name = name; Index = index; Value = value; } /// <remarks> /// Doesn't (and doesn't need to) reflect the number of digits in <see cref="Index"/> since /// it's only used for a conservative approximation (shorter is more conservative when trying /// to determine the minimum number of members that will fill the output). /// </remarks> public int MinimalLength { get { return (Name != null ? Name.Length : "[0]".Length) + Value.Length; } } public string GetDisplayName() { return Name ?? "[" + Index.ToString() + "]"; } public bool HasKeyName() { return Index >= 0 && Name != null && Name.Length >= 2 && Name[0] == '[' && Name[Name.Length - 1] == ']'; } public bool AppendAsCollectionEntry(Builder result) { // Some BCL collections use [{key.ToString()}]: {value.ToString()} pattern to display collection entries. // We want them to be printed initializer-style, i.e. { <key>, <value> } if (HasKeyName()) { result.AppendGroupOpening(); result.AppendCollectionItemSeparator(isFirst: true, inline: true); result.Append(Name, 1, Name.Length - 2); result.AppendCollectionItemSeparator(isFirst: false, inline: true); result.Append(Value); result.AppendGroupClosing(inline: true); } else { result.Append(Value); } return true; } public bool Append(Builder result, string separator) { result.Append(GetDisplayName()); result.Append(separator); result.Append(Value); return true; } } } } }
-1
dotnet/roslyn
55,132
Support lambda expressions and method groups as `var` initializers
```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
cston
2021-07-27T03:12:21Z
2021-07-27T18:26:42Z
61a565cfcd777158cb6354351436aff997ad7bf6
5840335153dcca42570a853cdacd06d660fe9596
Support lambda expressions and method groups as `var` initializers. ```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
./src/EditorFeatures/CSharpTest2/Recommendations/ReadOnlyKeywordRecommenderTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Threading.Tasks; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations { public class ReadOnlyKeywordRecommenderTests : KeywordRecommenderTests { [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAtRoot() { await VerifyKeywordAsync( @"$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterClass() { await VerifyKeywordAsync( @"class C { } $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterGlobalStatement() { await VerifyKeywordAsync( @"System.Console.WriteLine(); $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterGlobalVariableDeclaration() { await VerifyKeywordAsync( @"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 TestAfterExtern() { await VerifyKeywordAsync(@"extern alias Goo; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterUsing() { await VerifyKeywordAsync(@"using Goo; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterGlobalUsing() { await VerifyKeywordAsync(@"global using Goo; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNamespace() { await VerifyKeywordAsync(@"namespace N {} $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterFileScopedNamespace() { await VerifyKeywordAsync( @"namespace N; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterTypeDeclaration() { await VerifyKeywordAsync(@"class C {} $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterDelegateDeclaration() { await VerifyKeywordAsync(@"delegate void Goo(); $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterMethod() { await VerifyKeywordAsync( @"class C { void Goo() {} $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterField() { await VerifyKeywordAsync( @"class C { int i; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterProperty() { await VerifyKeywordAsync( @"class C { int i { get; } $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotBeforeUsing() { await VerifyAbsenceAsync(SourceCodeKind.Regular, @"$$ using Goo;"); } [WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/9880"), Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotBeforeUsing_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"$$ using Goo;"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotBeforeGlobalUsing() { await VerifyAbsenceAsync(SourceCodeKind.Regular, @"$$ global using Goo;"); } [WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/9880"), Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotBeforeGlobalUsing_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"$$ global using Goo;"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterAssemblyAttribute() { await VerifyKeywordAsync(@"[assembly: goo] $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterRootAttribute() { await VerifyKeywordAsync(@"[goo] $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedAttribute() { await VerifyKeywordAsync( @"class C { [goo] $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInsideStruct() { await VerifyKeywordAsync( @"struct S { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInsideInterface() { await VerifyKeywordAsync(@"interface I { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInsideEnum() { await VerifyAbsenceAsync(@"enum E { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInsideClass() { await VerifyKeywordAsync( @"class C { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterPartial() => await VerifyKeywordAsync(@"partial $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterAbstract() => await VerifyKeywordAsync(@"abstract $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterInternal() => await VerifyKeywordAsync(@"internal $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedInternal() { await VerifyKeywordAsync( @"class C { internal $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterPublic() => await VerifyKeywordAsync(@"public $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedPublic() { await VerifyKeywordAsync( @"class C { public $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterPrivate() { await VerifyKeywordAsync(@"private $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedPrivate() { await VerifyKeywordAsync( @"class C { private $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterProtected() { await VerifyKeywordAsync( @"protected $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedProtected() { await VerifyKeywordAsync( @"class C { protected $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterSealed() => await VerifyKeywordAsync(@"sealed $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedSealed() { await VerifyKeywordAsync( @"class C { sealed $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterStatic() => await VerifyKeywordAsync(@"static $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedStatic() { await VerifyKeywordAsync( @"class C { static $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterStaticPublic() => await VerifyKeywordAsync(@"static public $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedStaticPublic() { await VerifyKeywordAsync( @"class C { static public $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterDelegate() => await VerifyAbsenceAsync(@"delegate $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterEvent() { await VerifyAbsenceAsync( @"class C { event $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterConst() { await VerifyAbsenceAsync( @"class C { const $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterReadOnly() { await VerifyKeywordAsync( @"class C { readonly $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterVolatile() { await VerifyAbsenceAsync( @"class C { volatile $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterRef() => await VerifyKeywordAsync(@"ref $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInRefStruct() => await VerifyKeywordAsync(@"ref $$ struct { }"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInRefStructBeforeRef() => await VerifyKeywordAsync(@"$$ ref struct { }"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem(44423, "https://github.com/dotnet/roslyn/issues/44423")] public async Task TestAfterNew() => await VerifyAbsenceAsync(@"new $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNewInClass() => await VerifyKeywordAsync(@"class C { new $$ }"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedNew() { await VerifyKeywordAsync( @"class C { new $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInMethod() { await VerifyAbsenceAsync( @"class C { void Goo() { $$"); } [CompilerTrait(CompilerFeature.ReadOnlyReferences)] [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TestRefReadonlyNotAsParameterModifierInMethods() { await VerifyAbsenceAsync(@" class Program { public static void Test(ref $$ p) { } }"); } [CompilerTrait(CompilerFeature.ReadOnlyReferences)] [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TestRefReadonlyNotAsParameterModifierInSecondParameter() { await VerifyAbsenceAsync(@" class Program { public static void Test(int p1, ref $$ p2) { } }"); } [CompilerTrait(CompilerFeature.ReadOnlyReferences)] [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TestRefReadonlyNotAsParameterModifierInDelegates() { await VerifyAbsenceAsync(@" public delegate int Delegate(ref $$ int p);"); } [CompilerTrait(CompilerFeature.ReadOnlyReferences)] [Theory, Trait(Traits.Feature, Traits.Features.Completion)] [CombinatorialData] public async Task TestRefReadonlyNotAsParameterModifierInLocalFunctions(bool topLevelStatement) { await VerifyAbsenceAsync(AddInsideMethod( @"void localFunc(ref $$ int p) { }", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); } [CompilerTrait(CompilerFeature.ReadOnlyReferences)] [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TestRefReadonlyNotAsParameterModifierInLambdaExpressions() { await VerifyAbsenceAsync(@" public delegate int Delegate(ref int p); class Program { public static void Test() { // This is bad. We can't put 'ref $ int p' like in the other tests here because in this scenario: // 'Delegate lambda = (ref r int p) => p;' (partially written 'readonly' keyword), // the syntax tree is completely broken and there is no lambda expression at all here. // 'ref' starts a new local declaration and therefore we do offer 'readonly'. // Fixing that would have to involve either changing the parser or doing some really nasty hacks. // Delegate lambda = (ref $$ int p) => p; } }"); } [CompilerTrait(CompilerFeature.ReadOnlyReferences)] [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TestRefReadonlyNotAsParameterModifierInAnonymousMethods() { await VerifyAbsenceAsync(@" public delegate int Delegate(ref int p); class Program { public static void Test() { Delegate anonymousDelegate = delegate (ref $$ int p) { return p; }; } }"); } [CompilerTrait(CompilerFeature.ReadOnlyReferences)] [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TestRefReadonlyAsModifierInMethodReturnTypes() { await VerifyKeywordAsync(@" class Program { public ref $$ int Test() { return ref x; } }"); } [CompilerTrait(CompilerFeature.ReadOnlyReferences)] [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TestRefReadonlyAsModifierInGlobalMemberDeclaration() { await VerifyKeywordAsync(@" public ref $$ "); } [CompilerTrait(CompilerFeature.ReadOnlyReferences)] [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TestRefReadonlyAsModifierInDelegateReturnType() { await VerifyKeywordAsync(@" public delegate ref $$ int Delegate(); class Program { }"); } [CompilerTrait(CompilerFeature.ReadOnlyReferences)] [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TestRefReadonlyAsModifierInMemberDeclaration() { await VerifyKeywordAsync(@" class Program { public ref $$ int Test { get; set; } }"); } [CompilerTrait(CompilerFeature.ReadOnlyReferences)] [Theory, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(25569, "https://github.com/dotnet/roslyn/issues/25569")] [CombinatorialData] public async Task TestRefReadonlyInStatementContext(bool topLevelStatement) { await VerifyKeywordAsync(AddInsideMethod( @"ref $$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); } [CompilerTrait(CompilerFeature.ReadOnlyReferences)] [Theory, Trait(Traits.Feature, Traits.Features.Completion)] [CombinatorialData] public async Task TestRefReadonlyInLocalDeclaration(bool topLevelStatement) { await VerifyKeywordAsync(AddInsideMethod( @"ref $$ int local;", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); } [CompilerTrait(CompilerFeature.ReadOnlyReferences)] [Theory, Trait(Traits.Feature, Traits.Features.Completion)] [CombinatorialData] public async Task TestRefReadonlyInLocalFunction(bool topLevelStatement) { await VerifyKeywordAsync(AddInsideMethod( @"ref $$ int Function();", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); } [CompilerTrait(CompilerFeature.ReadOnlyReferences)] [Theory, Trait(Traits.Feature, Traits.Features.Completion)] [CombinatorialData] public async Task TestRefReadonlyNotInRefExpression(bool topLevelStatement) { await VerifyAbsenceAsync(AddInsideMethod( @"ref int x = ref $$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInFunctionPointerTypeAfterRef() { await VerifyKeywordAsync(@" class C { delegate*<ref $$"); } [Fact] public async Task TestNotInFunctionPointerTypeWithoutRef() { await VerifyAbsenceAsync(@" class C { delegate*<$$"); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [InlineData("in")] [InlineData("out")] [InlineData("ref readonly")] public async Task TestNotInFunctionPointerTypeAfterOtherRefModifier(string modifier) { await VerifyAbsenceAsync($@" class C {{ delegate*<{modifier} $$"); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Threading.Tasks; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations { public class ReadOnlyKeywordRecommenderTests : KeywordRecommenderTests { [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAtRoot() { await VerifyKeywordAsync( @"$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterClass() { await VerifyKeywordAsync( @"class C { } $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterGlobalStatement() { await VerifyKeywordAsync( @"System.Console.WriteLine(); $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterGlobalVariableDeclaration() { await VerifyKeywordAsync( @"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 TestAfterExtern() { await VerifyKeywordAsync(@"extern alias Goo; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterUsing() { await VerifyKeywordAsync(@"using Goo; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterGlobalUsing() { await VerifyKeywordAsync(@"global using Goo; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNamespace() { await VerifyKeywordAsync(@"namespace N {} $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterFileScopedNamespace() { await VerifyKeywordAsync( @"namespace N; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterTypeDeclaration() { await VerifyKeywordAsync(@"class C {} $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterDelegateDeclaration() { await VerifyKeywordAsync(@"delegate void Goo(); $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterMethod() { await VerifyKeywordAsync( @"class C { void Goo() {} $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterField() { await VerifyKeywordAsync( @"class C { int i; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterProperty() { await VerifyKeywordAsync( @"class C { int i { get; } $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotBeforeUsing() { await VerifyAbsenceAsync(SourceCodeKind.Regular, @"$$ using Goo;"); } [WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/9880"), Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotBeforeUsing_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"$$ using Goo;"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotBeforeGlobalUsing() { await VerifyAbsenceAsync(SourceCodeKind.Regular, @"$$ global using Goo;"); } [WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/9880"), Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotBeforeGlobalUsing_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"$$ global using Goo;"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterAssemblyAttribute() { await VerifyKeywordAsync(@"[assembly: goo] $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterRootAttribute() { await VerifyKeywordAsync(@"[goo] $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedAttribute() { await VerifyKeywordAsync( @"class C { [goo] $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInsideStruct() { await VerifyKeywordAsync( @"struct S { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInsideInterface() { await VerifyKeywordAsync(@"interface I { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInsideEnum() { await VerifyAbsenceAsync(@"enum E { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInsideClass() { await VerifyKeywordAsync( @"class C { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterPartial() => await VerifyKeywordAsync(@"partial $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterAbstract() => await VerifyKeywordAsync(@"abstract $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterInternal() => await VerifyKeywordAsync(@"internal $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedInternal() { await VerifyKeywordAsync( @"class C { internal $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterPublic() => await VerifyKeywordAsync(@"public $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedPublic() { await VerifyKeywordAsync( @"class C { public $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterPrivate() { await VerifyKeywordAsync(@"private $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedPrivate() { await VerifyKeywordAsync( @"class C { private $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterProtected() { await VerifyKeywordAsync( @"protected $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedProtected() { await VerifyKeywordAsync( @"class C { protected $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterSealed() => await VerifyKeywordAsync(@"sealed $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedSealed() { await VerifyKeywordAsync( @"class C { sealed $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterStatic() => await VerifyKeywordAsync(@"static $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedStatic() { await VerifyKeywordAsync( @"class C { static $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterStaticPublic() => await VerifyKeywordAsync(@"static public $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedStaticPublic() { await VerifyKeywordAsync( @"class C { static public $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterDelegate() => await VerifyAbsenceAsync(@"delegate $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterEvent() { await VerifyAbsenceAsync( @"class C { event $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterConst() { await VerifyAbsenceAsync( @"class C { const $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterReadOnly() { await VerifyKeywordAsync( @"class C { readonly $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterVolatile() { await VerifyAbsenceAsync( @"class C { volatile $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterRef() => await VerifyKeywordAsync(@"ref $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInRefStruct() => await VerifyKeywordAsync(@"ref $$ struct { }"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInRefStructBeforeRef() => await VerifyKeywordAsync(@"$$ ref struct { }"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem(44423, "https://github.com/dotnet/roslyn/issues/44423")] public async Task TestAfterNew() => await VerifyAbsenceAsync(@"new $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNewInClass() => await VerifyKeywordAsync(@"class C { new $$ }"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedNew() { await VerifyKeywordAsync( @"class C { new $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInMethod() { await VerifyAbsenceAsync( @"class C { void Goo() { $$"); } [CompilerTrait(CompilerFeature.ReadOnlyReferences)] [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TestRefReadonlyNotAsParameterModifierInMethods() { await VerifyAbsenceAsync(@" class Program { public static void Test(ref $$ p) { } }"); } [CompilerTrait(CompilerFeature.ReadOnlyReferences)] [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TestRefReadonlyNotAsParameterModifierInSecondParameter() { await VerifyAbsenceAsync(@" class Program { public static void Test(int p1, ref $$ p2) { } }"); } [CompilerTrait(CompilerFeature.ReadOnlyReferences)] [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TestRefReadonlyNotAsParameterModifierInDelegates() { await VerifyAbsenceAsync(@" public delegate int Delegate(ref $$ int p);"); } [CompilerTrait(CompilerFeature.ReadOnlyReferences)] [Theory, Trait(Traits.Feature, Traits.Features.Completion)] [CombinatorialData] public async Task TestRefReadonlyNotAsParameterModifierInLocalFunctions(bool topLevelStatement) { await VerifyAbsenceAsync(AddInsideMethod( @"void localFunc(ref $$ int p) { }", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); } [CompilerTrait(CompilerFeature.ReadOnlyReferences)] [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TestRefReadonlyNotAsParameterModifierInLambdaExpressions() { await VerifyAbsenceAsync(@" public delegate int Delegate(ref int p); class Program { public static void Test() { // This is bad. We can't put 'ref $ int p' like in the other tests here because in this scenario: // 'Delegate lambda = (ref r int p) => p;' (partially written 'readonly' keyword), // the syntax tree is completely broken and there is no lambda expression at all here. // 'ref' starts a new local declaration and therefore we do offer 'readonly'. // Fixing that would have to involve either changing the parser or doing some really nasty hacks. // Delegate lambda = (ref $$ int p) => p; } }"); } [CompilerTrait(CompilerFeature.ReadOnlyReferences)] [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TestRefReadonlyNotAsParameterModifierInAnonymousMethods() { await VerifyAbsenceAsync(@" public delegate int Delegate(ref int p); class Program { public static void Test() { Delegate anonymousDelegate = delegate (ref $$ int p) { return p; }; } }"); } [CompilerTrait(CompilerFeature.ReadOnlyReferences)] [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TestRefReadonlyAsModifierInMethodReturnTypes() { await VerifyKeywordAsync(@" class Program { public ref $$ int Test() { return ref x; } }"); } [CompilerTrait(CompilerFeature.ReadOnlyReferences)] [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TestRefReadonlyAsModifierInGlobalMemberDeclaration() { await VerifyKeywordAsync(@" public ref $$ "); } [CompilerTrait(CompilerFeature.ReadOnlyReferences)] [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TestRefReadonlyAsModifierInDelegateReturnType() { await VerifyKeywordAsync(@" public delegate ref $$ int Delegate(); class Program { }"); } [CompilerTrait(CompilerFeature.ReadOnlyReferences)] [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TestRefReadonlyAsModifierInMemberDeclaration() { await VerifyKeywordAsync(@" class Program { public ref $$ int Test { get; set; } }"); } [CompilerTrait(CompilerFeature.ReadOnlyReferences)] [Theory, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(25569, "https://github.com/dotnet/roslyn/issues/25569")] [CombinatorialData] public async Task TestRefReadonlyInStatementContext(bool topLevelStatement) { await VerifyKeywordAsync(AddInsideMethod( @"ref $$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); } [CompilerTrait(CompilerFeature.ReadOnlyReferences)] [Theory, Trait(Traits.Feature, Traits.Features.Completion)] [CombinatorialData] public async Task TestRefReadonlyInLocalDeclaration(bool topLevelStatement) { await VerifyKeywordAsync(AddInsideMethod( @"ref $$ int local;", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); } [CompilerTrait(CompilerFeature.ReadOnlyReferences)] [Theory, Trait(Traits.Feature, Traits.Features.Completion)] [CombinatorialData] public async Task TestRefReadonlyInLocalFunction(bool topLevelStatement) { await VerifyKeywordAsync(AddInsideMethod( @"ref $$ int Function();", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); } [CompilerTrait(CompilerFeature.ReadOnlyReferences)] [Theory, Trait(Traits.Feature, Traits.Features.Completion)] [CombinatorialData] public async Task TestRefReadonlyNotInRefExpression(bool topLevelStatement) { await VerifyAbsenceAsync(AddInsideMethod( @"ref int x = ref $$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInFunctionPointerTypeAfterRef() { await VerifyKeywordAsync(@" class C { delegate*<ref $$"); } [Fact] public async Task TestNotInFunctionPointerTypeWithoutRef() { await VerifyAbsenceAsync(@" class C { delegate*<$$"); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [InlineData("in")] [InlineData("out")] [InlineData("ref readonly")] public async Task TestNotInFunctionPointerTypeAfterOtherRefModifier(string modifier) { await VerifyAbsenceAsync($@" class C {{ delegate*<{modifier} $$"); } } }
-1
dotnet/roslyn
55,132
Support lambda expressions and method groups as `var` initializers
```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
cston
2021-07-27T03:12:21Z
2021-07-27T18:26:42Z
61a565cfcd777158cb6354351436aff997ad7bf6
5840335153dcca42570a853cdacd06d660fe9596
Support lambda expressions and method groups as `var` initializers. ```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
./src/Compilers/Core/Portable/PEWriter/TypeReferenceIndexer.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET 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.Emit; using EmitContext = Microsoft.CodeAnalysis.Emit.EmitContext; namespace Microsoft.Cci { /// <summary> /// Visitor to force translation of all symbols that will be referred to /// in metadata. Allows us to build the set of types that must be embedded /// as local types (for NoPia). /// </summary> internal sealed class TypeReferenceIndexer : ReferenceIndexerBase { internal TypeReferenceIndexer(EmitContext context) : base(context) { } public override void Visit(CommonPEModuleBuilder module) { //EDMAURER visit these assembly-level attributes even when producing a module. //They'll be attached off the "AssemblyAttributesGoHere" typeRef if a module is being produced. this.Visit(module.GetSourceAssemblyAttributes(Context.IsRefAssembly)); this.Visit(module.GetSourceAssemblySecurityAttributes()); this.Visit(module.GetSourceModuleAttributes()); } protected override void RecordAssemblyReference(IAssemblyReference assemblyReference) { } protected override void RecordFileReference(IFileReference fileReference) { } protected override void RecordModuleReference(IModuleReference moduleReference) { } public override void Visit(IPlatformInvokeInformation platformInvokeInformation) { } protected override void ProcessMethodBody(IMethodDefinition method) { } protected override void RecordTypeReference(ITypeReference typeReference) { } protected override void ReserveFieldToken(IFieldReference fieldReference) { } protected override void ReserveMethodToken(IMethodReference methodReference) { } protected override void RecordTypeMemberReference(ITypeMemberReference typeMemberReference) { } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET 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.Emit; using EmitContext = Microsoft.CodeAnalysis.Emit.EmitContext; namespace Microsoft.Cci { /// <summary> /// Visitor to force translation of all symbols that will be referred to /// in metadata. Allows us to build the set of types that must be embedded /// as local types (for NoPia). /// </summary> internal sealed class TypeReferenceIndexer : ReferenceIndexerBase { internal TypeReferenceIndexer(EmitContext context) : base(context) { } public override void Visit(CommonPEModuleBuilder module) { //EDMAURER visit these assembly-level attributes even when producing a module. //They'll be attached off the "AssemblyAttributesGoHere" typeRef if a module is being produced. this.Visit(module.GetSourceAssemblyAttributes(Context.IsRefAssembly)); this.Visit(module.GetSourceAssemblySecurityAttributes()); this.Visit(module.GetSourceModuleAttributes()); } protected override void RecordAssemblyReference(IAssemblyReference assemblyReference) { } protected override void RecordFileReference(IFileReference fileReference) { } protected override void RecordModuleReference(IModuleReference moduleReference) { } public override void Visit(IPlatformInvokeInformation platformInvokeInformation) { } protected override void ProcessMethodBody(IMethodDefinition method) { } protected override void RecordTypeReference(ITypeReference typeReference) { } protected override void ReserveFieldToken(IFieldReference fieldReference) { } protected override void ReserveMethodToken(IMethodReference methodReference) { } protected override void RecordTypeMemberReference(ITypeMemberReference typeMemberReference) { } } }
-1
dotnet/roslyn
55,132
Support lambda expressions and method groups as `var` initializers
```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
cston
2021-07-27T03:12:21Z
2021-07-27T18:26:42Z
61a565cfcd777158cb6354351436aff997ad7bf6
5840335153dcca42570a853cdacd06d660fe9596
Support lambda expressions and method groups as `var` initializers. ```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
./src/Features/CSharp/Portable/DocumentationComments/CSharpDocumentationCommentFormattingService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Composition; using System.Diagnostics.CodeAnalysis; using Microsoft.CodeAnalysis.DocumentationComments; using Microsoft.CodeAnalysis.Host.Mef; namespace Microsoft.CodeAnalysis.CSharp.DocumentationComments { [ExportLanguageService(typeof(IDocumentationCommentFormattingService), LanguageNames.CSharp), Shared] internal class CSharpDocumentationCommentFormattingService : AbstractDocumentationCommentFormattingService { [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] public CSharpDocumentationCommentFormattingService() { } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Composition; using System.Diagnostics.CodeAnalysis; using Microsoft.CodeAnalysis.DocumentationComments; using Microsoft.CodeAnalysis.Host.Mef; namespace Microsoft.CodeAnalysis.CSharp.DocumentationComments { [ExportLanguageService(typeof(IDocumentationCommentFormattingService), LanguageNames.CSharp), Shared] internal class CSharpDocumentationCommentFormattingService : AbstractDocumentationCommentFormattingService { [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] public CSharpDocumentationCommentFormattingService() { } } }
-1
dotnet/roslyn
55,132
Support lambda expressions and method groups as `var` initializers
```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
cston
2021-07-27T03:12:21Z
2021-07-27T18:26:42Z
61a565cfcd777158cb6354351436aff997ad7bf6
5840335153dcca42570a853cdacd06d660fe9596
Support lambda expressions and method groups as `var` initializers. ```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
./src/Tools/ExternalAccess/FSharp/Editor/Implementation/Debugging/FSharpBreakpointResolutionResult.cs
// Licensed to the .NET Foundation under one or more agreements. // 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.Debugging; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.ExternalAccess.FSharp.Editor.Implementation.Debugging { // TODO: Should be readonly struct. internal sealed class FSharpBreakpointResolutionResult { internal readonly BreakpointResolutionResult UnderlyingObject; private FSharpBreakpointResolutionResult(BreakpointResolutionResult result) => UnderlyingObject = result; public Document Document => UnderlyingObject.Document; public TextSpan TextSpan => UnderlyingObject.TextSpan; public string? LocationNameOpt => UnderlyingObject.LocationNameOpt; public bool IsLineBreakpoint => UnderlyingObject.IsLineBreakpoint; public static FSharpBreakpointResolutionResult CreateSpanResult(Document document, TextSpan textSpan, string? locationNameOpt = null) => new FSharpBreakpointResolutionResult(BreakpointResolutionResult.CreateSpanResult(document, textSpan, locationNameOpt)); public static FSharpBreakpointResolutionResult CreateLineResult(Document document, string? locationNameOpt = null) => new FSharpBreakpointResolutionResult(BreakpointResolutionResult.CreateLineResult(document, locationNameOpt)); } }
// Licensed to the .NET Foundation under one or more agreements. // 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.Debugging; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.ExternalAccess.FSharp.Editor.Implementation.Debugging { // TODO: Should be readonly struct. internal sealed class FSharpBreakpointResolutionResult { internal readonly BreakpointResolutionResult UnderlyingObject; private FSharpBreakpointResolutionResult(BreakpointResolutionResult result) => UnderlyingObject = result; public Document Document => UnderlyingObject.Document; public TextSpan TextSpan => UnderlyingObject.TextSpan; public string? LocationNameOpt => UnderlyingObject.LocationNameOpt; public bool IsLineBreakpoint => UnderlyingObject.IsLineBreakpoint; public static FSharpBreakpointResolutionResult CreateSpanResult(Document document, TextSpan textSpan, string? locationNameOpt = null) => new FSharpBreakpointResolutionResult(BreakpointResolutionResult.CreateSpanResult(document, textSpan, locationNameOpt)); public static FSharpBreakpointResolutionResult CreateLineResult(Document document, string? locationNameOpt = null) => new FSharpBreakpointResolutionResult(BreakpointResolutionResult.CreateLineResult(document, locationNameOpt)); } }
-1
dotnet/roslyn
55,132
Support lambda expressions and method groups as `var` initializers
```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
cston
2021-07-27T03:12:21Z
2021-07-27T18:26:42Z
61a565cfcd777158cb6354351436aff997ad7bf6
5840335153dcca42570a853cdacd06d660fe9596
Support lambda expressions and method groups as `var` initializers. ```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
./src/Compilers/CSharp/Portable/FlowAnalysis/AbstractRegionDataFlowPass.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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 Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; namespace Microsoft.CodeAnalysis.CSharp { internal abstract class AbstractRegionDataFlowPass : DefiniteAssignmentPass { internal AbstractRegionDataFlowPass( CSharpCompilation compilation, Symbol member, BoundNode node, BoundNode firstInRegion, BoundNode lastInRegion, HashSet<Symbol> initiallyAssignedVariables = null, HashSet<PrefixUnaryExpressionSyntax> unassignedVariableAddressOfSyntaxes = null, bool trackUnassignments = false) : base(compilation, member, node, firstInRegion, lastInRegion, initiallyAssignedVariables, unassignedVariableAddressOfSyntaxes, trackUnassignments) { } /// <summary> /// To scan the whole body, we start outside (before) the region. /// </summary> protected override ImmutableArray<PendingBranch> Scan(ref bool badRegion) { MakeSlots(MethodParameters); if ((object)MethodThisParameter != null) GetOrCreateSlot(MethodThisParameter); var result = base.Scan(ref badRegion); return result; } public override BoundNode VisitLambda(BoundLambda node) { MakeSlots(node.Symbol.Parameters); return base.VisitLambda(node); } public override BoundNode VisitLocalFunctionStatement(BoundLocalFunctionStatement node) { MakeSlots(node.Symbol.Parameters); return base.VisitLocalFunctionStatement(node); } private void MakeSlots(ImmutableArray<ParameterSymbol> parameters) { // assign slots to the parameters foreach (var parameter in parameters) { GetOrCreateSlot(parameter); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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 Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; namespace Microsoft.CodeAnalysis.CSharp { internal abstract class AbstractRegionDataFlowPass : DefiniteAssignmentPass { internal AbstractRegionDataFlowPass( CSharpCompilation compilation, Symbol member, BoundNode node, BoundNode firstInRegion, BoundNode lastInRegion, HashSet<Symbol> initiallyAssignedVariables = null, HashSet<PrefixUnaryExpressionSyntax> unassignedVariableAddressOfSyntaxes = null, bool trackUnassignments = false) : base(compilation, member, node, firstInRegion, lastInRegion, initiallyAssignedVariables, unassignedVariableAddressOfSyntaxes, trackUnassignments) { } /// <summary> /// To scan the whole body, we start outside (before) the region. /// </summary> protected override ImmutableArray<PendingBranch> Scan(ref bool badRegion) { MakeSlots(MethodParameters); if ((object)MethodThisParameter != null) GetOrCreateSlot(MethodThisParameter); var result = base.Scan(ref badRegion); return result; } public override BoundNode VisitLambda(BoundLambda node) { MakeSlots(node.Symbol.Parameters); return base.VisitLambda(node); } public override BoundNode VisitLocalFunctionStatement(BoundLocalFunctionStatement node) { MakeSlots(node.Symbol.Parameters); return base.VisitLocalFunctionStatement(node); } private void MakeSlots(ImmutableArray<ParameterSymbol> parameters) { // assign slots to the parameters foreach (var parameter in parameters) { GetOrCreateSlot(parameter); } } } }
-1
dotnet/roslyn
55,132
Support lambda expressions and method groups as `var` initializers
```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
cston
2021-07-27T03:12:21Z
2021-07-27T18:26:42Z
61a565cfcd777158cb6354351436aff997ad7bf6
5840335153dcca42570a853cdacd06d660fe9596
Support lambda expressions and method groups as `var` initializers. ```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
./src/ExpressionEvaluator/CSharp/Source/ResultProvider/CSharpFormatter.Values.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.ObjectModel; using System.Diagnostics; using System.Text; using Microsoft.CodeAnalysis.ExpressionEvaluator; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.VisualStudio.Debugger.Clr; using Roslyn.Utilities; using Type = Microsoft.VisualStudio.Debugger.Metadata.Type; namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator { internal sealed partial class CSharpFormatter : Formatter { private void AppendEnumTypeAndName(StringBuilder builder, Type typeToDisplayOpt, string name) { if (typeToDisplayOpt != null) { // We're showing the type of a value, so "dynamic" does not apply. bool unused; int index1 = 0; int index2 = 0; AppendQualifiedTypeName( builder, typeToDisplayOpt, null, ref index1, null, ref index2, escapeKeywordIdentifiers: true, sawInvalidIdentifier: out unused); builder.Append('.'); AppendIdentifierEscapingPotentialKeywords(builder, name, sawInvalidIdentifier: out unused); } else { builder.Append(name); } } internal override string GetArrayDisplayString(DkmClrAppDomain appDomain, Type lmrType, ReadOnlyCollection<int> sizes, ReadOnlyCollection<int> lowerBounds, ObjectDisplayOptions options) { Debug.Assert(lmrType.IsArray); Type originalLmrType = lmrType; // Strip off all array types. We'll process them at the end. while (lmrType.IsArray) { lmrType = lmrType.GetElementType(); } var pooled = PooledStringBuilder.GetInstance(); var builder = pooled.Builder; builder.Append('{'); // We're showing the type of a value, so "dynamic" does not apply. bool unused; builder.Append(GetTypeName(new TypeAndCustomInfo(DkmClrType.Create(appDomain, lmrType)), escapeKeywordIdentifiers: false, sawInvalidIdentifier: out unused)); // NOTE: call our impl directly, since we're coupled anyway. var numSizes = sizes.Count; builder.Append('['); for (int i = 0; i < numSizes; i++) { if (i > 0) { builder.Append(", "); } var lowerBound = lowerBounds[i]; var size = sizes[i]; if (lowerBound == 0) { builder.Append(FormatLiteral(size, options)); } else { builder.Append(FormatLiteral(lowerBound, options)); builder.Append(".."); builder.Append(FormatLiteral(size + lowerBound - 1, options)); } } builder.Append(']'); lmrType = originalLmrType.GetElementType(); // Strip off one layer (already handled). while (lmrType.IsArray) { builder.Append('['); builder.Append(',', lmrType.GetArrayRank() - 1); builder.Append(']'); lmrType = lmrType.GetElementType(); } builder.Append('}'); return pooled.ToStringAndFree(); } internal override string GetArrayIndexExpression(string[] indices) { return indices.ToCommaSeparatedString('[', ']'); } internal override string GetCastExpression(string argument, string type, DkmClrCastExpressionOptions options) { Debug.Assert(!string.IsNullOrEmpty(argument)); Debug.Assert(!string.IsNullOrEmpty(type)); var pooled = PooledStringBuilder.GetInstance(); var builder = pooled.Builder; if ((options & DkmClrCastExpressionOptions.ParenthesizeEntireExpression) != 0) { builder.Append('('); } if ((options & DkmClrCastExpressionOptions.ParenthesizeArgument) != 0) { argument = $"({argument})"; } if ((options & DkmClrCastExpressionOptions.ConditionalCast) != 0) { builder.Append(argument); builder.Append(" as "); builder.Append(type); } else { builder.Append('('); builder.Append(type); builder.Append(')'); builder.Append(argument); } if ((options & DkmClrCastExpressionOptions.ParenthesizeEntireExpression) != 0) { builder.Append(')'); } return pooled.ToStringAndFree(); } internal override string GetTupleExpression(string[] values) { return values.ToCommaSeparatedString('(', ')'); } internal override string GetNamesForFlagsEnumValue(ArrayBuilder<EnumField> fields, object value, ulong underlyingValue, ObjectDisplayOptions options, Type typeToDisplayOpt) { var usedFields = ArrayBuilder<EnumField>.GetInstance(); FillUsedEnumFields(usedFields, fields, underlyingValue); if (usedFields.Count == 0) { return null; } var pooled = PooledStringBuilder.GetInstance(); var builder = pooled.Builder; for (int i = usedFields.Count - 1; i >= 0; i--) // Backwards to list smallest first. { AppendEnumTypeAndName(builder, typeToDisplayOpt, usedFields[i].Name); if (i > 0) { builder.Append(" | "); } } usedFields.Free(); return pooled.ToStringAndFree(); } internal override string GetNameForEnumValue(ArrayBuilder<EnumField> fields, object value, ulong underlyingValue, ObjectDisplayOptions options, Type typeToDisplayOpt) { foreach (var field in fields) { // First match wins (deterministic since sorted). if (underlyingValue == field.Value) { var pooled = PooledStringBuilder.GetInstance(); var builder = pooled.Builder; AppendEnumTypeAndName(builder, typeToDisplayOpt, field.Name); return pooled.ToStringAndFree(); } } return null; } internal override string GetObjectCreationExpression(string type, string[] arguments) { Debug.Assert(!string.IsNullOrEmpty(type)); var pooled = PooledStringBuilder.GetInstance(); var builder = pooled.Builder; builder.Append("new "); builder.Append(type); builder.Append('('); builder.AppendCommaSeparatedList(arguments); builder.Append(')'); return pooled.ToStringAndFree(); } internal override string FormatLiteral(char c, ObjectDisplayOptions options) { return ObjectDisplay.FormatLiteral(c, options); } internal override string FormatLiteral(int value, ObjectDisplayOptions options) { return ObjectDisplay.FormatLiteral(value, options & ~(ObjectDisplayOptions.UseQuotes | ObjectDisplayOptions.EscapeNonPrintableCharacters)); } internal override string FormatPrimitiveObject(object value, ObjectDisplayOptions options) { return ObjectDisplay.FormatPrimitive(value, options); } internal override string FormatString(string str, ObjectDisplayOptions options) { return ObjectDisplay.FormatLiteral(str, options); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.ObjectModel; using System.Diagnostics; using System.Text; using Microsoft.CodeAnalysis.ExpressionEvaluator; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.VisualStudio.Debugger.Clr; using Roslyn.Utilities; using Type = Microsoft.VisualStudio.Debugger.Metadata.Type; namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator { internal sealed partial class CSharpFormatter : Formatter { private void AppendEnumTypeAndName(StringBuilder builder, Type typeToDisplayOpt, string name) { if (typeToDisplayOpt != null) { // We're showing the type of a value, so "dynamic" does not apply. bool unused; int index1 = 0; int index2 = 0; AppendQualifiedTypeName( builder, typeToDisplayOpt, null, ref index1, null, ref index2, escapeKeywordIdentifiers: true, sawInvalidIdentifier: out unused); builder.Append('.'); AppendIdentifierEscapingPotentialKeywords(builder, name, sawInvalidIdentifier: out unused); } else { builder.Append(name); } } internal override string GetArrayDisplayString(DkmClrAppDomain appDomain, Type lmrType, ReadOnlyCollection<int> sizes, ReadOnlyCollection<int> lowerBounds, ObjectDisplayOptions options) { Debug.Assert(lmrType.IsArray); Type originalLmrType = lmrType; // Strip off all array types. We'll process them at the end. while (lmrType.IsArray) { lmrType = lmrType.GetElementType(); } var pooled = PooledStringBuilder.GetInstance(); var builder = pooled.Builder; builder.Append('{'); // We're showing the type of a value, so "dynamic" does not apply. bool unused; builder.Append(GetTypeName(new TypeAndCustomInfo(DkmClrType.Create(appDomain, lmrType)), escapeKeywordIdentifiers: false, sawInvalidIdentifier: out unused)); // NOTE: call our impl directly, since we're coupled anyway. var numSizes = sizes.Count; builder.Append('['); for (int i = 0; i < numSizes; i++) { if (i > 0) { builder.Append(", "); } var lowerBound = lowerBounds[i]; var size = sizes[i]; if (lowerBound == 0) { builder.Append(FormatLiteral(size, options)); } else { builder.Append(FormatLiteral(lowerBound, options)); builder.Append(".."); builder.Append(FormatLiteral(size + lowerBound - 1, options)); } } builder.Append(']'); lmrType = originalLmrType.GetElementType(); // Strip off one layer (already handled). while (lmrType.IsArray) { builder.Append('['); builder.Append(',', lmrType.GetArrayRank() - 1); builder.Append(']'); lmrType = lmrType.GetElementType(); } builder.Append('}'); return pooled.ToStringAndFree(); } internal override string GetArrayIndexExpression(string[] indices) { return indices.ToCommaSeparatedString('[', ']'); } internal override string GetCastExpression(string argument, string type, DkmClrCastExpressionOptions options) { Debug.Assert(!string.IsNullOrEmpty(argument)); Debug.Assert(!string.IsNullOrEmpty(type)); var pooled = PooledStringBuilder.GetInstance(); var builder = pooled.Builder; if ((options & DkmClrCastExpressionOptions.ParenthesizeEntireExpression) != 0) { builder.Append('('); } if ((options & DkmClrCastExpressionOptions.ParenthesizeArgument) != 0) { argument = $"({argument})"; } if ((options & DkmClrCastExpressionOptions.ConditionalCast) != 0) { builder.Append(argument); builder.Append(" as "); builder.Append(type); } else { builder.Append('('); builder.Append(type); builder.Append(')'); builder.Append(argument); } if ((options & DkmClrCastExpressionOptions.ParenthesizeEntireExpression) != 0) { builder.Append(')'); } return pooled.ToStringAndFree(); } internal override string GetTupleExpression(string[] values) { return values.ToCommaSeparatedString('(', ')'); } internal override string GetNamesForFlagsEnumValue(ArrayBuilder<EnumField> fields, object value, ulong underlyingValue, ObjectDisplayOptions options, Type typeToDisplayOpt) { var usedFields = ArrayBuilder<EnumField>.GetInstance(); FillUsedEnumFields(usedFields, fields, underlyingValue); if (usedFields.Count == 0) { return null; } var pooled = PooledStringBuilder.GetInstance(); var builder = pooled.Builder; for (int i = usedFields.Count - 1; i >= 0; i--) // Backwards to list smallest first. { AppendEnumTypeAndName(builder, typeToDisplayOpt, usedFields[i].Name); if (i > 0) { builder.Append(" | "); } } usedFields.Free(); return pooled.ToStringAndFree(); } internal override string GetNameForEnumValue(ArrayBuilder<EnumField> fields, object value, ulong underlyingValue, ObjectDisplayOptions options, Type typeToDisplayOpt) { foreach (var field in fields) { // First match wins (deterministic since sorted). if (underlyingValue == field.Value) { var pooled = PooledStringBuilder.GetInstance(); var builder = pooled.Builder; AppendEnumTypeAndName(builder, typeToDisplayOpt, field.Name); return pooled.ToStringAndFree(); } } return null; } internal override string GetObjectCreationExpression(string type, string[] arguments) { Debug.Assert(!string.IsNullOrEmpty(type)); var pooled = PooledStringBuilder.GetInstance(); var builder = pooled.Builder; builder.Append("new "); builder.Append(type); builder.Append('('); builder.AppendCommaSeparatedList(arguments); builder.Append(')'); return pooled.ToStringAndFree(); } internal override string FormatLiteral(char c, ObjectDisplayOptions options) { return ObjectDisplay.FormatLiteral(c, options); } internal override string FormatLiteral(int value, ObjectDisplayOptions options) { return ObjectDisplay.FormatLiteral(value, options & ~(ObjectDisplayOptions.UseQuotes | ObjectDisplayOptions.EscapeNonPrintableCharacters)); } internal override string FormatPrimitiveObject(object value, ObjectDisplayOptions options) { return ObjectDisplay.FormatPrimitive(value, options); } internal override string FormatString(string str, ObjectDisplayOptions options) { return ObjectDisplay.FormatLiteral(str, options); } } }
-1
dotnet/roslyn
55,132
Support lambda expressions and method groups as `var` initializers
```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
cston
2021-07-27T03:12:21Z
2021-07-27T18:26:42Z
61a565cfcd777158cb6354351436aff997ad7bf6
5840335153dcca42570a853cdacd06d660fe9596
Support lambda expressions and method groups as `var` initializers. ```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
./src/Workspaces/Core/Portable/Workspace/DocumentEventArgs.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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 Roslyn.Utilities; namespace Microsoft.CodeAnalysis { public class DocumentEventArgs : EventArgs { public Document Document { get; } public DocumentEventArgs(Document document) { Contract.ThrowIfNull(document); this.Document = document; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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 Roslyn.Utilities; namespace Microsoft.CodeAnalysis { public class DocumentEventArgs : EventArgs { public Document Document { get; } public DocumentEventArgs(Document document) { Contract.ThrowIfNull(document); this.Document = document; } } }
-1
dotnet/roslyn
55,132
Support lambda expressions and method groups as `var` initializers
```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
cston
2021-07-27T03:12:21Z
2021-07-27T18:26:42Z
61a565cfcd777158cb6354351436aff997ad7bf6
5840335153dcca42570a853cdacd06d660fe9596
Support lambda expressions and method groups as `var` initializers. ```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
./src/VisualStudio/Core/Impl/CodeModel/InternalElements/CodeEnum.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Runtime.InteropServices; using Microsoft.VisualStudio.LanguageServices.Implementation.Interop; namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.InternalElements { [ComVisible(true)] [ComDefaultInterface(typeof(EnvDTE.CodeEnum))] public sealed partial class CodeEnum : AbstractCodeType, EnvDTE.CodeEnum { internal static EnvDTE.CodeEnum Create( CodeModelState state, FileCodeModel fileCodeModel, SyntaxNodeKey nodeKey, int? nodeKind) { var element = new CodeEnum(state, fileCodeModel, nodeKey, nodeKind); var result = (EnvDTE.CodeEnum)ComAggregate.CreateAggregatedObject(element); fileCodeModel.OnCodeElementCreated(nodeKey, (EnvDTE.CodeElement)result); return result; } internal static EnvDTE.CodeEnum CreateUnknown( CodeModelState state, FileCodeModel fileCodeModel, int nodeKind, string name) { var element = new CodeEnum(state, fileCodeModel, nodeKind, name); return (EnvDTE.CodeEnum)ComAggregate.CreateAggregatedObject(element); } private CodeEnum( CodeModelState state, FileCodeModel fileCodeModel, SyntaxNodeKey nodeKey, int? nodeKind) : base(state, fileCodeModel, nodeKey, nodeKind) { } private CodeEnum( CodeModelState state, FileCodeModel fileCodeModel, int nodeKind, string name) : base(state, fileCodeModel, nodeKind, name) { } public override EnvDTE.vsCMElement Kind { get { return EnvDTE.vsCMElement.vsCMElementEnum; } } public EnvDTE.CodeVariable AddMember(string name, object value, object position) { return FileCodeModel.EnsureEditor(() => { return FileCodeModel.AddEnumMember(LookupNode(), name, value, position); }); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Runtime.InteropServices; using Microsoft.VisualStudio.LanguageServices.Implementation.Interop; namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.InternalElements { [ComVisible(true)] [ComDefaultInterface(typeof(EnvDTE.CodeEnum))] public sealed partial class CodeEnum : AbstractCodeType, EnvDTE.CodeEnum { internal static EnvDTE.CodeEnum Create( CodeModelState state, FileCodeModel fileCodeModel, SyntaxNodeKey nodeKey, int? nodeKind) { var element = new CodeEnum(state, fileCodeModel, nodeKey, nodeKind); var result = (EnvDTE.CodeEnum)ComAggregate.CreateAggregatedObject(element); fileCodeModel.OnCodeElementCreated(nodeKey, (EnvDTE.CodeElement)result); return result; } internal static EnvDTE.CodeEnum CreateUnknown( CodeModelState state, FileCodeModel fileCodeModel, int nodeKind, string name) { var element = new CodeEnum(state, fileCodeModel, nodeKind, name); return (EnvDTE.CodeEnum)ComAggregate.CreateAggregatedObject(element); } private CodeEnum( CodeModelState state, FileCodeModel fileCodeModel, SyntaxNodeKey nodeKey, int? nodeKind) : base(state, fileCodeModel, nodeKey, nodeKind) { } private CodeEnum( CodeModelState state, FileCodeModel fileCodeModel, int nodeKind, string name) : base(state, fileCodeModel, nodeKind, name) { } public override EnvDTE.vsCMElement Kind { get { return EnvDTE.vsCMElement.vsCMElementEnum; } } public EnvDTE.CodeVariable AddMember(string name, object value, object position) { return FileCodeModel.EnsureEditor(() => { return FileCodeModel.AddEnumMember(LookupNode(), name, value, position); }); } } }
-1
dotnet/roslyn
55,132
Support lambda expressions and method groups as `var` initializers
```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
cston
2021-07-27T03:12:21Z
2021-07-27T18:26:42Z
61a565cfcd777158cb6354351436aff997ad7bf6
5840335153dcca42570a853cdacd06d660fe9596
Support lambda expressions and method groups as `var` initializers. ```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
./src/Compilers/CSharp/Test/Symbol/Symbols/ErrorTypeSymbolTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Symbols { public class ErrorTypeSymbolTests : CSharpTestBase { [WorkItem(546143, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546143")] [Fact] public void ConstructedErrorTypes() { var source1 = @"public class A<T> { public class B<U> { } }"; var compilation1 = CreateCompilation(source1, assemblyName: "91AB32B7-DDDF-4E50-87EF-4E8B0A664A41"); compilation1.VerifyDiagnostics(); var reference1 = MetadataReference.CreateFromImage(compilation1.EmitToArray(options: new EmitOptions(metadataOnly: true))); // Binding types in source, no missing types. var source2 = @"class C1<T, U> : A<T>.B<U> { } class C2<T, U> : A<T>.B<U> { } class C3<T> : A<T>.B<object> { } class C4<T> : A<object>.B<T> { } class C5 : A<object>.B<int> { } class C6 : A<string>.B<object> { } class C7 : A<string>.B<object> { }"; var compilation2 = CreateCompilation(source2, references: new[] { reference1 }, assemblyName: "91AB32B7-DDDF-4E50-87EF-4E8B0A664A42"); compilation2.VerifyDiagnostics(); CompareConstructedErrorTypes(compilation2, missingTypes: false, fromSource: true); var reference2 = MetadataReference.CreateFromImage(compilation2.EmitToArray(options: new EmitOptions(metadataOnly: true))); // Loading types from metadata, no missing types. var source3 = @""; var compilation3 = CreateCompilation(source3, references: new[] { reference1, reference2 }); compilation3.VerifyDiagnostics(); CompareConstructedErrorTypes(compilation3, missingTypes: false, fromSource: false); // Binding types in source, missing types, resulting inExtendedErrorTypeSymbols. var compilation4 = CreateCompilation(source2); CompareConstructedErrorTypes(compilation4, missingTypes: true, fromSource: true); // Loading types from metadata, missing types, resulting in ErrorTypeSymbols. var source5 = @""; var compilation5 = CreateCompilation(source5, references: new[] { reference2 }); CompareConstructedErrorTypes(compilation5, missingTypes: true, fromSource: false); } private void CompareConstructedErrorTypes(CSharpCompilation compilation, bool missingTypes, bool fromSource) { // Get all root types. var allTypes = compilation.GlobalNamespace.GetTypeMembers(); // Get base class for each type named "C?". var types = new[] { "C1", "C2", "C3", "C4", "C5", "C6", "C7" }.Select(name => allTypes.First(t => t.Name == name).BaseType()).ToArray(); foreach (var type in types) { var constructedFrom = type.ConstructedFrom; Assert.NotEqual(type, constructedFrom); if (missingTypes) { Assert.True(type.IsErrorType()); Assert.True(constructedFrom.IsErrorType()); var extendedError = constructedFrom as ExtendedErrorTypeSymbol; if (fromSource) { Assert.NotNull(extendedError); } else { Assert.Null(extendedError); } } else { Assert.False(type.IsErrorType()); Assert.False(constructedFrom.IsErrorType()); } } // Compare pairs of types. The only error types that // should compare equal are C6 and C7. const int n = 7; for (int i = 0; i < n - 1; i++) { var typeA = types[i]; for (int j = i + 1; j < n; j++) { var typeB = types[j]; bool expectedEqual = (i == 5) && (j == 6); Assert.Equal(TypeSymbol.Equals(typeA, typeB, TypeCompareKind.ConsiderEverything2), expectedEqual); } } } [WorkItem(52516, "https://github.com/dotnet/roslyn/issues/52516")] [Fact] public void ErrorInfo_01() { var error = new MissingMetadataTypeSymbol.Nested(new UnsupportedMetadataTypeSymbol(), "Test", 0, false); var info = error.ErrorInfo; Assert.Equal(ErrorCode.ERR_BogusType, (ErrorCode)info.Code); Assert.Null(error.ContainingModule); Assert.Null(error.ContainingAssembly); Assert.NotNull(error.ContainingSymbol); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Symbols { public class ErrorTypeSymbolTests : CSharpTestBase { [WorkItem(546143, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546143")] [Fact] public void ConstructedErrorTypes() { var source1 = @"public class A<T> { public class B<U> { } }"; var compilation1 = CreateCompilation(source1, assemblyName: "91AB32B7-DDDF-4E50-87EF-4E8B0A664A41"); compilation1.VerifyDiagnostics(); var reference1 = MetadataReference.CreateFromImage(compilation1.EmitToArray(options: new EmitOptions(metadataOnly: true))); // Binding types in source, no missing types. var source2 = @"class C1<T, U> : A<T>.B<U> { } class C2<T, U> : A<T>.B<U> { } class C3<T> : A<T>.B<object> { } class C4<T> : A<object>.B<T> { } class C5 : A<object>.B<int> { } class C6 : A<string>.B<object> { } class C7 : A<string>.B<object> { }"; var compilation2 = CreateCompilation(source2, references: new[] { reference1 }, assemblyName: "91AB32B7-DDDF-4E50-87EF-4E8B0A664A42"); compilation2.VerifyDiagnostics(); CompareConstructedErrorTypes(compilation2, missingTypes: false, fromSource: true); var reference2 = MetadataReference.CreateFromImage(compilation2.EmitToArray(options: new EmitOptions(metadataOnly: true))); // Loading types from metadata, no missing types. var source3 = @""; var compilation3 = CreateCompilation(source3, references: new[] { reference1, reference2 }); compilation3.VerifyDiagnostics(); CompareConstructedErrorTypes(compilation3, missingTypes: false, fromSource: false); // Binding types in source, missing types, resulting inExtendedErrorTypeSymbols. var compilation4 = CreateCompilation(source2); CompareConstructedErrorTypes(compilation4, missingTypes: true, fromSource: true); // Loading types from metadata, missing types, resulting in ErrorTypeSymbols. var source5 = @""; var compilation5 = CreateCompilation(source5, references: new[] { reference2 }); CompareConstructedErrorTypes(compilation5, missingTypes: true, fromSource: false); } private void CompareConstructedErrorTypes(CSharpCompilation compilation, bool missingTypes, bool fromSource) { // Get all root types. var allTypes = compilation.GlobalNamespace.GetTypeMembers(); // Get base class for each type named "C?". var types = new[] { "C1", "C2", "C3", "C4", "C5", "C6", "C7" }.Select(name => allTypes.First(t => t.Name == name).BaseType()).ToArray(); foreach (var type in types) { var constructedFrom = type.ConstructedFrom; Assert.NotEqual(type, constructedFrom); if (missingTypes) { Assert.True(type.IsErrorType()); Assert.True(constructedFrom.IsErrorType()); var extendedError = constructedFrom as ExtendedErrorTypeSymbol; if (fromSource) { Assert.NotNull(extendedError); } else { Assert.Null(extendedError); } } else { Assert.False(type.IsErrorType()); Assert.False(constructedFrom.IsErrorType()); } } // Compare pairs of types. The only error types that // should compare equal are C6 and C7. const int n = 7; for (int i = 0; i < n - 1; i++) { var typeA = types[i]; for (int j = i + 1; j < n; j++) { var typeB = types[j]; bool expectedEqual = (i == 5) && (j == 6); Assert.Equal(TypeSymbol.Equals(typeA, typeB, TypeCompareKind.ConsiderEverything2), expectedEqual); } } } [WorkItem(52516, "https://github.com/dotnet/roslyn/issues/52516")] [Fact] public void ErrorInfo_01() { var error = new MissingMetadataTypeSymbol.Nested(new UnsupportedMetadataTypeSymbol(), "Test", 0, false); var info = error.ErrorInfo; Assert.Equal(ErrorCode.ERR_BogusType, (ErrorCode)info.Code); Assert.Null(error.ContainingModule); Assert.Null(error.ContainingAssembly); Assert.NotNull(error.ContainingSymbol); } } }
-1
dotnet/roslyn
55,132
Support lambda expressions and method groups as `var` initializers
```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
cston
2021-07-27T03:12:21Z
2021-07-27T18:26:42Z
61a565cfcd777158cb6354351436aff997ad7bf6
5840335153dcca42570a853cdacd06d660fe9596
Support lambda expressions and method groups as `var` initializers. ```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
./src/Compilers/CSharp/Test/Symbol/Symbols/Metadata/PE/TypeKindTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Xunit; using static Roslyn.Test.Utilities.TestMetadata; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Symbols.Metadata.PE { public class TypeKindTests : CSharpTestBase { [Fact] public void Test1() { var assembly = MetadataTestHelpers.GetSymbolForReference(Net40.mscorlib); TestTypeKindHelper(assembly); } private void TestTypeKindHelper(AssemblySymbol assembly) { var module0 = assembly.Modules[0]; var system = (from n in module0.GlobalNamespace.GetMembers() where n.Name.Equals("System") select n).Cast<NamespaceSymbol>().Single(); var obj = (from t in system.GetTypeMembers() where t.Name.Equals("Object") select t).Single(); Assert.Equal(TypeKind.Class, obj.TypeKind); var @enum = (from t in system.GetTypeMembers() where t.Name.Equals("Enum") select t).Single(); Assert.Equal(TypeKind.Class, @enum.TypeKind); var int32 = (from t in system.GetTypeMembers() where t.Name.Equals("Int32") select t).Single(); Assert.Equal(TypeKind.Struct, int32.TypeKind); var func = (from t in system.GetTypeMembers() where t.Name.Equals("Func") && t.Arity == 1 select t).Single(); Assert.Equal(TypeKind.Delegate, func.TypeKind); var collections = (from n in system.GetMembers() where n.Name.Equals("Collections") select n).Cast<NamespaceSymbol>().Single(); var ienumerable = (from t in collections.GetTypeMembers() where t.Name.Equals("IEnumerable") select t).Single(); Assert.Equal(TypeKind.Interface, ienumerable.TypeKind); Assert.Null(ienumerable.BaseType()); var typeCode = (from t in system.GetTypeMembers() where t.Name.Equals("TypeCode") select t).Single(); Assert.Equal(TypeKind.Enum, typeCode.TypeKind); Assert.False(obj.IsAbstract); Assert.False(obj.IsSealed); Assert.False(obj.IsStatic); Assert.True(@enum.IsAbstract); Assert.False(@enum.IsSealed); Assert.False(@enum.IsStatic); Assert.False(func.IsAbstract); Assert.True(func.IsSealed); Assert.False(func.IsStatic); var console = system.GetTypeMembers("Console").Single(); Assert.False(console.IsAbstract); Assert.False(console.IsSealed); Assert.True(console.IsStatic); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Xunit; using static Roslyn.Test.Utilities.TestMetadata; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Symbols.Metadata.PE { public class TypeKindTests : CSharpTestBase { [Fact] public void Test1() { var assembly = MetadataTestHelpers.GetSymbolForReference(Net40.mscorlib); TestTypeKindHelper(assembly); } private void TestTypeKindHelper(AssemblySymbol assembly) { var module0 = assembly.Modules[0]; var system = (from n in module0.GlobalNamespace.GetMembers() where n.Name.Equals("System") select n).Cast<NamespaceSymbol>().Single(); var obj = (from t in system.GetTypeMembers() where t.Name.Equals("Object") select t).Single(); Assert.Equal(TypeKind.Class, obj.TypeKind); var @enum = (from t in system.GetTypeMembers() where t.Name.Equals("Enum") select t).Single(); Assert.Equal(TypeKind.Class, @enum.TypeKind); var int32 = (from t in system.GetTypeMembers() where t.Name.Equals("Int32") select t).Single(); Assert.Equal(TypeKind.Struct, int32.TypeKind); var func = (from t in system.GetTypeMembers() where t.Name.Equals("Func") && t.Arity == 1 select t).Single(); Assert.Equal(TypeKind.Delegate, func.TypeKind); var collections = (from n in system.GetMembers() where n.Name.Equals("Collections") select n).Cast<NamespaceSymbol>().Single(); var ienumerable = (from t in collections.GetTypeMembers() where t.Name.Equals("IEnumerable") select t).Single(); Assert.Equal(TypeKind.Interface, ienumerable.TypeKind); Assert.Null(ienumerable.BaseType()); var typeCode = (from t in system.GetTypeMembers() where t.Name.Equals("TypeCode") select t).Single(); Assert.Equal(TypeKind.Enum, typeCode.TypeKind); Assert.False(obj.IsAbstract); Assert.False(obj.IsSealed); Assert.False(obj.IsStatic); Assert.True(@enum.IsAbstract); Assert.False(@enum.IsSealed); Assert.False(@enum.IsStatic); Assert.False(func.IsAbstract); Assert.True(func.IsSealed); Assert.False(func.IsStatic); var console = system.GetTypeMembers("Console").Single(); Assert.False(console.IsAbstract); Assert.False(console.IsSealed); Assert.True(console.IsStatic); } } }
-1
dotnet/roslyn
55,132
Support lambda expressions and method groups as `var` initializers
```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
cston
2021-07-27T03:12:21Z
2021-07-27T18:26:42Z
61a565cfcd777158cb6354351436aff997ad7bf6
5840335153dcca42570a853cdacd06d660fe9596
Support lambda expressions and method groups as `var` initializers. ```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
./src/Compilers/CSharp/Portable/Parser/Lexer.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Globalization; using System.Linq; using System.Text; using Microsoft.CodeAnalysis.Syntax.InternalSyntax; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax { [Flags] internal enum LexerMode { Syntax = 0x0001, DebuggerSyntax = 0x0002, Directive = 0x0004, XmlDocComment = 0x0008, XmlElementTag = 0x0010, XmlAttributeTextQuote = 0x0020, XmlAttributeTextDoubleQuote = 0x0040, XmlCrefQuote = 0x0080, XmlCrefDoubleQuote = 0x0100, XmlNameQuote = 0x0200, XmlNameDoubleQuote = 0x0400, XmlCDataSectionText = 0x0800, XmlCommentText = 0x1000, XmlProcessingInstructionText = 0x2000, XmlCharacter = 0x4000, MaskLexMode = 0xFFFF, // The following are lexer driven, which is to say the lexer can push a change back to the // blender. There is in general no need to use a whole bit per enum value, but the debugging // experience is bad if you don't do that. XmlDocCommentLocationStart = 0x00000, XmlDocCommentLocationInterior = 0x10000, XmlDocCommentLocationExterior = 0x20000, XmlDocCommentLocationEnd = 0x40000, MaskXmlDocCommentLocation = 0xF0000, XmlDocCommentStyleSingleLine = 0x000000, XmlDocCommentStyleDelimited = 0x100000, MaskXmlDocCommentStyle = 0x300000, None = 0 } // Needs to match LexMode.XmlDocCommentLocation* internal enum XmlDocCommentLocation { Start = 0, Interior = 1, Exterior = 2, End = 4 } // Needs to match LexMode.XmlDocCommentStyle* internal enum XmlDocCommentStyle { SingleLine = 0, Delimited = 1 } internal partial class Lexer : AbstractLexer { private const int TriviaListInitialCapacity = 8; private readonly CSharpParseOptions _options; private LexerMode _mode; private readonly StringBuilder _builder; private char[] _identBuffer; private int _identLen; private DirectiveStack _directives; private readonly LexerCache _cache; private readonly bool _allowPreprocessorDirectives; private readonly bool _interpolationFollowedByColon; private DocumentationCommentParser _xmlParser; private int _badTokenCount; // cumulative count of bad tokens produced internal struct TokenInfo { // scanned values internal SyntaxKind Kind; internal SyntaxKind ContextualKind; internal string Text; internal SpecialType ValueKind; internal bool RequiresTextForXmlEntity; internal bool HasIdentifierEscapeSequence; internal string StringValue; internal char CharValue; internal int IntValue; internal uint UintValue; internal long LongValue; internal ulong UlongValue; internal float FloatValue; internal double DoubleValue; internal decimal DecimalValue; internal bool IsVerbatim; } public Lexer(SourceText text, CSharpParseOptions options, bool allowPreprocessorDirectives = true, bool interpolationFollowedByColon = false) : base(text) { Debug.Assert(options != null); _options = options; _builder = new StringBuilder(); _identBuffer = new char[32]; _cache = new LexerCache(); _createQuickTokenFunction = this.CreateQuickToken; _allowPreprocessorDirectives = allowPreprocessorDirectives; _interpolationFollowedByColon = interpolationFollowedByColon; } public override void Dispose() { _cache.Free(); if (_xmlParser != null) { _xmlParser.Dispose(); } base.Dispose(); } public bool SuppressDocumentationCommentParse { get { return _options.DocumentationMode < DocumentationMode.Parse; } } public CSharpParseOptions Options { get { return _options; } } public DirectiveStack Directives { get { return _directives; } } /// <summary> /// The lexer is for the contents of an interpolation that is followed by a colon that signals the start of the format string. /// </summary> public bool InterpolationFollowedByColon { get { return _interpolationFollowedByColon; } } public void Reset(int position, DirectiveStack directives) { this.TextWindow.Reset(position); _directives = directives; } private static LexerMode ModeOf(LexerMode mode) { return mode & LexerMode.MaskLexMode; } private bool ModeIs(LexerMode mode) { return ModeOf(_mode) == mode; } private static XmlDocCommentLocation LocationOf(LexerMode mode) { return (XmlDocCommentLocation)((int)(mode & LexerMode.MaskXmlDocCommentLocation) >> 16); } private bool LocationIs(XmlDocCommentLocation location) { return LocationOf(_mode) == location; } private void MutateLocation(XmlDocCommentLocation location) { _mode &= ~LexerMode.MaskXmlDocCommentLocation; _mode |= (LexerMode)((int)location << 16); } private static XmlDocCommentStyle StyleOf(LexerMode mode) { return (XmlDocCommentStyle)((int)(mode & LexerMode.MaskXmlDocCommentStyle) >> 20); } private bool StyleIs(XmlDocCommentStyle style) { return StyleOf(_mode) == style; } private bool InDocumentationComment { get { switch (ModeOf(_mode)) { case LexerMode.XmlDocComment: case LexerMode.XmlElementTag: case LexerMode.XmlAttributeTextQuote: case LexerMode.XmlAttributeTextDoubleQuote: case LexerMode.XmlCrefQuote: case LexerMode.XmlCrefDoubleQuote: case LexerMode.XmlNameQuote: case LexerMode.XmlNameDoubleQuote: case LexerMode.XmlCDataSectionText: case LexerMode.XmlCommentText: case LexerMode.XmlProcessingInstructionText: case LexerMode.XmlCharacter: return true; default: return false; } } } public SyntaxToken Lex(ref LexerMode mode) { var result = Lex(mode); mode = _mode; return result; } #if DEBUG internal static int TokensLexed; #endif public SyntaxToken Lex(LexerMode mode) { #if DEBUG TokensLexed++; #endif _mode = mode; switch (_mode) { case LexerMode.Syntax: case LexerMode.DebuggerSyntax: return this.QuickScanSyntaxToken() ?? this.LexSyntaxToken(); case LexerMode.Directive: return this.LexDirectiveToken(); } switch (ModeOf(_mode)) { case LexerMode.XmlDocComment: return this.LexXmlToken(); case LexerMode.XmlElementTag: return this.LexXmlElementTagToken(); case LexerMode.XmlAttributeTextQuote: case LexerMode.XmlAttributeTextDoubleQuote: return this.LexXmlAttributeTextToken(); case LexerMode.XmlCDataSectionText: return this.LexXmlCDataSectionTextToken(); case LexerMode.XmlCommentText: return this.LexXmlCommentTextToken(); case LexerMode.XmlProcessingInstructionText: return this.LexXmlProcessingInstructionTextToken(); case LexerMode.XmlCrefQuote: case LexerMode.XmlCrefDoubleQuote: return this.LexXmlCrefOrNameToken(); case LexerMode.XmlNameQuote: case LexerMode.XmlNameDoubleQuote: // Same lexing as a cref attribute, just treat the identifiers a little differently. return this.LexXmlCrefOrNameToken(); case LexerMode.XmlCharacter: return this.LexXmlCharacter(); default: throw ExceptionUtilities.UnexpectedValue(ModeOf(_mode)); } } private SyntaxListBuilder _leadingTriviaCache = new SyntaxListBuilder(10); private SyntaxListBuilder _trailingTriviaCache = new SyntaxListBuilder(10); private static int GetFullWidth(SyntaxListBuilder builder) { int width = 0; if (builder != null) { for (int i = 0; i < builder.Count; i++) { width += builder[i].FullWidth; } } return width; } private SyntaxToken LexSyntaxToken() { _leadingTriviaCache.Clear(); this.LexSyntaxTrivia(afterFirstToken: TextWindow.Position > 0, isTrailing: false, triviaList: ref _leadingTriviaCache); var leading = _leadingTriviaCache; var tokenInfo = default(TokenInfo); this.Start(); this.ScanSyntaxToken(ref tokenInfo); var errors = this.GetErrors(GetFullWidth(leading)); _trailingTriviaCache.Clear(); this.LexSyntaxTrivia(afterFirstToken: true, isTrailing: true, triviaList: ref _trailingTriviaCache); var trailing = _trailingTriviaCache; return Create(ref tokenInfo, leading, trailing, errors); } internal SyntaxTriviaList LexSyntaxLeadingTrivia() { _leadingTriviaCache.Clear(); this.LexSyntaxTrivia(afterFirstToken: TextWindow.Position > 0, isTrailing: false, triviaList: ref _leadingTriviaCache); return new SyntaxTriviaList(default(Microsoft.CodeAnalysis.SyntaxToken), _leadingTriviaCache.ToListNode(), position: 0, index: 0); } internal SyntaxTriviaList LexSyntaxTrailingTrivia() { _trailingTriviaCache.Clear(); this.LexSyntaxTrivia(afterFirstToken: true, isTrailing: true, triviaList: ref _trailingTriviaCache); return new SyntaxTriviaList(default(Microsoft.CodeAnalysis.SyntaxToken), _trailingTriviaCache.ToListNode(), position: 0, index: 0); } private SyntaxToken Create(ref TokenInfo info, SyntaxListBuilder leading, SyntaxListBuilder trailing, SyntaxDiagnosticInfo[] errors) { Debug.Assert(info.Kind != SyntaxKind.IdentifierToken || info.StringValue != null); var leadingNode = leading?.ToListNode(); var trailingNode = trailing?.ToListNode(); SyntaxToken token; if (info.RequiresTextForXmlEntity) { token = SyntaxFactory.Token(leadingNode, info.Kind, info.Text, info.StringValue, trailingNode); } else { switch (info.Kind) { case SyntaxKind.IdentifierToken: token = SyntaxFactory.Identifier(info.ContextualKind, leadingNode, info.Text, info.StringValue, trailingNode); break; case SyntaxKind.NumericLiteralToken: switch (info.ValueKind) { case SpecialType.System_Int32: token = SyntaxFactory.Literal(leadingNode, info.Text, info.IntValue, trailingNode); break; case SpecialType.System_UInt32: token = SyntaxFactory.Literal(leadingNode, info.Text, info.UintValue, trailingNode); break; case SpecialType.System_Int64: token = SyntaxFactory.Literal(leadingNode, info.Text, info.LongValue, trailingNode); break; case SpecialType.System_UInt64: token = SyntaxFactory.Literal(leadingNode, info.Text, info.UlongValue, trailingNode); break; case SpecialType.System_Single: token = SyntaxFactory.Literal(leadingNode, info.Text, info.FloatValue, trailingNode); break; case SpecialType.System_Double: token = SyntaxFactory.Literal(leadingNode, info.Text, info.DoubleValue, trailingNode); break; case SpecialType.System_Decimal: token = SyntaxFactory.Literal(leadingNode, info.Text, info.DecimalValue, trailingNode); break; default: throw ExceptionUtilities.UnexpectedValue(info.ValueKind); } break; case SyntaxKind.InterpolatedStringToken: // we do not record a separate "value" for an interpolated string token, as it must be rescanned during parsing. token = SyntaxFactory.Literal(leadingNode, info.Text, info.Kind, info.Text, trailingNode); break; case SyntaxKind.StringLiteralToken: token = SyntaxFactory.Literal(leadingNode, info.Text, info.Kind, info.StringValue, trailingNode); break; case SyntaxKind.CharacterLiteralToken: token = SyntaxFactory.Literal(leadingNode, info.Text, info.CharValue, trailingNode); break; case SyntaxKind.XmlTextLiteralNewLineToken: token = SyntaxFactory.XmlTextNewLine(leadingNode, info.Text, info.StringValue, trailingNode); break; case SyntaxKind.XmlTextLiteralToken: token = SyntaxFactory.XmlTextLiteral(leadingNode, info.Text, info.StringValue, trailingNode); break; case SyntaxKind.XmlEntityLiteralToken: token = SyntaxFactory.XmlEntity(leadingNode, info.Text, info.StringValue, trailingNode); break; case SyntaxKind.EndOfDocumentationCommentToken: case SyntaxKind.EndOfFileToken: token = SyntaxFactory.Token(leadingNode, info.Kind, trailingNode); break; case SyntaxKind.None: token = SyntaxFactory.BadToken(leadingNode, info.Text, trailingNode); break; default: Debug.Assert(SyntaxFacts.IsPunctuationOrKeyword(info.Kind)); token = SyntaxFactory.Token(leadingNode, info.Kind, trailingNode); break; } } if (errors != null && (_options.DocumentationMode >= DocumentationMode.Diagnose || !InDocumentationComment)) { token = token.WithDiagnosticsGreen(errors); } return token; } private void ScanSyntaxToken(ref TokenInfo info) { // Initialize for new token scan info.Kind = SyntaxKind.None; info.ContextualKind = SyntaxKind.None; info.Text = null; char character; char surrogateCharacter = SlidingTextWindow.InvalidCharacter; bool isEscaped = false; int startingPosition = TextWindow.Position; // Start scanning the token character = TextWindow.PeekChar(); switch (character) { case '\"': case '\'': this.ScanStringLiteral(ref info, inDirective: false); break; case '/': TextWindow.AdvanceChar(); if (TextWindow.PeekChar() == '=') { TextWindow.AdvanceChar(); info.Kind = SyntaxKind.SlashEqualsToken; } else { info.Kind = SyntaxKind.SlashToken; } break; case '.': if (!this.ScanNumericLiteral(ref info)) { TextWindow.AdvanceChar(); if (TextWindow.PeekChar() == '.') { TextWindow.AdvanceChar(); if (TextWindow.PeekChar() == '.') { // Triple-dot: explicitly reject this, to allow triple-dot // to be added to the language without a breaking change. // (without this, 0...2 would parse as (0)..(.2), i.e. a range from 0 to 0.2) this.AddError(ErrorCode.ERR_TripleDotNotAllowed); } info.Kind = SyntaxKind.DotDotToken; } else { info.Kind = SyntaxKind.DotToken; } } break; case ',': TextWindow.AdvanceChar(); info.Kind = SyntaxKind.CommaToken; break; case ':': TextWindow.AdvanceChar(); if (TextWindow.PeekChar() == ':') { TextWindow.AdvanceChar(); info.Kind = SyntaxKind.ColonColonToken; } else { info.Kind = SyntaxKind.ColonToken; } break; case ';': TextWindow.AdvanceChar(); info.Kind = SyntaxKind.SemicolonToken; break; case '~': TextWindow.AdvanceChar(); info.Kind = SyntaxKind.TildeToken; break; case '!': TextWindow.AdvanceChar(); if (TextWindow.PeekChar() == '=') { TextWindow.AdvanceChar(); info.Kind = SyntaxKind.ExclamationEqualsToken; } else { info.Kind = SyntaxKind.ExclamationToken; } break; case '=': TextWindow.AdvanceChar(); if ((character = TextWindow.PeekChar()) == '=') { TextWindow.AdvanceChar(); info.Kind = SyntaxKind.EqualsEqualsToken; } else if (character == '>') { TextWindow.AdvanceChar(); info.Kind = SyntaxKind.EqualsGreaterThanToken; } else { info.Kind = SyntaxKind.EqualsToken; } break; case '*': TextWindow.AdvanceChar(); if (TextWindow.PeekChar() == '=') { TextWindow.AdvanceChar(); info.Kind = SyntaxKind.AsteriskEqualsToken; } else { info.Kind = SyntaxKind.AsteriskToken; } break; case '(': TextWindow.AdvanceChar(); info.Kind = SyntaxKind.OpenParenToken; break; case ')': TextWindow.AdvanceChar(); info.Kind = SyntaxKind.CloseParenToken; break; case '{': TextWindow.AdvanceChar(); info.Kind = SyntaxKind.OpenBraceToken; break; case '}': TextWindow.AdvanceChar(); info.Kind = SyntaxKind.CloseBraceToken; break; case '[': TextWindow.AdvanceChar(); info.Kind = SyntaxKind.OpenBracketToken; break; case ']': TextWindow.AdvanceChar(); info.Kind = SyntaxKind.CloseBracketToken; break; case '?': TextWindow.AdvanceChar(); if (TextWindow.PeekChar() == '?') { TextWindow.AdvanceChar(); if (TextWindow.PeekChar() == '=') { TextWindow.AdvanceChar(); info.Kind = SyntaxKind.QuestionQuestionEqualsToken; } else { info.Kind = SyntaxKind.QuestionQuestionToken; } } else { info.Kind = SyntaxKind.QuestionToken; } break; case '+': TextWindow.AdvanceChar(); if ((character = TextWindow.PeekChar()) == '=') { TextWindow.AdvanceChar(); info.Kind = SyntaxKind.PlusEqualsToken; } else if (character == '+') { TextWindow.AdvanceChar(); info.Kind = SyntaxKind.PlusPlusToken; } else { info.Kind = SyntaxKind.PlusToken; } break; case '-': TextWindow.AdvanceChar(); if ((character = TextWindow.PeekChar()) == '=') { TextWindow.AdvanceChar(); info.Kind = SyntaxKind.MinusEqualsToken; } else if (character == '-') { TextWindow.AdvanceChar(); info.Kind = SyntaxKind.MinusMinusToken; } else if (character == '>') { TextWindow.AdvanceChar(); info.Kind = SyntaxKind.MinusGreaterThanToken; } else { info.Kind = SyntaxKind.MinusToken; } break; case '%': TextWindow.AdvanceChar(); if (TextWindow.PeekChar() == '=') { TextWindow.AdvanceChar(); info.Kind = SyntaxKind.PercentEqualsToken; } else { info.Kind = SyntaxKind.PercentToken; } break; case '&': TextWindow.AdvanceChar(); if ((character = TextWindow.PeekChar()) == '=') { TextWindow.AdvanceChar(); info.Kind = SyntaxKind.AmpersandEqualsToken; } else if (TextWindow.PeekChar() == '&') { TextWindow.AdvanceChar(); info.Kind = SyntaxKind.AmpersandAmpersandToken; } else { info.Kind = SyntaxKind.AmpersandToken; } break; case '^': TextWindow.AdvanceChar(); if (TextWindow.PeekChar() == '=') { TextWindow.AdvanceChar(); info.Kind = SyntaxKind.CaretEqualsToken; } else { info.Kind = SyntaxKind.CaretToken; } break; case '|': TextWindow.AdvanceChar(); if (TextWindow.PeekChar() == '=') { TextWindow.AdvanceChar(); info.Kind = SyntaxKind.BarEqualsToken; } else if (TextWindow.PeekChar() == '|') { TextWindow.AdvanceChar(); info.Kind = SyntaxKind.BarBarToken; } else { info.Kind = SyntaxKind.BarToken; } break; case '<': TextWindow.AdvanceChar(); if (TextWindow.PeekChar() == '=') { TextWindow.AdvanceChar(); info.Kind = SyntaxKind.LessThanEqualsToken; } else if (TextWindow.PeekChar() == '<') { TextWindow.AdvanceChar(); if (TextWindow.PeekChar() == '=') { TextWindow.AdvanceChar(); info.Kind = SyntaxKind.LessThanLessThanEqualsToken; } else { info.Kind = SyntaxKind.LessThanLessThanToken; } } else { info.Kind = SyntaxKind.LessThanToken; } break; case '>': TextWindow.AdvanceChar(); if (TextWindow.PeekChar() == '=') { TextWindow.AdvanceChar(); info.Kind = SyntaxKind.GreaterThanEqualsToken; } else { info.Kind = SyntaxKind.GreaterThanToken; } break; case '@': if (TextWindow.PeekChar(1) == '"') { var errorCode = this.ScanVerbatimStringLiteral(ref info, allowNewlines: true); if (errorCode is ErrorCode code) this.AddError(code); } else if (TextWindow.PeekChar(1) == '$' && TextWindow.PeekChar(2) == '"') { this.ScanInterpolatedStringLiteral(isVerbatim: true, ref info); CheckFeatureAvailability(MessageID.IDS_FeatureAltInterpolatedVerbatimStrings); break; } else if (!this.ScanIdentifierOrKeyword(ref info)) { TextWindow.AdvanceChar(); info.Text = TextWindow.GetText(intern: true); this.AddError(ErrorCode.ERR_ExpectedVerbatimLiteral); } break; case '$': if (TextWindow.PeekChar(1) == '"') { this.ScanInterpolatedStringLiteral(isVerbatim: false, ref info); CheckFeatureAvailability(MessageID.IDS_FeatureInterpolatedStrings); break; } else if (TextWindow.PeekChar(1) == '@' && TextWindow.PeekChar(2) == '"') { this.ScanInterpolatedStringLiteral(isVerbatim: true, ref info); CheckFeatureAvailability(MessageID.IDS_FeatureInterpolatedStrings); break; } else if (this.ModeIs(LexerMode.DebuggerSyntax)) { goto case 'a'; } goto default; // All the 'common' identifier characters are represented directly in // these switch cases for optimal perf. Calling IsIdentifierChar() functions is relatively // expensive. case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g': case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n': case 'o': case 'p': case 'q': case 'r': case 's': case 't': case 'u': case 'v': case 'w': case 'x': case 'y': case 'z': case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G': case 'H': case 'I': case 'J': case 'K': case 'L': case 'M': case 'N': case 'O': case 'P': case 'Q': case 'R': case 'S': case 'T': case 'U': case 'V': case 'W': case 'X': case 'Y': case 'Z': case '_': this.ScanIdentifierOrKeyword(ref info); break; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': this.ScanNumericLiteral(ref info); break; case '\\': { // Could be unicode escape. Try that. character = TextWindow.PeekCharOrUnicodeEscape(out surrogateCharacter); isEscaped = true; if (SyntaxFacts.IsIdentifierStartCharacter(character)) { goto case 'a'; } goto default; } case SlidingTextWindow.InvalidCharacter: if (!TextWindow.IsReallyAtEnd()) { goto default; } if (_directives.HasUnfinishedIf()) { this.AddError(ErrorCode.ERR_EndifDirectiveExpected); } if (_directives.HasUnfinishedRegion()) { this.AddError(ErrorCode.ERR_EndRegionDirectiveExpected); } info.Kind = SyntaxKind.EndOfFileToken; break; default: if (SyntaxFacts.IsIdentifierStartCharacter(character)) { goto case 'a'; } if (isEscaped) { SyntaxDiagnosticInfo error; TextWindow.NextCharOrUnicodeEscape(out surrogateCharacter, out error); AddError(error); } else { TextWindow.AdvanceChar(); } if (_badTokenCount++ > 200) { // If we get too many characters that we cannot make sense of, absorb the rest of the input. int end = TextWindow.Text.Length; int width = end - startingPosition; info.Text = TextWindow.Text.ToString(new TextSpan(startingPosition, width)); TextWindow.Reset(end); } else { info.Text = TextWindow.GetText(intern: true); } this.AddError(ErrorCode.ERR_UnexpectedCharacter, info.Text); break; } } #nullable enable private void CheckFeatureAvailability(MessageID feature) { var info = feature.GetFeatureAvailabilityDiagnosticInfo(Options); if (info != null) { AddError(info.Code, info.Arguments); } } #nullable disable private bool ScanInteger() { int start = TextWindow.Position; char ch; while ((ch = TextWindow.PeekChar()) >= '0' && ch <= '9') { TextWindow.AdvanceChar(); } return start < TextWindow.Position; } // Allows underscores in integers, except at beginning for decimal and end private void ScanNumericLiteralSingleInteger(ref bool underscoreInWrongPlace, ref bool usedUnderscore, ref bool firstCharWasUnderscore, bool isHex, bool isBinary) { if (TextWindow.PeekChar() == '_') { if (isHex || isBinary) { firstCharWasUnderscore = true; } else { underscoreInWrongPlace = true; } } bool lastCharWasUnderscore = false; while (true) { char ch = TextWindow.PeekChar(); if (ch == '_') { usedUnderscore = true; lastCharWasUnderscore = true; } else if (!(isHex ? SyntaxFacts.IsHexDigit(ch) : isBinary ? SyntaxFacts.IsBinaryDigit(ch) : SyntaxFacts.IsDecDigit(ch))) { break; } else { _builder.Append(ch); lastCharWasUnderscore = false; } TextWindow.AdvanceChar(); } if (lastCharWasUnderscore) { underscoreInWrongPlace = true; } } private bool ScanNumericLiteral(ref TokenInfo info) { int start = TextWindow.Position; char ch; bool isHex = false; bool isBinary = false; bool hasDecimal = false; bool hasExponent = false; info.Text = null; info.ValueKind = SpecialType.None; _builder.Clear(); bool hasUSuffix = false; bool hasLSuffix = false; bool underscoreInWrongPlace = false; bool usedUnderscore = false; bool firstCharWasUnderscore = false; ch = TextWindow.PeekChar(); if (ch == '0') { ch = TextWindow.PeekChar(1); if (ch == 'x' || ch == 'X') { TextWindow.AdvanceChar(2); isHex = true; } else if (ch == 'b' || ch == 'B') { CheckFeatureAvailability(MessageID.IDS_FeatureBinaryLiteral); TextWindow.AdvanceChar(2); isBinary = true; } } if (isHex || isBinary) { // It's OK if it has no digits after the '0x' -- we'll catch it in ScanNumericLiteral // and give a proper error then. ScanNumericLiteralSingleInteger(ref underscoreInWrongPlace, ref usedUnderscore, ref firstCharWasUnderscore, isHex, isBinary); if ((ch = TextWindow.PeekChar()) == 'L' || ch == 'l') { if (ch == 'l') { this.AddError(TextWindow.Position, 1, ErrorCode.WRN_LowercaseEllSuffix); } TextWindow.AdvanceChar(); hasLSuffix = true; if ((ch = TextWindow.PeekChar()) == 'u' || ch == 'U') { TextWindow.AdvanceChar(); hasUSuffix = true; } } else if ((ch = TextWindow.PeekChar()) == 'u' || ch == 'U') { TextWindow.AdvanceChar(); hasUSuffix = true; if ((ch = TextWindow.PeekChar()) == 'L' || ch == 'l') { TextWindow.AdvanceChar(); hasLSuffix = true; } } } else { ScanNumericLiteralSingleInteger(ref underscoreInWrongPlace, ref usedUnderscore, ref firstCharWasUnderscore, isHex: false, isBinary: false); if (this.ModeIs(LexerMode.DebuggerSyntax) && TextWindow.PeekChar() == '#') { // Previously, in DebuggerSyntax mode, "123#" was a valid identifier. TextWindow.AdvanceChar(); info.StringValue = info.Text = TextWindow.GetText(intern: true); info.Kind = SyntaxKind.IdentifierToken; this.AddError(MakeError(ErrorCode.ERR_LegacyObjectIdSyntax)); return true; } if ((ch = TextWindow.PeekChar()) == '.') { var ch2 = TextWindow.PeekChar(1); if (ch2 >= '0' && ch2 <= '9') { hasDecimal = true; _builder.Append(ch); TextWindow.AdvanceChar(); ScanNumericLiteralSingleInteger(ref underscoreInWrongPlace, ref usedUnderscore, ref firstCharWasUnderscore, isHex: false, isBinary: false); } else if (_builder.Length == 0) { // we only have the dot so far.. (no preceding number or following number) TextWindow.Reset(start); return false; } } if ((ch = TextWindow.PeekChar()) == 'E' || ch == 'e') { _builder.Append(ch); TextWindow.AdvanceChar(); hasExponent = true; if ((ch = TextWindow.PeekChar()) == '-' || ch == '+') { _builder.Append(ch); TextWindow.AdvanceChar(); } if (!(((ch = TextWindow.PeekChar()) >= '0' && ch <= '9') || ch == '_')) { // use this for now (CS0595), cant use CS0594 as we dont know 'type' this.AddError(MakeError(ErrorCode.ERR_InvalidReal)); // add dummy exponent, so parser does not blow up _builder.Append('0'); } else { ScanNumericLiteralSingleInteger(ref underscoreInWrongPlace, ref usedUnderscore, ref firstCharWasUnderscore, isHex: false, isBinary: false); } } if (hasExponent || hasDecimal) { if ((ch = TextWindow.PeekChar()) == 'f' || ch == 'F') { TextWindow.AdvanceChar(); info.ValueKind = SpecialType.System_Single; } else if (ch == 'D' || ch == 'd') { TextWindow.AdvanceChar(); info.ValueKind = SpecialType.System_Double; } else if (ch == 'm' || ch == 'M') { TextWindow.AdvanceChar(); info.ValueKind = SpecialType.System_Decimal; } else { info.ValueKind = SpecialType.System_Double; } } else if ((ch = TextWindow.PeekChar()) == 'f' || ch == 'F') { TextWindow.AdvanceChar(); info.ValueKind = SpecialType.System_Single; } else if (ch == 'D' || ch == 'd') { TextWindow.AdvanceChar(); info.ValueKind = SpecialType.System_Double; } else if (ch == 'm' || ch == 'M') { TextWindow.AdvanceChar(); info.ValueKind = SpecialType.System_Decimal; } else if (ch == 'L' || ch == 'l') { if (ch == 'l') { this.AddError(TextWindow.Position, 1, ErrorCode.WRN_LowercaseEllSuffix); } TextWindow.AdvanceChar(); hasLSuffix = true; if ((ch = TextWindow.PeekChar()) == 'u' || ch == 'U') { TextWindow.AdvanceChar(); hasUSuffix = true; } } else if (ch == 'u' || ch == 'U') { hasUSuffix = true; TextWindow.AdvanceChar(); if ((ch = TextWindow.PeekChar()) == 'L' || ch == 'l') { TextWindow.AdvanceChar(); hasLSuffix = true; } } } if (underscoreInWrongPlace) { this.AddError(MakeError(start, TextWindow.Position - start, ErrorCode.ERR_InvalidNumber)); } else if (firstCharWasUnderscore) { CheckFeatureAvailability(MessageID.IDS_FeatureLeadingDigitSeparator); } else if (usedUnderscore) { CheckFeatureAvailability(MessageID.IDS_FeatureDigitSeparator); } info.Kind = SyntaxKind.NumericLiteralToken; info.Text = TextWindow.GetText(true); Debug.Assert(info.Text != null); var valueText = TextWindow.Intern(_builder); ulong val; switch (info.ValueKind) { case SpecialType.System_Single: info.FloatValue = this.GetValueSingle(valueText); break; case SpecialType.System_Double: info.DoubleValue = this.GetValueDouble(valueText); break; case SpecialType.System_Decimal: info.DecimalValue = this.GetValueDecimal(valueText, start, TextWindow.Position); break; default: if (string.IsNullOrEmpty(valueText)) { if (!underscoreInWrongPlace) { this.AddError(MakeError(ErrorCode.ERR_InvalidNumber)); } val = 0; //safe default } else { val = this.GetValueUInt64(valueText, isHex, isBinary); } // 2.4.4.2 Integer literals // ... // The type of an integer literal is determined as follows: // * If the literal has no suffix, it has the first of these types in which its value can be represented: int, uint, long, ulong. if (!hasUSuffix && !hasLSuffix) { if (val <= Int32.MaxValue) { info.ValueKind = SpecialType.System_Int32; info.IntValue = (int)val; } else if (val <= UInt32.MaxValue) { info.ValueKind = SpecialType.System_UInt32; info.UintValue = (uint)val; // TODO: See below, it may be desirable to mark this token // as special for folding if its value is 2147483648. } else if (val <= Int64.MaxValue) { info.ValueKind = SpecialType.System_Int64; info.LongValue = (long)val; } else { info.ValueKind = SpecialType.System_UInt64; info.UlongValue = val; // TODO: See below, it may be desirable to mark this token // as special for folding if its value is 9223372036854775808 } } else if (hasUSuffix && !hasLSuffix) { // * If the literal is suffixed by U or u, it has the first of these types in which its value can be represented: uint, ulong. if (val <= UInt32.MaxValue) { info.ValueKind = SpecialType.System_UInt32; info.UintValue = (uint)val; } else { info.ValueKind = SpecialType.System_UInt64; info.UlongValue = val; } } // * If the literal is suffixed by L or l, it has the first of these types in which its value can be represented: long, ulong. else if (!hasUSuffix & hasLSuffix) { if (val <= Int64.MaxValue) { info.ValueKind = SpecialType.System_Int64; info.LongValue = (long)val; } else { info.ValueKind = SpecialType.System_UInt64; info.UlongValue = val; // TODO: See below, it may be desirable to mark this token // as special for folding if its value is 9223372036854775808 } } // * If the literal is suffixed by UL, Ul, uL, ul, LU, Lu, lU, or lu, it is of type ulong. else { Debug.Assert(hasUSuffix && hasLSuffix); info.ValueKind = SpecialType.System_UInt64; info.UlongValue = val; } break; // Note, the following portion of the spec is not implemented here. It is implemented // in the unary minus analysis. // * When a decimal-integer-literal with the value 2147483648 (231) and no integer-type-suffix appears // as the token immediately following a unary minus operator token (§7.7.2), the result is a constant // of type int with the value −2147483648 (−231). In all other situations, such a decimal-integer- // literal is of type uint. // * When a decimal-integer-literal with the value 9223372036854775808 (263) and no integer-type-suffix // or the integer-type-suffix L or l appears as the token immediately following a unary minus operator // token (§7.7.2), the result is a constant of type long with the value −9223372036854775808 (−263). // In all other situations, such a decimal-integer-literal is of type ulong. } return true; } // TODO: Change to Int64.TryParse when it supports NumberStyles.AllowBinarySpecifier (inline this method into GetValueUInt32/64) private static bool TryParseBinaryUInt64(string text, out ulong value) { value = 0; foreach (char c in text) { // if uppermost bit is set, then the next bitshift will overflow if ((value & 0x8000000000000000) != 0) { return false; } // We shouldn't ever get a string that's nonbinary (see ScanNumericLiteral), // so don't explicitly check for it (there's a debug assert in SyntaxFacts) var bit = (ulong)SyntaxFacts.BinaryValue(c); value = (value << 1) | bit; } return true; } //used in directives private int GetValueInt32(string text, bool isHex) { int result; if (!Int32.TryParse(text, isHex ? NumberStyles.AllowHexSpecifier : NumberStyles.None, CultureInfo.InvariantCulture, out result)) { //we've already lexed the literal, so the error must be from overflow this.AddError(MakeError(ErrorCode.ERR_IntOverflow)); } return result; } //used for all non-directive integer literals (cast to desired type afterward) private ulong GetValueUInt64(string text, bool isHex, bool isBinary) { ulong result; if (isBinary) { if (!TryParseBinaryUInt64(text, out result)) { this.AddError(MakeError(ErrorCode.ERR_IntOverflow)); } } else if (!UInt64.TryParse(text, isHex ? NumberStyles.AllowHexSpecifier : NumberStyles.None, CultureInfo.InvariantCulture, out result)) { //we've already lexed the literal, so the error must be from overflow this.AddError(MakeError(ErrorCode.ERR_IntOverflow)); } return result; } private double GetValueDouble(string text) { double result; if (!RealParser.TryParseDouble(text, out result)) { //we've already lexed the literal, so the error must be from overflow this.AddError(MakeError(ErrorCode.ERR_FloatOverflow, "double")); } return result; } private float GetValueSingle(string text) { float result; if (!RealParser.TryParseFloat(text, out result)) { //we've already lexed the literal, so the error must be from overflow this.AddError(MakeError(ErrorCode.ERR_FloatOverflow, "float")); } return result; } private decimal GetValueDecimal(string text, int start, int end) { // Use decimal.TryParse to parse value. Note: the behavior of // decimal.TryParse differs from Dev11 in several cases: // // 1. [-]0eNm where N > 0 // The native compiler ignores sign and scale and treats such cases // as 0e0m. decimal.TryParse fails so these cases are compile errors. // [Bug #568475] // 2. 1e-Nm where N >= 1000 // The native compiler reports CS0594 "Floating-point constant is // outside the range of type 'decimal'". decimal.TryParse allows // N >> 1000 but treats decimals with very small exponents as 0. // [No bug.] // 3. Decimals with significant digits below 1e-49 // The native compiler considers digits below 1e-49 when rounding. // decimal.TryParse ignores digits below 1e-49 when rounding. This // last difference is perhaps the most significant since existing code // will continue to compile but constant values may be rounded differently. // (Note that the native compiler does not round in all cases either since // the native compiler chops the string at 50 significant digits. For example // ".100000000000000000000000000050000000000000000000001m" is not // rounded up to 0.1000000000000000000000000001.) // [Bug #568494] decimal result; if (!decimal.TryParse(text, NumberStyles.AllowDecimalPoint | NumberStyles.AllowExponent, CultureInfo.InvariantCulture, out result)) { //we've already lexed the literal, so the error must be from overflow this.AddError(this.MakeError(start, end - start, ErrorCode.ERR_FloatOverflow, "decimal")); } return result; } private void ResetIdentBuffer() { _identLen = 0; } private void AddIdentChar(char ch) { if (_identLen >= _identBuffer.Length) { this.GrowIdentBuffer(); } _identBuffer[_identLen++] = ch; } private void GrowIdentBuffer() { var tmp = new char[_identBuffer.Length * 2]; Array.Copy(_identBuffer, tmp, _identBuffer.Length); _identBuffer = tmp; } private bool ScanIdentifier(ref TokenInfo info) { return ScanIdentifier_FastPath(ref info) || (InXmlCrefOrNameAttributeValue ? ScanIdentifier_CrefSlowPath(ref info) : ScanIdentifier_SlowPath(ref info)); } // Implements a faster identifier lexer for the common case in the // language where: // // a) identifiers are not verbatim // b) identifiers don't contain unicode characters // c) identifiers don't contain unicode escapes // // Given that nearly all identifiers will contain [_a-zA-Z0-9] and will // be terminated by a small set of known characters (like dot, comma, // etc.), we can sit in a tight loop looking for this pattern and only // falling back to the slower (but correct) path if we see something we // can't handle. // // Note: this function also only works if the identifier (and terminator) // can be found in the current sliding window of chars we have from our // source text. With this constraint we can avoid the costly overhead // incurred with peek/advance/next. Because of this we can also avoid // the unnecessary stores/reads from identBuffer and all other instance // state while lexing. Instead we just keep track of our start, end, // and max positions and use those for quick checks internally. // // Note: it is critical that this method must only be called from a // code path that checked for IsIdentifierStartChar or '@' first. private bool ScanIdentifier_FastPath(ref TokenInfo info) { if ((_mode & LexerMode.MaskLexMode) == LexerMode.DebuggerSyntax) { // Debugger syntax is wonky. Can't use the fast path for it. return false; } var currentOffset = TextWindow.Offset; var characterWindow = TextWindow.CharacterWindow; var characterWindowCount = TextWindow.CharacterWindowCount; var startOffset = currentOffset; while (true) { if (currentOffset == characterWindowCount) { // no more contiguous characters. Fall back to slow path return false; } switch (characterWindow[currentOffset]) { case '&': // CONSIDER: This method is performance critical, so // it might be safer to kick out at the top (as for // LexerMode.DebuggerSyntax). // If we're in a cref, this could be the start of an // xml entity that belongs in the identifier. if (InXmlCrefOrNameAttributeValue) { // Fall back on the slow path. return false; } // Otherwise, end the identifier. goto case '\0'; case '\0': case ' ': case '\r': case '\n': case '\t': case '!': case '%': case '(': case ')': case '*': case '+': case ',': case '-': case '.': case '/': case ':': case ';': case '<': case '=': case '>': case '?': case '[': case ']': case '^': case '{': case '|': case '}': case '~': case '"': case '\'': // All of the following characters are not valid in an // identifier. If we see any of them, then we know we're // done. var length = currentOffset - startOffset; TextWindow.AdvanceChar(length); info.Text = info.StringValue = TextWindow.Intern(characterWindow, startOffset, length); info.IsVerbatim = false; return true; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': if (currentOffset == startOffset) { return false; } else { goto case 'A'; } case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G': case 'H': case 'I': case 'J': case 'K': case 'L': case 'M': case 'N': case 'O': case 'P': case 'Q': case 'R': case 'S': case 'T': case 'U': case 'V': case 'W': case 'X': case 'Y': case 'Z': case '_': case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g': case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n': case 'o': case 'p': case 'q': case 'r': case 's': case 't': case 'u': case 'v': case 'w': case 'x': case 'y': case 'z': // All of these characters are valid inside an identifier. // consume it and keep processing. currentOffset++; continue; // case '@': verbatim identifiers are handled in the slow path // case '\\': unicode escapes are handled in the slow path default: // Any other character is something we cannot handle. i.e. // unicode chars or an escape. Just break out and move to // the slow path. return false; } } } private bool ScanIdentifier_SlowPath(ref TokenInfo info) { int start = TextWindow.Position; this.ResetIdentBuffer(); info.IsVerbatim = TextWindow.PeekChar() == '@'; if (info.IsVerbatim) { TextWindow.AdvanceChar(); } bool isObjectAddress = false; while (true) { char surrogateCharacter = SlidingTextWindow.InvalidCharacter; bool isEscaped = false; char ch = TextWindow.PeekChar(); top: switch (ch) { case '\\': if (!isEscaped && TextWindow.IsUnicodeEscape()) { // ^^^^^^^ otherwise \u005Cu1234 looks just like \u1234! (i.e. escape within escape) info.HasIdentifierEscapeSequence = true; isEscaped = true; ch = TextWindow.PeekUnicodeEscape(out surrogateCharacter); goto top; } goto default; case '$': if (!this.ModeIs(LexerMode.DebuggerSyntax) || _identLen > 0) { goto LoopExit; } break; case SlidingTextWindow.InvalidCharacter: if (!TextWindow.IsReallyAtEnd()) { goto default; } goto LoopExit; case '_': case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G': case 'H': case 'I': case 'J': case 'K': case 'L': case 'M': case 'N': case 'O': case 'P': case 'Q': case 'R': case 'S': case 'T': case 'U': case 'V': case 'W': case 'X': case 'Y': case 'Z': case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g': case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n': case 'o': case 'p': case 'q': case 'r': case 's': case 't': case 'u': case 'v': case 'w': case 'x': case 'y': case 'z': { // Again, these are the 'common' identifier characters... break; } case '0': { if (_identLen == 0) { // Debugger syntax allows @0x[hexdigit]+ for object address identifiers. if (info.IsVerbatim && this.ModeIs(LexerMode.DebuggerSyntax) && (char.ToLower(TextWindow.PeekChar(1)) == 'x')) { isObjectAddress = true; } else { goto LoopExit; } } // Again, these are the 'common' identifier characters... break; } case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': { if (_identLen == 0) { goto LoopExit; } // Again, these are the 'common' identifier characters... break; } case ' ': case '\t': case '.': case ';': case '(': case ')': case ',': // ...and these are the 'common' stop characters. goto LoopExit; case '<': if (_identLen == 0 && this.ModeIs(LexerMode.DebuggerSyntax) && TextWindow.PeekChar(1) == '>') { // In DebuggerSyntax mode, identifiers are allowed to begin with <>. TextWindow.AdvanceChar(2); this.AddIdentChar('<'); this.AddIdentChar('>'); continue; } goto LoopExit; default: { // This is the 'expensive' call if (_identLen == 0 && ch > 127 && SyntaxFacts.IsIdentifierStartCharacter(ch)) { break; } else if (_identLen > 0 && ch > 127 && SyntaxFacts.IsIdentifierPartCharacter(ch)) { //// BUG 424819 : Handle identifier chars > 0xFFFF via surrogate pairs if (UnicodeCharacterUtilities.IsFormattingChar(ch)) { if (isEscaped) { SyntaxDiagnosticInfo error; TextWindow.NextCharOrUnicodeEscape(out surrogateCharacter, out error); AddError(error); } else { TextWindow.AdvanceChar(); } continue; // Ignore formatting characters } break; } else { // Not a valid identifier character, so bail. goto LoopExit; } } } if (isEscaped) { SyntaxDiagnosticInfo error; TextWindow.NextCharOrUnicodeEscape(out surrogateCharacter, out error); AddError(error); } else { TextWindow.AdvanceChar(); } this.AddIdentChar(ch); if (surrogateCharacter != SlidingTextWindow.InvalidCharacter) { this.AddIdentChar(surrogateCharacter); } } LoopExit: var width = TextWindow.Width; // exact size of input characters if (_identLen > 0) { info.Text = TextWindow.GetInternedText(); // id buffer is identical to width in input if (_identLen == width) { info.StringValue = info.Text; } else { info.StringValue = TextWindow.Intern(_identBuffer, 0, _identLen); } if (isObjectAddress) { // @0x[hexdigit]+ const int objectAddressOffset = 2; Debug.Assert(string.Equals(info.Text.Substring(0, objectAddressOffset + 1), "@0x", StringComparison.OrdinalIgnoreCase)); var valueText = TextWindow.Intern(_identBuffer, objectAddressOffset, _identLen - objectAddressOffset); // Verify valid hex value. if ((valueText.Length == 0) || !valueText.All(IsValidHexDigit)) { goto Fail; } // Parse hex value to check for overflow. this.GetValueUInt64(valueText, isHex: true, isBinary: false); } return true; } Fail: info.Text = null; info.StringValue = null; TextWindow.Reset(start); return false; } private static bool IsValidHexDigit(char c) { if ((c >= '0') && (c <= '9')) { return true; } c = char.ToLower(c); return (c >= 'a') && (c <= 'f'); } /// <summary> /// This method is essentially the same as ScanIdentifier_SlowPath, /// except that it can handle XML entities. Since ScanIdentifier /// is hot code and since this method does extra work, it seem /// worthwhile to separate it from the common case. /// </summary> /// <param name="info"></param> /// <returns></returns> private bool ScanIdentifier_CrefSlowPath(ref TokenInfo info) { Debug.Assert(InXmlCrefOrNameAttributeValue); int start = TextWindow.Position; this.ResetIdentBuffer(); if (AdvanceIfMatches('@')) { // In xml name attribute values, the '@' is part of the value text of the identifier // (to match dev11). if (InXmlNameAttributeValue) { AddIdentChar('@'); } else { info.IsVerbatim = true; } } while (true) { int beforeConsumed = TextWindow.Position; char consumedChar; char consumedSurrogate; if (TextWindow.PeekChar() == '&') { if (!TextWindow.TryScanXmlEntity(out consumedChar, out consumedSurrogate)) { // If it's not a valid entity, then it's not part of the identifier. TextWindow.Reset(beforeConsumed); goto LoopExit; } } else { consumedChar = TextWindow.NextChar(); consumedSurrogate = SlidingTextWindow.InvalidCharacter; } // NOTE: If the surrogate is non-zero, then consumedChar won't match // any of the cases below (UTF-16 guarantees that members of surrogate // pairs aren't separately valid). bool isEscaped = false; top: switch (consumedChar) { case '\\': // NOTE: For completeness, we should allow xml entities in unicode escape // sequences (DevDiv #16321). Since it is not currently a priority, we will // try to make the interim behavior sensible: we will only attempt to scan // a unicode escape if NONE of the characters are XML entities (including // the backslash, which we have already consumed). // When we're ready to implement this behavior, we can drop the position // check and use AdvanceIfMatches instead of PeekChar. if (!isEscaped && (TextWindow.Position == beforeConsumed + 1) && (TextWindow.PeekChar() == 'u' || TextWindow.PeekChar() == 'U')) { Debug.Assert(consumedSurrogate == SlidingTextWindow.InvalidCharacter, "Since consumedChar == '\\'"); info.HasIdentifierEscapeSequence = true; TextWindow.Reset(beforeConsumed); // ^^^^^^^ otherwise \u005Cu1234 looks just like \u1234! (i.e. escape within escape) isEscaped = true; SyntaxDiagnosticInfo error; consumedChar = TextWindow.NextUnicodeEscape(out consumedSurrogate, out error); AddCrefError(error); goto top; } goto default; case '_': case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G': case 'H': case 'I': case 'J': case 'K': case 'L': case 'M': case 'N': case 'O': case 'P': case 'Q': case 'R': case 'S': case 'T': case 'U': case 'V': case 'W': case 'X': case 'Y': case 'Z': case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g': case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n': case 'o': case 'p': case 'q': case 'r': case 's': case 't': case 'u': case 'v': case 'w': case 'x': case 'y': case 'z': { // Again, these are the 'common' identifier characters... break; } case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': { if (_identLen == 0) { TextWindow.Reset(beforeConsumed); goto LoopExit; } // Again, these are the 'common' identifier characters... break; } case ' ': case '$': case '\t': case '.': case ';': case '(': case ')': case ',': case '<': // ...and these are the 'common' stop characters. TextWindow.Reset(beforeConsumed); goto LoopExit; case SlidingTextWindow.InvalidCharacter: if (!TextWindow.IsReallyAtEnd()) { goto default; } TextWindow.Reset(beforeConsumed); goto LoopExit; default: { // This is the 'expensive' call if (_identLen == 0 && consumedChar > 127 && SyntaxFacts.IsIdentifierStartCharacter(consumedChar)) { break; } else if (_identLen > 0 && consumedChar > 127 && SyntaxFacts.IsIdentifierPartCharacter(consumedChar)) { //// BUG 424819 : Handle identifier chars > 0xFFFF via surrogate pairs if (UnicodeCharacterUtilities.IsFormattingChar(consumedChar)) { continue; // Ignore formatting characters } break; } else { // Not a valid identifier character, so bail. TextWindow.Reset(beforeConsumed); goto LoopExit; } } } this.AddIdentChar(consumedChar); if (consumedSurrogate != SlidingTextWindow.InvalidCharacter) { this.AddIdentChar(consumedSurrogate); } } LoopExit: if (_identLen > 0) { // NOTE: If we don't intern the string value, then we won't get a hit // in the keyword dictionary! (It searches for a key using identity.) // The text does not have to be interned (and probably shouldn't be // if it contains entities (else-case). var width = TextWindow.Width; // exact size of input characters // id buffer is identical to width in input if (_identLen == width) { info.StringValue = TextWindow.GetInternedText(); info.Text = info.StringValue; } else { info.StringValue = TextWindow.Intern(_identBuffer, 0, _identLen); info.Text = TextWindow.GetText(intern: false); } return true; } else { info.Text = null; info.StringValue = null; TextWindow.Reset(start); return false; } } private bool ScanIdentifierOrKeyword(ref TokenInfo info) { info.ContextualKind = SyntaxKind.None; if (this.ScanIdentifier(ref info)) { // check to see if it is an actual keyword if (!info.IsVerbatim && !info.HasIdentifierEscapeSequence) { if (this.ModeIs(LexerMode.Directive)) { SyntaxKind keywordKind = SyntaxFacts.GetPreprocessorKeywordKind(info.Text); if (SyntaxFacts.IsPreprocessorContextualKeyword(keywordKind)) { // Let the parser decide which instances are actually keywords. info.Kind = SyntaxKind.IdentifierToken; info.ContextualKind = keywordKind; } else { info.Kind = keywordKind; } } else { if (!_cache.TryGetKeywordKind(info.Text, out info.Kind)) { info.ContextualKind = info.Kind = SyntaxKind.IdentifierToken; } else if (SyntaxFacts.IsContextualKeyword(info.Kind)) { info.ContextualKind = info.Kind; info.Kind = SyntaxKind.IdentifierToken; } } if (info.Kind == SyntaxKind.None) { info.Kind = SyntaxKind.IdentifierToken; } } else { info.ContextualKind = info.Kind = SyntaxKind.IdentifierToken; } return true; } else { info.Kind = SyntaxKind.None; return false; } } private void LexSyntaxTrivia(bool afterFirstToken, bool isTrailing, ref SyntaxListBuilder triviaList) { bool onlyWhitespaceOnLine = !isTrailing; while (true) { this.Start(); char ch = TextWindow.PeekChar(); if (ch == ' ') { this.AddTrivia(this.ScanWhitespace(), ref triviaList); continue; } else if (ch > 127) { if (SyntaxFacts.IsWhitespace(ch)) { ch = ' '; } else if (SyntaxFacts.IsNewLine(ch)) { ch = '\n'; } } switch (ch) { case ' ': case '\t': // Horizontal tab case '\v': // Vertical Tab case '\f': // Form-feed case '\u001A': this.AddTrivia(this.ScanWhitespace(), ref triviaList); break; case '/': if ((ch = TextWindow.PeekChar(1)) == '/') { if (!this.SuppressDocumentationCommentParse && TextWindow.PeekChar(2) == '/' && TextWindow.PeekChar(3) != '/') { // Doc comments should never be in trailing trivia. // Stop processing so that it will be leading trivia on the next token. if (isTrailing) { return; } this.AddTrivia(this.LexXmlDocComment(XmlDocCommentStyle.SingleLine), ref triviaList); break; } // normal single line comment this.ScanToEndOfLine(); var text = TextWindow.GetText(false); this.AddTrivia(SyntaxFactory.Comment(text), ref triviaList); onlyWhitespaceOnLine = false; break; } else if (ch == '*') { if (!this.SuppressDocumentationCommentParse && TextWindow.PeekChar(2) == '*' && TextWindow.PeekChar(3) != '*' && TextWindow.PeekChar(3) != '/') { // Doc comments should never be in trailing trivia. // Stop processing so that it will be leading trivia on the next token. if (isTrailing) { return; } this.AddTrivia(this.LexXmlDocComment(XmlDocCommentStyle.Delimited), ref triviaList); break; } bool isTerminated; this.ScanMultiLineComment(out isTerminated); if (!isTerminated) { // The comment didn't end. Report an error at the start point. this.AddError(ErrorCode.ERR_OpenEndedComment); } var text = TextWindow.GetText(false); this.AddTrivia(SyntaxFactory.Comment(text), ref triviaList); onlyWhitespaceOnLine = false; break; } // not trivia return; case '\r': case '\n': this.AddTrivia(this.ScanEndOfLine(), ref triviaList); if (isTrailing) { return; } onlyWhitespaceOnLine = true; break; case '#': if (_allowPreprocessorDirectives) { this.LexDirectiveAndExcludedTrivia(afterFirstToken, isTrailing || !onlyWhitespaceOnLine, ref triviaList); break; } else { return; } // Note: we specifically do not look for the >>>>>>> pattern as the start of // a conflict marker trivia. That's because *technically* (albeit unlikely) // >>>>>>> could be the end of a very generic construct. So, instead, we only // recognize >>>>>>> as we are scanning the trivia after a ======= marker // (which can never be part of legal code). // case '>': case '=': case '<': if (!isTrailing) { if (IsConflictMarkerTrivia()) { this.LexConflictMarkerTrivia(ref triviaList); break; } } return; default: return; } } } // All conflict markers consist of the same character repeated seven times. If it is // a <<<<<<< or >>>>>>> marker then it is also followed by a space. private static readonly int s_conflictMarkerLength = "<<<<<<<".Length; private bool IsConflictMarkerTrivia() { var position = TextWindow.Position; var text = TextWindow.Text; if (position == 0 || SyntaxFacts.IsNewLine(text[position - 1])) { var firstCh = text[position]; Debug.Assert(firstCh == '<' || firstCh == '=' || firstCh == '>'); if ((position + s_conflictMarkerLength) <= text.Length) { for (int i = 0, n = s_conflictMarkerLength; i < n; i++) { if (text[position + i] != firstCh) { return false; } } if (firstCh == '=') { return true; } return (position + s_conflictMarkerLength) < text.Length && text[position + s_conflictMarkerLength] == ' '; } } return false; } private void LexConflictMarkerTrivia(ref SyntaxListBuilder triviaList) { this.Start(); this.AddError(TextWindow.Position, s_conflictMarkerLength, ErrorCode.ERR_Merge_conflict_marker_encountered); var startCh = this.TextWindow.PeekChar(); // First create a trivia from the start of this merge conflict marker to the // end of line/file (whichever comes first). LexConflictMarkerHeader(ref triviaList); // Now add the newlines as the next trivia. LexConflictMarkerEndOfLine(ref triviaList); // Now, if it was an ======= marker, then also created a DisabledText trivia for // the contents of the file after it, up until the next >>>>>>> marker we see. if (startCh == '=') { LexConflictMarkerDisabledText(ref triviaList); } } private SyntaxListBuilder LexConflictMarkerDisabledText(ref SyntaxListBuilder triviaList) { // Consume everything from the start of the mid-conflict marker to the start of the next // end-conflict marker. this.Start(); var hitEndConflictMarker = false; while (true) { var ch = this.TextWindow.PeekChar(); if (ch == SlidingTextWindow.InvalidCharacter) { break; } // If we hit the end-conflict marker, then lex it out at this point. if (ch == '>' && IsConflictMarkerTrivia()) { hitEndConflictMarker = true; break; } this.TextWindow.AdvanceChar(); } if (this.TextWindow.Width > 0) { this.AddTrivia(SyntaxFactory.DisabledText(TextWindow.GetText(false)), ref triviaList); } if (hitEndConflictMarker) { LexConflictMarkerTrivia(ref triviaList); } return triviaList; } private void LexConflictMarkerEndOfLine(ref SyntaxListBuilder triviaList) { this.Start(); while (SyntaxFacts.IsNewLine(this.TextWindow.PeekChar())) { this.TextWindow.AdvanceChar(); } if (this.TextWindow.Width > 0) { this.AddTrivia(SyntaxFactory.EndOfLine(TextWindow.GetText(false)), ref triviaList); } } private void LexConflictMarkerHeader(ref SyntaxListBuilder triviaList) { while (true) { var ch = this.TextWindow.PeekChar(); if (ch == SlidingTextWindow.InvalidCharacter || SyntaxFacts.IsNewLine(ch)) { break; } this.TextWindow.AdvanceChar(); } this.AddTrivia(SyntaxFactory.ConflictMarker(TextWindow.GetText(false)), ref triviaList); } private void AddTrivia(CSharpSyntaxNode trivia, ref SyntaxListBuilder list) { if (this.HasErrors) { trivia = trivia.WithDiagnosticsGreen(this.GetErrors(leadingTriviaWidth: 0)); } if (list == null) { list = new SyntaxListBuilder(TriviaListInitialCapacity); } list.Add(trivia); } private bool ScanMultiLineComment(out bool isTerminated) { if (TextWindow.PeekChar() == '/' && TextWindow.PeekChar(1) == '*') { TextWindow.AdvanceChar(2); char ch; while (true) { if ((ch = TextWindow.PeekChar()) == SlidingTextWindow.InvalidCharacter && TextWindow.IsReallyAtEnd()) { isTerminated = false; break; } else if (ch == '*' && TextWindow.PeekChar(1) == '/') { TextWindow.AdvanceChar(2); isTerminated = true; break; } else { TextWindow.AdvanceChar(); } } return true; } else { isTerminated = false; return false; } } private void ScanToEndOfLine() { char ch; while (!SyntaxFacts.IsNewLine(ch = TextWindow.PeekChar()) && (ch != SlidingTextWindow.InvalidCharacter || !TextWindow.IsReallyAtEnd())) { TextWindow.AdvanceChar(); } } /// <summary> /// Scans a new-line sequence (either a single new-line character or a CR-LF combo). /// </summary> /// <returns>A trivia node with the new-line text</returns> private CSharpSyntaxNode ScanEndOfLine() { char ch; switch (ch = TextWindow.PeekChar()) { case '\r': TextWindow.AdvanceChar(); if (TextWindow.PeekChar() == '\n') { TextWindow.AdvanceChar(); return SyntaxFactory.CarriageReturnLineFeed; } return SyntaxFactory.CarriageReturn; case '\n': TextWindow.AdvanceChar(); return SyntaxFactory.LineFeed; default: if (SyntaxFacts.IsNewLine(ch)) { TextWindow.AdvanceChar(); return SyntaxFactory.EndOfLine(ch.ToString()); } return null; } } /// <summary> /// Scans all of the whitespace (not new-lines) into a trivia node until it runs out. /// </summary> /// <returns>A trivia node with the whitespace text</returns> private SyntaxTrivia ScanWhitespace() { if (_createWhitespaceTriviaFunction == null) { _createWhitespaceTriviaFunction = this.CreateWhitespaceTrivia; } int hashCode = Hash.FnvOffsetBias; // FNV base bool onlySpaces = true; top: char ch = TextWindow.PeekChar(); switch (ch) { case '\t': // Horizontal tab case '\v': // Vertical Tab case '\f': // Form-feed case '\u001A': onlySpaces = false; goto case ' '; case ' ': TextWindow.AdvanceChar(); hashCode = Hash.CombineFNVHash(hashCode, ch); goto top; case '\r': // Carriage Return case '\n': // Line-feed break; default: if (ch > 127 && SyntaxFacts.IsWhitespace(ch)) { goto case '\t'; } break; } if (TextWindow.Width == 1 && onlySpaces) { return SyntaxFactory.Space; } else { var width = TextWindow.Width; if (width < MaxCachedTokenSize) { return _cache.LookupTrivia( TextWindow.CharacterWindow, TextWindow.LexemeRelativeStart, width, hashCode, _createWhitespaceTriviaFunction); } else { return _createWhitespaceTriviaFunction(); } } } private Func<SyntaxTrivia> _createWhitespaceTriviaFunction; private SyntaxTrivia CreateWhitespaceTrivia() { return SyntaxFactory.Whitespace(TextWindow.GetText(intern: true)); } private void LexDirectiveAndExcludedTrivia( bool afterFirstToken, bool afterNonWhitespaceOnLine, ref SyntaxListBuilder triviaList) { var directive = this.LexSingleDirective(true, true, afterFirstToken, afterNonWhitespaceOnLine, ref triviaList); // also lex excluded stuff var branching = directive as BranchingDirectiveTriviaSyntax; if (branching != null && !branching.BranchTaken) { this.LexExcludedDirectivesAndTrivia(true, ref triviaList); } } private void LexExcludedDirectivesAndTrivia(bool endIsActive, ref SyntaxListBuilder triviaList) { while (true) { bool hasFollowingDirective; var text = this.LexDisabledText(out hasFollowingDirective); if (text != null) { this.AddTrivia(text, ref triviaList); } if (!hasFollowingDirective) { break; } var directive = this.LexSingleDirective(false, endIsActive, false, false, ref triviaList); var branching = directive as BranchingDirectiveTriviaSyntax; if (directive.Kind == SyntaxKind.EndIfDirectiveTrivia || (branching != null && branching.BranchTaken)) { break; } else if (directive.Kind == SyntaxKind.IfDirectiveTrivia) { this.LexExcludedDirectivesAndTrivia(false, ref triviaList); } } } private CSharpSyntaxNode LexSingleDirective( bool isActive, bool endIsActive, bool afterFirstToken, bool afterNonWhitespaceOnLine, ref SyntaxListBuilder triviaList) { if (SyntaxFacts.IsWhitespace(TextWindow.PeekChar())) { this.Start(); this.AddTrivia(this.ScanWhitespace(), ref triviaList); } CSharpSyntaxNode directive; var saveMode = _mode; using (var dp = new DirectiveParser(this, _directives)) { directive = dp.ParseDirective(isActive, endIsActive, afterFirstToken, afterNonWhitespaceOnLine); } this.AddTrivia(directive, ref triviaList); _directives = directive.ApplyDirectives(_directives); _mode = saveMode; return directive; } // consume text up to the next directive private CSharpSyntaxNode LexDisabledText(out bool followedByDirective) { this.Start(); int lastLineStart = TextWindow.Position; int lines = 0; bool allWhitespace = true; while (true) { char ch = TextWindow.PeekChar(); switch (ch) { case SlidingTextWindow.InvalidCharacter: if (!TextWindow.IsReallyAtEnd()) { goto default; } followedByDirective = false; return TextWindow.Width > 0 ? SyntaxFactory.DisabledText(TextWindow.GetText(false)) : null; case '#': if (!_allowPreprocessorDirectives) goto default; followedByDirective = true; if (lastLineStart < TextWindow.Position && !allWhitespace) { goto default; } TextWindow.Reset(lastLineStart); // reset so directive parser can consume the starting whitespace on this line return TextWindow.Width > 0 ? SyntaxFactory.DisabledText(TextWindow.GetText(false)) : null; case '\r': case '\n': this.ScanEndOfLine(); lastLineStart = TextWindow.Position; allWhitespace = true; lines++; break; default: if (SyntaxFacts.IsNewLine(ch)) { goto case '\n'; } allWhitespace = allWhitespace && SyntaxFacts.IsWhitespace(ch); TextWindow.AdvanceChar(); break; } } } private SyntaxToken LexDirectiveToken() { this.Start(); TokenInfo info = default(TokenInfo); this.ScanDirectiveToken(ref info); var errors = this.GetErrors(leadingTriviaWidth: 0); var trailing = this.LexDirectiveTrailingTrivia(info.Kind == SyntaxKind.EndOfDirectiveToken); return Create(ref info, null, trailing, errors); } private bool ScanDirectiveToken(ref TokenInfo info) { char character; char surrogateCharacter; bool isEscaped = false; switch (character = TextWindow.PeekChar()) { case SlidingTextWindow.InvalidCharacter: if (!TextWindow.IsReallyAtEnd()) { goto default; } // don't consume end characters here info.Kind = SyntaxKind.EndOfDirectiveToken; break; case '\r': case '\n': // don't consume end characters here info.Kind = SyntaxKind.EndOfDirectiveToken; break; case '#': TextWindow.AdvanceChar(); info.Kind = SyntaxKind.HashToken; break; case '(': TextWindow.AdvanceChar(); info.Kind = SyntaxKind.OpenParenToken; break; case ')': TextWindow.AdvanceChar(); info.Kind = SyntaxKind.CloseParenToken; break; case ',': TextWindow.AdvanceChar(); info.Kind = SyntaxKind.CommaToken; break; case '-': TextWindow.AdvanceChar(); info.Kind = SyntaxKind.MinusToken; break; case '!': TextWindow.AdvanceChar(); if (TextWindow.PeekChar() == '=') { TextWindow.AdvanceChar(); info.Kind = SyntaxKind.ExclamationEqualsToken; } else { info.Kind = SyntaxKind.ExclamationToken; } break; case '=': TextWindow.AdvanceChar(); if (TextWindow.PeekChar() == '=') { TextWindow.AdvanceChar(); info.Kind = SyntaxKind.EqualsEqualsToken; } else { info.Kind = SyntaxKind.EqualsToken; } break; case '&': if (TextWindow.PeekChar(1) == '&') { TextWindow.AdvanceChar(2); info.Kind = SyntaxKind.AmpersandAmpersandToken; break; } goto default; case '|': if (TextWindow.PeekChar(1) == '|') { TextWindow.AdvanceChar(2); info.Kind = SyntaxKind.BarBarToken; break; } goto default; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': this.ScanInteger(); info.Kind = SyntaxKind.NumericLiteralToken; info.Text = TextWindow.GetText(true); info.ValueKind = SpecialType.System_Int32; info.IntValue = this.GetValueInt32(info.Text, false); break; case '\"': this.ScanStringLiteral(ref info, inDirective: true); break; case '\\': { // Could be unicode escape. Try that. character = TextWindow.PeekCharOrUnicodeEscape(out surrogateCharacter); isEscaped = true; if (SyntaxFacts.IsIdentifierStartCharacter(character)) { this.ScanIdentifierOrKeyword(ref info); break; } goto default; } default: if (!isEscaped && SyntaxFacts.IsNewLine(character)) { goto case '\n'; } if (SyntaxFacts.IsIdentifierStartCharacter(character)) { this.ScanIdentifierOrKeyword(ref info); } else { // unknown single character if (isEscaped) { SyntaxDiagnosticInfo error; TextWindow.NextCharOrUnicodeEscape(out surrogateCharacter, out error); AddError(error); } else { TextWindow.AdvanceChar(); } info.Kind = SyntaxKind.None; info.Text = TextWindow.GetText(true); } break; } Debug.Assert(info.Kind != SyntaxKind.None || info.Text != null); return info.Kind != SyntaxKind.None; } private SyntaxListBuilder LexDirectiveTrailingTrivia(bool includeEndOfLine) { SyntaxListBuilder trivia = null; CSharpSyntaxNode tr; while (true) { var pos = TextWindow.Position; tr = this.LexDirectiveTrivia(); if (tr == null) { break; } else if (tr.Kind == SyntaxKind.EndOfLineTrivia) { if (includeEndOfLine) { AddTrivia(tr, ref trivia); } else { // don't consume end of line... TextWindow.Reset(pos); } break; } else { AddTrivia(tr, ref trivia); } } return trivia; } private CSharpSyntaxNode LexDirectiveTrivia() { CSharpSyntaxNode trivia = null; this.Start(); char ch = TextWindow.PeekChar(); switch (ch) { case '/': if (TextWindow.PeekChar(1) == '/') { // normal single line comment this.ScanToEndOfLine(); var text = TextWindow.GetText(false); trivia = SyntaxFactory.Comment(text); } break; case '\r': case '\n': trivia = this.ScanEndOfLine(); break; case ' ': case '\t': // Horizontal tab case '\v': // Vertical Tab case '\f': // Form-feed trivia = this.ScanWhitespace(); break; default: if (SyntaxFacts.IsWhitespace(ch)) { goto case ' '; } if (SyntaxFacts.IsNewLine(ch)) { goto case '\n'; } break; } return trivia; } private CSharpSyntaxNode LexXmlDocComment(XmlDocCommentStyle style) { var saveMode = _mode; bool isTerminated; var mode = style == XmlDocCommentStyle.SingleLine ? LexerMode.XmlDocCommentStyleSingleLine : LexerMode.XmlDocCommentStyleDelimited; if (_xmlParser == null) { _xmlParser = new DocumentationCommentParser(this, mode); } else { _xmlParser.ReInitialize(mode); } var docComment = _xmlParser.ParseDocumentationComment(out isTerminated); // We better have finished with the whole comment. There should be error // code in the implementation of ParseXmlDocComment that ensures this. Debug.Assert(this.LocationIs(XmlDocCommentLocation.End) || TextWindow.PeekChar() == SlidingTextWindow.InvalidCharacter); _mode = saveMode; if (!isTerminated) { // The comment didn't end. Report an error at the start point. // NOTE: report this error even if the DocumentationMode is less than diagnose - the comment // would be malformed as a non-doc comment as well. this.AddError(TextWindow.LexemeStartPosition, TextWindow.Width, ErrorCode.ERR_OpenEndedComment); } return docComment; } /// <summary> /// Lexer entry point for LexMode.XmlDocComment /// </summary> private SyntaxToken LexXmlToken() { TokenInfo xmlTokenInfo = default(TokenInfo); SyntaxListBuilder leading = null; this.LexXmlDocCommentLeadingTrivia(ref leading); this.Start(); this.ScanXmlToken(ref xmlTokenInfo); var errors = this.GetErrors(GetFullWidth(leading)); return Create(ref xmlTokenInfo, leading, null, errors); } private bool ScanXmlToken(ref TokenInfo info) { char ch; Debug.Assert(!this.LocationIs(XmlDocCommentLocation.Start)); Debug.Assert(!this.LocationIs(XmlDocCommentLocation.Exterior)); if (this.LocationIs(XmlDocCommentLocation.End)) { info.Kind = SyntaxKind.EndOfDocumentationCommentToken; return true; } switch (ch = TextWindow.PeekChar()) { case '&': this.ScanXmlEntity(ref info); info.Kind = SyntaxKind.XmlEntityLiteralToken; break; case '<': this.ScanXmlTagStart(ref info); break; case '\r': case '\n': ScanXmlTextLiteralNewLineToken(ref info); break; case SlidingTextWindow.InvalidCharacter: if (!TextWindow.IsReallyAtEnd()) { goto default; } info.Kind = SyntaxKind.EndOfDocumentationCommentToken; break; default: if (SyntaxFacts.IsNewLine(ch)) { goto case '\n'; } this.ScanXmlText(ref info); info.Kind = SyntaxKind.XmlTextLiteralToken; break; } Debug.Assert(info.Kind != SyntaxKind.None || info.Text != null); return info.Kind != SyntaxKind.None; } private void ScanXmlTextLiteralNewLineToken(ref TokenInfo info) { this.ScanEndOfLine(); info.StringValue = info.Text = TextWindow.GetText(intern: false); info.Kind = SyntaxKind.XmlTextLiteralNewLineToken; this.MutateLocation(XmlDocCommentLocation.Exterior); } private void ScanXmlTagStart(ref TokenInfo info) { Debug.Assert(TextWindow.PeekChar() == '<'); if (TextWindow.PeekChar(1) == '!') { if (TextWindow.PeekChar(2) == '-' && TextWindow.PeekChar(3) == '-') { TextWindow.AdvanceChar(4); info.Kind = SyntaxKind.XmlCommentStartToken; } else if (TextWindow.PeekChar(2) == '[' && TextWindow.PeekChar(3) == 'C' && TextWindow.PeekChar(4) == 'D' && TextWindow.PeekChar(5) == 'A' && TextWindow.PeekChar(6) == 'T' && TextWindow.PeekChar(7) == 'A' && TextWindow.PeekChar(8) == '[') { TextWindow.AdvanceChar(9); info.Kind = SyntaxKind.XmlCDataStartToken; } else { // TODO: Take the < by itself, I guess? TextWindow.AdvanceChar(); info.Kind = SyntaxKind.LessThanToken; } } else if (TextWindow.PeekChar(1) == '/') { TextWindow.AdvanceChar(2); info.Kind = SyntaxKind.LessThanSlashToken; } else if (TextWindow.PeekChar(1) == '?') { TextWindow.AdvanceChar(2); info.Kind = SyntaxKind.XmlProcessingInstructionStartToken; } else { TextWindow.AdvanceChar(); info.Kind = SyntaxKind.LessThanToken; } } private void ScanXmlEntity(ref TokenInfo info) { info.StringValue = null; Debug.Assert(TextWindow.PeekChar() == '&'); TextWindow.AdvanceChar(); _builder.Clear(); XmlParseErrorCode? error = null; object[] errorArgs = null; char ch; if (IsXmlNameStartChar(ch = TextWindow.PeekChar())) { while (IsXmlNameChar(ch = TextWindow.PeekChar())) { // Important bit of information here: none of \0, \r, \n, and crucially for // delimited comments, * are considered Xml name characters. Also, since // entities appear in xml text and attribute text, it's relevant here that // none of <, /, >, ', ", =, are Xml name characters. Note that - and ] are // irrelevant--entities do not appear in comments or cdata. TextWindow.AdvanceChar(); _builder.Append(ch); } switch (_builder.ToString()) { case "lt": info.StringValue = "<"; break; case "gt": info.StringValue = ">"; break; case "amp": info.StringValue = "&"; break; case "apos": info.StringValue = "'"; break; case "quot": info.StringValue = "\""; break; default: error = XmlParseErrorCode.XML_RefUndefinedEntity_1; errorArgs = new[] { _builder.ToString() }; break; } } else if (ch == '#') { TextWindow.AdvanceChar(); bool isHex = TextWindow.PeekChar() == 'x'; uint charValue = 0; if (isHex) { TextWindow.AdvanceChar(); // x while (SyntaxFacts.IsHexDigit(ch = TextWindow.PeekChar())) { TextWindow.AdvanceChar(); // disallow overflow if (charValue <= 0x7FFFFFF) { charValue = (charValue << 4) + (uint)SyntaxFacts.HexValue(ch); } } } else { while (SyntaxFacts.IsDecDigit(ch = TextWindow.PeekChar())) { TextWindow.AdvanceChar(); // disallow overflow if (charValue <= 0x7FFFFFF) { charValue = (charValue << 3) + (charValue << 1) + (uint)SyntaxFacts.DecValue(ch); } } } if (TextWindow.PeekChar() != ';') { error = XmlParseErrorCode.XML_InvalidCharEntity; } if (MatchesProductionForXmlChar(charValue)) { char lowSurrogate; char highSurrogate = SlidingTextWindow.GetCharsFromUtf32(charValue, out lowSurrogate); _builder.Append(highSurrogate); if (lowSurrogate != SlidingTextWindow.InvalidCharacter) { _builder.Append(lowSurrogate); } info.StringValue = _builder.ToString(); } else { if (error == null) { error = XmlParseErrorCode.XML_InvalidUnicodeChar; } } } else { if (SyntaxFacts.IsWhitespace(ch) || SyntaxFacts.IsNewLine(ch)) { if (error == null) { error = XmlParseErrorCode.XML_InvalidWhitespace; } } else { if (error == null) { error = XmlParseErrorCode.XML_InvalidToken; errorArgs = new[] { ch.ToString() }; } } } ch = TextWindow.PeekChar(); if (ch == ';') { TextWindow.AdvanceChar(); } else { if (error == null) { error = XmlParseErrorCode.XML_InvalidToken; errorArgs = new[] { ch.ToString() }; } } // If we don't have a value computed from above, then we don't recognize the entity, in which // case we will simply use the text. info.Text = TextWindow.GetText(true); if (info.StringValue == null) { info.StringValue = info.Text; } if (error != null) { this.AddError(error.Value, errorArgs ?? Array.Empty<object>()); } } private static bool MatchesProductionForXmlChar(uint charValue) { // Char ::= #x9 | #xA | #xD | [#x20-#xD7FF] | [#xE000-#xFFFD] | [#x10000-#x10FFFF] /* any Unicode character, excluding the surrogate blocks, FFFE, and FFFF. */ return charValue == 0x9 || charValue == 0xA || charValue == 0xD || (charValue >= 0x20 && charValue <= 0xD7FF) || (charValue >= 0xE000 && charValue <= 0xFFFD) || (charValue >= 0x10000 && charValue <= 0x10FFFF); } private void ScanXmlText(ref TokenInfo info) { // Collect "]]>" strings into their own XmlText. if (TextWindow.PeekChar() == ']' && TextWindow.PeekChar(1) == ']' && TextWindow.PeekChar(2) == '>') { TextWindow.AdvanceChar(3); info.StringValue = info.Text = TextWindow.GetText(false); this.AddError(XmlParseErrorCode.XML_CDataEndTagNotAllowed); return; } while (true) { var ch = TextWindow.PeekChar(); switch (ch) { case SlidingTextWindow.InvalidCharacter: if (!TextWindow.IsReallyAtEnd()) { goto default; } info.StringValue = info.Text = TextWindow.GetText(false); return; case '&': case '<': case '\r': case '\n': info.StringValue = info.Text = TextWindow.GetText(false); return; case '*': if (this.StyleIs(XmlDocCommentStyle.Delimited) && TextWindow.PeekChar(1) == '/') { // we're at the end of the comment, but don't lex it yet. info.StringValue = info.Text = TextWindow.GetText(false); return; } goto default; case ']': if (TextWindow.PeekChar(1) == ']' && TextWindow.PeekChar(2) == '>') { info.StringValue = info.Text = TextWindow.GetText(false); return; } goto default; default: if (SyntaxFacts.IsNewLine(ch)) { goto case '\n'; } TextWindow.AdvanceChar(); break; } } } /// <summary> /// Lexer entry point for LexMode.XmlElementTag /// </summary> private SyntaxToken LexXmlElementTagToken() { TokenInfo tagInfo = default(TokenInfo); SyntaxListBuilder leading = null; this.LexXmlDocCommentLeadingTriviaWithWhitespace(ref leading); this.Start(); this.ScanXmlElementTagToken(ref tagInfo); var errors = this.GetErrors(GetFullWidth(leading)); // PERF: De-dupe common XML element tags if (errors == null && tagInfo.ContextualKind == SyntaxKind.None && tagInfo.Kind == SyntaxKind.IdentifierToken) { SyntaxToken token = DocumentationCommentXmlTokens.LookupToken(tagInfo.Text, leading); if (token != null) { return token; } } return Create(ref tagInfo, leading, null, errors); } private bool ScanXmlElementTagToken(ref TokenInfo info) { char ch; Debug.Assert(!this.LocationIs(XmlDocCommentLocation.Start)); Debug.Assert(!this.LocationIs(XmlDocCommentLocation.Exterior)); if (this.LocationIs(XmlDocCommentLocation.End)) { info.Kind = SyntaxKind.EndOfDocumentationCommentToken; return true; } switch (ch = TextWindow.PeekChar()) { case '<': this.ScanXmlTagStart(ref info); break; case '>': TextWindow.AdvanceChar(); info.Kind = SyntaxKind.GreaterThanToken; break; case '/': if (TextWindow.PeekChar(1) == '>') { TextWindow.AdvanceChar(2); info.Kind = SyntaxKind.SlashGreaterThanToken; break; } goto default; case '"': TextWindow.AdvanceChar(); info.Kind = SyntaxKind.DoubleQuoteToken; break; case '\'': TextWindow.AdvanceChar(); info.Kind = SyntaxKind.SingleQuoteToken; break; case '=': TextWindow.AdvanceChar(); info.Kind = SyntaxKind.EqualsToken; break; case ':': TextWindow.AdvanceChar(); info.Kind = SyntaxKind.ColonToken; break; case '\r': case '\n': // Assert? break; case SlidingTextWindow.InvalidCharacter: if (!TextWindow.IsReallyAtEnd()) { goto default; } info.Kind = SyntaxKind.EndOfDocumentationCommentToken; break; case '*': if (this.StyleIs(XmlDocCommentStyle.Delimited) && TextWindow.PeekChar(1) == '/') { // Assert? We should have gotten this in the leading trivia. Debug.Assert(false, "Should have picked up leading indentationTrivia, but didn't."); break; } goto default; default: if (IsXmlNameStartChar(ch)) { this.ScanXmlName(ref info); info.StringValue = info.Text; info.Kind = SyntaxKind.IdentifierToken; } else if (SyntaxFacts.IsWhitespace(ch) || SyntaxFacts.IsNewLine(ch)) { // whitespace! needed to do a better job with trivia Debug.Assert(false, "Should have picked up leading indentationTrivia, but didn't."); } else { TextWindow.AdvanceChar(); info.Kind = SyntaxKind.None; info.StringValue = info.Text = TextWindow.GetText(false); } break; } Debug.Assert(info.Kind != SyntaxKind.None || info.Text != null); return info.Kind != SyntaxKind.None; } private void ScanXmlName(ref TokenInfo info) { int start = TextWindow.Position; while (true) { char ch = TextWindow.PeekChar(); // Important bit of information here: none of \0, \r, \n, and crucially for // delimited comments, * are considered Xml name characters. if (ch != ':' && IsXmlNameChar(ch)) { // Although ':' is a name char, we don't include it in ScanXmlName // since it is its own token. This enables the parser to add structure // to colon-separated names. // TODO: Could put a big switch here for common cases // if this is a perf bottleneck. TextWindow.AdvanceChar(); } else { break; } } info.Text = TextWindow.GetText(start, TextWindow.Position - start, intern: true); } /// <summary> /// Determines whether this Unicode character can start a XMLName. /// </summary> /// <param name="ch">The Unicode character.</param> private static bool IsXmlNameStartChar(char ch) { // TODO: which is the right one? return XmlCharType.IsStartNCNameCharXml4e(ch); // return XmlCharType.IsStartNameSingleChar(ch); } /// <summary> /// Determines if this Unicode character can be part of an XML Name. /// </summary> /// <param name="ch">The Unicode character.</param> private static bool IsXmlNameChar(char ch) { // TODO: which is the right one? return XmlCharType.IsNCNameCharXml4e(ch); //return XmlCharType.IsNameSingleChar(ch); } // TODO: There is a lot of duplication between attribute text, CDATA text, and comment text. // It would be nice to factor them together. /// <summary> /// Lexer entry point for LexMode.XmlAttributeText /// </summary> private SyntaxToken LexXmlAttributeTextToken() { TokenInfo info = default(TokenInfo); SyntaxListBuilder leading = null; this.LexXmlDocCommentLeadingTrivia(ref leading); this.Start(); this.ScanXmlAttributeTextToken(ref info); var errors = this.GetErrors(GetFullWidth(leading)); return Create(ref info, leading, null, errors); } private bool ScanXmlAttributeTextToken(ref TokenInfo info) { Debug.Assert(!this.LocationIs(XmlDocCommentLocation.Start)); Debug.Assert(!this.LocationIs(XmlDocCommentLocation.Exterior)); if (this.LocationIs(XmlDocCommentLocation.End)) { info.Kind = SyntaxKind.EndOfDocumentationCommentToken; return true; } char ch; switch (ch = TextWindow.PeekChar()) { case '"': if (this.ModeIs(LexerMode.XmlAttributeTextDoubleQuote)) { TextWindow.AdvanceChar(); info.Kind = SyntaxKind.DoubleQuoteToken; break; } goto default; case '\'': if (this.ModeIs(LexerMode.XmlAttributeTextQuote)) { TextWindow.AdvanceChar(); info.Kind = SyntaxKind.SingleQuoteToken; break; } goto default; case '&': this.ScanXmlEntity(ref info); info.Kind = SyntaxKind.XmlEntityLiteralToken; break; case '<': TextWindow.AdvanceChar(); info.Kind = SyntaxKind.LessThanToken; break; case '\r': case '\n': ScanXmlTextLiteralNewLineToken(ref info); break; case SlidingTextWindow.InvalidCharacter: if (!TextWindow.IsReallyAtEnd()) { goto default; } info.Kind = SyntaxKind.EndOfDocumentationCommentToken; break; default: if (SyntaxFacts.IsNewLine(ch)) { goto case '\n'; } this.ScanXmlAttributeText(ref info); info.Kind = SyntaxKind.XmlTextLiteralToken; break; } Debug.Assert(info.Kind != SyntaxKind.None || info.Text != null); return info.Kind != SyntaxKind.None; } private void ScanXmlAttributeText(ref TokenInfo info) { while (true) { var ch = TextWindow.PeekChar(); switch (ch) { case '"': if (this.ModeIs(LexerMode.XmlAttributeTextDoubleQuote)) { info.StringValue = info.Text = TextWindow.GetText(false); return; } goto default; case '\'': if (this.ModeIs(LexerMode.XmlAttributeTextQuote)) { info.StringValue = info.Text = TextWindow.GetText(false); return; } goto default; case '&': case '<': case '\r': case '\n': info.StringValue = info.Text = TextWindow.GetText(false); return; case SlidingTextWindow.InvalidCharacter: if (!TextWindow.IsReallyAtEnd()) { goto default; } info.StringValue = info.Text = TextWindow.GetText(false); return; case '*': if (this.StyleIs(XmlDocCommentStyle.Delimited) && TextWindow.PeekChar(1) == '/') { // we're at the end of the comment, but don't lex it yet. info.StringValue = info.Text = TextWindow.GetText(false); return; } goto default; default: if (SyntaxFacts.IsNewLine(ch)) { goto case '\n'; } TextWindow.AdvanceChar(); break; } } } /// <summary> /// Lexer entry point for LexerMode.XmlCharacter. /// </summary> private SyntaxToken LexXmlCharacter() { TokenInfo info = default(TokenInfo); //TODO: Dev11 allows C# comments and newlines in cref trivia (DevDiv #530523). SyntaxListBuilder leading = null; this.LexXmlDocCommentLeadingTriviaWithWhitespace(ref leading); this.Start(); this.ScanXmlCharacter(ref info); var errors = this.GetErrors(GetFullWidth(leading)); return Create(ref info, leading, null, errors); } /// <summary> /// Scan a single XML character (or entity). Assumes that leading trivia has already /// been consumed. /// </summary> private bool ScanXmlCharacter(ref TokenInfo info) { Debug.Assert(!this.LocationIs(XmlDocCommentLocation.Start)); Debug.Assert(!this.LocationIs(XmlDocCommentLocation.Exterior)); if (this.LocationIs(XmlDocCommentLocation.End)) { info.Kind = SyntaxKind.EndOfDocumentationCommentToken; return true; } switch (TextWindow.PeekChar()) { case '&': this.ScanXmlEntity(ref info); info.Kind = SyntaxKind.XmlEntityLiteralToken; break; case SlidingTextWindow.InvalidCharacter: if (!TextWindow.IsReallyAtEnd()) { goto default; } info.Kind = SyntaxKind.EndOfFileToken; break; default: info.Kind = SyntaxKind.XmlTextLiteralToken; info.Text = info.StringValue = TextWindow.NextChar().ToString(); break; } return true; } /// <summary> /// Lexer entry point for LexerMode.XmlCrefQuote, LexerMode.XmlCrefDoubleQuote, /// LexerMode.XmlNameQuote, and LexerMode.XmlNameDoubleQuote. /// </summary> private SyntaxToken LexXmlCrefOrNameToken() { TokenInfo info = default(TokenInfo); //TODO: Dev11 allows C# comments and newlines in cref trivia (DevDiv #530523). SyntaxListBuilder leading = null; this.LexXmlDocCommentLeadingTriviaWithWhitespace(ref leading); this.Start(); this.ScanXmlCrefToken(ref info); var errors = this.GetErrors(GetFullWidth(leading)); return Create(ref info, leading, null, errors); } /// <summary> /// Scan a single cref attribute token. Assumes that leading trivia has already /// been consumed. /// </summary> /// <remarks> /// Within this method, characters that are not XML meta-characters can be seamlessly /// replaced with the corresponding XML entities. /// </remarks> private bool ScanXmlCrefToken(ref TokenInfo info) { Debug.Assert(!this.LocationIs(XmlDocCommentLocation.Start)); Debug.Assert(!this.LocationIs(XmlDocCommentLocation.Exterior)); if (this.LocationIs(XmlDocCommentLocation.End)) { info.Kind = SyntaxKind.EndOfDocumentationCommentToken; return true; } int beforeConsumed = TextWindow.Position; char consumedChar = TextWindow.NextChar(); char consumedSurrogate = SlidingTextWindow.InvalidCharacter; // This first switch is for special characters. If we see the corresponding // XML entities, we DO NOT want to take these actions. switch (consumedChar) { case '"': if (this.ModeIs(LexerMode.XmlCrefDoubleQuote) || this.ModeIs(LexerMode.XmlNameDoubleQuote)) { info.Kind = SyntaxKind.DoubleQuoteToken; return true; } break; case '\'': if (this.ModeIs(LexerMode.XmlCrefQuote) || this.ModeIs(LexerMode.XmlNameQuote)) { info.Kind = SyntaxKind.SingleQuoteToken; return true; } break; case '<': info.Text = TextWindow.GetText(intern: false); this.AddError(XmlParseErrorCode.XML_LessThanInAttributeValue, info.Text); //ErrorCode.WRN_XMLParseError return true; case SlidingTextWindow.InvalidCharacter: if (!TextWindow.IsReallyAtEnd()) { goto default; } info.Kind = SyntaxKind.EndOfDocumentationCommentToken; return true; case '\r': case '\n': TextWindow.Reset(beforeConsumed); ScanXmlTextLiteralNewLineToken(ref info); break; case '&': TextWindow.Reset(beforeConsumed); if (!TextWindow.TryScanXmlEntity(out consumedChar, out consumedSurrogate)) { TextWindow.Reset(beforeConsumed); this.ScanXmlEntity(ref info); info.Kind = SyntaxKind.XmlEntityLiteralToken; return true; } // TryScanXmlEntity advances even when it returns false. break; case '{': consumedChar = '<'; break; case '}': consumedChar = '>'; break; default: if (SyntaxFacts.IsNewLine(consumedChar)) { goto case '\n'; } break; } Debug.Assert(TextWindow.Position > beforeConsumed, "First character or entity has been consumed."); // NOTE: None of these cases will be matched if the surrogate is non-zero (UTF-16 rules) // so we don't need to check for that explicitly. // NOTE: there's a lot of overlap between this switch and the one in // ScanSyntaxToken, but we probably don't want to share code because // ScanSyntaxToken is really hot code and this switch does some extra // work. switch (consumedChar) { //// Single-Character Punctuation/Operators //// case '(': info.Kind = SyntaxKind.OpenParenToken; break; case ')': info.Kind = SyntaxKind.CloseParenToken; break; case '[': info.Kind = SyntaxKind.OpenBracketToken; break; case ']': info.Kind = SyntaxKind.CloseBracketToken; break; case ',': info.Kind = SyntaxKind.CommaToken; break; case '.': if (AdvanceIfMatches('.')) { if (TextWindow.PeekChar() == '.') { // See documentation in ScanSyntaxToken this.AddCrefError(ErrorCode.ERR_UnexpectedCharacter, "."); } info.Kind = SyntaxKind.DotDotToken; } else { info.Kind = SyntaxKind.DotToken; } break; case '?': info.Kind = SyntaxKind.QuestionToken; break; case '&': info.Kind = SyntaxKind.AmpersandToken; break; case '*': info.Kind = SyntaxKind.AsteriskToken; break; case '|': info.Kind = SyntaxKind.BarToken; break; case '^': info.Kind = SyntaxKind.CaretToken; break; case '%': info.Kind = SyntaxKind.PercentToken; break; case '/': info.Kind = SyntaxKind.SlashToken; break; case '~': info.Kind = SyntaxKind.TildeToken; break; // NOTE: Special case - convert curly brackets into angle brackets. case '{': info.Kind = SyntaxKind.LessThanToken; break; case '}': info.Kind = SyntaxKind.GreaterThanToken; break; //// Multi-Character Punctuation/Operators //// case ':': if (AdvanceIfMatches(':')) info.Kind = SyntaxKind.ColonColonToken; else info.Kind = SyntaxKind.ColonToken; break; case '=': if (AdvanceIfMatches('=')) info.Kind = SyntaxKind.EqualsEqualsToken; else info.Kind = SyntaxKind.EqualsToken; break; case '!': if (AdvanceIfMatches('=')) info.Kind = SyntaxKind.ExclamationEqualsToken; else info.Kind = SyntaxKind.ExclamationToken; break; case '>': if (AdvanceIfMatches('=')) info.Kind = SyntaxKind.GreaterThanEqualsToken; // GreaterThanGreaterThanToken is synthesized in the parser since it is ambiguous (with closing nested type parameter lists) // else if (AdvanceIfMatches('>')) info.Kind = SyntaxKind.GreaterThanGreaterThanToken; else info.Kind = SyntaxKind.GreaterThanToken; break; case '<': if (AdvanceIfMatches('=')) info.Kind = SyntaxKind.LessThanEqualsToken; else if (AdvanceIfMatches('<')) info.Kind = SyntaxKind.LessThanLessThanToken; else info.Kind = SyntaxKind.LessThanToken; break; case '+': if (AdvanceIfMatches('+')) info.Kind = SyntaxKind.PlusPlusToken; else info.Kind = SyntaxKind.PlusToken; break; case '-': if (AdvanceIfMatches('-')) info.Kind = SyntaxKind.MinusMinusToken; else info.Kind = SyntaxKind.MinusToken; break; } if (info.Kind != SyntaxKind.None) { Debug.Assert(info.Text == null, "Haven't tried to set it yet."); Debug.Assert(info.StringValue == null, "Haven't tried to set it yet."); string valueText = SyntaxFacts.GetText(info.Kind); string actualText = TextWindow.GetText(intern: false); if (!string.IsNullOrEmpty(valueText) && actualText != valueText) { info.RequiresTextForXmlEntity = true; info.Text = actualText; info.StringValue = valueText; } } else { // If we didn't match any of the above cases, then we either have an // identifier or an unexpected character. TextWindow.Reset(beforeConsumed); if (this.ScanIdentifier(ref info) && info.Text.Length > 0) { // ACASEY: All valid identifier characters should be valid in XML attribute values, // but I don't want to add an assert because XML character classification is expensive. // check to see if it is an actual keyword // NOTE: name attribute values don't respect keywords - everything is an identifier. SyntaxKind keywordKind; if (!InXmlNameAttributeValue && !info.IsVerbatim && !info.HasIdentifierEscapeSequence && _cache.TryGetKeywordKind(info.StringValue, out keywordKind)) { if (SyntaxFacts.IsContextualKeyword(keywordKind)) { info.Kind = SyntaxKind.IdentifierToken; info.ContextualKind = keywordKind; // Don't need to set any special flags to store the original text of an identifier. } else { info.Kind = keywordKind; info.RequiresTextForXmlEntity = info.Text != info.StringValue; } } else { info.ContextualKind = info.Kind = SyntaxKind.IdentifierToken; } } else { if (consumedChar == '@') { // Saw '@', but it wasn't followed by an identifier (otherwise ScanIdentifier would have succeeded). if (TextWindow.PeekChar() == '@') { TextWindow.NextChar(); info.Text = TextWindow.GetText(intern: true); info.StringValue = ""; // Can't be null for an identifier. } else { this.ScanXmlEntity(ref info); } info.Kind = SyntaxKind.IdentifierToken; this.AddError(ErrorCode.ERR_ExpectedVerbatimLiteral); } else if (TextWindow.PeekChar() == '&') { this.ScanXmlEntity(ref info); info.Kind = SyntaxKind.XmlEntityLiteralToken; this.AddCrefError(ErrorCode.ERR_UnexpectedCharacter, info.Text); } else { char bad = TextWindow.NextChar(); info.Text = TextWindow.GetText(intern: false); // If it's valid in XML, then it was unexpected in cref mode. // Otherwise, it's just bad XML. if (MatchesProductionForXmlChar((uint)bad)) { this.AddCrefError(ErrorCode.ERR_UnexpectedCharacter, info.Text); } else { this.AddError(XmlParseErrorCode.XML_InvalidUnicodeChar); } } } } Debug.Assert(info.Kind != SyntaxKind.None || info.Text != null); return info.Kind != SyntaxKind.None; } /// <summary> /// Given a character, advance the input if either the character or the /// corresponding XML entity appears next in the text window. /// </summary> /// <param name="ch"></param> /// <returns></returns> private bool AdvanceIfMatches(char ch) { char peekCh = TextWindow.PeekChar(); if ((peekCh == ch) || (peekCh == '{' && ch == '<') || (peekCh == '}' && ch == '>')) { TextWindow.AdvanceChar(); return true; } if (peekCh == '&') { int pos = TextWindow.Position; char nextChar; char nextSurrogate; if (TextWindow.TryScanXmlEntity(out nextChar, out nextSurrogate) && nextChar == ch && nextSurrogate == SlidingTextWindow.InvalidCharacter) { return true; } TextWindow.Reset(pos); } return false; } /// <summary> /// Convenience property for determining whether we are currently lexing the /// value of a cref or name attribute. /// </summary> private bool InXmlCrefOrNameAttributeValue { get { switch (_mode & LexerMode.MaskLexMode) { case LexerMode.XmlCrefQuote: case LexerMode.XmlCrefDoubleQuote: case LexerMode.XmlNameQuote: case LexerMode.XmlNameDoubleQuote: return true; default: return false; } } } /// <summary> /// Convenience property for determining whether we are currently lexing the /// value of a name attribute. /// </summary> private bool InXmlNameAttributeValue { get { switch (_mode & LexerMode.MaskLexMode) { case LexerMode.XmlNameQuote: case LexerMode.XmlNameDoubleQuote: return true; default: return false; } } } /// <summary> /// Diagnostics that occur within cref attributes need to be /// wrapped with ErrorCode.WRN_ErrorOverride. /// </summary> private void AddCrefError(ErrorCode code, params object[] args) { this.AddCrefError(MakeError(code, args)); } /// <summary> /// Diagnostics that occur within cref attributes need to be /// wrapped with ErrorCode.WRN_ErrorOverride. /// </summary> private void AddCrefError(DiagnosticInfo info) { if (info != null) { this.AddError(ErrorCode.WRN_ErrorOverride, info, info.Code); } } /// <summary> /// Lexer entry point for LexMode.XmlCDataSectionText /// </summary> private SyntaxToken LexXmlCDataSectionTextToken() { TokenInfo info = default(TokenInfo); SyntaxListBuilder leading = null; this.LexXmlDocCommentLeadingTrivia(ref leading); this.Start(); this.ScanXmlCDataSectionTextToken(ref info); var errors = this.GetErrors(GetFullWidth(leading)); return Create(ref info, leading, null, errors); } private bool ScanXmlCDataSectionTextToken(ref TokenInfo info) { char ch; Debug.Assert(!this.LocationIs(XmlDocCommentLocation.Start)); Debug.Assert(!this.LocationIs(XmlDocCommentLocation.Exterior)); if (this.LocationIs(XmlDocCommentLocation.End)) { info.Kind = SyntaxKind.EndOfDocumentationCommentToken; return true; } switch (ch = TextWindow.PeekChar()) { case ']': if (TextWindow.PeekChar(1) == ']' && TextWindow.PeekChar(2) == '>') { TextWindow.AdvanceChar(3); info.Kind = SyntaxKind.XmlCDataEndToken; break; } goto default; case '\r': case '\n': ScanXmlTextLiteralNewLineToken(ref info); break; case SlidingTextWindow.InvalidCharacter: if (!TextWindow.IsReallyAtEnd()) { goto default; } info.Kind = SyntaxKind.EndOfDocumentationCommentToken; break; default: if (SyntaxFacts.IsNewLine(ch)) { goto case '\n'; } this.ScanXmlCDataSectionText(ref info); info.Kind = SyntaxKind.XmlTextLiteralToken; break; } return true; } private void ScanXmlCDataSectionText(ref TokenInfo info) { while (true) { var ch = TextWindow.PeekChar(); switch (ch) { case ']': if (TextWindow.PeekChar(1) == ']' && TextWindow.PeekChar(2) == '>') { info.StringValue = info.Text = TextWindow.GetText(false); return; } goto default; case '\r': case '\n': info.StringValue = info.Text = TextWindow.GetText(false); return; case SlidingTextWindow.InvalidCharacter: if (!TextWindow.IsReallyAtEnd()) { goto default; } info.StringValue = info.Text = TextWindow.GetText(false); return; case '*': if (this.StyleIs(XmlDocCommentStyle.Delimited) && TextWindow.PeekChar(1) == '/') { // we're at the end of the comment, but don't lex it yet. info.StringValue = info.Text = TextWindow.GetText(false); return; } goto default; default: if (SyntaxFacts.IsNewLine(ch)) { goto case '\n'; } TextWindow.AdvanceChar(); break; } } } /// <summary> /// Lexer entry point for LexMode.XmlCommentText /// </summary> private SyntaxToken LexXmlCommentTextToken() { TokenInfo info = default(TokenInfo); SyntaxListBuilder leading = null; this.LexXmlDocCommentLeadingTrivia(ref leading); this.Start(); this.ScanXmlCommentTextToken(ref info); var errors = this.GetErrors(GetFullWidth(leading)); return Create(ref info, leading, null, errors); } private bool ScanXmlCommentTextToken(ref TokenInfo info) { char ch; Debug.Assert(!this.LocationIs(XmlDocCommentLocation.Start)); Debug.Assert(!this.LocationIs(XmlDocCommentLocation.Exterior)); if (this.LocationIs(XmlDocCommentLocation.End)) { info.Kind = SyntaxKind.EndOfDocumentationCommentToken; return true; } switch (ch = TextWindow.PeekChar()) { case '-': if (TextWindow.PeekChar(1) == '-') { if (TextWindow.PeekChar(2) == '>') { TextWindow.AdvanceChar(3); info.Kind = SyntaxKind.XmlCommentEndToken; break; } else { TextWindow.AdvanceChar(2); info.Kind = SyntaxKind.MinusMinusToken; break; } } goto default; case '\r': case '\n': ScanXmlTextLiteralNewLineToken(ref info); break; case SlidingTextWindow.InvalidCharacter: if (!TextWindow.IsReallyAtEnd()) { goto default; } info.Kind = SyntaxKind.EndOfDocumentationCommentToken; break; default: if (SyntaxFacts.IsNewLine(ch)) { goto case '\n'; } this.ScanXmlCommentText(ref info); info.Kind = SyntaxKind.XmlTextLiteralToken; break; } return true; } private void ScanXmlCommentText(ref TokenInfo info) { while (true) { var ch = TextWindow.PeekChar(); switch (ch) { case '-': if (TextWindow.PeekChar(1) == '-') { info.StringValue = info.Text = TextWindow.GetText(false); return; } goto default; case '\r': case '\n': info.StringValue = info.Text = TextWindow.GetText(false); return; case SlidingTextWindow.InvalidCharacter: if (!TextWindow.IsReallyAtEnd()) { goto default; } info.StringValue = info.Text = TextWindow.GetText(false); return; case '*': if (this.StyleIs(XmlDocCommentStyle.Delimited) && TextWindow.PeekChar(1) == '/') { // we're at the end of the comment, but don't lex it yet. info.StringValue = info.Text = TextWindow.GetText(false); return; } goto default; default: if (SyntaxFacts.IsNewLine(ch)) { goto case '\n'; } TextWindow.AdvanceChar(); break; } } } /// <summary> /// Lexer entry point for LexMode.XmlProcessingInstructionText /// </summary> private SyntaxToken LexXmlProcessingInstructionTextToken() { TokenInfo info = default(TokenInfo); SyntaxListBuilder leading = null; this.LexXmlDocCommentLeadingTrivia(ref leading); this.Start(); this.ScanXmlProcessingInstructionTextToken(ref info); var errors = this.GetErrors(GetFullWidth(leading)); return Create(ref info, leading, null, errors); } // CONSIDER: This could easily be merged with ScanXmlCDataSectionTextToken private bool ScanXmlProcessingInstructionTextToken(ref TokenInfo info) { char ch; Debug.Assert(!this.LocationIs(XmlDocCommentLocation.Start)); Debug.Assert(!this.LocationIs(XmlDocCommentLocation.Exterior)); if (this.LocationIs(XmlDocCommentLocation.End)) { info.Kind = SyntaxKind.EndOfDocumentationCommentToken; return true; } switch (ch = TextWindow.PeekChar()) { case '?': if (TextWindow.PeekChar(1) == '>') { TextWindow.AdvanceChar(2); info.Kind = SyntaxKind.XmlProcessingInstructionEndToken; break; } goto default; case '\r': case '\n': ScanXmlTextLiteralNewLineToken(ref info); break; case SlidingTextWindow.InvalidCharacter: if (!TextWindow.IsReallyAtEnd()) { goto default; } info.Kind = SyntaxKind.EndOfDocumentationCommentToken; break; default: if (SyntaxFacts.IsNewLine(ch)) { goto case '\n'; } this.ScanXmlProcessingInstructionText(ref info); info.Kind = SyntaxKind.XmlTextLiteralToken; break; } return true; } // CONSIDER: This could easily be merged with ScanXmlCDataSectionText private void ScanXmlProcessingInstructionText(ref TokenInfo info) { while (true) { var ch = TextWindow.PeekChar(); switch (ch) { case '?': if (TextWindow.PeekChar(1) == '>') { info.StringValue = info.Text = TextWindow.GetText(false); return; } goto default; case '\r': case '\n': info.StringValue = info.Text = TextWindow.GetText(false); return; case SlidingTextWindow.InvalidCharacter: if (!TextWindow.IsReallyAtEnd()) { goto default; } info.StringValue = info.Text = TextWindow.GetText(false); return; case '*': if (this.StyleIs(XmlDocCommentStyle.Delimited) && TextWindow.PeekChar(1) == '/') { // we're at the end of the comment, but don't lex it yet. info.StringValue = info.Text = TextWindow.GetText(false); return; } goto default; default: if (SyntaxFacts.IsNewLine(ch)) { goto case '\n'; } TextWindow.AdvanceChar(); break; } } } /// <summary> /// Collects XML doc comment exterior trivia, and therefore is a no op unless we are in the Start or Exterior of an XML doc comment. /// </summary> /// <param name="trivia">List in which to collect the trivia</param> private void LexXmlDocCommentLeadingTrivia(ref SyntaxListBuilder trivia) { var start = TextWindow.Position; this.Start(); if (this.LocationIs(XmlDocCommentLocation.Start) && this.StyleIs(XmlDocCommentStyle.Delimited)) { // Read the /** that begins an XML doc comment. Since these are recognized only // when the trailing character is not a '*', we wind up in the interior of the // doc comment at the end. if (TextWindow.PeekChar() == '/' && TextWindow.PeekChar(1) == '*' && TextWindow.PeekChar(2) == '*' && TextWindow.PeekChar(3) != '*') { TextWindow.AdvanceChar(3); var text = TextWindow.GetText(true); this.AddTrivia(SyntaxFactory.DocumentationCommentExteriorTrivia(text), ref trivia); this.MutateLocation(XmlDocCommentLocation.Interior); return; } } else if (this.LocationIs(XmlDocCommentLocation.Start) || this.LocationIs(XmlDocCommentLocation.Exterior)) { // We're in the exterior of an XML doc comment and need to eat the beginnings of // lines, for single line and delimited comments. We chew up white space until // a non-whitespace character, and then make the right decision depending on // what kind of comment we're in. while (true) { char ch = TextWindow.PeekChar(); switch (ch) { case ' ': case '\t': case '\v': case '\f': TextWindow.AdvanceChar(); break; case '/': if (this.StyleIs(XmlDocCommentStyle.SingleLine) && TextWindow.PeekChar(1) == '/' && TextWindow.PeekChar(2) == '/' && TextWindow.PeekChar(3) != '/') { TextWindow.AdvanceChar(3); var text = TextWindow.GetText(true); this.AddTrivia(SyntaxFactory.DocumentationCommentExteriorTrivia(text), ref trivia); this.MutateLocation(XmlDocCommentLocation.Interior); return; } goto default; case '*': if (this.StyleIs(XmlDocCommentStyle.Delimited)) { while (TextWindow.PeekChar() == '*' && TextWindow.PeekChar(1) != '/') { TextWindow.AdvanceChar(); } var text = TextWindow.GetText(true); if (!String.IsNullOrEmpty(text)) { this.AddTrivia(SyntaxFactory.DocumentationCommentExteriorTrivia(text), ref trivia); } // This setup ensures that on the final line of a comment, if we have // the string " */", the "*/" part is separated from the whitespace // and therefore recognizable as the end of the comment. if (TextWindow.PeekChar() == '*' && TextWindow.PeekChar(1) == '/') { TextWindow.AdvanceChar(2); this.AddTrivia(SyntaxFactory.DocumentationCommentExteriorTrivia("*/"), ref trivia); this.MutateLocation(XmlDocCommentLocation.End); } else { this.MutateLocation(XmlDocCommentLocation.Interior); } return; } goto default; default: if (SyntaxFacts.IsWhitespace(ch)) { goto case ' '; } // so here we have something else. if this is a single-line xml // doc comment, that means we're on a line that's no longer a doc // comment, so we need to rewind. if we're in a delimited doc comment, // then that means we hit pay dirt and we're back into xml text. if (this.StyleIs(XmlDocCommentStyle.SingleLine)) { TextWindow.Reset(start); this.MutateLocation(XmlDocCommentLocation.End); } else // XmlDocCommentStyle.Delimited { Debug.Assert(this.StyleIs(XmlDocCommentStyle.Delimited)); var text = TextWindow.GetText(true); if (!String.IsNullOrEmpty(text)) this.AddTrivia(SyntaxFactory.DocumentationCommentExteriorTrivia(text), ref trivia); this.MutateLocation(XmlDocCommentLocation.Interior); } return; } } } else if (!this.LocationIs(XmlDocCommentLocation.End) && this.StyleIs(XmlDocCommentStyle.Delimited)) { if (TextWindow.PeekChar() == '*' && TextWindow.PeekChar(1) == '/') { TextWindow.AdvanceChar(2); var text = TextWindow.GetText(true); this.AddTrivia(SyntaxFactory.DocumentationCommentExteriorTrivia(text), ref trivia); this.MutateLocation(XmlDocCommentLocation.End); } } } private void LexXmlDocCommentLeadingTriviaWithWhitespace(ref SyntaxListBuilder trivia) { while (true) { this.LexXmlDocCommentLeadingTrivia(ref trivia); char ch = TextWindow.PeekChar(); if (this.LocationIs(XmlDocCommentLocation.Interior) && (SyntaxFacts.IsWhitespace(ch) || SyntaxFacts.IsNewLine(ch))) { this.LexXmlWhitespaceAndNewLineTrivia(ref trivia); } else { break; } } } /// <summary> /// Collects whitespace and new line trivia for XML doc comments. Does not see XML doc comment exterior trivia, and is a no op unless we are in the interior. /// </summary> /// <param name="trivia">List in which to collect the trivia</param> private void LexXmlWhitespaceAndNewLineTrivia(ref SyntaxListBuilder trivia) { this.Start(); if (this.LocationIs(XmlDocCommentLocation.Interior)) { char ch = TextWindow.PeekChar(); switch (ch) { case ' ': case '\t': // Horizontal tab case '\v': // Vertical Tab case '\f': // Form-feed this.AddTrivia(this.ScanWhitespace(), ref trivia); break; case '\r': case '\n': this.AddTrivia(this.ScanEndOfLine(), ref trivia); this.MutateLocation(XmlDocCommentLocation.Exterior); return; case '*': if (this.StyleIs(XmlDocCommentStyle.Delimited) && TextWindow.PeekChar(1) == '/') { // we're at the end of the comment, but don't add as trivia here. return; } goto default; default: if (SyntaxFacts.IsWhitespace(ch)) { goto case ' '; } if (SyntaxFacts.IsNewLine(ch)) { goto case '\n'; } return; } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Globalization; using System.Linq; using System.Text; using Microsoft.CodeAnalysis.Syntax.InternalSyntax; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax { [Flags] internal enum LexerMode { Syntax = 0x0001, DebuggerSyntax = 0x0002, Directive = 0x0004, XmlDocComment = 0x0008, XmlElementTag = 0x0010, XmlAttributeTextQuote = 0x0020, XmlAttributeTextDoubleQuote = 0x0040, XmlCrefQuote = 0x0080, XmlCrefDoubleQuote = 0x0100, XmlNameQuote = 0x0200, XmlNameDoubleQuote = 0x0400, XmlCDataSectionText = 0x0800, XmlCommentText = 0x1000, XmlProcessingInstructionText = 0x2000, XmlCharacter = 0x4000, MaskLexMode = 0xFFFF, // The following are lexer driven, which is to say the lexer can push a change back to the // blender. There is in general no need to use a whole bit per enum value, but the debugging // experience is bad if you don't do that. XmlDocCommentLocationStart = 0x00000, XmlDocCommentLocationInterior = 0x10000, XmlDocCommentLocationExterior = 0x20000, XmlDocCommentLocationEnd = 0x40000, MaskXmlDocCommentLocation = 0xF0000, XmlDocCommentStyleSingleLine = 0x000000, XmlDocCommentStyleDelimited = 0x100000, MaskXmlDocCommentStyle = 0x300000, None = 0 } // Needs to match LexMode.XmlDocCommentLocation* internal enum XmlDocCommentLocation { Start = 0, Interior = 1, Exterior = 2, End = 4 } // Needs to match LexMode.XmlDocCommentStyle* internal enum XmlDocCommentStyle { SingleLine = 0, Delimited = 1 } internal partial class Lexer : AbstractLexer { private const int TriviaListInitialCapacity = 8; private readonly CSharpParseOptions _options; private LexerMode _mode; private readonly StringBuilder _builder; private char[] _identBuffer; private int _identLen; private DirectiveStack _directives; private readonly LexerCache _cache; private readonly bool _allowPreprocessorDirectives; private readonly bool _interpolationFollowedByColon; private DocumentationCommentParser _xmlParser; private int _badTokenCount; // cumulative count of bad tokens produced internal struct TokenInfo { // scanned values internal SyntaxKind Kind; internal SyntaxKind ContextualKind; internal string Text; internal SpecialType ValueKind; internal bool RequiresTextForXmlEntity; internal bool HasIdentifierEscapeSequence; internal string StringValue; internal char CharValue; internal int IntValue; internal uint UintValue; internal long LongValue; internal ulong UlongValue; internal float FloatValue; internal double DoubleValue; internal decimal DecimalValue; internal bool IsVerbatim; } public Lexer(SourceText text, CSharpParseOptions options, bool allowPreprocessorDirectives = true, bool interpolationFollowedByColon = false) : base(text) { Debug.Assert(options != null); _options = options; _builder = new StringBuilder(); _identBuffer = new char[32]; _cache = new LexerCache(); _createQuickTokenFunction = this.CreateQuickToken; _allowPreprocessorDirectives = allowPreprocessorDirectives; _interpolationFollowedByColon = interpolationFollowedByColon; } public override void Dispose() { _cache.Free(); if (_xmlParser != null) { _xmlParser.Dispose(); } base.Dispose(); } public bool SuppressDocumentationCommentParse { get { return _options.DocumentationMode < DocumentationMode.Parse; } } public CSharpParseOptions Options { get { return _options; } } public DirectiveStack Directives { get { return _directives; } } /// <summary> /// The lexer is for the contents of an interpolation that is followed by a colon that signals the start of the format string. /// </summary> public bool InterpolationFollowedByColon { get { return _interpolationFollowedByColon; } } public void Reset(int position, DirectiveStack directives) { this.TextWindow.Reset(position); _directives = directives; } private static LexerMode ModeOf(LexerMode mode) { return mode & LexerMode.MaskLexMode; } private bool ModeIs(LexerMode mode) { return ModeOf(_mode) == mode; } private static XmlDocCommentLocation LocationOf(LexerMode mode) { return (XmlDocCommentLocation)((int)(mode & LexerMode.MaskXmlDocCommentLocation) >> 16); } private bool LocationIs(XmlDocCommentLocation location) { return LocationOf(_mode) == location; } private void MutateLocation(XmlDocCommentLocation location) { _mode &= ~LexerMode.MaskXmlDocCommentLocation; _mode |= (LexerMode)((int)location << 16); } private static XmlDocCommentStyle StyleOf(LexerMode mode) { return (XmlDocCommentStyle)((int)(mode & LexerMode.MaskXmlDocCommentStyle) >> 20); } private bool StyleIs(XmlDocCommentStyle style) { return StyleOf(_mode) == style; } private bool InDocumentationComment { get { switch (ModeOf(_mode)) { case LexerMode.XmlDocComment: case LexerMode.XmlElementTag: case LexerMode.XmlAttributeTextQuote: case LexerMode.XmlAttributeTextDoubleQuote: case LexerMode.XmlCrefQuote: case LexerMode.XmlCrefDoubleQuote: case LexerMode.XmlNameQuote: case LexerMode.XmlNameDoubleQuote: case LexerMode.XmlCDataSectionText: case LexerMode.XmlCommentText: case LexerMode.XmlProcessingInstructionText: case LexerMode.XmlCharacter: return true; default: return false; } } } public SyntaxToken Lex(ref LexerMode mode) { var result = Lex(mode); mode = _mode; return result; } #if DEBUG internal static int TokensLexed; #endif public SyntaxToken Lex(LexerMode mode) { #if DEBUG TokensLexed++; #endif _mode = mode; switch (_mode) { case LexerMode.Syntax: case LexerMode.DebuggerSyntax: return this.QuickScanSyntaxToken() ?? this.LexSyntaxToken(); case LexerMode.Directive: return this.LexDirectiveToken(); } switch (ModeOf(_mode)) { case LexerMode.XmlDocComment: return this.LexXmlToken(); case LexerMode.XmlElementTag: return this.LexXmlElementTagToken(); case LexerMode.XmlAttributeTextQuote: case LexerMode.XmlAttributeTextDoubleQuote: return this.LexXmlAttributeTextToken(); case LexerMode.XmlCDataSectionText: return this.LexXmlCDataSectionTextToken(); case LexerMode.XmlCommentText: return this.LexXmlCommentTextToken(); case LexerMode.XmlProcessingInstructionText: return this.LexXmlProcessingInstructionTextToken(); case LexerMode.XmlCrefQuote: case LexerMode.XmlCrefDoubleQuote: return this.LexXmlCrefOrNameToken(); case LexerMode.XmlNameQuote: case LexerMode.XmlNameDoubleQuote: // Same lexing as a cref attribute, just treat the identifiers a little differently. return this.LexXmlCrefOrNameToken(); case LexerMode.XmlCharacter: return this.LexXmlCharacter(); default: throw ExceptionUtilities.UnexpectedValue(ModeOf(_mode)); } } private SyntaxListBuilder _leadingTriviaCache = new SyntaxListBuilder(10); private SyntaxListBuilder _trailingTriviaCache = new SyntaxListBuilder(10); private static int GetFullWidth(SyntaxListBuilder builder) { int width = 0; if (builder != null) { for (int i = 0; i < builder.Count; i++) { width += builder[i].FullWidth; } } return width; } private SyntaxToken LexSyntaxToken() { _leadingTriviaCache.Clear(); this.LexSyntaxTrivia(afterFirstToken: TextWindow.Position > 0, isTrailing: false, triviaList: ref _leadingTriviaCache); var leading = _leadingTriviaCache; var tokenInfo = default(TokenInfo); this.Start(); this.ScanSyntaxToken(ref tokenInfo); var errors = this.GetErrors(GetFullWidth(leading)); _trailingTriviaCache.Clear(); this.LexSyntaxTrivia(afterFirstToken: true, isTrailing: true, triviaList: ref _trailingTriviaCache); var trailing = _trailingTriviaCache; return Create(ref tokenInfo, leading, trailing, errors); } internal SyntaxTriviaList LexSyntaxLeadingTrivia() { _leadingTriviaCache.Clear(); this.LexSyntaxTrivia(afterFirstToken: TextWindow.Position > 0, isTrailing: false, triviaList: ref _leadingTriviaCache); return new SyntaxTriviaList(default(Microsoft.CodeAnalysis.SyntaxToken), _leadingTriviaCache.ToListNode(), position: 0, index: 0); } internal SyntaxTriviaList LexSyntaxTrailingTrivia() { _trailingTriviaCache.Clear(); this.LexSyntaxTrivia(afterFirstToken: true, isTrailing: true, triviaList: ref _trailingTriviaCache); return new SyntaxTriviaList(default(Microsoft.CodeAnalysis.SyntaxToken), _trailingTriviaCache.ToListNode(), position: 0, index: 0); } private SyntaxToken Create(ref TokenInfo info, SyntaxListBuilder leading, SyntaxListBuilder trailing, SyntaxDiagnosticInfo[] errors) { Debug.Assert(info.Kind != SyntaxKind.IdentifierToken || info.StringValue != null); var leadingNode = leading?.ToListNode(); var trailingNode = trailing?.ToListNode(); SyntaxToken token; if (info.RequiresTextForXmlEntity) { token = SyntaxFactory.Token(leadingNode, info.Kind, info.Text, info.StringValue, trailingNode); } else { switch (info.Kind) { case SyntaxKind.IdentifierToken: token = SyntaxFactory.Identifier(info.ContextualKind, leadingNode, info.Text, info.StringValue, trailingNode); break; case SyntaxKind.NumericLiteralToken: switch (info.ValueKind) { case SpecialType.System_Int32: token = SyntaxFactory.Literal(leadingNode, info.Text, info.IntValue, trailingNode); break; case SpecialType.System_UInt32: token = SyntaxFactory.Literal(leadingNode, info.Text, info.UintValue, trailingNode); break; case SpecialType.System_Int64: token = SyntaxFactory.Literal(leadingNode, info.Text, info.LongValue, trailingNode); break; case SpecialType.System_UInt64: token = SyntaxFactory.Literal(leadingNode, info.Text, info.UlongValue, trailingNode); break; case SpecialType.System_Single: token = SyntaxFactory.Literal(leadingNode, info.Text, info.FloatValue, trailingNode); break; case SpecialType.System_Double: token = SyntaxFactory.Literal(leadingNode, info.Text, info.DoubleValue, trailingNode); break; case SpecialType.System_Decimal: token = SyntaxFactory.Literal(leadingNode, info.Text, info.DecimalValue, trailingNode); break; default: throw ExceptionUtilities.UnexpectedValue(info.ValueKind); } break; case SyntaxKind.InterpolatedStringToken: // we do not record a separate "value" for an interpolated string token, as it must be rescanned during parsing. token = SyntaxFactory.Literal(leadingNode, info.Text, info.Kind, info.Text, trailingNode); break; case SyntaxKind.StringLiteralToken: token = SyntaxFactory.Literal(leadingNode, info.Text, info.Kind, info.StringValue, trailingNode); break; case SyntaxKind.CharacterLiteralToken: token = SyntaxFactory.Literal(leadingNode, info.Text, info.CharValue, trailingNode); break; case SyntaxKind.XmlTextLiteralNewLineToken: token = SyntaxFactory.XmlTextNewLine(leadingNode, info.Text, info.StringValue, trailingNode); break; case SyntaxKind.XmlTextLiteralToken: token = SyntaxFactory.XmlTextLiteral(leadingNode, info.Text, info.StringValue, trailingNode); break; case SyntaxKind.XmlEntityLiteralToken: token = SyntaxFactory.XmlEntity(leadingNode, info.Text, info.StringValue, trailingNode); break; case SyntaxKind.EndOfDocumentationCommentToken: case SyntaxKind.EndOfFileToken: token = SyntaxFactory.Token(leadingNode, info.Kind, trailingNode); break; case SyntaxKind.None: token = SyntaxFactory.BadToken(leadingNode, info.Text, trailingNode); break; default: Debug.Assert(SyntaxFacts.IsPunctuationOrKeyword(info.Kind)); token = SyntaxFactory.Token(leadingNode, info.Kind, trailingNode); break; } } if (errors != null && (_options.DocumentationMode >= DocumentationMode.Diagnose || !InDocumentationComment)) { token = token.WithDiagnosticsGreen(errors); } return token; } private void ScanSyntaxToken(ref TokenInfo info) { // Initialize for new token scan info.Kind = SyntaxKind.None; info.ContextualKind = SyntaxKind.None; info.Text = null; char character; char surrogateCharacter = SlidingTextWindow.InvalidCharacter; bool isEscaped = false; int startingPosition = TextWindow.Position; // Start scanning the token character = TextWindow.PeekChar(); switch (character) { case '\"': case '\'': this.ScanStringLiteral(ref info, inDirective: false); break; case '/': TextWindow.AdvanceChar(); if (TextWindow.PeekChar() == '=') { TextWindow.AdvanceChar(); info.Kind = SyntaxKind.SlashEqualsToken; } else { info.Kind = SyntaxKind.SlashToken; } break; case '.': if (!this.ScanNumericLiteral(ref info)) { TextWindow.AdvanceChar(); if (TextWindow.PeekChar() == '.') { TextWindow.AdvanceChar(); if (TextWindow.PeekChar() == '.') { // Triple-dot: explicitly reject this, to allow triple-dot // to be added to the language without a breaking change. // (without this, 0...2 would parse as (0)..(.2), i.e. a range from 0 to 0.2) this.AddError(ErrorCode.ERR_TripleDotNotAllowed); } info.Kind = SyntaxKind.DotDotToken; } else { info.Kind = SyntaxKind.DotToken; } } break; case ',': TextWindow.AdvanceChar(); info.Kind = SyntaxKind.CommaToken; break; case ':': TextWindow.AdvanceChar(); if (TextWindow.PeekChar() == ':') { TextWindow.AdvanceChar(); info.Kind = SyntaxKind.ColonColonToken; } else { info.Kind = SyntaxKind.ColonToken; } break; case ';': TextWindow.AdvanceChar(); info.Kind = SyntaxKind.SemicolonToken; break; case '~': TextWindow.AdvanceChar(); info.Kind = SyntaxKind.TildeToken; break; case '!': TextWindow.AdvanceChar(); if (TextWindow.PeekChar() == '=') { TextWindow.AdvanceChar(); info.Kind = SyntaxKind.ExclamationEqualsToken; } else { info.Kind = SyntaxKind.ExclamationToken; } break; case '=': TextWindow.AdvanceChar(); if ((character = TextWindow.PeekChar()) == '=') { TextWindow.AdvanceChar(); info.Kind = SyntaxKind.EqualsEqualsToken; } else if (character == '>') { TextWindow.AdvanceChar(); info.Kind = SyntaxKind.EqualsGreaterThanToken; } else { info.Kind = SyntaxKind.EqualsToken; } break; case '*': TextWindow.AdvanceChar(); if (TextWindow.PeekChar() == '=') { TextWindow.AdvanceChar(); info.Kind = SyntaxKind.AsteriskEqualsToken; } else { info.Kind = SyntaxKind.AsteriskToken; } break; case '(': TextWindow.AdvanceChar(); info.Kind = SyntaxKind.OpenParenToken; break; case ')': TextWindow.AdvanceChar(); info.Kind = SyntaxKind.CloseParenToken; break; case '{': TextWindow.AdvanceChar(); info.Kind = SyntaxKind.OpenBraceToken; break; case '}': TextWindow.AdvanceChar(); info.Kind = SyntaxKind.CloseBraceToken; break; case '[': TextWindow.AdvanceChar(); info.Kind = SyntaxKind.OpenBracketToken; break; case ']': TextWindow.AdvanceChar(); info.Kind = SyntaxKind.CloseBracketToken; break; case '?': TextWindow.AdvanceChar(); if (TextWindow.PeekChar() == '?') { TextWindow.AdvanceChar(); if (TextWindow.PeekChar() == '=') { TextWindow.AdvanceChar(); info.Kind = SyntaxKind.QuestionQuestionEqualsToken; } else { info.Kind = SyntaxKind.QuestionQuestionToken; } } else { info.Kind = SyntaxKind.QuestionToken; } break; case '+': TextWindow.AdvanceChar(); if ((character = TextWindow.PeekChar()) == '=') { TextWindow.AdvanceChar(); info.Kind = SyntaxKind.PlusEqualsToken; } else if (character == '+') { TextWindow.AdvanceChar(); info.Kind = SyntaxKind.PlusPlusToken; } else { info.Kind = SyntaxKind.PlusToken; } break; case '-': TextWindow.AdvanceChar(); if ((character = TextWindow.PeekChar()) == '=') { TextWindow.AdvanceChar(); info.Kind = SyntaxKind.MinusEqualsToken; } else if (character == '-') { TextWindow.AdvanceChar(); info.Kind = SyntaxKind.MinusMinusToken; } else if (character == '>') { TextWindow.AdvanceChar(); info.Kind = SyntaxKind.MinusGreaterThanToken; } else { info.Kind = SyntaxKind.MinusToken; } break; case '%': TextWindow.AdvanceChar(); if (TextWindow.PeekChar() == '=') { TextWindow.AdvanceChar(); info.Kind = SyntaxKind.PercentEqualsToken; } else { info.Kind = SyntaxKind.PercentToken; } break; case '&': TextWindow.AdvanceChar(); if ((character = TextWindow.PeekChar()) == '=') { TextWindow.AdvanceChar(); info.Kind = SyntaxKind.AmpersandEqualsToken; } else if (TextWindow.PeekChar() == '&') { TextWindow.AdvanceChar(); info.Kind = SyntaxKind.AmpersandAmpersandToken; } else { info.Kind = SyntaxKind.AmpersandToken; } break; case '^': TextWindow.AdvanceChar(); if (TextWindow.PeekChar() == '=') { TextWindow.AdvanceChar(); info.Kind = SyntaxKind.CaretEqualsToken; } else { info.Kind = SyntaxKind.CaretToken; } break; case '|': TextWindow.AdvanceChar(); if (TextWindow.PeekChar() == '=') { TextWindow.AdvanceChar(); info.Kind = SyntaxKind.BarEqualsToken; } else if (TextWindow.PeekChar() == '|') { TextWindow.AdvanceChar(); info.Kind = SyntaxKind.BarBarToken; } else { info.Kind = SyntaxKind.BarToken; } break; case '<': TextWindow.AdvanceChar(); if (TextWindow.PeekChar() == '=') { TextWindow.AdvanceChar(); info.Kind = SyntaxKind.LessThanEqualsToken; } else if (TextWindow.PeekChar() == '<') { TextWindow.AdvanceChar(); if (TextWindow.PeekChar() == '=') { TextWindow.AdvanceChar(); info.Kind = SyntaxKind.LessThanLessThanEqualsToken; } else { info.Kind = SyntaxKind.LessThanLessThanToken; } } else { info.Kind = SyntaxKind.LessThanToken; } break; case '>': TextWindow.AdvanceChar(); if (TextWindow.PeekChar() == '=') { TextWindow.AdvanceChar(); info.Kind = SyntaxKind.GreaterThanEqualsToken; } else { info.Kind = SyntaxKind.GreaterThanToken; } break; case '@': if (TextWindow.PeekChar(1) == '"') { var errorCode = this.ScanVerbatimStringLiteral(ref info, allowNewlines: true); if (errorCode is ErrorCode code) this.AddError(code); } else if (TextWindow.PeekChar(1) == '$' && TextWindow.PeekChar(2) == '"') { this.ScanInterpolatedStringLiteral(isVerbatim: true, ref info); CheckFeatureAvailability(MessageID.IDS_FeatureAltInterpolatedVerbatimStrings); break; } else if (!this.ScanIdentifierOrKeyword(ref info)) { TextWindow.AdvanceChar(); info.Text = TextWindow.GetText(intern: true); this.AddError(ErrorCode.ERR_ExpectedVerbatimLiteral); } break; case '$': if (TextWindow.PeekChar(1) == '"') { this.ScanInterpolatedStringLiteral(isVerbatim: false, ref info); CheckFeatureAvailability(MessageID.IDS_FeatureInterpolatedStrings); break; } else if (TextWindow.PeekChar(1) == '@' && TextWindow.PeekChar(2) == '"') { this.ScanInterpolatedStringLiteral(isVerbatim: true, ref info); CheckFeatureAvailability(MessageID.IDS_FeatureInterpolatedStrings); break; } else if (this.ModeIs(LexerMode.DebuggerSyntax)) { goto case 'a'; } goto default; // All the 'common' identifier characters are represented directly in // these switch cases for optimal perf. Calling IsIdentifierChar() functions is relatively // expensive. case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g': case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n': case 'o': case 'p': case 'q': case 'r': case 's': case 't': case 'u': case 'v': case 'w': case 'x': case 'y': case 'z': case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G': case 'H': case 'I': case 'J': case 'K': case 'L': case 'M': case 'N': case 'O': case 'P': case 'Q': case 'R': case 'S': case 'T': case 'U': case 'V': case 'W': case 'X': case 'Y': case 'Z': case '_': this.ScanIdentifierOrKeyword(ref info); break; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': this.ScanNumericLiteral(ref info); break; case '\\': { // Could be unicode escape. Try that. character = TextWindow.PeekCharOrUnicodeEscape(out surrogateCharacter); isEscaped = true; if (SyntaxFacts.IsIdentifierStartCharacter(character)) { goto case 'a'; } goto default; } case SlidingTextWindow.InvalidCharacter: if (!TextWindow.IsReallyAtEnd()) { goto default; } if (_directives.HasUnfinishedIf()) { this.AddError(ErrorCode.ERR_EndifDirectiveExpected); } if (_directives.HasUnfinishedRegion()) { this.AddError(ErrorCode.ERR_EndRegionDirectiveExpected); } info.Kind = SyntaxKind.EndOfFileToken; break; default: if (SyntaxFacts.IsIdentifierStartCharacter(character)) { goto case 'a'; } if (isEscaped) { SyntaxDiagnosticInfo error; TextWindow.NextCharOrUnicodeEscape(out surrogateCharacter, out error); AddError(error); } else { TextWindow.AdvanceChar(); } if (_badTokenCount++ > 200) { // If we get too many characters that we cannot make sense of, absorb the rest of the input. int end = TextWindow.Text.Length; int width = end - startingPosition; info.Text = TextWindow.Text.ToString(new TextSpan(startingPosition, width)); TextWindow.Reset(end); } else { info.Text = TextWindow.GetText(intern: true); } this.AddError(ErrorCode.ERR_UnexpectedCharacter, info.Text); break; } } #nullable enable private void CheckFeatureAvailability(MessageID feature) { var info = feature.GetFeatureAvailabilityDiagnosticInfo(Options); if (info != null) { AddError(info.Code, info.Arguments); } } #nullable disable private bool ScanInteger() { int start = TextWindow.Position; char ch; while ((ch = TextWindow.PeekChar()) >= '0' && ch <= '9') { TextWindow.AdvanceChar(); } return start < TextWindow.Position; } // Allows underscores in integers, except at beginning for decimal and end private void ScanNumericLiteralSingleInteger(ref bool underscoreInWrongPlace, ref bool usedUnderscore, ref bool firstCharWasUnderscore, bool isHex, bool isBinary) { if (TextWindow.PeekChar() == '_') { if (isHex || isBinary) { firstCharWasUnderscore = true; } else { underscoreInWrongPlace = true; } } bool lastCharWasUnderscore = false; while (true) { char ch = TextWindow.PeekChar(); if (ch == '_') { usedUnderscore = true; lastCharWasUnderscore = true; } else if (!(isHex ? SyntaxFacts.IsHexDigit(ch) : isBinary ? SyntaxFacts.IsBinaryDigit(ch) : SyntaxFacts.IsDecDigit(ch))) { break; } else { _builder.Append(ch); lastCharWasUnderscore = false; } TextWindow.AdvanceChar(); } if (lastCharWasUnderscore) { underscoreInWrongPlace = true; } } private bool ScanNumericLiteral(ref TokenInfo info) { int start = TextWindow.Position; char ch; bool isHex = false; bool isBinary = false; bool hasDecimal = false; bool hasExponent = false; info.Text = null; info.ValueKind = SpecialType.None; _builder.Clear(); bool hasUSuffix = false; bool hasLSuffix = false; bool underscoreInWrongPlace = false; bool usedUnderscore = false; bool firstCharWasUnderscore = false; ch = TextWindow.PeekChar(); if (ch == '0') { ch = TextWindow.PeekChar(1); if (ch == 'x' || ch == 'X') { TextWindow.AdvanceChar(2); isHex = true; } else if (ch == 'b' || ch == 'B') { CheckFeatureAvailability(MessageID.IDS_FeatureBinaryLiteral); TextWindow.AdvanceChar(2); isBinary = true; } } if (isHex || isBinary) { // It's OK if it has no digits after the '0x' -- we'll catch it in ScanNumericLiteral // and give a proper error then. ScanNumericLiteralSingleInteger(ref underscoreInWrongPlace, ref usedUnderscore, ref firstCharWasUnderscore, isHex, isBinary); if ((ch = TextWindow.PeekChar()) == 'L' || ch == 'l') { if (ch == 'l') { this.AddError(TextWindow.Position, 1, ErrorCode.WRN_LowercaseEllSuffix); } TextWindow.AdvanceChar(); hasLSuffix = true; if ((ch = TextWindow.PeekChar()) == 'u' || ch == 'U') { TextWindow.AdvanceChar(); hasUSuffix = true; } } else if ((ch = TextWindow.PeekChar()) == 'u' || ch == 'U') { TextWindow.AdvanceChar(); hasUSuffix = true; if ((ch = TextWindow.PeekChar()) == 'L' || ch == 'l') { TextWindow.AdvanceChar(); hasLSuffix = true; } } } else { ScanNumericLiteralSingleInteger(ref underscoreInWrongPlace, ref usedUnderscore, ref firstCharWasUnderscore, isHex: false, isBinary: false); if (this.ModeIs(LexerMode.DebuggerSyntax) && TextWindow.PeekChar() == '#') { // Previously, in DebuggerSyntax mode, "123#" was a valid identifier. TextWindow.AdvanceChar(); info.StringValue = info.Text = TextWindow.GetText(intern: true); info.Kind = SyntaxKind.IdentifierToken; this.AddError(MakeError(ErrorCode.ERR_LegacyObjectIdSyntax)); return true; } if ((ch = TextWindow.PeekChar()) == '.') { var ch2 = TextWindow.PeekChar(1); if (ch2 >= '0' && ch2 <= '9') { hasDecimal = true; _builder.Append(ch); TextWindow.AdvanceChar(); ScanNumericLiteralSingleInteger(ref underscoreInWrongPlace, ref usedUnderscore, ref firstCharWasUnderscore, isHex: false, isBinary: false); } else if (_builder.Length == 0) { // we only have the dot so far.. (no preceding number or following number) TextWindow.Reset(start); return false; } } if ((ch = TextWindow.PeekChar()) == 'E' || ch == 'e') { _builder.Append(ch); TextWindow.AdvanceChar(); hasExponent = true; if ((ch = TextWindow.PeekChar()) == '-' || ch == '+') { _builder.Append(ch); TextWindow.AdvanceChar(); } if (!(((ch = TextWindow.PeekChar()) >= '0' && ch <= '9') || ch == '_')) { // use this for now (CS0595), cant use CS0594 as we dont know 'type' this.AddError(MakeError(ErrorCode.ERR_InvalidReal)); // add dummy exponent, so parser does not blow up _builder.Append('0'); } else { ScanNumericLiteralSingleInteger(ref underscoreInWrongPlace, ref usedUnderscore, ref firstCharWasUnderscore, isHex: false, isBinary: false); } } if (hasExponent || hasDecimal) { if ((ch = TextWindow.PeekChar()) == 'f' || ch == 'F') { TextWindow.AdvanceChar(); info.ValueKind = SpecialType.System_Single; } else if (ch == 'D' || ch == 'd') { TextWindow.AdvanceChar(); info.ValueKind = SpecialType.System_Double; } else if (ch == 'm' || ch == 'M') { TextWindow.AdvanceChar(); info.ValueKind = SpecialType.System_Decimal; } else { info.ValueKind = SpecialType.System_Double; } } else if ((ch = TextWindow.PeekChar()) == 'f' || ch == 'F') { TextWindow.AdvanceChar(); info.ValueKind = SpecialType.System_Single; } else if (ch == 'D' || ch == 'd') { TextWindow.AdvanceChar(); info.ValueKind = SpecialType.System_Double; } else if (ch == 'm' || ch == 'M') { TextWindow.AdvanceChar(); info.ValueKind = SpecialType.System_Decimal; } else if (ch == 'L' || ch == 'l') { if (ch == 'l') { this.AddError(TextWindow.Position, 1, ErrorCode.WRN_LowercaseEllSuffix); } TextWindow.AdvanceChar(); hasLSuffix = true; if ((ch = TextWindow.PeekChar()) == 'u' || ch == 'U') { TextWindow.AdvanceChar(); hasUSuffix = true; } } else if (ch == 'u' || ch == 'U') { hasUSuffix = true; TextWindow.AdvanceChar(); if ((ch = TextWindow.PeekChar()) == 'L' || ch == 'l') { TextWindow.AdvanceChar(); hasLSuffix = true; } } } if (underscoreInWrongPlace) { this.AddError(MakeError(start, TextWindow.Position - start, ErrorCode.ERR_InvalidNumber)); } else if (firstCharWasUnderscore) { CheckFeatureAvailability(MessageID.IDS_FeatureLeadingDigitSeparator); } else if (usedUnderscore) { CheckFeatureAvailability(MessageID.IDS_FeatureDigitSeparator); } info.Kind = SyntaxKind.NumericLiteralToken; info.Text = TextWindow.GetText(true); Debug.Assert(info.Text != null); var valueText = TextWindow.Intern(_builder); ulong val; switch (info.ValueKind) { case SpecialType.System_Single: info.FloatValue = this.GetValueSingle(valueText); break; case SpecialType.System_Double: info.DoubleValue = this.GetValueDouble(valueText); break; case SpecialType.System_Decimal: info.DecimalValue = this.GetValueDecimal(valueText, start, TextWindow.Position); break; default: if (string.IsNullOrEmpty(valueText)) { if (!underscoreInWrongPlace) { this.AddError(MakeError(ErrorCode.ERR_InvalidNumber)); } val = 0; //safe default } else { val = this.GetValueUInt64(valueText, isHex, isBinary); } // 2.4.4.2 Integer literals // ... // The type of an integer literal is determined as follows: // * If the literal has no suffix, it has the first of these types in which its value can be represented: int, uint, long, ulong. if (!hasUSuffix && !hasLSuffix) { if (val <= Int32.MaxValue) { info.ValueKind = SpecialType.System_Int32; info.IntValue = (int)val; } else if (val <= UInt32.MaxValue) { info.ValueKind = SpecialType.System_UInt32; info.UintValue = (uint)val; // TODO: See below, it may be desirable to mark this token // as special for folding if its value is 2147483648. } else if (val <= Int64.MaxValue) { info.ValueKind = SpecialType.System_Int64; info.LongValue = (long)val; } else { info.ValueKind = SpecialType.System_UInt64; info.UlongValue = val; // TODO: See below, it may be desirable to mark this token // as special for folding if its value is 9223372036854775808 } } else if (hasUSuffix && !hasLSuffix) { // * If the literal is suffixed by U or u, it has the first of these types in which its value can be represented: uint, ulong. if (val <= UInt32.MaxValue) { info.ValueKind = SpecialType.System_UInt32; info.UintValue = (uint)val; } else { info.ValueKind = SpecialType.System_UInt64; info.UlongValue = val; } } // * If the literal is suffixed by L or l, it has the first of these types in which its value can be represented: long, ulong. else if (!hasUSuffix & hasLSuffix) { if (val <= Int64.MaxValue) { info.ValueKind = SpecialType.System_Int64; info.LongValue = (long)val; } else { info.ValueKind = SpecialType.System_UInt64; info.UlongValue = val; // TODO: See below, it may be desirable to mark this token // as special for folding if its value is 9223372036854775808 } } // * If the literal is suffixed by UL, Ul, uL, ul, LU, Lu, lU, or lu, it is of type ulong. else { Debug.Assert(hasUSuffix && hasLSuffix); info.ValueKind = SpecialType.System_UInt64; info.UlongValue = val; } break; // Note, the following portion of the spec is not implemented here. It is implemented // in the unary minus analysis. // * When a decimal-integer-literal with the value 2147483648 (231) and no integer-type-suffix appears // as the token immediately following a unary minus operator token (§7.7.2), the result is a constant // of type int with the value −2147483648 (−231). In all other situations, such a decimal-integer- // literal is of type uint. // * When a decimal-integer-literal with the value 9223372036854775808 (263) and no integer-type-suffix // or the integer-type-suffix L or l appears as the token immediately following a unary minus operator // token (§7.7.2), the result is a constant of type long with the value −9223372036854775808 (−263). // In all other situations, such a decimal-integer-literal is of type ulong. } return true; } // TODO: Change to Int64.TryParse when it supports NumberStyles.AllowBinarySpecifier (inline this method into GetValueUInt32/64) private static bool TryParseBinaryUInt64(string text, out ulong value) { value = 0; foreach (char c in text) { // if uppermost bit is set, then the next bitshift will overflow if ((value & 0x8000000000000000) != 0) { return false; } // We shouldn't ever get a string that's nonbinary (see ScanNumericLiteral), // so don't explicitly check for it (there's a debug assert in SyntaxFacts) var bit = (ulong)SyntaxFacts.BinaryValue(c); value = (value << 1) | bit; } return true; } //used in directives private int GetValueInt32(string text, bool isHex) { int result; if (!Int32.TryParse(text, isHex ? NumberStyles.AllowHexSpecifier : NumberStyles.None, CultureInfo.InvariantCulture, out result)) { //we've already lexed the literal, so the error must be from overflow this.AddError(MakeError(ErrorCode.ERR_IntOverflow)); } return result; } //used for all non-directive integer literals (cast to desired type afterward) private ulong GetValueUInt64(string text, bool isHex, bool isBinary) { ulong result; if (isBinary) { if (!TryParseBinaryUInt64(text, out result)) { this.AddError(MakeError(ErrorCode.ERR_IntOverflow)); } } else if (!UInt64.TryParse(text, isHex ? NumberStyles.AllowHexSpecifier : NumberStyles.None, CultureInfo.InvariantCulture, out result)) { //we've already lexed the literal, so the error must be from overflow this.AddError(MakeError(ErrorCode.ERR_IntOverflow)); } return result; } private double GetValueDouble(string text) { double result; if (!RealParser.TryParseDouble(text, out result)) { //we've already lexed the literal, so the error must be from overflow this.AddError(MakeError(ErrorCode.ERR_FloatOverflow, "double")); } return result; } private float GetValueSingle(string text) { float result; if (!RealParser.TryParseFloat(text, out result)) { //we've already lexed the literal, so the error must be from overflow this.AddError(MakeError(ErrorCode.ERR_FloatOverflow, "float")); } return result; } private decimal GetValueDecimal(string text, int start, int end) { // Use decimal.TryParse to parse value. Note: the behavior of // decimal.TryParse differs from Dev11 in several cases: // // 1. [-]0eNm where N > 0 // The native compiler ignores sign and scale and treats such cases // as 0e0m. decimal.TryParse fails so these cases are compile errors. // [Bug #568475] // 2. 1e-Nm where N >= 1000 // The native compiler reports CS0594 "Floating-point constant is // outside the range of type 'decimal'". decimal.TryParse allows // N >> 1000 but treats decimals with very small exponents as 0. // [No bug.] // 3. Decimals with significant digits below 1e-49 // The native compiler considers digits below 1e-49 when rounding. // decimal.TryParse ignores digits below 1e-49 when rounding. This // last difference is perhaps the most significant since existing code // will continue to compile but constant values may be rounded differently. // (Note that the native compiler does not round in all cases either since // the native compiler chops the string at 50 significant digits. For example // ".100000000000000000000000000050000000000000000000001m" is not // rounded up to 0.1000000000000000000000000001.) // [Bug #568494] decimal result; if (!decimal.TryParse(text, NumberStyles.AllowDecimalPoint | NumberStyles.AllowExponent, CultureInfo.InvariantCulture, out result)) { //we've already lexed the literal, so the error must be from overflow this.AddError(this.MakeError(start, end - start, ErrorCode.ERR_FloatOverflow, "decimal")); } return result; } private void ResetIdentBuffer() { _identLen = 0; } private void AddIdentChar(char ch) { if (_identLen >= _identBuffer.Length) { this.GrowIdentBuffer(); } _identBuffer[_identLen++] = ch; } private void GrowIdentBuffer() { var tmp = new char[_identBuffer.Length * 2]; Array.Copy(_identBuffer, tmp, _identBuffer.Length); _identBuffer = tmp; } private bool ScanIdentifier(ref TokenInfo info) { return ScanIdentifier_FastPath(ref info) || (InXmlCrefOrNameAttributeValue ? ScanIdentifier_CrefSlowPath(ref info) : ScanIdentifier_SlowPath(ref info)); } // Implements a faster identifier lexer for the common case in the // language where: // // a) identifiers are not verbatim // b) identifiers don't contain unicode characters // c) identifiers don't contain unicode escapes // // Given that nearly all identifiers will contain [_a-zA-Z0-9] and will // be terminated by a small set of known characters (like dot, comma, // etc.), we can sit in a tight loop looking for this pattern and only // falling back to the slower (but correct) path if we see something we // can't handle. // // Note: this function also only works if the identifier (and terminator) // can be found in the current sliding window of chars we have from our // source text. With this constraint we can avoid the costly overhead // incurred with peek/advance/next. Because of this we can also avoid // the unnecessary stores/reads from identBuffer and all other instance // state while lexing. Instead we just keep track of our start, end, // and max positions and use those for quick checks internally. // // Note: it is critical that this method must only be called from a // code path that checked for IsIdentifierStartChar or '@' first. private bool ScanIdentifier_FastPath(ref TokenInfo info) { if ((_mode & LexerMode.MaskLexMode) == LexerMode.DebuggerSyntax) { // Debugger syntax is wonky. Can't use the fast path for it. return false; } var currentOffset = TextWindow.Offset; var characterWindow = TextWindow.CharacterWindow; var characterWindowCount = TextWindow.CharacterWindowCount; var startOffset = currentOffset; while (true) { if (currentOffset == characterWindowCount) { // no more contiguous characters. Fall back to slow path return false; } switch (characterWindow[currentOffset]) { case '&': // CONSIDER: This method is performance critical, so // it might be safer to kick out at the top (as for // LexerMode.DebuggerSyntax). // If we're in a cref, this could be the start of an // xml entity that belongs in the identifier. if (InXmlCrefOrNameAttributeValue) { // Fall back on the slow path. return false; } // Otherwise, end the identifier. goto case '\0'; case '\0': case ' ': case '\r': case '\n': case '\t': case '!': case '%': case '(': case ')': case '*': case '+': case ',': case '-': case '.': case '/': case ':': case ';': case '<': case '=': case '>': case '?': case '[': case ']': case '^': case '{': case '|': case '}': case '~': case '"': case '\'': // All of the following characters are not valid in an // identifier. If we see any of them, then we know we're // done. var length = currentOffset - startOffset; TextWindow.AdvanceChar(length); info.Text = info.StringValue = TextWindow.Intern(characterWindow, startOffset, length); info.IsVerbatim = false; return true; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': if (currentOffset == startOffset) { return false; } else { goto case 'A'; } case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G': case 'H': case 'I': case 'J': case 'K': case 'L': case 'M': case 'N': case 'O': case 'P': case 'Q': case 'R': case 'S': case 'T': case 'U': case 'V': case 'W': case 'X': case 'Y': case 'Z': case '_': case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g': case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n': case 'o': case 'p': case 'q': case 'r': case 's': case 't': case 'u': case 'v': case 'w': case 'x': case 'y': case 'z': // All of these characters are valid inside an identifier. // consume it and keep processing. currentOffset++; continue; // case '@': verbatim identifiers are handled in the slow path // case '\\': unicode escapes are handled in the slow path default: // Any other character is something we cannot handle. i.e. // unicode chars or an escape. Just break out and move to // the slow path. return false; } } } private bool ScanIdentifier_SlowPath(ref TokenInfo info) { int start = TextWindow.Position; this.ResetIdentBuffer(); info.IsVerbatim = TextWindow.PeekChar() == '@'; if (info.IsVerbatim) { TextWindow.AdvanceChar(); } bool isObjectAddress = false; while (true) { char surrogateCharacter = SlidingTextWindow.InvalidCharacter; bool isEscaped = false; char ch = TextWindow.PeekChar(); top: switch (ch) { case '\\': if (!isEscaped && TextWindow.IsUnicodeEscape()) { // ^^^^^^^ otherwise \u005Cu1234 looks just like \u1234! (i.e. escape within escape) info.HasIdentifierEscapeSequence = true; isEscaped = true; ch = TextWindow.PeekUnicodeEscape(out surrogateCharacter); goto top; } goto default; case '$': if (!this.ModeIs(LexerMode.DebuggerSyntax) || _identLen > 0) { goto LoopExit; } break; case SlidingTextWindow.InvalidCharacter: if (!TextWindow.IsReallyAtEnd()) { goto default; } goto LoopExit; case '_': case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G': case 'H': case 'I': case 'J': case 'K': case 'L': case 'M': case 'N': case 'O': case 'P': case 'Q': case 'R': case 'S': case 'T': case 'U': case 'V': case 'W': case 'X': case 'Y': case 'Z': case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g': case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n': case 'o': case 'p': case 'q': case 'r': case 's': case 't': case 'u': case 'v': case 'w': case 'x': case 'y': case 'z': { // Again, these are the 'common' identifier characters... break; } case '0': { if (_identLen == 0) { // Debugger syntax allows @0x[hexdigit]+ for object address identifiers. if (info.IsVerbatim && this.ModeIs(LexerMode.DebuggerSyntax) && (char.ToLower(TextWindow.PeekChar(1)) == 'x')) { isObjectAddress = true; } else { goto LoopExit; } } // Again, these are the 'common' identifier characters... break; } case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': { if (_identLen == 0) { goto LoopExit; } // Again, these are the 'common' identifier characters... break; } case ' ': case '\t': case '.': case ';': case '(': case ')': case ',': // ...and these are the 'common' stop characters. goto LoopExit; case '<': if (_identLen == 0 && this.ModeIs(LexerMode.DebuggerSyntax) && TextWindow.PeekChar(1) == '>') { // In DebuggerSyntax mode, identifiers are allowed to begin with <>. TextWindow.AdvanceChar(2); this.AddIdentChar('<'); this.AddIdentChar('>'); continue; } goto LoopExit; default: { // This is the 'expensive' call if (_identLen == 0 && ch > 127 && SyntaxFacts.IsIdentifierStartCharacter(ch)) { break; } else if (_identLen > 0 && ch > 127 && SyntaxFacts.IsIdentifierPartCharacter(ch)) { //// BUG 424819 : Handle identifier chars > 0xFFFF via surrogate pairs if (UnicodeCharacterUtilities.IsFormattingChar(ch)) { if (isEscaped) { SyntaxDiagnosticInfo error; TextWindow.NextCharOrUnicodeEscape(out surrogateCharacter, out error); AddError(error); } else { TextWindow.AdvanceChar(); } continue; // Ignore formatting characters } break; } else { // Not a valid identifier character, so bail. goto LoopExit; } } } if (isEscaped) { SyntaxDiagnosticInfo error; TextWindow.NextCharOrUnicodeEscape(out surrogateCharacter, out error); AddError(error); } else { TextWindow.AdvanceChar(); } this.AddIdentChar(ch); if (surrogateCharacter != SlidingTextWindow.InvalidCharacter) { this.AddIdentChar(surrogateCharacter); } } LoopExit: var width = TextWindow.Width; // exact size of input characters if (_identLen > 0) { info.Text = TextWindow.GetInternedText(); // id buffer is identical to width in input if (_identLen == width) { info.StringValue = info.Text; } else { info.StringValue = TextWindow.Intern(_identBuffer, 0, _identLen); } if (isObjectAddress) { // @0x[hexdigit]+ const int objectAddressOffset = 2; Debug.Assert(string.Equals(info.Text.Substring(0, objectAddressOffset + 1), "@0x", StringComparison.OrdinalIgnoreCase)); var valueText = TextWindow.Intern(_identBuffer, objectAddressOffset, _identLen - objectAddressOffset); // Verify valid hex value. if ((valueText.Length == 0) || !valueText.All(IsValidHexDigit)) { goto Fail; } // Parse hex value to check for overflow. this.GetValueUInt64(valueText, isHex: true, isBinary: false); } return true; } Fail: info.Text = null; info.StringValue = null; TextWindow.Reset(start); return false; } private static bool IsValidHexDigit(char c) { if ((c >= '0') && (c <= '9')) { return true; } c = char.ToLower(c); return (c >= 'a') && (c <= 'f'); } /// <summary> /// This method is essentially the same as ScanIdentifier_SlowPath, /// except that it can handle XML entities. Since ScanIdentifier /// is hot code and since this method does extra work, it seem /// worthwhile to separate it from the common case. /// </summary> /// <param name="info"></param> /// <returns></returns> private bool ScanIdentifier_CrefSlowPath(ref TokenInfo info) { Debug.Assert(InXmlCrefOrNameAttributeValue); int start = TextWindow.Position; this.ResetIdentBuffer(); if (AdvanceIfMatches('@')) { // In xml name attribute values, the '@' is part of the value text of the identifier // (to match dev11). if (InXmlNameAttributeValue) { AddIdentChar('@'); } else { info.IsVerbatim = true; } } while (true) { int beforeConsumed = TextWindow.Position; char consumedChar; char consumedSurrogate; if (TextWindow.PeekChar() == '&') { if (!TextWindow.TryScanXmlEntity(out consumedChar, out consumedSurrogate)) { // If it's not a valid entity, then it's not part of the identifier. TextWindow.Reset(beforeConsumed); goto LoopExit; } } else { consumedChar = TextWindow.NextChar(); consumedSurrogate = SlidingTextWindow.InvalidCharacter; } // NOTE: If the surrogate is non-zero, then consumedChar won't match // any of the cases below (UTF-16 guarantees that members of surrogate // pairs aren't separately valid). bool isEscaped = false; top: switch (consumedChar) { case '\\': // NOTE: For completeness, we should allow xml entities in unicode escape // sequences (DevDiv #16321). Since it is not currently a priority, we will // try to make the interim behavior sensible: we will only attempt to scan // a unicode escape if NONE of the characters are XML entities (including // the backslash, which we have already consumed). // When we're ready to implement this behavior, we can drop the position // check and use AdvanceIfMatches instead of PeekChar. if (!isEscaped && (TextWindow.Position == beforeConsumed + 1) && (TextWindow.PeekChar() == 'u' || TextWindow.PeekChar() == 'U')) { Debug.Assert(consumedSurrogate == SlidingTextWindow.InvalidCharacter, "Since consumedChar == '\\'"); info.HasIdentifierEscapeSequence = true; TextWindow.Reset(beforeConsumed); // ^^^^^^^ otherwise \u005Cu1234 looks just like \u1234! (i.e. escape within escape) isEscaped = true; SyntaxDiagnosticInfo error; consumedChar = TextWindow.NextUnicodeEscape(out consumedSurrogate, out error); AddCrefError(error); goto top; } goto default; case '_': case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G': case 'H': case 'I': case 'J': case 'K': case 'L': case 'M': case 'N': case 'O': case 'P': case 'Q': case 'R': case 'S': case 'T': case 'U': case 'V': case 'W': case 'X': case 'Y': case 'Z': case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g': case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n': case 'o': case 'p': case 'q': case 'r': case 's': case 't': case 'u': case 'v': case 'w': case 'x': case 'y': case 'z': { // Again, these are the 'common' identifier characters... break; } case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': { if (_identLen == 0) { TextWindow.Reset(beforeConsumed); goto LoopExit; } // Again, these are the 'common' identifier characters... break; } case ' ': case '$': case '\t': case '.': case ';': case '(': case ')': case ',': case '<': // ...and these are the 'common' stop characters. TextWindow.Reset(beforeConsumed); goto LoopExit; case SlidingTextWindow.InvalidCharacter: if (!TextWindow.IsReallyAtEnd()) { goto default; } TextWindow.Reset(beforeConsumed); goto LoopExit; default: { // This is the 'expensive' call if (_identLen == 0 && consumedChar > 127 && SyntaxFacts.IsIdentifierStartCharacter(consumedChar)) { break; } else if (_identLen > 0 && consumedChar > 127 && SyntaxFacts.IsIdentifierPartCharacter(consumedChar)) { //// BUG 424819 : Handle identifier chars > 0xFFFF via surrogate pairs if (UnicodeCharacterUtilities.IsFormattingChar(consumedChar)) { continue; // Ignore formatting characters } break; } else { // Not a valid identifier character, so bail. TextWindow.Reset(beforeConsumed); goto LoopExit; } } } this.AddIdentChar(consumedChar); if (consumedSurrogate != SlidingTextWindow.InvalidCharacter) { this.AddIdentChar(consumedSurrogate); } } LoopExit: if (_identLen > 0) { // NOTE: If we don't intern the string value, then we won't get a hit // in the keyword dictionary! (It searches for a key using identity.) // The text does not have to be interned (and probably shouldn't be // if it contains entities (else-case). var width = TextWindow.Width; // exact size of input characters // id buffer is identical to width in input if (_identLen == width) { info.StringValue = TextWindow.GetInternedText(); info.Text = info.StringValue; } else { info.StringValue = TextWindow.Intern(_identBuffer, 0, _identLen); info.Text = TextWindow.GetText(intern: false); } return true; } else { info.Text = null; info.StringValue = null; TextWindow.Reset(start); return false; } } private bool ScanIdentifierOrKeyword(ref TokenInfo info) { info.ContextualKind = SyntaxKind.None; if (this.ScanIdentifier(ref info)) { // check to see if it is an actual keyword if (!info.IsVerbatim && !info.HasIdentifierEscapeSequence) { if (this.ModeIs(LexerMode.Directive)) { SyntaxKind keywordKind = SyntaxFacts.GetPreprocessorKeywordKind(info.Text); if (SyntaxFacts.IsPreprocessorContextualKeyword(keywordKind)) { // Let the parser decide which instances are actually keywords. info.Kind = SyntaxKind.IdentifierToken; info.ContextualKind = keywordKind; } else { info.Kind = keywordKind; } } else { if (!_cache.TryGetKeywordKind(info.Text, out info.Kind)) { info.ContextualKind = info.Kind = SyntaxKind.IdentifierToken; } else if (SyntaxFacts.IsContextualKeyword(info.Kind)) { info.ContextualKind = info.Kind; info.Kind = SyntaxKind.IdentifierToken; } } if (info.Kind == SyntaxKind.None) { info.Kind = SyntaxKind.IdentifierToken; } } else { info.ContextualKind = info.Kind = SyntaxKind.IdentifierToken; } return true; } else { info.Kind = SyntaxKind.None; return false; } } private void LexSyntaxTrivia(bool afterFirstToken, bool isTrailing, ref SyntaxListBuilder triviaList) { bool onlyWhitespaceOnLine = !isTrailing; while (true) { this.Start(); char ch = TextWindow.PeekChar(); if (ch == ' ') { this.AddTrivia(this.ScanWhitespace(), ref triviaList); continue; } else if (ch > 127) { if (SyntaxFacts.IsWhitespace(ch)) { ch = ' '; } else if (SyntaxFacts.IsNewLine(ch)) { ch = '\n'; } } switch (ch) { case ' ': case '\t': // Horizontal tab case '\v': // Vertical Tab case '\f': // Form-feed case '\u001A': this.AddTrivia(this.ScanWhitespace(), ref triviaList); break; case '/': if ((ch = TextWindow.PeekChar(1)) == '/') { if (!this.SuppressDocumentationCommentParse && TextWindow.PeekChar(2) == '/' && TextWindow.PeekChar(3) != '/') { // Doc comments should never be in trailing trivia. // Stop processing so that it will be leading trivia on the next token. if (isTrailing) { return; } this.AddTrivia(this.LexXmlDocComment(XmlDocCommentStyle.SingleLine), ref triviaList); break; } // normal single line comment this.ScanToEndOfLine(); var text = TextWindow.GetText(false); this.AddTrivia(SyntaxFactory.Comment(text), ref triviaList); onlyWhitespaceOnLine = false; break; } else if (ch == '*') { if (!this.SuppressDocumentationCommentParse && TextWindow.PeekChar(2) == '*' && TextWindow.PeekChar(3) != '*' && TextWindow.PeekChar(3) != '/') { // Doc comments should never be in trailing trivia. // Stop processing so that it will be leading trivia on the next token. if (isTrailing) { return; } this.AddTrivia(this.LexXmlDocComment(XmlDocCommentStyle.Delimited), ref triviaList); break; } bool isTerminated; this.ScanMultiLineComment(out isTerminated); if (!isTerminated) { // The comment didn't end. Report an error at the start point. this.AddError(ErrorCode.ERR_OpenEndedComment); } var text = TextWindow.GetText(false); this.AddTrivia(SyntaxFactory.Comment(text), ref triviaList); onlyWhitespaceOnLine = false; break; } // not trivia return; case '\r': case '\n': this.AddTrivia(this.ScanEndOfLine(), ref triviaList); if (isTrailing) { return; } onlyWhitespaceOnLine = true; break; case '#': if (_allowPreprocessorDirectives) { this.LexDirectiveAndExcludedTrivia(afterFirstToken, isTrailing || !onlyWhitespaceOnLine, ref triviaList); break; } else { return; } // Note: we specifically do not look for the >>>>>>> pattern as the start of // a conflict marker trivia. That's because *technically* (albeit unlikely) // >>>>>>> could be the end of a very generic construct. So, instead, we only // recognize >>>>>>> as we are scanning the trivia after a ======= marker // (which can never be part of legal code). // case '>': case '=': case '<': if (!isTrailing) { if (IsConflictMarkerTrivia()) { this.LexConflictMarkerTrivia(ref triviaList); break; } } return; default: return; } } } // All conflict markers consist of the same character repeated seven times. If it is // a <<<<<<< or >>>>>>> marker then it is also followed by a space. private static readonly int s_conflictMarkerLength = "<<<<<<<".Length; private bool IsConflictMarkerTrivia() { var position = TextWindow.Position; var text = TextWindow.Text; if (position == 0 || SyntaxFacts.IsNewLine(text[position - 1])) { var firstCh = text[position]; Debug.Assert(firstCh == '<' || firstCh == '=' || firstCh == '>'); if ((position + s_conflictMarkerLength) <= text.Length) { for (int i = 0, n = s_conflictMarkerLength; i < n; i++) { if (text[position + i] != firstCh) { return false; } } if (firstCh == '=') { return true; } return (position + s_conflictMarkerLength) < text.Length && text[position + s_conflictMarkerLength] == ' '; } } return false; } private void LexConflictMarkerTrivia(ref SyntaxListBuilder triviaList) { this.Start(); this.AddError(TextWindow.Position, s_conflictMarkerLength, ErrorCode.ERR_Merge_conflict_marker_encountered); var startCh = this.TextWindow.PeekChar(); // First create a trivia from the start of this merge conflict marker to the // end of line/file (whichever comes first). LexConflictMarkerHeader(ref triviaList); // Now add the newlines as the next trivia. LexConflictMarkerEndOfLine(ref triviaList); // Now, if it was an ======= marker, then also created a DisabledText trivia for // the contents of the file after it, up until the next >>>>>>> marker we see. if (startCh == '=') { LexConflictMarkerDisabledText(ref triviaList); } } private SyntaxListBuilder LexConflictMarkerDisabledText(ref SyntaxListBuilder triviaList) { // Consume everything from the start of the mid-conflict marker to the start of the next // end-conflict marker. this.Start(); var hitEndConflictMarker = false; while (true) { var ch = this.TextWindow.PeekChar(); if (ch == SlidingTextWindow.InvalidCharacter) { break; } // If we hit the end-conflict marker, then lex it out at this point. if (ch == '>' && IsConflictMarkerTrivia()) { hitEndConflictMarker = true; break; } this.TextWindow.AdvanceChar(); } if (this.TextWindow.Width > 0) { this.AddTrivia(SyntaxFactory.DisabledText(TextWindow.GetText(false)), ref triviaList); } if (hitEndConflictMarker) { LexConflictMarkerTrivia(ref triviaList); } return triviaList; } private void LexConflictMarkerEndOfLine(ref SyntaxListBuilder triviaList) { this.Start(); while (SyntaxFacts.IsNewLine(this.TextWindow.PeekChar())) { this.TextWindow.AdvanceChar(); } if (this.TextWindow.Width > 0) { this.AddTrivia(SyntaxFactory.EndOfLine(TextWindow.GetText(false)), ref triviaList); } } private void LexConflictMarkerHeader(ref SyntaxListBuilder triviaList) { while (true) { var ch = this.TextWindow.PeekChar(); if (ch == SlidingTextWindow.InvalidCharacter || SyntaxFacts.IsNewLine(ch)) { break; } this.TextWindow.AdvanceChar(); } this.AddTrivia(SyntaxFactory.ConflictMarker(TextWindow.GetText(false)), ref triviaList); } private void AddTrivia(CSharpSyntaxNode trivia, ref SyntaxListBuilder list) { if (this.HasErrors) { trivia = trivia.WithDiagnosticsGreen(this.GetErrors(leadingTriviaWidth: 0)); } if (list == null) { list = new SyntaxListBuilder(TriviaListInitialCapacity); } list.Add(trivia); } private bool ScanMultiLineComment(out bool isTerminated) { if (TextWindow.PeekChar() == '/' && TextWindow.PeekChar(1) == '*') { TextWindow.AdvanceChar(2); char ch; while (true) { if ((ch = TextWindow.PeekChar()) == SlidingTextWindow.InvalidCharacter && TextWindow.IsReallyAtEnd()) { isTerminated = false; break; } else if (ch == '*' && TextWindow.PeekChar(1) == '/') { TextWindow.AdvanceChar(2); isTerminated = true; break; } else { TextWindow.AdvanceChar(); } } return true; } else { isTerminated = false; return false; } } private void ScanToEndOfLine() { char ch; while (!SyntaxFacts.IsNewLine(ch = TextWindow.PeekChar()) && (ch != SlidingTextWindow.InvalidCharacter || !TextWindow.IsReallyAtEnd())) { TextWindow.AdvanceChar(); } } /// <summary> /// Scans a new-line sequence (either a single new-line character or a CR-LF combo). /// </summary> /// <returns>A trivia node with the new-line text</returns> private CSharpSyntaxNode ScanEndOfLine() { char ch; switch (ch = TextWindow.PeekChar()) { case '\r': TextWindow.AdvanceChar(); if (TextWindow.PeekChar() == '\n') { TextWindow.AdvanceChar(); return SyntaxFactory.CarriageReturnLineFeed; } return SyntaxFactory.CarriageReturn; case '\n': TextWindow.AdvanceChar(); return SyntaxFactory.LineFeed; default: if (SyntaxFacts.IsNewLine(ch)) { TextWindow.AdvanceChar(); return SyntaxFactory.EndOfLine(ch.ToString()); } return null; } } /// <summary> /// Scans all of the whitespace (not new-lines) into a trivia node until it runs out. /// </summary> /// <returns>A trivia node with the whitespace text</returns> private SyntaxTrivia ScanWhitespace() { if (_createWhitespaceTriviaFunction == null) { _createWhitespaceTriviaFunction = this.CreateWhitespaceTrivia; } int hashCode = Hash.FnvOffsetBias; // FNV base bool onlySpaces = true; top: char ch = TextWindow.PeekChar(); switch (ch) { case '\t': // Horizontal tab case '\v': // Vertical Tab case '\f': // Form-feed case '\u001A': onlySpaces = false; goto case ' '; case ' ': TextWindow.AdvanceChar(); hashCode = Hash.CombineFNVHash(hashCode, ch); goto top; case '\r': // Carriage Return case '\n': // Line-feed break; default: if (ch > 127 && SyntaxFacts.IsWhitespace(ch)) { goto case '\t'; } break; } if (TextWindow.Width == 1 && onlySpaces) { return SyntaxFactory.Space; } else { var width = TextWindow.Width; if (width < MaxCachedTokenSize) { return _cache.LookupTrivia( TextWindow.CharacterWindow, TextWindow.LexemeRelativeStart, width, hashCode, _createWhitespaceTriviaFunction); } else { return _createWhitespaceTriviaFunction(); } } } private Func<SyntaxTrivia> _createWhitespaceTriviaFunction; private SyntaxTrivia CreateWhitespaceTrivia() { return SyntaxFactory.Whitespace(TextWindow.GetText(intern: true)); } private void LexDirectiveAndExcludedTrivia( bool afterFirstToken, bool afterNonWhitespaceOnLine, ref SyntaxListBuilder triviaList) { var directive = this.LexSingleDirective(true, true, afterFirstToken, afterNonWhitespaceOnLine, ref triviaList); // also lex excluded stuff var branching = directive as BranchingDirectiveTriviaSyntax; if (branching != null && !branching.BranchTaken) { this.LexExcludedDirectivesAndTrivia(true, ref triviaList); } } private void LexExcludedDirectivesAndTrivia(bool endIsActive, ref SyntaxListBuilder triviaList) { while (true) { bool hasFollowingDirective; var text = this.LexDisabledText(out hasFollowingDirective); if (text != null) { this.AddTrivia(text, ref triviaList); } if (!hasFollowingDirective) { break; } var directive = this.LexSingleDirective(false, endIsActive, false, false, ref triviaList); var branching = directive as BranchingDirectiveTriviaSyntax; if (directive.Kind == SyntaxKind.EndIfDirectiveTrivia || (branching != null && branching.BranchTaken)) { break; } else if (directive.Kind == SyntaxKind.IfDirectiveTrivia) { this.LexExcludedDirectivesAndTrivia(false, ref triviaList); } } } private CSharpSyntaxNode LexSingleDirective( bool isActive, bool endIsActive, bool afterFirstToken, bool afterNonWhitespaceOnLine, ref SyntaxListBuilder triviaList) { if (SyntaxFacts.IsWhitespace(TextWindow.PeekChar())) { this.Start(); this.AddTrivia(this.ScanWhitespace(), ref triviaList); } CSharpSyntaxNode directive; var saveMode = _mode; using (var dp = new DirectiveParser(this, _directives)) { directive = dp.ParseDirective(isActive, endIsActive, afterFirstToken, afterNonWhitespaceOnLine); } this.AddTrivia(directive, ref triviaList); _directives = directive.ApplyDirectives(_directives); _mode = saveMode; return directive; } // consume text up to the next directive private CSharpSyntaxNode LexDisabledText(out bool followedByDirective) { this.Start(); int lastLineStart = TextWindow.Position; int lines = 0; bool allWhitespace = true; while (true) { char ch = TextWindow.PeekChar(); switch (ch) { case SlidingTextWindow.InvalidCharacter: if (!TextWindow.IsReallyAtEnd()) { goto default; } followedByDirective = false; return TextWindow.Width > 0 ? SyntaxFactory.DisabledText(TextWindow.GetText(false)) : null; case '#': if (!_allowPreprocessorDirectives) goto default; followedByDirective = true; if (lastLineStart < TextWindow.Position && !allWhitespace) { goto default; } TextWindow.Reset(lastLineStart); // reset so directive parser can consume the starting whitespace on this line return TextWindow.Width > 0 ? SyntaxFactory.DisabledText(TextWindow.GetText(false)) : null; case '\r': case '\n': this.ScanEndOfLine(); lastLineStart = TextWindow.Position; allWhitespace = true; lines++; break; default: if (SyntaxFacts.IsNewLine(ch)) { goto case '\n'; } allWhitespace = allWhitespace && SyntaxFacts.IsWhitespace(ch); TextWindow.AdvanceChar(); break; } } } private SyntaxToken LexDirectiveToken() { this.Start(); TokenInfo info = default(TokenInfo); this.ScanDirectiveToken(ref info); var errors = this.GetErrors(leadingTriviaWidth: 0); var trailing = this.LexDirectiveTrailingTrivia(info.Kind == SyntaxKind.EndOfDirectiveToken); return Create(ref info, null, trailing, errors); } private bool ScanDirectiveToken(ref TokenInfo info) { char character; char surrogateCharacter; bool isEscaped = false; switch (character = TextWindow.PeekChar()) { case SlidingTextWindow.InvalidCharacter: if (!TextWindow.IsReallyAtEnd()) { goto default; } // don't consume end characters here info.Kind = SyntaxKind.EndOfDirectiveToken; break; case '\r': case '\n': // don't consume end characters here info.Kind = SyntaxKind.EndOfDirectiveToken; break; case '#': TextWindow.AdvanceChar(); info.Kind = SyntaxKind.HashToken; break; case '(': TextWindow.AdvanceChar(); info.Kind = SyntaxKind.OpenParenToken; break; case ')': TextWindow.AdvanceChar(); info.Kind = SyntaxKind.CloseParenToken; break; case ',': TextWindow.AdvanceChar(); info.Kind = SyntaxKind.CommaToken; break; case '-': TextWindow.AdvanceChar(); info.Kind = SyntaxKind.MinusToken; break; case '!': TextWindow.AdvanceChar(); if (TextWindow.PeekChar() == '=') { TextWindow.AdvanceChar(); info.Kind = SyntaxKind.ExclamationEqualsToken; } else { info.Kind = SyntaxKind.ExclamationToken; } break; case '=': TextWindow.AdvanceChar(); if (TextWindow.PeekChar() == '=') { TextWindow.AdvanceChar(); info.Kind = SyntaxKind.EqualsEqualsToken; } else { info.Kind = SyntaxKind.EqualsToken; } break; case '&': if (TextWindow.PeekChar(1) == '&') { TextWindow.AdvanceChar(2); info.Kind = SyntaxKind.AmpersandAmpersandToken; break; } goto default; case '|': if (TextWindow.PeekChar(1) == '|') { TextWindow.AdvanceChar(2); info.Kind = SyntaxKind.BarBarToken; break; } goto default; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': this.ScanInteger(); info.Kind = SyntaxKind.NumericLiteralToken; info.Text = TextWindow.GetText(true); info.ValueKind = SpecialType.System_Int32; info.IntValue = this.GetValueInt32(info.Text, false); break; case '\"': this.ScanStringLiteral(ref info, inDirective: true); break; case '\\': { // Could be unicode escape. Try that. character = TextWindow.PeekCharOrUnicodeEscape(out surrogateCharacter); isEscaped = true; if (SyntaxFacts.IsIdentifierStartCharacter(character)) { this.ScanIdentifierOrKeyword(ref info); break; } goto default; } default: if (!isEscaped && SyntaxFacts.IsNewLine(character)) { goto case '\n'; } if (SyntaxFacts.IsIdentifierStartCharacter(character)) { this.ScanIdentifierOrKeyword(ref info); } else { // unknown single character if (isEscaped) { SyntaxDiagnosticInfo error; TextWindow.NextCharOrUnicodeEscape(out surrogateCharacter, out error); AddError(error); } else { TextWindow.AdvanceChar(); } info.Kind = SyntaxKind.None; info.Text = TextWindow.GetText(true); } break; } Debug.Assert(info.Kind != SyntaxKind.None || info.Text != null); return info.Kind != SyntaxKind.None; } private SyntaxListBuilder LexDirectiveTrailingTrivia(bool includeEndOfLine) { SyntaxListBuilder trivia = null; CSharpSyntaxNode tr; while (true) { var pos = TextWindow.Position; tr = this.LexDirectiveTrivia(); if (tr == null) { break; } else if (tr.Kind == SyntaxKind.EndOfLineTrivia) { if (includeEndOfLine) { AddTrivia(tr, ref trivia); } else { // don't consume end of line... TextWindow.Reset(pos); } break; } else { AddTrivia(tr, ref trivia); } } return trivia; } private CSharpSyntaxNode LexDirectiveTrivia() { CSharpSyntaxNode trivia = null; this.Start(); char ch = TextWindow.PeekChar(); switch (ch) { case '/': if (TextWindow.PeekChar(1) == '/') { // normal single line comment this.ScanToEndOfLine(); var text = TextWindow.GetText(false); trivia = SyntaxFactory.Comment(text); } break; case '\r': case '\n': trivia = this.ScanEndOfLine(); break; case ' ': case '\t': // Horizontal tab case '\v': // Vertical Tab case '\f': // Form-feed trivia = this.ScanWhitespace(); break; default: if (SyntaxFacts.IsWhitespace(ch)) { goto case ' '; } if (SyntaxFacts.IsNewLine(ch)) { goto case '\n'; } break; } return trivia; } private CSharpSyntaxNode LexXmlDocComment(XmlDocCommentStyle style) { var saveMode = _mode; bool isTerminated; var mode = style == XmlDocCommentStyle.SingleLine ? LexerMode.XmlDocCommentStyleSingleLine : LexerMode.XmlDocCommentStyleDelimited; if (_xmlParser == null) { _xmlParser = new DocumentationCommentParser(this, mode); } else { _xmlParser.ReInitialize(mode); } var docComment = _xmlParser.ParseDocumentationComment(out isTerminated); // We better have finished with the whole comment. There should be error // code in the implementation of ParseXmlDocComment that ensures this. Debug.Assert(this.LocationIs(XmlDocCommentLocation.End) || TextWindow.PeekChar() == SlidingTextWindow.InvalidCharacter); _mode = saveMode; if (!isTerminated) { // The comment didn't end. Report an error at the start point. // NOTE: report this error even if the DocumentationMode is less than diagnose - the comment // would be malformed as a non-doc comment as well. this.AddError(TextWindow.LexemeStartPosition, TextWindow.Width, ErrorCode.ERR_OpenEndedComment); } return docComment; } /// <summary> /// Lexer entry point for LexMode.XmlDocComment /// </summary> private SyntaxToken LexXmlToken() { TokenInfo xmlTokenInfo = default(TokenInfo); SyntaxListBuilder leading = null; this.LexXmlDocCommentLeadingTrivia(ref leading); this.Start(); this.ScanXmlToken(ref xmlTokenInfo); var errors = this.GetErrors(GetFullWidth(leading)); return Create(ref xmlTokenInfo, leading, null, errors); } private bool ScanXmlToken(ref TokenInfo info) { char ch; Debug.Assert(!this.LocationIs(XmlDocCommentLocation.Start)); Debug.Assert(!this.LocationIs(XmlDocCommentLocation.Exterior)); if (this.LocationIs(XmlDocCommentLocation.End)) { info.Kind = SyntaxKind.EndOfDocumentationCommentToken; return true; } switch (ch = TextWindow.PeekChar()) { case '&': this.ScanXmlEntity(ref info); info.Kind = SyntaxKind.XmlEntityLiteralToken; break; case '<': this.ScanXmlTagStart(ref info); break; case '\r': case '\n': ScanXmlTextLiteralNewLineToken(ref info); break; case SlidingTextWindow.InvalidCharacter: if (!TextWindow.IsReallyAtEnd()) { goto default; } info.Kind = SyntaxKind.EndOfDocumentationCommentToken; break; default: if (SyntaxFacts.IsNewLine(ch)) { goto case '\n'; } this.ScanXmlText(ref info); info.Kind = SyntaxKind.XmlTextLiteralToken; break; } Debug.Assert(info.Kind != SyntaxKind.None || info.Text != null); return info.Kind != SyntaxKind.None; } private void ScanXmlTextLiteralNewLineToken(ref TokenInfo info) { this.ScanEndOfLine(); info.StringValue = info.Text = TextWindow.GetText(intern: false); info.Kind = SyntaxKind.XmlTextLiteralNewLineToken; this.MutateLocation(XmlDocCommentLocation.Exterior); } private void ScanXmlTagStart(ref TokenInfo info) { Debug.Assert(TextWindow.PeekChar() == '<'); if (TextWindow.PeekChar(1) == '!') { if (TextWindow.PeekChar(2) == '-' && TextWindow.PeekChar(3) == '-') { TextWindow.AdvanceChar(4); info.Kind = SyntaxKind.XmlCommentStartToken; } else if (TextWindow.PeekChar(2) == '[' && TextWindow.PeekChar(3) == 'C' && TextWindow.PeekChar(4) == 'D' && TextWindow.PeekChar(5) == 'A' && TextWindow.PeekChar(6) == 'T' && TextWindow.PeekChar(7) == 'A' && TextWindow.PeekChar(8) == '[') { TextWindow.AdvanceChar(9); info.Kind = SyntaxKind.XmlCDataStartToken; } else { // TODO: Take the < by itself, I guess? TextWindow.AdvanceChar(); info.Kind = SyntaxKind.LessThanToken; } } else if (TextWindow.PeekChar(1) == '/') { TextWindow.AdvanceChar(2); info.Kind = SyntaxKind.LessThanSlashToken; } else if (TextWindow.PeekChar(1) == '?') { TextWindow.AdvanceChar(2); info.Kind = SyntaxKind.XmlProcessingInstructionStartToken; } else { TextWindow.AdvanceChar(); info.Kind = SyntaxKind.LessThanToken; } } private void ScanXmlEntity(ref TokenInfo info) { info.StringValue = null; Debug.Assert(TextWindow.PeekChar() == '&'); TextWindow.AdvanceChar(); _builder.Clear(); XmlParseErrorCode? error = null; object[] errorArgs = null; char ch; if (IsXmlNameStartChar(ch = TextWindow.PeekChar())) { while (IsXmlNameChar(ch = TextWindow.PeekChar())) { // Important bit of information here: none of \0, \r, \n, and crucially for // delimited comments, * are considered Xml name characters. Also, since // entities appear in xml text and attribute text, it's relevant here that // none of <, /, >, ', ", =, are Xml name characters. Note that - and ] are // irrelevant--entities do not appear in comments or cdata. TextWindow.AdvanceChar(); _builder.Append(ch); } switch (_builder.ToString()) { case "lt": info.StringValue = "<"; break; case "gt": info.StringValue = ">"; break; case "amp": info.StringValue = "&"; break; case "apos": info.StringValue = "'"; break; case "quot": info.StringValue = "\""; break; default: error = XmlParseErrorCode.XML_RefUndefinedEntity_1; errorArgs = new[] { _builder.ToString() }; break; } } else if (ch == '#') { TextWindow.AdvanceChar(); bool isHex = TextWindow.PeekChar() == 'x'; uint charValue = 0; if (isHex) { TextWindow.AdvanceChar(); // x while (SyntaxFacts.IsHexDigit(ch = TextWindow.PeekChar())) { TextWindow.AdvanceChar(); // disallow overflow if (charValue <= 0x7FFFFFF) { charValue = (charValue << 4) + (uint)SyntaxFacts.HexValue(ch); } } } else { while (SyntaxFacts.IsDecDigit(ch = TextWindow.PeekChar())) { TextWindow.AdvanceChar(); // disallow overflow if (charValue <= 0x7FFFFFF) { charValue = (charValue << 3) + (charValue << 1) + (uint)SyntaxFacts.DecValue(ch); } } } if (TextWindow.PeekChar() != ';') { error = XmlParseErrorCode.XML_InvalidCharEntity; } if (MatchesProductionForXmlChar(charValue)) { char lowSurrogate; char highSurrogate = SlidingTextWindow.GetCharsFromUtf32(charValue, out lowSurrogate); _builder.Append(highSurrogate); if (lowSurrogate != SlidingTextWindow.InvalidCharacter) { _builder.Append(lowSurrogate); } info.StringValue = _builder.ToString(); } else { if (error == null) { error = XmlParseErrorCode.XML_InvalidUnicodeChar; } } } else { if (SyntaxFacts.IsWhitespace(ch) || SyntaxFacts.IsNewLine(ch)) { if (error == null) { error = XmlParseErrorCode.XML_InvalidWhitespace; } } else { if (error == null) { error = XmlParseErrorCode.XML_InvalidToken; errorArgs = new[] { ch.ToString() }; } } } ch = TextWindow.PeekChar(); if (ch == ';') { TextWindow.AdvanceChar(); } else { if (error == null) { error = XmlParseErrorCode.XML_InvalidToken; errorArgs = new[] { ch.ToString() }; } } // If we don't have a value computed from above, then we don't recognize the entity, in which // case we will simply use the text. info.Text = TextWindow.GetText(true); if (info.StringValue == null) { info.StringValue = info.Text; } if (error != null) { this.AddError(error.Value, errorArgs ?? Array.Empty<object>()); } } private static bool MatchesProductionForXmlChar(uint charValue) { // Char ::= #x9 | #xA | #xD | [#x20-#xD7FF] | [#xE000-#xFFFD] | [#x10000-#x10FFFF] /* any Unicode character, excluding the surrogate blocks, FFFE, and FFFF. */ return charValue == 0x9 || charValue == 0xA || charValue == 0xD || (charValue >= 0x20 && charValue <= 0xD7FF) || (charValue >= 0xE000 && charValue <= 0xFFFD) || (charValue >= 0x10000 && charValue <= 0x10FFFF); } private void ScanXmlText(ref TokenInfo info) { // Collect "]]>" strings into their own XmlText. if (TextWindow.PeekChar() == ']' && TextWindow.PeekChar(1) == ']' && TextWindow.PeekChar(2) == '>') { TextWindow.AdvanceChar(3); info.StringValue = info.Text = TextWindow.GetText(false); this.AddError(XmlParseErrorCode.XML_CDataEndTagNotAllowed); return; } while (true) { var ch = TextWindow.PeekChar(); switch (ch) { case SlidingTextWindow.InvalidCharacter: if (!TextWindow.IsReallyAtEnd()) { goto default; } info.StringValue = info.Text = TextWindow.GetText(false); return; case '&': case '<': case '\r': case '\n': info.StringValue = info.Text = TextWindow.GetText(false); return; case '*': if (this.StyleIs(XmlDocCommentStyle.Delimited) && TextWindow.PeekChar(1) == '/') { // we're at the end of the comment, but don't lex it yet. info.StringValue = info.Text = TextWindow.GetText(false); return; } goto default; case ']': if (TextWindow.PeekChar(1) == ']' && TextWindow.PeekChar(2) == '>') { info.StringValue = info.Text = TextWindow.GetText(false); return; } goto default; default: if (SyntaxFacts.IsNewLine(ch)) { goto case '\n'; } TextWindow.AdvanceChar(); break; } } } /// <summary> /// Lexer entry point for LexMode.XmlElementTag /// </summary> private SyntaxToken LexXmlElementTagToken() { TokenInfo tagInfo = default(TokenInfo); SyntaxListBuilder leading = null; this.LexXmlDocCommentLeadingTriviaWithWhitespace(ref leading); this.Start(); this.ScanXmlElementTagToken(ref tagInfo); var errors = this.GetErrors(GetFullWidth(leading)); // PERF: De-dupe common XML element tags if (errors == null && tagInfo.ContextualKind == SyntaxKind.None && tagInfo.Kind == SyntaxKind.IdentifierToken) { SyntaxToken token = DocumentationCommentXmlTokens.LookupToken(tagInfo.Text, leading); if (token != null) { return token; } } return Create(ref tagInfo, leading, null, errors); } private bool ScanXmlElementTagToken(ref TokenInfo info) { char ch; Debug.Assert(!this.LocationIs(XmlDocCommentLocation.Start)); Debug.Assert(!this.LocationIs(XmlDocCommentLocation.Exterior)); if (this.LocationIs(XmlDocCommentLocation.End)) { info.Kind = SyntaxKind.EndOfDocumentationCommentToken; return true; } switch (ch = TextWindow.PeekChar()) { case '<': this.ScanXmlTagStart(ref info); break; case '>': TextWindow.AdvanceChar(); info.Kind = SyntaxKind.GreaterThanToken; break; case '/': if (TextWindow.PeekChar(1) == '>') { TextWindow.AdvanceChar(2); info.Kind = SyntaxKind.SlashGreaterThanToken; break; } goto default; case '"': TextWindow.AdvanceChar(); info.Kind = SyntaxKind.DoubleQuoteToken; break; case '\'': TextWindow.AdvanceChar(); info.Kind = SyntaxKind.SingleQuoteToken; break; case '=': TextWindow.AdvanceChar(); info.Kind = SyntaxKind.EqualsToken; break; case ':': TextWindow.AdvanceChar(); info.Kind = SyntaxKind.ColonToken; break; case '\r': case '\n': // Assert? break; case SlidingTextWindow.InvalidCharacter: if (!TextWindow.IsReallyAtEnd()) { goto default; } info.Kind = SyntaxKind.EndOfDocumentationCommentToken; break; case '*': if (this.StyleIs(XmlDocCommentStyle.Delimited) && TextWindow.PeekChar(1) == '/') { // Assert? We should have gotten this in the leading trivia. Debug.Assert(false, "Should have picked up leading indentationTrivia, but didn't."); break; } goto default; default: if (IsXmlNameStartChar(ch)) { this.ScanXmlName(ref info); info.StringValue = info.Text; info.Kind = SyntaxKind.IdentifierToken; } else if (SyntaxFacts.IsWhitespace(ch) || SyntaxFacts.IsNewLine(ch)) { // whitespace! needed to do a better job with trivia Debug.Assert(false, "Should have picked up leading indentationTrivia, but didn't."); } else { TextWindow.AdvanceChar(); info.Kind = SyntaxKind.None; info.StringValue = info.Text = TextWindow.GetText(false); } break; } Debug.Assert(info.Kind != SyntaxKind.None || info.Text != null); return info.Kind != SyntaxKind.None; } private void ScanXmlName(ref TokenInfo info) { int start = TextWindow.Position; while (true) { char ch = TextWindow.PeekChar(); // Important bit of information here: none of \0, \r, \n, and crucially for // delimited comments, * are considered Xml name characters. if (ch != ':' && IsXmlNameChar(ch)) { // Although ':' is a name char, we don't include it in ScanXmlName // since it is its own token. This enables the parser to add structure // to colon-separated names. // TODO: Could put a big switch here for common cases // if this is a perf bottleneck. TextWindow.AdvanceChar(); } else { break; } } info.Text = TextWindow.GetText(start, TextWindow.Position - start, intern: true); } /// <summary> /// Determines whether this Unicode character can start a XMLName. /// </summary> /// <param name="ch">The Unicode character.</param> private static bool IsXmlNameStartChar(char ch) { // TODO: which is the right one? return XmlCharType.IsStartNCNameCharXml4e(ch); // return XmlCharType.IsStartNameSingleChar(ch); } /// <summary> /// Determines if this Unicode character can be part of an XML Name. /// </summary> /// <param name="ch">The Unicode character.</param> private static bool IsXmlNameChar(char ch) { // TODO: which is the right one? return XmlCharType.IsNCNameCharXml4e(ch); //return XmlCharType.IsNameSingleChar(ch); } // TODO: There is a lot of duplication between attribute text, CDATA text, and comment text. // It would be nice to factor them together. /// <summary> /// Lexer entry point for LexMode.XmlAttributeText /// </summary> private SyntaxToken LexXmlAttributeTextToken() { TokenInfo info = default(TokenInfo); SyntaxListBuilder leading = null; this.LexXmlDocCommentLeadingTrivia(ref leading); this.Start(); this.ScanXmlAttributeTextToken(ref info); var errors = this.GetErrors(GetFullWidth(leading)); return Create(ref info, leading, null, errors); } private bool ScanXmlAttributeTextToken(ref TokenInfo info) { Debug.Assert(!this.LocationIs(XmlDocCommentLocation.Start)); Debug.Assert(!this.LocationIs(XmlDocCommentLocation.Exterior)); if (this.LocationIs(XmlDocCommentLocation.End)) { info.Kind = SyntaxKind.EndOfDocumentationCommentToken; return true; } char ch; switch (ch = TextWindow.PeekChar()) { case '"': if (this.ModeIs(LexerMode.XmlAttributeTextDoubleQuote)) { TextWindow.AdvanceChar(); info.Kind = SyntaxKind.DoubleQuoteToken; break; } goto default; case '\'': if (this.ModeIs(LexerMode.XmlAttributeTextQuote)) { TextWindow.AdvanceChar(); info.Kind = SyntaxKind.SingleQuoteToken; break; } goto default; case '&': this.ScanXmlEntity(ref info); info.Kind = SyntaxKind.XmlEntityLiteralToken; break; case '<': TextWindow.AdvanceChar(); info.Kind = SyntaxKind.LessThanToken; break; case '\r': case '\n': ScanXmlTextLiteralNewLineToken(ref info); break; case SlidingTextWindow.InvalidCharacter: if (!TextWindow.IsReallyAtEnd()) { goto default; } info.Kind = SyntaxKind.EndOfDocumentationCommentToken; break; default: if (SyntaxFacts.IsNewLine(ch)) { goto case '\n'; } this.ScanXmlAttributeText(ref info); info.Kind = SyntaxKind.XmlTextLiteralToken; break; } Debug.Assert(info.Kind != SyntaxKind.None || info.Text != null); return info.Kind != SyntaxKind.None; } private void ScanXmlAttributeText(ref TokenInfo info) { while (true) { var ch = TextWindow.PeekChar(); switch (ch) { case '"': if (this.ModeIs(LexerMode.XmlAttributeTextDoubleQuote)) { info.StringValue = info.Text = TextWindow.GetText(false); return; } goto default; case '\'': if (this.ModeIs(LexerMode.XmlAttributeTextQuote)) { info.StringValue = info.Text = TextWindow.GetText(false); return; } goto default; case '&': case '<': case '\r': case '\n': info.StringValue = info.Text = TextWindow.GetText(false); return; case SlidingTextWindow.InvalidCharacter: if (!TextWindow.IsReallyAtEnd()) { goto default; } info.StringValue = info.Text = TextWindow.GetText(false); return; case '*': if (this.StyleIs(XmlDocCommentStyle.Delimited) && TextWindow.PeekChar(1) == '/') { // we're at the end of the comment, but don't lex it yet. info.StringValue = info.Text = TextWindow.GetText(false); return; } goto default; default: if (SyntaxFacts.IsNewLine(ch)) { goto case '\n'; } TextWindow.AdvanceChar(); break; } } } /// <summary> /// Lexer entry point for LexerMode.XmlCharacter. /// </summary> private SyntaxToken LexXmlCharacter() { TokenInfo info = default(TokenInfo); //TODO: Dev11 allows C# comments and newlines in cref trivia (DevDiv #530523). SyntaxListBuilder leading = null; this.LexXmlDocCommentLeadingTriviaWithWhitespace(ref leading); this.Start(); this.ScanXmlCharacter(ref info); var errors = this.GetErrors(GetFullWidth(leading)); return Create(ref info, leading, null, errors); } /// <summary> /// Scan a single XML character (or entity). Assumes that leading trivia has already /// been consumed. /// </summary> private bool ScanXmlCharacter(ref TokenInfo info) { Debug.Assert(!this.LocationIs(XmlDocCommentLocation.Start)); Debug.Assert(!this.LocationIs(XmlDocCommentLocation.Exterior)); if (this.LocationIs(XmlDocCommentLocation.End)) { info.Kind = SyntaxKind.EndOfDocumentationCommentToken; return true; } switch (TextWindow.PeekChar()) { case '&': this.ScanXmlEntity(ref info); info.Kind = SyntaxKind.XmlEntityLiteralToken; break; case SlidingTextWindow.InvalidCharacter: if (!TextWindow.IsReallyAtEnd()) { goto default; } info.Kind = SyntaxKind.EndOfFileToken; break; default: info.Kind = SyntaxKind.XmlTextLiteralToken; info.Text = info.StringValue = TextWindow.NextChar().ToString(); break; } return true; } /// <summary> /// Lexer entry point for LexerMode.XmlCrefQuote, LexerMode.XmlCrefDoubleQuote, /// LexerMode.XmlNameQuote, and LexerMode.XmlNameDoubleQuote. /// </summary> private SyntaxToken LexXmlCrefOrNameToken() { TokenInfo info = default(TokenInfo); //TODO: Dev11 allows C# comments and newlines in cref trivia (DevDiv #530523). SyntaxListBuilder leading = null; this.LexXmlDocCommentLeadingTriviaWithWhitespace(ref leading); this.Start(); this.ScanXmlCrefToken(ref info); var errors = this.GetErrors(GetFullWidth(leading)); return Create(ref info, leading, null, errors); } /// <summary> /// Scan a single cref attribute token. Assumes that leading trivia has already /// been consumed. /// </summary> /// <remarks> /// Within this method, characters that are not XML meta-characters can be seamlessly /// replaced with the corresponding XML entities. /// </remarks> private bool ScanXmlCrefToken(ref TokenInfo info) { Debug.Assert(!this.LocationIs(XmlDocCommentLocation.Start)); Debug.Assert(!this.LocationIs(XmlDocCommentLocation.Exterior)); if (this.LocationIs(XmlDocCommentLocation.End)) { info.Kind = SyntaxKind.EndOfDocumentationCommentToken; return true; } int beforeConsumed = TextWindow.Position; char consumedChar = TextWindow.NextChar(); char consumedSurrogate = SlidingTextWindow.InvalidCharacter; // This first switch is for special characters. If we see the corresponding // XML entities, we DO NOT want to take these actions. switch (consumedChar) { case '"': if (this.ModeIs(LexerMode.XmlCrefDoubleQuote) || this.ModeIs(LexerMode.XmlNameDoubleQuote)) { info.Kind = SyntaxKind.DoubleQuoteToken; return true; } break; case '\'': if (this.ModeIs(LexerMode.XmlCrefQuote) || this.ModeIs(LexerMode.XmlNameQuote)) { info.Kind = SyntaxKind.SingleQuoteToken; return true; } break; case '<': info.Text = TextWindow.GetText(intern: false); this.AddError(XmlParseErrorCode.XML_LessThanInAttributeValue, info.Text); //ErrorCode.WRN_XMLParseError return true; case SlidingTextWindow.InvalidCharacter: if (!TextWindow.IsReallyAtEnd()) { goto default; } info.Kind = SyntaxKind.EndOfDocumentationCommentToken; return true; case '\r': case '\n': TextWindow.Reset(beforeConsumed); ScanXmlTextLiteralNewLineToken(ref info); break; case '&': TextWindow.Reset(beforeConsumed); if (!TextWindow.TryScanXmlEntity(out consumedChar, out consumedSurrogate)) { TextWindow.Reset(beforeConsumed); this.ScanXmlEntity(ref info); info.Kind = SyntaxKind.XmlEntityLiteralToken; return true; } // TryScanXmlEntity advances even when it returns false. break; case '{': consumedChar = '<'; break; case '}': consumedChar = '>'; break; default: if (SyntaxFacts.IsNewLine(consumedChar)) { goto case '\n'; } break; } Debug.Assert(TextWindow.Position > beforeConsumed, "First character or entity has been consumed."); // NOTE: None of these cases will be matched if the surrogate is non-zero (UTF-16 rules) // so we don't need to check for that explicitly. // NOTE: there's a lot of overlap between this switch and the one in // ScanSyntaxToken, but we probably don't want to share code because // ScanSyntaxToken is really hot code and this switch does some extra // work. switch (consumedChar) { //// Single-Character Punctuation/Operators //// case '(': info.Kind = SyntaxKind.OpenParenToken; break; case ')': info.Kind = SyntaxKind.CloseParenToken; break; case '[': info.Kind = SyntaxKind.OpenBracketToken; break; case ']': info.Kind = SyntaxKind.CloseBracketToken; break; case ',': info.Kind = SyntaxKind.CommaToken; break; case '.': if (AdvanceIfMatches('.')) { if (TextWindow.PeekChar() == '.') { // See documentation in ScanSyntaxToken this.AddCrefError(ErrorCode.ERR_UnexpectedCharacter, "."); } info.Kind = SyntaxKind.DotDotToken; } else { info.Kind = SyntaxKind.DotToken; } break; case '?': info.Kind = SyntaxKind.QuestionToken; break; case '&': info.Kind = SyntaxKind.AmpersandToken; break; case '*': info.Kind = SyntaxKind.AsteriskToken; break; case '|': info.Kind = SyntaxKind.BarToken; break; case '^': info.Kind = SyntaxKind.CaretToken; break; case '%': info.Kind = SyntaxKind.PercentToken; break; case '/': info.Kind = SyntaxKind.SlashToken; break; case '~': info.Kind = SyntaxKind.TildeToken; break; // NOTE: Special case - convert curly brackets into angle brackets. case '{': info.Kind = SyntaxKind.LessThanToken; break; case '}': info.Kind = SyntaxKind.GreaterThanToken; break; //// Multi-Character Punctuation/Operators //// case ':': if (AdvanceIfMatches(':')) info.Kind = SyntaxKind.ColonColonToken; else info.Kind = SyntaxKind.ColonToken; break; case '=': if (AdvanceIfMatches('=')) info.Kind = SyntaxKind.EqualsEqualsToken; else info.Kind = SyntaxKind.EqualsToken; break; case '!': if (AdvanceIfMatches('=')) info.Kind = SyntaxKind.ExclamationEqualsToken; else info.Kind = SyntaxKind.ExclamationToken; break; case '>': if (AdvanceIfMatches('=')) info.Kind = SyntaxKind.GreaterThanEqualsToken; // GreaterThanGreaterThanToken is synthesized in the parser since it is ambiguous (with closing nested type parameter lists) // else if (AdvanceIfMatches('>')) info.Kind = SyntaxKind.GreaterThanGreaterThanToken; else info.Kind = SyntaxKind.GreaterThanToken; break; case '<': if (AdvanceIfMatches('=')) info.Kind = SyntaxKind.LessThanEqualsToken; else if (AdvanceIfMatches('<')) info.Kind = SyntaxKind.LessThanLessThanToken; else info.Kind = SyntaxKind.LessThanToken; break; case '+': if (AdvanceIfMatches('+')) info.Kind = SyntaxKind.PlusPlusToken; else info.Kind = SyntaxKind.PlusToken; break; case '-': if (AdvanceIfMatches('-')) info.Kind = SyntaxKind.MinusMinusToken; else info.Kind = SyntaxKind.MinusToken; break; } if (info.Kind != SyntaxKind.None) { Debug.Assert(info.Text == null, "Haven't tried to set it yet."); Debug.Assert(info.StringValue == null, "Haven't tried to set it yet."); string valueText = SyntaxFacts.GetText(info.Kind); string actualText = TextWindow.GetText(intern: false); if (!string.IsNullOrEmpty(valueText) && actualText != valueText) { info.RequiresTextForXmlEntity = true; info.Text = actualText; info.StringValue = valueText; } } else { // If we didn't match any of the above cases, then we either have an // identifier or an unexpected character. TextWindow.Reset(beforeConsumed); if (this.ScanIdentifier(ref info) && info.Text.Length > 0) { // ACASEY: All valid identifier characters should be valid in XML attribute values, // but I don't want to add an assert because XML character classification is expensive. // check to see if it is an actual keyword // NOTE: name attribute values don't respect keywords - everything is an identifier. SyntaxKind keywordKind; if (!InXmlNameAttributeValue && !info.IsVerbatim && !info.HasIdentifierEscapeSequence && _cache.TryGetKeywordKind(info.StringValue, out keywordKind)) { if (SyntaxFacts.IsContextualKeyword(keywordKind)) { info.Kind = SyntaxKind.IdentifierToken; info.ContextualKind = keywordKind; // Don't need to set any special flags to store the original text of an identifier. } else { info.Kind = keywordKind; info.RequiresTextForXmlEntity = info.Text != info.StringValue; } } else { info.ContextualKind = info.Kind = SyntaxKind.IdentifierToken; } } else { if (consumedChar == '@') { // Saw '@', but it wasn't followed by an identifier (otherwise ScanIdentifier would have succeeded). if (TextWindow.PeekChar() == '@') { TextWindow.NextChar(); info.Text = TextWindow.GetText(intern: true); info.StringValue = ""; // Can't be null for an identifier. } else { this.ScanXmlEntity(ref info); } info.Kind = SyntaxKind.IdentifierToken; this.AddError(ErrorCode.ERR_ExpectedVerbatimLiteral); } else if (TextWindow.PeekChar() == '&') { this.ScanXmlEntity(ref info); info.Kind = SyntaxKind.XmlEntityLiteralToken; this.AddCrefError(ErrorCode.ERR_UnexpectedCharacter, info.Text); } else { char bad = TextWindow.NextChar(); info.Text = TextWindow.GetText(intern: false); // If it's valid in XML, then it was unexpected in cref mode. // Otherwise, it's just bad XML. if (MatchesProductionForXmlChar((uint)bad)) { this.AddCrefError(ErrorCode.ERR_UnexpectedCharacter, info.Text); } else { this.AddError(XmlParseErrorCode.XML_InvalidUnicodeChar); } } } } Debug.Assert(info.Kind != SyntaxKind.None || info.Text != null); return info.Kind != SyntaxKind.None; } /// <summary> /// Given a character, advance the input if either the character or the /// corresponding XML entity appears next in the text window. /// </summary> /// <param name="ch"></param> /// <returns></returns> private bool AdvanceIfMatches(char ch) { char peekCh = TextWindow.PeekChar(); if ((peekCh == ch) || (peekCh == '{' && ch == '<') || (peekCh == '}' && ch == '>')) { TextWindow.AdvanceChar(); return true; } if (peekCh == '&') { int pos = TextWindow.Position; char nextChar; char nextSurrogate; if (TextWindow.TryScanXmlEntity(out nextChar, out nextSurrogate) && nextChar == ch && nextSurrogate == SlidingTextWindow.InvalidCharacter) { return true; } TextWindow.Reset(pos); } return false; } /// <summary> /// Convenience property for determining whether we are currently lexing the /// value of a cref or name attribute. /// </summary> private bool InXmlCrefOrNameAttributeValue { get { switch (_mode & LexerMode.MaskLexMode) { case LexerMode.XmlCrefQuote: case LexerMode.XmlCrefDoubleQuote: case LexerMode.XmlNameQuote: case LexerMode.XmlNameDoubleQuote: return true; default: return false; } } } /// <summary> /// Convenience property for determining whether we are currently lexing the /// value of a name attribute. /// </summary> private bool InXmlNameAttributeValue { get { switch (_mode & LexerMode.MaskLexMode) { case LexerMode.XmlNameQuote: case LexerMode.XmlNameDoubleQuote: return true; default: return false; } } } /// <summary> /// Diagnostics that occur within cref attributes need to be /// wrapped with ErrorCode.WRN_ErrorOverride. /// </summary> private void AddCrefError(ErrorCode code, params object[] args) { this.AddCrefError(MakeError(code, args)); } /// <summary> /// Diagnostics that occur within cref attributes need to be /// wrapped with ErrorCode.WRN_ErrorOverride. /// </summary> private void AddCrefError(DiagnosticInfo info) { if (info != null) { this.AddError(ErrorCode.WRN_ErrorOverride, info, info.Code); } } /// <summary> /// Lexer entry point for LexMode.XmlCDataSectionText /// </summary> private SyntaxToken LexXmlCDataSectionTextToken() { TokenInfo info = default(TokenInfo); SyntaxListBuilder leading = null; this.LexXmlDocCommentLeadingTrivia(ref leading); this.Start(); this.ScanXmlCDataSectionTextToken(ref info); var errors = this.GetErrors(GetFullWidth(leading)); return Create(ref info, leading, null, errors); } private bool ScanXmlCDataSectionTextToken(ref TokenInfo info) { char ch; Debug.Assert(!this.LocationIs(XmlDocCommentLocation.Start)); Debug.Assert(!this.LocationIs(XmlDocCommentLocation.Exterior)); if (this.LocationIs(XmlDocCommentLocation.End)) { info.Kind = SyntaxKind.EndOfDocumentationCommentToken; return true; } switch (ch = TextWindow.PeekChar()) { case ']': if (TextWindow.PeekChar(1) == ']' && TextWindow.PeekChar(2) == '>') { TextWindow.AdvanceChar(3); info.Kind = SyntaxKind.XmlCDataEndToken; break; } goto default; case '\r': case '\n': ScanXmlTextLiteralNewLineToken(ref info); break; case SlidingTextWindow.InvalidCharacter: if (!TextWindow.IsReallyAtEnd()) { goto default; } info.Kind = SyntaxKind.EndOfDocumentationCommentToken; break; default: if (SyntaxFacts.IsNewLine(ch)) { goto case '\n'; } this.ScanXmlCDataSectionText(ref info); info.Kind = SyntaxKind.XmlTextLiteralToken; break; } return true; } private void ScanXmlCDataSectionText(ref TokenInfo info) { while (true) { var ch = TextWindow.PeekChar(); switch (ch) { case ']': if (TextWindow.PeekChar(1) == ']' && TextWindow.PeekChar(2) == '>') { info.StringValue = info.Text = TextWindow.GetText(false); return; } goto default; case '\r': case '\n': info.StringValue = info.Text = TextWindow.GetText(false); return; case SlidingTextWindow.InvalidCharacter: if (!TextWindow.IsReallyAtEnd()) { goto default; } info.StringValue = info.Text = TextWindow.GetText(false); return; case '*': if (this.StyleIs(XmlDocCommentStyle.Delimited) && TextWindow.PeekChar(1) == '/') { // we're at the end of the comment, but don't lex it yet. info.StringValue = info.Text = TextWindow.GetText(false); return; } goto default; default: if (SyntaxFacts.IsNewLine(ch)) { goto case '\n'; } TextWindow.AdvanceChar(); break; } } } /// <summary> /// Lexer entry point for LexMode.XmlCommentText /// </summary> private SyntaxToken LexXmlCommentTextToken() { TokenInfo info = default(TokenInfo); SyntaxListBuilder leading = null; this.LexXmlDocCommentLeadingTrivia(ref leading); this.Start(); this.ScanXmlCommentTextToken(ref info); var errors = this.GetErrors(GetFullWidth(leading)); return Create(ref info, leading, null, errors); } private bool ScanXmlCommentTextToken(ref TokenInfo info) { char ch; Debug.Assert(!this.LocationIs(XmlDocCommentLocation.Start)); Debug.Assert(!this.LocationIs(XmlDocCommentLocation.Exterior)); if (this.LocationIs(XmlDocCommentLocation.End)) { info.Kind = SyntaxKind.EndOfDocumentationCommentToken; return true; } switch (ch = TextWindow.PeekChar()) { case '-': if (TextWindow.PeekChar(1) == '-') { if (TextWindow.PeekChar(2) == '>') { TextWindow.AdvanceChar(3); info.Kind = SyntaxKind.XmlCommentEndToken; break; } else { TextWindow.AdvanceChar(2); info.Kind = SyntaxKind.MinusMinusToken; break; } } goto default; case '\r': case '\n': ScanXmlTextLiteralNewLineToken(ref info); break; case SlidingTextWindow.InvalidCharacter: if (!TextWindow.IsReallyAtEnd()) { goto default; } info.Kind = SyntaxKind.EndOfDocumentationCommentToken; break; default: if (SyntaxFacts.IsNewLine(ch)) { goto case '\n'; } this.ScanXmlCommentText(ref info); info.Kind = SyntaxKind.XmlTextLiteralToken; break; } return true; } private void ScanXmlCommentText(ref TokenInfo info) { while (true) { var ch = TextWindow.PeekChar(); switch (ch) { case '-': if (TextWindow.PeekChar(1) == '-') { info.StringValue = info.Text = TextWindow.GetText(false); return; } goto default; case '\r': case '\n': info.StringValue = info.Text = TextWindow.GetText(false); return; case SlidingTextWindow.InvalidCharacter: if (!TextWindow.IsReallyAtEnd()) { goto default; } info.StringValue = info.Text = TextWindow.GetText(false); return; case '*': if (this.StyleIs(XmlDocCommentStyle.Delimited) && TextWindow.PeekChar(1) == '/') { // we're at the end of the comment, but don't lex it yet. info.StringValue = info.Text = TextWindow.GetText(false); return; } goto default; default: if (SyntaxFacts.IsNewLine(ch)) { goto case '\n'; } TextWindow.AdvanceChar(); break; } } } /// <summary> /// Lexer entry point for LexMode.XmlProcessingInstructionText /// </summary> private SyntaxToken LexXmlProcessingInstructionTextToken() { TokenInfo info = default(TokenInfo); SyntaxListBuilder leading = null; this.LexXmlDocCommentLeadingTrivia(ref leading); this.Start(); this.ScanXmlProcessingInstructionTextToken(ref info); var errors = this.GetErrors(GetFullWidth(leading)); return Create(ref info, leading, null, errors); } // CONSIDER: This could easily be merged with ScanXmlCDataSectionTextToken private bool ScanXmlProcessingInstructionTextToken(ref TokenInfo info) { char ch; Debug.Assert(!this.LocationIs(XmlDocCommentLocation.Start)); Debug.Assert(!this.LocationIs(XmlDocCommentLocation.Exterior)); if (this.LocationIs(XmlDocCommentLocation.End)) { info.Kind = SyntaxKind.EndOfDocumentationCommentToken; return true; } switch (ch = TextWindow.PeekChar()) { case '?': if (TextWindow.PeekChar(1) == '>') { TextWindow.AdvanceChar(2); info.Kind = SyntaxKind.XmlProcessingInstructionEndToken; break; } goto default; case '\r': case '\n': ScanXmlTextLiteralNewLineToken(ref info); break; case SlidingTextWindow.InvalidCharacter: if (!TextWindow.IsReallyAtEnd()) { goto default; } info.Kind = SyntaxKind.EndOfDocumentationCommentToken; break; default: if (SyntaxFacts.IsNewLine(ch)) { goto case '\n'; } this.ScanXmlProcessingInstructionText(ref info); info.Kind = SyntaxKind.XmlTextLiteralToken; break; } return true; } // CONSIDER: This could easily be merged with ScanXmlCDataSectionText private void ScanXmlProcessingInstructionText(ref TokenInfo info) { while (true) { var ch = TextWindow.PeekChar(); switch (ch) { case '?': if (TextWindow.PeekChar(1) == '>') { info.StringValue = info.Text = TextWindow.GetText(false); return; } goto default; case '\r': case '\n': info.StringValue = info.Text = TextWindow.GetText(false); return; case SlidingTextWindow.InvalidCharacter: if (!TextWindow.IsReallyAtEnd()) { goto default; } info.StringValue = info.Text = TextWindow.GetText(false); return; case '*': if (this.StyleIs(XmlDocCommentStyle.Delimited) && TextWindow.PeekChar(1) == '/') { // we're at the end of the comment, but don't lex it yet. info.StringValue = info.Text = TextWindow.GetText(false); return; } goto default; default: if (SyntaxFacts.IsNewLine(ch)) { goto case '\n'; } TextWindow.AdvanceChar(); break; } } } /// <summary> /// Collects XML doc comment exterior trivia, and therefore is a no op unless we are in the Start or Exterior of an XML doc comment. /// </summary> /// <param name="trivia">List in which to collect the trivia</param> private void LexXmlDocCommentLeadingTrivia(ref SyntaxListBuilder trivia) { var start = TextWindow.Position; this.Start(); if (this.LocationIs(XmlDocCommentLocation.Start) && this.StyleIs(XmlDocCommentStyle.Delimited)) { // Read the /** that begins an XML doc comment. Since these are recognized only // when the trailing character is not a '*', we wind up in the interior of the // doc comment at the end. if (TextWindow.PeekChar() == '/' && TextWindow.PeekChar(1) == '*' && TextWindow.PeekChar(2) == '*' && TextWindow.PeekChar(3) != '*') { TextWindow.AdvanceChar(3); var text = TextWindow.GetText(true); this.AddTrivia(SyntaxFactory.DocumentationCommentExteriorTrivia(text), ref trivia); this.MutateLocation(XmlDocCommentLocation.Interior); return; } } else if (this.LocationIs(XmlDocCommentLocation.Start) || this.LocationIs(XmlDocCommentLocation.Exterior)) { // We're in the exterior of an XML doc comment and need to eat the beginnings of // lines, for single line and delimited comments. We chew up white space until // a non-whitespace character, and then make the right decision depending on // what kind of comment we're in. while (true) { char ch = TextWindow.PeekChar(); switch (ch) { case ' ': case '\t': case '\v': case '\f': TextWindow.AdvanceChar(); break; case '/': if (this.StyleIs(XmlDocCommentStyle.SingleLine) && TextWindow.PeekChar(1) == '/' && TextWindow.PeekChar(2) == '/' && TextWindow.PeekChar(3) != '/') { TextWindow.AdvanceChar(3); var text = TextWindow.GetText(true); this.AddTrivia(SyntaxFactory.DocumentationCommentExteriorTrivia(text), ref trivia); this.MutateLocation(XmlDocCommentLocation.Interior); return; } goto default; case '*': if (this.StyleIs(XmlDocCommentStyle.Delimited)) { while (TextWindow.PeekChar() == '*' && TextWindow.PeekChar(1) != '/') { TextWindow.AdvanceChar(); } var text = TextWindow.GetText(true); if (!String.IsNullOrEmpty(text)) { this.AddTrivia(SyntaxFactory.DocumentationCommentExteriorTrivia(text), ref trivia); } // This setup ensures that on the final line of a comment, if we have // the string " */", the "*/" part is separated from the whitespace // and therefore recognizable as the end of the comment. if (TextWindow.PeekChar() == '*' && TextWindow.PeekChar(1) == '/') { TextWindow.AdvanceChar(2); this.AddTrivia(SyntaxFactory.DocumentationCommentExteriorTrivia("*/"), ref trivia); this.MutateLocation(XmlDocCommentLocation.End); } else { this.MutateLocation(XmlDocCommentLocation.Interior); } return; } goto default; default: if (SyntaxFacts.IsWhitespace(ch)) { goto case ' '; } // so here we have something else. if this is a single-line xml // doc comment, that means we're on a line that's no longer a doc // comment, so we need to rewind. if we're in a delimited doc comment, // then that means we hit pay dirt and we're back into xml text. if (this.StyleIs(XmlDocCommentStyle.SingleLine)) { TextWindow.Reset(start); this.MutateLocation(XmlDocCommentLocation.End); } else // XmlDocCommentStyle.Delimited { Debug.Assert(this.StyleIs(XmlDocCommentStyle.Delimited)); var text = TextWindow.GetText(true); if (!String.IsNullOrEmpty(text)) this.AddTrivia(SyntaxFactory.DocumentationCommentExteriorTrivia(text), ref trivia); this.MutateLocation(XmlDocCommentLocation.Interior); } return; } } } else if (!this.LocationIs(XmlDocCommentLocation.End) && this.StyleIs(XmlDocCommentStyle.Delimited)) { if (TextWindow.PeekChar() == '*' && TextWindow.PeekChar(1) == '/') { TextWindow.AdvanceChar(2); var text = TextWindow.GetText(true); this.AddTrivia(SyntaxFactory.DocumentationCommentExteriorTrivia(text), ref trivia); this.MutateLocation(XmlDocCommentLocation.End); } } } private void LexXmlDocCommentLeadingTriviaWithWhitespace(ref SyntaxListBuilder trivia) { while (true) { this.LexXmlDocCommentLeadingTrivia(ref trivia); char ch = TextWindow.PeekChar(); if (this.LocationIs(XmlDocCommentLocation.Interior) && (SyntaxFacts.IsWhitespace(ch) || SyntaxFacts.IsNewLine(ch))) { this.LexXmlWhitespaceAndNewLineTrivia(ref trivia); } else { break; } } } /// <summary> /// Collects whitespace and new line trivia for XML doc comments. Does not see XML doc comment exterior trivia, and is a no op unless we are in the interior. /// </summary> /// <param name="trivia">List in which to collect the trivia</param> private void LexXmlWhitespaceAndNewLineTrivia(ref SyntaxListBuilder trivia) { this.Start(); if (this.LocationIs(XmlDocCommentLocation.Interior)) { char ch = TextWindow.PeekChar(); switch (ch) { case ' ': case '\t': // Horizontal tab case '\v': // Vertical Tab case '\f': // Form-feed this.AddTrivia(this.ScanWhitespace(), ref trivia); break; case '\r': case '\n': this.AddTrivia(this.ScanEndOfLine(), ref trivia); this.MutateLocation(XmlDocCommentLocation.Exterior); return; case '*': if (this.StyleIs(XmlDocCommentStyle.Delimited) && TextWindow.PeekChar(1) == '/') { // we're at the end of the comment, but don't add as trivia here. return; } goto default; default: if (SyntaxFacts.IsWhitespace(ch)) { goto case ' '; } if (SyntaxFacts.IsNewLine(ch)) { goto case '\n'; } return; } } } } }
-1
dotnet/roslyn
55,132
Support lambda expressions and method groups as `var` initializers
```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
cston
2021-07-27T03:12:21Z
2021-07-27T18:26:42Z
61a565cfcd777158cb6354351436aff997ad7bf6
5840335153dcca42570a853cdacd06d660fe9596
Support lambda expressions and method groups as `var` initializers. ```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
./src/Features/CSharp/Portable/Completion/CompletionProviders/PropertySubPatternCompletionProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Composition; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Completion; using Microsoft.CodeAnalysis.Completion.Providers; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Completion.Providers { [ExportCompletionProvider(nameof(PropertySubpatternCompletionProvider), LanguageNames.CSharp)] [ExtensionOrder(After = nameof(InternalsVisibleToCompletionProvider))] [Shared] internal class PropertySubpatternCompletionProvider : LSPCompletionProvider { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public PropertySubpatternCompletionProvider() { } // Examples: // is { $$ // is { Property.$$ // is { Property.Property2.$$ public override async Task ProvideCompletionsAsync(CompletionContext context) { var document = context.Document; var position = context.Position; var cancellationToken = context.CancellationToken; var tree = await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); // For `is { Property.Property2.$$`, we get: // - the property pattern clause `{ ... }` and // - the member access before the last dot `Property.Property2` (or null) var (propertyPatternClause, memberAccess) = TryGetPropertyPatternClause(tree, position, cancellationToken); if (propertyPatternClause is null) { return; } var semanticModel = await document.ReuseExistingSpeculativeModelAsync(position, cancellationToken).ConfigureAwait(false); var propertyPatternType = semanticModel.GetTypeInfo((PatternSyntax)propertyPatternClause.Parent, cancellationToken).ConvertedType; // For simple property patterns, the type we want is the "input type" of the property pattern, ie the type of `c` in `c is { $$ }`. // For extended property patterns, we get the type by following the chain of members that we have so far, ie // the type of `c.Property` for `c is { Property.$$ }` and the type of `c.Property1.Property2` for `c is { Property1.Property2.$$ }`. var type = GetMemberAccessType(propertyPatternType, memberAccess, document, semanticModel, position); if (type is null) { return; } // Find the members that can be tested. var members = GetCandidatePropertiesAndFields(document, semanticModel, position, type); members = members.WhereAsArray(m => m.IsEditorBrowsable(document.ShouldHideAdvancedMembers(), semanticModel.Compilation)); if (memberAccess is null) { // Filter out those members that have already been typed as simple (not extended) properties var alreadyTestedMembers = new HashSet<string>(propertyPatternClause.Subpatterns.Select( p => p.NameColon?.Name.Identifier.ValueText).Where(s => !string.IsNullOrEmpty(s))); members = members.WhereAsArray(m => !alreadyTestedMembers.Contains(m.Name)); } foreach (var member in members) { const string ColonString = ":"; context.AddItem(SymbolCompletionItem.CreateWithSymbolId( displayText: member.Name.EscapeIdentifier(), displayTextSuffix: ColonString, insertionText: null, symbols: ImmutableArray.Create(member), contextPosition: context.Position, rules: s_rules)); } return; // We have to figure out the type of the extended property ourselves, because // the semantic model could not provide the answer we want in incomplete syntax: // `c is { X. }` static ITypeSymbol GetMemberAccessType(ITypeSymbol type, ExpressionSyntax expression, Document document, SemanticModel semanticModel, int position) { if (expression is null) { return type; } else if (expression is MemberAccessExpressionSyntax memberAccess) { type = GetMemberAccessType(type, memberAccess.Expression, document, semanticModel, position); return GetMemberType(type, name: memberAccess.Name.Identifier.ValueText, document, semanticModel, position); } else if (expression is IdentifierNameSyntax identifier) { return GetMemberType(type, name: identifier.Identifier.ValueText, document, semanticModel, position); } throw ExceptionUtilities.Unreachable; } static ITypeSymbol GetMemberType(ITypeSymbol type, string name, Document document, SemanticModel semanticModel, int position) { var members = GetCandidatePropertiesAndFields(document, semanticModel, position, type); var matches = members.WhereAsArray(m => m.Name == name); if (matches.Length != 1) { return null; } return matches[0] switch { IPropertySymbol property => property.Type, IFieldSymbol field => field.Type, _ => throw ExceptionUtilities.Unreachable, }; } static ImmutableArray<ISymbol> GetCandidatePropertiesAndFields(Document document, SemanticModel semanticModel, int position, ITypeSymbol type) { var members = semanticModel.LookupSymbols(position, type); return members.WhereAsArray(m => m.CanBeReferencedByName && IsFieldOrReadableProperty(m) && !m.IsImplicitlyDeclared && !m.IsStatic); } } private static bool IsFieldOrReadableProperty(ISymbol symbol) { if (symbol.IsKind(SymbolKind.Field)) { return true; } if (symbol.IsKind(SymbolKind.Property) && !((IPropertySymbol)symbol).IsWriteOnly) { return true; } return false; } protected override Task<CompletionDescription> GetDescriptionWorkerAsync(Document document, CompletionItem item, CancellationToken cancellationToken) => SymbolCompletionItem.GetDescriptionAsync(item, document, cancellationToken); private static readonly CompletionItemRules s_rules = CompletionItemRules.Create(enterKeyRule: EnterKeyRule.Never); public override bool IsInsertionTrigger(SourceText text, int characterPosition, OptionSet options) => CompletionUtilities.IsTriggerCharacter(text, characterPosition, options) || text[characterPosition] == ' '; public override ImmutableHashSet<char> TriggerCharacters { get; } = CompletionUtilities.CommonTriggerCharacters.Add(' '); private static (PropertyPatternClauseSyntax, ExpressionSyntax) TryGetPropertyPatternClause(SyntaxTree tree, int position, CancellationToken cancellationToken) { if (tree.IsInNonUserCode(position, cancellationToken)) { return default; } var token = tree.FindTokenOnLeftOfPosition(position, cancellationToken); token = token.GetPreviousTokenIfTouchingWord(position); if (token.IsKind(SyntaxKind.CommaToken, SyntaxKind.OpenBraceToken)) { return token.Parent is PropertyPatternClauseSyntax { Parent: PatternSyntax } propertyPatternClause ? (propertyPatternClause, null) : default; } if (token.IsKind(SyntaxKind.DotToken)) { // is { Property1.$$ } // is { Property1.$$ Property1.Property2: ... } // typing before an existing pattern return token.Parent is MemberAccessExpressionSyntax memberAccess && IsExtendedPropertyPattern(memberAccess, out var propertyPatternClause) ? (propertyPatternClause, memberAccess.Expression) : default; } return default; bool IsExtendedPropertyPattern(MemberAccessExpressionSyntax memberAccess, out PropertyPatternClauseSyntax propertyPatternClause) { while (memberAccess.Parent.IsKind(SyntaxKind.SimpleMemberAccessExpression)) { memberAccess = (MemberAccessExpressionSyntax)memberAccess.Parent; } if (memberAccess is { Parent: { Parent: SubpatternSyntax { Parent: PropertyPatternClauseSyntax found } } }) { propertyPatternClause = found; return true; } propertyPatternClause = null; 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.Collections.Immutable; using System.Composition; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Completion; using Microsoft.CodeAnalysis.Completion.Providers; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Completion.Providers { [ExportCompletionProvider(nameof(PropertySubpatternCompletionProvider), LanguageNames.CSharp)] [ExtensionOrder(After = nameof(InternalsVisibleToCompletionProvider))] [Shared] internal class PropertySubpatternCompletionProvider : LSPCompletionProvider { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public PropertySubpatternCompletionProvider() { } // Examples: // is { $$ // is { Property.$$ // is { Property.Property2.$$ public override async Task ProvideCompletionsAsync(CompletionContext context) { var document = context.Document; var position = context.Position; var cancellationToken = context.CancellationToken; var tree = await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); // For `is { Property.Property2.$$`, we get: // - the property pattern clause `{ ... }` and // - the member access before the last dot `Property.Property2` (or null) var (propertyPatternClause, memberAccess) = TryGetPropertyPatternClause(tree, position, cancellationToken); if (propertyPatternClause is null) { return; } var semanticModel = await document.ReuseExistingSpeculativeModelAsync(position, cancellationToken).ConfigureAwait(false); var propertyPatternType = semanticModel.GetTypeInfo((PatternSyntax)propertyPatternClause.Parent, cancellationToken).ConvertedType; // For simple property patterns, the type we want is the "input type" of the property pattern, ie the type of `c` in `c is { $$ }`. // For extended property patterns, we get the type by following the chain of members that we have so far, ie // the type of `c.Property` for `c is { Property.$$ }` and the type of `c.Property1.Property2` for `c is { Property1.Property2.$$ }`. var type = GetMemberAccessType(propertyPatternType, memberAccess, document, semanticModel, position); if (type is null) { return; } // Find the members that can be tested. var members = GetCandidatePropertiesAndFields(document, semanticModel, position, type); members = members.WhereAsArray(m => m.IsEditorBrowsable(document.ShouldHideAdvancedMembers(), semanticModel.Compilation)); if (memberAccess is null) { // Filter out those members that have already been typed as simple (not extended) properties var alreadyTestedMembers = new HashSet<string>(propertyPatternClause.Subpatterns.Select( p => p.NameColon?.Name.Identifier.ValueText).Where(s => !string.IsNullOrEmpty(s))); members = members.WhereAsArray(m => !alreadyTestedMembers.Contains(m.Name)); } foreach (var member in members) { const string ColonString = ":"; context.AddItem(SymbolCompletionItem.CreateWithSymbolId( displayText: member.Name.EscapeIdentifier(), displayTextSuffix: ColonString, insertionText: null, symbols: ImmutableArray.Create(member), contextPosition: context.Position, rules: s_rules)); } return; // We have to figure out the type of the extended property ourselves, because // the semantic model could not provide the answer we want in incomplete syntax: // `c is { X. }` static ITypeSymbol GetMemberAccessType(ITypeSymbol type, ExpressionSyntax expression, Document document, SemanticModel semanticModel, int position) { if (expression is null) { return type; } else if (expression is MemberAccessExpressionSyntax memberAccess) { type = GetMemberAccessType(type, memberAccess.Expression, document, semanticModel, position); return GetMemberType(type, name: memberAccess.Name.Identifier.ValueText, document, semanticModel, position); } else if (expression is IdentifierNameSyntax identifier) { return GetMemberType(type, name: identifier.Identifier.ValueText, document, semanticModel, position); } throw ExceptionUtilities.Unreachable; } static ITypeSymbol GetMemberType(ITypeSymbol type, string name, Document document, SemanticModel semanticModel, int position) { var members = GetCandidatePropertiesAndFields(document, semanticModel, position, type); var matches = members.WhereAsArray(m => m.Name == name); if (matches.Length != 1) { return null; } return matches[0] switch { IPropertySymbol property => property.Type, IFieldSymbol field => field.Type, _ => throw ExceptionUtilities.Unreachable, }; } static ImmutableArray<ISymbol> GetCandidatePropertiesAndFields(Document document, SemanticModel semanticModel, int position, ITypeSymbol type) { var members = semanticModel.LookupSymbols(position, type); return members.WhereAsArray(m => m.CanBeReferencedByName && IsFieldOrReadableProperty(m) && !m.IsImplicitlyDeclared && !m.IsStatic); } } private static bool IsFieldOrReadableProperty(ISymbol symbol) { if (symbol.IsKind(SymbolKind.Field)) { return true; } if (symbol.IsKind(SymbolKind.Property) && !((IPropertySymbol)symbol).IsWriteOnly) { return true; } return false; } protected override Task<CompletionDescription> GetDescriptionWorkerAsync(Document document, CompletionItem item, CancellationToken cancellationToken) => SymbolCompletionItem.GetDescriptionAsync(item, document, cancellationToken); private static readonly CompletionItemRules s_rules = CompletionItemRules.Create(enterKeyRule: EnterKeyRule.Never); public override bool IsInsertionTrigger(SourceText text, int characterPosition, OptionSet options) => CompletionUtilities.IsTriggerCharacter(text, characterPosition, options) || text[characterPosition] == ' '; public override ImmutableHashSet<char> TriggerCharacters { get; } = CompletionUtilities.CommonTriggerCharacters.Add(' '); private static (PropertyPatternClauseSyntax, ExpressionSyntax) TryGetPropertyPatternClause(SyntaxTree tree, int position, CancellationToken cancellationToken) { if (tree.IsInNonUserCode(position, cancellationToken)) { return default; } var token = tree.FindTokenOnLeftOfPosition(position, cancellationToken); token = token.GetPreviousTokenIfTouchingWord(position); if (token.IsKind(SyntaxKind.CommaToken, SyntaxKind.OpenBraceToken)) { return token.Parent is PropertyPatternClauseSyntax { Parent: PatternSyntax } propertyPatternClause ? (propertyPatternClause, null) : default; } if (token.IsKind(SyntaxKind.DotToken)) { // is { Property1.$$ } // is { Property1.$$ Property1.Property2: ... } // typing before an existing pattern return token.Parent is MemberAccessExpressionSyntax memberAccess && IsExtendedPropertyPattern(memberAccess, out var propertyPatternClause) ? (propertyPatternClause, memberAccess.Expression) : default; } return default; bool IsExtendedPropertyPattern(MemberAccessExpressionSyntax memberAccess, out PropertyPatternClauseSyntax propertyPatternClause) { while (memberAccess.Parent.IsKind(SyntaxKind.SimpleMemberAccessExpression)) { memberAccess = (MemberAccessExpressionSyntax)memberAccess.Parent; } if (memberAccess is { Parent: { Parent: SubpatternSyntax { Parent: PropertyPatternClauseSyntax found } } }) { propertyPatternClause = found; return true; } propertyPatternClause = null; return false; } } } }
-1
dotnet/roslyn
55,132
Support lambda expressions and method groups as `var` initializers
```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
cston
2021-07-27T03:12:21Z
2021-07-27T18:26:42Z
61a565cfcd777158cb6354351436aff997ad7bf6
5840335153dcca42570a853cdacd06d660fe9596
Support lambda expressions and method groups as `var` initializers. ```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Extensions/SyntaxTriviaListExtensions.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; namespace Microsoft.CodeAnalysis.Shared.Extensions { internal static class SyntaxTriviaListExtensions { public static SyntaxTrivia? FirstOrNull(this SyntaxTriviaList triviaList, Func<SyntaxTrivia, bool> predicate) { foreach (var trivia in triviaList) { if (predicate(trivia)) { return trivia; } } return null; } public static SyntaxTrivia LastOrDefault(this SyntaxTriviaList triviaList) => triviaList.Any() ? triviaList.Last() : default; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; namespace Microsoft.CodeAnalysis.Shared.Extensions { internal static class SyntaxTriviaListExtensions { public static SyntaxTrivia? FirstOrNull(this SyntaxTriviaList triviaList, Func<SyntaxTrivia, bool> predicate) { foreach (var trivia in triviaList) { if (predicate(trivia)) { return trivia; } } return null; } public static SyntaxTrivia LastOrDefault(this SyntaxTriviaList triviaList) => triviaList.Any() ? triviaList.Last() : default; } }
-1
dotnet/roslyn
55,132
Support lambda expressions and method groups as `var` initializers
```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
cston
2021-07-27T03:12:21Z
2021-07-27T18:26:42Z
61a565cfcd777158cb6354351436aff997ad7bf6
5840335153dcca42570a853cdacd06d660fe9596
Support lambda expressions and method groups as `var` initializers. ```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
./src/Compilers/Core/Portable/Emit/EditAndContinue/EncLocalInfo.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Diagnostics; using Microsoft.CodeAnalysis.CodeGen; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Emit { [DebuggerDisplay("{GetDebuggerDisplay(), nq}")] internal readonly struct EncLocalInfo : IEquatable<EncLocalInfo> { public readonly LocalSlotDebugInfo SlotInfo; public readonly Cci.ITypeReference? Type; public readonly LocalSlotConstraints Constraints; public readonly byte[]? Signature; public readonly bool IsUnused; public EncLocalInfo(byte[] signature) { Debug.Assert(signature.Length > 0); SlotInfo = new LocalSlotDebugInfo(SynthesizedLocalKind.EmitterTemp, LocalDebugId.None); Type = null; Constraints = LocalSlotConstraints.None; Signature = signature; IsUnused = true; } public EncLocalInfo(LocalSlotDebugInfo slotInfo, Cci.ITypeReference type, LocalSlotConstraints constraints, byte[]? signature) { SlotInfo = slotInfo; Type = type; Constraints = constraints; Signature = signature; IsUnused = false; } public bool IsDefault => Type is null && Signature is null; public bool Equals(EncLocalInfo other) { return SlotInfo.Equals(other.SlotInfo) && Cci.SymbolEquivalentEqualityComparer.Instance.Equals(Type, other.Type) && Constraints == other.Constraints && IsUnused == other.IsUnused; } public override bool Equals(object? obj) => obj is EncLocalInfo info && Equals(info); public override int GetHashCode() { Debug.Assert(Type != null); return Hash.Combine(SlotInfo.GetHashCode(), Hash.Combine(Cci.SymbolEquivalentEqualityComparer.Instance.GetHashCode(Type), Hash.Combine((int)Constraints, Hash.Combine(IsUnused, 0)))); } private string GetDebuggerDisplay() { if (IsDefault) { return "[default]"; } if (IsUnused) { return "[invalid]"; } return string.Format("[Id={0}, SynthesizedKind={1}, Type={2}, Constraints={3}, Sig={4}]", SlotInfo.Id, SlotInfo.SynthesizedKind, Type, Constraints, (Signature != null) ? BitConverter.ToString(Signature) : "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.Diagnostics; using Microsoft.CodeAnalysis.CodeGen; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Emit { [DebuggerDisplay("{GetDebuggerDisplay(), nq}")] internal readonly struct EncLocalInfo : IEquatable<EncLocalInfo> { public readonly LocalSlotDebugInfo SlotInfo; public readonly Cci.ITypeReference? Type; public readonly LocalSlotConstraints Constraints; public readonly byte[]? Signature; public readonly bool IsUnused; public EncLocalInfo(byte[] signature) { Debug.Assert(signature.Length > 0); SlotInfo = new LocalSlotDebugInfo(SynthesizedLocalKind.EmitterTemp, LocalDebugId.None); Type = null; Constraints = LocalSlotConstraints.None; Signature = signature; IsUnused = true; } public EncLocalInfo(LocalSlotDebugInfo slotInfo, Cci.ITypeReference type, LocalSlotConstraints constraints, byte[]? signature) { SlotInfo = slotInfo; Type = type; Constraints = constraints; Signature = signature; IsUnused = false; } public bool IsDefault => Type is null && Signature is null; public bool Equals(EncLocalInfo other) { return SlotInfo.Equals(other.SlotInfo) && Cci.SymbolEquivalentEqualityComparer.Instance.Equals(Type, other.Type) && Constraints == other.Constraints && IsUnused == other.IsUnused; } public override bool Equals(object? obj) => obj is EncLocalInfo info && Equals(info); public override int GetHashCode() { Debug.Assert(Type != null); return Hash.Combine(SlotInfo.GetHashCode(), Hash.Combine(Cci.SymbolEquivalentEqualityComparer.Instance.GetHashCode(Type), Hash.Combine((int)Constraints, Hash.Combine(IsUnused, 0)))); } private string GetDebuggerDisplay() { if (IsDefault) { return "[default]"; } if (IsUnused) { return "[invalid]"; } return string.Format("[Id={0}, SynthesizedKind={1}, Type={2}, Constraints={3}, Sig={4}]", SlotInfo.Id, SlotInfo.SynthesizedKind, Type, Constraints, (Signature != null) ? BitConverter.ToString(Signature) : "null"); } } }
-1
dotnet/roslyn
55,132
Support lambda expressions and method groups as `var` initializers
```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
cston
2021-07-27T03:12:21Z
2021-07-27T18:26:42Z
61a565cfcd777158cb6354351436aff997ad7bf6
5840335153dcca42570a853cdacd06d660fe9596
Support lambda expressions and method groups as `var` initializers. ```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
./src/EditorFeatures/Core/ExternalAccess/VSTypeScript/Api/IVSTypeScriptSignatureHelpClassifierProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Classification; namespace Microsoft.CodeAnalysis.ExternalAccess.VSTypeScript.Api { internal interface IVSTypeScriptSignatureHelpClassifierProvider { IClassifier Create(ITextBuffer textBuffer, ClassificationTypeMap typeMap); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Classification; namespace Microsoft.CodeAnalysis.ExternalAccess.VSTypeScript.Api { internal interface IVSTypeScriptSignatureHelpClassifierProvider { IClassifier Create(ITextBuffer textBuffer, ClassificationTypeMap typeMap); } }
-1
dotnet/roslyn
55,132
Support lambda expressions and method groups as `var` initializers
```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
cston
2021-07-27T03:12:21Z
2021-07-27T18:26:42Z
61a565cfcd777158cb6354351436aff997ad7bf6
5840335153dcca42570a853cdacd06d660fe9596
Support lambda expressions and method groups as `var` initializers. ```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
./src/Analyzers/CSharp/Tests/NamingStyles/NamingStylesTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.CodeFixes; using Microsoft.CodeAnalysis.CodeFixes.NamingStyles; using Microsoft.CodeAnalysis.CSharp.Diagnostics.NamingStyles; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.UnitTests.Diagnostics.NamingStyles; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; using Xunit.Abstractions; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics.NamingStyles { public class NamingStylesTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest { public NamingStylesTests(ITestOutputHelper logger) : base(logger) { } private static readonly NamingStylesTestOptionSets s_options = new NamingStylesTestOptionSets(LanguageNames.CSharp); internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace) => (new CSharpNamingStyleDiagnosticAnalyzer(), new NamingStyleCodeFixProvider()); protected override TestComposition GetComposition() => base.GetComposition().AddParts(typeof(TestSymbolRenamedCodeActionOperationFactoryWorkspaceService)); [Fact, Trait(Traits.Feature, Traits.Features.NamingStyle)] public async Task TestPascalCaseClass_CorrectName() { await TestMissingInRegularAndScriptAsync( @"class [|C|] { }", new TestParameters(options: s_options.ClassNamesArePascalCase)); } [Fact, Trait(Traits.Feature, Traits.Features.NamingStyle)] public async Task TestPascalCaseClass_NameGetsCapitalized() { await TestInRegularAndScriptAsync( @"class [|c|] { }", @"class C { }", options: s_options.ClassNamesArePascalCase); } [Theory, Trait(Traits.Feature, Traits.Features.NamingStyle)] [InlineData("M_bar", "bar")] [InlineData("S_bar", "bar")] [InlineData("T_bar", "bar")] [InlineData("_Bar", "bar")] [InlineData("__Bar", "bar")] [InlineData("M_s__t_Bar", "bar")] [InlineData("m_bar", "bar")] [InlineData("s_bar", "bar")] [InlineData("t_bar", "bar")] [InlineData("_bar", "bar")] [InlineData("__bar", "bar")] [InlineData("m_s__t_Bar", "bar")] // Special cases to ensure empty identifiers are not produced [InlineData("M_", "m_")] [InlineData("M__", "_")] [InlineData("S_", "s_")] [InlineData("T_", "t_")] [InlineData("M_S__T_", "t_")] public async Task TestCamelCaseField_PrefixGetsStripped(string fieldName, string correctedName) { await TestInRegularAndScriptAsync( $@"class C {{ int [|{fieldName}|]; }}", $@"class C {{ int [|{correctedName}|]; }}", options: s_options.FieldNamesAreCamelCase); } [Theory, Trait(Traits.Feature, Traits.Features.NamingStyle)] [InlineData("M_bar", "_bar")] [InlineData("S_bar", "_bar")] [InlineData("T_bar", "_bar")] [InlineData("_Bar", "_bar")] [InlineData("__Bar", "_bar")] [InlineData("M_s__t_Bar", "_bar")] [InlineData("m_bar", "_bar")] [InlineData("s_bar", "_bar")] [InlineData("t_bar", "_bar")] [InlineData("bar", "_bar")] [InlineData("__bar", "_bar")] [InlineData("__s_bar", "_bar")] [InlineData("m_s__t_Bar", "_bar")] // Special cases to ensure empty identifiers are not produced [InlineData("M_", "_m_")] [InlineData("M__", "_")] [InlineData("S_", "_s_")] [InlineData("T_", "_t_")] [InlineData("M_S__T_", "_t_")] public async Task TestCamelCaseField_PrefixGetsStrippedBeforeAddition(string fieldName, string correctedName) { await TestInRegularAndScriptAsync( $@"class C {{ int [|{fieldName}|]; }}", $@"class C {{ int [|{correctedName}|]; }}", options: s_options.FieldNamesAreCamelCaseWithUnderscorePrefix); } [Fact, Trait(Traits.Feature, Traits.Features.NamingStyle)] public async Task TestPascalCaseMethod_CorrectName() { await TestMissingInRegularAndScriptAsync( @"class C { void [|M|]() { } }", new TestParameters(options: s_options.MethodNamesArePascalCase)); } [Theory, Trait(Traits.Feature, Traits.Features.NamingStyle)] [InlineData("")] [InlineData("public")] [InlineData("protected")] [InlineData("internal")] [InlineData("protected internal")] [InlineData("private")] [InlineData("protected private")] [WorkItem(20907, "https://github.com/dotnet/roslyn/issues/20907")] public async Task TestPascalCaseMethod_NoneAndDefaultAccessibilities(string accessibility) { await TestMissingInRegularAndScriptAsync( $@"class C {{ {accessibility} void [|m|]() {{ }} }}", new TestParameters(options: s_options.MethodNamesWithAccessibilityArePascalCase(ImmutableArray<Accessibility>.Empty))); await TestInRegularAndScriptAsync( $@"class C {{ {accessibility} void [|m|]() {{ }} }}", $@"class C {{ {accessibility} void M() {{ }} }}", options: s_options.MethodNamesWithAccessibilityArePascalCase(accessibilities: default)); } [Theory, Trait(Traits.Feature, Traits.Features.NamingStyle)] [InlineData("} namespace [|c2|] {", "} namespace C2 {")] [InlineData("class [|c2|] { }", "class C2 { }")] [InlineData("struct [|c2|] { }", "struct C2 { }")] [InlineData("interface [|c2|] { }", "interface C2 { }")] [InlineData("delegate void [|c2|]();", "delegate void C2();")] [InlineData("enum [|c2|] { }", "enum C2 { }")] [InlineData("class M<[|t|]> {}", "class M<T> {}")] [InlineData("void M<[|t|]>() {}", "void M<T>() {}")] [InlineData("int [|m|] { get; }", "int M { get; }")] [InlineData("void [|m|]() {}", "void M() {}")] [InlineData("void Outer() { void [|m|]() {} }", "void Outer() { void M() {} }")] [InlineData("int [|m|];", "int M;")] [InlineData("event System.EventHandler [|m|];", "event System.EventHandler M;")] [InlineData("void Outer(int [|m|]) {}", "void Outer(int M) {}")] [InlineData("void Outer() { int [|m|]; }", "void Outer() { int M; }")] [WorkItem(20907, "https://github.com/dotnet/roslyn/issues/20907")] public async Task TestPascalCaseSymbol_NoneAndDefaultSymbolKinds(string camelCaseSymbol, string pascalCaseSymbol) { await TestMissingInRegularAndScriptAsync( $@"class C {{ {camelCaseSymbol} }}", new TestParameters(options: s_options.SymbolKindsArePascalCaseEmpty())); await TestInRegularAndScriptAsync( $@"class C {{ {camelCaseSymbol} }}", $@"class C {{ {pascalCaseSymbol} }}", options: s_options.SymbolKindsArePascalCase(symbolKinds: default)); } [Theory, Trait(Traits.Feature, Traits.Features.NamingStyle)] [InlineData("} namespace [|c2|] {", "} namespace C2 {", SymbolKind.Namespace, Accessibility.Public)] [InlineData("class [|c2|] { }", "class C2 { }", TypeKind.Class, Accessibility.Private)] [InlineData("struct [|c2|] { }", "struct C2 { }", TypeKind.Struct, Accessibility.Private)] [InlineData("interface [|c2|] { }", "interface C2 { }", TypeKind.Interface, Accessibility.Private)] [InlineData("delegate void [|c2|]();", "delegate void C2();", TypeKind.Delegate, Accessibility.Private)] [InlineData("enum [|c2|] { }", "enum C2 { }", TypeKind.Enum, Accessibility.Private)] [InlineData("class M<[|t|]> {}", "class M<T> {}", SymbolKind.TypeParameter, Accessibility.Private)] [InlineData("void M<[|t|]>() {}", "void M<T>() {}", SymbolKind.TypeParameter, Accessibility.Private)] [InlineData("int [|m|] { get; }", "int M { get; }", SymbolKind.Property, Accessibility.Private)] [InlineData("void [|m|]() {}", "void M() {}", MethodKind.Ordinary, Accessibility.Private)] [InlineData("void Outer() { void [|m|]() {} }", "void Outer() { void M() {} }", MethodKind.LocalFunction, Accessibility.NotApplicable)] [InlineData("int [|m|];", "int M;", SymbolKind.Field, Accessibility.Private)] [InlineData("event System.EventHandler [|m|];", "event System.EventHandler M;", SymbolKind.Event, Accessibility.Private)] [InlineData("void Outer(int [|m|]) {}", "void Outer(int M) {}", SymbolKind.Parameter, Accessibility.Private)] [InlineData("void Outer() { void Inner(int [|m|]) {} }", "void Outer() { void Inner(int M) {} }", SymbolKind.Parameter, Accessibility.NotApplicable)] [InlineData("void Outer() { System.Action<int> action = [|m|] => {} }", "void Outer() { System.Action<int> action = M => {} }", SymbolKind.Parameter, Accessibility.NotApplicable)] [InlineData("void Outer() { System.Action<int> action = ([|m|]) => {} }", "void Outer() { System.Action<int> action = (M) => {} }", SymbolKind.Parameter, Accessibility.NotApplicable)] [InlineData("void Outer() { System.Action<int> action = (int [|m|]) => {} }", "void Outer() { System.Action<int> action = (int M) => {} }", SymbolKind.Parameter, Accessibility.NotApplicable)] [InlineData("void Outer() { System.Action<int> action = delegate (int [|m|]) {} }", "void Outer() { System.Action<int> action = delegate (int M) {} }", SymbolKind.Parameter, Accessibility.NotApplicable)] [InlineData("void Outer() { int [|m|]; }", "void Outer() { int M; }", SymbolKind.Local, Accessibility.NotApplicable)] [WorkItem(20907, "https://github.com/dotnet/roslyn/issues/20907")] public async Task TestPascalCaseSymbol_ExpectedSymbolAndAccessibility(string camelCaseSymbol, string pascalCaseSymbol, object symbolKind, Accessibility accessibility) { var alternateSymbolKind = TypeKind.Class.Equals(symbolKind) ? TypeKind.Interface : TypeKind.Class; var alternateAccessibility = accessibility == Accessibility.Public ? Accessibility.Protected : Accessibility.Public; // Verify that no diagnostic is reported if the symbol kind is wrong await TestMissingInRegularAndScriptAsync( $@"class C {{ {camelCaseSymbol} }}", new TestParameters(options: s_options.SymbolKindsArePascalCase(alternateSymbolKind))); // Verify that no diagnostic is reported if the accessibility is wrong await TestMissingInRegularAndScriptAsync( $@"class C {{ {camelCaseSymbol} }}", new TestParameters(options: s_options.AccessibilitiesArePascalCase(ImmutableArray.Create(alternateAccessibility)))); await TestInRegularAndScriptAsync( $@"class C {{ {camelCaseSymbol} }}", $@"class C {{ {pascalCaseSymbol} }}", options: s_options.AccessibilitiesArePascalCase(ImmutableArray.Create(accessibility))); } [Fact, Trait(Traits.Feature, Traits.Features.NamingStyle)] public async Task TestPascalCaseMethod_NameGetsCapitalized() { await TestInRegularAndScriptAsync( @"class C { void [|m|]() { } }", @"class C { void M() { } }", options: s_options.MethodNamesArePascalCase); } [Fact, Trait(Traits.Feature, Traits.Features.NamingStyle)] public async Task TestPascalCaseMethod_ConstructorsAreIgnored() { await TestMissingInRegularAndScriptAsync( @"class c { public [|c|]() { } }", new TestParameters(options: s_options.MethodNamesArePascalCase)); } [Fact, Trait(Traits.Feature, Traits.Features.NamingStyle)] public async Task TestPascalCaseMethod_PropertyAccessorsAreIgnored() { await TestMissingInRegularAndScriptAsync( @"class C { public int P { [|get|]; set; } }", new TestParameters(options: s_options.MethodNamesArePascalCase)); } [Fact, Trait(Traits.Feature, Traits.Features.NamingStyle)] public async Task TestPascalCaseMethod_IndexerNameIsIgnored() { await TestMissingInRegularAndScriptAsync( @"class C { public int [|this|][int index] { get { return 1; } } }", new TestParameters(options: s_options.MethodNamesArePascalCase)); } [Fact, Trait(Traits.Feature, Traits.Features.NamingStyle)] public async Task TestPascalCaseMethod_LocalFunctionIsIgnored() { await TestMissingInRegularAndScriptAsync( @"class C { void M() { void [|f|]() { } } }", new TestParameters(options: s_options.MethodNamesArePascalCase)); } [Fact, Trait(Traits.Feature, Traits.Features.NamingStyle)] public async Task TestCamelCaseParameters() { await TestInRegularAndScriptAsync( @"class C { public void M(int [|X|]) { } }", @"class C { public void M(int x) { } }", options: s_options.ParameterNamesAreCamelCase); } [Fact, Trait(Traits.Feature, Traits.Features.NamingStyle)] public async Task TestCamelCaseLocals_LocalDeclaration1() { await TestInRegularAndScriptAsync( @"class C { void M() { int [|X|]; } }", @"class C { void M() { int x; } }", options: s_options.LocalNamesAreCamelCase); } [Fact, Trait(Traits.Feature, Traits.Features.NamingStyle)] public async Task TestCamelCaseLocals_LocalDeclaration2() { await TestInRegularAndScriptAsync( @"class C { void M() { int X, [|Y|] = 0; } }", @"class C { void M() { int X, y = 0; } }", options: s_options.LocalNamesAreCamelCase); } [Fact, Trait(Traits.Feature, Traits.Features.NamingStyle)] public async Task TestCamelCaseLocals_UsingVariable1() { await TestInRegularAndScriptAsync( @"class C { void M() { using (object [|A|] = null) { } } }", @"class C { void M() { using (object a = null) { } } }", options: s_options.LocalNamesAreCamelCase); } [Fact, Trait(Traits.Feature, Traits.Features.NamingStyle)] public async Task TestCamelCaseLocals_UsingVariable2() { await TestInRegularAndScriptAsync( @"class C { void M() { using (object A = null, [|B|] = null) { } } }", @"class C { void M() { using (object A = null, b = null) { } } }", options: s_options.LocalNamesAreCamelCase); } [Fact, Trait(Traits.Feature, Traits.Features.NamingStyle)] public async Task TestCamelCaseLocals_ForVariable1() { await TestInRegularAndScriptAsync( @"class C { void M() { for (int [|I|] = 0, J = 0; I < J; ++I) { } } }", @"class C { void M() { for (int i = 0, J = 0; i < J; ++i) { } } }", options: s_options.LocalNamesAreCamelCase); } [Fact, Trait(Traits.Feature, Traits.Features.NamingStyle)] public async Task TestCamelCaseLocals_ForVariable2() { await TestInRegularAndScriptAsync( @"class C { void M() { for (int I = 0, [|J|] = 0; I < J; ++J) { } } }", @"class C { void M() { for (int I = 0, j = 0; I < j; ++j) { } } }", options: s_options.LocalNamesAreCamelCase); } [Fact, Trait(Traits.Feature, Traits.Features.NamingStyle)] public async Task TestCamelCaseLocals_ForEachVariable() { await TestInRegularAndScriptAsync( @"class C { void M() { foreach (var [|X|] in new string[] { }) { } } }", @"class C { void M() { foreach (var x in new string[] { }) { } } }", options: s_options.LocalNamesAreCamelCase); } [Fact, Trait(Traits.Feature, Traits.Features.NamingStyle)] public async Task TestCamelCaseLocals_CatchVariable() { await TestInRegularAndScriptAsync( @"using System; class C { void M() { try { } catch (Exception [|Exception|]) { } } }", @"using System; class C { void M() { try { } catch (Exception exception) { } } }", options: s_options.LocalNamesAreCamelCase); } [Fact, Trait(Traits.Feature, Traits.Features.NamingStyle)] public async Task TestCamelCaseLocals_CatchWithoutVariableIgnored() { await TestMissingInRegularAndScriptAsync( @"using System; class C { void M() { try { } catch ([|Exception|]) { } } }", new TestParameters(options: s_options.LocalNamesAreCamelCase)); } [Fact, Trait(Traits.Feature, Traits.Features.NamingStyle)] public async Task TestCamelCaseLocals_CatchWithoutDeclarationIgnored() { await TestMissingInRegularAndScriptAsync( @"using System; class C { void M() { try { } [|catch|] { } } }", new TestParameters(options: s_options.LocalNamesAreCamelCase)); } [Fact, Trait(Traits.Feature, Traits.Features.NamingStyle)] public async Task TestCamelCaseLocals_Deconstruction1() { await TestInRegularAndScriptAsync( @"class C { void M() { (int A, (string [|B|], var C)) = (0, (string.Empty, string.Empty)); System.Console.WriteLine(A + B + C); } }", @"class C { void M() { (int A, (string b, var C)) = (0, (string.Empty, string.Empty)); System.Console.WriteLine(A + b + C); } }", options: s_options.LocalNamesAreCamelCase); } [Fact, Trait(Traits.Feature, Traits.Features.NamingStyle)] public async Task TestCamelCaseLocals_Deconstruction2() { await TestInRegularAndScriptAsync( @"class C { void M() { var (A, (B, [|C|])) = (0, (string.Empty, string.Empty)); System.Console.WriteLine(A + B + C); } }", @"class C { void M() { var (A, (B, [|c|])) = (0, (string.Empty, string.Empty)); System.Console.WriteLine(A + B + c); } }", options: s_options.LocalNamesAreCamelCase); } [Fact, Trait(Traits.Feature, Traits.Features.NamingStyle)] public async Task TestCamelCaseLocals_ForEachDeconstruction1() { await TestInRegularAndScriptAsync( @"class C { void M() { foreach ((int A, (string [|B|], var C)) in new[] { (0, (string.Empty, string.Empty)) }) System.Console.WriteLine(A + B + C); } }", @"class C { void M() { foreach ((int A, (string b, var C)) in new[] { (0, (string.Empty, string.Empty)) }) System.Console.WriteLine(A + b + C); } }", options: s_options.LocalNamesAreCamelCase); } [Fact, Trait(Traits.Feature, Traits.Features.NamingStyle)] public async Task TestCamelCaseLocals_ForEachDeconstruction2() { await TestInRegularAndScriptAsync( @"class C { void M() { foreach (var (A, (B, [|C|])) in new[] { (0, (string.Empty, string.Empty)) }) System.Console.WriteLine(A + B + C); } }", @"class C { void M() { foreach (var (A, (B, c)) in new[] { (0, (string.Empty, string.Empty)) }) System.Console.WriteLine(A + B + c); } }", options: s_options.LocalNamesAreCamelCase); } [Fact, Trait(Traits.Feature, Traits.Features.NamingStyle)] public async Task TestCamelCaseLocals_OutVariable() { await TestInRegularAndScriptAsync( @"class C { void M() { if (int.TryParse(string.Empty, out var [|Value|])) System.Console.WriteLine(Value); } }", @"class C { void M() { if (int.TryParse(string.Empty, out var value)) System.Console.WriteLine(value); } }", options: s_options.LocalNamesAreCamelCase); } [Fact, Trait(Traits.Feature, Traits.Features.NamingStyle)] public async Task TestCamelCaseLocals_PatternVariable() { await TestInRegularAndScriptAsync( @"class C { void M() { if (new object() is int [|Value|]) System.Console.WriteLine(Value); } }", @"class C { void M() { if (new object() is int value) System.Console.WriteLine(value); } }", options: s_options.LocalNamesAreCamelCase); } [Fact, Trait(Traits.Feature, Traits.Features.NamingStyle)] public async Task TestCamelCaseLocals_QueryFromClauseIgnored() { // This is an IRangeVariableSymbol, not ILocalSymbol await TestMissingInRegularAndScriptAsync( @"using System.Linq; class C { void M() { var squares = from [|STRING|] in new string[] { } let Number = int.Parse(STRING) select Number * Number; } }", new TestParameters(options: s_options.LocalNamesAreCamelCase)); } [Fact, Trait(Traits.Feature, Traits.Features.NamingStyle)] public async Task TestCamelCaseLocals_QueryLetClauseIgnored() { // This is an IRangeVariableSymbol, not ILocalSymbol await TestMissingInRegularAndScriptAsync( @"using System.Linq; class C { void M() { var squares = from STRING in new string[] { } let [|Number|] = int.Parse(STRING) select Number * Number; } }", new TestParameters(options: s_options.LocalNamesAreCamelCase)); } [Fact, Trait(Traits.Feature, Traits.Features.NamingStyle)] public async Task TestCamelCaseLocals_ParameterIgnored() { await TestMissingInRegularAndScriptAsync( @"class C { void M(int [|X|]) { } }", new TestParameters(options: s_options.LocalNamesAreCamelCase)); } [Fact, Trait(Traits.Feature, Traits.Features.NamingStyle)] public async Task TestCamelCaseLocals_TupleTypeElementNameIgnored1() { await TestMissingInRegularAndScriptAsync( @"class C { void M() { (int [|A|], string B) tuple; } }", new TestParameters(options: s_options.LocalNamesAreCamelCase)); } [Fact, Trait(Traits.Feature, Traits.Features.NamingStyle)] public async Task TestCamelCaseLocals_TupleTypeElementNameIgnored2() { await TestMissingInRegularAndScriptAsync( @"class C { void M() { (int A, (string [|B|], string C)) tuple = (0, (string.Empty, string.Empty)); } }", new TestParameters(options: s_options.LocalNamesAreCamelCase)); } [Fact, Trait(Traits.Feature, Traits.Features.NamingStyle)] public async Task TestCamelCaseLocals_TupleExpressionElementNameIgnored() { await TestMissingInRegularAndScriptAsync( @"class C { void M() { var tuple = ([|A|]: 0, B: 0); } }", new TestParameters(options: s_options.LocalNamesAreCamelCase)); } [Fact, Trait(Traits.Feature, Traits.Features.NamingStyle)] public async Task TestUpperCaseConstants_ConstField() { await TestInRegularAndScriptAsync( @"class C { const int [|field|] = 0; }", @"class C { const int FIELD = 0; }", options: s_options.ConstantsAreUpperCase); } [Fact, Trait(Traits.Feature, Traits.Features.NamingStyle)] public async Task TestUpperCaseConstants_ConstLocal() { await TestInRegularAndScriptAsync( @"class C { void M() { const int local1 = 0, [|local2|] = 0; } }", @"class C { void M() { const int local1 = 0, LOCAL2 = 0; } }", options: s_options.ConstantsAreUpperCase); } [Fact, Trait(Traits.Feature, Traits.Features.NamingStyle)] public async Task TestUpperCaseConstants_NonConstFieldIgnored() { await TestMissingInRegularAndScriptAsync( @"class C { readonly int [|field|] = 0; }", new TestParameters(options: s_options.ConstantsAreUpperCase)); } [Fact, Trait(Traits.Feature, Traits.Features.NamingStyle)] public async Task TestUpperCaseConstants_NonConstLocalIgnored() { await TestMissingInRegularAndScriptAsync( @"class C { void M() { int local1 = 0, [|local2|] = 0; } }", new TestParameters(options: s_options.ConstantsAreUpperCase)); } [Fact, Trait(Traits.Feature, Traits.Features.NamingStyle)] public async Task TestCamelCaseLocalsUpperCaseConstants_ConstLocal() { await TestInRegularAndScriptAsync( @"class C { void M() { const int [|PascalCase|] = 0; } }", @"class C { void M() { const int PASCALCASE = 0; } }", options: s_options.LocalsAreCamelCaseConstantsAreUpperCase); } [Fact, Trait(Traits.Feature, Traits.Features.NamingStyle)] public async Task TestCamelCaseLocalsUpperCaseConstants_NonConstLocal() { await TestInRegularAndScriptAsync( @"class C { void M() { int [|PascalCase|] = 0; } }", @"class C { void M() { int pascalCase = 0; } }", options: s_options.LocalsAreCamelCaseConstantsAreUpperCase); } [Fact, Trait(Traits.Feature, Traits.Features.NamingStyle)] public async Task TestCamelCaseLocalFunctions() { await TestInRegularAndScriptAsync( @"class C { void M() { void [|F|]() { } } }", @"class C { void M() { void f() { } } }", options: s_options.LocalFunctionNamesAreCamelCase); } [Fact, Trait(Traits.Feature, Traits.Features.NamingStyle)] public async Task TestCamelCaseLocalFunctions_MethodIsIgnored() { await TestMissingInRegularAndScriptAsync( @"class C { void [|M|]() { } }", new TestParameters(options: s_options.LocalFunctionNamesAreCamelCase)); } [Fact, Trait(Traits.Feature, Traits.Features.NamingStyle)] public async Task TestAsyncFunctions_AsyncMethod() { await TestInRegularAndScriptAsync( @"class C { async void [|M|]() { } }", @"class C { async void MAsync() { } }", options: s_options.AsyncFunctionNamesEndWithAsync); } [Fact, Trait(Traits.Feature, Traits.Features.NamingStyle)] public async Task TestAsyncFunctions_AsyncLocalFunction() { await TestInRegularAndScriptAsync( @"class C { void M() { async void [|F|]() { } } }", @"class C { void M() { async void FAsync() { } } }", options: s_options.AsyncFunctionNamesEndWithAsync); } [Fact, Trait(Traits.Feature, Traits.Features.NamingStyle)] public async Task TestAsyncFunctions_NonAsyncMethodIgnored() { await TestMissingInRegularAndScriptAsync( @"class C { void [|M|]() { async void F() { } } }", new TestParameters(options: s_options.AsyncFunctionNamesEndWithAsync)); } [Fact, Trait(Traits.Feature, Traits.Features.NamingStyle)] public async Task TestAsyncFunctions_NonAsyncLocalFunctionIgnored() { await TestMissingInRegularAndScriptAsync( @"class C { async void M() { void [|F|]() { } } }", new TestParameters(options: s_options.AsyncFunctionNamesEndWithAsync)); } [Fact, Trait(Traits.Feature, Traits.Features.NamingStyle)] public async Task TestPascalCaseMethod_InInterfaceWithImplicitImplementation() { await TestInRegularAndScriptAsync( @"interface I { void [|m|](); } class C : I { public void m() { } }", @"interface I { void M(); } class C : I { public void M() { } }", options: s_options.MethodNamesArePascalCase); } [Fact, Trait(Traits.Feature, Traits.Features.NamingStyle)] public async Task TestPascalCaseMethod_InInterfaceWithExplicitImplementation() { await TestInRegularAndScriptAsync( @"interface I { void [|m|](); } class C : I { void I.m() { } }", @"interface I { void M(); } class C : I { void I.M() { } }", options: s_options.MethodNamesArePascalCase); } [Fact, Trait(Traits.Feature, Traits.Features.NamingStyle)] public async Task TestPascalCaseMethod_NotInImplicitInterfaceImplementation() { await TestMissingInRegularAndScriptAsync( @"interface I { void m(); } class C : I { public void [|m|]() { } }", new TestParameters(options: s_options.MethodNamesArePascalCase)); } [Fact, Trait(Traits.Feature, Traits.Features.NamingStyle)] public async Task TestPascalCaseMethod_NotInExplicitInterfaceImplementation() { await TestMissingInRegularAndScriptAsync( @"interface I { void m(); } class C : I { void I.[|m|]() { } }", new TestParameters(options: s_options.MethodNamesArePascalCase)); } [Fact, Trait(Traits.Feature, Traits.Features.NamingStyle)] public async Task TestPascalCaseMethod_InAbstractType() { await TestInRegularAndScriptAsync( @" abstract class C { public abstract void [|m|](); } class D : C { public override void m() { } }", @" abstract class C { public abstract void M(); } class D : C { public override void M() { } }", options: s_options.MethodNamesArePascalCase); } [Fact, Trait(Traits.Feature, Traits.Features.NamingStyle)] public async Task TestPascalCaseMethod_NotInAbstractMethodImplementation() { await TestMissingInRegularAndScriptAsync( @" abstract class C { public abstract void m(); } class D : C { public override void [|m|]() { } }", new TestParameters(options: s_options.MethodNamesArePascalCase)); } [Fact, Trait(Traits.Feature, Traits.Features.NamingStyle)] public async Task TestPascalCaseProperty_InInterface() { await TestInRegularAndScriptAsync( @" interface I { int [|p|] { get; set; } } class C : I { public int p { get { return 1; } set { } } }", @" interface I { int P { get; set; } } class C : I { public int P { get { return 1; } set { } } }", options: s_options.PropertyNamesArePascalCase); } [Fact, Trait(Traits.Feature, Traits.Features.NamingStyle)] public async Task TestPascalCaseProperty_NotInImplicitInterfaceImplementation() { await TestMissingInRegularAndScriptAsync( @" interface I { int p { get; set; } } class C : I { public int [|p|] { get { return 1; } set { } } }", new TestParameters(options: s_options.PropertyNamesArePascalCase)); } [Fact, Trait(Traits.Feature, Traits.Features.NamingStyle)] public async Task TestPascalCaseMethod_OverrideInternalMethod() { await TestMissingInRegularAndScriptAsync( @" abstract class C { internal abstract void m(); } class D : C { internal override void [|m|]() { } }", new TestParameters(options: s_options.MethodNamesArePascalCase)); } [Fact, Trait(Traits.Feature, Traits.Features.NamingStyle)] [WorkItem(19106, "https://github.com/dotnet/roslyn/issues/19106")] public async Task TestMissingOnSymbolsWithNoName() { await TestMissingInRegularAndScriptAsync( @" namespace Microsoft.CodeAnalysis.Host { internal interface [|}|] ", new TestParameters(options: s_options.InterfaceNamesStartWithI)); } #if CODE_STYLE [Fact(Skip = "https://github.com/dotnet/roslyn/issues/42218")] #else [Fact] #endif [Trait(Traits.Feature, Traits.Features.NamingStyle)] [WorkItem(16562, "https://github.com/dotnet/roslyn/issues/16562")] public async Task TestRefactorNotify() { var markup = @"public class [|c|] { }"; var testParameters = new TestParameters(options: s_options.ClassNamesArePascalCase); using var workspace = CreateWorkspaceFromOptions(markup, testParameters); var (_, action) = await GetCodeActionsAsync(workspace, testParameters); var previewOperations = await action.GetPreviewOperationsAsync(CancellationToken.None); Assert.Empty(previewOperations.OfType<TestSymbolRenamedCodeActionOperationFactoryWorkspaceService.Operation>()); var commitOperations = await action.GetOperationsAsync(CancellationToken.None); Assert.Equal(2, commitOperations.Length); var symbolRenamedOperation = (TestSymbolRenamedCodeActionOperationFactoryWorkspaceService.Operation)commitOperations[1]; Assert.Equal("c", symbolRenamedOperation._symbol.Name); Assert.Equal("C", symbolRenamedOperation._newName); } #if CODE_STYLE [Fact(Skip = "https://github.com/dotnet/roslyn/issues/42218")] #else [Fact] #endif [Trait(Traits.Feature, Traits.Features.NamingStyle)] [WorkItem(38513, "https://github.com/dotnet/roslyn/issues/38513")] public async Task TestRefactorNotifyInterfaceNamesStartWithI() { var markup = @"public interface [|test|] { }"; var testParameters = new TestParameters(options: s_options.InterfaceNamesStartWithI); using var workspace = CreateWorkspaceFromOptions(markup, testParameters); var (_, action) = await GetCodeActionsAsync(workspace, testParameters); var previewOperations = await action.GetPreviewOperationsAsync(CancellationToken.None); Assert.Empty(previewOperations.OfType<TestSymbolRenamedCodeActionOperationFactoryWorkspaceService.Operation>()); var commitOperations = await action.GetOperationsAsync(CancellationToken.None); Assert.Equal(2, commitOperations.Length); var symbolRenamedOperation = (TestSymbolRenamedCodeActionOperationFactoryWorkspaceService.Operation)commitOperations[1]; Assert.Equal("test", symbolRenamedOperation._symbol.Name); Assert.Equal("ITest", symbolRenamedOperation._newName); } #if CODE_STYLE [Fact(Skip = "https://github.com/dotnet/roslyn/issues/42218")] #else [Fact] #endif [Trait(Traits.Feature, Traits.Features.NamingStyle)] [WorkItem(38513, "https://github.com/dotnet/roslyn/issues/38513")] public async Task TestRefactorNotifyTypeParameterNamesStartWithT() { var markup = @"public class A { void DoOtherThing<[|arg|]>() { } }"; var testParameters = new TestParameters(options: s_options.TypeParameterNamesStartWithT); using var workspace = CreateWorkspaceFromOptions(markup, testParameters); var (_, action) = await GetCodeActionsAsync(workspace, testParameters); var previewOperations = await action.GetPreviewOperationsAsync(CancellationToken.None); Assert.Empty(previewOperations.OfType<TestSymbolRenamedCodeActionOperationFactoryWorkspaceService.Operation>()); var commitOperations = await action.GetOperationsAsync(CancellationToken.None); Assert.Equal(2, commitOperations.Length); var symbolRenamedOperation = (TestSymbolRenamedCodeActionOperationFactoryWorkspaceService.Operation)commitOperations[1]; Assert.Equal("arg", symbolRenamedOperation._symbol.Name); Assert.Equal("TArg", symbolRenamedOperation._newName); } [Fact, Trait(Traits.Feature, Traits.Features.NamingStyle)] [WorkItem(47508, "https://github.com/dotnet/roslyn/issues/47508")] public async Task TestRecordParameter_NoDiagnosticWhenCorrect() { await TestMissingInRegularAndScriptAsync( @"record Foo(int [|MyInt|]);", new TestParameters(options: s_options.MergeStyles(s_options.PropertyNamesArePascalCase, s_options.ParameterNamesAreCamelCaseWithPUnderscorePrefix))); } [Fact, Trait(Traits.Feature, Traits.Features.NamingStyle)] [WorkItem(47508, "https://github.com/dotnet/roslyn/issues/47508")] public async Task TestRecordConstructorParameter_NoDiagnosticWhenCorrect() { await TestMissingInRegularAndScriptAsync( @"record Foo(int MyInt) { public Foo(string [|p_myString|]) : this(1) { } }", new TestParameters(options: s_options.MergeStyles(s_options.PropertyNamesArePascalCase, s_options.ParameterNamesAreCamelCaseWithPUnderscorePrefix))); } [Fact, Trait(Traits.Feature, Traits.Features.NamingStyle)] [WorkItem(47508, "https://github.com/dotnet/roslyn/issues/47508")] public async Task TestRecordParameter_ParameterFormattedAsProperties() { await TestInRegularAndScriptAsync( @"public record Foo(int [|myInt|]);", @"public record Foo(int [|MyInt|]);", options: s_options.MergeStyles(s_options.PropertyNamesArePascalCase, s_options.ParameterNamesAreCamelCaseWithPUnderscorePrefix)); } [Theory] [InlineData("_")] [InlineData("_1")] [InlineData("_123")] public async Task TestDiscardParameterAsync(string identifier) { await TestMissingInRegularAndScriptAsync( $@"class C {{ void M(int [|{identifier}|]) {{ }} }}", new TestParameters(options: s_options.ParameterNamesAreCamelCase)); } [Theory] [InlineData("_")] [InlineData("_1")] [InlineData("_123")] public async Task TestDiscardLocalAsync(string identifier) { await TestMissingInRegularAndScriptAsync( $@"class C {{ void M() {{ int [|{identifier}|] = 0; }} }}", new TestParameters(options: s_options.LocalNamesAreCamelCase)); } [Fact] [WorkItem(49535, "https://github.com/dotnet/roslyn/issues/49535")] public async Task TestGlobalDirectiveAsync() { await TestMissingInRegularAndScriptAsync( @" interface I { int X { get; } } class C : I { int [|global::I.X|] => 0; }", new TestParameters(options: s_options.PropertyNamesArePascalCase)); } [Fact, Trait(Traits.Feature, Traits.Features.NamingStyle)] [WorkItem(50734, "https://github.com/dotnet/roslyn/issues/50734")] public async Task TestAsyncEntryPoint() { await TestMissingInRegularAndScriptAsync(@" using System.Threading.Tasks; class C { static async Task [|Main|]() { await Task.Delay(0); } }", new TestParameters(options: s_options.AsyncFunctionNamesEndWithAsync)); } [Fact, Trait(Traits.Feature, Traits.Features.NamingStyle)] [WorkItem(49648, "https://github.com/dotnet/roslyn/issues/49648")] public async Task TestAsyncEntryPoint_TopLevel() { await TestMissingInRegularAndScriptAsync(@" using System.Threading.Tasks; [|await Task.Delay(0);|] ", new TestParameters(options: s_options.AsyncFunctionNamesEndWithAsync)); } [Fact] [WorkItem(51727, "https://github.com/dotnet/roslyn/issues/51727")] public async Task TestExternAsync() { await TestMissingInRegularAndScriptAsync( @" class C { static extern void [|some_p_invoke()|]; }", new TestParameters(options: s_options.MethodNamesArePascalCase)); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.CodeFixes; using Microsoft.CodeAnalysis.CodeFixes.NamingStyles; using Microsoft.CodeAnalysis.CSharp.Diagnostics.NamingStyles; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.UnitTests.Diagnostics.NamingStyles; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; using Xunit.Abstractions; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics.NamingStyles { public class NamingStylesTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest { public NamingStylesTests(ITestOutputHelper logger) : base(logger) { } private static readonly NamingStylesTestOptionSets s_options = new NamingStylesTestOptionSets(LanguageNames.CSharp); internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace) => (new CSharpNamingStyleDiagnosticAnalyzer(), new NamingStyleCodeFixProvider()); protected override TestComposition GetComposition() => base.GetComposition().AddParts(typeof(TestSymbolRenamedCodeActionOperationFactoryWorkspaceService)); [Fact, Trait(Traits.Feature, Traits.Features.NamingStyle)] public async Task TestPascalCaseClass_CorrectName() { await TestMissingInRegularAndScriptAsync( @"class [|C|] { }", new TestParameters(options: s_options.ClassNamesArePascalCase)); } [Fact, Trait(Traits.Feature, Traits.Features.NamingStyle)] public async Task TestPascalCaseClass_NameGetsCapitalized() { await TestInRegularAndScriptAsync( @"class [|c|] { }", @"class C { }", options: s_options.ClassNamesArePascalCase); } [Theory, Trait(Traits.Feature, Traits.Features.NamingStyle)] [InlineData("M_bar", "bar")] [InlineData("S_bar", "bar")] [InlineData("T_bar", "bar")] [InlineData("_Bar", "bar")] [InlineData("__Bar", "bar")] [InlineData("M_s__t_Bar", "bar")] [InlineData("m_bar", "bar")] [InlineData("s_bar", "bar")] [InlineData("t_bar", "bar")] [InlineData("_bar", "bar")] [InlineData("__bar", "bar")] [InlineData("m_s__t_Bar", "bar")] // Special cases to ensure empty identifiers are not produced [InlineData("M_", "m_")] [InlineData("M__", "_")] [InlineData("S_", "s_")] [InlineData("T_", "t_")] [InlineData("M_S__T_", "t_")] public async Task TestCamelCaseField_PrefixGetsStripped(string fieldName, string correctedName) { await TestInRegularAndScriptAsync( $@"class C {{ int [|{fieldName}|]; }}", $@"class C {{ int [|{correctedName}|]; }}", options: s_options.FieldNamesAreCamelCase); } [Theory, Trait(Traits.Feature, Traits.Features.NamingStyle)] [InlineData("M_bar", "_bar")] [InlineData("S_bar", "_bar")] [InlineData("T_bar", "_bar")] [InlineData("_Bar", "_bar")] [InlineData("__Bar", "_bar")] [InlineData("M_s__t_Bar", "_bar")] [InlineData("m_bar", "_bar")] [InlineData("s_bar", "_bar")] [InlineData("t_bar", "_bar")] [InlineData("bar", "_bar")] [InlineData("__bar", "_bar")] [InlineData("__s_bar", "_bar")] [InlineData("m_s__t_Bar", "_bar")] // Special cases to ensure empty identifiers are not produced [InlineData("M_", "_m_")] [InlineData("M__", "_")] [InlineData("S_", "_s_")] [InlineData("T_", "_t_")] [InlineData("M_S__T_", "_t_")] public async Task TestCamelCaseField_PrefixGetsStrippedBeforeAddition(string fieldName, string correctedName) { await TestInRegularAndScriptAsync( $@"class C {{ int [|{fieldName}|]; }}", $@"class C {{ int [|{correctedName}|]; }}", options: s_options.FieldNamesAreCamelCaseWithUnderscorePrefix); } [Fact, Trait(Traits.Feature, Traits.Features.NamingStyle)] public async Task TestPascalCaseMethod_CorrectName() { await TestMissingInRegularAndScriptAsync( @"class C { void [|M|]() { } }", new TestParameters(options: s_options.MethodNamesArePascalCase)); } [Theory, Trait(Traits.Feature, Traits.Features.NamingStyle)] [InlineData("")] [InlineData("public")] [InlineData("protected")] [InlineData("internal")] [InlineData("protected internal")] [InlineData("private")] [InlineData("protected private")] [WorkItem(20907, "https://github.com/dotnet/roslyn/issues/20907")] public async Task TestPascalCaseMethod_NoneAndDefaultAccessibilities(string accessibility) { await TestMissingInRegularAndScriptAsync( $@"class C {{ {accessibility} void [|m|]() {{ }} }}", new TestParameters(options: s_options.MethodNamesWithAccessibilityArePascalCase(ImmutableArray<Accessibility>.Empty))); await TestInRegularAndScriptAsync( $@"class C {{ {accessibility} void [|m|]() {{ }} }}", $@"class C {{ {accessibility} void M() {{ }} }}", options: s_options.MethodNamesWithAccessibilityArePascalCase(accessibilities: default)); } [Theory, Trait(Traits.Feature, Traits.Features.NamingStyle)] [InlineData("} namespace [|c2|] {", "} namespace C2 {")] [InlineData("class [|c2|] { }", "class C2 { }")] [InlineData("struct [|c2|] { }", "struct C2 { }")] [InlineData("interface [|c2|] { }", "interface C2 { }")] [InlineData("delegate void [|c2|]();", "delegate void C2();")] [InlineData("enum [|c2|] { }", "enum C2 { }")] [InlineData("class M<[|t|]> {}", "class M<T> {}")] [InlineData("void M<[|t|]>() {}", "void M<T>() {}")] [InlineData("int [|m|] { get; }", "int M { get; }")] [InlineData("void [|m|]() {}", "void M() {}")] [InlineData("void Outer() { void [|m|]() {} }", "void Outer() { void M() {} }")] [InlineData("int [|m|];", "int M;")] [InlineData("event System.EventHandler [|m|];", "event System.EventHandler M;")] [InlineData("void Outer(int [|m|]) {}", "void Outer(int M) {}")] [InlineData("void Outer() { int [|m|]; }", "void Outer() { int M; }")] [WorkItem(20907, "https://github.com/dotnet/roslyn/issues/20907")] public async Task TestPascalCaseSymbol_NoneAndDefaultSymbolKinds(string camelCaseSymbol, string pascalCaseSymbol) { await TestMissingInRegularAndScriptAsync( $@"class C {{ {camelCaseSymbol} }}", new TestParameters(options: s_options.SymbolKindsArePascalCaseEmpty())); await TestInRegularAndScriptAsync( $@"class C {{ {camelCaseSymbol} }}", $@"class C {{ {pascalCaseSymbol} }}", options: s_options.SymbolKindsArePascalCase(symbolKinds: default)); } [Theory, Trait(Traits.Feature, Traits.Features.NamingStyle)] [InlineData("} namespace [|c2|] {", "} namespace C2 {", SymbolKind.Namespace, Accessibility.Public)] [InlineData("class [|c2|] { }", "class C2 { }", TypeKind.Class, Accessibility.Private)] [InlineData("struct [|c2|] { }", "struct C2 { }", TypeKind.Struct, Accessibility.Private)] [InlineData("interface [|c2|] { }", "interface C2 { }", TypeKind.Interface, Accessibility.Private)] [InlineData("delegate void [|c2|]();", "delegate void C2();", TypeKind.Delegate, Accessibility.Private)] [InlineData("enum [|c2|] { }", "enum C2 { }", TypeKind.Enum, Accessibility.Private)] [InlineData("class M<[|t|]> {}", "class M<T> {}", SymbolKind.TypeParameter, Accessibility.Private)] [InlineData("void M<[|t|]>() {}", "void M<T>() {}", SymbolKind.TypeParameter, Accessibility.Private)] [InlineData("int [|m|] { get; }", "int M { get; }", SymbolKind.Property, Accessibility.Private)] [InlineData("void [|m|]() {}", "void M() {}", MethodKind.Ordinary, Accessibility.Private)] [InlineData("void Outer() { void [|m|]() {} }", "void Outer() { void M() {} }", MethodKind.LocalFunction, Accessibility.NotApplicable)] [InlineData("int [|m|];", "int M;", SymbolKind.Field, Accessibility.Private)] [InlineData("event System.EventHandler [|m|];", "event System.EventHandler M;", SymbolKind.Event, Accessibility.Private)] [InlineData("void Outer(int [|m|]) {}", "void Outer(int M) {}", SymbolKind.Parameter, Accessibility.Private)] [InlineData("void Outer() { void Inner(int [|m|]) {} }", "void Outer() { void Inner(int M) {} }", SymbolKind.Parameter, Accessibility.NotApplicable)] [InlineData("void Outer() { System.Action<int> action = [|m|] => {} }", "void Outer() { System.Action<int> action = M => {} }", SymbolKind.Parameter, Accessibility.NotApplicable)] [InlineData("void Outer() { System.Action<int> action = ([|m|]) => {} }", "void Outer() { System.Action<int> action = (M) => {} }", SymbolKind.Parameter, Accessibility.NotApplicable)] [InlineData("void Outer() { System.Action<int> action = (int [|m|]) => {} }", "void Outer() { System.Action<int> action = (int M) => {} }", SymbolKind.Parameter, Accessibility.NotApplicable)] [InlineData("void Outer() { System.Action<int> action = delegate (int [|m|]) {} }", "void Outer() { System.Action<int> action = delegate (int M) {} }", SymbolKind.Parameter, Accessibility.NotApplicable)] [InlineData("void Outer() { int [|m|]; }", "void Outer() { int M; }", SymbolKind.Local, Accessibility.NotApplicable)] [WorkItem(20907, "https://github.com/dotnet/roslyn/issues/20907")] public async Task TestPascalCaseSymbol_ExpectedSymbolAndAccessibility(string camelCaseSymbol, string pascalCaseSymbol, object symbolKind, Accessibility accessibility) { var alternateSymbolKind = TypeKind.Class.Equals(symbolKind) ? TypeKind.Interface : TypeKind.Class; var alternateAccessibility = accessibility == Accessibility.Public ? Accessibility.Protected : Accessibility.Public; // Verify that no diagnostic is reported if the symbol kind is wrong await TestMissingInRegularAndScriptAsync( $@"class C {{ {camelCaseSymbol} }}", new TestParameters(options: s_options.SymbolKindsArePascalCase(alternateSymbolKind))); // Verify that no diagnostic is reported if the accessibility is wrong await TestMissingInRegularAndScriptAsync( $@"class C {{ {camelCaseSymbol} }}", new TestParameters(options: s_options.AccessibilitiesArePascalCase(ImmutableArray.Create(alternateAccessibility)))); await TestInRegularAndScriptAsync( $@"class C {{ {camelCaseSymbol} }}", $@"class C {{ {pascalCaseSymbol} }}", options: s_options.AccessibilitiesArePascalCase(ImmutableArray.Create(accessibility))); } [Fact, Trait(Traits.Feature, Traits.Features.NamingStyle)] public async Task TestPascalCaseMethod_NameGetsCapitalized() { await TestInRegularAndScriptAsync( @"class C { void [|m|]() { } }", @"class C { void M() { } }", options: s_options.MethodNamesArePascalCase); } [Fact, Trait(Traits.Feature, Traits.Features.NamingStyle)] public async Task TestPascalCaseMethod_ConstructorsAreIgnored() { await TestMissingInRegularAndScriptAsync( @"class c { public [|c|]() { } }", new TestParameters(options: s_options.MethodNamesArePascalCase)); } [Fact, Trait(Traits.Feature, Traits.Features.NamingStyle)] public async Task TestPascalCaseMethod_PropertyAccessorsAreIgnored() { await TestMissingInRegularAndScriptAsync( @"class C { public int P { [|get|]; set; } }", new TestParameters(options: s_options.MethodNamesArePascalCase)); } [Fact, Trait(Traits.Feature, Traits.Features.NamingStyle)] public async Task TestPascalCaseMethod_IndexerNameIsIgnored() { await TestMissingInRegularAndScriptAsync( @"class C { public int [|this|][int index] { get { return 1; } } }", new TestParameters(options: s_options.MethodNamesArePascalCase)); } [Fact, Trait(Traits.Feature, Traits.Features.NamingStyle)] public async Task TestPascalCaseMethod_LocalFunctionIsIgnored() { await TestMissingInRegularAndScriptAsync( @"class C { void M() { void [|f|]() { } } }", new TestParameters(options: s_options.MethodNamesArePascalCase)); } [Fact, Trait(Traits.Feature, Traits.Features.NamingStyle)] public async Task TestCamelCaseParameters() { await TestInRegularAndScriptAsync( @"class C { public void M(int [|X|]) { } }", @"class C { public void M(int x) { } }", options: s_options.ParameterNamesAreCamelCase); } [Fact, Trait(Traits.Feature, Traits.Features.NamingStyle)] public async Task TestCamelCaseLocals_LocalDeclaration1() { await TestInRegularAndScriptAsync( @"class C { void M() { int [|X|]; } }", @"class C { void M() { int x; } }", options: s_options.LocalNamesAreCamelCase); } [Fact, Trait(Traits.Feature, Traits.Features.NamingStyle)] public async Task TestCamelCaseLocals_LocalDeclaration2() { await TestInRegularAndScriptAsync( @"class C { void M() { int X, [|Y|] = 0; } }", @"class C { void M() { int X, y = 0; } }", options: s_options.LocalNamesAreCamelCase); } [Fact, Trait(Traits.Feature, Traits.Features.NamingStyle)] public async Task TestCamelCaseLocals_UsingVariable1() { await TestInRegularAndScriptAsync( @"class C { void M() { using (object [|A|] = null) { } } }", @"class C { void M() { using (object a = null) { } } }", options: s_options.LocalNamesAreCamelCase); } [Fact, Trait(Traits.Feature, Traits.Features.NamingStyle)] public async Task TestCamelCaseLocals_UsingVariable2() { await TestInRegularAndScriptAsync( @"class C { void M() { using (object A = null, [|B|] = null) { } } }", @"class C { void M() { using (object A = null, b = null) { } } }", options: s_options.LocalNamesAreCamelCase); } [Fact, Trait(Traits.Feature, Traits.Features.NamingStyle)] public async Task TestCamelCaseLocals_ForVariable1() { await TestInRegularAndScriptAsync( @"class C { void M() { for (int [|I|] = 0, J = 0; I < J; ++I) { } } }", @"class C { void M() { for (int i = 0, J = 0; i < J; ++i) { } } }", options: s_options.LocalNamesAreCamelCase); } [Fact, Trait(Traits.Feature, Traits.Features.NamingStyle)] public async Task TestCamelCaseLocals_ForVariable2() { await TestInRegularAndScriptAsync( @"class C { void M() { for (int I = 0, [|J|] = 0; I < J; ++J) { } } }", @"class C { void M() { for (int I = 0, j = 0; I < j; ++j) { } } }", options: s_options.LocalNamesAreCamelCase); } [Fact, Trait(Traits.Feature, Traits.Features.NamingStyle)] public async Task TestCamelCaseLocals_ForEachVariable() { await TestInRegularAndScriptAsync( @"class C { void M() { foreach (var [|X|] in new string[] { }) { } } }", @"class C { void M() { foreach (var x in new string[] { }) { } } }", options: s_options.LocalNamesAreCamelCase); } [Fact, Trait(Traits.Feature, Traits.Features.NamingStyle)] public async Task TestCamelCaseLocals_CatchVariable() { await TestInRegularAndScriptAsync( @"using System; class C { void M() { try { } catch (Exception [|Exception|]) { } } }", @"using System; class C { void M() { try { } catch (Exception exception) { } } }", options: s_options.LocalNamesAreCamelCase); } [Fact, Trait(Traits.Feature, Traits.Features.NamingStyle)] public async Task TestCamelCaseLocals_CatchWithoutVariableIgnored() { await TestMissingInRegularAndScriptAsync( @"using System; class C { void M() { try { } catch ([|Exception|]) { } } }", new TestParameters(options: s_options.LocalNamesAreCamelCase)); } [Fact, Trait(Traits.Feature, Traits.Features.NamingStyle)] public async Task TestCamelCaseLocals_CatchWithoutDeclarationIgnored() { await TestMissingInRegularAndScriptAsync( @"using System; class C { void M() { try { } [|catch|] { } } }", new TestParameters(options: s_options.LocalNamesAreCamelCase)); } [Fact, Trait(Traits.Feature, Traits.Features.NamingStyle)] public async Task TestCamelCaseLocals_Deconstruction1() { await TestInRegularAndScriptAsync( @"class C { void M() { (int A, (string [|B|], var C)) = (0, (string.Empty, string.Empty)); System.Console.WriteLine(A + B + C); } }", @"class C { void M() { (int A, (string b, var C)) = (0, (string.Empty, string.Empty)); System.Console.WriteLine(A + b + C); } }", options: s_options.LocalNamesAreCamelCase); } [Fact, Trait(Traits.Feature, Traits.Features.NamingStyle)] public async Task TestCamelCaseLocals_Deconstruction2() { await TestInRegularAndScriptAsync( @"class C { void M() { var (A, (B, [|C|])) = (0, (string.Empty, string.Empty)); System.Console.WriteLine(A + B + C); } }", @"class C { void M() { var (A, (B, [|c|])) = (0, (string.Empty, string.Empty)); System.Console.WriteLine(A + B + c); } }", options: s_options.LocalNamesAreCamelCase); } [Fact, Trait(Traits.Feature, Traits.Features.NamingStyle)] public async Task TestCamelCaseLocals_ForEachDeconstruction1() { await TestInRegularAndScriptAsync( @"class C { void M() { foreach ((int A, (string [|B|], var C)) in new[] { (0, (string.Empty, string.Empty)) }) System.Console.WriteLine(A + B + C); } }", @"class C { void M() { foreach ((int A, (string b, var C)) in new[] { (0, (string.Empty, string.Empty)) }) System.Console.WriteLine(A + b + C); } }", options: s_options.LocalNamesAreCamelCase); } [Fact, Trait(Traits.Feature, Traits.Features.NamingStyle)] public async Task TestCamelCaseLocals_ForEachDeconstruction2() { await TestInRegularAndScriptAsync( @"class C { void M() { foreach (var (A, (B, [|C|])) in new[] { (0, (string.Empty, string.Empty)) }) System.Console.WriteLine(A + B + C); } }", @"class C { void M() { foreach (var (A, (B, c)) in new[] { (0, (string.Empty, string.Empty)) }) System.Console.WriteLine(A + B + c); } }", options: s_options.LocalNamesAreCamelCase); } [Fact, Trait(Traits.Feature, Traits.Features.NamingStyle)] public async Task TestCamelCaseLocals_OutVariable() { await TestInRegularAndScriptAsync( @"class C { void M() { if (int.TryParse(string.Empty, out var [|Value|])) System.Console.WriteLine(Value); } }", @"class C { void M() { if (int.TryParse(string.Empty, out var value)) System.Console.WriteLine(value); } }", options: s_options.LocalNamesAreCamelCase); } [Fact, Trait(Traits.Feature, Traits.Features.NamingStyle)] public async Task TestCamelCaseLocals_PatternVariable() { await TestInRegularAndScriptAsync( @"class C { void M() { if (new object() is int [|Value|]) System.Console.WriteLine(Value); } }", @"class C { void M() { if (new object() is int value) System.Console.WriteLine(value); } }", options: s_options.LocalNamesAreCamelCase); } [Fact, Trait(Traits.Feature, Traits.Features.NamingStyle)] public async Task TestCamelCaseLocals_QueryFromClauseIgnored() { // This is an IRangeVariableSymbol, not ILocalSymbol await TestMissingInRegularAndScriptAsync( @"using System.Linq; class C { void M() { var squares = from [|STRING|] in new string[] { } let Number = int.Parse(STRING) select Number * Number; } }", new TestParameters(options: s_options.LocalNamesAreCamelCase)); } [Fact, Trait(Traits.Feature, Traits.Features.NamingStyle)] public async Task TestCamelCaseLocals_QueryLetClauseIgnored() { // This is an IRangeVariableSymbol, not ILocalSymbol await TestMissingInRegularAndScriptAsync( @"using System.Linq; class C { void M() { var squares = from STRING in new string[] { } let [|Number|] = int.Parse(STRING) select Number * Number; } }", new TestParameters(options: s_options.LocalNamesAreCamelCase)); } [Fact, Trait(Traits.Feature, Traits.Features.NamingStyle)] public async Task TestCamelCaseLocals_ParameterIgnored() { await TestMissingInRegularAndScriptAsync( @"class C { void M(int [|X|]) { } }", new TestParameters(options: s_options.LocalNamesAreCamelCase)); } [Fact, Trait(Traits.Feature, Traits.Features.NamingStyle)] public async Task TestCamelCaseLocals_TupleTypeElementNameIgnored1() { await TestMissingInRegularAndScriptAsync( @"class C { void M() { (int [|A|], string B) tuple; } }", new TestParameters(options: s_options.LocalNamesAreCamelCase)); } [Fact, Trait(Traits.Feature, Traits.Features.NamingStyle)] public async Task TestCamelCaseLocals_TupleTypeElementNameIgnored2() { await TestMissingInRegularAndScriptAsync( @"class C { void M() { (int A, (string [|B|], string C)) tuple = (0, (string.Empty, string.Empty)); } }", new TestParameters(options: s_options.LocalNamesAreCamelCase)); } [Fact, Trait(Traits.Feature, Traits.Features.NamingStyle)] public async Task TestCamelCaseLocals_TupleExpressionElementNameIgnored() { await TestMissingInRegularAndScriptAsync( @"class C { void M() { var tuple = ([|A|]: 0, B: 0); } }", new TestParameters(options: s_options.LocalNamesAreCamelCase)); } [Fact, Trait(Traits.Feature, Traits.Features.NamingStyle)] public async Task TestUpperCaseConstants_ConstField() { await TestInRegularAndScriptAsync( @"class C { const int [|field|] = 0; }", @"class C { const int FIELD = 0; }", options: s_options.ConstantsAreUpperCase); } [Fact, Trait(Traits.Feature, Traits.Features.NamingStyle)] public async Task TestUpperCaseConstants_ConstLocal() { await TestInRegularAndScriptAsync( @"class C { void M() { const int local1 = 0, [|local2|] = 0; } }", @"class C { void M() { const int local1 = 0, LOCAL2 = 0; } }", options: s_options.ConstantsAreUpperCase); } [Fact, Trait(Traits.Feature, Traits.Features.NamingStyle)] public async Task TestUpperCaseConstants_NonConstFieldIgnored() { await TestMissingInRegularAndScriptAsync( @"class C { readonly int [|field|] = 0; }", new TestParameters(options: s_options.ConstantsAreUpperCase)); } [Fact, Trait(Traits.Feature, Traits.Features.NamingStyle)] public async Task TestUpperCaseConstants_NonConstLocalIgnored() { await TestMissingInRegularAndScriptAsync( @"class C { void M() { int local1 = 0, [|local2|] = 0; } }", new TestParameters(options: s_options.ConstantsAreUpperCase)); } [Fact, Trait(Traits.Feature, Traits.Features.NamingStyle)] public async Task TestCamelCaseLocalsUpperCaseConstants_ConstLocal() { await TestInRegularAndScriptAsync( @"class C { void M() { const int [|PascalCase|] = 0; } }", @"class C { void M() { const int PASCALCASE = 0; } }", options: s_options.LocalsAreCamelCaseConstantsAreUpperCase); } [Fact, Trait(Traits.Feature, Traits.Features.NamingStyle)] public async Task TestCamelCaseLocalsUpperCaseConstants_NonConstLocal() { await TestInRegularAndScriptAsync( @"class C { void M() { int [|PascalCase|] = 0; } }", @"class C { void M() { int pascalCase = 0; } }", options: s_options.LocalsAreCamelCaseConstantsAreUpperCase); } [Fact, Trait(Traits.Feature, Traits.Features.NamingStyle)] public async Task TestCamelCaseLocalFunctions() { await TestInRegularAndScriptAsync( @"class C { void M() { void [|F|]() { } } }", @"class C { void M() { void f() { } } }", options: s_options.LocalFunctionNamesAreCamelCase); } [Fact, Trait(Traits.Feature, Traits.Features.NamingStyle)] public async Task TestCamelCaseLocalFunctions_MethodIsIgnored() { await TestMissingInRegularAndScriptAsync( @"class C { void [|M|]() { } }", new TestParameters(options: s_options.LocalFunctionNamesAreCamelCase)); } [Fact, Trait(Traits.Feature, Traits.Features.NamingStyle)] public async Task TestAsyncFunctions_AsyncMethod() { await TestInRegularAndScriptAsync( @"class C { async void [|M|]() { } }", @"class C { async void MAsync() { } }", options: s_options.AsyncFunctionNamesEndWithAsync); } [Fact, Trait(Traits.Feature, Traits.Features.NamingStyle)] public async Task TestAsyncFunctions_AsyncLocalFunction() { await TestInRegularAndScriptAsync( @"class C { void M() { async void [|F|]() { } } }", @"class C { void M() { async void FAsync() { } } }", options: s_options.AsyncFunctionNamesEndWithAsync); } [Fact, Trait(Traits.Feature, Traits.Features.NamingStyle)] public async Task TestAsyncFunctions_NonAsyncMethodIgnored() { await TestMissingInRegularAndScriptAsync( @"class C { void [|M|]() { async void F() { } } }", new TestParameters(options: s_options.AsyncFunctionNamesEndWithAsync)); } [Fact, Trait(Traits.Feature, Traits.Features.NamingStyle)] public async Task TestAsyncFunctions_NonAsyncLocalFunctionIgnored() { await TestMissingInRegularAndScriptAsync( @"class C { async void M() { void [|F|]() { } } }", new TestParameters(options: s_options.AsyncFunctionNamesEndWithAsync)); } [Fact, Trait(Traits.Feature, Traits.Features.NamingStyle)] public async Task TestPascalCaseMethod_InInterfaceWithImplicitImplementation() { await TestInRegularAndScriptAsync( @"interface I { void [|m|](); } class C : I { public void m() { } }", @"interface I { void M(); } class C : I { public void M() { } }", options: s_options.MethodNamesArePascalCase); } [Fact, Trait(Traits.Feature, Traits.Features.NamingStyle)] public async Task TestPascalCaseMethod_InInterfaceWithExplicitImplementation() { await TestInRegularAndScriptAsync( @"interface I { void [|m|](); } class C : I { void I.m() { } }", @"interface I { void M(); } class C : I { void I.M() { } }", options: s_options.MethodNamesArePascalCase); } [Fact, Trait(Traits.Feature, Traits.Features.NamingStyle)] public async Task TestPascalCaseMethod_NotInImplicitInterfaceImplementation() { await TestMissingInRegularAndScriptAsync( @"interface I { void m(); } class C : I { public void [|m|]() { } }", new TestParameters(options: s_options.MethodNamesArePascalCase)); } [Fact, Trait(Traits.Feature, Traits.Features.NamingStyle)] public async Task TestPascalCaseMethod_NotInExplicitInterfaceImplementation() { await TestMissingInRegularAndScriptAsync( @"interface I { void m(); } class C : I { void I.[|m|]() { } }", new TestParameters(options: s_options.MethodNamesArePascalCase)); } [Fact, Trait(Traits.Feature, Traits.Features.NamingStyle)] public async Task TestPascalCaseMethod_InAbstractType() { await TestInRegularAndScriptAsync( @" abstract class C { public abstract void [|m|](); } class D : C { public override void m() { } }", @" abstract class C { public abstract void M(); } class D : C { public override void M() { } }", options: s_options.MethodNamesArePascalCase); } [Fact, Trait(Traits.Feature, Traits.Features.NamingStyle)] public async Task TestPascalCaseMethod_NotInAbstractMethodImplementation() { await TestMissingInRegularAndScriptAsync( @" abstract class C { public abstract void m(); } class D : C { public override void [|m|]() { } }", new TestParameters(options: s_options.MethodNamesArePascalCase)); } [Fact, Trait(Traits.Feature, Traits.Features.NamingStyle)] public async Task TestPascalCaseProperty_InInterface() { await TestInRegularAndScriptAsync( @" interface I { int [|p|] { get; set; } } class C : I { public int p { get { return 1; } set { } } }", @" interface I { int P { get; set; } } class C : I { public int P { get { return 1; } set { } } }", options: s_options.PropertyNamesArePascalCase); } [Fact, Trait(Traits.Feature, Traits.Features.NamingStyle)] public async Task TestPascalCaseProperty_NotInImplicitInterfaceImplementation() { await TestMissingInRegularAndScriptAsync( @" interface I { int p { get; set; } } class C : I { public int [|p|] { get { return 1; } set { } } }", new TestParameters(options: s_options.PropertyNamesArePascalCase)); } [Fact, Trait(Traits.Feature, Traits.Features.NamingStyle)] public async Task TestPascalCaseMethod_OverrideInternalMethod() { await TestMissingInRegularAndScriptAsync( @" abstract class C { internal abstract void m(); } class D : C { internal override void [|m|]() { } }", new TestParameters(options: s_options.MethodNamesArePascalCase)); } [Fact, Trait(Traits.Feature, Traits.Features.NamingStyle)] [WorkItem(19106, "https://github.com/dotnet/roslyn/issues/19106")] public async Task TestMissingOnSymbolsWithNoName() { await TestMissingInRegularAndScriptAsync( @" namespace Microsoft.CodeAnalysis.Host { internal interface [|}|] ", new TestParameters(options: s_options.InterfaceNamesStartWithI)); } #if CODE_STYLE [Fact(Skip = "https://github.com/dotnet/roslyn/issues/42218")] #else [Fact] #endif [Trait(Traits.Feature, Traits.Features.NamingStyle)] [WorkItem(16562, "https://github.com/dotnet/roslyn/issues/16562")] public async Task TestRefactorNotify() { var markup = @"public class [|c|] { }"; var testParameters = new TestParameters(options: s_options.ClassNamesArePascalCase); using var workspace = CreateWorkspaceFromOptions(markup, testParameters); var (_, action) = await GetCodeActionsAsync(workspace, testParameters); var previewOperations = await action.GetPreviewOperationsAsync(CancellationToken.None); Assert.Empty(previewOperations.OfType<TestSymbolRenamedCodeActionOperationFactoryWorkspaceService.Operation>()); var commitOperations = await action.GetOperationsAsync(CancellationToken.None); Assert.Equal(2, commitOperations.Length); var symbolRenamedOperation = (TestSymbolRenamedCodeActionOperationFactoryWorkspaceService.Operation)commitOperations[1]; Assert.Equal("c", symbolRenamedOperation._symbol.Name); Assert.Equal("C", symbolRenamedOperation._newName); } #if CODE_STYLE [Fact(Skip = "https://github.com/dotnet/roslyn/issues/42218")] #else [Fact] #endif [Trait(Traits.Feature, Traits.Features.NamingStyle)] [WorkItem(38513, "https://github.com/dotnet/roslyn/issues/38513")] public async Task TestRefactorNotifyInterfaceNamesStartWithI() { var markup = @"public interface [|test|] { }"; var testParameters = new TestParameters(options: s_options.InterfaceNamesStartWithI); using var workspace = CreateWorkspaceFromOptions(markup, testParameters); var (_, action) = await GetCodeActionsAsync(workspace, testParameters); var previewOperations = await action.GetPreviewOperationsAsync(CancellationToken.None); Assert.Empty(previewOperations.OfType<TestSymbolRenamedCodeActionOperationFactoryWorkspaceService.Operation>()); var commitOperations = await action.GetOperationsAsync(CancellationToken.None); Assert.Equal(2, commitOperations.Length); var symbolRenamedOperation = (TestSymbolRenamedCodeActionOperationFactoryWorkspaceService.Operation)commitOperations[1]; Assert.Equal("test", symbolRenamedOperation._symbol.Name); Assert.Equal("ITest", symbolRenamedOperation._newName); } #if CODE_STYLE [Fact(Skip = "https://github.com/dotnet/roslyn/issues/42218")] #else [Fact] #endif [Trait(Traits.Feature, Traits.Features.NamingStyle)] [WorkItem(38513, "https://github.com/dotnet/roslyn/issues/38513")] public async Task TestRefactorNotifyTypeParameterNamesStartWithT() { var markup = @"public class A { void DoOtherThing<[|arg|]>() { } }"; var testParameters = new TestParameters(options: s_options.TypeParameterNamesStartWithT); using var workspace = CreateWorkspaceFromOptions(markup, testParameters); var (_, action) = await GetCodeActionsAsync(workspace, testParameters); var previewOperations = await action.GetPreviewOperationsAsync(CancellationToken.None); Assert.Empty(previewOperations.OfType<TestSymbolRenamedCodeActionOperationFactoryWorkspaceService.Operation>()); var commitOperations = await action.GetOperationsAsync(CancellationToken.None); Assert.Equal(2, commitOperations.Length); var symbolRenamedOperation = (TestSymbolRenamedCodeActionOperationFactoryWorkspaceService.Operation)commitOperations[1]; Assert.Equal("arg", symbolRenamedOperation._symbol.Name); Assert.Equal("TArg", symbolRenamedOperation._newName); } [Fact, Trait(Traits.Feature, Traits.Features.NamingStyle)] [WorkItem(47508, "https://github.com/dotnet/roslyn/issues/47508")] public async Task TestRecordParameter_NoDiagnosticWhenCorrect() { await TestMissingInRegularAndScriptAsync( @"record Foo(int [|MyInt|]);", new TestParameters(options: s_options.MergeStyles(s_options.PropertyNamesArePascalCase, s_options.ParameterNamesAreCamelCaseWithPUnderscorePrefix))); } [Fact, Trait(Traits.Feature, Traits.Features.NamingStyle)] [WorkItem(47508, "https://github.com/dotnet/roslyn/issues/47508")] public async Task TestRecordConstructorParameter_NoDiagnosticWhenCorrect() { await TestMissingInRegularAndScriptAsync( @"record Foo(int MyInt) { public Foo(string [|p_myString|]) : this(1) { } }", new TestParameters(options: s_options.MergeStyles(s_options.PropertyNamesArePascalCase, s_options.ParameterNamesAreCamelCaseWithPUnderscorePrefix))); } [Fact, Trait(Traits.Feature, Traits.Features.NamingStyle)] [WorkItem(47508, "https://github.com/dotnet/roslyn/issues/47508")] public async Task TestRecordParameter_ParameterFormattedAsProperties() { await TestInRegularAndScriptAsync( @"public record Foo(int [|myInt|]);", @"public record Foo(int [|MyInt|]);", options: s_options.MergeStyles(s_options.PropertyNamesArePascalCase, s_options.ParameterNamesAreCamelCaseWithPUnderscorePrefix)); } [Theory] [InlineData("_")] [InlineData("_1")] [InlineData("_123")] public async Task TestDiscardParameterAsync(string identifier) { await TestMissingInRegularAndScriptAsync( $@"class C {{ void M(int [|{identifier}|]) {{ }} }}", new TestParameters(options: s_options.ParameterNamesAreCamelCase)); } [Theory] [InlineData("_")] [InlineData("_1")] [InlineData("_123")] public async Task TestDiscardLocalAsync(string identifier) { await TestMissingInRegularAndScriptAsync( $@"class C {{ void M() {{ int [|{identifier}|] = 0; }} }}", new TestParameters(options: s_options.LocalNamesAreCamelCase)); } [Fact] [WorkItem(49535, "https://github.com/dotnet/roslyn/issues/49535")] public async Task TestGlobalDirectiveAsync() { await TestMissingInRegularAndScriptAsync( @" interface I { int X { get; } } class C : I { int [|global::I.X|] => 0; }", new TestParameters(options: s_options.PropertyNamesArePascalCase)); } [Fact, Trait(Traits.Feature, Traits.Features.NamingStyle)] [WorkItem(50734, "https://github.com/dotnet/roslyn/issues/50734")] public async Task TestAsyncEntryPoint() { await TestMissingInRegularAndScriptAsync(@" using System.Threading.Tasks; class C { static async Task [|Main|]() { await Task.Delay(0); } }", new TestParameters(options: s_options.AsyncFunctionNamesEndWithAsync)); } [Fact, Trait(Traits.Feature, Traits.Features.NamingStyle)] [WorkItem(49648, "https://github.com/dotnet/roslyn/issues/49648")] public async Task TestAsyncEntryPoint_TopLevel() { await TestMissingInRegularAndScriptAsync(@" using System.Threading.Tasks; [|await Task.Delay(0);|] ", new TestParameters(options: s_options.AsyncFunctionNamesEndWithAsync)); } [Fact] [WorkItem(51727, "https://github.com/dotnet/roslyn/issues/51727")] public async Task TestExternAsync() { await TestMissingInRegularAndScriptAsync( @" class C { static extern void [|some_p_invoke()|]; }", new TestParameters(options: s_options.MethodNamesArePascalCase)); } } }
-1
dotnet/roslyn
55,132
Support lambda expressions and method groups as `var` initializers
```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
cston
2021-07-27T03:12:21Z
2021-07-27T18:26:42Z
61a565cfcd777158cb6354351436aff997ad7bf6
5840335153dcca42570a853cdacd06d660fe9596
Support lambda expressions and method groups as `var` initializers. ```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
./src/Workspaces/Core/Portable/FindSymbols/FindReferences/Finders/OperatorSymbolReferenceFinder.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.FindSymbols.Finders { internal class OperatorSymbolReferenceFinder : AbstractMethodOrPropertyOrEventSymbolReferenceFinder<IMethodSymbol> { protected override bool CanFind(IMethodSymbol symbol) => symbol.MethodKind == MethodKind.UserDefinedOperator; protected override async Task<ImmutableArray<Document>> DetermineDocumentsToSearchAsync( IMethodSymbol symbol, Project project, IImmutableSet<Document>? documents, FindReferencesSearchOptions options, CancellationToken cancellationToken) { var op = symbol.GetPredefinedOperator(); var documentsWithOp = await FindDocumentsAsync(project, documents, op, cancellationToken).ConfigureAwait(false); var documentsWithGlobalAttributes = await FindDocumentsWithGlobalAttributesAsync(project, documents, cancellationToken).ConfigureAwait(false); return documentsWithOp.Concat(documentsWithGlobalAttributes); } protected override async ValueTask<ImmutableArray<FinderLocation>> FindReferencesInDocumentAsync( IMethodSymbol symbol, Document document, SemanticModel semanticModel, FindReferencesSearchOptions options, CancellationToken cancellationToken) { var syntaxFacts = document.GetRequiredLanguageService<ISyntaxFactsService>(); var op = symbol.GetPredefinedOperator(); var opReferences = await FindReferencesInDocumentAsync(symbol, document, semanticModel, t => IsPotentialReference(syntaxFacts, op, t), cancellationToken).ConfigureAwait(false); var suppressionReferences = await FindReferencesInDocumentInsideGlobalSuppressionsAsync(document, semanticModel, symbol, cancellationToken).ConfigureAwait(false); return opReferences.Concat(suppressionReferences); } private static bool IsPotentialReference( ISyntaxFactsService syntaxFacts, PredefinedOperator op, SyntaxToken token) { return syntaxFacts.TryGetPredefinedOperator(token, out var actualOperator) && actualOperator == op; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.FindSymbols.Finders { internal class OperatorSymbolReferenceFinder : AbstractMethodOrPropertyOrEventSymbolReferenceFinder<IMethodSymbol> { protected override bool CanFind(IMethodSymbol symbol) => symbol.MethodKind == MethodKind.UserDefinedOperator; protected override async Task<ImmutableArray<Document>> DetermineDocumentsToSearchAsync( IMethodSymbol symbol, Project project, IImmutableSet<Document>? documents, FindReferencesSearchOptions options, CancellationToken cancellationToken) { var op = symbol.GetPredefinedOperator(); var documentsWithOp = await FindDocumentsAsync(project, documents, op, cancellationToken).ConfigureAwait(false); var documentsWithGlobalAttributes = await FindDocumentsWithGlobalAttributesAsync(project, documents, cancellationToken).ConfigureAwait(false); return documentsWithOp.Concat(documentsWithGlobalAttributes); } protected override async ValueTask<ImmutableArray<FinderLocation>> FindReferencesInDocumentAsync( IMethodSymbol symbol, Document document, SemanticModel semanticModel, FindReferencesSearchOptions options, CancellationToken cancellationToken) { var syntaxFacts = document.GetRequiredLanguageService<ISyntaxFactsService>(); var op = symbol.GetPredefinedOperator(); var opReferences = await FindReferencesInDocumentAsync(symbol, document, semanticModel, t => IsPotentialReference(syntaxFacts, op, t), cancellationToken).ConfigureAwait(false); var suppressionReferences = await FindReferencesInDocumentInsideGlobalSuppressionsAsync(document, semanticModel, symbol, cancellationToken).ConfigureAwait(false); return opReferences.Concat(suppressionReferences); } private static bool IsPotentialReference( ISyntaxFactsService syntaxFacts, PredefinedOperator op, SyntaxToken token) { return syntaxFacts.TryGetPredefinedOperator(token, out var actualOperator) && actualOperator == op; } } }
-1