Пример #1
0
 public ushort[] Assemble(AssemblyContext ctx)
 {
     if (literal > maxDirectValue)
         return new ushort[] { literal };
     else
         return new ushort[] { };
 }
Пример #2
0
 public ushort[] Assemble(AssemblyContext ctx)
 {
     if (displacement == null)
         return new ushort[] { };
     else
         return displacement.Assemble(ctx);
 }
 public TinyMCECodeGenerator()
 {
     Context = new AssemblyContext();
     Assembly = new Assembly
     {
         Usings = new List<string> 
             { 
                 "System",
                 "System.Collections.Generic",
             }
     };
     Context.Assemblies.Add(Assembly);
     var asm = new Assembly
     {
         Classes = new List<Class>
         {
             new Class{Name="void"},
             new Class{Name="object"},
             new Class{Name="bool"},
             new Class{Name="string"},
             new Class{Name="Array"},
             new Class{Name="int"},
             new Class{Name="Function", IsDelegate=true},
         }
     };
     Context.Assemblies.Add(asm);
     ObjectClass = Context.GetClass("object");
 }
Пример #4
0
        public ushort[] Assemble(AssemblyContext ctx)
        {
            var instructionWord = (int)operation << 4;
            instructionWord |= (argument.DirectAssemble() << 10);

            return new[] { (ushort)instructionWord }.Concat(argument.Assemble(ctx)).ToArray();
        }
Пример #5
0
        public ushort[] Assemble(AssemblyContext ctx)
        {
            var instructionWord = (int)operation;
            instructionWord |= (destination.DirectAssemble() << 4);
            instructionWord |= (source.DirectAssemble() << 10);

            return new[] { (ushort)instructionWord }.Concat(destination.Assemble(ctx)).Concat(source.Assemble(ctx)).ToArray();
        }
Пример #6
0
 public ushort[] Assemble(AssemblyContext ctx)
 {
     try
     {
         return new[]{ctx.FullyResolvedLabels
         .Where(label => label.Name == symbol)
         .Where(label => label.Address.Absolute)
         .Select(label => label.Address.Pointer)
         .Single()};
     }
     catch (InvalidOperationException ioe)
     {
         throw new FormatException("label not found: " + symbol, ioe);
     }
 }
Пример #7
0
 internal void Copmile(AssemblyContext ctx)
 {
     foreach (var i in _template)
     {
         i.Emit(ctx);
     }
 }
Пример #8
0
 public ushort[] Assemble(AssemblyContext ctx)
 {
     return new ushort[] { pointer };
 }
Пример #9
0
 public void Assemble(ValueModel source, AssemblyContext context)
 {
     TileType = (source as PrimitiveModel).ToObject <string>();
 }
Пример #10
0
        public void HashCode()
        {
            // Verify that GetHashCode() works.

            var settings = new ModelGeneratorSettings()
            {
                SourceNamespace = typeof(Test_UxDataModel).Namespace,
                UxFramework     = UxFrameworks.Xaml
            };

            var generator = new ModelGenerator(settings);
            var output    = generator.Generate(Assembly.GetExecutingAssembly());

            Assert.False(output.HasErrors);

            var assemblyStream = ModelGenerator.Compile(output.SourceCode, "test-assembly", references => ModelGenTestHelper.ReferenceHandler(references));

            using (var context = new AssemblyContext("Neon.ModelGen.Output", assemblyStream))
            {
                // Verify that we see a [InvalidOperationException] when computing a hash
                // on a data model with no properties tagged by [HashSource].

                var emptyData = context.CreateDataWrapper <EmptyData>();

                Assert.Throws <InvalidOperationException>(() => emptyData.GetHashCode());

                // Verify that we compute HASH=0 for a data model with a
                // single tagged parameter set to NULL.

                var baseData = context.CreateDataWrapper <BaseModel>();

                Assert.Equal(0, baseData.GetHashCode());

                // Verify that we compute a non-zero HASH for a data model with a
                // single tagged parameter set to to a value.

                baseData = context.CreateDataWrapper <BaseModel>();
                baseData["ParentProperty"] = "Hello World!";
                Assert.NotEqual(0, baseData.GetHashCode());

                // Verify that we can compute a HASH code for a derived class
                // and that the hash includes properties from both the derived
                // and parent classes.

                var derivedData = context.CreateDataWrapper <DerivedModel>();
                derivedData["ChildProperty"] = "Goodbye World!";
                var derivedCode1 = derivedData.GetHashCode();
                Assert.NotEqual(0, derivedCode1);

                derivedData["ParentProperty"] = "Hello World!";
                var derivedCode2 = derivedData.GetHashCode();
                Assert.NotEqual(0, derivedCode2);
                Assert.NotEqual(derivedCode1, derivedCode2);

                // Verify that we can compute hash codes for models
                // with multiple hash source properties.

                var defaultValues = context.CreateDataWrapper <DefaultValues>();

                defaultValues["Name"] = null;
                defaultValues["Age"]  = 0;
                Assert.Equal(0, defaultValues.GetHashCode());

                defaultValues["Name"] = "JoeBob";
                defaultValues["Age"]  = 0;
                Assert.Equal("JoeBob".GetHashCode(), defaultValues.GetHashCode());

                defaultValues["Name"] = null;
                defaultValues["Age"]  = 67;
                Assert.Equal(67.GetHashCode(), defaultValues.GetHashCode());

                defaultValues["Name"] = "JoeBob";
                defaultValues["Age"]  = 67;
                Assert.Equal(67.GetHashCode() ^ "JoeBob".GetHashCode(), defaultValues.GetHashCode());
            }
        }
