示例#1
0
        public void UnifyStructural_MissingProperty_Fail()
        {
            var unifier    = new TypeUnifier();
            var typeToSlim = new TypeToTypeSlimConverter();

            var rtc          = new RuntimeCompiler();
            var typeBuilder1 = rtc.GetNewRecordTypeBuilder();
            var typeBuilder2 = rtc.GetNewRecordTypeBuilder();

            rtc.DefineRecordType(
                typeBuilder1,
                (new Dictionary <string, Type> {
                { "foo", typeof(int) }
            }).AsEnumerable(),
                true
                );

            rtc.DefineRecordType(
                typeBuilder2,
                (new Dictionary <string, Type> {
                { "bar", typeof(double) }
            }).AsEnumerable(),
                true
                );

            var structuralType1    = typeBuilder1.CreateType();
            var structuralType2    = typeBuilder2.CreateType();
            var slimStructuralType = typeToSlim.Visit(structuralType2);

            unifier.Unify(structuralType1, slimStructuralType);
        }
示例#2
0
        public void AnonymousTypeTupletizer_RecursiveType()
        {
            var rtc = new RuntimeCompiler();

            var atb1 = rtc.GetNewAnonymousTypeBuilder();
            var atb2 = rtc.GetNewAnonymousTypeBuilder();

            rtc.DefineAnonymousType(atb1, new[]
            {
                new KeyValuePair <string, Type>("Qux", typeof(int)),
                new KeyValuePair <string, Type>("Bar", atb2),
            }, Array.Empty <string>());

            rtc.DefineAnonymousType(atb2, new[]
            {
                new KeyValuePair <string, Type>("Baz", typeof(int)),
                new KeyValuePair <string, Type>("Foo", atb1),
            }, Array.Empty <string>());

            var foo = atb1.CreateType();
            var bar = atb2.CreateType();

            var e = Expression.New(foo.GetConstructors().Single(), Expression.Constant(1), Expression.Constant(value: null, bar));

            Assert.ThrowsException <NotSupportedException>(() => AnonymousTypeTupletizer.Tupletize(e, Expression.Constant(value: null)));
        }
示例#3
0
        public void UnifyStructural_DifferentPropertyTypes_Pass()
        {
            var unifier    = new TypeUnifier();
            var typeToSlim = new TypeToTypeSlimConverter();

            var rtc         = new RuntimeCompiler();
            var typeBuilder = rtc.GetNewRecordTypeBuilder();

            rtc.DefineRecordType(
                typeBuilder,
                (new Dictionary <string, Type> {
                { "foo", typeof(int) }
            }).AsEnumerable(),
                true
                );

            var structuralType     = typeBuilder.CreateType();
            var slimStructuralType = typeToSlim.Visit(structuralType);

            Assert.IsTrue(unifier.Unify(structuralType, slimStructuralType));

            Assert.AreEqual(1, unifier.Entries.Count);

            Assert.IsTrue(unifier.Entries.ContainsKey(slimStructuralType));
            Assert.AreEqual(unifier.Entries[slimStructuralType], structuralType);

            Assert.IsTrue(slimStructuralType is StructuralTypeSlim);
        }
示例#4
0
        public void RC_Syntax()
        {
            String[] errorTemplates = new String[] {
                "{if:Condition}",
                "{if:Condition}test{/if}{/if}",
                "{when:Something}{if:Condition}test{/if}{/when}",
                "{when:Something}{ifnot:Condition}test{/ifnot}{/when}",
                "{when:Something}{text:VarPath}{/when}",
                "{when:Something}{html:VarPath}{/when}",
                "{when:Something}{url:VarPath}{/when}",
                "{when:Something}{eq:@Const}{/eq}{each:Collection}{/each}{else}{/else}{/when}",
                "{when:Something}{when:Foo}{eq:@Const}test{/eq}{/when}{/when}",
                "{when:Something}test{/when}",
                "{eq:@Const}test{/eq}",
                "{begins:@Const}test{/begins}",
                "{ends:@Const}test{/ends}",
                "{contains:@Const}test{/contains}",
                "{else}test{/else}"
            };
            RuntimeCompiler compiler = new RuntimeCompiler(new CompilerOptions());

            foreach (String template in errorTemplates)
            {
                try {
                    compiler.Compile <Object>(template);
                    throw new AssertionException(String.Format("Syntax exception was expected, but it was not thrown. Template: \"{0}\".", template));
                }
                catch (SyntaxException) { }
            }
        }
