Skip to content

Commit

Permalink
Merge pull request #636 from zvirja/enable-nullability
Browse files Browse the repository at this point in the history
Add .NET 5 target and arrange nullability attributes
  • Loading branch information
zvirja authored Dec 10, 2020
2 parents 0daeb85 + 4c488c3 commit 46d4e06
Show file tree
Hide file tree
Showing 113 changed files with 642 additions and 366 deletions.
3 changes: 3 additions & 0 deletions .editorconfig
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
root = true

[*]
trim_trailing_whitespace = true

[*.{cs,fs,fsx}]
indent_size = 4
indent_style = space
Expand Down
4 changes: 2 additions & 2 deletions .travis.yml
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
language: csharp
dist: xenial
dotnet: 2.1.502
dotnet: 5.0.100
mono: none
env: CONFIGURATION=Release FRAMEWORK=netcoreapp2.1
env: CONFIGURATION=Release FRAMEWORK=net5.0

before_script:
- dotnet --info
Expand Down
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
### unreleased
* [NEW] Add .NET 5 support

### 4.2.2 (Jun 2020)

Expand Down
5 changes: 3 additions & 2 deletions Directory.Build.props
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
<Project>

<!-- Contains global properties for all projects in the solution.
These can be overridden in inner folders, if necessary.
These can be overridden in inner folders, if necessary.
See more here https://docs.microsoft.com/en-us/visualstudio/msbuild/customize-your-build?view=vs-2019 -->

<PropertyGroup>
<TargetIsNetFx Condition="$(TargetFramework.StartsWith('net4'))">true</TargetIsNetFx>
<TargetIsNet5 Condition="'$(TargetFramework)' == 'net5.0'">true</TargetIsNet5>
<LangVersion>latest</LangVersion>
</PropertyGroup>

Expand Down
4 changes: 2 additions & 2 deletions appveyor.yml
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
os: Visual Studio 2017
os: Visual Studio 2019
build: off

environment:
CONFIGURATION: Release

install:
- set PATH=C:\Ruby22\bin;%PATH%
- set PATH=C:\Ruby25\bin;%PATH%
- bundle install

before_test:
Expand Down
5 changes: 4 additions & 1 deletion src/NSubstitute/Arg.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,9 @@
using System.Linq.Expressions;
using NSubstitute.Core.Arguments;

// Disable nullability for client API, so it does not affect clients.
#nullable disable annotations

namespace NSubstitute
{
/// <summary>
Expand Down Expand Up @@ -89,7 +92,7 @@ public static ref TDelegate InvokeDelegate<TDelegate>(params object[] arguments)
/// </summary>
public static ref T Do<T>(Action<T> useArgument)
{
return ref ArgumentMatcher.Enqueue<T>(new AnyArgumentMatcher(typeof(T)), x => useArgument((T) x));
return ref ArgumentMatcher.Enqueue<T>(new AnyArgumentMatcher(typeof(T)), x => useArgument((T) x!));
}

/// <summary>
Expand Down
9 changes: 6 additions & 3 deletions src/NSubstitute/Callback.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,9 @@
using NSubstitute.Callbacks;
using NSubstitute.Core;

// Disable nullability for client API, so it does not affect clients.
#nullable disable annotations

namespace NSubstitute
{
/// <summary>
Expand Down Expand Up @@ -72,7 +75,8 @@ public static Callback AlwaysThrow<TException>(TException exception) where TExce
return AlwaysThrow(info => exception);
}

protected static Action<CallInfo> ToCallback<TException>(Func<CallInfo, TException> throwThis) where TException : Exception
protected static Action<CallInfo> ToCallback<TException>(Func<CallInfo, TException> throwThis)
where TException : notnull, Exception
{
return ci => { if (throwThis != null) throw throwThis(ci); };
}
Expand Down Expand Up @@ -111,8 +115,7 @@ public void Call(CallInfo callInfo)

private void CallFromStack(CallInfo callInfo)
{
Action<CallInfo> callback;
if (callbackQueue.TryDequeue(out callback))
if (callbackQueue.TryDequeue(out var callback))
{
callback(callInfo);
}
Expand Down
3 changes: 3 additions & 0 deletions src/NSubstitute/Callbacks/ConfiguredCallback.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
using System;
using NSubstitute.Core;

// Disable nullability for client API, so it does not affect clients.
#nullable disable annotations

namespace NSubstitute.Callbacks
{
public class ConfiguredCallback : EndCallbackChain
Expand Down
3 changes: 3 additions & 0 deletions src/NSubstitute/Compatibility/CompatArg.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
using System;
using System.Linq.Expressions;

// Disable nullability for client API, so it does not affect clients.
#nullable disable annotations

namespace NSubstitute.Compatibility
{
/// <summary>
Expand Down
142 changes: 142 additions & 0 deletions src/NSubstitute/Compatibility/DiagnosticsNullabilityAttributes.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,142 @@
#if !SYSTEM_DIAGNOSTICS_CODEANALYSIS_NULLABILITY

// This was copied from https://github.com/dotnet/runtime/blob/39b9607807f29e48cae4652cd74735182b31182e/src/libraries/System.Private.CoreLib/src/System/Diagnostics/CodeAnalysis/NullableAttributes.cs
// and updated to have the scope of the attributes be internal.
namespace System.Diagnostics.CodeAnalysis
{

/// <summary>Specifies that null is allowed as an input even if the corresponding type disallows it.</summary>
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.Property, Inherited = false)]
internal sealed class AllowNullAttribute : Attribute { }

/// <summary>Specifies that null is disallowed as an input even if the corresponding type allows it.</summary>
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.Property, Inherited = false)]
internal sealed class DisallowNullAttribute : Attribute { }

/// <summary>Specifies that an output may be null even if the corresponding type disallows it.</summary>
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.Property | AttributeTargets.ReturnValue, Inherited = false)]
internal sealed class MaybeNullAttribute : Attribute { }