Пример #11
0
        public void Correctly_returns_version_info()
        {
            IAssemblyContext context = new AssemblyContext();

            Assert.That(context.GetAssemblyVersion().StartsWith("1."));
        }
Пример #12
0
        public void Simple()
        {
            // Verify that we can generate code for a simple data model.

            var settings = new ModelGeneratorSettings()
            {
                SourceNamespace = typeof(Test_UxDataModel).Namespace,
                UxFramework     = UxFrameworks.Xaml
            };

            var generator = new ModelGenerator(settings);
            var output    = generator.Generate(Assembly.GetExecutingAssembly());

            Assert.False(output.HasErrors);

            var assemblyStream = ModelGenerator.Compile(output.SourceCode, "test-assembly", references => ModelGenTestHelper.ReferenceHandler(references));

            using (var context = new AssemblyContext("Neon.ModelGen.Output", assemblyStream))
            {
                var data = context.CreateDataWrapper <SimpleData>();
                Assert.Equal("{\"Name\":null,\"Age\":0,\"Enum\":\"One\"}", data.ToString());
                Assert.Equal("{\r\n  \"Name\": null,\r\n  \"Age\": 0,\r\n  \"Enum\": \"One\"\r\n}", data.ToString(indented: true));

                data         = context.CreateDataWrapper <SimpleData>();
                data["Name"] = "Jeff";
                data["Age"]  = 58;
                data["Enum"] = MyEnum1.Two;
                Assert.Equal("{\"Name\":\"Jeff\",\"Age\":58,\"Enum\":\"Two\"}", data.ToString());

                data         = context.CreateDataWrapperFrom <SimpleData>("{\"Name\":\"Jeff\",\"Age\":58,\"Enum\":\"Two\"}");
                data["Name"] = "Jeff";
                data["Age"]  = 58;
                data["Enum"] = MyEnum1.Two;
                Assert.Equal("{\"Name\":\"Jeff\",\"Age\":58,\"Enum\":\"Two\"}", data.ToString());

                var jObject = data.ToJObject();
                data         = context.CreateDataWrapperFrom <SimpleData>(jObject);
                data["Name"] = "Jeff";
                data["Age"]  = 58;
                data["Enum"] = MyEnum1.Two;
                Assert.Equal("{\"Name\":\"Jeff\",\"Age\":58,\"Enum\":\"Two\"}", data.ToString());

                var jsonText = data.ToString(indented: false);
                data         = context.CreateDataWrapperFrom <SimpleData>(jsonText);
                data["Name"] = "Jeff";
                data["Age"]  = 58;
                data["Enum"] = MyEnum1.Two;
                Assert.Equal("{\"Name\":\"Jeff\",\"Age\":58,\"Enum\":\"Two\"}", data.ToString());

                jsonText     = data.ToString(indented: true);
                data         = context.CreateDataWrapperFrom <SimpleData>(jsonText);
                data["Name"] = "Jeff";
                data["Age"]  = 58;
                data["Enum"] = MyEnum1.Two;
                Assert.Equal("{\"Name\":\"Jeff\",\"Age\":58,\"Enum\":\"Two\"}", data.ToString());

                //-------------------------------------------------------------
                // Verify Equals():

                var value1 = context.CreateDataWrapperFrom <SimpleData>("{\"Name\":\"Jeff\",\"Age\":58,\"Enum\":\"Two\"}");
                var value2 = context.CreateDataWrapperFrom <SimpleData>("{\"Name\":\"Jeff\",\"Age\":58,\"Enum\":\"Two\"}");

                Assert.True(value1.Equals(value1));
                Assert.True(value1.Equals(value2));
                Assert.True(value2.Equals(value1));

                Assert.False(value1.Equals(null));
                Assert.False(value1.Equals("Hello World!"));

                value2["Name"] = "Bob";

                Assert.True(value1.Equals(value1));

                Assert.False(value1.Equals(value2));
                Assert.False(value2.Equals(value1));
                Assert.False(value1.Equals(null));
                Assert.False(value1.Equals("Hello World!"));

                //-------------------------------------------------------------
                // Verify FromBytes() and ToBytes()

                var newValue1 = context.CreateDataWrapperFrom <SimpleData>(value1.ToBytes());
                var newValue2 = context.CreateDataWrapperFrom <SimpleData>(value2.ToBytes());

                Assert.True(value1.Equals(newValue1));
                Assert.True(value2.Equals(newValue2));
            }
        }
