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

Make the soure generator format enums using their identifiers rather than numeric values. #87557

Merged
merged 2 commits into from
Jun 15, 2023
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
109 changes: 109 additions & 0 deletions src/libraries/System.Text.Json/gen/Helpers/EnumFormatter.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;

namespace System.Text.Json.SourceGeneration
{
public static class EnumFormatter<TEnum> where TEnum : struct, Enum
eiriktsarpalis marked this conversation as resolved.
Show resolved Hide resolved
{
private static readonly bool s_IsFlagsEnum = typeof(TEnum).GetCustomAttribute<FlagsAttribute>() != null;
private static readonly TEnum[] s_definedValues = (TEnum[])Enum.GetValues(typeof(TEnum));

public static string FormatEnumLiteral(string enumTypeName, TEnum value)
{
if (TryGetEnumComponents(value, out TEnum? singleValue, out List<TEnum>? flagComponents))
{
if (singleValue != null)
{
return FormatDefinedValue(value);
}
else
{
Debug.Assert(flagComponents?.Count > 1);
return string.Join(" | ", flagComponents.Select(FormatDefinedValue));
}

string FormatDefinedValue(TEnum value)
{
return $"{enumTypeName}.{value}";
}
}

// Does not correspond to an enum value, format as numeric value.
int numericValue = GetNumericValue(value);
return numericValue >= 0
? $"({enumTypeName}){numericValue}"
: $"({enumTypeName})({numericValue})";
}

private static bool TryGetEnumComponents(TEnum value, out TEnum? singleValue, out List<TEnum>? flagComponents)
{
singleValue = null;
flagComponents = null;

if (!s_IsFlagsEnum)
{
int idx = Array.IndexOf(s_definedValues, value);
if (idx < 0)
{
return false;
}

singleValue = s_definedValues[idx];
return true;
}

int numericValue = GetNumericValue(value);

foreach (TEnum definedValue in s_definedValues)
{
int definedNumericValue = GetNumericValue(definedValue);
bool isContainedInValue = definedNumericValue != 0
? (numericValue & definedNumericValue) == definedNumericValue
: numericValue == 0;

if (isContainedInValue)
{
if (singleValue is null && flagComponents is null)
{
singleValue = definedValue;
}
else
{
if (flagComponents is null)
{
Debug.Assert(singleValue.HasValue);
flagComponents = new() { singleValue.Value };
singleValue = null;
}

flagComponents.Add(definedValue);
}

numericValue &= ~definedNumericValue;
}
}

// The enum contains bits that do not correspond to defined values.
// Discard accumulated state and return false.
if (numericValue != 0)
{
flagComponents = null;
singleValue = null;
}

return singleValue != null || flagComponents != null;
}

private static int GetNumericValue(TEnum value)
{
Debug.Assert(Type.GetTypeCode(typeof(TEnum)) is TypeCode.Int32, "only int-backed enums supported for now.");
return Unsafe.As<TEnum, int>(ref value);
}
}
}
23 changes: 8 additions & 15 deletions src/libraries/System.Text.Json/gen/JsonSourceGenerator.Emitter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1211,23 +1211,16 @@ private SourceText GetPropertyNameInitialization(ContextGenerationSpec contextSp
return CompleteSourceFileAndReturnText(writer);
}

private static string GetNumberHandlingAsStr(JsonNumberHandling? numberHandling) =>
numberHandling switch
{
null => "null",
>= 0 => $"({JsonNumberHandlingTypeRef}){(int)numberHandling.Value}",
< 0 => $"({JsonNumberHandlingTypeRef})({(int)numberHandling.Value})"
};
private static string GetNumberHandlingAsStr(JsonNumberHandling? numberHandling)
=> numberHandling.HasValue
? EnumFormatter<JsonNumberHandling>.FormatEnumLiteral(JsonNumberHandlingTypeRef, numberHandling.Value)
: "null";

private static string GetObjectCreationHandlingAsStr(JsonObjectCreationHandling creationHandling) =>
creationHandling >= 0
? $"({JsonObjectCreationHandlingTypeRef}){(int)creationHandling}"
: $"({JsonObjectCreationHandlingTypeRef})({(int)creationHandling})";
private static string GetObjectCreationHandlingAsStr(JsonObjectCreationHandling creationHandling)
=> EnumFormatter<JsonObjectCreationHandling>.FormatEnumLiteral(JsonObjectCreationHandlingTypeRef, creationHandling);

private static string GetUnmappedMemberHandlingAsStr(JsonUnmappedMemberHandling unmappedMemberHandling) =>
unmappedMemberHandling >= 0
? $"({JsonUnmappedMemberHandlingTypeRef}){(int)unmappedMemberHandling}"
: $"({JsonUnmappedMemberHandlingTypeRef})({(int)unmappedMemberHandling})";
private static string GetUnmappedMemberHandlingAsStr(JsonUnmappedMemberHandling unmappedMemberHandling)
=> EnumFormatter<JsonUnmappedMemberHandling>.FormatEnumLiteral(JsonUnmappedMemberHandlingTypeRef, unmappedMemberHandling);

private static string GetCreateValueInfoMethodRef(string typeCompilableName) => $"{CreateValueInfoMethodName}<{typeCompilableName}>";

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@
<Compile Include="..\Common\ThrowHelper.cs" Link="Common\System\Text\Json\ThrowHelper.cs" />
<Compile Include="$(CommonPath)\Roslyn\GetBestTypeByMetadataName.cs" Link="Common\Roslyn\GetBestTypeByMetadataName.cs" />
<Compile Include="Helpers\DiagnosticInfo.cs" />
<Compile Include="Helpers\EnumFormatter.cs" />
<Compile Include="Helpers\ImmutableEquatableArray.cs" />
<Compile Include="Helpers\KnownTypeSymbols.cs" />
<Compile Include="Helpers\RoslynExtensions.cs" />
Expand Down