Exemplo n.º 1
0
        private void WriteFieldHandler(
            Compiler.CompilerContext ctx, Type expected, Compiler.Local loc,
            Compiler.CodeLabel handler, Compiler.CodeLabel @continue, IProtoSerializer serializer)
        {
            ctx.MarkLabel(handler);
            if (serializer.ExpectedType == forType)
            {
                EmitCreateIfNull(ctx, loc);
                serializer.EmitRead(ctx, loc);
            }
            else
            {
                RuntimeTypeModel rtm = (RuntimeTypeModel)ctx.Model;
                if (((IProtoTypeSerializer)serializer).CanCreateInstance())
                {
                    Compiler.CodeLabel allDone = ctx.DefineLabel();

                    ctx.LoadValue(loc);
                    ctx.BranchIfFalse(allDone, false); // null is always ok

                    ctx.LoadValue(loc);
                    ctx.TryCast(serializer.ExpectedType);
                    ctx.BranchIfTrue(allDone, false); // not null, but of the correct type

                    // otherwise, need to convert it
                    ctx.LoadReaderWriter();
                    ctx.LoadValue(loc);
                    ((IProtoTypeSerializer)serializer).EmitCreateInstance(ctx);
                    ctx.EmitCall(ctx.MapType(typeof(ProtoReader)).GetMethod("Merge"));
                    ctx.Cast(expected);
                    ctx.StoreValue(loc); // Merge always returns a value

                    // nothing needs doing
                    ctx.MarkLabel(allDone);
                }
                ctx.LoadValue(loc);
                ctx.Cast(serializer.ExpectedType);
                serializer.EmitRead(ctx, null);
            }

            if (serializer.ReturnsValue)
            {   // update the variable
                ctx.StoreValue(loc);
            }
            ctx.Branch(@continue, false); // "continue"
        }
Exemplo n.º 2
0
 protected override void EmitWrite(Compiler.CompilerContext ctx, Compiler.Local valueFrom)
 {
     if (getSpecified == null)
     {
         Tail.EmitWrite(ctx, valueFrom);
         return;
     }
     using (Compiler.Local loc = ctx.GetLocalWithValue(ExpectedType, valueFrom))
     {
         ctx.LoadAddress(loc, ExpectedType);
         ctx.EmitCall(getSpecified);
         Compiler.CodeLabel done = ctx.DefineLabel();
         ctx.BranchIfFalse(done, false);
         Tail.EmitWrite(ctx, loc);
         ctx.MarkLabel(done);
     }
 }
Exemplo n.º 3
0
        private void EmitCreateIfNull(Compiler.CompilerContext ctx, Type type, Compiler.Local storage)
        {
            Helpers.DebugAssert(storage != null);
            if (!type.IsValueType)
            {
                Compiler.CodeLabel afterNullCheck = ctx.DefineLabel();
                ctx.LoadValue(storage);
                ctx.BranchIfTrue(afterNullCheck, true);

                // different ways of creating a new instance
                if (!useConstructor)
                {   // DataContractSerializer style
                    ctx.LoadValue(forType);
                    ctx.EmitCall(typeof(BclHelpers).GetMethod("GetUninitializedObject"));
                    ctx.Cast(forType);
                }
                else if (type.IsClass && !type.IsAbstract && (
                             (type.GetConstructor(
                                  BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public,
                                  null, Helpers.EmptyTypes, null)) != null))
                {   // XmlSerializer style
                    ctx.EmitCtor(type);
                }
                else
                {
                    ctx.LoadValue(type);
                    ctx.EmitCall(typeof(TypeModel).GetMethod("ThrowCannotCreateInstance",
                                                             BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic));
                    ctx.LoadNullRef();
                }
                if (baseCtorCallbacks != null)
                {
                    for (int i = 0; i < baseCtorCallbacks.Length; i++)
                    {
                        EmitInvokeCallback(ctx, baseCtorCallbacks[i]);
                    }
                }
                if (callbacks != null)
                {
                    EmitInvokeCallback(ctx, callbacks.BeforeDeserialize);
                }
                ctx.StoreValue(storage);
                ctx.MarkLabel(afterNullCheck);
            }
        }
            protected override void EmitRead(Compiler.CompilerContext ctx, Compiler.Local valueFrom)
            {
                using (ctx.StartDebugBlockAuto(this))
                {
                    Tail.EmitRead(ctx, valueFrom);
                    ctx.CopyValue();
                    Compiler.CodeLabel @nonEmpty = ctx.DefineLabel(), @end = ctx.DefineLabel();
                    ctx.LoadValue(typeof(string).GetProperty("Length"));
                    ctx.BranchIfTrue(@nonEmpty, true);
                    ctx.DiscardValue();
                    ctx.LoadNullRef();
                    ctx.Branch(@end, true);
                    ctx.MarkLabel(@nonEmpty);
                    ctx.EmitCtor(expectedType, ctx.MapType(typeof(string)));
                    ctx.MarkLabel(@end);
                }
#endif
    }
Exemplo n.º 5
0
        protected override void EmitRead(Compiler.CompilerContext ctx, Compiler.Local valueFrom)
        {
            using (Compiler.Local loc = ctx.GetLocalWithValue(ExpectedType, valueFrom))
            {
                if (Tail.RequiresOldValue)
                {
                    ctx.LoadAddress(loc, ExpectedType);
                    ctx.LoadValue(field);
                }
                // value is either now on the stack or not needed
                ctx.ReadNullCheckedTail(field.FieldType, Tail, null, overrideType);

                if (Tail.ReturnsValue)
                {
                    var newType = overrideType != null ? overrideType : field.FieldType;
                    using (Compiler.Local newVal = new Compiler.Local(ctx, newType))
                    {
                        ctx.StoreValue(newVal);
                        if (Helpers.IsValueType(field.FieldType))
                        {
                            ctx.LoadAddress(loc, ExpectedType);
                            ctx.LoadValue(newVal);
                            ctx.StoreValue(field);
                        }
                        else
                        {
                            Compiler.CodeLabel allDone = ctx.DefineLabel();
                            ctx.LoadValue(newVal);
                            ctx.BranchIfFalse(allDone, true); // interpret null as "don't assign"

                            ctx.LoadAddress(loc, ExpectedType);
                            ctx.LoadValue(newVal);
                            if (overrideType != null)
                            {
                                ctx.Cast(field.FieldType);
                            }
                            ctx.StoreValue(field);

                            ctx.MarkLabel(allDone);
                        }
                    }
                }
            }
        }
Exemplo n.º 6
0
        protected override void EmitWrite(Compiler.CompilerContext ctx, Compiler.Local valueFrom)
        {
            using (ctx.StartDebugBlockAuto(this))
            {
                Compiler.CodeLabel done     = ctx.DefineLabel();
                Compiler.CodeLabel onCancel = ctx.DefineLabel();
                if (valueFrom.IsNullRef())
                {
                    ctx.CopyValue(); // on the stack
                    Compiler.CodeLabel needToPop = ctx.DefineLabel();

                    EmitBranchIfDefaultValue(ctx, needToPop);
                    // if != defaultValue
                    {
                        Tail.EmitWrite(ctx, null);
                        ctx.Branch(done, true);
                    }
                    // else
                    {
                        ctx.MarkLabel(needToPop);
                        ctx.DiscardValue();
                        // onCancel
                    }
                }
                else
                {
                    ctx.LoadValue(valueFrom); // variable/parameter

                    EmitBranchIfDefaultValue(ctx, onCancel);
                    // if != defaultValue
                    {
                        Tail.EmitWrite(ctx, valueFrom);
                        ctx.Branch(done, true);
                    }
                    // else
                    // onCancel
                }
                ctx.MarkLabel(onCancel);
                ctx.LoadReaderWriter();
                ctx.EmitCall(ctx.MapType(typeof(ProtoWriter)).GetMethod(nameof(ProtoWriter.WriteFieldHeaderCancelBegin)));
                ctx.MarkLabel(done);
            }
        }
Exemplo n.º 7
0
        private void EmitCreateIfNull(Compiler.CompilerContext ctx, Compiler.Local storage)
        {
            Helpers.DebugAssert(storage != null);
            if (!ExpectedType.IsValueType)
            {
                Compiler.CodeLabel afterNullCheck = ctx.DefineLabel();
                ctx.LoadValue(storage);
                ctx.BranchIfTrue(afterNullCheck, false);

                ((IProtoTypeSerializer)this).EmitCreateInstance(ctx);

                if (callbacks != null)
                {
                    EmitInvokeCallback(ctx, callbacks.BeforeDeserialize, true, null, forType);
                }
                ctx.StoreValue(storage);
                ctx.MarkLabel(afterNullCheck);
            }
        }
Exemplo n.º 8
0
        protected override void EmitRead(Compiler.CompilerContext ctx, Compiler.Local valueFrom)
        {
            using (Compiler.Local loc = ctx.GetLocalWithValue(ExpectedType, valueFrom))
            {
                ctx.LoadAddress(loc, ExpectedType);
                if (Tail.RequiresOldValue)
                {
                    ctx.CopyValue();
                    ctx.LoadValue(field);
                }
                // value is either now on the stack or not needed
                ctx.ReadNullCheckedTail(field.FieldType, Tail, null);

                if (Tail.ReturnsValue)
                {
                    if (field.FieldType.IsValueType)
                    {
                        // stack is now the return value
                        ctx.StoreValue(field);
                    }
                    else
                    {
                        Compiler.CodeLabel hasValue = ctx.DefineLabel(), allDone = ctx.DefineLabel();
                        ctx.CopyValue();
                        ctx.BranchIfTrue(hasValue, true); // interpret null as "don't assign"

                        // no value, discard
                        ctx.DiscardValue();
                        ctx.DiscardValue();
                        ctx.Branch(allDone, true);

                        ctx.MarkLabel(hasValue);
                        ctx.StoreValue(field);
                        ctx.MarkLabel(allDone);
                    }
                }
                else
                {
                    ctx.DiscardValue();
                }
            }
        }
Exemplo n.º 9
0
        protected override void EmitWrite(ProtoBuf.Compiler.CompilerContext ctx, ProtoBuf.Compiler.Local valueFrom)
        {
            // int i and T[] arr
            using (Compiler.Local arr = ctx.GetLocalWithValue(arrayType, valueFrom))
                using (Compiler.Local i = new ProtoBuf.Compiler.Local(ctx, typeof(int)))
                {
                    if (packedFieldNumber > 0)
                    {
                        Compiler.CodeLabel allDone = ctx.DefineLabel();
                        ctx.LoadLength(arr, false);
                        ctx.BranchIfFalse(allDone, false);

                        ctx.LoadValue(packedFieldNumber);
                        ctx.LoadValue((int)WireType.String);
                        ctx.LoadReaderWriter();
                        ctx.EmitCall(typeof(ProtoWriter).GetMethod("WriteFieldHeader"));

                        ctx.LoadValue(arr);
                        ctx.LoadReaderWriter();
                        ctx.EmitCall(typeof(ProtoWriter).GetMethod("StartSubItem"));
                        using (Compiler.Local token = new Compiler.Local(ctx, typeof(SubItemToken))) {
                            ctx.StoreValue(token);

                            ctx.LoadValue(packedFieldNumber);
                            ctx.LoadReaderWriter();
                            ctx.EmitCall(typeof(ProtoWriter).GetMethod("SetPackedField"));

                            EmitWriteArrayLoop(ctx, i, arr);

                            ctx.LoadValue(token);
                            ctx.LoadReaderWriter();
                            ctx.EmitCall(typeof(ProtoWriter).GetMethod("EndSubItem"));
                        }
                        ctx.MarkLabel(allDone);
                    }
                    else
                    {
                        EmitWriteArrayLoop(ctx, i, arr);
                    }
                }
        }
Exemplo n.º 10
0
 protected override void EmitWrite(Compiler.CompilerContext ctx, Compiler.Local valueFrom)
 {
     Compiler.CodeLabel done = ctx.DefineLabel();
     if (valueFrom == null)
     {
         ctx.CopyValue(); // on the stack
         Compiler.CodeLabel needToPop = ctx.DefineLabel();
         EmitBranchIfDefaultValue(ctx, needToPop);
         Tail.EmitWrite(ctx, null);
         ctx.Branch(done, true);
         ctx.MarkLabel(needToPop);
         ctx.DiscardValue();
     }
     else
     {
         ctx.LoadValue(valueFrom); // variable/parameter
         EmitBranchIfDefaultValue(ctx, done);
         Tail.EmitWrite(ctx, valueFrom);
     }
     ctx.MarkLabel(done);
 }
