Ejemplo n.º 1
0
        public ScriptObject Call(Dictionary <String, ScriptObject> objs, ScriptObject[] parameters)
        {
            int length = parameters.Length;

            if (m_Params)
            {
                m_ParamsArray.Clear();
                for (int i = 0; i < m_ParameterCount - 1; ++i)
                {
                    objs[m_ListParameters[i]] = (parameters != null && length > i) ? parameters[i] : ScriptNull.Instance;
                }
                for (int i = m_ParameterCount - 1; i < length; ++i)
                {
                    m_ParamsArray.Add(parameters[i]);
                }
                objs[m_ListParameters[m_ParameterCount - 1]] = m_ParamsArray;
            }
            else
            {
                for (int i = 0; i < m_ParameterCount; ++i)
                {
                    objs[m_ListParameters[i]] = (parameters != null && length > i) ? parameters[i] : ScriptNull.Instance;
                }
            }
            m_Context.Initialize(m_ParentContext, objs);
            return(m_Context.Execute());
        }
Ejemplo n.º 2
0
        public ScriptObject Call(ScriptContext parentContext, Dictionary <string, ScriptObject> objs, ScriptObject[] parameters)
        {
            int length = parameters.Length;

            if (this.m_Params)
            {
                ScriptArray array = this.m_Script.CreateArray();
                for (int i = 0; i < (this.m_ParameterCount - 1); i++)
                {
                    objs[this.m_ListParameters[i]] = ((parameters != null) && (length > i)) ? parameters[i] : this.m_Script.Null;
                }
                for (int j = this.m_ParameterCount - 1; j < length; j++)
                {
                    array.Add(parameters[j]);
                }
                objs[this.m_ListParameters[this.m_ParameterCount - 1]] = array;
            }
            else
            {
                for (int k = 0; k < this.m_ParameterCount; k++)
                {
                    objs[this.m_ListParameters[k]] = ((parameters != null) && (length > k)) ? parameters[k] : this.m_Script.Null;
                }
            }
            ScriptContext context = new ScriptContext(this.m_Script, this.m_ScriptExecutable, parentContext, Executable_Block.Function);

            context.Initialize(objs);
            return(context.Execute());
        }
Ejemplo n.º 3
0
        /// <summary>
        /// Concatenates two lists.
        /// </summary>
        /// <param name="list1">The 1st input list.</param>
        /// <param name="list2">The 2nd input list.</param>
        /// <returns>The concatenation of the two input lists.</returns>
        /// <remarks>
        /// ```template-text
        /// {{ [1, 2, 3] | array.concat [4, 5] }}
        /// ```
        /// ```html
        /// [1, 2, 3, 4, 5]
        /// ```
        /// </remarks>
        public static IEnumerable Concat(IEnumerable list1, IEnumerable list2)
        {
            if (list2 == null && list1 == null)
            {
                return(null);
            }

            if (list2 == null)
            {
                return(list1);
            }

            if (list1 == null)
            {
                return(list2);
            }

            ScriptArray result = new ScriptArray(list1);

            foreach (var item in list2)
            {
                result.Add(item);
            }

            return(result);
        }
Ejemplo n.º 4
0
            ScriptValue ParseArray()
            {
                var array = new ScriptArray(m_Script);
                var ret   = new ScriptValue(array);

                while (true)
                {
                    var ch = EatWhiteSpace;
                    switch (ch)
                    {
                    case RIGHT_BRACKET: return(ret);

                    case COMMA: continue;

                    case END_CHAR:
                        throw new ExecutionException("Json解析, 未找到array结尾 ]");

                    default: {
                        --m_Index;
                        array.Add(ReadObject());
                        continue;
                    }
                    }
                }
            }
Ejemplo n.º 5
0
        public static ScriptArray Values(TemplateContext context, object value)