示例#5
0
        private string TestCompileFromSnippets(ref int failCount, ref int testCount)
        {
            RuntimeCompiler compiler     = new RuntimeCompiler();
            string          assemblyName = "TestAssembly";

            compiler.AssemblyName = assemblyName;
            List <string> source = new List <string>();

            using (StreamReader reader = new StreamReader(new FileStream("HelloWorld.cs", FileMode.Open)))
                source.Add(reader.ReadToEnd());

            compiler.SourceCode = source;
            testCount++;
            Assembly asm = null;
            string   ret = "";

            try { asm = compiler.CompileSourceSnippets(); }
            catch (ArgumentException ae) { failCount++; ret += ae + "\n"; }
            ret += TestAssembly(ref failCount, ref testCount, asm);
            if (string.IsNullOrWhiteSpace(ret))
            {
                return("No Errors");
            }
            return(ret);
        }
        public void AnonymousType_Nested()
        {
            var rtc = new RuntimeCompiler();

            var atb1 = rtc.GetNewAnonymousTypeBuilder();
            var atb2 = rtc.GetNewAnonymousTypeBuilder();

            rtc.DefineAnonymousType(atb1, new[]
            {
                new KeyValuePair <string, Type>("Qux", typeof(int)),
            });

            rtc.DefineAnonymousType(atb2, new[]
            {
                new KeyValuePair <string, Type>("Foo", atb1),
                new KeyValuePair <string, Type>("Baz", typeof(int)),
            }, new[] { "Foo" });

            var foo = atb1.CreateType();
            var bar = atb2.CreateType();

            var objFoo1 = Activator.CreateInstance(foo, new object[] { 42 });
            var objFoo2 = Activator.CreateInstance(foo, new object[] { 42 });

            var objBar1 = Activator.CreateInstance(bar, new object[] { objFoo1, 43 });
            var objBar2 = Activator.CreateInstance(bar, new object[] { objFoo2, 44 });

            Assert.AreEqual(objBar1, objBar2);
            Assert.AreEqual("{ Foo = { Qux = 42 }, Baz = 43 }", objBar1.ToString());
            Assert.AreEqual("{ Foo = { Qux = 42 }, Baz = 44 }", objBar2.ToString());
        }
