AddInterfaceImplementation() public method

public AddInterfaceImplementation ( System interfaceType ) : void
interfaceType System
return void
		public void ImplementProxy(TypeBuilder typeBuilder)
		{
			// Implement the IProxy interface
			typeBuilder.AddInterfaceImplementation(typeof (IProxy));

			field = typeBuilder.DefineField("__interceptor", typeof (IInterceptor), FieldAttributes.Private);

			// Implement the getter
			MethodBuilder getterMethod = typeBuilder.DefineMethod("get_Interceptor", InterceptorMethodsAttributes, CallingConventions.HasThis, typeof(IInterceptor), new System.Type[0]);
			getterMethod.SetImplementationFlags(MethodImplAttributes.Managed | MethodImplAttributes.IL);

			ILGenerator IL = getterMethod.GetILGenerator();

			// This is equivalent to:
			// get { return __interceptor;
			IL.Emit(OpCodes.Ldarg_0);
			IL.Emit(OpCodes.Ldfld, field);
			IL.Emit(OpCodes.Ret);

			// Implement the setter
			MethodBuilder setterMethod = typeBuilder.DefineMethod("set_Interceptor", InterceptorMethodsAttributes, CallingConventions.HasThis, typeof (void), new[] {typeof (IInterceptor)});

			setterMethod.SetImplementationFlags(MethodImplAttributes.Managed | MethodImplAttributes.IL);
			IL = setterMethod.GetILGenerator();
			IL.Emit(OpCodes.Ldarg_0);
			IL.Emit(OpCodes.Ldarg_1);
			IL.Emit(OpCodes.Stfld, field);
			IL.Emit(OpCodes.Ret);

			MethodInfo originalSetter = typeof (IProxy).GetMethod("set_Interceptor");
			MethodInfo originalGetter = typeof (IProxy).GetMethod("get_Interceptor");

			typeBuilder.DefineMethodOverride(setterMethod, originalSetter);
			typeBuilder.DefineMethodOverride(getterMethod, originalGetter);
		}
		public void ImplementProxy(TypeBuilder typeBuilder)
		{
			typeBuilder.AddInterfaceImplementation(typeof (IProxy));
			InterceptorField = typeBuilder
				.DefineField("__interceptor",
							 typeof (Proxy.DynamicProxy.IInterceptor),
							 FieldAttributes.Private);
			var getterMethod = typeBuilder
				.DefineMethod("get_Interceptor",
							  InterceptorMethodsAttributes,
							  CallingConventions.HasThis,
							  typeof (Proxy.DynamicProxy.IInterceptor),
							  new System.Type[0]);
			getterMethod.SetImplementationFlags(MethodImplAttributes.IL);
			var il = getterMethod.GetILGenerator();
			il.Emit(OpCodes.Ldarg_0);
			il.Emit(OpCodes.Ldfld, InterceptorField);
			il.Emit(OpCodes.Ret);
			var setterMethod = typeBuilder
				.DefineMethod("set_Interceptor",
							  InterceptorMethodsAttributes,
							  CallingConventions.HasThis,
							  typeof (void),
							  new[] {typeof (Proxy.DynamicProxy.IInterceptor)});
			setterMethod.SetImplementationFlags(MethodImplAttributes.IL);
			il = setterMethod.GetILGenerator();
			il.Emit(OpCodes.Ldarg_0);
			il.Emit(OpCodes.Ldarg_1);
			il.Emit(OpCodes.Stfld, InterceptorField);
			il.Emit(OpCodes.Ret);
			var originalSetter = typeof (IProxy).GetMethod("set_Interceptor");
			var originalGetter = typeof (IProxy).GetMethod("get_Interceptor");
			typeBuilder.DefineMethodOverride(setterMethod, originalSetter);
			typeBuilder.DefineMethodOverride(getterMethod, originalGetter);
		}
        /// <summary>
        /// Generates the type.
        /// </summary>
        /// <returns></returns>
        public Type GenerateType()
        {
            if (_generatedType == null)
            {
                // Setup the assembly and type builder
                AssemblyName assemblyName = new AssemblyName("Mock.Generated-" + _interfaceToImplement.Name);
                AssemblyBuilder assemblyBuilder = Thread.GetDomain().DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Run);
                ModuleBuilder moduleBuilder = assemblyBuilder.DefineDynamicModule(assemblyName.Name);
                _typeBuilder = moduleBuilder.DefineType("Mock.Generated.Mock" + _interfaceToImplement.Name, TypeAttributes.Public);
                _typeBuilder.AddInterfaceImplementation(_interfaceToImplement);

                // Generate the body of the type
                this.CreateFields();
                this.CreateConstructor();
                foreach (MethodInfo method in _interfaceToImplement.GetMethods(BindingFlags.Public | BindingFlags.Instance).Where(m => !m.Name.StartsWith("get_")))
                {
                    this.ImplementMethod(method);
                }
                foreach (PropertyInfo property in _interfaceToImplement.GetProperties(BindingFlags.Public | BindingFlags.Instance))
                {
                    this.ImplementProperty(property);
                }

                // Store the generated type for use again
                _generatedType = _typeBuilder.CreateType();
            }
            return _generatedType;
        }
Example #4
0
        private void ImplementInterfaceProperties(Type interfaceOfTypeToCreate, System.Reflection.Emit.TypeBuilder typeBuilder)
        {
            typeBuilder.AddInterfaceImplementation(interfaceOfTypeToCreate);
            foreach (var implementedInterfaceType in interfaceOfTypeToCreate.GetInterfaces())
            {
                ImplementInterfaceProperties(implementedInterfaceType, typeBuilder);
            }

            foreach (var pi in interfaceOfTypeToCreate.GetProperties())
            {
                var backingFieldBuilder = typeBuilder.DefineField($"{interfaceOfTypeToCreate.Name}._{ToCamelCase(pi.Name)}", pi.PropertyType, FieldAttributes.Private);

                var accessorAttributes = MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.Virtual | MethodAttributes.HideBySig;

                var mbGetAccessor = typeBuilder.DefineMethod($"get_{pi.Name}", accessorAttributes, pi.PropertyType, Type.EmptyTypes);
                var mbGetIL       = mbGetAccessor.GetILGenerator();
                mbGetIL.Emit(OpCodes.Ldarg_0);
                mbGetIL.Emit(OpCodes.Ldfld, backingFieldBuilder);
                mbGetIL.Emit(OpCodes.Ret);

                var mbSetAccessor = typeBuilder.DefineMethod($"set_{pi.Name}", accessorAttributes, null, new[] { pi.PropertyType });
                var mbSetIL       = mbSetAccessor.GetILGenerator();
                mbSetIL.Emit(OpCodes.Ldarg_0);
                mbSetIL.Emit(OpCodes.Ldarg_1);
                mbSetIL.Emit(OpCodes.Stfld, backingFieldBuilder);
                mbSetIL.Emit(OpCodes.Ret);

                var propertyBuilder = typeBuilder.DefineProperty(pi.Name, PropertyAttributes.HasDefault, pi.PropertyType, null);
                propertyBuilder.SetGetMethod(mbGetAccessor);
                propertyBuilder.SetSetMethod(mbSetAccessor);
            }
        }
        // 构造类型
        void BuildType()
        {
            _typeBuilder = _moduleBuilder.DefineType(string.Format(TypeNameFormat, _realProxyType.Name),
                TypeAttributes.Public | TypeAttributes.Sealed);
            _typeBuilder.AddInterfaceImplementation(_interfaceType);

            //if ( _baseType!=null)
            //    _typeBuilder.SetParent(_baseType);

        }
        internal static FieldBuilder ImplementIInterceptingProxy(TypeBuilder typeBuilder)
        {
            typeBuilder.AddInterfaceImplementation(typeof(IInterceptingProxy));
            FieldBuilder proxyInterceptorPipelineField =
                typeBuilder.DefineField(
                    "pipeline",
                    typeof(InterceptionBehaviorPipeline),
                    FieldAttributes.Private | FieldAttributes.InitOnly);

            ImplementAddInterceptionBehavior(typeBuilder, proxyInterceptorPipelineField);

            return proxyInterceptorPipelineField;
        }
