Skip to content
Open
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 @@ -19,28 +19,36 @@ IExistingTargetMapping delegateMapping
{
private const string NullableValueProperty = nameof(Nullable<>.Value);

public override IEnumerable<StatementSyntax> Build(TypeMappingBuildContext ctx, ExpressionSyntax target)
public override IEnumerable<StatementSyntax> Build(TypeMappingBuildContext ctx, ExpressionSyntax target) =>
Build(ctx, target, ctx.Source, unwrapNullableSource: true);

public IEnumerable<StatementSyntax> Build(
TypeMappingBuildContext ctx,
ExpressionSyntax target,
ExpressionSyntax nullSafeSource,
bool unwrapNullableSource = false
)
{
// if the source or target type is nullable, add a null guard.
if (!SourceType.IsNullable() && !TargetType.IsNullable())
return delegateMapping.Build(ctx, target);

var body = BuildBody(ctx, target);
var body = BuildBody(ctx, target, unwrapNullableSource);

// if body is empty don't generate an if statement
if (body.Length == 0)
return [];

// if (source != null && target != null) { body }
var condition = IfNoneNull((SourceType, ctx.Source), (TargetType, target));
var condition = IfNoneNull((SourceType, nullSafeSource), (TargetType, target));
var ifStatement = ctx.SyntaxFactory.If(condition, body);
return [ifStatement];
}

private StatementSyntax[] BuildBody(TypeMappingBuildContext ctx, ExpressionSyntax target)
private StatementSyntax[] BuildBody(TypeMappingBuildContext ctx, ExpressionSyntax target, bool unwrapNullableSource)
{
ctx = ctx.AddIndentation();
if (SourceType.IsNullableValueType())
if (unwrapNullableSource && SourceType.IsNullableValueType())
{
ctx = ctx.WithSource(MemberAccess(ctx.Source, NullableValueProperty));
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
using System.Diagnostics.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Riok.Mapperly.Descriptors.Mappings.ExistingTarget;
using Riok.Mapperly.Helpers;
using Riok.Mapperly.Symbols.Members;

namespace Riok.Mapperly.Descriptors.Mappings.MemberMappings;
Expand All @@ -25,8 +26,30 @@ public bool TryGetMemberAssignmentMappingContainer([NotNullWhen(true)] out IMemb

public IEnumerable<StatementSyntax> Build(TypeMappingBuildContext ctx, ExpressionSyntax targetAccess)
{
var source = sourcePath.BuildAccess(ctx.Source);
var target = targetPath.BuildAccess(targetAccess);
return delegateMapping.Build(ctx.WithSource(source), target);

if (!sourcePath.MemberPath.IsAnyObjectReadPathNullable())
{
var source = sourcePath.BuildAccess(ctx.Source);
return delegateMapping.Build(ctx.WithSource(source), target);
}

if (delegateMapping is NullDelegateExistingTargetMapping nullDelegateMapping && nullDelegateMapping.SourceType.IsNullable())
{
var nullSafeSource = sourcePath.BuildAccess(ctx.Source, nullConditional: true);
var source = sourcePath.BuildAccess(ctx.Source, addValuePropertyOnNullable: true);
return nullDelegateMapping.Build(ctx.WithSource(source), target, nullSafeSource);
}

if (delegateMapping.SourceType.IsNullable())
{
var nullSafeSource = sourcePath.BuildAccess(ctx.Source, nullConditional: true);
return delegateMapping.Build(ctx.WithSource(nullSafeSource), target);
}

var notNullCondition = sourcePath.BuildNotNullCondition(ctx.Source, useNullConditionalAccess: true)!;
var sourceAccess = sourcePath.BuildAccess(ctx.Source, addValuePropertyOnNullable: true);
var body = delegateMapping.Build(ctx.AddIndentation().WithSource(sourceAccess), target).ToArray();
return body.Length == 0 ? [] : [ctx.SyntaxFactory.If(notNullCondition, body)];
}
}
165 changes: 165 additions & 0 deletions test/Riok.Mapperly.Tests/Mapping/EnumerableExistingTargetTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -169,4 +169,169 @@ public Task MapArrayToReadOnlyArrayShouldDiagnostic()
);
return TestHelper.VerifyGenerator(source);
}

[Fact]
public void MapNestedEnumerableToReadOnlyListWithDisabledNullable()
{
var source = TestSourceBuilder.MapperWithBodyAndTypes(
"""
[MapProperty(nameof(@A.Nested.Items), nameof(B.Items))]
partial B Map(A source);
""",
"class A { public Nested Nested { get; set; } }",
"class Nested { public IEnumerable<int> Items { get; set; } }",
"class B { public readonly List<int> Items = []; }"
);
TestHelper
.GenerateMapper(source, TestHelperOptions.DisabledNullable)
.Should()
.HaveSingleMethodBody(
"""
if (source == null)
return default;
var target = new global::B();
if (source.Nested?.Items != null && target.Items != null)
{
if (global::System.Linq.Enumerable.TryGetNonEnumeratedCount(source.Nested.Items, out var sourceCount))
{
target.Items.EnsureCapacity(sourceCount + target.Items.Count);
}
foreach (var item in source.Nested.Items)
{
target.Items.Add(item);
}
}
return target;
"""
);
}

[Fact]
public void MapNestedNullableParentEnumerableToReadOnlyList()
{
var source = TestSourceBuilder.MapperWithBodyAndTypes(
"""
[MapProperty(nameof(@A.Nested.Items), nameof(B.Items))]
partial B Map(A source);
""",
"class A { public Nested? Nested { get; set; } }",
"class Nested { public IEnumerable<int> Items { get; set; } = []; }",
"class B { public readonly List<int> Items = []; }"
);
TestHelper
.GenerateMapper(source, TestHelperOptions.AllowInfoDiagnostics)
.Should()
.HaveSingleMethodBody(
"""
var target = new global::B();
if (source.Nested?.Items != null)
{
if (global::System.Linq.Enumerable.TryGetNonEnumeratedCount(source.Nested.Items, out var sourceCount))
{
target.Items.EnsureCapacity(sourceCount + target.Items.Count);
}
foreach (var item in source.Nested.Items)
{
target.Items.Add(item);
}
}
return target;
"""
);
}

[Fact]
public void MapNestedNullableStructParentEnumerableToReadOnlyList()
{
var source = TestSourceBuilder.MapperWithBodyAndTypes(
"""
[MapProperty(nameof(@A.Nested.Items), nameof(B.Items))]
partial B Map(A source);
""",
"class A { public Nested? Nested { get; set; } }",
"struct Nested { public C? Items { get; set; } }",
"struct C : IEnumerable<int> { public IEnumerator<int> GetEnumerator() => throw null!; System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() => throw null!; }",
"class B { public readonly List<int> Items = []; }"
);
TestHelper
.GenerateMapper(source, TestHelperOptions.AllowInfoDiagnostics)
.Should()
.HaveSingleMethodBody(
"""
var target = new global::B();
if (source.Nested?.Items != null)
{
if (global::System.Linq.Enumerable.TryGetNonEnumeratedCount(source.Nested.Value.Items.Value, out var sourceCount))
{
target.Items.EnsureCapacity(sourceCount + target.Items.Count);
}
foreach (var item in source.Nested.Value.Items.Value)
{
target.Items.Add(item);
}
}
return target;
"""
);
}

[Fact]
public void MapNestedNullableParentNonNullableValueTypeEnumerableToReadOnlyList()
{
var source = TestSourceBuilder.MapperWithBodyAndTypes(
"""
[MapProperty(nameof(@A.Nested.Items), nameof(B.Items))]
partial B Map(A source);
""",
"class A { public Nested? Nested { get; set; } }",
"class Nested { public C Items { get; set; } }",
"struct C : IEnumerable<int> { public IEnumerator<int> GetEnumerator() => throw null!; System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() => throw null!; }",
"class B { public readonly List<int> Items = []; }"
);
TestHelper
.GenerateMapper(source, TestHelperOptions.AllowInfoDiagnostics)
.Should()
.HaveSingleMethodBody(
"""
var target = new global::B();
if (source.Nested?.Items != null)
{
if (global::System.Linq.Enumerable.TryGetNonEnumeratedCount(source.Nested.Items, out var sourceCount))
{
target.Items.EnsureCapacity(sourceCount + target.Items.Count);
}
foreach (var item in source.Nested.Items)
{
target.Items.Add(item);
}
}
return target;
"""
);
}

[Fact]
public void MapNestedNullableParentWithUserImplementedExistingTargetMethod()
{
var source = TestSourceBuilder.MapperWithBodyAndTypes(
"""
[MapProperty(nameof(@A.Nested.Items), nameof(B.Items), Use = nameof(MapItems))]
partial B Map(A source);
private void MapItems(IEnumerable<int>? source, List<int> target) {}
""",
"class A { public Nested? Nested { get; set; } }",
"class Nested { public IEnumerable<int>? Items { get; set; } }",
"class B { public readonly List<int> Items = []; }"
);
TestHelper
.GenerateMapper(source)
.Should()
.HaveSingleMethodBody(
"""
var target = new global::B();
MapItems(source.Nested?.Items, target.Items);
return target;
"""
);
}
}