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 @@ -66,11 +66,7 @@ public static bool TryBuild(
[NotNullWhen(true)] out SourceValueBuilder.MappedValue? result
)
{
var mappingKey = memberMappingInfo.ToTypeMappingKey();
var delegateMapping = ctx.BuilderContext.FindOrBuildLooseNullableMapping(
mappingKey,
diagnosticLocation: memberMappingInfo.Configuration?.Location
);
var delegateMapping = FindDelegateMapping(ctx.BuilderContext, memberMappingInfo);

var sourceMember = memberMappingInfo.SourceMember!;
var targetMember = memberMappingInfo.TargetMember;
Expand Down Expand Up @@ -147,6 +143,34 @@ public static bool TryBuild(
return true;
}

private static INewInstanceMapping? FindDelegateMapping(MappingBuilderContext ctx, MemberMappingInfo memberMappingInfo)
{
var mappingKey = memberMappingInfo.ToTypeMappingKey();

// Null-conditional access lifts a value type leaf to Nullable<T> when a parent is nullable.
// Only prefer an existing user implementation; otherwise retain the usual mapping and null handling.
// Expression trees cannot use the null-conditional access emitted for these mappings.
if (
!ctx.IsExpression
&& memberMappingInfo.IsSourceNullable
&& mappingKey.Source.IsValueType
&& !mappingKey.Source.IsRefLikeType
&& !mappingKey.Source.IsNullableValueType()
&& mappingKey.Configuration.UseNamedMapping == null
)
{
var nullableSource = ctx
.Types.Get(typeof(Nullable<>))
.Construct(mappingKey.Source.NonNullable())
.WithNullableAnnotation(NullableAnnotation.Annotated);
var nullableKey = new TypeMappingKey(nullableSource, mappingKey.Target, mappingKey.Configuration);
if (ctx.FindUserImplementedMapping(nullableKey) is { } mapping)
return mapping;
}

return ctx.FindOrBuildLooseNullableMapping(mappingKey, diagnosticLocation: memberMappingInfo.Configuration?.Location);
}

private static MemberPathGetter? GetTargetValueGetterIfNeeded(
IMembersBuilderContext<IMapping> ctx,
INewInstanceMapping delegateMapping,
Expand Down
6 changes: 6 additions & 0 deletions src/Riok.Mapperly/Descriptors/MappingBuilderContext.cs
Original file line number Diff line number Diff line change
Expand Up @@ -153,6 +153,12 @@ private static ParameterScope BuildParameterScope(IUserMapping? userMapping) =>
public virtual INewInstanceMapping? FindMapping(TypeMappingKey mappingKey, ParameterScope? scope = null) =>
MappingBuilder.Find(mappingKey, scope);

/// <summary>
/// Finds a user-implemented mapping without marking rejected mappings or their additional parameters as used.
/// </summary>
public UserImplementedMethodMapping? FindUserImplementedMapping(TypeMappingKey mappingKey) =>
MappingBuilder.FindUserImplemented(mappingKey, ParameterScope);

/// <summary>
/// Tries to find an existing mapping for the provided types.
/// If none is found, a new one is created.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,9 @@ public class MappingBuilder(MappingCollection mappings, MapperDeclaration mapper
public INewInstanceMapping? Find(TypeMappingKey mapping, ParameterScope? scope = null) =>
mappings.FindNewInstanceMapping(mapping, scope);

public UserImplementedMethodMapping? FindUserImplemented(TypeMappingKey mapping, ParameterScope? scope = null) =>
mappings.FindNewInstanceUserImplementedMapping(mapping, scope);

public INewInstanceMapping? FindOrResolveNamed(SimpleMappingBuilderContext ctx, string name, out bool ambiguousName)
{
if (!ctx.Configuration.Mapper.AutoUserMappings && _resolvedMappingNames.Add(name))
Expand Down
30 changes: 21 additions & 9 deletions src/Riok.Mapperly/Descriptors/MappingCollection.cs
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,19 @@ public class MappingCollection(GenericTypeChecker genericTypeChecker)

public INewInstanceUserMapping? FindNewInstanceUserMapping(IMethodSymbol method) => _newInstanceMappings.FindUserMapping(method);

public UserImplementedMethodMapping? FindNewInstanceUserImplementedMapping(TypeMappingKey mappingKey, ParameterScope? scope = null)
{
if (
_newInstanceMappings.Find(mappingKey, scope, static m => m is UserImplementedMethodMapping)
is UserImplementedMethodMapping mapping
)
{
return mapping;
}

return mappingKey.Configuration.UseNamedMapping == null ? TryMatchGenericNewInstanceTemplate(mappingKey) : null;
}

public INewInstanceMapping? FindNamedNewInstanceMapping(string name, out bool ambiguousName) =>
_newInstanceMappings.FindNamed(name, out ambiguousName);

Expand Down Expand Up @@ -206,7 +219,7 @@ public void AddNamedExistingInstanceUserMapping(string name, IExistingTargetUser
_existingTargetMappings.AddNamedUserMapping(name, mapping);
}

private INewInstanceMapping? TryMatchGenericNewInstanceTemplate(TypeMappingKey mappingKey)
private UserImplementedGenericMethodMapping? TryMatchGenericNewInstanceTemplate(TypeMappingKey mappingKey)
{
if (_genericNewInstanceTemplates.Count == 0)
return null;
Expand Down Expand Up @@ -313,19 +326,18 @@ private sealed class MappingCollectionInstance<T, TUserMapping>

public TUserMapping? FindUserMapping(IMethodSymbol method) => _userMappingsByMethod.GetValueOrDefault(method);

public T? Find(TypeMappingKey mappingKey, ParameterScope? scope = null)
public T? Find(TypeMappingKey mappingKey, ParameterScope? scope = null, Func<T, bool>? filter = null)
{
if (scope is { IsEmpty: false } && FindByParameters(mappingKey, scope) is { } parameterizedMapping)
if (scope is { IsEmpty: false } && FindByParameters(mappingKey, scope, filter) is { } parameterizedMapping)
{
_usedMappingKeys.Add(mappingKey);
return parameterizedMapping;
}

if (_defaultMappings.TryGetValue(mappingKey, out var mapping))
{
_usedMappingKeys.Add(mappingKey);
}
if (!_defaultMappings.TryGetValue(mappingKey, out var mapping) || filter?.Invoke(mapping) == false)
return default;

_usedMappingKeys.Add(mappingKey);
return mapping;
}

Expand All @@ -341,13 +353,13 @@ private sealed class MappingCollectionInstance<T, TUserMapping>
return mapping;
}

private TUserMapping? FindByParameters(TypeMappingKey key, ParameterScope scope)
private TUserMapping? FindByParameters(TypeMappingKey key, ParameterScope scope, Func<T, bool>? filter)
{
var candidates = _userMappings.GetOrEmpty(key).Where(m => m is IParameterizedMapping { AdditionalSourceParameters.Count: > 0 });

foreach (var mapping in candidates)
{
if (scope.TryUseParameters(mapping))
if (filter?.Invoke(mapping) != false && scope.TryUseParameters(mapping))
return mapping;
}

Expand Down
5 changes: 5 additions & 0 deletions src/Riok.Mapperly/Descriptors/ParameterScope.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,11 @@

namespace Riok.Mapperly.Descriptors;

/// <summary>
/// Manages additional source parameters available to mappings and tracks their usage.
/// Child scopes share their parent's parameters and delegate usage tracking to the root scope
/// for unused-parameter diagnostics.
/// </summary>
public class ParameterScope
{
private static readonly IReadOnlyDictionary<string, MethodParameter> _emptyParameters = new Dictionary<string, MethodParameter>();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,31 @@ public UnsafeConstructorAccessor GetOrBuildConstructor(IMethodSymbol ctorSymbol)
);
}

internal static ExpressionSyntax BuildNullConditionalAccess(
ISymbol member,
INamedTypeSymbol containingType,
ExpressionSyntax receiver,
ExpressionSyntax access
)
{
// Accessors are cached by the original definition, so resolve the member type
// on the actual containing type before lifting value types to Nullable<T>.
var constructedMember = containingType
.GetMembers(member.Name)
.First(m => SymbolEqualityComparer.Default.Equals(m.OriginalDefinition, member.OriginalDefinition));
var memberType = constructedMember switch
{
IPropertySymbol property => property.Type,
IFieldSymbol field => field.Type,
_ => throw new ArgumentException("Only properties and fields support null-conditional unsafe access", nameof(member)),
};
ExpressionSyntax nullValue =
memberType.IsValueType && !memberType.IsNullableValueType() && !memberType.IsRefLikeType
? CastExpression(NullableType(NonNullableIdentifier(memberType)), NullLiteral())
: DefaultLiteral();
return Conditional(IsNotNull(receiver, containingType), access, nullValue);
}

internal MemberDeclarationSyntax BuildSyntax(SourceEmitterContext ctx, CancellationToken cancellationToken)
{
var accessorCtx = ctx.AddIndentation();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,12 @@ public ExpressionSyntax BuildAccess(ExpressionSyntax? baseAccess, INamedTypeSymb
if (!nullConditional)
return invocation;

return Conditional(IsNotNull(baseAccess, containingType ?? symbol.ContainingType), invocation, DefaultLiteral());
return UnsafeAccessorTypeContext.BuildNullConditionalAccess(
symbol,
containingType ?? symbol.ContainingType,
baseAccess,
invocation
);
}

public ExpressionSyntax BuildAssignment(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,11 @@ public ExpressionSyntax BuildAccess(ExpressionSyntax? baseAccess, INamedTypeSymb
if (!nullConditional)
return invocation;

return Conditional(IsNotNull(baseAccess, containingType ?? symbol.ContainingType), invocation, DefaultLiteral());
return UnsafeAccessorTypeContext.BuildNullConditionalAccess(
symbol,
containingType ?? symbol.ContainingType,
baseAccess,
invocation
);
}
}
69 changes: 69 additions & 0 deletions test/Riok.Mapperly.Tests/Mapping/ObjectPropertyNullableTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1603,4 +1603,73 @@ class B
"""
);
}

[Fact]
public void NullableParentShouldPreferNullableUserMapping()
{
var source = TestSourceBuilder.MapperWithBodyAndTypes(
"""
[MapProperty("NullableItem.Value", "NullableValue")]
[MapProperty("Item.Value", "Value")]
partial B Map(A source);
int MapNullable(int? source) => source ?? -1;
int MapNonNullable(int source) => source + 1;
""",
"record A(C? NullableItem, C Item);",
"record C(int Value);",
"class B { public int NullableValue { get; init; } public int Value { get; init; } }"
);

TestHelper
.GenerateMapper(source)
.Should()
.HaveMapMethodBody(
"""
var target = new global::B()
{
NullableValue = MapNullable(source.NullableItem?.Value),
Value = MapNonNullable(source.Item.Value),
};
return target;
"""
);
}

[Fact]
public void NullableParentWithGeneratedNullableMappingsShouldKeepNullFallback()
{
var source = TestSourceBuilder.MapperWithBodyAndTypes(
"""
[MapProperty("Item.Value", "Value")]
partial B Map(A source);
private partial int MapNullable(int? source);
private partial int OtherNullable(int? source);
""",
TestSourceBuilderOptions.Default with
{
ThrowOnMappingNullMismatch = true,
},
"record A(C? Item);",
"record C(int Value);",
"record B(int Value);"
);

TestHelper
.GenerateMapper(source, TestHelperOptions.AllowDiagnostics)
.Should()
.HaveDiagnostic(
DiagnosticDescriptors.NullableSourceValueToNonNullableTargetValue,
"Mapping the nullable source property Item.Value of A to the target property Value of B which is not nullable"
)
.HaveDiagnostic(DiagnosticDescriptors.NullableSourceTypeToNonNullableTargetType)
.HaveAssertedAllDiagnostics()
.HaveMapMethodBody(
"""
var target = new global::B(
source.Item?.Value ?? throw new global::System.ArgumentNullException(nameof(source.Item.Value))
);
return target;
"""
);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -945,4 +945,41 @@ class B
"""
);
}

[Fact]
public void NullableParentShouldKeepExplicitMapping()
{
var source = TestSourceBuilder.MapperWithBodyAndTypes(
"""
[MapProperty("Item.Value", "Value", Use = nameof(MapNonNullable))]
partial B Map(A source);
int MapNullable(int? source) => source ?? -1;
int MapNonNullable(int source) => source + 1;
""",
TestSourceBuilderOptions.Default with
{
ThrowOnMappingNullMismatch = true,
},
"record A(C? Item);",
"record C(int Value);",
"record B(int Value);"
);

TestHelper
.GenerateMapper(source, TestHelperOptions.AllowDiagnostics)
.Should()
.HaveDiagnostic(
DiagnosticDescriptors.NullableSourceValueToNonNullableTargetValue,
"Mapping the nullable source property Item.Value of A to the target property Value of B which is not nullable"
)
.HaveAssertedAllDiagnostics()
.HaveMapMethodBody(
"""
var target = new global::B(
source.Item != null ? MapNonNullable(source.Item.Value) : throw new global::System.ArgumentNullException(nameof(source.Item.Value))
);
return target;
"""
);
}
}
60 changes: 60 additions & 0 deletions test/Riok.Mapperly.Tests/Mapping/UnsafeAccessorTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -826,4 +826,64 @@ public partial class CarMapper

return TestHelper.VerifyGenerator(source);
}

