Ejemplo n.º 1
0
            public BaseAccessor(TypeAccessor typeAccessor, ParameterExpression par, MemberExpression expr)
                : base(typeAccessor, expr.Member)
            {
                Expression ex = expr;

                if (ex.Type.IsEnum && ex.Type != typeof(T))
                {
                    ex = Expression.Convert(ex, typeof(T));
                }

                Getter = Expression.Lambda <Func <object, T> >(ex, par).Compile();

                var mi = expr.Member;

                HasSetterValue = !(mi is PropertyInfo) || ((PropertyInfo)mi).GetSetMethod(true) != null;

                if (HasSetterValue)
                {
                    var dm = new DynamicMethod(
                        "setter_" + mi.Name + "_" + ++_counter,
                        typeof(void),
                        new[] { typeof(object), typeof(T) },
                        typeAccessor.Type);
                    var emit = new EmitHelper(dm.GetILGenerator());

                    emit
                    .ldarg_0
                    .castType(typeAccessor.Type)
                    .ldarg_1
                    .end();

                    if (mi is FieldInfo)
                    {
                        emit.stfld((FieldInfo)mi);
                    }
                    else
                    {
                        emit.callvirt(((PropertyInfo)mi).GetSetMethod(true));
                    }

                    emit.ret();

                    Setter = (Action <object, T>)dm.CreateDelegate(typeof(Action <object, T>));
                }
            }
Ejemplo n.º 2
0
        public void AddEdge(IEdge edge)
        {
            if (dumpInfo.IsExcludedEdgeType(edge.Type))
            {
                return;
            }

            String erName = edgeRealizer ?? GetEdgeRealizer(edge.Type);

            String edgeName = graph.GetElementName(edge);
            String srcName  = graph.GetElementName(edge.Source);
            String tgtName  = graph.GetElementName(edge.Target);

            ycompStream.Write("addEdge \"e" + edgeName + "\" \"n" + srcName + "\" \"n" + tgtName
                              + "\" \"" + erName + "\" \"" + GetElemLabel(edge) + "\"\n");
            foreach (AttributeType attrType in edge.Type.AttributeTypes)
            {
                if (attrType.Kind == AttributeKind.SetAttr || attrType.Kind == AttributeKind.MapAttr)
                {
                    IDictionary setmap = (IDictionary)edge.GetAttribute(attrType.Name);
                    string      attrTypeString;
                    string      attrValue;
                    EmitHelper.ToString(setmap, out attrTypeString, out attrValue, attrType, graph);
                    ycompStream.Write("changeEdgeAttr \"e" + edgeName + "\" \"" + attrType.OwnerType.Name + "::" + attrType.Name + " : "
                                      + attrTypeString + "\" \"" + Encode(attrValue) + "\"\n");
                }
                else if (attrType.Kind == AttributeKind.ArrayAttr)
                {
                    IList  array = (IList)edge.GetAttribute(attrType.Name);
                    string attrTypeString;
                    string attrValue;
                    EmitHelper.ToString(array, out attrTypeString, out attrValue, attrType, graph);
                    ycompStream.Write("changeEdgeAttr \"e" + edgeName + "\" \"" + attrType.OwnerType.Name + "::" + attrType.Name + " : "
                                      + attrTypeString + "\" \"" + Encode(attrValue) + "\"\n");
                }
                else
                {
                    object attr = edge.GetAttribute(attrType.Name);
                    ycompStream.Write("changeEdgeAttr \"e" + edgeName + "\" \"" + attrType.OwnerType.Name + "::" + attrType.Name + " : "
                                      + GetKindName(attrType) + "\" \"" + EncodeAttr(attr) + "\"\n");
                }
            }
            isDirty       = true;
            isLayoutDirty = true;
        }
Ejemplo n.º 3
0
        public void EmitGet()
        {
            if (this.ClassContext is ContextNestedClass)
            {
                FieldBuilder fieldBuilder = this.ProcContext.ClassContext.GetZCompilingType()
                                            .SearchDeclaredZField(VarName).FieldBuilder;

                EmitHelper.EmitThis(IL, false);
                EmitHelper.LoadField(IL, fieldBuilder);
                base.EmitConv();
            }
            else
            {
                //Console.WriteLine(ArgSymbol.EmitIndex);
                EmitSymbolHelper.EmitLoad(IL, ArgSymbol);
                base.EmitConv();
            }
        }
        private void GeneratePropertySet(EmitHelper emit, int typeCode, MemberInfo memberInfo)
        {
            Type propertyType = null;

            if (memberInfo.MemberType == MemberTypes.Property)
            {
                propertyType = memberInfo.DeclaringType.GetProperty(memberInfo.Name).PropertyType;
            }
            if (memberInfo is FieldInfo)
            {
                propertyType = memberInfo.DeclaringType.GetField(memberInfo.Name).FieldType;
            }
            if (propertyType == null)
            {
                throw new ArgumentNullException(memberInfo.Name);
            }
            emit.ldloc_0.ldarg_0.ldloc_1.callvirt(typeof(AMFReader).GetMethod("ReadAMF3Data", new Type[] { typeof(byte) })).ldtoken(propertyType).call(typeof(Type).GetMethod("GetTypeFromHandle", new Type[] { typeof(RuntimeTypeHandle) })).call(typeof(TypeHelper).GetMethod("ChangeType", new Type[] { typeof(object), typeof(Type) })).CastFromObject(propertyType).GenerateSetMember(memberInfo).end();
        }
Ejemplo n.º 5
0
        private void GenerateOneToManyGetPropertyBody(MethodBuilder methodBuilder, FieldInfo fieldInfo,
                                                      ConstructorInfo hashSetConstructor)
        {
            var generator = new EmitHelper(methodBuilder.GetILGenerator());

            Label afterInitialization = generator.DefineLabel();

            generator.ldarg_0()
            .ldfld(fieldInfo)
            .brtrue_s(afterInitialization)
            .ldarg_0()
            .newobj(hashSetConstructor)
            .stfld(fieldInfo)
            .MarkLabel(afterInitialization)
            .ldarg_0()
            .ldfld(fieldInfo)
            .ret();
        }
Ejemplo n.º 6
0
        public override void EmitSet(Exp valueExp)
        {
            if (this.ClassContext is ContextNestedClass)
            {
                FieldBuilder fieldBuilder = this.ProcContext.ClassContext.GetZCompilingType()
                                            .SearchDeclaredZField(VarName).FieldBuilder;

                EmitHelper.EmitThis(IL, false);
                EmitValueExp(valueExp);
                EmitHelper.StormField(IL, fieldBuilder);
                base.EmitConv();
            }
            else
            {
                EmitValueExp(valueExp);
                EmitSymbolHelper.EmitStorm(IL, ArgSymbol);
            }
        }
