diff --git a/ImpromptuInterface/src/EmitProxy/ActLikeMaker.cs b/ImpromptuInterface/src/EmitProxy/ActLikeMaker.cs index f985351c..0934cca2 100644 --- a/ImpromptuInterface/src/EmitProxy/ActLikeMaker.cs +++ b/ImpromptuInterface/src/EmitProxy/ActLikeMaker.cs @@ -8,7 +8,6 @@ using System.Reflection; using System.Reflection.Emit; using System.Runtime.CompilerServices; -using Dynamitey; using ImpromptuInterface.Optimization; using Microsoft.CSharp.RuntimeBinder; @@ -57,7 +56,7 @@ public dynamic ActLike(object originalDynamic, params Type[] otherInterfaces) public TInterface Create(params object[] args) where TInterface : class { - return this.ActLike(Dynamic.InvokeConstructor(typeof(TTarget), args)); + return this.ActLike(DynamicConstructor.Invoke(typeof(TTarget), args)); } public IEnumerable AllActLike(IEnumerable originalDynamic, params Type[] otherInterfaces) where TInterface : class @@ -544,6 +543,43 @@ private object CustomAttributeTypeArgument(CustomAttributeTypedArgument argument } + private static readonly Type[] FuncKinds = + { + typeof(Func<>), typeof(Func<,>), typeof(Func<,,>), typeof(Func<,,,>), typeof(Func<,,,,>), + typeof(Func<,,,,,>), typeof(Func<,,,,,,>), typeof(Func<,,,,,,,>), typeof(Func<,,,,,,,,>), + typeof(Func<,,,,,,,,,>), typeof(Func<,,,,,,,,,,>), typeof(Func<,,,,,,,,,,,>), + typeof(Func<,,,,,,,,,,,,>), typeof(Func<,,,,,,,,,,,,,>), typeof(Func<,,,,,,,,,,,,,,>), + typeof(Func<,,,,,,,,,,,,,,,>), typeof(Func<,,,,,,,,,,,,,,,,>) + }; + + private static readonly Type[] ActionKinds = + { + typeof(Action), typeof(Action<>), typeof(Action<,>), typeof(Action<,,>), typeof(Action<,,,>), + typeof(Action<,,,,>), typeof(Action<,,,,,>), typeof(Action<,,,,,,>), typeof(Action<,,,,,,,>), + typeof(Action<,,,,,,,,>), typeof(Action<,,,,,,,,,>), typeof(Action<,,,,,,,,,,>), + typeof(Action<,,,,,,,,,,,>), typeof(Action<,,,,,,,,,,,,>), typeof(Action<,,,,,,,,,,,,,>), + typeof(Action<,,,,,,,,,,,,,,>), typeof(Action<,,,,,,,,,,,,,,,>) + }; + + /// + /// The open `Func`/`Action` of that shape. `paramCount` counts the return type for a + /// `Func`, as the caller's list does. + /// + private static Type GenericDelegateType(int paramCount, bool returnVoid = false) + { + var count = returnVoid ? paramCount : paramCount - 1; + if (count > 16) + throw new ArgumentException( + $"{(returnVoid ? "Action" : "Func")} only handles at most {(returnVoid ? 16 : 17)} parameters", + nameof(paramCount)); + if (count < 0) + throw new ArgumentException( + $"{(returnVoid ? "Action" : "Func")} must have at least {(returnVoid ? 0 : 1)} parameter(s)", + nameof(paramCount)); + + return returnVoid ? ActionKinds[count] : FuncKinds[count]; + } + private CustomAttributeBuilder GetAttributeBuilder(CustomAttributeData data) { var tPropertyInfos = new List(); @@ -1705,7 +1741,7 @@ internal Type GenerateCallSiteFuncType(IEnumerable argTypes, Type returnTy if (tIsFunc) tList.Add(returnType); - var tFuncGeneric = Dynamitey.Dynamic.GenericDelegateType(tList.Count, !tIsFunc); + var tFuncGeneric = GenericDelegateType(tList.Count, !tIsFunc); var tFuncType = tFuncGeneric.MakeGenericType(tList.ToArray()); diff --git a/ImpromptuInterface/src/Optimization/BareBonesList.cs b/ImpromptuInterface/src/Optimization/BareBonesList.cs deleted file mode 100644 index ca3149ad..00000000 --- a/ImpromptuInterface/src/Optimization/BareBonesList.cs +++ /dev/null @@ -1,133 +0,0 @@ -// -// Copyright 2011 Ekon Benefits -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -using System; -using System.Collections; -using System.Collections.Generic; - -namespace ImpromptuInterface.Optimization -{ - internal class BareBonesList: ICollection - { - private T[] _list; - private int _addIndex; - - private int _length; - - - /// - /// Initializes a new instance of the class. - /// - /// The max length that the list cannot grow beyound - public BareBonesList(int length) - { - _list = new T[length]; - _length = length; - } - - public void Add(T item) - { - _list[_addIndex++] = item; - } - - public void Clear() - { - throw new NotSupportedException(); - } - - public bool Contains(T item) - { - throw new NotSupportedException(); - } - - public void CopyTo(T[] array, int arrayIndex) - { - Array.Copy(_list,arrayIndex,array,0,_length); - } - - public bool Remove(T item) - { - throw new NotSupportedException(); - } - - public int Count - { - get { return _length; } - } - - public bool IsReadOnly - { - get { return false; } - } - - /// - /// Gets the enumerator. with bare bones this is good only once - /// - /// - public IEnumerator GetEnumerator() - { - return new BareBonesEnumerator(_list,_addIndex); - } - - IEnumerator IEnumerable.GetEnumerator() - { - return GetEnumerator(); - } - - - internal class BareBonesEnumerator : IEnumerator - - { - private T[] _list; - private int _enumerateInex = -1; - private int _length; - - public BareBonesEnumerator(T[] list, int length) - { - _list = list; - _length = length; - } - - public void Dispose() - { - - } - - public bool MoveNext() - { - _enumerateInex++; - return _enumerateInex < _length; - } - - public void Reset() - { - _enumerateInex = 0; - } - - public T Current - { - get { return _list[_enumerateInex]; } - } - - object IEnumerator.Current - { - get { return Current; } - } - } - - } - - -} \ No newline at end of file diff --git a/ImpromptuInterface/src/Optimization/BinderHash.cs b/ImpromptuInterface/src/Optimization/BinderHash.cs deleted file mode 100644 index 57b47a80..00000000 --- a/ImpromptuInterface/src/Optimization/BinderHash.cs +++ /dev/null @@ -1,152 +0,0 @@ -// -// Copyright 2011 Ekon Benefits -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using Dynamitey; - -namespace ImpromptuInterface.Optimization -{ - internal class BinderHash - { - - - protected BinderHash(Type delegateType, String_OR_InvokeMemberName name, Type context, string[] argNames, Type binderType, bool staticContext, bool isEvent, bool knownBinder) - { - KnownBinder = knownBinder; - BinderType = binderType; - StaticContext = staticContext; - DelegateType = delegateType; - Name = name; - Context = context; - ArgNames = argNames; - IsEvent = isEvent; - - } - - - - public static BinderHash Create(Type delType, String_OR_InvokeMemberName name, Type context, string[] argNames, Type binderType, bool staticContext, bool isEvent, bool knownBinder) - { - return new BinderHash(delType, name, context, argNames, binderType, staticContext, isEvent, knownBinder); - } - - public bool KnownBinder { get; protected set; } - public Type BinderType { get; protected set; } - public bool StaticContext { get; protected set; } - public bool IsEvent { get; protected set; } - public Type DelegateType { get; protected set; } - public String_OR_InvokeMemberName Name { get; protected set; } - public Type Context { get; protected set; } - public string[] ArgNames { get; protected set; } - - public virtual bool Equals(BinderHash other) - { - if (ReferenceEquals(null, other)) return false; - if (ReferenceEquals(this, other)) return true; - - var tArgNames = ArgNames; - var tOtherArgNames = other.ArgNames; - - return - !(tOtherArgNames == null ^ tArgNames == null) - && other.IsEvent == IsEvent - && other.StaticContext == StaticContext - && Equals(other.Context, Context) - && (KnownBinder || Equals(other.BinderType, BinderType)) - && Equals(other.DelegateType, DelegateType) - && Equals(other.Name, Name) - && (tArgNames == null - // ReSharper disable AssignNullToNotNullAttribute - //Exclusive Or Makes Sure this doesn't happen - - || tOtherArgNames.SequenceEqual(tArgNames)); - // ReSharper restore AssignNullToNotNullAttribute - } - - - public override bool Equals(object obj) - { - if (ReferenceEquals(null, obj)) return false; - if (ReferenceEquals(this, obj)) return true; - if (!(obj is BinderHash)) return false; - return Equals((BinderHash) obj); - } - - public override int GetHashCode() - { - unchecked - { - var tArgNames = ArgNames; - - int result = (tArgNames == null ? 0 : tArgNames.Length * 397); - result = (result ^ StaticContext.GetHashCode()); - result = (result * 397) ^ DelegateType.GetHashCode(); - result = (result * 397) ^ Context.GetHashCode(); - result = (result * 397) ^ Name.GetHashCode(); - return result; - } - } - } - - internal class GenericBinderHashBase : BinderHash - { - protected GenericBinderHashBase(Type delegateType, String_OR_InvokeMemberName name, Type context, string[] argNames, Type binderType, bool staticContext, bool isEvent, bool knownBinder) - : base(delegateType, name, context, argNames, binderType, staticContext, isEvent, knownBinder) - { - } - } - - internal class BinderHash : GenericBinderHashBase where T : class - { - - public static BinderHash Create(String_OR_InvokeMemberName name, Type context, string[] argNames, Type binderType, bool staticContext, bool isEvent, bool knownBinder) - { - return new BinderHash(name, context, argNames, binderType, staticContext, isEvent, knownBinder); - } - - protected BinderHash(String_OR_InvokeMemberName name, Type context, string[] argNames, Type binderType, bool staticContext, bool isEvent,bool knownBinder) - : base(typeof(T), name, context, argNames, binderType, staticContext, isEvent,knownBinder) - { - } - - - public override bool Equals(BinderHash other) - { - if (other is GenericBinderHashBase) - { - if (other is BinderHash) - { - return - !(other.ArgNames == null ^ ArgNames == null) - && other.IsEvent == IsEvent - && other.StaticContext == StaticContext - && (KnownBinder || Equals(other.BinderType, BinderType)) - && Equals(other.Context, Context) - && Equals(other.Name, Name) - && (ArgNames == null - // ReSharper disable AssignNullToNotNullAttribute - //Exclusive Or Makes Sure this doesn't happen - || other.ArgNames.SequenceEqual(ArgNames)); - // ReSharper restore AssignNullToNotNullAttribute - } - return false; - } - return base.Equals(other); - } - } -} diff --git a/ImpromptuInterface/src/Optimization/DynamicConstructor.cs b/ImpromptuInterface/src/Optimization/DynamicConstructor.cs new file mode 100644 index 00000000..f615a9f3 --- /dev/null +++ b/ImpromptuInterface/src/Optimization/DynamicConstructor.cs @@ -0,0 +1,81 @@ +// +// Copyright 2011 Ekon Benefits +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.Linq; +using System.Linq.Expressions; +using Microsoft.CSharp.RuntimeBinder; +using Binder = Microsoft.CSharp.RuntimeBinder.Binder; + +namespace ImpromptuInterface.Optimization +{ + /// + /// `new T(args)` with the constructor chosen by the arguments' runtime types, as C#'s + /// `new T(dynamicArg)` does — rather than by , whose overload + /// resolution is not the same. + /// + /// + /// The call site is built once per (type, argument count) and cached: the shape is what a + /// site is compiled for, and the arguments' runtime types are what it dispatches on. + /// + internal static class DynamicConstructor + { + private static readonly ConcurrentDictionary, Func> _sites = + new ConcurrentDictionary, Func>(); + + /// Constructs with . + internal static object Invoke(Type type, params object[] args) + { + if (type == null) throw new ArgumentNullException(nameof(type)); + args = args ?? new object[0]; + + // A dynamic invocation does not see a value type's parameterless constructor. + if (args.Length == 0 && type.IsValueType) + return Activator.CreateInstance(type); + + var site = _sites.GetOrAdd(Tuple.Create(type, args.Length), key => Compile(key.Item1, key.Item2)); + return site(args); + } + + private static Func Compile(Type type, int count) + { + var argsParameter = Expression.Parameter(typeof(object[]), "args"); + + // The type is the site's first argument, as a static type; each real argument + // arrives as object, so the binder dispatches on its runtime type. + var infos = new List + { + CSharpArgumentInfo.Create( + CSharpArgumentInfoFlags.IsStaticType | CSharpArgumentInfoFlags.UseCompileTimeType, null) + }; + var arguments = new List { Expression.Constant(type, typeof(Type)) }; + + for (var i = 0; i < count; i++) + { + infos.Add(CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null)); + arguments.Add(Expression.ArrayIndex(argsParameter, Expression.Constant(i))); + } + + var call = Expression.Dynamic( + Binder.InvokeConstructor(CSharpBinderFlags.None, type, infos), + typeof(object), + arguments); + + return Expression.Lambda>(call, argsParameter).Compile(); + } + } +}