Пример #13
0
        public void Complex()
        {
            // Verify that we can generate code for complex data types.

            var settings = new ModelGeneratorSettings()
            {
                SourceNamespace = typeof(Test_UxDataModel).Namespace,
                UxFramework     = UxFrameworks.Xaml
            };

            var generator = new ModelGenerator(settings);
            var output    = generator.Generate(Assembly.GetExecutingAssembly());

            Assert.False(output.HasErrors);

            var assemblyStream = ModelGenerator.Compile(output.SourceCode, "test-assembly", references => ModelGenTestHelper.ReferenceHandler(references));

            using (var context = new AssemblyContext("Neon.ModelGen.Output", assemblyStream))
            {
                var data = context.CreateDataWrapper <ComplexData>();

                // This is going to throw a serialization exception because 0 is not a valid
                // [Enum2] orginal value, but that's what it will be initially set to because
                // we didn't use [DefaultValue].

                Assert.Throws <SerializationException>(() => data.ToString());

                // Set a valid [Enum2] Value and test again.

                data["Enum2"] = MyEnum2.Three;
                Assert.Equal("{\"List\":null,\"Dictionary\":null,\"Enum1\":\"One\",\"Enum2\":\"three\",\"Simple\":null,\"SingleArray\":null,\"DoubleArray\":null}", data.ToString());

                // Initialize the list and verify.

                data["List"] = new ObservableCollection <string>()
                {
                    "item0", "item1"
                };

                Assert.Equal("{\"List\":[\"item0\",\"item1\"],\"Dictionary\":null,\"Enum1\":\"One\",\"Enum2\":\"three\",\"Simple\":null,\"SingleArray\":null,\"DoubleArray\":null}", data.ToString());

                // Initialize the dictionary and verify.

                data["Dictionary"] = new Dictionary <string, int>()
                {
                    { "zero", 0 },
                    { "one", 1 }
                };

                Assert.Equal("{\"List\":[\"item0\",\"item1\"],\"Dictionary\":{\"zero\":0,\"one\":1},\"Enum1\":\"One\",\"Enum2\":\"three\",\"Simple\":null,\"SingleArray\":null,\"DoubleArray\":null}", data.ToString());

                // Initialize the one dimensional array and verify.

                data["SingleArray"] = new int[] { 100, 200 };
                Assert.Equal("{\"List\":[\"item0\",\"item1\"],\"Dictionary\":{\"zero\":0,\"one\":1},\"Enum1\":\"One\",\"Enum2\":\"three\",\"Simple\":null,\"SingleArray\":[100,200],\"DoubleArray\":null}", data.ToString());

                // Initialize the two dimensional array and verify.

                data["DoubleArray"] = new int[][]
                {
                    new int[] { 100, 200 },
                    new int[] { 300, 400 }
                };

                Assert.Equal("{\"List\":[\"item0\",\"item1\"],\"Dictionary\":{\"zero\":0,\"one\":1},\"Enum1\":\"One\",\"Enum2\":\"three\",\"Simple\":null,\"SingleArray\":[100,200],\"DoubleArray\":[[100,200],[300,400]]}", data.ToString());

                // Verify that a property with [JsonIgnore] is not persisted.

                data["IgnoreThis"] = 1000;
                Assert.DoesNotContain("IgnoreThis", data.ToString());

                //-------------------------------------------------------------
                // Verify Equals():

                var value1 = context.CreateDataWrapperFrom <ComplexData>("{\"List\":[\"zero\"],\"Dictionary\":null,\"Enum1\":\"One\",\"Enum2\":\"three\",\"Simple\":null,\"SingleArray\":null,\"DoubleArray\":null}");
                var value2 = context.CreateDataWrapperFrom <ComplexData>("{\"List\":[\"zero\"],\"Dictionary\":null,\"Enum1\":\"One\",\"Enum2\":\"three\",\"Simple\":null,\"SingleArray\":null,\"DoubleArray\":null}");

                Assert.True(value1.Equals(value1));
                Assert.True(value1.Equals(value2));
                Assert.True(value2.Equals(value1));

                Assert.False(value1.Equals(null));
                Assert.False(value1.Equals("Hello World!"));

                value2 = context.CreateDataWrapperFrom <ComplexData>("{\"List\":[\"NOT-ZERO\"],\"Dictionary\":null,\"Enum1\":\"One\",\"Enum2\":\"three\",\"Simple\":null,\"SingleArray\":null,\"DoubleArray\":null}");

                Assert.True(value1.Equals(value1));

                Assert.False(value1.Equals(value2));
                Assert.False(value2.Equals(value1));
                Assert.False(value1.Equals(null));
                Assert.False(value1.Equals("Hello World!"));
            }
        }
