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::BufRead;
use std::process;
use std::cell::RefCell;
use std::collections::HashMap;
use tokenizer::tokenize;
use parser::{parse, ParseResult};
@ -11,12 +13,32 @@ mod tokenizer;
mod parser;
mod evaluate;
type BinopTable = HashMap<&'static str, i32>;
thread_local!(static BINOP_TABLE: RefCell<BinopTable> = RefCell::new(HashMap::new()));
fn main() {
println!("Unnamed language 0.01");
init_binop_table();
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() {
let stdin = io::stdin();
let mut stdout = io::stdout();

View File

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