/// <summary> /// Runs the interpreter. /// </summary> /// <returns>Return s false whether application end is requested.</returns> public override async Task Run() { Output.WriteLine("Welcome! Write a command. (Consider using \"help\" command if U R lost.)"); while (Running) { RunningCommand = await GetInterpreter(); if (RunningCommand != null) { RunningCommand.Input = Input; RunningCommand.Output = Output; RunningCommand.ConsoleContext = ConsoleContext; await RunningCommand.Run(); RunningCommand = null; Output.WriteLine(); } else { Output.WriteLine("Unrecognized command!"); } } Output.WriteLine("Have a nice day."); }
public void Load(IInterpreter itpr, Env env) { var code = @" empty = builtin empty fnx head x xs => x fnx tail x xs => xs fnx list x => x fn bool x => builtin bool x fn not x => builtin not x fnx is_empty x => builtin is_empty x fnx is_single x => builtin is_single x fnx is_many x => builtin is_many x fn match cond t f => builtin match cond t f fn if cond t => builtin if cond t fn exec exp => builtin exec exp fn equal x y => builtin equal x y fn not_equal x y => builtin not_equal x y fn lt x y => builtin lt x y fn gt x y => builtin gt x y fn lte x y => builtin lte x y fn gte x y => builtin gte x y fn range x y => builtin range x y "; env.LockVariable = true; foreach (var item in code.Split('\n')) { itpr.Input(item); } env.LockVariable = false; }
public TcpAcceptor(int port, IInterpreter interpreter) { Contract.Requires(interpreter != null); this.Port = port; this.Listener = new TcpListener(new IPEndPoint(IPAddress.Any, port)); this.Interpreter = interpreter; }
public void SetUp() { var lexer = Lexer.CreateDefault(); var parser = new Parser(); var funcFactory = FunctionFactory.Create(x => Activator.CreateInstance(x)); var executor = new Executor(funcFactory); _interpreter = new Interpreter(lexer, parser, executor); }
public TcpConnector(IPAddress hostAddress, int port, IInterpreter interpreter) { Contract.Requires(hostAddress != null); Contract.Requires(interpreter != null); this.HostAddress = hostAddress; this.Port = port; this.Interpreter = interpreter; }
public SanitizingStringInterpreter(IInterpreter<Byte> interpreter) : base(interpreter) { if (interpreter == null) { throw new ArgumentNullException(); } this.strict = false; }
public TcpMessager(TcpClient client, IInterpreter interpreter) { Contract.Requires(client != null); Contract.Requires(interpreter != null); this.TcpClient = client; this.Interpreter = interpreter; var stream = client.GetStream(); this.writer = new BinaryWriter(stream); this.reader = new BinaryReader(stream); }
/// <summary> /// Parallel.ss contains a "test" function that evaluates three expressions in parallel, using the "parallel" primitive. /// Each one sleeps asynchronously 100 milliseconds before finishing. /// So at first the evaluation is not completed. /// After the wait, they all should be completed. /// The result of the test function is a list of the completion results of the three evaluations. /// This illustrates retrieving the async result after completion. /// </summary> public static void Main() { interp = Interpreter.New(new[] { "parallel.ss" }); var startTime = DateTime.Now; IAsyncResult res = interp.BeginEval(interp.Read("(test)"), null, null); Console.WriteLine("Completed: {0}", res.IsCompleted); res.AsyncWaitHandle.WaitOne(); Console.WriteLine("Completed: {0} in {1} ms", res.IsCompleted, (DateTime.Now - startTime).Milliseconds); Console.WriteLine("Result: {0}", ((AsyncResult<SchemeObject>)res).Result); Console.ReadLine(); }
private static bool isComplete; // = false; #endregion Fields #region Methods /// <summary> /// Async.ss uses System.Net.WebRequest to (asynchronously) fetch a web page (in the function get-content). /// Since it is asynchronous, it has not completed when the evaluation returns. /// After completion, the callback ShowResult is called, which displays the page contents. /// This allows the main method to proceed. /// While it is executing, get-content displays the number of bytes in each read that it does. /// </summary> public static void Main() { interp = Interpreter.New(new[] { "async.ss" }); IAsyncResult res = interp.BeginEval(interp.Read(@"(get-content ""http://microsoft.com"")"), ShowResult, null); Console.WriteLine("Completed: {0}", res.IsCompleted); while (isComplete == false) { Thread.Sleep(100); } Console.WriteLine("Completed: {0}", res.IsCompleted); Console.ReadLine(); }
public void Load(IInterpreter itpr, Env env) { var code = @" E = builtin E PI = builtin PI fnx square _ => builtin square _ fnx sqrt _ => builtin sqrt _ fnx sin _ => builtin sin _ fnx sin _ => builtin sin _ fnx cos _ => builtin cos _ fnx tan _ => builtin tan _ fnx asin _ => builtin asin _ fnx acos _ => builtin acos _ fnx atan _ => builtin atan _ fnx sinh _ => builtin sinh _ fnx cosh _ => builtin cosh _ fnx tanh _ => builtin tanh _ fnx sign _ => builtin sign _ fnx abs _ => builtin abs _ fnx exp _ => builtin exp _ fnx floor _ => builtin floor _ fnx ceiling _ => builtin ceiling _ fnx log _ => builtin log _ fnx log10 _ => builtin log10 _ fnx round _ => builtin round _ fn pow _ __ => builtin pow _ __ fnx max _ => builtin max _ fnx min _ => builtin min _ fnx sum _ => builtin sum _ fnx product _ => builtin product _ "; env.LockVariable = true; foreach (var item in code.Split('\n')) { itpr.Input(item); } env.LockVariable = false; }
public async Task <object> Load(IInterpreter interpreter, FrameContext context, PyModuleSpec spec) { var foundPath = (string)spec.LoaderState; var inFile = File.ReadAllText(foundPath); var moduleCode = await ByteCodeCompiler.Compile(inFile, new Dictionary <string, object>(), interpreter.Scheduler); await interpreter.CallInto(context, moduleCode, new object[0]); if (context.EscapedDotNetException != null) { throw context.EscapedDotNetException; } var moduleFrame = context.callStack.Pop(); var module = PyModule.Create(spec.Name); for (int local_i = 0; local_i < moduleFrame.LocalNames.Count; ++local_i) { module.__setattr__(moduleFrame.LocalNames[local_i], moduleFrame.Locals[local_i]); } return(module); }
public static async Task <PyString> __repr__(IInterpreter interpreter, FrameContext context, PyObject self) { var asList = (PyList)self; PyString retStr = PyString.Create("["); for (int i = 0; i < asList.list.Count; ++i) { var pyObj = asList.list[i] as PyObject; if (pyObj != null) { var __repr__ = pyObj.__getattribute__(PyClass.__REPR__); var functionToRun = __repr__ as IPyCallable; var returned = await functionToRun.Call(interpreter, context, new object[0]); if (returned != null) { var asPyString = (PyString)returned; retStr = (PyString)PyStringClass.__add__(retStr, asPyString); } } else if (asList.list[i] == null) { retStr = (PyString)PyStringClass.__add__(retStr, PyString.Create("null")); } else { retStr = (PyString)PyStringClass.__add__(retStr, PyString.Create(asList.list[i].ToString())); } // Appending commas except on last index if (i < asList.list.Count - 1) { retStr = (PyString)PyStringClass.__add__(retStr, PyString.Create(", ")); } } return((PyString)PyStringClass.__add__(retStr, PyString.Create("]"))); }
private void SetupSut() { _mockTeletype = new MockTeletype(); _mockTokeniser = new Mock <ITokeniser>(); _mockRunEnvironment = new Mock <IRunEnvironment>(); _mockProgramRepository = new Mock <IProgramRepository>(); _mockExecutor = new Mock <IExecutor>(); // Make default return true so executor returns back. _mockExecutor.SetReturnsDefault(true); var system = new ProgramLine(null, new List <IToken> { new Token("A") }); _mockTokeniser.Setup(mt => mt.Tokenise("SYSTEM")).Returns(system); _sut = new Interpreter( new TeletypeWithPosition(_mockTeletype), _mockTokeniser.Object, _mockRunEnvironment.Object, _mockProgramRepository.Object, _mockExecutor.Object); }
/// <summary> /// Constructor. /// </summary> /// <param name="interpreter">An IInterpreter instance.</param> /// <param name="definitionWord">A word, in which this DOES is used.</param> /// <param name="doesIndex">An index of the DOES word inside of the definitionWord. Used to find the first word, that belongs to the newly CREATEd word.</param> public DoesWord(IInterpreter interpreter, NonPrimitiveWord definitionWord, int doesIndex) : base(interpreter) { Name = "DOES"; IsControlWord = true; Action = () => { // The currently defined word should be the one thats CREATEd. var createdWord = Interpreter.WordBeingDefined as CreatedWord; if (createdWord == null) { throw new Exception("A CREATEd word expected."); } // Add the "get-data-field-start" word. createdWord.AddWord(new SingleCellIntegerLiteralWord(Interpreter, createdWord.DataFieldIndex)); // Copy runtime words to the CREATEd one. for (var i = _doesIndex + 1; i < _definitionWord.WordsCount; i++) { // TODO: Clone definitions words! createdWord.AddWord(_definitionWord.GetWord(i)); } // And use them for the further execution. createdWord.ActivateDefinedWords(); // Do not execute remaining words from the currently running word. _definitionWord.BreakExecution(); return(1); }; _definitionWord = definitionWord ?? throw new ArgumentNullException(nameof(definitionWord)); _doesIndex = doesIndex; }
public void Interpret <contextT>(contextT context) where contextT : Antlr4.Runtime.ParserRuleContext { StartInterpreation(context); // get the requested interpreter from the factory and set/update the needed properties IInterpreter <contextT> interpreter = Factory.GetInterpreter <contextT>(); interpreter.Controller = this; interpreter.Memory = Memory; try { interpreter.Run(context); } catch (Exception ex) { if (!HandleException(ex, context)) { throw; } } EndInterpreation(context); }
public MainWindow(IInterpreter theInterpreter, IParserFunction theParserFunction) { InitializeComponent(); m_interpreter = theInterpreter; m_parserFunction = theParserFunction; textSource.Focus(); m_baseTitle = this.Title + " - "; OpenLastIfPossible(); //textSource.Text = "; This is a comment\nprint(\"Hello World\")"; //textSource.Text = "; This is a comment\nset(text,\"Hello World\")\nprint(text)"; //textSource.Text = "; This is a comment\nset(text,\"Hello World\"\nprint(text)"; //textSource.Text = "; This is a comment\nprint(\"text)"; //textSource.Text = "; This is a comment\nset(sum,1+1)\nprint(sum)"; textSource.Text = "; Thi`s is a comment\n:myVar=3+10/2-3\nprint(:myVar)"; textSource.Text = "; Thi`s is a comment\n:myVar=3+10/2-3\nprint(:myVar)\nprint(3=3)\nprint(3=\"test\")\nprint(3=\"3\")"; //textSource.Text = "; This is a comment\nprint(3+10/2-3)"; // Temporary for now. Long term this would be IoC. m_interpreter.Initialize(); }
/// <summary> /// Метод выполняет команду, и возвращает результат в виде строки /// </summary> /// <param name="cmd">Команда с набором параметров</param> /// <returns></returns> public string ExecuteCommand(string cmd) { string empty_tmp = cmd.Trim(); if (empty_tmp.Equals(string.Empty)) return string.Empty; AddHistoryCmd(cmd); if (cmd.ToLower().IndexOf("exit") != -1) { this.curInterpreter = this; return String.Empty; } return this.curInterpreter.Exec(empty_tmp.Split(' ')); }
/// <summary> /// Добавить утилиту /// </summary> /// <param name="interpreter"></param> public void AppendInterpreter(IInterpreter interpreter) { this.listIntrp.Add(interpreter); }
private void MinimumInit() { this.curInterpreter = this; this.listIntrp = new List<IInterpreter>(); this.Name = "core"; LoadHistoryCmd(); }
private string cmd_start(string[] cmd) { int count = cmd.Count(); if (count > 1) { IInterpreter intrpr = this.listIntrp.Find((x) => x.Name.Equals(cmd[1])); if (intrpr != null) { this.curInterpreter = intrpr; return this.curInterpreter.DescriptionAtStartup; } return string.Format("Утилита \"{0}\" не найдена", cmd[1]); } return "У команды \"start\" должен быть как минимум 1 операнд"; }
public void AddInterpreter(IInterpreter interpreter) { Interpreters.Add(interpreter); }
public Messanger(IInterpreter messageInterpreter, IMessageSender messageSender) { _messageInterpreter = messageInterpreter; _messageSender = messageSender; }
public void MyTestInitialize() { this.interpreter = Interpreter.New(); }
public void MyTestInitialize() { this.interpreter = Interpreter.New(); sleepCounter = 0; }
internal TcpMessageClient(IPAddress hostAddress, int port, IInterpreter interpreter) : base(new TcpConnector(hostAddress, port, interpreter)) { }
public void RunCommand(IInterpreter<ConsoleContext<Dungeon>> interpreter) { interpreterPromise.SetResult(interpreter);//TODO try set result (maybe) }
internal TcpMessageServer(int port, int idBase, IInterpreter interpreter) : base(new TcpAcceptor(port, interpreter), idBase) { }
public InputReader(IInterpreter interpreter) { this.interpreter = interpreter; }
public void RunCommand(IInterpreter<ConsoleContext<Dungeon>> cmd) { ActivateDeactivateConsole(); interpreter.RunCommand(cmd); //input.WriteLineToInput(""); }
public PrintFunction(IParserFunction parserFunction, IInterpreter interpreter) { m_parserFunction = parserFunction; m_interpreter = interpreter; }
public void SetUp() { TimeLanguageConsole.Writer = new StringWriter(); realInterpreter = TimeLanguageConsole.Interpreter; }
static BluetoothHandler() { interpreter = new Interpreter(); }
public TasksController(ITaskHandler taskHandler, IInterpreter interpreter) { this.taskHandler = taskHandler; this.interpreter = interpreter; }
public void InitBuiltin(IInterpreter itpr, IStandardIo io, Env env) { _itpr = itpr; _env = env; io.Out.WriteLine("Builtin :: Loading..."); Init(); var modules = new IModule[] { new CoreModule(), new MathModule(), }; foreach (var item in modules) { io.Out.WriteLine($"Builtin :: {item.Name}"); AddModule(item); } var builtinFuncs = new Fun[] { new BuiltinFun(EvalBuiltin) { FunName = "builtin", Limit = false, Args = new List<string>() { "name", "args" } }, new BuiltinFun(EvalType) { FunName = "type", Limit = true, Args = new List<string>() { "t" } }, new BuiltinFun(EvalLoad) { FunName = "load", Limit = true, Args = new List<string>() { "name" } }, new LazyFun(EvalLazy) { FunName = "lazy" }, }; foreach (var item in builtinFuncs) { item.RegisterToEnv(env); } var code = @" load Core "; env.LockVariable = true; foreach (var item in code.Split('\n')) { itpr.Input(item); } env.LockVariable = false; io.Out.WriteLine("Builtin :: OK"); }
public ConfigBuilder AddInterpreter(IInterpreter interpreter) { component.AddInterpreter(interpreter); return this; }