Skip to content

Commit

Permalink
[release/6.0] Fix Logging source generator failures with various synt…
Browse files Browse the repository at this point in the history
…ax (#64779)
  • Loading branch information
maryamariyan authored Feb 9, 2022
1 parent 7a62f17 commit 3334f3b
Show file tree
Hide file tree
Showing 10 changed files with 276 additions and 13 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ namespace {lc.Namespace}
// loop until you find top level nested class
while (parent != null)
{
parentClasses.Add($"partial {parent.Keyword} {parent.Name} {parent.Constraints}");
parentClasses.Add($"partial {parent.Keyword} {parent.Name} ");
parent = parent.ParentClass;
}

Expand All @@ -92,7 +92,7 @@ namespace {lc.Namespace}
}

_builder.Append($@"
{nestedIndentation}partial {lc.Keyword} {lc.Name} {lc.Constraints}
{nestedIndentation}partial {lc.Keyword} {lc.Name}
{nestedIndentation}{{");

foreach (LoggerMethod lm in lc.Methods)
Expand Down Expand Up @@ -196,7 +196,7 @@ private void GenFieldAssignments(LoggerMethod lm, string nestedIndentation)
{
foreach (LoggerParameter p in lm.TemplateParameters)
{
_builder.AppendLine($" {nestedIndentation}this._{p.Name} = {p.Name};");
_builder.AppendLine($" {nestedIndentation}this._{p.Name} = {p.CodeName};");
}
}

Expand Down Expand Up @@ -255,7 +255,7 @@ private void GenCallbackArguments(LoggerMethod lm)
{
foreach (LoggerParameter p in lm.TemplateParameters)
{
_builder.Append($"{p.Name}, ");
_builder.Append($"{p.CodeName}, ");
}
}

Expand Down Expand Up @@ -309,7 +309,11 @@ private void GenParameters(LoggerMethod lm)
_builder.Append(", ");
}

_builder.Append($"{p.Type} {p.Name}");
if (p.Qualifier != null)
{
_builder.Append($"{p.Qualifier} ");
}
_builder.Append($"{p.Type} {p.CodeName}");
}
}

Expand All @@ -327,7 +331,7 @@ private void GenArguments(LoggerMethod lm)
_builder.Append(", ");
}

_builder.Append($"{p.Type} {p.Name}");
_builder.Append($"{p.Type} {p.CodeName}");
}
}

Expand All @@ -343,7 +347,7 @@ private void GenHolder(LoggerMethod lm)
_builder.Append(", ");
}

_builder.Append(p.Name);
_builder.Append(p.CodeName);
}

