예제 #1
0
            public static Cell Eval(Cell code, CodeResult cr, SchemeEnvironment env)
            {
                List <Cell> args = new List <Cell>();

                args.Add(code);
                args.Add(new Cell(env));

                Machine machine = new Machine(cr, args);

                try {
                    System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
                    sw.Start();
                    while (machine.Finished == false)
                    {
                        machine.Step();
                    }
                    StepsExecuted += machine.Steps;
                    sw.Stop();
                    Console.WriteLine("!Eval ran in {0}", sw.Elapsed);
                } catch (Exception e) {
                    Debug.WriteLine("Eval failed: {0}", e.Message);
                }

                return(machine.A);
            }
예제 #2
0
        static void Main(string[] args)
        {
            ProgramArguments PArgs = ReadArguments(args);

            if (PArgs.Help)
            {
                Console.WriteLine("Usage: executable [-I] [-E evaluator] [-T] [-t] [-d] [file1 file2 ..] [-help]");
                Console.WriteLine("");
                Console.WriteLine("Where:");
                Console.WriteLine("\t-I            Enter interactive (REPL) mode. Default if no files specified.");
                Console.WriteLine("\t-E evaluator  Use given evaluator, valid options: cell, classic, frame");
                Console.WriteLine("\t-T            Run tests");
                Console.WriteLine("\t-t            Enable timing");
                Console.WriteLine("\t-d            Enable instruction debugging");
                Console.WriteLine("\tfile1..       File to run");
                Console.WriteLine("\t-help         Show this help");
                Console.WriteLine("");
                Console.WriteLine("Evaluators:");
                Console.WriteLine("\tframe         Frame evaluator. Combines cell and classic benefits. Default.");
                Console.WriteLine("\tcell          Cell virtual machine.");
                Console.WriteLine("\tclassic       Classic eval loop, no multitasking.");
                return;
            }

            Debug       = PArgs.Debug;
            ShowTimings = PArgs.Timing;
            Evaluator   = Activator.CreateInstance(PArgs.EvaluatorType) as ISchemeEval;

            SchemeEnvironment env = new SchemeEnvironment();

            StandardRuntime.AddGlobals(env);
            AddProgramGlobals(env);

            if (PArgs.Tests)
            {
                RunTests();
            }
            else if (PArgs.Files.Count == 0)
            {
                PArgs.Interactive = true;
            }

            if (PArgs.Files.Count > 0)
            {
                foreach (string file in PArgs.Files)
                {
                    RunSpecifiedFile(file, env);
                }
            }
            if (PArgs.Interactive)
            {
                REPL(env);
            }
            else if (System.Diagnostics.Debugger.IsAttached)
            {
                Console.WriteLine("[DEBUG] Press ENTER to end.");
                Console.ReadLine();
            }
        }
예제 #3
0
            public override Cell Eval(Cell Arg, SchemeEnvironment Env)
            {
                CodeResult cr      = GetCodeResult("Eval.asm");
                Machine    machine = new Machine(cr, new Cell[] { Arg, new Cell(Env) });

                machine.DebugMode = useDebug;
                while (machine.Finished == false)
                {
                    machine.Step();
                }
                stepCounter += machine.Steps;
                return(Result = machine.A);
            }
예제 #4
0
 protected static Cell DoEval(Cell code, SchemeEnvironment env)
 {
     // Update/set (debug) function
     env.Insert("debug", new Cell(btargs => {
         if (btargs.Length > 0)
         {
             Evaluator.Debug = (btargs[0] == StandardRuntime.True);
         }
         Debug = Evaluator.Debug;
         return(Debug ? StandardRuntime.True : StandardRuntime.False);
     }));
     Evaluator.Debug = Debug;
     Evaluator.Eval(code, env);
     return(Evaluator.Result);
 }
예제 #5
0
 static void RunSpecifiedFile(string path, SchemeEnvironment env = null)
 {
     try {
         // Read in specified file
         string specCode     = File.ReadAllText(GetFilePath(path));
         Cell   specCodeCell = StandardRuntime.Read(specCode);
         if (env == null)
         {
             // Create environment
             env = new SchemeEnvironment();
             StandardRuntime.AddGlobals(env);
         }
         Stopwatch sw = new Stopwatch();
         DoEval(specCodeCell, env);
         sw.Stop();
         if (ShowTimings)
         {
             Console.WriteLine("=== Executed {0} steps in {1}ms", Evaluator.Steps, sw.ElapsedMilliseconds);
         }
         Console.Error.WriteLine("Finish with value: {0}", Evaluator.Result);
     } catch (Exception e) {
         Console.Error.WriteLine("!!! {0}", e.Message);
     }
 }
예제 #6
0
            public static Cell Eval(string code, CodeResult cr, SchemeEnvironment env)
            {
                Cell codeCell = StandardRuntime.Read(code);

                return(Eval(codeCell, cr, env));
            }
