use crate::heap::{Heap, StringId, SymbolId};
use crate::value::{Value, canonical_numeric_index};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum PropertyKey {
Index(u32),
String(StringId),
Symbol(SymbolId),
}
pub(crate) const MAX_INDEX: u32 = u32::MAX - 1;
#[must_use]
pub fn index_of(units: &[u16]) -> Option<u32> {
if units.is_empty() || units.len() > 10 {
return None;
}
if units[0] == u16::from(b'0') {
return (units.len() == 1).then_some(0);
}
let mut value = 0_u64;
for unit in units {
let digit = u64::from(*unit).checked_sub(u64::from(b'0'))?;
if digit > 9 {
return None;
}
value = value * 10 + digit;
}
(value <= u64::from(MAX_INDEX)).then_some(value as u32)
}
impl PropertyKey {
pub fn from_units(heap: &mut Heap, units: &[u16]) -> Self {
match index_of(units) {
Some(index) => Self::Index(index),
None => Self::String(heap.intern(units)),
}
}
#[must_use]
pub fn from_index(index: u32) -> Self {
Self::Index(index)
}
pub fn from_symbol(id: SymbolId) -> Self {
Self::Symbol(id)
}
pub fn from_string(heap: &mut Heap, id: StringId) -> Self {
match heap.string(id).and_then(index_of) {
Some(index) => Self::Index(index),
None => Self::String(heap.intern_id(id)),
}
}
pub fn to_value(self, heap: &mut Heap) -> crate::value::Value {
match self {
Self::Index(index) => crate::value::Value::String(spell(heap, index)),
Self::String(id) => crate::value::Value::String(id),
Self::Symbol(id) => crate::value::Value::Symbol(id),
}
}
pub fn spelling(self, heap: &mut Heap) -> Option<StringId> {
match self {
Self::Index(index) => Some(spell(heap, index)),
Self::String(id) => Some(id),
Self::Symbol(_) => None,
}
}
#[must_use]
pub fn spells(self, heap: &Heap, units: &[u16]) -> bool {
match self {
Self::Index(index) => index_of(units) == Some(index),
Self::String(id) => heap.string(id) == Some(units),
Self::Symbol(_) => false,
}
}
#[must_use]
pub fn describe(self, heap: &Heap) -> Option<String> {
match self {
Self::Index(index) => Some(index.to_string()),
Self::String(id) => heap.string(id).map(String::from_utf16_lossy),
Self::Symbol(_) => None,
}
}
#[must_use]
pub fn is_spellable(self) -> bool {
!matches!(self, Self::Symbol(_))
}
pub fn as_symbol(self) -> Option<SymbolId> {
match self {
Self::Symbol(id) => Some(id),
Self::Index(_) | Self::String(_) => None,
}
}
pub fn as_array_index(self) -> Option<u32> {
match self {
Self::Index(index) => Some(index),
Self::String(_) | Self::Symbol(_) => None,
}
}
pub fn as_integer_index(self, heap: &Heap) -> Option<f64> {
let id = match self {
Self::Index(index) => return Some(f64::from(index)),
Self::String(id) => id,
Self::Symbol(_) => return None,
};
let units = heap.string(id)?;
let index = canonical_numeric_index(units)?;
let integral = index.fract() == 0.0;
(integral && index.is_sign_positive() && index <= 9_007_199_254_740_991.0).then_some(index)
}
}
fn spell(heap: &mut Heap, index: u32) -> StringId {
let mut digits = [0_u16; 10];
let mut at = digits.len();
let mut value = index;
loop {
at -= 1;
digits[at] = u16::from(b'0') + u16::try_from(value % 10).unwrap_or(0);
value /= 10;
if value == 0 {
break;
}
}
heap.intern(&digits[at..])
}
#[derive(Debug, Clone, Copy)]
pub struct Property {
pub kind: PropertyKind,
pub enumerable: bool,
pub configurable: bool,
}
#[derive(Debug, Clone, Copy)]
pub enum PropertyKind {
Data {
value: Value,
writable: bool,
},
Accessor {
getter: Value,
setter: Value,
},
}
impl Property {
pub fn to_descriptor(&self) -> PropertyDescriptor {
let mut descriptor = PropertyDescriptor {
enumerable: Some(self.enumerable),
configurable: Some(self.configurable),
..PropertyDescriptor::EMPTY
};
match self.kind {
PropertyKind::Data { value, writable } => {
descriptor.value = Some(value);
descriptor.writable = Some(writable);
}
PropertyKind::Accessor { getter, setter } => {
descriptor.getter = Some(getter);
descriptor.setter = Some(setter);
}
}
descriptor
}
}
#[derive(Debug, Clone, Copy)]
pub struct PropertyDescriptor {
pub value: Option<Value>,
pub writable: Option<bool>,
pub getter: Option<Value>,
pub setter: Option<Value>,
pub enumerable: Option<bool>,
pub configurable: Option<bool>,
}
impl PropertyDescriptor {
pub const EMPTY: Self = Self {
value: None,
writable: None,
getter: None,
setter: None,
enumerable: None,
configurable: None,
};
pub const fn data(value: Value) -> Self {
Self {
value: Some(value),
writable: Some(true),
enumerable: Some(true),
configurable: Some(true),
..Self::EMPTY
}
}
pub fn is_accessor_descriptor(&self) -> bool {
self.getter.is_some() || self.setter.is_some()
}
pub fn is_data_descriptor(&self) -> bool {
self.value.is_some() || self.writable.is_some()
}
pub fn is_generic_descriptor(&self) -> bool {
!self.is_accessor_descriptor() && !self.is_data_descriptor()
}
pub fn complete(&self) -> Self {
let mut completed = *self;
if self.is_generic_descriptor() || self.is_data_descriptor() {
completed.value = completed.value.or(Some(Value::Undefined));
completed.writable = completed.writable.or(Some(false));
} else {
completed.getter = completed.getter.or(Some(Value::Undefined));
completed.setter = completed.setter.or(Some(Value::Undefined));
}
completed.enumerable = completed.enumerable.or(Some(false));
completed.configurable = completed.configurable.or(Some(false));
completed
}
}
#[cfg(test)]
mod tests {
use super::*;
fn key(heap: &mut Heap, text: &str) -> PropertyKey {
PropertyKey::from_units(heap, &text.encode_utf16().collect::<Vec<_>>())
}
#[test]
fn two_keys_spelled_the_same_are_one_key_though_their_strings_were_two() {
let mut heap = Heap::new();
let written = key(&mut heap, "a");
let read = key(&mut heap, "a");
assert_eq!(written, read);
assert_eq!(written.spelling(&mut heap), read.spelling(&mut heap));
assert_ne!(written, key(&mut heap, "b"));
let computed = heap.new_string("a".encode_utf16().collect());
assert_ne!(Some(computed), written.spelling(&mut heap));
assert_eq!(PropertyKey::from_string(&mut heap, computed), written);
}
#[test]
fn every_string_is_a_key_including_the_empty_one_and_a_lone_surrogate() {
let mut heap = Heap::new();
let empty = PropertyKey::from_units(&mut heap, &[]);
let surrogate = PropertyKey::from_units(&mut heap, &[0xd800]);
assert_ne!(empty, surrogate);
assert_eq!(empty, PropertyKey::from_units(&mut heap, &[]));
assert_eq!(
empty.spelling(&mut heap).and_then(|id| heap.string(id)),
Some(&[][..])
);
assert_eq!(empty.as_array_index(), None);
assert_eq!(surrogate.as_integer_index(&heap), None);
}
#[test]
fn only_the_canonical_spelling_of_a_number_is_an_index() {
let mut heap = Heap::new();
for text in ["0", "1", "42", "4294967294", "9007199254740991"] {
assert!(
key(&mut heap, text).as_integer_index(&heap).is_some(),
"{text:?} should be an integer index"
);
}
for text in [
"01", "1.0", "1e0", " 1", "1 ", "+1", "0x1", "1_0", "", "a", "1.5", "NaN",
] {
assert_eq!(
key(&mut heap, text).as_integer_index(&heap),
None,
"{text:?} should not be an integer index"
);
}
}
#[test]
fn minus_zero_is_canonical_and_is_still_not_an_index() {
let mut heap = Heap::new();
assert_eq!(
canonical_numeric_index(&"-0".encode_utf16().collect::<Vec<_>>()),
Some(-0.0)
);
let minus_zero = key(&mut heap, "-0");
assert_eq!(minus_zero.as_integer_index(&heap), None);
assert_eq!(minus_zero.as_array_index(), None);
let plus_zero = key(&mut heap, "0");
assert_eq!(plus_zero.as_array_index(), Some(0));
assert_ne!(minus_zero, plus_zero);
}
#[test]
fn an_array_index_stops_one_short_of_the_largest_length() {
let mut heap = Heap::new();
assert_eq!(
key(&mut heap, "4294967294").as_array_index(),
Some(4_294_967_294)
);
assert_eq!(key(&mut heap, "4294967295").as_array_index(), None);
assert_eq!(
key(&mut heap, "4294967295").as_integer_index(&heap),
Some(4_294_967_295.0)
);
assert_eq!(
key(&mut heap, "9007199254740991").as_integer_index(&heap),
Some(9_007_199_254_740_991.0)
);
assert_eq!(
key(&mut heap, "9007199254740992").as_integer_index(&heap),
None
);
assert_eq!(key(&mut heap, "-1").as_integer_index(&heap), None);
assert_eq!(key(&mut heap, "Infinity").as_integer_index(&heap), None);
}
#[test]
fn one_key_has_one_representation_however_it_was_made() {
let mut heap = Heap::new();
for index in [0_u32, 1, 9, 10, 99, 1_000, 4_294_967_294] {
let spelled = key(&mut heap, &index.to_string());
let counted = PropertyKey::from_index(index);
assert_eq!(spelled, counted, "{index} spelled and counted are two keys");
assert!(
matches!(spelled, PropertyKey::Index(_)),
"{index} kept text"
);
let text = counted.spelling(&mut heap).expect("an index is spellable");
assert_eq!(
heap.string(text).map(<[u16]>::to_vec),
Some(index.to_string().encode_utf16().collect::<Vec<_>>())
);
assert_eq!(PropertyKey::from_string(&mut heap, text), counted);
}
let awkward = key(&mut heap, "01");
assert!(matches!(awkward, PropertyKey::String(_)));
assert_ne!(awkward, PropertyKey::from_index(1));
}
#[test]
fn a_key_spells_its_own_name_and_no_other() {
let mut heap = Heap::new();
let units = |text: &str| text.encode_utf16().collect::<Vec<u16>>();
let one = PropertyKey::from_index(1);
assert!(one.spells(&heap, &units("1")));
assert!(!one.spells(&heap, &units("2")));
assert!(
!one.spells(&heap, &units("01")),
"a non-canonical spelling is another key"
);
assert!(!one.spells(&heap, &units("x")));
let name = key(&mut heap, "x");
assert!(name.spells(&heap, &units("x")));
assert!(!name.spells(&heap, &units("y")));
assert!(!name.spells(&heap, &units("1")));
let symbol = PropertyKey::from_symbol(heap.new_symbol(None));
assert!(!symbol.spells(&heap, &units("x")));
assert!(!symbol.spells(&heap, &units("1")));
assert!(!symbol.spells(&heap, &units("")));
}
#[test]
fn the_cheap_index_test_agrees_with_the_general_one() {
let corpus = [
"",
"0",
"-0",
"00",
"01",
"1",
"1.0",
"1.5",
"1e0",
"1e3",
" 1",
"1 ",
"+1",
"-1",
"0x1",
"1_0",
"a",
"NaN",
"Infinity",
"-Infinity",
"4294967293",
"4294967294",
"4294967295",
"4294967296",
"9007199254740991",
"99999999999",
"0.0",
"10",
"000",
];
for text in corpus {
let units: Vec<u16> = text.encode_utf16().collect();
let general = canonical_numeric_index(&units).filter(|number| {
number.fract() == 0.0
&& number.is_sign_positive()
&& *number <= f64::from(MAX_INDEX)
});
let cheap = index_of(&units).map(f64::from);
assert_eq!(cheap, general, "{text:?} is judged two different ways");
}
}
#[test]
fn a_descriptor_is_classified_by_which_fields_it_has_not_by_their_values() {
let undefined_getter = PropertyDescriptor {
getter: Some(Value::Undefined),
..PropertyDescriptor::EMPTY
};
assert!(undefined_getter.is_accessor_descriptor());
assert!(!undefined_getter.is_data_descriptor());
assert!(!undefined_getter.is_generic_descriptor());
let undefined_value = PropertyDescriptor {
value: Some(Value::Undefined),
..PropertyDescriptor::EMPTY
};
assert!(undefined_value.is_data_descriptor());
assert!(!undefined_value.is_accessor_descriptor());
let writable_only = PropertyDescriptor {
writable: Some(false),
..PropertyDescriptor::EMPTY
};
assert!(writable_only.is_data_descriptor());
let setter_only = PropertyDescriptor {
setter: Some(Value::Undefined),
..PropertyDescriptor::EMPTY
};
assert!(setter_only.is_accessor_descriptor());
let attributes_only = PropertyDescriptor {
enumerable: Some(true),
..PropertyDescriptor::EMPTY
};
assert!(attributes_only.is_generic_descriptor());
assert!(PropertyDescriptor::EMPTY.is_generic_descriptor());
}
#[test]
fn completing_a_descriptor_fills_in_one_kind_and_never_both() {
let completed = PropertyDescriptor::EMPTY.complete();
assert!(matches!(completed.value, Some(Value::Undefined)));
assert_eq!(completed.writable, Some(false));
assert!(completed.getter.is_none());
assert!(completed.setter.is_none());
assert_eq!(completed.enumerable, Some(false));
assert_eq!(completed.configurable, Some(false));
let accessor = PropertyDescriptor {
getter: Some(Value::Undefined),
enumerable: Some(true),
..PropertyDescriptor::EMPTY
};
let completed = accessor.complete();
assert!(matches!(completed.setter, Some(Value::Undefined)));
assert!(completed.value.is_none());
assert!(completed.writable.is_none());
assert_eq!(completed.enumerable, Some(true));
assert_eq!(completed.configurable, Some(false));
}
#[test]
fn a_stored_property_describes_itself_with_the_fields_of_its_own_kind() {
let data = Property {
kind: PropertyKind::Data {
value: Value::Number(1.0),
writable: true,
},
enumerable: true,
configurable: false,
};
let descriptor = data.to_descriptor();
assert!(descriptor.is_data_descriptor());
assert!(!descriptor.is_accessor_descriptor());
assert_eq!(descriptor.writable, Some(true));
assert_eq!(descriptor.enumerable, Some(true));
assert_eq!(descriptor.configurable, Some(false));
assert!(descriptor.getter.is_none());
let accessor = Property {
kind: PropertyKind::Accessor {
getter: Value::Number(0.0),
setter: Value::Undefined,
},
enumerable: false,
configurable: true,
};
let descriptor = accessor.to_descriptor();
assert!(descriptor.is_accessor_descriptor());
assert!(!descriptor.is_data_descriptor());
assert!(matches!(descriptor.setter, Some(Value::Undefined)));
assert!(descriptor.value.is_none());
let completed = descriptor.complete();
assert!(completed.value.is_none());
assert_eq!(completed.configurable, Some(true));
}
}