Example #7
0
        public Type CreateType(String typeName, Type parent)
        {
            _typeBuilder = _moduleBuilder.DefineType(typeName,
                                                                  TypeAttributes.Public | TypeAttributes.Class | TypeAttributes.AutoClass |
                                                                  TypeAttributes.AnsiClass | TypeAttributes.BeforeFieldInit | TypeAttributes.AutoLayout,
                                                                  parent, new[] { typeof(IProxy) });
            _typeBuilder.AddInterfaceImplementation(typeof(IProxy));

            ImplementProxyInterface(parent);
            var propHandlerDic = OverrideProperties(parent);
            GenerateConstructor(propHandlerDic);

            return _typeBuilder.CreateType();
        }
        public void Build(TypeBuilder builder, Type contractType)
        {
            builder.AddInterfaceImplementation(typeof(IAutoNotifyPropertyChanged));

            FieldBuilder addPropertyChangedField = builder.DefineField("PropertyChanged", typeof (PropertyChangingEventHandler), FieldAttributes.Private);

            MethodBuilder addMethod = DefineAddOnMethod(builder, addPropertyChangedField);
            MethodBuilder removeMethod = DefineRemoveOnMethod(builder, addPropertyChangedField);
            MethodBuilder notifyPropertyChangedMethod = DefineRaiseMethod(builder, addPropertyChangedField);

            EventBuilder pcevent = builder.DefineEvent("PropertyChanged", EventAttributes.None, typeof(PropertyChangedEventHandler));
            pcevent.SetRaiseMethod(notifyPropertyChangedMethod);
            pcevent.SetAddOnMethod(addMethod);
            pcevent.SetRemoveOnMethod(removeMethod);
        }
 public void ImplementProxy(TypeBuilder b)
 {
     var dynamicProxyType = typeof(IDynamicProxy);
     b.AddInterfaceImplementation(dynamicProxyType);
     _fieldBuilder = b.DefineField("__interceptor", typeof(IMethodInterceptor), FieldAttributes.Private);
     const MethodAttributes attributes = MethodAttributes.SpecialName | MethodAttributes.VtableLayoutMask | MethodAttributes.HideBySig | MethodAttributes.Virtual | MethodAttributes.Public;
     var getMethodBuilder = b.DefineMethod("get_Interceptor", attributes, CallingConventions.HasThis, typeof(IMethodInterceptor), new Type[0]);
     getMethodBuilder.SetImplementationFlags(MethodImplAttributes.IL);
     var w = getMethodBuilder.GetILGenerator();
     w.Emit(OpCodes.Ldarg_0);
     w.Emit(OpCodes.Ldfld, _fieldBuilder);
     w.Emit(OpCodes.Ret);
     var setMethodBuilder = b.DefineMethod("set_Interceptor", attributes, CallingConventions.HasThis, typeof(void), new Type[] { typeof(IMethodInterceptor) });
     setMethodBuilder.SetImplementationFlags(MethodImplAttributes.IL);
     w = setMethodBuilder.GetILGenerator();
     w.Emit(OpCodes.Ldarg_0);
     w.Emit(OpCodes.Ldarg_1);
     w.Emit(OpCodes.Stfld, _fieldBuilder);
     w.Emit(OpCodes.Ret);
     b.DefineMethodOverride(setMethodBuilder, dynamicProxyType.GetMethod("set_Interceptor"));
     b.DefineMethodOverride(getMethodBuilder, dynamicProxyType.GetMethod("get_Interceptor"));
 }
		public static void Implement (TypeBuilder typeB, Type iface)
		{
			typeB.AddInterfaceImplementation (iface);

			foreach (MethodInfo declMethod in iface.GetMethods ()) {

				MethodBuilder method_builder = typeB.DefineMethod (declMethod.Name, MethodAttributes.Public | MethodAttributes.Virtual, declMethod.ReturnType, Mapper.GetTypes (ArgDirection.In, declMethod.GetParameters ()));
				ILGenerator ilg = method_builder.GetILGenerator ();

				//Mapper.GetTypes (ArgDirection.In, declMethod.GetParameters ())

				ParameterInfo[] delegateParms = declMethod.GetParameters ();
				Type[] hookupParms = new Type[delegateParms.Length+1];
				hookupParms[0] = typeof (BusObject);
				for (int i = 0; i < delegateParms.Length ; i++)
					hookupParms[i+1] = delegateParms[i].ParameterType;

				GenHookupMethod (ilg, declMethod, sendMethodCallMethod, Mapper.GetInterfaceName (iface), declMethod.Name, hookupParms);

				typeB.DefineMethodOverride (method_builder, declMethod);
			}
		}
Example #11
0
        private void DefineMethodWithInterfaces(TypeBuilder typeBuilder)
        {
            var interfaceList = new List <Type>(interfaceTypes);

            if (interfaceList.Any())
            {
                var i = 0;

                for (var interfaceType = interfaceList[0]; i < interfaceList.Count; ++i)
                {
                    interfaceType = interfaceList[i];

                    typeBuilder.AddInterfaceImplementation(interfaceType);

                    foreach (var interfaceMethod in interfaceType.GetMethods())
                    {
                        if (methodMappingMap.TryGetValue(interfaceMethod.Name, out var methodMapping) == false)
                        {
                            methodMappingMap[interfaceMethod.Name] = methodMapping = DefineMethod(typeBuilder, interfaceMethod);
                        }

                        methodMapping.Insert(methodMapping.Count, interfaceMethod);

                        typeBuilder.DefineMethodOverride(methodMapping.MethodBuilder, interfaceMethod);
                    }

                    foreach (var nestedInterfaceType in interfaceType.GetInterfaces())
                    {
                        if (interfaceList.Contains(nestedInterfaceType))
                        {
                            continue;
                        }

                        interfaceList.Insert(interfaceList.Count, nestedInterfaceType);
                    }
                }
            }
        }
