Address some new Roslyn nullability warnings (#35782)
authorLevi Broderick <GrabYourPitchforks@users.noreply.github.com>
Tue, 5 May 2020 04:59:46 +0000 (21:59 -0700)
committerGitHub <noreply@github.com>
Tue, 5 May 2020 04:59:46 +0000 (21:59 -0700)
14 files changed:
src/coreclr/src/System.Private.CoreLib/src/System/IO/FileLoadException.CoreCLR.cs
src/coreclr/src/System.Private.CoreLib/src/System/Reflection/Assembly.CoreCLR.cs
src/coreclr/src/System.Private.CoreLib/src/System/Reflection/Emit/AssemblyBuilder.cs
src/coreclr/src/System.Private.CoreLib/src/System/Reflection/RuntimeAssembly.cs
src/coreclr/src/System.Private.CoreLib/src/System/Runtime/CompilerServices/QCallHandles.cs
src/coreclr/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/ConstantSplittableMap.cs
src/coreclr/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/DictionaryToMapAdapter.cs
src/coreclr/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/IReadOnlyDictionaryToIMapViewAdapter.cs
src/libraries/System.Private.CoreLib/src/System/Array.cs
src/libraries/System.Private.CoreLib/src/System/Collections/Concurrent/ConcurrentQueue.cs
src/libraries/System.Private.CoreLib/src/System/Runtime/CompilerServices/AsyncTaskMethodBuilderT.cs
src/libraries/System.Private.CoreLib/src/System/Runtime/CompilerServices/AsyncValueTaskMethodBuilderT.cs
src/libraries/System.Private.CoreLib/src/System/Threading/LazyInitializer.cs
src/libraries/System.Threading/ref/System.Threading.cs

index 2878b89..b426926 100644 (file)
@@ -29,7 +29,7 @@ namespace System.IO
             else
                 GetMessageForHR(hResult, new StringHandleOnStack(ref message));
 
-            return string.Format(format, fileName, message);
+            return string.Format(format!, fileName, message);
         }
 
         [DllImport(RuntimeHelpers.QCall, CharSet = CharSet.Unicode)]
index c227155..8ef9d01 100644 (file)
@@ -62,7 +62,7 @@ namespace System.Reflection
         {
             RuntimeAssembly? retAssembly = null;
             GetExecutingAssemblyNative(new StackCrawlMarkHandle(ref stackMark), ObjectHandleOnStack.Create(ref retAssembly));
-            return retAssembly;
+            return retAssembly!;
         }
 
         // Get the assembly that the current code is running from.
index 2e0acab..3b19094 100644 (file)
@@ -191,7 +191,7 @@ namespace System.Reflection.Emit
                                   new StackCrawlMarkHandle(ref stackMark),
                                   (int)access,
                                   ObjectHandleOnStack.Create(ref retAssembly));
-            _internalAssemblyBuilder = (InternalAssemblyBuilder)retAssembly;
+            _internalAssemblyBuilder = (InternalAssemblyBuilder)retAssembly!;
 
             _assemblyData = new AssemblyBuilderData(_internalAssemblyBuilder, access);
 
index 60379a0..fd6eeb2 100644 (file)
@@ -327,7 +327,7 @@ namespace System.Reflection
                          throwOnFileNotFound,
                          ObjectHandleOnStack.Create(ref assemblyLoadContext),
                          ObjectHandleOnStack.Create(ref retAssembly));
-            return retAssembly;
+            return retAssembly!;
         }
 
         [DllImport(RuntimeHelpers.QCall, CharSet = CharSet.Unicode)]
index 63a8fbf..6a3418a 100644 (file)
@@ -15,7 +15,7 @@ namespace System.Runtime.CompilerServices
     {
         private void* _ptr;
 
-        internal StringHandleOnStack([NotNull] ref string? s)
+        internal StringHandleOnStack(ref string? s)
         {
             _ptr = Unsafe.AsPointer(ref s);
         }
@@ -31,7 +31,7 @@ namespace System.Runtime.CompilerServices
             _ptr = pObject;
         }
 
