internal static bool IsAssemblyQualifiedNameAssignableFrom(Type t1, Type t2)
 {
     if ((t1 == null) || (t2 == null))
     {
         return false;
     }
     if (!AssemblyQualifiedNameEquals(t1, t2))
     {
         if (IsLooseSubClassOf(t2, t1))
         {
             return true;
         }
         if (t1.IsInterface)
         {
             return LooselyImplementInterface(t2, t1);
         }
         if (!t1.IsGenericParameter)
         {
             return false;
         }
         Type[] genericParameterConstraints = t1.GetGenericParameterConstraints();
         for (int i = 0; i < genericParameterConstraints.Length; i++)
         {
             if (!IsAssemblyQualifiedNameAssignableFrom(genericParameterConstraints[i], t2))
             {
                 return false;
             }
         }
     }
     return true;
 }
Ejemplo n.º 2
0
        private IAstTypeReference RecursionSafeReflect(Type type, IDictionary<Type, IAstTypeReference> alreadyReflected)
        {
            var reflected = alreadyReflected.GetValueOrDefault(type);
            if (reflected != null)
                return reflected;

            if (type == typeof(object))
                return AstAnyType.Instance;

            if (type.IsGenericParameter) {
                var constraints = type.GetGenericParameterConstraints();
                return new AstGenericPlaceholderType(
                    type.Name,
                    p => {
                        alreadyReflected.Add(type, p);
                        return constraints.Select(c => this.RecursionSafeReflect(c, alreadyReflected));
                    },
                    target: type
                );
            }

            if (IsFunctionType(type))
                return ReflectFunctionType(type, alreadyReflected);

            if (type.IsGenericType && !type.IsGenericTypeDefinition)
                return ReflectGenericType(type, alreadyReflected);

            return new AstReflectedType(type, this);
        }
Ejemplo n.º 3
0
		public static GenericConstraints GetConstraints (Type t)
		{
			Type [] constraints = t.GetGenericParameterConstraints ();
			GenericParameterAttributes attrs = t.GenericParameterAttributes;
			if (constraints.Length == 0 && attrs == GenericParameterAttributes.None)
				return null;
			return new ReflectionConstraints (t.Name, constraints, attrs);
		}
Ejemplo n.º 4
0
		private static bool CheckGenericTypeConstraints(Type genType, Type parameterType) {
			Type[] constraints = genType.GetGenericParameterConstraints();

			for (int i = 0; i < constraints.Length; i++)
				if (!constraints[i].IsAssignableFrom(parameterType))
					return false;

			return true;
		}
Ejemplo n.º 5
0
        public static bool CheckConstraints(Type goal, Type probe)
        {
            var constraints = goal.GetGenericParameterConstraints();

            for (var i = 0; i < constraints.Length; i++)
                if (!constraints[i].IsAssignableFrom(probe))
                    return false;

            return true;
        }
Ejemplo n.º 6
0
        public static bool MeetsGenericParameterConstraints(this Type type, Type genericArgument)
        {
            if (!genericArgument.IsGenericParameter)
                throw new ArgumentException("The argument must be a generic parameter.", "genericArgument");

            Type[] constraints = genericArgument.GetGenericParameterConstraints();
            for (int i = 0; i < constraints.Length; i++)
            {
                if (!constraints[i].IsAssignableFrom(type))
                    return false;
            }

            return true;
        }
Ejemplo n.º 7
0
        static private void AppendType(Type type, StringBuilder sb, bool showGenericConstraints = false)
        {
            if (showGenericConstraints && type.IsGenericParameter)
            {
                if (type.GenericParameterAttributes.HasFlag(GenericParameterAttributes.ReferenceTypeConstraint)) sb.Append("class ");
                if (type.GenericParameterAttributes.HasFlag(GenericParameterAttributes.NotNullableValueTypeConstraint)) sb.Append("valuetype ");
                if (type.GenericParameterAttributes.HasFlag(GenericParameterAttributes.DefaultConstructorConstraint)) sb.Append(".ctor ");

                var genericConstraints = type.GetGenericParameterConstraints();
                if (genericConstraints.Length > 0)
                {
                    sb.Append("(");
                    foreach (var genericConstraint in genericConstraints)
                    {
                        AppendType(genericConstraint, sb);
                        AppendComma(sb);
                    }
                    RemoveTrailingComma(sb);
                    sb.Append(") ");
                }
            }
            sb.Append(type);
        }