예제 #7
0
            public static void TestCompileEval()
            {
                string eval  = System.IO.File.ReadAllText(Program.GetFilePath("Eval.asm"));
                string entry = "main";
                CellMachineAssembler assembler = new CellMachineAssembler(eval, entry);
                CodeResult           cr;

                try {
                    cr = CellMachineAssembler.Assemble(eval, entry);
                } catch (Exception e) {
                    Console.WriteLine("Failed to assemble: {0}", e.Message);
#if DEBUG
                    Console.WriteLine("Stack trace:");
                    Console.WriteLine(e.StackTrace);
#endif
                    return;
                }

                Console.WriteLine("Compiled Core/Eval.asm, {0} bytes into:", eval.Length);
                Console.WriteLine("  Code: {0} instructions ({1} bytes)", cr.Code.Count, cr.Code.Count * sizeof(int));
                int wordlength = 0;
                foreach (Cell c in cr.Data)
                {
                    wordlength += c.Value.Length;
                }
                Console.WriteLine("  Data: {0} elements ({1} bytes)", cr.Data.Count, wordlength);

                SchemeEnvironment env = new SchemeEnvironment();
                StandardRuntime.AddGlobals(env);

                string code = ""
                              + "(begin "
                              + "   (define fac (lambda (n) (if (<= n 1) 1 (* n (fac (- n 1))))))"
                              + "   (fac 10))";
                if (1 == 1)
                {
                    AssertEqual(Eval(StandardRuntime.True.Value, cr, env), StandardRuntime.True);
                }
                if (1 == 1)
                {
                    AssertEqual(Eval("1", cr, env), new Cell(1));
                }
                if (1 == 1)
                {
                    AssertEqual(Eval(new Cell(new Cell[] { }), cr, env), StandardRuntime.Nil);
                }
                if (1 == 1)
                {
                    AssertEqual(Eval("()", cr, env), StandardRuntime.Nil);
                }
                if (1 == 1)
                {
                    AssertEqual(Eval("(quote 1 2 3)", cr, env), new Cell(1));
                }
                if (1 == 1)
                {
                    AssertEqual(Eval("(define x 123)", cr, env), new Cell(123));
                }
                if (1 == 1)
                {
                    AssertEqual(Eval("x", cr, env), new Cell(123));
                }
                if (1 == 1)
                {
                    AssertEqual(Eval("(set! x 456)", cr, env), new Cell(456));
                }
                if (1 == 1)
                {
                    AssertEqual(Eval("x", cr, env), new Cell(456));
                }
                if (1 == 1)
                {
                    AssertEqual(Eval("(lambda (x y) (+ x y))", cr, env), new Cell("#Lambda((x y) (+ x y))"));
                }
                if (1 == 1)
                {
                    AssertEqual(Eval("(begin (define y 789) y)", cr, env), new Cell(789));
                }
                if (1 == 1)
                {
                    AssertEqual(Eval("(+ 1 2)", cr, env), new Cell(3));
                }
                if (1 == 1)
                {
                    AssertEqual(Eval("(begin (define add (lambda (x y) (+ x y))) (add 1 2))", cr, env), new Cell(3));
                }
                if (1 == 1)
                {
                    AssertEqual(Eval("(if (= 1 1) 1 0)", cr, env), new Cell("1"));
                }
                if (1 == 1)
                {
                    AssertEqual(Eval("(if (= 0 1) 0 1)", cr, env), new Cell("1"));
                }
                if (1 == 1)
                {
                    AssertEqual(Eval("(if (= 1 1) 1)", cr, env), new Cell("1"));
                }
                if (1 == 1)
                {
                    AssertEqual(Eval("(if (= 1 0) 1)", cr, env), StandardRuntime.Nil);
                }
                if (1 == 1)
                {
                    AssertEqual(Eval(code, cr, env), new Cell(3628800));
                }
                if (1 == 1)
                {
                    AssertEqual(Eval("(if (= 1 1) (+ 1 1) (- 1 1))", cr, env), new Cell(2));
                }
                if (1 == 1)
                {
                    AssertEqual(Eval("(if (= 1 1) (begin 1) (- 1 1))", cr, env), new Cell(1));
                }
            }
예제 #8
0
 public virtual void Init(Cell item, SchemeEnvironment env)
 {
     Item        = item;
     Environment = env;
 }
예제 #9
0
 public override void Init(Cell item, SchemeEnvironment env)
 {
     base.Init(item, env);
     machine = new CellMachine.Machine(cr, new Cell[] { Item, new Cell(Environment) });
 }
예제 #10
0
 public override void Init(Cell item, SchemeEnvironment env)
 {
     base.Init(item, env);
     state = new FrameEval.FrameState(Item, new Cell(Environment));
 }
예제 #11
0
 static void REPL(SchemeEnvironment env)
 {
     env["help"].ProcValue(new Cell[] { });             // invoke
     env["repl"].ProcValue(new Cell[] { });             // invoke
 }
