int ReadMembers(int index, ClassDataContract classContract, BitFlagsGenerator expectedElements, ref int memberIndex)
        {
            int memberCount = (classContract.BaseContract == null) ? 0 : ReadMembers(index, classContract.BaseContract, expectedElements,
                                                                                     ref memberIndex);

            if (memberCount <= index && index < memberCount + classContract.Members.Count)
            {
                DataMember dataMember = classContract.Members [index - memberCount];
                Type       memberType = dataMember.MemberType;

                memberIndex = memberCount;
                if (!expectedElements.Load(index))
                {
                    XmlObjectSerializerReadContextComplexJson.ThrowDuplicateMemberException(objectLocal, memberNames, memberIndex);
                }

                if (dataMember.IsGetOnlyCollection)
                {
                    var value = CodeInterpreter.GetMember(dataMember.MemberInfo, objectLocal);
                    context.StoreCollectionMemberInfo(value);
                    ReadValue(memberType, dataMember.Name);
                }
                else
                {
                    var value = ReadValue(memberType, dataMember.Name);
                    CodeInterpreter.SetMember(dataMember.MemberInfo, objectLocal, value);
                }
                memberIndex = index;
                ResetExpectedElements(expectedElements, index);
            }
            return(memberCount + classContract.Members.Count);
        }
        void CreateObject(ClassDataContract classContract)
        {
            Type type = objectType = classContract.UnderlyingType;

            if (type.IsValueType && !classContract.IsNonAttributedType)
            {
                type = Globals.TypeOfValueType;
            }

            if (classContract.UnderlyingType == Globals.TypeOfDBNull)
            {
                objectLocal = DBNull.Value;
            }
            else if (classContract.IsNonAttributedType)
            {
                if (type.IsValueType)
                {
                    objectLocal = FormatterServices.GetUninitializedObject(type);
                }
                else
                {
                    objectLocal = classContract.GetNonAttributedTypeConstructor().Invoke(new object [0]);
                }
            }
            else
            {
                objectLocal = CodeInterpreter.ConvertValue(XmlFormatReaderGenerator.UnsafeGetUninitializedObject(DataContract.GetIdForInitialization(classContract)), Globals.TypeOfObject, type);
            }
        }
        void StoreCollectionValue(object collection, Type valueType, object value, CollectionDataContract collectionContract)
        {
            if (collectionContract.Kind == CollectionKind.GenericDictionary || collectionContract.Kind == CollectionKind.Dictionary)
            {
                ClassDataContract keyValuePairContract = DataContract.GetDataContract(valueType) as ClassDataContract;
                if (keyValuePairContract == null)
                {
                    Fx.Assert("Failed to create contract for KeyValuePair type");
                }
                DataMember keyMember   = keyValuePairContract.Members [0];
                DataMember valueMember = keyValuePairContract.Members [1];
                object     pkey        = CodeInterpreter.GetMember(keyMember.MemberInfo, value);
                object     pvalue      = CodeInterpreter.GetMember(valueMember.MemberInfo, value);

                try {
                    collectionContract.AddMethod.Invoke(collection, new object [] { pkey, pvalue });
                } catch (TargetInvocationException ex) {
                    if (ex.InnerException != null)
                    {
                        throw ex.InnerException;
                    }
                    else
                    {
                        throw;
                    }
                }
            }
            else
            {
                collectionContract.AddMethod.Invoke(collection, new object [] { value });
            }
        }
 bool InvokeFactoryMethod(ClassDataContract classContract)
 {
     if (HasFactoryMethod(classContract))
     {
         objectLocal = CodeInterpreter.ConvertValue(context.GetRealObject((IObjectReference)objectLocal, Globals.NewObjectId), Globals.TypeOfObject, classContract.UnderlyingType);
         return(true);
     }
     return(false);
 }
 void InitArgs(Type objType)
 {
     if (objType == Globals.TypeOfDateTimeOffsetAdapter)
     {
         objLocal = DateTimeOffsetAdapter.GetDateTimeOffsetAdapter((DateTimeOffset)obj);
     }
     else
     {
         objLocal = CodeInterpreter.ConvertValue(obj, typeof(object), objType);
     }
 }