Ejemplo n.º 8
0
        private static void Step(Type current)
        {
            if (types.Contains(current) ||
                current.Name.StartsWith("<") ||
                (current.FullName != null && current.FullName.StartsWith("System") && !(current.IsGenericType && current.GetGenericTypeDefinition() == typeof(IEnumerable<>))))
            {
                return;
            }

            types.Add(current);

            if (current.IsInterface)
            {
                foreach (var type in allTypes)
                {
                    if (type.GetInterfaces().Contains(current))
                    {
                        dependencies.Add(new Tuple<Type, Type>(current, type));
                        Step(type);
                    }
                }

                if (current.IsGenericType)
                {
                    foreach (var type in allTypes)
                    {
                        if (type.GetInterfaces().Where(i => i.IsGenericType).Select(i => i.GetGenericTypeDefinition()).Contains(current.GetGenericTypeDefinition()))
                        {
                            dependencies.Add(new Tuple<Type, Type>(current, type));
                            Step(type);
                        }
                    }
                }
            }

            if (current.IsGenericType)
            {
                var genericArguments = current.GetGenericArguments();

                foreach (Type genericArgument in genericArguments)
                {
                    dependencies.Add(new Tuple<Type, Type>(current, genericArgument));

                    Step(genericArgument);
                }
            }

            if (current.IsGenericParameter)
            {
                foreach (var parameter in current.GetGenericParameterConstraints())
                {
                    dependencies.Add(new Tuple<Type, Type>(current, parameter));
                    Step(parameter);

                    foreach (var type in allTypes)
                    {
                        if (type.BaseType == parameter)
                        {
                            dependencies.Add(new Tuple<Type, Type>(current, type));
                            Step(type);
                        }

                        foreach (Type @interface in type.GetInterfaces())
                        {
                            if (@interface == parameter)
                            {
                                dependencies.Add(new Tuple<Type, Type>(current, @interface));
                                Step(@interface);
                            }

                            if (@interface.IsGenericType)
                            {
                                if (@interface.GetGenericTypeDefinition() == parameter)
                                {
                                    dependencies.Add(new Tuple<Type, Type>(current, @interface));
                                    Step(@interface);
                                }
                            }
                        }
                    }
                }
            }

            if (current.Name.EndsWith("Factory"))
            {
                MethodInfo[] methods = current.GetMethods(BindingFlags.Instance | BindingFlags.Public);
                foreach (MethodInfo method in methods)
                {
                    dependencies.Add(new Tuple<Type, Type>(current, method.ReturnType));
                    Step(method.ReturnType);
                }
            }

            var constructors = current.GetConstructors(BindingFlags.Public | BindingFlags.Instance);
            if (constructors.Count() == 1)
            {
                var parameters = constructors.Single().GetParameters();

                foreach (var parameter in parameters)
                {
                    dependencies.Add(new Tuple<Type, Type>(current, parameter.ParameterType));

                    Step(parameter.ParameterType);
                }
            }
        }
Ejemplo n.º 9
0
		TypeParameterSpec CreateTypeParameter (Type type, TypeSpec declaringType)
		{
			Variance variance;
			switch (type.GenericParameterAttributes & GenericParameterAttributes.VarianceMask) {
			case GenericParameterAttributes.Covariant:
				variance = Variance.Covariant;
				break;
			case GenericParameterAttributes.Contravariant:
				variance = Variance.Contravariant;
				break;
			default:
				variance = Variance.None;
				break;
			}

			SpecialConstraint special = SpecialConstraint.None;
			var import_special = type.GenericParameterAttributes & GenericParameterAttributes.SpecialConstraintMask;

			if ((import_special & GenericParameterAttributes.NotNullableValueTypeConstraint) != 0) {
				special |= SpecialConstraint.Struct;
			} else if ((import_special & GenericParameterAttributes.DefaultConstructorConstraint) != 0) {
				special = SpecialConstraint.Constructor;
			}

			if ((import_special & GenericParameterAttributes.ReferenceTypeConstraint) != 0) {
				special |= SpecialConstraint.Class;
			}

			TypeParameterSpec spec;
			var def = new ImportedTypeParameterDefinition (type);
			if (type.DeclaringMethod != null)
				spec = new TypeParameterSpec (type.GenericParameterPosition, def, special, variance, type);
			else
				spec = new TypeParameterSpec (declaringType, type.GenericParameterPosition, def, special, variance, type);

			// Add it now, so any constraint can reference it and get same instance
			import_cache.Add (type, spec);

			var constraints = type.GetGenericParameterConstraints ();
			List<TypeSpec> tparams = null;
			foreach (var ct in constraints) {
				if (ct.IsGenericParameter) {
					if (tparams == null)
						tparams = new List<TypeSpec> ();

					tparams.Add (CreateType (ct));
					continue;
				}

				if (ct.IsClass) {
					spec.BaseType = CreateType (ct);
					continue;
				}

				spec.AddInterface (CreateType (ct));
			}

			if (spec.BaseType == null)
				spec.BaseType = TypeManager.object_type;

			if (tparams != null)
				spec.TypeArguments = tparams.ToArray ();

			return spec;
		}