Example #12
0
		public static void Implement (TypeBuilder typeB, Type iface)
		{
			typeB.AddInterfaceImplementation (iface);

			foreach (MethodInfo declMethod in iface.GetMethods ()) {
				ParameterInfo[] parms = declMethod.GetParameters ();

				Type[] parmTypes = new Type[parms.Length];
				for (int i = 0 ; i < parms.Length ; i++)
					parmTypes[i] = parms[i].ParameterType;

				MethodAttributes attrs = declMethod.Attributes ^ MethodAttributes.Abstract;
				MethodBuilder method_builder = typeB.DefineMethod (declMethod.Name, attrs, declMethod.ReturnType, parmTypes);
				typeB.DefineMethodOverride (method_builder, declMethod);

				//define in/out/ref/name for each of the parameters
				for (int i = 0; i < parms.Length ; i++)
					method_builder.DefineParameter (i, parms[i].Attributes, parms[i].Name);

				ILGenerator ilg = method_builder.GetILGenerator ();
				GenHookupMethod (ilg, declMethod, sendMethodCallMethod, Mapper.GetInterfaceName (iface), declMethod.Name);
			}
		}
        /// <summary>
        /// Implements an interface.
		/// </summary>
        /// <remarks>
        /// Generates proxy methods that belongs to the interface 
        /// using the specified <paramref name="proxyMethodBuilder"/>.
        /// </remarks>
        /// <param name="typeBuilder">The type builder to use.</param>
        /// <param name="proxyMethodBuilder">
        /// The <see cref="IProxyMethodBuilder"/> implementation to use
        /// </param>
        /// <param name="intf">The interface to implement.</param>
        /// <param name="targetType">
        /// The <see cref="System.Type"/> of the target object.
        /// </param>
        /// <param name="proxyVirtualMethods">
        /// <see langword="false"/> if target virtual methods should not be proxied;
        /// otherwise <see langword="true"/>.
        /// </param>
		protected virtual void ImplementInterface(TypeBuilder typeBuilder,
            IProxyMethodBuilder proxyMethodBuilder, Type intf, 
            Type targetType, bool proxyVirtualMethods)
		{
            Dictionary<string, MethodBuilder> methodMap = new Dictionary<string, MethodBuilder>();

            InterfaceMapping mapping = GetInterfaceMapping(targetType, intf);

            typeBuilder.AddInterfaceImplementation(intf);

            for (int i = 0; i < mapping.InterfaceMethods.Length; i++)
			{
                if (!proxyVirtualMethods && 
                    !mapping.TargetMethods[i].DeclaringType.IsInterface &&
                    mapping.TargetMethods[i].IsVirtual &&
                    !mapping.TargetMethods[i].IsFinal)
                    continue;

                MethodBuilder methodBuilder = proxyMethodBuilder.BuildProxyMethod(
                    mapping.TargetMethods[i], mapping.InterfaceMethods[i]);

                ApplyMethodAttributes(methodBuilder, mapping.TargetMethods[i]);

                methodMap[mapping.InterfaceMethods[i].Name] = methodBuilder;
			}
			foreach (PropertyInfo property in intf.GetProperties())
			{
                ImplementProperty(typeBuilder, intf, property, methodMap);
			}
			foreach (EventInfo evt in intf.GetEvents())
			{
                ImplementEvent(typeBuilder, intf, evt, methodMap);
			}
		}
Example #14
0
        public Type Compile(Type superType, Type stubType, IPersistentVector interfaces, bool onetimeUse, GenContext context)
        {
            if (_compiledType != null)
                return _compiledType;

            string publicTypeName = IsDefType || (_isStatic && Compiler.IsCompiling) ? InternalName : InternalName + "__" + RT.nextID();

            _typeBuilder = context.AssemblyGen.DefinePublicType(publicTypeName, superType, true);
            context = context.WithNewDynInitHelper().WithTypeBuilder(_typeBuilder);

            Var.pushThreadBindings(RT.map(Compiler.CompilerContextVar, context));

            try
            {
                if (interfaces != null)
                {
                    for (int i = 0; i < interfaces.count(); i++)
                        _typeBuilder.AddInterfaceImplementation((Type)interfaces.nth(i));
                }

                ObjExpr.MarkAsSerializable(_typeBuilder);
                GenInterface.SetCustomAttributes(_typeBuilder, _classMeta);

                try
                {
                    if (IsDefType)
                    {
                        Compiler.RegisterDuplicateType(_typeBuilder);

                        Var.pushThreadBindings(RT.map(
                            Compiler.CompileStubOrigClassVar, stubType
                            ));
                        //,
                        //Compiler.COMPILE_STUB_CLASS, _baseType));
                    }
                    EmitConstantFieldDefs(_typeBuilder);
                    EmitKeywordCallsiteDefs(_typeBuilder);

                    DefineStaticConstructor(_typeBuilder);

                    if (SupportsMeta)
                        _metaField = _typeBuilder.DefineField("__meta", typeof(IPersistentMap), FieldAttributes.Public | FieldAttributes.InitOnly);

                    // If this IsDefType, then it has already emitted the closed-over fields on the base class.
                    if ( ! IsDefType )
                        EmitClosedOverFields(_typeBuilder);
                    EmitProtocolCallsites(_typeBuilder);

                    _ctorInfo = EmitConstructor(_typeBuilder, superType);

                    if (_altCtorDrops > 0)
                        EmitFieldOnlyConstructor(_typeBuilder, superType);

                    if (SupportsMeta)
                    {
                        EmitNonMetaConstructor(_typeBuilder, superType);
                        EmitMetaFunctions(_typeBuilder);
                    }

                    EmitStatics(_typeBuilder);
                    EmitMethods(_typeBuilder);

                    //if (KeywordCallsites.count() > 0)
                    //    EmitSwapThunk(_typeBuilder);

                    _compiledType = _typeBuilder.CreateType();

                    if (context.DynInitHelper != null)
                        context.DynInitHelper.FinalizeType();

                    _ctorInfo = GetConstructorWithArgCount(_compiledType, CtorTypes().Length);

                    return _compiledType;
                }
                finally
                {
                    if (IsDefType)
                        Var.popThreadBindings();
                }
            }
            finally
            {
                Var.popThreadBindings();
            }
        }