Exemplo n.º 11
0
        protected override void EmitWrite(Compiler.CompilerContext ctx, Compiler.Local valueFrom)
        {
            using (Compiler.Local valOrNull = ctx.GetLocalWithValue(expectedType, valueFrom))
                using (Compiler.Local token = new Compiler.Local(ctx, ctx.MapType(typeof(SubItemToken))))
                {
                    ctx.LoadNullRef();
                    ctx.LoadReaderWriter();
                    ctx.EmitCall(ctx.MapType(typeof(ProtoWriter)).GetMethod("StartSubItem"));
                    ctx.StoreValue(token);

                    if (expectedType.IsValueType)
                    {
                        ctx.LoadAddress(valOrNull, expectedType);
                        ctx.LoadValue(expectedType.GetProperty("HasValue"));
                    }
                    else
                    {
                        ctx.LoadValue(valOrNull);
                    }
                    Compiler.CodeLabel @end = ctx.DefineLabel();
                    ctx.BranchIfFalse(@end, false);
                    if (expectedType.IsValueType)
                    {
                        ctx.LoadAddress(valOrNull, expectedType);
                        ctx.EmitCall(expectedType.GetMethod("GetValueOrDefault", Helpers.EmptyTypes));
                    }
                    else
                    {
                        ctx.LoadValue(valOrNull);
                    }
                    Tail.EmitWrite(ctx, null);

                    ctx.MarkLabel(@end);

                    ctx.LoadValue(token);
                    ctx.LoadReaderWriter();
                    ctx.EmitCall(ctx.MapType(typeof(ProtoWriter)).GetMethod("EndSubItem"));
                }
        }
Exemplo n.º 12
0
        private void EmitBeq(Compiler.CompilerContext ctx, Compiler.CodeLabel label, Type type)
        {
            switch (Helpers.GetTypeCode(type))
            {
            case ProtoTypeCode.Boolean:
            case ProtoTypeCode.Byte:
            case ProtoTypeCode.Char:
            case ProtoTypeCode.Double:
            case ProtoTypeCode.Int16:
            case ProtoTypeCode.Int32:
            case ProtoTypeCode.Int64:
            case ProtoTypeCode.SByte:
            case ProtoTypeCode.Single:
            case ProtoTypeCode.UInt16:
            case ProtoTypeCode.UInt32:
            case ProtoTypeCode.UInt64:
                ctx.BranchIfEqual(label, false);
                break;

            default:
#if COREFX
                MethodInfo method = type.GetMethod("op_Equality", new Type[] { type, type });
                if (method == null || !method.IsPublic || !method.IsStatic)
                {
                    method = null;
                }
#else
                MethodInfo method = type.GetMethod("op_Equality", BindingFlags.Public | BindingFlags.Static,
                                                   null, new Type[] { type, type }, null);
#endif
                if (method == null || method.ReturnType != ctx.MapType(typeof(bool)))
                {
                    throw new InvalidOperationException("No suitable equality operator found for default-values of type: " + type.FullName);
                }
                ctx.EmitCall(method);
                ctx.BranchIfTrue(label, false);
                break;
            }
        }
Exemplo n.º 13
0
 void IProtoSerializer.EmitWrite(Compiler.CompilerContext ctx, Compiler.Local valueFrom)
 {
     using (ctx.StartDebugBlockAuto(this))
     {
         ProtoTypeCode typeCode = GetTypeCode();
         if (_map == null)
         {
             ctx.LoadValue(valueFrom);
             ctx.ConvertToInt32(typeCode, false);
             ctx.EmitBasicWrite("WriteInt32", null);
         }
         else
         {
             using (Compiler.Local loc = ctx.GetLocalWithValue(ExpectedType, valueFrom))
             {
                 Compiler.CodeLabel @continue = ctx.DefineLabel();
                 for (int i = 0; i < _map.Length; i++)
                 {
                     Compiler.CodeLabel tryNextValue = ctx.DefineLabel(), processThisValue = ctx.DefineLabel();
                     ctx.LoadValue(loc);
                     WriteEnumValue(ctx, typeCode, _map[i].RawValue);
                     ctx.BranchIfEqual(processThisValue, true);
                     ctx.Branch(tryNextValue, true);
                     ctx.MarkLabel(processThisValue);
                     ctx.LoadValue(_map[i].WireValue);
                     ctx.EmitBasicWrite("WriteInt32", null);
                     ctx.Branch(@continue, false);
                     ctx.MarkLabel(tryNextValue);
                 }
                 ctx.LoadReaderWriter();
                 ctx.LoadValue(loc);
                 ctx.CastToObject(ExpectedType);
                 ctx.EmitCall(ctx.MapType(typeof(ProtoWriter)).GetMethod("ThrowEnumException"));
                 ctx.MarkLabel(@continue);
             }
         }
     }
 }
Exemplo n.º 14
0
        private void WriteFieldHandler(
            Compiler.CompilerContext ctx, Type expected, Compiler.Local loc,
            Compiler.CodeLabel handler, Compiler.CodeLabel @continue, IProtoSerializer serializer)
        {
            ctx.MarkLabel(handler);
            if (serializer.ExpectedType == forType)
            {
                EmitCreateIfNull(ctx, expected, loc);
                serializer.EmitRead(ctx, loc);
            }
            else
            {
                ctx.LoadValue(loc);
                ctx.Cast(serializer.ExpectedType);
                serializer.EmitRead(ctx, null);
            }

            if (serializer.ReturnsValue)
            {   // update the variable
                ctx.StoreValue(loc);
            }
            ctx.Branch(@continue, false); // "continue"
        }
Exemplo n.º 15
0
        protected override void EmitRead(ProtoBuf.Compiler.CompilerContext ctx, ProtoBuf.Compiler.Local valueFrom)
        {
            Type listType;

#if NO_GENERICS
            listType = typeof(BasicList);
#else
            listType = ctx.MapType(typeof(System.Collections.Generic.List <>)).MakeGenericType(itemType);
#endif
            using (Compiler.Local oldArr = AppendToCollection ? ctx.GetLocalWithValue(ExpectedType, valueFrom) : null)
                using (Compiler.Local newArr = new Compiler.Local(ctx, ExpectedType))
                    using (Compiler.Local list = new Compiler.Local(ctx, listType))
                    {
                        ctx.EmitCtor(listType);
                        ctx.StoreValue(list);
                        ListDecorator.EmitReadList(ctx, list, Tail, listType.GetMethod("Add"), packedWireType, false);

                        // leave this "using" here, as it can share the "FieldNumber" local with EmitReadList
                        using (Compiler.Local oldLen = AppendToCollection ? new ProtoBuf.Compiler.Local(ctx, ctx.MapType(typeof(int))) : null) {
                            Type[] copyToArrayInt32Args = new Type[] { ctx.MapType(typeof(Array)), ctx.MapType(typeof(int)) };

                            if (AppendToCollection)
                            {
                                ctx.LoadLength(oldArr, true);
                                ctx.CopyValue();
                                ctx.StoreValue(oldLen);

                                ctx.LoadAddress(list, listType);
                                ctx.LoadValue(listType.GetProperty("Count"));
                                ctx.Add();
                                ctx.CreateArray(itemType, null); // length is on the stack
                                ctx.StoreValue(newArr);

                                ctx.LoadValue(oldLen);
                                Compiler.CodeLabel nothingToCopy = ctx.DefineLabel();
                                ctx.BranchIfFalse(nothingToCopy, true);
                                ctx.LoadValue(oldArr);
                                ctx.LoadValue(newArr);
                                ctx.LoadValue(0); // index in target

                                ctx.EmitCall(ExpectedType.GetMethod("CopyTo", copyToArrayInt32Args));
                                ctx.MarkLabel(nothingToCopy);

                                ctx.LoadValue(list);
                                ctx.LoadValue(newArr);
                                ctx.LoadValue(oldLen);
                            }
                            else
                            {
                                ctx.LoadAddress(list, listType);
                                ctx.LoadValue(listType.GetProperty("Count"));
                                ctx.CreateArray(itemType, null);
                                ctx.StoreValue(newArr);

                                ctx.LoadAddress(list, listType);
                                ctx.LoadValue(newArr);
                                ctx.LoadValue(0);
                            }

                            copyToArrayInt32Args[0] = ExpectedType; // // prefer: CopyTo(T[], int)
                            MethodInfo copyTo = listType.GetMethod("CopyTo", copyToArrayInt32Args);
                            if (copyTo == null)
                            { // fallback: CopyTo(Array, int)
                                copyToArrayInt32Args[1] = ctx.MapType(typeof(Array));
                                copyTo = listType.GetMethod("CopyTo", copyToArrayInt32Args);
                            }
                            ctx.EmitCall(copyTo);
                        }
                        ctx.LoadValue(newArr);
                    }
        }
Exemplo n.º 16
0
 void IProtoSerializer.EmitRead(Compiler.CompilerContext ctx, Compiler.Local valueFrom)
 {
     TypeCode typeCode = GetTypeCode();
     if (map == null)
     {
         ctx.EmitBasicRead("ReadInt32", typeof(int));
         ctx.ConvertFromInt32(typeCode);
     }
     else
     {
         int[] wireValues = new int[map.Length];
         object[] values = new object[map.Length];
         for (int i = 0; i < map.Length; i++)
         {
             wireValues[i] = map[i].WireValue;
             values[i] = map[i].Value;
         }
         using (Compiler.Local result = new Compiler.Local(ctx, ExpectedType))
         using (Compiler.Local wireValue = new Compiler.Local(ctx, typeof(int)))
         {
             ctx.EmitBasicRead("ReadInt32", typeof(int));
             ctx.StoreValue(wireValue);
             Compiler.CodeLabel @continue = ctx.DefineLabel();
             foreach (BasicList.Group group in BasicList.GetContiguousGroups(wireValues, values))
             {
                 Compiler.CodeLabel tryNextGroup = ctx.DefineLabel();
                 int groupItemCount = group.Items.Count;
                 if (groupItemCount == 1)
                 {
                     // discreet group; use an equality test
                     ctx.LoadValue(wireValue);
                     ctx.LoadValue(group.First);
                     Compiler.CodeLabel processThisValue = ctx.DefineLabel();
                     ctx.BranchIfEqual(processThisValue, true);
                     ctx.Branch(tryNextGroup, false);
                     WriteEnumValue(ctx, typeCode, processThisValue, @continue, group.Items[0], @result);
                 }
                 else
                 {
                     // implement as a jump-table-based switch
                     ctx.LoadValue(wireValue);
                     ctx.LoadValue(group.First);
                     ctx.Subtract(); // jump-tables are zero-based
                     Compiler.CodeLabel[] jmp = new Compiler.CodeLabel[groupItemCount];
                     for (int i = 0; i < groupItemCount; i++) {
                         jmp[i] = ctx.DefineLabel();
                     }
                     ctx.Switch(jmp);
                     // write the default...
                     ctx.Branch(tryNextGroup, false);
                     for (int i = 0; i < groupItemCount; i++)
                     {
                         WriteEnumValue(ctx, typeCode, jmp[i], @continue, group.Items[i], @result);
                     }
                 }
                 ctx.MarkLabel(tryNextGroup);
             }
             // throw source.CreateEnumException(ExpectedType, wireValue);
             ctx.LoadReaderWriter();
             ctx.LoadValue(ExpectedType);
             ctx.LoadValue(wireValue);
             ctx.EmitCall(typeof(ProtoReader).GetMethod("ThrowEnumException"));
             ctx.MarkLabel(@continue);
             ctx.LoadValue(result);
         }
     }
 }
Exemplo n.º 17
0
        private void WriteFieldHandler(
            Compiler.CompilerContext ctx, Type expected, Compiler.Local loc,
            Compiler.CodeLabel handler, Compiler.CodeLabel @continue, IProtoSerializer serializer)
        {
            ctx.MarkLabel(handler);
            Type serType = serializer.ExpectedType;

            if (serType == ExpectedType)
            {
                EmitCreateIfNull(ctx, loc);
                serializer.EmitRead(ctx, loc);
            }
            else
            {
                //RuntimeTypeModel rtm = (RuntimeTypeModel)ctx.Model;
                if (((IProtoTypeSerializer)serializer).CanCreateInstance())
                {
                    Compiler.CodeLabel allDone = ctx.DefineLabel();

                    ctx.LoadValue(loc);
                    ctx.BranchIfFalse(allDone, false); // null is always ok

                    ctx.LoadValue(loc);
                    ctx.TryCast(serType);
                    ctx.BranchIfTrue(allDone, false); // not null, but of the correct type

                    // otherwise, need to convert it
                    ctx.LoadReader(false);
                    ctx.LoadValue(loc);
                    ((IProtoTypeSerializer)serializer).EmitCreateInstance(ctx);

                    ctx.EmitCall(typeof(ProtoReader).GetMethod("Merge",
                                                               new[] { typeof(ProtoReader), typeof(object), typeof(object) }));
                    ctx.Cast(expected);
                    ctx.StoreValue(loc); // Merge always returns a value

                    // nothing needs doing
                    ctx.MarkLabel(allDone);
                }

                if (Helpers.IsValueType(serType))
                {
                    Compiler.CodeLabel initValue = ctx.DefineLabel();
                    Compiler.CodeLabel hasValue  = ctx.DefineLabel();
                    using (Compiler.Local emptyValue = new Compiler.Local(ctx, serType))
                    {
                        ctx.LoadValue(loc);
                        ctx.BranchIfFalse(initValue, false);

                        ctx.LoadValue(loc);
                        ctx.CastFromObject(serType);
                        ctx.Branch(hasValue, false);

                        ctx.MarkLabel(initValue);
                        ctx.InitLocal(serType, emptyValue);
                        ctx.LoadValue(emptyValue);

                        ctx.MarkLabel(hasValue);
                    }
                }
                else
                {
                    ctx.LoadValue(loc);
                    ctx.Cast(serType);
                }

                serializer.EmitRead(ctx, null);
            }

            if (serializer.ReturnsValue)
            {   // update the variable
                if (Helpers.IsValueType(serType))
                {
                    // but box it first in case of value type
                    ctx.CastToObject(serType);
                }
                ctx.StoreValue(loc);
            }
            ctx.Branch(@continue, false); // "continue"
        }
