Fix LoggerMessageGenerator parser to check for expression bodied method (#75601)
authorWei Chen <weichch87@gmail.com>
Tue, 27 Sep 2022 13:53:10 +0000 (02:53 +1300)
committerGitHub <noreply@github.com>
Tue, 27 Sep 2022 13:53:10 +0000 (08:53 -0500)
* 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

src/libraries/Microsoft.Extensions.Logging.Abstractions/gen/LoggerMessageGenerator.Parser.cs
src/libraries/Microsoft.Extensions.Logging.Abstractions/tests/Microsoft.Extensions.Logging.Generators.Tests/LoggerMessageGeneratorParserTests.cs

index cc8dc0b..0a6eadb 100644 (file)
@@ -248,9 +248,10 @@ namespace Microsoft.Extensions.Logging.Generators
                                             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;
                                         }
 
index 4bb4271..b09409a 100644 (file)
@@ -80,6 +80,23 @@ namespace Microsoft.Extensions.Logging.Generators.Tests
             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}\"")]