示例#7
0
        public void RC_IfNotToken()
        {
            ConditionalTokenTestModel model    = new ConditionalTokenTestModel();
            RuntimeCompiler           compiler = new RuntimeCompiler(new CompilerOptions());

            Assert.AreEqual("", compiler.Compile(model.GetType(), "{ifnot:Bool_True}condition text{/ifnot}", OutputFormat.Text).DynamicInvoke(model, null));
            Assert.AreEqual("", compiler.Compile(model.GetType(), "{ifnot:Int32_True}condition text{/ifnot}", OutputFormat.Text).DynamicInvoke(model, null));
            Assert.AreEqual("", compiler.Compile(model.GetType(), "{ifnot:UInt32_True}condition text{/ifnot}", OutputFormat.Text).DynamicInvoke(model, null));
            Assert.AreEqual("", compiler.Compile(model.GetType(), "{ifnot:Int16_True}condition text{/ifnot}", OutputFormat.Text).DynamicInvoke(model, null));
            Assert.AreEqual("", compiler.Compile(model.GetType(), "{ifnot:UInt16_True}condition text{/ifnot}", OutputFormat.Text).DynamicInvoke(model, null));
            Assert.AreEqual("", compiler.Compile(model.GetType(), "{ifnot:Int64_True}condition text{/ifnot}", OutputFormat.Text).DynamicInvoke(model, null));
            Assert.AreEqual("", compiler.Compile(model.GetType(), "{ifnot:UInt64_True}condition text{/ifnot}", OutputFormat.Text).DynamicInvoke(model, null));
            Assert.AreEqual("", compiler.Compile(model.GetType(), "{ifnot:String_True}condition text{/ifnot}", OutputFormat.Text).DynamicInvoke(model, null));
            Assert.AreEqual("", compiler.Compile(model.GetType(), "{ifnot:Object_True}condition text{/ifnot}", OutputFormat.Text).DynamicInvoke(model, null));
            Assert.AreEqual("condition text", compiler.Compile(model.GetType(), "{ifnot:Bool_False}condition text{/ifnot}", OutputFormat.Text).DynamicInvoke(model, null));
            Assert.AreEqual("condition text", compiler.Compile(model.GetType(), "{ifnot:Int32_False}condition text{/ifnot}", OutputFormat.Text).DynamicInvoke(model, null));
            Assert.AreEqual("condition text", compiler.Compile(model.GetType(), "{ifnot:UInt32_False}condition text{/ifnot}", OutputFormat.Text).DynamicInvoke(model, null));
            Assert.AreEqual("condition text", compiler.Compile(model.GetType(), "{ifnot:Int16_False}condition text{/ifnot}", OutputFormat.Text).DynamicInvoke(model, null));
            Assert.AreEqual("condition text", compiler.Compile(model.GetType(), "{ifnot:UInt16_False}condition text{/ifnot}", OutputFormat.Text).DynamicInvoke(model, null));
            Assert.AreEqual("condition text", compiler.Compile(model.GetType(), "{ifnot:Int64_False}condition text{/ifnot}", OutputFormat.Text).DynamicInvoke(model, null));
            Assert.AreEqual("condition text", compiler.Compile(model.GetType(), "{ifnot:UInt64_False}condition text{/ifnot}", OutputFormat.Text).DynamicInvoke(model, null));
            Assert.AreEqual("condition text", compiler.Compile(model.GetType(), "{ifnot:String_False}condition text{/ifnot}", OutputFormat.Text).DynamicInvoke(model, null));
            Assert.AreEqual("condition text", compiler.Compile(model.GetType(), "{ifnot:Object_False}condition text{/ifnot}", OutputFormat.Text).DynamicInvoke(model, null));
            Assert.AreEqual("[Level1][Level2][/Level2][/Level1]", compiler.Compile(model.GetType(), "{ifnot:Object_False}[Level1]{ifnot:Int32_False}[Level2][/Level2]{/ifnot}[/Level1]{/ifnot}", OutputFormat.Text).DynamicInvoke(model, null));
            Assert.AreEqual("[Level1][/Level1]", compiler.Compile(model.GetType(), "{ifnot:Object_False}[Level1]{ifnot:Int32_True}[Level2][/Level2]{/ifnot}[/Level1]{/ifnot}", OutputFormat.Text).DynamicInvoke(model, null));
            Assert.AreEqual("", compiler.Compile(model.GetType(), "{ifnot:Object_True}[Level1]{ifnot:Int32_False}[Level2][/Level2]{/ifnot}[/Level1]{/ifnot}", OutputFormat.Text).DynamicInvoke(model, null));
        }
        public void ClosureType_Visibility()
        {
            var props = new[] { new KeyValuePair <string, Type>("bar", typeof(Bar)) };

            Assert.ThrowsException <InvalidOperationException>(() => RuntimeCompiler.CreateClosureType(props));
            Assert.ThrowsException <InvalidOperationException>(() => { var rtc = new RuntimeCompiler(); var atb = rtc.GetNewClosureTypeBuilder(); rtc.DefineClosureType(atb, props); });
        }
示例#9
0
        public void UnifyStructuralEquivalence_Pass()
        {
            var rt1 = RuntimeCompiler.CreateRecordType(
                new Dictionary <string, Type>
            {
                { "Foo", typeof(int) },
                { "Bar", typeof(string) }
            },
                true);

            var rt2 = RuntimeCompiler.CreateRecordType(
                new Dictionary <string, Type>
            {
                { "Foo", typeof(int) },
                { "Bar", typeof(string) }
            },
                true);

            var typeToSlim = new TypeToTypeSlimConverter();
            var slim       = typeToSlim.Visit(rt1);
            var unifier    = new TypeUnifier();

            Assert.IsTrue(unifier.Unify(rt1, slim));
            Assert.IsTrue(unifier.Unify(rt2, slim));
            Assert.AreEqual(1, unifier.Entries.Count);
            Assert.AreSame(rt1, unifier.Entries[slim]);
        }
        public void DataModelTypeUnifier_UnifyFails_ThrowsInvalidOperation()
        {
            var record = RuntimeCompiler.CreateRecordType(new Dictionary <string, Type> {
                { "zoo", typeof(int) }
            }, valueEquality: true);

            Assert.ThrowsException <InvalidOperationException>(() => Unify(typeof(IAsyncReactiveQbservable <>).MakeGenericType(record), typeof(IReactiveQbservable <Foo>)).ToArray());
        }
        public void AnonymousType_UnknownKey()
        {
            var rtc = new RuntimeCompiler();

            var atb = rtc.GetNewAnonymousTypeBuilder();

            AssertEx.ThrowsException <ArgumentException>(() => rtc.DefineAnonymousType(atb, new[] { new KeyValuePair <string, Type>("Bar", typeof(int)) }, "Baz"), ex => Assert.AreEqual("keys", ex.ParamName));
        }
        public void DataModelTypeUnifier_UnifyRecursive()
        {
            var record = RuntimeCompiler.CreateRecordType(new Dictionary <string, Type> {
                { "bar", typeof(int) }
            }, valueEquality: true);

            Assert.AreEqual(1, Unify(typeof(IAsyncReactiveQbservable <>).MakeGenericType(typeof(IAsyncReactiveQbservable <>).MakeGenericType(record)), typeof(IReactiveQbservable <IReactiveQbservable <Foo> >)).ToArray().Length);
        }
