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
1 change: 1 addition & 0 deletions docs/docs/breaking-changes/5-0.md
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ description: How to upgrade to Mapperly 5.0 and a list of all its breaking chang
- `RMG032` (enum mapping strategy not supported in projection mappings) is now an error and no cast fallback is generated, [see below](#rmg032-is-now-an-error).
- User-implemented mappings are no longer reused for mappings with inexact source or target types, [see below](#user-implemented-mappings-require-exact-types).
- Methods annotated with `[UserMapping(Ignore = true)]` are skipped before their signature is validated, so `RMG001` is no longer reported for ignored methods with unsupported signatures.
- A `[MappingTargetOriginalValue]` parameter receives its default value when the target member is not readable or has a type the parameter cannot take. The new warnings `RMG102` and `RMG101` report these cases, see [target original value parameter](../configuration/user-implemented-methods.mdx#target-original-value-parameter).

## User-implemented mappings require exact types

Expand Down
11 changes: 11 additions & 0 deletions docs/docs/configuration/user-implemented-methods.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -222,3 +222,14 @@ This lets the method use the existing destination value e.g. as a fallback when
```
</TabItem>
</Tabs>

Mapperly passes the current value only when all of the following apply:

- The target member is set by an assignment.
Init-only members, constructor parameters and queryable projections are not.
- The target member is readable.
- The target member type converts implicitly to the parameter type.

Otherwise the parameter receives its default value.
For a target member set by an assignment, Mapperly reports `RMG102` if the member is not readable
and `RMG101` if its type does not fit.
2 changes: 2 additions & 0 deletions src/Riok.Mapperly/AnalyzerReleases.Shipped.md
Original file line number Diff line number Diff line change
Expand Up @@ -226,6 +226,8 @@ RMG097 | Mapper | Error | MapValue Use method parameters cannot be satisfied
RMG098 | Mapper | Error | Named mapping additional parameters cannot be satisfied
RMG099 | Mapper | Error | Duplicate additional parameter names differing only in casing
RMG100 | Mapper | Error | [MappingTargetOriginalValue] is not supported on generated (partial) mapping methods.
RMG101 | Mapper | Warning | The target member type does not match the [MappingTargetOriginalValue] parameter type
RMG102 | Mapper | Warning | The target member cannot be read for the [MappingTargetOriginalValue] parameter

### Changed Rules

Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
using System.Diagnostics.CodeAnalysis;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Riok.Mapperly.Descriptors.MappingBodyBuilders.BuilderContext;
using Riok.Mapperly.Descriptors.Mappings;
using Riok.Mapperly.Descriptors.Mappings.MemberMappings;
Expand Down Expand Up @@ -104,7 +105,7 @@ public static bool TryBuild(
);
}

var targetValueGetter = GetTargetValueGetterIfNeeded(ctx, delegateMapping, memberMappingInfo.TargetMember);
var targetValueGetter = GetTargetValueGetterIfNeeded(ctx, delegateMapping, memberMappingInfo.TargetMember, codeStyle);

if (
(memberSourceNullable == delegateSourceNullable && memberTargetAcceptsNull == delegateTargetNullable)
Expand Down Expand Up @@ -174,11 +175,51 @@ public static bool TryBuild(
private static MemberPathGetter? GetTargetValueGetterIfNeeded(
IMembersBuilderContext<IMapping> ctx,
INewInstanceMapping delegateMapping,
NonEmptyMemberPath targetMember
) =>
delegateMapping is UserImplementedMethodMapping { TargetOriginalValueParameter: not null }
? targetMember.BuildGetter(ctx.BuilderContext)
: null;
NonEmptyMemberPath targetMember,
CodeStyle codeStyle
)
{
if (delegateMapping is CompositeMapping composite)
delegateMapping = composite.NamedMapping;

if (delegateMapping is not UserImplementedMethodMapping { TargetOriginalValueParameter: { } parameter } userMapping)
return null;

// An initializer never passes the target value, so a diagnostic only helps for an assignment.
var reportDiagnostics = codeStyle == CodeStyle.Statement;

if (!targetMember.Member.CanGet)
{
if (reportDiagnostics)
{
ctx.BuilderContext.ReportDiagnostic(
DiagnosticDescriptors.MappingTargetOriginalValueMemberNotReadable,
targetMember.ToDisplayString(),
parameter.Name,
userMapping.Method.Name
);
}

return null;
}

// The getter reads the member itself, so its type decides whether the parameter accepts the value.
if (ctx.BuilderContext.Compilation.ClassifyConversion(targetMember.Member.Type, parameter.Type).IsImplicit)
return targetMember.BuildGetter(ctx.BuilderContext);

if (reportDiagnostics)
{
ctx.BuilderContext.ReportDiagnostic(
DiagnosticDescriptors.MappingTargetOriginalValueTypeMismatch,
targetMember.ToDisplayString(),
parameter.Name,
parameter.Type.ToDisplayString(),
userMapping.Method.Name
);
}

return null;
}

private static bool ValidateLoopMapping(
IMembersBuilderContext<IMapping> ctx,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,20 +47,16 @@ public static class UseNamedMappingBuilder
var differentSourceType = !SymbolEqualityComparer.IncludeNullability.Equals(ctx.Source, mapping.SourceType);
var differentTargetType = !SymbolEqualityComparer.IncludeNullability.Equals(ctx.Target, mapping.TargetType);

// use a delegate mapping,
// otherwise the user-defined method mapping may get built twice
// (if it is returned here directly, it is re-added to the mappings to be built)
if (!differentSourceType && !differentTargetType)
return new DelegateMapping(mapping.SourceType, mapping.TargetType, mapping);
var inputMapping = differentSourceType ? TryMapSource(ctx, mapping) : null;
if (differentSourceType && inputMapping == null)
return null;

if (differentSourceType)
{
mapping = TryMapSource(ctx, mapping);
if (mapping == null)
return null;
}
var outputMapping = differentTargetType ? TryMapTarget(ctx, mapping) : null;
if (differentTargetType && outputMapping == null)
return null;

return differentTargetType ? TryMapTarget(ctx, mapping) : mapping;
// Wrap even exact matches to avoid re-adding the named mapping to the mappings to be built.
return new CompositeMapping(mapping, inputMapping, outputMapping);
}

public static IExistingTargetMapping? TryBuildExistingTargetMapping(MappingBuilderContext ctx)
Expand Down Expand Up @@ -182,7 +178,7 @@ IExistingTargetMapping existingTargetMapping
return null;
}

return new CompositeMapping(outputMapping, mapping);
return outputMapping;
}

private static INewInstanceMapping? TryMapSource(MappingBuilderContext ctx, INewInstanceMapping mapping)
Expand All @@ -205,6 +201,6 @@ IExistingTargetMapping existingTargetMapping
return null;
}

return new CompositeMapping(mapping, inputMapping);
return inputMapping;
}
}
20 changes: 15 additions & 5 deletions src/Riok.Mapperly/Descriptors/Mappings/CompositeMapping.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,23 @@
namespace Riok.Mapperly.Descriptors.Mappings;

/// <summary>
/// Creates a composition of two mappings
/// Invokes a named mapping with optional input and output conversions.
/// <code>
/// OutputMapping(InnerMapping(source));
/// OutputMapping(NamedMapping(InputMapping(source)));
/// </code>
/// </summary>
public class CompositeMapping(INewInstanceMapping outerMapping, INewInstanceMapping innerMapping)
: NewInstanceMapping(innerMapping.SourceType, outerMapping.TargetType)
public class CompositeMapping(INewInstanceMapping namedMapping, INewInstanceMapping? inputMapping, INewInstanceMapping? outputMapping)
: NewInstanceMapping(inputMapping?.SourceType ?? namedMapping.SourceType, outputMapping?.TargetType ?? namedMapping.TargetType)
{
public override ExpressionSyntax Build(TypeMappingBuildContext ctx) => outerMapping.Build(ctx.WithSource(innerMapping.Build(ctx)));
internal INewInstanceMapping NamedMapping { get; } = namedMapping;

public override ExpressionSyntax Build(TypeMappingBuildContext ctx)
{
// The input and output conversions do not receive the target value, even if they use [MappingTargetOriginalValue].
// The target value is passed only to the named mapping.
var conversionCtx = ctx.WithTargetValue(null);
var source = inputMapping?.Build(conversionCtx) ?? ctx.Source;
var result = NamedMapping.Build(ctx.WithSource(source));
return outputMapping?.Build(conversionCtx.WithSource(result)) ?? result;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ private TypeMappingBuildContext(
public TypeMappingBuildContext AddIndentation() =>
new(Source, ReferenceHandler, NameBuilder, SyntaxFactory.AddIndentation(), AdditionalParameters, OriginalTargetValueExpression);

public TypeMappingBuildContext WithTargetValue(ExpressionSyntax targetValue) =>
public TypeMappingBuildContext WithTargetValue(ExpressionSyntax? targetValue) =>
new(Source, ReferenceHandler, NameBuilder, SyntaxFactory, AdditionalParameters, targetValue);

/// <summary>
Expand Down
18 changes: 18 additions & 0 deletions src/Riok.Mapperly/Diagnostics/DiagnosticDescriptors.cs
Original file line number Diff line number Diff line change
Expand Up @@ -857,6 +857,24 @@ public static class DiagnosticDescriptors
isEnabledByDefault: true
);

public static readonly DiagnosticDescriptor MappingTargetOriginalValueTypeMismatch = new(
"RMG101",
"The target member type does not match the [MappingTargetOriginalValue] parameter type",
"The target member {0} cannot be passed to the [MappingTargetOriginalValue] parameter {1} of type {2} in {3}, the default value is used instead",
DiagnosticCategories.Mapper,
DiagnosticSeverity.Warning,
isEnabledByDefault: true
);

public static readonly DiagnosticDescriptor MappingTargetOriginalValueMemberNotReadable = new(
"RMG102",
"The target member cannot be read for the [MappingTargetOriginalValue] parameter",
"The target member {0} cannot be read and cannot be passed to the [MappingTargetOriginalValue] parameter {1} in {2}, the default value is used instead",
DiagnosticCategories.Mapper,
DiagnosticSeverity.Warning,
isEnabledByDefault: true
);

private static string BuildHelpUri(string id)
{
#if ENV_NEXT
Expand Down
Loading
Loading