/// <summary>
 /// Evaluates the function using <paramref name="args"/> as the input.
 /// </summary>
 /// <param name="args">The function arguments, including the result.</param>
 protected override void DoRun(FunctionArgs args)
 {
     object[] parameters = args.EvaluateParameters(new List<Type> { typeof(object[]), typeof(object[]) });
     object[] arr1 = (object[])parameters[0];
     object[] arr2 = (object[])parameters[1];
     args.Result = !arr2.Intersect(arr1).Any();
 }
 /// <summary>
 /// NCalc custom function evaluator
 /// </summary>
 /// <param name="name">name of the function to be evaluated</param>
 /// <param name="args">FunctionArgs object from where the function arguments will be read and the function evaluation result will be stored</param>
 private void EvaluateFunction(string name, FunctionArgs args)
 {
     if (name == "defined")
     {
         //it is here assumed that defined always takes one argument and is of type identifier
         Identifier identifier = (Identifier)args.Parameters[0].ParsedExpression;
         args.Result = _definesHandler.IsDefined(identifier.Name);
     }
 }
        /// <summary>
        /// Evaluates the function using <paramref name="args"/> as the input.
        /// </summary>
        /// <param name="name">The name of the function to evaluate.</param>
        /// <param name="args">The function arguments, including the result.</param>
        public void Run(string name, FunctionArgs args)
        {
            if (name != this.FunctionName)
            {
                // Use the default implementation.
                return;
            }

            this.DoRun(args);
        }
        /// <summary>
        /// Evaluates the function using <paramref name="args"/> as the input.
        /// </summary>
        /// <param name="args">The function arguments, including the result.</param>
        protected override void DoRun(FunctionArgs args)
        {
            List<Type> parameterTypes = new List<Type> { typeof(string), typeof(DateTime), typeof(DateTime) };
            object[] parameters = args.EvaluateParameters(parameterTypes);
            string unitOfMeasure = parameters[0] as string;
            DateTime? date1 = parameters[1] as DateTime?;
            DateTime? date2 = parameters[2] as DateTime?;

            TimeSpan ts = date2.Value - date1.Value;
            PropertyInfo propInfo = ts.GetType().GetProperty("Total" + unitOfMeasure);
            args.Result = propInfo.GetValue(ts, null);
        }
 /// <summary>
 /// Evaluates the function using <paramref name="args"/> as the input.
 /// </summary>
 /// <param name="args">The function arguments, including the result.</param>
 protected override void DoRun(FunctionArgs args)
 {
     args.Result = false;
     foreach (Expression childExpression in args.Parameters)
     {
         object result = childExpression.Evaluate();
         if (result.Equals(true))
         {
             args.Result = true;
             break;
         }
     }
 }
        /// <summary>
        /// Evaluates the function using <paramref name="args"/> as the input.
        /// </summary>
        /// <param name="args">The function arguments, including the result.</param>
        protected override void DoRun(FunctionArgs args)
        {
            // Try dates first.
            if (this.TryMaxDate(args))
            {
                return;
            }

            // If not dates assume they are numbers.
            object max = args.Parameters[0].Evaluate();
            for (int i = 1; i < args.Parameters.Length; i++)
            {
                max = Numbers.Max(max, args.Parameters[i].Evaluate());
            }

            args.Result = max;
        }
        /// <summary>
        /// Attempts to evaluate the function using <paramref name="args"/> as the input.
        /// Will only succeed if all function arguments are of type <see cref="System.DateTime"/>.
        /// </summary>
        /// <param name="args">The function arguments, including the result.</param>
        /// <returns>true if a result is determined; otherwise false.</returns>
        private bool TryMaxDate(FunctionArgs args)
        {
            ValueExpression[] valueExpressions = args.Parameters.Select(p => p.ParsedExpression as ValueExpression).ToArray();
            if (valueExpressions.Count(e => e == null || e.Type != NCalcValueType.DateTime) > 0)
            {
                return false;
            }

            DateTime maxDate = (DateTime)args.Parameters[0].Evaluate();
            for (int i = 1; i < args.Parameters.Length; i++)
            {
                DateTime compareVal = (DateTime)args.Parameters[i].Evaluate();
                if (maxDate.CompareTo(compareVal) < 0)
                {
                    maxDate = compareVal;
                }
            }

            args.Result = maxDate;
            return true;
        }
        /// <summary>
        /// Some extra functions for NCalc engine.
        /// </summary>
        public static void NCalcExtensionFunctions(string name, FunctionArgs functionArgs)
        {
            //
            // TO LEARN MORE ABOUT THIS SYSTEM PLEASE
            // HAVE A LOOK AT: HTTP://NCALC.CODEPLEX.COM
            //

            //
            // FACTORIAL FUNCTION
            //

            if (name == "fact") {

                if (functionArgs.Parameters.Length == 1) {

                    functionArgs.Result = fact ((int)functionArgs.Parameters [0].Evaluate ());

                } else {

                    functionArgs.Result = 1;

                }
            }
        }
        protected bool HandleLimitFunc(FunctionArgs args, List<double> evaluatedArgs)
        {
            if (evaluatedArgs.Count != 1)
            {
                return false;
            }

            if (evaluatedArgs[0] > 1)
            {
                args.Result = 1;
            }
            else if (evaluatedArgs[0] < 0)
            {
                args.Result = 0;
            }
            else
            {
                args.Result = evaluatedArgs[0];
            }

            return true;
        }
 /// <summary>
 /// Evaluates the function using <paramref name="args"/> as the input.
 /// </summary>
 /// <param name="args">The function arguments, including the result.</param>
 protected abstract void DoRun(FunctionArgs args);
        /// <summary>
        /// The snap function will transform a curve so that it starts and ends at the control points on either side of it.
        /// </summary>
        /// <param name="args">args should have 1 parameter that stores an equation to apply snap to.</param>
        protected bool HandleSnapFunc(FunctionArgs args, List<double> evaluatedArgs)
        {
            if (evaluatedArgs.Count != 1)
            {
                return false;
            }

            //Get the index of the curve to apply snap to.
            int curveIndex = GetCurveIndex();

            //True if there is a control point before the curve.
            bool pointBeforeCurveExists = (curveIndex > 0);
            //True if there is a control point after the curve.
            bool pointAfterCurveExists = (curveIndex < this.controlPointValues.Count);

            Expression remainingExpression = args.Parameters[0];

            //Store the raw output of the argument.
            double snapOutputValue = evaluatedArgs[0];

            bool errorEncountered = false;
            ReturnStatus<double> evaluateStatus;

            //If there is a control point on either side of the equation then snap will need to
            //modify the output.
            if (pointBeforeCurveExists || pointAfterCurveExists)
            {
                XyPoint<double> pointBeforeCurve = null;
                XyPoint<double> rawCurveStart = null;

                XyPoint<double> pointAfterCurve = null;
                XyPoint<double> rawCurveEnd = null;

                EvaluationCurveInput endpointInput = (EvaluationCurveInput)this.evalInput.Clone();

                //If there is a control point before the equation then we need to evaluate the
                //equation at this point.
                if (pointBeforeCurveExists)
                {
                    pointBeforeCurve = controlPointValues[curveIndex - 1];
                    endpointInput.setPrimaryInputVal(pointBeforeCurve.X);
                    SetExpressionCurveParameters(endpointInput, remainingExpression);

                    evaluateStatus = EvaluateExpression(remainingExpression);
                    errorEncountered |= !evaluateStatus.IsValid;
                    rawCurveStart = new XyPoint<double>(pointBeforeCurve.X, evaluateStatus.Value);

                }

                //If there is a control point after the equation then we need to evaluate the
                //equation at this point.
                if (pointAfterCurveExists && errorEncountered == false)
                {
                    pointAfterCurve = controlPointValues[curveIndex];
                    endpointInput.setPrimaryInputVal(pointAfterCurve.X);
                    SetExpressionCurveParameters(endpointInput, remainingExpression);

                    evaluateStatus = EvaluateExpression(remainingExpression);
                    errorEncountered |= !evaluateStatus.IsValid;

                    rawCurveEnd = new XyPoint<double>(pointAfterCurve.X, evaluateStatus.Value);
                }

                if (errorEncountered == false)
                {
                    if (pointBeforeCurveExists && pointAfterCurveExists)
                    {
                        snapOutputValue += GetEndPointSnapOffset(pointBeforeCurve.Y, rawCurveStart.Y,
                            pointBeforeCurve.X, pointAfterCurve.X, this.evalInput.getPrimaryInputVal());

                        snapOutputValue += GetEndPointSnapOffset(pointAfterCurve.Y, rawCurveEnd.Y,
                            pointAfterCurve.X, pointBeforeCurve.X, this.evalInput.getPrimaryInputVal());
                    }
                    else if (pointBeforeCurveExists)
                    {
                        double yOffset = pointBeforeCurve.Y - rawCurveStart.Y;
                        snapOutputValue += yOffset;
                    }
                    else //pointAfterCurveExists
                    {
                        Debug.Assert(pointAfterCurveExists);
                        double yOffset = pointAfterCurve.Y - rawCurveEnd.Y;
                        snapOutputValue += yOffset;
                    }
                }
            }

            if (errorEncountered)
            {
                return false;
            }
            else
            {
                args.Result = snapOutputValue;
                return true;
            }
        }
        //See EvaluationJob.FunctionHandler for documentation
        protected override ReturnStatus<bool> HandleCustomFunctions(string funcName, 
            FunctionArgs args,
            List<double> evaluatedArgs)
        {
            ReturnStatus<bool> retStatus = new ReturnStatus<bool>();

            switch (funcName)
            {
                case FUNC_NAME_SNAP:
                    retStatus.IsValid = HandleSnapFunc(args, evaluatedArgs);
                    break;
                case FUNC_NAME_LFO:
                    retStatus.IsValid = HandleLfoFunc(args, evaluatedArgs);
                    break;
                case FUNC_NAME_WAVEFORM:
                    retStatus.IsValid = HandleWaveformFunc(args, evaluatedArgs);
                    break;
                default:
                    return HandleBaseFunctions(funcName, args, evaluatedArgs);
            }

            retStatus.Value = true;
            return retStatus;
        }
