Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix hashing in Logging source gen #111073

Merged
merged 2 commits into from
Jan 6, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -916,7 +916,8 @@ internal static int GetNonRandomizedHashCode(string s)
{
result = (c ^ result) * 16777619;
}
return Math.Abs((int)result);

return (int)(result & 0x7FFFFFFF); // Ensure the result is non-negative
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -535,7 +535,7 @@ partial class C(ILogger logger)
public partial void M1();
}
");

Assert.Equal(2, diagnostics.Count);

Assert.Equal(DiagnosticDescriptors.PrimaryConstructorParameterLoggerHidden.Id, diagnostics[0].Id);
Expand Down Expand Up @@ -988,6 +988,23 @@ static partial class C
Assert.Empty(diagnostics); // should fail quietly on broken code
}

[Fact]
public async Task EventIdGenerationTest()
{
// hashing Dzoggee should not result breaking generation.
// in our hashing, Dzoggee result to int.MinValue before we convert it to non-negative value.
IReadOnlyList<Diagnostic> diagnostics = await RunGenerator(@"
using Microsoft.Extensions.Logging;
internal static partial class LoggerExtensions
{
[LoggerMessage(Level = LogLevel.Information)]
public static partial void Dzoggee(this ILogger logger);
}
");

Assert.Empty(diagnostics);
}

[Fact]
internal void MultipleTypeDefinitions()
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -67,17 +67,16 @@ internal static bool IsConvertibleBasicType(ITypeSymbol typeSymbol)

/// <summary>
/// Returns a non-randomized hash code for the given string.
/// We always return a positive value.
/// </summary>
internal static int GetNonRandomizedHashCode(string s)
internal static uint GetNonRandomizedHashCode(string s)
{
uint result = 2166136261u;
foreach (char c in s)
{
result = (c ^ result) * 16777619;
}

return Math.Abs((int)result);
return result;
}
}
}