예제 #1
0
        private object MtCons(ScriptThread thread, object[] args)
        {
            var ret = new MtResult();

            var head = args[0] as MtResult;
            var tail = args[1] as MtResult;

            // we can eval the head later ;)
            tail.GetValue(o =>
            {
                var arr = o.Value as MtResult[];
                if (arr == null)
                {
                    throw new Exception("Cons expected a list!");
                }

                var ret_arr = new MtResult[arr.Length + 1];

                ret_arr[0] = head;
                Array.Copy(arr, 0, ret_arr, 1, arr.Length);

                ret.SetValue(new MtObject(ret_arr));
            });

            return(ret);
        }
예제 #2
0
        protected override object DoEvaluate(ScriptThread thread)
        {
            thread.CurrentNode = this;
            try
            {
                var result       = new MtResult();
                var targetThread = _target.NewScriptThread(thread);
                var rTarget      = _target.Evaluate(targetThread) as MtResult;

                var sourceThread = _source.NewScriptThread(thread);
                var rSource      = _source.Evaluate(sourceThread) as MtResult;

                rTarget.GetValue(target =>
                {
                    rSource.GetValue(source =>
                    {
                        MtStream.ReadFromWriteTo(
                            source.Value as MtStream, target.Value as MtStream, () => {
                            result.SetValue(MtObject.True);
                        });
                    });
                });

                return(result);
            }
            catch (Exception e)
            {
                throw new Exception("Exception on MtFlowRightToLeft.DoEvaluate", e);
            }
            finally
            {
                //thread.CurrentNode = Parent;
            }
        }
예제 #3
0
        private object MtGreater(ScriptThread thread, object[] args)
        {
            var ret = new MtResult();

            var arg0 = args[0] as MtResult;
            var arg1 = args[1] as MtResult;

            arg0.GetValue(o1 =>
            {
                arg1.GetValue(o2 =>
                {
                    int i1 = (int)o1.Value;
                    int i2 = (int)o2.Value;

                    if (i1 > i2)
                    {
                        ret.SetValue(MtObject.True);
                    }
                    else
                    {
                        ret.SetValue(MtObject.False);
                    }
                });
            });

            return(ret);
        }
예제 #4
0
        protected override object DoEvaluate(Irony.Interpreter.ScriptThread thread)
        {
            thread.CurrentNode = this;
            try
            {
                var res = new MtResult();

                var accessor = thread.Bind(_targetName.AsString, BindingRequestFlags.Write | BindingRequestFlags.ExistingOrNew);
                accessor.SetValueRef(thread, res);

                // To allow recursive definitions, we have
                // to evaluate _expression inside the new context.
                var exprResult = _expression.Evaluate(thread) as MtResult;
                exprResult.GetValue((o) =>
                {
                    res.SetValue((state) =>
                    {
                        return(o);
                    });
                });

                return(res);
            }
            catch (Exception e)
            {
                throw new Exception("Exception on MtBind.DoEvaluate", e);
            }
            finally
            {
                //thread.CurrentNode = Parent;
            }
        }
예제 #5
0
        public object MtHttpStream(ScriptThread thread, object[] arguments)
        {
            var result = new MtResult();

            var arg0 = arguments[0] as MtResult;

            arg0.GetValue(httpstuff =>
            {
                if (httpstuff.Value is HttpListenerRequest)
                {
                    var wrkValue = httpstuff.Value as HttpListenerRequest;
                    result.SetValue(new MtObject(new MtStreamWrapper(wrkValue.InputStream)));
                }
                else if (httpstuff.Value is HttpListenerResponse)
                {
                    var wrkValue = httpstuff.Value as HttpListenerResponse;
                    result.SetValue(new MtObject(new MtStreamWrapper(wrkValue.OutputStream)));
                }
                else
                {
                    throw new Exception("Neither a request nor a response!");
                }
            });

            return(result);
        }