[Fact]
public void NullableGenericParentWithInheritedPrivatePropertyShouldPassNullToUserMapping()
{
var source = TestSourceBuilder.MapperWithBodyAndTypes(
"""
[MapProperty("Item.Value", "Value")]
partial B Map(A source);
int MapNullable(int? source) => source ?? -1;
""",
TestSourceBuilderOptions.WithMemberVisibility(MemberVisibility.All),
"class A { public D<int>? Item { get; set; } }",
"class B { public int Value { get; set; } }",
"class C<T> { private T Value { get; set; } }",
"class D<T> : C<T> { }"
);

TestHelper
.GenerateMapper(source)
.Should()
.HaveMapMethodBody(
"""
var target = new global::B();
target.Value = MapNullable(
source.Item != null ? CAccessor<int>.GetValue(source.Item) : (int?)null
);
return target;
"""
);
}

[Fact]
public void NullableGenericParentWithInheritedPrivateFieldShouldPassNullToUserMapping()
{
var source = TestSourceBuilder.MapperWithBodyAndTypes(
"""
[MapProperty("Item.Value", "Value")]
partial B Map(A source);
int MapNullable(int? source) => source ?? -1;
""",
TestSourceBuilderOptions.WithMemberVisibility(MemberVisibility.All),
"class A { public D<int>? Item { get; set; } }",
"class B { public int Value { get; set; } }",
"class C<T> { private T Value; }",
"class D<T> : C<T> { }"
);

TestHelper
.GenerateMapper(source)
.Should()
.HaveMapMethodBody(
"""
var target = new global::B();
target.Value = MapNullable(
source.Item != null ? CAccessor<int>.GetValue(source.Item) : (int?)null
);
return target;
"""
);
}
}
Loading
Loading