Beispiel #1
0
        public static string StandardPrintFunction(ExecContext context, List <object> args)
        {
            string result = "";

            foreach (object val in args)
            {
                result += CoreLib.ValueToString(context, val, false);
            }
            return(result);
        }
Beispiel #2
0
        public static void Register(Engine engine)
        {
            //@ class List<T>
            TypeDef_Class ourType = TypeFactory.GetTypeDef_Class("List", new ArgList {
                IntrinsicTypeDefs.TEMPLATE_0
            }, false);
            ClassDef classDef = engine.defaultContext.CreateClass("List", ourType, null, new List <string> {
                "T"
            });

            classDef.childAllocator = () => {
                return(new PebbleList());
            };
            classDef.Initialize();

            //@ List<T> Add(T newValue, ...) or List<T> Push(T newValue, ...)
            //   Adds one or more elements to the end of the list.
            //   Cannot be used in a foreach loop.
            {
                FunctionValue_Host.EvaluateDelegate eval = (context, args, thisScope) => {
                    PebbleList scope = thisScope as PebbleList;
                    if (scope.enumeratingCount > 0)
                    {
                        context.SetRuntimeError(RuntimeErrorType.ForeachModifyingContainer, "Add: Attempt to modify a list that is being enumerated by a foreach loop.");
                        return(null);
                    }

                    var list        = scope.list;
                    var listType    = (TypeDef_Class)scope.classDef.typeDef;
                    var elementType = listType.genericTypes[0];
                    for (int ii = 0; ii < args.Count; ++ii)
                    {
                        object ret = args[ii];
                        list.Add(new Variable(null, elementType, ret));
                    }

                    return(thisScope);
                };

                FunctionValue_Host newValue = new FunctionValue_Host(ourType, new ArgList {
                    IntrinsicTypeDefs.TEMPLATE_0
                }, eval, true, ourType);
                classDef.AddMemberLiteral("Add", newValue.valType, newValue);
                classDef.AddMemberLiteral("Push", newValue.valType, newValue);
            }

            //@ List<T> Clear()
            //   Removes all elements from the list.
            //   Cannot be used in a foreach loop.
            {
                FunctionValue_Host.EvaluateDelegate eval = (context, args, thisScope) => {
                    PebbleList pebList = thisScope as PebbleList;
                    if (pebList.enumeratingCount > 0)
                    {
                        context.SetRuntimeError(RuntimeErrorType.ForeachModifyingContainer, "Clear: Attempt to modify a list that is being enumerated by a foreach loop.");
                        return(null);
                    }

                    var list = pebList.list;
                    list.Clear();
                    return(thisScope);
                };

                FunctionValue_Host newValue = new FunctionValue_Host(ourType, new ArgList {
                }, eval, false, ourType);
                classDef.AddMemberLiteral("Clear", newValue.valType, newValue);
            }

            //@ num Count()
            //   Returns the number of elements in the list.
            {
                FunctionValue_Host.EvaluateDelegate eval = (context, args, thisScope) => {
                    var list = (thisScope as PebbleList).list;
                    return(System.Convert.ToDouble(list.Count));
                };

                FunctionValue_Host newValue = new FunctionValue_Host(IntrinsicTypeDefs.NUMBER, new ArgList {
                }, eval, false, ourType);
                classDef.AddMemberLiteral("Count", newValue.valType, newValue);
            }

            //@ T Get(num index)
            //   Returns the value of the element of the list at the given index.
            {
                FunctionValue_Host.EvaluateDelegate eval = (context, args, thisScope) => {
                    double dix = (double)args[0];
                    int    ix  = (int)dix;

                    var list = (thisScope as PebbleList).list;

                    // Bounds checking.
                    if (ix < 0 || ix >= list.Count)
                    {
                        context.SetRuntimeError(RuntimeErrorType.ArrayIndexOutOfBounds, "Get: Index " + ix + " out of bounds of array of length " + list.Count + ".");
                        return(null);
                    }

                    return(list[ix].value);
                };

                FunctionValue_Host newValue = new FunctionValue_Host(IntrinsicTypeDefs.TEMPLATE_0, new ArgList {
                    IntrinsicTypeDefs.NUMBER
                }, eval, false, ourType);
                classDef.AddMemberLiteral("Get", newValue.valType, newValue);
            }

            //@ List<T> Insert(num index, T item)
            //   Inserts a new element into the list at the given index. Existing elements at and after the given index are pushed further down the list.
            //   Cannot be used in a foreach loop.
            {
                FunctionValue_Host.EvaluateDelegate eval = (context, args, thisScope) => {
                    PebbleList scope = thisScope as PebbleList;
                    if (scope.enumeratingCount > 0)
                    {
                        context.SetRuntimeError(RuntimeErrorType.ForeachModifyingContainer, "Insert: Attempt to modify a list that is being enumerated by a foreach loop.");
                        return(null);
                    }

                    var list        = scope.list;
                    var listType    = (TypeDef_Class)scope.classDef.typeDef;
                    var elementType = listType.genericTypes[0];
                    var indexDouble = (double)args[0];
                    var item        = args[1];
                    var index       = Convert.ToInt32(indexDouble);
                    if (index < 0 || index > list.Count)
                    {
                        context.SetRuntimeError(RuntimeErrorType.ArrayIndexOutOfBounds, "Insert: array index out of bounds.");
                        return(null);
                    }

                    list.Insert(index, new Variable(null, elementType, item));

                    return(thisScope);
                };

                FunctionValue_Host newValue = new FunctionValue_Host(ourType, new ArgList {
                    IntrinsicTypeDefs.NUMBER, IntrinsicTypeDefs.TEMPLATE_0
                }, eval, false, ourType);
                classDef.AddMemberLiteral("Insert", newValue.valType, newValue);
            }

            //@ T Pop()
            //   Returns the value of the last element of the list and removes it from the list.
            //   Cannot be used in a foreach loop.
            {
                FunctionValue_Host.EvaluateDelegate eval = (context, args, thisScope) => {
                    PebbleList pebList = thisScope as PebbleList;
                    if (pebList.enumeratingCount > 0)
                    {
                        context.SetRuntimeError(RuntimeErrorType.ForeachModifyingContainer, "Pop: Attempt to remove an element from a list that is being enumerated in a foreach loop.");
                        return(null);
                    }

                    var list = pebList.list;
                    int ix   = list.Count - 1;
                    if (ix < 0)
                    {
                        context.SetRuntimeError(RuntimeErrorType.ArrayIndexOutOfBounds, "Pop: List is empty.");
                        return(null);
                    }

                    var result = list[ix].value;
                    list.RemoveAt(ix);
                    return(result);
                };

                FunctionValue_Host newValue = new FunctionValue_Host(IntrinsicTypeDefs.TEMPLATE_0, new ArgList {
                }, eval, false, ourType);
                classDef.AddMemberLiteral("Pop", newValue.valType, newValue);
            }

            //@ List<T> RemoveAt(num index)
            //   Removes element at the given index, and returns the list.
            //   Cannot be used in a foreach loop.
            {
                FunctionValue_Host.EvaluateDelegate eval = (context, args, thisScope) => {
                    double dix = (double)args[0];
                    int    ix  = (int)dix;

                    PebbleList pebList = thisScope as PebbleList;
                    if (pebList.enumeratingCount > 0)
                    {
                        context.SetRuntimeError(RuntimeErrorType.ForeachModifyingContainer, "RemoveAt: Attempt to modify a list that is being enumerated by a foreach loop.");
                        return(null);
                    }

                    var list = pebList.list;
                    if (ix < 0 || ix >= list.Count)
                    {
                        context.SetRuntimeError(RuntimeErrorType.ArrayIndexOutOfBounds, "RemoveAt: Index " + ix + " out of bounds of array of length " + list.Count + ".");
                        return(null);
                    }

                    list.RemoveAt(ix);
                    return(thisScope);
                };

                FunctionValue_Host newValue = new FunctionValue_Host(ourType, new ArgList {
                    IntrinsicTypeDefs.NUMBER
                }, eval, false, ourType);
                classDef.AddMemberLiteral("RemoveAt", newValue.valType, newValue);
            }

            //@ List<T> RemoveRange(num start, num count)
            //   Removes elements in the given range of indices, and returns the list.
            //   Cannot be used in a foreach loop.
            {
                FunctionValue_Host.EvaluateDelegate eval = (context, args, thisScope) => {
                    double dstart = (double)args[0];
                    int    start  = (int)dstart;
                    double dcount = (double)args[1];
                    int    count  = (int)dcount;

                    PebbleList pebList = thisScope as PebbleList;
                    if (pebList.enumeratingCount > 0)
                    {
                        context.SetRuntimeError(RuntimeErrorType.ForeachModifyingContainer, "RemoveRange: Attempt to modify a list that is being enumerated by a foreach loop.");
                        return(null);
                    }

                    var list = pebList.list;
                    if (start < 0 || start >= list.Count)
                    {
                        context.SetRuntimeError(RuntimeErrorType.ArrayIndexOutOfBounds, "RemoveRange: Start " + start + " out of bounds of array of length " + list.Count + ".");
                        return(null);
                    }
                    if (count < 0)
                    {
                        context.SetRuntimeError(RuntimeErrorType.ArrayIndexOutOfBounds, "RemoveRange: Count (" + count + ") cannot be negative.");
                        return(null);
                    }
                    if ((start + count) >= list.Count)
                    {
                        context.SetRuntimeError(RuntimeErrorType.ArrayIndexOutOfBounds, "RemoveRange: Count " + count + " exceeds array length (" + list.Count + ").");
                        return(null);
                    }

                    list.RemoveRange(start, count);
                    return(thisScope);
                };

                FunctionValue_Host newValue = new FunctionValue_Host(ourType, new ArgList {
                    IntrinsicTypeDefs.NUMBER, IntrinsicTypeDefs.NUMBER
                }, eval, false, ourType);
                classDef.AddMemberLiteral("RemoveRange", newValue.valType, newValue);
            }

            //@ List<T> Reverse()
            //   Reverses the list and returns it.
            {
                FunctionValue_Host.EvaluateDelegate eval = (context, args, thisScope) => {
                    var list = (thisScope as PebbleList).list;
                    list.Reverse();
                    return(thisScope);
                };

                FunctionValue_Host newValue = new FunctionValue_Host(ourType, new ArgList {
                }, eval, false, ourType);
                classDef.AddMemberLiteral("Reverse", newValue.valType, newValue);
            }

            //@ List<T> Set(num index, T newValue)
            //   Changes the value of the element at the given index, and returns the list.
            {
                FunctionValue_Host.EvaluateDelegate eval = (context, args, thisScope) => {
                    double dix = (double)args[0];
                    int    ix  = (int)dix;

                    object value = args[1];

                    var list = (thisScope as PebbleList).list;

                    // Bounds checking.
                    if (ix < 0 || ix >= list.Count)
                    {
                        context.SetRuntimeError(RuntimeErrorType.ArrayIndexOutOfBounds, "Set: Index " + ix + " out of bounds of array of length " + list.Count + ".");
                        return(null);
                    }

                    list[ix].value = value;

                    return(thisScope);
                };

                FunctionValue_Host newValue = new FunctionValue_Host(ourType, new ArgList {
                    IntrinsicTypeDefs.NUMBER, IntrinsicTypeDefs.TEMPLATE_0
                }, eval, false, ourType);
                classDef.AddMemberLiteral("Set", newValue.valType, newValue);
            }

            //@ List<T> Shuffle()
            //   Shuffles the list, putting the elements in random order.
            //	 Returns the list.
            {
                FunctionValue_Host.EvaluateDelegate eval = (context, args, thisScope) => {
                    var list = (thisScope as PebbleList).list;

                    Random rng = new Random();

                    int n = list.Count;
                    while (n > 1)
                    {
                        --n;
                        int      k     = rng.Next(n + 1);
                        Variable value = list[k];
                        list[k] = list[n];
                        list[n] = value;
                    }

                    return(thisScope);
                };

                FunctionValue_Host newValue = new FunctionValue_Host(ourType, new ArgList {
                }, eval, false, ourType);
                classDef.AddMemberLiteral("Shuffle", newValue.valType, newValue);
            }

            //@ List<T> Sort(functype<num(T, T>)> comparator)
            //   Sorts the list using the given comparator function.
            //   The comparator should behave the same as a C# Comparer. The first argument should be earlier in the
            //   list than the second, return a number < 0. If It should be later, return a number > 0. If their order
            //   is irrelevant, return 0.
            {
                FunctionValue_Host.EvaluateDelegate eval = (context, args, thisScope) => {
                    var list = (thisScope as PebbleList).list;

                    if (null == args[0])
                    {
                        context.SetRuntimeError(RuntimeErrorType.ArgumentInvalid, "Sort: comparator may not be null.");
                        return(null);
                    }

                    FunctionValue comparator = (FunctionValue)args[0];

                    List <object> argvals = new List <object>();
                    argvals.Add(0);
                    argvals.Add(0);

                    Comparison <Variable> hostComparator = new Comparison <Variable>(
                        (a, b) => {
                        argvals[0] = a.value;
                        argvals[1] = b.value;

                        // Note we use null instead of thisScope here. There is no way the sort function could be a
                        // class member because Sort's signature only takes function's whose type has no class.
                        double result = (double)comparator.Evaluate(context, argvals, null);
                        return(Convert.ToInt32(result));
                    }
                        );

                    list.Sort(hostComparator);
                    return(thisScope);
                };

                TypeDef_Function comparatorType = TypeFactory.GetTypeDef_Function(IntrinsicTypeDefs.NUMBER, new ArgList {
                    IntrinsicTypeDefs.TEMPLATE_0, IntrinsicTypeDefs.TEMPLATE_0
                }, -1, false, null, false, false);

                FunctionValue_Host newValue = new FunctionValue_Host(ourType, new ArgList {
                    comparatorType
                }, eval, false, ourType);
                classDef.AddMemberLiteral("Sort", newValue.valType, newValue);
            }

            //@ string ThisToScript(string prefix)
            //   ThisToScript is used by Serialize. A classes' ThisToScript function should return code which can rebuild the class.
            //   Note that it's only the content of the class, not the "new A" part. ie., it's the code that goes in the defstructor.
            {
                FunctionValue_Host.EvaluateDelegate eval = (context, args, thisScope) => {
                    string result = "";
                    string prefix = (string)args[0] + "\t";

                    var list = (thisScope as PebbleList).list;
                    for (int ii = 0; ii < list.Count; ++ii)
                    {
                        result += prefix + "Add(" + CoreLib.ValueToScript(context, list[ii].value, prefix + "\t", false) + ");\n";
                    }

                    return(result);
                };

                FunctionValue_Host newValue = new FunctionValue_Host(IntrinsicTypeDefs.STRING, new ArgList {
                    IntrinsicTypeDefs.STRING
                }, eval, false, ourType);
                classDef.AddMemberLiteral("ThisToScript", newValue.valType, newValue);
            }

            //@ string ToString()
            //   Returns a string representation of at least the first few elements of the list.
            {
                FunctionValue_Host.EvaluateDelegate eval = (context, args, thisScope) => {
                    var    list   = (thisScope as PebbleList).list;
                    string result = "List(" + list.Count + ")[";
                    for (int ii = 0; ii < Math.Min(4, list.Count); ++ii)
                    {
                        if (ii > 0)
                        {
                            result += ", ";
                        }
                        result += CoreLib.ValueToString(context, list[ii].value, true);
                    }
                    if (list.Count > 4)
                    {
                        result += ", ...";
                    }
                    return(result + "]");
                };

                FunctionValue_Host newValue = new FunctionValue_Host(IntrinsicTypeDefs.STRING, new ArgList {
                }, eval, false, ourType);
                classDef.AddMemberLiteral("ThisToString", newValue.valType, newValue);
            }

            classDef.FinalizeClass(engine.defaultContext);

            UnitTests.testFuncDelegates.Add("CoreList", RunTests);
        }
