use alloc::collections::BTreeMap;
use alloc::string::{String, ToString};
use alloc::vec;
use alloc::vec::Vec;
use crate::runtime::{Object, Runtime, RuntimeError, RuntimeFailure, Value, put};
use crate::runtime::SharedCell;
const STATE: &str = "enumerator state";
const PAIRS: &str = "pairs";
const PLACE: &str = "at";
const STATE_CLASS: &str = "enumerator-state";
const PROPERTIES: [&str; 5] = ["name", "minparams", "maxparams", "isbuiltin", "isvariadic"];
const METHODS: [&str; 13] = [
"call",
"isoptional",
"isbyref",
"bind",
"ownprops",
"hasownprop",
"defineprop",
"deleteprop",
"getownpropdesc",
"hasprop",
"hasmethod",
"getmethod",
"hasbase",
];
#[derive(Clone, Copy)]
pub(crate) enum Alone {
TheKey,
TheValue,
}
pub(crate) fn names() -> Vec<&'static str> {
PROPERTIES.iter().chain(METHODS.iter()).copied().collect()
}
pub(crate) fn make(pairs: Vec<(Value, Value)>, alone: Alone) -> Value {
let mut state = Object {
class: STATE_CLASS.to_string(),
properties: BTreeMap::new(),
};
set_pairs(&mut state, pairs);
put(
&mut state.properties,
"alone",
Value::Int(match alone {
Alone::TheKey => 0,
Alone::TheValue => 1,
}),
);
put(&mut state.properties, PLACE, Value::Int(0));
let mut table = BTreeMap::new();
put(
&mut table,
STATE,
Value::Object(SharedCell::new(state)),
);
Value::Object(SharedCell::new(Object {
class: "enumerator".to_string(),
properties: table,
}))
}
pub(crate) fn is_one(value: &Value) -> bool {
let Value::Object(object) = value else {
return false;
};
object.borrow().class == "enumerator"
}
pub(crate) fn the_count(this: &Value) -> i64 {
let Some(state) = state(this) else { return 0 };
let state = state.borrow();
let place = the_place(&state);
let total = the_number_of_pairs(&state);
total.saturating_sub(place) as i64
}
pub(crate) fn the_turn(this: &Value, wanted: usize) -> Option<Value> {
let (key, value, alone) = the_pair(this)?;
if wanted >= 2 {
return Some(Value::List(vec![key, value]));
}
Some(match alone {
Alone::TheKey => key,
Alone::TheValue => value,
})
}
pub(crate) fn call(
method: &str,
this: &Value,
arguments: &[Value],
rt: &mut Runtime,
line: u32,
) -> Option<Result<Value, RuntimeFailure>> {
match method {
"call" => Some(the_call(this, arguments, rt, line)),
"ownprops" => Some(Ok(make(Vec::new(), Alone::TheKey))),
"hasownprop" => {
let name = arguments
.first()
.map(|value| value.to_text())
.unwrap_or_default();
let key = name.to_lowercase();
let answer = match this {
Value::Object(object) => {
key != STATE && object.borrow().properties.contains_key(&key)
}
_ => false,
};
Some(Ok(Value::Int(answer as i64)))
}
"isoptional" => Some(Ok(Value::Int(0))),
"isbyref" => Some(Ok(Value::Int(0))),
"bind" => Some(Err(RuntimeFailure::Error(RuntimeError {
message: "this runtime does not bind a function to an object.".into(),
line,
}))),
_ => None,
}
}
pub(crate) fn call_the_value(
this: &Value,
arguments: &[Value],
rt: &mut Runtime,
line: u32,
) -> Option<Result<Value, RuntimeFailure>> {
call("call", this, arguments, rt, line)
}
pub(crate) fn property(
name: &str,
_this: &Value,
_rt: &mut Runtime,
_line: u32,
) -> Option<Result<Value, RuntimeFailure>> {
Some(Ok(match name {
"name" => Value::Text(String::new()),
"minparams" => Value::Int(0),
"maxparams" => Value::Int(0),
"isbuiltin" => Value::Int(1),
"isvariadic" => Value::Int(0),
_ => return None,
}))
}
fn the_call(
this: &Value,
arguments: &[Value],
rt: &mut Runtime,
_line: u32,
) -> Result<Value, RuntimeFailure> {
let Some((key, value, alone)) = the_pair(this) else {
return Ok(Value::Int(0));
};
let alone_value = match alone {
Alone::TheKey => key.clone(),
Alone::TheValue => value.clone(),
};
if arguments.len() >= 2 {
rt.write_reference(&arguments[0], key);
if crate::runtime::is_a_value_without_one(&value) {
rt.unset_reference(&arguments[1]);
} else {
rt.write_reference(&arguments[1], value);
}
} else if let Some(argument) = arguments.first() {
if crate::runtime::is_a_value_without_one(&alone_value) {
rt.unset_reference(argument);
} else {
rt.write_reference(argument, alone_value);
}
}
Ok(Value::Int(1))
}
fn state(enumerator: &Value) -> Option<SharedCell<Object>> {
let Value::Object(object) = enumerator else {
return None;
};
let state = object.borrow().value_of(STATE)?;
match state {
Value::Object(state) => Some(state),
_ => None,
}
}
fn set_pairs(state: &mut Object, pairs: Vec<(Value, Value)>) {
let items: Vec<Value> = pairs
.into_iter()
.map(|(key, value)| Value::List(vec![key, value]))
.collect();
put(&mut state.properties, PAIRS, Value::List(items));
}
fn the_number_of_pairs(state: &Object) -> usize {
match state.value_ref(PAIRS) {
Some(Value::List(items)) => items.len(),
_ => 0,
}
}
fn the_place(state: &Object) -> usize {
state
.value_of(PLACE)
.and_then(|value| value.to_number())
.map(|number| number as usize)
.unwrap_or(0)
}
fn the_pair_at(state: &Object, place: usize) -> Option<(Value, Value)> {
let Some(Value::List(items)) = state.value_ref(PAIRS) else {
return None;
};
let item = items.get(place)?;
Some(match item {
Value::List(pair) if pair.len() == 2 => (pair[0].clone(), pair[1].clone()),
_ => (item.clone(), Value::Text(String::new())),
})
}
pub(crate) fn the_pairs_of(enumerator: &Value) -> Vec<(Value, Value)> {
let Some(state) = state(enumerator) else {
return Vec::new();
};
let state = state.borrow();
let place = the_place(&state);
let Some(Value::List(items)) = state.value_ref(PAIRS) else {
return Vec::new();
};
items
.iter()
.skip(place)
.map(|item| match item {
Value::List(pair) if pair.len() == 2 => (pair[0].clone(), pair[1].clone()),
_ => (item.clone(), Value::Text(String::new())),
})
.collect()
}
fn the_pair(this: &Value) -> Option<(Value, Value, Alone)> {
let state = state(this)?;
let mut state = state.borrow_mut();
let place = the_place(&state);
let (key, value) = the_pair_at(&state, place)?;
put(&mut state.properties, PLACE, Value::Int(place as i64 + 1));
let alone = match state.value_of("alone").and_then(|value| value.to_number()) {
Some(number) if number >= 1.0 => Alone::TheValue,
_ => Alone::TheKey,
};
Some((key, value, alone))
}
#[cfg(all(test, feature = "std"))]
mod tests {
use super::*;
use alloc::format;
#[test]
fn the_turns_of_an_enumerator_come_in_the_order_of_the_pairs() {
let pairs: Vec<(Value, Value)> = (1..=5)
.map(|number| (Value::Int(number), Value::Text(format!("v{number}"))))
.collect();
let enumerator = make(pairs, Alone::TheValue);
assert_eq!(the_count(&enumerator), 5);
for number in 1..=5 {
let turn = the_turn(&enumerator, 2).expect("the enumerator has a turn");
let Value::List(pair) = turn else {
panic!("the turn of the enumerator is not a pair: {turn:?}");
};
assert_eq!(pair[0], Value::Int(number));
assert_eq!(pair[1], Value::Text(format!("v{number}")));
assert_eq!(the_count(&enumerator), 5 - number);
}
assert!(the_turn(&enumerator, 2).is_none());
assert_eq!(the_count(&enumerator), 0);
}
#[test]
fn the_pairs_of_an_enumerator_are_the_ones_that_are_left() {
let pairs: Vec<(Value, Value)> = (1..=4)
.map(|number| (Value::Int(number), Value::Int(number * 10)))
.collect();
let enumerator = make(pairs, Alone::TheKey);
assert_eq!(the_pairs_of(&enumerator).len(), 4);
let _ = the_turn(&enumerator, 2);
let left = the_pairs_of(&enumerator);
assert_eq!(left.len(), 3);
assert_eq!(left[0].0, Value::Int(2));
assert_eq!(left[2].0, Value::Int(4));
}
#[test]
fn the_enumerator_that_gives_the_key_alone_gives_the_key_of_the_turn() {
let enumerator = make(
vec![(Value::Int(1), Value::Text("a".into())), (Value::Int(2), Value::Text("b".into()))],
Alone::TheKey,
);
assert_eq!(the_turn(&enumerator, 1), Some(Value::Int(1)));
assert_eq!(the_turn(&enumerator, 1), Some(Value::Int(2)));
assert_eq!(the_turn(&enumerator, 1), None);
}
}