Skip to content
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 @@ -12,7 +12,7 @@ namespace Microsoft.Extensions.Configuration.Binder.SourceGeneration
public sealed partial class ConfigurationBindingGenerator
{
/// <summary>
/// Supresses false-positive diagnostics emitted by the linker
/// Suppresses false-positive diagnostics emitted by the linker
/// when analyzing binding invocations that we have intercepted.
/// Workaround for https://github.com/dotnet/roslyn/issues/68669.
/// </summary>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1180,7 +1180,10 @@ private bool EmitObjectInit(ComplexTypeSpec type, string memberAccessExpr, Initi

if (strategy is ObjectInstantiationStrategy.ParameterlessConstructor)
{
initExpr = $"new {typeFQN}()";
// value tuple types will be declared with syntax like:
// (int, int) value = default;
// This is to avoid using invalid syntax calling the parameterless constructor
initExpr = type.IsValueTuple ? "default" : $"new {typeFQN}()";
}
else
{
Expand All @@ -1195,7 +1198,11 @@ private bool EmitObjectInit(ComplexTypeSpec type, string memberAccessExpr, Initi
case InitializationKind.Declaration:
{
Debug.Assert(!memberAccessExpr.Contains('.'));
_writer.WriteLine($"var {memberAccessExpr} = {initExpr};");
// value tuple will be declared with syntax like:
// (int, int) value = default;
// We need to specify the typeFQN as we assign the variable to default value.
string declarationType = type.IsValueTuple ? typeFQN : $"var";
_writer.WriteLine($"{declarationType} {memberAccessExpr} = {initExpr};");
}
break;
case InitializationKind.AssignmentWithNullCheck:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ public TypeSpec(ITypeSymbol type)
(DisplayString, FullName) = type.GetTypeNames();
IdentifierCompatibleSubstring = type.ToIdentifierCompatibleSubstring();
IsValueType = type.IsValueType;
IsValueTuple = type is INamedTypeSymbol namedTypeSymbol && namedTypeSymbol.IsTupleType;
}

public TypeRef TypeRef { get; }
Expand All @@ -36,6 +37,8 @@ public TypeSpec(ITypeSymbol type)
public string IdentifierCompatibleSubstring { get; }

public bool IsValueType { get; }

public bool IsValueTuple { get; }
}

public abstract record ComplexTypeSpec : TypeSpec
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -202,5 +202,18 @@ private static HashSet<Assembly> GetFilteredAssemblyRefs(IEnumerable<Type> exclu
}
return assemblies;
}

public static byte[] CreateAssemblyImage(Compilation compilation)
{
MemoryStream ms = new MemoryStream();
var emitResult = compilation.Emit(ms);
if (!emitResult.Success)
{
// Explicit failures to include in the test output.
string errorMessage = string.Join(Environment.NewLine, emitResult.Diagnostics.Select(d => d.ToString()));
throw new InvalidOperationException(errorMessage);
}
return ms.ToArray();
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -257,6 +257,43 @@ async Task Test(bool expectOutput)
}
}

[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsNetCore))]
public async Task ListOfTupleTest()
{
string source = """
using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Generic;

public class Program
{
public static void Main()
{
ConfigurationBuilder configurationBuilder = new();
IConfiguration config = configurationBuilder.Build();

var settingsSection = config.GetSection("Settings");

Settings options = settingsSection.Get<Settings>()!;
}
}

public class Settings
{
public List<(string Item1, string? Item2)>? Items { get; set; }
}
""";

ConfigBindingGenRunResult result = await RunGeneratorAndUpdateCompilation(source, assemblyReferences: GetAssemblyRefsWithAdditional(typeof(ConfigurationBuilder), typeof(List<>)));
Assert.NotNull(result.GeneratedSource);
Assert.Empty(result.Diagnostics);

// Ensure the generated code can be compiled.
// If there is any compilation error, exception will be thrown with the list of the errors in the exception message.
byte[] emittedAssemblyImage = CreateAssemblyImage(result.OutputCompilation);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Interesting this is the first time we're compiling the generator output -- we didn't have any other patterns to follow here for validating this?

Copy link
Member Author

@tarekgh tarekgh May 1, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We do in other places, for example:

used to compile and run the generated code. In my case I wanted to validate it compile fine. This is used also in other generators too like regex and json.

Assert.NotNull(emittedAssemblyImage);
}

/// <summary>
/// We binding the type "SslClientAuthenticationOptions" which has a property "CipherSuitesPolicy" of type "CipherSuitesPolicy". We can't bind this type.
/// This test is to ensure not including the property "CipherSuitesPolicy" in the generated code caused a build break.
Expand Down
Loading