예제 #6
0
        private MtResult MtCdr(ScriptThread thread, object[] args)
        {
            var ret = new MtResult();
            var arr = args[0] as MtResult;

            arr.GetValue((o) =>
            {
                var wrkArr = o.Value as MtResult[];
                if (wrkArr == null)
                {
                    throw new Exception("Argument is not an array!");
                }

                if (wrkArr.Length == 0 || wrkArr.Length == 1)
                {
                    ret.SetValue(new MtObject(new MtResult[0]));
                }
                else
                {
                    ret.SetValue((state) =>
                    {
                        var tail = new MtResult[wrkArr.Length - 1];

                        Array.Copy(wrkArr, 1, tail, 0, tail.Length);

                        return(new MtObject(tail));
                    });
                }
            });
            return(ret);
        }
예제 #7
0
        private object MtAnd(ScriptThread thread, object[] args)
        {
            var ret = new MtResult();

            var arg0 = args[0] as MtResult;
            var arg1 = args[1] as MtResult;

            arg0.GetValue(o1 =>
            {
                arg1.GetValue(o2 =>
                {
                    if (MtObject.True.Value == o1.Value &&
                        MtObject.True.Value == o2.Value)
                    {
                        ret.SetValue(MtObject.True);
                    }
                    else
                    {
                        ret.SetValue(MtObject.False);
                    }
                });
            });

            return(ret);
        }
예제 #8
0
        private object MtSliceUntil(ScriptThread thread, object[] args)
        {
            var ret = new MtResult();

            var the_list = args[0] as MtResult;
            var the_idx  = args[1] as MtResult;

            the_list.GetValue(o_list =>
            {
                var arr = o_list.Value as MtResult[];
                if (arr == null)
                {
                    throw new Exception("slice_until expected a list!");
                }

                the_idx.GetValue(o_idx =>
                {
                    var idx = (int)o_idx.Value;

                    var ret_arr = new MtResult[idx];
                    Array.Copy(arr, ret_arr, ret_arr.Length);

                    ret.SetValue(new MtObject(ret_arr));
                });
            });

            return(ret);
        }
예제 #9
0
        protected override object DoEvaluate(ScriptThread thread)
        {
            thread.CurrentNode = this;
            try
            {
                var programResult = new MtResult();

                // do NOT use this for anything else other than counting the number of to-finish-threads
                var count           = _chains.Count;
                var waitForAllToEnd = new ManualResetEvent(false);

                // TODO THIS NEEDS TO BE FIXED!
                // The rest of the program only cares about the result of the last expression
                // which doesn't depend of the result of the previous expressions;
                // however, the program shouldn't end.
                // SOLUTION: Keep a global counter of all awaiting MtResults?

                for (int i = 0; i < _chains.Count; ++i)
                {
                    // This is here because of issues with closures using the for variable
                    var safe_i    = i + 0;
                    var ch        = _chains[i];
                    var subthread = ch.NewScriptThread(thread);
                    var chResult  = ch.Evaluate(subthread) as MtResult;

                    // Lookout:
                    // do not capture anything loop related inside here
                    chResult.GetValue(delegate(MtObject x)
                    {
                        if (Interlocked.Decrement(ref count) == 0)
                        {
                            waitForAllToEnd.Set();
                        }

                        // Wait for the last chain to end.
                        // Last refers in the order of the chain in the code,
                        // not the order of execution!!!
                        if (safe_i == _chains.Count - 1)
                        {
                            // Wait for the end of *all* the chains before returning ...
                            waitForAllToEnd.WaitOne();
                            programResult.SetValue(x);
                        }
                    });
                }


                // Return value does not matter. This is asynchronous, remember?
                return(programResult);
            }
            catch (Exception e)
            {
                throw new Exception("Exception on MtProgram.", e);
            }
            finally
            {
                //thread.CurrentNode = Parent;
            }
        }
예제 #10
0
        public MtResult MtDiv(ScriptThread thread, object[] args)
        {
            var result  = new MtResult();
            var reducer = new DivReducer(result);

            reducer.Reduce(args);
            return(result);
        }