示例#13
0
 private void ExecuteExe(string exeName)
 {
     var(exitCode, output) = RuntimeCompiler.ExecuteExe(exeName, _input);
     if (exitCode != 0)
     {
         throw new Exception();
     }
 }
        public void CreateAnonymousType_ArgumentChecks()
        {
            AssertEx.ThrowsException <ArgumentNullException>(() => RuntimeCompiler.CreateAnonymousType((KeyValuePair <string, Type>[])null), ex => Assert.AreEqual("properties", ex.ParamName));
            AssertEx.ThrowsException <ArgumentNullException>(() => RuntimeCompiler.CreateAnonymousType((KeyValuePair <string, Type>[])null, Array.Empty <string>()), ex => Assert.AreEqual("properties", ex.ParamName));

            AssertEx.ThrowsException <ArgumentNullException>(() => RuntimeCompiler.CreateAnonymousType((StructuralFieldDeclaration[])null), ex => Assert.AreEqual("properties", ex.ParamName));
            AssertEx.ThrowsException <ArgumentNullException>(() => RuntimeCompiler.CreateAnonymousType((StructuralFieldDeclaration[])null, Array.Empty <string>()), ex => Assert.AreEqual("properties", ex.ParamName));
        }
        /// <summary>
        ///     Specifies the first trigger property
        /// </summary>
        /// <typeparam name="TParent"></typeparam>
        /// <typeparam name="TTargetProperty"></typeparam>
        /// <param name="token"></param>
        /// <param name="propertySelectors"></param>
        /// <returns></returns>
        public static void OnChanged <TParent, TTargetProperty>(
            this FluentToken <TParent, TTargetProperty> token, params Expression <Func <TParent, object> >[] propertySelectors)
        {
            foreach (var propertySelector in propertySelectors)
            {
                token.PropertyNames.Add(ExpressionTreeHelper.PropertyName(propertySelector));
            }

            var propertyName = ExpressionTreeHelper.PropertyName(token.TargetPropertySelector);

            bool Updater(TParent parent)
            {
                if (token.IfPredicate != null)
                {
                    if (!token.IfPredicate(parent))
                    {
                        return(false);
                    }
                }

                var newValue = token.ValueComputer(parent);

                var oldValue = RuntimeCompiler <TParent, TTargetProperty> .Getter(token.TargetPropertySelector)(parent);

                if (Equals(oldValue, newValue))
                {
                    return(false);
                }

                RuntimeCompiler <TParent, TTargetProperty> .SetterFromGetter(token.TargetPropertySelector)(parent,
                                                                                                           newValue);

                return(true);
            }

            var rule = new Rule <TParent>
            {
                TriggerProperties      = token.PropertyNames,
                Updater                = Updater,
                TargetPropertyName     = propertyName,
                IfExplained            = token.IfExplained,
                ValueComputerExplained = token.ValueComputerExplained
            };


            token.MappingRulesContainer.Rules.Add(rule);

            foreach (var name in token.PropertyNames)
            {
                if (!token.MappingRulesContainer.RulesByTrigger.TryGetValue(name, out var rules))
                {
                    rules = new List <Rule <TParent> >();
                    token.MappingRulesContainer.RulesByTrigger.Add(name, rules);
                }

                rules.Add(rule);
            }
        }
