use std::collections::{BTreeMap, HashMap};
use crate::value::Value;
pub type ModuleId = usize;
pub const ROOT_MODULE: ModuleId = 0;
pub struct Globals {
values: Vec<Option<Value>>,
names: Vec<String>,
builtins: HashMap<String, u16>,
modules: Vec<HashMap<String, u16>>,
builtin_slots: Vec<bool>,
}
impl Default for Globals {
fn default() -> Self {
Globals::new()
}
}
impl Globals {
pub fn new() -> Globals {
Globals {
values: Vec::new(),
names: Vec::new(),
builtins: HashMap::new(),
modules: vec![HashMap::new()],
builtin_slots: Vec::new(),
}
}
pub fn new_module(&mut self) -> ModuleId {
self.modules.push(HashMap::new());
self.modules.len() - 1
}
pub fn slot_for(&mut self, module: ModuleId, name: &str) -> Option<u16> {
if let Some(slot) = self.modules[module].get(name) {
return Some(*slot);
}
if let Some(slot) = self.builtins.get(name) {
return Some(*slot);
}
self.fresh_slot(module, name)
}
pub fn slot_for_declaration(&mut self, module: ModuleId, name: &str) -> Option<u16> {
if let Some(slot) = self.modules[module].get(name) {
return Some(*slot);
}
self.fresh_slot(module, name)
}
fn fresh_slot(&mut self, module: ModuleId, name: &str) -> Option<u16> {
let slot = u16::try_from(self.values.len()).ok()?;
self.values.push(None);
self.names.push(name.to_string());
self.builtin_slots.push(false);
self.modules[module].insert(name.to_string(), slot);
Some(slot)
}
pub fn slot_for_builtin(&mut self, name: &str) -> Option<u16> {
if let Some(slot) = self.builtins.get(name) {
return Some(*slot);
}
let slot = u16::try_from(self.values.len()).ok()?;
self.values.push(None);
self.names.push(name.to_string());
self.builtin_slots.push(true);
self.builtins.insert(name.to_string(), slot);
Some(slot)
}
pub fn define(&mut self, slot: u16, value: Value) {
self.values[slot as usize] = Some(value);
}
pub fn get(&self, slot: u16) -> Option<&Value> {
self.values[slot as usize].as_ref()
}
pub fn assign(&mut self, slot: u16, value: Value) -> bool {
if self.builtin_slots[slot as usize] {
return false;
}
let cell = &mut self.values[slot as usize];
if cell.is_none() {
return false;
}
*cell = Some(value);
true
}
pub fn builtin_count(&self) -> usize {
self.builtins.len()
}
pub fn contains(&self, name: &str) -> bool {
self.builtins.contains_key(name) || self.modules[ROOT_MODULE].contains_key(name)
}
pub fn exports(&self, module: ModuleId) -> BTreeMap<String, Value> {
self.modules[module]
.iter()
.filter_map(|(name, slot)| {
self.values[*slot as usize]
.clone()
.map(|value| (name.clone(), value))
})
.collect()
}
pub fn name(&self, slot: u16) -> &str {
&self.names[slot as usize]
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn slots_are_stable_and_reused_per_name() {
let mut globals = Globals::new();
let a = globals.slot_for(ROOT_MODULE, "a").expect("a slot");
let b = globals.slot_for(ROOT_MODULE, "b").expect("a slot");
assert_ne!(a, b);
assert_eq!(globals.slot_for(ROOT_MODULE, "a"), Some(a));
assert_eq!(globals.name(a), "a");
}
#[test]
fn two_modules_can_define_the_same_name() {
let mut globals = Globals::new();
let other = globals.new_module();
let root_total = globals.slot_for(ROOT_MODULE, "total").expect("a slot");
let other_total = globals.slot_for(other, "total").expect("a slot");
assert_ne!(root_total, other_total);
globals.define(root_total, Value::Int(1));
globals.define(other_total, Value::Int(2));
assert_eq!(
globals.get(root_total).map(Value::repr),
Some("1".to_string())
);
assert_eq!(
globals.get(other_total).map(Value::repr),
Some("2".to_string())
);
assert_eq!(globals.slot_for(ROOT_MODULE, "total"), Some(root_total));
assert_eq!(globals.slot_for(other, "total"), Some(other_total));
}
#[test]
fn a_builtin_resolves_the_same_from_every_module() {
let mut globals = Globals::new();
crate::builtins::register(&mut globals);
let other = globals.new_module();
assert_eq!(
globals.slot_for(ROOT_MODULE, "print"),
globals.slot_for(other, "print")
);
let slot = globals.slot_for(ROOT_MODULE, "print").expect("a slot");
globals.define(slot, Value::Int(5));
assert_eq!(globals.get(slot).map(Value::repr), Some("5".to_string()));
}
#[test]
fn contains_reports_membership_without_creating_a_slot() {
let mut globals = Globals::new();
assert!(!globals.contains("print"));
crate::builtins::register(&mut globals);
assert!(globals.contains("print"));
assert!(!globals.contains("definitely_not_a_builtin"));
}
#[test]
fn a_slot_starts_undefined() {
let mut globals = Globals::new();
let slot = globals.slot_for(ROOT_MODULE, "x").expect("a slot");
assert!(globals.get(slot).is_none());
assert!(!globals.assign(slot, Value::Int(1)));
globals.define(slot, Value::Int(1));
assert!(globals.get(slot).is_some());
assert!(globals.assign(slot, Value::Int(2)));
}
}