Ejemplo n.º 10
0
        private static PlTerm typeToSpec(Type type)
        {
            if (type == null) return PLNULL;
            if (type.IsArray && type.HasElementType)
            {
                if (type.GetArrayRank() != 1)
                {
                    return PlC("arrayOf", typeToSpec(type.GetElementType()), ToProlog(type.GetArrayRank()));
                }
                return PlC("arrayOf", typeToSpec(type.GetElementType()));
            }
            if (type.IsGenericParameter)
            {
                Type[] gt = type.GetGenericParameterConstraints();
                return PlC("<" + type.FullName ?? type.Name + ">", ToPlTermVSpecs(gt));
            }
            if (type.IsPointer)
            {
                Type gt = type.GetElementType();
                return PlC("pointer", typeToSpec(gt));
            }
            if (type.IsByRef)
            {
                Type gt = type.GetElementType();
                return PlC("byref", typeToSpec(gt));
            }
            // @todo if false , use IsGenericType
            if (false) if (typeof(Nullable<>).IsAssignableFrom(type))
            {
                Embedded.Error("@todo Not Implemented NULLABLE");
                Type gt = type.GetElementType();
                return PlC("nullable", typeToSpec(gt));
            }

            if (type.IsGenericType )
            {
                Type gt = type.GetGenericTypeDefinition();
                Type[] gtp = type.GetGenericArguments();
                PlTermV vt = ToPlTermVSpecs(gtp);
                string typeName = type.FullName ?? type.Name;
                int gtpLength = gtp.Length;
                int indexOf = typeName.IndexOf("`" + gtpLength);
                if (indexOf > 0)
                {
                    typeName = typeName.Substring(0, indexOf);
                }
                else
                {
                    Embedded.Debug("cant chop arity {0} off string '{1}' ", gtpLength, typeName);
                }
                return PlC(typeName, vt);
            }
            if (type.HasElementType)
            {
                string named = typeToName(type);
                Embedded.Error("@todo Not Implemented " + named);
                Type gt = type.GetElementType();
                if (gt == type) gt = typeof(object);
                return PlC("elementType", PlTerm.PlAtom(named), typeToSpec(gt));
            }
            if (type.IsSpecialName || String.IsNullOrEmpty(type.Name) || String.IsNullOrEmpty(type.FullName) || String.IsNullOrEmpty(type.Namespace))
            {
                string named = typeToName(type);
                Embedded.Error("@todo Not Implemented " + named);
                Type gt = type.UnderlyingSystemType;
                if (gt == type) gt = typeof (object);
                return PlC("static", PlTerm.PlAtom(named), typeToSpec(gt));
            }
            return PlTerm.PlAtom(typeToName(type));
        }
Ejemplo n.º 11
0
        private void GenerateTypeParamElement(IProcessingContext context, MemberInfo mInfo, Type tp)
        {
            var tpElem = new XElement("typeparam", new XAttribute("name", tp.Name));

            if (tp.GenericParameterAttributes.HasFlag(GenericParameterAttributes.Contravariant))
                tpElem.Add(new XAttribute("isContravariant", XmlConvert.ToString(true)));

            if (tp.GenericParameterAttributes.HasFlag(GenericParameterAttributes.Covariant))
                tpElem.Add(new XAttribute("isCovariant", XmlConvert.ToString(true)));

            if (tp.GenericParameterAttributes.HasFlag(GenericParameterAttributes.NotNullableValueTypeConstraint))
                tpElem.Add(new XAttribute("isValueType", XmlConvert.ToString(true)));

            if (tp.GenericParameterAttributes.HasFlag(GenericParameterAttributes.ReferenceTypeConstraint))
                tpElem.Add(new XAttribute("isReferenceType", XmlConvert.ToString(true)));

            if (tp.GenericParameterAttributes.HasFlag(GenericParameterAttributes.DefaultConstructorConstraint))
                tpElem.Add(new XAttribute("hasDefaultConstructor", XmlConvert.ToString(true)));

            context.Element.Add(tpElem);

            foreach (Type constraint in tp.GetGenericParameterConstraints())
            {
                var ctElement = new XElement("constraint");
                tpElem.Add(ctElement);
                GenerateTypeRef(context.Clone(ctElement), constraint);
            }

            // enrich typeparam
            foreach (IEnricher enricher in this.Enrichers)
                enricher.EnrichTypeParameter(context.Clone(tpElem), tp);
        }
		internal static void AddConstraintsFromType(ITypeParameter tp, Type type)
		{
			foreach (Type constraint in type.GetGenericParameterConstraints()) {
				if (tp.Method != null) {
					tp.Constraints.Add(ReflectionReturnType.Create(tp.Method, constraint));
				} else {
					tp.Constraints.Add(ReflectionReturnType.Create(tp.Class, constraint));
				}
			}
		}
Ejemplo n.º 13
0
 private GenericSymbol ImportGenericType(Type type)
 {
     var attribute = new List<AttributeSymbol>();
     AppendEmbededAttribute(attribute, type);
     var constraint = CreateConstraintList(type.GetGenericParameterConstraints());
     var elem = new GenericSymbol(type.Name, attribute, constraint);
     if (ImportDictionary.ContainsKey(type))
     {
         return (GenericSymbol)ImportDictionary[type];
     }
     ImportDictionary.Add(type, elem);
     return elem;
 }
