Esempio n. 1
0
        public static bool IsGenericTypeOf(this Type t, Type genericDefinition, out Type[] genericParameters)
        {
            genericParameters = new Type[] { };
            if (!genericDefinition.IsGenericType())
            {
                return false;
            }

            var isMatch = t.IsGenericType() && t.GetGenericTypeDefinition() == genericDefinition.GetGenericTypeDefinition();
            if (!isMatch && t.GetBaseType() != null)
            {
                isMatch = IsGenericTypeOf(t.GetBaseType(), genericDefinition, out genericParameters);
            }
            if (!isMatch && genericDefinition.IsInterface() && t.GetInterfaces().Any())
            {
                foreach (var i in t.GetInterfaces())
                {
                    if (i.IsGenericTypeOf(genericDefinition, out genericParameters))
                    {
                        isMatch = true;
                        break;
                    }
                }
            }

            if (isMatch && !genericParameters.Any())
            {
                genericParameters = t.GetGenericArguments();
            }
            return isMatch;
        }
Esempio n. 2
0
 public static RubyClass ToClass(RubyContext/*!*/ context, Type/*!*/ self)
 {
     if (self.IsInterface()) {
         RubyExceptions.CreateTypeError("Cannot convert a CLR interface to a Ruby class");
     }
     return context.GetClass(self);
 }
Esempio n. 3
0
        public static object CreateDictionary(Type dictionaryType, Type keyType, Type valueType)
        {
            var type = dictionaryType.IsInterface()
                ? typeof (Dictionary<,>).MakeGenericType(keyType, valueType)
                : dictionaryType;

            return CreateObject(type);
        }
Esempio n. 4
0
 public static object CreateObject(Type type)
 {
     return type.IsArray
         ? CreateArray(type.GetElementType(), 0)
         : type == typeof (string)
             ? null
             : type.IsInterface() && type.IsDictionaryType()
                 ? CreateDictionary(type) 
                 : DelegateFactory.CreateCtor(type)();
 }
Esempio n. 5
0
        public static object CreateDictionary(Type dictionaryType)
        {
            Type keyType = dictionaryType.GetTypeInfo().GenericTypeArguments[0];
            Type valueType = dictionaryType.GetTypeInfo().GenericTypeArguments[1];
            var type = dictionaryType.IsInterface()
                ? typeof (Dictionary<,>).MakeGenericType(keyType, valueType)
                : dictionaryType;

            return DelegateFactory.CreateCtor(type)();
        }
		public void AddEmptyInterface(Type @interface)
		{
			DebugExtender.Assert(@interface != null, "@interface == null", "Shouldn't be adding empty interfaces...");
			DebugExtender.Assert(@interface.IsInterface(), "@interface.IsInterface()", "Should be adding interfaces only...");
			DebugExtender.Assert(!interfaces.Contains(@interface), "!interfaces.Contains(@interface)",
			             "Shouldn't be adding same interface twice...");
			DebugExtender.Assert(!empty.Contains(@interface), "!empty.Contains(@interface)",
			             "Shouldn't be adding same interface twice...");
			empty.Add(@interface);
		}
		private bool IsPrimitiveOrClass(Type type)
		{
			if ((type.IsPrimitive() && type != typeof(IntPtr)))
			{
				return true;
			}
			return ((type.IsClass() || type.IsInterface()) &&
			        type.IsGenericParameter == false &&
			        type.IsByRef == false);
		}
        /// <summary>
        /// Returns a value which indicates failure when a OldConvertToAction of ImplicitTry or
        /// ExplicitTry.
        /// </summary>
        public static Expression GetTryConvertReturnValue(Type type)
        {
            Expression res;
            if (type.IsInterface() || type.IsClass()) {
                res = AstUtils.Constant(null, type);
            } else {
                res = AstUtils.Constant(null);
            }

            return res;
        }
 private object CreateProxyUsingCastleProxyGenerator(Type typeToProxy, Type[] additionalInterfaces,
                                                     object[] constructorArguments,
                                                     IInterceptor interceptor,
                                                     ProxyGenerationOptions proxyGenerationOptions)
 {
     if (typeToProxy.IsInterface())
     {
         VerifyNoConstructorArgumentsGivenForInterface(constructorArguments);
         return _proxyGenerator.CreateInterfaceProxyWithoutTarget(typeToProxy, additionalInterfaces, proxyGenerationOptions, interceptor);
     }
     return _proxyGenerator.CreateClassProxy(typeToProxy, additionalInterfaces, proxyGenerationOptions, constructorArguments, interceptor);
 }
