示例#1
0
        public void Register(MondState state, MondValue function)
        {
            if (function.Type != MondValueType.Function)
                throw new MondRuntimeException("register: first argument must be a function");

            CancellationToken.Register(() => state.Call(function));
        }
示例#2
0
        private static MondValue Length(MondState state, MondValue instance, params MondValue[] arguments)
        {
            if (instance.Type != MondValueType.Array)
                throw new MondRuntimeException("Array.length must be called on a String");

            return instance.ArrayValue.Count;
        }
示例#3
0
 public IEnumerable<IMondLibrary> Create(MondState state)
 {
     yield return new ErrorLibrary();
     yield return new RequireLibrary();
     yield return new CharLibrary();
     yield return new MathLibrary();
     yield return new RandomLibrary();
 }
        public MondValue Get( MondState state, MondValue instance, string name )
        {
            var newPath = _path + "." + name;

            var type = InteropLibrary.LookupType( newPath );
            if( type != null )
                return MondObjectBinder.Bind( type, state, MondBindingOptions.AutoLock );

            return new NamespaceReference( newPath ).ToMond( state );
        }
示例#5
0
        public IEnumerable<IMondLibrary> Create(MondState state)
        {
            var libraries = new IMondLibraryCollection[]
            {
                new ConsoleOutputLibraries(),
                new ConsoleInputLibraries()
            };

            return libraries.SelectMany(l => l.Create(state));
        }
示例#6
0
        public MondValue Get( MondState state, MondValue instance, string name )
        {
            var typeName = this.Type.FullName + "+" + name;

            var type = InteropLibrary.LookupType( typeName );
            if( type == null )
                throw new Exception( "Could not find type: " + typeName );

            return MondObjectBinder.Bind( type, state, MondBindingOptions.AutoLock );
        }
示例#7
0
文件: Machine.cs 项目: krixalis/Mond
        public Machine(MondState state)
        {
            _state = state;
            _programs = new List<MondProgram>();

            _callStack = new Stack<ReturnAddress>();
            _localStack = new Stack<Frame>();
            _evalStack = new Stack<MondValue>();

            Global = new MondValue(MondValueType.Object);
        }
        public MondValue Call( MondState state, MondValue instance, params MondValue[] args )
        {
            var types = InteropLibrary.GetTypeArray( args );

            var typeName = _path + "`" + types.Length;
            var type = InteropLibrary.LookupType( typeName );
            if( type == null )
                throw new Exception( "Could not find type: " + typeName );

            var boundType = type.MakeGenericType( types );
            return MondObjectBinder.Bind( boundType, state, MondBindingOptions.AutoLock );
        }
