private static ReadOnlyCollection <Type> GetConcreteTypesCore(Type genericType, LinkList <Binding> bindings)
        {
            Debug.Assert(genericType != null);
            Debug.Assert(bindings != null);

            bool cached  = concreteTypeCache_.ContainsKey(genericType);
            bool unbound = genericType.GetGenericArguments( )
                           .All((a) => !Binding.ContainsArgument(bindings, a));

            // If the type has already been evaluated and there are no interfering bindings, return cached value.
            if (cached && unbound)
            {
                return(concreteTypeCache_[genericType]);
            }


            // Otherwise, get a concrete type for each set of bindings.
            LinkList <Type>   openArguments;
            BindingCollection concreteTypeBindngs = GenericTypeResolver.GetConcreteTypeBindings(genericType, bindings, out openArguments);
            var concreteTypes = concreteTypeBindngs
                                .Transform((argumentBindings) => MakeConcreteType(genericType, openArguments, argumentBindings))
                                .ToReadOnlyCollection( );

            // If there are no interfering bindings, cache the concrete types.
            if (!cached && unbound)
            {
                concreteTypeCache_.TryAdd(genericType, concreteTypes);
                concreteTypes = concreteTypeCache_[genericType];
            }

            return(concreteTypes);
        }
Esempio n. 2
0
        public void ctor_WithNoArguments_ReturnsEmptyCollection( )
        {
            var collection = new BindingCollection( );

            Assert.Equal(collection.Count, 0);
            Assert.Empty(collection);
        }
        private static IEnumerable <IInstanceCreator> GetGenericCreators(Type targetType, Type genericType)
        {
            Debug.Assert(targetType != null);
            Debug.Assert(genericType != null);
            Debug.Assert(genericType.ContainsGenericParameters);

            // Get all bindings for the generic type's arguments that satisfy the inheritance constraint.
            var openArguments = GenericTypeResolver.GetOpenGenericArguments(genericType);

            Assembly[]            referenceAssemblies;
            LinkList <Constraint> inheritanceConstraints =
                targetType.IsGenericParameter
                    ? Constraint.GetConstraints(targetType, out referenceAssemblies)
                    : Constraint.GetInheritanceConstraint(targetType).MakeLinkList( );
            var argumentBindings = new BindingCollection(Binding.EmptyBindings);

            Constraint.SatisfyConstraints(argumentBindings, genericType, inheritanceConstraints);

            // Construct concrete types for each set of argument bindings,
            //  and return the creators for each concrete type.
            var creators =
                from arguments in argumentBindings
                let concreteType = GenericTypeResolver.CreateConcreteType(genericType, openArguments, arguments)
                                   where concreteType != null
                                   from creator in TypeCreator.GetInstanceCreators(targetType, concreteType)
                                   select creator;

            return(creators);
        }
        /// <summary>
        /// Retrieves all bindings satisfying the constraints for the specified <see cref="Type"/>.
        /// </summary>
        public static void SatisfyConstraints(BindingCollection bindings, Type type, LinkList <Constraint> constraints)
        {
            Debug.Assert(bindings != null);
            Debug.Assert(type != null);
            Debug.Assert(constraints != null);

            bindings.Reduce(constraints, (b, c) => c.SatisfyCore(type, b));
        }
