Skip to content

Commit

Permalink
allow assignments of MapValue constant value types to nullable value …
Browse files Browse the repository at this point in the history
…types
  • Loading branch information
latonz committed Oct 14, 2024
1 parent e5ea41c commit f5c6a33
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,9 @@ private static bool TryBuildConstantSourceValue(
return true;
}

if (!SymbolEqualityComparer.Default.Equals(value.ConstantValue.Type, memberMappingInfo.TargetMember.MemberType))
// use non-nullable target type to allow non-null value type assignments
// to nullable value types
if (!SymbolEqualityComparer.Default.Equals(value.ConstantValue.Type, memberMappingInfo.TargetMember.MemberType.NonNullable()))
{
ctx.BuilderContext.ReportDiagnostic(
DiagnosticDescriptors.MapValueTypeMismatch,
Expand All @@ -135,7 +137,7 @@ private static bool TryBuildConstantSourceValue(
// expand enum member access to fully qualified identifier
// use simple member name approach instead of slower visitor pattern on the expression
var enumMemberName = ((MemberAccessExpressionSyntax)value.Expression).Name.Identifier.Text;
var enumTypeFullName = FullyQualifiedIdentifier(memberMappingInfo.TargetMember.MemberType);
var enumTypeFullName = FullyQualifiedIdentifier(memberMappingInfo.TargetMember.MemberType.NonNullable());
sourceValue = new ConstantSourceValue(MemberAccess(enumTypeFullName, enumMemberName));
return true;
case TypedConstantKind.Type:
Expand Down
24 changes: 24 additions & 0 deletions test/Riok.Mapperly.Tests/Mapping/ObjectPropertyValueTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,30 @@ public void StringToNestedNullableProperty()
);
}

[Fact]
public void ValueTypeToNestedNullableProperty()
{
var source = TestSourceBuilder.MapperWithBodyAndTypes(
"""[MapValue("Nested.Value", E.E1)] partial B Map(A source);""",
"class A;",
"class B { public C? Nested { get; set; } }",
"class C { public E? Value { get; set; } }",
"enum E { E1 }"
);

TestHelper
.GenerateMapper(source)
.Should()
.HaveSingleMethodBody(
"""
var target = new global::B();
target.Nested ??= new global::C();
target.Nested.Value = global::E.E1;
return target;
"""
);
}

[Fact]
public void StringToNestedPropertyWithMapProperty()
{
Expand Down

0 comments on commit f5c6a33

Please sign in to comment.