Ejemplo n.º 14
0
            protected Type FindAClassThatMeetsTheGenericParameter(Type input)
            {
                var genericConstraint = input.GetGenericParameterConstraints().FirstOrDefault();

                //Now find a class that meets this constraint...

                //If there are no constraints, then any object should do, including System.Object.
                if (genericConstraint == null)
                {
                    return typeof (object);
                }

                bool constraintRequiresDefaultConstructor =
                    (input.GenericParameterAttributes & GenericParameterAttributes.DefaultConstructorConstraint) !=
                    GenericParameterAttributes.DefaultConstructorConstraint;
                bool isConstraintConcrete = !genericConstraint.IsAbstract;

                bool typeOfTheConstraintFulfillsTheConstraint = constraintRequiresDefaultConstructor || isConstraintConcrete;
                
                if (typeOfTheConstraintFulfillsTheConstraint)
                {
                    return genericConstraint;
                }

                //But if it's abstract, and the generic requires a default constructor, we have to find a class that implments it.
                //If we've made it this far, then we know that typeOfGenericInterface is an abstract class.  Go find something that implments it...
                
                //Uncomment this and change the code it to use the correct marker interface if you have the State Resource Extensions.
                //var extensionClassThatInheritsFromTheConstraint =
                //    typeof(Marker_EdFi_Dashboards_Extensions_STATE_Resources).Assembly.GetTypes().FirstOrDefault(type => type.IsSubclassOf(genericConstraint));
                //if (extensionClassThatInheritsFromTheConstraint != null)
                //    return extensionClassThatInheritsFromTheConstraint;

                var coreClassThatInheritsFromTheConstraint =
                    typeof(Marker_EdFi_Dashboards_Resources).Assembly.GetTypes().FirstOrDefault(type => type.IsSubclassOf(genericConstraint));
                
                if (coreClassThatInheritsFromTheConstraint != null)
                    return coreClassThatInheritsFromTheConstraint;

                throw new ApplicationException("Unable to find an implementation for " + input);
            }