Ejemplo n.º 7
0
        public override void Build(BuildContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            ParameterInfo pi = (ParameterInfo)TargetElement;

            if (pi.ParameterType.IsValueType == false)
            {
                EmitHelper emit  = context.MethodBuilder.Emitter;
                Label      label = emit.DefineLabel();

                string message = _message != null?string.Format(_message, pi.Name) : string.Empty;

                emit
                .ldarg(pi)
                .brtrue_s(label)
                ;

                if (string.IsNullOrEmpty(message))
                {
                    emit
                    .ldstr(pi.Name)
                    .newobj(typeof(ArgumentNullException), typeof(string))
                    ;
                }
                else
                {
                    emit
                    .ldnull
                    .ldstr(message)
                    .newobj(typeof(ArgumentNullException), typeof(string), typeof(string))
                    ;
                }

                emit
                .@throw
                .MarkLabel(label)
                ;
            }
        }
Ejemplo n.º 8
0
        bool TryGenerate(Type type, out int id)
        {
            // 0- try to resolve type
            var resolvedTypes = new List <Type>();
            int nextId        = _nextId;

            if (!TryResolveType(type, ref nextId, resolvedTypes))
            {
                id = -1;
                return(false);
            }

            // 1- generate the actual code for the type
            EmitHelper.EmitSerializationCode(_emitCtx, resolvedTypes, EmitHelper.EmitDynamicSerializeStub);
            EmitHelper.EmitDeserializationCode(_emitCtx, resolvedTypes, EmitHelper.EmitDynamicDeserializeStub);

            // 2- generate delegators and add to list
            for (int i = 0; i < resolvedTypes.Count; i++)
            {
                var resolved           = resolvedTypes[i];
                var writer             = _emitCtx.GetWriteStub(resolved);
                var serializeDelegator = EmitHelper.EmitDynamicSerializeDelegator(resolved, writer);
                _serializationDelegates.Add(serializeDelegator);

                var reader = _emitCtx.GetReadStub(resolved);
                var deserializeDelegator = EmitHelper.EmitDynamicDeserializeDelegator(resolved, reader);
                _deserializationDelegates.Add(deserializeDelegator);
            }

            if (_onTypeGenerated != null)
            {
                for (int i = 0; i < resolvedTypes.Count; i++)
                {
                    _onTypeGenerated(resolvedTypes[i]);
                }
            }

            // 3- set ids
            _nextId = nextId;
            id      = GetTypeId(type);

            return(true);
        }
Ejemplo n.º 9
0
        private void EmitSet(TypeBuilder classBuilder, string propertyName, Type propertyType, bool isStatic, FieldBuilder field, PropertyBuilder property, MethodAttributes methodAttr)
        {
            MethodBuilder methodSet = classBuilder.DefineMethod("set_" + propertyName, methodAttr, typeof(void), new Type[] { propertyType });
            ILGenerator   ilSet     = methodSet.GetILGenerator();

            EmitHelper.EmitThis(ilSet, isStatic);
            if (isStatic)
            {
                ilSet.Emit(OpCodes.Ldarg_0);
            }
            else
            {
                ilSet.Emit(OpCodes.Ldarg_1);
            }

            EmitHelper.StormField(ilSet, field);
            ilSet.Emit(OpCodes.Ret);
            property.SetSetMethod(methodSet);
        }
Ejemplo n.º 10
0
        private static Type CreateEntityType(
            EntityInfo entity,
            ModuleBuilder entityModule)
        {
            string cliTypeName = TypeHelper.NormalizeForCliTypeName(entity.TableName.FullName);

            TypeBuilder entityTypeBuilder = entityModule.DefineType(cliTypeName, TypeAttributes.Public);

            foreach (EntityPropertyInfo property in entity.Properties)
            {
                EmitHelper.AddProperty(entityTypeBuilder, property.Name, property.ClrType);
            }

#if NETSTANDARD
            return(entityTypeBuilder.CreateTypeInfo());
#else
            return(entityTypeBuilder.CreateType());
#endif
        }
Ejemplo n.º 11
0
        public override void EmitWrite(Type type)
        {
            // arg0: stream, arg1: value, arg2: ctx

            //if (value == null)
            //{
            //    WriteInt32(stream, -1);
            //    return;
            //}
            //WriteInt32(stream, value.Length);
            //for(int i = 0; i < value.Length; i++)
            //    Serialize(stream, value[i], ctx);

            // if (value == null) WriteInt(stream, -1); return;
            EmitHelper.HandleNullWrite();

            // WriteInt(stream, value.Length);
            var writeInt = Basic.GetWriter <int>();

            emit.ldarg_0()
            .ldarg_1()
            .ldlen()
            .call(writeInt);

            EmitHelper.EmitSerializeRef();

            EmitHelper.EmitArrayForLoop(type, null, i =>
            {
                var elementType = type.GetElementType();
                var serialize   = ctx.GetWriteMethod(elementType);

                // Serialize(stream, value[i], ctx)
                emit.ldarg_0()
                .ldarg_1()
                .ldloc_s(i)
                .ldelem(elementType)
                .ldarg_2()
                .call(serialize);
            });

            emit.ret();
        }
Ejemplo n.º 12
0
        private void EmitSerialize(FieldInfo field, ref EmitHelper serializerEmit)
        {
            var obj = serializerEmit.DeclareLocal(typeof(object));
            var propertyNullLabel    = serializerEmit.DefineLabel();
            var propertyNotNullLabel = serializerEmit.DefineLabel();
            var objectExistsLocal    = serializerEmit.DefineLabel();
            var objectNotExistsLocal = serializerEmit.DefineLabel();

            serializerEmit
            .ldarg_0
            .ldfld(field)
            .stloc(obj)
            .ldloc(obj)
            .brtrue(propertyNotNullLabel)
            .ldarg_1
            .ldc_i4_m1
            .call(typeof(BinaryWriter).GetMethod("Write", new[] { typeof(int) }))
            .br(propertyNullLabel)
            .MarkLabel(propertyNotNullLabel)
            .ldarg_2
            .ldloc(obj)
            .call(typeof(IDictionary <object, int>).GetMethod("ContainsKey", new[] { typeof(object) }))
            .brtrue(objectExistsLocal)
            .ldarg_1
            .ldarg_3
            .call(typeof(BinaryWriter).GetMethod("Write", new[] { typeof(int) }))
            .ldloc(obj)
            .castclass(typeof(ISerializable))
            .ldarg_1
            .ldarg_2
            .ldarg_3
            .call(typeof(ISerializable).GetMethod("Serialize"))
            .br(objectNotExistsLocal)
            .MarkLabel(objectExistsLocal)
            .ldarg_1
            .ldarg_2
            .ldloc(obj)
            .call(typeof(IDictionary <object, int>).GetMethod("get_Item", new[] { typeof(object) }))
            .call(typeof(BinaryWriter).GetMethod("Write", new[] { typeof(int) }))
            .MarkLabel(objectNotExistsLocal)
            .MarkLabel(propertyNullLabel);
        }
