Exemple #1
0
        public static MondValue GetEnumerator([MondInstance] MondValue instance)
        {
            EnsureObject("getEnumerator", instance);

            var enumerator = MondValue.Object();
            var keys       = instance.ObjectValue.Values.Keys.ToList();
            var i          = 0;

            enumerator["current"]  = MondValue.Undefined;
            enumerator["moveNext"] = MondValue.Function((_, args) =>
            {
                if (i >= keys.Count)
                {
                    return(false);
                }

                var pair      = MondValue.Object();
                pair["key"]   = keys[i];
                pair["value"] = instance.ObjectValue.Values[keys[i]];

                enumerator["current"] = pair;
                i++;
                return(true);
            });

            enumerator["dispose"] = new MondFunction((_, args) => MondValue.Undefined);

            return(enumerator);
        }
Exemple #2
0
        public MondCodeRunner RegisterFunction(Delegate f, string alias)
        {
            State[alias] = MondValue.Function((_, args) =>
            {
                f.DynamicInvoke(args.Select(val => val.UserData));
                return(MondValue.Undefined);
            });

            return(this);
        }
Exemple #3
0
        private static MondValue CopyToObject(Dictionary <string, MondInstanceFunction> functions, MondState state)
        {
            var obj = MondValue.Object(state);

            obj.Prototype = MondValue.Null;

            foreach (var func in functions)
            {
                obj[func.Key] = MondValue.Function(func.Value);
            }

            obj.Prototype = ValuePrototype.Value;
            return(obj);
        }
Exemple #4
0
        public void WrappedInstanceFunction()
        {
            var obj = MondValue.Object();

            var func = MondValue.Function((state, instance, args) => MondValue.Undefined);

            Assert.True(func.FunctionValue.Type == ClosureType.InstanceNative);

            obj["test"] = func;
            var closure = obj["test"];

            Assert.True(closure.FunctionValue.Type == ClosureType.Native);

            Assert.True(new MondState().Call(obj["test"]) == MondValue.Undefined);
        }
Exemple #5
0
        public void NativeTransitions(string testName, bool hasNativeTransition)
        {
            var state = new MondState();

            state["runtimeEx"] = MondValue.Function((_, args) => { throw new MondRuntimeException("runtime"); });
            state["genericEx"] = MondValue.Function((_, args) => { throw new Exception("generic"); });
            state["call"]      = MondValue.Function((_, args) => state.Call(args[0]));

            const string programTemplate = @"
                return {{
                    runtime: () -> global.runtimeEx(),
                    generic: () -> global.genericEx(),
                    indirect: () -> global.call(() -> global.runtimeEx())
                }}.{0}();
            ";

            var program   = string.Format(programTemplate, testName);
            var exception = Assert.Throws <MondRuntimeException>(() => state.Run(program));

            Assert.AreEqual(hasNativeTransition, exception.ToString().Contains("[... native ...]"), testName);
        }
Exemple #6
0
        public static MondValue GetEnumerator([MondInstance] MondValue instance)
        {
            var enumerator = MondValue.Object();
            var str        = (string)instance;
            var i          = 0;

            enumerator["current"]  = MondValue.Undefined;
            enumerator["moveNext"] = MondValue.Function((_, args) =>
            {
                if (i >= str.Length)
                {
                    return(false);
                }

                enumerator["current"] = new string(str[i++], 1);
                return(true);
            });

            enumerator["dispose"] = new MondFunction((_, args) => MondValue.Undefined);

            return(enumerator);
        }
Exemple #7
0
        public static MondValue GetEnumerator([MondInstance] MondValue instance)
        {
            EnsureArray("getEnumerator", instance);

            var enumerator = MondValue.Object();
            var i          = 0;

            enumerator["current"]  = MondValue.Undefined;
            enumerator["moveNext"] = MondValue.Function((_, args) =>
            {
                if (i >= instance.ArrayValue.Count)
                {
                    return(false);
                }

                enumerator["current"] = instance.ArrayValue[i++];
                return(true);
            });

            enumerator["dispose"] = new MondFunction((_, args) => MondValue.Undefined);

            return(enumerator);
        }