示例#13
0
        private void EvaluateTranslate(FunctionArgs args, List<Dictionary<string, object>> localVariableStack, List<object> dotOperatorStack)
        {
            string evaluated = (string)args.Parameters[0].Evaluate();

            args.Result = LocalizationManager.Translate(evaluated);
        }
示例#14
0
        private void EvaluateFunctionGetStaticMember(ElementRuntime elementRuntime, FunctionArgs args, CodeContext codeContext)
        {

            string argument = (string)args.Parameters[0].ParsedExpression.ToString();

            string value = (string) mExpressionParser.EvaluateExpression(argument, codeContext);

            ReferencedFileSave rfs = elementRuntime.AssociatedIElement.GetReferencedFileSaveByInstanceNameRecursively(value);

            args.Result = elementRuntime.LoadReferencedFileSave(rfs, true, elementRuntime.AssociatedIElement);
        }
示例#15
0
        private void HandleFlatRedBallServicesValues(FunctionArgs args, List<object> dotOperatorStack, string containerName, ref bool found, ref bool wasSet)
        {
            if (!found && containerName == "FlatRedBallServices")
            {
                dotOperatorStack.Add("FlatRedBallServices");

                wasSet = true;
                args.Result = args.Parameters[1].Evaluate();

                dotOperatorStack.RemoveAt(dotOperatorStack.Count - 1);
            }
            if (!found && containerName == "GraphicsOptions" && GetDottedChainString(dotOperatorStack) == "FlatRedBallServices.")
            {
                dotOperatorStack.Add("GraphicsOptions");

                wasSet = true;
                args.Result = args.Parameters[1].Evaluate();

                dotOperatorStack.RemoveAt(dotOperatorStack.Count - 1);
            }

        }