Ejemplo n.º 13
0
        protected FieldBuilder GetArrayInitializer(Type arrayType)
        {
            string       fieldName = "_array_of_$_" + arrayType.FullName;
            FieldBuilder field     = Context.GetField(fieldName);

            if (field == null)
            {
                field = Context.CreatePrivateStaticField(fieldName, arrayType);

                EmitHelper emit = Context.TypeBuilder.TypeInitializer.Emitter;

                int rank = arrayType.GetArrayRank();

                if (rank > 1)
                {
                    Type[] parameters = new Type[rank];

                    for (int i = 0; i < parameters.Length; i++)
                    {
                        parameters[i] = typeof(int);
                        emit.ldc_i4_0.end();
                    }

                    ConstructorInfo ci = TypeHelper.GetConstructor(arrayType, parameters);

                    emit
                    .newobj(ci)
                    .stsfld(field)
                    ;
                }
                else
                {
                    emit
                    .ldc_i4_0
                    .newarr(arrayType.GetElementType())
                    .stsfld(field)
                    ;
                }
            }

            return(field);
        }
Ejemplo n.º 14
0
        protected virtual ReadDataInvoker CreateReadDataMethod(Type type, AMFReader reader, object instance)
        {
            bool            skipVisibility  = SecurityManager.IsGranted(new ReflectionPermission(ReflectionPermissionFlag.MemberAccess));
            DynamicMethod   method          = new DynamicMethod(string.Empty, typeof(object), new Type[] { typeof(AMFReader), typeof(ClassDefinition) }, base.GetType(), skipVisibility);
            ILGenerator     iLGenerator     = method.GetILGenerator();
            LocalBuilder    builder         = iLGenerator.DeclareLocal(type);
            LocalBuilder    builder2        = iLGenerator.DeclareLocal(typeof(byte));
            LocalBuilder    builder3        = iLGenerator.DeclareLocal(typeof(string));
            LocalBuilder    builder4        = iLGenerator.DeclareLocal(typeof(object));
            LocalBuilder    builder5        = iLGenerator.DeclareLocal(typeof(int));
            LocalBuilder    builder6        = iLGenerator.DeclareLocal(typeof(int));
            LocalBuilder    builder7        = iLGenerator.DeclareLocal(typeof(object));
            LocalBuilder    builder8        = iLGenerator.DeclareLocal(typeof(Type));
            EmitHelper      emit            = new EmitHelper(iLGenerator);
            ConstructorInfo constructorInfo = type.GetConstructor(EmitHelper.AnyVisibilityInstance, null, CallingConventions.HasThis, Type.EmptyTypes, null);
            MethodInfo      methodInfo      = typeof(AMFReader).GetMethod("AddReference");
            MethodInfo      info3           = typeof(AMFReader).GetMethod("ReadString");
            MethodInfo      info4           = typeof(AMFReader).GetMethod("ReadByte");

            emit.newobj(constructorInfo).stloc_0.ldarg_0.ldloc_0.callvirt(methodInfo).ldc_i4_0.stloc_1.ldnull.stloc_2.end();
            string memberName = reader.ReadString();

            for (byte i = reader.ReadByte(); i != 9; i = reader.ReadByte())
            {
                emit.ldarg_0.callvirt(info3).stloc_2.ldarg_0.callvirt(info4).stloc_1.end();
                object obj2 = reader.ReadData(i);
                reader.SetMember(instance, memberName, obj2);
                MemberInfo[] member = type.GetMember(memberName);
                if ((member == null) || (member.Length <= 0))
                {
                    throw new MissingMemberException(type.FullName, memberName);
                }
                this.GeneratePropertySet(emit, i, member[0]);
                memberName = reader.ReadString();
            }
            Label           label = emit.DefineLabel();
            ConstructorInfo info5 = typeof(UnexpectedAMF).GetConstructor(EmitHelper.AnyVisibilityInstance, null, CallingConventions.HasThis, Type.EmptyTypes, null);

            emit.ldarg_0.callvirt(info3).stloc_2.ldarg_0.callvirt(info4).stloc_1.ldloc_1.ldc_i4_s(9).ceq.brtrue_s(label).newobj(info5)[email protected]();
            emit.MarkLabel(label).ldloc_0.ret();
            return((ReadDataInvoker)method.CreateDelegate(typeof(ReadDataInvoker)));
        }
Ejemplo n.º 15
0
        private void BuildLazyInstanceEnsurer()
        {
            string              fieldName  = GetFieldName();
            FieldBuilder        field      = Context.GetField(fieldName);
            TypeHelper          fieldType  = new TypeHelper(field.FieldType);
            TypeHelper          objectType = new TypeHelper(GetObjectType());
            MethodBuilderHelper ensurer    = Context.TypeBuilder.DefineMethod(
                string.Format("$EnsureInstance{0}", fieldName),
                MethodAttributes.Private | MethodAttributes.HideBySig);

            EmitHelper emit = ensurer.Emitter;
            Label      end  = emit.DefineLabel();

            emit
            .ldarg_0
            .ldfld(field)
            .brtrue_s(end)
            ;

            object[]        parameters = TypeHelper.GetPropertyParameters(Context.CurrentProperty);
            ConstructorInfo ci         = objectType.GetPublicConstructor(typeof(InitContext));

            if (ci != null || objectType.IsAbstract)
            {
                CreateInitContextLazyInstance(field, fieldType, objectType, emit, parameters);
            }
            else if (parameters == null)
            {
                CreateDefaultInstance(field, fieldType, objectType, emit);
            }
            else
            {
                CreateParametrizedInstance(field, fieldType, objectType, emit, parameters);
            }

            emit
            .MarkLabel(end)
            .ret()
            ;

            Context.Items.Add("$BLToolkit.FieldInstanceEnsurer." + fieldName, ensurer);
        }