Пример #14
0
        private string FlushCodeToDisk(CustomAttributeDeclaration[] assemblyAttributes, AssemblyContext assemblyContext)
        {
            var assemblyPath = assemblyContext.GeneratedCodeFlusher.FlushCodeToDisk(assemblyAttributes);

            assemblyContext.ResetParticipantState();
            return(assemblyPath);
        }
Пример #15
0
 public ushort[] Assemble(AssemblyContext ctx)
 {
     return characters
         .Select(c => (ushort)c)
         .ToArray();
 }
Пример #16
0
 public SqlSerialization()
 {
     asm = new AssemblyContext();
 }
Пример #17
0
        public void FlushCodeToDisk_FlushesMultipleAssemblies_ReturnsNonNullResultPaths()
        {
            var assemblyAttribute = CustomAttributeDeclarationObjectMother.Create();

            var generatedCodeFlusherMock1 = MockRepository.GenerateStrictMock <IGeneratedCodeFlusher>();
            var assemblyContext1          = new AssemblyContext(MockRepository.GenerateStrictMock <IMutableTypeBatchCodeGenerator>(), generatedCodeFlusherMock1);
            var participantState1         = assemblyContext1.ParticipantState;

            var generatedCodeFlusherMock2 = MockRepository.GenerateStrictMock <IGeneratedCodeFlusher>();
            var assemblyContext2          = new AssemblyContext(MockRepository.GenerateStrictMock <IMutableTypeBatchCodeGenerator>(), generatedCodeFlusherMock2);
            var participantState2         = assemblyContext2.ParticipantState;

            var generatedCodeFlusherMock3 = MockRepository.GenerateStrictMock <IGeneratedCodeFlusher>();
            var assemblyContext3          = new AssemblyContext(MockRepository.GenerateStrictMock <IMutableTypeBatchCodeGenerator>(), generatedCodeFlusherMock3);
            var participantState3         = assemblyContext3.ParticipantState;

            bool isDequeued = false;

            _assemblyContextPool
            .Expect(mock => mock.DequeueAll())
            .Return(new[] { assemblyContext1, assemblyContext2, assemblyContext3 })
            .WhenCalled(mi => { isDequeued = true; });

            bool isFlushed1 = false;

            generatedCodeFlusherMock1
            .Expect(mock => mock.FlushCodeToDisk(Arg <IEnumerable <CustomAttributeDeclaration> > .Is.Anything))
            .Return("path1")
            .WhenCalled(
                mi =>
            {
                Assert.That(isDequeued, Is.True);
                isFlushed1 = true;
            });

            bool isFlushed2 = false;

            generatedCodeFlusherMock2
            .Expect(mock => mock.FlushCodeToDisk(Arg <IEnumerable <CustomAttributeDeclaration> > .Is.Anything))
            .Return(null)
            .WhenCalled(
                mi =>
            {
                Assert.That(isDequeued, Is.True);
                isFlushed2 = true;
            });

            bool isFlushed3 = false;

            generatedCodeFlusherMock3
            .Expect(mock => mock.FlushCodeToDisk(Arg <IEnumerable <CustomAttributeDeclaration> > .Is.Anything))
            .Return("path3")
            .WhenCalled(
                mi =>
            {
                Assert.That(isDequeued, Is.True);
                isFlushed3 = true;
            });

            _assemblyContextPool
            .Expect(mock => mock.Enqueue(assemblyContext1))
            .WhenCalled(
                mi =>
            {
                Assert.That(isFlushed1, Is.True);
                Assert.That(assemblyContext1.ParticipantState, Is.Not.SameAs(participantState1));
            });

            _assemblyContextPool
            .Expect(mock => mock.Enqueue(assemblyContext2))
            .WhenCalled(
                mi =>
            {
                Assert.That(isFlushed2, Is.True);
                Assert.That(assemblyContext2.ParticipantState, Is.Not.SameAs(participantState2));
            });

            _assemblyContextPool
            .Expect(mock => mock.Enqueue(assemblyContext3))
            .WhenCalled(
                mi =>
            {
                Assert.That(isFlushed3, Is.True);
                Assert.That(assemblyContext3.ParticipantState, Is.Not.SameAs(participantState3));
            });

            var result = _manager.FlushCodeToDisk(new[] { assemblyAttribute });

            _assemblyContextPool.VerifyAllExpectations();
            generatedCodeFlusherMock1.VerifyAllExpectations();
            generatedCodeFlusherMock2.VerifyAllExpectations();
            generatedCodeFlusherMock3.VerifyAllExpectations();

            Assert.That(result, Is.EquivalentTo(new[] { "path1", "path3" }));
        }
        public override void Assemble(object obj, IAssignableMemberInfo member, ValueModel model, Type expectedType, AssemblyContext context)
        {
            if (!ValueModel.IsNull(model))
            {
                if (model is PathModel pathModel)
                {
                    UnityEngine.Object value = (UnityEngine.Object)SerializationFileAccess.LoadObjectFromFile(pathModel.Path, expectedType);

                    member.SetValue(obj, value);
                    return;
                }
                throw new InvalidOperationException(nameof(model) + " must be a " + nameof(PathModel));
            }
        }