Example #15
0
        private void GenerateFnClass(IPersistentVector interfaces, GenContext context)
        {
            string publicTypeName = IsDefType || (IsStatic && Compiler.IsCompiling) ? _internalName : _internalName + "__" + RT.nextID();

            //Console.WriteLine("DefFn {0}, {1}", publicTypeName, context.AssemblyBuilder.GetName().Name);

            _typeBuilder = context.AssemblyGen.DefinePublicType(publicTypeName, _baseType, true);
            for (int i = 0; i < interfaces.count(); i++)
                _typeBuilder.AddInterfaceImplementation((Type)interfaces.nth(i));

            MarkAsSerializable(_typeBuilder);

            GenInterface.SetCustomAttributes(_typeBuilder, _classMeta);

            GenerateStaticConstructor(_typeBuilder, _baseType, context.IsDebuggable);
            _ctorInfo = GenerateConstructor(_typeBuilder, _baseType);

            if (_altCtorDrops > 0)
                GenerateFieldOnlyConstructor(_typeBuilder, _baseType);

            if (SupportsMeta)
            {
                _nonmetaCtorInfo = GenerateNonMetaConstructor(_typeBuilder, _baseType);
            }
            GenerateMetaFunctions(_typeBuilder);

            //GenerateReloadVarsMethod(_typeBuilder, context);

            // The incoming context holds info on the containing function.
            // That is the one that holds the closed-over variable values.

            //GenContext newContext = CreateContext(context, _typeBuilder, _baseType);
            //GenerateMethods(newContext);
            GenerateStatics(context);
            GenerateMethods(context);
        }
        /// <summary>
        /// Implements the proxy interceptor fields.
        /// </summary>
        /// <param name="typeBuilder">
        /// The <see cref="TypeBuilder"/> for the current proxy type.
        /// </param>
        /// <returns>
        /// The <see cref="FieldBuilder"/> for the interceptor.
        /// </returns>
        public static FieldBuilder Emit(TypeBuilder typeBuilder)
        {
            // Implement the IProxy interface
            typeBuilder.AddInterfaceImplementation(typeof(IProxy));

            // Define the private "interceptor" filed.
            FieldBuilder fieldBuilder = typeBuilder.DefineField("interceptor", typeof(IInterceptor), FieldAttributes.Private);

            // Define the correct attributes fot the property. This makes it public virtual.
            const MethodAttributes Attributes = MethodAttributes.Public | MethodAttributes.HideBySig |
                                                MethodAttributes.SpecialName | MethodAttributes.NewSlot |
                                                MethodAttributes.Virtual;

            // Implement the getter
            MethodBuilder getterMethod = typeBuilder.DefineMethod(
                "get_Interceptor",
                Attributes,
                CallingConventions.HasThis,
                typeof(IInterceptor),
                new Type[0]);

            // Set the correct flags to signal the property is managed and implemented in intermediate language.
            // ReSharper disable once BitwiseOperatorOnEnumWithoutFlags
            getterMethod.SetImplementationFlags(MethodImplAttributes.Managed | MethodImplAttributes.IL);

            ILGenerator il = getterMethod.GetILGenerator();

            // This is equivalent to:
            // get { return this.interceptor; }
            il.Emit(OpCodes.Ldarg_0);
            il.Emit(OpCodes.Ldfld, fieldBuilder);
            il.Emit(OpCodes.Ret);

            // Implement the setter
            MethodBuilder setterMethod = typeBuilder.DefineMethod(
                "set_Interceptor",
                Attributes,
                CallingConventions.HasThis,
                typeof(void),
                new[] { typeof(IInterceptor) });

            // ReSharper disable once BitwiseOperatorOnEnumWithoutFlags
            setterMethod.SetImplementationFlags(MethodImplAttributes.Managed | MethodImplAttributes.IL);
            il = setterMethod.GetILGenerator();

            // This is equivalent to:
            // set { this.interceptor = value; }
            il.Emit(OpCodes.Ldarg_0);
            il.Emit(OpCodes.Ldarg_1);
            il.Emit(OpCodes.Stfld, fieldBuilder);
            il.Emit(OpCodes.Ret);

            // Implement the properties on the IProxy interface
            MethodInfo originalSetter = typeof(IProxy).GetMethod("set_Interceptor");
            MethodInfo originalGetter = typeof(IProxy).GetMethod("get_Interceptor");

            typeBuilder.DefineMethodOverride(setterMethod, originalSetter);
            typeBuilder.DefineMethodOverride(getterMethod, originalGetter);

            return fieldBuilder;
        }
Example #17
0
        private void FinishType(TypeBuilder typeBuilder, Cci.ITypeDefinition typeDef)
        {
            // implemented interfaces
            foreach (var iface in typeDef.Interfaces(_context))
            {
                // an implemented interface must be loaded before the type that implements it:
                typeBuilder.AddInterfaceImplementation(ResolveType(iface, dependentType: typeBuilder, valueTypeDependency: false));
            }

            // method implementations
            foreach (Cci.MethodImplementation impl in typeDef.GetExplicitImplementationOverrides(_context))
            {
                typeBuilder.DefineMethodOverride(ResolveMethod(impl.ImplementingMethod), ResolveMethod(impl.ImplementedMethod));
            }

            // properties (don't need to be defined prior custom attributes - we don't use CustomAttributeBuilders):
            foreach (Cci.IPropertyDefinition propertyDef in typeDef.GetProperties(_context))
            {
                EmitCustomAttributes(DefineProperty(typeBuilder, propertyDef), propertyDef.GetAttributes(_context));
            }

            // events
            foreach (Cci.IEventDefinition eventDef in typeDef.Events)
            {
                EmitCustomAttributes(DefineEvent(typeBuilder, eventDef), eventDef.GetAttributes(_context));
            }

            // custom attributes
            EmitCustomAttributes(typeBuilder, typeDef.GetAttributes(_context));

            // TODO:
            // decl security
        }
        // Makes sure the surrogate type implements ICloneable. We use ICloneable during deserialization 
        // to get the real exposed object from a surrogate object.
        // Note that ideally we'd use an internal "IWrapper" interface, but the interface needs to be public 
        // because the surrogates live in their own assembly. Instead of defining a public interface, we decided 
        // to reuse ICloneable.
        private static FieldInfo EmitICloneableImplementation(TypeBuilder typeBuilder, Type type, Type parentSurrogateType)
        {
            if (parentSurrogateType == typeof(object))
            {
                // protected Entity _wrapper
                FieldInfo wrapperField = typeBuilder.DefineField("_$wrapper", type, FieldAttributes.Family);

                // Implement ICloneable.
                typeBuilder.AddInterfaceImplementation(typeof(ICloneable));

                // public object GetUnderlyingObject() {
                //     return _$wrapper;
                // }
                MethodBuilder getUnderlyingObjectMethodBuilder = typeBuilder.DefineMethod("Clone", MethodAttributes.Public | MethodAttributes.Virtual, typeof(object), Type.EmptyTypes);

                // The surrogate assembly is SecurityCritical, but ICloneable is Transparent, so make sure our Clone method 
                // is marked as SecuritySafeCritical.
                getUnderlyingObjectMethodBuilder.SetCustomAttribute(
                    new CustomAttributeBuilder(
                        typeof(SecuritySafeCriticalAttribute).GetConstructor(Type.EmptyTypes),
                        new object[0]));

                ILGenerator getUnderlyingObjectMethodGenerator = getUnderlyingObjectMethodBuilder.GetILGenerator();

                getUnderlyingObjectMethodGenerator.Emit(OpCodes.Ldarg_0);
                getUnderlyingObjectMethodGenerator.Emit(OpCodes.Ldfld, wrapperField);
                getUnderlyingObjectMethodGenerator.Emit(OpCodes.Ret);
                return wrapperField;
            }
            else
            {
                return parentSurrogateType.GetField("_$wrapper", BindingFlags.Instance | BindingFlags.NonPublic);
            }
        }