Esempio n. 5
0
        public void ctor_GivenSingleBinding_InitializesCollectionWithBinding( )
        {
            var expected = List(typeof(int));

            var collection = new BindingCollection(expected);

            Assert.Equal(collection.Count, 1);
            Assert.Same(Assert.Single(collection), expected);
        }
        /// <summary>
        /// Returns bindings for all assigned generic arguments in the specified list of bindings.
        /// </summary>
        public static void GetAssignedGenericArguments(BindingCollection bindings, Type concreteType, Type genericType)
        {
            Debug.Assert(bindings != null);
            Debug.Assert(concreteType != null);
            Debug.Assert(genericType != null);
            Debug.Assert(concreteType.Is(genericType));

            IEnumerable <Tuple <Type, Type> > concreteTypes = GetConcreteTypes(concreteType, genericType);

            bindings.Expand(concreteTypes, (currentBindings, tuple) => {
                Type type                  = tuple.Item1;
                Type generic               = tuple.Item2;
                Type[] assignedArguments   = type.GetGenericArguments( );
                Type[] unassignedArguments = generic.GetGenericArguments( );
                Debug.Assert(assignedArguments.Length == unassignedArguments.Length);

                for (int i = 0; currentBindings.Count > 0 && i < unassignedArguments.Length; ++i)
                {
                    Type unassignedArgument = unassignedArguments[i];
                    Type assignedArgument   = assignedArguments[i];

                    if (assignedArgument.IsGenericParameter)
                    {
                        continue;
                    }

                    if (!unassignedArgument.IsGenericParameter)
                    {
                        if (unassignedArgument.ContainsGenericParameters)
                        {
                            GenericTypeResolver.GetAssignedGenericArguments(currentBindings, assignedArgument, unassignedArgument);
                        }
                        continue;
                    }

                    if (!assignedArgument.Is(unassignedArgument))
                    {
                        currentBindings.Clear( );
                        break;
                    }

                    currentBindings.Reduce(b => {
                        Binding existingBinding = Binding.ForArgument(b, unassignedArgument);
                        return(existingBinding == null
                             ? b.Add(new Binding(unassignedArgument, assignedArgument))
                             : (existingBinding.Type == assignedArgument ? b : null));
                    });
                }

                if (genericType.IsGenericParameter)
                {
                    currentBindings.Reduce(b => b.Add(new Binding(genericType, concreteType)));
                }
            });
        }
Esempio n. 7
0
        public void Transform_GivenItemTransformer_RemovesDuplicateResults( )
        {
            var initial    = new[] { List(typeof(double)), List(typeof(double)) };
            var expected   = new[] { initial[1].Value };
            var collection = new BindingCollection(initial);

            var results = collection.Transform((b) => b.Value);
            var actual  = results.ToArray( );

            Assert.Equal(actual, expected);
        }
Esempio n. 8
0
        public void Reduce_GivenCollectionProcessor_UpdatesBindingsAgainstAllInputs( )
        {
            var initial    = List(typeof(int));
            var expected   = new[] { List(typeof(Tuple <Tuple <int> >)) };
            var collection = new BindingCollection(initial);

            collection.Reduce(Enumerable.Repeat(1, 2), (b, i) => new[] { List(typeof(Tuple <>).MakeGenericType(b.Value.Type)) });
            var actual = collection.ToArray( );

            Assert.Equal(actual, expected);
        }
Esempio n. 9
0
        public void Expand_GivenCollectionProcessor_UpdatesWithAllBindings( )
        {
            var initial    = List(typeof(int));
            var expected   = new[] { List(typeof(Tuple <int>)), List(typeof(Tuple <int>)) };
            var collection = new BindingCollection(initial);

            collection.Expand(Enumerable.Repeat(1, 2), (bs, i) => bs.Reduce(b => List(typeof(Tuple <>).MakeGenericType(b.Value.Type))));
            var actual = collection.ToArray( );

            Assert.Equal(actual, expected);
        }
Esempio n. 10
0
        public void Reduce_GivenCollectionProcessor_UpdatesAllBindings( )
        {
            var initial    = List(typeof(int));
            var expected   = new[] { List(typeof(Tuple <int>)) };
            var collection = new BindingCollection(initial);

            collection.Reduce((b) => new[] { List(typeof(Tuple <>).MakeGenericType(b.Value.Type)) });
            var actual = collection.ToArray( );

            Assert.Equal(actual, expected);
        }
