Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
67 commits
Select commit Hold shift + click to select a range
667a3d5
use Enum.Parse<TEnum>
lbargaoanu Jul 30, 2022
77086e8
less allocations
lbargaoanu Jul 31, 2022
e3aecd3
reuse the execution plan between user Map calls and internal Map calls
lbargaoanu Aug 1, 2022
6581906
remove IObjectMapperInfo
lbargaoanu Aug 2, 2022
5f0cebd
use the more efficient Expression.Invoke instead of ConvertReplacePar…
lbargaoanu Aug 3, 2022
9fc7cdf
less allocations
lbargaoanu Aug 3, 2022
7fdf915
less null checks
lbargaoanu Aug 4, 2022
4b507ee
unreachable, As maps are sealed by default
lbargaoanu Aug 6, 2022
84e3fff
less allocations
lbargaoanu Aug 6, 2022
b5cc0a6
don't try to match ignored members
lbargaoanu Aug 7, 2022
df48e72
more efficient
lbargaoanu Aug 7, 2022
12eaef9
drop RegEx
lbargaoanu Aug 8, 2022
06b0713
docs
lbargaoanu Aug 8, 2022
dc7e58f
cosmetic
lbargaoanu Aug 8, 2022
9356388
less allocations
lbargaoanu Aug 8, 2022
39fccd9
cosmetic
lbargaoanu Aug 9, 2022
a3ae964
less allocations
lbargaoanu Aug 9, 2022
00d29ee
we don't need to create As type maps
lbargaoanu Aug 11, 2022
c9bceef
remove ITypeMapConfiguration
lbargaoanu Aug 11, 2022
a0988d7
cosmetic
lbargaoanu Aug 11, 2022
0b9cf8c
try to show a better error message when mapping records through const…
lbargaoanu Aug 11, 2022
b9699dd
less allocations
lbargaoanu Aug 13, 2022
ed9097f
special case the defaults for naming conventions
lbargaoanu Aug 13, 2022
93576ef
make TypeMapPlanBuilder a struct
lbargaoanu Aug 15, 2022
3adb02f
use readonly record struct
lbargaoanu Aug 15, 2022
7720ac8
assume that a protected constructor with CompilerGeneratedAttribute m…
lbargaoanu Aug 15, 2022
4e1117f
less allocations
lbargaoanu Aug 15, 2022
dac3062
rename configurationProvider to the shorter configuration in most places
lbargaoanu Aug 17, 2022
b24560f
less allocations
lbargaoanu Aug 17, 2022
953d66d
converters with no source should throw
lbargaoanu Aug 17, 2022
ebd2c43
less allocations
lbargaoanu Aug 18, 2022
c5d7c36
cosmetic
lbargaoanu Aug 18, 2022
12676dd
less allocations
lbargaoanu Aug 19, 2022
85ff705
make MapFrom name more like the built-in mapping
lbargaoanu Aug 19, 2022
c71f168
less allocations
lbargaoanu Aug 20, 2022
3de255f
cosmetic
lbargaoanu Aug 21, 2022
6925737
use profiles in the benchmark
lbargaoanu Aug 21, 2022
08ec72a
simplify conventions
lbargaoanu Aug 21, 2022
e9287a2
merge the profile member configuration with the global one
lbargaoanu Aug 21, 2022
0d2aa50
cosmetic
lbargaoanu Aug 22, 2022
ec0a832
test reusing the execution plan
lbargaoanu Aug 22, 2022
593ad53
refactor test base classes
lbargaoanu Aug 22, 2022
806e73f
cosmetic
lbargaoanu Aug 23, 2022
d0e0e24
avoid changing the resolver configuration objects because they're reu…
lbargaoanu Aug 31, 2022
77e0015
cosmetic
lbargaoanu Aug 31, 2022
20c283a
less allocations
lbargaoanu Sep 3, 2022
66f0020
cosmetic
lbargaoanu Sep 3, 2022
f1655e1
file scoped namespaces
lbargaoanu Sep 3, 2022
288c4ad
global usings
lbargaoanu Sep 3, 2022
e6f2ca3
cosmetic
lbargaoanu Sep 4, 2022
daacd80
less allocations
lbargaoanu Sep 10, 2022
c608787
NullMappingOrderComesFirst
lbargaoanu Sep 10, 2022
434703c
less allocations
lbargaoanu Sep 10, 2022
4ba0e5f
we could include a different constructor
lbargaoanu Sep 10, 2022
b98273e
less allocations
lbargaoanu Sep 10, 2022
7eeaf59
cosmetic
lbargaoanu Sep 11, 2022
efd1df9
allocate _runtimeTypeDetails lazily
lbargaoanu Sep 12, 2022
3a491a3
create the projection builder lazily
lbargaoanu Sep 12, 2022
7da36f6
cosmetic
lbargaoanu Sep 12, 2022
970ab2d
an adhoc fix for including open generic config
lbargaoanu Sep 14, 2022
e7ba023
cosmetic
lbargaoanu Sep 18, 2022
2b99e96
MapFrom should override ignore
lbargaoanu Sep 18, 2022
3f8448a
UseDestinationValueNullable
lbargaoanu Sep 19, 2022
8b83aa7
cosmetic
lbargaoanu Sep 21, 2022
5e0066e
avoid LINQ
lbargaoanu Sep 23, 2022
7d65b78
the destination type name is already in the error message
lbargaoanu Sep 24, 2022
3c2d8cd
cosmetic
lbargaoanu Sep 24, 2022
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
Prev Previous commit
Next Next commit
less null checks
  • Loading branch information