Example #19
0
        private void CompileAnaClass()
        {
            AnaClass = utilityClass.DefineNestedType(Constants.AnaClassName,
                            TypeAttributes.Sealed | TypeAttributes.Class | TypeAttributes.NestedPublic,
                            null, TypeBuilder.EmptyTypes);

            var anaClassGenericParameters = AnaClass.DefineGenericParameters(new[] { Constants.AnaClassGenericParameterName }.Concat(declaration.TypeParameters).ToArray());

            if (declaration.TypeParameters.Any())
            {
                AnaClass.AddInterfaceImplementation(TypeBuilder.MakeGenericType(anaClassGenericParameters.Skip(1).ToArray()));
            }
            else
            {
                AnaClass.AddInterfaceImplementation(TypeBuilder);
            }

            var anaClassGeneratorType = typeof(IFunction<,>).MakeGenericType(anaClassGenericParameters[0],
                FunctorTypeMapper.Map(declaration.Type, declaration.VariableName, anaClassGenericParameters[0], anaClassGenericParameters.Skip(1).ToArray(), runtimeContainer));

            var seedField = AnaClass.DefineField(Constants.AnaClassSeedFieldName, anaClassGenericParameters[0], FieldAttributes.Private);
            var generatorField = AnaClass.DefineField(Constants.AnaClassGeneratorFieldName, anaClassGeneratorType, FieldAttributes.Private);

            AnaClassConstructor = AnaClass.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard, new[] { anaClassGenericParameters[0], anaClassGeneratorType });
            var ctorBody = AnaClassConstructor.GetILGenerator();
            ctorBody.Emit(OpCodes.Ldarg_0);
            ctorBody.Emit(OpCodes.Call, typeof(object).GetConstructors()[0]);
            ctorBody.Emit(OpCodes.Ldarg_0);
            ctorBody.Emit(OpCodes.Ldarg_1);
            ctorBody.Emit(OpCodes.Stfld, seedField);
            ctorBody.Emit(OpCodes.Ldarg_0);
            ctorBody.Emit(OpCodes.Ldarg_2);
            ctorBody.Emit(OpCodes.Stfld, generatorField);
            ctorBody.Emit(OpCodes.Ret);

            var apply = AnaClass.DefineMethod(Constants.ApplyMethodName, MethodAttributes.Public | MethodAttributes.Virtual);

            var resultType = apply.DefineGenericParameters(Constants.GFixFunctionClassGenericParameterName)[0];

            var applyFunctionGenericParameters = new[] { resultType }.Concat(anaClassGenericParameters.Skip(1)).ToArray();

            apply.SetParameters(GreatestFixedPointFunction.MakeGenericType(applyFunctionGenericParameters));
            apply.SetReturnType(resultType);

            var applyMethodGenericClass = TypeBuilder.GetMethod(
               GreatestFixedPointFunction.MakeGenericType(applyFunctionGenericParameters),
               GreatestFixedPointFunctionApplyMethod);
            var applyMethodGenericMethod = applyMethodGenericClass.MakeGenericMethod(anaClassGenericParameters[0]);

            var applyBody = apply.GetILGenerator();
            applyBody.Emit(OpCodes.Ldarg_1);
            applyBody.Emit(OpCodes.Ldarg_0);
            applyBody.Emit(OpCodes.Ldfld, seedField);
            applyBody.Emit(OpCodes.Ldarg_0);
            applyBody.Emit(OpCodes.Ldfld, generatorField);
            applyBody.Emit(OpCodes.Callvirt, applyMethodGenericMethod);
            applyBody.Emit(OpCodes.Ret);
        }