-        internal static ObjectHandleOnStack Create<T>([NotNull] ref T o) where T : class?
+        internal static ObjectHandleOnStack Create<T>(ref T o) where T : class?
         {
             return new ObjectHandleOnStack(Unsafe.AsPointer(ref o));
         }
index f19d63e..d7cd618 100644 (file)
@@ -78,9 +78,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
 
         public TValue Lookup(TKey key)
         {
-            bool found = TryGetValue(key, out TValue value);
-
-            if (!found)
+            if (!TryGetValue(key, out TValue value))
             {
                 Debug.Assert(key != null);
                 Exception e = new KeyNotFoundException(SR.Format(SR.Arg_KeyNotFoundWithKey, key.ToString()));
index d24a0c9..bdacad0 100644 (file)
@@ -28,9 +28,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
         internal V Lookup<K, V>(K key) where K : notnull
         {
             IDictionary<K, V> _this = Unsafe.As<IDictionary<K, V>>(this);
-            bool keyFound = _this.TryGetValue(key, out V value);
-
-            if (!keyFound)
+            if (!_this.TryGetValue(key, out V value))
             {
                 Debug.Assert(key != null);
                 Exception e = new KeyNotFoundException(SR.Format(SR.Arg_KeyNotFoundWithKey, key.ToString()));
index 5ba2469..81c3a45 100644 (file)
@@ -28,9 +28,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
         internal V Lookup<K, V>(K key) where K : notnull
         {
             IReadOnlyDictionary<K, V> _this = Unsafe.As<IReadOnlyDictionary<K, V>>(this);
-            bool keyFound = _this.TryGetValue(key, out V value);
-
-            if (!keyFound)
+            if (!_this.TryGetValue(key, out V value))
             {
                 Debug.Assert(key != null);
                 Exception e = new KeyNotFoundException(SR.Format(SR.Arg_KeyNotFoundWithKey, key.ToString()));
index fa80d26..d3753a1 100644 (file)
@@ -64,6 +64,8 @@ namespace System
                 Copy(larray, 0, newArray, 0, larray.Length > newSize ? newSize : larray.Length);
                 array = newArray;
             }
+
+            Debug.Assert(array != null);
         }
 
         public static Array CreateInstance(Type elementType, params long[] lengths)
index 480890e..b47e97c 100644 (file)
@@ -198,7 +198,7 @@ namespace System.Collections.Concurrent
         /// <remarks>For <see cref="ConcurrentQueue{T}"/>, this operation will attempt to remove the object
         /// from the beginning of the <see cref="ConcurrentQueue{T}"/>.
         /// </remarks>
-        bool IProducerConsumerCollection<T>.TryTake(out T item) => TryDequeue(out item);
+        bool IProducerConsumerCollection<T>.TryTake([MaybeNullWhen(false)] out T item) => TryDequeue(out item);
 
         /// <summary>
         /// Gets a value that indicates whether the <see cref="ConcurrentQueue{T}"/> is empty.
index 8aefd8a..e195976 100644 (file)
@@ -60,7 +60,7 @@ namespace System.Runtime.CompilerServices
             AwaitOnCompleted(ref awaiter, ref stateMachine, ref m_task);
 
         internal static void AwaitOnCompleted<TAwaiter, TStateMachine>(
-            ref TAwaiter awaiter, ref TStateMachine stateMachine, [NotNull] ref Task<TResult>? taskField)
+            ref TAwaiter awaiter, ref TStateMachine stateMachine, ref Task<TResult>? taskField)
             where TAwaiter : INotifyCompletion
             where TStateMachine : IAsyncStateMachine
         {
index d2bd7ec..c298c05 100644 (file)
@@ -150,7 +150,7 @@ namespace System.Runtime.CompilerServices
         }
 
         internal static void AwaitOnCompleted<TAwaiter, TStateMachine>(
-            ref TAwaiter awaiter, ref TStateMachine stateMachine, [NotNull] ref StateMachineBox? box)
+            ref TAwaiter awaiter, ref TStateMachine stateMachine, ref StateMachineBox? box)
             where TAwaiter : INotifyCompletion
             where TStateMachine : IAsyncStateMachine
         {
index 0e9ecac..8e2e63c 100644 (file)
@@ -49,7 +49,7 @@ namespace System.Threading
         /// </para>
         /// </remarks>
         public static T EnsureInitialized<T>([NotNull] ref T? target) where T : class =>
-            Volatile.Read(ref target) ?? EnsureInitializedCore(ref target);
+            Volatile.Read(ref target!) ?? EnsureInitializedCore(ref target);
 
         /// <summary>
         /// Initializes a target reference type with the type's default constructor (slow path)
@@ -101,7 +101,7 @@ namespace System.Threading
         /// </para>
         /// </remarks>
         public static T EnsureInitialized<T>([NotNull] ref T? target, Func<T> valueFactory) where T : class =>
-            Volatile.Read(ref target) ?? EnsureInitializedCore(ref target, valueFactory);
+            Volatile.Read(ref target!) ?? EnsureInitializedCore(ref target, valueFactory);
 
         /// <summary>
         /// Initialize the target using the given delegate (slow path).
@@ -133,9 +133,10 @@ namespace System.Threading
         /// <param name="initialized">A reference to a boolean that determines whether the target has already
         /// been initialized.</param>
         /// <param name="syncLock">A reference to an object used as the mutually exclusive lock for initializing
-        /// <paramref name="target"/>. If <paramref name="syncLock"/> is null, a new object will be instantiated.</param>
+        /// <paramref name="target"/>. If <paramref name="syncLock"/> is null, and if the target hasn't already
+        /// been initialized, a new object will be instantiated.</param>
         /// <returns>The initialized value of type <typeparamref name="T"/>.</returns>
-        public static T EnsureInitialized<T>([AllowNull] ref T target, ref bool initialized, [NotNull] ref object? syncLock)
+        public static T EnsureInitialized<T>([AllowNull] ref T target, ref bool initialized, [NotNullIfNotNull("syncLock")] ref object? syncLock)
         {
             // Fast path.
             if (Volatile.Read(ref initialized))
@@ -190,11 +191,12 @@ namespace System.Threading
         /// <param name="initialized">A reference to a boolean that determines whether the target has already
         /// been initialized.</param>
         /// <param name="syncLock">A reference to an object used as the mutually exclusive lock for initializing
-        /// <paramref name="target"/>. If <paramref name="syncLock"/> is null, a new object will be instantiated.</param>
+        /// <paramref name="target"/>. If <paramref name="syncLock"/> is null, and if the target hasn't already
+        /// been initialized, a new object will be instantiated.</param>
         /// <param name="valueFactory">The <see cref="System.Func{T}"/> invoked to initialize the
         /// reference or value.</param>
         /// <returns>The initialized value of type <typeparamref name="T"/>.</returns>
-        public static T EnsureInitialized<T>([AllowNull] ref T target, ref bool initialized, [NotNull] ref object? syncLock, Func<T> valueFactory)
+        public static T EnsureInitialized<T>([AllowNull] ref T target, ref bool initialized, [NotNullIfNotNull("syncLock")] ref object? syncLock, Func<T> valueFactory)
         {
             // Fast path.
             if (Volatile.Read(ref initialized))
@@ -239,11 +241,12 @@ namespace System.Threading
         /// <typeparam name="T">The type of the reference to be initialized. Has to be reference type.</typeparam>
         /// <param name="target">A reference of type <typeparamref name="T"/> to initialize if it has not already been initialized.</param>
         /// <param name="syncLock">A reference to an object used as the mutually exclusive lock for initializing
-        /// <paramref name="target"/>. If <paramref name="syncLock"/> is null, a new object will be instantiated.</param>
+        /// <paramref name="target"/>. If <paramref name="syncLock"/> is null, and if the target hasn't already
+        /// been initialized, a new object will be instantiated.</param>
         /// <param name="valueFactory">The <see cref="System.Func{T}"/> invoked to initialize the reference.</param>
         /// <returns>The initialized value of type <typeparamref name="T"/>.</returns>
-        public static T EnsureInitialized<T>([NotNull] ref T? target, [NotNull] ref object? syncLock, Func<T> valueFactory) where T : class =>
-            Volatile.Read(ref target) ?? EnsureInitializedCore(ref target, ref syncLock, valueFactory);
+        public static T EnsureInitialized<T>([NotNull] ref T? target, [NotNullIfNotNull("syncLock")] ref object? syncLock, Func<T> valueFactory) where T : class =>
+            Volatile.Read(ref target!) ?? EnsureInitializedCore(ref target, ref syncLock, valueFactory);
 
         /// <summary>
         /// Ensure the target is initialized and return the value (slow path). This overload works only for reference type targets.
@@ -272,7 +275,8 @@ namespace System.Threading
                 }
             }
 
-            return target!; // TODO-NULLABLE: Compiler can't infer target's non-nullness (https://github.com/dotnet/roslyn/issues/37300)
+            Debug.Assert(target != null);
+            return target;
         }
 
         /// <summary>
index 4c8dabc..719a4c3 100644 (file)
@@ -216,10 +216,10 @@ namespace System.Threading
     public static partial class LazyInitializer
     {
         public static T EnsureInitialized<T>([System.Diagnostics.CodeAnalysis.NotNullAttribute] ref T? target) where T : class { throw null; }
-        public static T EnsureInitialized<T>([System.Diagnostics.CodeAnalysis.AllowNullAttribute] ref T target, ref bool initialized, [System.Diagnostics.CodeAnalysis.NotNullAttribute] ref object? syncLock) { throw null; }
-        public static T EnsureInitialized<T>([System.Diagnostics.CodeAnalysis.AllowNullAttribute] ref T target, ref bool initialized, [System.Diagnostics.CodeAnalysis.NotNullAttribute] ref object? syncLock, System.Func<T> valueFactory) { throw null; }
+        public static T EnsureInitialized<T>([System.Diagnostics.CodeAnalysis.AllowNullAttribute] ref T target, ref bool initialized, [System.Diagnostics.CodeAnalysis.NotNullIfNotNullAttribute("syncLock")] ref object? syncLock) { throw null; }
+        public static T EnsureInitialized<T>([System.Diagnostics.CodeAnalysis.AllowNullAttribute] ref T target, ref bool initialized, [System.Diagnostics.CodeAnalysis.NotNullIfNotNullAttribute("syncLock")] ref object? syncLock, System.Func<T> valueFactory) { throw null; }
         public static T EnsureInitialized<T>([System.Diagnostics.CodeAnalysis.NotNullAttribute] ref T? target, System.Func<T> valueFactory) where T : class { throw null; }
-        public static T EnsureInitialized<T>([System.Diagnostics.CodeAnalysis.NotNullAttribute] ref T? target, [System.Diagnostics.CodeAnalysis.NotNullAttribute] ref object? syncLock, System.Func<T> valueFactory) where T : class { throw null; }
+        public static T EnsureInitialized<T>([System.Diagnostics.CodeAnalysis.NotNullAttribute] ref T? target, [System.Diagnostics.CodeAnalysis.NotNullIfNotNullAttribute("syncLock")] ref object? syncLock, System.Func<T> valueFactory) where T : class { throw null; }
     }
     public partial struct LockCookie
     {