Beispiel #3
0
        /*
         * delegate bool LibraryTestFunc(Engine engine, bool verbose);
         *
         * public static void RegisterLibraryTests(LibraryTestFunc testFunc) {
         *      testFunc();
         * }
         */

        // **************************************************************************

        public Engine()
        {
            defaultContext = new ExecContext(this);
            CoreLib.Register(this);
        }
Beispiel #4
0
        public static void Register(Engine engine)
        {
            PebbleEnum consoleColorEnum = new PebbleEnum(engine.defaultContext, "ConsoleColor", IntrinsicTypeDefs.CONST_NUMBER);

            consoleColorEnum.AddValue_Literal(engine.defaultContext, "Black", 0.0);
            consoleColorEnum.AddValue_Literal(engine.defaultContext, "DarkBlue", 1.0);
            consoleColorEnum.AddValue_Literal(engine.defaultContext, "DarkGreen", 2.0);
            consoleColorEnum.AddValue_Literal(engine.defaultContext, "DarkCyan", 3.0);
            consoleColorEnum.AddValue_Literal(engine.defaultContext, "DarkRed", 4.0);
            consoleColorEnum.AddValue_Literal(engine.defaultContext, "DarkMagenta", 5.0);
            consoleColorEnum.AddValue_Literal(engine.defaultContext, "DarkYellow", 6.0);
            consoleColorEnum.AddValue_Literal(engine.defaultContext, "LightGray", 7.0);
            consoleColorEnum.AddValue_Literal(engine.defaultContext, "DarkGray", 8.0);
            consoleColorEnum.AddValue_Literal(engine.defaultContext, "Blue", 9.0);
            consoleColorEnum.AddValue_Literal(engine.defaultContext, "Green", 10.0);
            consoleColorEnum.AddValue_Literal(engine.defaultContext, "Cyan", 11.0);
            consoleColorEnum.AddValue_Literal(engine.defaultContext, "Red", 12.0);
            consoleColorEnum.AddValue_Literal(engine.defaultContext, "Magenta", 13.0);
            consoleColorEnum.AddValue_Literal(engine.defaultContext, "Yellow", 14.0);
            consoleColorEnum.AddValue_Literal(engine.defaultContext, "White", 15.0);
            // Finalize.
            consoleColorEnum.EvaluateValues(engine.defaultContext);

            // **********************************

            Regex colorRegex = new Regex(@"(#\d+b?#)", RegexOptions.Compiled);

            TypeDef_Class ourType  = TypeFactory.GetTypeDef_Class("Console", null, false);
            ClassDef      classDef = engine.defaultContext.CreateClass("Console", ourType, null, null, true);

            classDef.Initialize();

            //@ global void Clear()
            //   Clears the screen.
            {
                FunctionValue_Host.EvaluateDelegate eval = (context, args, thisScope) => {
                    Console.Clear();
                    return(null);
                };
                FunctionValue newValue = new FunctionValue_Host(IntrinsicTypeDefs.VOID, new ArgList {
                }, eval, false);
                classDef.AddMemberLiteral("Clear", newValue.valType, newValue, true);
            }

            //@ global string GetCh()
            //   Waits for the user to press a key and returns it.
            {
                FunctionValue_Host.EvaluateDelegate eval = (context, args, thisScope) => {
                    ConsoleKeyInfo cki = Console.ReadKey(true);
                    return(cki.KeyChar.ToString());
                };
                FunctionValue newValue = new FunctionValue_Host(IntrinsicTypeDefs.STRING, new ArgList {
                }, eval, false);
                classDef.AddMemberLiteral("GetCh", newValue.valType, newValue, true);
            }

            //@ global string Print(...)
            //   Alias of WriteLine.

            //@ global string ReadLine()
            //   Reads a line of input and returns it.
            {
                FunctionValue_Host.EvaluateDelegate eval = (context, args, thisScope) => {
                    return(Console.ReadLine());
                };
                FunctionValue newValue = new FunctionValue_Host(IntrinsicTypeDefs.STRING, new ArgList {
                }, eval, false);
                classDef.AddMemberLiteral("ReadLine", newValue.valType, newValue, true);
            }

            //@ global void ResetColor()
            //   Resets foreground and background colors to their defaults.
            {
                FunctionValue_Host.EvaluateDelegate eval = (context, args, thisScope) => {
                    Console.ResetColor();
                    return(null);
                };
                FunctionValue newValue = new FunctionValue_Host(IntrinsicTypeDefs.VOID, new ArgList {
                }, eval, false);
                classDef.AddMemberLiteral("ResetColor", newValue.valType, newValue, true);
            }

            //@ global num SetBackgroundColor(ConsoleColor color)
            //   Sets the background color to the given value.
            //   Returns the previous color.
            {
                FunctionValue_Host.EvaluateDelegate eval = (context, args, thisScope) => {
                    ClassValue_Enum enumVal = args[0] as ClassValue_Enum;
                    int             iColor  = Convert.ToInt32((double)enumVal.GetValue());

                    int iPrevColor = Convert.ToInt32(Console.BackgroundColor);
                    Console.BackgroundColor = (ConsoleColor)iColor;
                    return(consoleColorEnum._classDef.staticVars[iPrevColor].value);
                };
                FunctionValue newValue = new FunctionValue_Host(consoleColorEnum.enumType, new ArgList {
                    consoleColorEnum.enumType
                }, eval, false);
                classDef.AddMemberLiteral("SetBackgroundColor", newValue.valType, newValue, true);
            }

            //@ global num SetForegroundColor(num color)
            //   Sets the foreground color to the given value. The valid values are 0-15.
            //   Returns the previous color.
            {
                FunctionValue_Host.EvaluateDelegate eval = (context, args, thisScope) => {
                    ClassValue_Enum enumVal = args[0] as ClassValue_Enum;
                    int             iColor  = Convert.ToInt32((double)enumVal.GetValue());

                    int iPrevColor = Convert.ToInt32(Console.ForegroundColor);
                    Console.ForegroundColor = (ConsoleColor)iColor;
                    return(consoleColorEnum._classDef.staticVars[iPrevColor].value);
                };
                FunctionValue newValue = new FunctionValue_Host(consoleColorEnum.enumType, new ArgList {
                    consoleColorEnum.enumType
                }, eval, false);
                classDef.AddMemberLiteral("SetForegroundColor", newValue.valType, newValue, true);
            }

            //@ global string Write(...)
            //   Works much like Print but doesn't automatically include a newline, so you can write partial lines.
            //   Also, if an argument is a ConsoleColor, rather than writing it the function temporarily sets the foreground color to the given color.
            //   Colors can be inserted into the string by using, for example, #1#, which will set the foreground color to 1, or #11b# which sets the background color to 11.
            //   This function restores the colors to what they were before the function was called.
            //   Returns the aggregated string, minus any provided colors.
            FunctionValue_Host.EvaluateDelegate evalWrite;
            {
                FunctionValue_Host.EvaluateDelegate eval = (context, args, thisScope) => {
                    ConsoleColor startingForeground = Console.ForegroundColor;
                    ConsoleColor startingBackground = Console.BackgroundColor;

                    string result = "";
                    foreach (object val in args)
                    {
                        if (val is ClassValue_Enum)
                        {
                            ClassValue_Enum cve = (ClassValue_Enum)val;
                            if (cve.classDef == consoleColorEnum._classDef)
                            {
                                int color = Convert.ToInt32((double)cve.GetValue());
                                Console.ForegroundColor = (ConsoleColor)color;
                                continue;
                            }
                        }


                        if (val is string)
                        {
                            string v = val as string;

                            string[] splits = colorRegex.Split(v);
                            foreach (string str in splits)
                            {
                                if (str.Length > 2 && '#' == str[0] && '#' == str[str.Length - 1])
                                {
                                    int  iColor;
                                    bool background = false;
                                    if ('b' == str[str.Length - 2])
                                    {
                                        iColor     = Convert.ToInt32(str.Substring(1, str.Length - 3));
                                        background = true;
                                    }
                                    else
                                    {
                                        iColor = Convert.ToInt32(str.Substring(1, str.Length - 2));
                                    }

                                    if (iColor < 0 || iColor > 15)
                                    {
                                        context.SetRuntimeError(RuntimeErrorType.ArgumentInvalid, "Write: Color escapes must be between 0 and 15.");
                                        Console.ForegroundColor = startingForeground;
                                        Console.BackgroundColor = startingBackground;
                                        return(null);
                                    }
                                    if (background)
                                    {
                                        Console.BackgroundColor = (ConsoleColor)iColor;
                                    }
                                    else
                                    {
                                        Console.ForegroundColor = (ConsoleColor)iColor;
                                    }
                                }
                                else
                                {
                                    result += str;
                                    Console.Write(str);
                                }
                            }
                        }
                        else
                        {
                            string s = CoreLib.ValueToString(context, val, false);
                            result += s;
                            Console.Write(s);
                        }
                    }

                    Console.ForegroundColor = startingForeground;
                    Console.BackgroundColor = startingBackground;

                    return(result);
                };
                FunctionValue newValue = new FunctionValue_Host(IntrinsicTypeDefs.STRING, new ArgList {
                    IntrinsicTypeDefs.ANY
                }, eval, true);
                classDef.AddMemberLiteral("Write", newValue.valType, newValue, true);

                evalWrite = eval;
            }

            //@ global string WriteLine(...)
            //   Works exactly like Write but just adds a newline at the end.
            //   Returns the aggregated string, minus any provided colors.
            {
                FunctionValue_Host.EvaluateDelegate eval = (context, args, thisScope) => {
                    object result = evalWrite(context, args, thisScope);
                    Console.Write("\n");
                    return(result);
                };
                FunctionValue newValue = new FunctionValue_Host(IntrinsicTypeDefs.STRING, new ArgList {
                    IntrinsicTypeDefs.ANY
                }, eval, true);
                classDef.AddMemberLiteral("WriteLine", newValue.valType, newValue, true);
                classDef.AddMemberLiteral("Print", newValue.valType, newValue, true);
            }

            classDef.FinalizeClass(engine.defaultContext);
        }