Ejemplo n.º 16
0
        public void AddNode(INode node)
        {
            if (dumpInfo.IsExcludedNodeType(node.Type))
            {
                return;
            }

            String nrName = nodeRealizer ?? GetNodeRealizer(node.Type);

            String name = graph.GetElementName(node);

            ycompStream.Write("addNode \"-1\" \"n" + name + "\" \"" + nrName + "\" \"" + GetElemLabel(node) + "\"\n");
            foreach (AttributeType attrType in node.Type.AttributeTypes)
            {
                if (attrType.Kind == AttributeKind.SetAttr || attrType.Kind == AttributeKind.MapAttr)
                {
                    IDictionary setmap = (IDictionary)node.GetAttribute(attrType.Name);
                    string      attrTypeString;
                    string      attrValue;
                    EmitHelper.ToString(setmap, out attrTypeString, out attrValue, attrType, graph);
                    ycompStream.Write("changeNodeAttr \"n" + name + "\" \"" + attrType.OwnerType.Name + "::" + attrType.Name + " : "
                                      + attrTypeString + "\" \"" + Encode(attrValue) + "\"\n");
                }
                else if (attrType.Kind == AttributeKind.ArrayAttr)
                {
                    IList  array = (IList)node.GetAttribute(attrType.Name);
                    string attrTypeString;
                    string attrValue;
                    EmitHelper.ToString(array, out attrTypeString, out attrValue, attrType, graph);
                    ycompStream.Write("changeNodeAttr \"n" + name + "\" \"" + attrType.OwnerType.Name + "::" + attrType.Name + " : "
                                      + attrTypeString + "\" \"" + Encode(attrValue) + "\"\n");
                }
                else
                {
                    object attr = node.GetAttribute(attrType.Name);
                    ycompStream.Write("changeNodeAttr \"n" + name + "\" \"" + attrType.OwnerType.Name + "::" + attrType.Name + " : "
                                      + GetKindName(attrType) + "\" \"" + EncodeAttr(attr) + "\"\n");
                }
            }
            isDirty       = true;
            isLayoutDirty = true;
        }
Ejemplo n.º 17
0
        public List <T> GetAllFromQuery <T>(SqlConnectionType connectionType, string query)
            where T : ILoadDr
        {
            var result = new List <T>();

            using (SqlConnection conn = GetSqlConnection(connectionType))
            {
                using (SqlDataReader dr = SqlHelper.ExecuteReader(conn, query, CommandType.Text, null))
                {
                    while (dr.Read())
                    {
                        var model = (T)EmitHelper.GetInstanceCreator(typeof(T)).Invoke();
                        model.LoadData(dr);
                        result.Add(model);
                    }
                }
            }

            return(result);
        }
Ejemplo n.º 18
0
        protected FieldBuilder GetTypeAccessorField()
        {
            string       fieldName = "_" + GetObjectType().FullName + "_$typeAccessor";
            FieldBuilder field     = Context.GetField(fieldName);

            if (field == null)
            {
                field = Context.CreatePrivateStaticField(fieldName, typeof(TypeAccessor));

                EmitHelper emit = Context.TypeBuilder.TypeInitializer.Emitter;

                emit
                .LoadType(GetObjectType())
                .call(typeof(TypeAccessor), "GetAccessor", typeof(Type))
                .stsfld(field)
                ;
            }

            return(field);
        }
Ejemplo n.º 19
0
        private void CallBaseMethod()
        {
            EmitHelper emit   = Context.MethodBuilder.Emitter;
            MethodInfo method = Context.MethodBuilder.OverriddenMethod;

            ParameterInfo[] ps = method.GetParameters();

            emit.ldarg_0.end();

            for (int i = 0; i < ps.Length; i++)
            {
                emit.ldarg(i + 1);
            }

            emit.call(method);

            if (Context.ReturnValue != null)
            {
                emit.stloc(Context.ReturnValue);
            }
        }
Ejemplo n.º 20
0
 /// <summary>
 /// 设置返回值信息。
 /// </summary>
 /// <param name="emitter"></param>
 /// <param name="returnType"></param>
 /// <param name="lbRetValNotNull"></param>
 /// <returns></returns>
 private static EmitHelper GetReturnValue(this EmitHelper emitter, Type returnType, Label lbRetValNotNull)
 {
     return(emitter
            .ldloc(STACK_CALLINFO_INDEX)
            .callvirt(InterceptCache.CallInfoGetReturnValue)
            .Assert(returnType.IsValueType, e1 =>
                    e1.brtrue_s(lbRetValNotNull)
                    .ldtoken(returnType)
                    .call(InterceptCache.TypeGetTypeFromHandle)
                    .call(InterceptCache.MethodGetDefaultValue)
                    .Assert(returnType.IsValueType, e => e.unbox_any(returnType))
                    .ret()
                    .MarkLabel(lbRetValNotNull)
                    .ldloc(STACK_CALLINFO_INDEX)
                    .callvirt(InterceptCache.CallInfoGetReturnValue)
                    .Assert(returnType.IsValueType, e => e.unbox_any(returnType))
                    .ret(),
                    e1 =>
                    e1.ret()
                    ));
 }
Ejemplo n.º 21
0
 public override void Emit( )
 {
     if (OpToken.Kind == TokenKindSymbol.ADD)
     {
         RightExp.Emit();
     }
     else
     {
         if (ZTypeUtil.IsFloat(RetType))//(RetType.SharpType == typeof(float))
         {
             IL.Emit(OpCodes.Ldc_R4, 0.0);
         }
         else if (ZTypeUtil.IsInt(RetType))//if (RetType.SharpType == typeof(int))
         {
             EmitHelper.LoadInt(IL, 0);
         }
         RightExp.Emit();
         IL.Emit(OpCodes.Sub);
     }
     base.EmitConv();
 }
Ejemplo n.º 22
0
        public override void Emit()
        {
            var          zlistType   = TypeExp.RetType.SharpType;
            var          Constructor = zlistType.GetConstructor(new Type[] {});// ConstructorDesc.Constructor;
            LocalBuilder varLocal    = IL.DeclareLocal(zlistType);

            EmitHelper.NewObj(IL, Constructor);
            IL.Emit(OpCodes.Stloc, varLocal);

            MethodInfo  addMethod       = zlistType.GetMethod(CompileConstant.ZListAddMethodName);//"Add");
            ZMethodInfo exAddMethodInfo = new ZMethodInfo(addMethod);

            foreach (var exp in ArgExp.InneExps)
            {
                EmitHelper.LoadVar(IL, varLocal);//il.Emit(OpCodes.Ldloc, varLocal);
                exp.Emit();
                EmitHelper.CallDynamic(IL, exAddMethodInfo.SharpMethod);
            }
            EmitHelper.LoadVar(IL, varLocal);//il.Emit(OpCodes.Ldloc, varLocal);
            base.EmitConv();
        }
Ejemplo n.º 23
0
        protected FieldBuilder GetParameterField()
        {
            string       fieldName = GetFieldName() + "_$parameters";
            FieldBuilder field     = Context.GetField(fieldName);

            if (field == null)
            {
                field = Context.CreatePrivateStaticField(fieldName, typeof(object[]));

                FieldBuilder piField = GetPropertyInfoField();
                EmitHelper   emit    = Context.TypeBuilder.TypeInitializer.Emitter;

                emit
                .ldsfld(piField)
                .call(typeof(TypeHelper).GetMethod("GetPropertyParameters"))
                .stsfld(field)
                ;
            }

            return(field);
        }
