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
15 changes: 15 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,21 @@ Before v1.0, a minor version may introduce breaking changes.

## [Unreleased]

### Added

- **The four members a migration from AutoMapper actually writes.** `ForMember` taking the
destination member as text, `MapFrom` taking the source member as text, `ForAllMembers`, and
`ForSourceMember` with the one thing there is to say about a source member — `DoNotValidate()`,
which excuses it from validation against the source list. All four were run side by side against
AutoMapper and answer the same.
- A dotted name walks a path, the shape the expression overloads already accepted, and the name is
resolved while the configuration is built: a misspelling is a configuration error rather than a
member that quietly maps to nothing. The expression overloads are still the ones to prefer,
since they keep the compiler involved.
- The rest of the surface comparison was left alone on purpose. Copying AutoMapper's overload list
wholesale would break source compatibility here: its extra `PreCondition` overloads make
`o.PreCondition(s => false)` ambiguous, and that call compiles today.

### Fixed

- **`ForPath` now owns the member its path starts at.** It only owned the one the path ends at,
Expand Down
13 changes: 13 additions & 0 deletions src/Mapperion.Analyzers/ConfigurationAnalyzer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -321,8 +321,21 @@ private static bool IsScope(
/// The destination member a lambda points at, as it is written, so that
/// <c>d =&gt; d.Customer.Name</c> becomes <c>Customer.Name</c>.
/// </summary>
/// <remarks>
/// A member is selected either by an expression or, since the overloads that take one as
/// text exist, by a literal string. A name built at run time cannot be read here, and a
/// member this returns null for is simply not tracked — the diagnostics below say that two
/// calls disagree, so saying nothing is the right answer when one of them is unknowable.
/// </remarks>
private static string? Path(ExpressionSyntax expression)
{
if (expression is LiteralExpressionSyntax literal &&
literal.IsKind(SyntaxKind.StringLiteralExpression))
{
string text = literal.Token.ValueText;
return text.Length == 0 ? null : text;
}

if (expression is not LambdaExpressionSyntax lambda || lambda.Body is not ExpressionSyntax body)
{
return null;
Expand Down
49 changes: 49 additions & 0 deletions src/Mapperion/Configuration/IMappingExpression.cs
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,55 @@ IMappingExpression<TSource, TDestination> ForPath<TMember>(
Expression<Func<TDestination, TMember>> destinationPath,
Action<IMemberConfigurationExpression<TSource, TDestination, TMember>> pathOptions);

/// <summary>
/// Configures one destination member, named as text rather than selected by an expression.
/// </summary>
/// <remarks>
/// For a member chosen somewhere a lambda cannot reach — a settings file, a table of
/// overrides, a loop. It costs the compiler's checking, so the expression overload is the
/// one to reach for when there is a choice. A dotted name walks a path, exactly as
/// <see cref="ForPath"/> does.
/// </remarks>
/// <param name="destinationMember">The member name, or a dotted path to one.</param>
/// <param name="memberOptions">The configuration applied to that member.</param>
/// <returns>This expression, for chaining.</returns>
/// <exception cref="ArgumentNullException">Either argument is <see langword="null"/>.</exception>
/// <exception cref="MapperConfigurationException">
/// The destination has no member of that name.
/// </exception>
IMappingExpression<TSource, TDestination> ForMember(
string destinationMember,
Action<IMemberConfigurationExpression<TSource, TDestination, object>> memberOptions);

/// <summary>
/// Applies the same configuration to every destination member.
/// </summary>
/// <remarks>
/// Every writable member of the destination, including the ones no call has mentioned.
/// It runs before the conventions fill anything in, so a member it ignores stays ignored
/// and a member it gives a source to keeps that source.
/// </remarks>
/// <param name="memberOptions">The configuration applied to each member.</param>
/// <returns>This expression, for chaining.</returns>
/// <exception cref="ArgumentNullException"><paramref name="memberOptions"/> is <see langword="null"/>.</exception>
IMappingExpression<TSource, TDestination> ForAllMembers(
Action<IMemberConfigurationExpression<TSource, TDestination, object>> memberOptions);

/// <summary>
/// Configures one member of the source.
/// </summary>
/// <remarks>
/// There is one thing to say about a source member, and it only means anything under
/// <see cref="Model.MemberListValidation.Source"/>: that it is allowed to go unread.
/// </remarks>
/// <param name="sourceMember">A member access on the source.</param>
/// <param name="memberOptions">The configuration applied to that member.</param>
/// <returns>This expression, for chaining.</returns>
/// <exception cref="ArgumentNullException">Either argument is <see langword="null"/>.</exception>
IMappingExpression<TSource, TDestination> ForSourceMember(
Expression<Func<TSource, object?>> sourceMember,
Action<ISourceMemberConfigurationExpression> memberOptions);

/// <summary>
/// Configures one parameter of the destination constructor. Parameter names are matched
/// ignoring case, because C# names parameters in camelCase and properties in PascalCase.
Expand Down
15 changes: 15 additions & 0 deletions src/Mapperion/Configuration/IMemberConfigurationExpression.cs
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,21 @@ public interface IMemberConfigurationExpression<TSource, TDestination, TMember>
/// <param name="sourceMember">The expression that reads the value.</param>
void MapFrom<TSourceMember>(Expression<Func<TSource, TSourceMember>> sourceMember);

/// <summary>
/// Takes the value from the source member of the given name, or from the dotted path to
/// one.
/// </summary>
/// <remarks>
/// The name is resolved while the configuration is built, so a misspelling is a
/// configuration error and not a member that quietly maps to nothing.
/// </remarks>
/// <param name="sourceMember">The source member name, or a dotted path to one.</param>
/// <exception cref="ArgumentNullException"><paramref name="sourceMember"/> is <see langword="null"/>.</exception>
/// <exception cref="MapperConfigurationException">
/// The source has no member of that name.
/// </exception>
void MapFrom(string sourceMember);

/// <summary>
/// Takes the value from a resolver, which sees the whole source and destination.
/// </summary>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
namespace Mapperion
{
/// <summary>
/// What can be said about a member of the source.
/// </summary>
/// <remarks>
/// There is one thing, and it only means anything under
/// <see cref="Model.MemberListValidation.Source"/>: validation against the source list reports
/// every readable member that no destination member reads, and this excuses one of them.
/// </remarks>
public interface ISourceMemberConfigurationExpression
{
/// <summary>
/// Leaves this source member out of validation, so it may go unread without being
/// reported.
/// </summary>
void DoNotValidate();
}
}
10 changes: 10 additions & 0 deletions src/Mapperion/Configuration/MemberConfiguration.cs
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,16 @@ public void MapFrom<TValueResolver>()
isIgnored = false;
}

public void MapFrom(string sourceMember)
{
Guard.NotNull(sourceMember, nameof(sourceMember));

source = new MemberPathSource(
MemberNameResolver.Path(typeof(TSource), sourceMember, "source"));

isIgnored = false;
}

public void ConvertUsing<TValueConverter, TSourceMember>()
where TValueConverter : IValueConverter<TSourceMember, TMember>
{
Expand Down
83 changes: 83 additions & 0 deletions src/Mapperion/Configuration/MemberNameResolver.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Reflection;
using Mapperion.Internal;
using Mapperion.Model;

namespace Mapperion.Configuration
{
/// <summary>
/// Finds a member from its name, for the overloads that take one as text.
/// </summary>
/// <remarks>
/// <para>
/// A name is what you have when the member is chosen somewhere a lambda cannot reach — a
/// configuration file, a table of overrides, a loop over names. It costs the compiler's
/// checking, which is why the expression overloads exist and are the ones to prefer.
/// </para>
/// <para>
/// A dotted name is a path, the same shape the expression overloads accept: <c>Customer.Name</c>
/// walks two steps. The name is resolved here, while the configuration is being built, so a
/// misspelling is a configuration error rather than a member that silently maps to nothing.
/// </para>
/// </remarks>
internal static class MemberNameResolver
{
private const BindingFlags Lookup =
BindingFlags.Public | BindingFlags.Instance | BindingFlags.FlattenHierarchy;

internal static MemberPath Path(Type type, string name, string role)
{
Guard.NotNull(type, nameof(type));

if (string.IsNullOrWhiteSpace(name))
{
throw new MapperConfigurationException("A " + role + " member name cannot be empty.");
}

string[] steps = name!.Split('.');
var descriptors = new List<MemberDescriptor>(steps.Length);
Type current = type;

foreach (string step in steps)
{
MemberDescriptor descriptor = Step(current, step.Trim(), name!, role);
descriptors.Add(descriptor);
current = descriptor.MemberType;
}

return new MemberPath(descriptors);
}

[UnconditionalSuppressMessage("Trimming", "IL2070", Justification =
"Members are looked up by name here, which the trimmer cannot follow. The fluent configuration is only reachable through MapperConfiguration, which already says so.")]
private static MemberDescriptor Step(Type type, string step, string whole, string role)
{
PropertyInfo? property = type.GetProperty(step, Lookup);

if (property is not null)
{
return MemberDescriptor.ForProperty(property);
}

FieldInfo? field = type.GetField(step, Lookup);

if (field is not null)
{
return MemberDescriptor.ForField(field);
}

MethodInfo? method = type.GetMethod(step, Lookup, null, Type.EmptyTypes, null);

if (method is not null && method.ReturnType != typeof(void))
{
return MemberDescriptor.ForMethod(method);
}

throw new MapperConfigurationException(
"'" + type.Name + "' has no " + role + " member called '" + step + "'" +
(whole == step ? "." : ", named as part of '" + whole + "'."));
}
}
}
12 changes: 12 additions & 0 deletions src/Mapperion/Configuration/SourceMemberConfiguration.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
namespace Mapperion.Configuration
{
/// <summary>
/// What <c>ForSourceMember</c> collects. One flag, because there is one thing to say.
/// </summary>
internal sealed class SourceMemberConfiguration : ISourceMemberConfigurationExpression
{
internal bool IsExcludedFromValidation { get; private set; }

public void DoNotValidate() => IsExcludedFromValidation = true;
}
}
91 changes: 91 additions & 0 deletions src/Mapperion/Configuration/TypeMapConfiguration.cs
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ internal sealed class TypeMapConfiguration<TSource, TDestination>
private readonly List<TypeMapKey> derivedMaps = new List<TypeMapKey>();
private readonly List<TypeMapKey> baseMaps = new List<TypeMapKey>();
private readonly List<MemberPath> includedMembers = new List<MemberPath>();
private readonly List<MemberDescriptor> unvalidatedSourceMembers = new List<MemberDescriptor>();
private readonly List<object> beforeMapActions = new List<object>();
private readonly List<object> afterMapActions = new List<object>();
private int? maxDepth;
Expand Down Expand Up @@ -87,6 +88,64 @@ public IMappingExpression<TSource, TDestination> ForPath<TMember>(
return this;
}

public IMappingExpression<TSource, TDestination> ForMember(
string destinationMember,
Action<IMemberConfigurationExpression<TSource, TDestination, object>> memberOptions)
{
Guard.NotNull(destinationMember, nameof(destinationMember));
Guard.NotNull(memberOptions, nameof(memberOptions));

MemberPath path = MemberNameResolver.Path(
typeof(TDestination), destinationMember, "destination");

// A single step is a member and not a path, which is the same rule ForPath follows.
MemberConfiguration<TSource, TDestination, object> configuration = path.IsFlattened
? FindOrAddPath<object>(path)
: FindOrAdd<object>(path.Leaf);

memberOptions(configuration);
return this;
}

/// <remarks>
/// Every writable member of the destination, whether or not a call has already mentioned
/// it, and the ones already mentioned keep what they were given first — the action is
/// applied on top. It runs here rather than at build time so that the conventions see the
/// result and leave those members alone.
/// </remarks>
public IMappingExpression<TSource, TDestination> ForAllMembers(
Action<IMemberConfigurationExpression<TSource, TDestination, object>> memberOptions)
{
Guard.NotNull(memberOptions, nameof(memberOptions));

foreach (MemberDescriptor destination in DestinationMembers())
{
memberOptions(FindOrAdd<object>(destination));
}

return this;
}

public IMappingExpression<TSource, TDestination> ForSourceMember(
Expression<Func<TSource, object?>> sourceMember,
Action<ISourceMemberConfigurationExpression> memberOptions)
{
Guard.NotNull(sourceMember, nameof(sourceMember));
Guard.NotNull(memberOptions, nameof(memberOptions));

MemberPath path = MemberExpressionParser.ParseIncludedMember(sourceMember);
var configuration = new SourceMemberConfiguration();

memberOptions(configuration);

if (configuration.IsExcludedFromValidation)
{
unvalidatedSourceMembers.Add(path.Steps[0]);
}

return this;
}

public IMappingExpression<TSource, TDestination> IncludeMembers(
params Expression<Func<TSource, object?>>[] members)
{
Expand Down Expand Up @@ -285,9 +344,41 @@ public TypeMapDefinition Build(MapperOptions options)
AfterMapActions = afterMapActions.ToArray(),
MaxDepth = maxDepth,
PreserveReferences = preserveReferences,
UnvalidatedSourceMembers = unvalidatedSourceMembers.ToArray(),
};
}

/// <remarks>
/// Every writable member of the destination, found the plain way. ForAllMembers is the
/// only caller and it runs while the configuration is being written, before the options
/// that drive the real member walk are known.
/// </remarks>
[UnconditionalSuppressMessage("Trimming", "IL2090", Justification =
"Members are looked up by name here, which the trimmer cannot follow. The fluent configuration is only reachable through MapperConfiguration, which already says so.")]
private static IEnumerable<MemberDescriptor> DestinationMembers()
{
const System.Reflection.BindingFlags lookup =
System.Reflection.BindingFlags.Public |
System.Reflection.BindingFlags.Instance |
System.Reflection.BindingFlags.FlattenHierarchy;

foreach (System.Reflection.PropertyInfo property in typeof(TDestination).GetProperties(lookup))
{
if (property.CanWrite && property.GetIndexParameters().Length == 0)
{
yield return MemberDescriptor.ForProperty(property);
}
}

foreach (System.Reflection.FieldInfo field in typeof(TDestination).GetFields(lookup))
{
if (!field.IsInitOnly)
{
yield return MemberDescriptor.ForField(field);
}
}
}

private CtorParamConfiguration<TSource> FindOrAddParameter(string name)
{
for (int i = 0; i < constructorParameters.Count; i++)
Expand Down
8 changes: 8 additions & 0 deletions src/Mapperion/Model/TypeMapDefinition.cs
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,13 @@ public TypeMapDefinition(TypeMapKey key)
/// <summary>Gets which side must be fully covered for this map to validate.</summary>
public MemberListValidation MemberListValidation { get; init; } = MemberListValidation.Destination;

/// <summary>
/// Source members that <c>ForSourceMember(..., o =&gt; o.DoNotValidate())</c> excused from
/// validation against the source list.
/// </summary>
public IReadOnlyList<MemberDescriptor> UnvalidatedSourceMembers { get; init; } =
System.Array.Empty<MemberDescriptor>();

/// <summary>Gets the maps for derived type pairs handled polymorphically by this one.</summary>
public IReadOnlyList<TypeMapKey> DerivedMaps { get; init; } = NoKeys;

Expand Down Expand Up @@ -126,6 +133,7 @@ internal TypeMapDefinition WithResolved(
MaxDepth = MaxDepth,
PreserveReferences = PreserveReferences,
MemberListValidation = MemberListValidation,
UnvalidatedSourceMembers = UnvalidatedSourceMembers,
DerivedMaps = DerivedMaps,
BaseMaps = BaseMaps,
IncludedMembers = IncludedMembers,
Expand Down
Loading
Loading