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);
}
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 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>>>,
}
#[derive(Clone)]
pub struct Builtin {
pub name: &'static str,
pub func: BuiltinFn,
}
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<RefCell<Vec<Value>>>),
Map(Rc<RefCell<BTreeMap<String, Value>>>),
Closure(Rc<Closure>),
Builtin(Builtin),
HostBuiltin(HostBuiltin),
Nil,
Error(Rc<crate::MiruError>),
}
impl Value {
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 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()),
}
}
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(Rc::new(RefCell::new(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());
}
}