diff --git a/src/Benchmark/Benchmark.csproj b/src/Benchmark/Benchmark.csproj index c1215562..3b9b1438 100644 --- a/src/Benchmark/Benchmark.csproj +++ b/src/Benchmark/Benchmark.csproj @@ -1,13 +1,42 @@ - + Exe netcoreapp2.0 + true - + + + + + + + TextTemplatingFileGenerator + CustomerMapper.cs + + + TextTemplatingFileGenerator + FooMapper.cs + + + + + + + + True + True + CustomerMapper.tt + + + True + True + FooMapper.tt + + \ No newline at end of file diff --git a/src/Benchmark/CustomerMapper.cs b/src/Benchmark/CustomerMapper.cs new file mode 100644 index 00000000..eaef0f03 --- /dev/null +++ b/src/Benchmark/CustomerMapper.cs @@ -0,0 +1,103 @@ + + + + + + + +using System.Collections.Generic; +using Benchmark.Classes; + + +namespace Benchmark +{ + public static class CustomerMapper + { + public static CustomerDTO Map(Customer p1) + { + return p1 == null ? null : new CustomerDTO() + { + Id = p1.Id, + Name = p1.Name, + Address = p1.Address == null ? null : new Address() + { + Id = p1.Address.Id, + Street = p1.Address.Street, + City = p1.Address.City, + Country = p1.Address.Country + }, + HomeAddress = p1.HomeAddress == null ? null : new AddressDTO() + { + Id = p1.HomeAddress.Id, + City = p1.HomeAddress.City, + Country = p1.HomeAddress.Country + }, + Addresses = func1(p1.Addresses), + WorkAddresses = func2(p1.WorkAddresses), + AddressCity = p1.Address == null ? null : p1.Address.City + }; + } + + private static AddressDTO[] func1(Address[] p2) + { + AddressDTO[] result; + + if (p2 == null) + { + result = null; + } + else + { + result = new AddressDTO[p2.Length]; + + int v = 0; + + int i = 0; + int len = p2.Length; + + while (i < len) + { + Address item = p2[i]; + result[v++] = item == null ? null : new AddressDTO() + { + Id = item.Id, + City = item.City, + Country = item.Country + }; + i++; + } + } + return result; + } + + private static List func2(ICollection
p3) + { + List result; + + if (p3 == null) + { + result = null; + } + else + { + result = new List(p3.Count); + + ICollection list = result; + + IEnumerator
enumerator = p3.GetEnumerator(); + + while (enumerator.MoveNext()) + { + Address item = enumerator.Current; + list.Add(item == null ? null : new AddressDTO() + { + Id = item.Id, + City = item.City, + Country = item.Country + }); + } + } + return result; + } + } +} diff --git a/src/Benchmark/CustomerMapper.tt b/src/Benchmark/CustomerMapper.tt new file mode 100644 index 00000000..4521a513 --- /dev/null +++ b/src/Benchmark/CustomerMapper.tt @@ -0,0 +1,35 @@ +<#@ template debug="true" hostspecific="true" language="C#" #> +<#@ output extension=".cs" #> + +<#@ Assembly Name="/usr/local/share/dotnet/sdk/2.2.103/Microsoft/Microsoft.NET.Build.Extensions/net461/lib/netstandard.dll" #> +<#@ Assembly Name="System.Core" #> +<#@ Assembly Name="System.Runtime" #> +<#@ Assembly Name="System.Linq.Expressions" #> +<#@ Assembly Name="$(TargetDir)/Benchmark.dll" #> +<#@ Assembly Name="$(TargetDir)/Mapster.dll" #> +<#@ Assembly Name="$(TargetDir)/ExpressionTranslator.dll" #> +<#@ import namespace="System" #> +<#@ import namespace="System.IO" #> +<#@ import namespace="System.Diagnostics" #> +<#@ import namespace="System.Linq" #> +<#@ import namespace="System.Collections" #> +<#@ import namespace="System.Collections.Generic" #> +<#@ import namespace="Benchmark.Classes" #> +<#@ import namespace="ExpressionDebugger" #> +<#@ import namespace="Mapster" #> + +<# + TypeAdapterConfig.GlobalSettings.SelfContainedCodeGeneration = true; + var foo = default(Customer); + var def = new ExpressionDefinitions + { + IsStatic = true, + MethodName = "Map", + Namespace = "Benchmark", + TypeName = "CustomerMapper" + }; + var code = foo.BuildAdapter() + .CreateMapExpression() + .ToScript(def); + WriteLine(code); +#> \ No newline at end of file diff --git a/src/Benchmark/FooMapper.cs b/src/Benchmark/FooMapper.cs new file mode 100644 index 00000000..08095908 --- /dev/null +++ b/src/Benchmark/FooMapper.cs @@ -0,0 +1,86 @@ + + + + + + + +using System; +using System.Linq; +using Benchmark.Classes; +using Mapster; +using Mapster.Utils; + + +namespace Benchmark +{ + public static class FooMapper + { + public static Foo Map(Foo p1) + { + return p1 == null ? null : new Foo() + { + Name = p1.Name, + Int32 = p1.Int32, + Int64 = p1.Int64, + NullInt = p1.NullInt, + Floatn = p1.Floatn, + Doublen = p1.Doublen, + DateTime = p1.DateTime, + Foo1 = Map(p1.Foo1), + Foos = p1.Foos == null ? null : p1.Foos.Select(func1), + FooArr = func2(p1.FooArr), + IntArr = func3(p1.IntArr), + Ints = p1.Ints == null ? null : MapsterHelper.ToEnumerable(p1.Ints) + }; + } + + private static Foo func1(Foo p2) + { + return Map(p2); + } + + private static Foo[] func2(Foo[] p3) + { + Foo[] result; + + if (p3 == null) + { + result = null; + } + else + { + result = new Foo[p3.Length]; + + int v = 0; + + int i = 0; + int len = p3.Length; + + while (i < len) + { + Foo item = p3[i]; + result[v++] = Map(item); + i++; + } + } + return result; + } + + private static int[] func3(int[] p4) + { + int[] result; + + if (p4 == null) + { + result = null; + } + else + { + result = new int[p4.Length]; + Array.Copy(p4, 0, result, 0, p4.Length); + } + return result; + } + } +} diff --git a/src/Benchmark/FooMapper.tt b/src/Benchmark/FooMapper.tt new file mode 100644 index 00000000..9fa1c2e7 --- /dev/null +++ b/src/Benchmark/FooMapper.tt @@ -0,0 +1,37 @@ +<#@ template debug="true" hostspecific="true" language="C#" #> +<#@ output extension=".cs" #> + +<#@ Assembly Name="/usr/local/share/dotnet/sdk/2.2.103/Microsoft/Microsoft.NET.Build.Extensions/net461/lib/netstandard.dll" #> +<#@ Assembly Name="System.Core" #> +<#@ Assembly Name="System.Runtime" #> +<#@ Assembly Name="System.Linq.Expressions" #> +<#@ Assembly Name="$(TargetDir)/Benchmark.dll" #> +<#@ Assembly Name="$(TargetDir)/Mapster.dll" #> +<#@ Assembly Name="$(TargetDir)/ExpressionTranslator.dll" #> +<#@ import namespace="System" #> +<#@ import namespace="System.IO" #> +<#@ import namespace="System.Diagnostics" #> +<#@ import namespace="System.Linq" #> +<#@ import namespace="System.Linq.Expressions" #> +<#@ import namespace="System.Collections" #> +<#@ import namespace="System.Collections.Generic" #> +<#@ import namespace="Benchmark.Classes" #> +<#@ import namespace="ExpressionDebugger" #> +<#@ import namespace="Mapster" #> + +<# + TypeAdapterConfig.GlobalSettings.SelfContainedCodeGeneration = true; + var foo = default(Foo); + var def = new ExpressionDefinitions + { + IsStatic = true, + MethodName = "Map", + Namespace = "Benchmark", + TypeName = "FooMapper" + }; + var code = foo.BuildAdapter() + .CreateMapExpression() + .ToScript(def); + code = code.Replace("TypeAdapter.Map.Invoke", "Map"); + WriteLine(code); +#> \ No newline at end of file diff --git a/src/Benchmark/Program.cs b/src/Benchmark/Program.cs index ae6dc33a..54cb8777 100644 --- a/src/Benchmark/Program.cs +++ b/src/Benchmark/Program.cs @@ -6,6 +6,7 @@ using Mapster; using FastExpressionCompiler; using System.Linq.Expressions; +using ExpressionDebugger; namespace Benchmark { @@ -117,10 +118,11 @@ static void Test(Customer item, int iterations) item.Adapt(); //exercise TestMapsterAdapter(item, iterations, ref sMP); - TypeAdapterConfig.GlobalSettings.Compiler = exp => exp.CompileFast(); //switch compiler - TypeAdapterConfig.GlobalSettings.Compile(typeof(Customer), typeof(CustomerDTO)); //recompile - item.Adapt(); //exercise - TestMapsterAdapter(item, iterations, ref sMF); + //TypeAdapterConfig.GlobalSettings.Compiler = exp => exp.CompileFast(); //switch compiler + //TypeAdapterConfig.GlobalSettings.Compile(typeof(Customer), typeof(CustomerDTO)); //recompile + //item.Adapt(); //exercise + //TestMapsterAdapter(item, iterations, ref sMF); + TestCodeGen(item, iterations, ref sMF); ExpressMapper.Mapper.Map(item); //exercise TestExpressMapper(item, iterations, ref sEM); @@ -143,10 +145,11 @@ static void TestSimple(Foo item, int iterations) item.Adapt(); //exercise TestMapsterAdapter(item, iterations, ref sMP); - TypeAdapterConfig.GlobalSettings.Compiler = exp => exp.CompileFast(); //switch compiler - TypeAdapterConfig.GlobalSettings.Compile(typeof(Foo), typeof(Foo)); //recompile - item.Adapt(); //exercise - TestMapsterAdapter(item, iterations, ref sMF); + //TypeAdapterConfig.GlobalSettings.Compiler = exp => exp.CompileFast(); //switch compiler + //TypeAdapterConfig.GlobalSettings.Compile(typeof(Foo), typeof(Foo)); //recompile + //item.Adapt(); //exercise + //TestMapsterAdapter(item, iterations, ref sMF); + TestCodeGen(item, iterations, ref sMF); //TestValueInjecter(item, iterations); @@ -218,6 +221,20 @@ static void TestAutoMapper(TSrc item, int iterations, ref double co counter += time; } + static void TestCodeGen(Customer item, int iterations, ref double counter) + { + var time = Loop(item, get => CustomerMapper.Map(get), iterations); + Console.WriteLine("Codegen:\t\t" + time); + counter += time; + } + + static void TestCodeGen(Foo item, int iterations, ref double counter) + { + var time = Loop(item, get => FooMapper.Map(get), iterations); + Console.WriteLine("Codegen:\t\t" + time); + counter += time; + } + static long Loop(T item, Action action, int iterations = 1000000) { return Time(item, a => diff --git a/src/Mapster/Adapters/BaseAdapter.cs b/src/Mapster/Adapters/BaseAdapter.cs index db6d167b..6e337300 100644 --- a/src/Mapster/Adapters/BaseAdapter.cs +++ b/src/Mapster/Adapters/BaseAdapter.cs @@ -63,6 +63,8 @@ protected virtual bool CanInline(Expression source, Expression destination, Comp return false; if (arg.Settings.AfterMappingFactories.Count > 0) return false; + if (arg.Settings.BeforeMappingFactories.Count > 0) + return false; if (arg.Settings.Includes.Count > 0) return false; return true; @@ -70,16 +72,18 @@ protected virtual bool CanInline(Expression source, Expression destination, Comp protected virtual Expression CreateExpressionBody(Expression source, Expression destination, CompileArgument arg) { - if (this.CheckExplicitMapping - && arg.Context.Config.RequireExplicitMapping - && !arg.ExplicitMapping) + if (this.CheckExplicitMapping) { - throw new InvalidOperationException("Implicit mapping is not allowed (check GlobalSettings.RequireExplicitMapping) and no configuration exists"); + if (arg.Settings.MaxDepth <= 0) + return arg.DestinationType.CreateDefault(); + + if (arg.Context.Config.RequireExplicitMapping && !arg.ExplicitMapping) + throw new InvalidOperationException("Implicit mapping is not allowed (check GlobalSettings.RequireExplicitMapping) and no configuration exists"); } if (CanInline(source, destination, arg) && arg.Settings.AvoidInlineMapping != true) return CreateInlineExpressionBody(source, arg).To(arg.DestinationType, true); - else if (arg.Context.Running.Count > 1) + else if (!arg.Context.Config.SelfContainedCodeGeneration && arg.Context.Running.Count > 1) return null; else return CreateBlockExpressionBody(source, destination, arg); @@ -96,34 +100,22 @@ protected Expression CreateBlockExpressionBody(Expression source, Expression des if (set.NodeType != ExpressionType.Throw) { - Expression assign = Expression.Assign(result, set); - set = CreateBlockExpression(source, result, arg); + var actions = new List + { + Expression.Assign(result, set) + }; + + //before(source, result); + var beforeMappings = arg.Settings.BeforeMappingFactories.Select(it => InvokeMapping(it, source, result, arg)); + actions.AddRange(beforeMappings); //result.prop = adapt(source.prop); - //action(source, result); - if (arg.Settings.AfterMappingFactories.Count > 0) - { - var actions = new List { set }; - - foreach (var afterMappingFactory in arg.Settings.AfterMappingFactories) - { - var afterMapping = afterMappingFactory(arg); - var args = afterMapping.Parameters; - Expression invoke; - if (args[0].Type.IsReferenceAssignableFrom(source.Type) && args[1].Type.IsReferenceAssignableFrom(result.Type)) - { - var replacer = new ParameterExpressionReplacer(args, source, result); - invoke = replacer.Visit(afterMapping.Body); - } - else - { - invoke = Expression.Invoke(afterMapping, source.To(args[0].Type), result.To(args[1].Type)); - } - actions.Add(invoke); - } + set = CreateBlockExpression(source, result, arg); + actions.Add(set); - set = Expression.Block(actions); - } + //after(source, result); + var afterMappings = arg.Settings.AfterMappingFactories.Select(it => InvokeMapping(it, source, result, arg)); + actions.AddRange(afterMappings); //using (var scope = new MapContextScope()) { // var references = scope.Context.Reference; @@ -153,7 +145,8 @@ protected Expression CreateBlockExpressionBody(Expression source, Expression des var refAssign = Expression.Assign( Expression.Property(dict, indexer, Expression.Convert(source, typeof(object))), Expression.Convert(result, typeof(object))); - var setResultAndCache = Expression.Block(assign, refAssign, set); + actions.Add(refAssign); + var setResultAndCache = Expression.Block(actions); var cache = Expression.Variable(typeof(object), "cache"); var tryGetMethod = typeof(Dictionary).GetMethod("TryGetValue", new[] { typeof(object), typeof(object).MakeByRefType() }); @@ -169,7 +162,7 @@ protected Expression CreateBlockExpressionBody(Expression source, Expression des } else { - set = Expression.Block(assign, set); + set = Expression.Block(actions); } //TDestination result; @@ -247,6 +240,16 @@ protected Expression CreateBlockExpressionBody(Expression source, Expression des return Expression.Block(new[] { result }, set, result); } + private Expression InvokeMapping(Func mappingFactory, Expression source, Expression result, CompileArgument arg) + { + var afterMapping = mappingFactory(arg); + var args = afterMapping.Parameters; + var invoke = afterMapping.Apply(source.To(args[0].Type), result.To(args[1].Type)); + if (invoke.Type != typeof(void)) + invoke = ExpressionEx.Assign(result, invoke); + return invoke; + } + protected Expression CreateInlineExpressionBody(Expression source, CompileArgument arg) { //source == null ? default(TDestination) : adapt(source) @@ -301,9 +304,7 @@ protected virtual Expression CreateInstantiationExpression(Expression source, Ex throw new InvalidOperationException($"No default constructor for type '{arg.DestinationType.Name}', please use 'ConstructUsing'"); //dest ?? new TDest(); - return destination == null - ? newObj - : Expression.Coalesce(destination, newObj); + return newObj; } protected Expression CreateAdaptExpression(Expression source, Type destinationType, CompileArgument arg) @@ -313,8 +314,12 @@ protected Expression CreateAdaptExpression(Expression source, Type destinationTy return source; //adapt(source); - var lambda = arg.Context.Config.CreateInlineMapExpression(source.Type, destinationType, arg.MapType, arg.Context); - var exp = lambda.Apply(source); + var lambda = arg.Context.Config.CreateInlineMapExpression(source.Type, destinationType, arg.MapType == MapType.MapToTarget ? MapType.Map : arg.MapType, arg.Context); + var exp = !lambda.IsMultiLine() + ? lambda.Apply(source) + : arg.Context.Config.SelfContainedCodeGeneration + ? (Expression)Expression.Invoke(lambda, source) + : arg.Context.Config.CreateMapInvokeExpression(source.Type, destinationType); //transform(adapt(source)); if (arg.Settings.DestinationTransforms.Transforms.ContainsKey(exp.Type)) @@ -335,7 +340,11 @@ protected Expression CreateAdaptToExpression(Expression source, Expression desti //adapt(source, dest); var lambda = arg.Context.Config.CreateInlineMapExpression(source.Type, destination.Type, arg.MapType, arg.Context); - var exp = lambda.Apply(source, destination); + var exp = !lambda.IsMultiLine() + ? lambda.Apply(source, destination) + : arg.Context.Config.SelfContainedCodeGeneration + ? (Expression)Expression.Invoke(lambda, source, destination) + : arg.Context.Config.CreateMapToTargetInvokeExpression(source.Type, destination.Type); //transform(adapt(source, dest)); if (arg.Settings.DestinationTransforms.Transforms.ContainsKey(exp.Type)) diff --git a/src/Mapster/Adapters/BaseClassAdapter.cs b/src/Mapster/Adapters/BaseClassAdapter.cs index 2c39c4a1..a7a3bea3 100644 --- a/src/Mapster/Adapters/BaseClassAdapter.cs +++ b/src/Mapster/Adapters/BaseClassAdapter.cs @@ -2,28 +2,25 @@ using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; +using System.Reflection; using Mapster.Models; +using Mapster.Utils; namespace Mapster.Adapters { internal abstract class BaseClassAdapter : BaseAdapter { - protected abstract ClassModel GetClassModel(Type destinationType, CompileArgument arg); - #region Build the Adapter Model - protected ClassMapping CreateClassConverter(Expression source, Expression destination, CompileArgument arg) + protected ClassMapping CreateClassConverter(Expression source, ClassModel classModel, CompileArgument arg) { - var classModel = GetClassModel(arg.DestinationType, arg); var destinationMembers = classModel.Members; - var unmappedDestinationMembers = new List(); - var properties = new List(); foreach (var destinationMember in destinationMembers) { - if (ProcessIgnores(arg.Settings, destinationMember, out var setterCondition)) + if (ProcessIgnores(arg, destinationMember, out var setterCondition)) continue; var member = destinationMember; @@ -46,6 +43,9 @@ protected ClassMapping CreateClassConverter(Expression source, Expression destin } else if (classModel.ConstructorInfo != null) { + var info = (ParameterInfo)member.Info; + if (!info.IsOptional) + return null; var propertyModel = new MemberMapping { Getter = null, @@ -73,18 +73,66 @@ protected ClassMapping CreateClassConverter(Expression source, Expression destin } protected static bool ProcessIgnores( - TypeAdapterSettings config, + CompileArgument arg, IMemberModel destinationMember, out LambdaExpression condition) { condition = null; - if (!destinationMember.ShouldMapMember(config.ShouldMapMember, MemberSide.Destination)) + if (!destinationMember.ShouldMapMember(arg, MemberSide.Destination)) return true; - return config.IgnoreIfs.TryGetValue(destinationMember.Name, out condition) + return arg.Settings.IgnoreIfs.TryGetValue(destinationMember.Name, out condition) && condition == null; } + + protected Expression CreateInstantiationExpression(Expression source, ClassMapping classConverter, CompileArgument arg) + { + var members = classConverter.Members; + + var arguments = new List(); + foreach (var member in members) + { + var parameterInfo = (ParameterInfo)member.DestinationMember.Info; + var defaultConst = parameterInfo.IsOptional + ? Expression.Constant(parameterInfo.DefaultValue, member.DestinationMember.Type) + : parameterInfo.ParameterType.CreateDefault(); + + Expression getter; + if (member.Getter == null) + { + getter = defaultConst; + } + else + { + getter = CreateAdaptExpression(member.Getter, member.DestinationMember.Type, arg); + + if (arg.Settings.IgnoreNullValues == true && member.Getter.Type.CanBeNull()) + { + var condition = Expression.NotEqual(member.Getter, Expression.Constant(null, member.Getter.Type)); + getter = Expression.Condition(condition, getter, defaultConst); + } + if (member.SetterCondition != null) + { + var condition = ExpressionEx.Not(member.SetterCondition.Apply(source, arg.DestinationType.CreateDefault())); + getter = Expression.Condition(condition, getter, defaultConst); + } + } + arguments.Add(getter); + } + + return Expression.New(classConverter.ConstructorInfo, arguments); + } + + protected ClassModel GetClassModel(ConstructorInfo ctor) + { + return new ClassModel + { + ConstructorInfo = ctor, + Members = ctor.GetParameters().Select(ReflectionUtils.CreateModel) + }; + } + #endregion } } diff --git a/src/Mapster/Adapters/ClassAdapter.cs b/src/Mapster/Adapters/ClassAdapter.cs index 50c2ea76..e8a52f69 100644 --- a/src/Mapster/Adapters/ClassAdapter.cs +++ b/src/Mapster/Adapters/ClassAdapter.cs @@ -20,13 +20,7 @@ internal class ClassAdapter : BaseClassAdapter protected override bool CanMap(PreCompileArgument arg) { - var bindingFlags = arg.ExplicitMapping - ? BindingFlags.Public | BindingFlags.NonPublic - : BindingFlags.Public; - if (!arg.DestinationType.IsPoco(bindingFlags)) - return false; - - return true; + return arg.ExplicitMapping || arg.DestinationType.IsPoco(); } protected override bool CanInline(Expression source, Expression destination, CompileArgument arg) @@ -56,6 +50,25 @@ protected override bool CanInline(Expression source, Expression destination, Com return true; } + protected override Expression CreateInstantiationExpression(Expression source, Expression destination, CompileArgument arg) + { + //new TDestination(src.Prop1, src.Prop2) + + if (arg.Settings.ConstructUsingFactory != null || arg.Settings.MapToConstructor != true) + return base.CreateInstantiationExpression(source, destination, arg); + + var classConverter = arg.DestinationType.GetConstructors() + .OrderByDescending(it => it.GetParameters().Length) + .Select(GetClassModel) + .Select(it => CreateClassConverter(source, it, arg)) + .FirstOrDefault(it => it != null); + + if (classConverter == null) + throw new Exception(); + + return CreateInstantiationExpression(source, classConverter, arg); + } + protected override Expression CreateBlockExpression(Expression source, Expression destination, CompileArgument arg) { //### !IgnoreNullValues @@ -68,7 +81,8 @@ protected override Expression CreateBlockExpression(Expression source, Expressio //if (src.Prop2 != null) // dest.Prop2 = convert(src.Prop2); - var classConverter = CreateClassConverter(source, destination, arg); + var classModel = GetClassModel(arg.DestinationType); + var classConverter = CreateClassConverter(source, classModel, arg); var members = classConverter.Members; var lines = new List(); @@ -108,7 +122,7 @@ protected override Expression CreateBlockExpression(Expression source, Expressio foreach (var kvp in conditions) { var condition = Expression.IfThen( - Expression.Not(kvp.Key.Apply(source, destination)), + ExpressionEx.Not(kvp.Key.Apply(source, destination)), Expression.Block(kvp.Value)); lines.Add(condition); } @@ -128,7 +142,8 @@ protected override Expression CreateInlineExpression(Expression source, CompileA var memberInit = exp as MemberInitExpression; var newInstance = memberInit?.NewExpression ?? (NewExpression)exp; - var classConverter = CreateClassConverter(source, newInstance, arg); + var classModel = GetClassModel(arg.DestinationType); + var classConverter = CreateClassConverter(source, classModel, arg); var members = classConverter.Members; var lines = new List(); @@ -161,7 +176,7 @@ protected override Expression CreateInlineExpression(Expression source, CompileA return Expression.MemberInit(newInstance, lines); } - protected override ClassModel GetClassModel(Type destinationType, CompileArgument arg) + private ClassModel GetClassModel(Type destinationType) { return new ClassModel { diff --git a/src/Mapster/Adapters/CollectionAdapter.cs b/src/Mapster/Adapters/CollectionAdapter.cs index 7d74ff95..764722f1 100644 --- a/src/Mapster/Adapters/CollectionAdapter.cs +++ b/src/Mapster/Adapters/CollectionAdapter.cs @@ -101,8 +101,8 @@ protected override Expression CreateInlineExpression(Expression source, CompileA return source; //create new enumerable to prevent destination casting back to original type and alter directly - var toEnum = (from m in typeof(CoreExtensions).GetMethods() - where m.Name == nameof(CoreExtensions.ToEnumerable) + var toEnum = (from m in typeof(MapsterHelper).GetMethods() + where m.Name == nameof(MapsterHelper.ToEnumerable) select m).First().MakeGenericMethod(destinationElementType); return Expression.Call(toEnum, source); } diff --git a/src/Mapster/Adapters/DictionaryAdapter.cs b/src/Mapster/Adapters/DictionaryAdapter.cs index ee45b0d3..1886ec31 100644 --- a/src/Mapster/Adapters/DictionaryAdapter.cs +++ b/src/Mapster/Adapters/DictionaryAdapter.cs @@ -76,7 +76,7 @@ protected override Expression CreateBlockExpression(Expression source, Expressio else { var setWithCondition = Expression.IfThen( - Expression.Not(ignoreIf.Value.Apply(source, destination)), + ExpressionEx.Not(ignoreIf.Value.Apply(source, destination)), set); dict.Add(ignoreIf.Key, setWithCondition); } @@ -141,7 +141,8 @@ protected override Expression CreateInlineExpression(Expression source, CompileA var listInit = exp as ListInitExpression; var newInstance = listInit?.NewExpression ?? (NewExpression)exp; - var classConverter = CreateClassConverter(source, newInstance, arg); + var classModel = GetClassModel(arg); + var classConverter = CreateClassConverter(source, classModel, arg); var members = classConverter.Members; var dictType = arg.DestinationType.GetDictionaryType(); @@ -164,27 +165,22 @@ protected override Expression CreateInlineExpression(Expression source, CompileA return Expression.ListInit(newInstance, lines); } - protected override ClassModel GetClassModel(Type destinationType, CompileArgument arg) + private ClassModel GetClassModel(CompileArgument arg) { //get member name from map - var destNames = arg.Settings.Resolvers.Select(r => r.DestinationMemberName); + var destNames = arg.GetDestinationNames().AsEnumerable(); //get member name from properties if (arg.SourceType.GetDictionaryType() == null) { - var srcNames = arg.Settings.Resolvers.Select(r => r.SourceMemberName) - .Where(name => name != null) - .ToHashSet(); var propNames = arg.SourceType.GetFieldsAndProperties(accessorFlags: BindingFlags.NonPublic | BindingFlags.Public) - .Where(model => model.ShouldMapMember(arg.Settings.ShouldMapMember, MemberSide.Source)) - .Select(model => model.Name) - .Where(name => !srcNames.Contains(name)) - .Select(name => arg.Settings.NameMatchingStrategy.SourceMemberNameConverter(name)); + .Where(model => model.ShouldMapMember(arg, MemberSide.Source)) + .Select(model => arg.Settings.NameMatchingStrategy.SourceMemberNameConverter(model.Name)); destNames = destNames.Union(propNames); } //create model - var dictType = destinationType.GetDictionaryType(); + var dictType = arg.DestinationType.GetDictionaryType(); var valueType = dictType.GetGenericArguments()[1]; var getFn = GetFunction(arg, dictType); @@ -206,8 +202,8 @@ private static Func GetFunction(CompileArgum if (strategy.DestinationMemberNameConverter != NameMatchingStrategy.Identity) { var args = dictType.GetGenericArguments(); - var getMethod = typeof(CoreExtensions).GetMethods() - .First(m => m.Name == nameof(CoreExtensions.FlexibleGet)) + var getMethod = typeof(MapsterHelper).GetMethods() + .First(m => m.Name == nameof(MapsterHelper.FlexibleGet)) .MakeGenericMethod(args[1]); var destNameConverter = Expression.Constant(strategy.DestinationMemberNameConverter); return (dict, key) => Expression.Call(getMethod, dict, key, destNameConverter); @@ -215,8 +211,8 @@ private static Func GetFunction(CompileArgum else { var args = dictType.GetGenericArguments(); - var getMethod = typeof(CoreExtensions).GetMethods() - .First(m => m.Name == nameof(CoreExtensions.GetValueOrDefault)) + var getMethod = typeof(MapsterHelper).GetMethods() + .First(m => m.Name == nameof(MapsterHelper.GetValueOrDefault)) .MakeGenericMethod(args); return (dict, key) => Expression.Call(getMethod, dict, key); } @@ -229,8 +225,8 @@ private static Func SetFunction( strategy.DestinationMemberNameConverter != NameMatchingStrategy.Identity) { var args = dictType.GetGenericArguments(); - var setMethod = typeof(CoreExtensions).GetMethods() - .First(m => m.Name == nameof(CoreExtensions.FlexibleSet)) + var setMethod = typeof(MapsterHelper).GetMethods() + .First(m => m.Name == nameof(MapsterHelper.FlexibleSet)) .MakeGenericMethod(args[1]); var destNameConverter = Expression.Constant(strategy.DestinationMemberNameConverter); return (dict, key, value) => Expression.Call(setMethod, dict, key, destNameConverter, value); diff --git a/src/Mapster/Adapters/RecordTypeAdapter.cs b/src/Mapster/Adapters/RecordTypeAdapter.cs index 27df6e14..418514fb 100644 --- a/src/Mapster/Adapters/RecordTypeAdapter.cs +++ b/src/Mapster/Adapters/RecordTypeAdapter.cs @@ -1,10 +1,5 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Linq.Expressions; +using System.Linq.Expressions; using System.Reflection; -using Mapster.Models; -using Mapster.Utils; namespace Mapster.Adapters { @@ -14,10 +9,7 @@ internal class RecordTypeAdapter : BaseClassAdapter protected override bool CanMap(PreCompileArgument arg) { - if (!arg.DestinationType.IsRecordType()) - return false; - - return true; + return arg.DestinationType.IsRecordType(); } protected override Expression CreateInstantiationExpression(Expression source, Expression destination, CompileArgument arg) @@ -27,41 +19,10 @@ protected override Expression CreateInstantiationExpression(Expression source, E if (arg.Settings.ConstructUsingFactory != null) return base.CreateInstantiationExpression(source, destination, arg); - var classConverter = CreateClassConverter(source, null, arg); - var members = classConverter.Members; - - var arguments = new List(); - foreach (var member in members) - { - var parameterInfo = (ParameterInfo)member.DestinationMember.Info; - var defaultConst = parameterInfo.IsOptional - ? Expression.Constant(parameterInfo.DefaultValue, member.DestinationMember.Type) - : parameterInfo.ParameterType.CreateDefault(); - - Expression getter; - if (member.Getter == null) - { - getter = defaultConst; - } - else - { - getter = CreateAdaptExpression(member.Getter, member.DestinationMember.Type, arg); - - if (arg.Settings.IgnoreNullValues == true && member.Getter.Type.CanBeNull()) - { - var condition = Expression.NotEqual(member.Getter, Expression.Constant(null, member.Getter.Type)); - getter = Expression.Condition(condition, getter, defaultConst); - } - if (member.SetterCondition != null) - { - var condition = Expression.Not(member.SetterCondition.Apply(source, arg.DestinationType.CreateDefault())); - getter = Expression.Condition(condition, getter, defaultConst); - } - } - arguments.Add(getter); - } - - return Expression.New(classConverter.ConstructorInfo, arguments); + var ctor = arg.DestinationType.GetConstructors()[0]; + var classModel = GetClassModel(ctor); + var classConverter = CreateClassConverter(source, classModel, arg); + return CreateInstantiationExpression(source, classConverter, arg); } protected override Expression CreateBlockExpression(Expression source, Expression destination, CompileArgument arg) @@ -73,17 +34,6 @@ protected override Expression CreateInlineExpression(Expression source, CompileA { return CreateInstantiationExpression(source, arg); } - - protected override ClassModel GetClassModel(Type destinationType, CompileArgument arg) - { - var ctor = destinationType.GetConstructors()[0]; - return new ClassModel - { - ConstructorInfo = ctor, - Members = ctor.GetParameters().Select(ReflectionUtils.CreateModel) - }; - } - } } diff --git a/src/Mapster/Compile/CompileArgument.cs b/src/Mapster/Compile/CompileArgument.cs index 2f560291..94ada109 100644 --- a/src/Mapster/Compile/CompileArgument.cs +++ b/src/Mapster/Compile/CompileArgument.cs @@ -1,4 +1,7 @@ -using System; +using Mapster.Utils; +using System; +using System.Collections.Generic; +using System.Linq; namespace Mapster { @@ -10,5 +13,21 @@ public class CompileArgument public bool ExplicitMapping; public TypeAdapterSettings Settings; public CompileContext Context; + + private HashSet _srcNames; + public HashSet GetSourceNames() + { + return _srcNames ?? (_srcNames = (from it in Settings.Resolvers + where it.SourceMemberName != null + select it.SourceMemberName.Split('.').First()).ToHashSet()); + } + + private HashSet _destNames; + public HashSet GetDestinationNames() + { + return _destNames ?? (_destNames = (from it in Settings.Resolvers + where it.DestinationMemberName != null + select it.DestinationMemberName.Split('.').First()).ToHashSet()); + } } } \ No newline at end of file diff --git a/src/Mapster/Extensions.cs b/src/Mapster/Extensions.cs index e6579a59..40602eb5 100644 --- a/src/Mapster/Extensions.cs +++ b/src/Mapster/Extensions.cs @@ -25,24 +25,5 @@ public static T GetCustomAttribute(this IMemberModel member) { return (T) member.GetCustomAttributes(true).FirstOrDefault(attr => attr is T); } - - /// - /// Determines whether the specific has default constructor. - /// - /// The type. - /// - /// true if specific has default constructor; otherwise false. - /// - public static bool HasDefaultConstructor(this Type type) - { - if (type == typeof(void) - || type.GetTypeInfo().IsAbstract - || type.GetTypeInfo().IsInterface) - return false; - if (type.GetTypeInfo().IsValueType) - return true; - return type.GetConstructor(Type.EmptyTypes) != null; - } - } } diff --git a/src/Mapster/Mapster.csproj b/src/Mapster/Mapster.csproj index 45ef2742..954cce96 100644 --- a/src/Mapster/Mapster.csproj +++ b/src/Mapster/Mapster.csproj @@ -4,7 +4,7 @@ A fast, fun and stimulating object to object mapper. Kind of like AutoMapper, just simpler and way, way faster. Copyright (c) 2016 Chaowlert Chaisrichalermpol, Eric Swann chaowlert;eric_swann - netstandard1.3;net45;net40 + netstandard2.0;netstandard1.3;net45;net40 Mapster Mapster.snk true @@ -16,9 +16,10 @@ https://github.com/MapsterMapper/Mapster/blob/master/LICENSE 1.6.1 True - 3.3.2 Mapster - 3.3.2.0 + 0 + 3.3.2 + 3.3.2.0 diff --git a/src/Mapster/Settings/SettingStore.cs b/src/Mapster/Settings/SettingStore.cs index f8372e32..213b876b 100644 --- a/src/Mapster/Settings/SettingStore.cs +++ b/src/Mapster/Settings/SettingStore.cs @@ -31,12 +31,12 @@ public void Set(string key, object value) return _booleanStore.GetValueOrDefault(key); } - public T Get(string key) where T : class + public T Get(string key) { return (T)_objectStore.GetValueOrDefault(key); } - public T Get(string key, Func initializer) where T : class + public T Get(string key, Func initializer) { var value = _objectStore.GetValueOrDefault(key); if (value == null) diff --git a/src/Mapster/Settings/ValueAccessingStrategy.cs b/src/Mapster/Settings/ValueAccessingStrategy.cs index 527617ab..f28379aa 100644 --- a/src/Mapster/Settings/ValueAccessingStrategy.cs +++ b/src/Mapster/Settings/ValueAccessingStrategy.cs @@ -75,7 +75,7 @@ private static Expression PropertyOrFieldFn(Expression source, IMemberModel dest var strategy = arg.Settings.NameMatchingStrategy; var destinationMemberName = destinationMember.GetMemberName(arg.Settings.GetMemberNames, strategy.DestinationMemberNameConverter); return members - .Where(member => member.ShouldMapMember(arg.Settings.ShouldMapMember, MemberSide.Source)) + .Where(member => member.ShouldMapMember(arg, MemberSide.Source)) .Where(member => member.GetMemberName(arg.Settings.GetMemberNames, strategy.SourceMemberNameConverter) == destinationMemberName) .Select(member => member.GetExpression(source)) .FirstOrDefault(); @@ -109,7 +109,7 @@ private static Expression GetDeepFlattening(Expression source, string propertyNa var members = source.Type.GetFieldsAndProperties(); foreach (var member in members) { - if (!member.ShouldMapMember(arg.Settings.ShouldMapMember, MemberSide.Source)) + if (!member.ShouldMapMember(arg, MemberSide.Source)) continue; var sourceMemberName = member.GetMemberName(arg.Settings.GetMemberNames, strategy.SourceMemberNameConverter); var propertyType = member.Type; @@ -147,12 +147,12 @@ private static Expression DictionaryFn(Expression source, IMemberModel destinati var args = dictType.GetGenericArguments(); if (strategy.SourceMemberNameConverter != NameMatchingStrategy.Identity) { - var method = typeof(CoreExtensions).GetMethods().First(m => m.Name == nameof(CoreExtensions.FlexibleGet)).MakeGenericMethod(args[1]); + var method = typeof(MapsterHelper).GetMethods().First(m => m.Name == nameof(MapsterHelper.FlexibleGet)).MakeGenericMethod(args[1]); return Expression.Call(method, source.To(dictType), key, Expression.Constant(strategy.SourceMemberNameConverter)); } else { - var method = typeof(CoreExtensions).GetMethods().First(m => m.Name == nameof(CoreExtensions.GetValueOrDefault)).MakeGenericMethod(args); + var method = typeof(MapsterHelper).GetMethods().First(m => m.Name == nameof(MapsterHelper.GetValueOrDefault)).MakeGenericMethod(args); return Expression.Call(method, source.To(dictType), key); } } @@ -167,7 +167,7 @@ private static Expression CustomResolverForDictionaryFn(Expression source, IMemb if (dictType == null) return null; var args = dictType.GetGenericArguments(); - var method = typeof(CoreExtensions).GetMethods().First(m => m.Name == nameof(CoreExtensions.GetValueOrDefault)).MakeGenericMethod(args); + var method = typeof(MapsterHelper).GetMethods().First(m => m.Name == nameof(MapsterHelper.GetValueOrDefault)).MakeGenericMethod(args); Expression getter = null; LambdaExpression lastCondition = null; diff --git a/src/Mapster/TypeAdapterConfig.cs b/src/Mapster/TypeAdapterConfig.cs index b15e4525..02cd64ac 100644 --- a/src/Mapster/TypeAdapterConfig.cs +++ b/src/Mapster/TypeAdapterConfig.cs @@ -81,6 +81,7 @@ private static List CreateRuleTemplate() public bool RequireExplicitMapping { get; set; } public bool AllowImplicitDestinationInheritance { get; set; } public bool AllowImplicitSourceInheritance { get; set; } = true; + public bool SelfContainedCodeGeneration { get; set; } internal static Func DefaultCompiler = lambda => lambda.Compile(); public Func Compiler { get; set; } = DefaultCompiler; @@ -369,12 +370,12 @@ private LambdaExpression CreateDynamicMapExpression(TypeTuple tuple) pNew); } - internal LambdaExpression CreateInlineMapExpression(Type sourceType, Type destinationType, MapType parentMapType, CompileContext context) + internal LambdaExpression CreateInlineMapExpression(Type sourceType, Type destinationType, MapType mapType, CompileContext context) { var tuple = new TypeTuple(sourceType, destinationType); if (context.Running.Contains(tuple)) { - if (parentMapType == MapType.Projection) + if (mapType == MapType.Projection) throw new InvalidOperationException("Projection does not support circular reference"); return CreateMapInvokeExpression(sourceType, destinationType); } @@ -382,18 +383,11 @@ internal LambdaExpression CreateInlineMapExpression(Type sourceType, Type destin context.Running.Add(tuple); try { - var arg = GetCompileArgument(tuple, parentMapType, context); + var arg = GetCompileArgument(tuple, mapType, context); var exp = CreateMapExpression(arg, true); - if (exp != null) - { - var detector = new BlockExpressionDetector(); - detector.Visit(exp); - if (detector.IsBlockExpression) - exp = null; - } if (exp != null) return exp; - if (parentMapType == MapType.MapToTarget) + if (mapType == MapType.MapToTarget) return CreateMapToTargetInvokeExpression(sourceType, destinationType); else return CreateMapInvokeExpression(sourceType, destinationType); @@ -404,7 +398,7 @@ internal LambdaExpression CreateInlineMapExpression(Type sourceType, Type destin } } - private LambdaExpression CreateMapInvokeExpression(Type sourceType, Type destinationType) + internal LambdaExpression CreateMapInvokeExpression(Type sourceType, Type destinationType) { Expression invoker; if (this == GlobalSettings) @@ -424,7 +418,7 @@ private LambdaExpression CreateMapInvokeExpression(Type sourceType, Type destina return Expression.Lambda(invoke, p); } - private LambdaExpression CreateMapToTargetInvokeExpression(Type sourceType, Type destinationType) + internal LambdaExpression CreateMapToTargetInvokeExpression(Type sourceType, Type destinationType) { var method = (from m in typeof(TypeAdapterConfig).GetMethods(BindingFlags.Instance | BindingFlags.Public) where m.Name == nameof(TypeAdapterConfig.GetMapToTargetFunction) diff --git a/src/Mapster/TypeAdapterSetter.cs b/src/Mapster/TypeAdapterSetter.cs index 7bfdaa1d..75caedf4 100644 --- a/src/Mapster/TypeAdapterSetter.cs +++ b/src/Mapster/TypeAdapterSetter.cs @@ -134,10 +134,6 @@ public static TSetter Map( Invoker = invoker, Condition = null }); - setter.Settings.ShouldMapMember.Add((member, side) => - (member.Name == memberName && side == MemberSide.Destination) - ? (bool?)true - : null); return setter; } @@ -152,13 +148,8 @@ public static TSetter Map( { DestinationMemberName = memberName, Invoker = source, - SourceMemberName = ReflectionUtils.GetMemberInfo(source, true)?.Member.Name, Condition = null }); - setter.Settings.ShouldMapMember.Add((member, side) => - (member.Name == memberName && side == MemberSide.Destination) - ? (bool?)true - : null); return setter; } @@ -174,24 +165,6 @@ public static TSetter Map( SourceMemberName = sourceMemberName, Condition = null }); - if (sourceMemberName != destinationMemberName) - { - setter.Settings.ShouldMapMember.Add((member, side) => - (member.Name == destinationMemberName && side == MemberSide.Destination) - ? (bool?)true - : null); - setter.Settings.ShouldMapMember.Add((member, side) => - (member.Name == sourceMemberName && side == MemberSide.Source) - ? (bool?)true - : null); - } - else - { - setter.Settings.ShouldMapMember.Add((member, _) => - member.Name == destinationMemberName - ? (bool?)true - : null); - } return setter; } @@ -237,6 +210,22 @@ public static TSetter GetMemberName(this TSetter setter, Func(this TSetter setter, int? value) where TSetter : TypeAdapterSetter + { + setter.CheckCompiled(); + + setter.Settings.MaxDepth = value; + return setter; + } + + public static TSetter MapToConstructor(this TSetter setter, bool value) where TSetter : TypeAdapterSetter + { + setter.CheckCompiled(); + + setter.Settings.MapToConstructor = value; + return setter; + } } public class TypeAdapterSetter : TypeAdapterSetter @@ -251,7 +240,7 @@ public TypeAdapterSetter Ignore(params Expression Map( { this.CheckCompiled(); - var memberExp = ReflectionUtils.GetMemberInfo(member); var invoker = Expression.Lambda(source.Body, Expression.Parameter(typeof (object))); Settings.Resolvers.Add(new InvokerModel { - DestinationMemberName = memberExp.Member.Name, + DestinationMemberName = ReflectionUtils.GetMemberPath(member), Invoker = invoker, Condition = null }); @@ -279,17 +267,12 @@ public TypeAdapterSetter Map( { this.CheckCompiled(); - var memberExp = ReflectionUtils.GetMemberInfo(destinationMember); Settings.Resolvers.Add(new InvokerModel { - DestinationMemberName = memberExp.Member.Name, + DestinationMemberName = ReflectionUtils.GetMemberPath(destinationMember), SourceMemberName = sourceMemberName, Condition = null }); - Settings.ShouldMapMember.Add((member, side) => - (member.Name == sourceMemberName && side == MemberSide.Source) - ? (bool?)true - : null); return this; } @@ -303,6 +286,22 @@ public TypeAdapterSetter ConstructUsing(Expression BeforeMapping(Action action) + { + this.CheckCompiled(); + + Settings.BeforeMappingFactories.Add(arg => + { + var p1 = Expression.Parameter(arg.SourceType); + var p2 = Expression.Parameter(arg.DestinationType); + var actionType = action.GetType(); + var actionExp = Expression.Constant(action, actionType); + var invoke = Expression.Call(actionExp, "Invoke", null, p2); + return Expression.Lambda(invoke, p1, p2); + }); + return this; + } + public TypeAdapterSetter AfterMapping(Action action) { this.CheckCompiled(); @@ -318,7 +317,6 @@ public TypeAdapterSetter AfterMapping(Action action) }); return this; } - } public class TypeAdapterSetter : TypeAdapterSetter @@ -353,6 +351,11 @@ internal TypeAdapterSetter(TypeAdapterSettings settings, TypeAdapterConfig paren return (TypeAdapterSetter)base.ConstructUsing(constructUsing); } + public new TypeAdapterSetter BeforeMapping(Action action) + { + return (TypeAdapterSetter)base.BeforeMapping(action); + } + public new TypeAdapterSetter AfterMapping(Action action) { return (TypeAdapterSetter)base.AfterMapping(action); @@ -368,7 +371,7 @@ public TypeAdapterSetter IgnoreIf( foreach (var member in members) { - var name = ReflectionUtils.GetMemberInfo(member).Member.Name; + var name = ReflectionUtils.GetMemberPath(member); Settings.IgnoreIfs.Merge(name, condition); } return this; @@ -387,18 +390,26 @@ public TypeAdapterSetter IgnoreIf( return this; } + public TypeAdapterSetter TwoWaysMap( + Expression> member, + Expression> source) + { + this.Map(member, source); + this.Config.ForType() + .Map(source, member); + return this; + } + public TypeAdapterSetter Map( Expression> member, Expression> source, Expression> shouldMap = null) { this.CheckCompiled(); - var memberExp = ReflectionUtils.GetMemberInfo(member); Settings.Resolvers.Add(new InvokerModel { - DestinationMemberName = memberExp.Member.Name, + DestinationMemberName = ReflectionUtils.GetMemberPath(member), Invoker = source, - SourceMemberName = ReflectionUtils.GetMemberInfo(source, true)?.Member.Name, Condition = shouldMap }); return this; @@ -414,13 +425,8 @@ public TypeAdapterSetter Map( { DestinationMemberName = memberName, Invoker = source, - SourceMemberName = ReflectionUtils.GetMemberInfo(source, true)?.Member.Name, Condition = shouldMap }); - Settings.ShouldMapMember.Add((member, side) => - (member.Name == memberName && side == MemberSide.Destination) - ? (bool?)true - : null); return this; } @@ -474,6 +480,22 @@ public TypeAdapterSetter MapToTargetWith(Expression BeforeMapping(Action action) + { + this.CheckCompiled(); + + Settings.BeforeMappingFactories.Add(arg => + { + var p1 = Expression.Parameter(arg.SourceType); + var p2 = Expression.Parameter(arg.DestinationType); + var actionType = action.GetType(); + var actionExp = Expression.Constant(action, actionType); + var invoke = Expression.Call(actionExp, "Invoke", null, p1, p2); + return Expression.Lambda(invoke, p1, p2); + }); + return this; + } + public TypeAdapterSetter AfterMapping(Action action) { this.CheckCompiled(); diff --git a/src/Mapster/TypeAdapterSettings.cs b/src/Mapster/TypeAdapterSettings.cs index aef10c52..ff8d9c85 100644 --- a/src/Mapster/TypeAdapterSettings.cs +++ b/src/Mapster/TypeAdapterSettings.cs @@ -20,6 +20,11 @@ public NameMatchingStrategy NameMatchingStrategy get => Get("NameMatchingStrategy", () => new NameMatchingStrategy()); set => Set("NameMatchingStrategy", value); } + public int? MaxDepth + { + get => Get("MaxDepth"); + set => Set("MaxDepth", value); + } public bool? PreserveReference { @@ -51,6 +56,11 @@ public bool? AvoidInlineMapping get => Get("AvoidInlineMapping"); set => Set("AvoidInlineMapping", value); } + public bool? MapToConstructor + { + get => Get("MapToConstructor"); + set => Set("MapToConstructor", value); + } public List> ShouldMapMember { @@ -64,6 +74,10 @@ public List Resolvers { get => Get("Resolvers", () => new List()); } + public List> BeforeMappingFactories + { + get => Get("BeforeMappingFactories", () => new List>()); + } public List> AfterMappingFactories { get => Get("AfterMappingFactories", () => new List>()); diff --git a/src/Mapster/Utils/CoreExtensions.cs b/src/Mapster/Utils/CoreExtensions.cs index fd24a9a6..c9efa877 100644 --- a/src/Mapster/Utils/CoreExtensions.cs +++ b/src/Mapster/Utils/CoreExtensions.cs @@ -6,59 +6,22 @@ namespace Mapster.Utils { internal static class CoreExtensions { - public static HashSet ToHashSet(this IEnumerable source) - { - return new HashSet(source); - } - public static string ToPascalCase(this string name) { return NameMatchingStrategy.PascalCase(name); } - public static U GetValueOrDefault(this IDictionary dict, T key) - { - return dict.TryGetValue(key, out var value) ? value : default(U); - } - - public static U FlexibleGet(this IDictionary dict, string key, Func keyConverter) +#if !NETCOREAPP2_0 + public static HashSet ToHashSet(this IEnumerable source) { - return (from kvp in dict - where keyConverter(kvp.Key) == key - select kvp.Value).FirstOrDefault(); + return new HashSet(source); } - public static void FlexibleSet(this IDictionary dict, string key, Func keyConverter, U value) + public static U GetValueOrDefault(this IDictionary dict, T key) { - var dictKey = (from kvp in dict - where keyConverter(kvp.Key) == key - select kvp.Key).FirstOrDefault(); - dict[dictKey ?? key] = value; + return dict.TryGetValue(key, out var value) ? value : default(U); } +#endif - public static IEnumerable ToEnumerable(this IEnumerable source) - { - if (source is T[] array) - { - for (int i = 0, count = array.Length; i < count; i++) - { - yield return array[i]; - } - } - else if (source is IList list) - { - for (int i = 0, count = list.Count; i < count; i++) - { - yield return list[i]; - } - } - else - { - foreach (var item in source) - { - yield return item; - } - } - } } } diff --git a/src/Mapster/Utils/ExpressionEx.cs b/src/Mapster/Utils/ExpressionEx.cs index 1eb45b29..a31f97d4 100644 --- a/src/Mapster/Utils/ExpressionEx.cs +++ b/src/Mapster/Utils/ExpressionEx.cs @@ -17,6 +17,13 @@ public static Expression Assign(Expression left, Expression right) return Expression.Assign(left, middle); } + public static Expression Not(Expression exp) + { + if (exp is UnaryExpression unary && unary.NodeType == ExpressionType.Not) + return unary.Operand; + return Expression.Not(exp); + } + public static Expression Apply(this LambdaExpression lambda, params Expression[] exps) { var replacer = new ParameterExpressionReplacer(lambda.Parameters, exps); @@ -209,5 +216,12 @@ public static bool IsSingleValue(this Expression exp) return false; } } + + public static bool IsMultiLine(this LambdaExpression lambda) + { + var detector = new BlockExpressionDetector(); + detector.Visit(lambda); + return detector.IsBlockExpression; + } } } diff --git a/src/Mapster/Utils/MapsterHelper.cs b/src/Mapster/Utils/MapsterHelper.cs new file mode 100644 index 00000000..fe7fccb4 --- /dev/null +++ b/src/Mapster/Utils/MapsterHelper.cs @@ -0,0 +1,54 @@ +using System; +using System.Collections.Generic; +using System.Linq; + +namespace Mapster.Utils +{ + public static class MapsterHelper + { + public static U GetValueOrDefault(IDictionary dict, T key) + { + return dict.TryGetValue(key, out var value) ? value : default(U); + } + + public static U FlexibleGet(IDictionary dict, string key, Func keyConverter) + { + return (from kvp in dict + where keyConverter(kvp.Key) == key + select kvp.Value).FirstOrDefault(); + } + + public static void FlexibleSet(IDictionary dict, string key, Func keyConverter, U value) + { + var dictKey = (from kvp in dict + where keyConverter(kvp.Key) == key + select kvp.Key).FirstOrDefault(); + dict[dictKey ?? key] = value; + } + + public static IEnumerable ToEnumerable(IEnumerable source) + { + if (source is T[] array) + { + for (int i = 0, count = array.Length; i < count; i++) + { + yield return array[i]; + } + } + else if (source is IList list) + { + for (int i = 0, count = list.Count; i < count; i++) + { + yield return list[i]; + } + } + else + { + foreach (var item in source) + { + yield return item; + } + } + } + } +} diff --git a/src/Mapster/Utils/ReflectionUtils.cs b/src/Mapster/Utils/ReflectionUtils.cs index bab901b5..df2cfb62 100644 --- a/src/Mapster/Utils/ReflectionUtils.cs +++ b/src/Mapster/Utils/ReflectionUtils.cs @@ -45,7 +45,7 @@ public static bool CanBeNull(this Type type) return !type.GetTypeInfo().IsValueType || type.IsNullable(); } - public static bool IsPoco(this Type type, BindingFlags accessorFlags = BindingFlags.Public) + public static bool IsPoco(this Type type) { //not nullable if (type.IsNullable()) @@ -55,7 +55,7 @@ public static bool IsPoco(this Type type, BindingFlags accessorFlags = BindingFl if (type.IsConvertible()) return false; - return type.GetFieldsAndProperties(allowNoSetter: false, accessorFlags: accessorFlags).Any(); + return type.GetFieldsAndProperties(allowNoSetter: false).Any(); } public static IEnumerable GetFieldsAndProperties(this Type type, bool allowNoSetter = true, BindingFlags accessorFlags = BindingFlags.Public) @@ -127,30 +127,20 @@ public static Type UnwrapNullable(this Type type) return type.IsNullable() ? type.GetGenericArguments()[0] : type; } - public static MemberExpression GetMemberInfo(Expression member, bool source = false) + public static string GetMemberPath(Expression expr) { - var lambda = member as LambdaExpression; - if (lambda == null) - throw new ArgumentNullException(nameof(member)); - - var expr = lambda.Body; - if (lambda.Body.NodeType == ExpressionType.Convert) - expr = ((UnaryExpression)lambda.Body).Operand; - - MemberExpression memberExpr = null; - if (expr.NodeType == ExpressionType.MemberAccess) + var props = new List(); + expr = expr.TrimConversion(true); + while (expr?.NodeType == ExpressionType.MemberAccess) { - var tmp = (MemberExpression)expr; - if (tmp.Expression?.NodeType == ExpressionType.Parameter) - memberExpr = tmp; - else if (!source) - throw new ArgumentException("Only first level member access on destination allowed (eg. dest => dest.Name)", nameof(member)); + var memEx = (MemberExpression)expr; + props.Add(memEx.Member.Name); + expr = memEx.Expression; } - - if (memberExpr == null && !source) - throw new ArgumentException("Argument must be member access", nameof(member)); - - return memberExpr; + if (props.Count == 0 || expr?.NodeType != ExpressionType.Parameter) + throw new ArgumentException("Allow only member access (eg. obj => obj.Child.Name)", nameof(expr)); + props.Reverse(); + return string.Join(".", props); } public static bool IsReferenceAssignableFrom(this Type destType, Type srcType) @@ -269,10 +259,15 @@ public static AccessModifier GetAccessModifier(this MethodBase methodBase) return AccessModifier.Private; } - public static bool ShouldMapMember(this IMemberModel member, IEnumerable> predicates, MemberSide side) + public static bool ShouldMapMember(this IMemberModel member, CompileArgument arg, MemberSide side) { - return predicates.Select(predicate => predicate(member, side)) - .FirstOrDefault(result => result != null) == true; + var predicates = arg.Settings.ShouldMapMember; + var result = predicates.Select(predicate => predicate(member, side)) + .FirstOrDefault(it => it != null); + if (result != null) + return result == true; + var names = side == MemberSide.Destination ? arg.GetDestinationNames() : arg.GetSourceNames(); + return names.Contains(member.Name); } public static string GetMemberName(this IMemberModel member, List> getMemberNames, Func nameConverter) @@ -293,5 +288,24 @@ public static Expression CreateDefault(this Type type) ? Expression.Constant(null, type) : Expression.Constant(Activator.CreateInstance(type), type); } + + /// + /// Determines whether the specific has default constructor. + /// + /// The type. + /// + /// true if specific has default constructor; otherwise false. + /// + public static bool HasDefaultConstructor(this Type type) + { + if (type == typeof(void) + || type.GetTypeInfo().IsAbstract + || type.GetTypeInfo().IsInterface) + return false; + if (type.GetTypeInfo().IsValueType) + return true; + return type.GetConstructor(Type.EmptyTypes) != null; + } + } } \ No newline at end of file