Skip to content

Configuration Binding Generator Initializes Suffixed Default Values Incorrectly #92773

Closed

Description

@chrisoverzero

Description

When configuration binding generation is enabled by means of:

<EnableConfigurationBindingGenerator>true</EnableConfigurationBindingGenerator>
<Features>$(Features);InterceptorsPreview</Features>

…a project can fail to compile with this error message:

/app/repro/Microsoft.Extensions.Configuration.Binder.SourceGeneration/Microsoft.Extensions.Configuration.Binder.SourceGeneration.ConfigurationBindingGenerator/BindingExtensions.g.cs(87,25): e
rror CS0664: Literal of type double cannot be implicitly converted to type 'decimal'; use an 'M' suffix to create a literal of this type [/app/repro/repro.csproj]

Reproduction Steps

Given the following project file:

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net8.0</TargetFramework>
    <ImplicitUsings>enable</ImplicitUsings>
    <Nullable>enable</Nullable>
    <EnableConfigurationBindingGenerator>true</EnableConfigurationBindingGenerator>
    <Features>$(Features);InterceptorsPreview</Features>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Microsoft.Extensions.Hosting" Version="8.0.0-rtm.23477.9" />
    <PackageReference Include="Microsoft.Extensions.Configuration.Binder" Version="8.0.0-rtm.23477.9" />
  </ItemGroup>

</Project>

…and the following Program.cs:

using Microsoft.Extensions.Configuration;

var c = new ConfigurationBuilder().Build();
var x = c.GetSection("Anything").Get<Values>();
Console.WriteLine(x);

readonly record struct Values(int A, string B, decimal C = 2.30m);

…run dotnet build via SDK version "8.0.100-rtm.23477.37".

Expected behavior

The compilation succeeds, and the value is bound from configuration.

Actual behavior

Compilation fails with the following error:

/app/repro/Microsoft.Extensions.Configuration.Binder.SourceGeneration/Microsoft.Extensions.Configuration.Binder.SourceGeneration.ConfigurationBindingGenerator/BindingExtensions.g.cs(87,25): e
rror CS0664: Literal of type double cannot be implicitly converted to type 'decimal'; use an 'M' suffix to create a literal of this type [/app/repro/repro.csproj]

The line in question in the generated code appears here in a method named InitializeValues (but really Initialize{typename}):

decimal C = 2.30;
if (configuration["C"] is string value2)
{
    C = ParseDecimal(value2, () => configuration.GetSection("C").Path);
}

Regression?

I'm afraid I don't know.

Known Workarounds

No response

Configuration

.NET Version: 8.0.100-rtm.23477.37
OS and version: macOS 13.5.1 (22G90)
Architecture: x64
Specific?: No, I don't think so.
Blazor: ❌

Other information

You know what, I just checked initializing float C = 2.30f as well, and it behaves the same.

float C = 2.3;
if (configuration["C"] is string value2)
{
    C = ParseFloat(value2, () => configuration.GetSection("C").Path);
}

