2025-10-03 19:07:12 +02:00
|
|
|
use std::collections::HashMap;
|
|
|
|
|
|
|
|
|
|
use crate::{
|
|
|
|
|
frontend::{source_registry::SourceSlice, tokens::LiteralValue},
|
2025-10-04 21:05:00 +02:00
|
|
|
result::{runtime_error, LoxResult},
|
2025-10-03 19:07:12 +02:00
|
|
|
};
|
|
|
|
|
|
2025-10-06 18:52:32 +02:00
|
|
|
#[derive(Debug, Clone, PartialEq)]
|
2025-10-04 21:05:00 +02:00
|
|
|
pub struct EnvironmentStack {
|
|
|
|
|
stack: Vec<HashMap<String, LiteralValue>>,
|
2025-10-03 19:07:12 +02:00
|
|
|
}
|
|
|
|
|
|
2025-10-04 21:05:00 +02:00
|
|
|
impl EnvironmentStack {
|
2025-10-03 19:07:12 +02:00
|
|
|
pub fn new() -> Self {
|
2025-10-04 21:05:00 +02:00
|
|
|
EnvironmentStack {
|
|
|
|
|
stack: vec![HashMap::new()],
|
2025-10-03 19:07:12 +02:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2025-10-04 21:05:00 +02:00
|
|
|
pub fn push_new_scope(&mut self) {
|
|
|
|
|
self.stack.push(HashMap::new());
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
pub fn pop_scope(&mut self) {
|
|
|
|
|
self.stack.pop();
|
2025-10-03 19:07:12 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
pub fn get(&self, name: &str) -> LoxResult<LiteralValue> {
|
2025-10-04 21:05:00 +02:00
|
|
|
let size = self.stack.len();
|
|
|
|
|
|
|
|
|
|
for i in (0..size).rev() {
|
|
|
|
|
if let Some(value) = self.stack[i].get(name) {
|
|
|
|
|
return Ok(value.clone());
|
|
|
|
|
}
|
2025-10-03 19:07:12 +02:00
|
|
|
}
|
2025-10-04 21:05:00 +02:00
|
|
|
runtime_error(
|
|
|
|
|
SourceSlice::default(), // todo change this to the actual source slice
|
|
|
|
|
format!("Undefined variable '{}'", name),
|
|
|
|
|
)
|
2025-10-03 19:07:12 +02:00
|
|
|
}
|
|
|
|
|
|
2025-10-06 18:52:32 +02:00
|
|
|
pub fn declare(&mut self, name: String, value: LiteralValue) -> LoxResult<LiteralValue> {
|
|
|
|
|
self.stack.last_mut().unwrap().insert(name, value.clone());
|
|
|
|
|
Ok(value)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
pub fn set(&mut self, name: String, value: LiteralValue) -> LoxResult<LiteralValue> {
|
|
|
|
|
let size = self.stack.len();
|
|
|
|
|
|
|
|
|
|
for i in (0..size).rev() {
|
|
|
|
|
if let Some(_) = self.stack[i].get(&name) {
|
|
|
|
|
let mut founded = false;
|
|
|
|
|
self.stack[i].entry(name.clone()).and_modify(|v| {
|
|
|
|
|
*v = value.clone();
|
|
|
|
|
founded = true;
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
if founded {
|
|
|
|
|
return Ok(value);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
runtime_error(
|
|
|
|
|
SourceSlice::default(), // todo change this to the actual source slice
|
|
|
|
|
format!("Undefined variable '{}'", name),
|
|
|
|
|
)
|
2025-10-03 19:07:12 +02:00
|
|
|
}
|
|
|
|
|
}
|