Пример #19
0
        public void FlushCodeToDisk_FlushesMultipleAssemblies_ReturnsNonNullResultPaths()
        {
            var assemblyAttribute = CustomAttributeDeclarationObjectMother.Create();

            var generatedCodeFlusherMock1 = new Mock <IGeneratedCodeFlusher> (MockBehavior.Strict);
            var assemblyContext1          = new AssemblyContext(new Mock <IMutableTypeBatchCodeGenerator> (MockBehavior.Strict).Object, generatedCodeFlusherMock1.Object);
            var participantState1         = assemblyContext1.ParticipantState;

            var generatedCodeFlusherMock2 = new Mock <IGeneratedCodeFlusher> (MockBehavior.Strict);
            var assemblyContext2          = new AssemblyContext(new Mock <IMutableTypeBatchCodeGenerator> (MockBehavior.Strict).Object, generatedCodeFlusherMock2.Object);
            var participantState2         = assemblyContext2.ParticipantState;

            var generatedCodeFlusherMock3 = new Mock <IGeneratedCodeFlusher> (MockBehavior.Strict);
            var assemblyContext3          = new AssemblyContext(new Mock <IMutableTypeBatchCodeGenerator> (MockBehavior.Strict).Object, generatedCodeFlusherMock3.Object);
            var participantState3         = assemblyContext3.ParticipantState;

            var isDequeued = false;

            _assemblyContextPool
            .Setup(mock => mock.DequeueAll())
            .Returns(new[] { assemblyContext1, assemblyContext2, assemblyContext3 })
            .Callback(() => { isDequeued = true; })
            .Verifiable();

            var isFlushed1 = false;

            generatedCodeFlusherMock1
            .Setup(mock => mock.FlushCodeToDisk(It.IsAny <IEnumerable <CustomAttributeDeclaration> >()))
            .Returns("path1")
            .Callback(
                (IEnumerable <CustomAttributeDeclaration> assemblyAttributes) =>
            {
                Assert.That(isDequeued, Is.True);
                isFlushed1 = true;
            })
            .Verifiable();

            var isFlushed2 = false;

            generatedCodeFlusherMock2
            .Setup(mock => mock.FlushCodeToDisk(It.IsAny <IEnumerable <CustomAttributeDeclaration> >()))
            .Returns((string)null)
            .Callback(
                (IEnumerable <CustomAttributeDeclaration> assemblyAttributes) =>
            {
                Assert.That(isDequeued, Is.True);
                isFlushed2 = true;
            })
            .Verifiable();

            var isFlushed3 = false;

            generatedCodeFlusherMock3
            .Setup(mock => mock.FlushCodeToDisk(It.IsAny <IEnumerable <CustomAttributeDeclaration> >()))
            .Returns("path3")
            .Callback(
                (IEnumerable <CustomAttributeDeclaration> assemblyAttributes) =>
            {
                Assert.That(isDequeued, Is.True);
                isFlushed3 = true;
            })
            .Verifiable();

            _assemblyContextPool
            .Setup(mock => mock.Enqueue(assemblyContext1))
            .Callback(
                (AssemblyContext _) =>
            {
                Assert.That(isFlushed1, Is.True);
                Assert.That(assemblyContext1.ParticipantState, Is.Not.SameAs(participantState1));
            })
            .Verifiable();

            _assemblyContextPool
            .Setup(mock => mock.Enqueue(assemblyContext2))
            .Callback(
                (AssemblyContext assemblyContext) =>
            {
                Assert.That(isFlushed2, Is.True);
                Assert.That(assemblyContext2.ParticipantState, Is.Not.SameAs(participantState2));
            })
            .Verifiable();

            _assemblyContextPool
            .Setup(mock => mock.Enqueue(assemblyContext3))
            .Callback(
                (AssemblyContext assemblyContext) =>
            {
                Assert.That(isFlushed3, Is.True);
                Assert.That(assemblyContext3.ParticipantState, Is.Not.SameAs(participantState3));
            })
            .Verifiable();

            var result = _manager.FlushCodeToDisk(new[] { assemblyAttribute });

            _assemblyContextPool.Verify();
            generatedCodeFlusherMock1.Verify();
            generatedCodeFlusherMock2.Verify();
            generatedCodeFlusherMock3.Verify();

            Assert.That(result, Is.EquivalentTo(new[] { "path1", "path3" }));
        }
Пример #20
0
 private void CloseAssemblyContext()
 {
     _currentAssemblyContext = null;
 }
 public abstract void Assemble(ObjectModel model, T target, AssemblyContext context);
Пример #22
0
 public abstract void Emit(AssemblyContext c);
