예제 #1
0
        private Expression HandleMethodCallExpression(MethodCallExpression helperCall)
        {
            if (helperCall.Type != typeof(void))
            {
                return(helperCall.Update(helperCall.Object,
                                         ReplaceValuesOf <TextWriter>(helperCall.Arguments, ExpressionShortcuts.Null <TextWriter>()).Select(Visit)
                                         ));
            }

            var context = ExpressionShortcuts.Var <BindingContext>();
            var writer  = ExpressionShortcuts.Var <TextWriter>();

            helperCall = helperCall.Update(ExpressionUtils.ReplaceParameters(helperCall.Object, context),
                                           ExpressionUtils.ReplaceParameters(
                                               ReplaceValuesOf <TextWriter>(helperCall.Arguments, writer), new Expression[] { context }
                                               ).Select(Visit)
                                           );

            var formatProvider = ExpressionShortcuts.Arg(CompilationContext.Configuration.FormatProvider);
            var block          = ExpressionShortcuts.Block()
                                 .Parameter(writer, ExpressionShortcuts.New(() => new PolledStringWriter((IFormatProvider)formatProvider)))
                                 .Line(writer.Using((o, body) =>
                                                    body.Line(helperCall)
                                                    .Line(o.Call(x => (object)x.ToString()))
                                                    ));

            var continuation = _expressionCompiler.Compile(Expression.Lambda <Func <BindingContext, object> >(block, (ParameterExpression)context));

            return(ExpressionShortcuts.Arg <object>(Expression.Invoke(Expression.Constant(continuation), CompilationContext.BindingContext)));
        }
예제 #2
0
        public Mapping <TSource, TDestination> GenerateCompleteMapping <TSource, TDestination>(Expression <Func <TSource, TDestination> > userInput, IFlashMapperMappingCallbacks <TSource, TDestination> callbacks)
        {
            var buildExpression   = mappingExpressionAutocompleteService.CompleteBuildExpression(userInput, callbacks);
            var mapDataExpression = mappingExpressionAutocompleteService.CompleteMapDataExpression(userInput, callbacks);
            var buildMethod       = expressionCompiler.Compile(buildExpression);
            var mapDataMethod     = expressionCompiler.Compile(mapDataExpression);

            return(new Mapping <TSource, TDestination>(buildMethod, mapDataMethod, settings));
        }
예제 #3
0
        public Action <object, T> GetSetter <T>(IStateMember member)
        {
            ParameterExpression instance = Expression.Parameter(typeof(object));
            ParameterExpression value    = Expression.Parameter(typeof(T));

            Expression <Action <object, T> > lambda =
                Expression.Lambda <Action <object, T> >
                    (member.GetSetExpression(instance, value),
                    "Setter_" + member.Name,
                    new[] { instance, value });

            return(_compiler.Compile(lambda));
        }
예제 #4
0
 internal virtual object Parse(string formula, RangeAddress rangeAddress)
 {
     using (var scope = _parsingContext.Scopes.NewScope(rangeAddress))
     {
         var tokens = _lexer.Tokenize(formula);
         var graph  = _graphBuilder.Build(tokens);
         if (graph.Expressions.Count() == 0)
         {
             return(null);
         }
         return(_compiler.Compile(graph.Expressions).Result);
     }
 }
        public void ShouldCompileTwoInterExpressionsToCorrectResult()
        {
            var exp1 = new IntegerExpression("2");

            exp1.Operator = Operator.Plus;
            _graph.Add(exp1);
            var exp2 = new IntegerExpression("2");

            _graph.Add(exp2);

            var result = _expressionCompiler.Compile(_graph.Expressions);

            Assert.AreEqual(4d, result.Result);
        }
예제 #6
0
        public override void Compile(TextWriter writer, bool isRootStatement)
        {
            IExpressionCompiler expressionCompiler = ParentStatement.MethodCallExpression.Compiler();

            using (var tempVariables = Context.UseTempVariables())
            {
                if (expressionCompiler.Type == EV3Type.Void)
                {
                    expressionCompiler.Compile(writer, null);
                }
                else
                {
                    expressionCompiler.Compile(writer, tempVariables.CreateVariable(expressionCompiler.Type));
                }
            }
        }
