diff --git a/src/lexer/mod.rs b/src/lexer/mod.rs index 49b3327..d35a816 100644 --- a/src/lexer/mod.rs +++ b/src/lexer/mod.rs @@ -86,10 +86,10 @@ impl Display for TokenType { TokenType::True => "true", TokenType::False => "false", TokenType::Return => "return", - _ => { - eprintln!("{:?}", self); - unreachable!() - } + TokenType::EOF => "EOF", + TokenType::Illegal => "illegal", + TokenType::Ident => "ident", + TokenType::Int => "int", }) } } diff --git a/src/parser/ast/mod.rs b/src/parser/ast/mod.rs index fd878e3..fb491a9 100644 --- a/src/parser/ast/mod.rs +++ b/src/parser/ast/mod.rs @@ -601,11 +601,10 @@ impl FunctionLiteral { impl Display for FunctionLiteral { fn fmt(&self, f: &mut Formatter) -> FmtResult { f.write_fmt(format_args!( - "{} {}({}) {}", - self.token.name.to_string(), - self.token.literal.as_ref().unwrap(), - self.parameters.iter().join(","), - "" + "{}({}) {{ {} }}", + self.token.name, + self.parameters.iter().join(", "), + self.body )) } } diff --git a/src/parser/mod.rs b/src/parser/mod.rs index c702c9a..b1412c3 100644 --- a/src/parser/mod.rs +++ b/src/parser/mod.rs @@ -33,7 +33,7 @@ lazy_static! { pub struct Parser<'a> { lexer: Peekable>, - errors: Vec, + pub errors: Vec, prefix_parse_fns: HashMap, infix_parse_fns: HashMap, } diff --git a/src/repl.rs b/src/repl.rs index 8875260..efc4b8e 100644 --- a/src/repl.rs +++ b/src/repl.rs @@ -1,5 +1,8 @@ -use crate::{lexer::Lexer, parser::Parser}; -use std::io::{self, BufRead, Write}; +use crate::{ + lexer::Lexer, + parser::{Error as ParserError, Parser}, +}; +use std::io::{self, BufRead, Result as IoResult, Write}; const PROMPT: &[u8] = b">> "; @@ -18,19 +21,28 @@ fn start(mut ip: R, mut out: W) { out.flush().unwrap(); let mut s = String::new(); ip.read_line(&mut s).unwrap(); + let tokens = Lexer::new(&s); - - for token in tokens.clone() { - println!("{:?}", token); - } - let mut parser = Parser::new(tokens); - let program = parser.parse_program(); - - match program { - Some(stmts) => println!("{}", stmts), - None => (), + if !parser.errors.is_empty() { + print_parser_errors(&mut out, &parser.errors).unwrap(); + continue; } + match program { + Some(prg) => { + for stmt in &prg.statements { + out.write_fmt(format_args!("{}\n", stmt)).unwrap(); + } + } + None => (), + }; } } + +fn print_parser_errors(mut out: W, errors: &[ParserError]) -> IoResult<()> { + for error in errors { + out.write_fmt(format_args!("\t{}\n", error)).unwrap(); + } + out.flush() +}