-
-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
TypeMapPlanBuilder.cs
520 lines (457 loc) · 23.4 KB
/
TypeMapPlanBuilder.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
namespace AutoMapper.Execution
{
using Configuration;
using Mappers;
using static Expression;
using static ExpressionExtensions;
public class TypeMapPlanBuilder
{
private static readonly Expression<Func<IRuntimeMapper, ResolutionContext>> CreateContext = mapper => new ResolutionContext(mapper.DefaultContext.Options, mapper);
private static readonly Expression<Func<AutoMapperMappingException>> CtorExpression = () => new AutoMapperMappingException(null, null, default(TypePair), null, null);
private static readonly Expression<Action<ResolutionContext>> IncTypeDepthInfo = ctxt => ctxt.IncrementTypeDepth(default(TypePair));
private static readonly Expression<Action<ResolutionContext>> DecTypeDepthInfo = ctxt => ctxt.DecrementTypeDepth(default(TypePair));
private static readonly Expression<Func<ResolutionContext, int>> GetTypeDepthInfo = ctxt => ctxt.GetTypeDepth(default(TypePair));
private readonly IConfigurationProvider _configurationProvider;
private readonly TypeMap _typeMap;
private readonly TypeMapRegistry _typeMapRegistry;
private readonly ParameterExpression _source;
private readonly ParameterExpression _initialDestination;
private readonly ParameterExpression _context;
private readonly ParameterExpression _destination;
public ParameterExpression Source => _source;
public ParameterExpression Context => _context;
public TypeMapPlanBuilder(IConfigurationProvider configurationProvider, TypeMapRegistry typeMapRegistry, TypeMap typeMap)
{
_configurationProvider = configurationProvider;
_typeMapRegistry = typeMapRegistry;
_typeMap = typeMap;
_source = Parameter(typeMap.SourceType, "src");
_initialDestination = Parameter(typeMap.DestinationTypeToUse, "dest");
_context = Parameter(typeof(ResolutionContext), "ctxt");
_destination = Variable(_initialDestination.Type, "typeMapDestination");
}
public LambdaExpression CreateMapperLambda()
{
if(_typeMap.SourceType.IsGenericTypeDefinition() || _typeMap.DestinationTypeToUse.IsGenericTypeDefinition())
{
return null;
}
var customExpression = TypeConverterMapper() ?? _typeMap.Substitution ?? _typeMap.CustomMapper ?? _typeMap.CustomProjection;
if(customExpression != null)
{
return Lambda(customExpression.ReplaceParameters(_source, _initialDestination, _context), _source, _initialDestination, _context);
}
bool constructorMapping;
var destinationFunc = CreateDestinationFunc(out constructorMapping);
var assignmentFunc = CreateAssignmentFunc(destinationFunc, constructorMapping);
var mapperFunc = CreateMapperFunc(assignmentFunc);
var checkContext = CheckContext(_typeMap, _context);
var lambaBody = (checkContext != null) ? new[] { checkContext, mapperFunc } : new[] { mapperFunc };
return Lambda(Block(new[] { _destination }, lambaBody), _source, _initialDestination, _context);
}
private LambdaExpression TypeConverterMapper()
{
if(_typeMap.TypeConverterType == null)
{
return null;
}
Type type;
if(_typeMap.TypeConverterType.IsGenericTypeDefinition())
{
var genericTypeParam = _typeMap.SourceType.IsGenericType()
? _typeMap.SourceType.GetTypeInfo().GenericTypeArguments[0]
: _typeMap.DestinationTypeToUse.GetTypeInfo().GenericTypeArguments[0];
type = _typeMap.TypeConverterType.MakeGenericType(genericTypeParam);
}
else
{
type = _typeMap.TypeConverterType;
}
// (src, dest, ctxt) => ((ITypeConverter<TSource, TDest>)ctxt.Options.CreateInstance<TypeConverterType>()).ToType(src, ctxt);
var converterInterfaceType = typeof(ITypeConverter<,>).MakeGenericType(_typeMap.SourceType, _typeMap.DestinationTypeToUse);
return Lambda(
Call(
ToType(CreateInstance(type), converterInterfaceType),
converterInterfaceType.GetDeclaredMethod("Convert"),
_source, _initialDestination, _context
),
_source, _initialDestination, _context);
}
public static ConditionalExpression CheckContext(TypeMap typeMap, Expression context)
{
if(typeMap.MaxDepth > 0 || typeMap.PreserveReferences)
{
var mapper = Property(context, "Mapper");
return IfThen(Property(context, "IsDefault"), Assign(context, Invoke(CreateContext, mapper)));
}
return null;
}
private Expression CreateDestinationFunc(out bool constructorMapping)
{
var newDestFunc = ToType(CreateNewDestinationFunc(out constructorMapping), _typeMap.DestinationTypeToUse);
var getDest = _typeMap.DestinationTypeToUse.IsValueType()
? newDestFunc
: Coalesce(_initialDestination, newDestFunc);
Expression destinationFunc = Assign(_destination, getDest);
if(_typeMap.PreserveReferences)
{
var dest = Variable(typeof(object), "dest");
var setValue = _context.Type.GetDeclaredMethod("CacheDestination");
var set = Call(_context, setValue, _source, Constant(_destination.Type), _destination);
var setCache = IfThen(NotEqual(_source, Constant(null)), set);
destinationFunc = Block(new[] { dest }, Assign(dest, destinationFunc), setCache, dest);
}
return destinationFunc;
}
private Expression CreateAssignmentFunc(Expression destinationFunc, bool constructorMapping)
{
var actions = new List<Expression>();
foreach(var propertyMap in _typeMap.GetPropertyMaps())
{
if(!propertyMap.CanResolveValue())
{
continue;
}
var property = TryPropertyMap(propertyMap);
if(constructorMapping && _typeMap.ConstructorParameterMatches(propertyMap.DestinationProperty.Name))
{
property = IfThen(NotEqual(_initialDestination, Constant(null)), property);
}
actions.Add(property);
}
foreach(var beforeMapAction in _typeMap.BeforeMapActions)
{
actions.Insert(0, beforeMapAction.ReplaceParameters(_source, _destination, _context));
}
actions.Insert(0, destinationFunc);
if(_typeMap.MaxDepth > 0)
{
actions.Insert(0, Call(_context, ((MethodCallExpression)IncTypeDepthInfo.Body).Method, Constant(_typeMap.Types)));
}
actions.AddRange(
_typeMap.AfterMapActions.Select(
afterMapAction => afterMapAction.ReplaceParameters(_source, _destination, _context)));
if(_typeMap.MaxDepth > 0)
{
actions.Add(Call(_context, ((MethodCallExpression)DecTypeDepthInfo.Body).Method, Constant(_typeMap.Types)));
}
actions.Add(_destination);
return Block(actions);
}
private Expression CreateMapperFunc(Expression assignmentFunc)
{
var mapperFunc = assignmentFunc;
if(_typeMap.Condition != null)
{
mapperFunc =
Condition(_typeMap.Condition.Body,
mapperFunc, Default(_typeMap.DestinationTypeToUse));
//mapperFunc = (source, context, destFunc) => _condition(context) ? inner(source, context, destFunc) : default(TDestination);
}
if(_typeMap.MaxDepth > 0)
{
mapperFunc = Condition(
LessThanOrEqual(
Call(_context, ((MethodCallExpression)GetTypeDepthInfo.Body).Method, Constant(_typeMap.Types)),
Constant(_typeMap.MaxDepth)
),
mapperFunc,
Default(_typeMap.DestinationTypeToUse));
//mapperFunc = (source, context, destFunc) => context.GetTypeDepth(types) <= maxDepth ? inner(source, context, destFunc) : default(TDestination);
}
if(_typeMap.Profile.AllowNullDestinationValues && !_typeMap.SourceType.IsValueType())
{
mapperFunc =
Condition(Equal(_source, Default(_typeMap.SourceType)),
Default(_typeMap.DestinationTypeToUse), mapperFunc.RemoveIfNotNull(_source));
//mapperFunc = (source, context, destFunc) => source == default(TSource) ? default(TDestination) : inner(source, context, destFunc);
}
if(_typeMap.PreserveReferences)
{
var cache = Variable(_typeMap.DestinationTypeToUse, "cachedDestination");
var getDestination = _context.Type.GetDeclaredMethod("GetDestination");
var assignCache =
Assign(cache, ToType(Call(_context, getDestination, _source, Constant(_destination.Type)), _destination.Type));
var condition = Condition(
AndAlso(NotEqual(_source, Constant(null)), NotEqual(assignCache, Constant(null))),
cache,
mapperFunc);
mapperFunc = Block(new[] { cache }, condition);
}
return mapperFunc;
}
private Expression CreateNewDestinationFunc(out bool constructorMapping)
{
constructorMapping = false;
if(_typeMap.DestinationCtor != null)
return _typeMap.DestinationCtor.ReplaceParameters(_source, _context);
if(_typeMap.ConstructDestinationUsingServiceLocator)
return CreateInstance(_typeMap.DestinationTypeToUse);
if(_typeMap.ConstructorMap?.CanResolve == true)
{
constructorMapping = true;
return _typeMap.ConstructorMap.BuildExpression(this);
}
#if NET45
if(_typeMap.DestinationTypeToUse.IsInterface())
{
var ctor = Call(Constant(ObjectCreator.DelegateFactory), typeof(DelegateFactory).GetDeclaredMethod("CreateCtor", new[] { typeof(Type) }), Call(New(typeof(ProxyGenerator)), typeof(ProxyGenerator).GetDeclaredMethod("GetProxyType"), Constant(_typeMap.DestinationTypeToUse)));
// We're invoking a delegate here
return Invoke(ctor);
}
#endif
if(_typeMap.DestinationTypeToUse.IsAbstract())
return Constant(null);
if(_typeMap.DestinationTypeToUse.IsGenericTypeDefinition())
return Constant(null);
return DelegateFactory.GenerateConstructorExpression(_typeMap.DestinationTypeToUse);
}
private Expression TryPropertyMap(PropertyMap propertyMap)
{
var pmExpression = CreatePropertyMapFunc(propertyMap);
if(pmExpression == null)
return null;
var exception = Parameter(typeof(Exception), "ex");
var mappingExceptionCtor = ((NewExpression)CtorExpression.Body).Constructor;
return TryCatch(Block(typeof(void), pmExpression),
MakeCatchBlock(typeof(Exception), exception,
Throw(New(mappingExceptionCtor, Constant("Error mapping types."), exception, Constant(propertyMap.TypeMap.Types), Constant(propertyMap.TypeMap), Constant(propertyMap))), null));
}
private Expression CreatePropertyMapFunc(PropertyMap propertyMap)
{
var destMember = MakeMemberAccess(_destination, propertyMap.DestinationProperty);
Expression getter;
var pi = propertyMap.DestinationProperty as PropertyInfo;
if(pi != null && pi.GetGetMethod(true) == null)
{
getter = Default(propertyMap.DestinationPropertyType);
}
else
{
getter = destMember;
}
Expression destValueExpr;
if(propertyMap.UseDestinationValue)
{
destValueExpr = getter;
}
else
{
if(_initialDestination.Type.IsValueType())
{
destValueExpr = Default(propertyMap.DestinationPropertyType);
}
else
{
destValueExpr = Condition(Equal(_initialDestination, Constant(null)), Default(propertyMap.DestinationPropertyType), getter);
}
}
var valueResolverExpr = BuildValueResolverFunc(propertyMap, getter);
var resolvedValue = Variable(valueResolverExpr.Type, "resolvedValue");
var setResolvedValue = Assign(resolvedValue, valueResolverExpr);
valueResolverExpr = resolvedValue;
var typePair = new TypePair(valueResolverExpr.Type, propertyMap.DestinationPropertyType);
valueResolverExpr = propertyMap.Inline ?
MapExpression(typePair, valueResolverExpr, propertyMap, destValueExpr) :
ContextMap(typePair, valueResolverExpr, _context, destValueExpr);
ParameterExpression propertyValue;
Expression setPropertyValue;
if(valueResolverExpr == resolvedValue)
{
propertyValue = resolvedValue;
setPropertyValue = setResolvedValue;
}
else
{
propertyValue = Variable(valueResolverExpr.Type, "propertyValue");
setPropertyValue = Assign(propertyValue, valueResolverExpr);
}
Expression mapperExpr;
if(propertyMap.DestinationProperty is FieldInfo)
{
mapperExpr = propertyMap.SourceType != propertyMap.DestinationPropertyType
? Assign(destMember, ToType(propertyValue, propertyMap.DestinationPropertyType))
: Assign(getter, propertyValue);
}
else
{
var setter = ((PropertyInfo)propertyMap.DestinationProperty).GetSetMethod(true);
if(setter == null)
{
mapperExpr = propertyValue;
}
else
{
mapperExpr = Assign(destMember, ToType(propertyValue, propertyMap.DestinationPropertyType));
}
}
if(propertyMap.Condition != null)
{
mapperExpr = IfThen(
propertyMap.Condition.ConvertReplaceParameters(
_source,
_destination,
ToType(propertyValue, propertyMap.Condition.Parameters[2].Type),
ToType(getter, propertyMap.Condition.Parameters[2].Type),
_context
),
mapperExpr
);
}
mapperExpr = Block(new[] { setResolvedValue, setPropertyValue, mapperExpr }.Distinct());
if(propertyMap.PreCondition != null)
{
mapperExpr = IfThen(
propertyMap.PreCondition.ConvertReplaceParameters(_source, _context),
mapperExpr
);
}
return Block(new[] { resolvedValue, propertyValue }.Distinct(), mapperExpr);
}
private Expression BuildValueResolverFunc(PropertyMap propertyMap, Expression destValueExpr)
{
Expression valueResolverFunc;
var destinationPropertyType = propertyMap.DestinationPropertyType;
var valueResolverConfig = propertyMap.ValueResolverConfig;
var typeMap = propertyMap.TypeMap;
if(valueResolverConfig != null)
{
valueResolverFunc = ToType(BuildResolveCall(destValueExpr, valueResolverConfig), destinationPropertyType);
}
else if(propertyMap.CustomResolver != null)
{
valueResolverFunc = propertyMap.CustomResolver.ConvertReplaceParameters(_source, _destination, destValueExpr, _context);
}
else if(propertyMap.CustomExpression != null)
{
var nullCheckedExpression = propertyMap.CustomExpression.ReplaceParameters(_source).IfNotNull(destinationPropertyType);
var destinationNullable = destinationPropertyType.IsNullableType();
var returnType = destinationNullable && destinationPropertyType.GetTypeOfNullable() == nullCheckedExpression.Type
? destinationPropertyType
: nullCheckedExpression.Type;
valueResolverFunc =
TryCatch(
ToType(nullCheckedExpression, returnType),
Catch(typeof(NullReferenceException), Default(returnType)),
Catch(typeof(ArgumentNullException), Default(returnType))
);
}
else if(propertyMap.SourceMembers.Any()
&& propertyMap.SourceType != null
)
{
var last = propertyMap.SourceMembers.Last();
var pi = last as PropertyInfo;
if(pi != null && pi.GetGetMethod(true) == null)
{
valueResolverFunc = Default(last.GetMemberType());
}
else
{
valueResolverFunc = propertyMap.SourceMembers.Aggregate(
(Expression)_source,
(inner, getter) => getter is MethodInfo
? getter.IsStatic()
? Call(null, (MethodInfo)getter, inner)
: (Expression)Call(inner, (MethodInfo)getter)
: MakeMemberAccess(getter.IsStatic() ? null : inner, getter)
);
valueResolverFunc = valueResolverFunc.IfNotNull(destinationPropertyType);
}
}
else if(propertyMap.SourceMember != null)
{
valueResolverFunc = MakeMemberAccess(_source, propertyMap.SourceMember);
}
else
{
valueResolverFunc = Throw(Constant(new Exception("I done blowed up")));
}
if(propertyMap.NullSubstitute != null)
{
var nullSubstitute = Constant(propertyMap.NullSubstitute);
valueResolverFunc = Coalesce(valueResolverFunc, ToType(nullSubstitute, valueResolverFunc.Type));
}
else if(!typeMap.Profile.AllowNullDestinationValues)
{
var toCreate = propertyMap.SourceType ?? destinationPropertyType;
if(!toCreate.IsAbstract() && toCreate.IsClass())
{
valueResolverFunc = Coalesce(
valueResolverFunc,
ToType(Call(
typeof(ObjectCreator).GetDeclaredMethod("CreateNonNullValue"),
Constant(toCreate)
), propertyMap.SourceType));
}
}
return valueResolverFunc;
}
private Expression CreateInstance(Type type)
{
return Call(Property(_context, "Options"), "CreateInstance", new[] { type });
}
private Expression BuildResolveCall(Expression destValueExpr, ValueResolverConfiguration valueResolverConfig)
{
var resolverInstance = valueResolverConfig.Instance != null ? Constant(valueResolverConfig.Instance) : CreateInstance(valueResolverConfig.ConcreteType);
var sourceMember = valueResolverConfig.SourceMember?.ReplaceParameters(_source) ??
(valueResolverConfig.SourceMemberName != null ?
PropertyOrField(_source, valueResolverConfig.SourceMemberName) :
null);
var iResolverType = valueResolverConfig.InterfaceType;
var parameters = new[] { _source, _destination, sourceMember, destValueExpr }.Where(p => p != null)
.Zip(iResolverType.GetGenericArguments(), (e, type) => ToType(e, type))
.Concat(new[] { _context });
return Call(ToType(resolverInstance, iResolverType), iResolverType.GetDeclaredMethod("Resolve"), parameters);
}
public Expression MapExpression(TypePair typePair, Expression sourceParameter, PropertyMap propertyMap = null, Expression destinationParameter = null)
{
return MapExpression(_typeMapRegistry, _configurationProvider, typePair, sourceParameter, _context, propertyMap, destinationParameter);
}
public static Expression MapExpression(TypeMapRegistry typeMapRegistry, IConfigurationProvider configurationProvider,
TypePair typePair, Expression sourceParameter, Expression contextParameter, PropertyMap propertyMap = null, Expression destinationParameter = null)
{
if(destinationParameter == null)
{
destinationParameter = Default(typePair.DestinationType);
}
var typeMap = configurationProvider.ResolveTypeMap(typePair);
if(typeMap != null)
{
if(!typeMap.HasDerivedTypesToInclude())
{
typeMap.Seal(typeMapRegistry, configurationProvider);
if(typeMap.MapExpression != null)
{
return typeMap.MapExpression.ConvertReplaceParameters(sourceParameter, destinationParameter, contextParameter);
}
else
{
return ContextMap(typePair, sourceParameter, contextParameter, destinationParameter);
}
}
else
{
return ContextMap(typePair, sourceParameter, contextParameter, destinationParameter);
}
}
var match = configurationProvider.GetMappers().FirstOrDefault(m => m.IsMatch(typePair));
if(match != null)
{
var mapperExpression = match.MapExpression(typeMapRegistry, configurationProvider, propertyMap, sourceParameter, destinationParameter, contextParameter);
return ToType(mapperExpression, typePair.DestinationType);
}
return ContextMap(typePair, sourceParameter, contextParameter, destinationParameter);
}
private static Expression ContextMap(TypePair typePair, Expression sourceParameter, Expression contextParameter, Expression destinationParameter)
{
var mapMethod = typeof(ResolutionContext).GetDeclaredMethods().First(m => m.Name == "Map").MakeGenericMethod(typePair.SourceType, typePair.DestinationType);
return Call(contextParameter, mapMethod, sourceParameter, destinationParameter);
}
}
}