Ejemplo n.º 15
0
        /// <summary>
        /// Verifies that two types are equivalent.
        /// </summary>
        /// <param name="actual">The actual type.</param>
        /// <param name="expected">The expected type.</param>
        private static void AreTypesEquivalent(Type actual, Type expected)
        {
            // Check type properties.
            Assert.That(actual.IsAbstract, Is.EqualTo(expected.IsAbstract));
            Assert.That(actual.IsAnsiClass, Is.EqualTo(expected.IsAnsiClass));
            Assert.That(actual.IsArray, Is.EqualTo(expected.IsArray));
            Assert.That(actual.IsAutoClass, Is.EqualTo(expected.IsAutoClass));
            Assert.That(actual.IsAutoLayout, Is.EqualTo(expected.IsAutoLayout));
            Assert.That(actual.IsByRef, Is.EqualTo(expected.IsByRef));
            Assert.That(actual.IsClass, Is.EqualTo(expected.IsClass));
            Assert.That(actual.IsCOMObject, Is.EqualTo(expected.IsCOMObject));
            Assert.That(actual.IsContextful, Is.EqualTo(expected.IsContextful));
            Assert.That(actual.IsEnum, Is.EqualTo(expected.IsEnum));
            Assert.That(actual.IsExplicitLayout, Is.EqualTo(expected.IsExplicitLayout));
            Assert.That(actual.IsInterface, Is.EqualTo(expected.IsInterface));
            Assert.That(actual.IsLayoutSequential, Is.EqualTo(expected.IsLayoutSequential));
            Assert.That(actual.IsMarshalByRef, Is.EqualTo(expected.IsMarshalByRef));
            Assert.That(actual.IsNested, Is.EqualTo(expected.IsNested));
            Assert.That(actual.IsNestedAssembly, Is.EqualTo(expected.IsNestedAssembly));
            Assert.That(actual.IsNestedFamANDAssem, Is.EqualTo(expected.IsNestedFamANDAssem));
            Assert.That(actual.IsNestedFamily, Is.EqualTo(expected.IsNestedFamily));
            Assert.That(actual.IsNestedFamORAssem, Is.EqualTo(expected.IsNestedFamORAssem));
            Assert.That(actual.IsNestedPrivate, Is.EqualTo(expected.IsNestedPrivate));
            Assert.That(actual.IsNestedPublic, Is.EqualTo(expected.IsNestedPublic));
            Assert.That(actual.IsNotPublic, Is.EqualTo(expected.IsNotPublic));
            Assert.That(actual.IsPointer, Is.EqualTo(expected.IsPointer));
            Assert.That(actual.IsPrimitive, Is.EqualTo(expected.IsPrimitive));
            Assert.That(actual.IsPublic, Is.EqualTo(expected.IsPublic));
            Assert.That(actual.IsSealed, Is.EqualTo(expected.IsSealed));
            //Assert.That(actual.IsSecuritySafeCritical, Is.EqualTo(expected.IsSecuritySafeCritical));
            Assert.That(actual.IsSerializable, Is.EqualTo(expected.IsSerializable));
            Assert.That(actual.IsSpecialName, Is.EqualTo(expected.IsSpecialName));
            Assert.That(actual.IsUnicodeClass, Is.EqualTo(expected.IsUnicodeClass));
            Assert.That(actual.IsValueType, Is.EqualTo(expected.IsValueType));
            Assert.That(actual.IsVisible, Is.EqualTo(expected.IsVisible));
            Assert.That(actual.MemberType, Is.EqualTo(expected.MemberType));
            Assert.That(actual.Name, Is.EqualTo(expected.Name));
            Assert.That(actual.StructLayoutAttribute, Is.EqualTo(expected.StructLayoutAttribute));
            Assert.That(actual.IsGenericType, Is.EqualTo(expected.IsGenericType));

            // Ignore .NET Framework 4 properties.
            //Assert.That(actual.IsSecurityCritical, Is.EqualTo(expected.IsSecurityCritical));
            //Assert.That(actual.IsSecurityTransparent, Is.EqualTo(expected.IsSecurityTransparent));

            // Check type attributes.
            Assert.That(actual.Attributes, Is.EqualTo(expected.Attributes));

            // Check element type.
            Assert.That(actual.HasElementType, Is.EqualTo(expected.HasElementType));

            if (actual.HasElementType)
                AreTypesEquivalent(actual.GetElementType(), expected.GetElementType());

            // Check generic parameters.
            Assert.That(actual.ContainsGenericParameters, Is.EqualTo(expected.ContainsGenericParameters));

            if (actual.ContainsGenericParameters)
                AreTypesEquivalent(actual.GetGenericArguments(), expected.GetGenericArguments());

            // Check generic parameter.
            Assert.That(actual.IsGenericParameter, Is.EqualTo(expected.IsGenericParameter));

            if (actual.IsGenericParameter)
            {
                Assert.That(actual.GenericParameterAttributes, Is.EqualTo(expected.GenericParameterAttributes));
                AreTypesEquivalent(actual.GetGenericParameterConstraints(), expected.GetGenericParameterConstraints());
                Assert.That(actual.GenericParameterPosition, Is.EqualTo(expected.GenericParameterPosition));
            }

            // Check generic type definition.
            Assert.That(actual.IsGenericTypeDefinition, Is.EqualTo(expected.IsGenericTypeDefinition));

            if (actual.IsGenericTypeDefinition)
                AreTypesEquivalent(actual.GetGenericTypeDefinition(), expected.GetGenericTypeDefinition());
        }
            private CodeDocGenericParameter CreateGenericTypeParameter(Type genericArgument, ICodeDocMemberDataProvider provider)
            {
                Contract.Requires(genericArgument != null);
                Contract.Requires(provider != null);
                Contract.Ensures(Contract.Result<CodeDocGenericParameter>() != null);
                var argumentName = genericArgument.Name;
                Contract.Assume(!String.IsNullOrEmpty(argumentName));
                var typeConstraints = genericArgument.GetGenericParameterConstraints();
                var model = new CodeDocGenericParameter(argumentName);

                model.SummaryContents = provider
                    .GetGenericTypeSummaryContents(argumentName)
                    .ToArray();

                if (typeConstraints.Length > 0)
                    model.TypeConstraints = Array.ConvertAll(typeConstraints, t => GetOrConvert(t, CodeDocMemberDetailLevel.Minimum));

                model.IsContravariant = genericArgument.GenericParameterAttributes.HasFlag(
                    GenericParameterAttributes.Contravariant);
                model.IsCovariant = genericArgument.GenericParameterAttributes.HasFlag(
                    GenericParameterAttributes.Covariant);
                model.HasDefaultConstructorConstraint = genericArgument.GenericParameterAttributes.HasFlag(
                    GenericParameterAttributes.DefaultConstructorConstraint);
                model.HasNotNullableValueTypeConstraint = genericArgument.GenericParameterAttributes.HasFlag(
                    GenericParameterAttributes.NotNullableValueTypeConstraint);
                model.HasReferenceTypeConstraint = genericArgument.GenericParameterAttributes.HasFlag(
                    GenericParameterAttributes.ReferenceTypeConstraint);

                return model;
            }
 internal static bool IsOrInheritsFrom(Type Derived, Type Base)
 {
     if (Derived == Base)
     {
         return true;
     }
     if (Derived.IsGenericParameter)
     {
         if ((IsClass(Base) && ((Derived.GenericParameterAttributes & GenericParameterAttributes.NotNullableValueTypeConstraint) > GenericParameterAttributes.None)) && IsOrInheritsFrom(typeof(ValueType), Base))
         {
             return true;
         }
         foreach (Type type in Derived.GetGenericParameterConstraints())
         {
             if (IsOrInheritsFrom(type, Base))
             {
                 return true;
             }
         }
     }
     else if (IsInterface(Derived))
     {
         if (IsInterface(Base))
         {
             foreach (Type type2 in Derived.GetInterfaces())
             {
                 if (type2 == Base)
                 {
                     return true;
                 }
             }
         }
     }
     else if (IsClass(Base) && IsClassOrValueType(Derived))
     {
         return Derived.IsSubclassOf(Base);
     }
     return false;
 }
        /// <summary>
        /// Generates a runtime generated type for the specified <paramref name="genericType"/> based upon the type
        /// constraints.
        /// </summary>
        /// <param name="genericType">The generic type.</param>
        /// <returns>A runtime generated type for the specified <paramref name="genericType"/>.</returns>
        /// <exception cref="ArgumentNullException">The <paramref name="genericType"/> parameter is
        /// <see langword="null"/>.</exception>
        private static Type GenerateRuntimeType(Type genericType)
        {
            if (genericType == null)
                throw new ArgumentNullException("genericType");

            Type[] constraints = genericType.GetGenericParameterConstraints();

            // Cannot yet handle mixed constraints, so just return the generic type which will cause a failure later.
            if (constraints.Any(c => !c.IsInterface))
                return genericType;

            TypeBuilder builder =
                ModuleBuilder.DefineType(
                    string.Format("{0}_Dynamic_{1:N}", genericType.Name, Guid.NewGuid()),
                    TypeAttributes.Interface | TypeAttributes.Abstract | TypeAttributes.Public);

            foreach (Type constraint in constraints)
            {
                builder.AddInterfaceImplementation(constraint);
            }

            try
            {
                // Try to create the type.
                return builder.CreateType();
            }
            catch
            {
                // If create failed return the generic type which will cause a failure later.
                return genericType;
            }
        }
        /// <summary>
        /// Tries a simple solution to to get a non generic type by using either a built in type or the constraint type
        /// if there is only one.
        /// </summary>
        /// <param name="genericType">The generic type.</param>
        /// <param name="nonGenericType">The non generic type for the <paramref name="genericType"/>.</param>
        /// <returns><see langword="true"/> if a <paramref name="nonGenericType"/> can be used; otherwise
        /// <see langword="false"/>.</returns>
        /// <exception cref="ArgumentNullException">The <paramref name="genericType"/> parameter is
        /// <see langword="null"/>.</exception>
        private static bool TrySimple(Type genericType, out Type nonGenericType)
        {
            if (genericType == null)
                throw new ArgumentNullException("genericType");

            Type[] constraints = genericType.GetGenericParameterConstraints();
            GenericParameterAttributes attributes = genericType.GenericParameterAttributes;

            // Handle the simple situation where there are no constraints.
            if (constraints.Length == 0)
            {
                if (attributes == GenericParameterAttributes.None
                    || attributes.HasFlag(GenericParameterAttributes.ReferenceTypeConstraint))
                {
                    nonGenericType = typeof(object);
                    return true;
                }
            }

            // Handle the simple situation where the single constraint.
            if (constraints.Length == 1)
            {
                Type constraint = constraints[0];
                if (constraint == typeof(ValueType))
                {
                    nonGenericType = typeof(int);
                    return true;
                }

                // If there is a single constraint with no attributes, just use the constraint as the non generic type.
                if (attributes == GenericParameterAttributes.None)
                {
                    nonGenericType = constraint;
                    return true;
                }

                // If there is a single constraint, the generic type requires a default constructor and the constraint
                // has a default constructor, just use the constraint as the non generic type.
                if (attributes == GenericParameterAttributes.DefaultConstructorConstraint)
                {
                    if (constraint.GetConstructor(Type.EmptyTypes) != null)
                    {
                        nonGenericType = constraint;
                        return true;
                    }
                }
            }

            nonGenericType = null;
            return false;
        }