Ejemplo n.º 24
0
        private void EndEmitMethod()
        {
            EmitHelper emit = _context.MethodBuilder.Emitter;

            // Prepare return.
            //
            emit.MarkLabel(_context.ReturnLabel);

            if (_context.ReturnValue != null)
            {
                emit.ldloc(_context.ReturnValue);
            }

            emit.ret();

            // Cleanup the context.
            //
            _context.ReturnValue   = null;
            _context.CurrentMethod = null;
            _context.MethodBuilder = null;
        }
Ejemplo n.º 25
0
        void generateEveryOne(EmitExpContext context)
        {
            ILGenerator il          = context.ILout;
            var         True_Label  = il.DefineLabel();
            var         False_Label = il.DefineLabel();

            generateList(context, everyoneExp);
            generateCount(context);
            genInitIndex(context);

            generateCondition(context);
            il.Emit(OpCodes.Brfalse, False_Label);

            //定义一个标签,表示从下面开始进入循环体
            il.MarkLabel(True_Label);
            genBody(context);
            EmitHelper.Inc(il, indexSymbol.VarBuilder);
            generateCondition(context);
            il.Emit(OpCodes.Brtrue, True_Label);
            il.MarkLabel(False_Label);
        }
Ejemplo n.º 26
0
        private void HighlightDictionary(IDictionary value, string name, bool addAnnotation)
        {
            Type keyType;
            Type valueType;

            ContainerHelper.GetDictionaryTypes(value.GetType(), out keyType, out valueType);
            if (valueType == typeof(SetValueType))
            {
                foreach (DictionaryEntry entry in value)
                {
                    if (entry.Key is IGraphElement)
                    {
                        HighlightSingleValue(entry.Key, name, addAnnotation);
                    }
                }
            }
            else
            {
                int cnt = 0;
                foreach (DictionaryEntry entry in value)
                {
                    if (entry.Key is INode && entry.Value is INode)
                    {
                        HighlightMapping((INode)entry.Key, (INode)entry.Value, name, cnt, addAnnotation);
                        ++cnt;
                    }
                    else
                    {
                        if (entry.Key is IGraphElement)
                        {
                            HighlightSingleValue(entry.Key, name + ".Domain -> " + EmitHelper.ToString(entry.Value, shellProcEnv.ProcEnv.NamedGraph), addAnnotation);
                        }
                        if (entry.Value is IGraphElement)
                        {
                            HighlightSingleValue(entry.Value, EmitHelper.ToString(entry.Key, shellProcEnv.ProcEnv.NamedGraph) + " -> " + name + ".Range", addAnnotation);
                        }
                    }
                }
            }
        }
Ejemplo n.º 27
0
        protected override void BuildAbstractMethod()
        {
            EmitHelper           emit             = Context.MethodBuilder.Emitter;
            List <ParameterInfo> parameters       = new List <ParameterInfo>();
            ParameterInfo        callback         = null;
            ParameterInfo        exceptionHandler = null;

            foreach (ParameterInfo p in Context.CurrentMethod.GetParameters())
            {
                Type   parameterType = p.ParameterType;
                string paramTypeName = parameterType.Name.Split('`')[0];

                if (paramTypeName == "Action")
                {
                    if (parameterType.IsGenericType && parameterType.GetGenericArguments()[0] == typeof(Exception))
                    {
                        exceptionHandler = p;
                    }
                    else
                    {
                        callback = p;
                    }
                }
                else
                {
                    parameters.Add(p);
                }
            }

            EmitMethodName(emit);

            if (callback == null)
            {
                EmitSyncCall(parameters, emit);
            }
            else
            {
                EmitAsyncCall(parameters, emit, callback, exceptionHandler);
            }
        }
Ejemplo n.º 28
0
        public override void Emit()
        {
            Type toType  = ZTypeUtil.GetTypeOrBuilder(TypeExp.RetType);
            Type argType = ZTypeUtil.GetTypeOrBuilder(ArgExp.RetType);

            if (toType == typeof(int))
            {
                if (argType == typeof(int))
                {
                    ArgExp.Emit();
                    return;
                }
                else if (argType == typeof(float))
                {
                    ArgExp.Emit();
                    IL.Emit(OpCodes.Conv_I);
                    return;
                }
            }
            else if (toType == typeof(float))
            {
                if (argType == typeof(int))
                {
                    ArgExp.Emit();
                    IL.Emit(OpCodes.Conv_R4);
                    return;
                }
                else if (argType == typeof(float))
                {
                    ArgExp.Emit();
                    return;
                }
            }

            caseMethod         = MakeCastMethod(TypeExp.RetType);
            ArgExp.RequireType = ZLangBasicTypes.ZOBJECT;
            ArgExp.Emit();
            EmitHelper.CallDynamic(IL, caseMethod);
            base.EmitConv();
        }
        /// <summary>
        /// DataTable转List
        /// </summary>
        /// <typeparam name="T">转换类型</typeparam>
        /// <param name="dt">数据源</param>
        /// <returns></returns>
        public static List <T> EmitToList <T>(this DataTable dt)
        {
            //确认参数有效
            if (dt == null)
            {
                return(null);
            }

            List <T> list       = new List <T>();
            var      objBuilder = EmitHelper.CreateBuilder(typeof(T));

            for (int i = 0; i < dt.Rows.Count; i++)
            {
                //创建泛型对象
                T _t = (T)objBuilder();
                //获取对象所有属性
                PropertyInfo[] propertyInfo = _t.GetType().GetProperties();
                for (int j = 0; j < dt.Columns.Count; j++)
                {
                    foreach (PropertyInfo info in propertyInfo)
                    {
                        //属性名称和列名相同时赋值
                        if (dt.Columns[j].ColumnName.ToUpper().Equals(info.Name.ToUpper()))
                        {
                            if (dt.Rows[i][j] != DBNull.Value)
                            {
                                info.SetValue(_t, dt.Rows[i][j], null);
                            }
                            else
                            {
                                info.SetValue(_t, null, null);
                            }
                            break;
                        }
                    }
                }
                list.Add(_t);
            }
            return(list);
        }