Exemplo n.º 18
0
        void IProtoSerializer.EmitRead(Compiler.CompilerContext ctx, Compiler.Local valueFrom)
        {
            Type expected = ExpectedType;

            Helpers.DebugAssert(valueFrom != null);

            using (Compiler.Local loc = ctx.GetLocalWithValue(expected, valueFrom))
                using (Compiler.Local fieldNumber = new Compiler.Local(ctx, ctx.MapType(typeof(int))))
                {
                    // pre-callbacks
                    if (HasCallbacks(TypeModel.CallbackType.BeforeDeserialize))
                    {
                        if (ExpectedType.IsValueType)
                        {
                            EmitCallbackIfNeeded(ctx, loc, TypeModel.CallbackType.BeforeDeserialize);
                        }
                        else
                        { // could be null
                            Compiler.CodeLabel callbacksDone = ctx.DefineLabel();
                            ctx.LoadValue(loc);
                            ctx.BranchIfFalse(callbacksDone, false);
                            EmitCallbackIfNeeded(ctx, loc, TypeModel.CallbackType.BeforeDeserialize);
                            ctx.MarkLabel(callbacksDone);
                        }
                    }

                    Compiler.CodeLabel @continue = ctx.DefineLabel(), processField = ctx.DefineLabel();
                    ctx.Branch(@continue, false);

                    ctx.MarkLabel(processField);
                    foreach (BasicList.Group group in BasicList.GetContiguousGroups(fieldNumbers, serializers))
                    {
                        Compiler.CodeLabel tryNextField = ctx.DefineLabel();
                        int groupItemCount = group.Items.Count;
                        if (groupItemCount == 1)
                        {
                            // discreet group; use an equality test
                            ctx.LoadValue(fieldNumber);
                            ctx.LoadValue(group.First);
                            Compiler.CodeLabel processThisField = ctx.DefineLabel();
                            ctx.BranchIfEqual(processThisField, true);
                            ctx.Branch(tryNextField, false);
                            WriteFieldHandler(ctx, expected, loc, processThisField, @continue, (IProtoSerializer)group.Items[0]);
                        }
                        else
                        { // implement as a jump-table-based switch
                            ctx.LoadValue(fieldNumber);
                            ctx.LoadValue(group.First);
                            ctx.Subtract(); // jump-tables are zero-based
                            Compiler.CodeLabel[] jmp = new Compiler.CodeLabel[groupItemCount];
                            for (int i = 0; i < groupItemCount; i++)
                            {
                                jmp[i] = ctx.DefineLabel();
                            }
                            ctx.Switch(jmp);
                            // write the default...
                            ctx.Branch(tryNextField, false);
                            for (int i = 0; i < groupItemCount; i++)
                            {
                                WriteFieldHandler(ctx, expected, loc, jmp[i], @continue, (IProtoSerializer)group.Items[i]);
                            }
                        }
                        ctx.MarkLabel(tryNextField);
                    }

                    EmitCreateIfNull(ctx, loc);
                    ctx.LoadReaderWriter();
                    if (isExtensible)
                    {
                        ctx.LoadValue(loc);
                        ctx.EmitCall(ctx.MapType(typeof(ProtoReader)).GetMethod("AppendExtensionData"));
                    }
                    else
                    {
                        ctx.EmitCall(ctx.MapType(typeof(ProtoReader)).GetMethod("SkipField"));
                    }

                    ctx.MarkLabel(@continue);
                    ctx.EmitBasicRead("ReadFieldHeader", ctx.MapType(typeof(int)));
                    ctx.CopyValue();
                    ctx.StoreValue(fieldNumber);
                    ctx.LoadValue(0);
                    ctx.BranchIfGreater(processField, false);

                    EmitCreateIfNull(ctx, loc);
                    // post-callbacks
                    EmitCallbackIfNeeded(ctx, loc, TypeModel.CallbackType.AfterDeserialize);

                    if (valueFrom != null && !loc.IsSame(valueFrom))
                    {
                        ctx.LoadValue(loc);
                        ctx.Cast(valueFrom.Type);
                        ctx.StoreValue(valueFrom);
                    }
                }
        }
Exemplo n.º 19
0
        protected override void EmitRead(Compiler.CompilerContext ctx, Compiler.Local valueFrom)
        {

            bool writeValue;
            SanityCheck(ctx.Model, property, Tail, out writeValue, ctx.NonPublic, ctx.AllowInternal(property));
            if (ExpectedType.IsValueType && valueFrom == null)
            {
                throw new InvalidOperationException("Attempt to mutate struct on the head of the stack; changes would be lost");
            }

            ctx.LoadAddress(valueFrom, ExpectedType); // stack is: old-addr
            if (writeValue && Tail.RequiresOldValue)
            { // need to read and write
                ctx.CopyValue();
            }
            // stack is: [old-addr]|old-addr
            if (Tail.RequiresOldValue)
            {
                ctx.LoadValue(property); // stack is: [old-addr]|old-value
            }
            Type propertyType = property.PropertyType;
            ctx.ReadNullCheckedTail(propertyType, Tail, null); // stack is [old-addr]|[new-value]
            
            if (writeValue)
            {
                // stack is old-addr|new-value
                Compiler.CodeLabel @skip = new Compiler.CodeLabel(), allDone = new Compiler.CodeLabel(); // <=== default structs
                if (!propertyType.IsValueType)
                { // if the tail returns a null, intepret that as *no assign*
                    ctx.CopyValue(); // old-addr|new-value|new-value
                    @skip = ctx.DefineLabel();
                    allDone = ctx.DefineLabel();
                    ctx.BranchIfFalse(@skip, true); // old-addr|new-value
                }
                
                if (shadowSetter == null)
                {
                    ctx.StoreValue(property);
                }
                else
                {
                    ctx.EmitCall(shadowSetter);
                }
                if (!propertyType.IsValueType)
                {
                    ctx.Branch(allDone, true);

                    ctx.MarkLabel(@skip); // old-addr|new-value
                    ctx.DiscardValue();
                    ctx.DiscardValue();

                    ctx.MarkLabel(allDone);
                }

            }
            else
            { // don't want return value; drop it if anything there
                // stack is [new-value]
                if (Tail.ReturnsValue) { ctx.DiscardValue(); }
            }
        }
Exemplo n.º 20
0
        protected override void EmitRead(ProtoBuf.Compiler.CompilerContext ctx, ProtoBuf.Compiler.Local valueFrom)
        {
            /* This looks more complex than it is. Look at the non-compiled Read to
             * see what it is trying to do, but note that it needs to cope with a
             * few more scenarios. Note that it picks the **most specific** Add,
             * unlike the runtime version that uses IList when possible. The core
             * is just a "do {list.Add(readValue())} while {thereIsMore}"
             *
             * The complexity is due to:
             *  - value types vs reference types (boxing etc)
             *  - initialization if we need to pass in a value to the tail
             *  - handling whether or not the tail *returns* the value vs updates the input
             */
            bool returnList = ReturnList;

            using (Compiler.Local list = AppendToCollection ? ctx.GetLocalWithValue(ExpectedType, valueFrom) : new Compiler.Local(ctx, declaredType))
                using (Compiler.Local origlist = (returnList && AppendToCollection) ? new Compiler.Local(ctx, ExpectedType) : null)
                {
                    if (!AppendToCollection)
                    { // always new
                        ctx.LoadNullRef();
                        ctx.StoreValue(list);
                    }
                    else if (returnList)
                    { // need a copy
                        ctx.LoadValue(list);
                        ctx.StoreValue(origlist);
                    }
                    if (concreteType != null)
                    {
                        ctx.LoadValue(list);
                        Compiler.CodeLabel notNull = ctx.DefineLabel();
                        ctx.BranchIfTrue(notNull, true);
                        ctx.EmitCtor(concreteType);
                        ctx.StoreValue(list);
                        ctx.MarkLabel(notNull);
                    }

                    bool castListForAdd = !add.DeclaringType.IsAssignableFrom(declaredType);
                    EmitReadList(ctx, list, Tail, add, packedWireType, castListForAdd);

                    if (returnList)
                    {
                        if (AppendToCollection)
                        {
                            // remember ^^^^ we had a spare copy of the list on the stack; now we'll compare
                            ctx.LoadValue(origlist);
                            ctx.LoadValue(list); // [orig] [new-value]
                            Compiler.CodeLabel sameList = ctx.DefineLabel(), allDone = ctx.DefineLabel();
                            ctx.BranchIfEqual(sameList, true);
                            ctx.LoadValue(list);
                            ctx.Branch(allDone, true);
                            ctx.MarkLabel(sameList);
                            ctx.LoadNullRef();
                            ctx.MarkLabel(allDone);
                        }
                        else
                        {
                            ctx.LoadValue(list);
                        }
                    }
                }
        }
Exemplo n.º 21
0
        protected override void EmitRead(Compiler.CompilerContext ctx, Compiler.Local valueFrom)
        {
            bool writeValue;

            SanityCheck(ctx.Model, property, Tail, out writeValue, ctx.NonPublic, ctx.AllowInternal(property));
            if (ExpectedType.IsValueType && valueFrom == null)
            {
                throw new InvalidOperationException("Attempt to mutate struct on the head of the stack; changes would be lost");
            }

            ctx.LoadAddress(valueFrom, ExpectedType); // stack is: old-addr
            if (writeValue && Tail.RequiresOldValue)
            {                                         // need to read and write
                ctx.CopyValue();
            }
            // stack is: [old-addr]|old-addr
            if (Tail.RequiresOldValue)
            {
                ctx.LoadValue(property); // stack is: [old-addr]|old-value
            }
            Type propertyType = property.PropertyType;

            ctx.ReadNullCheckedTail(propertyType, Tail, null); // stack is [old-addr]|[new-value]

            if (writeValue)
            {
                // stack is old-addr|new-value
                Compiler.CodeLabel @skip = new Compiler.CodeLabel(), allDone = new Compiler.CodeLabel(); // <=== default structs
                if (!propertyType.IsValueType)
                {                                                                                        // if the tail returns a null, intepret that as *no assign*
                    ctx.CopyValue();                                                                     // old-addr|new-value|new-value
                    @skip   = ctx.DefineLabel();
                    allDone = ctx.DefineLabel();
                    ctx.BranchIfFalse(@skip, true); // old-addr|new-value
                }

                if (shadowSetter == null)
                {
                    ctx.StoreValue(property);
                }
                else
                {
                    ctx.EmitCall(shadowSetter);
                }
                if (!propertyType.IsValueType)
                {
                    ctx.Branch(allDone, true);

                    ctx.MarkLabel(@skip); // old-addr|new-value
                    ctx.DiscardValue();
                    ctx.DiscardValue();

                    ctx.MarkLabel(allDone);
                }
            }
            else
            { // don't want return value; drop it if anything there
                // stack is [new-value]
                if (Tail.ReturnsValue)
                {
                    ctx.DiscardValue();
                }
            }
        }
