From 3d48a6fb0c8e3e8f19a6c2b2b5239fb5cb0ae61e Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Fri, 20 Nov 2020 11:46:19 +0100 Subject: [PATCH] Added ThrowHelper type --- .../Extensions/HResultExtensions.cs | 5 +- src/ComputeSharp.Core/Helpers/ThrowHelper.cs | 93 +++++++++++++++++++ .../Extensions/ID3D12DeviceExtensions.cs | 3 +- src/ComputeSharp.Graphics/GraphicsDevice.cs | 7 +- .../Helpers/DeviceHelper.cs | 8 +- .../Extensions/ILGeneratorExtensions.cs | 5 +- .../Extensions/SyntaxNodeExtensions.cs | 9 +- .../Translation/MethodDecompiler.cs | 3 +- .../Translation/Models/ReadableMember.cs | 5 +- .../Translation/ShaderLoader{T}.IL.cs | 6 +- .../Translation/ShaderLoader{T}.cs | 8 +- 11 files changed, 125 insertions(+), 27 deletions(-) create mode 100644 src/ComputeSharp.Core/Helpers/ThrowHelper.cs diff --git a/src/ComputeSharp.Core/Extensions/HResultExtensions.cs b/src/ComputeSharp.Core/Extensions/HResultExtensions.cs index 2a816833..549fac1d 100644 --- a/src/ComputeSharp.Core/Extensions/HResultExtensions.cs +++ b/src/ComputeSharp.Core/Extensions/HResultExtensions.cs @@ -1,6 +1,7 @@ using System.ComponentModel; using System.Diagnostics; using System.Runtime.CompilerServices; +using ComputeSharp.Core.Helpers; using HRESULT = System.Int32; namespace ComputeSharp.Graphics.Helpers @@ -21,9 +22,7 @@ namespace ComputeSharp.Graphics.Helpers { if (result < 0) { - static void Throw(HRESULT result) => throw new Win32Exception(result); - - Throw(result); + ThrowHelper.ThrowWin32Exception(result); } } } diff --git a/src/ComputeSharp.Core/Helpers/ThrowHelper.cs b/src/ComputeSharp.Core/Helpers/ThrowHelper.cs new file mode 100644 index 00000000..15586d1a --- /dev/null +++ b/src/ComputeSharp.Core/Helpers/ThrowHelper.cs @@ -0,0 +1,93 @@ +using System; +using System.ComponentModel; +using System.Diagnostics.CodeAnalysis; + +namespace ComputeSharp.Core.Helpers +{ + /// + /// Helper methods to efficiently throw exceptions. + /// + internal static partial class ThrowHelper + { + /// + /// Throws a new . + /// + /// Thrown with no parameters. + [DoesNotReturn] + public static void ThrowArgumentException() + { + throw new ArgumentException(); + } + + /// + /// Throws a new . + /// + /// The message to include in the exception. + /// Thrown with the specified parameter. + [DoesNotReturn] + public static void ThrowArgumentException(string message) + { + throw new ArgumentException(message); + } + + /// + /// Throws a new . + /// + /// The message to include in the exception. + /// Thrown with the specified parameter. + [DoesNotReturn] + public static void ThrowInvalidOperationException(string message) + { + throw new InvalidOperationException(message); + } + + /// + /// Throws a new . + /// + /// The Win32 error code associated with this exception. + /// Thrown with the specified parameter. + [DoesNotReturn] + public static void ThrowWin32Exception(int error) + { + throw new Win32Exception(error); + } + + /// + /// Throws a new . + /// + /// The type of expected result. + /// Thrown with no parameters. + /// This method always throws, so it actually never returns a value. + [DoesNotReturn] + public static T ThrowArgumentException() + { + throw new ArgumentException(); + } + + /// + /// Throws a new . + /// + /// The type of expected result. + /// The message to include in the exception. + /// Thrown with the specified parameter. + /// This method always throws, so it actually never returns a value. + [DoesNotReturn] + public static T ThrowArgumentException(string message) + { + throw new ArgumentException(message); + } + + /// + /// Throws a new . + /// + /// The type of expected result. + /// The message to include in the exception. + /// Thrown with the specified parameter. + /// This method always throws, so it actually never returns a value. + [DoesNotReturn] + public static T ThrowNotSupportedException(string message) + { + throw new NotSupportedException(message); + } + } +} \ No newline at end of file diff --git a/src/ComputeSharp.Graphics/Extensions/ID3D12DeviceExtensions.cs b/src/ComputeSharp.Graphics/Extensions/ID3D12DeviceExtensions.cs index 38cb3e7c..99678bed 100644 --- a/src/ComputeSharp.Graphics/Extensions/ID3D12DeviceExtensions.cs +++ b/src/ComputeSharp.Graphics/Extensions/ID3D12DeviceExtensions.cs @@ -14,6 +14,7 @@ using static TerraFX.Interop.D3D12_HEAP_TYPE; using static TerraFX.Interop.D3D12_RESOURCE_FLAGS; using static TerraFX.Interop.D3D12_RESOURCE_STATES; using FX = TerraFX.Interop.Windows; +using ComputeSharp.Core.Helpers; namespace ComputeSharp.Graphics.Extensions { @@ -116,7 +117,7 @@ namespace ComputeSharp.Graphics.Extensions BufferType.ReadWrite => (D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COMMON), BufferType.ReadBack => (D3D12_HEAP_TYPE_READBACK, D3D12_RESOURCE_FLAG_NONE, D3D12_RESOURCE_STATE_COPY_DEST), BufferType.Upload => (D3D12_HEAP_TYPE_UPLOAD, D3D12_RESOURCE_FLAG_NONE, D3D12_RESOURCE_STATE_GENERIC_READ), - _ => throw null! + _ => ThrowHelper.ThrowArgumentException<(D3D12_HEAP_TYPE, D3D12_RESOURCE_FLAGS, D3D12_RESOURCE_STATES)>() }; using ComPtr d3D12Resource = default; diff --git a/src/ComputeSharp.Graphics/GraphicsDevice.cs b/src/ComputeSharp.Graphics/GraphicsDevice.cs index c9535d94..7b10dee5 100644 --- a/src/ComputeSharp.Graphics/GraphicsDevice.cs +++ b/src/ComputeSharp.Graphics/GraphicsDevice.cs @@ -1,4 +1,5 @@ -using ComputeSharp.Core.Interop; +using ComputeSharp.Core.Helpers; +using ComputeSharp.Core.Interop; using ComputeSharp.Graphics.Commands; using ComputeSharp.Graphics.Extensions; using ComputeSharp.Graphics.Helpers; @@ -137,7 +138,7 @@ namespace ComputeSharp.Graphics { D3D12_COMMAND_LIST_TYPE_COMPUTE => this.computeCommandAllocatorPool.GetCommandAllocator(this.d3D12Device, this.d3D12ComputeFence), D3D12_COMMAND_LIST_TYPE_COPY => this.copyCommandAllocatorPool.GetCommandAllocator(this.d3D12Device, this.d3D12CopyFence), - _ => throw null! + _ => ThrowHelper.ThrowArgumentException>() }; } @@ -178,7 +179,7 @@ namespace ComputeSharp.Graphics d3D12Fence = this.d3D12CopyFence; d3D12FenceValue = this.nextD3D12CopyFenceValue++; break; - default: throw null!; + default: ThrowHelper.ThrowArgumentException(); return; } // Execute the command list and signal to the target fence diff --git a/src/ComputeSharp.Graphics/Helpers/DeviceHelper.cs b/src/ComputeSharp.Graphics/Helpers/DeviceHelper.cs index b10e2249..4a219cd3 100644 --- a/src/ComputeSharp.Graphics/Helpers/DeviceHelper.cs +++ b/src/ComputeSharp.Graphics/Helpers/DeviceHelper.cs @@ -1,6 +1,7 @@ using System; using System.Diagnostics; using System.Diagnostics.Contracts; +using ComputeSharp.Core.Helpers; using TerraFX.Interop; using FX = TerraFX.Interop.Windows; using HRESULT = System.Int32; @@ -40,12 +41,7 @@ namespace ComputeSharp.Graphics.Helpers return new GraphicsDevice(d3d12device.Move(), &dxgiDescription1); } - static GraphicsDevice Throw() - { - throw new NotSupportedException("There isn't a supported GPU device on the current machine"); - } - - return Throw(); + return ThrowHelper.ThrowNotSupportedException("There isn't a supported GPU device on the current machine"); } /// diff --git a/src/ComputeSharp.Shaders/Extensions/ILGeneratorExtensions.cs b/src/ComputeSharp.Shaders/Extensions/ILGeneratorExtensions.cs index 9aa9af8f..755da5da 100644 --- a/src/ComputeSharp.Shaders/Extensions/ILGeneratorExtensions.cs +++ b/src/ComputeSharp.Shaders/Extensions/ILGeneratorExtensions.cs @@ -1,5 +1,6 @@ using System.Runtime.CompilerServices; using System.Runtime.InteropServices; +using ComputeSharp.Core.Helpers; namespace System.Reflection.Emit { @@ -23,7 +24,7 @@ namespace System.Reflection.Emit case PropertyInfo property when property.CanRead: il.EmitCall(property.GetMethod!.IsStatic ? OpCodes.Call : OpCodes.Callvirt, property.GetMethod, null); break; - default: throw new ArgumentException($"The input {member.GetType()} instance can't be read"); + default: ThrowHelper.ThrowArgumentException("The input MemberInfo instance can't be read"); return; } } @@ -58,7 +59,7 @@ namespace System.Reflection.Emit 6 => OpCodes.Ldc_I4_6, 7 => OpCodes.Ldc_I4_7, 8 => OpCodes.Ldc_I4_8, - _ => throw new InvalidOperationException($"Invalid offset value [{offset}]") + _ => ThrowHelper.ThrowArgumentException("Invalid offset value") }); } else if (offset <= 127) il.Emit(OpCodes.Ldc_I4_S, (byte)offset); diff --git a/src/ComputeSharp.Shaders/Extensions/SyntaxNodeExtensions.cs b/src/ComputeSharp.Shaders/Extensions/SyntaxNodeExtensions.cs index c5c50b6e..74582357 100644 --- a/src/ComputeSharp.Shaders/Extensions/SyntaxNodeExtensions.cs +++ b/src/ComputeSharp.Shaders/Extensions/SyntaxNodeExtensions.cs @@ -4,6 +4,7 @@ using System.Globalization; using System.Linq; using System.Reflection; using ComputeSharp; +using ComputeSharp.Core.Helpers; using ComputeSharp.Shaders.Mappings; using ComputeSharp.Shaders.Translation.Models; @@ -97,7 +98,7 @@ namespace Microsoft.CodeAnalysis.CSharp.Syntax string methodName = $"{methodInfo.DeclaringType!.Name}_{methodInfo.Name}"; method = (methodName, methodInfo); return SyntaxFactory.IdentifierName(methodName).WithLeadingTrivia(node.GetLeadingTrivia()).WithTrailingTrivia(node.GetTrailingTrivia()); - default: throw new InvalidOperationException($"Invalid symbol kind: {memberInfos.First().GetType()}"); + default: ThrowHelper.ThrowArgumentException("Invalid symbol kind"); return null!; } // Handle the loaded info @@ -148,7 +149,7 @@ namespace Microsoft.CodeAnalysis.CSharp.Syntax isReadonly = !propertyInfo.CanWrite; memberInfo = propertyInfo; break; - default: throw new InvalidOperationException($"Invalid symbol kind: {memberSymbol.Kind}"); + default: ThrowHelper.ThrowArgumentException("Invalid symbol kind"); return null!; } // Handle the loaded info @@ -197,7 +198,7 @@ namespace Microsoft.CodeAnalysis.CSharp.Syntax case MethodInfo methodInfo: method = (name, methodInfo); return SyntaxFactory.InvocationExpression(SyntaxFactory.ParseExpression(name), node.ArgumentList).WithLeadingTrivia(node.GetLeadingTrivia()).WithTrailingTrivia(node.GetTrailingTrivia()); - default: throw new InvalidOperationException($"Invalid symbol kind: {result.Value.MemberInfo.GetType()}"); + default: ThrowHelper.ThrowArgumentException("Invalid symbol kind"); return null!; } // Return the mapped expression @@ -263,7 +264,7 @@ namespace Microsoft.CodeAnalysis.CSharp.Syntax Bool b when b => SyntaxFactory.LiteralExpression(SyntaxKind.TrueLiteralExpression, SyntaxFactory.Token(SyntaxKind.TrueKeyword)), Bool b when !b => SyntaxFactory.LiteralExpression(SyntaxKind.TrueLiteralExpression, SyntaxFactory.Token(SyntaxKind.FalseKeyword)), IFormattable scalar => SyntaxFactory.LiteralExpression(SyntaxKind.NumericLiteralExpression, SyntaxFactory.ParseToken(scalar.ToString(null, CultureInfo.InvariantCulture))), - _ => throw new InvalidOperationException($"Invalid field of type {memberInfo.MemberType}") + _ => ThrowHelper.ThrowArgumentException("Invalid field type") }; return expression.WithLeadingTrivia(node.GetLeadingTrivia()).WithTrailingTrivia(node.GetTrailingTrivia()); } diff --git a/src/ComputeSharp.Shaders/Translation/MethodDecompiler.cs b/src/ComputeSharp.Shaders/Translation/MethodDecompiler.cs index ac0b4854..08a65e53 100644 --- a/src/ComputeSharp.Shaders/Translation/MethodDecompiler.cs +++ b/src/ComputeSharp.Shaders/Translation/MethodDecompiler.cs @@ -7,6 +7,7 @@ using System.Linq; using System.Reflection; using System.Reflection.Metadata; using System.Text.RegularExpressions; +using ComputeSharp.Core.Helpers; using ComputeSharp.Shaders.Mappings; using ComputeSharp.Shaders.Translation.Enums; using ICSharpCode.Decompiler; @@ -139,7 +140,7 @@ namespace ComputeSharp.Shaders.Translation { MethodType.Execute => GetSyntaxTreeForExecuteMethod(methodInfo), MethodType.Static => GetSyntaxTreeForStaticMethod(methodInfo), - _ => throw new ArgumentOutOfRangeException(nameof(methodType), $"Invalid method type: {methodType}") + _ => ThrowHelper.ThrowArgumentException("Invalid method type") }; // Load the type syntax tree diff --git a/src/ComputeSharp.Shaders/Translation/Models/ReadableMember.cs b/src/ComputeSharp.Shaders/Translation/Models/ReadableMember.cs index 1e816f38..af84ef4b 100644 --- a/src/ComputeSharp.Shaders/Translation/Models/ReadableMember.cs +++ b/src/ComputeSharp.Shaders/Translation/Models/ReadableMember.cs @@ -2,6 +2,7 @@ using System.Collections.Generic; using System.Diagnostics.Contracts; using System.Reflection; +using ComputeSharp.Core.Helpers; namespace ComputeSharp.Shaders.Translation.Models { @@ -39,7 +40,7 @@ namespace ComputeSharp.Shaders.Translation.Models IsStatic = propertyInfo.GetMethod!.IsStatic; MemberType = propertyInfo.PropertyType; } - else throw new InvalidOperationException("Field and property can't both be null at the same time"); + else ThrowHelper.ThrowArgumentException("Field and property can't both be null at the same time"); } /// @@ -78,7 +79,7 @@ namespace ComputeSharp.Shaders.Translation.Models { FieldInfo field => field.GetValue(instance)!, PropertyInfo property => property.GetValue(instance)!, - _ => throw new InvalidOperationException("Field and property can't both be null at the same time") + _ => ThrowHelper.ThrowArgumentException("Field and property can't both be null at the same time") }; } diff --git a/src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.IL.cs b/src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.IL.cs index 0b7eda25..1d0a16c2 100644 --- a/src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.IL.cs +++ b/src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.IL.cs @@ -1,11 +1,11 @@ -using System; -using System.Buffers; +using System.Buffers; using System.Collections.Generic; using System.Diagnostics.Contracts; using System.Reflection; using System.Reflection.Emit; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; +using ComputeSharp.Core.Helpers; using ComputeSharp.Graphics.Buffers.Abstract; using ComputeSharp.Shaders.Mappings; using ComputeSharp.Shaders.Translation.Models; @@ -129,7 +129,7 @@ namespace ComputeSharp.Shaders.Translation this.totalVariablesByteSize += size; } - else throw new InvalidOperationException($"Invalid captured member of type {member.MemberType}"); + else ThrowHelper.ThrowArgumentException("Invalid captured member type"); } il.Emit(OpCodes.Ret); diff --git a/src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.cs b/src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.cs index 1a55b48c..785e156d 100644 --- a/src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.cs +++ b/src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.cs @@ -5,6 +5,7 @@ using System.Linq; using System.Reflection; using System.Runtime.InteropServices; using System.Text.RegularExpressions; +using ComputeSharp.Core.Helpers; using ComputeSharp.Graphics.Extensions; using ComputeSharp.Shaders.Mappings; using ComputeSharp.Shaders.Renderer.Models.Fields; @@ -148,7 +149,10 @@ namespace ComputeSharp.Shaders.Translation BindingFlags.Public | BindingFlags.NonPublic).ToArray(); - if (shaderFields.Count == 0) throw new InvalidOperationException("Empty shader body"); + if (shaderFields.Count == 0) + { + ThrowHelper.ThrowInvalidOperationException("The shader body must contain at least one field"); + } // Descriptor for the buffer for captured scalar/vector variables D3D12_DESCRIPTOR_RANGE1 d3D12DescriptorRange1 = new(D3D12_DESCRIPTOR_RANGE_TYPE_CBV, 1, this.constantBuffersCount++); @@ -230,7 +234,7 @@ namespace ComputeSharp.Shaders.Translation // Captured static delegates with a return type LoadStaticMethodSource(shader, fieldName, func.Method); } - else throw new ArgumentException($"Invalid captured variable of type {fieldType} with name \"{memberInfo.Name}\""); + else ThrowHelper.ThrowArgumentException("Invalid captured variable"); } ///