Esempio n. 10
0
        public static IEnumerable<Type> GetImplementedInterfaces(Type type)
        {
            if (type.IsInterface())
            {
                yield return type;
            }

            foreach (var implementedInterface in type.GetInterfaces())
            {
                yield return implementedInterface;
            }
        }
        IProvider CreateProviderForType(
            Type contractType, IPrefabInstantiator instantiator)
        {
            if (contractType == typeof(GameObject))
            {
                return new PrefabGameObjectProvider(instantiator);
            }

            Assert.That(contractType.IsInterface() || contractType.DerivesFrom<Component>());

            return new GetFromPrefabComponentProvider(
                contractType, instantiator);
        }
Esempio n. 12
0
        public static void RegisterValidator(this Container container, Type validator, ReuseScope scope=ReuseScope.None)
        {
            var baseType = validator.BaseType();
            if (validator.IsInterface() || baseType == null) return;
            while (!baseType.IsGenericType())
            {
                baseType = baseType.BaseType();
            }

            var dtoType = baseType.GetGenericArguments()[0];
            var validatorType = typeof(IValidator<>).GetCachedGenericType(dtoType);

            container.RegisterAutoWiredType(validator, validatorType, scope);
        }
Esempio n. 13
0
        public CodeTypeReference(Type type) {
            if (type == null)
                throw new ArgumentNullException("type");
            
            if (type.IsArray) {
                this.arrayRank = type.GetArrayRank();
                this.arrayElementType = new CodeTypeReference(type.GetElementType());
                this.baseType = null;
            } else {
                InitializeFromType(type);
                this.arrayRank = 0;
                this.arrayElementType = null;
            }

            this.isInterface = type.IsInterface();
        }
		public object Create(Type type)
		{
			if (type.IsInterface())
			{
				Type implementationType;
				if (defaultInterfaceImplementations.TryGetValue(type.GetGenericTypeDefinition(), out implementationType))
				{
					type = implementationType.MakeGenericType(type.GetGenericArguments());
				}
			}

			try
			{
				return Activator.CreateInstance(type);
			}
			catch (Exception err)
			{
				var message = string.Format("Failed to create an instance of type '{0}'.", type);
				throw new InvalidOperationException(message, err);
			}
		}
Esempio n. 15
0
		protected void AddMapping(Type @interface, ITypeContributor implementer, IDictionary<Type, ITypeContributor> mapping)
		{
			Debug.Assert(implementer != null, "implementer != null");
			Debug.Assert(@interface != null, "@interface != null");
			Debug.Assert(@interface.IsInterface(), "@interface.IsInterface()");

			if (!mapping.ContainsKey(@interface))
			{
				AddMappingNoCheck(@interface, implementer, mapping);
			}
		}
Esempio n. 16
0
		internal Object InstantiateObject(Type objectType, out Dictionary<string, MemberInfo> memberMap)
		{
#if NETFX_CORE
            if (objectType.IsInterface() || objectType.IsAbstract() || objectType.IsValueType())
#else
			if (objectType.IsInterface || objectType.IsAbstract || objectType.IsValueType)
#endif
			{
				throw new JsonTypeCoercionException(
					String.Format(TypeCoercionUtility.ErrorCannotInstantiate, objectType.FullName));
			}

#if NETFX_CORE
            ConstructorInfo ctor = objectType.GetParameterlessConstructor();
#else
            ConstructorInfo ctor = objectType.GetConstructor(Type.EmptyTypes);
#endif
			if (ctor == null)
			{
				throw new JsonTypeCoercionException(
					String.Format(TypeCoercionUtility.ErrorDefaultCtor, objectType.FullName));
			}
			Object result;
			try
			{
				// always try-catch Invoke() to expose real exception
				result = ctor.Invoke(null);
			}
			catch (TargetInvocationException ex)
			{
				if (ex.InnerException != null)
				{
					throw new JsonTypeCoercionException(ex.InnerException.Message, ex.InnerException);
				}
				throw new JsonTypeCoercionException("Error instantiating " + objectType.FullName, ex);
			}

			memberMap = GetMemberMap (objectType);
			
			return result;
		}