Ejemplo n.º 20
0
        private void WriteGenericArgument(XmlWriter writer, string memberName, Type genericArgument)
        {
#if NET_2_0
            writer.WriteStartElement("genericArgument");
            writer.WriteAttributeString("name", genericArgument.Name);

            writer.WriteAttributeString("position", genericArgument.GenericParameterPosition.ToString(CultureInfo.InvariantCulture));

            writer.WriteAttributeString("constraint", genericArgument.GenericParameterAttributes.ToString());
            foreach (Type t in genericArgument.GetGenericParameterConstraints())
            {
                writer.WriteStartElement("constraintType");
                //writer.WriteAttributeString("type", MemberID.GetTypeName(t, false));
                writer.WriteAttributeString("type", MemberID.GetTypeName(t));
                writer.WriteAttributeString("displayName", MemberDisplayName.GetMemberDisplayName(t));
                writer.WriteEndElement();
            }
            writer.WriteEndElement();
#endif
        }
Ejemplo n.º 21
0
        /// <summary>
        /// Determines whether a <see cref="Type"/> meets the constraints for a generic parameter, i.e. whether it could be used 
        /// as the concrete type for a generic parameter.
        /// </summary>
        /// <param name="type">
        /// The <see cref="Type"/> to check.
        /// </param>
        /// <param name="parameterType">
        /// The generic parameter <see cref="Type"/>.
        /// </param>
        /// <returns>
        /// <c>true</c>if <paramref name="type"/> meets the generic constraints; otherwise <c>false</c>.
        /// </returns>
        /// <exception cref="ArgumentNullException">
        /// Either <paramref name="type"/> or <paramref name="parameterType"/> is <c>null</c>.
        /// </exception>
        /// <exception cref="ArgumentException">
        /// <paramref name="parameterType"/>is not a generic parameter (i.e. <see cref="Type.IsGenericParameter"/> is <c>false</c>).
        /// </exception>
        public static bool MeetsGenericParameterConstraints(this Type type, Type parameterType)
        {
            if ((parameterType.GenericParameterAttributes & GenericParameterAttributes.ReferenceTypeConstraint) != 0 && type.IsValueType)
            {
                return false;
            }

            if ((parameterType.GenericParameterAttributes & GenericParameterAttributes.NotNullableValueTypeConstraint) != 0 && (!type.IsValueType || type.IsNullableT()))
            {
                return false;
            }

            if ((parameterType.GenericParameterAttributes & GenericParameterAttributes.DefaultConstructorConstraint) != 0 && !type.IsValueType
                && type.GetConstructor(Type.EmptyTypes) == null)
            {
                return false;
            }

            foreach (Type constraintType in parameterType.GetGenericParameterConstraints())
            {
                if (!type.MeetsGenericParameterConstraint(constraintType))
                {
                    return false;
                }
            }

            return true;
        }