Beispiel #5
0
        public static void Register(Engine engine)
        {
            //*****************************
            // Create ScriptError enum.

            scriptErrorEnum = new PebbleEnum(engine.defaultContext, "ScriptError", IntrinsicTypeDefs.CONST_STRING);

            // Add a value for "no error" since enums can't be null.
            scriptErrorEnum.AddValue_Literal(engine.defaultContext, "NoError", "NoError");

            // Add both Parse and Runtime errors to the list.
            foreach (string name in Enum.GetNames(typeof(ParseErrorType)))
            {
                scriptErrorEnum.AddValue_Literal(engine.defaultContext, name, name);
            }
            foreach (string name in Enum.GetNames(typeof(RuntimeErrorType)))
            {
                scriptErrorEnum.AddValue_Literal(engine.defaultContext, name, name);
            }

            // Finalize.
            scriptErrorEnum.EvaluateValues(engine.defaultContext);

            // Save the value for NoError for convenience.
            scriptErrorEnum_noErrorValue = scriptErrorEnum.GetValue("NoError");

            //*******************************
            //@ class Result<T>
            //   This was added just in case users might have a need for a templated class that encapsulates a value and a status code.
            {
                TypeDef_Class ourType = TypeFactory.GetTypeDef_Class("Result", new ArgList {
                    IntrinsicTypeDefs.TEMPLATE_0
                }, false);
                ClassDef classDef = engine.defaultContext.CreateClass("Result", ourType, null, new List <string> {
                    "T"
                });
                classDef.Initialize();

                //@ T value;
                //   The resultant value IF there was no error.
                classDef.AddMember("value", IntrinsicTypeDefs.TEMPLATE_0);
                //@ num status;
                //   A numeric status code. By convention, 0 means no error and anything else means error.
                classDef.AddMemberLiteral("status", IntrinsicTypeDefs.NUMBER, 0.0);
                //@ string message;
                //   A place to store error messages if desired.
                classDef.AddMember("message", IntrinsicTypeDefs.STRING);

                //@ bool IsSuccess()
                //   Returns true iff status == 0.
                {
                    FunctionValue_Host.EvaluateDelegate eval = (context, args, thisScope) => {
                        ClassValue scope = thisScope as ClassValue;
                        return((double)scope.GetByName("status").value == 0.0);
                    };

                    FunctionValue_Host newValue = new FunctionValue_Host(IntrinsicTypeDefs.BOOL, new ArgList {
                    }, eval, false, ourType);
                    classDef.AddMemberLiteral("IsSuccess", newValue.valType, newValue);
                }

                //@ string ToString()
                //   Returns a string representation of the Result.
                {
                    FunctionValue_Host.EvaluateDelegate eval = (context, args, thisScope) => {
                        ClassValue scope  = thisScope as ClassValue;
                        double     status = (double)scope.GetByName("status").value;

                        string result = scope.classDef.typeDef.ToString() + "[";
                        if (0.0 == status)
                        {
                            result += CoreLib.ValueToString(context, scope.GetByName("value").value, true);
                        }
                        else
                        {
                            result += status + ": \"" + (string)scope.GetByName("message").value + "\"";
                        }

                        return(result + "]");
                    };

                    FunctionValue_Host newValue = new FunctionValue_Host(IntrinsicTypeDefs.STRING, new ArgList {
                    }, eval, false, ourType);
                    classDef.AddMemberLiteral("ThisToString", newValue.valType, newValue);
                }

                classDef.FinalizeClass(engine.defaultContext);
                resultClassDef = classDef;
            }

            //*******************************
            //@ class ScriptResult<T>
            //   For returning the result of something that can error, like an Exec call.
            {
                TypeDef_Class ourType = TypeFactory.GetTypeDef_Class("ScriptResult", new ArgList {
                    IntrinsicTypeDefs.TEMPLATE_0
                }, false);
                ClassDef classDef = engine.defaultContext.CreateClass("ScriptResult", ourType, null, new List <string> {
                    "T"
                });
                classDef.Initialize();

                //@ T value;
                //   The return value if there was no error.
                classDef.AddMember("value", IntrinsicTypeDefs.TEMPLATE_0);
                //@ ScriptError error;
                //   ScriptError.NoError if no error.
                classDef.AddMemberLiteral("error", CoreLib.scriptErrorEnum._classDef.typeDef, CoreLib.scriptErrorEnum_noErrorValue);
                //@ string message;
                //   Optional error message.
                classDef.AddMember("message", IntrinsicTypeDefs.STRING);

                //@ bool IsSuccess()
                //   Returns true iff error == ScriptError.NoError.
                {
                    FunctionValue_Host.EvaluateDelegate eval = (context, args, thisScope) => {
                        ClassValue scope = thisScope as ClassValue;
                        return(scope.GetByName("error").value == CoreLib.scriptErrorEnum_noErrorValue);
                    };

                    FunctionValue_Host newValue = new FunctionValue_Host(IntrinsicTypeDefs.BOOL, new ArgList {
                    }, eval, false, ourType);
                    classDef.AddMemberLiteral("IsSuccess", newValue.valType, newValue);
                }

                //@ string ToString()
                //   Returns a string representation of the ScriptError.
                {
                    FunctionValue_Host.EvaluateDelegate eval = (context, args, thisScope) => {
                        ClassValue scope = thisScope as ClassValue;
                        var        error = (ClassValue_Enum)scope.GetByName("error").value;

                        string result = scope.classDef.typeDef.ToString() + "[";
                        if (CoreLib.scriptErrorEnum_noErrorValue == error)
                        {
                            result += CoreLib.ValueToString(context, scope.GetByName("value").value, true);
                        }
                        else
                        {
                            result += error.GetName() + ": \"" + (string)scope.GetByName("message").value + "\"";
                        }

                        return(result + "]");
                    };

                    FunctionValue_Host newValue = new FunctionValue_Host(IntrinsicTypeDefs.STRING, new ArgList {
                    }, eval, false, ourType);
                    classDef.AddMemberLiteral("ThisToString", newValue.valType, newValue);
                }

                classDef.FinalizeClass(engine.defaultContext);
                resultClassDef = classDef;
            }

            // This code makes sure that Result<bool> is a registered class and type.
            List <ITypeDef> genericTypes = new ArgList();

            genericTypes.Add(IntrinsicTypeDefs.BOOL);
            scriptResultBoolTypeDef  = TypeFactory.GetTypeDef_Class("ScriptResult", genericTypes, false);
            scriptResultBoolClassDef = engine.defaultContext.RegisterIfUnregisteredTemplate(scriptResultBoolTypeDef);
            Pb.Assert(null != scriptResultBoolTypeDef && null != scriptResultBoolClassDef, "Error initializing ScriptResult<bool>.");


            ////////////////////////////////////////////////////////////////////////////
            // Register non-optional libraries.

            //CoreResult.Register(engine);
            // List and Dictionary probably need to be first because other libraries sometimes use them.
            CoreList.Register(engine);
            CoreDictionary.Register(engine);
            MathLib.Register(engine);
            RegexLib.Register(engine);
            StringLib.Register(engine);
            StreamLib.Register(engine);

            //@ global const num FORMAX;
            //   The highest value a for iterator can be. Attempting to exceed it generates an error.
            engine.defaultContext.CreateGlobal("FORMAX", IntrinsicTypeDefs.CONST_NUMBER, Expr_For.MAX);

            ////////////////////////////////////////////////////////////////////////////
            // Library functions

            //@ global ScriptResult<bool> Exec(string script)
            //   Executes the supplied script.
            //   Since this is not running "interactive" (or inline), the only way the script can
            //   have an external effect is if it affects global things (variables, class definitions).
            //   The returned ScriptResult's value is only true(success) or false (error).
            {
                FunctionValue_Host.EvaluateDelegate eval = (context, args, thisScope) => {
                    string script = (string)args[0];

                    ClassValue scriptResultInst = scriptResultBoolClassDef.Allocate(context);
                    Variable   value            = scriptResultInst.GetByName("value");
                    Variable   error            = scriptResultInst.GetByName("error");
                    Variable   message          = scriptResultInst.GetByName("message");

                    ScriptResult result = context.engine.RunScript(script, false, null, true);
                    if (null != result.parseErrors)
                    {
                        value.value   = false;
                        error.value   = scriptErrorEnum.GetValue(result.parseErrors[0].type.ToString());;
                        message.value = result.parseErrors[0].ToString();
                    }
                    else if (null != result.runtimeError)
                    {
                        value.value   = false;
                        error.value   = result.value;
                        message.value = result.runtimeError.ToString();
                    }
                    else
                    {
                        value.value   = true;
                        error.value   = scriptErrorEnum_noErrorValue;
                        message.value = "";
                    }

                    return(scriptResultInst);
                };
                FunctionValue newValue = new FunctionValue_Host(scriptResultBoolTypeDef, new ArgList {
                    IntrinsicTypeDefs.STRING
                }, eval, false);
                engine.AddBuiltInFunction(newValue, "Exec");
            }

            //@ global ScriptResult<bool> ExecInline(string)
            //   This executes the given script in the current scope. This is different from Exec, because Exec exists in its own scope.
            //   The returned ScriptResult's value is only true(success) or false (error).
            {
                FunctionValue_Host.EvaluateDelegate eval = (context, args, thisScope) => {
                    string script = (string)args[0];

                    ClassValue scriptResultInst = scriptResultBoolClassDef.Allocate(context);
                    Variable   value            = scriptResultInst.GetByName("value");
                    Variable   error            = scriptResultInst.GetByName("error");
                    Variable   message          = scriptResultInst.GetByName("message");

                    ScriptResult result = context.engine.RunInteractiveScript(script, false);
                    if (null != result.parseErrors)
                    {
                        value.value   = false;
                        error.value   = scriptErrorEnum.GetValue(result.parseErrors[0].type.ToString());;
                        message.value = result.parseErrors[0].ToString();
                    }
                    else if (null != result.runtimeError)
                    {
                        value.value   = false;
                        error.value   = result.value;
                        message.value = result.runtimeError.ToString();
                    }
                    else
                    {
                        value.value   = true;
                        error.value   = scriptErrorEnum_noErrorValue;
                        message.value = "";
                    }
                    return(scriptResultInst);
                };
                FunctionValue newValue = new FunctionValue_Host(scriptResultBoolTypeDef, new ArgList {
                    IntrinsicTypeDefs.STRING
                }, eval, false);
                engine.AddBuiltInFunction(newValue, "ExecInline");
            }

            //@ global string Print(...)
            //   Converts all arguments to strings, concatenates them, then outputs the result using the Engine' Log function.
            //   This function can be set to whatever the host program likes: see Engine.Log
            {
                FunctionValue_Host.EvaluateDelegate eval = (context, args, thisScope) => {
                    string result = StandardPrintFunction(context, args);
                    context.engine.Log(result);
                    return(result);
                };

                FunctionValue newValue = new FunctionValue_Host(IntrinsicTypeDefs.STRING, new List <ITypeDef> {
                    IntrinsicTypeDefs.ANY
                }, eval, true);
                engine.AddBuiltInFunction(newValue, "Print");
            }

            //@ global string ToScript(any)
            //   Returns a script which, when run, returns a value equal to the value passed into ToScript.
            {
                FunctionValue_Host.EvaluateDelegate eval = (context, args, thisScope) => {
                    object val0 = args[0];
                    return(ValueToScript(context, val0));
                };
                FunctionValue newValue = new FunctionValue_Host(IntrinsicTypeDefs.STRING, new ArgList {
                    IntrinsicTypeDefs.ANY
                }, eval, false);
                engine.AddBuiltInFunction(newValue, "ToScript");
            }


            /////////////////////////////////////////////////////////////////
            // Type Conversion

            //@ global bool ToBool(any)
            //   Attempts to convert input into a boolean value.
            //   0 and null are false. != 0 and non-null references are true. Strings are handled by Convert.ToBoolean,
            //   which can throw an exception if it doesn't know how to convert the string.
            {
                FunctionValue_Host.EvaluateDelegate eval = (context, args, thisScope) => {
                    object val = args[0];
                    if (null == val)
                    {
                        return(false);
                    }
                    else if (val is bool)
                    {
                        return((bool)val);
                    }
                    else if (val is double)
                    {
                        return(Convert.ToBoolean((double)val));
                    }
                    else if (val is string)
                    {
                        try {
                            return(Convert.ToBoolean((string)val));                            // this loves to throw errors
                        } catch (Exception e) {
                            context.SetRuntimeError(RuntimeErrorType.ConversionInvalid, "ToBool - C# error: " + e.ToString());
                            return(null);
                        }
                    }
                    else
                    {
                        return(true);
                    }
                };
                FunctionValue newValue = new FunctionValue_Host(IntrinsicTypeDefs.BOOL, new ArgList {
                    IntrinsicTypeDefs.ANY
                }, eval, false);
                engine.AddBuiltInFunction(newValue, "ToBool");
            }

            //@ global num ToNum(any)
            //   Attempts to convert input to a num.
            //   true -> 1, false -> 0, null -> 0, non-null object reference -> 1. Strings are handled by Convert.ToDouble,
            //   which can throw an error if it doesn't know how to convert the string.
            {
                FunctionValue_Host.EvaluateDelegate eval = (context, args, thisScope) => {
                    object val = args[0];
                    if (null == val)
                    {
                        return(0.0);
                    }
                    else if (val is double)
                    {
                        return((double)val);
                    }
                    else if (val is bool)
                    {
                        return((bool)val ? 1.0 : 0.0);
                    }
                    else if (val is string)
                    {
                        try {
                            return(Convert.ToDouble((string)val));                              // this loves to throw errors
                        } catch {
                            context.SetRuntimeError(RuntimeErrorType.ConversionInvalid, "ToNum - Cannot convert string \"" + ((string)val) + "\" to number.");
                            return(null);
                        }
                    }
                    else
                    {
                        return(1.0);
                    }
                };
                FunctionValue newValue = new FunctionValue_Host(IntrinsicTypeDefs.NUMBER, new ArgList {
                    IntrinsicTypeDefs.ANY
                }, eval, false);
                engine.AddBuiltInFunction(newValue, "ToNum");
            }

            //@ global string ToString(...)
            //   Converts all arguments to strings, concatenates them, and returns the result.
            {
                FunctionValue_Host.EvaluateDelegate eval = (context, args, thisScope) => {
                    return(StandardPrintFunction(context, args));
                };
                FunctionValue newValue = new FunctionValue_Host(IntrinsicTypeDefs.STRING, new ArgList {
                    IntrinsicTypeDefs.ANY
                }, eval, true);
                engine.AddBuiltInFunction(newValue, "ToString");
            }

            UnitTests.testFuncDelegates.Add("CoreLib", RunTests);
        }
