Skip to content

Commit

Permalink
input function
Browse files Browse the repository at this point in the history
  • Loading branch information
eliaperantoni committed Mar 25, 2021
1 parent 1a36974 commit ce0d832
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 1 deletion.
7 changes: 7 additions & 0 deletions src/interp/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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),
Expand Down
23 changes: 23 additions & 0 deletions src/interp/native.rs
Original file line number Diff line number Diff line change
@@ -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;

Expand All @@ -25,6 +27,27 @@ pub fn print(int: &mut Interpreter, args: Vec<Value>) -> Value {
Value::Nil
}

pub fn input(int: &mut Interpreter, mut args: Vec<Value>) -> 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>) -> Value {
let code = match args.remove(0) {
Value::Num(num) if num.trunc() == num => num as i32,
Expand Down
3 changes: 2 additions & 1 deletion src/interp/test.rs
Original file line number Diff line number Diff line change
@@ -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());
Expand Down

0 comments on commit ce0d832

Please sign in to comment.