Esempio n. 17
0
        // TODO: Put exception messages into the resources.
        //
        public static int GetInheritanceLevel(this Type type, Type @base)
        {
            type.EnsureNotNull(nameof(type));
            @base.EnsureNotNull(nameof(@base));
            if (!(type.IsClass() || type.IsInterface()))
            {
                throw new ArgumentException(message: FormatXResource(typeof(ArgumentException), "ValueIsInvalid/Type/NotClass", type), paramName: nameof(type));
            }
            else if (!(@base.IsClass() || @base.IsInterface()))
            {
                throw new ArgumentException(message: FormatXResource(typeof(ArgumentException), "ValueIsInvalid/Type/NotClass", @base), paramName: nameof(@base));
            }
            else if ([email protected](type))
            {
                throw new ArgumentException(message: FormatXResource(typeof(ArgumentException), "ValueIsInvalid/Type/InvalidDerivation", type, @base), paramName: nameof(type));
            }
            //
            Func <Type, Type, int> computeInheritanceLevelFunc = (b, d) => {
                var c = 0;
                for (c = 0; b != d;)
                {
                    c++;
                    d = d.BaseType();
                }
                return(c);
            };
            int level;

            if (@base.IsInterface())
            {
                if (type.IsInterface())
                {
                    level = computeInheritanceLevelFunc(@base, type);
                }
                else
                {
                    level = 0;
#if TRG_NETFRAMEWORK
                    InterfaceMapping currentInterfaceMapping;
                    for (; derivedClassOrInterface != null;)
                    {
                        currentInterfaceMapping = derivedClassOrInterface.GetInterfaceMap(baseClassOrInterface);
                        if (currentInterfaceMapping.TargetMethods != null && currentInterfaceMapping.TargetMethods.Length > 0)
                        {
                            break;
                        }
                        level++;
                        derivedClassOrInterface = derivedClassOrInterface.BaseType();
                    }
#endif
                }
            }
            else if (type.IsInterface())
            {
                throw new ArgumentException(message: FormatXResource(typeof(ArgumentException), "ValueIsInvalid"), paramName: nameof(type));
            }
            else
            {
                level = computeInheritanceLevelFunc(@base, type);
            }
            return(level);
        }
Esempio n. 18
0
 /// <summary>
 /// Returns true if the CLR type is treated as Ruby module (as opposed to a Ruby class)
 /// </summary>
 public static bool IsModuleType(Type/*!*/ type) {
     return type.IsInterface() || type.IsGenericTypeDefinition();
 }
Esempio n. 19
0
        internal static Convertibility CanConvertFrom(DynamicMetaObject fromArg, Type/*!*/ fromType, Type/*!*/ toType, bool toNotNullable,
            NarrowingLevel level, bool explicitProtocolConversions, bool implicitProtocolConversions)
        {
            ContractUtils.RequiresNotNull(fromType, "fromType");
            ContractUtils.RequiresNotNull(toType, "toType");

            var metaConvertible = fromArg as IConvertibleMetaObject;
            var rubyMetaConvertible = fromArg as IConvertibleRubyMetaObject;

            //
            // narrowing level 0:
            //

            if (toType == fromType) {
                return Convertibility.AlwaysConvertible;
            }

            if (fromType == typeof(DynamicNull)) {
                if (toNotNullable) {
                    return Convertibility.NotConvertible;
                }

                if (toType.IsGenericType() && toType.GetGenericTypeDefinition() == typeof(Nullable<>)) {
                    return Convertibility.AlwaysConvertible;
                }

                if (!toType.IsValueType()) {
                    // null convertible to any reference type:
                    return Convertibility.AlwaysConvertible;
                } else if (toType == typeof(bool)) {
                    return Convertibility.AlwaysConvertible;
                } else if (!ProtocolConversionAction.HasDefaultConversion(toType)) {
                    // null not convertible to a value type unless a protocol conversion is allowed:
                    return Convertibility.NotConvertible;
                }
            }

            // blocks:
            if (fromType == typeof(MissingBlockParam)) {
                return new Convertibility(toType == typeof(BlockParam) && !toNotNullable, null);
            }

            if (fromType == typeof(BlockParam) && toType == typeof(MissingBlockParam)) {
                return Convertibility.AlwaysConvertible;
            }

            if (toType.IsAssignableFrom(fromType)) {
                return Convertibility.AlwaysConvertible;
            }

            if (HasImplicitNumericConversion(fromType, toType)) {
                return Convertibility.AlwaysConvertible;
            }

            if (CompilerHelpers.GetImplicitConverter(fromType, toType) != null) {
                return Convertibility.AlwaysConvertible;
            }

            if (rubyMetaConvertible != null) {
                return rubyMetaConvertible.IsConvertibleTo(toType, false);
            } else if (metaConvertible != null) {
                return new Convertibility(metaConvertible.CanConvertTo(toType, false), null);
            }

            //
            // narrowing level 1:
            //

            if (level < NarrowingLevel.One) {
                return Convertibility.NotConvertible;
            }

            if (explicitProtocolConversions && ProtocolConversionAction.HasDefaultConversion(toType)) {
                return Convertibility.AlwaysConvertible;
            }

            //
            // narrowing level 2:
            //

            if (level < NarrowingLevel.Two) {
                return Convertibility.NotConvertible;
            }

            if (HasExplicitNumericConversion(fromType, toType)) {
                return Convertibility.AlwaysConvertible;
            }

            if (CompilerHelpers.GetExplicitConverter(fromType, toType) != null) {
                return Convertibility.AlwaysConvertible;
            }

            if (CompilerHelpers.HasTypeConverter(fromType, toType)) {
                return Convertibility.AlwaysConvertible;
            }

            if (fromType == typeof(char) && toType == typeof(string)) {
                return Convertibility.AlwaysConvertible;
            }

            if (toType == typeof(bool)) {
                return Convertibility.AlwaysConvertible;
            }

            if (rubyMetaConvertible != null) {
                return rubyMetaConvertible.IsConvertibleTo(toType, true);
            } else if (metaConvertible != null) {
                return new Convertibility(metaConvertible.CanConvertTo(toType, true), null);
            }

            //
            // narrowing level 3:
            //

            if (level < NarrowingLevel.Three) {
                return Convertibility.NotConvertible;
            }

            if (implicitProtocolConversions && ProtocolConversionAction.HasDefaultConversion(toType)) {
                return Convertibility.AlwaysConvertible;
            }

            // A COM object can potentially be converted to the given interface, but might also be not so use this only as the last resort:
            if (TypeUtils.IsComObjectType(fromType) && toType.IsInterface()) {
                return Convertibility.AlwaysConvertible;
            }

            return Convertibility.NotConvertible;
        }