Пример #23
0
 public ushort[] Assemble(AssemblyContext ctx)
 {
     return new[] { literal };
 }
Пример #24
0
 private TestCollection(IEnumerable <string> sources, AssemblyContext assemblyContext, IEnumerable <Test> tests)
 {
     _assemblyContext = assemblyContext;
     Sources          = ImmutableArray.CreateRange(sources);
     Tests            = ImmutableArray.CreateRange(tests);
 }
Пример #25
0
        public void BasicTypes()
        {
            // Verify that we can generate code for basic data types.

            var settings = new ModelGeneratorSettings()
            {
                SourceNamespace = typeof(Test_UxDataModel).Namespace,
                UxFramework     = UxFrameworks.Xaml
            };

            var generator = new ModelGenerator(settings);
            var output    = generator.Generate(Assembly.GetExecutingAssembly());

            Assert.False(output.HasErrors);

            var assemblyStream = ModelGenerator.Compile(output.SourceCode, "test-assembly", references => ModelGenTestHelper.ReferenceHandler(references));

            using (var context = new AssemblyContext("Neon.ModelGen.Output", assemblyStream))
            {
                var data = context.CreateDataWrapper <BasicTypes>();
                Assert.Equal("{\"Bool\":false,\"Byte\":0,\"SByte\":0,\"Short\":0,\"UShort\":0,\"Int\":0,\"UInt\":0,\"Long\":0,\"ULong\":0,\"Float\":0.0,\"Double\":0.0,\"Decimal\":0.0,\"String\":null}", data.ToString());

                data["Bool"]    = true;
                data["Byte"]    = (byte)1;
                data["SByte"]   = (sbyte)2;
                data["Short"]   = (short)3;
                data["UShort"]  = (ushort)4;
                data["Int"]     = (int)5;
                data["UInt"]    = (uint)6;
                data["Long"]    = (long)7;
                data["ULong"]   = (ulong)8;
                data["Float"]   = (float)9;
                data["Double"]  = (double)10;
                data["Decimal"] = (decimal)11;
                data["String"]  = "12";

                Assert.Equal("{\"Bool\":true,\"Byte\":1,\"SByte\":2,\"Short\":3,\"UShort\":4,\"Int\":5,\"UInt\":6,\"Long\":7,\"ULong\":8,\"Float\":9.0,\"Double\":10.0,\"Decimal\":11.0,\"String\":\"12\"}", data.ToString());

                var jsonText = data.ToString(indented: false);
                data = context.CreateDataWrapperFrom <BasicTypes>(jsonText);
                Assert.Equal("{\"Bool\":true,\"Byte\":1,\"SByte\":2,\"Short\":3,\"UShort\":4,\"Int\":5,\"UInt\":6,\"Long\":7,\"ULong\":8,\"Float\":9.0,\"Double\":10.0,\"Decimal\":11.0,\"String\":\"12\"}", data.ToString());

                jsonText = data.ToString(indented: true);
                data     = context.CreateDataWrapperFrom <BasicTypes>(jsonText);
                Assert.Equal("{\"Bool\":true,\"Byte\":1,\"SByte\":2,\"Short\":3,\"UShort\":4,\"Int\":5,\"UInt\":6,\"Long\":7,\"ULong\":8,\"Float\":9.0,\"Double\":10.0,\"Decimal\":11.0,\"String\":\"12\"}", data.ToString());

                //-------------------------------------------------------------
                // Verify Equals():

                var value1 = context.CreateDataWrapperFrom <BasicTypes>("{\"Bool\":true,\"Byte\":1,\"SByte\":2,\"Short\":3,\"UShort\":4,\"Int\":5,\"UInt\":6,\"Long\":7,\"ULong\":8,\"Float\":9.0,\"Double\":10.0,\"Decimal\":11.0,\"String\":\"12\"}");
                var value2 = context.CreateDataWrapperFrom <BasicTypes>("{\"Bool\":true,\"Byte\":1,\"SByte\":2,\"Short\":3,\"UShort\":4,\"Int\":5,\"UInt\":6,\"Long\":7,\"ULong\":8,\"Float\":9.0,\"Double\":10.0,\"Decimal\":11.0,\"String\":\"12\"}");

                Assert.True(value1.Equals(value1));
                Assert.True(value1.Equals(value2));
                Assert.True(value2.Equals(value1));

                Assert.False(value1.Equals(null));
                Assert.False(value1.Equals("Hello World!"));

                value2["String"] = "Bob";

                Assert.True(value1.Equals(value1));

                Assert.False(value1.Equals(value2));
                Assert.False(value2.Equals(value1));
                Assert.False(value1.Equals(null));
                Assert.False(value1.Equals("Hello World!"));
            }
        }
Пример #26
0
 public IAssemblyContext OpenAssemblyContext(string filename)
 {
     if (_currentAssemblyContext != null) {
         throw new InvalidOperationException("There's already an AssemblyContext open");
     }
     _currentAssemblyContext = new AssemblyContext(filename, _collectViolations, CloseAssemblyContext);
     _assemblyContexts.Add(_currentAssemblyContext);
     return _currentAssemblyContext;
 }