示例#16
0
        public void StructuralTypeEqualityComparer_ManOrBoy_Failure()
        {
            var rtc = new RuntimeCompiler();
            var rt1 = rtc.GetNewRecordTypeBuilder();
            var rt2 = rtc.GetNewRecordTypeBuilder();
            var at1 = rtc.GetNewAnonymousTypeBuilder();
            var at2 = rtc.GetNewAnonymousTypeBuilder();

            rtc.DefineRecordType(
                rt1,
                new Dictionary <string, Type>
            {
                { "Self", rt1 },
                { "Copy", rt2 },
                { "Other", typeof(int) }
            },
                true);

            rtc.DefineRecordType(
                rt2,
                new Dictionary <string, Type>
            {
                { "Self", rt2 },
                { "Copy", rt1 },
                { "Other", typeof(string) }
            },
                true);

            rtc.DefineAnonymousType(
                at1,
                new Dictionary <string, Type>
            {
                { "Self", at1 },
                { "Copy", at2 },
                { "Other", typeof(int) }
            },
                null);

            rtc.DefineAnonymousType(
                at2,
                new Dictionary <string, Type>
            {
                { "Self", at2 },
                { "Copy", at1 },
                { "Other", typeof(string) }
            },
                null);

            rt1.CreateType();
            rt2.CreateType();
            at1.CreateType();
            at2.CreateType();

            var eq = new StructuralTypeEqualityComparer();

            Assert.IsFalse(eq.Equals(rt1, rt2));
            Assert.IsFalse(eq.Equals(at1, at2));
        }
        public void DefineClosureType_ArgumentChecks()
        {
            var rtc = new RuntimeCompiler();

            var atb = rtc.GetNewClosureTypeBuilder();

            AssertEx.ThrowsException <ArgumentNullException>(() => rtc.DefineClosureType(closureTypeBuilder: null, Array.Empty <KeyValuePair <string, Type> >()), ex => Assert.AreEqual("closureTypeBuilder", ex.ParamName));
            AssertEx.ThrowsException <ArgumentNullException>(() => rtc.DefineClosureType(atb, fields: null), ex => Assert.AreEqual("fields", ex.ParamName));
        }
示例#18
0
文件: UIManager.cs 项目: baovien/bkb
    private void Start()
    {
        rtc = GameObject.FindGameObjectWithTag("ModManager").GetComponent <RuntimeCompiler>();

        foreach (var mod in rtc.navn)
        {
            ModsText.text += mod + "\n";
        }
    }
示例#19
0
        public void RC_EachToken()
        {
            EachTokenTestModel model    = new EachTokenTestModel();
            RuntimeCompiler    compiler = new RuntimeCompiler(new CompilerOptions());

            Assert.AreEqual("", compiler.Compile(model.GetType(), "{each:EmptyList}text{/each}", OutputFormat.Text).DynamicInvoke(model, null));
            Assert.AreEqual("(1/7)2 (2/7)1 (3/7)2 (4/7)8 (5/7)5 (6/7)0 (7/7)6 ", compiler.Compile(model.GetType(), "{each:ValueList}({text:thisNum}/{text:thisCount}){text:this} {/each}", OutputFormat.Text).DynamicInvoke(model, null));
            Assert.AreEqual("0:Item 1; 1:Item 2; 2:Item 3; ", compiler.Compile(model.GetType(), "{each:ModelList}{text:thisIndex}:{text:Text}; {/each}", OutputFormat.Text).DynamicInvoke(model, null));
            Assert.AreEqual("to be or not to be ", compiler.Compile(model.GetType(), "{each:ComplexModel}{each:Children}{text:this}{/each} {/each}", OutputFormat.Text).DynamicInvoke(model, null));
        }
        public void RecordType_PropertyAttribute_NoMatchingConstructor()
        {
            var props = new[] { new StructuralFieldDeclaration("bar", typeof(string), new List <CustomAttributeDeclaration> {
                    new CustomAttributeDeclaration(typeof(FooAttribute), new List <object> {
                        0
                    }.AsReadOnly())
                }.AsReadOnly()) };

            Assert.ThrowsException <InvalidOperationException>(() => RuntimeCompiler.CreateRecordType(props, valueEquality: true));
        }
        public void DefineRecordType_ArgumentChecks()
        {
            var rtc = new RuntimeCompiler();

            var rtb = rtc.GetNewRecordTypeBuilder();

            AssertEx.ThrowsException <ArgumentNullException>(() => rtc.DefineRecordType(recordTypeBuilder: null, Array.Empty <KeyValuePair <string, Type> >(), valueEquality: true), ex => Assert.AreEqual("recordTypeBuilder", ex.ParamName));
            AssertEx.ThrowsException <ArgumentNullException>(() => rtc.DefineRecordType(rtb, properties: (KeyValuePair <string, Type>[])null, valueEquality: true), ex => Assert.AreEqual("properties", ex.ParamName));
            AssertEx.ThrowsException <ArgumentNullException>(() => rtc.DefineRecordType(recordTypeBuilder: null, Array.Empty <StructuralFieldDeclaration>(), valueEquality: true), ex => Assert.AreEqual("recordTypeBuilder", ex.ParamName));
            AssertEx.ThrowsException <ArgumentNullException>(() => rtc.DefineRecordType(rtb, properties: (StructuralFieldDeclaration[])null, valueEquality: true), ex => Assert.AreEqual("properties", ex.ParamName));
        }