Esempio n. 20
0
        // Helpers/Type
        private static IEnumerable <string> GetKeywords(this Type type)
        {
            if (!type.IsNested)
            {
                if (type.IsPublic)
                {
                    yield return("public");
                }
                else
                {
                    yield return("internal");
                }
            }
            else
            {
                if (type.IsNestedPublic)
                {
                    yield return("public");
                }
                if (type.IsNestedAssembly)
                {
                    yield return("internal");
                }
                if (type.IsNestedFamily)
                {
                    yield return("protected");
                }
                if (type.IsNestedFamORAssem)
                {
                    yield return("protected internal");                         // Can be accessed by any code in the assembly in which it's declared, or from within a derived class in another assembly.
                }
                if (type.IsNestedFamANDAssem)
                {
                    yield return("private protected");                          // Can be accessed only within its declaring assembly, by code in the same class or in a type that is derived from that class.
                }
                if (type.IsNestedPrivate)
                {
                    yield return("private");
                }
            }

            if (type.IsClass())
            {
                if (type.IsStatic())
                {
                    yield return("static");
                }
                if (type.IsAbstract())
                {
                    yield return("abstract");
                }
                if (type.IsSealed())
                {
                    yield return("sealed");
                }
            }

            if (type.IsInterface())
            {
                yield return("interface");
            }
            if (type.IsClass())
            {
                yield return("class");
            }
            if (type.IsStruct())
            {
                yield return("struct");
            }
            if (type.IsEnum())
            {
                yield return("enum");
            }
            if (type.IsDelegate())
            {
                yield return("delegate");
            }
        }
Esempio n. 21
0
            public override IList<Type/*!*/>/*!*/ GetContributingTypes(Type/*!*/ t) {
                Debug.Assert(t != null);

                List<Type> res = new List<Type>();

                IList<PythonType> mro = DynamicHelpers.GetPythonTypeFromType(t).ResolutionOrder;

                foreach (PythonType pt in mro) {
                    res.Add(pt.UnderlyingSystemType);
                }

                foreach (PythonType pt in mro) {
                    res.AddRange(Binder.GetExtensionTypesInternal(pt.UnderlyingSystemType));
                }

                if (t.IsInterface()) {
                    foreach (Type iface in t.GetInterfaces()) {
                        res.Add(iface);
                    }
                }

                return res;
            }