Activity

  1. ghost added
    untriaged
    on Sep 28, 2023
  2. changed the title [-]Configuration Binding Generator Initializes `decimal` Default Value Incorrectly[/-] [+]Configuration Binding Generator Initializes Suffixed Default Values Incorrectly[/+] on Sep 29, 2023
  3. removed
    untriaged
    on Oct 3, 2023
  4. added this to the 8.0.0 milestone on Oct 3, 2023
  5. ericstj commented on Oct 3, 2023

    @ericstj
    Member

    I confirmed this repro in the latest codebase. We'll need to see what's missing from how we emit the default value. Thanks for the report @chrisoverzero

  6. ericstj commented on Oct 6, 2023

    @ericstj
    Member

    So it would seem that JSON has a similar bug to this. It doesn't produce code that doesn't compile, but it does produce code that loses precision. Then using that code at runtime produces an exception.

    Here's the JSON repro:

    using System.Text.Json;
    using System.Text.Json.Serialization;
    
    var deserialized = JsonSerializer.Deserialize<MyPi>("{}", SourceGenerationContext.Default.MyPi);
    
    Console.WriteLine(deserialized);
    
    public struct MyPi
    {
        [JsonConstructor]
        public MyPi(decimal value = 3.1415926535897932384626433M) { Value = value; }
        public decimal Value { get; }
    }
    
    [JsonSerializable(typeof(MyPi), GenerationMode = JsonSourceGenerationMode.Metadata)]
    internal partial class SourceGenerationContext : JsonSerializerContext { }

    This happens because JSON produces this:

        private static global::System.Text.Json.Serialization.Metadata.JsonParameterInfoValues[] MyPiCtorParamInit()
        {
            var parameters = new global::System.Text.Json.Serialization.Metadata.JsonParameterInfoValues[1];
    
            parameters[0] = new()
            {
                Name = "value",
                ParameterType = typeof(decimal),
                Position = 0,
                HasDefaultValue = true,
                DefaultValue = 3.1415926535897932384626433
            };
            
            return parameters;
        }

    DefaultValue here is

    That syntax results in initializing the object value to a boxed double which will throw at runtime:

    Unhandled exception. System.InvalidCastException: Unable to cast object of type 'System.Double' to type 'System.Decimal'.
       at System.Text.Json.Serialization.Metadata.JsonParameterInfo`1..ctor(JsonParameterInfoValues parameterInfoValues, JsonPropertyInfo`1 matchingPropertyInfo)
       at System.Text.Json.Serialization.Metadata.JsonPropertyInfo`1.CreateJsonParameterInfo(JsonParameterInfoValues parameterInfoValues)
       at System.Text.Json.Serialization.Metadata.JsonTypeInfo.ConfigureConstructorParameters()
       at System.Text.Json.Serialization.Metadata.JsonTypeInfo.Configure()
       at System.Text.Json.Serialization.Metadata.JsonTypeInfo.<EnsureConfigured>g__ConfigureSynchronized|170_0()
       at System.Text.Json.JsonSerializerOptions.GetTypeInfoInternal(Type type, Boolean ensureConfigured, Nullable`1 ensureNotNull, Boolean resolveIfMutable, Boolean fallBackToNearestAncestorType)
       at System.Text.Json.JsonSerializerOptions.GetTypeInfo(Type type)
       at SourceGenerationContext.get_MyPi() in C:\scratch\jsonDecimal\System.Text.Json.SourceGeneration\System.Text.Json.SourceGeneration.JsonSourceGenerator\SourceGenerationContext.MyPi.g.cs:line 18
       at Program.<Main>$(String[] args) in C:\scratch\jsonDecimal\Program.cs:line 4
    

    This is related to this issue, which was missing this case: dotnet/roslyn#58705

    I believe the fix here, needed for both Configuration and Json is refine and share our literal formatting helper:

    private static string FormatDefaultConstructorParameter(object? value, TypeRef type)
    {
    if (value == null)
    {
    return $"default({type.FullyQualifiedName})";
    }
    if (type.TypeKind is TypeKind.Enum)
    {
    // Return the numeric value.
    return FormatNumber();
    }
    switch (value)
    {
    case string @string:
    return SymbolDisplay.FormatLiteral(@string, quote: true); ;
    case char @char:
    return SymbolDisplay.FormatLiteral(@char, quote: true);
    case double.NegativeInfinity:
    return "double.NegativeInfinity";
    case double.PositiveInfinity:
    return "double.PositiveInfinity";
    case double.NaN:
    return "double.NaN";
    case double @double:
    return $"({type.FullyQualifiedName})({@double.ToString(JsonConstants.DoubleFormatString, CultureInfo.InvariantCulture)})";
    case float.NegativeInfinity:
    return "float.NegativeInfinity";
    case float.PositiveInfinity:
    return "float.PositiveInfinity";
    case float.NaN:
    return "float.NaN";
    case float @float:
    return $"({type.FullyQualifiedName})({@float.ToString(JsonConstants.SingleFormatString, CultureInfo.InvariantCulture)})";
    case decimal.MaxValue:
    return "decimal.MaxValue";
    case decimal.MinValue:
    return "decimal.MinValue";
    case decimal @decimal:
    return @decimal.ToString(CultureInfo.InvariantCulture);
    case bool @bool:
    return FormatBool(@bool);
    default:
    // Assume this is a number.
    return FormatNumber();
    }
    string FormatNumber() => $"({type.FullyQualifiedName})({Convert.ToString(value, CultureInfo.InvariantCulture)})";
    }

    CC @dotnet/area-system-text-json

  7. self-assigned this
    on Oct 7, 2023
  8. ericstj commented on Oct 7, 2023

    @ericstj
    Member

    I have a fix for this, but in testing it I hit #93159. I'll try to get the fix done for just this case and move on to that next.

  9. ghost added
    in-pr
    on Oct 7, 2023
  10. ghost removed
    in-pr
    on Oct 10, 2023
  11. ericstj commented on Oct 10, 2023

    @ericstj
    Member

    @chrisoverzero is this issue blocking your adoption of the source generator in 8.0? I'm trying to determine if this is worth backporting to our release branch.

  12. chrisoverzero commented on Oct 10, 2023

    @chrisoverzero
    Author

    It is not blocking me at this time, no. It’s something I discovered when doing reproduction for another issue.

  13. modified the milestones: 8.0.0, 9.0.0 on Oct 10, 2023
  14. ericstj commented on Oct 10, 2023

    @ericstj
    Member

    Ok, closing this out for now, the fix will remain in the 9.0 codebase.

  15. ericstj commented on Oct 26, 2023

    @ericstj
    Member

    While the decimal case isn't common, this also fixed the formatting of Enums with default values with is much more common. We should consider this for servicing.

  16. ericstj commented on Jul 22, 2024

    @ericstj
    Member

    This was serviced in 213f1a2

  17. locked and limited conversation to collaborators on Aug 22, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions