Skip to content

Commit

Permalink
Fix exception expressions
Browse files Browse the repository at this point in the history
  • Loading branch information
afxres committed May 26, 2024
1 parent a7d01dd commit b1041ea
Show file tree
Hide file tree
Showing 18 changed files with 36 additions and 74 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
using Mikodev.Binary.Attributes;
using System;
using System.Collections.Generic;
using System.Linq;
using Xunit;

[SourceGeneratorContext]
Expand Down Expand Up @@ -43,29 +42,22 @@ public void EncodeNullValueTest<T>(T source) where T : class
var bufferSecond = converterSecond.Encode(source);
Assert.Equal(buffer, bufferSecond);

var a = Assert.Throws<ArgumentNullException>(() => converter.Encode(null));
var b = Assert.Throws<ArgumentNullException>(() => converterSecond.Encode(null));
var c = Assert.Throws<ArgumentNullException>(() =>
var a = Assert.Throws<ArgumentException>(() => converter.Encode(null));
var b = Assert.Throws<ArgumentException>(() => converterSecond.Encode(null));
var c = Assert.Throws<ArgumentException>(() =>
{
var allocator = new Allocator();
converter.EncodeAuto(ref allocator, null);
});
var d = Assert.Throws<ArgumentNullException>(() =>
var d = Assert.Throws<ArgumentException>(() =>
{
var allocator = new Allocator();
converterSecond.EncodeAuto(ref allocator, null);
});

var h = Converter.GetMethod(converter, "Encode");
var i = Converter.GetMethod(converterSecond, "Encode");
var j = Converter.GetMethod(converter, "EncodeAuto");
var k = Converter.GetMethod(converterSecond, "EncodeAuto");
var message = $"Tuple can not be null, type: {typeof(T)}";
var exceptions = new[] { a, b, c, d };
var parameters = new[] { h, i, j, k }.Select(x => x.GetParameters()[1]);

Assert.All(parameters, x => Assert.Equal("item", x.Name));
Assert.All(exceptions, x => Assert.Equal("item", x.ParamName));
Assert.All(exceptions, x => Assert.Null(x.ParamName));
Assert.All(exceptions, x => Assert.StartsWith(message, x.Message));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -37,10 +37,10 @@ private void AppendExceptMethod()
{
if (Symbol.IsValueType)
return;
Output.AppendIndent(2, $"[System.Diagnostics.CodeAnalysis.DoesNotReturn]");
Output.AppendIndent(2, $"[System.Diagnostics.DebuggerStepThrough, System.Diagnostics.CodeAnalysis.DoesNotReturn]");
Output.AppendIndent(2, $"private static void Except()");
Output.AppendIndent(2, $"{{");
Output.AppendIndent(3, $"throw new System.ArgumentNullException(\"item\", $\"Tuple can not be null, type: {{typeof({SymbolTypeFullName})}}\");");
Output.AppendIndent(3, $"throw new System.ArgumentException($\"Tuple can not be null, type: {{typeof({SymbolTypeFullName})}}\");");
Output.AppendIndent(2, $"}}");
Output.AppendIndent();
CancellationToken.ThrowIfCancellationRequested();
Expand Down
8 changes: 4 additions & 4 deletions code/Binary.Tests.FSharp/Attributes/AttributeTests.fs
Original file line number Diff line number Diff line change
Expand Up @@ -820,12 +820,12 @@ type AttributeTests() =
[<InlineData(typeof<ClassAsTupleObjectWithPartiallyKey>)>]
member __.``Tuple Object Null`` (t : Type) =
let converter = generator.GetConverter t |> box :?> IConverter
let alpha = Assert.Throws<ArgumentNullException>(fun () -> let mutable allocator = Allocator() in converter.Encode(&allocator, null))
let bravo = Assert.Throws<ArgumentNullException>(fun () -> converter.Encode null |> ignore)
let alpha = Assert.Throws<ArgumentException>(fun () -> let mutable allocator = Allocator() in converter.Encode(&allocator, null))
let bravo = Assert.Throws<ArgumentException>(fun () -> converter.Encode null |> ignore)
let message = sprintf "Tuple can not be null, type: %O" t
Assert.Equal("item", alpha.ParamName)
Assert.Null(alpha.ParamName)
Assert.StartsWith(message, alpha.Message)
Assert.Equal("item", bravo.ParamName)
Assert.Null(bravo.ParamName)
Assert.StartsWith(message, bravo.Message)
()

Expand Down
10 changes: 0 additions & 10 deletions code/Binary.Tests.FSharp/Contexts/AllocatorModuleTests.fs
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,6 @@ let ``Append Action (default constructor, length invalid)`` (length : int) =
let methodInfos = allocatorType.GetMethods() |> Array.filter (fun x -> x.Name = "Append" && x.GetParameters().Length = 4)
let methodInfo = methodInfos |> Array.filter (fun x -> x.GetParameters().[3].ParameterType.Name.StartsWith "SpanAction`2") |> Array.exactlyOne
let parameter = methodInfo.GetParameters().[1]
Assert.StartsWith("Argument length must be greater than or equal to zero!", error.Message)
Assert.Equal("length", error.ParamName)
Assert.Equal("length", parameter.Name)
()
Expand All @@ -64,7 +63,6 @@ let ``Append Max Length (default constructor, max length invalid)`` (maxLength :
let methodInfos = allocatorType.GetMethods() |> Array.filter (fun x -> x.Name = "Append" && x.GetParameters().Length = 4)
let methodInfo = methodInfos |> Array.filter (fun x -> x.GetParameters().[3].ParameterType.Name.StartsWith "AllocatorWriter`1") |> Array.exactlyOne
let parameter = methodInfo.GetParameters().[1]
Assert.StartsWith("Argument max length must be greater than or equal to zero!", error.Message)
Assert.Equal("maxLength", error.ParamName)
Assert.Equal("maxLength", parameter.Name)
()
Expand All @@ -81,7 +79,6 @@ let ``Append Max Length With Length Prefix (default constructor, max length inva
let methodInfos = allocatorType.GetMethods() |> Array.filter (fun x -> x.Name = "AppendWithLengthPrefix" && x.GetParameters().Length = 4)
let methodInfo = methodInfos |> Array.filter (fun x -> x.GetParameters().[3].ParameterType.Name.StartsWith "AllocatorWriter`1") |> Array.exactlyOne
let parameter = methodInfo.GetParameters().[1]
Assert.StartsWith("Argument max length must be greater than or equal to zero!", error.Message)
Assert.Equal("maxLength", error.ParamName)
Assert.Equal("maxLength", parameter.Name)
()
Expand All @@ -92,7 +89,6 @@ let ``Append Action (default constructor, length overflow)`` () =
let mutable allocator = Allocator()
Allocator.Append(&allocator, Int32.MaxValue + 1, null :> obj, fun a b -> raise (NotSupportedException()); ())
())
Assert.StartsWith("Argument length must be greater than or equal to zero!", error.Message)
Assert.Equal("length", error.ParamName)
()

Expand All @@ -102,7 +98,6 @@ let ``Append Max Length (default constructor, max length overflow)`` () =
let mutable allocator = Allocator()
Allocator.Append(&allocator, Int32.MaxValue + 1, null :> obj, fun a b -> raise (NotSupportedException()); -1)
())
Assert.StartsWith("Argument max length must be greater than or equal to zero!", error.Message)
Assert.Equal("maxLength", error.ParamName)
()

Expand All @@ -112,7 +107,6 @@ let ``Append Max Length With Length Prefix (default constructor, max length over
let mutable allocator = Allocator()
Allocator.AppendWithLengthPrefix(&allocator, Int32.MaxValue + 1, null :> obj, fun a b -> raise (NotSupportedException()); -1)
())
Assert.StartsWith("Argument max length must be greater than or equal to zero!", error.Message)
Assert.Equal("maxLength", error.ParamName)
()

Expand Down Expand Up @@ -162,7 +156,6 @@ let ``Append Action (append some then, length invalid)`` (length : int) =
Allocator.Append(&allocator, length, null :> obj, fun a b -> raise (NotSupportedException()); ())
())
Assert.Equal(1, flag)
Assert.StartsWith("Argument length must be greater than or equal to zero!", error.Message)
Assert.Equal("length", error.ParamName)
()

Expand All @@ -179,7 +172,6 @@ let ``Append Max Length (append some then, max length invalid)`` (maxLength : in
Allocator.Append(&allocator, maxLength, null :> obj, fun a b -> raise (NotSupportedException()); -1)
())
Assert.Equal(1, flag)
Assert.StartsWith("Argument max length must be greater than or equal to zero!", error.Message)
Assert.Equal("maxLength", error.ParamName)
()

Expand All @@ -196,7 +188,6 @@ let ``Append Max Length With Length Prefix (append some then, max length invalid
Allocator.AppendWithLengthPrefix(&allocator, maxLength, null :> obj, fun a b -> raise (NotSupportedException()); -1)
())
Assert.Equal(1, flag)
Assert.StartsWith("Argument max length must be greater than or equal to zero!", error.Message)
Assert.Equal("maxLength", error.ParamName)
()

Expand Down Expand Up @@ -444,7 +435,6 @@ let ``Ensure (negative)`` (maxCapacity : int, offset : int, length : int) =
let parameter = methodInfo.GetParameters() |> Array.last
Assert.Equal("length", parameter.Name)
Assert.Equal("length", error.ParamName)
Assert.StartsWith("Argument length must be greater than or equal to zero!", error.Message)
()

[<Theory>]
Expand Down
2 changes: 0 additions & 2 deletions code/Binary.Tests.FSharp/Contexts/AllocatorTests.fs
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,6 @@ let ``Constructor (argument out of range)`` (limits : int) =
Assert.Equal("maxCapacity", parameterName)
Assert.Equal("maxCapacity", a.ParamName)
Assert.Equal("maxCapacity", b.ParamName)
Assert.StartsWith("Argument max capacity must be greater than or equal to zero!", a.Message)
Assert.StartsWith("Argument max capacity must be greater than or equal to zero!", b.Message)
()

[<Fact>]
Expand Down
1 change: 0 additions & 1 deletion code/Binary.Tests.FSharp/Contexts/ConverterTests.fs
Original file line number Diff line number Diff line change
Expand Up @@ -175,7 +175,6 @@ type ConverterTests() =
let error = Assert.Throws<ArgumentOutOfRangeException>(fun () -> CustomConverter<obj>(length) |> ignore)
Assert.Equal("length", parameter.Name)
Assert.Equal("length", error.ParamName)
Assert.StartsWith("Argument length must be greater than or equal to zero!", error.Message)
()

[<Theory>]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,7 @@ type GeneratorObjectConverterTests() =
[<Theory>]
[<MemberData("Encode Arguments")>]
member __.``Encode Object Instance`` (action : Action<obj>, _ : string) =
let error = Assert.Throws<NotSupportedException>(fun () -> action.Invoke(obj()))
let error = Assert.Throws<ArgumentException>(fun () -> action.Invoke(obj()))
let message = "Can not encode object, type: System.Object"
Assert.Equal(message, error.Message)
()
Expand Down
2 changes: 1 addition & 1 deletion code/Binary.Tests.FSharp/Contexts/GeneratorTests.fs
Original file line number Diff line number Diff line change
Expand Up @@ -112,7 +112,7 @@ let ``Get Converter (non-generic collection)`` () =
[<Fact>]
let ``Encode (obj, instance)`` () =
let source = obj()
let error = Assert.Throws<NotSupportedException>(fun () -> generator.Encode source |> ignore)
let error = Assert.Throws<ArgumentException>(fun () -> generator.Encode source |> ignore)
Assert.Equal("Can not encode object, type: System.Object", error.Message)
()

Expand Down
8 changes: 4 additions & 4 deletions code/Binary.Tests.FSharp/TupleLike/TupleTests.fs
Original file line number Diff line number Diff line change
Expand Up @@ -33,11 +33,11 @@ let TestNull<'T> () =
let value = Unchecked.defaultof<'T>
let converter = generator.GetConverter<'T> ()
let message = sprintf "Tuple can not be null, type: %O" typeof<'T>
let alpha = Assert.Throws<ArgumentNullException>(fun () -> let mutable allocator = Allocator() in converter.Encode(&allocator, value))
Assert.Equal("item", alpha.ParamName)
let alpha = Assert.Throws<ArgumentException>(fun () -> let mutable allocator = Allocator() in converter.Encode(&allocator, value))
Assert.Null(alpha.ParamName)
Assert.StartsWith(message, alpha.Message)
let bravo = Assert.Throws<ArgumentNullException>(fun () -> let mutable allocator = Allocator() in converter.EncodeAuto(&allocator, value))
Assert.Equal("item", bravo.ParamName)
let bravo = Assert.Throws<ArgumentException>(fun () -> let mutable allocator = Allocator() in converter.EncodeAuto(&allocator, value))
Assert.Null(bravo.ParamName)
Assert.StartsWith(message, bravo.Message)
()

Expand Down
2 changes: 0 additions & 2 deletions code/Binary.Tests/Contexts/ConverterStaticTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,6 @@ public void EncodeByAllocatorOverflowTest(int number)
var parameters = method.GetParameters();
Assert.Equal("number", error.ParamName);
Assert.Equal("number", parameters[1].Name);
Assert.StartsWith("Argument number must be greater than or equal to zero!", error.Message);
}

private delegate void Write(Span<byte> span, int number, out int written);
Expand All @@ -47,7 +46,6 @@ public void EncodeBySpanOverflowTest(int number)
var parameters = method.GetParameters();
Assert.Equal("number", error.ParamName);
Assert.Equal("number", parameters[1].Name);
Assert.StartsWith("Argument number must be greater than or equal to zero!", error.Message);
}