Exemplo n.º 22
0
        private Compiler.CompilerContext WriteSerializeDeserialize(string assemblyName, TypeBuilder type, SerializerPair[] methodPairs, Compiler.CompilerContext.ILVersion ilVersion, ref ILGenerator il)
        {
            il = Override(type, "Serialize");
            Compiler.CompilerContext ctx = new Compiler.CompilerContext(il, false, true, methodPairs, this, ilVersion, assemblyName, MapType(typeof(object)));
            // arg0 = this, arg1 = key, arg2=obj, arg3=dest
            Compiler.CodeLabel[] jumpTable = new Compiler.CodeLabel[types.Count];
            for (int i = 0; i < jumpTable.Length; i++)
            {
                jumpTable[i] = ctx.DefineLabel();
            }
            il.Emit(OpCodes.Ldarg_1);
            ctx.Switch(jumpTable);
            ctx.Return();
            for (int i = 0; i < jumpTable.Length; i++)
            {
                SerializerPair pair = methodPairs[i];
                ctx.MarkLabel(jumpTable[i]);
                il.Emit(OpCodes.Ldarg_2);
                ctx.CastFromObject(pair.Type.Type);
                il.Emit(OpCodes.Ldarg_3);
                il.EmitCall(OpCodes.Call, pair.Serialize, null);
                ctx.Return();
            }

            il = Override(type, "Deserialize");
            ctx = new Compiler.CompilerContext(il, false, false, methodPairs, this, ilVersion, assemblyName, MapType(typeof(object)));
            // arg0 = this, arg1 = key, arg2=obj, arg3=source
            for (int i = 0; i < jumpTable.Length; i++)
            {
                jumpTable[i] = ctx.DefineLabel();
            }
            il.Emit(OpCodes.Ldarg_1);
            ctx.Switch(jumpTable);
            ctx.LoadNullRef();
            ctx.Return();
            for (int i = 0; i < jumpTable.Length; i++)
            {
                SerializerPair pair = methodPairs[i];
                ctx.MarkLabel(jumpTable[i]);
                Type keyType = pair.Type.Type;
                if (keyType.IsValueType)
                {
                    il.Emit(OpCodes.Ldarg_2);
                    il.Emit(OpCodes.Ldarg_3);
                    il.EmitCall(OpCodes.Call, EmitBoxedSerializer(type, i, keyType, methodPairs, this, ilVersion, assemblyName), null);
                    ctx.Return();
                }
                else
                {
                    il.Emit(OpCodes.Ldarg_2);
                    ctx.CastFromObject(keyType);
                    il.Emit(OpCodes.Ldarg_3);
                    il.EmitCall(OpCodes.Call, pair.Deserialize, null);
                    ctx.Return();
                }
            }
            return ctx;
        }
        public void EmitRead(Compiler.CompilerContext ctx, Compiler.Local incoming)
        {
			bool issueReferenceDirectives = !baseTupleAsReference && asReference;
        	
			Compiler.CodeLabel @end = ctx.DefineLabel();

			using (Compiler.Local tupleKey = new Compiler.Local(ctx, typeof(int)))
			using (Compiler.Local oldTuple = new Compiler.Local(ctx, typeof(object)))
			using (Compiler.Local objValue = ctx.GetLocalWithValue(ExpectedType, incoming))
			{
				Compiler.Local[] locals = new Compiler.Local[members.Length];
				try
				{
					if (issueReferenceDirectives)
					{
						//int tupleKey = 0;
						ctx.LoadValue(0);
						ctx.StoreValue(tupleKey);

						//object oldTuple = null;
						ctx.LoadNullRef();
						ctx.StoreValue(oldTuple);

						//tupleKey = (int)source.ReadUInt32();
						ctx.LoadReaderWriter();
						ctx.EmitCall(typeof (ProtoReader).GetMethod("ReadUInt32"));
						//ctx.CastToObject(typeof (int));
						ctx.StoreValue(tupleKey);

						Compiler.CodeLabel @objectNotFound = ctx.DefineLabel();

						ctx.LoadValue(tupleKey);
						ctx.LoadValue(0);
						ctx.BranchIfEqual(@objectNotFound, true);

						//// return source.NetCache.GetKeyedObject(tupleKey);
						ctx.LoadReaderWriter();
						ctx.LoadValue(typeof (ProtoReader).GetProperty("NetCache"));
						ctx.LoadValue(tupleKey);
						ctx.EmitCall(typeof (NetObjectCache).GetMethod("GetKeyedObject"));
						ctx.CastFromObject(ExpectedType);
						ctx.StoreValue(objValue);
						ctx.Branch(@end, false);

						ctx.MarkLabel(@objectNotFound);

						ctx.EmitCtor(typeof (object));
						ctx.StoreValue(oldTuple);

						// tupleKey = source.NetCache.AddObjectKey(oldTuple, out dummy);
						using (Compiler.Local dummy = new Compiler.Local(ctx, typeof (bool)))
						{
							ctx.LoadReaderWriter();
							ctx.LoadValue(typeof (ProtoReader).GetProperty("NetCache"));
							ctx.LoadValue(oldTuple);
							ctx.LoadAddress(dummy, typeof (bool));
							ctx.EmitCall(typeof (NetObjectCache).GetMethod("AddObjectKey", new Type[] { typeof(object), typeof(bool).MakeByRefType() }));
							ctx.StoreValue(tupleKey);
						}
					}

					for (int i = 0; i < locals.Length; i++)
					{
						Type type = GetMemberType(i);
						bool store = true;
						locals[i] = new Compiler.Local(ctx, type);
						if (!ExpectedType.IsValueType)
						{
							// value-types always read the old value
							if (type.IsValueType)
							{
								switch (Helpers.GetTypeCode(type))
								{
									case ProtoTypeCode.Boolean:
									case ProtoTypeCode.Byte:
									case ProtoTypeCode.Int16:
									case ProtoTypeCode.Int32:
									case ProtoTypeCode.SByte:
									case ProtoTypeCode.UInt16:
									case ProtoTypeCode.UInt32:
										ctx.LoadValue(0);
										break;
									case ProtoTypeCode.Int64:
									case ProtoTypeCode.UInt64:
										ctx.LoadValue(0L);
										break;
									case ProtoTypeCode.Single:
										ctx.LoadValue(0.0F);
										break;
									case ProtoTypeCode.Double:
										ctx.LoadValue(0.0D);
										break;
									case ProtoTypeCode.Decimal:
										ctx.LoadValue(0M);
										break;
									case ProtoTypeCode.Guid:
										ctx.LoadValue(Guid.Empty);
										break;
									default:
										ctx.LoadAddress(locals[i], type);
										ctx.EmitCtor(type);
										store = false;
										break;
								}
							}
							else
							{
								ctx.LoadNullRef();
							}
							if (store)
							{
								ctx.StoreValue(locals[i]);
							}
						}
					}

					Compiler.CodeLabel skipOld = ExpectedType.IsValueType
					                             	? new Compiler.CodeLabel()
					                             	: ctx.DefineLabel();
					if (!ExpectedType.IsValueType)
					{
						ctx.LoadAddress(objValue, ExpectedType);
						ctx.BranchIfFalse(skipOld, false);
					}

					for (int i = 0; i < members.Length; i++)
					{
						ctx.LoadAddress(objValue, ExpectedType);
						switch (members[i].MemberType)
						{
							case MemberTypes.Field:
								ctx.LoadValue((FieldInfo) members[i]);
								break;
							case MemberTypes.Property:
								ctx.LoadValue((PropertyInfo) members[i]);
								break;
						}
						ctx.StoreValue(locals[i]);
					}

					if (!ExpectedType.IsValueType) ctx.MarkLabel(skipOld);

					using (Compiler.Local fieldNumber = new Compiler.Local(ctx, typeof (int)))
					using (Compiler.Local j = new Compiler.Local(ctx, typeof (int)))
					{
						// j = 0
						ctx.LoadValue(0);
						ctx.StoreValue(j);

						Compiler.CodeLabel @continue = ctx.DefineLabel(),
						                   processField = ctx.DefineLabel(),
						                   notRecognised = ctx.DefineLabel(),
						                   @endWhileLoop = ctx.DefineLabel();

						ctx.Branch(@continue, false);

						Compiler.CodeLabel[] handlers = new Compiler.CodeLabel[members.Length];

						for (int i = 0; i < members.Length; i++)
						{
							handlers[i] = ctx.DefineLabel();
						}

						ctx.MarkLabel(processField);

						ctx.LoadValue(fieldNumber);
						ctx.LoadValue(1);
						ctx.Subtract(); // jump-table is zero-based
						ctx.Switch(handlers);

						// and the default:
						ctx.Branch(notRecognised, false);

						for (int i = 0; i < handlers.Length; i++)
						{
							ctx.MarkLabel(handlers[i]);
							IProtoSerializer tail = tails[i];
							Compiler.Local oldValIfNeeded = tail.RequiresOldValue ? locals[i] : null;
							ctx.ReadNullCheckedTail(locals[i].Type, tail, oldValIfNeeded);

							if (tail.ReturnsValue)
							{
								if (locals[i].Type.IsValueType)
								{
									ctx.StoreValue(locals[i]);
								}
								else
								{
									Compiler.CodeLabel hasValue = ctx.DefineLabel(), allDone = ctx.DefineLabel();

									ctx.CopyValue();
									ctx.BranchIfTrue(hasValue, true); // interpret null as "don't assign"
									ctx.DiscardValue();
									ctx.Branch(allDone, true);
									ctx.MarkLabel(hasValue);
									ctx.StoreValue(locals[i]);
									ctx.MarkLabel(allDone);
								}
							}

							ctx.Branch(@continue, false);
						}

						ctx.MarkLabel(notRecognised);
						ctx.LoadReaderWriter();
						ctx.EmitCall(typeof (ProtoReader).GetMethod("SkipField"));

						ctx.MarkLabel(@continue);

						// j < values.Length
						ctx.LoadValue(j);
						ctx.LoadValue(members.Length);
						ctx.BranchIfGreaterOrEqual(@endWhileLoop, false);

						//j++
						ctx.LoadValue(j);
						ctx.LoadValue(1);
						ctx.Add();
						ctx.StoreValue(j);

						// source.ReadNextFieldHack() > 0
						ctx.LoadReaderWriter();
						ctx.EmitCall(typeof (ProtoReader).GetMethod("ReadNextFieldHack"));
						ctx.LoadValue(0);
						ctx.BranchIfLessOrEqual(@endWhileLoop, true);

						// field = source.ReadFieldHeader();
						ctx.LoadReaderWriter();
						ctx.EmitCall(typeof (ProtoReader).GetMethod("ReadFieldHeader"));
						ctx.StoreValue(fieldNumber);
						ctx.Branch(processField, false);

						ctx.MarkLabel(@endWhileLoop);
					}

					for (int i = 0; i < locals.Length; i++)
					{
						ctx.LoadValue(locals[i]);
					}

					ctx.EmitCtor(ctor);
					ctx.StoreValue(objValue);

					if (issueReferenceDirectives)
					{
						//source.NetCache.UpdateKeyedObject(tupleKey, oldTuple, result);
						ctx.LoadReaderWriter();
						ctx.LoadValue(typeof (ProtoReader).GetProperty("NetCache"));
						ctx.LoadValue(tupleKey);
						ctx.LoadValue(oldTuple);
						ctx.LoadValue(objValue);
						ctx.CastToObject(ExpectedType);
						ctx.EmitCall(typeof (NetObjectCache).GetMethod("UpdateKeyedObject"));
					}

					if (forceIssueFakeHeader)
					{
						//source.ReadEndGroupFieldHeaderHack();
						ctx.LoadReaderWriter();
						ctx.EmitCall(typeof (ProtoReader).GetMethod("ReadEndGroupFieldHeaderHack"));
					}

					ctx.MarkLabel(@end);
					ctx.LoadValue(objValue);
				}
				finally
				{
					for (int i = 0; i < locals.Length; i++)
					{
						if (locals[i] != null)
							locals[i].Dispose(); // release for re-use
					}
				}
			}
        }
Exemplo n.º 24
0
        protected override void EmitRead(Compiler.CompilerContext ctx, Compiler.Local valueFrom)
        {
            using (Compiler.Local oldValue = ctx.GetLocalWithValue(expectedType, valueFrom))
                using (Compiler.Local token = new Compiler.Local(ctx, ctx.MapType(typeof(SubItemToken))))
                    using (Compiler.Local field = new Compiler.Local(ctx, ctx.MapType(typeof(int))))
                    {
                        ctx.LoadReaderWriter();
                        ctx.EmitCall(ctx.MapType(typeof(ProtoReader)).GetMethod("StartSubItem"));
                        ctx.StoreValue(token);

                        Compiler.CodeLabel next = ctx.DefineLabel(), processField = ctx.DefineLabel(), end = ctx.DefineLabel();

                        ctx.MarkLabel(next);

                        ctx.EmitBasicRead("ReadFieldHeader", ctx.MapType(typeof(int)));
                        ctx.CopyValue();
                        ctx.StoreValue(field);
                        ctx.LoadValue(Tag); // = 1 - process
                        ctx.BranchIfEqual(processField, true);
                        ctx.LoadValue(field);
                        ctx.LoadValue(1); // < 1 - exit
                        ctx.BranchIfLess(end, false);

                        // default: skip
                        ctx.LoadReaderWriter();
                        ctx.EmitCall(ctx.MapType(typeof(ProtoReader)).GetMethod("SkipField"));
                        ctx.Branch(next, true);

                        // process
                        ctx.MarkLabel(processField);
                        if (Tail.RequiresOldValue)
                        {
                            if (expectedType.IsValueType)
                            {
                                ctx.LoadAddress(oldValue, expectedType);
                                ctx.EmitCall(expectedType.GetMethod("GetValueOrDefault", Helpers.EmptyTypes));
                            }
                            else
                            {
                                ctx.LoadValue(oldValue);
                            }
                        }
                        Tail.EmitRead(ctx, null);
                        // note we demanded always returns a value
                        if (expectedType.IsValueType)
                        {
                            ctx.EmitCtor(expectedType, Tail.ExpectedType); // re-nullable<T> it
                        }
                        ctx.StoreValue(oldValue);
                        ctx.Branch(next, false);

                        // outro
                        ctx.MarkLabel(end);

                        ctx.LoadValue(token);
                        ctx.LoadReaderWriter();
                        ctx.EmitCall(ctx.MapType(typeof(ProtoReader)).GetMethod("EndSubItem"));
                        ctx.LoadValue(oldValue); // load the old value
                    }
        }