示例#22
0
        public void TypeSubstitutionExpressionVisitor_Anonymize()
        {
            var pers  = typeof(Person);
            var query = (Expression <Func <IEnumerable <Person>, IEnumerable <string> > >)(xs => from x in xs where x.Age > 10 let name = x.Name where name.StartsWith("B") select name.ToUpper() + " is " + x.Age);

            var check1 = new TypeErasureChecker(new[] { typeof(Person) });

            Assert.ThrowsException <InvalidOperationException>(() => check1.Visit(query));


            var anon = RuntimeCompiler.CreateAnonymousType(new[]
            {
                new KeyValuePair <string, Type>("Name", typeof(string)),
                new KeyValuePair <string, Type>("Age", typeof(int)),
            });

            var subst1 = new TypeSubstitutionExpressionVisitor(new Dictionary <Type, Type>
            {
                { pers, anon }
            });

            var res1 = subst1.Apply(query);

            check1.Visit(res1);

            var check2 = new TypeErasureChecker(new[] { anon });

            Assert.ThrowsException <InvalidOperationException>(() => check2.Visit(res1));


            var f = ((LambdaExpression)res1).Compile();

            var cast       = ((MethodInfo)ReflectionHelpers.InfoOf(() => Enumerable.Cast <int>(null))).GetGenericMethodDefinition().MakeGenericMethod(anon);
            var peopleObj  = new[] { Activator.CreateInstance(anon, new object[] { "Bart", 10 }), Activator.CreateInstance(anon, new object[] { "Lisa", 8 }), Activator.CreateInstance(anon, new object[] { "Bart", 21 }) };
            var peopleAnon = cast.Invoke(obj: null, new object[] { peopleObj });
            var qres       = (IEnumerable <string>)f.DynamicInvoke(peopleAnon);

            Assert.IsTrue(new[] { "BART is 21" }.SequenceEqual(qres));

            var subst2 = new TypeSubstitutionExpressionVisitor(new Dictionary <Type, Type>
            {
                { anon, pers }
            });

            var res2 = subst2.Apply(res1);

            check2.Visit(res2);

            Assert.ThrowsException <InvalidOperationException>(() => check1.Visit(res2));

            var eq = new ExpressionEqualityComparer();

            Assert.IsTrue(eq.Equals(query, res2));
        }
 public void ClosureType_NonTrivial_Static()
 {
     ClosureType_NonTrivial_Impl(() =>
     {
         return(RuntimeCompiler.CreateClosureType(new[]
         {
             new KeyValuePair <string, Type>("bar", typeof(int)),
             new KeyValuePair <string, Type>("foo", typeof(string)),
         }));
     });
 }
 public void AnonymousType_VisualBasic_Static()
 {
     AnonymousType_VisualBasic_Impl(() =>
     {
         return(RuntimeCompiler.CreateAnonymousType(new[]
         {
             new KeyValuePair <string, Type>("Name", typeof(string)),
             new KeyValuePair <string, Type>("Age", typeof(int)),
         }, new[] { "Name" }));
     });
 }
        public void DataModelTypeUnifier_UnifyParameterized()
        {
            var record1 = RuntimeCompiler.CreateRecordType(new Dictionary <string, Type> {
                { "bar", typeof(int) }
            }, valueEquality: true);
            var record2 = RuntimeCompiler.CreateRecordType(new Dictionary <string, Type> {
                { "qux", typeof(int) }
            }, valueEquality: true);

            Assert.AreEqual(2, Unify(typeof(Func <,>).MakeGenericType(record2, typeof(IAsyncReactiveQbservable <>).MakeGenericType(record1)), typeof(Func <Bar, IReactiveQbservable <Foo> >)).ToArray().Length);
        }
 public void AnonymousType_CSharp_StructuralFields_Static_WithKeys()
 {
     AnonymousType_CSharp_Impl(() =>
     {
         return(RuntimeCompiler.CreateAnonymousType(new[]
         {
             new StructuralFieldDeclaration("Name", typeof(string)),
             new StructuralFieldDeclaration("Age", typeof(int)),
         }, new[] { "Name", "Age" }));
     });
 }