Exemplo n.º 6
0
        private void InitializeCompiler()
        {
            _compiler = new MetaCodeCompiler();
            CompilerService = CompilerService.Instance;
            MacroInterpreter = new MacroInterpreter(CompilerService);
            CodeInterpreter = new CodeInterpreter(CompilerService);
            CodeGenerator = new CodeGenerator();
            SemanticParser = new SemanticParser(CompilerService);

            InitializeFunctions();
            WindowTitle = "MetaCode IDE";
        }
        bool TryWritePrimitive(Type type, Func <object> value, MemberInfo memberInfo, int?arrayItemIndex, XmlDictionaryString name, int nameIndex)
        {
            PrimitiveDataContract primitiveContract = PrimitiveDataContract.GetPrimitiveDataContract(type);

            if (primitiveContract == null || primitiveContract.UnderlyingType == Globals.TypeOfObject)
            {
                return(false);
            }

            object callee = null;
            var    args   = new List <object> ();

            // load writer
            if (type.IsValueType)
            {
                callee = writer;
            }
            else
            {
                callee = context;
                args.Add(writer);
            }
            // load primitive value
            if (value != null)
            {
                args.Add(value());
            }
            else if (memberInfo != null)
            {
                args.Add(CodeInterpreter.GetMember(memberInfo, objLocal));
            }
            else
            {
                args.Add(((Array)objLocal).GetValue(new int [] { (int)arrayItemIndex }));
            }
            // load name
            if (name != null)
            {
                args.Add(name);
            }
            else
            {
                args.Add(memberNames [nameIndex]);
            }
            // load namespace
            args.Add(null);
            // call method to write primitive
            primitiveContract.XmlFormatWriterMethod.Invoke(callee, args.ToArray());
            return(true);
        }
 object ReadCollectionItem(CollectionDataContract collectionContract, Type itemType)
 {
     if (collectionContract.Kind == CollectionKind.Dictionary || collectionContract.Kind == CollectionKind.GenericDictionary)
     {
         context.ResetAttributes();
         var revisedContract = XmlObjectSerializerWriteContextComplexJson.GetRevisedItemContract(collectionContract.ItemContract);
         var v = DataContractJsonSerializer.ReadJsonValue(revisedContract, xmlReader, context);
         return(CodeInterpreter.ConvertValue(v, Globals.TypeOfObject, itemType));
     }
     else
     {
         return(ReadValue(itemType, JsonGlobals.itemString));
     }
 }
        object InternalDeserialize(Type type, string name)
        {
            Type declaredType = type.IsPointer ? Globals.TypeOfReflectionPointer : type;
            var  obj          = context.InternalDeserialize(xmlReader, DataContract.GetId(declaredType.TypeHandle), declaredType.TypeHandle, name, string.Empty);

            if (type.IsPointer)
            {
                // wow, there is no way to convert void* to object in strongly typed way...
                return(JsonFormatGeneratorStatics.UnboxPointer.Invoke(null, new object [] { obj }));
            }
            else
            {
                return(CodeInterpreter.ConvertValue(obj, Globals.TypeOfObject, type));
            }
        }
Exemplo n.º 10
0
        public FunctionContext(string name, FunctionDeclarationStatementNode function, InterpreterContext interpreterContext, CodeInterpreter codeInterpreter)
            : base(name)
        {
            if (function == null)
                ThrowHelper.ThrowArgumentNullException(() => function);

            if (interpreterContext == null)
                ThrowHelper.ThrowArgumentNullException(() => interpreterContext);

            if (codeInterpreter == null)
                ThrowHelper.ThrowArgumentNullException(() => codeInterpreter);

            Function = function;
            InterpreterContext = interpreterContext;
            CodeInterpreter = codeInterpreter;
        }
Exemplo n.º 11
0
        public bool TryInterpret(CodeInterpreter compiler, CodeReader reader, out IProcess process)
        {
            process = null;

            var backup = reader.Backup();

            if (reader.ReadName(out var name))
            {
                process = new GetFieldProcess(name);

                return(true);
            }

            backup.Restore();

            return(false);
        }
        void InternalSerialize(MethodInfo methodInfo, Func <object> memberValue, Type memberType, bool writeXsiType)
        {
            var v = memberValue();
            var typeHandleValue = Type.GetTypeHandle(v);
            var isDeclaredType  = typeHandleValue.Equals(CodeInterpreter.ConvertValue(v, memberType, Globals.TypeOfObject));

            try {
                methodInfo.Invoke(context, new object [] { writer, memberValue != null ? v : null, isDeclaredType, writeXsiType, DataContract.GetId(memberType.TypeHandle), memberType.TypeHandle });
            } catch (TargetInvocationException ex) {
                if (ex.InnerException != null)
                {
                    throw ex.InnerException;
                }
                else
                {
                    throw;
                }
            }
        }
