mod array;
mod json_text;
mod ops;
pub mod realm;
mod string;
pub use array::{Array, MAX_ARRAY_LENGTH, Present};
pub use ops::*;
pub use realm::{BuiltinProto, Ctor, Intrinsic, Method};
pub use crate::next::realm::Builtin;
pub use string::{CodeUnits, JsString, JsStringBuilder};
use crate::markdown_it::js;
use crate::types::{JsObject, RenderableTreeNode, Scalar, Tag};
use indexmap::IndexMap;
use std::fmt;
use std::ops::{Deref, DerefMut};
use std::sync::Arc;
pub const RANGE_ERROR: &str = "RangeError: Maximum call stack size exceeded";
pub const INVALID_STRING_LENGTH: &str = "RangeError: Invalid string length";
pub const MAX_STRING_LENGTH: usize = (1 << 29) - 24;
pub const MAX_JOIN_DEPTH: usize = 3302;
pub(crate) const JOIN_COST: u64 = crate::depth::per_level(MAX_JOIN_DEPTH as u64);
pub const MAX_JSON_DEPTH: usize = 4170;
pub(crate) const JSON_COST: u64 = crate::depth::per_level(MAX_JSON_DEPTH as u64);
pub const MAX_RENDER_TREE_DEPTH: usize = 735;
fn render_tree_limit() -> usize {
if crate::depth::can_grow() {
MAX_JSON_DEPTH
} else {
MAX_RENDER_TREE_DEPTH
}
}
#[derive(Clone)]
pub enum Value {
Undefined,
Null,
Boolean(bool),
Number(f64),
String(JsString),
Array(Arc<Array>),
Object(Arc<Object>),
Tag(Arc<TagValue>),
Builtin(Builtin),
}
#[derive(Clone)]
pub enum Proto {
Builtin(Builtin),
Null,
Value(Value),
}
impl Proto {
pub const OBJECT: Proto = Proto::Builtin(Builtin::OBJECT_PROTOTYPE);
pub fn is_object_prototype(&self) -> bool {
matches!(self, Proto::Builtin(Builtin::OBJECT_PROTOTYPE))
}
pub fn from_value(proto: &Value) -> Option<Proto> {
match proto {
Value::Null => Some(Proto::Null),
Value::Array(_) | Value::Object(_) | Value::Tag(_) => Some(Proto::Value(proto.clone())),
Value::Builtin(b) => Some(Proto::Builtin(*b)),
_ => None,
}
}
}
#[derive(Clone)]
pub struct Object {
props: JsObject<Value>,
proto: Proto,
}
impl Default for Object {
fn default() -> Self {
Object::new(JsObject::new())
}
}
#[derive(Clone)]
pub struct TagValue {
pub name: Value,
pub attributes: Object,
pub children: Vec<Value>,
}
impl Object {
pub fn new(properties: JsObject<Value>) -> Self {
Object {
props: properties,
proto: Proto::OBJECT,
}
}
pub fn with_proto(properties: JsObject<Value>, proto: Proto) -> Self {
Object {
props: properties,
proto,
}
}
pub fn proto(&self) -> &Proto {
&self.proto
}
pub fn set_proto(&mut self, proto: Proto) {
self.proto = proto;
}
pub fn into_inner(mut self) -> JsObject<Value> {
std::mem::take(&mut self.props)
}
pub fn into_parts(mut self) -> (JsObject<Value>, Proto) {
let proto = std::mem::replace(&mut self.proto, Proto::Null);
(std::mem::take(&mut self.props), proto)
}
}
impl Deref for Object {
type Target = JsObject<Value>;
fn deref(&self) -> &JsObject<Value> {
&self.props
}
}
impl DerefMut for Object {
fn deref_mut(&mut self) -> &mut JsObject<Value> {
&mut self.props
}
}
impl From<JsObject<Value>> for Object {
fn from(properties: JsObject<Value>) -> Self {
Object::new(properties)
}
}
impl From<IndexMap<String, Value>> for Object {
fn from(properties: IndexMap<String, Value>) -> Self {
Object::new(properties.into())
}
}
impl<K: Into<String>, const N: usize> From<[(K, Value); N]> for Object {
fn from(entries: [(K, Value); N]) -> Self {
Object::new(entries.into())
}
}
impl From<Object> for JsObject<Value> {
fn from(object: Object) -> Self {
object.into_inner()
}
}
fn drop_values(mut pending: Vec<Value>) {
while let Some(value) = pending.pop() {
match value {
Value::Array(items) => {
if let Some(mut items) = Arc::into_inner(items) {
pending.append(&mut items.take_values());
}
}
Value::Object(object) => {
if let Some(mut object) = Arc::into_inner(object) {
pending.extend(std::mem::take(&mut object.props).into_values());
if let Proto::Value(p) = std::mem::replace(&mut object.proto, Proto::Null) {
pending.push(p);
}
}
}
Value::Tag(tag) => {
if let Some(mut tag) = Arc::into_inner(tag) {
pending.append(&mut tag.children);
pending.extend(std::mem::take(&mut tag.attributes.props).into_values());
if let Proto::Value(p) =
std::mem::replace(&mut tag.attributes.proto, Proto::Null)
{
pending.push(p);
}
pending.push(std::mem::replace(&mut tag.name, Value::Undefined));
}
}
_ => {}
}
}
}
impl Drop for Array {
fn drop(&mut self) {
let values = self.take_values();
if !values.is_empty() {
drop_values(values);
}
}
}
impl Drop for Object {
fn drop(&mut self) {
let mut values: Vec<Value> = Vec::new();
if !self.props.is_empty() {
values.extend(std::mem::take(&mut self.props).into_values());
}
if let Proto::Value(p) = std::mem::replace(&mut self.proto, Proto::Null) {
values.push(p);
}
if !values.is_empty() {
drop_values(values);
}
}
}
impl Drop for TagValue {
fn drop(&mut self) {
let mut pending = std::mem::take(&mut self.children);
pending.push(std::mem::replace(&mut self.name, Value::Undefined));
pending.extend(std::mem::take(&mut self.attributes.props).into_values());
if let Proto::Value(p) = std::mem::replace(&mut self.attributes.proto, Proto::Null) {
pending.push(p);
}
drop_values(pending);
}
}
impl TagValue {
pub fn is_tag(value: &Value) -> bool {
match value {
Value::Tag(_) => true,
Value::Undefined | Value::Null => false,
_ => matches!(get_value(value, "$$mdtype"), Ok(Value::String(t)) if t == "Tag"),
}
}
pub fn new(
name: impl Into<Value>,
attributes: impl Into<Object>,
children: Vec<Value>,
) -> Self {
Self {
name: name.into(),
attributes: attributes.into(),
children,
}
}
pub fn name_str(&self) -> Option<&JsString> {
match &self.name {
Value::String(s) => Some(s),
_ => None,
}
}
}
const DEBUG_DEPTH: usize = 64;
struct Nested<'a>(&'a Value, usize);
impl fmt::Debug for Nested<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let Nested(value, depth) = *self;
if depth >= DEBUG_DEPTH
&& matches!(value, Value::Array(_) | Value::Object(_) | Value::Tag(_))
{
return f.write_str("…");
}
match value {
Value::Undefined => f.write_str("Undefined"),
Value::Null => f.write_str("Null"),
Value::Boolean(b) => f.debug_tuple("Boolean").field(b).finish(),
Value::Number(n) => f.debug_tuple("Number").field(n).finish(),
Value::String(s) => f.debug_tuple("String").field(s).finish(),
Value::Array(items) => f
.debug_tuple("Array")
.field(&NestedArray(items, depth + 1))
.finish(),
Value::Object(o) => {
let mut t = f.debug_tuple("Object");
t.field(&NestedMap(o, depth + 1));
if !o.proto.is_object_prototype() {
t.field(&NestedProto(&o.proto, depth + 1));
}
t.finish()
}
Value::Tag(tag) => f
.debug_struct("Tag")
.field("name", &Nested(&tag.name, depth + 1))
.field("attributes", &NestedMap(&tag.attributes, depth + 1))
.field("children", &NestedList(&tag.children, depth + 1))
.finish(),
Value::Builtin(b) => f.debug_tuple("Builtin").field(b).finish(),
}
}
}
struct NestedProto<'a>(&'a Proto, usize);
impl fmt::Debug for NestedProto<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self.0 {
Proto::Builtin(p) => write!(f, "__proto__: {p:?}"),
Proto::Null => f.write_str("__proto__: null"),
Proto::Value(v) => write!(f, "__proto__: {:?}", Nested(v, self.1)),
}
}
}
struct NestedList<'a>(&'a [Value], usize);
impl fmt::Debug for NestedList<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_list()
.entries(self.0.iter().map(|v| Nested(v, self.1)))
.finish()
}
}
struct NestedArray<'a>(&'a Array, usize);
impl fmt::Debug for NestedArray<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let array = self.0;
if let (Some(items), false) = (array.as_dense(), array.has_named()) {
return NestedList(items, self.1).fmt(f);
}
let mut m = f.debug_map();
m.entry(&"length", &array.len());
for (i, v) in array.present() {
m.entry(&i, &Nested(v, self.1));
}
for (k, v) in array.named() {
m.entry(k, &Nested(v, self.1));
}
m.finish()
}
}
struct NestedMap<'a>(&'a JsObject<Value>, usize);
impl fmt::Debug for NestedMap<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_map()
.entries(self.0.iter().map(|(k, v)| (k, Nested(v, self.1))))
.finish()
}
}
impl fmt::Debug for Value {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
Nested(self, 0).fmt(f)
}
}
impl fmt::Debug for Array {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
NestedArray(self, 1).fmt(f)
}
}
impl fmt::Debug for Object {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
NestedMap(&self.props, 1).fmt(f)
}
}
impl fmt::Debug for TagValue {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("TagValue")
.field("name", &Nested(&self.name, 1))
.field("attributes", &NestedMap(&self.attributes, 1))
.field("children", &NestedList(&self.children, 1))
.finish()
}
}
impl fmt::Debug for Proto {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
NestedProto(self, 1).fmt(f)
}
}
pub const OBJECT_PROTOTYPE: [&str; 12] = realm::OBJECT_PROTOTYPE;
pub fn is_object_prototype_name(key: &str) -> bool {
Builtin::OBJECT_PROTOTYPE.own(key).is_some()
}
impl Value {
pub fn array(items: Vec<Value>) -> Value {
Value::Array(Arc::new(Array::new(items)))
}
pub fn sparse_array(
length: u32,
present: impl IntoIterator<Item = (u32, Value)>,
named: IndexMap<String, Value>,
) -> Value {
Value::Array(Arc::new(Array::from_parts(length, present, named)))
}
pub fn object(properties: impl Into<JsObject<Value>>) -> Value {
Value::Object(Arc::new(Object::new(properties.into())))
}
pub fn object_with_proto(properties: impl Into<JsObject<Value>>, proto: Proto) -> Value {
Value::Object(Arc::new(Object::with_proto(properties.into(), proto)))
}
pub fn empty_object() -> Value {
Value::object(JsObject::new())
}
pub fn string(s: impl Into<JsString>) -> Value {
Value::String(s.into())
}
pub fn variable(path: Value) -> Value {
let props: JsObject<Value> =
[("$$mdtype", Value::string("Variable")), ("path", path)].into();
Value::object_with_proto(props, Proto::Builtin(Builtin::VARIABLE_PROTOTYPE))
}
pub fn ast_function(name: Value, parameters: Value) -> Value {
let props: JsObject<Value> = [
("$$mdtype", Value::string("Function")),
("name", name),
("parameters", parameters),
]
.into();
Value::object_with_proto(props, Proto::Builtin(Builtin::AST_FUNCTION_PROTOTYPE))
}
pub fn is_undefined(&self) -> bool {
matches!(self, Value::Undefined)
}
pub fn is_nullish(&self) -> bool {
matches!(self, Value::Undefined | Value::Null)
}
pub fn is_object(&self) -> bool {
matches!(
self,
Value::Array(_) | Value::Object(_) | Value::Tag(_) | Value::Builtin(_)
)
}
pub fn to_boolean(&self) -> bool {
match self {
Value::Undefined | Value::Null => false,
Value::Boolean(b) => *b,
Value::Number(n) => !(*n == 0.0 || n.is_nan()),
Value::String(s) => !s.is_empty(),
Value::Array(_) | Value::Object(_) | Value::Tag(_) | Value::Builtin(_) => true,
}
}
pub fn type_of(&self) -> &'static str {
type_of(self)
}
pub fn to_js_string(&self) -> Result<JsString, String> {
to_js_string(self)
}
pub fn as_str(&self) -> Option<&str> {
match self {
Value::String(s) => s.as_str(),
_ => None,
}
}
pub fn as_js_str(&self) -> Option<&JsString> {
match self {
Value::String(s) => Some(s),
_ => None,
}
}
pub fn from_json(json: &serde_json::Value) -> Value {
Value::from_json_with(json, &|_| None)
}
pub fn from_json_with(
json: &serde_json::Value,
revive: &dyn Fn(&serde_json::Map<String, serde_json::Value>) -> Option<Value>,
) -> Value {
enum Frame<'a> {
Array(std::slice::Iter<'a, serde_json::Value>, Vec<Value>),
Object(
serde_json::map::Iter<'a>,
JsObject<Value>,
Option<&'a String>,
),
}
let leaf = |json: &serde_json::Value| -> Option<Value> {
Some(match json {
serde_json::Value::Null => Value::Null,
serde_json::Value::Bool(b) => Value::Boolean(*b),
serde_json::Value::Number(n) => Value::Number(n.as_f64().unwrap_or(f64::NAN)),
serde_json::Value::String(s) => Value::string(s.as_str()),
serde_json::Value::Object(o) => return revive(o),
serde_json::Value::Array(_) => return None,
})
};
fn open(json: &serde_json::Value) -> Frame<'_> {
match json {
serde_json::Value::Array(items) => {
Frame::Array(items.iter(), Vec::with_capacity(items.len()))
}
serde_json::Value::Object(o) => Frame::Object(o.iter(), JsObject::new(), None),
_ => unreachable!("a leaf"),
}
}
if let Some(value) = leaf(json) {
return value;
}
let mut stack = vec![open(json)];
loop {
let top = stack.last_mut().expect("a frame");
let next = match top {
Frame::Array(items, _) => items.next(),
Frame::Object(entries, _, key) => entries.next().map(|(k, v)| {
*key = Some(k);
v
}),
};
let done = match next {
Some(json) => match leaf(json) {
Some(value) => value,
None => {
stack.push(open(json));
continue;
}
},
None => match stack.pop().expect("a frame") {
Frame::Array(_, items) => Value::array(items),
Frame::Object(_, object, _) => Value::object(object),
},
};
match stack.last_mut() {
None => return done,
Some(Frame::Array(_, items)) => items.push(done),
Some(Frame::Object(_, object, key)) => {
object.insert(key.take().expect("the key").clone(), done);
}
}
}
}
pub fn from_scalar(scalar: &Scalar) -> Value {
from_tree(Tree::Scalar(scalar))
}
pub fn to_scalar(&self) -> Result<Scalar, String> {
to_scalar(self)
}
pub fn to_render(&self) -> Result<RenderableTreeNode, String> {
self.to_scalar().map(RenderableTreeNode::from)
}
pub fn from_render(node: &RenderableTreeNode) -> Value {
from_tree(Tree::Node(node))
}
}
#[derive(Clone, Copy)]
enum Tree<'a> {
Scalar(&'a Scalar),
Node(&'a RenderableTreeNode),
Tag(&'a Tag),
}
fn from_tree(root: Tree<'_>) -> Value {
enum Kind {
Array,
Object,
Function(String),
}
enum Frame<'a> {
Array(std::slice::Iter<'a, Scalar>, Vec<Value>, Kind),
Object(
indexmap::map::Iter<'a, String, Scalar>,
JsObject<Value>,
Option<&'a String>,
Kind,
),
Tag {
attributes: indexmap::map::Iter<'a, String, Scalar>,
key: Option<&'a String>,
children: std::slice::Iter<'a, RenderableTreeNode>,
built: TagValue,
},
}
enum Step<'a> {
Leaf(Value),
Open(Frame<'a>),
}
fn path_scalar(step: &crate::ast::PathSegment) -> Value {
match step {
crate::ast::PathSegment::String(s) => Value::string(s.as_str()),
crate::ast::PathSegment::Number(n) => Value::Number(*n),
}
}
fn leaf(tree: Tree<'_>) -> Step<'_> {
let scalar = match tree {
Tree::Scalar(scalar) => scalar,
Tree::Node(RenderableTreeNode::Scalar(scalar)) => scalar,
Tree::Node(RenderableTreeNode::Tag(tag)) => return Step::Open(open_tag(tag)),
Tree::Tag(tag) => return Step::Open(open_tag(tag)),
};
Step::Leaf(match scalar {
Scalar::Undefined => Value::Undefined,
Scalar::Null => Value::Null,
Scalar::Boolean(b) => Value::Boolean(*b),
Scalar::Number(n) => Value::Number(*n),
Scalar::String(s) => Value::string(s.as_str()),
Scalar::Variable(v) => {
Value::variable(Value::array(v.path.iter().map(path_scalar).collect()))
}
Scalar::Js(js) => js.value().clone(),
Scalar::Function(f) => {
return Step::Open(Frame::Object(
f.parameters.iter(),
JsObject::new(),
None,
Kind::Function(f.name.clone()),
));
}
Scalar::Tag(tag) => return Step::Open(open_tag(tag)),
Scalar::Array(items) => {
return Step::Open(Frame::Array(
items.iter(),
Vec::with_capacity(items.len()),
Kind::Array,
));
}
Scalar::Object(o) => {
return Step::Open(Frame::Object(o.iter(), JsObject::new(), None, Kind::Object));
}
})
}
fn open_tag(tag: &Tag) -> Frame<'_> {
Frame::Tag {
attributes: tag.attributes.iter(),
key: None,
children: tag.children.iter(),
built: TagValue {
name: Value::string(tag.name.as_str()),
attributes: Object::default(),
children: Vec::with_capacity(tag.children.len()),
},
}
}
fn finish(kind: Kind, value: Value) -> Value {
match kind {
Kind::Array | Kind::Object => value,
Kind::Function(name) => Value::ast_function(Value::string(name), value),
}
}
let mut stack = match leaf(root) {
Step::Leaf(value) => return value,
Step::Open(frame) => vec![frame],
};
loop {
let top = stack.last_mut().expect("a frame");
let next: Option<Tree<'_>> = match top {
Frame::Array(items, _, _) => items.next().map(Tree::Scalar),
Frame::Object(entries, _, key, _) => entries.next().map(|(k, v)| {
*key = Some(k);
Tree::Scalar(v)
}),
Frame::Tag {
attributes,
key,
children,
..
} => match attributes.next() {
Some((k, v)) => {
*key = Some(k);
Some(Tree::Scalar(v))
}
None => {
*key = None;
children.next().map(Tree::Node)
}
},
};
let done = match next {
Some(tree) => match leaf(tree) {
Step::Leaf(value) => value,
Step::Open(frame) => {
stack.push(frame);
continue;
}
},
None => match stack.pop().expect("a frame") {
Frame::Array(_, items, kind) => finish(kind, Value::array(items)),
Frame::Object(_, object, _, kind) => finish(kind, Value::object(object)),
Frame::Tag { built, .. } => Value::Tag(Arc::new(built)),
},
};
match stack.last_mut() {
None => return done,
Some(Frame::Array(_, items, _)) => items.push(done),
Some(Frame::Object(_, object, key, _)) => {
object.insert(key.take().expect("the key").clone(), done);
}
Some(Frame::Tag { key, built, .. }) => match key.take() {
Some(k) => {
built.attributes.insert(k.clone(), done);
}
None => built.children.push(done),
},
}
}
}
#[derive(Debug, Default)]
pub struct PlainObject {
object: Object,
}
impl PlainObject {
pub fn new() -> Self {
Self::default()
}
pub fn with_proto(proto: Proto) -> Self {
PlainObject {
object: Object::with_proto(JsObject::new(), proto),
}
}
pub fn assign(&mut self, key: impl Into<String>, value: Value) {
set(&mut self.object, key.into(), value);
}
pub fn into_entries(self) -> IndexMap<String, Value> {
self.object.into_inner().into()
}
pub fn into_properties(self) -> JsObject<Value> {
self.object.into_inner()
}
pub fn into_object(self) -> Object {
self.object
}
}
impl TagValue {
pub fn to_tag(&self) -> Result<Tag, String> {
match &mut Value::Tag(Arc::new(self.clone())).to_scalar()? {
Scalar::Tag(tag) => Ok(std::mem::take(tag.as_mut())),
_ => unreachable!("a tag converts to a tag"),
}
}
pub fn from_tag(tag: &Tag) -> TagValue {
match from_tree(Tree::Tag(tag)) {
Value::Tag(tag) => Arc::into_inner(tag).expect("a tag nothing else holds yet"),
_ => unreachable!("a tag converts to a tag"),
}
}
}
impl From<Scalar> for Value {
fn from(scalar: Scalar) -> Self {
Value::from_scalar(&scalar)
}
}
impl From<&str> for Value {
fn from(s: &str) -> Self {
Value::String(s.into())
}
}
impl From<String> for Value {
fn from(s: String) -> Self {
Value::String(s.into())
}
}
impl From<JsString> for Value {
fn from(s: JsString) -> Self {
Value::String(s)
}
}
impl From<f64> for Value {
fn from(n: f64) -> Self {
Value::Number(n)
}
}
impl From<bool> for Value {
fn from(b: bool) -> Self {
Value::Boolean(b)
}
}
impl From<TagValue> for Value {
fn from(tag: TagValue) -> Self {
Value::Tag(Arc::new(tag))
}
}
fn to_scalar(value: &Value) -> Result<Scalar, String> {
enum Frame<'a> {
Array {
items: &'a Array,
next: usize,
out: Vec<Scalar>,
},
Object {
entries: crate::types::JsObjectIter<'a, Value>,
key: Option<&'a String>,
out: IndexMap<String, Scalar>,
},
Tag {
tag: &'a TagValue,
name: Option<Scalar>,
attributes: crate::types::JsObjectIter<'a, Value>,
key: Option<&'a String>,
out_attributes: IndexMap<String, Scalar>,
next_child: usize,
out_children: Vec<RenderableTreeNode>,
},
}
fn leaf(value: &Value) -> Option<Scalar> {
Some(match value {
Value::Undefined | Value::Null => Scalar::Null,
Value::Boolean(b) => Scalar::Boolean(*b),
Value::Number(n) => Scalar::Number(*n),
Value::String(s) => Scalar::String(s.to_string_lossy().into_owned()),
Value::Array(_) | Value::Object(_) | Value::Tag(_) => return None,
Value::Builtin(b) => match b.data().wrapped {
Some(crate::next::realm::Wrapped::String(s)) => Scalar::String(s.to_string()),
Some(crate::next::realm::Wrapped::Number(n)) => Scalar::Number(n),
Some(crate::next::realm::Wrapped::Boolean(v)) => Scalar::Boolean(v),
None if b.is_callable() => Scalar::Null,
None if b.is_array() => Scalar::Array(Vec::new()),
None => Scalar::Object(IndexMap::new()),
},
})
}
fn open(value: &Value) -> Result<Frame<'_>, String> {
Ok(match value {
Value::Array(items) => Frame::Array {
items,
next: 0,
out: Vec::with_capacity(items.len().min(SPARSE_CHECK)),
},
Value::Object(o) => Frame::Object {
entries: o.iter(),
key: None,
out: IndexMap::with_capacity(o.len()),
},
Value::Tag(tag) => Frame::Tag {
tag,
name: match &tag.name {
Value::String(_) => None,
other => Some(to_scalar(other)?),
},
attributes: tag.attributes.iter(),
key: None,
out_attributes: IndexMap::with_capacity(tag.attributes.len()),
next_child: 0,
out_children: Vec::with_capacity(tag.children.len()),
},
_ => unreachable!("a leaf"),
})
}
fn levels(frame: &Frame<'_>) -> usize {
if matches!(frame, Frame::Tag { .. }) {
2
} else {
1
}
}
if let Some(scalar) = leaf(value) {
return Ok(scalar);
}
let mut checked = false;
let mut check = |items: &Array| -> Result<(), String> {
if !checked && items.len() > SPARSE_CHECK {
checked = true;
json_stringify(value, "")?;
}
Ok(())
};
let first = open(value)?;
if let Frame::Array { items, .. } = &first {
check(items)?;
}
let mut nesting = levels(&first);
if nesting > render_tree_limit() {
return Err(RANGE_ERROR.into());
}
let mut stack = vec![first];
loop {
let top = stack.last_mut().expect("a frame");
let next: Option<&Value> = match top {
Frame::Array { items, next, .. } => {
if *next < items.len() {
let item = items.get(*next).unwrap_or(&Value::Undefined);
*next += 1;
Some(item)
} else {
None
}
}
Frame::Object { entries, key, .. } => loop {
match entries.next() {
Some((_, v)) if v.is_undefined() || is_callable(v) => continue,
Some((k, v)) => {
*key = Some(k);
break Some(v);
}
None => break None,
}
},
Frame::Tag {
tag,
attributes,
key,
next_child,
..
} => loop {
match attributes.next() {
Some((_, v)) if v.is_undefined() || is_callable(v) => continue,
Some((k, v)) => {
*key = Some(k);
break Some(v);
}
None => {
*key = None;
let child = tag.children.get(*next_child);
*next_child += 1;
break child;
}
}
},
};
let done = match next {
Some(child) => match leaf(child) {
Some(scalar) => scalar,
None => {
let frame = open(child)?;
if let Frame::Array { items, .. } = &frame {
check(items)?;
}
nesting += levels(&frame);
if nesting > render_tree_limit() {
return Err(RANGE_ERROR.into());
}
stack.push(frame);
continue;
}
},
None => {
let frame = stack.pop().expect("a frame");
nesting -= levels(&frame);
match frame {
Frame::Array { out, .. } => Scalar::Array(out),
Frame::Object { out, .. } => Scalar::Object(out),
Frame::Tag {
tag,
name,
out_attributes,
out_children,
..
} => match (name, &tag.name) {
(None, Value::String(n)) => Scalar::Tag(Box::new(Tag {
name: n.to_string_lossy().into_owned(),
attributes: out_attributes,
children: out_children,
})),
(name, _) => {
let mut object = IndexMap::with_capacity(4);
object.insert("$$mdtype".to_string(), Scalar::String("Tag".into()));
if let Some(name) = name.filter(|_| !tag.name.is_undefined()) {
object.insert("name".to_string(), name);
}
object.insert("attributes".to_string(), Scalar::Object(out_attributes));
object.insert(
"children".to_string(),
Scalar::Array(
out_children
.into_iter()
.map(|child| match child {
RenderableTreeNode::Tag(tag) => Scalar::Tag(tag),
RenderableTreeNode::Scalar(value) => value,
})
.collect(),
),
);
Scalar::Object(object)
}
},
}
}
};
match stack.last_mut() {
None => return Ok(done),
Some(Frame::Array { out, .. }) => out.push(done),
Some(Frame::Object { out, key, .. }) => {
out.insert(key.take().expect("the key").clone(), done);
}
Some(Frame::Tag {
key,
out_attributes,
out_children,
..
}) => match key.take() {
Some(k) => {
out_attributes.insert(k.clone(), done);
}
None => out_children.push(RenderableTreeNode::from(done)),
},
}
}
}
pub fn to_json_value(value: &Value) -> Result<Option<serde_json::Value>, String> {
use serde_json::Value as J;
enum Frame {
Array {
items: Arc<Array>,
next: usize,
out: Vec<J>,
},
Object {
members: std::vec::IntoIter<(String, Value)>,
key: Option<String>,
out: serde_json::Map<String, J>,
levels: usize,
},
}
fn leaf(value: &Value) -> Option<Option<J>> {
Some(Some(match value {
Value::Undefined => return Some(None),
Value::Null => J::Null,
Value::Boolean(b) => J::Bool(*b),
Value::Number(n) => crate::types::json_number(*n),
Value::String(s) => J::String(s.to_string_lossy().into_owned()),
Value::Array(_) | Value::Object(_) | Value::Tag(_) => return None,
Value::Builtin(b) => match b.data().wrapped {
Some(crate::next::realm::Wrapped::String(s)) => J::String(s.to_string()),
Some(crate::next::realm::Wrapped::Number(n)) => crate::types::json_number(n),
Some(crate::next::realm::Wrapped::Boolean(v)) => J::Bool(v),
None if b.is_callable() => return Some(None),
None if b.is_array() => J::Array(Vec::new()),
None => J::Object(serde_json::Map::new()),
},
}))
}
fn open(value: &Value) -> Frame {
match value {
Value::Array(items) => Frame::Array {
items: Arc::clone(items),
next: 0,
out: Vec::with_capacity(items.len().min(SPARSE_CHECK)),
},
other => Frame::Object {
members: own_entries(other).into_iter(),
key: None,
out: serde_json::Map::new(),
levels: if matches!(other, Value::Tag(_)) { 2 } else { 1 },
},
}
}
fn levels(frame: &Frame) -> usize {
match frame {
Frame::Array { .. } => 1,
Frame::Object { levels, .. } => *levels,
}
}
if let Some(json) = leaf(value) {
return Ok(json);
}
let mut checked = false;
let mut check = |frame: &Frame| -> Result<(), String> {
if let Frame::Array { items, .. } = frame
&& !checked
&& items.len() > SPARSE_CHECK
{
checked = true;
json_stringify(value, "")?;
}
Ok(())
};
let first = open(value);
check(&first)?;
let mut nesting = levels(&first);
if nesting > render_tree_limit() {
return Err(RANGE_ERROR.into());
}
let mut stack = vec![first];
loop {
let top = stack.last_mut().expect("a frame");
let next: Option<Value> = match top {
Frame::Array { items, next, .. } => {
if *next < items.len() {
let item = items.get(*next).cloned().unwrap_or(Value::Undefined);
*next += 1;
Some(item)
} else {
None
}
}
Frame::Object { members, key, .. } => loop {
match members.next() {
Some((_, v)) if v.is_undefined() || is_callable(&v) => continue,
Some((k, v)) => {
*key = Some(k);
break Some(v);
}
None => break None,
}
},
};
let done = match next {
Some(child) => match leaf(&child) {
Some(json) => json.unwrap_or(J::Null),
None => {
let frame = open(&child);
check(&frame)?;
nesting += levels(&frame);
if nesting > render_tree_limit() {
return Err(RANGE_ERROR.into());
}
stack.push(frame);
continue;
}
},
None => {
let frame = stack.pop().expect("a frame");
nesting -= levels(&frame);
match frame {
Frame::Array { out, .. } => J::Array(out),
Frame::Object { out, .. } => J::Object(out),
}
}
};
match stack.last_mut() {
None => return Ok(Some(done)),
Some(Frame::Array { out, .. }) => out.push(done),
Some(Frame::Object { out, key, .. }) => {
out.insert(key.take().expect("the key"), done);
}
}
}
}
const SPARSE_CHECK: usize = 1 << 20;
pub fn property_key(step: &crate::ast::PathSegment) -> String {
match step {
crate::ast::PathSegment::String(s) => s.clone(),
crate::ast::PathSegment::Number(n) => js::number_to_string(*n),
}
}
pub fn scalar_to_js_string(value: &Scalar) -> Result<String, String> {
Ok(Value::from_scalar(value)
.to_js_string()?
.into_string_lossy())
}
pub fn same_shape(a: &Value, b: &Value) -> bool {
let mut pending: Vec<(Value, Value)> = vec![(a.clone(), b.clone())];
while let Some((a, b)) = pending.pop() {
match (&a, &b) {
(Value::Undefined, Value::Undefined) | (Value::Null, Value::Null) => {}
(Value::Boolean(x), Value::Boolean(y)) if x == y => {}
(Value::Number(x), Value::Number(y)) if x == y || (x.is_nan() && y.is_nan()) => {}
(Value::String(x), Value::String(y)) if x == y => {}
(Value::Array(x), Value::Array(y)) => {
if Arc::ptr_eq(x, y) {
continue;
}
if x.len() != y.len()
|| x.present_len() != y.present_len()
|| x.named().count() != y.named().count()
{
return false;
}
for ((i, p), (j, q)) in x.present().zip(y.present()) {
if i != j {
return false;
}
pending.push((p.clone(), q.clone()));
}
for ((k, p), (l, q)) in x.named().zip(y.named()) {
if k != l {
return false;
}
pending.push((p.clone(), q.clone()));
}
}
(Value::Object(x), Value::Object(y)) => {
if Arc::ptr_eq(x, y) {
continue;
}
if x.len() != y.len() {
return false;
}
for ((k, p), (l, q)) in x.iter().zip(y.iter()) {
if k != l {
return false;
}
pending.push((p.clone(), q.clone()));
}
match (&x.proto, &y.proto) {
(Proto::Builtin(p), Proto::Builtin(q)) if p == q => {}
(Proto::Null, Proto::Null) => {}
(Proto::Value(p), Proto::Value(q)) => pending.push((p.clone(), q.clone())),
_ => return false,
}
}
(Value::Tag(x), Value::Tag(y)) => {
if Arc::ptr_eq(x, y) {
continue;
}
if x.children.len() != y.children.len() || x.attributes.len() != y.attributes.len()
{
return false;
}
pending.push((x.name.clone(), y.name.clone()));
for ((k, p), (l, q)) in x.attributes.iter().zip(y.attributes.iter()) {
if k != l {
return false;
}
pending.push((p.clone(), q.clone()));
}
for (p, q) in x.children.iter().zip(&y.children) {
pending.push((p.clone(), q.clone()));
}
}
_ => return false,
}
}
true
}
#[cfg(test)]
mod tests;