lbargaoanu committed Aug 5, 2022
commit 7fdf9150c5ad8fb40c1152c25b0ba39a755ee86c
27 changes: 16 additions & 11 deletions src/AutoMapper/Configuration/MapperConfiguration.cs
Original file line number Diff line number Diff line change
Expand Up @@ -207,33 +207,38 @@ static LambdaExpression GenerateTypeMapExpression(TypePair requestedTypes, TypeM
}
static Expression CheckNullValueType(Expression expression, Type runtimeType) =>
!expression.Type.IsValueType && runtimeType.IsValueType ? Coalesce(expression, Default(runtimeType)) : expression;
LambdaExpression GenerateObjectMapperExpression(in MapRequest mapRequest, IObjectMapper mapperToUse)
LambdaExpression GenerateObjectMapperExpression(in MapRequest mapRequest, IObjectMapper mapper)
{
var source = Parameter(mapRequest.RequestedTypes.SourceType, "source");
var destination = Parameter(mapRequest.RequestedTypes.DestinationType, "mapperDestination");
var destinationType = mapRequest.RequestedTypes.DestinationType;
var destination = Parameter(destinationType, "mapperDestination");
var runtimeDestinationType = mapRequest.RuntimeTypes.DestinationType;
Expression fullExpression;
if (mapperToUse == null)
bool nullCheck;
if (mapper == null)
{
var exception = new AutoMapperMappingException("Missing type map configuration or unsupported mapping.", null, mapRequest.RuntimeTypes)
{
MemberMap = mapRequest.MemberMap
};
nullCheck = true;
fullExpression = Throw(Constant(exception), runtimeDestinationType);
}
else
{
var checkNullValueTypeDest = CheckNullValueType(destination, runtimeDestinationType);
var map = mapperToUse.MapExpression(this, Configuration, mapRequest.MemberMap,
ToType(source, mapRequest.RuntimeTypes.SourceType),
ToType(checkNullValueTypeDest, runtimeDestinationType));
var mapperSource = ToType(source, mapRequest.RuntimeTypes.SourceType);
var map = mapper.MapExpression(this, Configuration, mapRequest.MemberMap, mapperSource, ToType(checkNullValueTypeDest, runtimeDestinationType));
nullCheck = map != mapperSource;
var newException = Call(MappingError, ExceptionParameter, Constant(mapRequest));
var throwExpression = Throw(newException, runtimeDestinationType);
fullExpression = TryCatch(ToType(map, runtimeDestinationType), Catch(ExceptionParameter, throwExpression));
fullExpression = TryCatch(ToType(map, destinationType), Catch(ExceptionParameter, Throw(newException, destinationType)));
}
var profileMap = mapRequest.MemberMap.Profile ?? Configuration;
var nullCheckSource = NullCheckSource(profileMap, source, destination, fullExpression, mapRequest.MemberMap);
return Lambda(nullCheckSource, source, destination, ContextParameter);
if (nullCheck)
{
var profileMap = mapRequest.MemberMap.Profile ?? Configuration;
fullExpression = NullCheckSource(profileMap, source, destination, fullExpression, mapRequest.MemberMap);
}
return Lambda(fullExpression, source, destination, ContextParameter);
}
}
static MapperConfigurationExpression Build(Action<IMapperConfigurationExpression> configure)
Expand Down
75 changes: 47 additions & 28 deletions src/AutoMapper/Execution/ExpressionBuilder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -43,15 +43,16 @@ public static class ExpressionBuilder
private static readonly UnaryExpression IncrementIndex = PostIncrementAssign(Index);

