Move to global precedence table

This commit is contained in:
greg 2015-08-06 00:53:50 -07:00
parent 7d6f946e22
commit 56b338a6a8
2 changed files with 31 additions and 13 deletions

View File

@ -2,6 +2,8 @@ use std::io;
use std::io::Write; use std::io::Write;
use std::io::BufRead; use std::io::BufRead;
use std::process; use std::process;
use std::cell::RefCell;
use std::collections::HashMap;
use tokenizer::tokenize; use tokenizer::tokenize;
use parser::{parse, ParseResult}; use parser::{parse, ParseResult};
@ -11,12 +13,32 @@ mod tokenizer;
mod parser; mod parser;
mod evaluate; mod evaluate;
type BinopTable = HashMap<&'static str, i32>;
thread_local!(static BINOP_TABLE: RefCell<BinopTable> = RefCell::new(HashMap::new()));
fn main() { fn main() {
println!("Unnamed language 0.01"); println!("Unnamed language 0.01");
init_binop_table();
repl(); repl();
} }
fn init_binop_table() {
BINOP_TABLE.with(|hm| {
macro_rules! insert_precedence {
($op:expr, $prec:expr) => { hm.borrow_mut().insert($op, $prec) }
}
insert_precedence!("+", 20);
insert_precedence!("-", 20);
insert_precedence!("*", 40);
insert_precedence!("/", 40);
insert_precedence!("==", 10);
insert_precedence!(">", 15);
insert_precedence!("<", 15);
insert_precedence!("<=>", 15);
});
}
fn repl() { fn repl() {
let stdin = io::stdin(); let stdin = io::stdin();
let mut stdout = io::stdout(); let mut stdout = io::stdout();

View File

@ -1,6 +1,5 @@
use std::slice::Iter; use std::slice::Iter;
use std::iter::Peekable; use std::iter::Peekable;
use std::collections::HashMap;
use tokenizer::{Token, Kw}; use tokenizer::{Token, Kw};
use tokenizer::Token::*; use tokenizer::Token::*;
@ -233,22 +232,19 @@ fn binop_rhs(precedence: i32, lhs: AST, tokens: &mut Tokens) -> ParseResult {
} }
fn get_binop_precedence(token: &Token) -> Option<i32> { fn get_binop_precedence(token: &Token) -> Option<i32> {
let identifier_str = match token { let identifier_str: &String = match token {
&Identifier(ref s) => s, &Identifier(ref s) => s,
_ => return None _ => return None
}; };
match &identifier_str[..] { let output =
"+" => Some(20), ::BINOP_TABLE.with(|hm| {
"-" => Some(20), let prec_table = hm.borrow();
"*" => Some(30), let val: Option<i32> = prec_table.get(&identifier_str[..]).map(|i| *i);
"/" => Some(30), val
"==" => Some(10), });
">" => Some(15),
"<" => Some(15), output
"<=>" => Some(15),
_ => None
}
} }
fn simple_expression(tokens: &mut Tokens) -> ParseResult { fn simple_expression(tokens: &mut Tokens) -> ParseResult {