Skip to content

Commit

Permalink
fix: use correct nullable types when referencing named mappings (#1237)
Browse files Browse the repository at this point in the history
  • Loading branch information
latonz authored Apr 15, 2024
1 parent de3b332 commit b3f79e8
Show file tree
Hide file tree
Showing 3 changed files with 57 additions and 1 deletion.
11 changes: 10 additions & 1 deletion src/Riok.Mapperly/Descriptors/MappingBuilderContext.cs
Original file line number Diff line number Diff line change
Expand Up @@ -175,7 +175,16 @@ bool ignoreDerivedTypes
Location? diagnosticLocation = null
)
{
return FindMapping(key) ?? FindOrBuildMapping(key.NonNullable(), options, diagnosticLocation);
if (FindMapping(key) is { } mapping)
return mapping;

// if a user mapping is referenced
// build it with the exact types
// as it may expect a nullable source type
if (key.Configuration.UseNamedMapping != null)
return BuildMapping(key, options, diagnosticLocation);

return FindOrBuildMapping(key.NonNullable(), options, diagnosticLocation);
}

/// <summary>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -347,4 +347,34 @@ class B
);
return TestHelper.VerifyGenerator(source);
}

[Fact]
public Task ShouldPassNullValueToNullableUserMappingMethod()
{
var source = TestSourceBuilder.MapperWithBodyAndTypes(
"""
[MapProperty(nameof(A.Value), nameof(B.Value), Use = nameof(MapString)]
public partial B Map(A source);
[UserMapping(Default = false)]
private string MapString(string? source)
=> source ?? "(null)";
""",
"""
class A
{
public string? Value { get; }
public string? Value2 { get; }
}
""",
"""
class B
{
public string Value { set; }
public string Value2 { set; }
}
"""
);
return TestHelper.VerifyGenerator(source);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
//HintName: Mapper.g.cs
// <auto-generated />
#nullable enable
public partial class Mapper
{
[global::System.CodeDom.Compiler.GeneratedCode("Riok.Mapperly", "0.0.1.0")]
public partial global::B Map(global::A source)
{
var target = new global::B();
if (source.Value2 != null)
{
target.Value2 = source.Value2;
}
target.Value = MapString(source.Value);
return target;
}
}

0 comments on commit b3f79e8

Please sign in to comment.