Ejemplo n.º 30
0
        public override void Emit()
        {
            lambdaExp.Emit();
            LocalBuilder lanmbdaLocalBuilder = IL.DeclareLocal(lambdaExp.NestedClassContext.EmitContext.ClassBuilder);

            IL.Emit(OpCodes.Newobj, lambdaExp.NewBuilder);
            EmitHelper.StormVar(IL, lanmbdaLocalBuilder);
            int i = 0;

            if (this.ExpContext.ClassContext.IsStaticClass == false)
            {
                SymbolDefField fieldSymbol = lambdaExp.FieldSymbols[0];
                EmitHelper.LoadVar(IL, lanmbdaLocalBuilder);
                EmitHelper.EmitThis(IL, false);
                IL.Emit(OpCodes.Stfld, fieldSymbol.Field);
                i++;
            }
            for (; i < this.BodySymbolVars.Count; i++)
            {
                SymbolBase     thisSymbol  = this.BodySymbolVars[i];
                SymbolDefField fieldSymbol = lambdaExp.FieldSymbols[i];

                EmitHelper.LoadVar(IL, lanmbdaLocalBuilder);
                //SymbolInfo inMethodSymbol = symbols.Get(field);
                //EmitHelper.EmitSymbolGet(IL, thisSymbol);
                if (EmitSymbolHelper.NeedCallThis(thisSymbol))
                {
                    EmitHelper.Emit_LoadThis(IL);
                }
                EmitSymbolHelper.EmitLoad(IL, thisSymbol);
                IL.Emit(OpCodes.Stfld, fieldSymbol.Field);
            }

            EmitHelper.LoadVar(IL, lanmbdaLocalBuilder);
            IL.Emit(OpCodes.Ldftn, lambdaExp.ProcBuilder);//.EmitContext.CurrentMethodBuilder);
            ConstructorInfo[] constructorInfos = lambdaExp.FnRetType.SharpType.GetConstructors();
            IL.Emit(OpCodes.Newobj, constructorInfos[0]);
            base.EmitConv();
        }
Ejemplo n.º 31
0
        public static Type Create(Type targetType, JSBindingOptions options, NamingConvention namingConvention)
        {
            Initialize();

            // create the type
            TypeBuilder type = module.DefineType(
                string.Format("{0}.{1}Proxy", namespaceName, targetType.FullName),
                TypeAttributes.Public | TypeAttributes.Sealed,
                typeof(JSObjectBase),
                new Type[] { targetType }
                );

            // TODO: properties

            // create members
            foreach (var method in targetType.GetMethods())
            {
                // explicit interface implementation
                MethodBuilder mb = type.DefineMethod(
                        targetType.Name + "." + method.Name,
                        MethodAttributes.Private | MethodAttributes.HideBySig |
                        MethodAttributes.NewSlot | MethodAttributes.Virtual |
                        MethodAttributes.Final,
                        method.ReturnType,
                        method.GetParameters().Select(_ => _.ParameterType).ToArray()
                        );
                type.DefineMethodOverride(mb, method);

                var emit = new EmitHelper(mb.GetILGenerator());
                emit.LdArg(1)
                    .Ret()
                    ;
            }

            return type.CreateType();
        }
Ejemplo n.º 32
0
		private LocalBuilder GetInitContextBuilder(
			string initContextName, EmitHelper emit)
		{
			var initField = Context.GetItem<LocalBuilder>(initContextName);

			if (initField == null)
			{
				Context.Items.Add(initContextName, initField = emit.DeclareLocal(InitContextType));

				emit
					.newobj   (InitContextType.GetPublicDefaultConstructor())

					.dup
					.ldarg_0
					.callvirt (InitContextType.GetProperty("Parent").GetSetMethod())

					.dup
					.ldc_i4_1
					.callvirt (InitContextType.GetProperty("IsInternal").GetSetMethod())

					.stloc    (initField)
					;

				Context.Items.Add("$BLToolkit.Default.DirtyParameters", false);
			}

			return initField;
		}
Ejemplo n.º 33
0
        private static void EmitInvoker(EmitHelper emit, MethodInfo method, int? argc, bool setter)
        {
            var parameters = method.GetParameters();
            var methodArgC = parameters.Length;

            if (!argc.HasValue)
            {
                EmitThrowIfArgumentCountMismatch(emit, methodArgC);
                argc = methodArgC;
            }

            emit.LdArg(retvalArgIndex);

            // instance method
            if (!method.IsStatic)
            {
                emit.LdArg(objArgIndex);
            }

            // prepare arguments
            for (var i = 0; i < parameters.Length; i++)
            {
                var parameter = parameters[i];

                if (i < argc.Value)
                {
                    var changeTypeMethod = CefConvert.GetChangeTypeMethod(typeof(cef_v8value_t*), parameter.ParameterType);

                    EmitLdV8Argument(emit, i);
                    emit.Call(changeTypeMethod);
                }
                else
                {
                    // push default arg
                    if (!parameter.IsOptional) throw new JSBindingException("MethodInvoker compilation error.");

                    EmitLdRawDefaultValue(emit, parameter.RawDefaultValue);
                }
            }

            // call target method
            if (method.IsStatic)
            {
                emit.Call(method);
            }
            else
            {
                emit.CallVirt(method);
            }

            if (method.ReturnType == typeof(void))
            {
                // If method is setter, then it can be called with retval == null from V8Accessor.
                if (setter)
                {
                    var returnValueLabel = emit.DefineLabel();

                    emit.Dup()
                        .BrTrueS(returnValueLabel)
                        .Pop()
                        .Ret()
                        .MarkLabel(returnValueLabel);
                    ;
                }

                if (ForceVoidToUndefined)
                {
                    emit.Call(createUndefinedNativeV8ValueMethod);
                }
                else
                {
                    emit.LdNull();
                }
            }
            else
            {
                // convert return value
                var retValchangeTypeMethod = CefConvert.GetChangeTypeMethod(method.ReturnType, typeof(cef_v8value_t*));
                emit.Call(retValchangeTypeMethod);
            }

            // store result at retval
            emit.StIndI();

            // return
            emit.Ret();
        }
Ejemplo n.º 34
0
		private void BuildHolderInstance(EmitHelper emit)
		{
			var fieldName  = GetFieldName();
			var field      = Context.GetField(fieldName);
			var fieldType  = new TypeHelper(field.FieldType);
			var objectType = new TypeHelper(GetObjectType());

			var ci = fieldType.GetPublicDefaultConstructor();

			if (ci != null)
			{
				emit
					.ldarg_0
					.newobj (ci)
					.stfld  (field)
					;
			}
			else
			{
				if (!CheckObjectHolderCtor(fieldType, objectType))
					return;

				emit
					.ldarg_0
					.ldnull
					.newobj (fieldType, objectType)
					.stfld  (field)
					;
			}
		}
Ejemplo n.º 35
0
		private void CreateDefaultInstance(
			FieldBuilder field, TypeHelper fieldType, TypeHelper objectType, EmitHelper emit)
		{
			if (!CheckObjectHolderCtor(fieldType, objectType))
				return;

			if (objectType.Type == typeof(string))
			{
				emit
					.ldarg_0
					.LoadInitValue (objectType)
					;
			}
			else if (objectType.IsArray)
			{
				var initializer = GetArrayInitializer(objectType);

				emit
					.ldarg_0
					.ldsfld  (initializer)
					;
			}
			else
			{
				var ci = objectType.GetPublicDefaultConstructor();

				if (ci == null)
				{
					if (objectType.Type.IsValueType)
						return;

					var message = string.Format(
						Resources.TypeBuilder_PropertyTypeHasNoPublicDefaultCtor,
						Context.CurrentProperty.Name,
						Context.Type.FullName,
						objectType.FullName);

					emit
						.ldstr  (message)
						.newobj (typeof(TypeBuilderException), typeof(string))
						.@throw
						.end()
						;

					return;
				}

				emit
					.ldarg_0
					.newobj  (ci)
					;
			}

			if (IsObjectHolder)
			{
				emit
					.newobj (fieldType, objectType)
					;
			}

			emit
				.stfld (field)
				;
		}
