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 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,
}),
);
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();
pairs(&state).len() 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 pairs(state: &Object) -> Vec<(Value, Value)> {
let Some(Value::List(items)) = state.value_of("pairs") else {
return Vec::new();
};
items
.iter()
.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 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_pair(this: &Value) -> Option<(Value, Value, Alone)> {
let state = state(this)?;
let mut state = state.borrow_mut();
let mut pairs = pairs(&state);
if pairs.is_empty() {
return None;
}
let (key, value) = pairs.remove(0);
set_pairs(&mut state, pairs);
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))
}