Ejemplo n.º 22
0
 public static TypeIndex FromSystemType(System.Type type)
 {
     if (string.IsNullOrEmpty(type.Namespace))
     {
         return(Object);
     }
     else if (type.IsByRef)
     {
         try
         {
             string tname = type.FullName.Substring(0, type.FullName.Length - 1);
             return(FromSystemType(type.Assembly.GetType(tname)));
         }
         catch { }
         return(Object);
     }
     else if (type.IsArray)
     {
         var ti = FromSystemType(typeof(Array));
         ti.Kind = TypeIndexKind.GenericType;
         ti.GenericParams.Add(FromSystemType(type.GetElementType()));
         return(ti);
     }
     else if (type.IsGenericParameter)
     {
         return(new TypeIndex(type.Name, TypeIndexKind.GenericParam));
     }
     else if (type.IsNested)
     {
         var ti = FromSystemType(type.DeclaringType);
         ti.Name += "." + type.Name;
         if (type.IsGenericTypeDefinition && ti.Name.Contains("`"))
         {
             ti.Name = ti.Name.Substring(0, type.Name.IndexOf('`'));
             foreach (var t in type.GetGenericParameterConstraints())
             {
                 ti.GenericParams.Add(FromSystemType(t));
             }
             ti.Kind = TypeIndexKind.GenericDefinition;
         }
         return(ti);
     }
     else if (type.IsGenericTypeDefinition)
     {
         var ti =
             new TypeIndex(
                 type.Namespace,
                 type.Name.Substring(0, type.Name.IndexOf('`')));
         foreach (var t in type.GetGenericArguments())
         {
             var pti = new TypeIndex(t.Name, TypeIndexKind.GenericParam);
             ti.GenericParams.Add(pti);
         }
         ti.Kind = TypeIndexKind.GenericDefinition;;
         return(ti);
     }
     else if (type.IsGenericType)
     {
         var gtype = type.GetGenericTypeDefinition();
         var ti    = FromSystemType(gtype);
         ti.GenericParams.Clear();
         foreach (var t in type.GenericTypeArguments)
         {
             ti.GenericParams.Add(FromSystemType(t));
         }
         ti.Kind = TypeIndexKind.GenericType;
         return(ti);
     }
     else
     {
         string name = type.FullName;
         if (_types.ContainsKey(name))
         {
             return(_types[name]);
         }
         if (type.Namespace != null && name.StartsWith(type.Namespace))
         {
             name = name.Substring(type.Namespace.Length + 1);
         }
         name = name.Replace("*", "");
         return(new TypeIndex(type.Namespace, name));
     }
 }
Ejemplo n.º 23
0
 private void MapGenericParameterConstraints(Type genericParameter, GenericParameter gp, IGenericParameterProvider owner)
 {
     foreach (var constraint in genericParameter.GetGenericParameterConstraints ()) {
         gp.Constraints.Add (owner.GenericParameterType == GenericParameterType.Type
             ? CreateReference(constraint, (TypeReference) owner)
             : CreateReference(constraint, (MethodReference) owner));
     }
 }
        private static IEnumerable<Type> GetNestedTypeArgumentsForTypeArgument(Type argument, IList<Type> processedArguments)
        {
            processedArguments.Add(argument);

            if (argument.IsGenericParameter)
            {
                var nestedArguments =
                    from constraint in argument.GetGenericParameterConstraints()
                    from arg in GetNestedTypeArgumentsForTypeArgument(constraint, processedArguments)
                    select arg;

                return nestedArguments.Concat(new[] { argument });
            }

            if (!argument.IsGenericType())
            {
                return Enumerable.Empty<Type>();
            }

            return
                from genericArgument in argument.GetGenericArguments().Except(processedArguments)
                from arg in GetNestedTypeArgumentsForTypeArgument(genericArgument, processedArguments)
                select arg;
        }