Exemple #8
0
        public void ImplicitBool()
        {
            var value = MondValue.Undefined;

            Assert.False(value);

            value = MondValue.Null;
            Assert.False(value);

            value = MondValue.False;
            Assert.False(value);

            value = MondValue.True;
            Assert.True(value);

            value = 0;
            Assert.True(value);

            value = 1;
            Assert.True(value);

            value = double.NaN;
            Assert.False(value);

            value = "hello";
            Assert.True(value);

            value = MondValue.Object();
            Assert.True(value);

            value = MondValue.Array();
            Assert.True(value);

            value = MondValue.Function((state, arguments) => MondValue.Undefined);
            Assert.True(value);
        }
Exemple #9
0
        public RunResult Run(string source)
        {
            _outputBuffer.Clear();

            var output = new LimitedTextWriter(new StringWriter(_outputBuffer), MaxOutputChars, MaxOutputLines);

            try
            {
                using (_connection = Database.CreateConnection())
                {
                    _transaction = _connection.BeginTransaction();

                    _state = new MondState
                    {
                        Options = new MondCompilerOptions
                        {
                            DebugInfo          = MondDebugInfoLevel.StackTrace,
                            UseImplicitGlobals = true,
                        },
                        Libraries = new MondLibraryManager
                        {
                            new ModifiedCoreLibraries(),
                            new ConsoleOutputLibraries(),
                            new ModifiedJsonLibraries(),
                            new HttpLibraries(),
                            new ImageLibraries(),
                            new RegexLibraries(),
                            new DateTimeLibraries(),
                            new AsyncLibraries(),
                        }
                    };

                    // eagerly initialize module cache (so it doesn't try to load from DB)
                    var moduleCache = MondValue.Object(_state);
                    moduleCache.Prototype = MondValue.Null;
                    _state["__modules"]   = moduleCache;

                    var searchDir = Path.Combine(Environment.CurrentDirectory, "Modules");

                    var requireWhitelist = new HashSet <string>
                    {
                        "Seq.mnd",
                        "Seq.Scalar.mnd",
                        "Seq.Sorting.mnd",
                    };

                    _state.Libraries.Configure(libs =>
                    {
                        var require = libs.Get <RequireLibrary>();
                        if (require != null)
                        {
                            require.Options            = _state.Options;
                            require.SearchBesideScript = false;
                            require.Resolver           = (name, directories) =>
                            {
                                string foundModule = null;

                                if (requireWhitelist.Contains(name))
                                {
                                    var modulePath = Path.Combine(searchDir, name);
                                    if (File.Exists(modulePath))
                                    {
                                        foundModule = modulePath;
                                    }
                                }

                                if (foundModule == null)
                                {
                                    throw new MondRuntimeException("require: module could not be found: {0}", name);
                                }

                                return(foundModule);
                            };
                        }

                        var consoleOut = libs.Get <ConsoleOutputLibrary>();
                        consoleOut.Out = output;
                    });

                    _state.EnsureLibrariesLoaded();

                    var global = _state.Run("return global;");
                    global.Prototype = MondValue.Null;

                    _variableCache    = new Dictionary <string, CacheEntry>();
                    _loadingVariables = new HashSet <string>();

                    var ops = MondValue.Object(_state);
                    ops["__get"]    = MondValue.Function(VariableGetterOldOperator);
                    _state["__ops"] = ops;

                    _state["__get"] = MondValue.Function(VariableGetter);
                    _state["__set"] = MondValue.Function(VariableSetter);

                    var program = source;

                    GC.Collect();

                    var result = _state.Run(program, "mondbox");

                    if (result != MondValue.Undefined)
                    {
                        output.WriteLine();

                        if (result["moveNext"])
                        {
                            output.WriteLine("sequence (15 max):");
                            foreach (var i in result.Enumerate(_state).Take(15))
                            {
                                output.WriteLine(i.Serialize());
                            }
                        }
                        else
                        {
                            output.WriteLine(result.Serialize());
                        }
                    }

                    SaveChanges(output);

                    _transaction.Commit();
                }
            }
            catch (OutOfMemoryException)
            {
                throw;
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                output.WriteLine(e.Message);
            }

            return(new RunResult(_outputBuffer.ToString(), ImageModule.GetImageData()));
        }