Пример #27
0
        public void SerializationDefaults()
        {
            // Verify that we honor the [JsonProperty(DefaultValueHandling)] options.

            var settings = new ModelGeneratorSettings()
            {
                SourceNamespace = typeof(Test_UxDataModel).Namespace,
                UxFramework     = UxFrameworks.Xaml
            };

            var generator = new ModelGenerator(settings);
            var output    = generator.Generate(Assembly.GetExecutingAssembly());

            Assert.False(output.HasErrors);

            var assemblyStream = ModelGenerator.Compile(output.SourceCode, "test-assembly", references => ModelGenTestHelper.ReferenceHandler(references));

            using (var context = new AssemblyContext("Neon.ModelGen.Output", assemblyStream))
            {
                var data = context.CreateDataWrapper <SerializationDefaultsModel>();

                // Verify that the instance starts out with the correct
                // default property values.

                Assert.Equal("Ignore", data["Ignore"]);
                Assert.Equal("IgnoreAndPopulate", data["IgnoreAndPopulate"]);
                Assert.Equal("Include", data["Include"]);
                Assert.Equal("Populate", data["Populate"]);

                // Verify that we get the same output when serializing
                // the same data multple times (this wasn't working
                // early on).

                var serialized = data.ToString();

                Assert.Equal(serialized, data.ToString());
                Assert.Equal(serialized, data.ToString());

                // Verify that defaults serialize correctly.

                Assert.Equal("{\"Include\":\"Include\",\"Populate\":\"Populate\"}", data.ToString());

                // Verify that defaults deserialize correctly.

                data = context.CreateDataWrapper <SerializationDefaultsModel>();
                data = context.CreateDataWrapperFrom <SerializationDefaultsModel>(data.ToString());

                Assert.Equal("Ignore", data["Ignore"]);
                Assert.Equal("IgnoreAndPopulate", data["IgnoreAndPopulate"]);
                Assert.Equal("Include", data["Include"]);
                Assert.Equal("Populate", data["Populate"]);

                // Verify that non-default values serialize/desearlize correctly.

                data = context.CreateDataWrapper <SerializationDefaultsModel>();

                data["Ignore"]            = "NotIgnore";
                data["IgnoreAndPopulate"] = "NotIgnoreAndPopulate";
                data["Include"]           = "NotInclude";
                data["Populate"]          = "NotPopulate";

                Assert.Equal("{\"Ignore\":\"NotIgnore\",\"IgnoreAndPopulate\":\"NotIgnoreAndPopulate\",\"Include\":\"NotInclude\",\"Populate\":\"NotPopulate\"}", data.ToString());

                data = context.CreateDataWrapperFrom <SerializationDefaultsModel>(data.ToString());
                Assert.Equal("{\"Ignore\":\"NotIgnore\",\"IgnoreAndPopulate\":\"NotIgnoreAndPopulate\",\"Include\":\"NotInclude\",\"Populate\":\"NotPopulate\"}", data.ToString());

                Assert.Equal("NotIgnore", data["Ignore"]);
                Assert.Equal("NotIgnoreAndPopulate", data["IgnoreAndPopulate"]);
                Assert.Equal("NotInclude", data["Include"]);
                Assert.Equal("NotPopulate", data["Populate"]);
            }
        }
Пример #28
0
 public override void Emit(AssemblyContext c)
 {
     var l = c.Generator.DeclareLocal(LocalType);
     c.Locals[Id] = l;
 }
Пример #29
0
 public SQLDeserialization()
 {
     asmMetadata = new AssemblyMetadata();
     asm         = new AssemblyContext();
 }
Пример #30
0
 public override void Emit(AssemblyContext c)
 {
     c.Generator.Emit(OpCode, Arg);
 }