예제 #7
0
        public override CompileResult Compile()
        {
            var result = _expressionCompiler.Compile(Children);

            if (result.IsNumeric && _isNegated)
            {
                return(new CompileResult(result.ResultNumeric * -1, result.DataType));
            }
            return(result);
        }
예제 #8
0
        private ClimbDelegate <T> CreateReferenceDelegate <T>(Type runtimeType)
        {
            var processor = Expression.Parameter(typeof(object), "processor");
            var value     = Expression.Parameter(typeof(T), "value");

            Expression owner = value.Convert(runtimeType);

            Expression castedProcessor = processor.Convert(_processorType);

            IEnumerable <IStateMember> members =
                _stateMemberProvider.Provide(runtimeType);

            List <Expression>          expressions         = new List <Expression>();
            List <ParameterExpression> descriptorVariables = new List <ParameterExpression>();

            foreach (IStateMember member in members)
            {
                DescriptorWriter writer = new DescriptorWriter(_climbStore);

                DescriptorVariable descriptor =
                    writer.GetDescriptor(castedProcessor, owner, member, member.MemberType);

                Expression callProcessor =
                    _mutator.GetExpression(castedProcessor, owner, member, descriptor.Reference);

                descriptorVariables.Add(descriptor.Reference);
                expressions.Add(descriptor.Declaration);
                expressions.Add(callProcessor);
            }

            BlockExpression climbBody =
                Expression.Block(descriptorVariables, expressions);

            Expression <ClimbDelegate <T> > lambda =
                Expression.Lambda <ClimbDelegate <T> >(climbBody,
                                                       "Climb_" + runtimeType.Name,
                                                       new[] { processor, value });

            ClimbDelegate <T> result = _compiler.Compile(lambda);

            return(result);
        }
예제 #9
0
        public Func <double, double> Compile(string expression)
        {
            expression = expression.ToLower();
            var tree = _Parser.Parse(expression);

            foreach (var opt in _Optimizers)
            {
                tree = opt.Optimize(tree);
            }

            return(_Compiler.Compile(tree));
        }
        public override CompileResult Compile()
        {
            var result = new List <object>();

            foreach (var childExpression in Children)
            {
                result.Add(_expressionCompiler.Compile(new List <Expression> {
                    childExpression
                }).Result);
            }
            return(new CompileResult(result, DataType.Enumerable));
        }
예제 #11
0
        public void StaticDependency_Relationships(string script, string expectedReferences)
        {
            var settings = CreateBuilderSettings("AA_Manager");

            IExpressionCompiler     compiler     = Factory.ExpressionCompiler;
            IExpression             expr         = compiler.Compile(script, settings);
            CalculationDependencies dependencies = compiler.GetCalculationDependencies(expr);

            var expected = expectedReferences
                           .Split(',', StringSplitOptions.RemoveEmptyEntries)
                           .Select(alias => new EntityRef(alias).Id)
                           .ToList();

            Assert.That(dependencies.Relationships, Is.EquivalentTo(expected));
        }
예제 #12
0
        public void CompileBranchForStringVariable(TextWriter writer, IExpressionCompiler valueCompiler, string label, bool negated)
        {
            if (CanCompileBoolean)
            {
                using (var tempVariables = Context.UseTempVariables())
                {
                    IEV3Variable tempResultVariable = tempVariables.CreateVariable(EV3Type.String);
                    IEV3Variable tempIsTrueVariable = tempVariables.CreateVariable(EV3Type.Float);
                    writer.WriteLine($"    CALL IS_TRUE {valueCompiler.Compile(writer, tempResultVariable)} {tempIsTrueVariable.Ev3Name}");
                    writer.WriteLine($"    JR_{(negated ? "EQ" : "NEQ")}8 {tempIsTrueVariable.Ev3Name} 0 {label}");

                    //writer.WriteLine($"    STRINGS DUPLICATE {Value} {tempResultVariable.Ev3Name}");
                    //writer.WriteLine($"    AND8888_32 {tempResultVariable.Ev3Name} -538976289 {tempResultVariable.Ev3Name}");
                    //writer.WriteLine($"    STRINGS COMPARE {tempResultVariable.Ev3Name} 'TRUE' {tempIsTrueVariable.Ev3Name}");
                    //writer.WriteLine($"    JR_EQ8 {tempIsTrueVariable.Ev3Name} 0 {label}");
                }
            }
        }