Esempio n. 11
0
        public void Reduce_GivenItemProcessor_RemovesBindingsWhenProcessorReturnsNull( )
        {
            var initial    = new[] { List(typeof(int)), List(typeof(double)) };
            var expected   = new[] { initial[1] };
            var collection = new BindingCollection(initial);

            collection.Reduce(Enumerable.Repeat(1, 2), (b, i) => i == 1 && b.Value.Type == typeof(int) ? null : b);
            var actual = collection.ToArray( );

            Assert.Equal(actual, expected);
        }
Esempio n. 12
0
        public void ctor_GivenMultipleBindings_InitializesCollectionWithBindings( )
        {
            var a        = List(typeof(int));
            var b        = List(typeof(double));
            var c        = List(typeof(DateTime));
            var expected = new[] { a, b, c };

            var collection = new BindingCollection(expected);
            var actual     = collection.ToArray( );

            Assert.Equal(actual, expected);
        }
        private static IEnumerable <IInstanceCreator> GetMethodCreators(Type targetType, MethodBase method)
        {
            Debug.Assert(targetType != null);
            Debug.Assert(method != null);
            Debug.Assert(method.IsGenericMethod || !targetType.ContainsGenericParameters);

            // Ignore recursive parameters.
            var parameters = method.GetParameters( );

            if (parameters.Any(p => p.ParameterType.Is(targetType) || p.ParameterType.Is(method.DeclaringType)))
            {
                yield break;
            }

            // Retrieve creators for each parameter.
            var availableArguments = parameters.Select((p) => TypeCreator.GetInstanceCreators(p.ParameterType).AsEnumerable( ));

            // Call constructor with all argument permutations.
            foreach (var arguments in Permuter.Permute(availableArguments))
            {
                // If method is concrete, use it.
                if (!method.IsGenericMethod)
                {
                    yield return(WeakInstanceCreator.ForMethod(targetType, method, arguments));
                }
                // Otherwise, try to resolve generic arguments on method.
                else if (method is MethodInfo)
                {
                    var methodInfo = (MethodInfo)method;
                    var bindings   = new BindingCollection(Binding.EmptyBindings);
                    for (int i = 0; i < parameters.Length; ++i)
                    {
                        ParameterInfo    parameter = parameters[i];
                        IInstanceCreator argument  = arguments[i];
                        if (parameter.ParameterType.ContainsGenericParameters)
                        {
                            GenericTypeResolver.GetAssignedGenericArguments(bindings, argument.InstanceType, parameter.ParameterType);
                        }
                    }

                    foreach (LinkList <Binding> b in bindings)
                    {
                        var concreteMethod = GenericTypeResolver.MakeConcreteMethod(methodInfo, b);
                        if (concreteMethod != null)
                        {
                            targetType = concreteMethod.ReturnType;
                            yield return(WeakInstanceCreator.ForMethod(targetType, concreteMethod, arguments));
                        }
                    }
                }
            }
        }