public static Expression MapExpression(this IGlobalConfiguration configurationProvider, ProfileMap profileMap, TypePair typePair, Expression source,
MemberMap propertyMap = null, Expression destination = null)
MemberMap memberMap = null, Expression destination = null)
{
destination ??= Default(typePair.DestinationType);
var typeMap = configurationProvider.ResolveTypeMap(typePair);
Expression mapExpression = null;
bool hasTypeConverter;
bool nullCheck;
if (typeMap != null)
{
hasTypeConverter = typeMap.HasTypeConverter;
var allowNull = memberMap?.AllowNull;
nullCheck = !typeMap.HasTypeConverter && allowNull.HasValue && allowNull != profileMap.AllowNullDestinationValues;
if (!typeMap.HasDerivedTypesToInclude)
{
configurationProvider.Seal(typeMap);
Expand All @@ -63,37 +64,41 @@ public static Expression MapExpression(this IGlobalConfiguration configurationPr
}
else
{
hasTypeConverter = false;
var mapper = configurationProvider.FindMapper(typePair);
mapExpression = mapper?.MapExpression(configurationProvider, profileMap, propertyMap, source, destination);
}
mapExpression ??= ContextMap(typePair, source, destination, propertyMap);
if (!hasTypeConverter)
{
mapExpression = NullCheckSource(profileMap, source, destination, mapExpression, propertyMap);
if (mapper != null)
{
mapExpression = mapper.MapExpression(configurationProvider, profileMap, memberMap, source, destination);
nullCheck = mapExpression != source;
mapExpression = ToType(mapExpression, typePair.DestinationType);
}
else
{
nullCheck = true;
}
}
return ToType(mapExpression, typePair.DestinationType);
mapExpression ??= ContextMap(typePair, source, destination, memberMap);
return nullCheck ? NullCheckSource(profileMap, source, destination, mapExpression, memberMap) : mapExpression;
}
public static Expression NullCheckSource(ProfileMap profileMap, Expression sourceParameter, Expression destinationParameter, Expression mapExpression, MemberMap memberMap)
public static Expression NullCheckSource(ProfileMap profileMap, Expression source, Expression destination, Expression mapExpression, MemberMap memberMap)
{
var sourceType = sourceParameter.Type;
var sourceType = source.Type;
if (sourceType.IsValueType && !sourceType.IsNullableType())
{
return mapExpression;
}
var destinationType = destinationParameter.Type;
var destinationType = destination.Type;
var isCollection = destinationType.IsCollection();
var mustUseDestination = memberMap is { MustUseDestination: true };
var ifSourceNull = mustUseDestination ? ClearDestinationCollection() : DefaultDestination();
return sourceParameter.IfNullElse(ifSourceNull, mapExpression);
return source.IfNullElse(ifSourceNull, mapExpression);
Expression ClearDestinationCollection()
{
if (!isCollection)
{
return destinationParameter;
return destination;
}
MethodInfo clearMethod;
var destinationVariable = Variable(destinationParameter.Type, "collectionDestination");
var destinationVariable = Variable(destination.Type, "collectionDestination");
Expression collection = destinationVariable;
if (destinationType.IsListType())
{
Expand All @@ -106,7 +111,7 @@ Expression ClearDestinationCollection()
{
if (!mustUseDestination)
{
return destinationParameter;
return destination;
}
var destinationElementType = GetEnumerableElementType(destinationType);
destinationCollectionType = typeof(ICollection<>).MakeGenericType(destinationElementType);
Expand All @@ -115,22 +120,22 @@ Expression ClearDestinationCollection()
clearMethod = destinationCollectionType.GetMethod("Clear");
}
return Block(new[] { destinationVariable },
Assign(destinationVariable, destinationParameter),
Assign(destinationVariable, destination),
Condition(ReferenceEqual(collection, Null), Empty, Expression.Call(collection, clearMethod)),
destinationVariable);
}
Expression DefaultDestination()
{
if ((isCollection && profileMap.AllowsNullCollectionsFor(memberMap)) || (!isCollection && profileMap.AllowsNullDestinationValuesFor(memberMap)))
{
return destinationParameter.NodeType == ExpressionType.Default ? destinationParameter : Default(destinationType);
return destination.NodeType == ExpressionType.Default ? destination : Default(destinationType);
}
if (destinationType.IsArray)
{
var destinationElementType = destinationType.GetElementType();
var rank = destinationType.GetArrayRank();
return rank == 1 ?
Expression.Call(ArrayEmptyMethod.MakeGenericMethod(destinationElementType)) :
return rank == 1 ?
Expression.Call(ArrayEmptyMethod.MakeGenericMethod(destinationElementType)) :
NewArrayBounds(destinationElementType, Enumerable.Repeat(Zero, rank));
}
return ObjectFactory.GenerateConstructorExpression(destinationType);
Expand Down Expand Up @@ -164,7 +169,7 @@ public static Expression ApplyTransformers(this MemberMap memberMap, Expression
}
var transformers = perMember.Concat(perMap).Concat(perProfile);
return Apply(transformers, memberMap, source);
static Expression Apply(IEnumerable<ValueTransformerConfiguration> transformers, MemberMap memberMap, Expression source) =>
static Expression Apply(IEnumerable<ValueTransformerConfiguration> transformers, MemberMap memberMap, Expression source) =>
transformers.Where(vt => vt.IsMatch(memberMap)).Aggregate(source,
(current, vtConfig) => ToType(vtConfig.TransformerExpression.ReplaceParameters(ToType(current, vtConfig.ValueType)), memberMap.DestinationType));
}
Expand Down Expand Up @@ -325,22 +330,36 @@ private static Expression Replace(this ParameterReplaceVisitor visitor, LambdaEx
return newLambda;
}
public static Expression Replace(this Expression exp, Expression old, Expression replace) => new ReplaceVisitor(old, replace).Visit(exp);
public static Expression NullCheck(this Expression expression, Type destinationType = null, Expression defaultValue = null)
public static Expression NullCheck(this Expression expression, MemberMap memberMap = null, Expression defaultValue = null)
{
var chain = expression.GetChain();
if (chain.Count == 0 || chain.Peek().Target is not ParameterExpression parameter)
var min = memberMap?.IncludedMember != null ? 1 : 2;
if (chain.Count < min || chain.Peek().Target is not ParameterExpression parameter)
{
return expression;
}
var destinationType = memberMap?.DestinationType;
var returnType = (destinationType != null && destinationType != expression.Type && Nullable.GetUnderlyingType(destinationType) == expression.Type) ?
destinationType : expression.Type;
var defaultReturn = (defaultValue is { NodeType: ExpressionType.Default } && defaultValue.Type == returnType) ? defaultValue : Default(returnType);
ParameterExpression[] variables = null;
var name = parameter.Name;
Expression begin;
string name;
if (min == 1)
{
begin = parameter;
name = parameter.Name;
}
else
{
var second = chain.Pop();
begin = second.Expression;
name = parameter.Name + second.MemberInfo.Name;
}
int index = 0;
var nullCheckedExpression = NullCheck(parameter);
var nullCheckedExpression = NullCheck(begin);
return variables == null ? nullCheckedExpression : Block(variables, nullCheckedExpression);
Expression NullCheck(ParameterExpression variable)
Expression NullCheck(Expression variable)
{
var member = chain.Pop();
if (chain.Count == 0)
Expand Down
9 changes: 3 additions & 6 deletions src/AutoMapper/Execution/TypeMapPlanBuilder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -235,10 +235,7 @@ private Expression CreateMapperFunc(Expression assignmentFunc)
{
mapperFunc = Condition(overMaxDepth, Default(DestinationType), mapperFunc);
}
if (_typeMap.Profile.AllowNullDestinationValues)
{
mapperFunc = Source.IfNullElse(Default(DestinationType), mapperFunc);
}
mapperFunc = NullCheckSource(_typeMap.Profile, Source, _initialDestination, mapperFunc, null);
return CheckReferencesCache(mapperFunc);
}
private Expression CheckReferencesCache(Expression valueBuilder)
Expand Down Expand Up @@ -421,7 +418,7 @@ public ExpressionResolver(LambdaExpression lambda) : base(lambda) { }
public Expression GetExpression(MemberMap memberMap, Expression source, Expression _, Expression destinationMember)
{
var mapFrom = Lambda.ReplaceParameters(source);
var nullCheckedExpression = mapFrom.NullCheck(memberMap.DestinationType, destinationMember);
var nullCheckedExpression = mapFrom.NullCheck(memberMap, destinationMember);
if (nullCheckedExpression != mapFrom)
{
return nullCheckedExpression;
Expand Down Expand Up @@ -461,7 +458,7 @@ public Expression GetExpression(MemberMap memberMap, Expression source, Expressi
var sourceMember = SourceMemberLambda?.ReplaceParameters(source) ??
(SourceMemberName != null ?
PropertyOrField(source, SourceMemberName) :
memberMap.ChainSourceMembers(source, iResolverTypeArgs[1], destinationMember) ?? Throw(Constant(BuildExceptionMessage()), iResolverTypeArgs[0]));
memberMap.ChainSourceMembers(source, destinationMember) ?? Throw(Constant(BuildExceptionMessage()), iResolverTypeArgs[0]));
return Call(ToType(_instance, InterfaceType), "Convert", ToType(sourceMember, iResolverTypeArgs[0]), ContextParameter);
AutoMapperConfigurationException BuildExceptionMessage()
=> new($"Cannot find a source member to pass to the value converter of type {ConcreteType}. Configure a source member to map from.");
Expand Down
25 changes: 8 additions & 17 deletions src/AutoMapper/Mappers/CollectionMapper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -74,13 +74,13 @@ Expression MapCollectionCore(Expression destExpression)
addItems = Condition(overMaxDepth, ExpressionBuilder.Empty, addItems);
}
var clearMethod = isIList ? IListClear : destinationCollectionType.GetMethod("Clear");
var checkNull = Block(new[] { newExpression, passedDestination },
Assign(passedDestination, destExpression),
assignNewExpression,
Call(destination, clearMethod),
addItems,
destination);
return CheckContext();
return Block(new[] { newExpression, passedDestination },
CheckContext() ?? ExpressionBuilder.Empty,
Assign(passedDestination, destExpression),
assignNewExpression,
Call(destination, clearMethod),
addItems,
destination);
void GetDestinationType()
{
var immutableCollection = !mustUseDestination && destinationType.IsValueType;
Expand Down Expand Up @@ -132,16 +132,7 @@ void UseDestinationValue()
Expression CheckContext()
{
var elementTypeMap = configurationProvider.ResolveTypeMap(sourceElementType, destinationElementType);
if (elementTypeMap == null)
{
return checkNull;
}
var checkContext = ExpressionBuilder.CheckContext(elementTypeMap);
if (checkContext == null)
{
return checkNull;
}
return Block(checkContext, checkNull);
return elementTypeMap == null ? null : ExpressionBuilder.CheckContext(elementTypeMap);
}
}
}
Expand Down
6 changes: 3 additions & 3 deletions src/AutoMapper/MemberMap.cs
Original file line number Diff line number Diff line change
Expand Up @@ -59,8 +59,8 @@ public void MapFrom(string sourceMembersPath)
}
public override string ToString() => DestinationName;
public Expression ChainSourceMembers(Expression source) => SourceMembers.Chain(source);
public Expression ChainSourceMembers(Expression source, Type destinationType, Expression defaultValue) =>
ChainSourceMembers(source)?.NullCheck(destinationType, defaultValue);
public Expression ChainSourceMembers(Expression source, Expression defaultValue) =>
ChainSourceMembers(source)?.NullCheck(this, defaultValue);
public bool AllowsNullDestinationValues => Profile?.AllowsNullDestinationValuesFor(this) ?? true;
public bool AllowsNullCollections => (Profile?.AllowsNullCollectionsFor(this)).GetValueOrDefault();
public ProfileMap Profile => TypeMap?.Profile;
Expand All @@ -76,7 +76,7 @@ public void MapByConvention(MemberInfo[] sourceMembers)
Resolver = this;
}
Expression IValueResolver.GetExpression(MemberMap memberMap, Expression source, Expression destination, Expression destinationMember) =>
ChainSourceMembers(source, memberMap.DestinationType, destinationMember);
ChainSourceMembers(source, destinationMember);
MemberInfo IValueResolver.GetSourceMember(MemberMap memberMap) => SourceMembers[0];
Type IValueResolver.ResolvedType => SourceMembers[^1].GetMemberType();
}
Expand Down