use alloc::collections::BTreeMap;
use alloc::format;
use alloc::string::{String, ToString};
use alloc::vec;
use alloc::vec::Vec;
use core::cell::RefCell;
use crate::classes::enumerator;
use crate::runtime::{Object, Runtime, RuntimeError, RuntimeFailure, Value, put};
use crate::runtime::SharedCell;
const STATE: &str = "array state";
const STATE_CLASS: &str = "array-state";
const KEY: &str = "key:";
const PROPERTIES: [&str; 3] = ["length", "capacity", "__item"];
const METHODS: [&str; 19] = [
"push",
"pop",
"insertat",
"removeat",
"delete",
"get",
"has",
"clone",
"__new",
"__enum",
"ownprops",
"hasownprop",
"defineprop",
"deleteprop",
"getownpropdesc",
"hasprop",
"hasmethod",
"getmethod",
"hasbase",
];
pub(crate) fn names() -> Vec<&'static str> {
PROPERTIES.iter().chain(METHODS.iter()).copied().collect()
}
pub(crate) fn construct(
arguments: &[Value],
_rt: &mut Runtime,
_line: u32,
) -> Result<Value, RuntimeFailure> {
let array = crate::classes::object_with("array", vec![(STATE, new_state(Vec::new(), 0))]);
for value in arguments {
push_value(&array, value.clone());
}
Ok(array)
}
pub(crate) fn construct_with_holes(
values: &[Option<Value>],
_rt: &mut Runtime,
_line: u32,
) -> Value {
let array = crate::classes::object_with("array", vec![(STATE, new_state(Vec::new(), 0))]);
for value in values {
push_element(&array, value.clone());
}
array
}
pub(crate) fn of_items(items: Vec<Value>) -> Value {
let array = crate::classes::object_with("array", vec![(STATE, new_state(Vec::new(), 0))]);
for value in items {
push_value(&array, value);
}
array
}
pub(crate) fn call(
method: &str,
this: &Value,
arguments: &[Value],
rt: &mut Runtime,
line: u32,
) -> Option<Result<Value, RuntimeFailure>> {
let method = method.to_lowercase();
let failure = |message: &str| {
Some(Err(RuntimeFailure::Error(RuntimeError {
message: message.to_string(),
line,
})))
};
let failure_with = |message: &str, extra: &str| {
Some(Err(crate::classes::the_failure_with(message, extra, line)))
};
let invalid_place = |method: &str, index: i64| {
failure_with(
&format!(
"Parameter #1 of {} is invalid.",
crate::classes::the_name_of("array", method)
),
&index.to_string(),
)
};
if rt
.dialect()
.carries_the_member_of_the_extension("array", &method)
{
return the_extension_answer(&method, this, arguments, rt, line);
}
match method.as_str() {
"push" | "__new" => {
for value in arguments {
push_value(this, value.clone());
}
Some(Ok(this.clone()))
}
"pop" => {
let Some(state) = state(this) else {
return failure("Invalid index.");
};
let mut state = state.borrow_mut();
let Some(items) = the_items_mut(&mut state) else {
return failure("Array is empty.");
};
let Some(last) = items.pop() else {
return failure("Array is empty.");
};
Some(Ok(
element_value(&last).unwrap_or(Value::Text(String::new()))
))
}
"insert" if rt.dialect().the_array_has_the_methods_of_the_v1() => {
let Some(state) = state(this) else {
return failure("Invalid index.");
};
let mut state = state.borrow_mut();
let Some(items) = the_items_mut(&mut state) else {
return failure("Invalid index.");
};
let length = items.len() as i64;
if arguments.len() < 2 {
if let Some(value) = arguments.first() {
items.push(element(Some(value.clone())));
}
return Some(Ok(Value::Text(String::new())));
}
let index = match rt.integer(&arguments[0], line) {
Ok(number) => number,
Err(failure) => return Some(Err(failure)),
};
let Some(place) = insert_place(index, length) else {
return invalid_place("Insert", index);
};
for (offset, value) in arguments.iter().skip(1).enumerate() {
items.insert(place + offset, element(Some(value.clone())));
}
Some(Ok(Value::Text(String::new())))
}
"remove" if rt.dialect().the_array_has_the_methods_of_the_v1() => {
let Some(state) = state(this) else {
return failure("Invalid index.");
};
let mut state = state.borrow_mut();
let Some(items) = the_items_mut(&mut state) else {
return failure("Invalid index.");
};
let length = items.len() as i64;
let Some(index) = arguments.first() else {
let Some(last) = items.pop() else {
return failure("Array is empty.");
};
return Some(Ok(
element_value(&last).unwrap_or(Value::Text(String::new()))
));
};
let index = match rt.integer(index, line) {
Ok(number) => number,
Err(failure) => return Some(Err(failure)),
};
let Some(place) = place(index, length) else {
return invalid_place("Remove", index);
};
let removed = items.remove(place);
Some(Ok(
element_value(&removed).unwrap_or(Value::Text(String::new()))
))
}
"insertat" => {
let Some(index) = arguments.first() else {
return failure("Too few parameters passed to function.");
};
if arguments.len() < 2 {
return failure("Too few parameters passed to function.");
}
let index = match rt.integer(index, line) {
Ok(number) => number,
Err(failure) => return Some(Err(failure)),
};
let Some(state) = state(this) else {
return failure("Invalid index.");
};
let mut state = state.borrow_mut();
let Some(items) = the_items_mut(&mut state) else {
return failure("Invalid index.");
};
let length = items.len() as i64;
let Some(place) = insert_place(index, length) else {
return invalid_place("InsertAt", index);
};
for (offset, value) in arguments.iter().skip(1).enumerate() {
items.insert(place + offset, element(Some(value.clone())));
}
Some(Ok(Value::Text(String::new())))
}
"removeat" => {
let Some(index) = arguments.first() else {
return failure("Too few parameters passed to function.");
};
let index = match rt.integer(index, line) {
Ok(number) => number,
Err(failure) => return Some(Err(failure)),
};
let Some(state) = state(this) else {
return failure("Invalid index.");
};
let mut state = state.borrow_mut();
let Some(items) = the_items_mut(&mut state) else {
return failure("Invalid index.");
};
let length = items.len() as i64;
let Some(place) = place(index, length) else {
return invalid_place("RemoveAt", index);
};
match arguments.get(1) {
None => {
let removed = items.remove(place);
Some(Ok(
element_value(&removed).unwrap_or(Value::Text(String::new()))
))
}
Some(count) => {
let count = match rt.integer(count, line) {
Ok(number) => number,
Err(failure) => return Some(Err(failure)),
};
let mut removed = 0;
for _ in 0..count.max(1) {
if place >= items.len() {
break;
}
if element_value(&items[place]).is_some() {
removed += 1;
}
items.remove(place);
}
Some(Ok(Value::Int(removed)))
}
}
}
"delete" => {
let Some(index) = arguments.first() else {
return failure("Too few parameters passed to function.");
};
let index = match rt.integer(index, line) {
Ok(number) => number,
Err(failure) => return Some(Err(failure)),
};
let Some(state) = state(this) else {
return failure("Invalid index.");
};
let mut state = state.borrow_mut();
let Some(items) = the_items_mut(&mut state) else {
return failure("Invalid index.");
};
let length = items.len() as i64;
let Some(place) = place(index, length) else {
return invalid_place("Delete", index);
};
let removed = element_value(&items[place]).unwrap_or(Value::Text(String::new()));
items[place] = element(None);
Some(Ok(removed))
}
"get" => {
let Some(index) = arguments.first() else {
return failure("Too few parameters passed to function.");
};
let index = match rt.integer(index, line) {
Ok(number) => number,
Err(failure) => return Some(Err(failure)),
};
let Some(state) = state(this) else {
return failure("Invalid index.");
};
let state = state.borrow();
let Some(items) = the_items_of(&state) else {
return failure_with("Invalid index.", &index.to_string());
};
let length = items.len() as i64;
let Some(place) = place(index, length) else {
return failure_with("Invalid index.", &index.to_string());
};
match element_value(&items[place]) {
Some(value) => Some(Ok(value)),
None => match arguments.get(1) {
Some(default) => Some(Ok(default.clone())),
None => match default_property(this) {
Some(default) => Some(Ok(default)),
None => failure("Item has no value."),
},
},
}
}
"has" => {
let Some(index) = arguments.first() else {
return failure("Too few parameters passed to function.");
};
let index = match rt.integer(index, line) {
Ok(number) => number,
Err(failure) => return Some(Err(failure)),
};
let Some(state) = state(this) else {
return Some(Ok(Value::Int(0)));
};
let state = state.borrow();
if rt.dialect().the_array_grows_with_the_write_of_an_item()
&& the_keyed_item_of(&state, index).is_some()
{
return Some(Ok(Value::Int(1)));
}
let Some(items) = the_items_of(&state) else {
return Some(Ok(Value::Int(0)));
};
let length = items.len() as i64;
let found = match place(index, length) {
Some(place) => element_value(&items[place]).is_some(),
None => false,
};
Some(Ok(Value::Int(found as i64)))
}
"clone" => Some(Ok(clone(this))),
"__enum" => {
let Some(state) = state(this) else {
return Some(Ok(enumerator::make(
Vec::new(),
enumerator::Alone::TheValue,
)));
};
let state = state.borrow();
let pairs: Vec<(Value, Value)> = if rt
.dialect()
.the_array_grows_with_the_write_of_an_item()
{
the_items_with_a_value(&state)
.into_iter()
.map(|(key, value)| (Value::Int(key), value))
.collect()
} else {
the_items_of(&state)
.map(|items| {
items
.iter()
.enumerate()
.map(|(index, item)| {
let value = element_value(item).unwrap_or_else(|| element(None));
(Value::Int(index as i64 + 1), value)
})
.collect()
})
.unwrap_or_default()
};
Some(Ok(enumerator::make(pairs, enumerator::Alone::TheValue)))
}
_ => base_method(&method, this, arguments, rt, line),
}
}
pub(crate) fn set_item(
key: &Value,
this: &Value,
value: Value,
rt: &mut Runtime,
line: u32,
) -> Option<Result<(), RuntimeFailure>> {
let Some(index) = rt.the_place_of_an_item(key) else {
if rt
.dialect()
.the_item_of_an_array_with_a_key_that_is_not_a_number_is_its_property()
{
let name = key.to_text();
return Some(
rt.write_property_of(this, &name, value, line)
.map_err(RuntimeFailure::Error),
);
}
return Some(Err(crate::classes::the_failure_with(
"Invalid index.",
&crate::runtime::the_extra_of_the_value(key),
line,
)));
};
let Some(state) = state(this) else {
return Some(Err(crate::classes::the_failure_with(
"Invalid index.",
&index.to_string(),
line,
)));
};
let mut state = state.borrow_mut();
if rt.dialect().the_array_grows_with_the_write_of_an_item() {
let length = the_items_of(&state).map_or(0, |items| items.len() as i64);
if index > length {
set_the_keyed_item(&mut state, index, value);
return Some(Ok(()));
}
}
let Some(items) = the_items_mut(&mut state) else {
return Some(Err(crate::classes::the_failure_with(
"Invalid index.",
&index.to_string(),
line,
)));
};
let length = items.len() as i64;
let place = if rt.dialect().the_array_grows_with_the_write_of_an_item() {
the_place_of_the_v1(index, length)
} else {
place(index, length)
};
let Some(place) = place else {
if rt.dialect().the_array_grows_with_the_write_of_an_item() {
if index > length {
while (items.len() as i64) < index - 1 {
items.push(element(None));
}
items.push(element(Some(value)));
return Some(Ok(()));
}
let name = key.to_text();
return Some(
rt.write_property_of(this, &name, value, line)
.map_err(RuntimeFailure::Error),
);
}
return Some(Err(crate::classes::the_failure_with(
"Invalid index.",
&index.to_string(),
line,
)));
};
items[place] = element(Some(value));
Some(Ok(()))
}
pub(crate) fn property(
name: &str,
this: &Value,
rt: &mut Runtime,
_line: u32,
) -> Option<Result<Value, RuntimeFailure>> {
let state = state(this)?;
if !rt.dialect().the_array_has_the_length_and_the_capacity() {
return None;
}
let state = state.borrow();
match name {
"length" => Some(Ok(Value::Int(
the_items_of(&state).map_or(0, |items| items.len() as i64),
))),
"capacity" => Some(Ok(Value::Int(capacity(&state)))),
_ => None,
}
}
pub(crate) fn set_property(
name: &str,
this: &Value,
value: Value,
rt: &mut Runtime,
line: u32,
) -> Option<Result<(), RuntimeFailure>> {
let failure = |message: &str| {
Some(Err(RuntimeFailure::Error(RuntimeError {
message: message.to_string(),
line,
})))
};
match name {
"length" => {
let wanted = match rt.integer(&value, line) {
Ok(number) => number,
Err(failure) => return Some(Err(failure)),
};
if wanted < 0 {
return failure("Invalid value.");
}
let state = state(this)?;
let mut state = state.borrow_mut();
let Some(items) = the_items_mut(&mut state) else {
return failure("Invalid value.");
};
items.truncate(wanted as usize);
while (items.len() as i64) < wanted {
items.push(element(None));
}
Some(Ok(()))
}
"capacity" => {
let wanted = match rt.integer(&value, line) {
Ok(number) => number,
Err(failure) => return Some(Err(failure)),
};
if wanted < 0 {
return failure("Invalid value.");
}
let state = state(this)?;
let mut state = state.borrow_mut();
let count = {
let Some(items) = the_items_mut(&mut state) else {
return failure("Invalid value.");
};
if (wanted as usize) < items.len() {
items.truncate(wanted as usize);
}
items.len() as i64
};
set_capacity(&mut state, wanted.max(count));
Some(Ok(()))
}
_ => None,
}
}
pub(crate) fn item(
key: &Value,
this: &Value,
rt: &mut Runtime,
line: u32,
) -> Option<Result<Value, RuntimeFailure>> {
let Some(index) = rt.the_place_of_an_item(key) else {
if rt
.dialect()
.the_item_of_an_array_with_a_key_that_is_not_a_number_is_its_property()
{
let name = key.to_text();
return Some(rt.read_property(this, &name, line));
}
return Some(Err(crate::classes::the_failure_with(
"Invalid index.",
&crate::runtime::the_extra_of_the_value(key),
line,
)));
};
let Some(state) = state(this) else {
return Some(Err(crate::classes::the_failure_with(
"Invalid index.",
&index.to_string(),
line,
)));
};
let state = state.borrow();
if rt.dialect().the_array_grows_with_the_write_of_an_item() {
if let Some(value) = the_keyed_item_of(&state, index) {
return Some(Ok(value));
}
}
let Some(items) = the_items_of(&state) else {
return Some(Err(crate::classes::the_failure_with(
"Invalid index.",
&index.to_string(),
line,
)));
};
let length = items.len() as i64;
let place = if rt
.dialect()
.the_item_of_an_array_that_is_not_there_is_the_empty_text()
{
the_place_of_the_v1(index, length)
} else {
place(index, length)
};
let Some(place) = place else {
if rt
.dialect()
.the_item_of_an_array_that_is_not_there_is_the_empty_text()
{
if index < 1 {
let name = key.to_text();
return Some(rt.read_property(this, &name, line));
}
return Some(Ok(Value::Text(String::new())));
}
return Some(Err(crate::classes::the_failure_with(
"Invalid index.",
&index.to_string(),
line,
)));
};
match element_value(&items[place]) {
Some(value) => Some(Ok(value)),
None => match default_property(this) {
Some(default) => Some(Ok(default)),
None => {
if rt
.dialect()
.the_place_without_a_value_of_an_array_is_the_empty_text()
{
return Some(Ok(Value::Text(String::new())));
}
Some(Err(RuntimeFailure::Error(RuntimeError {
message: "Item has no value.".into(),
line,
})))
}
},
}
}
fn state(array: &Value) -> Option<SharedCell<Object>> {
let Value::Object(object) = array else {
return None;
};
let state = object.borrow().value_of(STATE)?;
match state {
Value::Object(state) => Some(state),
_ => None,
}
}
fn new_state(items: Vec<Value>, capacity: i64) -> Value {
let mut state = Object {
class: STATE_CLASS.to_string(),
properties: BTreeMap::new(),
};
set_items(&mut state, items);
set_capacity(&mut state, capacity);
Value::Object(SharedCell::new(state))
}
fn items(state: &Object) -> Vec<Value> {
the_items_of(state).cloned().unwrap_or_default()
}
fn the_items_of(state: &Object) -> Option<&Vec<Value>> {
match state.value_ref("items") {
Some(Value::List(items)) => Some(items),
_ => None,
}
}
fn the_items_mut(state: &mut Object) -> Option<&mut Vec<Value>> {
match state.value_mut("items") {
Some(Value::List(items)) => Some(items),
_ => None,
}
}
fn the_name_of_a_key(key: i64) -> String {
format!("{}{:020}", KEY, key)
}
fn the_key_of_a_name(name: &str) -> Option<i64> {
name.strip_prefix(KEY)?.parse::<i64>().ok()
}
fn the_keyed_item_of(state: &Object, key: i64) -> Option<Value> {
state
.properties
.get(&the_name_of_a_key(key))
.map(|property| property.value.clone())
}
fn set_the_keyed_item(state: &mut Object, key: i64, value: Value) {
put(&mut state.properties, &the_name_of_a_key(key), value);
}
fn the_state_has_a_keyed_item(state: &Object) -> bool {
state
.properties
.keys()
.any(|name| the_key_of_a_name(name).is_some())
}
fn the_keyed_items_of(state: &Object) -> Vec<(i64, Value)> {
state
.properties
.iter()
.filter_map(|(name, property)| {
the_key_of_a_name(name).map(|key| (key, property.value.clone()))
})
.collect()
}
fn the_highest_key_of(state: &Object) -> Option<i64> {
state
.properties
.keys()
.filter_map(|name| the_key_of_a_name(name))
.max()
}
fn the_items_with_a_value(state: &Object) -> Vec<(i64, Value)> {
let mut items: BTreeMap<i64, Value> = BTreeMap::new();
if let Some(row) = the_items_of(state) {
for (place, item) in row.iter().enumerate() {
if let Some(value) = element_value(item) {
items.insert(place as i64 + 1, value);
}
}
}
for (key, value) in the_keyed_items_of(state) {
items.insert(key, value);
}
items.into_iter().collect()
}
pub(crate) fn the_items(array: &Value) -> Vec<Value> {
let Some(state) = state(array) else {
return Vec::new();
};
let state = state.borrow();
if the_state_has_a_keyed_item(&state) {
return the_items_with_a_value(&state)
.into_iter()
.map(|(_, value)| value)
.collect();
}
the_items_of(&state)
.map(|items| {
items
.iter()
.map(|element| element_value(element).unwrap_or(Value::Text(String::new())))
.collect()
})
.unwrap_or_default()
}
pub(crate) fn has_the_key(array: &Value, key: i64) -> bool {
let Some(state) = state(array) else {
return false;
};
let state = state.borrow();
if the_keyed_item_of(&state, key).is_some() {
return true;
}
let Some(items) = the_items_of(&state) else {
return false;
};
if key < 1 {
return false;
}
let place = key as usize - 1;
match items.get(place) {
Some(item) => element_value(item).is_some(),
None => false,
}
}
pub(crate) fn the_number_of_the_items(array: &Value) -> usize {
let Some(state) = state(array) else { return 0 };
let state = state.borrow();
let keyed = the_keyed_items_of(&state);
if keyed.is_empty() {
return the_items_of(&state)
.map(|items| {
items
.iter()
.filter(|item| element_value(item).is_some())
.count()
})
.unwrap_or(0);
}
let in_the_table = keyed
.iter()
.map(|(key, _)| (*key, ()))
.collect::<BTreeMap<i64, ()>>();
let in_the_row = the_items_of(&state)
.map(|items| {
items
.iter()
.enumerate()
.filter(|(place, item)| {
element_value(item).is_some()
&& !in_the_table.contains_key(&(*place as i64 + 1))
})
.count()
})
.unwrap_or(0);
in_the_row + keyed.len()
}
pub(crate) fn the_number_of_the_places(array: &Value) -> usize {
let Some(state) = state(array) else { return 0 };
let state = state.borrow();
let places = the_items_of(&state).map_or(0, |items| items.len());
match the_highest_key_of(&state) {
Some(key) => places.max(key as usize),
None => places,
}
}
pub(crate) fn the_indexes_with_a_value(array: &Value) -> Vec<i64> {
let Some(state) = state(array) else {
return Vec::new();
};
let state = state.borrow();
the_items_with_a_value(&state)
.into_iter()
.map(|(key, _)| key)
.collect()
}
fn set_items(state: &mut Object, items: Vec<Value>) {
put(&mut state.properties, "items", Value::List(items));
}
fn capacity(state: &Object) -> i64 {
state
.value_of("capacity")
.and_then(|value| value.to_number())
.map(|number| number as i64)
.unwrap_or(0)
}
fn set_capacity(state: &mut Object, capacity: i64) {
put(&mut state.properties, "capacity", Value::Int(capacity));
}
fn element(value: Option<Value>) -> Value {
match value {
Some(value) => Value::List(vec![Value::Int(1), value]),
None => crate::runtime::the_mark_of_a_value_without_one(),
}
}
fn element_value(element: &Value) -> Option<Value> {
match element {
Value::List(items) if items.len() == 2 && items[0] == Value::Int(1) => {
Some(items[1].clone())
}
_ => None,
}
}
fn default_property(array: &Value) -> Option<Value> {
let Value::Object(object) = array else {
return None;
};
object.borrow().value_of("default")
}
fn push_value(array: &Value, value: Value) {
push_element(array, Some(value));
}
fn push_element(array: &Value, value: Option<Value>) {
let Some(state) = state(array) else { return };
let mut state = state.borrow_mut();
let count = {
let Some(items) = the_items_mut(&mut state) else { return };
items.push(element(value));
items.len() as i64
};
if count > capacity(&state) {
set_capacity(&mut state, count);
}
}
fn clone(array: &Value) -> Value {
let (items, capacity, keyed) = match state(array) {
Some(state) => {
let state = state.borrow();
(items(&state), capacity(&state), the_keyed_items_of(&state))
}
None => (Vec::new(), 0, Vec::new()),
};
let mut properties = BTreeMap::new();
let mut copy = new_state(items, capacity);
if let Value::Object(cell) = &mut copy {
let mut state = cell.borrow_mut();
for (key, value) in keyed {
set_the_keyed_item(&mut state, key, value);
}
}
put(&mut properties, STATE, copy);
if let Value::Object(object) = array {
for (name, property) in object.borrow().properties.iter() {
if name != STATE {
properties.insert(name.clone(), property.clone());
}
}
}
Value::Object(SharedCell::new(Object {
class: "array".to_string(),
properties,
}))
}
fn place(index: i64, length: i64) -> Option<usize> {
let place = if index < 0 { length + index + 1 } else { index };
if place < 1 || place > length {
None
} else {
Some(place as usize - 1)
}
}
fn the_place_of_the_v1(index: i64, length: i64) -> Option<usize> {
if index < 1 || index > length {
None
} else {
Some(index as usize - 1)
}
}
fn insert_place(index: i64, length: i64) -> Option<usize> {
let place = if index < 0 {
length + index + 1
} else if index == 0 {
length + 1
} else {
index
};
if place < 1 || place > length + 1 {
None
} else {
Some(place as usize - 1)
}
}
fn base_method(
method: &str,
this: &Value,
arguments: &[Value],
rt: &mut Runtime,
line: u32,
) -> Option<Result<Value, RuntimeFailure>> {
let Value::Object(object) = this else {
return None;
};
if !rt.dialect().the_object_has_the_methods_of_the_base_object() {
return None;
}
let failure = |message: &str| {
Some(Err(RuntimeFailure::Error(RuntimeError {
message: message.to_string(),
line,
})))
};
let name = arguments
.first()
.map(|value| value.to_text())
.unwrap_or_default();
let key = name.to_lowercase();
match method {
"ownprops" => {
let pairs: Vec<(Value, Value)> = object
.borrow()
.properties
.iter()
.filter(|(name, _)| name.as_str() != STATE)
.map(|(_, property)| (Value::Text(property.name.clone()), property.value.clone()))
.collect();
Some(Ok(enumerator::make(pairs, enumerator::Alone::TheKey)))
}
"hasownprop" => Some(Ok(Value::Int(own_property(object, &key) as i64))),
"hasprop" => Some(Ok(Value::Int(
(PROPERTIES.contains(&key.as_str())
|| METHODS.contains(&key.as_str())
|| own_property(object, &key)
|| key == "__class"
|| key == "__init"
|| key == "base") as i64,
))),
"hasmethod" => Some(Ok(Value::Int(
(METHODS.contains(&key.as_str())
|| key == "__init") as i64,
))),
"getownpropdesc" => {
let name = arguments
.first()
.map(|value| value.to_text())
.unwrap_or_default();
let value = object.borrow().value_of(&key);
match value {
Some(value) => {
let table = match rt.the_members_of_a_descriptor(&value) {
Some(members) => members,
None => {
let mut table = BTreeMap::new();
put(&mut table, "value", value);
table
}
};
Some(Ok(Value::Object(SharedCell::new(Object {
class: "object".to_string(),
properties: table,
}))))
}
None => Some(Err(rt.no_property(this, &name, line))),
}
}
"defineprop" => {
if key == STATE {
return failure("the state of an array is not a property of it.");
}
let descriptor = match rt.the_descriptor(arguments.get(1), line) {
Ok(descriptor) => descriptor,
Err(failure) => return Some(Err(failure)),
};
put(&mut object.borrow_mut().properties, &name, descriptor);
Some(Ok(this.clone()))
}
"deleteprop" => {
if key == STATE {
return Some(Ok(Value::Text(String::new())));
}
let gone = object
.borrow_mut()
.properties
.remove(&key)
.map(|property| property.value);
Some(Ok(match gone {
None => Value::Text(String::new()),
Some(value) => match rt.the_value_of_the_descriptor(&value, this, &name, line) {
Ok(Some(value)) => value,
_ => value,
},
}))
}
_ => None,
}
}
fn own_property(object: &SharedCell<Object>, key: &str) -> bool {
key != STATE && object.borrow().properties.contains_key(key)
}
fn the_places_of_the_walk(start: usize, forward: bool, len: usize) -> Vec<usize> {
if forward {
(start..len).collect()
} else {
(0..=start).rev().collect()
}
}
fn the_start_of_the_search(start: i64, len: i64) -> Option<(usize, bool)> {
if start == 0 || start.unsigned_abs() as i64 > len {
return None;
}
if start > 0 {
Some(((start - 1) as usize, true))
} else {
Some(((len + start) as usize, false))
}
}
fn the_start_of_the_arguments(
arguments: &[Value],
who: &str,
line: u32,
) -> Result<i64, RuntimeFailure> {
let Some(value) = arguments.get(1) else {
return Ok(1);
};
let text = value.to_text();
let Ok(start) = text.trim().parse::<i64>() else {
return Err(crate::classes::the_failure_with(
&alloc::format!("Parameter #2 of Array.Prototype.{who} is invalid."),
&text,
line,
));
};
Ok(start)
}
fn the_search_matches(left: &Value, right: &Value) -> bool {
match (left, right) {
(Value::Object(one), Value::Object(other)) => SharedCell::ptr_eq(one, other),
(Value::Object(_), _) | (_, Value::Object(_)) => false,
(Value::Text(one), Value::Text(other)) => one == other,
(Value::Int(one), Value::Int(other)) => one == other,
(Value::Float(one), Value::Float(other)) => one == other,
(Value::Int(one), Value::Float(other)) | (Value::Float(other), Value::Int(one)) => {
(*one as f64) == *other
}
(Value::Unset, Value::Unset) => true,
_ => false,
}
}
fn the_place_of_the_match(
items: &[Value],
wanted: &Value,
arguments: &[Value],
who: &str,
_rt: &mut Runtime,
line: u32,
) -> Result<i64, RuntimeFailure> {
let len = items.len() as i64;
if len == 0 {
return Ok(0);
}
let start = the_start_of_the_arguments(arguments, who, line)?;
let Some((from, forward)) = the_start_of_the_search(start, len) else {
let text = arguments.get(1).map(|v| v.to_text()).unwrap_or_default();
return Err(crate::classes::the_failure_with(
&alloc::format!("Parameter #2 of Array.Prototype.{who} is invalid."),
&text,
line,
));
};
for place in the_places_of_the_walk(from, forward, items.len()) {
if let Some(item) = element_value(&items[place]) {
if the_search_matches(&item, wanted) {
return Ok(place as i64 + 1);
}
}
}
Ok(0)
}
fn the_call_of_the_callback(
callback: &Value,
item: &Value,
place: i64,
who: &str,
rt: &mut Runtime,
line: u32,
) -> Result<Value, RuntimeFailure> {
let invalid = || {
crate::classes::the_failure_with(
&alloc::format!("Parameter #1 of Array.Prototype.{who} is invalid."),
"a function",
line,
)
};
let Value::Object(_) = callback else {
return Err(invalid());
};
let count = rt.the_count_of_the_parameters_of_a_function(callback) as i64;
let arguments = if count >= 2 {
vec![item.clone(), Value::Int(place)]
} else {
vec![item.clone()]
};
match crate::classes::func::call_the_value(callback, &arguments, rt, line) {
Some(result) => result,
None => Err(invalid()),
}
}
fn the_sign_of(value: &Value) -> f64 {
match value {
Value::Int(number) => number.signum() as f64,
Value::Float(number) => number.signum(),
Value::Text(text) => text
.trim()
.parse::<f64>()
.map(|n| n.signum())
.unwrap_or(0.0),
_ => 0.0,
}
}
pub(crate) fn the_text_of_an_element(item: &Value, rt: &mut Runtime, line: u32) -> String {
let Some(value) = element_value(item) else {
return "unset".to_string();
};
the_text_of_a_value(&value, rt, line)
}
pub(crate) fn the_text_of_a_value(value: &Value, rt: &mut Runtime, line: u32) -> String {
match value {
Value::Text(text) => {
let mut out = String::from("\"");
for character in text.chars() {
if character == '"' || character == '\\' {
out.push('\\');
}
out.push(character);
}
out.push('"');
out
}
Value::Object(object) => {
let class = object.borrow().class.clone();
match crate::classes::call(&class, "tostring", value, &[], rt, line) {
Some(Ok(text)) => text.to_text(),
Some(Err(_)) => "<ERROR>".to_string(),
None => crate::classes::the_spelling_of(&class),
}
}
other => other.to_text(),
}
}
fn the_extension_answer(
method: &str,
this: &Value,
arguments: &[Value],
rt: &mut Runtime,
line: u32,
) -> Option<Result<Value, RuntimeFailure>> {
let invalid_first = |who: &str, extra: &str| {
crate::classes::the_failure_with(
&alloc::format!("Parameter #1 of Array.Prototype.{who} is invalid."),
extra,
line,
)
};
let Some(state) = state(this) else {
return Some(Err(RuntimeFailure::Error(RuntimeError {
message: "Invalid index.".to_string(),
line,
})));
};
let items = items(&state.borrow());
match method {
"contains" => {
let wanted = arguments.first().cloned().unwrap_or(Value::Unset);
let found =
match the_place_of_the_match(&items, &wanted, arguments, "Contains", rt, line) {
Ok(found) => found,
Err(failure) => return Some(Err(failure)),
};
Some(Ok(Value::Int((found != 0) as i64)))
}
"indexof" => {
let wanted = arguments.first().cloned().unwrap_or(Value::Unset);
let found =
match the_place_of_the_match(&items, &wanted, arguments, "IndexOf", rt, line) {
Ok(found) => found,
Err(failure) => return Some(Err(failure)),
};
Some(Ok(Value::Int(found)))
}
"findindex" => {
let Some(callback) = arguments.first().cloned() else {
return Some(Err(invalid_first("FindIndex", "a function")));
};
let len = items.len() as i64;
if len == 0 {
return Some(Ok(Value::Int(0)));
}
let start = match the_start_of_the_arguments(arguments, "FindIndex", line) {
Ok(start) => start,
Err(failure) => return Some(Err(failure)),
};
let Some((from, forward)) = the_start_of_the_search(start, len) else {
let text = arguments.get(1).map(|v| v.to_text()).unwrap_or_default();
return Some(Err(invalid_first("FindIndex", &text)));
};
for place in the_places_of_the_walk(from, forward, items.len()) {
let item = element_value(&items[place]).unwrap_or(Value::Unset);
let answer = match the_call_of_the_callback(
&callback,
&item,
place as i64 + 1,
"FindIndex",
rt,
line,
) {
Ok(answer) => answer,
Err(failure) => return Some(Err(failure)),
};
if answer.truthy() {
return Some(Ok(Value::Int(place as i64 + 1)));
}
}
Some(Ok(Value::Int(0)))
}
"filter" | "map" => {
let who = if method == "filter" { "Filter" } else { "Map" };
let Some(callback) = arguments.first().cloned() else {
return Some(Err(invalid_first(who, "a function")));
};
if items.is_empty() {
return Some(Ok(crate::classes::object_with(
"array",
vec![(STATE, new_state(Vec::new(), 0))],
)));
}
let start = match the_start_of_the_arguments(arguments, who, line) {
Ok(start) => start,
Err(failure) => return Some(Err(failure)),
};
let Some((from, forward)) = the_start_of_the_search(start, items.len() as i64) else {
let text = arguments.get(1).map(|v| v.to_text()).unwrap_or_default();
return Some(Err(invalid_first(who, &text)));
};
let mut out = Vec::new();
for place in the_places_of_the_walk(from, forward, items.len()) {
let item = element_value(&items[place]).unwrap_or(Value::Unset);
let answer = match the_call_of_the_callback(
&callback,
&item,
place as i64 + 1,
who,
rt,
line,
) {
Ok(answer) => answer,
Err(failure) => return Some(Err(failure)),
};
if method == "filter" {
if answer.truthy() {
out.push(items[place].clone());
}
} else {
out.push(element(Some(answer)));
}
}
Some(Ok(crate::classes::object_with(
"array",
vec![(STATE, new_state(out, 0))],
)))
}
"join" => {
let separator = arguments
.first()
.map(|value| value.to_text())
.unwrap_or_else(|| ",".to_string());
let parts: Vec<String> = items
.iter()
.map(|item| {
element_value(item)
.map(|value| value.to_text())
.unwrap_or_default()
})
.collect();
Some(Ok(Value::Text(parts.join(&separator))))
}
"remove" => {
if items.is_empty() {
return Some(Ok(Value::Int(0)));
}
let found = match arguments.first() {
None => items
.iter()
.position(|item| element_value(item).is_none())
.map(|place| place as i64 + 1)
.unwrap_or(0),
Some(wanted) => {
match the_place_of_the_match(&items, wanted, arguments, "Remove", rt, line) {
Ok(found) => found,
Err(failure) => return Some(Err(failure)),
}
}
};
if found == 0 {
return Some(Ok(Value::Int(0)));
}
let mut owned = items;
owned.remove((found - 1) as usize);
set_items(&mut state.borrow_mut(), owned);
Some(Ok(Value::Int(1)))
}
"sort" => {
let Some(callback) = arguments.first().cloned() else {
return Some(Err(invalid_first("Sort", "a function")));
};
if items.len() < 2 {
return Some(Ok(this.clone()));
}
let mut sorted = items;
let failure: RefCell<Option<RuntimeFailure>> = RefCell::new(None);
sorted.sort_by(|one, other| {
if failure.borrow().is_some() {
return core::cmp::Ordering::Equal;
}
let first = element_value(one).unwrap_or(Value::Unset);
let second = element_value(other).unwrap_or(Value::Unset);
let answer = match crate::classes::func::call_the_value(
&callback,
&[first, second],
rt,
line,
) {
Some(Ok(answer)) => answer,
Some(Err(raise)) => {
*failure.borrow_mut() = Some(raise);
return core::cmp::Ordering::Equal;
}
None => {
*failure.borrow_mut() = Some(invalid_first("Sort", "a function"));
return core::cmp::Ordering::Equal;
}
};
let sign = the_sign_of(&answer);
sign.partial_cmp(&0.0).unwrap_or(core::cmp::Ordering::Equal)
});
if let Some(failure) = failure.into_inner() {
return Some(Err(failure));
}
set_items(&mut state.borrow_mut(), sorted);
Some(Ok(this.clone()))
}
"tostring" => {
let mut out = String::new();
out.push('[');
for (index, item) in items.iter().enumerate() {
if index > 0 {
out.push_str(", ");
}
out.push_str(&the_text_of_an_element(item, rt, line));
}
out.push(']');
Some(Ok(Value::Text(out)))
}
_ => None,
}
}