Exemplo n.º 13
0
        public bool TryInterpret(CodeInterpreter compiler, CodeReader reader, out IProcess process)
        {
            var backup = reader.Backup();

            process = null;

            if (reader.ReadName(out var name) && reader.ReadChar(out var bracketBegin) && bracketBegin == '(')
            {
                var parameters = new List <IProcess>();

Loop:

                if (reader.CurrentChar(out var bracketEnd) && bracketEnd == ')')
                {
                    reader.Next();

                    process = new InvokeFunctionProcess(name, parameters.ToArray());

                    return(true);
                }
Exemplo n.º 14
0
        public bool TryInterpret(CodeInterpreter compiler, CodeReader reader, out IProcess process)
        {
            var backup = reader.Backup();

            if (reader.ReadChar(out var bracketBegin) && bracketBegin == '(')
            {
                process = compiler.Interpret(reader, Priorities.None);

                if (reader.ReadChar(out var bracketEnd) && bracketEnd == ')')
                {
                    return(true);
                }
            }

            process = null;

            backup.Restore();

            return(false);
        }
Exemplo n.º 15
0
        public bool TryInterpret(CodeInterpreter compiler, CodeReader reader, out IProcess process)
        {
            var backup = reader.Backup();

            process = null;

            if (reader.ReadName(out var _var) && _var == "var")
            {
Loop:

                if (reader.ReadName(out var name))
                {
                    IProcess initValue = null;

                    if (reader.CurrentChar(out var c) && c == '=')
                    {
                        reader.Next();

                        initValue = compiler.Interpret(reader, Priorities.AssignValueOperator);
                    }

                    if (reader.CurrentChar(out var c1) && c1 == ',')
                    {
                        reader.Next();

                        process = new VarProcess(name, initValue, process);

                        goto Loop;
                    }

                    process = new VarProcess(name, initValue, process);

                    return(true);
                }
            }

            backup.Restore();

            return(false);
        }
Exemplo n.º 16
0
        public bool TryInterpret(CodeInterpreter compiler, CodeReader reader, out IProcess process)
        {
            var backup = reader.Backup();

            process = null;

            if (compiler.TryInterpret(reader, Priority, out var before))
            {
                if (reader.ReadOperator(out var operatorText) && OperatorText == operatorText)
                {
                    if (compiler.TryInterpret(reader, Priority, out var after))
                    {
                        process = CreateProcess(before, after);

                        return(true);
                    }
                }
            }

            backup.Restore();

            return(false);
        }
Exemplo n.º 17
0
        public unsafe bool TryInterpret(CodeInterpreter compiler, CodeReader reader, out IProcess process)
        {
            var backup = reader.Backup();

            process = null;

            if (reader.ReadNumber(out var text))
            {
                fixed(char *pText = text)
                {
                    var numberInfo = NumberHelper.GetNumberInfo(pText, text.Length, 10);

                    if (numberInfo.IsNumber)
                    {
                        if (numberInfo.HaveExponent)
                        {
                            process = new ConstantProcess(new DoubleConstant(numberInfo.ToDouble()));
                        }
                        else if (numberInfo.IsFloat)
                        {
                            if (numberInfo.IsDecimal && numberInfo.IntegerCount + numberInfo.FractionalCount <= 28)
                            {
                                process = new ConstantProcess(new DecimalConstant(numberInfo.ToDecimal()));
                            }
                            else
                            {
                                process = new ConstantProcess(new DoubleConstant(numberInfo.ToDouble()));
                            }
                        }
                        else if (numberInfo.IntegerCount <= 18)
                        {
                            process = new ConstantProcess(new Int64Constant(numberInfo.ToInt64()));
                        }
                        else if (numberInfo.IsDecimal && numberInfo.IntegerCount <= 28)
                        {
                            process = new ConstantProcess(new DecimalConstant(numberInfo.ToDecimal()));
                        }
                        else
                        {
                            process = new ConstantProcess(new DoubleConstant(numberInfo.ToDouble()));
                        }

                        return(true);
                    }
                }

                if (long.TryParse(text, NumberStyles.Integer, NumberFormatInfo.CurrentInfo, out var int64Value))
                {
                    process = new ConstantProcess(new Int64Constant(int64Value));

                    return(true);
                }

                if (decimal.TryParse(text, NumberStyles.Float, NumberFormatInfo.CurrentInfo, out var decimalValue))
                {
                    process = new ConstantProcess(new DecimalConstant(decimalValue));

                    return(true);
                }

                if (double.TryParse(text, NumberStyles.Float, NumberFormatInfo.CurrentInfo, out var doubleValue))
                {
                    process = new ConstantProcess(new DoubleConstant(doubleValue));

                    return(true);
                }
            }

            backup.Restore();

            return(false);
        }
        public void InterpreterTest()
        {
            // GIVEN
            var source = @"
                var person: any = 0;    
                person.name = 'John Doe';
                person.age = 24;
                writeline(person.name);

                function max(a: number, b: number) : number do
                  writeline('call function max');
                  if (a > b)
                    result = a; 
                  else
                    result = b;
                  end;
                end;

                function min(a: number, b: number) : number do
                  writeline('call function min');
                  if (a < b)
                    result = a; 
                  else
                    result = b;
                  end;
                end;

                var j : number = 0;
                foreach (var i : number in [1,2,3,4,5,6]) do
                  j = max(3 * i, min(4 * i, 5 * i));
                  writeline(j + '. Hello World!');
                end;
            ";

            var compilerService = new CompilerService();
            var analyzer = new CodeInterpreter(compilerService);

            // WHEN
            var node = ParseWithAbstractTreeVisitor(Compiler, source);
            analyzer.VisitChild(node as CompilationUnit);

            // THEN
        }
        object ReadValue(Type type, string name)
        {
            var    valueType = type;
            object value     = null;
            bool   shouldAssignNullableValue = false;
            int    nullables = 0;

            while (type.IsGenericType && type.GetGenericTypeDefinition() == Globals.TypeOfNullable)
            {
                nullables++;
                type = type.GetGenericArguments() [0];
            }

            PrimitiveDataContract primitiveContract = PrimitiveDataContract.GetPrimitiveDataContract(type);

            if ((primitiveContract != null && primitiveContract.UnderlyingType != Globals.TypeOfObject) || nullables != 0 || type.IsValueType)
            {
                context.ReadAttributes(xmlReader);
                string objectId = context.ReadIfNullOrRef(xmlReader, type, DataContract.IsTypeSerializable(type));
                // Deserialize null
                if (objectId == Globals.NullObjectId)
                {
                    if (nullables != 0)
                    {
                        value = Activator.CreateInstance(valueType);
                    }
                    else if (type.IsValueType)
                    {
                        throw new SerializationException(SR.GetString(SR.ValueTypeCannotBeNull, DataContract.GetClrTypeFullName(type)));
                    }
                    else
                    {
                        value = null;
                    }
                }
                else if (objectId == string.Empty)
                {
                    // Deserialize value

                    // Compare against Globals.NewObjectId, which is set to string.Empty

                    objectId = context.GetObjectId();

                    if (type.IsValueType)
                    {
                        if (!string.IsNullOrEmpty(objectId))
                        {
                            throw new SerializationException(SR.GetString(SR.ValueTypeCannotHaveId, DataContract.GetClrTypeFullName(type)));
                        }
                    }
                    object innerValueRead = null;
                    if (nullables != 0)
                    {
                        shouldAssignNullableValue = true;
                    }

                    if (primitiveContract != null && primitiveContract.UnderlyingType != Globals.TypeOfObject)
                    {
                        value = primitiveContract.XmlFormatReaderMethod.Invoke(xmlReader, new object [0]);
                        if (!type.IsValueType)
                        {
                            context.AddNewObject(value);
                        }
                    }
                    else
                    {
                        value = InternalDeserialize(type, name);
                    }
                }
                else
                {
                    // Deserialize ref
                    if (type.IsValueType)
                    {
                        throw new SerializationException(SR.GetString(SR.ValueTypeCannotHaveRef, DataContract.GetClrTypeFullName(type)));
                    }
                    else
                    {
                        value = CodeInterpreter.ConvertValue(context.GetExistingObject(objectId, type, name, string.Empty), Globals.TypeOfObject, type);
                    }
                }

                if (shouldAssignNullableValue)
                {
                    if (objectId != Globals.NullObjectId)
                    {
                        value = WrapNullableObject(type, value, valueType, nullables);
                    }
                }
            }
            else
            {
                value = InternalDeserialize(type, name);
            }

            return(value);
        }
Exemplo n.º 20
0
        public InterpreterContext DeclareFunction(string name, FunctionDeclarationStatementNode function, CodeInterpreter codeInterpreter)
        {
            if (string.IsNullOrWhiteSpace(name))
                ThrowHelper.ThrowException("The 'name' is blank!");

            if (function == null)
                ThrowHelper.ThrowArgumentNullException(() => function);

            _functions.First()
                      .Add(name, new FunctionContext(name, function, this, codeInterpreter));

            return this;
        }
        void WriteCollection(CollectionDataContract collectionContract)
        {
            XmlDictionaryString itemName = context.CollectionItemName;

            if (collectionContract.Kind == CollectionKind.Array)
            {
                Type itemType = collectionContract.ItemType;
                int  i;

                // This check does not exist in the original dynamic code,
                // but there is no other way to check type mismatch.
                // CollectionSerialization.ArrayContract() shows that it is required.
                if (objLocal.GetType().GetElementType() != itemType)
                {
                    throw new InvalidCastException(string.Format("Cannot cast array of {0} to array of {1}", objLocal.GetType().GetElementType(), itemType));
                }

                context.IncrementArrayCount(writer, (Array)objLocal);

                if (!TryWritePrimitiveArray(collectionContract.UnderlyingType, itemType, () => objLocal, itemName))
                {
                    WriteArrayAttribute();
                    var arr = (Array)objLocal;
                    var idx = new int [1];
                    for (i = 0; i < arr.Length; i++)
                    {
                        if (!TryWritePrimitive(itemType, null, null, i, itemName, 0))
                        {
                            WriteStartElement(itemName, 0);
                            idx [0] = i;
                            var mbrVal = arr.GetValue(idx);
                            WriteValue(itemType, mbrVal);
                            WriteEndElement();
                        }
                    }
                }
            }
            else
            {
                // This check does not exist in the original dynamic code,
                // but there is no other way to check type mismatch.
                // CollectionSerialization.ArrayContract() shows that it is required.
                if (!collectionContract.UnderlyingType.IsAssignableFrom(objLocal.GetType()))
                {
                    throw new InvalidCastException(string.Format("Cannot cast {0} to {1}", objLocal.GetType(), collectionContract.UnderlyingType));
                }

                MethodInfo incrementCollectionCountMethod = null;
                switch (collectionContract.Kind)
                {
                case CollectionKind.Collection:
                case CollectionKind.List:
                case CollectionKind.Dictionary:
                    incrementCollectionCountMethod = XmlFormatGeneratorStatics.IncrementCollectionCountMethod;
                    break;

                case CollectionKind.GenericCollection:
                case CollectionKind.GenericList:
                    incrementCollectionCountMethod = XmlFormatGeneratorStatics.IncrementCollectionCountGenericMethod.MakeGenericMethod(collectionContract.ItemType);
                    break;

                case CollectionKind.GenericDictionary:
                    incrementCollectionCountMethod = XmlFormatGeneratorStatics.IncrementCollectionCountGenericMethod.MakeGenericMethod(Globals.TypeOfKeyValuePair.MakeGenericType(collectionContract.ItemType.GetGenericArguments()));
                    break;
                }
                if (incrementCollectionCountMethod != null)
                {
                    incrementCollectionCountMethod.Invoke(context, new object [] { writer, objLocal });
                }

                bool    isDictionary = false, isGenericDictionary = false;
                Type    enumeratorType = null;
                Type [] keyValueTypes  = null;
                if (collectionContract.Kind == CollectionKind.GenericDictionary)
                {
                    isGenericDictionary = true;
                    keyValueTypes       = collectionContract.ItemType.GetGenericArguments();
                    enumeratorType      = Globals.TypeOfGenericDictionaryEnumerator.MakeGenericType(keyValueTypes);
                }
                else if (collectionContract.Kind == CollectionKind.Dictionary)
                {
                    isDictionary   = true;
                    keyValueTypes  = new Type[] { Globals.TypeOfObject, Globals.TypeOfObject };
                    enumeratorType = Globals.TypeOfDictionaryEnumerator;
                }
                else
                {
                    enumeratorType = collectionContract.GetEnumeratorMethod.ReturnType;
                }
                MethodInfo moveNextMethod   = enumeratorType.GetMethod(Globals.MoveNextMethodName, BindingFlags.Instance | BindingFlags.Public, null, Globals.EmptyTypeArray, null);
                MethodInfo getCurrentMethod = enumeratorType.GetMethod(Globals.GetCurrentMethodName, BindingFlags.Instance | BindingFlags.Public, null, Globals.EmptyTypeArray, null);
                if (moveNextMethod == null || getCurrentMethod == null)
                {
                    if (enumeratorType.IsInterface)
                    {
                        if (moveNextMethod == null)
                        {
                            moveNextMethod = JsonFormatGeneratorStatics.MoveNextMethod;
                        }
                        if (getCurrentMethod == null)
                        {
                            getCurrentMethod = JsonFormatGeneratorStatics.GetCurrentMethod;
                        }
                    }
                    else
                    {
                        Type           ienumeratorInterface = Globals.TypeOfIEnumerator;
                        CollectionKind kind = collectionContract.Kind;
                        if (kind == CollectionKind.GenericDictionary || kind == CollectionKind.GenericCollection || kind == CollectionKind.GenericEnumerable)
                        {
                            Type[] interfaceTypes = enumeratorType.GetInterfaces();
                            foreach (Type interfaceType in interfaceTypes)
                            {
                                if (interfaceType.IsGenericType &&
                                    interfaceType.GetGenericTypeDefinition() == Globals.TypeOfIEnumeratorGeneric &&
                                    interfaceType.GetGenericArguments()[0] == collectionContract.ItemType)
                                {
                                    ienumeratorInterface = interfaceType;
                                    break;
                                }
                            }
                        }
                        if (moveNextMethod == null)
                        {
                            moveNextMethod = CollectionDataContract.GetTargetMethodWithName(Globals.MoveNextMethodName, enumeratorType, ienumeratorInterface);
                        }
                        if (getCurrentMethod == null)
                        {
                            getCurrentMethod = CollectionDataContract.GetTargetMethodWithName(Globals.GetCurrentMethodName, enumeratorType, ienumeratorInterface);
                        }
                    }
                }
                Type   elementType  = getCurrentMethod.ReturnType;
                object currentValue = null;                 // of elementType

                var enumerator = (IEnumerator)collectionContract.GetEnumeratorMethod.Invoke(objLocal, new object [0]);
                if (isDictionary)
                {
                    ConstructorInfo dictEnumCtor = enumeratorType.GetConstructor(Globals.ScanAllMembers, null, new Type[] { Globals.TypeOfIDictionaryEnumerator }, null);
                    enumerator = (IEnumerator)dictEnumCtor.Invoke(new object [] { enumerator });
                }
                else if (isGenericDictionary)
                {
                    Type            ctorParam    = Globals.TypeOfIEnumeratorGeneric.MakeGenericType(Globals.TypeOfKeyValuePair.MakeGenericType(keyValueTypes));
                    ConstructorInfo dictEnumCtor = enumeratorType.GetConstructor(Globals.ScanAllMembers, null, new Type[] { ctorParam }, null);
                    enumerator = (IEnumerator)Activator.CreateInstance(enumeratorType, new object [] { enumerator });
                }

                bool canWriteSimpleDictionary = isDictionary || isGenericDictionary;

                bool         writeSimpleDictionary = canWriteSimpleDictionary && context.UseSimpleDictionaryFormat;
                PropertyInfo genericDictionaryKeyProperty = null, genericDictionaryValueProperty = null;

                if (canWriteSimpleDictionary)
                {
                    Type genericDictionaryKeyValueType = Globals.TypeOfKeyValue.MakeGenericType(keyValueTypes);
                    genericDictionaryKeyProperty   = genericDictionaryKeyValueType.GetProperty(JsonGlobals.KeyString);
                    genericDictionaryValueProperty = genericDictionaryKeyValueType.GetProperty(JsonGlobals.ValueString);
                }

                if (writeSimpleDictionary)
                {
                    WriteObjectAttribute();
                    object key, value;
                    var    empty_args = new object [0];
                    while ((bool)moveNextMethod.Invoke(enumerator, empty_args))
                    {
                        currentValue = getCurrentMethod.Invoke(enumerator, empty_args);
                        key          = CodeInterpreter.GetMember(genericDictionaryKeyProperty, currentValue);
                        value        = CodeInterpreter.GetMember(genericDictionaryValueProperty, currentValue);

                        WriteStartElement(key, 0 /*nameIndex*/);
                        WriteValue(genericDictionaryValueProperty.PropertyType, value);
                        WriteEndElement();
                    }
                }
                else
                {
                    WriteArrayAttribute();

                    var emptyArray = new object [0];
                    while (enumerator != null && enumerator.MoveNext())
                    {
                        currentValue = getCurrentMethod.Invoke(enumerator, emptyArray);

                        if (incrementCollectionCountMethod == null)
                        {
                            XmlFormatGeneratorStatics.IncrementItemCountMethod.Invoke(context, new object [] { 1 });
                        }

                        if (!TryWritePrimitive(elementType, () => currentValue, null, null, itemName, 0))
                        {
                            WriteStartElement(itemName, 0);
                            if (isGenericDictionary || isDictionary)
                            {
                                var jc = JsonDataContract.GetJsonDataContract(XmlObjectSerializerWriteContextComplexJson.GetRevisedItemContract(
                                                                                  collectionDataContract.ItemContract));
                                // FIXME: this TypeHandle might be wrong; there is no easy way to get Type for currentValue though.
                                DataContractJsonSerializer.WriteJsonValue(jc, writer, currentValue, context, currentValue.GetType().TypeHandle);
                            }
                            else
                            {
                                WriteValue(elementType, currentValue);
                            }
                            WriteEndElement();
                        }
                    }
                }
            }
        }
 object LoadMemberValue(DataMember member)
 {
     return(CodeInterpreter.GetMember(member.MemberInfo, objLocal));
 }
        void WriteValue(Type memberType, object memberValue)
        {
            Pointer memberValueRefPointer = null;

            if (memberType.IsPointer)
            {
                memberValueRefPointer = (Pointer)JsonFormatGeneratorStatics.BoxPointer.Invoke(null, new object [] { memberValue, memberType });
            }
            bool isNullableOfT = (memberType.IsGenericType &&
                                  memberType.GetGenericTypeDefinition() == Globals.TypeOfNullable);

            if (memberType.IsValueType && !isNullableOfT)
            {
                PrimitiveDataContract primitiveContract = PrimitiveDataContract.GetPrimitiveDataContract(memberType);
                if (primitiveContract != null)
                {
                    primitiveContract.XmlFormatContentWriterMethod.Invoke(writer, new object [] { memberValue });
                }
                else
                {
                    InternalSerialize(XmlFormatGeneratorStatics.InternalSerializeMethod, () => memberValue, memberType, false);
                }
            }
            else
            {
                bool isNull;
                if (isNullableOfT)
                {
                    memberValue = UnwrapNullableObject(() => memberValue, ref memberType, out isNull);                     //Leaves !HasValue on stack
                }
                else
                {
                    isNull = memberValue == null;
                }
                if (isNull)
                {
                    XmlFormatGeneratorStatics.WriteNullMethod.Invoke(context, new object [] { writer, memberType, DataContract.IsTypeSerializable(memberType) });
                }
                else
                {
                    PrimitiveDataContract primitiveContract = PrimitiveDataContract.GetPrimitiveDataContract(memberType);
                    if (primitiveContract != null && primitiveContract.UnderlyingType != Globals.TypeOfObject)
                    {
                        if (isNullableOfT)
                        {
                            primitiveContract.XmlFormatContentWriterMethod.Invoke(writer, new object [] { memberValue });
                        }
                        else
                        {
                            primitiveContract.XmlFormatContentWriterMethod.Invoke(context, new object [] { writer, memberValue });
                        }
                    }
                    else
                    {
                        bool isNull2 = false;
                        if (memberType == Globals.TypeOfObject ||                         //boxed Nullable<T>
                            memberType == Globals.TypeOfValueType ||
                            ((IList)Globals.TypeOfNullable.GetInterfaces()).Contains(memberType))
                        {
                            var unwrappedMemberValue = CodeInterpreter.ConvertValue(memberValue, memberType.GetType(), Globals.TypeOfObject);
                            memberValue = unwrappedMemberValue;
                            isNull2     = memberValue == null;
                        }
                        if (isNull2)
                        {
                            XmlFormatGeneratorStatics.WriteNullMethod.Invoke(context, new object [] { writer, memberType, DataContract.IsTypeSerializable(memberType) });
                        }
                        else
                        {
                            InternalSerialize((isNullableOfT ? XmlFormatGeneratorStatics.InternalSerializeMethod : XmlFormatGeneratorStatics.InternalSerializeReferenceMethod),
                                              () => memberValue, memberType, false);
                        }
                    }
                }
            }
        }