#pragma warning restore CS0108
        {
            if (value == null)
            {
                return(new ScriptArray());
            }
            if (value is IDictionary <string, object> dictStringObject)
            {
                return(new ScriptArray(dictStringObject.Values));
            }
            // Don't try to return values of a custom function
            if (value is IScriptCustomFunction)
            {
                return(new ScriptArray());
            }

            var accessor    = context.GetMemberAccessor(value);
            var scriptArray = new ScriptArray();

            foreach (var member in accessor.GetMembers(context, context.CurrentSpan, value))
            {
                _ = accessor.TryGetValue(context, context.CurrentSpan, value, member, out var memberValue);
                scriptArray.Add(memberValue);
            }
            return(scriptArray);
        }
Ejemplo n.º 6
0
        private static ScriptTable Read(MessageReader reader, string tableName)
        {
            ScriptTable table  = m_Script.CreateTable();
            ScriptArray layout = (ScriptArray)m_Script.GetValue(tableName);
            int         sign   = reader.ReadInt32();

            for (int i = 0; i < layout.Count(); ++i)
            {
                ScriptObject config = layout.GetValue(i);
                if (MessageUtil.HasSign(sign, MessageUtil.ToInt32(config.GetValue(Index).ObjectValue)))
                {
                    string name  = (string)config.GetValue(Name).ObjectValue;
                    string type  = (string)config.GetValue(Type).ObjectValue;
                    bool   array = (bool)config.GetValue(Array).ObjectValue;
                    if (array)
                    {
                        int         count = reader.ReadInt32();
                        ScriptArray arr   = m_Script.CreateArray();
                        for (int j = 0; j < count; ++j)
                        {
                            arr.Add(ReadObject(reader, type));
                        }
                        table.SetValue(name, arr);
                    }
                    else
                    {
                        table.SetValue(name, ReadObject(reader, type));
                    }
                }
            }
            return(table);
        }
Ejemplo n.º 7
0
        public static void AddItem <T>(this ScriptArray sa, T item)
        {
            ScriptObject itemObj = new ScriptObject();

            itemObj.Import(item, renamer: HtmlRenderer.ScribanObjectRenamer);
            sa.Add(itemObj);
        }
Ejemplo n.º 8
0
        public ScriptObject Call(ScriptContext parentContext, ScorpioDictionary <ScriptObject> objs, ScriptObject[] parameters)
        {
            int length = parameters.Length;

            if (m_Params)
            {
                ScriptArray paramsArray = m_Script.CreateArray();
                for (int i = 0; i < m_ParameterCount - 1; ++i)
                {
                    objs[m_ListParameters[i]] = (parameters != null && length > i) ? parameters[i] : m_Script.Null;
                }
                for (int i = m_ParameterCount - 1; i < length; ++i)
                {
                    paramsArray.Add(parameters[i]);
                }
                objs[m_ListParameters[m_ParameterCount - 1]] = paramsArray;
            }
            else
            {
                for (int i = 0; i < m_ParameterCount; ++i)
                {
                    objs[m_ListParameters[i]] = (parameters != null && length > i) ? parameters[i] : m_Script.Null;
                }
            }
            ScriptContext context = new ScriptContext(m_Script, m_ScriptExecutable, parentContext, Executable_Block.Function);

            context.Initialize(objs);
            return(context.Execute());
        }
Ejemplo n.º 9
0
            public object Call(ScriptObject[] args)
            {
                ScriptArray  array = (ScriptArray)args[0];
                ScriptObject obj   = (ScriptObject)args[1];

                array.Add(obj);
                return(obj);
            }
Ejemplo n.º 10
0
        public ScriptArray GetParameters()
        {
            ScriptArray ret = m_Script.CreateArray();

            foreach (String par in m_ListParameters)
            {
                ret.Add(m_Script.CreateString(par));
            }
            return(ret);
        }