Example #20
0
        private void CompileAnaFunction()
        {
            AnaFunction = utilityClass.DefineNestedType(Constants.AnaFunctionClassName,
                           TypeAttributes.Sealed | TypeAttributes.Class | TypeAttributes.NestedPublic,
                           null, TypeBuilder.EmptyTypes);

            var anaClassGenericParameters = AnaFunction.DefineGenericParameters(new[] { Constants.AnaFunctionClassGenericParameterName }.Concat(declaration.TypeParameters).ToArray());

            var resultType = declaration.TypeParameters.Any()
                ? TypeBuilder.MakeGenericType(anaClassGenericParameters.Skip(1).ToArray())
                : TypeBuilder;

            AnaFunction.AddInterfaceImplementation(typeof(IFunction<,>).MakeGenericType(anaClassGenericParameters[0],
                 resultType));

            var seedType = typeof(IFunction<,>).MakeGenericType(anaClassGenericParameters[0],
                FunctorTypeMapper.Map(declaration.Type, declaration.VariableName, anaClassGenericParameters[0], anaClassGenericParameters.Skip(1).ToArray(), runtimeContainer));

            var seedField = AnaFunction.DefineField(Constants.AnaFunctionClassSeedFieldName, seedType, FieldAttributes.Private);

            AnaFunctionConstructor = AnaFunction.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard, new[] { seedType });

            var anaCtorBody = AnaFunctionConstructor.GetILGenerator();
            anaCtorBody.Emit(OpCodes.Ldarg_0);
            anaCtorBody.Emit(OpCodes.Call, typeof(object).GetConstructors()[0]);
            anaCtorBody.Emit(OpCodes.Ldarg_0);
            anaCtorBody.Emit(OpCodes.Ldarg_1);
            anaCtorBody.Emit(OpCodes.Stfld, seedField);
            anaCtorBody.Emit(OpCodes.Ret);

            var call = AnaFunction.DefineMethod(Constants.CallMethodName, MethodAttributes.Public | MethodAttributes.Virtual,
                resultType, new[] { anaClassGenericParameters[0] });

            var callBody = call.GetILGenerator();
            callBody.Emit(OpCodes.Ldarg_1);
            callBody.Emit(OpCodes.Ldarg_0);
            callBody.Emit(OpCodes.Ldfld, seedField);
            callBody.Emit(OpCodes.Call, Ana.MakeGenericMethod(anaClassGenericParameters));
            callBody.Emit(OpCodes.Ret);
        }
        /// <summary>
        /// Actually implements the <see cref="ISupportsWebDependencyInjection"/> interface.
        /// </summary>
        private void ImplementIDependencyInjectionAware(TypeBuilder typeBuilder, Type targetType, FieldInfo appContextField)
        {
            Type intf = typeof (ISupportsWebDependencyInjection);

            // Add interface declaration to type
            typeBuilder.AddInterfaceImplementation(intf);

            // get interface property
            PropertyInfo piApplicationContext = intf.GetProperty("DefaultApplicationContext");

            // define property
            string fullPropertyName = typeof (ISupportsWebDependencyInjection).FullName + "." + piApplicationContext.Name;
            PropertyBuilder appContextProperty =
                typeBuilder.DefineProperty(fullPropertyName, PropertyAttributes.None, typeof (IApplicationContext), null);

            MethodAttributes methodAtts = MethodAttributes.Private | MethodAttributes.HideBySig | MethodAttributes.SpecialName |
                                          MethodAttributes.NewSlot | MethodAttributes.Virtual | MethodAttributes.Final;

            // implement getter
            MethodInfo getApplicationContextMethod = piApplicationContext.GetGetMethod();
            string getterMethodName = typeof (ISupportsWebDependencyInjection).FullName + "." + getApplicationContextMethod.Name;
            MethodBuilder mbGet =
                typeBuilder.DefineMethod(getterMethodName,
                                         methodAtts,
                                         getApplicationContextMethod.CallingConvention, getApplicationContextMethod.ReturnType,
                                         Type.EmptyTypes);


            ILGenerator ilGet = mbGet.GetILGenerator();
            ilGet.Emit(OpCodes.Ldarg_0);
            ilGet.Emit(OpCodes.Ldfld, appContextField);
            ilGet.Emit(OpCodes.Ret);

            typeBuilder.DefineMethodOverride(mbGet, getApplicationContextMethod);
            appContextProperty.SetGetMethod(mbGet);

            // implement setter
            MethodInfo setApplicationContextMethod = piApplicationContext.GetSetMethod();
            string setterMethodName = typeof (ISupportsWebDependencyInjection).FullName + "." + setApplicationContextMethod.Name;
            MethodBuilder mbSet = typeBuilder.DefineMethod(setterMethodName, methodAtts,
                                                           setApplicationContextMethod.CallingConvention,
                                                           setApplicationContextMethod.ReturnType,
                                                           new Type[] {typeof (IApplicationContext)});

            ILGenerator ilSet = mbSet.GetILGenerator();
            ilSet.Emit(OpCodes.Ldarg_0);
            ilSet.Emit(OpCodes.Ldarg_1);
            ilSet.Emit(OpCodes.Stfld, appContextField);
            ilSet.Emit(OpCodes.Ret);

            typeBuilder.DefineMethodOverride(mbSet, setApplicationContextMethod);
            appContextProperty.SetSetMethod(mbSet);
        }
Example #22
0
        private void CompileAnaFunction1()
        {
            AnaFunction1 = utilityClass.DefineNestedType(Constants.AnaFunction1ClassName,
                           TypeAttributes.Sealed | TypeAttributes.Class | TypeAttributes.NestedPublic,
                           null, TypeBuilder.EmptyTypes);

            var anaClassGenericParameters = AnaFunction1.DefineGenericParameters(new[] { Constants.AnaFunction1ClassGenericParameterName }.Concat(declaration.TypeParameters).ToArray());

            var resultType = declaration.TypeParameters.Any()
                ? TypeBuilder.MakeGenericType(anaClassGenericParameters.Skip(1).ToArray())
                : TypeBuilder;

            var fAnaClassGenericParameter = FunctorTypeMapper.Map(declaration.Type, declaration.VariableName, anaClassGenericParameters[0], anaClassGenericParameters.Skip(1).ToArray(), runtimeContainer);

            var coalgebraType = typeof(IFunction<,>).MakeGenericType(anaClassGenericParameters[0], fAnaClassGenericParameter);
            var terminalMorphismType = typeof(IFunction<,>).MakeGenericType(anaClassGenericParameters[0], resultType);

            AnaFunction1.AddInterfaceImplementation(typeof(IFunction<,>).MakeGenericType(coalgebraType,
                 terminalMorphismType));

            AnaFunction1Constructor = AnaFunction1.DefineConstructor(MethodAttributes.Public,
                 CallingConventions.Standard, TypeBuilder.EmptyTypes);

            var anaCtorBody = AnaFunction1Constructor.GetILGenerator();
            anaCtorBody.Emit(OpCodes.Ldarg_0);
            anaCtorBody.Emit(OpCodes.Call, typeof(object).GetConstructors()[0]);
            anaCtorBody.Emit(OpCodes.Ret);

            var call = AnaFunction1.DefineMethod(Constants.CallMethodName, MethodAttributes.Public | MethodAttributes.Virtual,
                terminalMorphismType, new Type[] { coalgebraType });

            var callBody = call.GetILGenerator();
            callBody.Emit(OpCodes.Ldarg_1);
            callBody.Emit(OpCodes.Newobj, TypeBuilder.GetConstructor(
               AnaFunction.MakeGenericType(anaClassGenericParameters),
               AnaFunctionConstructor));
            callBody.Emit(OpCodes.Ret);
        }