Пример #31
0
        public virtual string[] GetReferencedFileNames(ConfigurationSelector configuration)
        {
            string s = GetReferencedFileName(configuration);

            /*		if (referenceType == ReferenceType.Package) {
             *                      List<string> result = new List<string> ();
             *                      result.Add (s);
             *                      AddRequiredPackages (result, Package);
             *                      return result.ToArray ();
             *              }*/

            if (s != null)
            {
                return new string[] { s }
            }
            ;
            return(new string [0]);
        }

        /*
         * void AddRequiredPackages (List<string> result, SystemPackage fromPackage)
         * {
         *      if (fromPackage == null || string.IsNullOrEmpty (fromPackage.Requires))
         *              return;
         *      foreach (string requiredPackageName in fromPackage.Requires.Split (' ')) {
         *              SystemPackage package = AssemblyContext.GetPackage (requiredPackageName);
         *              if (package == null)
         *                      continue;
         *              foreach (SystemAssembly assembly in package.Assemblies) {
         *                      if (assembly == null)
         *                              continue;
         *                      string location = AssemblyContext.GetAssemblyLocation (assembly.FullName, ownerProject != null ? ownerProject.TargetFramework : null);
         *                      result.Add (location);
         *              }
         *              AddRequiredPackages (result, package);
         *      }
         * }*/

        void UpdatePackageReference()
        {
            if (referenceType == ReferenceType.Package && ownerProject != null)
            {
                notFound = false;

                string cref = AssemblyContext.FindInstalledAssembly(reference, package, ownerProject.TargetFramework);
                if (cref == null)
                {
                    cref = reference;
                }
                cref     = AssemblyContext.GetAssemblyNameForVersion(cref, package, ownerProject.TargetFramework);
                notFound = (cref == null);
                if (cref != null && cref != reference)
                {
                    SystemAssembly asm = AssemblyContext.GetAssemblyFromFullName(cref, package, ownerProject.TargetFramework);
                    bool           isFrameworkAssembly = asm != null && asm.Package.IsFrameworkPackage;
                    if (loadedReference == null && !isFrameworkAssembly)
                    {
                        loadedReference = reference;
                    }
                    reference = cref;
                }
                cachedPackage = null;

                SystemPackage pkg = Package;
                if (pkg != null && pkg.IsFrameworkPackage)
                {
                    int i = Include.IndexOf(',');
                    if (i != -1)
                    {
                        Include = Include.Substring(0, i).Trim();
                    }
                }

                OnStatusChanged();
            }
        }

        IAssemblyContext AssemblyContext {
            get {
                if (ownerProject != null)
                {
                    return(ownerProject.AssemblyContext);
                }
                else
                {
                    return(Runtime.SystemAssemblyService.DefaultAssemblyContext);
                }
            }
        }

        TargetRuntime TargetRuntime {
            get {
                if (ownerProject != null)
                {
                    return(ownerProject.TargetRuntime);
                }
                else
                {
                    return(Runtime.SystemAssemblyService.DefaultRuntime);
                }
            }
        }

        TargetFramework TargetFramework {
            get {
                if (ownerProject != null)
                {
                    return(ownerProject.TargetFramework);
                }
                else
                {
                    return(null);
                }
            }
        }
 public void Assemble(ObjectModel model, Component target, AssemblyContext context)
 => Assemble(model, target as T, context);
Пример #33
0
 public override void Assemble(ObjectModel model, Rigidbody2D target, AssemblyContext context)
 {
     target.bodyType = model.GetValue <RigidbodyType2D>("BodyType");
 }
Пример #34
0
 public ErrorList Compile(Assembly a)
 {
     var e = new ErrorList();
     try
     {
         _template = new DynamicMethod(
             string.Format("__template_{0}", Name),
             typeof (void),
             new[] {typeof (VirtualTemplate)},
             typeof (VirtualTemplate),
             true);
         var ctx = new AssemblyContext {Generator = _template.GetILGenerator()};
         a.Copmile(ctx);
         _image = (RunTemplate) _template.CreateDelegate(typeof (RunTemplate));
         Assembly = new Assembly(a);
     }
     catch (Exception ex)
     {
         e.ErrorUnhandledCompileError(ex);
     }
     return e;
 }
Пример #35
0
 private void CloseAssemblyContext()
 {
     _currentAssemblyContext = null;
 }
Пример #36
0
        private Assembly Load(string name)
        {
            var assembly = AssemblyContext.LoadFromAssemblyName(new AssemblyName(name));

            return(HandleLoadedAssembly(assembly));
        }
Пример #37
0
 public override void Emit(AssemblyContext c)
 {
     c.Generator.Emit(OpCode, c.Labels[Id]);
 }
Пример #38
0
        /// <summary>
        /// Load assembly by name object<br/>
        /// 根据名称对象加载程序集<br/>
        /// </summary>
        private Assembly Load(AssemblyName assemblyName)
        {
            var assembly = AssemblyContext.LoadFromAssemblyName(assemblyName);

            return(HandleLoadedAssembly(assembly));
        }
Пример #39
0
 public override void Emit(AssemblyContext c)
 {
     var label = c.Generator.DefineLabel();
     c.Labels[Id] = label;
 }
Пример #40
0
 public override void Assemble(AssemblyContext context)
 {
     throw new System.NotImplementedException();
 }
Пример #41
0
 public override void Emit(AssemblyContext c)
 {
     var l = c.Labels[Id];
     c.Generator.MarkLabel(l);
 }
Пример #42
0
 public override LayerMask AssembleValue(ObjectModel value, AssemblyContext context)
 {
     return(value.GetValue <int>("Mask"));
 }
Пример #43
0
 public override void Emit(AssemblyContext c)
 {
     var local = c.Locals[Id];
     c.Generator.FastEmitLoadLocal(local.LocalIndex);
 }
 public abstract void Assemble(object obj, IAssignableMemberInfo member, ValueModel model, Type expectedType, AssemblyContext context);