Skip to content

Commit b2af65a

Browse files
authored
Fix LoggerMessageGenerator parser to check for expression bodied method (#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
1 parent 91706f1 commit b2af65a

File tree

2 files changed

+20
-2
lines changed

2 files changed

+20
-2
lines changed

src/libraries/Microsoft.Extensions.Logging.Abstractions/gen/LoggerMessageGenerator.Parser.cs

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -248,9 +248,10 @@ public IReadOnlyList<LoggerClass> GetLogClasses(IEnumerable<ClassDeclarationSynt
248248
keepMethod = false;
249249
}
250250

251-
if (method.Body != null)
251+
CSharpSyntaxNode? methodBody = method.Body as CSharpSyntaxNode ?? method.ExpressionBody;
252+
if (methodBody != null)
252253
{
253-
Diag(DiagnosticDescriptors.LoggingMethodHasBody, method.Body.GetLocation());
254+
Diag(DiagnosticDescriptors.LoggingMethodHasBody, methodBody.GetLocation());
254255
keepMethod = false;
255256
}
256257

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

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -80,6 +80,23 @@ static partial void M1(ILogger logger)
8080
Assert.Equal(DiagnosticDescriptors.LoggingMethodHasBody.Id, diagnostics[0].Id);
8181
}
8282

83+
[Fact]
84+
public async Task InvalidMethodExpressionBody()
85+
{
86+
IReadOnlyList<Diagnostic> diagnostics = await RunGenerator(@"
87+
partial class C
88+
{
89+
static partial void M1(ILogger logger);
90+
91+
[LoggerMessage(EventId = 0, Level = LogLevel.Debug, Message = ""M1"")]
92+
static partial void M1(ILogger logger) => throw new Exception();
93+
}
94+
");
95+
96+
Assert.Single(diagnostics);
97+
Assert.Equal(DiagnosticDescriptors.LoggingMethodHasBody.Id, diagnostics[0].Id);
98+
}
99+
83100
[Theory]
84101
[InlineData("EventId = 0, Level = null, Message = \"This is a message with {foo}\"")]
85102
[InlineData("eventId: 0, level: null, message: \"This is a message with {foo}\"")]

0 commit comments

Comments
 (0)