Exemplo n.º 25
0
        protected override void EmitRead(Compiler.CompilerContext ctx, Compiler.Local valueFrom)
        {
            SanityCheck(property, Tail, out bool writeValue, ctx.NonPublic, ctx.AllowInternal(property));
            if (ExpectedType.IsValueType && valueFrom is null)
            {
                throw new InvalidOperationException("Attempt to mutate struct on the head of the stack; changes would be lost");
            }

            using Compiler.Local loc = ctx.GetLocalWithValue(ExpectedType, valueFrom);
            if (Tail.RequiresOldValue)
            {
                ctx.LoadAddress(loc, ExpectedType); // stack is: old-addr
                ctx.LoadValue(property);            // stack is: old-value
            }
            Type propertyType = property.PropertyType;

            ctx.ReadNullCheckedTail(propertyType, Tail, null); // stack is [new-value]

            if (writeValue)
            {
                var localType = ChooseReadLocalType(property.PropertyType, Tail.ExpectedType);
                using Compiler.Local newVal = new Compiler.Local(ctx, localType);
                ctx.StoreValue(newVal);                                // stack is empty

                Compiler.CodeLabel allDone = new Compiler.CodeLabel(); // <=== default structs

                if (!localType.IsValueType)
                {                                      // if the tail returns a null, intepret that as *no assign*
                    allDone = ctx.DefineLabel();
                    ctx.LoadValue(newVal);             // stack is: new-value
                    ctx.BranchIfFalse(@allDone, true); // stack is empty
                }

                // assign the value
                ctx.LoadAddress(loc, ExpectedType); // parent-addr
                ctx.LoadValue(newVal);              // parent-obj|new-value

                // cast if needed (this is mostly for ReadMap/ReadRepeated)
                if (!property.PropertyType.IsValueType && !localType.IsValueType &&
                    !property.PropertyType.IsAssignableFrom(localType))
                {
                    ctx.Cast(property.PropertyType);
                }

                if (shadowSetter is null)
                {
                    ctx.StoreValue(property); // empty
                }
                else
                {
                    ctx.EmitCall(shadowSetter); // empty
                }
                if (!propertyType.IsValueType)
                {
                    ctx.MarkLabel(allDone);
                }
            }
            else
            { // don't want return value; drop it if anything there
              // stack is [new-value]
                if (Tail.ReturnsValue)
                {
                    ctx.DiscardValue();
                }
            }
        }
Exemplo n.º 26
0
        protected override void EmitWrite(CompilerContext ctx, Local valueFrom)
        {
            Type       itemType = typeof(KeyValuePair <TKey, TValue>);
            MethodInfo moveNext, current, getEnumerator = ListDecorator.GetEnumeratorInfo(
                ExpectedType, itemType, out moveNext, out current);
            Type enumeratorType = getEnumerator.ReturnType;

            MethodInfo key    = itemType.GetProperty(nameof(KeyValuePair <TKey, TValue> .Key)).GetGetMethod(),
                       @value = itemType.GetProperty(nameof(KeyValuePair <TKey, TValue> .Value)).GetGetMethod();

            using (Compiler.Local list = ctx.GetLocalWithValue(ExpectedType, valueFrom))
                using (Compiler.Local iter = new Compiler.Local(ctx, enumeratorType))
                    using (Compiler.Local token = new Compiler.Local(ctx, typeof(SubItemToken)))
                        using (Compiler.Local kvp = new Compiler.Local(ctx, itemType))
                        {
                            ctx.LoadAddress(list, ExpectedType);
                            ctx.EmitCall(getEnumerator, ExpectedType);
                            ctx.StoreValue(iter);
                            using (ctx.Using(iter))
                            {
                                Compiler.CodeLabel body = ctx.DefineLabel(), next = ctx.DefineLabel();
                                ctx.Branch(next, false);

                                ctx.MarkLabel(body);

                                ctx.LoadAddress(iter, enumeratorType);
                                ctx.EmitCall(current, enumeratorType);

                                if (itemType != typeof(object) && current.ReturnType == typeof(object))
                                {
                                    ctx.CastFromObject(itemType);
                                }
                                ctx.StoreValue(kvp);

                                ctx.LoadValue(fieldNumber);
                                ctx.LoadValue((int)wireType);
                                ctx.LoadWriter(true);
                                ctx.EmitCall(ProtoWriter.GetStaticMethod("WriteFieldHeader"));

                                ctx.LoadNullRef();
                                ctx.LoadWriter(true);
                                ctx.EmitCall(ProtoWriter.GetStaticMethod("StartSubItem"));
                                ctx.StoreValue(token);

                                ctx.LoadAddress(kvp, itemType);
                                ctx.EmitCall(key, itemType);
                                ctx.WriteNullCheckedTail(typeof(TKey), keyTail, null);

                                ctx.LoadAddress(kvp, itemType);
                                ctx.EmitCall(value, itemType);
                                ctx.WriteNullCheckedTail(typeof(TValue), Tail, null);

                                ctx.LoadValue(token);
                                ctx.LoadWriter(true);
                                ctx.EmitCall(ProtoWriter.GetStaticMethod("EndSubItem"));

                                ctx.MarkLabel(@next);
                                ctx.LoadAddress(iter, enumeratorType);
                                ctx.EmitCall(moveNext, enumeratorType);
                                ctx.BranchIfTrue(body, false);
                            }
                        }
        }
Exemplo n.º 27
0
        private void EmitBranchIfDefaultValue(Compiler.CompilerContext ctx, Compiler.CodeLabel label)
        {
            Type expected = ExpectedType;

            switch (Helpers.GetTypeCode(expected))
            {
            case ProtoTypeCode.Boolean:
                if ((bool)defaultValue)
                {
                    ctx.BranchIfTrue(label, false);
                }
                else
                {
                    ctx.BranchIfFalse(label, false);
                }
                break;

            case ProtoTypeCode.Byte:
                if ((byte)defaultValue == (byte)0)
                {
                    ctx.BranchIfFalse(label, false);
                }
                else
                {
                    ctx.LoadValue((int)(byte)defaultValue);
                    EmitBeq(ctx, label, expected);
                }
                break;

            case ProtoTypeCode.SByte:
                if ((sbyte)defaultValue == (sbyte)0)
                {
                    ctx.BranchIfFalse(label, false);
                }
                else
                {
                    ctx.LoadValue((int)(sbyte)defaultValue);
                    EmitBeq(ctx, label, expected);
                }
                break;

            case ProtoTypeCode.Int16:
                if ((short)defaultValue == (short)0)
                {
                    ctx.BranchIfFalse(label, false);
                }
                else
                {
                    ctx.LoadValue((int)(short)defaultValue);
                    EmitBeq(ctx, label, expected);
                }
                break;

            case ProtoTypeCode.UInt16:
                if ((ushort)defaultValue == (ushort)0)
                {
                    ctx.BranchIfFalse(label, false);
                }
                else
                {
                    ctx.LoadValue((int)(ushort)defaultValue);
                    EmitBeq(ctx, label, expected);
                }
                break;

            case ProtoTypeCode.Int32:
                if ((int)defaultValue == (int)0)
                {
                    ctx.BranchIfFalse(label, false);
                }
                else
                {
                    ctx.LoadValue((int)defaultValue);
                    EmitBeq(ctx, label, expected);
                }
                break;

            case ProtoTypeCode.UInt32:
                if ((uint)defaultValue == (uint)0)
                {
                    ctx.BranchIfFalse(label, false);
                }
                else
                {
                    ctx.LoadValue((int)(uint)defaultValue);
                    EmitBeq(ctx, label, expected);
                }
                break;

            case ProtoTypeCode.Char:
                if ((char)defaultValue == (char)0)
                {
                    ctx.BranchIfFalse(label, false);
                }
                else
                {
                    ctx.LoadValue((int)(char)defaultValue);
                    EmitBeq(ctx, label, expected);
                }
                break;

            case ProtoTypeCode.Int64:
                ctx.LoadValue((long)defaultValue);
                EmitBeq(ctx, label, expected);
                break;

            case ProtoTypeCode.UInt64:
                ctx.LoadValue((long)(ulong)defaultValue);
                EmitBeq(ctx, label, expected);
                break;

            case ProtoTypeCode.Double:
                ctx.LoadValue((double)defaultValue);
                EmitBeq(ctx, label, expected);
                break;

            case ProtoTypeCode.Single:
                ctx.LoadValue((float)defaultValue);
                EmitBeq(ctx, label, expected);
                break;

            case ProtoTypeCode.String:
                ctx.LoadValue((string)defaultValue);
                EmitBeq(ctx, label, expected);
                break;

            case ProtoTypeCode.Decimal:
            {
                decimal d = (decimal)defaultValue;
                ctx.LoadValue(d);
                EmitBeq(ctx, label, expected);
            }
            break;

            case ProtoTypeCode.TimeSpan:
            {
                TimeSpan ts = (TimeSpan)defaultValue;
                if (ts == TimeSpan.Zero)
                {
                    ctx.LoadValue(typeof(TimeSpan).GetField("Zero"));
                }
                else
                {
                    ctx.LoadValue(ts.Ticks);
                    ctx.EmitCall(ctx.MapType(typeof(TimeSpan)).GetMethod("FromTicks"));
                }
                EmitBeq(ctx, label, expected);
                break;
            }

            case ProtoTypeCode.Guid:
            {
                ctx.LoadValue((Guid)defaultValue);
                EmitBeq(ctx, label, expected);
                break;
            }

            case ProtoTypeCode.DateTime:
            {
#if FX11
                ctx.LoadValue(((DateTime)defaultValue).ToFileTime());
                ctx.EmitCall(typeof(DateTime).GetMethod("FromFileTime"));
#else
                ctx.LoadValue(((DateTime)defaultValue).ToBinary());
                ctx.EmitCall(ctx.MapType(typeof(DateTime)).GetMethod("FromBinary"));
#endif

                EmitBeq(ctx, label, expected);
                break;
            }

            default:
                throw new NotSupportedException("Type cannot be represented as a default value: " + expected.FullName);
            }
        }
Exemplo n.º 28
0
        protected override void EmitRead(Compiler.CompilerContext ctx, Compiler.Local valueFrom)
        {
            using (Compiler.Local oldList = AppendToCollection ? ctx.GetLocalWithValue(ExpectedType, valueFrom) : null)
                using (Compiler.Local builder = new Compiler.Local(ctx, builderFactory.ReturnType))
                {
                    ctx.EmitCall(builderFactory);
                    ctx.StoreValue(builder);

                    if (AppendToCollection)
                    {
                        Compiler.CodeLabel done = ctx.DefineLabel();
                        if (!Helpers.IsValueType(ExpectedType))
                        {
                            ctx.LoadValue(oldList);
                            ctx.BranchIfFalse(done, false); // old value null; nothing to add
                        }

                        ctx.LoadAddress(oldList, oldList.Type);
                        if (isEmpty != null)
                        {
                            ctx.EmitCall(Helpers.GetGetMethod(isEmpty, false, false));
                            ctx.BranchIfTrue(done, false); // old list is empty; nothing to add
                        }
                        else
                        {
                            ctx.EmitCall(Helpers.GetGetMethod(length, false, false));
                            ctx.BranchIfFalse(done, false); // old list is empty; nothing to add
                        }

                        Type voidType = typeof(void);
                        if (addRange != null)
                        {
                            ctx.LoadValue(builder);
                            ctx.LoadValue(oldList);
                            ctx.EmitCall(addRange);
                            if (addRange.ReturnType != null && add.ReturnType != voidType)
                            {
                                ctx.DiscardValue();
                            }
                        }
                        else
                        {
                            // loop and call Add repeatedly
                            MethodInfo moveNext, current, getEnumerator = GetEnumeratorInfo(out moveNext, out current);
                            Helpers.DebugAssert(moveNext != null);
                            Helpers.DebugAssert(current != null);
                            Helpers.DebugAssert(getEnumerator != null);

                            Type enumeratorType = getEnumerator.ReturnType;
                            using (Compiler.Local iter = new Compiler.Local(ctx, enumeratorType))
                            {
                                ctx.LoadAddress(oldList, ExpectedType);
                                ctx.EmitCall(getEnumerator);
                                ctx.StoreValue(iter);
                                using (ctx.Using(iter))
                                {
                                    Compiler.CodeLabel body = ctx.DefineLabel(), next = ctx.DefineLabel();
                                    ctx.Branch(next, false);

                                    ctx.MarkLabel(body);
                                    ctx.LoadAddress(builder, builder.Type);
                                    ctx.LoadAddress(iter, enumeratorType);
                                    ctx.EmitCall(current);
                                    ctx.EmitCall(add);
                                    if (add.ReturnType != null && add.ReturnType != voidType)
                                    {
                                        ctx.DiscardValue();
                                    }

                                    ctx.MarkLabel(@next);
                                    ctx.LoadAddress(iter, enumeratorType);
                                    ctx.EmitCall(moveNext);
                                    ctx.BranchIfTrue(body, false);
                                }
                            }
                        }

                        ctx.MarkLabel(done);
                    }

                    EmitReadList(ctx, builder, Tail, add, packedWireType, false);

                    ctx.LoadAddress(builder, builder.Type);
                    ctx.EmitCall(finish);
                    if (ExpectedType != finish.ReturnType)
                    {
                        ctx.Cast(ExpectedType);
                    }
                }
        }
