コード例 #1
0
 public CompiledMachineState(CompiledProgram program, IReadonlyExternalsMap externalsMap, Value[] internals, Value[] externals)
 {
     _program      = program;
     _externalsMap = externalsMap;
     _internals    = internals;
     _externals    = externals;
 }
コード例 #2
0
        public void Test()
        {
            string path = Path.GetTempFileName();

            try
            {
                Compiler compiler = new();

                // Define symbols used in source to prevent errors
                compiler.RegisterFunction("Color", 1, 2);
                compiler.RegisterFunction("ClearScreen", 0, 0);
                compiler.RegisterFunction("Print", 0, 99);
                compiler.RegisterFunction("PrintLine", 0, 99);
                compiler.RegisterVariable("White", new Variable());
                compiler.RegisterVariable("Blue", new Variable());
                Assert.IsTrue(compiler.CompileSource(Source, out CompiledProgram? program));

                program !.Save(path);
                program = CompiledProgram.FromFile(path);

                Runtime runtime = new(program !);

                Assert.AreEqual(5000, runtime.Execute());
            }
            finally
            {
                File.Delete(path);
            }
        }
コード例 #3
0
ファイル: RunProgram.cs プロジェクト: battyone/Silk
        public bool Compile(string path, out CompiledProgram program, bool createLogFile = false)
        {
            // Compile program
            Compiler compiler = new Compiler();

            compiler.CreateLogFile = createLogFile;

            // Register intrinsic functions
            foreach (string name in FunctionLookup.Keys)
            {
                FunctionInfo info = FunctionLookup[name];
                compiler.RegisterFunction(name, info.MinParameters, info.MaxParameters);
            }

            // Register intrinsic variables
            foreach (KnownColor color in Enum.GetValues(typeof(KnownColor)))
            {
                compiler.RegisterVariable(color.ToString(), new Variable((int)color));
            }

            // Compile program
            if (compiler.Compile(path, out program))
            {
                return(true);
            }
            else
            {
                Errors = compiler.Errors;
                return(false);
            }
        }
コード例 #4
0
ファイル: RunProgram.cs プロジェクト: battyone/Silk
        /// <summary>
        ///
        /// </summary>
        /// <param name="path"></param>
        /// <param name="result"></param>
        /// <returns></returns>
        public Variable Execute(CompiledProgram program, PictureBox picCanvas)
        {
            if (picCanvas == null)
            {
                throw new NullReferenceException(nameof(picCanvas));
            }

            Runtime runtime = new Runtime();

            runtime.Begin    += Runtime_Begin;
            runtime.Function += Runtime_Function;
            runtime.End      += Runtime_End;

            // TODO: Do we need to dispose of any of these objects?

            PicCanvas = picCanvas;
            Bitmap    = new Bitmap(PicCanvas.ClientSize.Width, PicCanvas.ClientSize.Height);
            using (Graphics = Graphics.FromImage(Bitmap))
            {
                //using (Bitmap = new Bitmap(PicCanvas.ClientSize.Width, PicCanvas.ClientSize.Height))
                //using (Graphics = Graphics.FromImage(Bitmap))
                PicCanvas.Image = Bitmap;

                return(runtime.Execute(program));
            }
        }
コード例 #5
0
        public LinesPerSecond()
        {
            // Pin to one core to reduce benchmarking noise.
            var proc = Process.GetCurrentProcess();

            if (OperatingSystem.IsLinux() || OperatingSystem.IsWindows())
            {
                const int affinity = 1 << 5;
                proc.ProcessorAffinity = (IntPtr)affinity;
            }

            // Make it high priority to reduce benchmarking noise.
            proc.PriorityClass = ProcessPriorityClass.High;

            var ast = Parse(_program);

            var staticTypes = new Dictionary <VariableName, Yolol.Execution.Type> {
                //{ new VariableName("b"), Yolol.Execution.Type.Number },
            };

            _externalsMap = new ExternalsMap();
            var timer = new Stopwatch();

            timer.Start();
            _compiled = ast.Compile(_externalsMap, 20, 1024, staticTypes, true);
            Console.WriteLine($"Compiled in: {timer.Elapsed.TotalMilliseconds}ms");

            _externals = new Value[_externalsMap.Count];
            Array.Fill(_externals, Number.Zero);
            _internals = new Value[_compiled.InternalsMap.Count];
            Array.Fill(_internals, Number.Zero);

            _externals[_externalsMap[new VariableName(":s")]] = new Value("Hello Cylon");
            _externals[_externalsMap[new VariableName(":i")]] = (Number)6;
        }