Example #23
0
        private void CompileInGeneratingFunction()
        {
            InClass = utilityClass.DefineNestedType(Constants.InGeneratingFunctionClassName,
                TypeAttributes.Sealed | TypeAttributes.Class | TypeAttributes.NestedPublic);

            var genericParameters = declaration.TypeParameters.Any() ? InClass.DefineGenericParameters(declaration.TypeParameters) : TypeBuilder.EmptyTypes;

            var greatestFixedPoint = declaration.TypeParameters.Any()
                ? TypeBuilder.MakeGenericType(genericParameters)
                : TypeBuilder;

            var fGreatestFixedPoint = FunctorTypeMapper.Map(declaration.Type, declaration.VariableName, greatestFixedPoint, genericParameters, runtimeContainer);

            InClass.AddInterfaceImplementation(GreatestFixedPointFunction.MakeGenericType(new[] { fGreatestFixedPoint }.Concat(genericParameters).ToArray()));

            InGeneratingFunctionConstructor = InClass.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard, TypeBuilder.EmptyTypes);
            var inCtorBody = InGeneratingFunctionConstructor.GetILGenerator();
            inCtorBody.Emit(OpCodes.Ldarg_0);
            inCtorBody.Emit(OpCodes.Call, typeof(object).GetConstructors()[0]);
            inCtorBody.Emit(OpCodes.Ret);

            var apply = InClass.DefineMethod(Constants.ApplyMethodName, MethodAttributes.Public | MethodAttributes.Virtual,
                fGreatestFixedPoint, TypeBuilder.EmptyTypes);

            var genericParameter = apply.DefineGenericParameters(Constants.ApplyMethodGenericParameterName)[0];

            var fGenericParameter = FunctorTypeMapper.Map(declaration.Type, declaration.VariableName, genericParameter, genericParameters, runtimeContainer);

            apply.SetParameters(genericParameter, typeof(IFunction<,>).MakeGenericType(genericParameter, fGenericParameter));

            var applyBody = apply.GetILGenerator();
            applyBody.Emit(OpCodes.Ldarg_2);
            applyBody.Emit(OpCodes.Newobj, TypeBuilder.GetConstructor(
               AnaFunction.MakeGenericType(new[] { genericParameter }.Concat(genericParameters).ToArray()),
               AnaFunctionConstructor));
            applyBody.Emit(OpCodes.Call, fmap.MakeGenericMethod(new Type[] { genericParameter, greatestFixedPoint }.Concat(genericParameters).ToArray()));
            applyBody.Emit(OpCodes.Ldarg_2);
            applyBody.Emit(OpCodes.Ldarg_1);
            applyBody.Emit(OpCodes.Callvirt, TypeBuilder.GetMethod(
                typeof(IFunction<,>).MakeGenericType(genericParameter, fGenericParameter),
                typeof(IFunction<,>).GetMethod(Constants.CallMethodName)));
            applyBody.Emit(OpCodes.Callvirt, TypeBuilder.GetMethod(
                typeof(IFunction<,>).MakeGenericType(fGenericParameter, fGreatestFixedPoint),
                typeof(IFunction<,>).GetMethod(Constants.CallMethodName)));
            applyBody.Emit(OpCodes.Ret);
        }
        /// <summary>
        /// creates the union in the module represented by modBuilder.
        /// </summary>
        /// <param name="visibility">specifies the visiblity of resulting type</param>
        public UnionGenerationHelper(ModuleBuilder modBuilder, string fullName, 
                                     TypeAttributes visibility) {
            TypeAttributes typeAttrs = TypeAttributes.Class | TypeAttributes.Serializable | 
                                       TypeAttributes.BeforeFieldInit | /* TypeAttributes.SequentialLayout | */
                                       TypeAttributes.Sealed | visibility;

            m_builder = modBuilder.DefineType(fullName, typeAttrs, ReflectionHelper.ValueTypeType,
                                              new System.Type[] { ReflectionHelper.IIdlEntityType });
            m_builder.AddInterfaceImplementation(ReflectionHelper.ISerializableType); // optimization for inter .NET communication
            BeginType();
        }
Example #25
0
        private void CompileOutFunction()
        {
            OutFunction = utilityClass.DefineNestedType(Constants.OutFunctionClassName,
                TypeAttributes.Sealed | TypeAttributes.Class | TypeAttributes.NestedPublic);

            var genericParameters = declaration.TypeParameters.Any() ? OutFunction.DefineGenericParameters(declaration.TypeParameters) : TypeBuilder.EmptyTypes;

            var fGreatestFixedPoint = FunctorTypeMapper.Map(declaration.Type, declaration.VariableName, TypeBuilder, genericParameters, runtimeContainer);

            OutFunction.AddInterfaceImplementation(typeof(IFunction<,>).MakeGenericType(fGreatestFixedPoint, TypeBuilder));

            OutFunctionConstructor = OutFunction.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard, TypeBuilder.EmptyTypes);
            var outCtorBody = OutFunctionConstructor.GetILGenerator();
            outCtorBody.Emit(OpCodes.Ldarg_0);
            outCtorBody.Emit(OpCodes.Call, typeof(object).GetConstructors()[0]);
            outCtorBody.Emit(OpCodes.Ret);

            var call = OutFunction.DefineMethod(Constants.CallMethodName, MethodAttributes.Public | MethodAttributes.Virtual,
               TypeBuilder, new Type[] { fGreatestFixedPoint });

            var callBody = call.GetILGenerator();
            callBody.Emit(OpCodes.Ldarg_1);
            callBody.Emit(OpCodes.Call, declaration.TypeParameters.Any()
                ? Out.MakeGenericMethod(genericParameters)
                : Out);
            callBody.Emit(OpCodes.Ret);
        }
Example #26
0
        /// <summary>
        /// Adds an implementation to the created type.
        /// </summary>
        /// <param name="tb">Type builder object.</param>
        /// <param name="typeToWrap">Created class.</param>
        private static void AddTypeImplementation(TypeBuilder tb, Type typeToWrap)
        {
            // add implementation for the interface
            if(IsInterface(typeToWrap))
            {
                tb.AddInterfaceImplementation(typeToWrap);
            }

            // create implementation for each type abstract method
            MethodInfo[] parentMethodInfo = typeToWrap.GetMethods(BindingFlags.Public | BindingFlags.NonPublic |BindingFlags.Instance /* | BindingFlags.DeclaredOnly */);
            for(int i = 0; i < parentMethodInfo.Length; ++i)
            {
                if(IsAbstractMethod(parentMethodInfo[i]))
                {
                    AddMethodImplementation(parentMethodInfo[i], tb);
                }
            }
        }
Example #27
0
 void Generate(ref TypeBuilder tBuilder, Class c)
 {
     // parent and interfaces
     foreach (Class baseType in c.BaseTypes) {
         Type t = GetType(baseType);
         if (t == null) {
             // parent, or interface is not
             // public namespace, or inner
             Console.WriteLine("WARNING: skipped base type {0} for {1}",
                 baseType, tBuilder.FullName);
             continue;
         }
         if (baseType.IsInterface) {
             tBuilder.AddInterfaceImplementation(t);
         } else {
             tBuilder.SetParent(t);
         }
     }
 }
        /// <summary>
        /// Implements serialization method.
        /// </summary>
        /// <param name="typeBuilder"></param>
        private void ImplementGetObjectDataMethod(TypeBuilder typeBuilder)
        {
            typeBuilder.AddInterfaceImplementation(typeof(ISerializable));

            MethodBuilder mb =
                typeBuilder.DefineMethod("GetObjectData",
                                         MethodAttributes.Public | MethodAttributes.HideBySig | 
                                         MethodAttributes.NewSlot | MethodAttributes.Virtual,
                                         typeof (void),
                                         new Type[] {typeof (SerializationInfo), typeof (StreamingContext)});

            ILGenerator il = mb.GetILGenerator();
            il.Emit(OpCodes.Ldarg_1);
            il.Emit(OpCodes.Ldstr, "advisedProxy");
            il.Emit(OpCodes.Ldarg_0);
            il.Emit(OpCodes.Ldfld, advisedProxyField);
            il.EmitCall(OpCodes.Callvirt, References.AddSerializationValue, null);
            il.Emit(OpCodes.Ret);

            //typeBuilder.DefineMethodOverride(mb, typeof(ISerializable).GetMethod("GetObjectData"));
        }