Esempio n. 14
0
        public void Satisfy_returns_expected_result(Type sourceType, Type boundType, bool isSatisfied)
        {
            Type argumentType = sourceType.GetGenericArguments( )[0];

            Assembly[] referencedAssemblies;

            var constraints = Constraint.GetConstraints(argumentType, out referencedAssemblies);
            var bindings    = new BindingCollection(Binding.EmptyBindings);

            Constraint.SatisfyConstraints(bindings, boundType, constraints);
            bool satisfied = bindings.Any( );

            Assert.Equal(isSatisfied, satisfied);
        }
        private static IEnumerable <IInstanceCreator> GetConstructorCreators(Type targetType, Type availableType)
        {
            Debug.Assert(targetType != null);
            Debug.Assert(availableType != null);
            Debug.Assert(!availableType.IsAbstract);

            if (targetType.ContainsGenericParameters)
            {
                Type definition = targetType.IsGenericParameter ? targetType : targetType.GetGenericTypeDefinition( );
                var  bindings   = new BindingCollection(Binding.EmptyBindings);
                GenericTypeResolver.GetAssignedGenericArguments(bindings, availableType, definition);

                foreach (var binding in bindings)
                {
                    Type resolvedType =
                        definition.IsGenericParameter
                            ? Binding.ForArgument(binding, definition).Type
                            : GenericTypeResolver.MakeConcreteType(definition, binding);

                    targetType = resolvedType;
                    break;
                }
            }

            var creators = new List <IInstanceCreator>( );

            // If type is an enumeration, get creator for enum values.
            if (availableType.IsEnum || availableType == typeof(bool))
            {
                creators.AddRange(WeakInstanceCreator.ForEnum(availableType));
            }
            // Otherwise, get creator for any default constructor.
            else if (Constraint.HasDefaultConstructor(availableType))
            {
                creators.Add(WeakInstanceCreator.ForType(availableType));
            }

            // Get creators for any parameterized constructors.
            var parameterizedConstructors = availableType.GetConstructors( ).Where((c) => c.GetParameters( ).Length > 0).ToArray( );

            if (parameterizedConstructors.Length < 3)
            {
                foreach (var constructor in parameterizedConstructors)
                {
                    creators.AddRange(TypeCreator.GetMethodCreators(targetType, constructor));
                }
            }

            return(creators);
        }
        private static void BindGenericArguments(BindingCollection bindings, LinkList <Type> openArguments)
        {
            Debug.Assert(bindings != null);
            Debug.Assert(openArguments != null);

            foreach (Type argument in openArguments)
            {
                // Get all types satisfying the current constraint.
                Assembly[] referenceAssemblies;
                var        constraints = Constraint.GetConstraints(argument, out referenceAssemblies);

                // If the argument has no limiting constraints, skip it.
                if (constraints.IsEmpty || referenceAssemblies.Length == 0)
                {
                    continue;
                }


                // Add each type satisfying the current generic argument to the list of bindings.
                bool onlyUsageConstraints = constraints.All((c) => c.IsUsageConstraint);
                bindings.Expand(TypeLoader.GetUsableTypes(referenceAssemblies), (constraintBindings, type) => {
                    LinkList <Type> openTypeArguments = GetOpenGenericArguments(type);
                    Constraint.SatisfyConstraints(constraintBindings, type, constraints);
                    constraintBindings.Reduce(constraintBinding => {
                        Type concreteType = MakeConcreteType(type, openTypeArguments, constraintBinding);
                        if (concreteType == null)
                        {
                            return(null);
                        }
                        else if (onlyUsageConstraints || Binding.ContainsArgument(constraintBinding, argument))
                        {
                            return(constraintBinding);
                        }
                        else
                        {
                            return(constraintBinding.Add(new Binding(argument, concreteType)));
                        }
                    });
                });

                if (bindings.Count == 0)
                {
                    break;
                }
            }
        }
        private static ICollection <MethodInfo> GetConcreteMethods(MethodInfo method, LinkList <Binding> bindings)
        {
            Debug.Assert(method != null);
            Debug.Assert(bindings != null);


            // Try to resolve generic arguments on method.
            var openArguments    = GenericTypeResolver.GetOpenGenericArguments(method.GetGenericArguments( ));
            var concreteBindings = new BindingCollection(bindings);

            GenericTypeResolver.BindGenericArguments(concreteBindings, openArguments);

            var concreteMethods = concreteBindings.Transform((b) => MakeConcreteMethod(method, openArguments, b));


            // If generic arguments cannot be resolved statically, try to bind method arguments by searching for creatable parameter types.
            if (concreteMethods.Count == 0)
            {
                var genericParameterTypes = method.GetParameters( )
                                            .Select(p => p.ParameterType)
                                            .Where(t => t.IsGenericType)
                                            .ToArray( );
                Debug.Assert(genericParameterTypes.All(t => !t.IsGenericParameter));

                var creatableParameterTypes = genericParameterTypes
                                              .Select(t => TypeCreator.GetCreators(t)
                                                      .Select(c => c.InstanceType)
                                                      .Distinct( )
                                                      );

                var parameterBindings = new BindingCollection(bindings);
                parameterBindings.Expand(Permuter.Permute(creatableParameterTypes), (b, permutation) => {
                    for (int i = 0; i < permutation.Length; ++i)
                    {
                        Type permutationType      = permutation[i];
                        Type genericParameterType = genericParameterTypes[i];
                        GenericTypeResolver.GetAssignedGenericArguments(b, permutationType, genericParameterType);
                    }
                });

                concreteMethods = parameterBindings.Transform((b) => MakeConcreteMethod(method, openArguments, b));
            }


            return(concreteMethods);
        }
        /// <summary>
        /// Expands the collection of bindings with the results from the specified input.
        /// </summary>
        public void Expand <T>(IEnumerable <T> input, Action <BindingCollection, T> processor)
        {
            Debug.Assert(input != null);
            Debug.Assert(processor != null);

            // Save current set of bindings.
            var currentBindings = new LinkList <Binding> [this.bindings_.Count];

            this.bindings_.CopyTo(currentBindings);
            this.bindings_.Clear( );

            // Get new bindings from all input items.
            foreach (T item in input)
            {
                BindingCollection newBindings = new BindingCollection(currentBindings);
                processor(newBindings, item);
                this.bindings_.AddRange(newBindings);
            }
        }
