Skip to content

Commit

Permalink
Fix LoggerMessageGenerator parser to check for expression bodied meth…
Browse files Browse the repository at this point in the history
…od (#75601)

* Check for expression bodied method

Fixed LoggerMessageGenerator parser to check for expression bodied
method and generate a proper diagnostic message.

Fix #66080

* Fix expression body in test

Fixed invalid expression body in test
  • Loading branch information
weichch committed Sep 27, 2022
1 parent 91706f1 commit b2af65a
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 2 deletions.
Expand Up @@ -248,9 +248,10 @@ public IReadOnlyList<LoggerClass> GetLogClasses(IEnumerable<ClassDeclarationSynt
keepMethod = false;
}

if (method.Body != null)
CSharpSyntaxNode? methodBody = method.Body as CSharpSyntaxNode ?? method.ExpressionBody;
if (methodBody != null)
{
Diag(DiagnosticDescriptors.LoggingMethodHasBody, method.Body.GetLocation());
Diag(DiagnosticDescriptors.LoggingMethodHasBody, methodBody.GetLocation());
keepMethod = false;
}

Expand Down
Expand Up @@ -80,6 +80,23 @@ partial class C
Assert.Equal(DiagnosticDescriptors.LoggingMethodHasBody.Id, diagnostics[0].Id);
}

[Fact]
public async Task InvalidMethodExpressionBody()
{
IReadOnlyList<Diagnostic> diagnostics = await RunGenerator(@"
partial class C
{
static partial void M1(ILogger logger);
[LoggerMessage(EventId = 0, Level = LogLevel.Debug, Message = ""M1"")]
static partial void M1(ILogger logger) => throw new Exception();
}
");

Assert.Single(diagnostics);
Assert.Equal(DiagnosticDescriptors.LoggingMethodHasBody.Id, diagnostics[0].Id);
}

[Theory]
[InlineData("EventId = 0, Level = null, Message = \"This is a message with {foo}\"")]
[InlineData("eventId: 0, level: null, message: \"This is a message with {foo}\"")]
Expand Down

0 comments on commit b2af65a

Please sign in to comment.