Updated REPL loop to print back string-ified AST. Parser Complete!
This commit is contained in:
parent
0833ba3448
commit
f3f50eed47
|
@ -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",
|
||||
})
|
||||
}
|
||||
}
|
||||
|
|
|
@ -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
|
||||
))
|
||||
}
|
||||
}
|
||||
|
|
|
@ -33,7 +33,7 @@ lazy_static! {
|
|||
|
||||
pub struct Parser<'a> {
|
||||
lexer: Peekable<Lexer<'a>>,
|
||||
errors: Vec<Error>,
|
||||
pub errors: Vec<Error>,
|
||||
prefix_parse_fns: HashMap<TokenType, PrefixParseFn>,
|
||||
infix_parse_fns: HashMap<TokenType, InfixParseFn>,
|
||||
}
|
||||
|
|
36
src/repl.rs
36
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<R: BufRead, W: Write>(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<W: Write>(mut out: W, errors: &[ParserError]) -> IoResult<()> {
|
||||
for error in errors {
|
||||
out.write_fmt(format_args!("\t{}\n", error)).unwrap();
|
||||
}
|
||||
out.flush()
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue
Block a user