use super::realm::{self, BuiltinProto, Ctor, Intrinsic, Method};
use super::{
INVALID_STRING_LENGTH, JsString, JsStringBuilder, MAX_STRING_LENGTH, Object, Proto,
RANGE_ERROR, Value,
};
use crate::markdown_it::js;
use crate::next::realm::{Builtin, Called, Wrapped};
use std::borrow::Cow;
use std::collections::BTreeMap;
use std::sync::Arc;
pub const NO_PRIMITIVE: &str = "TypeError: Cannot convert object to primitive value";
pub const NOT_AN_OBJECT: &str = "TypeError: Cannot convert undefined or null to object";
pub fn type_of(value: &Value) -> &'static str {
match value {
Value::Undefined => "undefined",
Value::Null | Value::Array(_) | Value::Object(_) | Value::Tag(_) => "object",
Value::Builtin(b) if b.is_callable() => "function",
Value::Builtin(_) => "object",
Value::Boolean(_) => "boolean",
Value::Number(_) => "number",
Value::String(_) => "string",
}
}
pub fn is_array(value: &Value) -> bool {
match value {
Value::Array(_) => true,
Value::Builtin(b) => b.is_array(),
_ => false,
}
}
pub fn is_callable(value: &Value) -> bool {
matches!(value, Value::Builtin(b) if b.is_callable())
}
pub fn prototype_of(value: &Value) -> Option<Proto> {
Some(match value {
Value::Undefined | Value::Null => return None,
Value::Boolean(_) => Proto::Builtin(BuiltinProto::BOOLEAN_PROTOTYPE),
Value::Number(_) => Proto::Builtin(BuiltinProto::NUMBER_PROTOTYPE),
Value::String(_) => Proto::Builtin(BuiltinProto::STRING_PROTOTYPE),
Value::Array(_) => Proto::Builtin(BuiltinProto::ARRAY_PROTOTYPE),
Value::Object(o) => o.proto().clone(),
Value::Tag(_) => Proto::Builtin(BuiltinProto::TAG_PROTOTYPE),
Value::Builtin(b) => match b.proto() {
Some(p) => Proto::Builtin(p),
None => Proto::Null,
},
})
}
pub fn has_object_prototype(value: &Value) -> bool {
matches!(value, Value::Object(o) if o.proto().is_object_prototype())
}
fn index_of(key: &str) -> Option<u32> {
crate::types::array_index(key)
}
pub fn own_property(value: &Value, key: &str) -> Option<Value> {
match value {
Value::Undefined | Value::Null | Value::Boolean(_) | Value::Number(_) => None,
Value::String(s) => {
if key == "length" {
return Some(Value::Number(s.len_utf16() as f64));
}
let i = index_of(key)? as usize;
s.code_units()
.nth(i)
.map(|unit| Value::String(JsString::from_code_unit(unit)))
}
Value::Array(items) => {
if key == "length" {
return Some(Value::Number(items.len() as f64));
}
match index_of(key) {
Some(i) => items.get(i as usize).cloned(),
None => items.named_get(key).cloned(),
}
}
Value::Object(o) => o.get(key).cloned(),
Value::Tag(tag) => match key {
"$$mdtype" => Some(Value::string("Tag")),
"name" => Some(tag.name.clone()),
"attributes" => Some(Value::Object(Arc::new(tag.attributes.clone()))),
"children" => Some(Value::array(tag.children.clone())),
_ => None,
},
Value::Builtin(b) => match &b.own(key)?.slot {
crate::next::realm::Slot::Data(d) => Some(d.to_value()),
crate::next::realm::Slot::Accessor { .. } => None,
},
}
}
fn has_own(value: &Value, key: &str) -> bool {
match value {
Value::Undefined | Value::Null | Value::Boolean(_) | Value::Number(_) => false,
Value::String(s) => {
key == "length" || index_of(key).is_some_and(|i| (i as usize) < s.len_utf16())
}
Value::Array(items) => {
key == "length"
|| match index_of(key) {
Some(i) => items.get(i as usize).is_some(),
None => items.named_get(key).is_some(),
}
}
Value::Object(o) => o.contains_key(key),
Value::Tag(_) => matches!(key, "$$mdtype" | "name" | "attributes" | "children"),
Value::Builtin(b) => b.own(key).is_some(),
}
}
#[derive(Debug, Clone)]
pub enum Found {
Value(Value),
Builtin(BuiltinProto, Intrinsic),
}
impl Found {
pub fn is_undefined(&self) -> bool {
matches!(
self,
Found::Value(Value::Undefined) | Found::Builtin(_, Intrinsic::Absent)
)
}
pub fn is_truthy(&self) -> bool {
match self {
Found::Value(v) => v.to_boolean(),
Found::Builtin(_, i) => *i != Intrinsic::Absent,
}
}
}
pub fn read_error(value: &Value, key: &str) -> String {
format!(
"TypeError: Cannot read properties of {} (reading '{key}')",
if value.is_undefined() {
"undefined"
} else {
"null"
}
)
}
pub fn lookup(value: &Value, key: &str) -> Result<Found, String> {
if value.is_nullish() {
return Err(read_error(value, key));
}
if let Value::Builtin(b) = value {
return at_builtin(*b, key, value);
}
if let Some(v) = own_property(value, key) {
return Ok(Found::Value(v));
}
let mut proto = prototype_of(value);
loop {
match proto {
None | Some(Proto::Null) => return Ok(Found::Value(Value::Undefined)),
Some(Proto::Builtin(p)) => return at_builtin(p, key, value),
Some(Proto::Value(p)) => {
if let Some(v) = own_property(&p, key) {
return Ok(Found::Value(v));
}
proto = prototype_of(&p);
}
}
}
}
fn at_builtin(p: BuiltinProto, key: &str, receiver: &Value) -> Result<Found, String> {
Ok(match realm::intrinsic(p, key) {
i @ (Intrinsic::Method(_) | Intrinsic::Ctor(_) | Intrinsic::Absent) => Found::Builtin(p, i),
Intrinsic::ProtoAccessor | Intrinsic::Other => {
Found::Value(realm::get_inherited(p, key, receiver)?)
}
})
}
pub(crate) enum Callee {
Model(Method),
Realm(Builtin),
None,
}
pub(crate) fn callee(found: Found, this: &Value) -> Callee {
let f = match found {
Found::Builtin(_, Intrinsic::Method(m)) => m.builtin(),
Found::Builtin(_, Intrinsic::Ctor(c)) => c.builtin(),
Found::Builtin(..) => return Callee::None,
Found::Value(Value::Builtin(f)) if f.is_callable() => f,
Found::Value(_) => return Callee::None,
};
match Method::of(f) {
Some(m) if !matches!(this, Value::Builtin(_)) => Callee::Model(m),
_ => Callee::Realm(f),
}
}
pub fn get(value: &Value, key: &str) -> Result<Value, String> {
match lookup(value, key)? {
Found::Value(v) => Ok(v),
Found::Builtin(p, _) => realm::get_inherited(p, key, value),
}
}
pub fn get_property(value: &Value, key: &str) -> Result<Value, String> {
get(value, key)
}
pub fn object_get(object: &Object, key: &str) -> Result<Value, String> {
if let Some(v) = object.get(key) {
return Ok(v.clone());
}
let mut proto = object.proto().clone();
loop {
match proto {
Proto::Null => return Ok(Value::Undefined),
Proto::Builtin(p) => {
return match realm::intrinsic(p, key) {
Intrinsic::Absent => Ok(Value::Undefined),
_ => realm::get_inherited(p, key, &Value::Object(Arc::new(object.clone()))),
};
}
Proto::Value(v) => {
if let Some(x) = own_property(&v, key) {
return Ok(x);
}
proto = prototype_of(&v).unwrap_or(Proto::Null);
}
}
}
}
pub fn object_is_undefined_at(object: &Object, key: &str) -> bool {
if let Some(v) = object.get(key) {
return v.is_undefined();
}
match object.proto() {
Proto::Null => true,
Proto::Builtin(p) => realm::intrinsic(*p, key) == Intrinsic::Absent,
Proto::Value(v) => lookup(v, key).is_ok_and(|f| f.is_undefined()),
}
}
pub fn object_has_property(object: &Object, key: &str) -> bool {
if object.contains_key(key) {
return true;
}
match object.proto() {
Proto::Null => false,
Proto::Builtin(p) => realm::has_inherited(*p, key),
Proto::Value(v) => has_property(v, key).unwrap_or(false),
}
}
pub fn array_like_elements(value: &Value) -> Result<(u64, Vec<(u64, Value)>), String> {
Ok(match value {
Value::Array(items) => (
items.len() as u64,
items
.present()
.map(|(i, v)| (u64::from(i), v.clone()))
.collect(),
),
Value::Builtin(b) if b.is_array() => (0, Vec::new()),
_ => {
let length = to_length(&get_value(value, "length")?)?.min(f64::from(u32::MAX)) as u64;
(length, chain_elements(value, length))
}
})
}
pub fn is_undefined_at(value: &Value, key: &str) -> Result<bool, String> {
Ok(lookup(value, key)?.is_undefined())
}
pub fn is_truthy_at(value: &Value, key: &str) -> Result<bool, String> {
Ok(lookup(value, key)?.is_truthy())
}
pub fn has_property(value: &Value, key: &str) -> Result<bool, String> {
if !value.is_object() {
return Err(format!(
"TypeError: Cannot use 'in' operator to search for '{key}' in {}",
to_js_string(value)
.map(JsString::into_string_lossy)
.unwrap_or_default()
));
}
let mut at = value.clone();
loop {
if has_own(&at, key) {
return Ok(true);
}
match prototype_of(&at) {
None | Some(Proto::Null) => return Ok(false),
Some(Proto::Builtin(p)) => return Ok(realm::has_inherited(p, key)),
Some(Proto::Value(p)) => at = p,
}
}
}
pub fn has_own_property(value: &Value, key: &str) -> Result<bool, String> {
if value.is_nullish() {
return Err(NOT_AN_OBJECT.into());
}
Ok(has_own(value, key))
}
pub fn set(object: &mut Object, key: String, value: Value) {
if let Some(slot) = object.get_mut(&key) {
*slot = value;
return;
}
if inherits_setter(object.proto(), &key) {
if let Some(proto) = Proto::from_value(&value) {
object.set_proto(proto);
}
return;
}
object.insert(key, value);
}
pub fn inherits_setter(proto: &Proto, key: &str) -> bool {
if key != "__proto__" {
return false;
}
let mut at = proto.clone();
loop {
match at {
Proto::Null => return false,
Proto::Builtin(p) => return realm::intrinsic(p, key) == Intrinsic::ProtoAccessor,
Proto::Value(v) => {
if has_own(&v, key) {
return false;
}
at = prototype_of(&v).unwrap_or(Proto::Null);
}
}
}
}
pub fn own_entries(value: &Value) -> Vec<(String, Value)> {
match value {
Value::Builtin(b) => b
.data()
.props
.iter()
.filter(|p| p.attrs & crate::next::realm::ENUMERABLE != 0)
.map(|p| {
let v = match &p.slot {
crate::next::realm::Slot::Data(d) => d.to_value(),
crate::next::realm::Slot::Accessor { .. } => Value::Undefined,
};
(p.key.to_string(), v)
})
.collect(),
Value::Undefined | Value::Null | Value::Boolean(_) | Value::Number(_) => Vec::new(),
Value::String(s) => s
.code_units()
.enumerate()
.map(|(i, unit)| (i.to_string(), Value::String(JsString::from_code_unit(unit))))
.collect(),
Value::Array(items) => items
.present()
.map(|(i, v)| (i.to_string(), v.clone()))
.chain(items.named().map(|(k, v)| (k.clone(), v.clone())))
.collect(),
Value::Object(o) => o.iter().map(|(k, v)| (k.clone(), v.clone())).collect(),
Value::Tag(tag) => vec![
("$$mdtype".into(), Value::string("Tag")),
("name".into(), tag.name.clone()),
(
"attributes".into(),
Value::Object(Arc::new(tag.attributes.clone())),
),
("children".into(), Value::array(tag.children.clone())),
],
}
}
pub fn own_entries_of(value: &Value) -> Result<Vec<(String, Value)>, String> {
if value.is_nullish() {
return Err(NOT_AN_OBJECT.into());
}
Ok(own_entries(value))
}
pub fn own_values_of(value: &Value) -> Result<Vec<Value>, String> {
Ok(own_entries_of(value)?.into_iter().map(|(_, v)| v).collect())
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Hint {
String,
Number,
Default,
}
enum Plan {
Primitive(Value),
Join(Value),
}
fn primitive_plan(object: &Value, hint: Hint) -> Result<Plan, String> {
let order: [&str; 2] = match hint {
Hint::String => ["toString", "valueOf"],
Hint::Number | Hint::Default => ["valueOf", "toString"],
};
for name in order {
let callee = match callee(lookup(object, name)?, object) {
Callee::Model(method) if !is_conversion(method) => Callee::Realm(method.builtin()),
other => other,
};
match callee {
Callee::Model(method) => {
if let Some(plan) = call_conversion(method, object)? {
return Ok(plan);
}
}
Callee::Realm(f) => {
if let Some(primitive) = crate::next::realm::call(f, object, &[])?.primitive() {
return Ok(Plan::Primitive(primitive));
}
}
Callee::None => {}
}
}
Err(NO_PRIMITIVE.into())
}
fn is_conversion(method: Method) -> bool {
matches!(
method,
Method::ObjectToString
| Method::ObjectValueOf
| Method::ArrayToString
| Method::ArrayJoin
| Method::StringToString
| Method::StringValueOf
| Method::NumberToString
| Method::NumberValueOf
| Method::BooleanToString
| Method::BooleanValueOf
)
}
fn call_conversion(method: Method, object: &Value) -> Result<Option<Plan>, String> {
Ok(Some(match method {
Method::ObjectToString => Plan::Primitive(Value::string(object_to_string(object))),
Method::ObjectValueOf => return Ok(None),
Method::ArrayToString => match callee(lookup(object, "join")?, object) {
Callee::Model(Method::ArrayJoin) => Plan::Join(object.clone()),
Callee::Model(m) => match crate::next::realm::call(m.builtin(), object, &[])? {
Called::Value(v) if !v.is_object() => Plan::Primitive(v),
_ => return Ok(None),
},
Callee::Realm(f) => match crate::next::realm::call(f, object, &[])? {
Called::Value(v) if !v.is_object() => Plan::Primitive(v),
_ => return Ok(None),
},
Callee::None => Plan::Primitive(Value::string(object_to_string(object))),
},
Method::ArrayJoin => Plan::Join(object.clone()),
Method::StringToString | Method::StringValueOf => {
return Err(this_error("String", method_name(method)));
}
Method::NumberToString | Method::NumberValueOf => {
return Err(this_error("Number", method_name(method)));
}
Method::BooleanToString | Method::BooleanValueOf => {
return Err(this_error("Boolean", method_name(method)));
}
_ => return Ok(None),
}))
}
fn method_name(method: Method) -> &'static str {
match method {
Method::StringToString | Method::NumberToString | Method::BooleanToString => "toString",
_ => "valueOf",
}
}
fn this_error(class: &str, method: &str) -> String {
format!("TypeError: {class}.prototype.{method} requires that 'this' be a {class}")
}
fn object_to_string(object: &Value) -> &'static str {
if is_array(object) {
"[object Array]"
} else {
"[object Object]"
}
}
pub fn to_primitive(value: &Value, hint: Hint) -> Result<Value, String> {
if !value.is_object() {
return Ok(value.clone());
}
match primitive_plan(value, hint)? {
Plan::Primitive(p) => Ok(p),
Plan::Join(o) => Ok(Value::String(join_with(&o, &JsString::from(","))?)),
}
}
pub fn to_js_string(value: &Value) -> Result<JsString, String> {
Ok(match value {
Value::Undefined => "undefined".into(),
Value::Null => "null".into(),
Value::Boolean(b) => (if *b { "true" } else { "false" }).into(),
Value::Number(n) => js::number_to_string(*n).into(),
Value::String(s) => s.clone(),
Value::Array(_) | Value::Object(_) | Value::Tag(_) | Value::Builtin(_) => {
return match primitive_plan(value, Hint::String)? {
Plan::Primitive(p) => to_js_string(&p),
Plan::Join(o) => join_with(&o, &JsString::from(",")),
};
}
})
}
pub fn to_number(value: &Value) -> Result<f64, String> {
Ok(match value {
Value::Undefined => f64::NAN,
Value::Null => 0.0,
Value::Boolean(b) => f64::from(u8::from(*b)),
Value::Number(n) => *n,
Value::String(s) => js::string_to_number(&s.to_utf16()),
Value::Array(_) | Value::Object(_) | Value::Tag(_) | Value::Builtin(_) => {
return to_number(&to_primitive(value, Hint::Number)?);
}
})
}
pub fn to_property_key(value: &Value) -> Result<String, String> {
Ok(to_js_string(value)?.into_string_lossy())
}
fn to_length(value: &Value) -> Result<f64, String> {
let n = to_number(value)?;
if n.is_nan() || n <= 0.0 {
return Ok(0.0);
}
Ok(n.trunc().min(9_007_199_254_740_991.0))
}
pub fn array_join(value: &Value, separator: &Value) -> Result<JsString, String> {
let separator = match separator {
Value::Undefined => JsString::from(","),
other => to_js_string(other)?,
};
join_with(value, &separator)
}
fn chain_elements(value: &Value, length: u64) -> Vec<(u64, Value)> {
let mut found: BTreeMap<u64, Value> = BTreeMap::new();
let mut at = Some(value.clone());
while let Some(v) = at.take() {
match &v {
Value::Array(items) => {
for (i, x) in items.present() {
if u64::from(i) >= length {
break;
}
found.entry(u64::from(i)).or_insert_with(|| x.clone());
}
}
Value::Object(o) => {
for (k, x) in o.iter() {
match index_of(k) {
Some(i) if u64::from(i) < length => {
found.entry(u64::from(i)).or_insert_with(|| x.clone());
}
Some(_) => {}
None => break,
}
}
}
Value::String(s) => {
for (i, unit) in s.code_units().enumerate() {
if i as u64 >= length {
break;
}
found
.entry(i as u64)
.or_insert_with(|| Value::String(JsString::from_code_unit(unit)));
}
}
_ => {}
}
if let Some(Proto::Value(p)) = prototype_of(&v) {
at = Some(p);
}
}
found.into_iter().collect()
}
struct JoinFrame {
elements: std::vec::IntoIter<(u64, Value)>,
length: u64,
pieces: Vec<(u64, JsString)>,
}
impl JoinFrame {
fn new(value: &Value) -> Result<JoinFrame, String> {
let (length, elements) = match value {
Value::Array(items) => (
items.len() as u64,
items
.present()
.map(|(i, v)| (u64::from(i), v.clone()))
.collect::<Vec<_>>(),
),
_ => {
let length = to_length(&get_value(value, "length")?)?;
if length > f64::from(u32::MAX) {
return Err("TypeError: Invalid array length".into());
}
let length = length as u64;
(length, chain_elements(value, length))
}
};
Ok(JoinFrame {
elements: elements.into_iter(),
length,
pieces: Vec::new(),
})
}
fn finish(self, separator: &JsString) -> Result<JsString, String> {
let separators = self.length.saturating_sub(1);
let sep_units = separator.len_utf16() as u64;
let units = self
.pieces
.iter()
.map(|(_, s)| s.len_utf16() as u64)
.sum::<u64>()
+ separators * sep_units;
if units > MAX_STRING_LENGTH as u64 {
return Err(INVALID_STRING_LENGTH.into());
}
let mut out = JsStringBuilder::new();
let repeat = |out: &mut JsStringBuilder, n: u64| {
if sep_units > 0 {
for _ in 0..n {
out.push_js(separator);
}
}
};
let mut written = 0u64;
for (i, piece) in &self.pieces {
repeat(&mut out, i - written);
written = *i;
out.push_js(piece);
}
repeat(&mut out, separators - written.min(separators));
Ok(out.finish())
}
}
fn join_with(value: &Value, separator: &JsString) -> Result<JsString, String> {
let limit = usize::try_from(crate::depth::left() / super::JOIN_COST).unwrap_or(usize::MAX);
if limit == 0 {
return Err(RANGE_ERROR.into());
}
let mut stack = vec![JoinFrame::new(value)?];
loop {
let next = stack.last_mut().expect("a frame").elements.next();
let Some((i, element)) = next else {
let frame = stack.pop().expect("a frame");
let s = frame.finish(separator)?;
match stack.last_mut() {
None => return Ok(s),
Some(parent) => parent.pieces.last_mut().expect("its placeholder").1 = s,
}
continue;
};
let piece = match &element {
Value::Undefined | Value::Null => JsString::new(),
Value::Array(_) | Value::Object(_) | Value::Tag(_) | Value::Builtin(_) => {
match primitive_plan(&element, Hint::String)? {
Plan::Primitive(p) => to_js_string(&p)?,
Plan::Join(o) => {
if stack.len() >= limit {
return Err(RANGE_ERROR.into());
}
let inner = JoinFrame::new(&o)?;
stack
.last_mut()
.expect("a frame")
.pieces
.push((i, JsString::new()));
stack.push(inner);
continue;
}
}
}
other => to_js_string(other)?,
};
stack.last_mut().expect("a frame").pieces.push((i, piece));
}
}
pub(crate) fn get_value(value: &Value, key: &str) -> Result<Value, String> {
get(value, key)
}
pub fn strict_equals(a: &Value, b: &Value) -> bool {
match (a, b) {
(Value::Undefined, Value::Undefined) | (Value::Null, Value::Null) => true,
(Value::Boolean(x), Value::Boolean(y)) => x == y,
(Value::Number(x), Value::Number(y)) => x == y,
(Value::String(x), Value::String(y)) => x == y,
(Value::Array(x), Value::Array(y)) => Arc::ptr_eq(x, y),
(Value::Object(x), Value::Object(y)) => Arc::ptr_eq(x, y),
(Value::Tag(x), Value::Tag(y)) => Arc::ptr_eq(x, y),
(Value::Builtin(x), Value::Builtin(y)) => x == y,
_ => false,
}
}
pub fn same_value_zero(a: &Value, b: &Value) -> bool {
match (a, b) {
(Value::Number(x), Value::Number(y)) if x.is_nan() && y.is_nan() => true,
_ => strict_equals(a, b),
}
}
pub fn truthy(value: &Value) -> bool {
!matches!(
value,
Value::Boolean(false) | Value::Undefined | Value::Null
)
}
pub fn species_check(array: &Value) -> Result<(), String> {
if !is_array(array) {
return Ok(());
}
match lookup(array, "constructor")? {
Found::Builtin(..) => Ok(()),
Found::Value(Value::Undefined) => Ok(()),
Found::Value(v) if v.is_object() => Ok(()),
Found::Value(_) => {
Err("TypeError: object.constructor[Symbol.species] is not a constructor".into())
}
}
}
pub fn array_method(
value: &Value,
name: &str,
method: Method,
expression: &str,
) -> Result<(), String> {
match lookup(value, name)? {
Found::Builtin(_, Intrinsic::Method(m)) if m == method => Ok(()),
Found::Value(Value::Builtin(f)) if Method::of(f) == Some(method) => Ok(()),
_ => Err(format!("TypeError: {expression}.{name} is not a function")),
}
}
pub fn constructor_is(value: &Value, ctor: Ctor) -> bool {
match lookup(value, "constructor") {
Ok(Found::Builtin(_, Intrinsic::Ctor(c))) => c == ctor,
Ok(Found::Value(Value::Builtin(f))) => f == ctor.builtin(),
_ => false,
}
}
pub fn is_ast(value: &Value) -> bool {
!value.is_nullish() && is_truthy_at(value, "$$mdtype").unwrap_or(false)
}
pub fn mdtype_is(value: &Value, kind: &str) -> bool {
if value.is_nullish() {
return false;
}
if let Value::Tag(_) = value {
return kind == "Tag";
}
matches!(lookup(value, "$$mdtype"), Ok(Found::Value(Value::String(t))) if t == kind)
}
pub fn json_stringify(value: &Value, gap: &str) -> Result<Option<String>, String> {
let limit = usize::try_from(crate::depth::left() / super::JSON_COST).unwrap_or(usize::MAX);
json_stringify_within(value, gap, limit)
}
enum JsonFrame {
Array {
length: u64,
elements: std::vec::IntoIter<(u64, Value)>,
at: u64,
stepback: usize,
},
Object {
members: std::vec::IntoIter<(String, Value)>,
any: bool,
stepback: usize,
},
}
struct JsonOut {
text: String,
units: u64,
counted: usize,
}
impl JsonOut {
fn units(&mut self) -> Option<u64> {
if self.text.len() <= MAX_STRING_LENGTH {
return None;
}
self.units += self.text[self.counted..].encode_utf16().count() as u64;
self.counted = self.text.len();
Some(self.units)
}
fn check(&mut self) -> Result<(), String> {
match self.units() {
Some(units) if units > MAX_STRING_LENGTH as u64 => Err(INVALID_STRING_LENGTH.into()),
_ => Ok(()),
}
}
fn push(&mut self, s: &str) -> Result<(), String> {
self.text.push_str(s);
self.check()
}
fn repeat(&mut self, s: &str, n: u64) -> Result<(), String> {
let bytes = (s.len() as u64).saturating_mul(n);
if self.text.len() as u64 + bytes > MAX_STRING_LENGTH as u64 {
let units = self.units().unwrap_or(self.text.len() as u64);
let more = (s.encode_utf16().count() as u64).saturating_mul(n);
if units + more > MAX_STRING_LENGTH as u64 {
return Err(INVALID_STRING_LENGTH.into());
}
}
for _ in 0..n {
self.text.push_str(s);
}
self.check()
}
}
fn json_value<'a>(value: &'a Value, key: &str) -> Result<Option<Cow<'a, Value>>, String> {
let to_json = match value {
Value::Undefined => return Ok(None),
Value::Null | Value::Boolean(_) | Value::Number(_) | Value::String(_) => {
return Ok(Some(Cow::Borrowed(value)));
}
Value::Array(items) => items.named_get("toJSON").cloned(),
Value::Object(o) if o.proto().is_object_prototype() => o.get("toJSON").cloned(),
Value::Tag(_) => None,
_ => match lookup(value, "toJSON")? {
Found::Value(v) => Some(v),
Found::Builtin(_, Intrinsic::Method(m)) => Some(Value::Builtin(m.builtin())),
Found::Builtin(..) => None,
},
};
let value = match to_json {
Some(Value::Builtin(f)) if f.is_callable() => {
let called = crate::next::realm::call::at_site(crate::next::realm::Site::Json, || {
crate::next::realm::call(f, value, &[Value::string(key)])
})?;
Cow::Owned(match called {
Called::Value(v) => v,
Called::Wrapper(primitive) => primitive,
})
}
_ => Cow::Borrowed(value),
};
Ok(match &*value {
Value::Undefined => None,
Value::Builtin(b) => match b.data().wrapped {
Some(Wrapped::String(s)) => Some(Cow::Owned(Value::string(s))),
Some(Wrapped::Number(n)) => Some(Cow::Owned(Value::Number(n))),
Some(Wrapped::Boolean(v)) => Some(Cow::Owned(Value::Boolean(v))),
None if b.is_callable() => None,
None => Some(value),
},
_ => Some(value),
})
}
fn serialize(
value: &Value,
out: &mut JsonOut,
indent_len: usize,
) -> Result<Option<JsonFrame>, String> {
match value {
Value::Undefined | Value::Null => out.push("null")?,
Value::Boolean(b) => out.push(if *b { "true" } else { "false" })?,
Value::Number(n) => {
if n.is_finite() {
out.text.push_str(&js::number_to_string(*n));
out.check()?;
} else {
out.push("null")?;
}
}
Value::String(s) => {
quote_json_js_string(s, &mut out.text);
out.check()?;
}
Value::Array(items) => {
return Ok(Some(JsonFrame::Array {
length: items.len() as u64,
elements: items
.present()
.map(|(i, v)| (u64::from(i), v.clone()))
.collect::<Vec<_>>()
.into_iter(),
at: 0,
stepback: indent_len,
}));
}
Value::Object(_) | Value::Tag(_) => {
return Ok(Some(JsonFrame::Object {
members: own_entries(value).into_iter(),
any: false,
stepback: indent_len,
}));
}
Value::Builtin(b) if b.is_array() => {
return Ok(Some(JsonFrame::Array {
length: 0,
elements: Vec::new().into_iter(),
at: 0,
stepback: indent_len,
}));
}
Value::Builtin(_) => {
return Ok(Some(JsonFrame::Object {
members: own_entries(value).into_iter(),
any: false,
stepback: indent_len,
}));
}
}
Ok(None)
}
pub(crate) fn json_stringify_within(
value: &Value,
gap: &str,
max_depth: usize,
) -> Result<Option<String>, String> {
if value.is_undefined() {
return Ok(None);
}
let mut out = JsonOut {
text: String::new(),
units: 0,
counted: 0,
};
let mut indent = String::new();
let mut stack: Vec<JsonFrame> = Vec::new();
let open = |frame: JsonFrame,
stack: &mut Vec<JsonFrame>,
out: &mut JsonOut,
indent: &mut String|
-> Result<(), String> {
if stack.len() >= max_depth {
return Err(RANGE_ERROR.into());
}
match &frame {
JsonFrame::Array { length: 0, .. } => return out.push("[]"),
JsonFrame::Array { .. } => out.push("[")?,
JsonFrame::Object { .. } => out.push("{")?,
}
indent.push_str(gap);
stack.push(frame);
Ok(())
};
let Some(value) = json_value(value, "")? else {
return Ok(None);
};
if let Some(frame) = serialize(&value, &mut out, 0)? {
open(frame, &mut stack, &mut out, &mut indent)?;
}
let newline = |out: &mut JsonOut, indent: &str| {
out.text.push('\n');
out.text.push_str(indent);
};
while let Some(top) = stack.last_mut() {
match top {
JsonFrame::Array {
length,
elements,
at,
stepback,
} => {
let next = elements.next();
let until = next.as_ref().map_or(*length, |(i, _)| *i);
if *at < until {
let holes = until - *at;
let mut item = String::new();
if !gap.is_empty() {
item.push('\n');
item.push_str(&indent);
}
item.push_str("null");
if *at == 0 {
out.push(&item)?;
out.repeat(&format!(",{item}"), holes - 1)?;
} else {
out.repeat(&format!(",{item}"), holes)?;
}
*at = until;
}
let Some((i, element)) = next else {
let stepback = *stepback;
stack.pop();
if !gap.is_empty() {
newline(&mut out, &indent[..stepback]);
}
out.push("]")?;
indent.truncate(stepback);
continue;
};
if i > 0 {
out.text.push(',');
}
if !gap.is_empty() {
newline(&mut out, &indent);
}
*at = i + 1;
match json_value(&element, &i.to_string())? {
None => out.push("null")?,
Some(element) => {
if let Some(frame) = serialize(&element, &mut out, indent.len())? {
open(frame, &mut stack, &mut out, &mut indent)?;
}
}
}
}
JsonFrame::Object {
members,
any,
stepback,
} => {
let Some((key, member)) = members.next() else {
let (any, stepback) = (*any, *stepback);
stack.pop();
if any && !gap.is_empty() {
newline(&mut out, &indent[..stepback]);
}
out.push("}")?;
indent.truncate(stepback);
continue;
};
let Some(member) = json_value(&member, &key)? else {
continue;
};
if *any {
out.text.push(',');
}
*any = true;
if !gap.is_empty() {
newline(&mut out, &indent);
}
quote_json_string(&key, &mut out.text);
out.text.push(':');
if !gap.is_empty() {
out.text.push(' ');
}
if let Some(frame) = serialize(&member, &mut out, indent.len())? {
open(frame, &mut stack, &mut out, &mut indent)?;
}
}
}
}
out.check()?;
Ok(Some(out.text))
}
pub fn quote_json_string(s: &str, out: &mut String) {
out.push('"');
for c in s.chars() {
quote_json_char(c, out);
}
out.push('"');
}
fn quote_json_char(c: char, out: &mut String) {
match c {
'"' => out.push_str("\\\""),
'\\' => out.push_str("\\\\"),
'\u{8}' => out.push_str("\\b"),
'\u{c}' => out.push_str("\\f"),
'\n' => out.push_str("\\n"),
'\r' => out.push_str("\\r"),
'\t' => out.push_str("\\t"),
c if (c as u32) < 0x20 => out.push_str(&format!("\\u{:04x}", c as u32)),
c => out.push(c),
}
}
pub fn quote_json_js_string(s: &JsString, out: &mut String) {
let Some(text) = s.as_str() else {
out.push('"');
for c in char::decode_utf16(s.code_units()) {
match c {
Ok(c) => quote_json_char(c, out),
Err(lone) => out.push_str(&format!("\\u{:04x}", lone.unpaired_surrogate())),
}
}
out.push('"');
return;
};
quote_json_string(text, out);
}