Esempio n. 19
0
            protected override IEnumerable <LinkList <Binding> > SatisfyCore(Type availableType, LinkList <Binding> bindings)
            {
                var newBindings    = new List <LinkList <Binding> >( );
                var currentBindngs = new BindingCollection(bindings);

                // Check if the available type derives from the base type.
                if (availableType.Is(this.requiredBaseType_))
                {
                    // Add any generic arguments assigned by the base type.
                    if (this.requiredBaseType_.IsGenericType && !this.requiredBaseType_.ContainsGenericParameters)
                    {
                        IEnumerable <Type> correspondingTypes = GenericTypeResolver.GetCorrespondingBaseTypes(availableType, this.requiredBaseType_);
                        foreach (Type correspondingType in correspondingTypes)
                        {
                            if (correspondingType.ContainsGenericParameters)
                            {
                                GenericTypeResolver.GetAssignedGenericArguments(currentBindngs, this.requiredBaseType_, correspondingType);
                            }
                        }
                    }

                    // Check all concrete version of the available type.
                    foreach (LinkList <Binding> b in currentBindngs)
                    {
                        var concreteTypes = GenericTypeResolver.GetConcreteTypes(availableType, b);
                        foreach (Type concreteAvailableType in concreteTypes)
                        {
                            // Add any newly assigned bindings from concrete and base types.
                            var assignedBindings = new BindingCollection(b);
                            GenericTypeResolver.GetAssignedGenericArguments(assignedBindings, concreteAvailableType, availableType);
                            if (this.requiredBaseType_.ContainsGenericParameters)
                            {
                                GenericTypeResolver.GetAssignedGenericArguments(assignedBindings, concreteAvailableType, this.requiredBaseType_);
                            }

                            newBindings.AddRange(assignedBindings);
                        }
                    }
                }

                return(newBindings);
            }
        private static BindingCollection GetConcreteTypeBindings(Type type, LinkList <Binding> bindings, out LinkList <Type> openArguments)
        {
            Debug.Assert(type != null);
            Debug.Assert(bindings != null);


            // Avoid recursive searches for generic type.
            if (type.ContainsGenericParameters)
            {
                if (Binding.ContainsType(bindings, type))
                {
                    openArguments = LinkList <Type> .Empty;
                    return(new BindingCollection( ));
                }
                bindings = bindings.Add(new Binding(null, type));
            }

            // Bind all unassigned generic argument on the generic type.
            openArguments = GenericTypeResolver.GetOpenGenericArguments(type);
            var collection = new BindingCollection(bindings);

            GenericTypeResolver.BindGenericArguments(collection, openArguments);
            return(collection);
        }