Пример #1
0
        private static (object value, string error) Evaluator(Expression expression, IMemory state, Options options)
        {
            object value = null;
            string error = null;
            IReadOnlyList <object> args;

            (args, error) = FunctionUtils.EvaluateChildren(expression, state, options);
            if (error == null)
            {
                if (args[1].IsInteger() && args[2] is string string2)
                {
                    var format = (args.Count == 4) ? (string)args[3] : FunctionUtils.DefaultDateTimeFormat;
                    Func <DateTime, DateTime> timeConverter;
                    (timeConverter, error) = FunctionUtils.DateTimeConverter(Convert.ToInt64(args[1], CultureInfo.InvariantCulture), string2);
                    if (error == null)
                    {
                        (value, error) = FunctionUtils.NormalizeToDateTime(args[0], dt => (timeConverter(dt).ToString(format, CultureInfo.InvariantCulture), null));
                    }
                }
                else
                {
                    error = $"{expression} should contain an ISO format timestamp, a time interval integer, a string unit of time and an optional output format string.";
                }
            }

            return(value, error);
        }
        private static (object value, string error) Evaluator(Expression expression, IMemory state, Options options)
        {
            object value = null;
            string error = null;
            IReadOnlyList <object> args;
            var locale = options.Locale != null ? new CultureInfo(options.Locale) : Thread.CurrentThread.CurrentCulture;
            var format = FunctionUtils.DefaultDateTimeFormat;

            (args, error) = FunctionUtils.EvaluateChildren(expression, state, options);

            if (error == null)
            {
                (format, locale, error) = FunctionUtils.DetermineFormatAndLocale(args, format, locale, 5);
            }

            if (error == null)
            {
                if (args[1].IsInteger() && args[2] is string timeUnit)
                {
                    (value, error) = EvalAddToTime(args[0], Convert.ToInt64(args[1], CultureInfo.InvariantCulture), timeUnit, format, locale);
                }
                else
                {
                    error = $"{expression} should contain an ISO format timestamp, a time interval integer, a string unit of time, an optional output format string and an optional locale string.";
                }
            }

            return(value, error);
        }
        private static (object value, string error) Evaluator(Expression expression, IMemory state, Options options)
        {
            object value = null;
            string error = null;
            IReadOnlyList <object> args;
            var locale = options.Locale != null ? new CultureInfo(options.Locale) : Thread.CurrentThread.CurrentCulture;
            var format = FunctionUtils.DefaultDateTimeFormat;

            (args, error) = FunctionUtils.EvaluateChildren(expression, state, options);
            if (error == null)
            {
                (format, locale, error) = FunctionUtils.DetermineFormatAndLocale(args, format, locale, 4);
            }

            if (error == null)
            {
                if (args[0].IsInteger() && args[1] is string string1)
                {
                    Func <DateTime, DateTime> timeConverter;
                    (timeConverter, error) = FunctionUtils.DateTimeConverter(Convert.ToInt64(args[0], CultureInfo.InvariantCulture), string1);
                    if (error == null)
                    {
                        value = timeConverter(DateTime.UtcNow).ToString(format, locale);
                    }
                }
                else
                {
                    error = $"{expression} should contain a time interval integer, a string unit of time, an optional output format string and an optional locale string.";
                }
            }

            return(value, error);
        }
Пример #4
0
        private static (object value, string error) Evaluator(Expression expression, IMemory state, Options options)
        {
            object result = -1;

            var(args, error) = FunctionUtils.EvaluateChildren(expression, state, options);
            if (error == null)
            {
                if (args[0] is string || args[0] == null)
                {
                    if (args[1] is string || args[1] == null)
                    {
                        result = FunctionUtils.ParseStringOrNull(args[0]).IndexOf(FunctionUtils.ParseStringOrNull(args[1]));
                    }
                    else
                    {
                        error = $"Can only look for indexof string in {expression}";
                    }
                }
                else if (FunctionUtils.TryParseList(args[0], out IList list))
                {
                    result = FunctionUtils.ResolveListValue(list).IndexOf(args[1]);
                }
                else
                {
                    error = $"{expression} works only on string or list.";
                }
            }

            return(result, error);
        }
