Skip to content

Commit

Permalink
Address new nullable warnings from compiler [MaybeNull] updates (#179)
Browse files Browse the repository at this point in the history
The compiler is updating its handling of maybe-null values, and in doing so we're getting a bunch of new warnings.  We've not yet ingested the new compiler, but this proactively addresses the warnings for when we do.
  • Loading branch information
stephentoub authored Nov 22, 2019
1 parent f23d7c0 commit 0d36b2f
Show file tree
Hide file tree
Showing 25 changed files with 47 additions and 42 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
// See the LICENSE file in the project root for more information.

using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.Serialization;

namespace System.Collections.Generic
Expand All @@ -16,7 +17,10 @@ public partial class SortedSet<T>
internal sealed class TreeSubSet : SortedSet<T>, ISerializable, IDeserializationCallback
{
private readonly SortedSet<T> _underlying;
private readonly T _min, _max;
[MaybeNull, AllowNull]
private readonly T _min;
[MaybeNull, AllowNull]
private readonly T _max;
// keeps track of whether the count variable is up to date
// up to date -> _countVersion = _underlying.version
// not up to date -> _countVersion < _underlying.version
Expand All @@ -35,7 +39,7 @@ internal override bool versionUpToDate()
}
#endif

public TreeSubSet(SortedSet<T> Underlying, T Min, T Max, bool lowerBoundActive, bool upperBoundActive)
public TreeSubSet(SortedSet<T> Underlying, [AllowNull] T Min, [AllowNull] T Max, bool lowerBoundActive, bool upperBoundActive)
: base(Underlying.Comparer)
{
_underlying = Underlying;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -757,9 +757,9 @@ internal virtual int InternalIndexOf(T item)
return -1;
}

internal Node? FindRange(T from, T to) => FindRange(from, to, lowerBoundActive: true, upperBoundActive: true);
internal Node? FindRange([AllowNull] T from, [AllowNull] T to) => FindRange(from, to, lowerBoundActive: true, upperBoundActive: true);

internal Node? FindRange(T from, T to, bool lowerBoundActive, bool upperBoundActive)
internal Node? FindRange([AllowNull] T from, [AllowNull] T to, bool lowerBoundActive, bool upperBoundActive)
{
Node? current = root;
while (current != null)
Expand Down Expand Up @@ -1561,7 +1561,7 @@ public IEnumerable<T> Reverse()
}
}

public virtual SortedSet<T> GetViewBetween(T lowerValue, T upperValue)
public virtual SortedSet<T> GetViewBetween([AllowNull] T lowerValue, [AllowNull] T upperValue)
{
if (Comparer.Compare(lowerValue, upperValue) > 0)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ private static T Reduce(IEnumerable<T> source, int sign)
Func<Pair<bool, T>, T> resultSelector = MakeResultSelectorFunction();

AssociativeAggregationOperator<T, Pair<bool, T>, T> aggregation =
new AssociativeAggregationOperator<T, Pair<bool, T>, T>(source, new Pair<bool, T>(false, default), null,
new AssociativeAggregationOperator<T, Pair<bool, T>, T>(source, new Pair<bool, T>(false, default!), null,
true, intermediateReduce, finalReduce, resultSelector, default(T)! != null, QueryAggregationOptions.AssociativeCommutative);

return aggregation.Aggregate();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,7 @@ internal override bool MoveNext(ref Pair<TInputOutput, THashKey> currentElement,
if (_source.MoveNext(ref current!, ref keyUnused))
{
currentElement = new Pair<TInputOutput, THashKey>(
current, _keySelector == null ? default : _keySelector(current));
current, _keySelector == null ? default! : _keySelector(current));
return true;
}
return false;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,7 @@ internal override bool MoveNext(ref Pair<TInputOutput, THashKey> currentElement,
if (_source.MoveNext(ref current!, ref currentKey))
{
currentElement = new Pair<TInputOutput, THashKey>(
current, _keySelector == null ? default : _keySelector(current));
current, _keySelector == null ? default! : _keySelector(current));
return true;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -297,7 +297,9 @@ internal override TSource GetElement(int index)

internal struct ConcatKey<TLeftKey, TRightKey>
{
[MaybeNull, AllowNull]
private readonly TLeftKey _leftKey;
[MaybeNull, AllowNull]
private readonly TRightKey _rightKey;
private readonly bool _isLeft;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,6 @@ internal sealed override bool MoveNext([MaybeNullWhen(false), AllowNull] ref TIn
return false;
}

protected abstract bool MoveNextCore(ref TIntermediate currentElement);
protected abstract bool MoveNextCore([MaybeNullWhen(false), AllowNull] ref TIntermediate currentElement);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ internal bool Add(TKey key, TValue value)
// Check whether value is in set
internal bool TryGetValue(TKey key, [MaybeNullWhen(false), AllowNull] ref TValue value)
{
return Find(key, false, false, ref value);
return Find(key, false, false, ref value!);
}

internal TValue this[TKey key]
Expand Down Expand Up @@ -77,7 +77,7 @@ private bool AreKeysEqual(TKey key1, TKey key2)
comparer.Equals(key1, key2));
}

private bool Find(TKey key, bool add, bool set, ref TValue value)
private bool Find(TKey key, bool add, bool set, [MaybeNullWhen(false)] ref TValue value)
{
int hashCode = GetKeyHashCode(key);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ internal struct Pair<T, U>
// A simple constructor that initializes the first/second fields.
//

public Pair(T first, [MaybeNull, AllowNull] U second)
public Pair(T first, U second)
{
_first = first;
_second = second;
Expand Down
2 changes: 1 addition & 1 deletion src/libraries/System.Linq/src/System/Linq/ElementAt.cs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ public static TSource ElementAt<TSource>(this IEnumerable<TSource> source, int i
TSource element = partition.TryGetElementAt(index, out bool found);
if (found)
{
return element;
return element!;
}
}
else
Expand Down
4 changes: 2 additions & 2 deletions src/libraries/System.Linq/src/System/Linq/First.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ public static TSource First<TSource>(this IEnumerable<TSource> source)
ThrowHelper.ThrowNoElementsException();
}

return first;
return first!;
}

public static TSource First<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate)
Expand All @@ -28,7 +28,7 @@ public static TSource First<TSource>(this IEnumerable<TSource> source, Func<TSou
ThrowHelper.ThrowNoMatchException();
}

return first;
return first!;
}

