Fix MA0145 on non-static accessors and MA0146 on constructor accessors
What
Two bugs in ValidateUnsafeAccessorAttributeUsageAnalyzer.
MA0145 false negative on non-static accessors. The runtime requires an extern static method, but the rule only checked IsExtern:
class Sample
{
[UnsafeAccessor(UnsafeAccessorKind.Field, Name = "a")]
extern ref int A(Sample s); // not reported, expected "method must be extern static"
}
MA0146 false positive on constructor accessors. The name of a Constructor accessor is not used, and the UnsafeAccessorAttribute documentation itself declares a local function with [UnsafeAccessor(UnsafeAccessorKind.Constructor)] and no Name. The rule reported it, and the fix added Name = "Create", which is useless at best:
void A()
{
[UnsafeAccessor(UnsafeAccessorKind.Constructor)]
static extern Sample Create(); // MA0146 reported
}
Fix
- MA0145: the check is now
!methodSymbol.IsExtern || !methodSymbol.IsStatic, which matches the existing "method must be extern static" message. - MA0146: the rule is not reported when the kind is
UnsafeAccessorKind.Constructor. Because the diagnostic is no longer reported, the MA0146 fixer no longer adds the name.
MA0145 has no code fixer (ValidateUnsafeAccessorAttributeUsageFixer only fixes MA0146), so no fixer adds static.
Both rule documentation pages are updated.
Tests
Added NotStaticExternMethod and LocalFunction_Constructor_WithoutNameParameter. Both fail before the fix. ValidateUnsafeAccessorAttributeUsageAnalyzerTests passes on roslyn5.9 (10/10) and roslyn4.8 (10/10).