示例#16
0
 private void GetEvaluated(ElementRuntime elementRuntime, FunctionArgs args, List<Dictionary<string, object>> localVariableStack, List<object> dotOperatorStack, out object firstEvaluated, out object secondEvaluated)
 {
     firstEvaluated = args.Parameters[0].Evaluate();
     secondEvaluated = args.Parameters[1].Evaluate();
 }
 protected override void DoRun(FunctionArgs args)
 {
     args.Result = null;
 }
示例#18
0
 /// <summary>
 /// Evaluates the function using <paramref name="args"/> as the input.
 /// </summary>
 /// <param name="args">The function arguments, including the result.</param>
 protected override void DoRun(FunctionArgs args)
 {
     args.Result = args.Parameters.Select(item => item.Evaluate()).ToArray();
 }
        public override void Visit(Function function)
        {
            var functionArgs = new FunctionArgs
            {
                Parameters = new Expression[function.Expressions.Length]
            };

            // Don't call parameters right now, instead let the function do it as needed.
            // Some parameters shouldn't be called, for instance, in a if(), the "not" value might be a division by zero
            // Evaluating every value could produce unexpected behaviour
            for (int i = 0; i < function.Expressions.Length; i++)
            {
                functionArgs.Parameters[i] = new Expression(function.Expressions[i], _options);
                functionArgs.Parameters[i].EvaluateFunction  += EvaluateFunction;
                functionArgs.Parameters[i].EvaluateParameter += EvaluateParameter;

                // Assign the parameters of the Expression to the arguments so that custom Functions and Parameters can use them
                functionArgs.Parameters[i].Parameters = Parameters;
            }

            OnEvaluateFunction(IgnoreCaseString ? function.Identifier.Name.ToLower() : function.Identifier.Name, functionArgs);

            var args = new L.Expression[function.Expressions.Length];

            for (int i = 0; i < function.Expressions.Length; i++)
            {
                function.Expressions[i].Accept(this);
                args[i] = _result;
            }

            switch (function.Identifier.Name.ToLowerInvariant())
            {
            case "abs":
                if (function.Expressions.Length != 1)
                {
                    throw new ArgumentException("Abs() takes exactly 1 argument");
                }

                var useDouble = _options.HasFlag(
                    EvaluateOptions.UseDoubleForAbsFunction);

                MethodInfo   absMethod;
                L.Expression absArg0;
                if (useDouble)
                {
                    absMethod = typeof(Math).GetRuntimeMethod(
                        nameof(Math.Abs),
                        new[] { typeof(double) });
                    absArg0 = L.Expression.Convert(args[0], typeof(double));
                }
                else
                {
                    absMethod = typeof(Math).GetRuntimeMethod(
                        nameof(Math.Abs),
                        new[] { typeof(decimal) });
                    absArg0 = L.Expression.Convert(args[0], typeof(decimal));
                }

                _result = L.Expression.Call(absMethod, absArg0);
                break;

            case "acos":
                if (function.Expressions.Length != 1)
                {
                    throw new ArgumentException("Acos() takes exactly 1 argument");
                }

                var acosMethod = typeof(Math).GetRuntimeMethod(
                    nameof(Math.Acos),
                    new[] { typeof(double) });
                var acosArg0 = L.Expression.Convert(args[0], typeof(double));
                _result = L.Expression.Call(acosMethod, acosArg0);
                break;

            case "asin":
                if (function.Expressions.Length != 1)
                {
                    throw new ArgumentException("Asin() takes exactly 1 argument");
                }

                var asinMethod = typeof(Math).GetRuntimeMethod(
                    nameof(Math.Asin),
                    new[] { typeof(double) });
                var asinArg0 = L.Expression.Convert(args[0], typeof(double));
                _result = L.Expression.Call(asinMethod, asinArg0);
                break;

            case "atan":
                if (function.Expressions.Length != 1)
                {
                    throw new ArgumentException("Atan() takes exactly 1 argument");
                }

                var atanMethod = typeof(Math).GetRuntimeMethod(
                    nameof(Math.Atan),
                    new[] { typeof(double) });
                var atanArgs0 = L.Expression.Convert(args[0], typeof(double));
                _result = L.Expression.Call(atanMethod, atanArgs0);
                break;

            case "ceiling":
                if (function.Expressions.Length != 1)
                {
                    throw new ArgumentException("Ceiling() takes exactly 1 argument");
                }

                var ceilingMethod = typeof(Math).GetRuntimeMethod(
                    nameof(Math.Ceiling),
                    new[] { typeof(double) });
                var ceilingArgs0 = L.Expression.Convert(args[0], typeof(double));
                _result = L.Expression.Call(ceilingMethod, ceilingArgs0);
                break;

            case "cos":
                if (function.Expressions.Length != 1)
                {
                    throw new ArgumentException("Cos() takes exactly 1 argument");
                }

                var cosMethod = typeof(Math).GetRuntimeMethod(
                    nameof(Math.Cos),
                    new[] { typeof(double) });
                var cosArgs0 = L.Expression.Convert(args[0], typeof(double));
                _result = L.Expression.Call(cosMethod, cosArgs0);
                break;

            case "exp":
                if (function.Expressions.Length != 1)
                {
                    throw new ArgumentException("Exp() takes exactly 1 argument");
                }

                var expMethod = typeof(Math).GetRuntimeMethod(
                    nameof(Math.Exp),
                    new[] { typeof(double) });
                var expArgs0 = L.Expression.Convert(args[0], typeof(double));
                _result = L.Expression.Call(expMethod, expArgs0);
                break;

            case "floor":
                if (function.Expressions.Length != 1)
                {
                    throw new ArgumentException("Floor() takes exactly 1 argument");
                }

                var floorMethod = typeof(Math).GetRuntimeMethod(
                    nameof(Math.Floor),
                    new[] { typeof(double) });
                var floorArgs0 = L.Expression.Convert(args[0], typeof(double));
                _result = L.Expression.Call(floorMethod, floorArgs0);
                break;

            case "ieeeremainder":
                if (function.Expressions.Length != 2)
                {
                    throw new ArgumentException("IEEEReaminer() takes exactly 2 arguments");
                }

                var ieeeMethod = typeof(Math).GetRuntimeMethod(
                    nameof(Math.IEEERemainder),
                    new[] { typeof(double), typeof(double) });
                var ieeeMethodArgs0 = L.Expression.Convert(
                    args[0],
                    typeof(double));
                var ieeeMethodArgs1 = L.Expression.Convert(
                    args[1],
                    typeof(double));
                _result = L.Expression.Call(ieeeMethod, ieeeMethodArgs0, ieeeMethodArgs1);
                break;

            case "log":
                if (function.Expressions.Length != 2)
                {
                    throw new ArgumentException("Log() takes exactly 2 arguments");
                }

                var logMethod = typeof(Math).GetRuntimeMethod(
                    nameof(Math.Log),
                    new[] { typeof(double), typeof(double) });
                var logMethodArgs0 = L.Expression.Convert(
                    args[0],
                    typeof(double));
                var logMethodArgs1 = L.Expression.Convert(
                    args[1],
                    typeof(double));
                _result = L.Expression.Call(logMethod, logMethodArgs0, logMethodArgs1);
                break;

            case "log10":
                if (function.Expressions.Length != 1)
                {
                    throw new ArgumentException("Log10() takes exactly 1 argument");
                }

                var log10Method = typeof(Math).GetRuntimeMethod(
                    nameof(Math.Log10),
                    new[] { typeof(double) });
                var log10Args0 = L.Expression.Convert(args[0], typeof(double));
                _result = L.Expression.Call(log10Method, log10Args0);
                break;

            case "round":
                var roundParameterCount = function.Expressions.Length;
                if (roundParameterCount == 0 || roundParameterCount > 2)
                {
                    throw new ArgumentException("Round() takes exactly 1 or 2 arguments");
                }

                var rounding =
                    _options.HasFlag(EvaluateOptions.RoundAwayFromZero)
                            ? MidpointRounding.AwayFromZero
                            : MidpointRounding.ToEven;

                if (roundParameterCount == 1)
                {
                    var roundMethod = typeof(Math).GetRuntimeMethod(
                        nameof(Math.Round),
                        new[]
                    {
                        typeof(double),
                        typeof(MidpointRounding)
                    });

                    var roundMethodArg0 = L.Expression.Convert(
                        args[0],
                        typeof(double));

                    _result = L.Expression.Call(
                        roundMethod,
                        roundMethodArg0,
                        L.Expression.Constant(rounding));
                }
                else
                {
                    var roundMethod = typeof(Math).GetRuntimeMethod(
                        nameof(Math.Round),
                        new[]
                    {
                        typeof(double), typeof(int),
                        typeof(MidpointRounding)
                    });
                    var roundMethodArg0 = L.Expression.Convert(
                        args[0],
                        typeof(double));
                    var roundMethodArg1 = L.Expression.Convert(
                        args[1],
                        typeof(int));
                    _result = L.Expression.Call(
                        roundMethod,
                        roundMethodArg0,
                        roundMethodArg1,
                        L.Expression.Constant(rounding));
                }

                break;

            case "sign":
                if (function.Expressions.Length != 1)
                {
                    throw new ArgumentException("Sign() takes exactly 1 argument");
                }

                var signMethod = typeof(Math).GetRuntimeMethod(
                    nameof(Math.Sign),
                    new[] { typeof(double) });
                var signArgs0 = L.Expression.Convert(args[0], typeof(double));
                _result = L.Expression.Call(signMethod, signArgs0);
                break;

            case "sin":
                if (function.Expressions.Length != 1)
                {
                    throw new ArgumentException("Sin() takes exactly 1 argument");
                }

                var sinMethod = typeof(Math).GetRuntimeMethod(
                    nameof(Math.Sin),
                    new[] { typeof(double) });
                var sinArgs0 = L.Expression.Convert(args[0], typeof(double));
                _result = L.Expression.Call(sinMethod, sinArgs0);
                break;

            case "sqrt":
                if (function.Expressions.Length != 1)
                {
                    throw new ArgumentException("Sqrt() takes exactly 1 argument");
                }

                var sqrtMethod = typeof(Math).GetRuntimeMethod(
                    nameof(Math.Sqrt),
                    new[] { typeof(double) });
                var sqrtArgs0 = L.Expression.Convert(args[0], typeof(double));
                _result = L.Expression.Call(sqrtMethod, sqrtArgs0);
                break;

            case "tan":
                if (function.Expressions.Length != 1)
                {
                    throw new ArgumentException("Tan() takes exactly 1 argument");
                }

                var tanMethod = typeof(Math).GetRuntimeMethod(
                    nameof(Math.Tan),
                    new[] { typeof(double) });
                var tanArgs0 = L.Expression.Convert(args[0], typeof(double));
                _result = L.Expression.Call(tanMethod, tanArgs0);
                break;

            case "truncate":
                if (function.Expressions.Length != 1)
                {
                    throw new ArgumentException("Truncate() takes exactly 1 argument");
                }

                var truncateMethod = typeof(Math).GetRuntimeMethod(
                    nameof(Math.Truncate),
                    new[] { typeof(double) });
                var truncateArgs0 = L.Expression.Convert(args[0], typeof(double));
                _result = L.Expression.Call(truncateMethod, truncateArgs0);
                break;

            case "if":
                if (args[0].Type != typeof(bool))
                {
                    throw new ArgumentException("if statement must have a boolean condition to process");
                }
                var(args1, args2) = AlignFloatingPointTypes(args[1], args[2]);
                _result           = L.Expression.Condition(args[0], args1, args2);
                break;

            case "in":
                var items = L.Expression.NewArrayInit(args[0].Type,
                                                      new ArraySegment <L.Expression>(args, 1, args.Length - 1).ToArray());
                var smi = typeof(Array).GetRuntimeMethod("IndexOf", new[] { typeof(Array), typeof(object) });
                var r   = L.Expression.Call(smi, L.Expression.Convert(items, typeof(Array)), L.Expression.Convert(args[0], typeof(object)));
                _result = L.Expression.GreaterThanOrEqual(r, L.Expression.Constant(0));
                break;

            case "min":
                var min_arg0 = L.Expression.Convert(args[0], typeof(double));
                var min_arg1 = L.Expression.Convert(args[1], typeof(double));
                _result = L.Expression.Condition(L.Expression.LessThan(min_arg0, min_arg1), min_arg0, min_arg1);
                break;

            case "max":
                var max_arg0 = L.Expression.Convert(args[0], typeof(double));
                var max_arg1 = L.Expression.Convert(args[1], typeof(double));
                _result = L.Expression.Condition(L.Expression.GreaterThan(max_arg0, max_arg1), max_arg0, max_arg1);
                break;

            case "pow":
                var pow_arg0 = L.Expression.Convert(args[0], typeof(double));
                var pow_arg1 = L.Expression.Convert(args[1], typeof(double));
                _result = L.Expression.Power(pow_arg0, pow_arg1);
                break;

            default:
                if (functionArgs.HasResult)
                {
                    _result = L.Expression.Constant(functionArgs.Result);
                    break;
                }

                var mi = FindMethod(function.Identifier.Name, args);
                _result = L.Expression.Call(_context, mi.BaseMethodInfo, mi.PreparedArguments);
                break;
            }
        }