[return: MaybeNull]
Expand Down
6 changes: 2 additions & 4 deletions src/libraries/System.Linq/src/System/Linq/Iterator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@

using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;

namespace System.Linq
{
Expand Down Expand Up @@ -34,8 +33,7 @@ internal abstract class Iterator<TSource> : IEnumerable<TSource>, IEnumerator<TS
{
private readonly int _threadId;
internal int _state;
[MaybeNull, AllowNull]
internal TSource _current = default; // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/37138
internal TSource _current = default!;

/// <summary>
/// Initializes a new instance of the <see cref="Iterator{TSource}"/> class.
Expand Down Expand Up @@ -67,7 +65,7 @@ protected Iterator()
/// </remarks>
public virtual void Dispose()
{
_current = default;
_current = default!;
_state = -1;
}

Expand Down
4 changes: 2 additions & 2 deletions src/libraries/System.Linq/src/System/Linq/Last.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ public static TSource Last<TSource>(this IEnumerable<TSource> source)
ThrowHelper.ThrowNoElementsException();
}

return last;
return last!;
}

public static TSource Last<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate)
Expand All @@ -28,7 +28,7 @@ public static TSource Last<TSource>(this IEnumerable<TSource> source, Func<TSour
ThrowHelper.ThrowNoMatchException();
}

return last;
return last!;
}

[return: MaybeNull]
Expand Down
6 changes: 3 additions & 3 deletions src/libraries/System.Linq/src/System/Linq/Select.SpeedOpt.cs
Original file line number Diff line number Diff line change
Expand Up @@ -572,7 +572,7 @@ public TResult TryGetElementAt(int index, out bool found)
bool sourceFound;
TSource input = _source.TryGetElementAt(index, out sourceFound);
found = sourceFound;
return sourceFound ? _selector(input) : default!;
return sourceFound ? _selector(input!) : default!;
}

[return: MaybeNull]
Expand All @@ -581,7 +581,7 @@ public TResult TryGetFirst(out bool found)
bool sourceFound;
TSource input = _source.TryGetFirst(out sourceFound);
found = sourceFound;
return sourceFound ? _selector(input) : default!;
return sourceFound ? _selector(input!) : default!;
}

[return: MaybeNull]
Expand All @@ -590,7 +590,7 @@ public TResult TryGetLast(out bool found)
bool sourceFound;
TSource input = _source.TryGetLast(out sourceFound);
found = sourceFound;
return sourceFound ? _selector(input) : default!;
return sourceFound ? _selector(input!) : default!;
}

private TResult[] LazyToArray()
Expand Down
3 changes: 1 addition & 2 deletions src/libraries/System.Linq/src/System/Linq/Set.cs
Original file line number Diff line number Diff line change
Expand Up @@ -125,7 +125,7 @@ public bool Remove(TElement value)
}

_slots[i]._hashCode = -1;
_slots[i]._value = default;
_slots[i]._value = default!;
_slots[i]._next = -1;
return true;
}
Expand Down Expand Up @@ -235,7 +235,6 @@ private struct Slot
/// <summary>
/// The item held by this slot.
/// </summary>
[MaybeNull, AllowNull]
internal TElement _value;
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -544,7 +544,7 @@ private static T GetItemWhenAvailable(ConcurrentQueueSegment<T> segment, int i)
}

// Return the value from the slot.
return segment._slots[i].Item;
return segment._slots[i].Item!;
}

