schala/src/parser.rs

69 lines
1.4 KiB
Rust
Raw Normal View History

2015-12-25 02:03:11 -08:00
use std::iter::Peekable;
use std::slice::Iter;
2015-12-24 22:01:59 -08:00
2015-12-25 02:03:11 -08:00
use tokenizer::Token;
2015-12-24 22:01:59 -08:00
#[derive(Debug)]
enum AST {
BinOp(Box<AST>, Box<AST>, Box<AST>),
Number(f64),
Name(String),
}
#[derive(Debug)]
pub struct ParseError {
err: String
}
pub type ParseResult = Result<AST, ParseError>;
2015-12-25 02:03:11 -08:00
/* grammar
2015-12-24 22:01:59 -08:00
2015-12-25 02:03:11 -08:00
expr : term ((PLUS|MIMUS) term)*
term : factor ((MUL | DIV) factor)*
factor : NUM | LPAREN expr RPAREN
*/
struct Parser<'a> {
tokens: Peekable<Iter<'a, Token>>
}
macro_rules! expect {
($tok:expr, $self_:ident) => {
match $self_.tokens.next() {
Some(next) if *next == $tok => (),
Some(next) => {
let err = format!("Expected {:?} but got {:?}", $tok, next);
return Err(ParseError { err: err });
},
None => {
let err = format!("Expected {:?} but got end of input", $tok);
return Err(ParseError { err: err });
}
}
}
}
2015-12-25 02:03:11 -08:00
impl<'a> Parser<'a> {
fn parse(&mut self) -> ParseResult {
let r = self.expr();
expect!(Token::Separator, self);
expect!(Token::EOF, self);
2015-12-25 02:03:11 -08:00
r
}
fn expr(&mut self) -> ParseResult {
self.tokens.next();
return Ok(AST::Number(5.0));
}
}
pub fn parse(input: Vec<Token>) -> ParseResult {
let mut iter = input.iter().peekable();
let mut parser = Parser { tokens: iter };
return parser.parse();
2015-12-24 22:01:59 -08:00
}