Ejemplo n.º 25
0
		/// <summary>
		/// Converts a PHP value to the given CLR type that is a generic parameter.
		/// </summary>
		private static void EmitConvertToClrGeneric(ILEmitter/*!*/ il, Type/*!*/ formalType, LocalBuilder/*!*/ strictnessLocal)
		{
			Debug.Assert(formalType.IsGenericParameter);

			// f...ing GenericTypeParameterBuilder will not allow us to read its attributes and constraints :(
			if (!(formalType is GenericTypeParameterBuilder))
			{
				GenericParameterAttributes attrs = formalType.GenericParameterAttributes;
				if (Reflection.Enums.GenericParameterAttrTest(attrs, GenericParameterAttributes.NotNullableValueTypeConstraint))
				{
					// we know that we are converting to a value type
					il.Ldloca(strictnessLocal);
					il.Emit(OpCodes.Call, Methods.ConvertToClr.TryObjectToStruct.MakeGenericMethod(formalType));
					return;
				}

				Type[] constraints = formalType.GetGenericParameterConstraints();
				for (int i = 0; i < constraints.Length; i++)
				{
					if (constraints[i].IsClass)
					{
						if (!constraints[i].IsArray && !typeof(Delegate).IsAssignableFrom(constraints[i]))
						{
							// we know that we are converting to a class that is not an array nor a delegate
							il.Ldloca(strictnessLocal);
							il.Emit(OpCodes.Call, Methods.ConvertToClr.TryObjectToClass.MakeGenericMethod(formalType));
							return;
						}
						else break;
					}
				}
			}

			// postpone the conversion to runtime
			il.Ldloca(strictnessLocal);
			il.Emit(OpCodes.Call, Methods.Convert.TryObjectToType.MakeGenericMethod(formalType));
		}
Ejemplo n.º 26
0
 private static bool MatchesGenericParameterConstraints(Type typeParameter, Type typeArgument)
 {
     return typeParameter.GetGenericParameterConstraints().All(typeArgument.IsAssignableFrom);
 }
Ejemplo n.º 27
0
        private void GenerateTypeParamElement(IProcessingContext context, MemberInfo mInfo, Type tp)
        {
            // AssetIdentifier assetId = AssetIdentifier.FromType(mInfo, tp);
            var tpElem = new XElement("typeparam",
                                      new XAttribute("name", tp.Name));

            context.Element.Add(tpElem);

            foreach (Type constraint in tp.GetGenericParameterConstraints())
            {
                var ctElement = new XElement("constraint");
                tpElem.Add(ctElement);
                GenerateTypeRef(context.Clone(ctElement), constraint);
            }

            // enrich typeparam
            foreach (IEnricher enricher in this.Enrichers)
                enricher.EnrichTypeParameter(context.Clone(tpElem), tp);
        }
Ejemplo n.º 28
0
            /// <summary>
            /// Checks if the constraints are violated by the given input for the specified generic method parameter.
            /// 
            /// This method must be supplied with a mapping for any dependent generic method type parameters which
            /// this one can be constrained to.  For example for the signature "void Foo{T0, T1}(T0 x, T1 y) where T0 : T1".
            /// we cannot know if the constraints are violated unless we know what we have calculated T1 to be.
            /// </summary>
            protected static bool ConstraintsViolated(Type inputType, Type genericMethodParameterType, Dictionary<Type, Type> prevConstraints) {
                if ((genericMethodParameterType.GenericParameterAttributes & GenericParameterAttributes.ReferenceTypeConstraint) != 0 && inputType.IsValueType) {
                    // value type to parameter type constrained as class
                    return true;
                } else if ((genericMethodParameterType.GenericParameterAttributes & GenericParameterAttributes.NotNullableValueTypeConstraint) != 0 &&
                    (!inputType.IsValueType || (inputType.IsGenericType && inputType.GetGenericTypeDefinition() == typeof(Nullable<>)))) {
                    // nullable<T> or class/interface to parameter type constrained as struct
                    return true;
                } else if ((genericMethodParameterType.GenericParameterAttributes & GenericParameterAttributes.DefaultConstructorConstraint) != 0 &&
                    (!inputType.IsValueType && inputType.GetConstructor(Type.EmptyTypes) == null)) {
                    // reference type w/o a default constructor to type constrianed as new()
                    return true;
                }

                Type[] constraints = genericMethodParameterType.GetGenericParameterConstraints();
                for (int i = 0; i < constraints.Length; i++) {
                    Type t = constraints[i];
                    if (t.ContainsGenericParameters) {
                        t = ReplaceTypes(t, prevConstraints);
                        if (t == null) {
                            return true;
                        }
                    } 

                    if (!t.IsAssignableFrom(inputType)) {
                        // constraint cannot be satisfied
                        return true;
                    }
                }
                return false;
            }