Пример #1
0
        public void Expressions_with_larger_long_casts_should_not_crash()
        {
            var y   = 65536;
            var yn1 = y + 1;

            Assert.IsTrue(ExpressionCompiler.Compile(() => yn1 != (long)y)());
        }
Пример #2
0
        public void Expressions_with_small_long_casts_should_not_crash()
        {
            var x = 65535;
            var y = 65535;

            Assert.IsTrue(ExpressionCompiler.Compile(() => x == (long)y)());
        }
Пример #3
0
 public void TestCompilePerformance()
 {
     for (int i = 0; i < 100000; i++)
     {
         ExpressionCompiler.Compile <Z, string>(z => z.Q[22].Qzz);
     }
 }
Пример #4
0
        public void Expressions_with_max_uint_constant()
        {
            const uint maxuint = UInt32.MaxValue;

            Assert.IsFalse(maxuint == -1);
            Assert.IsFalse(ExpressionCompiler.Compile(() => maxuint == -1)());
        }
Пример #5
0
        /// <summary>
        /// Compiles the specified code
        /// </summary>
        /// <param name="code">MuteScript code to compile</param>
        /// <returns>Returns a <see cref="CompilationResult" /></returns>
        public CompilationResult Compile(string code)
        {
            var lexer  = new MuteGrammarLexer(new AntlrInputStream(code));
            var parser = new MuteGrammarParser(new BufferedTokenStream(lexer));

            var errorListener = new TokenErrorListener {
                Messages = parser.Messages
            };

            parser.RemoveErrorListeners();
            parser.AddErrorListener(errorListener);
            parser.NamespaceLookup = this.NamespaceLookup;
            parser.UsingTypes      = this.ImplicitImports;

            var ctx = parser.compileUnit();

            if (parser.Messages.Count(x => x.Severity == MessageSeverity.Error) > 0)
            {
                return(new CompilationResult(null, parser.Messages));
            }

            var cmp    = new ExpressionCompiler();
            var result = cmp.Compile(ctx.module);

            return(new CompilationResult(result, parser.Messages));
        }
Пример #6
0
        private Action <SprocCall, T, UpdateBatch, DocumentMapping, Guid?, Guid, string> buildSprocWriter(DocumentMapping mapping)
        {
            var call         = Expression.Parameter(typeof(SprocCall), "call");
            var doc          = Expression.Parameter(typeof(T), "doc");
            var batch        = Expression.Parameter(typeof(UpdateBatch), "batch");
            var mappingParam = Expression.Parameter(typeof(DocumentMapping), "mapping");

            var currentVersion = Expression.Parameter(typeof(Guid?), "currentVersion");
            var newVersion     = Expression.Parameter(typeof(Guid), "newVersion");

            var tenantId = Expression.Parameter(typeof(string), "tenantId");

            var arguments = new UpsertFunction(mapping).OrderedArguments().Select(x =>
            {
                return(x.CompileUpdateExpression(_mapping.DuplicatedFieldEnumStorage, call, doc, batch, mappingParam, currentVersion, newVersion, tenantId, true));
            });

            var block = Expression.Block(arguments);

            var lambda = Expression.Lambda <Action <SprocCall, T, UpdateBatch, DocumentMapping, Guid?, Guid, string> >(block,
                                                                                                                       new ParameterExpression[]
            {
                call, doc, batch, mappingParam, currentVersion, newVersion, tenantId
            });

            return(ExpressionCompiler.Compile <Action <SprocCall, T, UpdateBatch, DocumentMapping, Guid?, Guid, string> >(lambda));
        }
Пример #7
0
        private Action <SprocCall, T, UpdateBatch, DocumentMapping, Guid?, Guid> buildSprocWriter(DocumentMapping mapping)
        {
            var call         = Expression.Parameter(typeof(SprocCall), "call");
            var doc          = Expression.Parameter(typeof(T), "doc");
            var batch        = Expression.Parameter(typeof(UpdateBatch), "batch");
            var mappingParam = Expression.Parameter(typeof(DocumentMapping), "mapping");

            var currentVersion = Expression.Parameter(typeof(Guid?), "currentVersion");
            var newVersion     = Expression.Parameter(typeof(Guid), "newVersion");

            var arguments = new UpsertFunction(mapping).OrderedArguments().Select(x =>
            {
                return(x.CompileUpdateExpression(_serializer.EnumStorage, call, doc, batch, mappingParam, currentVersion, newVersion, _useCharBufferPooling));
            });

            var block = Expression.Block(arguments);

            var lambda = Expression.Lambda <Action <SprocCall, T, UpdateBatch, DocumentMapping, Guid?, Guid> >(block,
                                                                                                               new ParameterExpression[]
            {
                call, doc, batch, mappingParam, currentVersion, newVersion
            });

            return(ExpressionCompiler.Compile <Action <SprocCall, T, UpdateBatch, DocumentMapping, Guid?, Guid> >(lambda));
        }