Ejemplo n.º 36
0
        private static void EmitLdRawDefaultValue(EmitHelper emit, object value)
        {
            if (value == null)
            {
                emit.LdNull();
            }
            else
            {
                switch (Type.GetTypeCode(value.GetType()))
                {
                    case TypeCode.Empty:
                        emit.LdNull();
                        break;

                    // case TypeCode.Object:
                    // case TypeCode.DBNull:

                    case TypeCode.Boolean:
                        emit.LdConstI4(((bool)value) ? 1 : 0);
                        break;

                    case TypeCode.Char:
                        emit.LdConstI4((int)(char)value);
                        break;

                    case TypeCode.SByte:
                        emit.LdConstI4((int)(sbyte)value);
                        break;

                    case TypeCode.Byte:
                        emit.LdConstI4((int)(byte)value);
                        break;

                    case TypeCode.Int16:
                        emit.LdConstI4((int)(short)value);
                        break;

                    case TypeCode.UInt16:
                        emit.LdConstI4((int)(ushort)value);
                        break;

                    case TypeCode.Int32:
                        emit.LdConstI4((int)value);
                        break;

                    // TODO: support types for opt args
                    // case TypeCode.UInt32:
                    // case TypeCode.Int64:
                    // case TypeCode.UInt64:
                    // case TypeCode.Single:
                    // case TypeCode.Double:
                    // case TypeCode.Decimal:
                    // case TypeCode.DateTime:

                    case TypeCode.String:
                        emit.LdStr((string)value);
                        break;

                    default:
                        throw new JSBindingException(string.Format("Type '{0}' for default values is not supported.", value.GetType().FullName));
                }
            }
        }
Ejemplo n.º 37
0
        private static void EmitLdV8Argument(EmitHelper emit, int index)
        {
            if (index < 0) throw new ArgumentException("index");

            emit.LdArg(argumentsArgIndex);
            if (index > 0)
            {
                emit.LdConstI4(index * IntPtr.Size)
                    .Add();
            }
            emit.LdIndI();
        }
Ejemplo n.º 38
0
        private static void EmitThrowIfArgumentCountMismatch(EmitHelper emit, int expectedArgumentCount)
        {
            var doneLabel = emit.DefineLabel();

            emit.LdArg(argumentsCountArgIndex)
                .LdConstI4(expectedArgumentCount)
                .BeqS(doneLabel)
                .Call(throwArgumentCountMismatchMethod)
                .MarkLabel(doneLabel)
                ;
        }
Ejemplo n.º 39
0
		private void CreateInitContextDefaultInstance(
			string       initContextName,
			FieldBuilder field,
			TypeHelper   fieldType,
			TypeHelper   objectType,
			EmitHelper   emit,
			object[]     parameters)
		{
			if (!CheckObjectHolderCtor(fieldType, objectType))
				return;

			var initField    = GetInitContextBuilder(initContextName, emit);
			var memberParams = InitContextType.GetProperty("MemberParameters").GetSetMethod();

			if (parameters != null)
			{
				emit
					.ldloc    (initField)
					.ldsfld   (GetParameterField())
					.callvirt (memberParams)
					;
			}
			else if ((bool)Context.Items["$BLToolkit.Default.DirtyParameters"])
			{
				emit
					.ldloc    (initField)
					.ldnull
					.callvirt (memberParams)
					;
			}

			Context.Items["$BLToolkit.Default.DirtyParameters"] = parameters != null;

			if (objectType.IsAbstract)
			{
				emit
					.ldarg_0
					.ldsfld             (GetTypeAccessorField())
					.ldloc              (initField)
					.callvirtNoGenerics (typeof(TypeAccessor), "CreateInstanceEx", _initContextType)
					.isinst             (objectType)
					;
			}
			else
			{
				emit
					.ldarg_0
					.ldloc   (initField)
					.newobj  (objectType.GetPublicConstructor(typeof(InitContext)))
					;
			}

			if (IsObjectHolder)
			{
				emit
					.newobj (fieldType, objectType)
					;
			}

			emit
				.stfld (field)
				;
		}
Ejemplo n.º 40
0
		private void CreateAbstractInitContextInstance(
			FieldBuilder field, TypeHelper fieldType, TypeHelper objectType, EmitHelper emit, object[] parameters)
		{
			if (!CheckObjectHolderCtor(fieldType, objectType))
				return;

			var memberParams = InitContextType.GetProperty("MemberParameters").GetSetMethod();
			var parentField  = Context.GetItem<LocalBuilder>("$BLToolkit.InitContext.Parent");

			if (parentField == null)
			{
				Context.Items.Add("$BLToolkit.InitContext.Parent", parentField = emit.DeclareLocal(typeof(object)));

				var label = emit.DefineLabel();

				emit
					.ldarg_1
					.brtrue_s  (label)

					.newobj    (InitContextType.GetPublicDefaultConstructor())
					.starg     (1)

					.ldarg_1
					.ldc_i4_1
					.callvirt  (InitContextType.GetProperty("IsInternal").GetSetMethod())

					.MarkLabel (label)

					.ldarg_1
					.callvirt  (InitContextType.GetProperty("Parent").GetGetMethod())
					.stloc     (parentField)
					;
			}

			emit
				.ldarg_1
				.ldarg_0
				.callvirt (InitContextType.GetProperty("Parent").GetSetMethod())
				;

			var isDirty = Context.GetItem<bool?>("$BLToolkit.InitContext.DirtyParameters");

			if (parameters != null)
			{
				emit
					.ldarg_1
					.ldsfld   (GetParameterField())
					.callvirt (memberParams)
					;
			}
			else if (isDirty != null && (bool)isDirty)
			{
				emit
					.ldarg_1
					.ldnull
					.callvirt (memberParams)
					;
			}

			if (Context.Items.ContainsKey("$BLToolkit.InitContext.DirtyParameters"))
				Context.Items["$BLToolkit.InitContext.DirtyParameters"] = (bool?)(parameters != null);
			else
				Context.Items.Add("$BLToolkit.InitContext.DirtyParameters", (bool?)(parameters != null));

			if (objectType.IsAbstract)
			{
				emit
					.ldarg_0
					.ldsfld             (GetTypeAccessorField())
					.ldarg_1
					.callvirtNoGenerics (typeof(TypeAccessor), "CreateInstanceEx", _initContextType)
					.isinst             (objectType)
					;
			}
			else
			{
				emit
					.ldarg_0
					.ldarg_1
					.newobj  (objectType.GetPublicConstructor(typeof(InitContext)))
					;
			}

			if (IsObjectHolder)
			{
				emit
					.newobj (fieldType, objectType)
					;
			}

			emit
				.stfld (field)
				;
		}