コード例 #6
0
            private CompiledProgramState(CompiledProgram compiled)
            {
                _compiled = compiled;

                Internals = new Value[compiled.InternalsMap.Count];
                Array.Fill(Internals, Number.Zero);
            }
コード例 #7
0
        public static void RunProgram(CompiledProgram program)
        {
            var runtime = new Runtime(program);

            runtime.Begin    += Runtime_Begin;
            runtime.Function += Runtime_Function;
            runtime.End      += Runtime_End;

            runtime.Execute();
        }
コード例 #8
0
ファイル: frmRun.cs プロジェクト: battyone/Silk
        public frmRun(RunProgram runProgram, CompiledProgram program)
        {
            if (runProgram == null)
            {
                throw new NullReferenceException(nameof(runProgram));
            }
            if (program == null)
            {
                throw new NullReferenceException(nameof(program));
            }

            RunProgram = runProgram;
            Program    = program;
            InitializeComponent();
        }
コード例 #9
0
        public static void RunProgram(CompiledProgram program)
        {
            Runtime runtime = new Runtime();

            KatanaForm.form2 = new Form2(mySourceFile);
            KatanaForm.form2.Show();

            KatanaForm.form3 = new Form3();
            KatanaForm.form3.Show();



            runtime.Begin    += Runtime_Begin;
            runtime.Function += Runtime_Function;
            runtime.End      += Runtime_End;

            Variable result = runtime.Execute(program);

            // Console.WriteLine(source + " ran successfully with exit code {0}.", result);
        }
コード例 #10
0
        public CompareInterpreter()
        {
            _ast = Parse(
                ":done++ b=97 c=89",
                ":o++ :done++",
                ":done++",
                "i=127-1 _=(i/3%1==0)*i/3>1+(i/5%1==0)*i/5>1+(i/7%1==0)*i/7>1 a=i/11%1==0",
                "_+=a*i/11>1+(i/13%1==0)*i/13>1+(i/17%1==0)*i/17>1+(i/19%1==0)*i/19>1",
                "_+=(i/23%1==0)*i/23>1+(i/29%1==0)*i/29>1+(i/31%1==0)*i/31>1a=i/37%1==0",
                "_+=a*i/37>1+(i/41%1==0)*i/41>1+(i/43%1==0)*i/43>1+(i/47%1==0)*i/47>1",
                "_+=(i/53%1==0)*i/53>1+(i/59%1==0)*i/59>1+(i/61%1==0)*i/61>1a=i/67%1==0",
                "_+=a*i/67>1+(i/71%1==0)*i/71>1+(i/73%1==0)*i/73>1+(i/79%1==0)*i/79>1",
                "_+=(i/83%1==0)*i/83>1+(i/c%1==0)*i/c>1+(i/b%1==0)*i/b>1:o+=_<1:done++",
                "z=:o :done++goto4"
                );

            _network = new Network((Number)1, (Number)2, (Number)0);
            _state   = new MachineState(_network);

            var types = new Dictionary <VariableName, Yolol.Execution.Type> {
                { new VariableName("a"), Yolol.Execution.Type.Number },
                { new VariableName("b"), Yolol.Execution.Type.Number },
                { new VariableName("c"), Yolol.Execution.Type.Number },
                { new VariableName("d"), Yolol.Execution.Type.Number },
                { new VariableName("e"), Yolol.Execution.Type.Number },
                { new VariableName("f"), Yolol.Execution.Type.Number },
            };
            var internalsPerLine = new InternalsMap();
            var externalsPerLine = new ExternalsMap();

            _compiledLines = new Func <ArraySegment <Value>, ArraySegment <Value>, LineResult> [_ast.Lines.Count];
            for (var i = 0; i < _ast.Lines.Count; i++)
            {
                _compiledLines[i] = _ast.Lines[i].Compile(i + 1, 20, 1024, internalsPerLine, externalsPerLine, types);
            }

            _internals = new Value[internalsPerLine.Count];
            _externals = new Value[externalsPerLine.Count];

            _compiledProgramLine = _ast.Compile(new ExternalsMap(), 20, 1024, types);
        }