Beispiel #6
0
        public static void Register(Engine engine)
        {
            //@ class String

            TypeDef_Class ourType  = TypeFactory.GetTypeDef_Class("String", null, false);
            ClassDef      classDef = engine.defaultContext.CreateClass("String", ourType, null, null, true);

            classDef.Initialize();

            // This makes sure List<num> is registered in the type library, as this class uses it and we can't rely
            // scripts to register it.
            engine.defaultContext.RegisterIfUnregisteredList(IntrinsicTypeDefs.NUMBER);

            //@ static num CompareTo(string, string)
            //   Wraps C# CompareTo function, which essentially returns a number < 0 if a comes before b
            //   alphabetically, > 0 if a comes after b, and 0 if they are identical.
            {
                FunctionValue_Host.EvaluateDelegate eval = (context, args, thisScope) => {
                    string a = (string)args[0];
                    string b = (string)args[1];
                    return(Convert.ToDouble(a.CompareTo(b)));
                };

                FunctionValue newValue = new FunctionValue_Host(IntrinsicTypeDefs.NUMBER, new ArgList {
                    IntrinsicTypeDefs.STRING, IntrinsicTypeDefs.STRING
                }, eval, false);
                classDef.AddMemberLiteral("CompareTo", newValue.valType, newValue, true);
            }

            //@ static string Concat(any[, ...])
            //   Converts all arguments to strings and concatenates them. Same as ToString.
            {
                FunctionValue_Host.EvaluateDelegate eval = (context, args, thisScope) => {
                    return(CoreLib.StandardPrintFunction(context, args));
                };
                FunctionValue newValue = new FunctionValue_Host(IntrinsicTypeDefs.STRING, new ArgList {
                    IntrinsicTypeDefs.ANY
                }, eval, true);
                classDef.AddMemberLiteral("Concat", newValue.valType, newValue, true);
            }

            //@ static bool EndsWith(string s, string search)
            //   Wrapper for C# EndsWith. Returns true if s ends with search.
            {
                FunctionValue_Host.EvaluateDelegate eval = (context, args, thisScope) => {
                    string a = (string)args[0];
                    string b = (string)args[1];
                    return(a.EndsWith(b));
                };

                FunctionValue newValue = new FunctionValue_Host(IntrinsicTypeDefs.BOOL, new ArgList {
                    IntrinsicTypeDefs.STRING, IntrinsicTypeDefs.STRING
                }, eval, false);
                classDef.AddMemberLiteral("EndsWith", newValue.valType, newValue, true);
            }

            //@ static bool Equals(string, string)
            //   Returns true iff the strings are exactly equal. The same thing as using the == operator.
            {
                FunctionValue_Host.EvaluateDelegate eval = (context, args, thisScope) => {
                    string a = (string)args[0];
                    string b = (string)args[1];
                    return(a.Equals(b));
                };

                FunctionValue newValue = new FunctionValue_Host(IntrinsicTypeDefs.BOOL, new ArgList {
                    IntrinsicTypeDefs.STRING, IntrinsicTypeDefs.STRING
                }, eval, false);
                classDef.AddMemberLiteral("Equals", newValue.valType, newValue, true);
            }

            //@ static bool EqualsI(string, string)
            //   Returns true if the strings are equal, ignoring case. Equivalent to the ~= operator.
            {
                FunctionValue_Host.EvaluateDelegate eval = (context, args, thisScope) => {
                    string a = (string)args[0];
                    string b = (string)args[1];
                    return(a.ToLower().Equals(b.ToLower()));
                };

                FunctionValue newValue = new FunctionValue_Host(IntrinsicTypeDefs.BOOL, new ArgList {
                    IntrinsicTypeDefs.STRING, IntrinsicTypeDefs.STRING
                }, eval, false);
                classDef.AddMemberLiteral("EqualsI", newValue.valType, newValue, true);
            }

            //@ static string Format(string[, any, ...])
            //   Generated formatted strings. Wrapper for C# String.Format(string, object[]). See documentation of that function for details.
            //   Putting weird things like Lists or functions into the args will produce undefined results.
            {
                FunctionValue_Host.EvaluateDelegate eval = (context, args, thisScope) => {
                    string   source = (string)args[0];
                    Object[] a      = new Object[args.Count - 1];
                    args.CopyTo(1, a, 0, args.Count - 1);
                    string result = "";
                    try {
                        result = String.Format(source, a);
                    } catch (Exception e) {
                        context.SetRuntimeError(RuntimeErrorType.NativeException, e.ToString());
                        return(null);
                    }
                    return(result);
                };

                FunctionValue newValue = new FunctionValue_Host(IntrinsicTypeDefs.STRING, new ArgList {
                    IntrinsicTypeDefs.STRING, IntrinsicTypeDefs.ANY
                }, eval, true);
                classDef.AddMemberLiteral("Format", newValue.valType, newValue, true);
            }

            //@ static List<string> GetCharList(string)
            //   Returns a list of strings containing one character of the input string.
            {
                FunctionValue_Host.EvaluateDelegate eval = (context, args, thisScope) => {
                    string source = (string)args[0];

                    PebbleList list = PebbleList.AllocateListString(context, "String::GetCharList result");
                    foreach (char c in source.ToCharArray())
                    {
                        list.list.Add(new Variable(null, IntrinsicTypeDefs.STRING, Convert.ToString(c)));
                    }

                    return(list);
                };

                FunctionValue newValue = new FunctionValue_Host(IntrinsicTypeDefs.LIST_STRING, new ArgList {
                    IntrinsicTypeDefs.STRING
                }, eval, false);
                classDef.AddMemberLiteral("GetCharList", newValue.valType, newValue, true);
            }

            //@ static List<num> GetUnicode(string)
            //   Returns the Unicode numeric values for the characters in the input string.
            //   Returns an empty list if the string is empty.
            {
                FunctionValue_Host.EvaluateDelegate eval = (context, args, thisScope) => {
                    string source = (string)args[0];

                    PebbleList list = PebbleList.AllocateListString(context, "String::GetUnicode result");
                    foreach (char c in source.ToCharArray())
                    {
                        list.list.Add(new Variable(null, IntrinsicTypeDefs.NUMBER, Convert.ToDouble(Convert.ToInt32(c))));
                    }

                    return(list);
                };

                FunctionValue newValue = new FunctionValue_Host(IntrinsicTypeDefs.LIST_NUMBER, new ArgList {
                    IntrinsicTypeDefs.STRING
                }, eval, false);
                classDef.AddMemberLiteral("GetUnicode", newValue.valType, newValue, true);
            }

            //@ static num IndexOfChar(string toBeSearched, string searchChars, num startIndex = 0)
            //   Returns the index of the first instance of any of the characters in search.
            {
                FunctionValue_Host.EvaluateDelegate eval = (context, args, thisScope) => {
                    string a          = (string)args[0];
                    string b          = (string)args[1];
                    int    startIndex = Convert.ToInt32((double)args[2]);

                    if (0 == a.Length || 0 == b.Length)
                    {
                        return(-1.0);
                    }

                    int lowestIx = Int32.MaxValue;
                    foreach (char c in b)
                    {
                        int ix = a.IndexOf(c, startIndex);
                        if (ix >= 0 && ix < lowestIx)
                        {
                            lowestIx = ix;
                        }
                    }

                    if (lowestIx < Int32.MaxValue)
                    {
                        return(Convert.ToDouble(lowestIx));
                    }

                    return(-1.0);
                };

                List <Expr_Literal> defaultArgVals = new List <Expr_Literal>();
                defaultArgVals.Add(null);
                defaultArgVals.Add(null);
                defaultArgVals.Add(new Expr_Literal(null, 0.0, IntrinsicTypeDefs.NUMBER));
                FunctionValue newValue = new FunctionValue_Host(IntrinsicTypeDefs.NUMBER, new ArgList {
                    IntrinsicTypeDefs.STRING, IntrinsicTypeDefs.STRING, IntrinsicTypeDefs.NUMBER
                }, eval, false, null, true, defaultArgVals);
                classDef.AddMemberLiteral("IndexOfChar", newValue.valType, newValue, true);
            }

            //@ static num IndexOfString(string toBeSearched, string searchString, num startIndex = 0)
            //   Returns the index of the first instance of the entire search string.
            {
                FunctionValue_Host.EvaluateDelegate eval = (context, args, thisScope) => {
                    string a          = (string)args[0];
                    string b          = (string)args[1];
                    int    startIndex = Convert.ToInt32((double)args[2]);

                    if (0 == a.Length || 0 == b.Length)
                    {
                        return(-1.0);
                    }

                    int ix = a.IndexOf(b, startIndex);
                    return(Convert.ToDouble(ix));
                };

                List <Expr_Literal> defaultArgVals = new List <Expr_Literal>();
                defaultArgVals.Add(null);
                defaultArgVals.Add(null);
                defaultArgVals.Add(new Expr_Literal(null, 0.0, IntrinsicTypeDefs.NUMBER));
                FunctionValue newValue = new FunctionValue_Host(IntrinsicTypeDefs.NUMBER, new ArgList {
                    IntrinsicTypeDefs.STRING, IntrinsicTypeDefs.STRING, IntrinsicTypeDefs.NUMBER
                }, eval, false, null, true, defaultArgVals);
                classDef.AddMemberLiteral("IndexOfString", newValue.valType, newValue, true);
            }

            //@ static num LastIndexOfChar(string toBeSearched, string searchChars, num startIndex = -1)
            //   Returns the index of the last instance of the entire search string,
            //   If startIndex is >= 0, starts searching backwards from the given index.
            {
                FunctionValue_Host.EvaluateDelegate eval = (context, args, thisScope) => {
                    string a          = (string)args[0];
                    string b          = (string)args[1];
                    int    startIndex = Convert.ToInt32((double)args[2]);

                    if (0 == a.Length || 0 == b.Length)
                    {
                        return(-1.0);
                    }

                    if (startIndex < 0)
                    {
                        startIndex = a.Length - 1;
                    }
                    else if (startIndex >= a.Length)
                    {
                        context.SetRuntimeError(RuntimeErrorType.ArgumentInvalid, "LastIndexOfChar startIndex argument is greater than the length of the string.");
                        return(null);
                    }

                    char[] chars    = b.ToCharArray();
                    int    lowestIx = Int32.MaxValue;
                    foreach (char c in b)
                    {
                        int ix = a.LastIndexOfAny(chars, startIndex);
                        if (ix >= 0 && ix < lowestIx)
                        {
                            lowestIx = ix;
                        }
                    }

                    if (lowestIx < Int32.MaxValue)
                    {
                        return(Convert.ToDouble(lowestIx));
                    }
                    return(-1.0);
                };

                List <Expr_Literal> defaultArgVals = new List <Expr_Literal>();
                defaultArgVals.Add(null);
                defaultArgVals.Add(null);
                defaultArgVals.Add(new Expr_Literal(null, -1.0, IntrinsicTypeDefs.NUMBER));
                FunctionValue newValue = new FunctionValue_Host(IntrinsicTypeDefs.NUMBER, new ArgList {
                    IntrinsicTypeDefs.STRING, IntrinsicTypeDefs.STRING, IntrinsicTypeDefs.NUMBER
                }, eval, false, null, true, defaultArgVals);
                classDef.AddMemberLiteral("LastIndexOfChar", newValue.valType, newValue, true);
            }

            //@ static num LastIndexOfString(string toBeSearched, string searchString, num startIndex = -1)
            //   Returns the index of the last instance of the entire search string,
            //   If startIndex is > 0, starts searching backwards from the given index.
            {
                FunctionValue_Host.EvaluateDelegate eval = (context, args, thisScope) => {
                    string a          = (string)args[0];
                    string b          = (string)args[1];
                    int    startIndex = Convert.ToInt32((double)args[2]);

                    if (0 == a.Length || 0 == b.Length)
                    {
                        return(-1.0);
                    }

                    if (startIndex < 0)
                    {
                        startIndex = a.Length - 1;
                    }
                    else if (startIndex >= a.Length)
                    {
                        context.SetRuntimeError(RuntimeErrorType.ArgumentInvalid, "LastIndexOfString startIndex argument is greater than the length of the string.");
                        return(null);
                    }

                    int ix = a.LastIndexOf(b, startIndex);
                    return(Convert.ToDouble(ix));
                };

                List <Expr_Literal> defaultArgVals = new List <Expr_Literal>();
                defaultArgVals.Add(null);
                defaultArgVals.Add(null);
                defaultArgVals.Add(new Expr_Literal(null, -1.0, IntrinsicTypeDefs.NUMBER));
                FunctionValue newValue = new FunctionValue_Host(IntrinsicTypeDefs.NUMBER, new ArgList {
                    IntrinsicTypeDefs.STRING, IntrinsicTypeDefs.STRING, IntrinsicTypeDefs.NUMBER
                }, eval, false, null, true, defaultArgVals);
                classDef.AddMemberLiteral("LastIndexOfString", newValue.valType, newValue, true);
            }

            //@ static num Length(string)
            //   Returns the length of the string.
            {
                FunctionValue_Host.EvaluateDelegate eval = (context, args, thisScope) => {
                    string a = (string)args[0];
                    return(Convert.ToDouble(a.Length));
                };

                FunctionValue newValue = new FunctionValue_Host(IntrinsicTypeDefs.NUMBER, new ArgList {
                    IntrinsicTypeDefs.STRING
                }, eval, false);
                classDef.AddMemberLiteral("Length", newValue.valType, newValue, true);
            }

            //@ static string PadLeft(string, num n, string pad)
            //   Returns s with n instances of string pad to the left.
            {
                FunctionValue_Host.EvaluateDelegate eval = (context, args, thisScope) => {
                    string a = (string)args[0];

                    double nd = (double)args[1];
                    int    n  = Convert.ToInt32(nd);

                    string p = (string)args[2];
                    if (0 == p.Length)
                    {
                        p = " ";
                    }

                    char c = p[0];
                    return(a.PadLeft(n, c));
                };

                FunctionValue newValue = new FunctionValue_Host(IntrinsicTypeDefs.STRING, new ArgList {
                    IntrinsicTypeDefs.STRING, IntrinsicTypeDefs.NUMBER, IntrinsicTypeDefs.STRING
                }, eval, false);
                classDef.AddMemberLiteral("PadLeft", newValue.valType, newValue, true);
            }

            //@ static string PadRight(string s, num n, string pad)
            //   Returns s with n instances of string pad to the left.
            {
                FunctionValue_Host.EvaluateDelegate eval = (context, args, thisScope) => {
                    string a = (string)args[0];

                    double nd = (double)args[1];
                    int    n  = Convert.ToInt32(nd);

                    string p = (string)args[2];
                    if (0 == p.Length)
                    {
                        p = " ";
                    }

                    char c = p[0];
                    return(a.PadRight(n, c));
                };

                FunctionValue newValue = new FunctionValue_Host(IntrinsicTypeDefs.STRING, new ArgList {
                    IntrinsicTypeDefs.STRING, IntrinsicTypeDefs.NUMBER, IntrinsicTypeDefs.STRING
                }, eval, false);
                classDef.AddMemberLiteral("PadRight", newValue.valType, newValue, true);
            }

            //@ static string Replace(string str, string find, string replace)
            //   Replaces all instances of the given string with the replacement string.
            {
                FunctionValue_Host.EvaluateDelegate eval = (context, args, thisScope) => {
                    string a       = (string)args[0];
                    string find    = (string)args[1];
                    string replace = (string)args[2];

                    if (0 == find.Length)
                    {
                        context.SetRuntimeError(RuntimeErrorType.ArgumentInvalid, "Find argument to Replace() cannot be the empty string.");
                        return(null);
                    }

                    return(a.Replace(find, replace));
                };

                FunctionValue newValue = new FunctionValue_Host(IntrinsicTypeDefs.STRING, new ArgList {
                    IntrinsicTypeDefs.STRING, IntrinsicTypeDefs.STRING, IntrinsicTypeDefs.STRING
                }, eval, false);
                classDef.AddMemberLiteral("Replace", newValue.valType, newValue, true);
            }

            //@ static List<string> Split(string str, List<string> separators = null)
            //   Splits input string into a list of strings given the provided separators.
            //   If no separators are provided, uses the newline character.
            {
                FunctionValue_Host.EvaluateDelegate eval = (context, args, thisScope) => {
                    string a = (string)args[0];

                    string[] splitted;
                    if (null == args[1])
                    {
                        splitted = a.Split(_defaultSeparators, StringSplitOptions.None);
                    }
                    else
                    {
                        PebbleList delimsList = args[1] as PebbleList;
                        if (0 == delimsList.list.Count)
                        {
                            context.SetRuntimeError(RuntimeErrorType.ArgumentInvalid, "String::Split : Separators list cannot be empty.");
                            return(null);
                        }

                        List <string> dlist = delimsList.GetNativeList();

                        // Usually I like to wrap native functions with a try-catch but I couldn't find a
                        // way to make this throw an exception.
                        splitted = a.Split(dlist.ToArray(), StringSplitOptions.None);
                    }

                    PebbleList list = PebbleList.AllocateListString(context, "String::Split result");
                    foreach (string s in splitted)
                    {
                        list.list.Add(new Variable(null, IntrinsicTypeDefs.STRING, s));
                    }
                    return(list);
                };

                List <Expr_Literal> defaults = new List <Expr_Literal>();
                defaults.Add(null);
                defaults.Add(new Expr_Literal(null, null, IntrinsicTypeDefs.NULL));
                FunctionValue newValue = new FunctionValue_Host(IntrinsicTypeDefs.LIST_STRING, new ArgList {
                    IntrinsicTypeDefs.STRING, IntrinsicTypeDefs.LIST_STRING
                }, eval, false, null, true, defaults);
                classDef.AddMemberLiteral("Split", newValue.valType, newValue, true);
            }

            //@ static bool StartsWith(string s, string start)
            //   Returns true if s starts with start.
            {
                FunctionValue_Host.EvaluateDelegate eval = (context, args, thisScope) => {
                    string a = (string)args[0];
                    string b = (string)args[1];
                    return(a.StartsWith(b));
                };

                FunctionValue newValue = new FunctionValue_Host(IntrinsicTypeDefs.BOOL, new ArgList {
                    IntrinsicTypeDefs.STRING, IntrinsicTypeDefs.STRING
                }, eval, false);
                classDef.AddMemberLiteral("StartsWith", newValue.valType, newValue, true);
            }

            //@ static string Substring(string, startIx, length)
            //   Returns a substring of the input, starting at startIx, that is length characters long.
            {
                FunctionValue_Host.EvaluateDelegate eval = (context, args, thisScope) => {
                    string a     = (string)args[0];
                    double b     = (double)args[1];
                    double c     = (double)args[2];
                    int    start = Convert.ToInt32(b);
                    int    len   = Convert.ToInt32(c);
                    if (start < 0 || len < 0)
                    {
                        context.SetRuntimeError(RuntimeErrorType.ArgumentInvalid, "Numeric arguments to Substring cannot be negative.");
                        return(null);
                    }
                    if (start + len > a.Length)
                    {
                        context.SetRuntimeError(RuntimeErrorType.ArgumentInvalid, "Substring attempting to read past end string.");
                        return(null);
                    }

                    return(a.Substring(start, len));
                };

                FunctionValue newValue = new FunctionValue_Host(IntrinsicTypeDefs.STRING, new ArgList {
                    IntrinsicTypeDefs.STRING, IntrinsicTypeDefs.NUMBER, IntrinsicTypeDefs.NUMBER
                }, eval, false);
                classDef.AddMemberLiteral("Substring", newValue.valType, newValue, true);
            }

            //@ static string SubstringLeft(string str, num length)
            //   Returns the left 'length' characters of str.
            {
                FunctionValue_Host.EvaluateDelegate eval = (context, args, thisScope) => {
                    string a   = (string)args[0];
                    double b   = (double)args[1];
                    int    len = Convert.ToInt32(b);
                    if (len < 0)
                    {
                        context.SetRuntimeError(RuntimeErrorType.ArgumentInvalid, "Numeric arguments to Substring cannot be negative.");
                        return(null);
                    }
                    if (len > a.Length)
                    {
                        context.SetRuntimeError(RuntimeErrorType.ArgumentInvalid, "Substring attempting to read past end string.");
                        return(null);
                    }

                    return(a.Substring(0, len));
                };

                FunctionValue newValue = new FunctionValue_Host(IntrinsicTypeDefs.STRING, new ArgList {
                    IntrinsicTypeDefs.STRING, IntrinsicTypeDefs.NUMBER
                }, eval, false);
                classDef.AddMemberLiteral("SubstringLeft", newValue.valType, newValue, true);
            }

            //@ static string SubstringRight(string, start)
            //   Returns the right part of the string starting at 'start'.
            {
                FunctionValue_Host.EvaluateDelegate eval = (context, args, thisScope) => {
                    string a     = (string)args[0];
                    double b     = (double)args[1];
                    int    start = Convert.ToInt32(b);
                    if (start < 0)
                    {
                        context.SetRuntimeError(RuntimeErrorType.ArgumentInvalid, "Numeric arguments to Substring cannot be negative.");
                        return(null);
                    }
                    if (start >= a.Length)
                    {
                        context.SetRuntimeError(RuntimeErrorType.ArgumentInvalid, "Substring attempting to read past end string.");
                        return(null);
                    }

                    return(a.Substring(a.Length - start));
                };

                FunctionValue newValue = new FunctionValue_Host(IntrinsicTypeDefs.STRING, new ArgList {
                    IntrinsicTypeDefs.STRING, IntrinsicTypeDefs.NUMBER
                }, eval, false);
                classDef.AddMemberLiteral("SubstringRight", newValue.valType, newValue, true);
            }

            //@ static string ToLower(string)
            //   Converts the string to lowercase.
            {
                FunctionValue_Host.EvaluateDelegate eval = (context, args, thisScope) => {
                    string a = (string)args[0];
                    return(a.ToLower());
                };

                FunctionValue newValue = new FunctionValue_Host(IntrinsicTypeDefs.STRING, new ArgList {
                    IntrinsicTypeDefs.STRING
                }, eval, false);
                classDef.AddMemberLiteral("ToLower", newValue.valType, newValue, true);
            }

            //@ static string ToUpper(string)
            //   Converts the string to uppercase.
            {
                FunctionValue_Host.EvaluateDelegate eval = (context, args, thisScope) => {
                    string a = (string)args[0];
                    return(a.ToUpper());
                };

                FunctionValue newValue = new FunctionValue_Host(IntrinsicTypeDefs.STRING, new ArgList {
                    IntrinsicTypeDefs.STRING
                }, eval, false);
                classDef.AddMemberLiteral("ToUpper", newValue.valType, newValue, true);
            }

            //@ static string Trim(string)
            //   Removes leading and trailing whitespace characters.
            {
                FunctionValue_Host.EvaluateDelegate eval = (context, args, thisScope) => {
                    string a = (string)args[0];
                    return(a.Trim());
                };

                FunctionValue newValue = new FunctionValue_Host(IntrinsicTypeDefs.STRING, new ArgList {
                    IntrinsicTypeDefs.STRING
                }, eval, false);
                classDef.AddMemberLiteral("Trim", newValue.valType, newValue, true);
            }

            //@ static string UnicodeToString(List<num>)
            //   Takes a list of numeric Unicode character codes, converts them to characters, concatenates them, and returns the resultant string.
            {
                FunctionValue_Host.EvaluateDelegate eval = (context, args, thisScope) => {
                    PebbleList list   = args[0] as PebbleList;
                    string     result = "";
                    try {
                        foreach (Variable v in list.list)
                        {
                            double d = (double)v.value;
                            result += Convert.ToChar(Convert.ToInt32(d));
                        }
                    } catch (Exception e) {
                        context.SetRuntimeError(RuntimeErrorType.NativeException, e.ToString());
                        return(null);
                    }

                    return(result);
                };

                FunctionValue newValue = new FunctionValue_Host(IntrinsicTypeDefs.STRING, new ArgList {
                    IntrinsicTypeDefs.LIST_NUMBER
                }, eval, false);
                classDef.AddMemberLiteral("UnicodeToString", newValue.valType, newValue, true);
            }

            classDef.FinalizeClass(engine.defaultContext);

            UnitTests.testFuncDelegates.Add("StringLib", RunTests);
        }