Пример #8
0
        public BulkLoader(ISerializer serializer, DocumentMapping mapping, IdAssignment <T> assignment)
        {
            _mapping    = mapping;
            _assignment = assignment;
            var upsertFunction = new UpsertFunction(mapping);

            _tempTableName = mapping.Table.Name + "_temp";


            var writer          = Expression.Parameter(typeof(NpgsqlBinaryImporter), "writer");
            var document        = Expression.Parameter(typeof(T), "document");
            var alias           = Expression.Parameter(typeof(string), "alias");
            var serializerParam = Expression.Parameter(typeof(ISerializer), "serializer");
            var textWriter      = Expression.Parameter(typeof(CharArrayTextWriter), "writer");
            var tenantId        = Expression.Parameter(typeof(string), "tenantId");

            var arguments   = upsertFunction.OrderedArguments().Where(x => !(x is CurrentVersionArgument)).ToArray();
            var expressions =
                arguments.Select(
                    x => x.CompileBulkImporter(mapping, serializer.EnumStorage, writer, document, alias, serializerParam, textWriter, tenantId));

            var columns = arguments.Select(x => $"\"{x.Column}\"").Join(", ");

            _baseSql = $"COPY %TABLE%({columns}) FROM STDIN BINARY";
            _sql     = _baseSql.Replace("%TABLE%", mapping.Table.QualifiedName);

            var block = Expression.Block(expressions);



            var lambda = Expression.Lambda <Action <T, string, ISerializer, NpgsqlBinaryImporter, CharArrayTextWriter, string> >(block, document, alias,
                                                                                                                                 serializerParam, writer, textWriter, tenantId);

            _transferData = ExpressionCompiler.Compile <Action <T, string, ISerializer, NpgsqlBinaryImporter, CharArrayTextWriter, string> >(lambda);
        }
Пример #9
0
        public void Should_compile_manually_composed_expr_with_parameters()
        {
            var manualExpr = ComposeManualExprWithParams();

            var lambda = ExpressionCompiler.Compile <Func <B, X> >(manualExpr);

            Assert.IsInstanceOf <X>(lambda(new B()));
        }
Пример #10
0
        public void Compile()
        {
            var compiler = new ExpressionCompiler();

            compiler.Compile(this);

            Verify();
        }
Пример #11
0
        public void Should_compile_manually_composed_expr()
        {
            var manualExpr = ComposeManualExpr();

            var lambda = ExpressionCompiler.Compile(manualExpr);

            Assert.IsInstanceOf <X>(lambda());
        }
Пример #12
0
        static Action <T, TProperty> GetSetMethod(PropertyInfo property)
        {
            var instance = Expression.Parameter(typeof(T), "instance");
            var value    = Expression.Parameter(typeof(TProperty), "value");
            var call     = Expression.Call(instance, property.SetMethod, value);

            return(ExpressionCompiler.Compile <Action <T, TProperty> >(Expression.Lambda <Action <T, TProperty> >(call, instance, value)));
        }
Пример #13
0
        static Func <TContext, Task> GenerateFunc <TContext, TStep>(IReadOnlyList <TStep> steps, string processMethodName)
            where TContext : StepContext
            where TStep : IStep
        {
            var expression = GenerateExpression <TContext, TStep>(steps, processMethodName, 0);

            return(ExpressionCompiler.Compile <Func <TContext, Task> >(expression));
            //return expression.Compile();
        }
Пример #14
0
        protected static Action <TVisitor, PropertyInfo> CompileCallMethod(MethodInfo methodType)
        {
            var visitor      = Expression.Parameter(typeof(TVisitor), "visitor");
            var propertyInfo = Expression.Parameter(typeof(PropertyInfo), "property");
            var call         = Expression.Call(visitor, methodType, propertyInfo);
            var lambda       = Expression.Lambda <Action <TVisitor, PropertyInfo> >(call, visitor, propertyInfo);

            return(ExpressionCompiler.Compile <Action <TVisitor, PropertyInfo> >(lambda));
        }
        public static string FormatCode(string code)
        {
            var ast           = new NodeTypeBinder().Process(Reduce(code, out _));
            var compiler      = new ExpressionCompiler();
            var expression    = compiler.Compile(ast as EntryNode);
            var codeGenerator = new XzaarScriptCodeFormatter();

            return(codeGenerator.Visit(expression).TrimEnd('\r', '\n'));
        }
