2023-06-16 12:58:06 -07:00
|
|
|
use crate::parser::Expression;
|
2023-06-14 14:36:58 -07:00
|
|
|
use std::collections::HashMap;
|
|
|
|
|
|
|
|
#[derive(Debug)]
|
|
|
|
pub struct Context {
|
2023-06-16 12:58:06 -07:00
|
|
|
history: Vec<Expression>,
|
|
|
|
variables: HashMap<String, Expression>
|
2023-06-14 14:36:58 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
impl Context {
|
|
|
|
pub fn new() -> Context {
|
|
|
|
Context{ history: Vec::new(), variables: HashMap::new() }
|
|
|
|
}
|
|
|
|
|
2023-06-16 12:58:06 -07:00
|
|
|
pub fn push_hist(&mut self, t: Expression) { self.history.push(t); }
|
2023-06-17 22:15:58 -07:00
|
|
|
pub fn push_var(&mut self, s: String, t: Expression) -> Result<(), ()> {
|
|
|
|
if self.valid_varible(&s) {
|
|
|
|
self.variables.insert(s, t);
|
|
|
|
return Ok(());
|
|
|
|
} else { return Err(()); }
|
|
|
|
}
|
2023-06-14 14:36:58 -07:00
|
|
|
pub fn del_var(&mut self, s: &String) { self.variables.remove(s); }
|
|
|
|
|
2023-06-16 12:58:06 -07:00
|
|
|
pub fn get_variable(&self, s: &String) -> Option<Expression> {
|
|
|
|
let v: Option<&Expression>;
|
2023-06-14 14:36:58 -07:00
|
|
|
if s == "ans" {
|
|
|
|
v = self.history.last();
|
|
|
|
} else {
|
2023-06-14 16:15:51 -07:00
|
|
|
v = self.variables.get(s);
|
2023-06-14 14:36:58 -07:00
|
|
|
}
|
|
|
|
if v.is_some() { Some(v.unwrap().clone()) } else { None }
|
|
|
|
}
|
2023-06-17 22:15:58 -07:00
|
|
|
|
|
|
|
pub fn valid_varible(&self, s: &str) -> bool {
|
|
|
|
return match s {
|
|
|
|
"ans" => false,
|
|
|
|
_ => true
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-08-02 15:36:55 -07:00
|
|
|
pub fn get_variables(&self) -> &HashMap<String, Expression> {
|
|
|
|
return &self.variables
|
|
|
|
}
|
|
|
|
|
2023-06-14 14:36:58 -07:00
|
|
|
}
|