Exemplo n.º 29
0
        void IProtoSerializer.EmitRead(Compiler.CompilerContext ctx, Compiler.Local valueFrom)
        {
            ProtoTypeCode typeCode = GetTypeCode();

            if (map == null)
            {
                ctx.EmitBasicRead("ReadInt32", ctx.MapType(typeof(int)));
                ctx.ConvertFromInt32(typeCode, false);
            }
            else
            {
                int[]    wireValues = new int[map.Length];
                object[] values     = new object[map.Length];
                for (int i = 0; i < map.Length; i++)
                {
                    wireValues[i] = map[i].WireValue;
                    values[i]     = map[i].RawValue;
                }
                using (Compiler.Local result = new Compiler.Local(ctx, ExpectedType))
                    using (Compiler.Local wireValue = new Compiler.Local(ctx, ctx.MapType(typeof(int))))
                    {
                        ctx.EmitBasicRead("ReadInt32", ctx.MapType(typeof(int)));
                        ctx.StoreValue(wireValue);
                        Compiler.CodeLabel @continue = ctx.DefineLabel();
                        foreach (BasicList.Group group in BasicList.GetContiguousGroups(wireValues, values))
                        {
                            Compiler.CodeLabel tryNextGroup = ctx.DefineLabel();
                            int groupItemCount = group.Items.Count;
                            if (groupItemCount == 1)
                            {
                                // discreet group; use an equality test
                                ctx.LoadValue(wireValue);
                                ctx.LoadValue(group.First);
                                Compiler.CodeLabel processThisValue = ctx.DefineLabel();
                                ctx.BranchIfEqual(processThisValue, true);
                                ctx.Branch(tryNextGroup, false);
                                WriteEnumValue(ctx, typeCode, processThisValue, @continue, group.Items[0], @result);
                            }
                            else
                            {
                                // implement as a jump-table-based switch
                                ctx.LoadValue(wireValue);
                                ctx.LoadValue(group.First);
                                ctx.Subtract(); // jump-tables are zero-based
                                Compiler.CodeLabel[] jmp = new Compiler.CodeLabel[groupItemCount];
                                for (int i = 0; i < groupItemCount; i++)
                                {
                                    jmp[i] = ctx.DefineLabel();
                                }
                                ctx.Switch(jmp);
                                // write the default...
                                ctx.Branch(tryNextGroup, false);
                                for (int i = 0; i < groupItemCount; i++)
                                {
                                    WriteEnumValue(ctx, typeCode, jmp[i], @continue, group.Items[i], @result);
                                }
                            }
                            ctx.MarkLabel(tryNextGroup);
                        }
                        // throw source.CreateEnumException(ExpectedType, wireValue);
                        ctx.LoadReaderWriter();
                        ctx.LoadValue(ExpectedType);
                        ctx.LoadValue(wireValue);
                        ctx.EmitCall(ctx.MapType(typeof(ProtoReader)).GetMethod("ThrowEnumException"));
                        ctx.MarkLabel(@continue);
                        ctx.LoadValue(result);
                    }
            }
        }
Exemplo n.º 30
0
        public void EmitRead(Compiler.CompilerContext ctx, Compiler.Local incoming)
        {
            using (Compiler.Local objValue = ctx.GetLocalWithValue(ExpectedType, incoming))
            {
                Compiler.Local[] locals = new Compiler.Local[members.Length];
                try
                {
                    for (int i = 0; i < locals.Length; i++)
                    {
                        Type type = GetMemberType(i);
                        bool store = true;
                        locals[i] = new Compiler.Local(ctx, type);
                        if (!Helpers.IsValueType(ExpectedType))
                        {
                            // value-types always read the old value
                            if (Helpers.IsValueType(type))
                            {
                                switch (Helpers.GetTypeCode(type))
                                {
                                    case ProtoTypeCode.Boolean:
                                    case ProtoTypeCode.Byte:
                                    case ProtoTypeCode.Int16:
                                    case ProtoTypeCode.Int32:
                                    case ProtoTypeCode.SByte:
                                    case ProtoTypeCode.UInt16:
                                    case ProtoTypeCode.UInt32:
                                        ctx.LoadValue(0);
                                        break;
                                    case ProtoTypeCode.Int64:
                                    case ProtoTypeCode.UInt64:
                                        ctx.LoadValue(0L);
                                        break;
                                    case ProtoTypeCode.Single:
                                        ctx.LoadValue(0.0F);
                                        break;
                                    case ProtoTypeCode.Double:
                                        ctx.LoadValue(0.0D);
                                        break;
                                    case ProtoTypeCode.Decimal:
                                        ctx.LoadValue(0M);
                                        break;
                                    case ProtoTypeCode.Guid:
                                        ctx.LoadValue(Guid.Empty);
                                        break;
                                    default:
                                        ctx.LoadAddress(locals[i], type);
                                        ctx.EmitCtor(type);
                                        store = false;
                                        break;
                                }
                            }
                            else
                            {
                                ctx.LoadNullRef();
                            }
                            if (store)
                            {
                                ctx.StoreValue(locals[i]);
                            }
                        }
                    }

                    Compiler.CodeLabel skipOld = Helpers.IsValueType(ExpectedType)
                                                        ? new Compiler.CodeLabel()
                                                        : ctx.DefineLabel();
                    if (!Helpers.IsValueType(ExpectedType))
                    {
                        ctx.LoadAddress(objValue, ExpectedType);
                        ctx.BranchIfFalse(skipOld, false);
                    }
                    for (int i = 0; i < members.Length; i++)
                    {
                        ctx.LoadAddress(objValue, ExpectedType);
                        if (members[i] is FieldInfo)
                        {
                            ctx.LoadValue((FieldInfo)members[i]);
                        }
                        else if (members[i] is PropertyInfo)
                        {
                            ctx.LoadValue((PropertyInfo)members[i]);
                        }
                        ctx.StoreValue(locals[i]);
                    }

                    if (!Helpers.IsValueType(ExpectedType)) ctx.MarkLabel(skipOld);

                    using (Compiler.Local fieldNumber = new Compiler.Local(ctx, ctx.MapType(typeof(int))))
                    {
                        Compiler.CodeLabel @continue = ctx.DefineLabel(),
                                           processField = ctx.DefineLabel(),
                                           notRecognised = ctx.DefineLabel();
                        ctx.Branch(@continue, false);

                        Compiler.CodeLabel[] handlers = new Compiler.CodeLabel[members.Length];
                        for (int i = 0; i < members.Length; i++)
                        {
                            handlers[i] = ctx.DefineLabel();
                        }

                        ctx.MarkLabel(processField);

                        ctx.LoadValue(fieldNumber);
                        ctx.LoadValue(1);
                        ctx.Subtract(); // jump-table is zero-based
                        ctx.Switch(handlers);

                        // and the default:
                        ctx.Branch(notRecognised, false);
                        for (int i = 0; i < handlers.Length; i++)
                        {
                            ctx.MarkLabel(handlers[i]);
                            IProtoSerializer tail = tails[i];
                            Compiler.Local oldValIfNeeded = tail.RequiresOldValue ? locals[i] : null;
                            ctx.ReadNullCheckedTail(locals[i].Type, tail, oldValIfNeeded);
                            if (tail.ReturnsValue)
                            {
                                if (Helpers.IsValueType(locals[i].Type))
                                {
                                    ctx.StoreValue(locals[i]);
                                }
                                else
                                {
                                    Compiler.CodeLabel hasValue = ctx.DefineLabel(), allDone = ctx.DefineLabel();

                                    ctx.CopyValue();
                                    ctx.BranchIfTrue(hasValue, true); // interpret null as "don't assign"
                                    ctx.DiscardValue();
                                    ctx.Branch(allDone, true);
                                    ctx.MarkLabel(hasValue);
                                    ctx.StoreValue(locals[i]);
                                    ctx.MarkLabel(allDone);
                                }
                            }
                            ctx.Branch(@continue, false);
                        }

                        ctx.MarkLabel(notRecognised);
                        ctx.LoadReaderWriter();
                        ctx.EmitCall(ctx.MapType(typeof(ProtoReader)).GetMethod("SkipField"));

                        ctx.MarkLabel(@continue);
                        ctx.EmitBasicRead("ReadFieldHeader", ctx.MapType(typeof(int)));
                        ctx.CopyValue();
                        ctx.StoreValue(fieldNumber);
                        ctx.LoadValue(0);
                        ctx.BranchIfGreater(processField, false);
                    }
                    for (int i = 0; i < locals.Length; i++)
                    {
                        ctx.LoadValue(locals[i]);
                    }

                    ctx.EmitCtor(ctor);
                    ctx.StoreValue(objValue);
                }
                finally
                {
                    for (int i = 0; i < locals.Length; i++)
                    {
                        if (locals[i] != null)
                            locals[i].Dispose(); // release for re-use
                    }
                }
            }

        }
Exemplo n.º 31
0
 private static void WriteEnumValue(Compiler.CompilerContext ctx, ProtoTypeCode typeCode, Compiler.CodeLabel handler, Compiler.CodeLabel @continue, object value, Compiler.Local local)
 {
     ctx.MarkLabel(handler);
     WriteEnumValue(ctx, typeCode, value);
     ctx.StoreValue(local);
     ctx.Branch(@continue, false); // "continue"
 }
Exemplo n.º 32
0
        public void EmitRead(Compiler.CompilerContext ctx, Compiler.Local incoming)
        {
            using (Compiler.Local objValue = ctx.GetLocalWithValue(ExpectedType, incoming))
            {
                Compiler.Local[] locals = new Compiler.Local[members.Length];
                try
                {
                    for (int i = 0; i < locals.Length; i++)
                    {
                        Type type  = GetMemberType(i);
                        bool store = true;
                        locals[i] = new Compiler.Local(ctx, type);
                        if (!ExpectedType.IsValueType)
                        {
                            // value-types always read the old value
                            if (type.IsValueType)
                            {
                                switch (Helpers.GetTypeCode(type))
                                {
                                case ProtoTypeCode.Boolean:
                                case ProtoTypeCode.Byte:
                                case ProtoTypeCode.Int16:
                                case ProtoTypeCode.Int32:
                                case ProtoTypeCode.SByte:
                                case ProtoTypeCode.UInt16:
                                case ProtoTypeCode.UInt32:
                                    ctx.LoadValue(0);
                                    break;

                                case ProtoTypeCode.Int64:
                                case ProtoTypeCode.UInt64:
                                    ctx.LoadValue(0L);
                                    break;

                                case ProtoTypeCode.Single:
                                    ctx.LoadValue(0.0F);
                                    break;

                                case ProtoTypeCode.Double:
                                    ctx.LoadValue(0.0D);
                                    break;

                                case ProtoTypeCode.Decimal:
                                    ctx.LoadValue(0M);
                                    break;

                                case ProtoTypeCode.Guid:
                                    ctx.LoadValue(Guid.Empty);
                                    break;

                                default:
                                    ctx.LoadAddress(locals[i], type);
                                    ctx.EmitCtor(type);
                                    store = false;
                                    break;
                                }
                            }
                            else
                            {
                                ctx.LoadNullRef();
                            }
                            if (store)
                            {
                                ctx.StoreValue(locals[i]);
                            }
                        }
                    }

                    Compiler.CodeLabel skipOld = ExpectedType.IsValueType
                                                        ? new Compiler.CodeLabel()
                                                        : ctx.DefineLabel();
                    if (!ExpectedType.IsValueType)
                    {
                        ctx.LoadAddress(objValue, ExpectedType);
                        ctx.BranchIfFalse(skipOld, false);
                    }
                    for (int i = 0; i < members.Length; i++)
                    {
                        ctx.LoadAddress(objValue, ExpectedType);
                        switch (members[i].MemberType)
                        {
                        case MemberTypes.Field:
                            ctx.LoadValue((FieldInfo)members[i]);
                            break;

                        case MemberTypes.Property:
                            ctx.LoadValue((PropertyInfo)members[i]);
                            break;
                        }
                        ctx.StoreValue(locals[i]);
                    }

                    if (!ExpectedType.IsValueType)
                    {
                        ctx.MarkLabel(skipOld);
                    }

                    using (Compiler.Local fieldNumber = new Compiler.Local(ctx, ctx.MapType(typeof(int))))
                    {
                        Compiler.CodeLabel @continue     = ctx.DefineLabel(),
                                           processField  = ctx.DefineLabel(),
                                           notRecognised = ctx.DefineLabel();
                        ctx.Branch(@continue, false);

                        Compiler.CodeLabel[] handlers = new Compiler.CodeLabel[members.Length];
                        for (int i = 0; i < members.Length; i++)
                        {
                            handlers[i] = ctx.DefineLabel();
                        }

                        ctx.MarkLabel(processField);

                        ctx.LoadValue(fieldNumber);
                        ctx.LoadValue(1);
                        ctx.Subtract(); // jump-table is zero-based
                        ctx.Switch(handlers);

                        // and the default:
                        ctx.Branch(notRecognised, false);
                        for (int i = 0; i < handlers.Length; i++)
                        {
                            ctx.MarkLabel(handlers[i]);
                            IProtoSerializer tail           = tails[i];
                            Compiler.Local   oldValIfNeeded = tail.RequiresOldValue ? locals[i] : null;
                            ctx.ReadNullCheckedTail(locals[i].Type, tail, oldValIfNeeded);
                            if (tail.ReturnsValue)
                            {
                                if (locals[i].Type.IsValueType)
                                {
                                    ctx.StoreValue(locals[i]);
                                }
                                else
                                {
                                    Compiler.CodeLabel hasValue = ctx.DefineLabel(), allDone = ctx.DefineLabel();

                                    ctx.CopyValue();
                                    ctx.BranchIfTrue(hasValue, true); // interpret null as "don't assign"
                                    ctx.DiscardValue();
                                    ctx.Branch(allDone, true);
                                    ctx.MarkLabel(hasValue);
                                    ctx.StoreValue(locals[i]);
                                    ctx.MarkLabel(allDone);
                                }
                            }
                            ctx.Branch(@continue, false);
                        }

                        ctx.MarkLabel(notRecognised);
                        ctx.LoadReaderWriter();
                        ctx.EmitCall(ctx.MapType(typeof(ProtoReader)).GetMethod("SkipField"));

                        ctx.MarkLabel(@continue);
                        ctx.EmitBasicRead("ReadFieldHeader", ctx.MapType(typeof(int)));
                        ctx.CopyValue();
                        ctx.StoreValue(fieldNumber);
                        ctx.LoadValue(0);
                        ctx.BranchIfGreater(processField, false);
                    }
                    for (int i = 0; i < locals.Length; i++)
                    {
                        ctx.LoadValue(locals[i]);
                    }

                    ctx.EmitCtor(ctor);
                    ctx.StoreValue(objValue);
                }
                finally
                {
                    for (int i = 0; i < locals.Length; i++)
                    {
                        if (locals[i] != null)
                        {
                            locals[i].Dispose(); // release for re-use
                        }
                    }
                }
            }
        }