示例#20
0
        private static void GetContainerAndVariableNames(FunctionArgs args, out string containerName, out string variableName)
        {
            containerName = (string)args.Parameters[0].ParsedExpression.ToString();
            variableName = (string)args.Parameters[1].ParsedExpression.ToString();

            // The ParsedExpression.ToString returns the variable name with brackets
            // so we need to remove the first and last char
            if (containerName.Length > 2)
            {
                containerName = containerName.Substring(1, containerName.Length - 2);
            }
            if (variableName.Length > 2)
            {
                variableName = variableName.Substring(1, variableName.Length - 2);
            }
        }
 private void OnEvaluateFunction(string name, FunctionArgs args)
 => EvaluateFunction?.Invoke(name, args);
示例#22
0
        private bool GetFloatValue(ElementRuntime elementRuntime, FunctionArgs args, string variableName)
        {
            float valueToSet = float.NaN;
            bool wasSet = false;
            switch (variableName)
            {
                case "PositiveInfinity":
                    valueToSet = float.PositiveInfinity;
                    wasSet = true;
                    break;
                case "NegativeInfinity":
                    valueToSet = float.NegativeInfinity;
                    wasSet = true;
                    break;
                case "MaxValue":
                    valueToSet = float.MaxValue;
                    wasSet = true;
                    break;
                case "MinValue":
                    valueToSet = float.MinValue;
                    wasSet = true;
                    break;
            }

            if (wasSet)
            {
                args.Result = valueToSet;
            }

            return wasSet;
        }
