From 8c3b966c1c85afb987cb4537812434fd98270148 Mon Sep 17 00:00:00 2001 From: bnewbold Date: Mon, 25 Apr 2016 18:34:23 -0400 Subject: rust: add basic file loading support --- rust/spectrum.rs | 28 ++++++++++++++++++++++++++-- 1 file changed, 26 insertions(+), 2 deletions(-) (limited to 'rust') diff --git a/rust/spectrum.rs b/rust/spectrum.rs index 097de53..3ab07b0 100644 --- a/rust/spectrum.rs +++ b/rust/spectrum.rs @@ -8,7 +8,9 @@ */ use std::io; -use std::io::Write; +use std::io::{Write, Read}; +use std::fs::File; +use std::path::Path; use std::collections::HashMap; //////////// Types and Constants @@ -646,7 +648,7 @@ fn scheme_eval(ast: &SchemeExpr, //////////// Top-Level Program -fn repl<'b>(verbose: bool, top_env: &mut HashMap) { +fn repl(verbose: bool, top_env: &mut HashMap) { let stdin = io::stdin(); let mut stdout = io::stdout(); @@ -707,10 +709,32 @@ fn repl<'b>(verbose: bool, top_env: &mut HashMap) { } } +fn import_file(fpath: &Path, top_env: &mut HashMap) -> Result<(), String> { + + let mut raw_bytes: Vec = Vec::new(); + + let mut f = File::open(fpath) + .expect(&format!("couldn't open file: {}", &fpath.to_str().unwrap())); + f.read_to_end(&mut raw_bytes) + .expect(&format!("couldn't read file: {}", &fpath.to_str().unwrap())); + let contents = String::from_utf8(raw_bytes) + .expect(&format!("UTF-8 decode error reading file: {}", &fpath.to_str().unwrap())); + + let tokens = try!(scheme_tokenize(&contents)); + let (ast_list, _) = try!(scheme_parse(&tokens, 0)); + for ast in ast_list.iter() { + try!(scheme_eval(&ast, top_env)); + }; + Ok(()) +} + fn main() { let mut top_env = HashMap::::new(); + let prelude_path = Path::new("../prelude.scm"); + import_file(&prelude_path, &mut top_env).unwrap(); + // For now only REPL mode is implemented repl(true, &mut top_env); } -- cgit v1.2.3