Background and motivation
We plan to ship analyzers and code fixers that will issue warnings for various patterns, such as APIs with unmanaged pointers in their signatures, LibraryImport attributes, and extern methods (among others). We need a better mechanism than #pragma warning to inform the analyzer that an API is safe. For example, all Math extern methods are pretty safe to require unsafe context on call sites:
#pragma warning disable IL5005 // whatever id for "'extern' must be [RequiresUnsafe]"
[MethodImpl(MethodImplOptions.InternalCall)]
public static extern double Sin(double a);
#pragma warning restore IL5005
with this API proposal it can be just:
[RequiresUnsafe(false)]
[MethodImpl(MethodImplOptions.InternalCall)]
public static extern double Sin(double a);
API Proposal
namespace System.Diagnostics.CodeAnalysis
{
public sealed class RequiresUnsafeAttribute : Attribute
{
+ public RequiresUnsafeAttribute(bool requiresUnsafe = true) { }
}
}
NOTE: since we've just introduced the attribute, I suspect it's not a breaking change to "remove" the default constructor.
API Usage
[RequiresUnsafe(false)]
[MethodImpl(MethodImplOptions.InternalCall)]
public static extern double Sin(double a);
[RequiresUnsafe] // 'true' by default
[LibraryImport(RuntimeHelpers.QCall)]
private static partial void _AddMemoryPressure(ulong bytesAllocated);
Alternative Designs
Alternatively, can be a new attribute with the opposite meaning, e.g.:
namespace System.Diagnostics.CodeAnalysis
{
public sealed class DoesNotRequireUnsafeAttribute : Attribute { }
}
The new attribute would be simpler for us as it won't require changes in C# spec/Roslyn.
Risks
No response
Background and motivation
We plan to ship analyzers and code fixers that will issue warnings for various patterns, such as APIs with unmanaged pointers in their signatures, LibraryImport attributes, and extern methods (among others). We need a better mechanism than #pragma warning to inform the analyzer that an API is safe. For example, all Math
externmethods are pretty safe to require unsafe context on call sites:with this API proposal it can be just:
API Proposal
namespace System.Diagnostics.CodeAnalysis { public sealed class RequiresUnsafeAttribute : Attribute { + public RequiresUnsafeAttribute(bool requiresUnsafe = true) { } } }NOTE: since we've just introduced the attribute, I suspect it's not a breaking change to "remove" the default constructor.
API Usage
Alternative Designs
Alternatively, can be a new attribute with the opposite meaning, e.g.:
The new attribute would be simpler for us as it won't require changes in C# spec/Roslyn.
Risks
No response