示例#23
0
        void EvaluateFunction(object target, string name, FunctionArgs args, Dictionary<string, object> extras, bool caseSensitive)
        {
            if (!caseSensitive)
            {
                name = name.ToLowerInvariant();
            }

            // If a dotted name then do a slow evaluation, for functions we can only have a list of properties then a function call
            if (!_funcs.ContainsKey(name) && name.Contains("."))
            {
                string[] parts = name.Split('.');
                object ret = EvaluateParameter(target, parts[0], extras, caseSensitive);

                for (int i = 1; i < parts.Length - 1; ++i)
                {
                    ret = GetValue(ret, parts[i], caseSensitive);
                }

                object[] oa = args.EvaluateParameters();

                Type type = ret as Type;

                if ((type != null) && typeof(PySnippet).IsAssignableFrom(type))
                {
                    PySnippet snippet = (PySnippet)Activator.CreateInstance(type);

                    _funcs.Add(name, (o, a) => snippet.Invoke(o, parts[parts.Length-1], a));

                    args.Result = _funcs[name](target, oa);
                }
                else
                {
                    ret = ret.GetType();
                    Type[] ta = new Type[oa.Length];

                    for (int i = 0; i < oa.Length; ++i)
                    {
                        ta[i] = oa[i].GetType();
                    }

                    MethodInfo method = null;
                    try
                    {
                        method = type.GetMethod(parts[parts.Length - 1], GetFlags(caseSensitive), null, ta, null);
                    }
                    catch (AmbiguousMatchException)
                    {
                    }

                    if (method == null)
                    {
                        throw new ArgumentException(String.Format(Properties.Resources.ExpressionResolver_CannotFuncFunction, name));
                    }

                    args.Result = method.Invoke(ret, oa);
                }
            }
            else
            {
                if (!_funcs.ContainsKey(name))
                {
                    if (_targetType == null)
                    {
                        throw new ArgumentException(String.Format(Properties.Resources.ExpressionResolver_CannotFuncFunction, name));
                    }

                    Type baseType = _targetType;

                    MethodInfo method = baseType.GetMethod(name, GetFlags(caseSensitive));
                    if (method == null)
                    {
                        // Not a method, try a type name which we expect to be a script
                        Type type = baseType.Assembly.GetType(name);

                        if ((type == null) || !typeof(PySnippet).IsAssignableFrom(type))
                        {
                            throw new ArgumentException(String.Format(Properties.Resources.ExpressionResolver_CannotFuncFunction, name));
                        }

                        PySnippet snippet = (PySnippet)Activator.CreateInstance(type);

                        _funcs.Add(name, (o, a) => snippet.Invoke(o, null, a));
                    }
                    else
                    {
                        _funcs.Add(name, (o, a) => method.Invoke(o, a));
                    }
                }

                args.Result = _funcs[name](target, args.EvaluateParameters());
            }
        }