예제 #13
0
 public override string Compile(TextWriter writer, IEV3Variable variable)
 {
     using (var tempVariables = Context.UseTempVariables())
     {
         IExpressionCompiler indexCompiler = ParentExpression.Indexer.Compiler();
         string indexValue = indexCompiler.Compile(writer, tempVariables.CreateVariable(EV3Type.Float));
         if (variable.Ev3Name.Equals(Variable.Ev3Name, StringComparison.InvariantCultureIgnoreCase) ||
             variable.Type != Type.BaseType())
         {
             variable = tempVariables.CreateVariable(Type.BaseType());
         }
         if (variable.Type == EV3Type.String)
         {
             writer.WriteLine($"    CALL ARRAYGET_STRING {indexValue} {variable.Ev3Name} {Variable.Ev3Name}");
         }
         else
         {
             if (Context.DoBoundsCheck)
             {
                 writer.WriteLine($"    CALL ARRAYGET_FLOAT {indexValue} {variable.Ev3Name} {Variable.Ev3Name}");
             }
             else
             {
                 if (indexCompiler.IsLiteral)
                 {
                     if (indexValue.EndsWith(".0"))
                     {
                         indexValue = indexValue.Remove(indexValue.Length - 2);
                     }
                 }
                 else
                 {
                     writer.WriteLine($"    MOVEF_32 {indexValue} INDEX");
                     indexValue = "INDEX";
                 }
                 writer.WriteLine($"    ARRAY_READ {Variable.Ev3Name} {indexValue} {variable.Ev3Name}");
             }
         }
         return(variable.Ev3Name);
     }
 }
예제 #14
0
        public void CompileAssignment(TextWriter writer, string compiledValue, string outputName)
        {
            using (var tempVariables = Context.UseTempVariables())
            {
                IExpressionCompiler indexCompiler = ParentExpression.Indexer.Compiler();
                string indexValue = indexCompiler.Compile(writer, tempVariables.CreateVariable(EV3Type.Float));

                switch (Type.BaseType())
                {
                case EV3Type.Int8:
                case EV3Type.Int16:
                case EV3Type.Int32:
                case EV3Type.Float:
                    if (Context.DoBoundsCheck)
                    {
                        writer.WriteLine($"    CALL ARRAYSTORE_FLOAT {indexValue} {compiledValue} {outputName}");
                    }
                    else
                    {
                        if (indexCompiler.IsLiteral)
                        {
                            if (indexValue.EndsWith(".0"))
                            {
                                indexValue = indexValue.Remove(indexValue.Length - 2);
                            }
                        }
                        else
                        {
                            writer.WriteLine($"    MOVEF_32 {indexValue} INDEX");
                            indexValue = "INDEX";
                        }
                        writer.WriteLine($"    ARRAY_WRITE {outputName} {indexValue} {compiledValue}");
                    }
                    break;

                case EV3Type.String:
                    writer.WriteLine($"    CALL ARRAYSTORE_STRING {indexValue} {compiledValue} {outputName}");
                    break;
                }
            }
        }
        public RouteDelegate GetRouteDelegate(IStateMember member, Type runtimeMemberType)
        {
            ParameterExpression processor          = Expression.Parameter(typeof(object), "processor");
            ParameterExpression owner              = Expression.Parameter(typeof(object), "owner");
            ParameterExpression skipSpecialMethods = Expression.Parameter(typeof(bool), "skipSpecialMethods");

            var castedProcessor =
                processor.Convert(_processorType);

            DescriptorWriter descriptorWriter = new DescriptorWriter(_climbStore);

            DescriptorVariable descriptor =
                descriptorWriter.GetDescriptor(processor, owner, member, runtimeMemberType);

            MethodInfo methodToCall =
                _methodMapper.GetMethod(_processorType, member, runtimeMemberType, true);

            MethodCallExpression callProcess =
                Expression.Call(castedProcessor, methodToCall, descriptor.Reference);

            Expression callProcessWithSpecialMethods =
                _specialMutator.Mutate(callProcess, castedProcessor, owner, member, descriptor.Reference);

            BlockExpression body =
                Expression.Block(new[] { descriptor.Reference },
                                 descriptor.Declaration,
                                 Expression.Condition(skipSpecialMethods,
                                                      callProcess,
                                                      callProcessWithSpecialMethods));

            Expression <RouteDelegate> lambda =
                Expression.Lambda <RouteDelegate>(body,
                                                  "Route_" + runtimeMemberType.Name,
                                                  new[] { processor, owner, skipSpecialMethods });

            return(_compiler.Compile(lambda));
        }
