1
0
Fork 0
This repository has been archived on 2025-03-30. You can view files and clone it, but you cannot make any changes to it's state, such as pushing and creating new issues, pull requests or comments.
compiler-course/src/compiler/symtab.rs

61 lines
1.7 KiB
Rust
Raw Normal View History

2025-02-04 14:10:16 +02:00
use crate::compiler::variable::Value;
use std::collections::HashMap;
#[derive(Default)]
pub struct SymTab<'source> {
tables: Vec<HashMap<&'source str, Value>>,
}
impl<'source> SymTab<'source> {
pub fn get(&mut self, symbol: &str) -> &mut Value {
for i in (0..self.tables.len()).rev() {
if self.tables[i].contains_key(symbol) {
return self.tables[i].get_mut(symbol).unwrap();
}
}
panic!("No symbol {} found!", symbol);
}
pub fn new() -> SymTab<'source> {
let globals = HashMap::from([
2025-02-03 23:04:36 +02:00
("+", Value::Func(Value::add)),
("*", Value::Func(Value::mul)),
("-", Value::Func(Value::sub)),
("/", Value::Func(Value::div)),
("%", Value::Func(Value::rem)),
("==", Value::Func(Value::eq)),
("!=", Value::Func(Value::neq)),
("<", Value::Func(Value::lt)),
("<=", Value::Func(Value::le)),
(">", Value::Func(Value::gt)),
(">=", Value::Func(Value::ge)),
("not", Value::Func(Value::not)),
("neg", Value::Func(Value::neg)),
]);
SymTab {
tables: vec![globals],
}
}
pub fn push_level(&mut self) {
self.tables.push(HashMap::new());
}
pub fn remove_level(&mut self) {
self.tables.pop();
}
pub fn insert(&mut self, name: &'source str, val: Value) {
if self
.tables
.last_mut()
.expect("Symbols table should never be empty!")
.insert(name, val)
.is_some()
{
panic!("Variable {} already defined in this scope!", name)
}
}
}