Ejemplo n.º 41
0
		private void CreateParametrizedInstance(
			FieldBuilder field, TypeHelper fieldType, TypeHelper objectType, EmitHelper emit, object[] parameters)
		{
			if (!CheckObjectHolderCtor(fieldType, objectType))
				return;

			Stack<ConstructorInfo> genericNestedConstructors;
			if (parameters.Length == 1)
			{
				var o = parameters[0];

				if (o == null)
				{
					if (objectType.IsValueType == false)
						emit
							.ldarg_0
							.ldnull
							.end()
							;

					if (IsObjectHolder)
					{
						emit
							.newobj (fieldType, objectType)
							;
					}
					else
					{
						if (objectType.Type.IsGenericType)
						{
							Type nullableType = null;
							genericNestedConstructors = GetGenericNestedConstructors(
								objectType,
								typeHelper =>
									typeHelper.IsValueType == false ||
									(typeHelper.Type.IsGenericType && typeHelper.Type.GetGenericTypeDefinition() == typeof (Nullable<>)),
								typeHelper => { nullableType = typeHelper.Type; },
								() => nullableType != null);

							if (nullableType == null)
								throw new Exception("Cannot find nullable type in generic types chain");

							if (nullableType.IsValueType == false)
							{
								emit
									.ldarg_0
									.ldnull
									.end()
									;
							}
							else
							{
								var nullable = emit.DeclareLocal(nullableType);

								emit
									.ldloca(nullable)
									.initobj(nullableType)
									.ldarg_0
									.ldloc(nullable)
									;

								if (genericNestedConstructors != null)
								{
									while (genericNestedConstructors.Count != 0)
									{
										emit
											.newobj(genericNestedConstructors.Pop())
											;
									}
								}
							}
						}
					}

					emit
						.stfld (field)
						;

					return;
				}
				
				if (objectType.Type == o.GetType())
				{
					if (objectType.Type == typeof(string))
					{
						emit
							.ldarg_0
							.ldstr   ((string)o)
							.stfld   (field)
							;

						return;
					}

					if (objectType.IsValueType)
					{
						emit.ldarg_0.end();

						if (emit.LoadWellKnownValue(o) == false)
						{
							emit
								.ldsfld     (GetParameterField())
								.ldc_i4_0
								.ldelem_ref
								.end()
								;
						}

						emit.stfld(field);

						return;
					}
				}
			}

			var types = new Type[parameters.Length];

			for (var i = 0; i < parameters.Length; i++)
			{
				if (parameters[i] != null)
				{
					var t = parameters[i].GetType();

					types[i] = (t.IsEnum) ? Enum.GetUnderlyingType(t) : t;
				}
				else
					types[i] = typeof(object);
			}

			// Do some heuristics for Nullable<DateTime> and EditableValue<Decimal>
			//
			ConstructorInfo objectCtor = null;
			genericNestedConstructors = GetGenericNestedConstructors(
				objectType,
				typeHelper => true,
				typeHelper => { objectCtor = typeHelper.GetPublicConstructor(types); },
				() => objectCtor != null);

			if (objectCtor == null)
			{
				if (objectType.IsValueType)
					return;

				throw new TypeBuilderException(
					string.Format(types.Length == 0?
							Resources.TypeBuilder_PropertyTypeHasNoPublicDefaultCtor:
							Resources.TypeBuilder_PropertyTypeHasNoPublicCtor,
						Context.CurrentProperty.Name,
						Context.Type.FullName,
						objectType.FullName));
			}

			var pi = objectCtor.GetParameters();

			emit.ldarg_0.end();

			for (var i = 0; i < parameters.Length; i++)
			{
				var o     = parameters[i];
				var oType = o.GetType();

				if (emit.LoadWellKnownValue(o))
				{
					if (oType.IsValueType)
					{
						if (!pi[i].ParameterType.IsValueType)
							emit.box(oType);
						else if (Type.GetTypeCode(oType) != Type.GetTypeCode(pi[i].ParameterType))
							emit.conv(pi[i].ParameterType);
					}
				}
				else
				{
					emit
						.ldsfld         (GetParameterField())
						.ldc_i4         (i)
						.ldelem_ref
						.CastFromObject (types[i])
						;

					if (oType.IsValueType && !pi[i].ParameterType.IsValueType)
						emit.box(oType);
				}
			}

			emit
				.newobj (objectCtor)
				;

			if (genericNestedConstructors != null)
			{
				while (genericNestedConstructors.Count != 0)
				{
					emit
						.newobj(genericNestedConstructors.Pop())
						;
				}
			}

			if (IsObjectHolder)
			{
				emit
					.newobj (fieldType, objectType)
					;
			}

			emit
				.stfld  (field)
				;
		}
Ejemplo n.º 42
0
		private void CreateInitContextLazyInstance(
			FieldBuilder field,
			TypeHelper   fieldType,
			TypeHelper   objectType,
			EmitHelper   emit,
			object[]     parameters)
		{
			if (!CheckObjectHolderCtor(fieldType, objectType))
				return;

			var initField = emit.DeclareLocal(InitContextType);

			emit
				.newobj   (InitContextType.GetPublicDefaultConstructor())

				.dup
				.ldarg_0
				.callvirt (InitContextType.GetProperty("Parent").GetSetMethod())

				.dup
				.ldc_i4_1
				.callvirt (InitContextType.GetProperty("IsInternal").GetSetMethod())

				.dup
				.ldc_i4_1
				.callvirt (InitContextType.GetProperty("IsLazyInstance").GetSetMethod())

				;

			if (parameters != null)
			{
				emit
					.dup
					.ldsfld   (GetParameterField())
					.callvirt (InitContextType.GetProperty("MemberParameters").GetSetMethod())
					;
			}

			emit
				.stloc    (initField);

			if (objectType.IsAbstract)
			{
				emit
					.ldarg_0
					.ldsfld             (GetTypeAccessorField())
					.ldloc              (initField)
					.callvirtNoGenerics (typeof(TypeAccessor), "CreateInstanceEx", _initContextType)
					.isinst             (objectType)
					;
			}
			else
			{
				emit
					.ldarg_0
					.ldloc   (initField)
					.newobj  (objectType.GetPublicConstructor(typeof(InitContext)))
					;
			}

			if (IsObjectHolder)
			{
				emit
					.newobj (fieldType, objectType)
					;
			}

			emit
				.stfld (field)
				;
		}