schala/src/parser.rs

93 lines
2.2 KiB
Rust
Raw Normal View History

2015-12-25 02:03:11 -08:00
use std::iter::Peekable;
use std::slice::Iter;
use std::vec::IntoIter;
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)]
pub enum AST {
2015-12-24 22:01:59 -08:00
BinOp(Box<AST>, Box<AST>, Box<AST>),
Number(f64),
Name(String),
}
#[derive(Debug)]
pub struct ParseError {
err: String
}
pub type ParseResult<T> = Result<T, ParseError>;
2015-12-24 22:01:59 -08:00
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 {
tokens: Peekable<IntoIter<Token>>
2015-12-25 02:03:11 -08:00
}
impl Parser {
fn next(&mut self) -> Option<Token> {
self.tokens.next()
}
fn lookahead(&mut self) -> Option<&Token> {
self.tokens.peek()
}
}
impl Parser {
fn expect(&mut self, expected: Token) -> ParseResult<()> {
match self.next() {
Some(ref next) if *next == expected => Ok(()),
Some(next) => {
let err = format!("Expected {:?} but got {:?}", expected, next);
return Err(ParseError { err: err });
},
None => {
let err = format!("Expected {:?} but got end of input", expected);
return Err(ParseError { err: err });
}
}
}
2015-12-25 02:03:11 -08:00
fn expect_identifier(&mut self, identifier_str: &str) -> ParseResult<()> {
use tokenizer::Token::*;
match self.next() {
Some(Identifier(ref s)) if s == identifier_str => Ok(()),
Some(next) => {
let err = format!("Expected identifier `{}` but got {:?}", identifier_str, next);
Err(ParseError { err: err })
}
None => {
let err = format!("Expected identifier `{}` but got end of input", identifier_str);
Err(ParseError { err: err })
}
}
}
fn parse(&mut self) -> ParseResult<AST> {
2015-12-25 02:03:11 -08:00
let r = self.expr();
try!(self.expect(Token::Separator));
try!(self.expect(Token::EOF));
2015-12-25 02:03:11 -08:00
r
}
fn expr(&mut self) -> ParseResult<AST> {
self.next();
2015-12-25 02:03:11 -08:00
return Ok(AST::Number(5.0));
}
}
pub fn parse(input: Vec<Token>) -> ParseResult<AST> {
let mut iter = input.into_iter().peekable();
2015-12-25 02:03:11 -08:00
let mut parser = Parser { tokens: iter };
return parser.parse();
2015-12-24 22:01:59 -08:00
}