示例#24
0
        private void EvaluateInterpolateBetween(FunctionArgs args, List<Dictionary<string, object>> localVariableStack, List<object> dotOperatorStack)
        {
            // finish here
            if (args.Parameters.Length == 3)
            {
                ElementRuntime elementRuntime = dotOperatorStack.Last() as ElementRuntime;


                object firstStateSaveAsObject = args.Parameters[0].Evaluate();
                object secondStateSaveAsObject = args.Parameters[1].Evaluate();
                object interpolationValueAsObject = args.Parameters[2].Evaluate();

                InterpolateBetween(elementRuntime, firstStateSaveAsObject, secondStateSaveAsObject, interpolationValueAsObject, LogStringBuilder);
                args.Result = SpecialValues.Null;
            }
            else
            {
                // This is bad code!
            }
        }
        /// <summary>
        /// Called by NCalc when attempting to evaluate custom functions.
        /// </summary>
        /// <param name="funcName">Name of the function being evaluated</param>
        /// <param name="args">Arguments for the function specified by funcName</param>
        protected void FunctionHandler(string funcName, FunctionArgs args)
        {
            List<double> evaluatedParams = new List<double>(args.Parameters.Length);

            foreach (Expression curParam in args.Parameters)
            {
                ReturnStatus<double> evaluateStatus = EvaluateExpression(curParam);
                if (evaluateStatus.IsValid)
                {
                    evaluatedParams.Add(evaluateStatus.Value);
                }
                else
                {
                    args.Result = double.NaN;
                    this.functionHandlingErrorEncountered = true;
                    return;
                }
            }

            ReturnStatus<bool> retStatus = HandleCustomFunctions(funcName, args, evaluatedParams);
            if (retStatus.IsValid == false)
            {
                args.Result = double.NaN;
                this.functionHandlingErrorEncountered = true;
            }
        }