예제 #12
0
        static void AddProgramGlobals(SchemeEnvironment env)
        {
            List <Cell> history = new List <Cell>();
            bool        quit    = false;
            bool        timing  = false;

            // Add a function to get a history result
            env.Insert("h", new Cell(args => new Cell(history[(int)(args[0])])));
            env.Insert("eval", new Cell((args, subenv) => {
                if (args.Length > 1)
                {
                    subenv = args[1].Environment;
                }
                return(DoEval(new Cell(args[0]), subenv));
            }));
            env.Insert("env", new Cell((args, subenv) => new Cell(subenv)));
            env.Insert("str", new Cell(args => new Cell(args[0].ToString())));
            env.Insert("env-str", new Cell(args => new Cell(args[0].Environment.ToString())));
            env.Insert("exit", new Cell(args => { quit = true; return(StandardRuntime.Nil); }));
            env.Insert("quit", env.Lookup(new Cell("exit")));
            env.Insert("timing", new Cell(args => {
                if (args.Length > 0)
                {
                    timing = ((string)args[0] == "on" || args[0] == StandardRuntime.True);
                    Console.Error.WriteLine("Timing is now " + (timing ? "on" : "off"));
                }
                return(timing ? StandardRuntime.True : StandardRuntime.False);
            }));

            // Add evaluator constants
            env.Insert("evcell", new Cell("evcell"));
            env.Insert("evclassic", new Cell("evclassic"));
            env.Insert("evframe", new Cell("evframe"));
            // Add function to change evaluator
            env.Insert("sweval", new Cell(args => {
                if (args.Length == 0)
                {
                    if (Evaluator.GetType() == typeof(CellMachineEval))
                    {
                        return(new Cell("evcell"));
                    }
                    else if (Evaluator.GetType() == typeof(StandardEval))
                    {
                        return(new Cell("evclassic"));
                    }
                    else if (Evaluator.GetType() == typeof(FrameEval))
                    {
                        return(new Cell("evframe"));
                    }
                    else
                    {
                        throw new InvalidDataException();
                    }
                }

                ISchemeEval newEvaluator;
                Cell result;
                switch (args[0].Value)
                {
                case "evcell":
                    newEvaluator = new CellMachineEval();
                    result       = new Cell("evcell");
                    break;

                case "evclassic":
                    newEvaluator = new StandardEval();
                    result       = new Cell("evclassic");
                    break;

                case "evframe":
                    newEvaluator = new FrameEval();
                    result       = new Cell("evframe");
                    break;

                default:
                    return(new Cell("#invalid_argument"));
                }

                // Copy details to new evaluator
                newEvaluator.Debug = Evaluator.Debug;
                Evaluator          = newEvaluator;

                return(result);
            }));
            // Add function to run unit tests on evaluator
            env.Insert("swtest", new Cell(args => {
                var results = SchemeEval.RunTests(Evaluator);
                Cell result = new Cell(CellType.LIST);
                result.ListValue.Add(new Cell(results.Success));
                result.ListValue.Add(new Cell(results.Failures));
                return(result);
            }));

            env.Insert("help", new Cell(args => {
                Console.Write("SchemingSharply v {0}", System.Reflection.Assembly.GetExecutingAssembly().GetName().Version);
#if DEBUG
                Console.WriteLine(" debug");
#else
                Console.WriteLine(" release");
#endif
                Console.WriteLine("Type `quit' or `\\q' to quit");
                Console.WriteLine("Type `(env-str (env))' to display environment");
                //Console.WriteLine("Use `(eval expr)' or `(eval expr (env))' for testing");
                Console.WriteLine("Use `(h n)' to view history item n");
                Console.WriteLine("Use `(timing #true)` to enable timing, `(debug #true)` to enable debugging");
                Console.WriteLine("Use `(sweval ...)` to get or set evaluator; valid options: evcell, evclassic, evframe");
                Console.WriteLine("Use `(swtest)` to run unit tests");
                Console.WriteLine("Use `(help)' to display this message again");
                Console.WriteLine();
                return(StandardRuntime.Nil);
            }));
            env.Insert("repl", new Cell(args => {
                quit = false;
                while (!quit)
                {
                    int index    = history.Count;
                    string entry = ReadLine(string.Format("{0}> ", index)).Trim();
                    if (entry.Equals("quit", StringComparison.OrdinalIgnoreCase) ||
                        entry.Equals("exit", StringComparison.OrdinalIgnoreCase) ||
                        entry == "\\q")
                    {
                        break;
                    }
                    if (entry.Equals(""))
                    {
                        continue;
                    }
                    try {
                        Stopwatch sw = new Stopwatch();
                        sw.Start();
                        Cell entered      = StandardRuntime.Read(entry);
                        LastExecutedSteps = Evaluator.Steps;
                        Cell result       = DoEval(entered, env);
                        string steps      = (Evaluator.Steps - LastExecutedSteps).ToString();
                        if (Evaluator.Steps < LastExecutedSteps)
                        {
                            steps = "??";
                        }
                        sw.Stop();
                        Console.WriteLine("===> {0}", result);
                        if (timing)
                        {
                            Console.WriteLine("=== Executed {0} steps in {1}ms", steps, sw.ElapsedMilliseconds);
                        }
                        history.Add(result);
                    } catch (Exception e) {
                        Console.WriteLine("!!!> {0}", e.Message);
                    }
                }
                return(StandardRuntime.Nil);
            }));
        }