Ejemplo n.º 11
0
        public ScriptArray GetParameters()
        {
            ScriptArray array = this.m_Script.CreateArray();

            foreach (string str in this.m_ListParameters)
            {
                array.Add(this.m_Script.CreateString(str));
            }
            return(array);
        }
Ejemplo n.º 12
0
        ScriptArray ParseArray(CodeArray array)
        {
            ScriptArray ret = m_script.CreateArray();

            foreach (CodeObject ele in array.Elements)
            {
                ret.Add(ResolveOperand(ele));
            }
            return(ret);
        }
Ejemplo n.º 13
0
        private ScriptArray ParseArray(CodeArray array)
        {
            ScriptArray array2 = this.m_script.CreateArray();

            foreach (CodeObject obj2 in array.Elements)
            {
                array2.Add(this.ResolveOperand(obj2).Assign());
            }
            return(array2);
        }
Ejemplo n.º 14
0
        public static void AddItem <T>(this ScriptArray sa, IEnumerable <T> items)
        {
            ScriptArray itemArr = new ScriptArray();

            foreach (T item in items)
            {
                AddItem(itemArr, item);
            }
            sa.Add(itemArr);
        }
Ejemplo n.º 15
0
        ScriptArray ParseArray(CodeArray array)
        {
            ScriptArray ret = m_script.CreateArray();
            int         num = array.Elements.Count;

            for (int i = 0; i < num; ++i)
            {
                ret.Add(ResolveOperand(array.Elements[i]));
            }
            return(ret);
        }
        public override object Evaluate(TemplateContext context)
        {
            ScriptArray scriptArray = new ScriptArray();

            foreach (ScriptExpression value in Values)
            {
                var valueEval = context.Evaluate(value);
                scriptArray.Add(valueEval);
            }
            return(scriptArray);
        }
Ejemplo n.º 17
0
            public ScriptValue Call(ScriptValue thisObject, ScriptValue[] args, int length)
            {
                var array = thisObject.Get <ScriptArray>();
                var ret   = new ScriptArray(array.getScript());

                for (var i = array.Length() - 1; i >= 0; --i)
                {
                    ret.Add(array[i]);
                }
                return(new ScriptValue(ret));
            }
Ejemplo n.º 18
0
            public ScriptValue Call(ScriptValue thisObject, ScriptValue[] args, int length)
            {
                var array = thisObject.Get <ScriptArray>();
                var ret   = new ScriptArray(array.getScript());
                var func  = args[0].Get <ScriptFunction>();

                for (int i = 0, count = array.Length(); i < count; ++i)
                {
                    ret.Add(func.Call(array[i]));
                }
                return(new ScriptValue(ret));
            }
Ejemplo n.º 19
0
        public object Invoke(TemplateContext context, ScriptNode callerContext, ScriptArray arguments, ScriptBlockStatement blockStatement)
        {
            if (arguments == null || arguments.Count == 0)
            {
                throw new ScriptRuntimeException(callerContext.Span, string.Format(RS.BadFunctionInvokeArgEmpty, "where"));
            }

            if (arguments.Count == 1)
            {
                return(arguments[0]);
            }

            // the second argument is a condition
            ScriptFunctionCall funcCall  = (ScriptFunctionCall)callerContext;
            ScriptExpression   condition = funcCall.Arguments[0];

            // hold the result in an array
            ScriptArray result = new ScriptArray();

            // the first argument doesn't have to be an array
            try
            {
                // string is enumerable but we want to treat it as a whole
                if (arguments[0] is string)
                {
                    throw new InvalidCastException();
                }

                IEnumerable array = (IEnumerable)arguments[0];
                foreach (object item in array)
                {
                    if ((bool)ReplaceCondition(condition, item).Evaluate(context))
                    {
                        result.Add(item);
                    }
                }
            }
            catch (InvalidCastException)
            {
                if ((bool)ReplaceCondition(condition, arguments[0]).Evaluate(context))
                {
                    return(arguments[0]);
                }
            }
            catch (Exception ex)
            {
                throw new ScriptParserRuntimeException(callerContext.Span, string.Format("RS.FilterFunctionException"), null, ex);
            }

            return(result);
        }