예제 #11
0
        public MtResult MtSleep(ScriptThread thread, object[] args)
        {
            var      result      = new MtResult();
            MtObject sleepResult = null;

            var sleepMs   = args[0] as MtResult;
            var sleepEval = args.Length > 1 ? args[1] as MtResult : MtResult.True;

            var waitValue = new ManualResetEvent(false);

            // eval number of milliseconds to wait
            sleepMs.GetValue((waitPeriod) =>
            {
                // eval value to return
                sleepEval.GetValue((retValue) =>
                {
                    sleepResult = retValue;

                    // Signal: We have a value!
                    waitValue.Set();
                });

                // set value, async
                result.SetValue((state) =>
                {
#if DEBUG && !SILVERLIGHT
                    Debug.Print("MtSleep #1 Thread {0} {1:mm:ss.ffff} start sleep", Thread.CurrentThread.ManagedThreadId, DateTime.Now);
#endif

                    // Wait period and, if need be, wait for sleepResult
                    var to_wait = (int)waitPeriod.Value;
                    if (to_wait > 0)
                    {
                        Thread.Sleep(to_wait);
                    }
#if DEBUG && !SILVERLIGHT
                    Debug.Print("MtSleep #2 Thread {0} {1:mm:ss.ffff} end sleep, wait value", Thread.CurrentThread.ManagedThreadId, DateTime.Now);
#endif

                    // Wait for signal...
                    waitValue.WaitOne();

#if DEBUG && !SILVERLIGHT
                    Debug.Print("MtSleep #3 Thread {0} {1:mm:ss.ffff} has value", Thread.CurrentThread.ManagedThreadId, DateTime.Now);
#endif

                    if (sleepResult == null)
                    {
                        throw new Exception("Sleep can't return null!");
                    }

                    return(sleepResult);
                });
            });

            return(result);
        }
예제 #12
0
        private MtResult MtMap(ScriptThread thread, object[] args)
        {
            var result        = new MtResult();
            var arrExpression = args[0] as MtResult;
            var fun           = args[1];

            arrExpression.GetValue((arr) =>
            {
                // arr
                MtResult[] wrkArr = arr.Value as MtResult[];

                if (wrkArr == null)
                {
                    throw new Exception("Array expression is null!");
                }

                MtFunctionObjectBase.ExtractAsFunction(fun, (wrkFun) =>
                {
                    // Launch and wait for all to end
                    var count = wrkArr.Length;
                    var res   = new MtResult[count];

                    if (count > 0)
                    {
                        var waitForEndOfAll = new ManualResetEvent(false);

                        for (var i = 0; i < wrkArr.Length; ++i)
                        {
                            int copy_i = i;

                            var ret = wrkFun.Call(thread, new object[] { wrkArr[i] });
                            if (ret == null)
                            {
                                throw new Exception("Return of application in map is null!");
                            }

                            var wrkRet = ret as MtResult;
                            wrkRet.WaitForValue((r) =>
                            {
                                res[copy_i] = r;

                                if (Interlocked.Decrement(ref count) == 0)
                                {
                                    waitForEndOfAll.Set();
                                }
                            });
                        }

                        waitForEndOfAll.WaitOne();
                    }

                    result.SetValue(new MtObject(res));
                });
            });

            return(result);
        }
예제 #13
0
        protected override object DoEvaluate(Irony.Interpreter.ScriptThread thread)
        {
            // PROLOG
            thread.CurrentNode = this;
            try
            {
                var appResult = new MtResult();

                MtResult[] args = _args.Evaluate(thread) as MtResult[];
                if (args == null)
                {
                    throw new Exception("Args evaluated to null!");
                }

                var subthreadF = _head.NewScriptThread(thread);
                var headResult = _head.Evaluate(subthreadF);
                if (headResult == null)
                {
                    throw new Exception("Head can't evaluate to null!");
                }

                MtFunctionObjectBase.ExtractAsFunction(headResult, (wrkFun) =>
                {
#if DEBUG && !SILVERLIGHT
                    if (wrkFun is BuiltInCallTarget)
                    {
                        var builtin = wrkFun as BuiltInCallTarget;
                        Debug.Print("Calling builtin: {0}", builtin.Name);
                    }
                    else
                    {
                        Debug.Print("Calling user function");
                    }
#endif

                    var resultFun = wrkFun.Call(thread, args) as MtResult;
                    resultFun.GetValue((r3) =>
                    {
                        appResult.SetValue(r3);
                    });
                });

                return(appResult);
            }
            catch (Exception e)
            {
                throw new Exception("Exception on MtApplication.", e);
            }
            finally
            {
                // EPILOG
                //thread.CurrentNode = Parent;
            }
        }
