#![allow(clippy::redundant_closure_call)]
use super::call::no_such_function;
use super::call::{Called, argument as arg, done, opaque, opaque_function, type_err};
use super::{Builtin, is_object};
use crate::next::schema::value::{self, PlainObject, Value, get_property};
type R<T> = Result<T, String>;
fn not_callable(text: &str) -> String {
type_err(format!("{text} is not a function"))
}
fn read(value: &Value, key: &str) -> R<Value> {
get_property(value, key)
}
fn invoke(value: &Value, method: &str, args: &[Value], text: &str) -> R<Called> {
let f = read(value, method)?;
match f {
Value::Builtin(b) if b.is_callable() => super::call::call(b, value, args),
_ => Err(not_callable(text)),
}
}
fn plain(called: Called) -> Value {
match called {
Called::Value(v) | Called::Wrapper(v) => v,
}
}
fn find_schema(node: &Value) -> R<Value> {
let tag = read(node, "tag")?;
let name = if tag.to_boolean() {
tag
} else {
read(node, "type")?
};
let key = super::call::property_key(&name)?;
Ok(crate::next::schema::inherited(&key))
}
fn transform_node(node: &Value) -> R<Value> {
let _ = find_schema(node)?;
transform_children(node)
}
fn transform_children(node: &Value) -> R<Value> {
let children = read(node, "children")?;
let flat_map = read(&children, "flatMap")?;
match flat_map {
Value::Builtin(Builtin::ARRAY_PROTOTYPE_FLAT_MAP) => {}
_ => return Err(not_callable("node2.children.flatMap")),
}
let len = super::call::len_of(&children)?;
let mut out = Vec::new();
for k in super::call::indices(&children, len) {
let child = read(&children, &super::call::key_of(k))?;
match transform_node(&child)? {
Value::Array(items) => out.extend(items.present().map(|(_, v)| v.clone())),
other if value::is_array(&other) => {}
other => out.push(other),
}
}
for item in &out {
if crate::next::realm::is_object(item) {
read(item, "then")?;
}
}
Ok(Value::array(out))
}
fn transform_attributes(node: &Value) -> R<Value> {
let schema = find_schema(node)?;
let _ = schema;
let mut output = PlainObject::new();
for key in ["class", "id"] {
let attributes = read(node, "attributes")?;
let mut value = read(&attributes, key)?;
if key == "class" {
value = crate::next::schema::class_transform(value);
}
if value.is_undefined() {
continue;
}
output.assign(key, value);
}
Ok(Value::object(output.into_properties()))
}
fn resolve_value(v: &Value, config: &Value) -> R<Value> {
if v.is_nullish() || super::call::type_of(v) != "object" {
return Ok(v.clone());
}
if let Value::Array(items) = v {
let mut present = Vec::with_capacity(items.present_len());
for (i, item) in items.present() {
present.push((i, resolve_value(item, config)?));
}
return Ok(Value::sparse_array(
items.len() as u32,
present,
indexmap::IndexMap::new(),
));
}
if value::is_array(v) {
return Ok(Value::array(Vec::new()));
}
if read(v, "$$mdtype")?.to_boolean()
&& let Value::Builtin(f) = read(v, "resolve")?
&& f.is_callable()
{
return Ok(plain(super::call::call(
f,
v,
std::slice::from_ref(config),
)?));
}
if !matches!(
crate::next::realm::prototype_of(v),
Value::Builtin(Builtin::OBJECT_PROTOTYPE)
) {
return Ok(v.clone());
}
let mut output = PlainObject::new();
for (k, item) in value::own_entries(v) {
output.assign(k, resolve_value(&item, config)?);
}
Ok(Value::object(output.into_properties()))
}
fn node_resolve(this: &Value, config: &Value) -> R<Value> {
let children = read(this, "children")?;
let map = read(&children, "map")?;
if !matches!(map, Value::Builtin(Builtin::ARRAY_PROTOTYPE_MAP)) {
return Err(not_callable("this.children.map"));
}
let len = super::call::len_of(&children)?;
let mut resolved_children = vec![Value::Undefined; len as usize];
for k in super::call::indices(&children, len) {
let child = read(&children, &super::call::key_of(k))?;
resolved_children[k as usize] = plain(invoke(
&child,
"resolve",
std::slice::from_ref(config),
"child.resolve",
)?);
}
let attributes = resolve_value(&read(this, "attributes")?, config)?;
let slots = read(this, "slots")?;
if slots.is_nullish() {
return Err(type_err("Cannot convert undefined or null to object"));
}
let mut resolved_slots = crate::types::JsObject::new();
for (name, slot) in value::own_entries(&slots) {
let v = plain(invoke(
&slot,
"resolve",
std::slice::from_ref(config),
"slot2.resolve",
)?);
resolved_slots.insert(name, v);
}
let mut node = PlainObject::new();
node.assign("$$mdtype", Value::string("Node"));
node.assign("errors", Value::array(Vec::new()));
node.assign("lines", Value::array(Vec::new()));
node.assign("inline", Value::Boolean(false));
node.assign("attributes", Value::empty_object());
node.assign("children", Value::array(Vec::new()));
node.assign("type", Value::string("node"));
node.assign("tag", Value::Undefined);
node.assign("annotations", Value::array(Vec::new()));
node.assign("slots", Value::empty_object());
for (k, v) in value::own_entries(this) {
node.assign(k, v);
}
node.assign("children", Value::array(resolved_children));
node.assign("attributes", attributes);
node.assign("slots", Value::object(resolved_slots));
Ok(Value::object(node.into_properties()))
}
fn variable_resolve(this: &Value) -> R<Value> {
let path = read(this, "path")?;
let reduce = read(&path, "reduce")?;
if !matches!(reduce, Value::Builtin(Builtin::ARRAY_PROTOTYPE_REDUCE)) {
return Err(not_callable("this.path.reduce"));
}
let len = super::call::len_of(&path)?;
let mut obj = Value::Undefined;
for k in super::call::indices(&path, len) {
let key = read(&path, &super::call::key_of(k))?;
if obj.is_undefined() {
obj = Value::empty_object();
}
let key = super::call::property_key(&key)?;
obj = read(&obj, &key)?;
}
Ok(obj)
}
pub(super) fn ast_function(f: Builtin, this: &Value, args: &[Value]) -> R<Called> {
let a0 = arg(args, 0);
match f {
Builtin::NODE_PROTOTYPE_WALK => (|| -> R<Called> { Ok(opaque()) })(),
Builtin::NODE_PROTOTYPE_PUSH => (|| -> R<Called> {
let children = read(this, "children")?;
invoke(&children, "push", &[a0], "this.children.push")?;
done(Value::Undefined)
})(),
Builtin::NODE_PROTOTYPE_RESOLVE => (|| -> R<Called> {
let config = if a0.is_undefined() {
Value::empty_object()
} else {
a0
};
done(node_resolve(this, &config)?)
})(),
Builtin::NODE_PROTOTYPE_FIND_SCHEMA => (|| -> R<Called> { done(find_schema(this)?) })(),
Builtin::NODE_PROTOTYPE_TRANSFORM_ATTRIBUTES => {
(|| -> R<Called> { done(transform_attributes(this)?) })()
}
Builtin::NODE_PROTOTYPE_TRANSFORM_CHILDREN => {
(|| -> R<Called> { done(transform_children(this)?) })()
}
Builtin::NODE_PROTOTYPE_TRANSFORM => (|| -> R<Called> { done(transform_node(this)?) })(),
Builtin::VARIABLE_PROTOTYPE_RESOLVE => (|| -> R<Called> {
if matches!(a0, Value::Null) {
return Err(type_err(
"Cannot destructure property 'variables' of 'object null' as it is null.",
));
}
done(variable_resolve(this)?)
})(),
Builtin::AST_FUNCTION_PROTOTYPE_RESOLVE => (|| -> R<Called> { done(Value::Null) })(),
other => Err(no_such_function(other)),
}
}
pub(super) fn iterator_function(f: Builtin, this: &Value, args: &[Value]) -> R<Called> {
let a0 = arg(args, 0);
let helper = |name: &str| format!("Iterator.prototype.{name}");
match f {
Builtin::GENERATOR_FUNCTION => (|| -> R<Called> {
for a in args {
super::call::string(a)?;
}
Ok(opaque_function())
})(),
Builtin::GENERATOR_PROTOTYPE_NEXT
| Builtin::GENERATOR_PROTOTYPE_RETURN
| Builtin::GENERATOR_PROTOTYPE_THROW => {
let name = match f {
Builtin::GENERATOR_PROTOTYPE_NEXT => "next",
Builtin::GENERATOR_PROTOTYPE_RETURN => "return",
_ => "throw",
};
Err(type_err(format!(
"Method [Generator].prototype.{name} called on incompatible receiver {}",
super::call::no_side_effects_to_string(this)
)))
}
Builtin::ITERATOR => Err(type_err("Constructor Iterator requires 'new'")),
Builtin::ITERATOR_FROM => (|| -> R<Called> {
match a0 {
Value::String(_) => Ok(opaque()),
v if is_object(&v) => Ok(opaque()),
_ => Err(type_err("Iterator.from called on non-object")),
}
})(),
Builtin::ITERATOR_PROTOTYPE_MAP
| Builtin::ITERATOR_PROTOTYPE_FILTER
| Builtin::ITERATOR_PROTOTYPE_FOR_EACH
| Builtin::ITERATOR_PROTOTYPE_SOME
| Builtin::ITERATOR_PROTOTYPE_EVERY
| Builtin::ITERATOR_PROTOTYPE_FIND
| Builtin::ITERATOR_PROTOTYPE_REDUCE => {
let name = f.name().rsplit('.').next().unwrap_or_default();
Err(type_err(format!(
"string \"{}\" is not a function",
helper(name)
)))
}
Builtin::ITERATOR_PROTOTYPE_FLAT_MAP => {
(|| -> R<Called> { Err(type_err("Iterator.prototype.flatMap is not a function")) })()
}
Builtin::ITERATOR_PROTOTYPE_TAKE | Builtin::ITERATOR_PROTOTYPE_DROP => (|| -> R<Called> {
let n = super::call::number(&a0)?;
if n.is_nan() || super::call::integer(&a0)? < 0.0 {
return Err(format!(
"RangeError: {} must be positive",
super::call::describe_primitive(&a0)
));
}
Ok(opaque())
})(),
Builtin::ITERATOR_PROTOTYPE_TO_ARRAY => (|| -> R<Called> {
let next = read(this, "next")?;
match next {
Value::Builtin(b) if b.is_callable() => {
let result = super::call::call(b, this, &[])?;
match plain(result) {
r if is_object(&r) => {
if read(&r, "done")?.to_boolean() {
done(Value::array(Vec::new()))
} else {
Err("RangeError: Invalid array length".into())
}
}
r => Err(type_err(format!(
"Iterator result {} is not an object",
super::call::describe_primitive(&r)
))),
}
}
other => Err(type_err(format!(
"{} is not a function",
super::call::default_call_site(&other)
))),
}
})(),
other => Err(no_such_function(other)),
}
}