Ejemplo n.º 1
0
 public void Evaluate(VariableContext vc)
 {
     foreach (Expression expression in Expressions)
     {
         new MathyLanguageService().CreateEvaluator().Evaluate(expression, vc);
     }
 }
Ejemplo n.º 2
0
 /// <summary>
 /// Initializes a new instance of the <see cref="CommonSteps"/> class.
 /// Привязка общих шагов к работе с переменным через контекст.
 /// </summary>
 /// <param name="variableContext">Контекст для работы с переменными.</param>
 /// <param name="fileSupport">Контекст для работы с файлами.</param>
 /// <param name="consoleOutputHelper">Capturing Output.</param>
 public CommonSteps(VariableContext variableContext, FileSupport fileSupport,
                    ITestOutputHelper consoleOutputHelper)
 {
     this.variableContext     = variableContext;
     this.fileSupport         = fileSupport;
     this.consoleOutputHelper = consoleOutputHelper;
 }
Ejemplo n.º 3
0
        public static Variable EvaluateDecisionByName(VariableContext runtimeContext, string decisionName)
        {
            if (runtimeContext == null || runtimeContext.DecisionMetaByName == null)
            {
                return(null);
            }

            runtimeContext.DecisionMetaByName.TryGetValue(decisionName, out var decision);

            if (decision == null)
            {
                return(null);
            }

            //cannot run a decision serivce input without an input override value
            if (decision.Id != null)
            {
                runtimeContext.HrefInputDecisionToDecisionServices.TryGetValue(decision.Id, out var decisionServices);
                runtimeContext.InputNameDict.TryGetValue("decisionName", out var decisionInput);
                if (decisionServices != null && decisionInput == null)
                {
                    throw new DMNException($"Decision :{decisionName} is part of a decision service input and is missing input data");
                }
            }

            return(decision.Expression
                   switch {
                TLiteralExpression litExpr => EvalLiteralExpression(litExpr.Text, runtimeContext),
                TDecisionTable decisionTable => EvalDecisionTable(decisionTable, runtimeContext),
                TContext contextDecision => EvalContext(contextDecision, runtimeContext),
                TRelation relation => EvalRelation(relation, runtimeContext),
                _ =>
                throw new DMNException($"Decision expression {decision.Expression.Id} is not supported yet"),
            });
Ejemplo n.º 4
0
        public object Execute(VariableContext context = null)
        {
            var leftVal  = this.Left.Execute(context);
            var rightVal = this.Right.Execute(context);

            if (leftVal is Variable l && rightVal is Variable r)
            {
                if (l.ValueType != r.ValueType)
                {
                    throw new FEELException("The variable type does not match for the arithmetic action");
                }
                switch (l.ValueType)
                {
                case DataTypeEnum.Decimal:
                    return(new Variable(l.NumericVal + r.NumericVal));

                case DataTypeEnum.String:
                    return(new Variable($"{l.StringVal}{r.StringVal}"));

                case DataTypeEnum.Date:
                case DataTypeEnum.DateTime:
                case DataTypeEnum.Time:
                case DataTypeEnum.YearMonthDuration:
                case DataTypeEnum.DayTimeDuration:
                    return(DateAndTimeHelper.Addition(l, r));

                default:
                    throw new FEELException("Failed to perform addition to incorrect FEEL type");
                }
            }

            throw new FEELException("Failed to perform addition due to values not being a variable");
        }
 public GenericVariable(VariableContext context, string name, string value)
 {
     this.Context       = context;
     this.ContextString = context.ToString();
     this.Name          = name;
     this.Value         = value;
 }
Ejemplo n.º 6
0
        public object Execute(VariableContext context = null)
        {
            var funcName = _function.Execute(context);

            if (funcName is Variable outFuncVar && outFuncVar.ValueType == DataTypeEnum.Function)
            {
                if (_parameters is PositionalParameters)
                {
                    var lVars = RetrieveListOfParameters(context);
                    return(outFuncVar.UserFunction.Execute(lVars, context));
                }
                if (_parameters is NamedParameters nParams)
                {
                    return(outFuncVar.UserFunction.Execute(null, context, nParams));
                }
            }

            if (funcName is Variable outFuncName && outFuncName.ValueType == DataTypeEnum.String)
            {
                List <Variable> lVars = new List <Variable> ();

                if (_parameters is PositionalParameters)
                {
                    lVars = RetrieveListOfParameters(context);
                    if (VariableContextHelper.RetrieveBkm(outFuncName, context, out var bkmMeta))
                    {
                        return(DMNDoerHelper.EvalBkm(bkmMeta.BKMModel, context, lVars));
                    }
                    if (context.DecisionServiceMetaByName.TryGetValue(outFuncName, out var decisionService))
                    {
                        return(DMNDoerHelper.EvalDecisionService(decisionService, context, lVars));
                    }
                }

                if (_parameters is NamedParameters namedParam)
                {
                    if (VariableContextHelper.RetrieveBkm(outFuncName, context, out var bkmMeta))
                    {
                        lVars = BKMConvertNamedParameter(namedParam, bkmMeta.BKMModel, context);
                        return(DMNDoerHelper.EvalBkm(bkmMeta.BKMModel, context, lVars));
                    }
                    if (context.DecisionServiceMetaByName.TryGetValue(outFuncName, out var decisionService))
                    {
                        lVars = DecisionServiceConvertNamedParameter(namedParam, decisionService, context);
                        return(DMNDoerHelper.EvalDecisionService(decisionService, context, lVars));
                    }
                }

                var funcMeta = BuiltInFactory.GetFunc(outFuncName);

                if (_parameters is NamedParameters nParam)
                {
                    lVars = BuiltInFactory.ConvertNamedParameter(nParam, funcMeta.Item2, context);
                }

                return(funcMeta.Item1.Execute(lVars));
            }

            throw new FEELException("Function name is not a variable of string type");
        }
Ejemplo n.º 7
0
        private object EvaluteMultiIndexingExpression(MultiIndexingExpression e, VariableContext context)
        {
            object value = Evaluate(e.Operand, context);

            int[] indexers = e.Indexers.Select(i => Types.ConvertValue <int>(Evaluate(i, context))).ToArray();

            if (e.Operand.Type.IsArray)
            {
                Array array = value as Array;

                return(array.GetValue(indexers[0]));
            }
            else if (e.Operand.Type.Equals(typeof(Matrix)))
            {
                Matrix m = value as Matrix;

                if (indexers.Length == 1)
                {
                    return(m.GetRow(indexers[0] - 1));
                }
                else
                {
                    return(m[indexers[0] - 1, indexers[1] - 1]);
                }
            }
            else
            {
                Vector v = value as Vector;

                return(v[indexers[0] - 1]);
            }
        }
Ejemplo n.º 8
0
        public Variable Execute(List <Variable> inputParams, VariableContext mainContext, NamedParameters nParams = null)
        {
            if (_isExternal)
            {
                //TODO: add error logging for no support for external java/PMML function types
                return(new Variable());
            }

            var context = mainContext ?? new VariableContext();

            if (nParams != null)
            {
                inputParams = BuiltInFactory.ConvertNamedParameter(nParams, _formalParams.Select(v => v.TwoTuple.a.StringVal).ToArray(), context);
            }

            if (inputParams != null && _formalParams.Count > 0)
            {
                if (_formalParams.Count != inputParams.Count)
                {
                    //TODO: Add to error logging for missmatch expected input
                    return(new Variable());
                }

                for (int i = _formalParams.Count - 1; i >= 0; i--)
                {
                    context.AddToFunctionInputs(_formalParams[i].TwoTuple.a.StringVal, inputParams[i]);
                }
            }

            try {
                return((Variable)_body.Execute(context));
            } catch (Exception) {
                return(new Variable());
            }
        }
Ejemplo n.º 9
0
        public object Execute(VariableContext context = null)
        {
            var contextInput = new ContextInputs();

            if (context == null)
            {
                context = new VariableContext();
            }

            if (context.LocalContext == null)
            {
                context.LocalContext = contextInput;
            }
            else if (context.LocalContext.ContextDict.ContainsKey("__currentContextX__"))
            {
                context.LocalContext.ContextDict["__currentContextX__"] = contextInput;
            }
            else
            {
                context.LocalContext.Add("__currentContextX__", contextInput);
            }

            foreach (var item in ContextEntries)
            {
                var itemVal = (Variable)item.Execute(context);
                contextInput.Add(itemVal.TwoTuple.a, itemVal.TwoTuple.b);
            }

            if (context.LocalContext != null)
            {
                context.LocalContext.ContextDict.Remove("__currentContextX__");
            }

            return(new Variable(contextInput));
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="UtilsTest"/> class.
 /// Инициализация переменных.
 /// </summary>
 public UtilsTest()
 {
     this.variableContext = new VariableContext();
     this.variableContext.SetVariable("first", typeof(string), "1");
     this.variableContext.SetVariable("second", typeof(string), "2");
     this.variableContext.SetVariable("third", typeof(string), "3");
 }
Ejemplo n.º 11
0
        private bool ParseAndEval(string exprText, VariableContext context, string inputName)
        {
            var eval    = new Evaluation();
            var boolVal = eval.EvaluateUnaryTestsBase(exprText, context, inputName);

            return(boolVal);
        }
Ejemplo n.º 12
0
        public static MultiVariableFunction FromString(string expression, params string[] variableNames)
        {
            var ctx  = VariableContext.FromVariableNames(variableNames);
            var root = StringTokenizer.ToExpression(expression, ctx);

            return(new MultiVariableFunction(root, variableNames));
        }
Ejemplo n.º 13
0
 public static void CanBuildExpressionWithComplexParentheses()
 {
     var ctx = new VariableContext(new Dictionary <string, ISymbol> {
         { "x", new Variable("x") }
     });
     var result = StringTokenizer.ToExpression("3*x + 3*x + ((3*x * 1)/(3*x * 1))", ctx);
 }
Ejemplo n.º 14
0
        public object Execute(VariableContext context = null)
        {
            var leftVal      = _left.Execute(context);
            var whichTypeVal = _whichType.Execute(context);

            if (whichTypeVal is Variable outType && outType.ValueType == DataTypeEnum.String)
            {
                ValidTypeNames.StringTypeToEnum.TryGetValue(outType.StringVal, out DataTypeEnum outDataType);

                if (leftVal is Variable outLeftVal)
                {
                    if (outDataType == DataTypeEnum.Any && outLeftVal.ValueType != DataTypeEnum.Null)
                    {
                        return(new Variable(true));
                    }
                    if (outLeftVal.ValueType == outDataType)
                    {
                        return(new Variable(true));
                    }
                    return(new Variable(false));
                }

                return(new Variable());
            }

            return(new Variable());
        }
Ejemplo n.º 15
0
        public static VariableContextExpression diff(VariableContextExpression expression, string variableName)
        {
            VariableContext c    = expression.VariableContext;
            Expression      diff = new Differ(expression.Expression, variableName).Calculate(c);

            TypeCheckingContext context = new MathyLanguageService().CreateTypeCheckingContext(c);

            foreach (VariableInfo variable in expression.Variables)
            {
                c.Set(variable.Name, context.CreateAutoCreatedVariableValue(variable.Type));
            }

            VariableContextExpression result = new VariableContextExpression(diff, expression.Variables, 0, 0)
            {
                VariableContext = expression.VariableContext
            };

            new MathyLanguageService().CreateTypeChecker().PerformTypeChecking(result, context);

            result = new VariableContextExpression(new Cherimoya.Reduction.ExpressionReductor(new MathyLanguageService()).Reduce(diff), expression.Variables, 0, 0)
            {
                VariableContext = expression.VariableContext
            };
            new MathyLanguageService().CreateTypeChecker().PerformTypeChecking(result, context);

            foreach (VariableInfo variable in expression.Variables)
            {
                context.VariableContext.Remove(variable.Name);
            }


            return(result);
        }
Ejemplo n.º 16
0
        //  a    b  a and b a or b
        // true true true true
        // true false false true
        // true otherwise null true
        // false true false true
        // false false false false
        // false otherwise false null
        // otherwise true null true
        // otherwise false false null
        // otherwise otherwise null null
        public object Execute(VariableContext context = null)
        {
            var leftVar  = Left.Execute(context);
            var rightVar = Right.Execute(context);

            if (leftVar is Variable outLVar && rightVar is Variable outRVar)
            {
                if (outLVar.ValueType == DataTypeEnum.Boolean && outRVar.ValueType == DataTypeEnum.Boolean)
                {
                    return(new Variable(outLVar.BoolVal || outRVar.BoolVal));
                }
                if (outLVar.ValueType == DataTypeEnum.Boolean && outLVar.BoolVal == true)
                {
                    return(new Variable(true));
                }
                if (outRVar.ValueType == DataTypeEnum.Boolean && outRVar.BoolVal == true)
                {
                    return(new Variable(true));
                }

                return(new Variable());
            }

            throw new FEELException("Expected both left and right values to be a variable");
        }
        private object EvaluteIndexingExpression(IndexingExpression expression, VariableContext context)
        {
            object instance = Evaluate(expression.Operand, context);
            int    index    = (int)Evaluate(expression.Indexer, context);

            return(((object[])instance)[index]);
        }
Ejemplo n.º 18
0
        public static void Test()
        {
            Assembly a;
            var      bs = BinarySerializerWithString.Create();

            using (var s = Streams.OpenReadable("Assembly.bin"))
            {
                a = bs.Read <Assembly>(s);
            }

            var vc = new VariableContext <int>();

            foreach (var m in a.Modules)
            {
                foreach (var f in m.Functions)
                {
                    vc.Replace(f.Name, f);
                }
            }

            var c = new Calculation(a);

            Trace.Assert(c.Character.GetUpgradeExperience(1, 2) == 2);

            TestBasic(vc);

            TestInteractive(vc);
        }
        private object EvaluteCastExpression(CastExpression expression, VariableContext context)
        {
            object value = Evaluate(expression.Operand, context);


            return(Types.CoerceValue(value, expression.TargetType));
        }
Ejemplo n.º 20
0
        public object Execute(VariableContext context = null)
        {
            var dateExprVar = DateExpression.Execute();

            if (dateExprVar is Variable dateExprOut)
            {
                switch (DateFunction)
                {
                case "date":
                    return(DateAndTimeHelper.DateVal(dateExprOut.StringVal));

                case "date and time":
                    return(DateAndTimeHelper.DateTimeVal(dateExprOut.StringVal));

                case "time":
                    return(DateAndTimeHelper.TimeVal(dateExprOut.StringVal));

                case "duration":
                    return(DateAndTimeHelper.DurationVal(dateExprOut.StringVal));

                default:
                    throw new FEELException($"The following date function {DateFunction} is not supported");
                }
            }

            throw new FEELException($"Failed executing date function {DateFunction}");
        }
Ejemplo n.º 21
0
        public ISymbol MakeSubstitutions(VariableContext ctx)
        {
            var o1 = Operand1.MakeSubstitutions(ctx);
            var o2 = Operand2.MakeSubstitutions(ctx);

            return(FromValues(Type, o1, o2));
        }
Ejemplo n.º 22
0
        public void EvaluateForStatement(string exprText, Variable expected)
        {
            VariableContext context = new VariableContext();

            Variable variable = ParseAndEval(exprText, context);

            Assert.True(variable.Equals(expected));
        }
Ejemplo n.º 23
0
        public void EvaluateQuantifiedStatement(string exprText, bool expectedBool)
        {
            VariableContext context = new VariableContext();

            Variable variable = ParseAndEval(exprText, context);

            Assert.Equal <bool> (expectedBool, variable);
        }
Ejemplo n.º 24
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void testEmptyVariableContext()
        public virtual void testEmptyVariableContext()
        {
            VariableContext varContext = emptyVariableContext();

            assertTrue(varContext.Keys.Count == 0);
            assertNull(varContext.resolve("nonExisting"));
            assertFalse(varContext.containsVariable("nonExisting"));
        }
        public override object Evaluate(Expression expression, VariableContext context)
        {
            if (expression is CastExpression)
            {
                return(EvaluteCastExpression((CastExpression)expression, context));
            }
            else if (expression is CreateObjectExpression)
            {
                return(EvaluteCreateObjectExpression((CreateObjectExpression)expression, context));
            }
            else if (expression is CreateArrayExpression)
            {
                return(EvaluteCreateArrayExpression((CreateArrayExpression)expression, context));
            }
            else if (expression is BinaryExpression)
            {
                return(EvaluteBinaryExpression((BinaryExpression)expression, context));
            }
            else if (expression is VariableExpression)
            {
                return(EvaluateVariableExpression((VariableExpression)expression, context));
            }
            else if (expression is MethodCallExpression)
            {
                return(EvaluteMethodCallExpression((MethodCallExpression)expression, context));
            }
            else if (expression is FunctionCallExpression)
            {
                return(EvaluteFunctionCallExpression((FunctionCallExpression)expression, context));
            }
            else if (expression is IndexingExpression)
            {
                return(EvaluteIndexingExpression((IndexingExpression)expression, context));
            }
            else if (expression is FieldExpression)
            {
                return(EvaluteFieldExpression((FieldExpression)expression, context));
            }
            else if (expression is LambdaExpression)
            {
                return(expression);
            }
            else if (expression is ConstantExpression)
            {
                return(EvaluateConstantExpression((ConstantExpression)expression));
            }
            else if (expression is UnaryExpression)
            {
                return(EvaluateUnaryExpression((UnaryExpression)expression, context));
            }
            else if (expression is IfElseExpression)
            {
                return(EvaluateIfElseExpression((IfElseExpression)expression, context));
            }


            return(null);
        }
Ejemplo n.º 26
0
        public static Matrix map(Matrix m, LambdaExpression mapper, VariableContext vc)
        {
            ExpressionEvaluator evaluator = new MathyLanguageService().CreateEvaluator();

            List <List <double> > result = new List <List <double> >();

            double[] row = new double[m.ColumnCount];

            for (int i = 0; i <= m.RowCount - 1; i++)
            {
                for (int j = 0; j <= m.ColumnCount - 1; j++)
                {
                    row[j] = m[i, j];
                }

                vc.Set(mapper.VariableNames[0], row.Where(c => !double.IsNaN(c)).ToArray());

                if (mapper.VariableNames.Length > 1)
                {
                    vc.Set(mapper.VariableNames[1], i);
                }

                double[] mappedRow;
                var      obj = evaluator.Evaluate(mapper.Body, vc);
                try
                {
                    mappedRow = (double[])obj;
                }
                catch (Exception ex)
                {
                    var a = (object[])obj;
                    mappedRow = (double[])a[0];
                }


                result.Add(new List <double>());

                for (int j = 0; j <= mappedRow.Length - 1; j++)
                {
                    result[i].Add(mappedRow[j]);
                }
            }

            vc.Remove(mapper.VariableNames[0]);


            List <double> cells = new List <double>();

            foreach (List <double> resultRow in result)
            {
                foreach (double cell in resultRow)
                {
                    cells.Add(cell);
                }
            }

            return(new Matrix(m.RowCount, result[0].Count, cells.ToArray()));
        }
Ejemplo n.º 27
0
        public static SingleVariableFunction FromString(string expression, string variableName)
        {
            var ctx = VariableContext.FromVariableNames(new List <string> {
                variableName
            });
            var root = StringTokenizer.ToExpression(expression, ctx);

            return(new SingleVariableFunction(root, variableName));
        }
Ejemplo n.º 28
0
        // TODO Remove
        //public static bool IsPropertyGetterOverride(this Object node, Property prop)
        //{
        //    var bt = node.BaseType;

        //    while (bt != null)
        //    {
        //        if (bt.Properties.Any(bp => bp.Name == prop.Name))
        //            return true;

        //        bt = bt.BaseType;
        //    }

        //    return false;
        //}

        //public static bool IsPropertySetterOverride(this Object node, Property prop)
        //{
        //    if (!prop.IsReadOnly)
        //        return false;

        //    var bt = node.BaseType;

        //    while (bt != null)
        //    {
        //        if (bt.Properties.Any(bp => bp.Name == prop.Name && !bp.IsReadOnly))
        //            return true;

        //        bt = bt.BaseType;
        //    }

        //    return false;
        //}


        public static IVariable ToVariable(this Type node, VariableContext ctx = VariableContext.Member, string name = null)
        {
            return(new Parameter()
            {
                Type = node,
                Name = name,
                Context = ctx
            });
        }
Ejemplo n.º 29
0
 public Parameter(Type type, string name, VariableContext ctx, bool isArray, bool hasDefaultValue = false, object defaultValue = null) : base(Construct.Parameter)
 {
     Type            = type;
     Name            = name;
     Context         = ctx;
     IsArray         = isArray;
     HasDefaultValue = hasDefaultValue;
     DefaultValue    = defaultValue;
 }
Ejemplo n.º 30
0
        public static Bitmap Visualize(string expressions, Dictionary <string, object> variables)
        {
            VariableContext c = Funcs.CreateVariableContext(variables);

            return(new NodeVisualizer(
                       new MathyLanguageService().Compile(expressions, c)
                       .Select(i => new NodeConverter().Convert(i))
                       .ToArray()).VisulizeAsBitmap());
        }
Ejemplo n.º 31
0
        /// <summary>
        /// Pushes the current in-scope Graph onto the Graph stack and creates a new empty Graph to be the in-scope Graph
        /// </summary>
        /// <remarks>
        /// Used for Graph Literal parsing - Base Uri and Namespace Maps of the outermost Graph is propogated to the innermost Graph
        /// </remarks>
        public void PushGraph()
        {
            Graph h = new Graph();
            h.NamespaceMap.Import(this.Namespaces);
            h.BaseUri = this.BaseUri;

            this._handlers.Push(this._handler);
            this._handler = new GraphHandler(h);
            this._handler.StartRdf();

            this._subgraphs.Push(this._g);
            this._g = h;

            VariableContext v = new VariableContext(VariableContextType.None);
            this._varContexts.Push(this._varContext);
            this._varContext = v;
        }
Ejemplo n.º 32
0
        private bool GenerateVariableQuantificationOutput(CompressingTurtleWriterContext context, VariableContext varContext)
        {
            if (varContext.Type == VariableContextType.None)
            {
                return false;
            }
            else if (varContext.Type == VariableContextType.Existential)
            {
                context.Output.Write("@forSome ");
            }
            else
            {
                context.Output.Write("@forAll ");
            }
            foreach (INode var in varContext.Variables)
            {
                context.Output.Write(context.NodeFormatter.Format(var));
                context.Output.Write(' ');
            }
            context.Output.WriteLine('.');

            if (varContext.InnerContext != null)
            {
                this.GenerateVariableQuantificationOutput(context, varContext.InnerContext);
            }
            return true;
        }
Ejemplo n.º 33
0
 /// <summary>
 /// Pops a Graph from the Graph stack to become the in-scope Graph
 /// </summary>
 /// <remarks>
 /// Used for Graph Literal parsing
 /// </remarks>
 public void PopGraph()
 {
     if (this._handlers.Count > 0)
     {
         this._g = this._subgraphs.Pop();
         this._handler.EndRdf(true);
         this._handler = this._handlers.Pop();
         this._varContext = this._varContexts.Pop();
     }
     else
     {
         throw new RdfParseException("Cannot pop a RDF Handler from the Parser Context to become the in-scope RDF Handler since there are no RDF Handlers on the stack");
     }
 }