use std::cell::RefCell;
use std::collections::BTreeMap;
use std::rc::Rc;
use crate::chunk::Chunk;
pub trait Output {
fn write(&mut self, text: &str);
fn write_error(&mut self, text: &str);
fn request_exit(&mut self, code: i32);
}
pub trait Input {
fn read_line(&mut self) -> Option<String>;
}
pub struct EmptyInput;
impl Input for EmptyInput {
fn read_line(&mut self) -> Option<String> {
None
}
}
pub type BuiltinFn = fn(&mut dyn Output, &mut dyn Input, Vec<Value>) -> Result<Value, String>;
pub trait System {
fn read_file(&mut self, path: &str) -> Result<String, String>;
fn write_file(&mut self, path: &str, contents: &str) -> Result<(), String>;
fn file_exists(&mut self, path: &str) -> bool;
fn arguments(&self) -> Vec<String>;
}
pub struct NoSystem;
impl NoSystem {
const REFUSAL: &'static str = "this program is running where there is no file system";
}
impl System for NoSystem {
fn read_file(&mut self, _path: &str) -> Result<String, String> {
Err(NoSystem::REFUSAL.to_string())
}
fn write_file(&mut self, _path: &str, _contents: &str) -> Result<(), String> {
Err(NoSystem::REFUSAL.to_string())
}
fn file_exists(&mut self, _path: &str) -> bool {
false
}
fn arguments(&self) -> Vec<String> {
Vec::new()
}
}
pub type SystemFn = fn(&mut dyn System, Vec<Value>) -> Result<Value, String>;
pub struct CompiledFunction {
pub name: Option<String>,
pub arity: usize,
pub chunk: Chunk,
pub file: Option<Rc<String>>,
}
pub enum Upvalue {
Open(usize),
Closed(Value),
}
pub struct Closure {
pub function: Rc<CompiledFunction>,
pub upvalues: Vec<Rc<RefCell<Upvalue>>>,
}
pub struct ArrayBody(RefCell<Vec<Value>>);
impl ArrayBody {
pub fn new(items: Vec<Value>) -> ArrayBody {
ArrayBody(RefCell::new(items))
}
}
impl std::ops::Deref for ArrayBody {
type Target = RefCell<Vec<Value>>;
fn deref(&self) -> &Self::Target {
&self.0
}
}
pub struct MapBody(RefCell<BTreeMap<String, Value>>);
impl MapBody {
pub fn new(entries: BTreeMap<String, Value>) -> MapBody {
MapBody(RefCell::new(entries))
}
}
impl std::ops::Deref for MapBody {
type Target = RefCell<BTreeMap<String, Value>>;
fn deref(&self) -> &Self::Target {
&self.0
}
}
fn release(mut work: Vec<Value>) {
while let Some(value) = work.pop() {
match value {
Value::Array(rc) => {
if let Ok(body) = Rc::try_unwrap(rc) {
work.append(&mut body.borrow_mut());
}
}
Value::Map(rc) => {
if let Ok(body) = Rc::try_unwrap(rc) {
let mut entries = body.borrow_mut();
work.extend(std::mem::take(&mut *entries).into_values());
}
}
Value::Closure(rc) => {
if let Ok(mut closure) = Rc::try_unwrap(rc) {
work.extend(closed_captures(&mut closure.upvalues));
}
}
_ => {}
}
}
}
fn closed_captures(upvalues: &mut Vec<Rc<RefCell<Upvalue>>>) -> Vec<Value> {
std::mem::take(upvalues)
.into_iter()
.filter_map(|slot| match Rc::try_unwrap(slot) {
Ok(upvalue) => match upvalue.into_inner() {
Upvalue::Closed(inner) => Some(inner),
Upvalue::Open(_) => None,
},
Err(_) => None,
})
.collect()
}
impl Drop for ArrayBody {
fn drop(&mut self) {
release(std::mem::take(&mut *self.borrow_mut()));
}
}
impl Drop for MapBody {
fn drop(&mut self) {
release(
std::mem::take(&mut *self.borrow_mut())
.into_values()
.collect(),
);
}
}
impl Drop for Closure {
fn drop(&mut self) {
release(closed_captures(&mut self.upvalues));
}
}
#[derive(Clone)]
pub struct Builtin {
pub name: &'static str,
pub func: NativeFn,
}
#[derive(Clone, Copy)]
pub enum NativeFn {
Plain(BuiltinFn),
System(SystemFn),
}
pub type HostFn = fn(Vec<Value>) -> Result<crate::builtins::HostTask, String>;
#[derive(Clone)]
pub struct HostBuiltin {
pub name: &'static str,
pub func: HostFn,
}
#[derive(Clone)]
pub enum Value {
Int(i64),
Float(f64),
Bool(bool),
Str(Rc<String>),
Array(Rc<ArrayBody>),
Map(Rc<MapBody>),
Closure(Rc<Closure>),
Builtin(Builtin),
HostBuiltin(HostBuiltin),
Nil,
Error(Rc<crate::MiruError>),
}
const _: () = assert!(
std::mem::size_of::<Value>() == 4 * std::mem::size_of::<usize>(),
"Value changed size; the VM stack is a Vec<Value>, so measure before accepting it"
);
impl Value {
pub fn array(items: Vec<Value>) -> Value {
Value::Array(Rc::new(ArrayBody::new(items)))
}
pub fn map(entries: BTreeMap<String, Value>) -> Value {
Value::Map(Rc::new(MapBody::new(entries)))
}
pub fn type_name(&self) -> &'static str {
match self {
Value::Int(_) => "int",
Value::Float(_) => "float",
Value::Bool(_) => "bool",
Value::Str(_) => "string",
Value::Array(_) => "array",
Value::Map(_) => "map",
Value::Closure(_) | Value::Builtin(_) | Value::HostBuiltin(_) => "function",
Value::Nil => "nil",
Value::Error(_) => "error",
}
}
pub fn is_truthy(&self) -> bool {
!matches!(self, Value::Bool(false) | Value::Nil)
}
pub fn condition(&self) -> Result<bool, String> {
match self {
Value::Bool(false) | Value::Nil => Ok(false),
Value::Error(error) => Err(format!("unhandled error: {}", error.message)),
_ => Ok(true),
}
}
pub fn display(&self) -> String {
match self {
Value::Str(s) => s.as_str().to_string(),
other => other.repr(),
}
}
pub fn repr(&self) -> String {
self.repr_within(Value::MAX_DEPTH, &mut Vec::new())
}
fn repr_within(&self, depth: usize, open: &mut Vec<usize>) -> String {
let address = match self {
Value::Array(items) => Some(Rc::as_ptr(items) as usize),
Value::Map(entries) => Some(Rc::as_ptr(entries) as usize),
_ => None,
};
if let Some(address) = address {
if open.contains(&address) || depth == 0 {
return match self {
Value::Array(_) => "[...]".to_string(),
Value::Map(_) => "{...}".to_string(),
_ => unreachable!("only a container has an address"),
};
}
open.push(address);
}
let text = self.repr_parts(depth.saturating_sub(1), open);
if address.is_some() {
open.pop();
}
text
}
fn repr_parts(&self, depth: usize, open: &mut Vec<usize>) -> String {
match self {
Value::Int(n) => n.to_string(),
Value::Float(f) => format_float(*f),
Value::Bool(b) => b.to_string(),
Value::Nil => "nil".to_string(),
Value::Str(s) => format!("\"{}\"", escape_string(s)),
Value::Array(items) => {
let parts: Vec<String> = items
.borrow()
.iter()
.map(|item| item.repr_within(depth, open))
.collect();
format!("[{}]", parts.join(", "))
}
Value::Map(entries) => {
let parts: Vec<String> = entries
.borrow()
.iter()
.map(|(key, value)| {
format!(
"\"{}\": {}",
escape_string(key),
value.repr_within(depth, open)
)
})
.collect();
format!("{{{}}}", parts.join(", "))
}
Value::Closure(closure) => match &closure.function.name {
Some(name) => format!("<fn {name}>"),
None => "<fn>".to_string(),
},
Value::Builtin(builtin) => format!("<builtin {}>", builtin.name),
Value::HostBuiltin(builtin) => format!("<builtin {}>", builtin.name),
Value::Error(error) => format!("<error: {}>", error.message),
}
}
const MAX_DEPTH: usize = 256;
pub fn equals(&self, other: &Value) -> Result<bool, String> {
self.equals_within(other, Value::MAX_DEPTH)
}
fn equals_within(&self, other: &Value, depth: usize) -> Result<bool, String> {
match (self, other) {
(Value::Array(a), Value::Array(b)) if Rc::ptr_eq(a, b) => return Ok(true),
(Value::Map(a), Value::Map(b)) if Rc::ptr_eq(a, b) => return Ok(true),
_ => {}
}
let Some(depth) = depth.checked_sub(1) else {
return Err("value is nested too deeply to compare".to_string());
};
match (self, other) {
(Value::Int(a), Value::Int(b)) => Ok(a == b),
(Value::Float(a), Value::Float(b)) => Ok(a == b),
(Value::Int(a), Value::Float(b)) => Ok((*a as f64) == *b),
(Value::Float(a), Value::Int(b)) => Ok(*a == (*b as f64)),
(Value::Bool(a), Value::Bool(b)) => Ok(a == b),
(Value::Str(a), Value::Str(b)) => Ok(a == b),
(Value::Nil, Value::Nil) => Ok(true),
(Value::Array(a), Value::Array(b)) => {
let a = a.borrow();
let b = b.borrow();
if a.len() != b.len() {
return Ok(false);
}
for (x, y) in a.iter().zip(b.iter()) {
if !x.equals_within(y, depth)? {
return Ok(false);
}
}
Ok(true)
}
(Value::Closure(a), Value::Closure(b)) => Ok(Rc::ptr_eq(a, b)),
(Value::Builtin(a), Value::Builtin(b)) => Ok(a.name == b.name),
(Value::HostBuiltin(a), Value::HostBuiltin(b)) => Ok(a.name == b.name),
(Value::Map(a), Value::Map(b)) => {
let a = a.borrow();
let b = b.borrow();
if a.len() != b.len() {
return Ok(false);
}
for (key, value) in a.iter() {
match b.get(key) {
Some(other) if value.equals_within(other, depth)? => {}
_ => return Ok(false),
}
}
Ok(true)
}
_ => Ok(false),
}
}
}
impl std::fmt::Display for Value {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.display())
}
}
fn format_float(f: f64) -> String {
if f.is_nan() {
return "nan".to_string();
}
if f.is_infinite() {
return if f > 0.0 { "inf" } else { "-inf" }.to_string();
}
let text = f.to_string();
if text.contains(['.', 'e', 'E']) {
text
} else {
format!("{text}.0")
}
}
fn escape_string(s: &str) -> String {
let mut out = String::with_capacity(s.len());
for c in s.chars() {
match c {
'"' => out.push_str("\\\""),
'\\' => out.push_str("\\\\"),
'\n' => out.push_str("\\n"),
'\t' => out.push_str("\\t"),
'\r' => out.push_str("\\r"),
other => out.push(other),
}
}
out
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn releasing_one_holder_leaves_a_shared_body_intact() {
let shared = Rc::new(ArrayBody::new(vec![Value::Int(1), Value::Int(2)]));
let first = Value::Array(Rc::clone(&shared));
let second = Value::Array(Rc::clone(&shared));
assert_eq!(Rc::strong_count(&shared), 3);
drop(first);
assert_eq!(Rc::strong_count(&shared), 2);
assert_eq!(shared.borrow().len(), 2, "the contents survived");
drop(second);
assert_eq!(Rc::strong_count(&shared), 1);
assert_eq!(shared.borrow().len(), 2, "and survive while we hold it");
}
#[test]
fn releasing_the_last_holder_releases_the_contents() {
let inner = Rc::new(ArrayBody::new(vec![Value::Int(7)]));
let outer = Value::array(vec![Value::Array(Rc::clone(&inner))]);
assert_eq!(Rc::strong_count(&inner), 2);
drop(outer);
assert_eq!(
Rc::strong_count(&inner),
1,
"the outer array gave up its reference to the inner one"
);
}
#[test]
fn a_chain_longer_than_the_stack_is_released() {
let mut chain = Value::array(Vec::new());
for _ in 0..200_000 {
chain = Value::array(vec![chain]);
}
drop(chain);
}
#[test]
fn an_error_value_names_its_type_and_shows_what_it_holds() {
let value = Value::Error(Rc::new(crate::MiruError::with_column(
3,
5,
"division by zero",
)));
assert_eq!(value.type_name(), "error");
assert_eq!(value.repr(), "<error: division by zero>");
assert_eq!(value.display(), "<error: division by zero>");
match &value {
Value::Error(error) => {
assert_eq!((error.line, error.column), (3, 5));
}
other => panic!("expected an error, found {}", other.type_name()),
}
}
#[test]
fn a_character_that_is_not_ascii_prints_as_itself() {
let emoji = Value::Str(Rc::new("\u{1F600}".to_string()));
assert_eq!(emoji.display(), "\u{1F600}");
assert_eq!(emoji.repr(), "\"\u{1F600}\"");
assert_eq!(Value::array(vec![emoji.clone()]).repr(), "[\"\u{1F600}\"]");
assert_eq!(
map(&[("\u{1F600}", Value::Int(1))]).repr(),
"{\"\u{1F600}\": 1}"
);
}
fn map(pairs: &[(&str, Value)]) -> Value {
let mut entries = BTreeMap::new();
for (key, value) in pairs {
entries.insert((*key).to_string(), value.clone());
}
Value::map(entries)
}
#[test]
fn map_repr_is_sorted_and_quoted() {
let m = map(&[
("name", Value::Str(Rc::new("Aiko".to_string()))),
("age", Value::Int(3)),
]);
assert_eq!(m.repr(), "{\"age\": 3, \"name\": \"Aiko\"}");
}
#[test]
fn map_type_name_and_truthiness() {
let m = map(&[]);
assert_eq!(m.type_name(), "map");
assert!(m.is_truthy());
}
#[test]
fn maps_compare_by_entries() {
let a = map(&[("x", Value::Int(1))]);
let b = map(&[("x", Value::Int(1))]);
let c = map(&[("x", Value::Int(2))]);
assert!(a.equals(&b).unwrap());
assert!(!a.equals(&c).unwrap());
}
}