Esempio n. 22
0
        /// <summary>
        /// Provides a resolution for __hash__, first looking for IStructuralEquatable.GetHashCode,
        /// then IValueEquality.GetValueHashCode.
        /// </summary>
        private static MemberGroup/*!*/ HashResolver(MemberBinder/*!*/ binder, Type/*!*/ type) {
#if FEATURE_VALUE_EQUALITY
            if (typeof(IStructuralEquatable).IsAssignableFrom(type) && !type.IsInterface()) {
#else
            if ((typeof(IStructuralEquatable).IsAssignableFrom(type) ||
                 typeof(IValueEquality).IsAssignableFrom(type)) && !type.IsInterface) {
#endif
                // check and see if __hash__ has been overridden by the base type.
                foreach (Type t in binder.GetContributingTypes(type)) {
                    // if it's defined on object, it's not overridden
                    if (t == typeof(ObjectOps) || t == typeof(object)) {
                        break;
                    }

                    MemberInfo[] hash = t.GetMember("__hash__");
                    if (hash.Length > 0) {
                        return MemberGroup.EmptyGroup;
                    }
                }

#if FEATURE_VALUE_EQUALITY
                return GetInstanceOpsMethod(type, "StructuralHashMethod");
#else
                if (typeof(IStructuralEquatable).IsAssignableFrom(type)) {
                    return GetInstanceOpsMethod(type, "StructuralHashMethod");
                }

                if (typeof(IValueEquality).IsAssignableFrom(type)) {
                    return new MemberGroup(typeof(IValueEquality).GetMethod("GetValueHashCode"));
                }
#endif
            }

            // otherwise we'll pick up __hash__ from ObjectOps which will call .NET's .GetHashCode therefore
            // we don't explicitly search to see if the object overrides GetHashCode here.
            return MemberGroup.EmptyGroup;
        }
Esempio n. 23
0
            public override IList<Type/*!*/>/*!*/ GetInterfaces(Type/*!*/ t) {
                if (t.IsInterface()) {
                    return t.GetInterfaces();
                }

                Type[] allInterfaces = t.GetInterfaces();
                List<Type> res = new List<Type>();
                foreach (Type intf in allInterfaces) {
                    try {
                        InterfaceMapping imap = t.GetInterfaceMap(intf);
                        foreach (MethodInfo mi in imap.TargetMethods) {
                            if (mi != null && mi.DeclaringType == t) {
                                res.Add(intf);
                                break;
                            }
                        }
                    } catch (ArgumentException) {
                        // this fails when the CLR is manufacturing an interface
                        // type for a built in type.  For example IList<string>
                        // for Array[str].  This can be reproed by doing:
                        //
                        // import System
                        // System.Array[str].__dict__['__contains__']

                        // __contains__ is actually inherited from Array's IList
                        // implementation but IList<str> interferes here.
                    }
                }

                return res;
            }
 public List<MetadataAttribute> ToAttributes(Type type)
 {
     return !(type.IsUserType() || type.IsUserEnum() || type.IsInterface()) 
             || type.IsOrHasGenericInterfaceTypeOf(typeof(IEnumerable<>))
         ? null
         : ToAttributes(type.AllAttributes());
 }
    internal JsonContract(Type underlyingType)
    {
      ValidationUtils.ArgumentNotNull(underlyingType, "underlyingType");

      UnderlyingType = underlyingType;

      IsSealed = underlyingType.IsSealed();
      IsInstantiable = !(underlyingType.IsInterface() || underlyingType.IsAbstract());

      IsNullable = ReflectionUtils.IsNullable(underlyingType);
      NonNullableUnderlyingType = (IsNullable && ReflectionUtils.IsNullableType(underlyingType)) ? Nullable.GetUnderlyingType(underlyingType) : underlyingType;

      CreatedType = NonNullableUnderlyingType;

      IsConvertable = ConvertUtils.IsConvertible(NonNullableUnderlyingType);
      IsEnum = NonNullableUnderlyingType.IsEnum();

      if (NonNullableUnderlyingType == typeof(byte[]))
      {
        InternalReadType = ReadType.ReadAsBytes;
      }
      else if (NonNullableUnderlyingType == typeof(int))
      {
        InternalReadType = ReadType.ReadAsInt32;
      }
      else if (NonNullableUnderlyingType == typeof(decimal))
      {
        InternalReadType = ReadType.ReadAsDecimal;
      }
      else if (NonNullableUnderlyingType == typeof(string))
      {
        InternalReadType = ReadType.ReadAsString;
      }
      else if (NonNullableUnderlyingType == typeof(DateTime))
      {
        InternalReadType = ReadType.ReadAsDateTime;
      }
#if !NET20
      else if (NonNullableUnderlyingType == typeof(DateTimeOffset))
      {
        InternalReadType = ReadType.ReadAsDateTimeOffset;
      }
#endif
      else
      {
        InternalReadType = ReadType.Read;
      }
    }
        public HashSet<string> GetNamespacesUsed(Type type)
        {
            var to = new HashSet<string>();

            if (type.IsUserType() || type.IsInterface() || type.IsOrHasGenericInterfaceTypeOf(typeof(IEnumerable<>)))
            {
                foreach (var pi in GetInstancePublicProperties(type))
                {
                    if (pi.PropertyType.Namespace != null)
                    {
                        to.Add(pi.PropertyType.Namespace);
                    }

                    if (pi.PropertyType.IsGenericType())
                    {
                        pi.PropertyType.GetGenericArguments()
                            .Where(x => x.Namespace != null).Each(x => to.Add(x.Namespace));
                    }
                }

                if (type.IsGenericType())
                {
                    type.GetGenericArguments()
                        .Where(x => x.Namespace != null).Each(x => to.Add(x.Namespace));
                }
            }

            if (type.Namespace != null)
            {
                to.Add(type.Namespace);
            }

            return to;
        }
        public MetadataType ToType(Type type)
        {
            if (type == null) 
                return null;

            if (type.IsGenericType())
                type = type.GetGenericTypeDefinition();

            var metaType = new MetadataType
            {
                Name = type.GetOperationName(),
                Namespace = type.Namespace,
                GenericArgs = type.IsGenericType() ? GetGenericArgs(type) : null,
                Implements = ToInterfaces(type),
                Attributes = ToAttributes(type),
                Properties = ToProperties(type),
                IsNested = type.IsNested ? true : (bool?)null,
                IsEnum = type.IsEnum() ? true : (bool?)null,
                IsEnumInt = JsConfig.TreatEnumAsInteger || type.IsEnumFlags() ? true : (bool?)null,
                IsInterface = type.IsInterface() ? true : (bool?)null,
                IsAbstract = type.IsAbstract() ? true : (bool?)null,
            };

            if (type.BaseType() != null && type.BaseType() != typeof(object) && !type.IsEnum()
                && !type.HasInterface(typeof(IService)))
            {
                metaType.Inherits = ToTypeName(type.BaseType());
            }

            if (type.GetTypeWithInterfaceOf(typeof(IReturnVoid)) != null)
            {
                metaType.ReturnVoidMarker = true;
            }
            else
            {
                var genericMarker = type != typeof(IReturn<>)
                    ? type.GetTypeWithGenericTypeDefinitionOf(typeof(IReturn<>))
                    : null;

                if (genericMarker != null)
                {
                    var returnType = genericMarker.GetGenericArguments().First();
                    metaType.ReturnMarkerTypeName = ToTypeName(returnType);
                }
            }

            var routeAttrs = HostContext.AppHost.GetRouteAttributes(type).ToList();
            if (routeAttrs.Count > 0)
            {
                metaType.Routes = routeAttrs.ConvertAll(x =>
                    new MetadataRoute
                    {
                        Path = x.Path,
                        Notes = x.Notes,
                        Summary = x.Summary,
                        Verbs = x.Verbs,
                    });
            }

            metaType.Description = type.GetDescription();

            var dcAttr = type.GetDataContract();
            if (dcAttr != null)
            {
                metaType.DataContract = new MetadataDataContract
                {
                    Name = dcAttr.Name,
                    Namespace = dcAttr.Namespace,
                };
            }

            if (type.IsEnum())
            {
                metaType.EnumNames = new List<string>();
                metaType.EnumValues = new List<string>();

                var isDefaultLayout = true;
                var values = Enum.GetValues(type);
                for (var i = 0; i < values.Length; i++)
                {
                    var value = values.GetValue(i);
                    var name = value.ToString();
                    var enumValue = Convert.ToInt64(value).ToString();

                    if (enumValue != i.ToString())
                        isDefaultLayout = false;

                    metaType.EnumNames.Add(name);
                    metaType.EnumValues.Add(enumValue);
                }

                if (isDefaultLayout)
                    metaType.EnumValues = null;
            }

            var innerTypes = type.GetNestedTypes(BindingFlags.Public | BindingFlags.NonPublic);
            foreach (var innerType in innerTypes)
            {
                if (metaType.InnerTypes == null)
                    metaType.InnerTypes = new List<MetadataTypeName>();

                metaType.InnerTypes.Add(new MetadataTypeName
                {
                    Name = innerType.GetOperationName(),
                    Namespace = innerType.Namespace,
                    GenericArgs = innerType.IsGenericType()
                        ? innerType.GetGenericArguments().Select(x => x.GetOperationName()).ToArray()
                        : null,
                });
            }

            return metaType;
        }
Esempio n. 28
0
        /// <summary>
        /// Overrides methods - this includes all accessible virtual methods as well as protected non-virtual members
        /// including statics and non-statics.
        /// </summary>
        private void OverrideMethods(Type type, Dictionary<string, string[]> specialNames) {
            // if we have conflicting virtual's do to new slots only override the methods on the
            // most derived class.
            Dictionary<KeyValuePair<string, MethodSignatureInfo>, MethodInfo> added = new Dictionary<KeyValuePair<string, MethodSignatureInfo>, MethodInfo>();

            MethodInfo overridden;
            MethodInfo[] methods = type.GetMethods(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static | BindingFlags.FlattenHierarchy);

            foreach (MethodInfo mi in methods) {
                KeyValuePair<string, MethodSignatureInfo> key = new KeyValuePair<string, MethodSignatureInfo>(mi.Name, new MethodSignatureInfo(mi));

                if (!added.TryGetValue(key, out overridden)) {
                    added[key] = mi;
                    continue;
                }

                if (overridden.DeclaringType.IsAssignableFrom(mi.DeclaringType)) {
                    added[key] = mi;
                }
            }
            
            if (type.IsAbstract() && !type.IsInterface()) {
                // abstract types can define interfaces w/o implementations
                foreach (Type iface in type.GetInterfaces()) {
                    InterfaceMapping mapping = type.GetInterfaceMap(iface);
                    for (int i = 0; i < mapping.TargetMethods.Length; i++) {
                        
                        if (mapping.TargetMethods[i] == null) {
                            MethodInfo mi = mapping.InterfaceMethods[i];

                            KeyValuePair<string, MethodSignatureInfo> key = new KeyValuePair<string, MethodSignatureInfo>(mi.Name, new MethodSignatureInfo(mi));

                            added[key] = mi;
                        }
                    }
                }
            }

            Dictionary<PropertyInfo, PropertyBuilder> overriddenProperties = new Dictionary<PropertyInfo, PropertyBuilder>();
            foreach (MethodInfo mi in added.Values) {
                if (!CanOverrideMethod(mi)) continue;

                if (mi.IsPublic || mi.IsProtected()) {
                    if (mi.IsSpecialName) {
                        OverrideSpecialName(mi, specialNames, overriddenProperties);
                    } else {
                        OverrideBaseMethod(mi, specialNames);
                    }
                }
            }
        }
        public List<MetadataPropertyType> ToProperties(Type type)
        {
            var props = (!type.IsUserType() && !type.IsInterface() && !type.IsTuple()) || type.IsOrHasGenericInterfaceTypeOf(typeof(IEnumerable<>))
                ? null
                : GetInstancePublicProperties(type).Select(x => ToProperty(x)).ToList();

            return props == null || props.Count == 0 ? null : props;
        }
Esempio n. 30
0
File: Lua.cs Progetto: JCH2k/NLua
		/// <summary>
		/// Adds an entry to <see cref = "globals"/> (recursivley handles 2 levels of members)
		/// </summary>
		/// <param name = "path">The index accessor path ot the entry</param>
		/// <param name = "type">The type of the entry</param>
		/// <param name = "recursionCounter">How deep have we gone with recursion?</param>
		private void RegisterGlobal (string path, Type type, int recursionCounter)
		{
			// If the type is a global method, list it directly
			if (type == typeof(LuaNativeFunction)) {
				// Format for easy method invocation
				globals.Add (path + "(");
			}
			// If the type is a class or an interface and recursion hasn't been running too long, list the members
			else if ((type.IsClass () || type.IsInterface ()) && type != typeof(string) && recursionCounter < 2) {
				#region Methods
				foreach (var method in type.GetMethods(BindingFlags.Public | BindingFlags.Instance)) {
					string name = method.Name;
					if (
						// Check that the LuaHideAttribute and LuaGlobalAttribute were not applied
						(!method.GetCustomAttributes (typeof(LuaHideAttribute), false).Any ()) &&
						(!method.GetCustomAttributes (typeof(LuaGlobalAttribute), false).Any ()) &&
					// Exclude some generic .NET methods that wouldn't be very usefull in Lua
						name != "GetType" && name != "GetHashCode" && name != "Equals" &&
						name != "ToString" && name != "Clone" && name != "Dispose" &&
						name != "GetEnumerator" && name != "CopyTo" &&
						!name.StartsWith ("get_", StringComparison.Ordinal) &&
						!name.StartsWith ("set_", StringComparison.Ordinal) &&
						!name.StartsWith ("add_", StringComparison.Ordinal) &&
						!name.StartsWith ("remove_", StringComparison.Ordinal)) {
						// Format for easy method invocation
						string command = path + ":" + name + "(";

						if (method.GetParameters ().Length == 0)
							command += ")";
						globals.Add (command);
					}
				}
				#endregion

				#region Fields
				foreach (var field in type.GetFields(BindingFlags.Public | BindingFlags.Instance)) {
					if (
						// Check that the LuaHideAttribute and LuaGlobalAttribute were not applied
						(!field.GetCustomAttributes (typeof(LuaHideAttribute), false).Any ()) &&
						(!field.GetCustomAttributes (typeof(LuaGlobalAttribute), false).Any ())) {
						// Go into recursion for members
						RegisterGlobal (path + "." + field.Name, field.FieldType, recursionCounter + 1);
					}
				}
				#endregion

				#region Properties
				foreach (var property in type.GetProperties (BindingFlags.Public | BindingFlags.Instance)) {
					if (
						// Check that the LuaHideAttribute and LuaGlobalAttribute were not applied
						(!property.GetCustomAttributes (typeof(LuaHideAttribute), false).Any ()) &&
						(!property.GetCustomAttributes (typeof(LuaGlobalAttribute), false).Any ())
					// Exclude some generic .NET properties that wouldn't be very useful in Lua
						&& property.Name != "Item") {
						// Go into recursion for members
						RegisterGlobal (path + "." + property.Name, property.PropertyType, recursionCounter + 1);
					}
				}
				#endregion
			} else
				globals.Add (path); // Otherwise simply add the element to the list

			// List will need to be sorted on next access
			globalsSorted = false;
		}
Esempio n. 31
0
		internal ExtractValue CheckLuaType (LuaState luaState, int stackPos, Type paramType)
		{
			var luatype = LuaLib.LuaType (luaState, stackPos);

			if (paramType.IsByRef)
				paramType = paramType.GetElementType ();

			var underlyingType = Nullable.GetUnderlyingType (paramType);
			
			if (underlyingType != null) {
				paramType = underlyingType;	 // Silently convert nullable types to their non null requics
			}

			var extractKey = GetExtractDictionaryKey (paramType);
			
			bool netParamIsNumeric = paramType == typeof (int) ||
									 paramType == typeof (uint) ||
									 paramType == typeof (long) ||
									 paramType == typeof (ulong) ||
									 paramType == typeof (short) ||
									 paramType == typeof (ushort) ||
									 paramType == typeof (float) ||
									 paramType == typeof (double) ||
									 paramType == typeof (decimal) ||
									 paramType == typeof (byte);

			// If it is a nullable
			if (underlyingType != null) {
				// null can always be assigned to nullable
				if (luatype == LuaTypes.Nil) {
					// Return the correct extractor anyways
					if (netParamIsNumeric || paramType == typeof (bool))
						return extractValues [extractKey];
					return extractNetObject;
				}
			}

			if (paramType.Equals (typeof(object)))
				return extractValues [extractKey];

			//CP: Added support for generic parameters
			if (paramType.IsGenericParameter) {
				if (luatype == LuaTypes.Boolean)
					return extractValues [GetExtractDictionaryKey (typeof(bool))];
				else if (luatype == LuaTypes.String)
					return extractValues[GetExtractDictionaryKey (typeof(string))];
				else if (luatype == LuaTypes.Table)
					return extractValues [GetExtractDictionaryKey (typeof(LuaTable))];
				else if (luatype == LuaTypes.UserData)
					return extractValues [GetExtractDictionaryKey (typeof(object))];
				else if (luatype == LuaTypes.Function)
					return extractValues [GetExtractDictionaryKey (typeof(LuaFunction))];
				else if (luatype == LuaTypes.Number)
					return extractValues [GetExtractDictionaryKey (typeof(double))];
			}
			bool netParamIsString = paramType == typeof (string) || paramType == typeof (char []);

			if (netParamIsNumeric) {
				if (LuaLib.LuaIsNumber (luaState, stackPos) && !netParamIsString)
					return extractValues [extractKey];
			} else if (paramType == typeof(bool)) {
				if (LuaLib.LuaIsBoolean (luaState, stackPos))
					return extractValues [extractKey];
			} else if (netParamIsString) {
				if (LuaLib.LuaNetIsStringStrict (luaState, stackPos))
					return extractValues [extractKey];
				else if (luatype == LuaTypes.Nil)
					return extractNetObject; // kevinh - silently convert nil to a null string pointer
			} else if (paramType == typeof(LuaTable)) {
				if (luatype == LuaTypes.Table || luatype == LuaTypes.Nil)
					return extractValues [extractKey];
			} else if (paramType == typeof(LuaUserData)) {
				if (luatype == LuaTypes.UserData || luatype == LuaTypes.Nil)
					return extractValues [extractKey];
			} else if (paramType == typeof(LuaFunction)) {
				if (luatype == LuaTypes.Function || luatype == LuaTypes.Nil)
					return extractValues [extractKey];
			} else if (typeof(Delegate).IsAssignableFrom (paramType) && luatype == LuaTypes.Function)
				return new ExtractValue (new DelegateGenerator (translator, paramType).ExtractGenerated);
			else if (paramType.IsInterface() && luatype == LuaTypes.Table)
				return new ExtractValue (new ClassGenerator (translator, paramType).ExtractGenerated);
			else if ((paramType.IsInterface() || paramType.IsClass()) && luatype == LuaTypes.Nil) {
				// kevinh - allow nil to be silently converted to null - extractNetObject will return null when the item ain't found
				return extractNetObject;
			} else if (LuaLib.LuaType (luaState, stackPos) == LuaTypes.Table) {
				if (LuaLib.LuaLGetMetafield (luaState, stackPos, "__index")) {
					object obj = translator.GetNetObject (luaState, -1);
					LuaLib.LuaSetTop (luaState, -2);
					if (obj != null && paramType.IsAssignableFrom (obj.GetType ()))
						return extractNetObject;
				} else
					return null;
			} else {
				object obj = translator.GetNetObject (luaState, stackPos);
				if (obj != null && paramType.IsAssignableFrom (obj.GetType ()))
					return extractNetObject;
			}

			return null;
		}
Esempio n. 32
0
		void GetReturnTypesFromClass (Type klass, out Type[][] returnTypes)
		{
			var classMethods = klass.GetMethods ();
			returnTypes = new Type[classMethods.Length][];

			int i = 0;

			foreach (var method in classMethods) {
				if (klass.IsInterface ()) {
					GetReturnTypesFromMethod (method, out returnTypes [i]);
					i++;
				} else {
					if (!method.IsPrivate && !method.IsFinal && method.IsVirtual) {
						GetReturnTypesFromMethod (method, out returnTypes [i]);
						i++;
					}
				}
			}
		}