Beispiel #7
0
        public static void Register(Engine engine)
        {
            //@ class Dictionary<K, V>
            TypeDef_Class ourType = TypeFactory.GetTypeDef_Class("Dictionary", new ArgList {
                IntrinsicTypeDefs.TEMPLATE_0, IntrinsicTypeDefs.TEMPLATE_1
            }, false);

            ClassDef classDef = engine.defaultContext.CreateClass("Dictionary", ourType, null, new List <string> {
                "K", "V"
            });

            classDef.childAllocator = () => {
                return(new PebbleDictionary());
            };
            classDef.Initialize();

            //@ Dictionary<K, V> Add(K key, V value)
            //  Adds a new element to the dictionary.
            //   Cannot be used in a foreach loop.
            {
                FunctionValue_Host.EvaluateDelegate eval = (context, args, thisScope) => {
                    object key   = args[0];
                    object value = args[1];

                    PebbleDictionary scope = thisScope as PebbleDictionary;
                    if (scope.enumeratingCount > 0)
                    {
                        context.SetRuntimeError(RuntimeErrorType.ForeachModifyingContainer, "Add: Attempt to modify a dictionary that is being enumerated by a foreach loop.");
                        return(null);
                    }

                    var dictionary     = scope.dictionary;
                    var dictionaryType = (TypeDef_Class)scope.classDef.typeDef;
                    var valueType      = dictionaryType.genericTypes[1];
                    if (dictionary.ContainsKey(key))
                    {
                        context.SetRuntimeError(RuntimeErrorType.KeyAlreadyExists, "Dictionary already contains key '" + key + "'.");
                        return(null);
                    }

                    dictionary.Add(key, new Variable(null, valueType, value));

                    return(thisScope);
                };

                FunctionValue_Host newValue = new FunctionValue_Host(ourType, new ArgList {
                    IntrinsicTypeDefs.TEMPLATE_0, IntrinsicTypeDefs.TEMPLATE_1
                }, eval, false, ourType);
                classDef.AddMemberLiteral("Add", newValue.valType, newValue);
            }

            //@ Dictionary<K, V> Clear()
            //  Removes all elements from the dictionary.
            //   Cannot be used in a foreach loop.
            {
                FunctionValue_Host.EvaluateDelegate eval = (context, args, thisScope) => {
                    PebbleDictionary pebDict = thisScope as PebbleDictionary;
                    var dictionary           = pebDict.dictionary;
                    if (pebDict.enumeratingCount > 0)
                    {
                        context.SetRuntimeError(RuntimeErrorType.ForeachModifyingContainer, "Clear: Attempt to modify a dictionary that is being enumerated by a foreach loop.");
                        return(null);
                    }

                    dictionary.Clear();
                    return(thisScope);
                };

                FunctionValue_Host newValue = new FunctionValue_Host(ourType, new ArgList {
                }, eval, false, ourType);
                classDef.AddMemberLiteral("Clear", newValue.valType, newValue);
            }

            //@ bool ContainsKey(K)
            //  Returns true iff the dictionary contains an element with the given key.
            {
                FunctionValue_Host.EvaluateDelegate eval = (context, args, thisScope) => {
                    object key = args[0];

                    PebbleDictionary pebDict = thisScope as PebbleDictionary;
                    var dictionary           = pebDict.dictionary;

                    return(dictionary.ContainsKey(key));
                };

                FunctionValue_Host newValue = new FunctionValue_Host(IntrinsicTypeDefs.BOOL, new ArgList {
                    IntrinsicTypeDefs.TEMPLATE_0
                }, eval, false, ourType);
                classDef.AddMemberLiteral("ContainsKey", newValue.valType, newValue);
            }

            //@ num Count()
            //  Returns number of elements in the dictionary.
            {
                FunctionValue_Host.EvaluateDelegate eval = (context, args, thisScope) => {
                    var dictionary = (thisScope as PebbleDictionary).dictionary;
                    return(System.Convert.ToDouble(dictionary.Count));
                };

                FunctionValue_Host newValue = new FunctionValue_Host(IntrinsicTypeDefs.NUMBER, new ArgList {
                }, eval, false, ourType);
                classDef.AddMemberLiteral("Count", newValue.valType, newValue);
            }

            //@ V Get(K)
            //  Returns the value of the element with the given key.
            {
                FunctionValue_Host.EvaluateDelegate eval = (context, args, thisScope) => {
                    object key = args[0];

                    PebbleDictionary pebDict = thisScope as PebbleDictionary;

                    // Bounds checking.
                    var dictionary = pebDict.dictionary;
                    if (!dictionary.ContainsKey(key))
                    {
                        context.SetRuntimeError(RuntimeErrorType.KeyNotFound, "Get: Key '" + key + "' not in dictionary.");
                        return(null);
                    }

                    return(dictionary[key].value);
                };

                FunctionValue_Host newValue = new FunctionValue_Host(IntrinsicTypeDefs.TEMPLATE_1, new ArgList {
                    IntrinsicTypeDefs.TEMPLATE_0
                }, eval, false, ourType);
                classDef.AddMemberLiteral("Get", newValue.valType, newValue);
            }

            //@ Dictionary<K, V> Remove(K key)
            //   Removes element with given key.
            //   Cannot be used in a foreach loop.
            {
                FunctionValue_Host.EvaluateDelegate eval = (context, args, thisScope) => {
                    object key = args[0];

                    PebbleDictionary pebDict = thisScope as PebbleDictionary;
                    var dictionary           = pebDict.dictionary;
                    if (pebDict.enumeratingCount > 0)
                    {
                        context.SetRuntimeError(RuntimeErrorType.ForeachModifyingContainer, "Remove: Attempt to modify a dictionary that is being enumerated by a foreach loop.");
                        return(null);
                    }

                    if (!dictionary.ContainsKey(key))
                    {
                        context.SetRuntimeError(RuntimeErrorType.KeyNotFound, "Remove: Key '" + key + "' not in dictionary.");
                        return(null);
                    }

                    dictionary.Remove(key);
                    return(thisScope);
                };

                FunctionValue_Host newValue = new FunctionValue_Host(ourType, new ArgList {
                    IntrinsicTypeDefs.TEMPLATE_0
                }, eval, false, ourType);
                classDef.AddMemberLiteral("Remove", newValue.valType, newValue);
            }

            //@ Dictionary<K, V> Set(K key, V newValue)
            //   Replaces value of existing element with the given key.
            {
                FunctionValue_Host.EvaluateDelegate eval = (context, args, thisScope) => {
                    object key   = args[0];
                    object value = args[1];

                    var dictionary = (thisScope as PebbleDictionary).dictionary;

                    // Bounds checking.
                    if (!dictionary.ContainsKey(key))
                    {
                        context.SetRuntimeError(RuntimeErrorType.KeyNotFound, "Get: Key '" + key + "' not in dictionary.");
                        return(null);
                    }

                    dictionary[key].value = value;

                    return(thisScope);
                };

                FunctionValue_Host newValue = new FunctionValue_Host(ourType, new ArgList {
                    IntrinsicTypeDefs.TEMPLATE_0, IntrinsicTypeDefs.TEMPLATE_1
                }, eval, false, ourType);
                classDef.AddMemberLiteral("Set", newValue.valType, newValue);
            }

            //@ string ThisToScript(string prefix)
            //   ThisToScript is used by Serialize. A classes' ThisToScript function should return code which can rebuild the class.
            //   Note that it's only the content of the class, not the "new A" part. ie., it's the code that goes in the defstructor.
            {
                FunctionValue_Host.EvaluateDelegate eval = (context, args, thisScope) => {
                    string result = "";
                    string prefix = (string)args[0] + "\t";

                    var dictionary = (thisScope as PebbleDictionary).dictionary;
                    //bool first = true;
                    foreach (KeyValuePair <object, Variable> kvp in dictionary)
                    {
                        result += prefix + "Add(" + CoreLib.ValueToScript(context, kvp.Key, prefix + "\t", false) + ", " + CoreLib.ValueToScript(context, kvp.Value.value, prefix + "\t", false) + ");\n";
                    }

                    return(result);
                };

                FunctionValue_Host newValue = new FunctionValue_Host(IntrinsicTypeDefs.STRING, new ArgList {
                    IntrinsicTypeDefs.STRING
                }, eval, false, ourType);
                classDef.AddMemberLiteral("ThisToScript", newValue.valType, newValue);
            }

            //@ string ToString()
            //   Returns a human readable version of at least the first few elements of the dictionary.
            {
                FunctionValue_Host.EvaluateDelegate eval = (context, args, thisScope) => {
                    var dictionary = (thisScope as PebbleDictionary).dictionary;

                    string result = "Dictionary(" + dictionary.Count + ")[";
                    int    count  = 0;
                    foreach (KeyValuePair <object, Variable> kvp in dictionary)
                    {
                        if (count != 0)
                        {
                            result += ", ";
                        }
                        result += "(" + CoreLib.ValueToString(context, kvp.Key, true) + ", " + CoreLib.ValueToString(context, kvp.Value.value, true) + ")";

                        if (++count >= 4)
                        {
                            break;
                        }
                    }
                    if (dictionary.Count > 4)
                    {
                        result += ", ...";
                    }
                    return(result + "]");
                };

                FunctionValue_Host newValue = new FunctionValue_Host(IntrinsicTypeDefs.STRING, new ArgList {
                }, eval, false, ourType);
                classDef.AddMemberLiteral("ThisToString", newValue.valType, newValue);
            }

            bool error = false;

            classDef.FinalizeClass(engine.defaultContext);
            Pb.Assert(!error);

            UnitTests.testFuncDelegates.Add("CoreDictionary", RunTests);
        }