예제 #14
0
        public MtResult MtPrint(ScriptThread thread, object[] args)
        {
            try
            {
                var r = new MtResult();

                Monitor.Enter(_mtPrintLock);
                try
                {
                    Reduce(args, (o) =>
                    {
                        String toWrite = o == null ? "<null>" : o.ToString();

                        if (OutputStream != null)
                        {
                            byte[] raw = Encoding.UTF8.GetBytes(toWrite);
                            OutputStream.Write(raw, 0, raw.Length);
                        }

                        thread.App.Write(toWrite);
                    }, () =>
                    {
                        // Write new lines
                        if (OutputStream != null)
                        {
                            OutputStream.Write(_newLineRaw, 0, _newLineRaw.Length);
                            OutputStream.Flush();
                        }

                        thread.App.WriteLine("");

                        r.SetValue(MtObject.True);
                    });
                }
                catch (Exception e)
                {
                    throw new Exception("Error printing stuff.", e);
                }
                finally
                {
                    // Sync wait to avoid race conditions
                    // while printing ...
                    r.WaitForValue();
                    Monitor.Exit(_mtPrintLock);
                }

                return(r);
            }
            catch (Exception e)
            {
                throw new Exception("Exception on Runtime function: print", e);
            }
        }
예제 #15
0
        protected override object DoEvaluate(Irony.Interpreter.ScriptThread thread)
        {
            thread.CurrentNode = this;
            try
            {
                MtResult[] result = new MtResult[_args.Count];

                for (var i = 0; i < _args.Count; ++i)
                {
                    try
                    {
                        var subthread  = _args[i].NewScriptThread(thread);
                        var evalResult = _args[i].Evaluate(subthread);

                        if (evalResult == null)
                        {
                            throw new Exception(string.Format("_args[{0}].Evaluate evaluated to null!", i));
                        }

                        if (evalResult is MtResult)
                        {
                            result[i] = evalResult as MtResult;
                        }
                        else
                        {
                            // A function, wrap it!
                            result[i] = MtResult.CreateAndWrap(evalResult);
                        }

                        if (result[i] == null)
                        {
                            throw new Exception("Result is a non-MtResult!");
                        }
                    }
                    catch (Exception e)
                    {
                        throw new Exception(string.Format("There was a problem evaluating arg {0}", i), e);
                    }
                }

                return(result);
            }
            catch (Exception e)
            {
                throw new Exception("Error on MtArguments.DoEvaluate", e);
            }
            finally
            {
                //thread.CurrentNode = Parent;
            }
        }
예제 #16
0
        public object MtWait(ScriptThread thread, object[] arguments)
        {
            // Wait for all arguments. Blocking.
            for (var i = 0; i < arguments.Length; ++i)
            {
                var arg = arguments[i] as MtResult;
                if (arg == null)
                {
                    throw new Exception("Unexpected argument!");
                }
                arg.WaitForValue();
            }

            // Returns all the arguments, in an array
            return(MtResult.CreateAndWrap(arguments));
        }
예제 #17
0
        public object MtHttpEnd(ScriptThread thread, object[] arguments)
        {
            var result = new MtResult();

            var arg0 = arguments[0] as MtResult;

            arg0.GetValue(response =>
            {
                var wrkResponse = response.Value as HttpListenerResponse;
                if (wrkResponse == null)
                {
                    throw new Exception("No response!");
                }
                wrkResponse.Close();
            });

            return(result);
        }
예제 #18
0
        protected override object DoEvaluate(Irony.Interpreter.ScriptThread thread)
        {
            thread.CurrentNode = this;
            try
            {
                var myRes = new MtResult();

                // Eval expression
                var subthread = _expression.NewScriptThread(thread);
                var res       = _expression.Evaluate(subthread) as MtResult;
                res.GetValue((resExpr) =>
                {
                    AstNode toEval = null;
                    if (resExpr.Value == MtObject.False.Value)
                    {
                        // Evaluate false branch
                        toEval = _falseBranch;
                    }
                    else
                    {
                        // Evaluate true branch
                        toEval = _trueBranch;
                    }

                    // Evaluate!
                    var subsubthread = toEval.NewScriptThread(thread);
                    var resBranch    = toEval.Evaluate(subsubthread) as MtResult;
                    resBranch.GetValue((_resBranch) =>
                    {
                        myRes.SetValue(_resBranch);
                    });
                });

                return(myRes);
            }
            catch (Exception e)
            {
                throw new Exception("Exception on If.DoEvaluate.", e);
            }
            finally
            {
                //thread.CurrentNode = Parent;
            }
        }