Exemplo n.º 33
0
        protected override void EmitWrite(ProtoBuf.Compiler.CompilerContext ctx, ProtoBuf.Compiler.Local valueFrom)
        {
            using (Compiler.Local list = ctx.GetLocalWithValue(ExpectedType, valueFrom))
            {
                MethodInfo moveNext, current, getEnumerator = GetEnumeratorInfo(ctx.Model, out moveNext, out current);
                Helpers.DebugAssert(moveNext != null);
                Helpers.DebugAssert(current != null);
                Helpers.DebugAssert(getEnumerator != null);
                Type enumeratorType = getEnumerator.ReturnType;
                bool writePacked    = WritePacked;
                using (Compiler.Local iter = new Compiler.Local(ctx, enumeratorType))
                    using (Compiler.Local token = writePacked ? new Compiler.Local(ctx, ctx.MapType(typeof(SubItemToken))) : null)
                    {
                        if (writePacked)
                        {
                            ctx.LoadValue(fieldNumber);
                            ctx.LoadValue((int)WireType.String);
                            ctx.LoadReaderWriter();
                            ctx.EmitCall(ctx.MapType(typeof(ProtoWriter)).GetMethod("WriteFieldHeader"));

                            ctx.LoadValue(list);
                            ctx.LoadReaderWriter();
                            ctx.EmitCall(ctx.MapType(typeof(ProtoWriter)).GetMethod("StartSubItem"));
                            ctx.StoreValue(token);

                            ctx.LoadValue(fieldNumber);
                            ctx.LoadReaderWriter();
                            ctx.EmitCall(ctx.MapType(typeof(ProtoWriter)).GetMethod("SetPackedField"));
                        }

                        ctx.LoadAddress(list, ExpectedType);
                        ctx.EmitCall(getEnumerator);
                        ctx.StoreValue(iter);
                        using (ctx.Using(iter))
                        {
                            Compiler.CodeLabel body = ctx.DefineLabel(), next = ctx.DefineLabel();
                            ctx.Branch(next, false);

                            ctx.MarkLabel(body);

                            ctx.LoadAddress(iter, enumeratorType);
                            ctx.EmitCall(current);
                            Type itemType = Tail.ExpectedType;
                            if (itemType != ctx.MapType(typeof(object)) && current.ReturnType == ctx.MapType(typeof(object)))
                            {
                                ctx.CastFromObject(itemType);
                            }
                            Tail.EmitWrite(ctx, null);

                            ctx.MarkLabel(@next);
                            ctx.LoadAddress(iter, enumeratorType);
                            ctx.EmitCall(moveNext);
                            ctx.BranchIfTrue(body, false);
                        }

                        if (writePacked)
                        {
                            ctx.LoadValue(token);
                            ctx.LoadReaderWriter();
                            ctx.EmitCall(ctx.MapType(typeof(ProtoWriter)).GetMethod("EndSubItem"));
                        }
                    }
            }
        }
Exemplo n.º 34
0
        void IProtoSerializer.EmitRead(Compiler.CompilerContext ctx, Compiler.Local valueFrom)
        {
            Type expected = ExpectedType;
            Helpers.DebugAssert(valueFrom != null);

            using (Compiler.Local loc = ctx.GetLocalWithValue(expected, valueFrom))
            using (Compiler.Local fieldNumber = new Compiler.Local(ctx, typeof(int)))
            {
                // pre-callbacks
                if (HasCallbacks(TypeModel.CallbackType.BeforeDeserialize))
                {
                    Compiler.CodeLabel callbacksDone = ctx.DefineLabel();
                    ctx.LoadValue(loc);
                    ctx.BranchIfFalse(callbacksDone, false);
                    EmitCallbackIfNeeded(ctx, loc, TypeModel.CallbackType.BeforeDeserialize);
                    ctx.MarkLabel(callbacksDone);
                }

                Compiler.CodeLabel @continue = ctx.DefineLabel(), processField = ctx.DefineLabel();
                ctx.Branch(@continue, false);

                ctx.MarkLabel(processField);
                foreach (BasicList.Group group in BasicList.GetContiguousGroups(fieldNumbers, serializers))
                {
                    Compiler.CodeLabel tryNextField = ctx.DefineLabel();
                    int groupItemCount = group.Items.Count;
                    if (groupItemCount == 1)
                    {
                        // discreet group; use an equality test
                        ctx.LoadValue(fieldNumber);
                        ctx.LoadValue(group.First);
                        Compiler.CodeLabel processThisField = ctx.DefineLabel();
                        ctx.BranchIfEqual(processThisField, true);
                        ctx.Branch(tryNextField, false);
                        WriteFieldHandler(ctx, expected, loc, processThisField, @continue, (IProtoSerializer)group.Items[0]);
                    }
                    else
                    {   // implement as a jump-table-based switch
                        ctx.LoadValue(fieldNumber);
                        ctx.LoadValue(group.First);
                        ctx.Subtract(); // jump-tables are zero-based
                        Compiler.CodeLabel[] jmp = new Compiler.CodeLabel[groupItemCount];
                        for (int i = 0; i < groupItemCount; i++) {
                            jmp[i] = ctx.DefineLabel();
                        }
                        ctx.Switch(jmp);
                        // write the default...
                        ctx.Branch(tryNextField, false);
                        for (int i = 0; i < groupItemCount; i++)
                        {
                            WriteFieldHandler(ctx, expected, loc, jmp[i], @continue, (IProtoSerializer)group.Items[i]);
                        }
                    }
                    ctx.MarkLabel(tryNextField);
                }

                EmitCreateIfNull(ctx, expected, loc);
                ctx.LoadReaderWriter();
                if (isExtensible)
                {
                    ctx.LoadValue(loc);
                    ctx.EmitCall(typeof(ProtoReader).GetMethod("AppendExtensionData"));
                }
                else
                {
                    ctx.EmitCall(typeof(ProtoReader).GetMethod("SkipField"));
                }

                ctx.MarkLabel(@continue);
                ctx.EmitBasicRead("ReadFieldHeader", typeof(int));
                ctx.CopyValue();
                ctx.StoreValue(fieldNumber);
                ctx.LoadValue(0);
                ctx.BranchIfGreater(processField, false);

                EmitCreateIfNull(ctx, expected, loc);
                // post-callbacks
                EmitCallbackIfNeeded(ctx, loc, TypeModel.CallbackType.AfterDeserialize);
            }
        }
Exemplo n.º 35
0
        }                                                            // updates field directly
#if FEAT_COMPILER
        void IProtoSerializer.EmitWrite(Compiler.CompilerContext ctx, Compiler.Local valueFrom)
        {
            Type expected = ExpectedType;

            using (Compiler.Local loc = ctx.GetLocalWithValue(expected, valueFrom))
            {
                // pre-callbacks
                EmitCallbackIfNeeded(ctx, loc, TypeModel.CallbackType.BeforeSerialize);

                Compiler.CodeLabel startFields = ctx.DefineLabel();
                // inheritance
                if (CanHaveInheritance)
                {
                    for (int i = 0; i < serializers.Length; i++)
                    {
                        IProtoSerializer ser     = serializers[i];
                        Type             serType = ser.ExpectedType;
                        if (serType != forType)
                        {
                            Compiler.CodeLabel ifMatch = ctx.DefineLabel(), nextTest = ctx.DefineLabel();
                            ctx.LoadValue(loc);
                            ctx.TryCast(serType);
                            ctx.CopyValue();
                            ctx.BranchIfTrue(ifMatch, true);
                            ctx.DiscardValue();
                            ctx.Branch(nextTest, true);
                            ctx.MarkLabel(ifMatch);
                            ser.EmitWrite(ctx, null);
                            ctx.Branch(startFields, false);
                            ctx.MarkLabel(nextTest);
                        }
                    }


                    if (constructType != null && constructType != forType)
                    {
                        using (Compiler.Local actualType = new Compiler.Local(ctx, ctx.MapType(typeof(System.Type))))
                        {
                            // would have jumped to "fields" if an expected sub-type, so two options:
                            // a: *exactly* that type, b: an *unexpected* type
                            ctx.LoadValue(loc);
                            ctx.EmitCall(ctx.MapType(typeof(object)).GetMethod("GetType"));
                            ctx.CopyValue();
                            ctx.StoreValue(actualType);
                            ctx.LoadValue(forType);
                            ctx.BranchIfEqual(startFields, true);

                            ctx.LoadValue(actualType);
                            ctx.LoadValue(constructType);
                            ctx.BranchIfEqual(startFields, true);
                        }
                    }
                    else
                    {
                        // would have jumped to "fields" if an expected sub-type, so two options:
                        // a: *exactly* that type, b: an *unexpected* type
                        ctx.LoadValue(loc);
                        ctx.EmitCall(ctx.MapType(typeof(object)).GetMethod("GetType"));
                        ctx.LoadValue(forType);
                        ctx.BranchIfEqual(startFields, true);
                    }
                    // unexpected, then... note that this *might* be a proxy, which
                    // is handled by ThrowUnexpectedSubtype
                    ctx.LoadValue(forType);
                    ctx.LoadValue(loc);
                    ctx.EmitCall(ctx.MapType(typeof(object)).GetMethod("GetType"));
                    ctx.EmitCall(ctx.MapType(typeof(TypeModel)).GetMethod("ThrowUnexpectedSubtype",
                                                                          BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static));
                }
                // fields

                ctx.MarkLabel(startFields);
                for (int i = 0; i < serializers.Length; i++)
                {
                    IProtoSerializer ser = serializers[i];
                    if (ser.ExpectedType == forType)
                    {
                        ser.EmitWrite(ctx, loc);
                    }
                }

                // extension data
                if (isExtensible)
                {
                    ctx.LoadValue(loc);
                    ctx.LoadReaderWriter();
                    ctx.EmitCall(ctx.MapType(typeof(ProtoWriter)).GetMethod("AppendExtensionData"));
                }
                // post-callbacks
                EmitCallbackIfNeeded(ctx, loc, TypeModel.CallbackType.AfterSerialize);
            }
        }