Ejemplo n.º 20
0
        private static object ReadEvent(EventReader reader)
        {
            // Read a plain scalar and decode it to a C# value
            if (reader.Accept <Scalar>())
            {
                var scalar = reader.Expect <Scalar>();

                // We try to parse scalar with an extended YamlSchema
                // If we find a int,double... -> convert it to the proper C# type
                string defaultTag;
                object value;
                return(DefaultSchema.TryParse(scalar, true, out defaultTag, out value) ? value : scalar.Value);
            }

            // Read a YAML sequence to a ScriptArray
            if (reader.Accept <SequenceStart>())
            {
                var array = new ScriptArray();
                reader.Expect <SequenceStart>();
                while (!reader.Accept <SequenceEnd>())
                {
                    array.Add(ReadEvent(reader));
                }
                reader.Expect <SequenceEnd>();
                return(array);
            }

            // Read a YAML mapping to a ScriptObject
            if (reader.Accept <MappingStart>())
            {
                var obj = new ScriptObject();
                reader.Expect <MappingStart>();
                while (!reader.Accept <MappingEnd>())
                {
                    var key   = ReadEvent(reader).ToString();
                    var value = ReadEvent(reader);
                    try
                    {
                        obj.Add(key, value);
                    }
                    catch (ArgumentException err)
                    {
                        throw new YamlException(reader.Parser.Current.Start, reader.Parser.Current.End, "Duplicate key", err);
                    }
                }
                reader.Expect <MappingEnd>();
                return(obj);
            }

            throw new YamlException(reader.Parser.Current.Start, reader.Parser.Current.End, $"Unsupported Yaml Event {reader.Parser.Current}");
        }
Ejemplo n.º 21
0
            public object Call(ScriptObject[] args)
            {
                string str = (args[0] as ScriptString).Value;
                string tko = (args[1] as ScriptString).Value;

                string[]    strs = str.Split(tko.ToCharArray());
                ScriptArray ret  = m_script.CreateArray();

                foreach (string s in strs)
                {
                    ret.Add(m_script.CreateString(s));
                }
                return(ret);
            }
Ejemplo n.º 22
0
            private ScriptArray ReadStrictArray(Stream src)
            {
                byte[] bs = new byte[4];
                src.Read(bs, 0, 4);
                offset += 4;
                ScriptArray array = new ScriptArray();
                uint        count = ByteUtil.ByteToUInt(bs, 4);

                for (uint i = 0; i < count; i++)
                {
                    array.Add(ReadElement(src));
                }
                return(array);
            }
Ejemplo n.º 23
0
        public object Call(ScriptObject[] args)
        {
            string      path      = args[0].ToString();
            string      parttern  = args[1].ToString();
            bool        recursive = (args[2] as ScriptBoolean).Value;
            var         files     = Directory.GetFiles(parttern, parttern, recursive ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly);
            ScriptArray array     = m_script.CreateArray();

            foreach (var file in files)
            {
                array.Add(m_script.CreateString(file));
            }
            return(array);
        }
Ejemplo n.º 24
0
            public ScriptValue Call(ScriptValue thisObject, ScriptValue[] args, int length)
            {
                var array = thisObject.Get <ScriptArray>();
                var ret   = new ScriptArray(array.getScript());
                var func  = args[0].Get <ScriptFunction>();

                if (func != null)
                {
                    foreach (var value in array)
                    {
                        ret.Add(func.Call(value));
                    }
                }
                return(new ScriptValue(ret));
            }