示例#9
0
        public void NativeFunction()
        {
            var state = new MondState();

            state["function"] = new MondFunction((_, args) => args[0]);

            var result = state.Run(@"
                return global.function('arg');
            ");

            Assert.True(result == "arg");
        }
        public MondValue ToMond( MondState state )
        {
            MondValue prototype;
            MondClassBinder.Bind<NamespaceReference>( out prototype, state );

            var obj = new MondValue( state );
            obj.UserData = this;
            obj.Prototype = prototype;
            obj.Lock();

            return obj;
        }
示例#11
0
        public void NativeInstanceFunction()
        {
            var state = new MondState();

            state["value"] = 123;
            state["function"] = new MondInstanceFunction((_, instance, arguments) => instance[arguments[0]]);

            var result = state.Run(@"
                return global.function('value');
            ");

            Assert.True(result == 123);
        }
示例#12
0
        public Machine(MondState state)
            : this()
        {
            _state = state;
            Global = new MondValue(state);
            Global["__ops"] = new MondValue(state);

            _debugAction = MondDebugAction.Run;
            _debugSkip = false;
            _debugAlign = false;
            _debugDepth = 0;
            Debugger = null;
        }
示例#13
0
        public IEnumerable<IMondLibrary> Create(MondState state)
        {
            var libraries = new IMondLibraryCollection[]
            {
                new CoreLibraries(),
                new ConsoleLibraries(),
                new JsonLibraries(),
            #if !UNITY
                new AsyncLibraries(),
            #endif
            };

            return libraries.SelectMany(l => l.Create(state));
        }
示例#14
0
        static void InteractiveMain(string[] args)
        {
            var useColoredInput = args.Any(s => s == "-c");

            if (useColoredInput)
            {
                _readLine = () => Highlighted.ReadLine(ref _highlighter);

                Console.CancelKeyPress += (sender, eventArgs) => Console.ResetColor();
            }
            else
            {
                _readLine = Console.ReadLine;
            }

            _input = new Queue<char>();
            _first = true;

            var libraries = new MondLibraryManager
            {
                new StandardLibraries()
            };

            var state = new MondState();
            var options = new MondCompilerOptions
            {
                MakeRootDeclarationsGlobal = true,
                UseImplicitGlobals = true
            };

            libraries.Load(state);

            while (true)
            {
                try
                {
                    options.FirstLineNumber = _line + 1;

                    foreach (var program in MondProgram.CompileStatements(ConsoleInput(), "stdin", options))
                    {
                        InteractiveRun(state, program);
                    }
                }
                catch (Exception e)
                {
                    PrintException(e);
                }
            }
        }
示例#15
0
        public MondValue Call( MondState state, MondValue instance, params MondValue[] args )
        {
            if( this.Type.IsGenericType && !this.Type.ContainsGenericParameters )
                throw new Exception( "Generic type is already bound: " + this.Type.FullName );

            var types = InteropLibrary.GetTypeArray( args );

            var typeName = this.Type.FullName + "`" + types.Length;
            var type = InteropLibrary.LookupType( typeName );
            if( type == null )
                throw new Exception( "Could not find type: " + typeName );

            var boundType = type.MakeGenericType( types );
            return MondObjectBinder.Bind( boundType, state, MondBindingOptions.AutoLock );
        }
示例#16
0
        internal MondDebugContext(
            MondState state, MondProgram program, int address,
            Frame locals, Frame args,
            ReturnAddress[] callStack,  int callStackTop, int callStackBottom)
        {
            _state = state;
            _address = address;
            _locals = locals;
            _args = args;

            Program = program;
            DebugInfo = program.DebugInfo;

            CallStack = GenerateCallStack(address, callStack, callStackTop, callStackBottom).AsReadOnly();

            _localObject = CreateLocalObject();
        }
示例#17
0
        public static MondValue Try(MondState state, MondValue function, params MondValue[] arguments)
        {
            if (function.Type != MondValueType.Function)
                throw new MondRuntimeException("try: first argument must be a function");

            var obj = new MondValue(MondValueType.Object);

            try
            {
                var result = state.Call(function, arguments);
                obj["result"] = result;
            }
            catch (Exception e)
            {
                obj["error"] = e.Message;
            }

            return obj;
        }
示例#18
0
        public void Call()
        {
            // __call

            var state = new MondState();
            var result = state.Run(@"
                var obj = {
                    __call: fun (this, x, y) {
                        return x + y;
                    }
                };

                global.obj = obj;

                return obj(1, 3) + obj(...[1, 3]);
            ");

            Assert.True(result == 8);

            Assert.True(state.Call(state["obj"], 1, 3) == 4);
        }
示例#19
0
 /// <summary>
 /// containsValue(value): bool
 /// </summary>
 private static MondValue ContainsValue(MondState state, MondValue instance, params MondValue[] arguments)
 {
     Check("containsValue", instance.Type, arguments, MondValueType.Undefined);
     return(instance.ObjectValue.Values.ContainsValue(arguments[0]));
 }
示例#20
0
        private static MondValue CopyToObject(Dictionary <string, MondFunction> functions, MondState state)
        {
            var obj = MondValue.Object(state);

            obj.Prototype = MondValue.Null;

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

            obj.Prototype = ValuePrototype.Value;
            return(obj);
        }
示例#21
0
 /// <summary>
 /// Generates module bindings for T. Returns an object containing the bound methods.
 /// </summary>
 /// <param name="state">Optional state to bind to. Only required if you plan on using metamethods.</param>
 public static MondValue Bind <T>(MondState state)
 {
     return(Bind(typeof(T), state));
 }
示例#22
0
        public static object[] MarshalToClr( MondValue[] values, Type[] expectedTypes, MondState state )
        {
            if( !MatchTypes( values, expectedTypes ) )
                throw new ArgumentException( "Given values do not match expected types", "values" );

            return values.Zip( expectedTypes, ( a, b ) => new { Value = a, ExpectedType = b } ).Select( x => MarshalToClr( x.Value, x.ExpectedType, state ) ).ToArray();
        }
示例#23
0
 /// <summary>
 /// lastIndexOf(item): number
 /// </summary>
 private static MondValue LastIndexOf(MondState state, MondValue instance, params MondValue[] arguments)
 {
     Check("lastIndexOf", instance.Type, arguments, MondValueType.Undefined);
     return(instance.ArrayValue.LastIndexOf(arguments[0]));
 }
示例#24
0
            public static double SumOrDouble(MondState state, MondValue range)
            {
                if (range.Type == MondValueType.Number)
                    return range * 2d;

                return range.Enumerate(state).Sum(n => (double)n);
            }
示例#25
0
        public void Slice()
        {
            var arr = new MondValue(MondValueType.Array);
            arr.ArrayValue.AddRange(new MondValue[] { 1, 2, 3, 4, 5 });

            var state = new MondState();
            state["arr"] = arr;

            Assert.True(state.Run("return global.arr[:];").Enumerate(state).SequenceEqual(new MondValue[] { 1, 2, 3, 4, 5 }), "no values");

            Assert.True(state.Run("return global.arr[3:];").Enumerate(state).SequenceEqual(new MondValue[] { 4, 5 }), "just start");

            Assert.True(state.Run("return global.arr[:2];").Enumerate(state).SequenceEqual(new MondValue[] { 1, 2, 3 }), "just end");

            Assert.True(state.Run("return global.arr[::-1];").Enumerate(state).SequenceEqual(new MondValue[] { 5, 4, 3, 2, 1 }), "just step");

            Assert.True(state.Run("return global.arr[1:2];").Enumerate(state).SequenceEqual(new MondValue[] { 2, 3 }));

            Assert.True(state.Run("return global.arr[0:4:2];").Enumerate(state).SequenceEqual(new MondValue[] { 1, 3, 5 }));

            Assert.Throws<MondCompilerException>(() => state.Run("return global.arr[::];"), "no values, extra colon");

            Assert.Throws<MondCompilerException>(() => state.Run("return global.arr[0:1:];"), "indices, extra colon");
        }
示例#26
0
        public IEnumerable <KeyValuePair <string, MondValue> > GetDefinitions(MondState state)
        {
            var randomModule = MondModuleBinder.Bind(typeof(BetterRandomModule), state);

            yield return(new KeyValuePair <string, MondValue>("Random", randomModule));
        }
示例#27
0
 public static MondValue Call(MondState state, MondValue self, params MondValue[] args) => state["Random"];
示例#28
0
        static void InteractiveMain()
        {
            _input = new Queue <char>();

            var state   = new MondState();
            var options = new MondCompilerOptions
            {
                GenerateDebugInfo          = true,
                MakeRootDeclarationsGlobal = true,
                UseImplicitGlobals         = true
            };

            Functions.Register(state);

            var line = 1;

            while (true)
            {
                try
                {
                    MondValue result;

                    do
                    {
                        var program = MondProgram.CompileStatement(ConsoleInput(), string.Format("stdin_{0:D}", line), options);
                        result = state.Load(program);

                        // get rid of leading whitespace
                        while (_input.Count > 0 && char.IsWhiteSpace(_input.Peek()))
                        {
                            _input.Dequeue();
                        }
                    } while (_input.Count > 0); // we only want the result of the last statement

                    line++;

                    // ignore undefined return value, it's almost always useless
                    if (result == MondValue.Undefined)
                    {
                        continue;
                    }

                    if (result["moveNext"] && result.IsEnumerable)
                    {
                        foreach (var value in result.Enumerate(state))
                        {
                            value.Serialize(Console.Out);
                            Console.WriteLine();
                        }
                    }
                    else
                    {
                        result.Serialize(Console.Out);
                        Console.WriteLine();
                    }

                    Console.WriteLine();
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.Message);
                    Console.WriteLine();

                    _input.Clear();
                }
            }
        }
示例#29
0
        public void EnableThisStackTrace(string testName, bool hasNativeTransition)
        {
            var state = new MondState();

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

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

            var program = string.Format(programTemplate, testName);
            var exception = Assert.Throws<MondRuntimeException>(() => state.Run(program));
            Assert.AreEqual(hasNativeTransition, exception.ToString().Contains("[... native ...]"), testName);
        }
示例#30
0
 public void SetUp()
 {
     _state = new MondState();
     _state["Ov"] = MondModuleBinder.Bind<OverloadedModule>();
 }
示例#31
0
        public ConsoleInputLibrary(MondState state)
        {
            _state = state;

            In = System.Console.In;
        }
示例#32
0
        public MondValue Require(MondState state, string fileName)
        {
            if (_require.Loader == null)
            {
                throw new MondRuntimeException("require: module loader is not set");
            }

            const string cacheObjectName = "__modules";

            MondValue cacheObject;

            // make sure we have somewhere to cache modules
            if (state[cacheObjectName].Type != MondValueType.Object)
            {
                cacheObject            = new MondValue(state);
                cacheObject.Prototype  = MondValue.Null;
                state[cacheObjectName] = cacheObject;
            }
            else
            {
                cacheObject = state[cacheObjectName];
            }

            // return cached module if it exists
            var cachedExports = cacheObject[fileName];

            if (cachedExports.Type == MondValueType.Object)
            {
                return(cachedExports);
            }

            // create a new object to store the exports
            var exports = new MondValue(state);

            exports.Prototype = MondValue.Null;

            // instantly cache it so we can have circular dependencies
            cacheObject[fileName] = exports;

            try
            {
                IEnumerable <string> searchDirectories =
                    _require.SearchDirectories ?? Array.Empty <string>();

                if (_require.SearchBesideScript)
                {
                    var currentDir = Path.GetDirectoryName(state.CurrentScript);
                    searchDirectories = Enumerable.Repeat(currentDir, 1)
                                        .Concat(searchDirectories);
                }

                var moduleSource = _require.Loader(fileName, searchDirectories);

                // wrap the module script in a function so we can pass out exports object to it
                var source = _require.Definitions + "return fun (exports) {\n" + moduleSource + " return exports; };";

                var options = new MondCompilerOptions
                {
                    FirstLineNumber = -1
                };

                var requireOptions = _require.Options;
                if (requireOptions != null)
                {
                    options.DebugInfo = requireOptions.DebugInfo;
                    options.MakeRootDeclarationsGlobal = requireOptions.MakeRootDeclarationsGlobal;
                    options.UseImplicitGlobals         = requireOptions.UseImplicitGlobals;
                }

                var program     = MondProgram.Compile(source, fileName, options);
                var initializer = state.Load(program);

                var result = state.Call(initializer, exports);

                if (result.Type != MondValueType.Object)
                {
                    throw new MondRuntimeException("require: module must return an object (`{0}`)", fileName);
                }

                if (!ReferenceEquals(exports, result))
                {
                    // module returned a different object, merge with ours
                    foreach (var kv in result.Object)
                    {
                        var key   = kv.Key;
                        var value = kv.Value;

                        exports[key] = value;
                    }

                    exports.Prototype = result.Prototype;

                    if (result.IsLocked)
                    {
                        exports.Lock();
                    }
                }
            }
            catch
            {
                // if something goes wrong, remove the entry from the cache
                cacheObject[fileName] = MondValue.Undefined;
                throw;
            }

            return(exports);
        }
示例#33
0
        private static object[] BuildParameterArray(
            string errorPrefix,
            MethodTable methodTable,
            MondState state,
            MondValue instance,
            MondValue[] args,
            out MethodBase methodBase,
            out ReturnConverter returnConversion)
        {
            Method method = null;

            if (args.Length < methodTable.Methods.Count)
            {
                method = FindMatch(methodTable.Methods[args.Length], args);
            }

            if (method == null)
            {
                method = FindMatch(methodTable.ParamsMethods, args);
            }

            if (method != null)
            {
                methodBase       = method.Info;
                returnConversion = method.ReturnConversion;

                var parameters = method.Parameters;
                var result     = new object[parameters.Count];

                var j = 0;
                for (var i = 0; i < result.Length; i++)
                {
                    var param = parameters[i];

                    switch (param.Type)
                    {
                    case ParameterType.Value:
                        if (j < args.Length)
                        {
                            result[i] = param.Conversion(args[j++]);
                        }
                        else
                        {
                            result[i] = param.Info.DefaultValue;
                        }
                        break;

                    case ParameterType.Params:
                        result[i] = Slice(args, method.MondParameterCount);
                        break;

                    case ParameterType.Instance:
                        result[i] = instance;
                        break;

                    case ParameterType.State:
                        result[i] = state;
                        break;

                    default:
                        throw new NotSupportedException();
                    }
                }

                return(result);
            }

            throw new MondBindingException(BindingError.ParameterTypeError(errorPrefix, methodTable));
        }
示例#34
0
 private static object[] BuildParameterArray(
     string errorPrefix,
     MethodTable methodTable,
     MondState state,
     in MondValue instance,
示例#35
0
文件: Script.cs 项目: xserve98/Mond
 public static MondValue Run(out MondState state, string source)
 {
     state = NewState();
     return(state.Run(source));
 }
示例#36
0
 public static void Add(MondValue a, MondState state, MondValue b)
 {
     state["result"] = a + b;
 }
示例#37
0
        public ConsoleOutputLibrary(MondState state)
        {
            _state = state;

            Out = System.Console.Out;
        }
示例#38
0
 public void SetUp()
 {
     _state       = new MondState();
     _state["Ov"] = MondModuleBinder.Bind <OverloadedModule>(_state);
 }
示例#39
0
        public MondValue Require(MondState state, string fileName)
        {
            if (_require.Loader == null)
                throw new MondRuntimeException("require: module loader is not set");

            const string cacheObjectName = "__modules";

            MondValue cacheObject;

            // make sure we have somewhere to cache modules
            if (state[cacheObjectName].Type != MondValueType.Object)
            {
                cacheObject = new MondValue(state);
                cacheObject.Prototype = MondValue.Null;
                state[cacheObjectName] = cacheObject;
            }
            else
            {
                cacheObject = state[cacheObjectName];
            }

            // return cached module if it exists
            var cachedExports = cacheObject[fileName];
            if (cachedExports.Type == MondValueType.Object)
                return cachedExports;

            // create a new object to store the exports
            var exports = new MondValue(state);
            exports.Prototype = MondValue.Null;

            // instantly cache it so we can have circular dependencies
            cacheObject[fileName] = exports;

            try
            {
                var searchDirectories = new[] { Path.GetDirectoryName(state.CurrentScript), "" };
                var moduleSource = _require.Loader(fileName, searchDirectories.AsReadOnly());

                // wrap the module script in a function so we can pass out exports object to it
                var source = _require.Definitions + "return fun (exports) {\n" + moduleSource + " return exports; };";

                var options = new MondCompilerOptions
                {
                    FirstLineNumber = -1
                };

                var requireOptions = _require.Options;
                if (requireOptions != null)
                {
                    options.DebugInfo = requireOptions.DebugInfo;
                    options.MakeRootDeclarationsGlobal = requireOptions.MakeRootDeclarationsGlobal;
                    options.UseImplicitGlobals = requireOptions.UseImplicitGlobals;
                }

                var program = MondProgram.Compile(source, fileName, options);
                var initializer = state.Load(program);

                var result = state.Call(initializer, exports);

                if (result.Type != MondValueType.Object)
                    throw new MondRuntimeException("require: module must return an object (`{0}`)", fileName);

                if (!ReferenceEquals(exports, result))
                {
                    // module returned a different object, merge with ours
                    foreach (var kv in result.Object)
                    {
                        var key = kv.Key;
                        var value = kv.Value;

                        exports[key] = value;
                    }

                    exports.Prototype = result.Prototype;

                    if (result.IsLocked)
                        exports.Lock();
                }
            }
            catch
            {
                // if something goes wrong, remove the entry from the cache
                cacheObject[fileName] = MondValue.Undefined;
                throw;
            }

            return exports;
        }
示例#40
0
        public IEnumerable <KeyValuePair <string, MondValue> > GetDefinitions(MondState state)
        {
            var httpModule = MondModuleBinder.Bind(typeof(HttpModule), state);

            yield return(new KeyValuePair <string, MondValue>("Http", httpModule));
        }
示例#41
0
        public static object MarshalToClr( MondValue value, Type expectedType, MondState state )
        {
            if( !MatchType( value, expectedType ) )
                throw new ArgumentException( "Given value does not match expected type", "value" );

            if( expectedType == typeof( MondValue ) )
                return value;

            switch( value.Type )
            {
                case MondValueType.False:
                case MondValueType.True:
                    return (bool)value;

                case MondValueType.Null:
                case MondValueType.Undefined:
                    return null;

                case MondValueType.String:
                    var str = value.ToString();
                    if( expectedType == typeof( char ) )
                    {
                        if( str.Length != 1 )
                            throw new ArgumentException( "Value cannot be converted to char", "value" );

                        return str[0];
                    }

                    return str;

                case MondValueType.Number:
                    if( expectedType.IsEnum )
                    {
                        var underlying = Enum.GetUnderlyingType( expectedType );
                        var rawValue = Convert.ChangeType( (double)value, underlying );
                        var valueName = Enum.GetName( expectedType, rawValue );

                        return Enum.Parse( expectedType, valueName );
                    }

                    return Convert.ChangeType( (double)value, expectedType );

                case MondValueType.Object:
                    return value.UserData;

                case MondValueType.Function:
                    Func<object[], object> shim = delegate( object[] args )
                    {
                        var result = null as MondValue;

                        if( args == null )
                            result = state.Call( value );
                        else
                        {
                            var mondTypes = ToMondTypes( args.Select( a => a.GetType() ).ToArray() );
                            var mondValues = MarshalToMond( args, mondTypes );
                            result = state.Call( value, mondValues );
                        }

                        var clrType = ToClrType( result );
                        return MarshalToClr( result, clrType, state );
                    };

                    return shim;

                default:
                    UnsupportedMondTypeError( value.Type );
                    break;
            }

            return null; // we should never get here
        }
示例#42
0
 public IEnumerable<IMondLibrary> Create(MondState state)
 {
     yield return new ConsoleOutputLibrary();
 }
示例#43
0
 /// <summary>
 /// Generates module bindings for a type. Returns an object containing the bound methods.
 /// </summary>
 /// <param name="type"></param>
 /// <param name="state">Optional state to bind to. Only required if you plan on using metamethods.</param>
 public static MondValue Bind(Type type, MondState state)
 {
     return(CopyToObject(BindImpl(type), state));
 }
示例#44
0
        private static void SerializeImpl(MondState state, MondValue value, StringBuilder sb, int depth)
        {
            if (depth >= 32)
            {
                throw new MondRuntimeException(SerializePrefix + "maximum depth exceeded");
            }

            if (sb.Length >= 1 * 1024 * 1024)
            {
                throw new MondRuntimeException(SerializePrefix + "maximum size exceeded");
            }

            var first = true;

            switch (value.Type)
            {
            case MondValueType.True:
                sb.Append("true");
                break;

            case MondValueType.False:
                sb.Append("false");
                break;

            case MondValueType.Null:
                sb.Append("null");
                break;

            case MondValueType.Undefined:
                sb.Append("undefined");
                break;

            case MondValueType.Number:
                var number = (double)value;

                if (double.IsNaN(number))
                {
                    throw new MondRuntimeException(CantSerializePrefix + "NaN");
                }

                if (double.IsInfinity(number))
                {
                    throw new MondRuntimeException(CantSerializePrefix + "Infinity");
                }

                sb.Append(number);
                break;

            case MondValueType.String:
                SerializeString(value, sb);
                break;

            case MondValueType.Object:
                var serializeMethod = value["__serialize"];
                if (serializeMethod)
                {
                    value = state.Call(serializeMethod, value);

                    if (value.Type != MondValueType.Object)
                    {
                        SerializeImpl(state, value, sb, depth + 1);
                        return;
                    }
                }

                sb.Append('{');

                foreach (var kvp in value.AsDictionary)
                {
                    if (kvp.Value == MondValue.Undefined)
                    {
                        continue;
                    }

                    if (first)
                    {
                        first = false;
                    }
                    else
                    {
                        sb.Append(',');
                    }

                    SerializeImpl(state, kvp.Key, sb, depth + 1);

                    sb.Append(':');

                    SerializeImpl(state, kvp.Value, sb, depth + 1);
                }

                sb.Append('}');
                break;

            case MondValueType.Array:
                sb.Append('[');

                foreach (var v in value.AsList)
                {
                    if (first)
                    {
                        first = false;
                    }
                    else
                    {
                        sb.Append(',');
                    }

                    SerializeImpl(state, v, sb, depth + 1);
                }

                sb.Append(']');
                break;

            default:
                throw new MondRuntimeException(CantSerializePrefix + "{0}s", value.Type.GetName());
            }
        }
示例#45
0
 /// <summary>
 /// length(): number
 /// </summary>
 private static MondValue Length(MondState state, MondValue instance, params MondValue[] arguments)
 {
     Check("length", instance.Type, arguments);
     return(instance.ObjectValue.Values.Count);
 }
示例#46
0
        public void SetUp()
        {
            _state = new MondState();
            _state["Person"] = MondClassBinder.Bind<Person>();

            _state.Run(@"
                global.brian = global.Person('Brian');
            ");
        }
示例#47
0
 private static MondValue PrintLn(MondState state, params MondValue[] arguments)
 {
     Print(state, arguments);
     Console.WriteLine();
     return(MondValue.Undefined);
 }
示例#48
0
 private static MondValue Stdin(MondState state, params MondValue[] arguments)
 {
     return(MondValue.FromEnumerable(StdinEnumerable().Select(c => new MondValue(new string(c, 1)))));
 }
示例#49
0
 public ErrorLibrary(MondState state) => _state = state;
示例#50
0
 public IEnumerable <IMondLibrary> Create(MondState state)
 {
     yield return(new InteropLibrary());
 }
示例#51
0
 public IEnumerable <IMondLibrary> Create(MondState state)
 {
     yield return(new JsonLibrary(state));
 }
示例#52
0
 public AsyncLibrary(MondState state) => _state = state;
示例#53
0
文件: Worker.cs 项目: Rohansi/Mondbot
        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()));
        }
示例#54
0
 /// <summary>
 /// remove(item): array
 /// </summary>
 private static MondValue Remove(MondState state, MondValue instance, params MondValue[] arguments)
 {
     Check("remove", instance.Type, arguments, MondValueType.Undefined);
     instance.ArrayValue.Remove(arguments[0]);
     return(instance);
 }
示例#55
0
 public void SetUp()
 {
     _state = new MondState();
     MondOperatorModuleBinder.Bind<MyOperators>(_state);
 }
示例#56
0
 /// <summary>
 /// contains(item): bool
 /// </summary>
 private static MondValue Contains(MondState state, MondValue instance, params MondValue[] arguments)
 {
     Check("contains", instance.Type, arguments, MondValueType.Undefined);
     return(instance.ArrayValue.Contains(arguments[0]));
 }
示例#57
0
 public void SetUp()
 {
     _state         = new MondState();
     _state["Test"] = MondModuleBinder.Bind <Test>(_state);
 }
示例#58
0
 public IEnumerable <IMondLibrary> Create(MondState state)
 {
     yield return(new ConsoleInputLibrary(state));
 }
示例#59
0
 public IEnumerable<IMondLibrary> Create(MondState state)
 {
     yield return new JsonLibrary();
 }
示例#60
0
 public void ChangeState(MondState state)
 {
     state["test"] = 100;
 }