예제 #19
0
 protected override object DoEvaluate(Irony.Interpreter.ScriptThread thread)
 {
     // PROLOG
     thread.CurrentNode = this;
     try
     {
         // Atoms are synchronous, and evaluate to MtObjects
         return(MtResult.CreateAndWrap(_value));
     }
     catch (Exception e)
     {
         throw new Exception("Exception on MtAtom.", e);
     }
     finally
     {
         // EPILOG
         //thread.CurrentNode = Parent;
     }
 }
예제 #20
0
        public object MtUriStreamCreate(ScriptThread thread, object[] arguments)
        {
#if DEBUG && !SILVERLIGHT
            Debug.Print("Create stream from uri");
#endif

            try
            {
                var result = new MtResult();
                var rUri   = arguments[0] as MtResult;
                rUri.GetValue((uri) =>
                {
                    string strUri = uri.Value as string;

                    try
                    {
                        var dummy = new Uri(strUri);
                    }
                    catch
                    {
                        // Assume its a filename
                        // Try to combine with Env.CurrentDir
                        strUri = Path.Combine(Environment.CurrentDirectory, strUri);
                    }

                    var wrkUri = new Uri(strUri);
                    if (wrkUri.Scheme == Uri.UriSchemeFile)
                    {
                        result.SetValue(new MtObject(new MtStreamFile(strUri as string)));
                    }
                    else
                    {
                        throw new Exception("Unsupported uri scheme: " + wrkUri.Scheme);
                    }
                });

                return(result);
            }
            catch (Exception e)
            {
                throw new Exception("Exception on uri stream create.", e);
            }
        }
예제 #21
0
        public object MtHttpSetCode(ScriptThread thread, object[] arguments)
        {
            var result = new MtResult();
            var arg0   = arguments[0] as MtResult;
            var arg1   = arguments[1] as MtResult;

            arg0.GetValue(o =>
            {
                arg1.GetValue(code =>
                {
                    var response        = o.Value as HttpListenerResponse;
                    response.StatusCode = (int)code.Value;

                    result.SetValue(MtObject.True);
                });
            });

            return(result);
        }
예제 #22
0
        public object MtStreamsClose(ScriptThread thread, object[] arguments)
        {
#if DEBUG && !SILVERLIGHT
            Debug.Print("Close streams");
#endif

            try
            {
                var result = new MtResult();
                var count  = arguments.Length;

                foreach (var arg in arguments)
                {
                    var wrkArg = arg as MtResult;
                    if (wrkArg == null)
                    {
                        throw new Exception("Argument is not a MtResult!");
                    }

                    wrkArg.GetValue(stream =>
                    {
                        var wrkStream = stream.Value as MtStream;
                        if (wrkStream == null)
                        {
                            throw new Exception("Argument is not a stream!");
                        }

                        wrkStream.Close();

                        if (Interlocked.Decrement(ref count) == 0)
                        {
                            result.SetValue(MtObject.True);
                        }
                    });
                }
                return(result);
            }
            catch (Exception e)
            {
                throw new Exception("Exception on close(streams, ...)", e);
            }
        }
예제 #23
0
        private object MtNot(ScriptThread thread, object[] args)
        {
            var ret = new MtResult();

            var the_arg = args[0] as MtResult;

            the_arg.GetValue(o =>
            {
                if (o.Value == MtObject.False.Value)
                {
                    ret.SetValue(MtObject.True);
                }
                else
                {
                    ret.SetValue(MtObject.False);
                }
            });

            return(ret);
        }