_builder.Append(')');
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -308,6 +308,15 @@ public IReadOnlyList<LoggerClass> GetLogClasses(IEnumerable<ClassDeclarationSynt
foreach (IParameterSymbol paramSymbol in methodSymbol.Parameters)
{
string paramName = paramSymbol.Name;
bool needsAtSign = false;
if (paramSymbol.DeclaringSyntaxReferences.Length > 0)
{
ParameterSyntax paramSyntax = paramSymbol.DeclaringSyntaxReferences[0].GetSyntax(_cancellationToken) as ParameterSyntax;
if (paramSyntax != null && !string.IsNullOrEmpty(paramSyntax.Identifier.Text))
{
needsAtSign = paramSyntax.Identifier.Text[0] == '@';
}
}
if (string.IsNullOrWhiteSpace(paramName))
{
// semantic problem, just bail quietly
Expand All @@ -323,6 +332,15 @@ public IReadOnlyList<LoggerClass> GetLogClasses(IEnumerable<ClassDeclarationSynt
break;
}

string? qualifier = null;
if (paramSymbol.RefKind == RefKind.In)
{
qualifier = "in";
}
else if (paramSymbol.RefKind == RefKind.Ref)
{
qualifier = "ref";
}
string typeName = paramTypeSymbol.ToDisplayString(
SymbolDisplayFormat.FullyQualifiedFormat.WithMiscellaneousOptions(
SymbolDisplayMiscellaneousOptions.IncludeNullableReferenceTypeModifier));
Expand All @@ -331,6 +349,8 @@ public IReadOnlyList<LoggerClass> GetLogClasses(IEnumerable<ClassDeclarationSynt
{
Name = paramName,
Type = typeName,
Qualifier = qualifier,
CodeName = needsAtSign ? "@" + paramName : paramName,
IsLogger = !foundLogger && IsBaseOrIdentity(paramTypeSymbol!, loggerSymbol),
IsException = !foundException && IsBaseOrIdentity(paramTypeSymbol!, exceptionSymbol),
IsLogLevel = !foundLogLevel && IsBaseOrIdentity(paramTypeSymbol!, logLevelSymbol),
Expand Down Expand Up @@ -476,7 +496,6 @@ potentialNamespaceParent is not NamespaceDeclarationSyntax
Keyword = classDec.Keyword.ValueText,
Namespace = nspace,
Name = classDec.Identifier.ToString() + classDec.TypeParameterList,
Constraints = classDec.ConstraintClauses.ToString(),
ParentClass = null,
};

Expand All @@ -495,7 +514,6 @@ bool IsAllowedKind(SyntaxKind kind) =>
Keyword = parentLoggerClass.Keyword.ValueText,
Namespace = nspace,
Name = parentLoggerClass.Identifier.ToString() + parentLoggerClass.TypeParameterList,
Constraints = parentLoggerClass.ConstraintClauses.ToString(),
ParentClass = null,
};

Expand Down Expand Up @@ -681,7 +699,6 @@ internal class LoggerClass
public string Keyword = string.Empty;
public string Namespace = string.Empty;
public string Name = string.Empty;
public string Constraints = string.Empty;
public LoggerClass? ParentClass;
}

Expand Down Expand Up @@ -712,6 +729,8 @@ internal class LoggerParameter
{
public string Name = string.Empty;
public string Type = string.Empty;
public string CodeName = string.Empty;
public string? Qualifier;
public bool IsLogger;
public bool IsException;
public bool IsLogLevel;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@ Microsoft.Extensions.Logging.LogLevel
Microsoft.Extensions.Logging.Logger&lt;T&gt;
Microsoft.Extensions.Logging.LoggerMessage
Microsoft.Extensions.Logging.Abstractions.NullLogger</PackageDescription>
<GeneratePackageOnBuild>true</GeneratePackageOnBuild>
<ServicingVersion>1</ServicingVersion>
</PropertyGroup>

<ItemGroup>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,11 @@ namespace Microsoft.Extensions.Logging.Generators.Tests.TestClasses.NestedNamesp
{
partial record NestedRecord
{
partial class NestedClassTestsExtensions<T1> where T1 : Class1
partial class NestedClassTestsExtensions<T1>
{
partial class NestedMiddleParentClass
{
partial class Nested<T2> where T2 : Class2
partial class Nested<T2>
{
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.Extensions.Logging.Generators", "%VERSION%")]
private static readonly global::System.Action<global::Microsoft.Extensions.Logging.ILogger, global::System.Exception?> __M9Callback =
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,12 @@

using System;
using System.Collections.Generic;
using Microsoft.Extensions.Logging.Abstractions;
using Microsoft.Extensions.Logging.Generators.Tests.TestClasses;
using Microsoft.Extensions.Logging.Generators.Tests.TestClasses.UsesConstraintInAnotherNamespace;
using Xunit;
using NamespaceForABC;
using ConstraintInAnotherNamespace;

namespace Microsoft.Extensions.Logging.Generators.Tests
{
Expand Down Expand Up @@ -410,6 +414,71 @@ public void SkipEnabledCheckTests()
Assert.Equal(1, logger.CallCount);
Assert.Equal("LoggerMethodWithTrueSkipEnabledCheck", logger.LastEventId.Name);
}
private struct MyStruct { }

[Fact]
public void ConstraintsTests()
{
var logger = new MockLogger();

var printer = new MessagePrinter<Message>();
logger.Reset();
printer.Print(logger, new Message() { Text = "Hello" });
Assert.Equal(LogLevel.Information, logger.LastLogLevel);
Assert.Null(logger.LastException);
Assert.Equal("The message is Hello.", logger.LastFormattedString);
Assert.Equal(1, logger.CallCount);

var printer2 = new MessagePrinterHasConstraintOnLogClassAndLogMethod<Message>();
logger.Reset();
printer2.Print(logger, new Message() { Text = "Hello" });
Assert.Equal(LogLevel.Information, logger.LastLogLevel);
Assert.Null(logger.LastException);
Assert.Equal("The message is `Hello`.", logger.LastFormattedString);
Assert.Equal(1, logger.CallCount);

logger.Reset();
ConstraintsTestExtensions<Object>.M0(logger, 12);
Assert.Equal(LogLevel.Debug, logger.LastLogLevel);
Assert.Null(logger.LastException);
Assert.Equal("M012", logger.LastFormattedString);
Assert.Equal(1, logger.CallCount);

logger.Reset();
ConstraintsTestExtensions1<MyStruct>.M0(logger, 12);
Assert.Equal(LogLevel.Debug, logger.LastLogLevel);
Assert.Null(logger.LastException);
Assert.Equal("M012", logger.LastFormattedString);
Assert.Equal(1, logger.CallCount);

logger.Reset();
ConstraintsTestExtensions2<MyStruct>.M0(logger, 12);
Assert.Equal(LogLevel.Debug, logger.LastLogLevel);
Assert.Null(logger.LastException);
Assert.Equal("M012", logger.LastFormattedString);
Assert.Equal(1, logger.CallCount);

logger.Reset();
ConstraintsTestExtensions3<MyStruct>.M0(logger, 12);
Assert.Equal(LogLevel.Debug, logger.LastLogLevel);
Assert.Null(logger.LastException);
Assert.Equal("M012", logger.LastFormattedString);
Assert.Equal(1, logger.CallCount);

logger.Reset();
ConstraintsTestExtensions4<Attribute>.M0(logger, 12);
Assert.Equal(LogLevel.Debug, logger.LastLogLevel);
Assert.Null(logger.LastException);
Assert.Equal("M012", logger.LastFormattedString);
Assert.Equal(1, logger.CallCount);

logger.Reset();
ConstraintsTestExtensions5<MyStruct>.M0(logger, 12);
Assert.Equal(LogLevel.Debug, logger.LastLogLevel);
Assert.Null(logger.LastException);
Assert.Equal("M012", logger.LastFormattedString);
Assert.Equal(1, logger.CallCount);
}

[Fact]
public void NestedClassTests()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -606,6 +606,21 @@ partial class C
Assert.Equal(DiagnosticDescriptors.LoggingMethodIsGeneric.Id, diagnostics[0].Id);
}

[Theory]
[InlineData("ref")]
[InlineData("in")]
public async Task SupportsRefKindsInAndRef(string modifier)
{
IReadOnlyList<Diagnostic> diagnostics = await RunGenerator(@$"
partial class C
{{
[LoggerMessage(EventId = 0, Level = LogLevel.Debug, Message = ""Parameter {{P1}}"")]
static partial void M(ILogger logger, {modifier} int p1);
}}");

Assert.Empty(diagnostics);
}

[Fact]
public async Task Templates()
{
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

namespace Microsoft.Extensions.Logging.Generators.Tests.TestClasses
{
internal static partial class AtSymbolTestExtensions
{
[LoggerMessage(EventId = 0, Level = LogLevel.Information, Message = "M0 {event}")]
internal static partial void M0(ILogger logger, string @event);
}
}
Loading

0 comments on commit 3334f3b

Please sign in to comment.