示例#27
0
        protected void Test([CallerMemberName] string testName = null)
        {
            var(success, diagnostics) = RuntimeCompiler.CompileToExe(testName, TestSource);
            Assert.IsTrue(success, message: string.Join(Environment.NewLine, diagnostics));

            for (int i = 0; i < TestInputs.Count; ++i)
            {
                var(exitCode, output) = RuntimeCompiler.ExecuteExe(testName, TestInputs[i]);
                Assert.AreEqual(0, exitCode, message: "Non-zero exit code (runtime error).");
                Assert.AreEqual(TestOutputs[i], output);
            }
        }
        /// <summary>
        ///     Always the last NON OPTIONAL statement in a rule declaration
        ///     Internally produces an instance of <see cref="Rule{TParent}" /> and adds it into the rules engine
        /// </summary>
        /// <typeparam name="TParent"></typeparam>
        /// <typeparam name="TTargetProperty"></typeparam>
        /// <param name="token"></param>
        public static void EndRule <TParent, TTargetProperty>(this FluentToken <TParent, TTargetProperty> token)
        {
            if (token.MappingRulesContainer == null)
            {
                throw new NotSupportedException("Error in fluent syntax. Start with a Set() statement");
            }

            var propertyName = ExpressionTreeHelper.PropertyName(token.TargetPropertySelector);

            bool Updater(TParent parent)
            {
                if (token.IfPredicate != null)
                {
                    if (!token.IfPredicate(parent))
                    {
                        return(false);
                    }
                }

                var newValue = token.ValueComputer(parent);

                var oldValue = RuntimeCompiler <TParent, TTargetProperty> .Getter(token.TargetPropertySelector)(parent);

                if (Equals(oldValue, newValue))
                {
                    return(false);
                }

                RuntimeCompiler <TParent, TTargetProperty> .SetterFromGetter(token.TargetPropertySelector)(parent,
                                                                                                           newValue);

                return(true);
            }

            var rule = new Rule <TParent>
            {
                TriggerProperties  = token.PropertyNames,
                Updater            = Updater,
                TargetPropertyName = propertyName
            };

            foreach (var name in token.PropertyNames)
            {
                if (!token.MappingRulesContainer.RulesByTrigger.TryGetValue(name, out var rules))
                {
                    rules = new List <Rule <TParent> >();
                    token.MappingRulesContainer.RulesByTrigger.Add(name, rules);
                }

                rules.Add(rule);
            }
        }
示例#29
0
        public void Generate_setter_from_getter_expression()
        {
            var setter = RuntimeCompiler <CdsTrade, string> .SetterFromGetter(cds => cds.CdsProduct.RefEntity);

            var trade = new CdsTrade
            {
                Product = new CreditDefaultSwap()
            };

            setter(trade, "xxx");

            Assert.AreEqual("xxx", trade.CdsProduct.RefEntity);
        }
示例#30
0
 static void Main(string[] args)
 {
     try
     {
         RuntimeCompiler.CompileAllFilesInDirectory(Path.Combine(Environment.CurrentDirectory, "Items"), new string[] { "System.Linq.dll" }).DoAction(s => Console.WriteLine(s)); ;
     }
     catch (Exception)
     {
         Console.WriteLine("Could not compile runtime files");
     }
     MainForm form = new MainForm();
     form.ShowDialog();
 }