Ejemplo n.º 25
0
            public ScriptValue Call(ScriptValue thisObject, ScriptValue[] args, int length)
            {
                var array = thisObject.Get <ScriptArray>();
                var ret   = new ScriptArray(array.getScript());
                var func  = args[0].Get <ScriptFunction>();

                for (var i = array.Length() - 1; i >= 0; --i)
                {
                    if (func.Call(array[i]).IsTrue)
                    {
                        ret.Add(new ScriptValue((double)i));
                    }
                }
                return(new ScriptValue(ret));
            }
Ejemplo n.º 26
0
        /// <summary>
        /// Searches an input string for a substring that matches a regular expression pattern and returns an array with the match occurences.
        /// </summary>
        /// <param name="context">The template context (to fetch the timeout configuration)</param>
        /// <param name="text">The string to search for a match.</param>
        /// <param name="pattern">The regular expression pattern to match.</param>
        /// <param name="options">A string with regex options, that can contain the following option characters (default is `null`):
        /// - `i`: Specifies case-insensitive matching.
        /// - `m`: Multiline mode. Changes the meaning of `^` and `$` so they match at the beginning and end, respectively, of any line, and not just the beginning and end of the entire string.
        /// - `s`: Specifies single-line mode. Changes the meaning of the dot `.` so it matches every character (instead of every character except `\n`).
        /// - `x`: Eliminates unescaped white space from the pattern and enables comments marked with `#`.
        /// </param>
        /// <returns>An array that contains all the match groups. The first group contains the entire match. The other elements contain regex matched groups `(..)`. An empty array returned means no match.</returns>
        /// <remarks>
        /// ```scriban-html
        /// {{ "this is a text123" | regex.match `(\w+) a ([a-z]+\d+)` }}
        /// ```
        /// ```html
        /// ["is a text123", "is", "text123"]
        /// ```
        /// Notice that the first element returned in the array is the entire regex match, followed by the regex group matches.
        /// </remarks>
        public static ScriptArray Match(TemplateContext context, string text, string pattern, string options = null)
        {
            var match       = Regex.Match(text, pattern, GetOptions(options), context.RegexTimeOut);
            var matchObject = new ScriptArray();

            if (match.Success)
            {
                foreach (Group group in match.Groups)
                {
                    matchObject.Add(group.Value);
                }
            }

            // otherwise return an empty array
            return(matchObject);
        }
Ejemplo n.º 27
0
        public static ScriptArray Match(string pattern, string input)
        {
            var match       = Regex.Match(input, pattern);
            var matchObject = new ScriptArray();

            if (match.Success)
            {
                foreach (Group group in match.Groups)
                {
                    matchObject.Add(group.Value);
                }
            }

            // otherwise return an empty array
            return(matchObject);
        }
Ejemplo n.º 28
0
            public ScriptValue Call(ScriptValue thisObject, ScriptValue[] args, int length)
            {
                var splits = new string[length];

                for (var i = 0; i < length; ++i)
                {
                    splits[i] = args[i].ToString();
                }
                var strs = thisObject.stringValue.Split(splits, StringSplitOptions.RemoveEmptyEntries);
                var ret  = new ScriptArray(m_script);

                foreach (string str in strs)
                {
                    ret.Add(new ScriptValue(str));
                }
                return(new ScriptValue(ret));
            }
Ejemplo n.º 29
0
 public bool ExpandParameters(object value, ScriptArray expandedParameters)
 {
     // Handle parameters expansion for a function call when the operator ~ is used
     if (Operator == ScriptUnaryOperator.FunctionParametersExpand)
     {
         var valueEnumerator = value as IEnumerable;
         if (valueEnumerator != null)
         {
             foreach (var subValue in valueEnumerator)
             {
                 expandedParameters.Add(subValue);
             }
             return true;
         }
     }
     return false;
 }