コード例 #11
0
 private static Variable RunProgram(CompiledProgram program) => new Runtime(program).Execute();
コード例 #12
0
 public Dictionary <CompiledFunction, List <Path> > GenerateConstraints(CompiledProgram program)
 => program.Functions.ToDictionary(f => f, f => GenerateConstriants(f));
コード例 #13
0
ファイル: Compiler.cs プロジェクト: Ciastex/Silk
        public bool Compile(string path, out CompiledProgram program)
        {
            Functions       = new OrderedDictionary <string, Function>(StringComparer.OrdinalIgnoreCase);
            Variables       = new OrderedDictionary <string, Variable>(StringComparer.OrdinalIgnoreCase);
            Literals        = new List <Variable>();
            Lexer           = new LexicalAnalyzer();
            Lexer.Error    += Lexer_Error;
            Writer          = new ByteCodeWriter(Lexer);
            InHeader        = true;
            CurrentFunction = null;
            Errors          = new List <Error>();
            program         = null;

            // Add intrinsic functions to function collection
            foreach (var function in IntrinsicFunctions.Values)
            {
                Functions.Add(function.Name, function);
            }
            // Add intrinsic variables to variable collection
            foreach (var pair in IntrinsicVariables.GetKeyValuePairs())
            {
                Variables.Add(pair.Key, pair.Value);
            }
            // Add internal functions and variables
            if (EnableInternalFunctions)
            {
                InternalFunctions.AddInternalFunctionsAndVariables(Functions, Variables);
            }

            try
            {
                // Load file and initialize lexer
                Lexer.Reset(File.ReadAllText(path));
                // Write bytecodes to call function main.
                // Also causes error if main function is not defined
                Writer.Write(OpCode.ExecFunction, GetFunctionId(Function.Main));
                // Parse statements
                while (ParseStatement())
                {
                }

                // Verify end of file
                Token token = Lexer.GetNext();
                if (token.Type != TokenType.EndOfFile)
                {
                    Error(ErrorCode.UnexpectedToken, token);
                }
                // Check for undefined functions
                foreach (var funcInfo in Functions.GetKeyValuePairs())
                {
                    if (funcInfo.Value == null)
                    {
                        if (funcInfo.Key.Equals(Function.Main, StringComparison.CurrentCultureIgnoreCase))
                        {
                            Error(ErrorCode.MainNotDefined, Function.Main.MakeQuoted());
                        }
                        else
                        {
                            Error(ErrorCode.FunctionNotDefined, funcInfo.Key.MakeQuoted());
                        }
                    }
                }
            }
            catch (TooManyErrorsException)
            {
                // Already handled
            }
            catch (Exception ex)
            {
                Error(ErrorCode.InternalError, ex.Message, ErrorLevel.FatalError);
            }
            // Done if compile failed
            if (Errors.Count > 0)
            {
                return(false);
            }
            // Implement logging
            if (CreateLogFile)
            {
                Writer.WriteLogFile(path, Path.ChangeExtension(path, "log"));
            }
            // Return compiled data
            program = new CompiledProgram
            {
                ByteCodes = Writer.GetBytecodes(),
                Functions = Functions.Values.Select(f =>
                                                    (f is CompileTimeUserFunction userFunction) ? new UserFunction(userFunction) : f).ToArray(),
                Variables   = Variables.Values.ToArray(),
                Literals    = Literals.ToArray(),
                LineNumbers = EnableLineNumbers ? Writer.GetLineNumbers() : null,
            };
            return(true);
        }