예제 #24
0
        private MtResult MtCar(ScriptThread thread, object[] args)
        {
            var ret = new MtResult();
            var arr = args[0] as MtResult;

            arr.GetValue((o) =>
            {
                var wrkArr = o.Value as MtResult[];
                if (wrkArr == null)
                {
                    throw new Exception("Argument is not an array!");
                }

                wrkArr[0].GetValue((head) =>
                {
                    ret.SetValue(head);
                });
            });
            return(ret);
        }
예제 #25
0
        private object MtLength(ScriptThread thread, object[] args)
        {
            var ret  = new MtResult();
            var arg0 = args[0] as MtResult;

            arg0.GetValue((o) =>
            {
                var arr = o.Value as MtResult[];
                if (arr == null)
                {
                    ret.SetValue(new MtObject(0));
                }
                else
                {
                    ret.SetValue(new MtObject(arr.Length));
                }
            });

            return(ret);
        }
예제 #26
0
        private MtResult MtZero(ScriptThread thread, object[] args)
        {
            try
            {
                var res = new MtResult();

                var arg = args[0] as MtResult;
                arg.GetValue((o) =>
                {
                    int value = (int)o.Value;
                    res.SetValue(value == 0 ? MtObject.True : MtObject.False);
                });

                return(res);
            }
            catch (Exception e)
            {
                throw new Exception("Exception on Runtime function: zero", e);
            }
        }
예제 #27
0
        protected override object DoEvaluate(Irony.Interpreter.ScriptThread thread)
        {
            thread.CurrentNode = this;
            try
            {
                var ret = new MtResult();

                ret.SetValue(new MtObject(new MtFunctionObject(_body, _arguments, thread)));

                return(ret);
            }
            catch (Exception e)
            {
                throw new Exception("Error on MtFunctionLiteral.DoEvaluate", e);
            }
            finally
            {
                //thread.CurrentNode = Parent;
            }
        }
예제 #28
0
        public object MtStringStreamCreate(ScriptThread thread, object[] arguments)
        {
#if DEBUG && !SILVERLIGHT
            Debug.Print("Create stream from string");
#endif

            try
            {
                var result = new MtResult();
                var rStr   = arguments[0] as MtResult;
                rStr.GetValue((str) =>
                {
                    result.SetValue(new MtObject(new MtStreamString(str.Value as string)));
                });
                return(result);
            }
            catch (Exception e)
            {
                throw new Exception("Error on string stream create.", e);
            }
        }
예제 #29
0
        private object MtSliceFrom(ScriptThread thread, object[] args)
        {
            var ret = new MtResult();

            var the_list = args[0] as MtResult;
            var the_idx  = args[1] as MtResult;

            the_list.GetValue(o_list =>
            {
                var arr = o_list.Value as MtResult[];
                if (arr == null)
                {
                    throw new Exception("slice_from expected a list!");
                }

                the_idx.GetValue(o_idx =>
                {
                    var idx = (int)o_idx.Value;
                    idx     = idx < 0 ? 0 : idx;

                    if (idx >= arr.Length)
                    {
                        // If idx is outside array, return an empty array
                        ret.SetValue(new MtObject(new MtResult[0]));
                    }
                    else
                    {
                        var len = arr.Length;

                        var ret_arr = new MtResult[len - idx];
                        Array.Copy(arr, idx, ret_arr, 0, ret_arr.Length);

                        ret.SetValue(new MtObject(ret_arr));
                    }
                });
            });

            return(ret);
        }
예제 #30
0
        /// <summary>
        /// Create http server. Pass prefixes as arguments
        /// </summary>
        /// <param name="thread"></param>
        /// <param name="arguments"></param>
        /// <returns></returns>
        public object MtHttpServerCreate(ScriptThread thread, object[] arguments)
        {
            var result   = new MtResult();
            var prefixes = new string[arguments.Length];
            var count    = arguments.Length;

            for (var i = 0; i < arguments.Length; ++i)
            {
                var copy_i = i;
                var wrkArg = arguments[copy_i] as MtResult;

                wrkArg.GetValue(o =>
                {
                    prefixes[copy_i] = o.Value as string;

                    if (Interlocked.Decrement(ref count) == 0)
                    {
                        result.SetValue(new MtObject(new MtServerHttp(prefixes)));
                    }
                });
            }

            return(result);
        }