private IEnumerator<T> Enumerate(ConcurrentQueueSegment<T> head, int headHead, ConcurrentQueueSegment<T> tail, int tailTail)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -160,7 +160,7 @@ public bool TryDequeue([MaybeNullWhen(false)] out T item)
{
// Successfully reserved the slot. Note that after the above CompareExchange, other threads
// trying to dequeue from this slot will end up spinning until we do the subsequent Write.
item = slots[slotsIndex].Item;
item = slots[slotsIndex].Item!;
if (!Volatile.Read(ref _preservedForObservation))
{
// If we're preserving, though, we don't zero out the slot, as we need it for
Expand Down Expand Up @@ -230,7 +230,7 @@ public bool TryPeek([MaybeNullWhen(false)] out T result, bool resultUsed)
int diff = sequenceNumber - (currentHead + 1);
if (diff == 0)
{
result = resultUsed ? slots[slotsIndex].Item : default!;
result = resultUsed ? slots[slotsIndex].Item! : default!;
return true;
}
else if (diff < 0)
Expand Down
1 change: 1 addition & 0 deletions src/libraries/System.Private.CoreLib/src/System/Lazy.cs
Original file line number Diff line number Diff line change
Expand Up @@ -525,6 +525,7 @@ public LazyDebugView(Lazy<T> lazy)
public bool IsValueCreated => _lazy.IsValueCreated;

/// <summary>Returns the value of the Lazy object.</summary>
[MaybeNull]
public T Value => _lazy.ValueForDebugDisplay;

/// <summary>Returns the execution mode of the Lazy object</summary>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -98,8 +98,8 @@ public readonly struct AsyncLocalValueChangedArgs<T>

internal AsyncLocalValueChangedArgs([AllowNull] T previousValue, [AllowNull] T currentValue, bool contextChanged)
{
PreviousValue = previousValue;
CurrentValue = currentValue;
PreviousValue = previousValue!;
CurrentValue = currentValue!;
ThreadContextChanged = contextChanged;
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -140,7 +140,7 @@ public static T EnsureInitialized<T>([AllowNull] ref T target, ref bool initiali
// Fast path.
if (Volatile.Read(ref initialized))
{
return target;
return target!;
}

return EnsureInitializedCore(ref target, ref initialized, ref syncLock);
Expand Down Expand Up @@ -177,7 +177,7 @@ private static T EnsureInitializedCore<T>([AllowNull] ref T target, ref bool ini
}
}

return target;
return target!;
}

/// <summary>
Expand All @@ -199,7 +199,7 @@ public static T EnsureInitialized<T>([AllowNull] ref T target, ref bool initiali
// Fast path.
if (Volatile.Read(ref initialized))
{
return target;
return target!;
}

return EnsureInitializedCore(ref target, ref initialized, ref syncLock, valueFactory);
Expand Down Expand Up @@ -230,7 +230,7 @@ private static T EnsureInitializedCore<T>([AllowNull] ref T target, ref bool ini
}
}

return target;
return target!;
}

/// <summary>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ namespace System.Threading.Tasks
public class Task<TResult> : Task
{
// The value itself, if set.
[MaybeNull] internal TResult m_result = default!;
[MaybeNull, AllowNull] internal TResult m_result = default!;

private static readonly TaskFactory<TResult> s_Factory = new TaskFactory<TResult>();

Expand Down Expand Up @@ -439,7 +439,7 @@ internal void DangerousSetResult(TResult result)
public TResult Result =>
IsWaitNotificationEnabledOrNotRanToCompletion ?
GetResultCore(waitCompletionNotification: true) :
m_result;
m_result!;

/// <summary>
/// Gets the result value of this <see cref="Task{TResult}"/> once the task has completed successfully.
Expand All @@ -454,7 +454,7 @@ internal TResult ResultOnSuccess
{
Debug.Assert(!IsWaitNotificationEnabledOrNotRanToCompletion,
"Should only be used when the task completed successfully and there's no wait notification enabled");
return m_result;
return m_result!;
}
}

Expand All @@ -473,7 +473,7 @@ internal TResult GetResultCore(bool waitCompletionNotification)
// We shouldn't be here if the result has not been set.
Debug.Assert(IsCompletedSuccessfully, "Task<T>.Result getter: Expected result to have been set.");

return m_result;
return m_result!;
}

/// <summary>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -805,6 +805,7 @@ public SystemThreading_ThreadLocalDebugView(ThreadLocal<T> tlocal)
public bool IsValueCreated => _tlocal.IsValueCreated;

/// <summary>Returns the value of the ThreadLocal object.</summary>
[MaybeNull]
public T Value => _tlocal.ValueForDebugDisplay;

/// <summary>Return all values for all threads that have accessed this instance.</summary>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ public bool TryGetTarget([MaybeNullWhen(false), NotNullWhen(true)] out T target)
{
// Call the worker method that has more performant but less user friendly signature.
T o = this.Target;
target = o;
target = o!;
return o != null;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -163,7 +163,7 @@ public TResult GetResult(short token)
}

error?.Throw();
return result;
return result!;
}

/// <summary>Gets the result of the operation.</summary>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -215,7 +215,7 @@ private T DequeueItemAndPostProcess()
VoidAsyncOperationWithData<T> w = parent._blockedWriters.DequeueHead();
if (w.TrySetResult(default))
{
parent._items.EnqueueTail(w.Item);
parent._items.EnqueueTail(w.Item!);
return item;
}
}
Expand Down

0 comments on commit 0d36b2f

Please sign in to comment.