Пример #16
0
        static Func <TContext, Task> GenerateFunc <TContext, TStep>(IReadOnlyList <TStep> steps, string processMethodName)
            where TContext : StepContext
            where TStep : IStep
        {
            var expression = GenerateExpression <TContext, TStep>(steps, processMethodName);

            // use Dadhi's fast expression compiler because he's awesome - https://github.com/dadhi
            return(ExpressionCompiler.Compile <Func <TContext, Task> >(expression));
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="SimpleQuery{TResult}"/> class.
        /// </summary>
        /// <param name="operationDefinition">The GraphQL operation definition.</param>
        /// <param name="resultBuilder">
        /// A function which transforms JSON data into the final result.
        /// </param>
        public SimpleQuery(
            OperationDefinition operationDefinition,
            Expression <Func <JObject, TResult> > resultBuilder)
        {
            var serializer = new QuerySerializer();

            OperationDefinition = operationDefinition;
            Query         = serializer.Serialize(operationDefinition);
            ResultBuilder = ExpressionCompiler.Compile(resultBuilder);
        }
        public void TestCases(ArgumentMismatchTestCase testCase)
        {
            var tokens = Lexer.Process(DemoUtility.OperatorMap, testCase.Infix);
            var node   = AstParser.Parse(DemoUtility.OperatorMap, tokens);

            var ex = Assert.Throws <OverloadMismatchException>(() => ExpressionCompiler.Compile <double>(DemoUtility.CompilerFunctions, node));

            Assert.AreEqual(testCase.ExpectedOperator, ex.OperatorNode.OperatorInfo.Keyword);
            Assert.AreEqual(testCase.ActualArguments, ex.OperatorNode.Children.Count);
        }
Пример #19
0
        public static XzaarExpression CompileExpression(this EntryNode node)
        {
            var compiler   = new ExpressionCompiler();
            var expression = compiler.Compile(node);

            if (compiler.Errors.Count > 0)
            {
                throw new Exception(string.Join(Environment.NewLine, compiler.Errors.ToArray()));
            }
            return(expression);
        }
Пример #20
0
        public void Should_compile_nested_lambda()
        {
            var a = new A();
            Expression <Func <X> > getXExpr = () => X.Get(it => new X(it), new Lazy <A>(() => a));

            var getX = ExpressionCompiler.Compile(getXExpr);

            var x = getX();

            Assert.AreSame(a, x.A);
        }
Пример #21
0
        public static Func <TTarget, TField> GetField <TTarget, TField>(FieldInfo field)
        {
            var target = Expression.Parameter(typeof(TTarget), "target");

            var fieldAccess = Expression.Field(target, field);

            var lambda = field.FieldType == typeof(TField)
                ? Expression.Lambda <Func <TTarget, TField> >(fieldAccess, target)
                : Expression.Lambda <Func <TTarget, TField> >(Expression.Convert(fieldAccess, typeof(TField)), target);

            return(ExpressionCompiler.Compile <Func <TTarget, TField> >(lambda));
        }
Пример #22
0
        public void TestCases(End2EndTestCase <double> testCase)
        {
            var tokens = Lexer.Process(DemoUtility.OperatorMap, testCase.Infix);

            var node = AstParser.Parse(DemoUtility.OperatorMap, tokens);

            Assert.AreEqual(testCase.ExpectedNodeString, node.ToString());

            var functionActual = ExpressionCompiler.Compile <Context <double>, double>(DemoUtility.CompilerFunctions, node);

            Assert.AreEqual(testCase.ExpectedFunction(s_ctx), functionActual(s_ctx));
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="SimpleQuery{TResult}"/> class.
 /// </summary>
 /// <param name="masterQuery">The master query.</param>
 /// <param name="subqueries">The sub-queries.</param>
 /// <param name="parentIds">
 /// A function which given the data from the master query, returns the IDs of the
 /// entities which can be auto-paged.
 /// </param>
 /// <param name="pageInfo">
 /// A function which given the data from the sub-query, returns the paging info.
 /// </param>
 /// <param name="parentPageInfo">
 /// A function which given the data from the master query, returns the paging info
 /// for all entities which can be auto-paged.
 /// </param>
 public PagedSubquery(
     SimpleQuery <TResult> masterQuery,
     IEnumerable <ISubquery> subqueries,
     Expression <Func <JObject, IEnumerable <JToken> > > parentIds,
     Expression <Func <JObject, JToken> > pageInfo,
     Expression <Func <JObject, IEnumerable <JToken> > > parentPageInfo)
     : base(masterQuery, subqueries)
 {
     ParentIds      = ExpressionCompiler.Compile(parentIds);
     PageInfo       = ExpressionCompiler.Compile(pageInfo);
     ParentPageInfo = ExpressionCompiler.Compile(parentPageInfo);
 }
Пример #24
0
        private static MondProgram CompileImpl(Expression expression, MondCompilerOptions options, string debugSourceCode = null)
        {
            expression = expression.Simplify();
            expression.SetParent(null);

            //using (var printer = new ExpressionPrintVisitor(Console.Out))
            //    expression.Accept(printer);

            var compiler = new ExpressionCompiler(options);

            return(compiler.Compile(expression, debugSourceCode));
        }
Пример #25
0
            public void Add(MethodCollection methods, MethodInfo method, Type aggregateType, IList <ParameterExpression> parameters)
            {
                Expression body       = Expression.Call(parameters[0], method, parameters.OfType <Expression>().Skip(1).ToArray());
                var        expression = Expression.Lambda <T>(body, parameters);


                var lambda = ExpressionCompiler.Compile <T>(expression);

                var eventType = method.GetEventType(aggregateType);

                methods.AddLambda(lambda, eventType);
            }
Пример #26
0
        public static Action <TTarget, TField> SetField <TTarget, TField>(FieldInfo field)
        {
            var target = Expression.Parameter(typeof(TTarget), "target");
            var value  = Expression.Parameter(typeof(TField), "value");

            var fieldAccess = Expression.Field(target, field);
            var fieldSetter = Expression.Assign(fieldAccess, value);

            var lambda = Expression.Lambda <Action <TTarget, TField> >(fieldSetter, target, value);

            return(ExpressionCompiler.Compile <Action <TTarget, TField> >(lambda));
        }
Пример #27
0
        static void Main(string[] args)
        {
            string infix = string.Join(' ', args);

            Console.WriteLine(infix);

            var tokens = Lexer.Process(DemoUtility.OperatorMap, infix);
            var node   = AstParser.Parse(DemoUtility.OperatorMap, tokens);
            var func   = ExpressionCompiler.Compile <double>(DemoUtility.CompilerFunctions, node);

            Console.WriteLine(func());
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="SimpleQuery{TResult}"/> class.
 /// </summary>
 /// <param name="operationDefinition">The GraphQL operation definition.</param>
 /// <param name="resultBuilder">
 /// A function which transforms JSON data into the final result.
 /// </param>
 /// <param name="parentIds">
 /// A function which given the data from the master query, returns the IDs of the
 /// entities which can be auto-paged.
 /// </param>
 /// <param name="pageInfo">
 /// A function which given the data from the sub-query, returns the paging info.
 /// </param>
 /// <param name="parentPageInfo">
 /// A function which given the data from the master query, returns the paging info
 /// for all entities which can be auto-paged.
 /// </param>
 public SimpleSubquery(
     OperationDefinition operationDefinition,
     Expression <Func <JObject, TResult> > resultBuilder,
     Expression <Func <JObject, IEnumerable <JToken> > > parentIds,
     Expression <Func <JObject, JToken> > pageInfo,
     Expression <Func <JObject, IEnumerable <JToken> > > parentPageInfo)
     : base(operationDefinition, resultBuilder)
 {
     ParentIds      = ExpressionCompiler.Compile(parentIds);
     PageInfo       = ExpressionCompiler.Compile(pageInfo);
     ParentPageInfo = ExpressionCompiler.Compile(parentPageInfo);
 }
Пример #29
0
        public AggregateFinder()
        {
            var idMember = DocumentMapping.FindIdMember(typeof(T));

            var docParam = Expression.Parameter(typeof(T), "doc");
            var idParam  = Expression.Parameter(typeof(Guid), "id");

            var member = Expression.PropertyOrField(docParam, idMember.Name);
            var assign = Expression.Assign(member, idParam);

            var lambda = Expression.Lambda <Action <T, Guid> >(assign, docParam, idParam);

            _setId = ExpressionCompiler.Compile <Action <T, Guid> >(lambda);
        }
Пример #30
0
        private static MondProgram CompileImpl(Expression expression, MondCompilerOptions options)
        {
            options = options ?? new MondCompilerOptions();

            expression.SetParent(null);
            expression.Simplify();

            //using (var writer = new IndentTextWriter(Console.Out, " "))
            //    expression.Print(writer);

            var compiler = new ExpressionCompiler(options);

            return(compiler.Compile(expression));
        }
 private void EvaluateCommand_Click(object sender, EventArgs e)
 {
     try
     {
         var compiler = new ExpressionCompiler();
         var function = compiler.Compile(ScriptInput.Text);
         var input = compiler.LastExpressionParams.ToArray();
         var form = new ValuesInputForm(input);
         if (form.ShowDialog() == System.Windows.Forms.DialogResult.OK)
         {
             var result = function(form.Values);
             MessageBox.Show(string.Format("The result is: {0}", result), "Result");
         }
     }
     catch (Exception ex)
     {
         MessageBox.Show(ex.Message, "Error",
             MessageBoxButtons.OK, MessageBoxIcon.Error);
     }
 }