Пример #5
0
        private static (object value, string error) Evaluator(Expression expression, IMemory state, Options options)
        {
            var found = false;

            var(args, error) = FunctionUtils.EvaluateChildren(expression, state, options);
            if (error == null)
            {
                if (args[0] is string string0 && args[1] is string string1)
                {
                    found = string0.Contains(string1);
                }
                else if (FunctionUtils.TryParseList(args[0], out IList ilist))
                {
                    // list to find a value
                    var operands = FunctionUtils.ResolveListValue(ilist);

                    foreach (var item in operands)
                    {
                        if (FunctionUtils.CommonEquals(item, args[1]))
                        {
                            found = true;
                            break;
                        }
                    }
                }
                else if (args[1] is string string2)
                {
                    found = FunctionUtils.TryAccessProperty((object)args[0], string2, out var _);
                }
            }
Пример #6
0
        private static (object value, string error) EvalJoin(Expression expression, IMemory state, Options options)
        {
            object result = null;

            var(args, error) = FunctionUtils.EvaluateChildren(expression, state, options);
            if (error == null)
            {
                if (!FunctionUtils.TryParseList(args[0], out IList list))
                {
                    error = $"{expression.Children[0]} evaluates to {args[0]} which is not a list.";
                }
                else
                {
                    if (args.Count == 2)
                    {
                        result = string.Join(args[1].ToString(), list.OfType <object>().Select(x => x.ToString()));
                    }
                    else
                    {
                        if (list.Count < 3)
                        {
                            result = string.Join(args[2].ToString(), list.OfType <object>().Select(x => x.ToString()));
                        }
                        else
                        {
                            var firstPart = string.Join(args[1].ToString(), list.OfType <object>().TakeWhile(o => o != null && o != list.OfType <object>().LastOrDefault()));
                            result = firstPart + args[2] + list.OfType <object>().Last().ToString();
                        }
                    }
                }
            }

            return(result, error);
        }
Пример #7
0
        private static (object value, string error) Evaluator(Expression expression, IMemory state, Options options)
        {
            object value = null;
            string error = null;
            IReadOnlyList <object> args;

            (args, error) = FunctionUtils.EvaluateChildren(expression, state, options);
            if (error == null)
            {
                if (args[0].IsInteger() && args[1] is string string1)
                {
                    var format = (args.Count() == 3) ? (string)args[2] : FunctionUtils.DefaultDateTimeFormat;
                    Func <DateTime, DateTime> timeConverter;
                    (timeConverter, error) = FunctionUtils.DateTimeConverter(Convert.ToInt64(args[0]), string1);
                    if (error == null)
                    {
                        value = timeConverter(DateTime.UtcNow).ToString(format);
                    }
                }
                else
                {
                    error = $"{expression} should contain a time interval integer, a string unit of time and an optional output format string.";
                }
            }

            return(value, error);
        }
Пример #8
0
        private static (object value, string error) Evaluator(Expression expression, IMemory state, Options options)
        {
            object value = null;
            string error = null;
            IReadOnlyList <object> args;
            var locale = options.Locale != null ? new CultureInfo(options.Locale) : Thread.CurrentThread.CurrentCulture;
            var format = DefaultFormat;

            (args, error) = FunctionUtils.EvaluateChildren(expression, state, options);
            if (error == null)
            {
                (format, locale, error) = FunctionUtils.DetermineFormatAndLocale(args, format, locale, 4);
            }

            if (error == null)
            {
                if (args[1] is string targetTimeZone)
                {
                    (value, error) = EvalConvertFromUTC(args[0], targetTimeZone, format, locale);
                }
                else
                {
                    error = $"{expression} should contain an ISO format timestamp, a destination time zone string, an optional output format string and an optional locale string.";
                }
            }

            return(value, error);
        }
        private static EvaluateExpressionDelegate Evaluator(Func <IReadOnlyList <object>, bool> function, FunctionUtils.VerifyExpression verify)
        {
            return((expression, state, options) =>
            {
                var result = false;
                string error = null;
                IReadOnlyList <object> args;
                (args, error) = FunctionUtils.EvaluateChildren(expression, state, new Options(options)
                {
                    NullSubstitution = null
                }, verify);
                if (error == null)
                {
                    try
                    {
                        result = function(args);
                    }
#pragma warning disable CA1031 // Do not catch general exception types (we are capturing the exception and returning it)
                    catch (Exception e)
#pragma warning restore CA1031 // Do not catch general exception types
                    {
                        // NOTE: This should not happen in normal execution
                        error = e.Message;
                    }
                }
                else
                {
                    // Swallow errors and treat as false
                    error = null;
                }

                return (result, error);
            });
        }
        private static (object value, string error) Evaluator(Expression expression, IMemory state, Options options)
        {
            TimexProperty          parsed = null;
            string                 value  = null;
            string                 error  = null;
            IReadOnlyList <object> args;

            (args, error) = FunctionUtils.EvaluateChildren(expression, state, options);
            if (error == null)
            {
                (parsed, error) = FunctionUtils.ParseTimexProperty(args[0]);
            }

            // if the parsed TimexProperty has no types, then it cannot be resolved
            if (error == null && parsed.Types.Count == 0)
            {
                error = $"The parsed TimexProperty of {args[0]} in {expression} has no types. It can't be resolved to a string value.";
            }

            if (error == null)
            {
                var formatedTimex = TimexFormat.Format(parsed);
                try
                {
                    var resolvedValues = TimexResolver.Resolve(new string[] { formatedTimex });
                    value = resolvedValues.Values[0].Value;
                }
                catch (ArgumentException err)
                {
                    error = $"{args[0]} in {expression} is not a valid argument. {err.Message}";
                }
            }

            return(value, error);
        }
Пример #11
0
        private static (object value, string error) Evaluator(Expression expression, IMemory state, Options options)
        {
            object dateTimeStart = null;
            object dateTimeEnd   = null;
            object value         = null;
            string error         = null;
            IReadOnlyList <object> args;

            (args, error) = FunctionUtils.EvaluateChildren(expression, state, options);
            if (error == null)
            {
                (dateTimeStart, error) = FunctionUtils.TicksWithError(args[0]);
                if (error == null)
                {
                    (dateTimeEnd, error) = FunctionUtils.TicksWithError(args[1]);
                }
                else
                {
                    error = $"{expression} must have two ISO timestamps.";
                }
            }

            if (error == null)
            {
                value = (long)dateTimeStart - (long)dateTimeEnd;
            }

            return(value, error);
        }
Пример #12
0
        private static EvaluateExpressionDelegate Evaluator(Func <IReadOnlyList <object>, bool> function, FunctionUtils.VerifyExpression verify)
        {
            return((expression, state, options) =>
            {
                var result = false;
                string error = null;
                IReadOnlyList <object> args;
                (args, error) = FunctionUtils.EvaluateChildren(expression, state, new Options(options)
                {
                    NullSubstitution = null
                }, verify);
                if (error == null)
                {
                    // Ensure args are all of same type
                    bool?isNumber = null;
                    foreach (var arg in args)
                    {
                        var obj = arg;
                        if (isNumber.HasValue)
                        {
                            if (obj != null && obj.IsNumber() != isNumber.Value)
                            {
                                error = $"Arguments must either all be numbers or strings in {expression}";
                                break;
                            }
                        }
                        else
                        {
                            isNumber = obj.IsNumber();
                        }
                    }

                    if (error == null)
                    {
                        try
                        {
                            result = function(args);
                        }
#pragma warning disable CA1031 // Do not catch general exception types (we are capturing the exception and returning it)
                        catch (Exception e)
#pragma warning restore CA1031 // Do not catch general exception types
                        {
                            // NOTE: This should not happen in normal execution
                            error = e.Message;
                        }
                    }
                }
                else
                {
                    // Swallow errors and treat as false
                    error = null;
                }

                return (result, error);
            });
        }
        private static (object value, string error) Evaluator(Expression expression, IMemory state, Options options)
        {
            object value = null;
            string error = null;
            IReadOnlyList <object> args;

            (args, error) = FunctionUtils.EvaluateChildren(expression, state, options);
            if (error == null)
            {
                (value, error) = FunctionUtils.TicksWithError(args[0]);
            }

            return(value, error);
        }
Пример #14
0
        private Templates InjectToExpressionFunction()
        {
            var totalTempaltes = new List <Templates> {
                this
            }.Union(References);

            foreach (var curTemplates in totalTempaltes)
            {
                var globalFuncs = curTemplates.GetGlobalFunctionTable(curTemplates.Options);
                foreach (var templateName in globalFuncs)
                {
                    if (curTemplates.Any(u => u.Name == templateName))
                    {
                        var prefix        = string.IsNullOrWhiteSpace(curTemplates.Namespace) ? string.Empty : curTemplates.Namespace + ".";
                        var newGlobalName = prefix + templateName;
                        Expression.Functions.Add(newGlobalName, new ExpressionEvaluator(
                                                     newGlobalName,
                                                     (expression, state, options) =>
                        {
                            object result    = null;
                            var evaluator    = new Evaluator(this, LgOptions);
                            var(args, error) = FunctionUtils.EvaluateChildren(expression, state, options);
                            if (error == null)
                            {
                                var parameters = evaluator.TemplateMap[templateName].Parameters;
                                var newScope   = parameters.Zip(args, (k, v) => new { k, v })
                                                 .ToDictionary(x => x.k, x => x.v);
                                var scope = new CustomizedMemory(state, new SimpleObjectMemory(newScope));
                                try
                                {
                                    result = evaluator.EvaluateTemplate(templateName, scope);
                                }
#pragma warning disable CA1031 // Do not catch general exception types
                                catch (Exception err)
#pragma warning restore CA1031 // Do not catch general exception types
                                {
                                    error = err.Message;
                                }
                            }

                            return(result, error);
                        },
                                                     ReturnType.Object));
                    }
                }
            }

            return(this);
        }
Пример #15
0
        private static (object value, string error) Evaluator(Expression expression, IMemory state, Options options)
        {
            object value = null;
            string error = null;
            IReadOnlyList <object> args;

            (args, error) = FunctionUtils.EvaluateChildren(expression, state, options);
            if (error == null)
            {
                var format = (args.Count() == 2) ? (string)args[1] : FunctionUtils.DefaultDateTimeFormat;
                (value, error) = StartOfHourWithError(args[0], format);
            }

            return(value, error);
        }
Пример #16
0
        private static EvaluateExpressionDelegate Evaluator(Func <DateTime, int, DateTime> function)
        {
            return((expression, state, options) =>
            {
                object value = null;
                string error = null;
                IReadOnlyList <object> args;
                var locale = options.Locale != null ? new CultureInfo(options.Locale) : Thread.CurrentThread.CurrentCulture;
                var format = FunctionUtils.DefaultDateTimeFormat;
                (args, error) = FunctionUtils.EvaluateChildren(expression, state, options);
                if (error == null)
                {
                    (format, locale, error) = FunctionUtils.DetermineFormatAndLocale(args, format, locale, 4);
                }

                if (error == null)
                {
                    if (args[1].IsInteger())
                    {
                        (value, error) = FunctionUtils.NormalizeToDateTime(args[0], dt =>
                        {
                            var result = dt;
                            var(interval, error) = FunctionUtils.ParseInt32(args[1]);
                            if (error == null)
                            {
                                result = function(dt, interval);
                            }

                            return (result, error);
                        });

                        if (error == null)
                        {
                            value = Convert.ToDateTime(value, CultureInfo.InvariantCulture).ToString(format, locale);
                        }
                    }
                    else
                    {
                        error = $"{expression} should contain an ISO format timestamp and a time interval integer.";
                    }
                }

                return (value, error);
            });
        }
Пример #17
0
        private static (object value, string error) Evaluator(Expression expression, IMemory state, Options options)
        {
            TimexProperty          parsed = null;
            bool?                  value  = null;
            string                 error  = null;
            IReadOnlyList <object> args;

            (args, error) = FunctionUtils.EvaluateChildren(expression, state, options);
            if (error == null)
            {
                (parsed, error) = FunctionUtils.ParseTimexProperty(args[0]);
            }

            if (error == null)
            {
                value = (parsed.Month != null && parsed.DayOfMonth != null) || parsed.DayOfWeek != null;
            }

            return(value, error);
        }
        private static (object value, string error) Evaluator(Expression expression, IMemory state, Options options)
        {
            object value = null;
            string error = null;
            IReadOnlyList <object> args;

            (args, error) = FunctionUtils.EvaluateChildren(expression, state, options);
            if (error == null)
            {
                if (args[0] is string uri)
                {
                    (value, error) = EvalUriQuery(uri);
                }
                else
                {
                    error = $"{expression} should contain a URI string.";
                }
            }

            return(value, error);
        }
Пример #19
0
        private static (object value, string error) Evaluator(Expression expression, IMemory state, Options options)
        {
            object value = null;
            string error = null;
            IReadOnlyList <object> args;

            (args, error) = FunctionUtils.EvaluateChildren(expression, state, options);
            if (error == null)
            {
                if (args[0].IsInteger())
                {
                    value = Convert.ToDouble(args[0], CultureInfo.InvariantCulture) / TicksPerHour;
                }
                else
                {
                    error = $"{expression} should contain an integer of ticks";
                }
            }

            return(value, error);
        }
Пример #20
0
        private static EvaluateExpressionDelegate Evaluator(Func <DateTime, int, DateTime> function)
        {
            return((expression, state, options) =>
            {
                object value = null;
                string error = null;
                IReadOnlyList <object> args;
                (args, error) = FunctionUtils.EvaluateChildren(expression, state, options);
                if (error == null)
                {
                    if (args[1].IsInteger())
                    {
                        var formatString = (args.Count == 3 && args[2] is string string1) ? string1 : FunctionUtils.DefaultDateTimeFormat;
                        (value, error) = FunctionUtils.NormalizeToDateTime(args[0], dt =>
                        {
                            var result = dt;
                            var(interval, error) = FunctionUtils.ParseInt32(args[1]);
                            if (error == null)
                            {
                                result = function(dt, interval);
                            }

                            return (result, error);
                        });

                        if (error == null)
                        {
                            value = Convert.ToDateTime(value, CultureInfo.InvariantCulture).ToString(formatString, CultureInfo.InvariantCulture);
                        }
                    }
                    else
                    {
                        error = $"{expression} should contain an ISO format timestamp and a time interval integer.";
                    }
                }

                return (value, error);
            });
        }
Пример #21
0
        private static (object value, string error) Evaluator(Expression expression, IMemory state, Options options)
        {
            object value = null;
            string error = null;
            IReadOnlyList <object> args;

            (args, error) = FunctionUtils.EvaluateChildren(expression, state, options);
            if (error == null)
            {
                var format = (args.Count == 3) ? (string)args[2] : FunctionUtils.DefaultDateTimeFormat;
                if (args[1] is string targetTimeZone)
                {
                    (value, error) = EvalConvertFromUTC(args[0], targetTimeZone, format);
                }
                else
                {
                    error = $"{expression} should contain an ISO format timestamp, a destination time zone string and an optional output format string.";
                }
            }

            return(value, error);
        }
Пример #22
0
        private static (object value, string error) Evaluator(Expression expression, IMemory state, Options options)
        {
            object value = null;
            string error = null;
            IReadOnlyList <object> args;

            (args, error) = FunctionUtils.EvaluateChildren(expression, state, options);
            if (error == null)
            {
                var format = (args.Count() == 4) ? (string)args[3] : FunctionUtils.DefaultDateTimeFormat;
                if (args[1].IsInteger() && args[2] is string timeUnit)
                {
                    (value, error) = EvalAddToTime(args[0], Convert.ToInt64(args[1]), timeUnit, format);
                }
                else
                {
                    error = $"{expression} should contain an ISO format timestamp, a time interval integer, a string unit of time and an optional output format string.";
                }
            }

            return(value, error);
        }
Пример #23
0
        private static (object value, string error) Evaluator(Expression expression, IMemory state, Options options)
        {
            object value = null;
            string error = null;
            IReadOnlyList <object> args;
            var locale = options.Locale != null ? new CultureInfo(options.Locale) : Thread.CurrentThread.CurrentCulture;
            var format = FunctionUtils.DefaultDateTimeFormat;

            (args, error) = FunctionUtils.EvaluateChildren(expression, state, options);

            if (error == null)
            {
                (format, locale, error) = FunctionUtils.DetermineFormatAndLocale(args, format, locale, 3);
            }

            if (error == null)
            {
                (value, error) = StartOfHourWithError(args[0], format, locale);
            }

            return(value, error);
        }
        private static (object value, string error) Evaluator(Expression expression, IMemory state, Options options)
        {
            TimexProperty parsed = null;
            string        result = null;
            string        error  = null;

            var(validHour, validMinute, validSecond) = (0, 0, 0);
            IReadOnlyList <object> args;
            var formatRegex       = new Regex("TXX:[0-5][0-9]:[0-5][0-9]");
            var currentUtcTime    = DateTime.UtcNow;
            var convertedDateTime = currentUtcTime;

            (args, error) = FunctionUtils.EvaluateChildren(expression, state, options);
            if (error == null)
            {
                if (!formatRegex.IsMatch(args[0] as string))
                {
                    error = $"{args[0]}  must be a timex string which only contains minutes and seconds, for example: 'TXX:15:28'";
                }
            }

            if (error == null)
            {
                if (args.Count == 2 && args[1] is string timezone)
                {
                    object convertedTimeZone = null;
                    (convertedTimeZone, error) = FunctionUtils.ConvertTimeZoneFormat(timezone);
                    if (error == null)
                    {
                        convertedDateTime = TimeZoneInfo.ConvertTimeFromUtc(currentUtcTime, (TimeZoneInfo)convertedTimeZone);
                    }
                }
                else
                {
                    convertedDateTime = currentUtcTime.ToLocalTime();
                }
            }

            if (error == null)
            {
                (parsed, error) = FunctionUtils.ParseTimexProperty((args[0] as string).Replace("XX", "00"));
            }

            if (error == null)
            {
                var(hour, minute, second) = (convertedDateTime.Hour, convertedDateTime.Minute, convertedDateTime.Second);
                if (parsed.Minute < minute || (parsed.Minute == minute && parsed.Second < second))
                {
                    validHour = hour;
                }
                else
                {
                    validHour = hour - 1;
                }

                if (validHour < 0)
                {
                    validHour += 24;
                }

                validMinute = parsed.Minute ?? 0;
                validSecond = parsed.Second ?? 0;
                result      = TimexProperty.FromTime(new Time(validHour, validMinute, validSecond)).TimexValue;
            }

            return(result, error);
        }
        private static (object value, string error) Evaluator(Expression expression, IMemory state, Options options)
        {
            TimexProperty parsed = null;
            string        result = null;
            string        error  = null;

            var(validYear, validMonth, validDay) = (0, 0, 0);
            var currentUtcTime    = DateTime.UtcNow;
            var convertedDateTime = currentUtcTime;
            IReadOnlyList <object> args;

            (args, error) = FunctionUtils.EvaluateChildren(expression, state, options);
            if (error == null)
            {
                (parsed, error) = FunctionUtils.ParseTimexProperty(args[0]);
            }

            if (error == null)
            {
                if (parsed.Year != null || parsed.Month == null || parsed.DayOfMonth == null)
                {
                    error = $"{args[0]} must be a timex string which only contains month and day-of-month, for example: 'XXXX-10-31'.";
                }
            }

            if (error == null)
            {
                if (args.Count == 2 && args[1] is string timezone)
                {
                    object convertedTimeZone = null;
                    (convertedTimeZone, error) = FunctionUtils.ConvertTimeZoneFormat(timezone);
                    if (error == null)
                    {
                        convertedDateTime = TimeZoneInfo.ConvertTimeFromUtc(currentUtcTime, (TimeZoneInfo)convertedTimeZone);
                    }
                }
                else
                {
                    convertedDateTime = currentUtcTime.ToLocalTime();
                }
            }

            if (error == null)
            {
                var(year, month, day) = (convertedDateTime.Year, convertedDateTime.Month, convertedDateTime.Day);
                if (parsed.Month <= month || (parsed.Month == month && parsed.DayOfMonth < day))
                {
                    validYear = year;
                }
                else
                {
                    validYear = year - 1;
                }

                validMonth = parsed.Month ?? 0;
                validDay   = parsed.DayOfMonth ?? 0;
                if (validMonth == 2 && validDay == 29)
                {
                    while (!DateTime.IsLeapYear(validYear))
                    {
                        validYear -= 1;
                    }
                }

                result = TimexProperty.FromDate(new DateTime(validYear, validMonth, validDay)).TimexValue;
            }

            return(result, error);
        }