/// <summary>Specifies that an output will not be null even if the corresponding type allows it.</summary>
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.Property | AttributeTargets.ReturnValue, Inherited = false)]
internal sealed class NotNullAttribute : Attribute { }

/// <summary>Specifies that when a method returns <see cref="ReturnValue"/>, the parameter may be null even if the corresponding type disallows it.</summary>
[AttributeUsage(AttributeTargets.Parameter, Inherited = false)]
internal sealed class MaybeNullWhenAttribute : Attribute
{
/// <summary>Initializes the attribute with the specified return value condition.</summary>
/// <param name="returnValue">
/// The return value condition. If the method returns this value, the associated parameter may be null.
/// </param>
public MaybeNullWhenAttribute(bool returnValue) => ReturnValue = returnValue;

/// <summary>Gets the return value condition.</summary>
public bool ReturnValue { get; }
}

/// <summary>Specifies that when a method returns <see cref="ReturnValue"/>, the parameter will not be null even if the corresponding type allows it.</summary>
[AttributeUsage(AttributeTargets.Parameter, Inherited = false)]
internal sealed class NotNullWhenAttribute : Attribute
{
/// <summary>Initializes the attribute with the specified return value condition.</summary>
/// <param name="returnValue">
/// The return value condition. If the method returns this value, the associated parameter will not be null.
/// </param>
public NotNullWhenAttribute(bool returnValue) => ReturnValue = returnValue;

/// <summary>Gets the return value condition.</summary>
public bool ReturnValue { get; }
}

/// <summary>Specifies that the output will be non-null if the named parameter is non-null.</summary>
[AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Property | AttributeTargets.ReturnValue, AllowMultiple = true, Inherited = false)]
internal sealed class NotNullIfNotNullAttribute : Attribute
{
/// <summary>Initializes the attribute with the associated parameter name.</summary>
/// <param name="parameterName">
/// The associated parameter name. The output will be non-null if the argument to the parameter specified is non-null.
/// </param>
public NotNullIfNotNullAttribute(string parameterName) => ParameterName = parameterName;

/// <summary>Gets the associated parameter name.</summary>
public string ParameterName { get; }
}

/// <summary>Applied to a method that will never return under any circumstance.</summary>
[AttributeUsage(AttributeTargets.Method, Inherited = false)]
internal sealed class DoesNotReturnAttribute : Attribute { }

/// <summary>Specifies that the method will not return if the associated Boolean parameter is passed the specified value.</summary>
[AttributeUsage(AttributeTargets.Parameter, Inherited = false)]
internal sealed class DoesNotReturnIfAttribute : Attribute
{
/// <summary>Initializes the attribute with the specified parameter value.</summary>
/// <param name="parameterValue">
/// The condition parameter value. Code after the method will be considered unreachable by diagnostics if the argument to
/// the associated parameter matches this value.
/// </param>
public DoesNotReturnIfAttribute(bool parameterValue) => ParameterValue = parameterValue;

/// <summary>Gets the condition parameter value.</summary>
public bool ParameterValue { get; }
}

/// <summary>Specifies that the method or property will ensure that the listed field and property members have not-null values.</summary>
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Property, Inherited = false, AllowMultiple = true)]
internal sealed class MemberNotNullAttribute : Attribute
{
/// <summary>Initializes the attribute with a field or property member.</summary>
/// <param name="member">
/// The field or property member that is promised to be not-null.
/// </param>
public MemberNotNullAttribute(string member) => Members = new[] { member };

/// <summary>Initializes the attribute with the list of field and property members.</summary>
/// <param name="members">
/// The list of field and property members that are promised to be not-null.
/// </param>
public MemberNotNullAttribute(params string[] members) => Members = members;

/// <summary>Gets field or property member names.</summary>
public string[] Members { get; }
}