Beispiel #8
0
            public bool Write(ExecContext context, PebbleStreamHelper stream, object value)
            {
                Pb.Assert(!(value is Variable));

                if (null != textWriter)
                {
                    string s = CoreLib.ValueToString(context, value, false);
                    textWriter.Write(s);
                    return(true);
                }

                if (null == value)
                {
                    writer.Write("null");
                }
                else if (value is FunctionValue)
                {
                    context.SetRuntimeError(RuntimeErrorType.SerializeUnknownType, "Cannot serialize functions.");
                    return(false);
                }
                else if (value is bool)
                {
                    writer.Write((bool)value);
                }
                else if (value is double)
                {
                    writer.Write((double)value);
                }
                else if (value is string)
                {
                    writer.Write((string)value);
                }
                else if (value is PebbleList)
                {
                    PebbleList plist = value as PebbleList;
                    // - Serialize full type, ie "List<string>".
                    writer.Write(plist.classDef.name);
                    // - Serialize count.
                    writer.Write(plist.list.Count);
                    // - Finally, serialize each object.
                    foreach (Variable listvar in plist.list)
                    {
                        if (!Write(context, stream, listvar.value))
                        {
                            return(false);
                        }
                    }
                }
                else if (value is PebbleDictionary)
                {
                    PebbleDictionary dic = value as PebbleDictionary;
                    // - class name
                    writer.Write(dic.classDef.name);
                    // - count
                    writer.Write((Int32)dic.dictionary.Count);
                    // - each key, value
                    foreach (var kvp in dic.dictionary)
                    {
                        if (!Write(context, stream, kvp.Key))
                        {
                            return(false);
                        }
                        if (!Write(context, stream, kvp.Value.value))
                        {
                            return(false);
                        }
                    }
                }
                else if (value is ClassValue_Enum)
                {
                    ClassValue_Enum enumVal = value as ClassValue_Enum;
                    writer.Write(enumVal.classDef.name);
                    writer.Write(enumVal.GetName());
                }
                else if (value is ClassValue)
                {
                    ClassValue classVal  = value as ClassValue;
                    MemberRef  serMemRef = classVal.classDef.GetMemberRef(null, "Serialize", ClassDef.SEARCH.NORMAL);
                    if (serMemRef.isInvalid)
                    {
                        context.SetRuntimeError(RuntimeErrorType.SerializeInvalidClass, "Class '" + classVal.classDef.name + "' cannot be serialized because it doesn't implement a serialization function.");
                        return(false);
                    }

                    writer.Write(classVal.classDef.name);

                    Variable      serVar  = classVal.Get(serMemRef);
                    FunctionValue serFunc = serVar.value as FunctionValue;
                    object        result  = serFunc.Evaluate(context, new List <object> {
                        stream
                    }, classVal);
                    if (context.IsRuntimeErrorSet())
                    {
                        return(false);
                    }
                    if (result is bool && false == (bool)result)
                    {
                        context.SetRuntimeError(RuntimeErrorType.SerializeFailed, "Serialize function of class '" + classVal.classDef.name + "' returned false.");
                        return(false);
                    }
                }
                else
                {
                    throw new Exception("Internal error: Unexpected type of value in stream Write.");
                }

                return(true);
            }