Ejemplo n.º 30
0
 public bool ExpandParameters(object value, ScriptArray expandedParameters)
 {
     // Handle parameters expansion for a function call when the operator ~ is used
     if (Operator == ScriptUnaryOperator.FunctionParametersExpand)
     {
         var valueEnumerator = value as IEnumerable;
         if (valueEnumerator != null)
         {
             foreach (var subValue in valueEnumerator)
             {
                 expandedParameters.Add(subValue);
             }
             return(true);
         }
     }
     return(false);
 }
Ejemplo n.º 31
0
        /// <summary>
        /// Removes any non-null values from the input list.
        /// </summary>
        /// <param name="list">An input list</param>
        /// <returns>Returns a list with null value removed</returns>
        /// <remarks>
        /// ```scriban-html
        /// {{ [1, null, 3] | array.compact }}
        /// ```
        /// ```html
        /// [1, 3]
        /// ```
        /// </remarks>
        public static ScriptArray Compact(IEnumerable list)
        {
            if (list == null)
            {
                return(null);
            }

            var result = new ScriptArray();

            foreach (var item in list)
            {
                if (item != null)
                {
                    result.Add(item);
                }
            }
            return(result);
        }
Ejemplo n.º 32
0
        public static object Call(TemplateContext context, ScriptNode callerContext, object functionObject, List<ScriptExpression> arguments = null)
        {
            if (callerContext == null) throw new ArgumentNullException(nameof(callerContext));
            if (functionObject == null)
            {
                throw new ScriptRuntimeException(callerContext.Span, $"The target function [{callerContext}] is null");
            }
            var function = functionObject as ScriptFunction;
            var externFunction = functionObject as IScriptCustomFunction;

            if (function == null && externFunction == null)
            {
                throw new ScriptRuntimeException(callerContext.Span, $"Invalid object function [{functionObject?.GetType()}]");
            }

            ScriptBlockStatement blockDelegate = null;
            if (context.BlockDelegates.Count > 0)
            {
                blockDelegate = context.BlockDelegates.Pop();
            }

            var argumentValues = new ScriptArray();
            if (arguments != null)
            {
                foreach (var argument in arguments)
                {
                    var value = context.Evaluate(argument);

                    // Handle parameters expansion for a function call when the operator ^ is used
                    var unaryExpression = argument as ScriptUnaryExpression;
                    if (unaryExpression != null && unaryExpression.ExpandParameters(value, argumentValues))
                    {
                        continue;
                    }

                    argumentValues.Add(value);
                }
            }

            // Handle pipe arguments here
            if (context.PipeArguments.Count > 0)
            {
                var additionalArgument = context.PipeArguments.Pop();

                var value = context.Evaluate(additionalArgument);

                // Handle parameters expansion for a function call when the operator ~ is used
                var unaryExpression = additionalArgument as ScriptUnaryExpression;
                if (unaryExpression == null || !unaryExpression.ExpandParameters(value, argumentValues))
                {
                    argumentValues.Add(value);
                }
            }

            object result = null;
            context.EnterFunction(callerContext);
            try
            {
                if (externFunction != null)
                {
                    result = externFunction.Evaluate(context, callerContext, argumentValues, blockDelegate);
                }
                else
                {
                    context.SetValue(ScriptVariable.Arguments, argumentValues, true);

                    // Set the block delegate
                    if (blockDelegate != null)
                    {
                        context.SetValue(ScriptVariable.BlockDelegate, blockDelegate, true);
                    }
                    result = context.Evaluate(function.Body);
                }
            }
            finally
            {
                context.ExitFunction();
            }

            // Restore the flow state to none
            context.FlowState = ScriptFlowState.None;
            return result;
        }
Ejemplo n.º 33
0
 private ScriptArray ReadStrictArray(Stream src)
 {
     byte[] bs = new byte[4];
     src.Read(bs, 0, 4);
     offset += 4;
     ScriptArray array = new ScriptArray();
     uint count = ByteUtil.ByteToUInt(bs, 4);
     for (uint i = 0; i < count; i++) {
         array.Add(ReadElement(src));
     }
     return array;
 }