Exemplo n.º 36
0
        protected override void EmitRead(Compiler.CompilerContext ctx, Compiler.Local valueFrom)
        {
            bool writeValue;
            SanityCheck(ctx.Model, property, Tail, out writeValue, ctx.NonPublic, ctx.AllowInternal(property));
            if (ExpectedType.IsValueType && valueFrom == null)
            {
                throw new InvalidOperationException("Attempt to mutate struct on the head of the stack; changes would be lost");
            }

            using (Compiler.Local loc = ctx.GetLocalWithValue(ExpectedType, valueFrom))
            {
                if (Tail.RequiresOldValue)
                {
                    ctx.LoadAddress(loc, ExpectedType); // stack is: old-addr
                    ctx.LoadValue(property); // stack is: old-value
                }
                Type propertyType = property.PropertyType;
                ctx.ReadNullCheckedTail(propertyType, Tail, null); // stack is [new-value]

                if (writeValue)
                {
                    using (Compiler.Local newVal = new Compiler.Local(ctx, property.PropertyType))
                    {
                        ctx.StoreValue(newVal); // stack is empty

                        Compiler.CodeLabel allDone = new Compiler.CodeLabel(); // <=== default structs
                        if (!propertyType.IsValueType)
                        { // if the tail returns a null, intepret that as *no assign*
                            allDone = ctx.DefineLabel();
                            ctx.LoadValue(newVal); // stack is: new-value
                            ctx.BranchIfFalse(@allDone, true); // stack is empty
                        }
                        // assign the value
                        ctx.LoadAddress(loc, ExpectedType); // parent-addr
                        ctx.LoadValue(newVal); // parent-obj|new-value
                        if (shadowSetter == null)
                        {
                            ctx.StoreValue(property); // empty
                        }
                        else
                        {
                            ctx.EmitCall(shadowSetter); // empty
                        }
                        if (!propertyType.IsValueType)
                        {
                            ctx.MarkLabel(allDone);
                        }
                    }

                }
                else
                { // don't want return value; drop it if anything there
                    // stack is [new-value]
                    if (Tail.ReturnsValue) { ctx.DiscardValue(); }
                }
            }
        }
Exemplo n.º 37
0
        private void WriteGetKeyImpl(TypeBuilder type, bool hasInheritance, SerializerPair[] methodPairs, Compiler.CompilerContext.ILVersion ilVersion, string assemblyName, out ILGenerator il, out int knownTypesCategory, out FieldBuilder knownTypes, out Type knownTypesLookupType)
        {

            il = Override(type, "GetKeyImpl");
            Compiler.CompilerContext ctx = new Compiler.CompilerContext(il, false, false, methodPairs, this, ilVersion, assemblyName, MapType(typeof(System.Type), true));
            
            if (types.Count <= KnownTypes_ArrayCutoff)
            {
                knownTypesCategory = KnownTypes_Array;
                knownTypesLookupType = MapType(typeof(System.Type[]), true);
            }
            else
            {
#if NO_GENERICS
                knownTypesLookupType = null;
#else
                knownTypesLookupType = MapType(typeof(System.Collections.Generic.Dictionary<System.Type, int>), false);
#endif
                if (knownTypesLookupType == null)
                {
                    knownTypesLookupType = MapType(typeof(Hashtable), true);
                    knownTypesCategory = KnownTypes_Hashtable;
                }
                else
                {
                    knownTypesCategory = KnownTypes_Dictionary;
                }
            }
            knownTypes = type.DefineField("knownTypes", knownTypesLookupType, FieldAttributes.Private | FieldAttributes.InitOnly | FieldAttributes.Static);

            switch (knownTypesCategory)
            {
                case KnownTypes_Array:
                    {
                        il.Emit(OpCodes.Ldsfld, knownTypes);
                        il.Emit(OpCodes.Ldarg_1);
                        // note that Array.IndexOf is not supported under CF
                        il.EmitCall(OpCodes.Callvirt, MapType(typeof(IList)).GetMethod(
                            "IndexOf", new Type[] { MapType(typeof(object)) }), null);
                        if (hasInheritance)
                        {
                            il.DeclareLocal(MapType(typeof(int))); // loc-0
                            il.Emit(OpCodes.Dup);
                            il.Emit(OpCodes.Stloc_0);

                            BasicList getKeyLabels = new BasicList();
                            int lastKey = -1;
                            for (int i = 0; i < methodPairs.Length; i++)
                            {
                                if (methodPairs[i].MetaKey == methodPairs[i].BaseKey) break;
                                if (lastKey == methodPairs[i].BaseKey)
                                {   // add the last label again
                                    getKeyLabels.Add(getKeyLabels[getKeyLabels.Count - 1]);
                                }
                                else
                                {   // add a new unique label
                                    getKeyLabels.Add(ctx.DefineLabel());
                                    lastKey = methodPairs[i].BaseKey;
                                }
                            }
                            Compiler.CodeLabel[] subtypeLabels = new Compiler.CodeLabel[getKeyLabels.Count];
                            getKeyLabels.CopyTo(subtypeLabels, 0);

                            ctx.Switch(subtypeLabels);
                            il.Emit(OpCodes.Ldloc_0); // not a sub-type; use the original value
                            il.Emit(OpCodes.Ret);

                            lastKey = -1;
                            // now output the different branches per sub-type (not derived type)
                            for (int i = subtypeLabels.Length - 1; i >= 0; i--)
                            {
                                if (lastKey != methodPairs[i].BaseKey)
                                {
                                    lastKey = methodPairs[i].BaseKey;
                                    // find the actual base-index for this base-key (i.e. the index of
                                    // the base-type)
                                    int keyIndex = -1;
                                    for (int j = subtypeLabels.Length; j < methodPairs.Length; j++)
                                    {
                                        if (methodPairs[j].BaseKey == lastKey && methodPairs[j].MetaKey == lastKey)
                                        {
                                            keyIndex = j;
                                            break;
                                        }
                                    }
                                    ctx.MarkLabel(subtypeLabels[i]);
                                    Compiler.CompilerContext.LoadValue(il, keyIndex);
                                    il.Emit(OpCodes.Ret);
                                }
                            }
                        }
                        else
                        {
                            il.Emit(OpCodes.Ret);
                        }
                    }
                    break;
                case KnownTypes_Dictionary:
                    {
                        LocalBuilder result = il.DeclareLocal(MapType(typeof(int)));
                        Label otherwise = il.DefineLabel();
                        il.Emit(OpCodes.Ldsfld, knownTypes);
                        il.Emit(OpCodes.Ldarg_1);
                        il.Emit(OpCodes.Ldloca_S, result);
                        il.EmitCall(OpCodes.Callvirt, knownTypesLookupType.GetMethod("TryGetValue", BindingFlags.Instance | BindingFlags.Public), null);
                        il.Emit(OpCodes.Brfalse_S, otherwise);
                        il.Emit(OpCodes.Ldloc_S, result);
                        il.Emit(OpCodes.Ret);
                        il.MarkLabel(otherwise);
                        il.Emit(OpCodes.Ldc_I4_M1);
                        il.Emit(OpCodes.Ret);
                    }
                    break;
                case KnownTypes_Hashtable:
                    {
                        Label otherwise = il.DefineLabel();
                        il.Emit(OpCodes.Ldsfld, knownTypes);
                        il.Emit(OpCodes.Ldarg_1);
                        il.EmitCall(OpCodes.Callvirt, knownTypesLookupType.GetProperty("Item").GetGetMethod(), null);
                        il.Emit(OpCodes.Dup);
                        il.Emit(OpCodes.Brfalse_S, otherwise);
#if FX11
                        il.Emit(OpCodes.Unbox, MapType(typeof(int)));
                        il.Emit(OpCodes.Ldobj, MapType(typeof(int)));
#else
                        if (ilVersion == Compiler.CompilerContext.ILVersion.Net1)
                        {
                            il.Emit(OpCodes.Unbox, MapType(typeof(int)));
                            il.Emit(OpCodes.Ldobj, MapType(typeof(int)));
                        }
                        else
                        {
                            il.Emit(OpCodes.Unbox_Any, MapType(typeof(int)));
                        }
#endif
                        il.Emit(OpCodes.Ret);
                        il.MarkLabel(otherwise);
                        il.Emit(OpCodes.Pop);
                        il.Emit(OpCodes.Ldc_I4_M1);
                        il.Emit(OpCodes.Ret);
                    }
                    break;
                default:
                    throw new InvalidOperationException();
            }
        }
Exemplo n.º 38
0
        protected override void EmitRead(CompilerContext ctx, Local valueFrom)
        {
            using (Compiler.Local list = AppendToCollection ? ctx.GetLocalWithValue(ExpectedType, valueFrom)
                : new Compiler.Local(ctx, typeof(TDictionary)))
                using (Compiler.Local token = new Compiler.Local(ctx, typeof(SubItemToken)))
                    using (Compiler.Local key = new Compiler.Local(ctx, typeof(TKey)))
                        using (Compiler.Local @value = new Compiler.Local(ctx, typeof(TValue)))
                            using (Compiler.Local fieldNumber = new Compiler.Local(ctx, typeof(int)))
                            {
                                if (!AppendToCollection)
                                { // always new
                                    ctx.LoadNullRef();
                                    ctx.StoreValue(list);
                                }
                                if (concreteType != null)
                                {
                                    ctx.LoadValue(list);
                                    Compiler.CodeLabel notNull = ctx.DefineLabel();
                                    ctx.BranchIfTrue(notNull, true);
                                    ctx.EmitCtor(concreteType);
                                    ctx.StoreValue(list);
                                    ctx.MarkLabel(notNull);
                                }

                                var redoFromStart = ctx.DefineLabel();
                                ctx.MarkLabel(redoFromStart);

                                // key = default(TKey); value = default(TValue);
                                if (typeof(TKey) == typeof(string))
                                {
                                    ctx.LoadValue("");
                                    ctx.StoreValue(key);
                                }
                                else
                                {
                                    ctx.InitLocal(typeof(TKey), key);
                                }
                                if (typeof(TValue) == typeof(string))
                                {
                                    ctx.LoadValue("");
                                    ctx.StoreValue(value);
                                }
                                else
                                {
                                    ctx.InitLocal(typeof(TValue), @value);
                                }

                                // token = ProtoReader.StartSubItem(reader);
                                ctx.LoadReader(true);
                                ctx.EmitCall(typeof(ProtoReader).GetMethod("StartSubItem", ProtoReader.State.ReaderStateTypeArray));
                                ctx.StoreValue(token);

                                Compiler.CodeLabel @continue = ctx.DefineLabel(), processField = ctx.DefineLabel();
                                // while ...
                                ctx.Branch(@continue, false);

                                // switch(fieldNumber)
                                ctx.MarkLabel(processField);
                                ctx.LoadValue(fieldNumber);
                                CodeLabel @default = ctx.DefineLabel(), one = ctx.DefineLabel(), two = ctx.DefineLabel();
                                ctx.Switch(new[] { @default, one, two }); // zero based, hence explicit 0

                                // case 0: default: reader.SkipField();
                                ctx.MarkLabel(@default);
                                ctx.LoadReader(true);
                                ctx.EmitCall(typeof(ProtoReader).GetMethod("SkipField", ProtoReader.State.StateTypeArray));
                                ctx.Branch(@continue, false);

                                // case 1: key = ...
                                ctx.MarkLabel(one);
                                keyTail.EmitRead(ctx, null);
                                ctx.StoreValue(key);
                                ctx.Branch(@continue, false);

                                // case 2: value = ...
                                ctx.MarkLabel(two);
                                Tail.EmitRead(ctx, Tail.RequiresOldValue ? @value : null);
                                ctx.StoreValue(value);

                                // (fieldNumber = reader.ReadFieldHeader()) > 0
                                ctx.MarkLabel(@continue);
                                ctx.EmitBasicRead("ReadFieldHeader", typeof(int));
                                ctx.CopyValue();
                                ctx.StoreValue(fieldNumber);
                                ctx.LoadValue(0);
                                ctx.BranchIfGreater(processField, false);

                                // ProtoReader.EndSubItem(token, reader);
                                ctx.LoadValue(token);
                                ctx.LoadReader(true);
                                ctx.EmitCall(typeof(ProtoReader).GetMethod("EndSubItem",
                                                                           new[] { typeof(SubItemToken), typeof(ProtoReader), ProtoReader.State.ByRefStateType }));

                                // list[key] = value;
                                ctx.LoadAddress(list, ExpectedType);
                                ctx.LoadValue(key);
                                ctx.LoadValue(@value);
                                ctx.EmitCall(indexerSet);

                                // while reader.TryReadFieldReader(fieldNumber)
                                ctx.LoadReader(true);
                                ctx.LoadValue(this.fieldNumber);
                                ctx.EmitCall(typeof(ProtoReader).GetMethod("TryReadFieldHeader",
                                                                           new[] { ProtoReader.State.ByRefStateType, typeof(int) }));
                                ctx.BranchIfTrue(redoFromStart, false);

                                if (ReturnsValue)
                                {
                                    ctx.LoadValue(list);
                                }
                            }
        }