Skip to content

Commit

Permalink
MA0052 is only reported for know formats
Browse files Browse the repository at this point in the history
  • Loading branch information
meziantou committed Mar 25, 2023
1 parent 72a513b commit 5e05913
Show file tree
Hide file tree
Showing 2 changed files with 120 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,31 @@ private static void Analyze(OperationAnalysisContext context)
if (expression.Member.ContainingType.EnumUnderlyingType == null)
return;

if (operation.Arguments.Length > 0)
{
var format = operation.Arguments[0].Value;
if (format is { ConstantValue: { HasValue: true, Value: var formatValue } })
{
if (!IsNameFormat(formatValue))
return;
}
else
{
return;
}
}

context.ReportDiagnostic(s_rule, operation);

static bool IsNameFormat(object? format)
{
if (format is null)
return true;

if (format is string str && str is "g" or "G" or "f" or "F" or "")
return true;

return false;
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -72,4 +72,99 @@ await CreateProjectBuilder()
.WithSourceCode(SourceCode)
.ValidateAsync();
}

[Theory]
[InlineData("null")]
[InlineData("\"\"")]
[InlineData("\"G\"")]
[InlineData("\"g\"")]
[InlineData("\"F\"")]
[InlineData("\"f\"")]
public async Task ToString_Formats(string format)
{
var sourceCode = $$"""
class Test
{
void A()
{
_ = [|MyEnum.A.ToString(format: {{format}})|];
}
}

enum MyEnum
{
A,
}
""";

var fix = """
class Test
{
void A()
{
_ = nameof(MyEnum.A);
}
}

enum MyEnum
{
A,
}
""";

await CreateProjectBuilder()
.WithSourceCode(sourceCode)
.ShouldFixCodeWith(fix)
.ValidateAsync();
}

[Theory]
[InlineData("\"x\"")]
[InlineData("\"X\"")]
[InlineData("\"d\"")]
[InlineData("\"D\"")]
public async Task ToString_IncompatibleFormats(string format)
{
var sourceCode = $$"""
class Test
{
void A()
{
_ = MyEnum.A.ToString(format: {{format}});
}
}

enum MyEnum
{
A,
}
""";

await CreateProjectBuilder()
.WithSourceCode(sourceCode)
.ValidateAsync();
}

[Fact]
public async Task ToString_DynamicFormat()
{
var sourceCode = $$"""
class Test
{
void A(string format)
{
_ = MyEnum.A.ToString(format);
}
}

enum MyEnum
{
A,
}
""";

await CreateProjectBuilder()
.WithSourceCode(sourceCode)
.ValidateAsync();
}
}

0 comments on commit 5e05913

Please sign in to comment.