[Theory(DisplayName = "Encode Decode Integration Test")]
Expand Down
2 changes: 0 additions & 2 deletions code/Binary.Tests/Contexts/ConverterStreamTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,6 @@ public void EncodeInvalidNumberTest(int number)
var parameters = method.GetParameters();
Assert.Equal("number", error.ParamName);
Assert.Equal("number", parameters[1].Name);
Assert.StartsWith("Argument number must be greater than or equal to zero!", error.Message);
}

[Theory(DisplayName = "Encode Invalid Number Async")]
Expand All @@ -80,7 +79,6 @@ public async Task EncodeInvalidNumberTestAsync(int number)
var parameters = method.GetParameters();
Assert.Equal("number", error.ParamName);
Assert.Equal("number", parameters[1].Name);
Assert.StartsWith("Argument number must be greater than or equal to zero!", error.Message);
}

private class TestStream : Stream
Expand Down
4 changes: 2 additions & 2 deletions code/Binary/Allocator.Invoke.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
namespace Mikodev.Binary;

using Mikodev.Binary.Internal;
using System;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
Expand All @@ -9,8 +10,7 @@ public ref partial struct Allocator
{
private static void Resize(ref Allocator allocator, int length)
{
if (length <= 0)
ThrowHelper.ThrowLengthNegative();
ArgumentOutOfRangeException.ThrowIfNegativeOrZero(length);
var offset = allocator.offset;
Debug.Assert(offset >= 0);
var limits = allocator.MaxCapacity;
Expand Down
6 changes: 2 additions & 4 deletions code/Binary/Allocator.Module.cs
Original file line number Diff line number Diff line change
Expand Up @@ -35,8 +35,7 @@ public static void Append<T>(ref Allocator allocator, int length, T data, SpanAc
public static void Append<T>(ref Allocator allocator, int maxLength, T data, AllocatorWriter<T> writer)
{
ArgumentNullException.ThrowIfNull(writer);
if (maxLength < 0)
ThrowHelper.ThrowMaxLengthNegative();
ArgumentOutOfRangeException.ThrowIfNegative(maxLength);
if (maxLength is 0)
return;
ref var target = ref Create(ref allocator, maxLength);
Expand All @@ -51,8 +50,7 @@ public static void Append<T>(ref Allocator allocator, int maxLength, T data, All
public static void AppendWithLengthPrefix<T>(ref Allocator allocator, int maxLength, T data, AllocatorWriter<T> writer)
{
ArgumentNullException.ThrowIfNull(writer);
if (maxLength < 0)
ThrowHelper.ThrowMaxLengthNegative();
ArgumentOutOfRangeException.ThrowIfNegative(maxLength);
var numberLength = NumberModule.EncodeLength((uint)maxLength);
ref var target = ref Create(ref allocator, maxLength + numberLength);
var actual = maxLength is 0 ? 0 : writer.Invoke(MemoryMarshal.CreateSpan(ref Unsafe.Add(ref target, numberLength), maxLength), data);
Expand Down
6 changes: 2 additions & 4 deletions code/Binary/Allocator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -39,8 +39,7 @@ public Allocator(Span<byte> span)
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public Allocator(Span<byte> span, int maxCapacity)
{
if (maxCapacity < 0)
ThrowHelper.ThrowMaxCapacityNegative();
ArgumentOutOfRangeException.ThrowIfNegative(maxCapacity);
this.underlying = null;
this.target = ref MemoryMarshal.GetReference(span);
this.bounds = Math.Min(span.Length, maxCapacity);
Expand All @@ -63,8 +62,7 @@ public Allocator(IAllocator underlyingAllocator)
public Allocator(IAllocator underlyingAllocator, int maxCapacity)
{
ArgumentNullException.ThrowIfNull(underlyingAllocator);
if (maxCapacity < 0)
ThrowHelper.ThrowMaxCapacityNegative();
ArgumentOutOfRangeException.ThrowIfNegative(maxCapacity);
this.underlying = underlyingAllocator;
this.target = ref Unsafe.NullRef<byte>();
this.bounds = 0;
Expand Down
6 changes: 2 additions & 4 deletions code/Binary/Converter.Static.cs
Original file line number Diff line number Diff line change
Expand Up @@ -28,8 +28,7 @@ public static MethodInfo GetMethod(IConverter converter, string name)

public static void Encode(scoped Span<byte> span, int number, out int bytesWritten)
{
if (number < 0)
ThrowHelper.ThrowNumberNegative();
ArgumentOutOfRangeException.ThrowIfNegative(number);
var numberLength = NumberModule.EncodeLength((uint)number);
if (span.Length < numberLength)
ThrowHelper.ThrowNotEnoughBytesToWrite();
Expand All @@ -49,8 +48,7 @@ public static int Decode(scoped ReadOnlySpan<byte> span, out int bytesRead)

public static void Encode(ref Allocator allocator, int number)
{
if (number < 0)
ThrowHelper.ThrowNumberNegative();
ArgumentOutOfRangeException.ThrowIfNegative(number);
var numberLength = NumberModule.EncodeLength((uint)number);
NumberModule.Encode(ref Allocator.Assign(ref allocator, numberLength), (uint)number, numberLength);
}
Expand Down
3 changes: 1 addition & 2 deletions code/Binary/Converter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,7 @@ protected Converter() : this(0) { }

protected Converter(int length)
{
if (length < 0)
ThrowHelper.ThrowLengthNegative();
ArgumentOutOfRangeException.ThrowIfNegative(length);
var parent = typeof(Converter<T>);
if (new DecodeDelegate<T>(DecodeAuto).Method.DeclaringType == parent && new DecodeDelegate<T>(DecodeWithLengthPrefix).Method.DeclaringType != parent)
ThrowHelper.ThrowNotOverride(nameof(DecodeAuto), nameof(DecodeWithLengthPrefix), GetType());
Expand Down
12 changes: 9 additions & 3 deletions code/Binary/Internal.Contexts/GeneratorObjectConverter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,18 +10,24 @@ internal sealed class GeneratorObjectConverter(IGenerator generator) : Converter
private readonly IGenerator generator = generator;

[DebuggerStepThrough, DoesNotReturn]
private static void ExceptNull() => throw new ArgumentException("Can not get type of null object.");
private static void ExceptNull()
{
throw new ArgumentException("Can not get type of null object.");
}

[DebuggerStepThrough, DoesNotReturn]
private static void ExceptEncode() => throw new NotSupportedException($"Can not encode object, type: {typeof(object)}");
private static void ExceptType()
{
throw new ArgumentException($"Can not encode object, type: {typeof(object)}");
}

private IConverter Ensure(object? item)
{
if (item is null)
ExceptNull();
var type = item.GetType();
if (type == typeof(object))
ExceptEncode();
ExceptType();
RuntimeHelpers.EnsureSufficientExecutionStack();
return this.generator.GetConverter(type);
}
Expand Down
14 changes: 1 addition & 13 deletions code/Binary/Internal/ThrowHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,26 +10,14 @@ internal static class ThrowHelper
[DoesNotReturn]
internal static void ThrowAllocatorInvalid() => throw new InvalidOperationException("Allocator has been modified unexpectedly!");

[DoesNotReturn]
internal static void ThrowLengthNegative() => throw new ArgumentOutOfRangeException("length", "Argument length must be greater than or equal to zero!");

[DoesNotReturn]
internal static void ThrowNumberNegative() => throw new ArgumentOutOfRangeException("number", "Argument number must be greater than or equal to zero!");

[DoesNotReturn]
internal static void ThrowMaxLengthNegative() => throw new ArgumentOutOfRangeException("maxLength", "Argument max length must be greater than or equal to zero!");

[DoesNotReturn]
internal static void ThrowMaxCapacityNegative() => throw new ArgumentOutOfRangeException("maxCapacity", "Argument max capacity must be greater than or equal to zero!");

[DoesNotReturn]
internal static void ThrowMaxCapacityOverflow() => throw new ArgumentException("Maximum capacity has been reached.");

[DoesNotReturn]
internal static void ThrowInvalidReturnValue() => throw new InvalidOperationException("Invalid return value.");

[DoesNotReturn]
internal static void ThrowTupleNull<T>() => throw new ArgumentNullException("item", $"Tuple can not be null, type: {typeof(T)}");
internal static void ThrowTupleNull<T>() => throw new ArgumentException($"Tuple can not be null, type: {typeof(T)}");

[DoesNotReturn]
internal static void ThrowNotEnoughBytesCollection<T>(int byteLength) => throw new ArgumentException($"Not enough bytes for collection element, byte length: {byteLength}, element type: {typeof(T)}");
Expand Down

0 comments on commit b1041ea

Please sign in to comment.