From ce0d8328db9fcb7977fb70394849959e96337e4b Mon Sep 17 00:00:00 2001 From: Elia Perantoni Date: Thu, 25 Mar 2021 17:40:33 +0100 Subject: [PATCH] input function --- src/interp/mod.rs | 7 +++++++ src/interp/native.rs | 23 +++++++++++++++++++++++ src/interp/test.rs | 3 ++- 3 files changed, 32 insertions(+), 1 deletion(-) diff --git a/src/interp/mod.rs b/src/interp/mod.rs index 098163e..1e8cfcb 100644 --- a/src/interp/mod.rs +++ b/src/interp/mod.rs @@ -65,6 +65,13 @@ impl Interpreter { receiver: None, })); + self.get_env_mut().def("input".to_string(), Value::Func(Func::Native { + name: "input".to_string(), + params: None, + func: input, + receiver: None, + })); + self.get_env_mut().def("exit".to_string(), Value::Func(Func::Native { name: "exit".to_string(), params: Some(1), diff --git a/src/interp/native.rs b/src/interp/native.rs index e24593f..7c59b11 100644 --- a/src/interp/native.rs +++ b/src/interp/native.rs @@ -1,5 +1,7 @@ use std::cell::RefCell; use std::collections::HashMap; +use std::io; +use std::io::{BufRead, Write}; use std::process; use std::rc::Rc; @@ -25,6 +27,27 @@ pub fn print(int: &mut Interpreter, args: Vec) -> Value { Value::Nil } +pub fn input(int: &mut Interpreter, mut args: Vec) -> Value { + if int.collector.is_some() { + panic!("called input in testing"); + } + + let msg = match args.remove(0) { + Value::String(msg) => msg, + _ => panic!("expected arg to be string") + }; + + print!("{}", msg); + io::stdout().flush().unwrap(); + + let mut buf = String::new(); + + let stdin = io::stdin(); + stdin.lock().read_line(&mut buf).unwrap(); + + Value::String(buf) +} + pub fn exit(_: &mut Interpreter, mut args: Vec) -> Value { let code = match args.remove(0) { Value::Num(num) if num.trunc() == num => num as i32, diff --git a/src/interp/test.rs b/src/interp/test.rs index 78c1993..a4f790a 100644 --- a/src/interp/test.rs +++ b/src/interp/test.rs @@ -1,9 +1,10 @@ +use std::fs; + use crate::lexer::new as new_lexer; use crate::parser::Parser; use super::*; use super::value::Value; -use std::fs; fn output(source: &str) -> String { let lexer = new_lexer(source.to_owned());