예제 #16
0
        protected string CompileWithConvert(TextWriter writer, IExpressionCompiler compiler, EV3Type resultType, EV3Variables.TempVariableCreator tempVariables)
        {
            string value = compiler.Compile(writer, tempVariables.CreateVariable(compiler.Type));

            if (compiler.Type.BaseType().IsNumber() && resultType.BaseType() == EV3Type.String)
            {
                if (compiler.IsLiteral)
                {
                    return("'" + SmallBasicExtensions.FormatFloat(value) + "'");
                }
                else
                {
                    IEV3Variable outputVariable = tempVariables.CreateVariable(EV3Type.String);

                    writer.WriteLine($"    STRINGS VALUE_FORMATTED {value} '%g' 99 {outputVariable.Ev3Name}");

                    return(outputVariable.Ev3Name);
                }
            }
            else
            {
                return(value);
            }
        }
 public override CompileResult Compile()
 {
     return(_expressionCompiler.Compile(Children));
 }
예제 #18
0
        public override void Compile(TextWriter writer, bool isRootStatement)
        {
            string      label    = Context.GetNextLabelNumber().ToString();
            EV3Variable variable = Context.FindVariable(ParentStatement);

            if (variable.Type == EV3Type.Unknown)
            {
                variable.Type = EV3Type.Float;
            }
            variable.IsConstant = false;

            IExpressionCompiler stepCompiler = ParentStatement.StepValue == null ? null : ParentStatement.StepValue.Compiler();

            using (var tempVariables = Context.UseTempVariables())
            {
                string initialValue = ParentStatement.InitialValue.Compiler().Compile(writer, variable);
                if (initialValue != variable.Ev3Name)
                {
                    writer.WriteLine($"    MOVEF_F {initialValue} {variable.Ev3Name}");
                }
                writer.WriteLine($"  for{label}:");
                string finalValue = ParentStatement.FinalValue.Compiler().Compile(writer, tempVariables.CreateVariable(EV3Type.Float));
                if (stepCompiler == null || stepCompiler.IsLiteral)
                {
                    if (stepCompiler is NegativeExpressionCompiler)
                    {
                        writer.WriteLine($"    JR_LTF {variable.Ev3Name} {finalValue} endfor{label}");
                    }
                    else
                    {
                        writer.WriteLine($"    JR_GTF {variable.Ev3Name} {finalValue} endfor{label}");
                    }
                }
                else
                {
                    string       stepValue = stepCompiler.Compile(writer, tempVariables.CreateVariable(EV3Type.Float));
                    IEV3Variable tempStepResultVariable = tempVariables.CreateVariable(EV3Type.Float);
                    writer.WriteLine($"    CALL LE_STEP8 {variable.Ev3Name} {finalValue} {stepValue} {tempStepResultVariable.Ev3Name}");
                    writer.WriteLine($"    JR_EQ8 {tempStepResultVariable.Ev3Name} 0 endfor{label}");
                }
            }
            using (var tempVariables = Context.UseTempVariables())
            {
                writer.WriteLine($"  forbody{label}:");
                ParentStatement.ForBody.Compile(writer, false);
                string stepValue = stepCompiler == null ? "1.0" : stepCompiler.Compile(writer, tempVariables.CreateVariable(EV3Type.Float));
                writer.WriteLine($"    ADDF {variable.Ev3Name} {stepValue} {variable.Ev3Name}");
                string finalValue2 = ParentStatement.FinalValue.Compiler().Compile(writer, tempVariables.CreateVariable(EV3Type.Float));
                if (stepCompiler == null || stepCompiler.IsLiteral)
                {
                    if (stepCompiler is NegativeExpressionCompiler)
                    {
                        writer.WriteLine($"    JR_GTEQF {variable.Ev3Name} {finalValue2} forbody{label}");
                    }
                    else
                    {
                        writer.WriteLine($"    JR_LTEQF {variable.Ev3Name} {finalValue2} forbody{label}");
                    }
                }
                else
                {
                    IEV3Variable tempStepResultVariable = tempVariables.CreateVariable(EV3Type.Float);
                    writer.WriteLine($"    CALL LE_STEP8 {variable.Ev3Name} {finalValue2} {stepValue} {tempStepResultVariable.Ev3Name}");
                    writer.WriteLine($"    JR_NEQ8 {tempStepResultVariable.Ev3Name} 0 forbody{label}");
                }
                writer.WriteLine($"  endfor{label}:");
            }
        }
        /// <summary>
        /// Creates the evaluator for a single calculated field.
        /// </summary>
        /// <param name="calculatedField">Entity for the calculated field.</param>
        /// <param name="settings">Settings.</param>
        /// <returns></returns>
        private CalculatedFieldMetadata GetSingleCalculatedFieldMetadata(Field calculatedField, CalculatedFieldSettings settings)
        {
            string          calculation = null;
            IExpression     expression  = null;
            ParseException  exception   = null;
            BuilderSettings builderSettings;

            try
            {
                // Get calculation
                calculation = calculatedField.FieldCalculation;
                if (string.IsNullOrEmpty(calculation))
                {
                    throw new ArgumentException("The field has no calculation script. It may not be a calculated field.");
                }

                // Get settings
                builderSettings = CreateBuilderSettingsForField(calculatedField, settings);

                // Compile
                expression = _expressionCompiler.Compile(calculation, builderSettings);

                // Register cache invalidations
                if (CacheContext.IsSet())
                {
                    CalculationDependencies dependencies = _expressionCompiler.GetCalculationDependencies(expression);

                    using (CacheContext cacheContext = CacheContext.GetContext())
                    {
                        cacheContext.Entities.Add(calculatedField.Id);
                        cacheContext.Entities.Add(dependencies.IdentifiedEntities);
                        cacheContext.Entities.Add(builderSettings.RootContextType.EntityTypeId);
                    }
                }
            }
            catch (InvalidMemberParseException ex)
            {
                exception = ex;

                // If a parse-exception resulted from being unable to look up a member name, then it may be corrected by renaming some arbitrary field or relationship
                // that could not be otherwise detected by dependencies.IdentifiedEntities. So invalidate parse exceptions if any field/relationship changes.
                if (CacheContext.IsSet())
                {
                    using (CacheContext cacheContext = CacheContext.GetContext())
                    {
                        cacheContext.Entities.Add(ex.TypeId);
                        // TODO: ideally just listen for all fields/relationships attached to type
                        var fieldTypes = PerTenantEntityTypeCache.Instance.GetDescendantsAndSelf(new EntityRef("core:field").Id);
                        cacheContext.EntityTypes.Add(fieldTypes);
                        cacheContext.EntityTypes.Add(new EntityRef("core:relationship").Id);
                    }
                }
            }
            catch (ParseException ex)
            {
                exception = ex;
            }

            // Build metadata
            CalculatedFieldMetadata metadata = new CalculatedFieldMetadata(calculatedField.Id, calculation, expression, exception);

            return(metadata);
        }
        public override void Compile(TextWriter writer, bool isRootStatement)
        {
            IAssignmentExpressionCompiler variableCompiler = ParentStatement.LeftValue.Compiler <IAssignmentExpressionCompiler>();

            if (variableCompiler != null)
            {
                EV3Variable         variable      = Context.FindVariable(variableCompiler.VariableName);
                IExpressionCompiler valueCompiler = ParentStatement.RightValue.Compiler();

                if (variable.Type == EV3Type.Unknown)
                {
                    variable.Type = valueCompiler.Type;
                    if (variableCompiler.IsArray)
                    {
                        variable.Type = variable.Type.ConvertToArray();
                    }
                }
                variable.IsConstant &= isRootStatement && Context.DoOptimization && valueCompiler.IsLiteral && !variable.Type.IsArray();

                if (variable.Type.IsArray())
                {
                    if (valueCompiler is IAssignmentExpressionCompiler)
                    {
                        variable.UpdateMaxIndex(((IAssignmentExpressionCompiler)valueCompiler).Index);
                    }
                    else if (valueCompiler is LiteralExpressionCompiler)
                    {
                        variable.UpdateMaxIndex(((LiteralExpressionCompiler)valueCompiler).MaxIndex);
                    }
                }

                //Console.WriteLine($"valueCompiler.Type = {valueCompiler.Type}, variable.Type = {variable.Type}, variableCompiler.Type = {variableCompiler.Type}");

                if (variableCompiler.Type.IsArray() && (valueCompiler.Type != variableCompiler.Type))
                {
                    AddError($"Cannot assign value to array variable '{variableCompiler.VariableName}' without index");
                }
                else if (!variableCompiler.Type.IsArray() && valueCompiler.Type.IsArray())
                {
                    AddError($"Cannot assign array value to non-array variable '{variableCompiler.VariableName}'");
                }
                else if (valueCompiler.Type == EV3Type.String && variableCompiler.Type.IsNumber())
                {
                    AddError($"Cannot assign {valueCompiler.Type} value to {variableCompiler.Type} variable '{variableCompiler.VariableName}'");
                }
                else if (valueCompiler.Type.IsNumber() && variableCompiler.Type == EV3Type.String && !variable.Type.IsArray())
                {
                    if (variable.IsConstant)
                    {
                        variable.Value = valueCompiler.Value;
                    }
                    else
                    {
                        using (var tempVariables = Context.UseTempVariables())
                        {
                            IEV3Variable tempVariable  = tempVariables.CreateVariable(valueCompiler.Type);
                            string       compiledValue = valueCompiler.Compile(writer, tempVariable);
                            if (string.IsNullOrEmpty(compiledValue))
                            {
                                return;
                            }

                            writer.WriteLine($"    STRINGS VALUE_FORMATTED {compiledValue} '%g' 99 {variable.Ev3Name}");
                        }
                    }
                }
                else
                {
                    if (variable.IsConstant)
                    {
                        variable.Value = valueCompiler.Value;
                    }
                    else
                    {
                        string compiledValue = valueCompiler.Compile(writer, variable);
                        if (string.IsNullOrEmpty(compiledValue))
                        {
                            return;
                        }

                        using (var tempVariables = Context.UseTempVariables())
                        {
                            if (valueCompiler.Type.IsNumber() && variable.Type == EV3Type.StringArray)
                            {
                                IEV3Variable tempVariable = tempVariables.CreateVariable(EV3Type.String);
                                writer.WriteLine($"    STRINGS VALUE_FORMATTED {compiledValue} '%g' 99 {tempVariable.Ev3Name}");
                                compiledValue = tempVariable.Ev3Name;
                            }
                            variableCompiler.CompileAssignment(writer, compiledValue, variable.Ev3Name);
                        }
                    }
                }
            }
            else
            {
                AddError($"Cannot assign value to this expression {ParentStatement.LeftValue}");
            }
        }