示例#26
0
        private void EvaluateCreateNewInstance(FunctionArgs args, List<Dictionary<string, object>> localVariableStack, List<object> dotOperatorStack)
        {
            string typeAsString = args.Parameters[0].ParsedExpression.ToString();
            typeAsString = typeAsString.Substring(1, typeAsString.Length - 2);

            Type type = TypeManager.GetTypeFromString(typeAsString);
            int constructorParameterCount = args.Parameters.Length - 1;
            object[] constructorParameters;

            constructorParameters = new object[constructorParameterCount];

            for (int i = 0; i < constructorParameterCount; i++)
            {
                constructorParameters[i] = args.Parameters[i + 1].Evaluate();
            }
            
            object toReturn = Activator.CreateInstance(type, constructorParameters);

            args.Result = toReturn;
        }
        //Return true if the function was handled
        protected ReturnStatus<bool> HandleBaseFunctions(string funcName, 
            FunctionArgs args,
            List<double> evaluatedArgs)
        {
            ReturnStatus<bool> retStatus = new ReturnStatus<bool>();

            switch (funcName)
            {
                case FUNC_NAME_LIMIT:
                    retStatus.IsValid = HandleLimitFunc(args, evaluatedArgs);
                    break;
                default:
                    retStatus.IsValid = true;
                    retStatus.Value = false;
                    return retStatus;
            }

            retStatus.Value = true;
            return retStatus;
        }
        protected bool HandleLfoFunc(FunctionArgs args, List<double>evaluatedArgs)
        {
            if (evaluatedArgs.Count != 6)
            {
                return false;
            }

            double input = evaluatedArgs[0];
            double attack = evaluatedArgs[1];
            WaveformShap shape = (WaveformShap)evaluatedArgs[2];
            double phase = evaluatedArgs[3];
            double cycles = evaluatedArgs[4];
            double amount = evaluatedArgs[5];

            if (attack < 0 || attack > 1)
            {
                return false;
            }

            if (Enum.IsDefined(typeof(WaveformShap), shape) == false)
            {
                return false;
            }

            //input
            double output = input;

            //cycles
            output *= cycles;

            //phase
            output += phase % 360 / 360.0;

            //shape
            HandleWaveformFunc(output, shape, out output);

            output -= 0.5;

            //attack
            double attackAtInput;
            if (attack == 0)
            {
                attackAtInput = 1;
            }
            else
            {
                attackAtInput = Math.Min(1, input / attack);
            }
            output *= attackAtInput;

            //amount
            output *= amount;

            output += 0.5;

            args.Result = output;
            return true;
        }
 protected virtual ReturnStatus<bool> HandleCustomFunctions(string funcName, 
     FunctionArgs args,
     List<double> evaluatedArgs)
 {
     return HandleBaseFunctions(funcName, args, evaluatedArgs);
 }
        protected bool HandleWaveformFunc(FunctionArgs args, List<double> evaluatedArgs)
        {
            if (evaluatedArgs.Count != 2)
            {
                return false;
            }

            double output;
            bool success = HandleWaveformFunc(evaluatedArgs[0],
                                              (WaveformShap)evaluatedArgs[1],
                                              out output);
            args.Result = output;
            return success;
        }
示例#31
0
文件: Filter.cs 项目: keithshort/HOPE
		protected void OnEvaluateFunction(string name, FunctionArgs args)
		{
			if (name.ToLower() == "contains")
			{
				string v1 = args.Parameters[0].Evaluate().ToString().ToLower();
				string v2 = args.Parameters[1].Evaluate().ToString().ToLower();

				args.Result = v1.Contains(v2);
			}
		}