Example #29
0
        void EmitBaseTypesAndAttributes(TypeDefinition typeDefinition, TypeBuilder typeBuilder)
        {
            foreach (TypeReference baseType in typeDefinition.BaseTypes)
            {
                Type type = GetSystemType(baseType);

                // For some reason you can't call IsClass on constructed types created at compile time,
                // so we'll ask the generic definition instead
                if ((type.IsGenericType && type.GetGenericTypeDefinition().IsClass) || (type.IsClass))
                {
                    typeBuilder.SetParent(type);
                }
                else
                {
                    typeBuilder.AddInterfaceImplementation(type);
                }
            }
        }
        /// <summary>
        /// Implements <see cref="Spring.Aop.Framework.IAopProxy"/> interface.
        /// </summary>
        /// <param name="typeBuilder">The type builder to use.</param>
        protected virtual void ImplementIAopProxy(TypeBuilder typeBuilder)
        {
            Type intf = typeof(IAopProxy);
            MethodInfo getProxyMethod = intf.GetMethod("GetProxy", Type.EmptyTypes);

            typeBuilder.AddInterfaceImplementation(intf);

            MethodBuilder mb = typeBuilder.DefineMethod(typeof(IAdvised).FullName + "." + getProxyMethod.Name,
                MethodAttributes.Private | MethodAttributes.HideBySig | MethodAttributes.NewSlot | MethodAttributes.Virtual | MethodAttributes.Final,
                getProxyMethod.CallingConvention, getProxyMethod.ReturnType, Type.EmptyTypes);

            ILGenerator il = mb.GetILGenerator();
            il.Emit(OpCodes.Ldarg_0);
            il.Emit(OpCodes.Ret);

            typeBuilder.DefineMethodOverride(mb, getProxyMethod);
        }
Example #31
0
        public Type Compile(Type superType, Type stubType, IPersistentVector interfaces, bool onetimeUse, GenContext context)
        {
            if (_compiledType != null)
                return _compiledType;

            string publicTypeName = IsDefType || (_isStatic && Compiler.IsCompiling) ? InternalName : InternalName + "__" + RT.nextID();

            //Console.WriteLine("DefFn {0}, {1}", publicTypeName, context.AssemblyBuilder.GetName().Name);

            _typeBuilder = context.AssemblyGen.DefinePublicType(publicTypeName, superType, true);
            context = context.WithNewDynInitHelper().WithTypeBuilder(_typeBuilder);

            Var.pushThreadBindings(RT.map(Compiler.CompilerContextVar, context));

            try
            {
                if (interfaces != null)
                {
                    for (int i = 0; i < interfaces.count(); i++)
                        _typeBuilder.AddInterfaceImplementation((Type)interfaces.nth(i));
                }

                ObjExpr.MarkAsSerializable(_typeBuilder);
                GenInterface.SetCustomAttributes(_typeBuilder, _classMeta);

                try
                {
                    if (IsDefType)
                    {
                        Compiler.RegisterDuplicateType(_typeBuilder);

                        Var.pushThreadBindings(RT.map(
                            Compiler.CompileStubOrigClassVar, stubType
                            ));
                        //,
                        //Compiler.COMPILE_STUB_CLASS, _baseType));
                    }
                    EmitConstantFieldDefs(_typeBuilder);
                    EmitKeywordCallsiteDefs(_typeBuilder);

                    DefineStaticConstructor(_typeBuilder);

                    if (SupportsMeta)
                        _metaField = _typeBuilder.DefineField("__meta", typeof(IPersistentMap), FieldAttributes.Public | FieldAttributes.InitOnly);

                    EmitClosedOverFields(_typeBuilder);
                    EmitProtocolCallsites(_typeBuilder);

                    _ctorInfo = EmitConstructor(_typeBuilder, superType);

                    if (_altCtorDrops > 0)
                        EmitFieldOnlyConstructor(_typeBuilder, superType);

                    if (SupportsMeta)
                    {
                        EmitNonMetaConstructor(_typeBuilder, superType);
                        EmitMetaFunctions(_typeBuilder);
                    }

                    EmitStatics(_typeBuilder);
                    EmitMethods(_typeBuilder);

                    //if (KeywordCallsites.count() > 0)
                    //    EmitSwapThunk(_typeBuilder);

                    _compiledType = _typeBuilder.CreateType();

                    if (context.DynInitHelper != null)
                        context.DynInitHelper.FinalizeType();

                    //  If we don't pick up the ctor after we finalize the type,
                    //    we sometimes get a ctor which is not a RuntimeConstructorInfo
                    //  This causes System.DynamicILGenerator.Emit(opcode,ContructorInfo) to blow up.
                    //    The error says the ConstructorInfo is null, but there is a second case in the code.
                    //  Thank heavens one can run Reflector on mscorlib.

                    ConstructorInfo[] cis = _compiledType.GetConstructors();
                    foreach (ConstructorInfo ci in cis)
                    {
                        if (ci.GetParameters().Length == CtorTypes().Length)
                        {
                            _ctorInfo = ci;
                            break;
                        }
                    }

                    return _compiledType;
                }
                finally
                {
                    if (IsDefType)
                        Var.popThreadBindings();
                }
            }
            finally
            {
                Var.popThreadBindings();
            }
        }
Example #32
0
        private static void InnerCreateType(TypeBuilder typeBuilder, Type interfaceType, IMethodEmit methodEmitter)
        {
            typeBuilder.AddInterfaceImplementation(interfaceType);
            foreach (MemberInfo member in interfaceType.GetMembers(BindingFlags.Instance | BindingFlags.Public))
            {
                //约定-成员必须是方法,不能有属性,事件之类的
                if (member.MemberType != MemberTypes.Method)
                {
                    throw (new ApplicationException("Could not emit " + member.MemberType + " automatically!"));
                }
                CreateMethod(typeBuilder, (MethodInfo)member, methodEmitter);
            }

            //获取派生自的父接口
            Type[] typeList = interfaceType.GetInterfaces();
            if (typeList == null || typeList.Length <= 0)
            {
                return;
            }

            //为父接口实现方法
            for (int i = 0; i < typeList.Length; i++)
            {
                InnerCreateType(typeBuilder, typeList[i], methodEmitter);
            }
        }