/// <summary>Specifies that the method or property will ensure that the listed field and property members have not-null values when returning with the specified return value condition.</summary>
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Property, Inherited = false, AllowMultiple = true)]
internal sealed class MemberNotNullWhenAttribute : Attribute
{
/// <summary>Initializes the attribute with the specified return value condition and a field or property member.</summary>
/// <param name="returnValue">
/// The return value condition. If the method returns this value, the associated parameter will not be null.
/// </param>
/// <param name="member">
/// The field or property member that is promised to be not-null.
/// </param>
public MemberNotNullWhenAttribute(bool returnValue, string member)
{
ReturnValue = returnValue;
Members = new[] { member };
}

/// <summary>Initializes the attribute with the specified return value condition and list of field and property members.</summary>
/// <param name="returnValue">
/// The return value condition. If the method returns this value, the associated parameter will not be null.
/// </param>
/// <param name="members">
/// The list of field and property members that are promised to be not-null.
/// </param>
public MemberNotNullWhenAttribute(bool returnValue, params string[] members)
{
ReturnValue = returnValue;
Members = members;
}

/// <summary>Gets the return value condition.</summary>
public bool ReturnValue { get; }

/// <summary>Gets field or property member names.</summary>
public string[] Members { get; }
}
}
#endif
20 changes: 10 additions & 10 deletions src/NSubstitute/Core/Argument.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,15 +5,15 @@ namespace NSubstitute.Core
{
public class Argument
{
private readonly ICall _call;
private readonly ICall? _call;
private readonly int _argIndex;

private readonly Type _declaredType;
private readonly Func<object> _getValue;
private readonly Action<object> _setValue;
private readonly Type? _declaredType;
private readonly Func<object?>? _getValue;
private readonly Action<object?>? _setValue;

[Obsolete("This constructor overload is deprecated and will be removed in the next version.")]
public Argument(Type declaredType, Func<object> getValue, Action<object> setValue)
public Argument(Type declaredType, Func<object?> getValue, Action<object?> setValue)
{
_declaredType = declaredType;
_getValue = getValue;
Expand All @@ -26,9 +26,9 @@ public Argument(ICall call, int argIndex)
_argIndex = argIndex;
}

public object Value
public object? Value
{
get => _getValue != null ? _getValue() : _call.GetArguments()[_argIndex];
get => _getValue != null ? _getValue() : _call!.GetArguments()[_argIndex];
set
{
if (_setValue != null)
Expand All @@ -37,14 +37,14 @@ public object Value
}
else
{
_call.GetArguments()[_argIndex] = value;
_call!.GetArguments()[_argIndex] = value;
}
}
}

public bool IsByRef => DeclaredType.IsByRef;

public Type DeclaredType => _declaredType ?? _call.GetParameterInfos()[_argIndex].ParameterType;
public Type DeclaredType => _declaredType ?? _call!.GetParameterInfos()[_argIndex].ParameterType;

public Type ActualType => Value == null ? DeclaredType : Value.GetType();

Expand All @@ -65,7 +65,7 @@ public bool CanSetValueWithInstanceOf(Type type)

private static Type AsNonByRefType(Type type)
{
return type.IsByRef ? type.GetElementType() : type;
return type.IsByRef ? type.GetElementType()! : type;
}
}
}
2 changes: 1 addition & 1 deletion src/NSubstitute/Core/Arguments/AnyArgumentMatcher.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,6 @@ public AnyArgumentMatcher(Type typeArgMustBeCompatibleWith)

public override string ToString() => "any " + _typeArgMustBeCompatibleWith.GetNonMangledTypeName();

public bool IsSatisfiedBy(object argument) => argument.IsCompatibleWith(_typeArgMustBeCompatibleWith);
public bool IsSatisfiedBy(object? argument) => argument.IsCompatibleWith(_typeArgMustBeCompatibleWith);
}
}
8 changes: 4 additions & 4 deletions src/NSubstitute/Core/Arguments/ArgumentFormatter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,13 @@ public class ArgumentFormatter : IArgumentFormatter
{
internal static IArgumentFormatter Default { get; } = new ArgumentFormatter();

public string Format(object argument, bool highlight)
public string Format(object? argument, bool highlight)
{
var formatted = Format(argument);
return highlight ? "*" + formatted + "*" : formatted;
}

private string Format(object arg)
private string Format(object? arg)
{
switch (arg)
{
Expand All @@ -24,11 +24,11 @@ private string Format(object arg)
case string str:
return string.Format(CultureInfo.InvariantCulture, "\"{0}\"", str);

case object obj when obj.GetType().GetMethod(nameof(ToString), Type.EmptyTypes).DeclaringType == typeof(object):
case object obj when obj.GetType().GetMethod(nameof(ToString), Type.EmptyTypes)!.DeclaringType == typeof(object):
return arg.GetType().GetNonMangledTypeName();

default:
return arg.ToString();
return arg.ToString() ?? string.Empty;
}
}
}
Expand Down
Loading

0 comments on commit 46d4e06

Please sign in to comment.