use crate::ast::{Function, Node, PathSegment, Variable};
use crate::next::realm::Builtin;
use crate::next::schema::value::{
self, Found as ValueFound, Intrinsic, Method, Object, PlainObject, Proto, TagValue, Value,
};
use crate::next::schema::{self, Config, Found, Schema, TypeSpec, Variables, lookup};
use crate::types::{JsObject, MarkdocError, Result, Scalar};
use indexmap::IndexMap;
use std::cell::Cell;
use std::sync::Arc;
#[derive(Debug, Clone)]
pub struct ResolvedNode<'a> {
pub node: &'a Node,
pub attributes: Value,
pub children: Vec<ResolvedNode<'a>>,
pub slots: IndexMap<String, ResolvedNode<'a>>,
}
impl ResolvedNode<'_> {
pub fn attribute(&self, key: &str) -> Result<Value> {
match &self.attributes {
Value::Object(o) => value::object_get(o, key).map_err(throw),
other => value::get(other, key).map_err(throw),
}
}
pub fn find_schema<'c>(&self, config: &'c Config) -> SchemaRef<'c> {
find_schema(self.node, config)
}
pub fn transform_attributes(&self, config: &Config) -> Result<Object> {
attributes(self, config)
}
pub fn transform_children(&self, config: &Config) -> Result<Vec<Value>> {
children(self, config)
}
pub fn transform(&self, config: &Config) -> Result<Value> {
node(self, config)
}
}
#[derive(Debug, Clone, Copy)]
pub enum SchemaRef<'c> {
Own(&'c Schema),
Inherited,
None,
}
static EMPTY_SCHEMA: Schema = Schema {
render: None,
children: None,
attributes: None,
slots: None,
self_closing: false,
inline: None,
transform: None,
validate: None,
description: None,
};
impl<'c> SchemaRef<'c> {
pub fn get(self) -> Option<&'c Schema> {
match self {
SchemaRef::Own(schema) => Some(schema),
SchemaRef::Inherited => Some(&EMPTY_SCHEMA),
SchemaRef::None => None,
}
}
}
pub fn find_schema<'c>(node: &Node, config: &'c Config) -> SchemaRef<'c> {
let found = match node.tag.as_deref() {
Some(tag) if !tag.is_empty() => lookup(&config.tags, tag),
_ => lookup(&config.nodes, node.node_type.as_str()),
};
match found {
Found::Own(Some(schema)) => SchemaRef::Own(schema),
Found::Own(None) | Found::Missing => SchemaRef::None,
Found::Inherited => SchemaRef::Inherited,
}
}
fn throw(message: impl Into<String>) -> MarkdocError {
MarkdocError::TransformError(message.into())
}
pub mod cost {
use crate::depth::{extra, per_level};
const PLAIN: u64 = per_level(1_459);
pub const NODE: u64 = PLAIN / 3;
pub const CHILDREN: u64 = PLAIN - NODE;
pub const TRANSFORM: u64 = extra(1_459, 1_066);
pub const FENCE: u64 = extra(1_066, 1_048);
pub const IF: u64 = per_level(1_116) - NODE - TRANSFORM;
pub const PARTIAL: u64 = extra(1_066, 906);
pub const SLOT: u64 = per_level(1_771) - NODE;
pub const RESOLVE_CHILD: u64 = per_level(super::MAX_RESOLVE_DEPTH as u64);
pub const RESOLVE_SLOT: u64 = per_level(1_819);
pub const RESOLVE_SELF: u64 = RESOLVE_CHILD / 3;
pub const VALUE_OBJECT: u64 = per_level(3_487);
pub const VALUE_ARRAY: u64 = per_level(1_720);
const NESTED_CALL: u64 = per_level(1_384);
pub const CALL: u64 = NESTED_CALL / 3 * 2;
pub const PARAMETERS: u64 = NESTED_CALL - CALL;
}
pub const MAX_TRANSFORM_DEPTH: usize = 1100;
pub const MAX_RESOLVE_DEPTH: usize = 2111;
pub const MAX_VALUE_DEPTH: usize = 1400;
const STACK_BUDGET_BYTES: usize = 1536 * 1024;
const CALL_LEVEL_BYTES: usize = 6 * 1024;
pub(crate) fn call_fits_stack() -> bool {
if crate::depth::can_grow() || TRANSFORM_DEPTH.get() + VALUE_DEPTH.get() == 0 {
return true;
}
STACK_BASE.get().abs_diff(crate::depth::stack_address()) + CALL_LEVEL_BYTES
<= STACK_BUDGET_BYTES
}
const STACK_OVERFLOW: &str = "RangeError: Maximum call stack size exceeded";
#[cold]
#[inline(never)]
fn overflow() -> MarkdocError {
throw(STACK_OVERFLOW)
}
thread_local! {
static TRANSFORM_DEPTH: Cell<usize> = const { Cell::new(0) };
static VALUE_DEPTH: Cell<usize> = const { Cell::new(0) };
static STACK_BASE: Cell<usize> = const { Cell::new(0) };
}
pub(crate) struct Nested {
_level: crate::depth::Level,
counter: Option<&'static std::thread::LocalKey<Cell<usize>>>,
}
pub(crate) fn enter_transform(cost: u64) -> Result<Nested> {
Nested::enter(cost, &TRANSFORM_DEPTH, MAX_TRANSFORM_DEPTH).ok_or_else(overflow)
}
pub(crate) fn charge(cost: u64) -> Result<crate::depth::Level> {
crate::depth::enter(cost).ok_or_else(overflow)
}
impl Nested {
fn enter(
cost: u64,
counter: &'static std::thread::LocalKey<Cell<usize>>,
limit: usize,
) -> Option<Nested> {
let counter = if crate::depth::can_grow() {
None
} else {
let depth = counter.get();
if depth >= limit {
return None;
}
let here = crate::depth::stack_address();
if TRANSFORM_DEPTH.get() + VALUE_DEPTH.get() == 0 {
STACK_BASE.set(here);
} else if STACK_BASE.get().abs_diff(here) > STACK_BUDGET_BYTES {
return None;
}
Some(counter)
};
let level = crate::depth::enter(cost)?;
if let Some(counter) = counter {
counter.set(counter.get() + 1);
}
Some(Nested {
_level: level,
counter,
})
}
}
impl Drop for Nested {
fn drop(&mut self) {
if let Some(counter) = self.counter {
counter.set(counter.get() - 1);
}
}
}
pub fn attributes(node: &ResolvedNode<'_>, config: &Config) -> Result<Object> {
let schema = find_schema(node.node, config).get();
let mut output = PlainObject::new();
let attrs = schema::merged_attributes(schema);
for (key, attr) in &attrs {
let Some(name) = schema::renders(attr, key).map_err(throw)? else {
continue;
};
let mut value = node.attribute(key)?;
if let Some(t) = &attr.attr_type
&& t.is_function()
{
match t {
TypeSpec::Markdoc(m) => {
if let Some(v) = m.transform(value.clone()) {
value = v;
}
}
TypeSpec::Custom(custom) => {
if let Some(v) = custom.transform(value.clone(), config) {
value = v?;
}
}
TypeSpec::Realm(b) if !b.is_constructor() => {
return Err(throw("TypeError: attr.type is not a constructor"));
}
_ => {}
}
}
if value.is_undefined() {
value = attr.default.clone().unwrap_or(Value::Undefined);
}
if value.is_undefined() {
continue;
}
output.assign(name, value);
}
if let Some(slots) = schema.and_then(|s| s.slots.as_ref()) {
for (key, slot) in slots {
let Some(name) = slot.renders(key).map_err(throw)? else {
continue;
};
match lookup(&node.slots, key) {
Found::Own(slot_node) => {
let value = {
let Some(_slot) = crate::depth::enter(cost::SLOT) else {
return Err(overflow());
};
self::node(slot_node, config)?
};
output.assign(name, value);
}
Found::Inherited => {
return Err(throw(
"TypeError: Cannot read properties of undefined (reading 'flatMap')",
));
}
Found::Missing => {}
}
}
}
Ok(output.into_object())
}
pub fn children(node: &ResolvedNode<'_>, config: &Config) -> Result<Vec<Value>> {
let mut out = Vec::new();
if node.children.is_empty() {
return Ok(out);
}
let Some(_level) = crate::depth::enter(cost::CHILDREN) else {
return Err(overflow());
};
for child in &node.children {
flat_push(&mut out, self::node(child, config)?);
}
Ok(out)
}
pub fn flat_push(out: &mut Vec<Value>, value: Value) {
match value {
Value::Array(items) => out.extend(items.present().map(|(_, v)| v.clone())),
other if value::is_array(&other) => {}
other => out.push(other),
}
}
pub fn node(node: &ResolvedNode<'_>, config: &Config) -> Result<Value> {
let Some(_depth) = Nested::enter(cost::NODE, &TRANSFORM_DEPTH, MAX_TRANSFORM_DEPTH) else {
return Err(overflow());
};
crate::depth::grow!(node_here(node, config))
}
#[inline(always)]
fn node_here(node: &ResolvedNode<'_>, config: &Config) -> Result<Value> {
let schema = find_schema(node.node, config).get();
if let Some(transform) = schema.and_then(|s| s.transform.as_ref()) {
let Some(_transform) = crate::depth::enter(cost::TRANSFORM) else {
return Err(overflow());
};
return transform(node, config);
}
let children = children(node, config)?;
rendered(node, config, schema, children)
}
#[inline(never)]
fn rendered(
node: &ResolvedNode<'_>,
config: &Config,
schema: Option<&Schema>,
children: Vec<Value>,
) -> Result<Value> {
let Some(render) = schema.and_then(|s| s.render.as_ref()) else {
return Ok(Value::array(children));
};
let attributes = attributes(node, config)?;
Ok(TagValue::new(render.clone(), attributes, children).into())
}
pub fn resolve_node<'a>(node: &'a Node, config: &Config) -> Result<ResolvedNode<'a>> {
struct Frame<'a> {
node: &'a Node,
children: Vec<ResolvedNode<'a>>,
attributes: Option<Value>,
slots: IndexMap<String, ResolvedNode<'a>>,
path: u64,
own: u64,
}
let frame = |node: &'a Node, path: u64, own: u64| Frame {
node,
children: Vec::with_capacity(node.children.len()),
attributes: None,
slots: IndexMap::new(),
path,
own,
};
let left = crate::depth::left();
if cost::RESOLVE_CHILD > left {
return Err(throw(STACK_OVERFLOW));
}
let mut stack = vec![frame(node, cost::RESOLVE_CHILD, cost::RESOLVE_CHILD)];
loop {
let top = stack
.last_mut()
.expect("the root is on the stack until it is done");
let next = if let Some(child) = top.node.children.get(top.children.len()) {
Some((child, cost::RESOLVE_CHILD))
} else {
if top.attributes.is_none() {
let path = top.path - top.own + cost::RESOLVE_SELF;
top.attributes = Some(resolve_attributes_at(top.node, path, config)?);
}
top.node
.slots
.get_index(top.slots.len())
.map(|(_, slot)| (slot, cost::RESOLVE_SLOT))
};
if let Some((next, cost)) = next {
let path = top.path + cost;
if path > left {
return Err(throw(STACK_OVERFLOW));
}
stack.push(frame(next, path, cost));
continue;
}
let done = stack.pop().expect("the frame just looked at");
let resolved = ResolvedNode {
node: done.node,
attributes: done.attributes.unwrap_or(Value::Undefined),
children: done.children,
slots: done.slots,
};
let Some(parent) = stack.last_mut() else {
return Ok(resolved);
};
if parent.children.len() < parent.node.children.len() {
parent.children.push(resolved);
} else {
let (name, _) = parent
.node
.slots
.get_index(parent.slots.len())
.expect("a slot was being resolved");
parent.slots.insert(name.clone(), resolved);
}
}
}
#[inline(never)]
fn resolve_attributes_at(node: &Node, path: u64, config: &Config) -> Result<Value> {
let _path = charge(path)?;
let _object = charge(cost::VALUE_OBJECT)?;
resolve_attributes(node, config)
}
pub fn resolve_attributes(node: &Node, config: &Config) -> Result<Value> {
match &node.attributes_prototype {
None => Ok(Value::Object(Arc::new(resolve_object(
&node.attributes,
config,
)?))),
Some(proto) => {
let props: JsObject<Value> = node
.attributes
.iter()
.map(|(k, v)| (k.clone(), Value::from_scalar(v)))
.collect();
let proto = match proto.as_ref() {
Scalar::Null => Proto::Null,
other => Proto::from_value(&Value::from_scalar(other)).unwrap_or(Proto::OBJECT),
};
resolve_js(
&Value::Object(Arc::new(Object::with_proto(props, proto))),
config,
)
}
}
}
pub fn resolve(value: &Scalar, config: &Config) -> Result<Value> {
let Some(_depth) = Nested::enter(value_cost(value), &VALUE_DEPTH, MAX_VALUE_DEPTH) else {
return Err(overflow());
};
match value {
Scalar::Array(items) => crate::depth::grow!(resolve_array(items, config)),
Scalar::Object(o) => {
crate::depth::grow!(resolve_object(o, config).map(|o| Value::Object(Arc::new(o))))
}
Scalar::Function(function) => resolve_function(function, config),
Scalar::Js(js) => resolve_js(js.value(), config),
_ => resolve_scalar(value, config),
}
}
fn value_cost(value: &Scalar) -> u64 {
match value {
Scalar::Array(_) => cost::VALUE_ARRAY,
Scalar::Object(_) => cost::VALUE_OBJECT,
Scalar::Function(_) => cost::CALL,
_ => 0,
}
}
#[inline(never)]
fn resolve_scalar(value: &Scalar, config: &Config) -> Result<Value> {
Ok(match value {
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::Array(items) => resolve_array(items, config)?,
Scalar::Object(o) => Value::Object(Arc::new(resolve_object(o, config)?)),
Scalar::Variable(variable) => resolve_variable(variable, config)?,
Scalar::Function(function) => resolve_function(function, config)?,
Scalar::Js(js) => resolve_js(js.value(), config)?,
Scalar::Tag(tag) => Value::Tag(Arc::new(TagValue::from_tag(tag))),
})
}
fn resolve_array(items: &[Scalar], config: &Config) -> Result<Value> {
let mut out = Vec::with_capacity(items.len());
for item in items {
out.push(resolve(item, config)?);
}
Ok(Value::array(out))
}
pub fn resolve_object(object: &IndexMap<String, Scalar>, config: &Config) -> Result<Object> {
let mut out = PlainObject::new();
for (k, v) in object {
let value = resolve(v, config)?;
out.assign(k.clone(), value);
}
Ok(out.into_object())
}
pub fn resolve_value(value: &Value, config: &Config) -> Result<Value> {
let cost = match value {
Value::Array(_) => cost::VALUE_ARRAY,
v if v.is_object() => cost::VALUE_OBJECT,
_ => 0,
};
let _depth = Nested::enter(cost, &VALUE_DEPTH, MAX_VALUE_DEPTH).ok_or_else(overflow)?;
crate::depth::grow!(resolve_js(value, config))
}
fn resolve_js(value: &Value, config: &Config) -> Result<Value> {
if !value.is_object() {
return Ok(value.clone());
}
if let Value::Array(items) = value {
value::array_method(value, "map", Method::ArrayMap, "value").map_err(throw)?;
value::species_check(value).map_err(throw)?;
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::new(),
));
}
if value::is_ast(value) {
match resolve_method(value)? {
Some(Ok(method)) => return call_resolve(method, value, config),
Some(Err(f)) => {
return match crate::next::realm::call(f, value, &[Value::empty_object()])
.map_err(throw)?
{
crate::next::realm::Called::Value(v)
| crate::next::realm::Called::Wrapper(v) => Ok(v),
};
}
None => {}
}
}
if !value::has_object_prototype(value) {
return Ok(value.clone());
}
let mut out = PlainObject::new();
for (k, v) in value::own_entries(value) {
let v = resolve_value(&v, config)?;
out.assign(k, v);
}
Ok(Value::Object(Arc::new(out.into_object())))
}
fn resolve_method(value: &Value) -> Result<Option<std::result::Result<Method, Builtin>>> {
let f = match value::lookup(value, "resolve").map_err(throw)? {
ValueFound::Builtin(_, Intrinsic::Method(m)) => m.builtin(),
ValueFound::Builtin(_, Intrinsic::Ctor(c)) => c.builtin(),
ValueFound::Value(Value::Builtin(f)) if f.is_callable() => f,
_ => return Ok(None),
};
Ok(Some(match Method::of(f) {
Some(m @ (Method::VariableResolve | Method::AstFunctionResolve | Method::NodeResolve)) => {
Ok(m)
}
_ => Err(f),
}))
}
fn call_resolve(method: Method, this: &Value, config: &Config) -> Result<Value> {
match method {
Method::VariableResolve => variable_resolve(this, config),
Method::AstFunctionResolve => function_resolve(this, config),
Method::NodeResolve => node_resolve(this, config),
_ => unreachable!("a resolve method"),
}
}
pub fn resolve_variable(variable: &Variable, config: &Config) -> Result<Value> {
let mut obj = match &config.variables {
Some(Variables::Fn(f)) => return Ok(f(&variable.path)),
Some(Variables::Value(v)) => v.clone(),
None => Value::Undefined,
};
for step in &variable.path {
if obj.is_undefined() {
obj = Value::empty_object();
}
obj = value::get_property(&obj, &value::property_key(step)).map_err(throw)?;
}
Ok(obj)
}
fn variable_resolve(this: &Value, config: &Config) -> Result<Value> {
let path = value::get(this, "path").map_err(throw)?;
let mut obj = match &config.variables {
Some(Variables::Fn(f)) => return Ok(f(&path_segments(&path))),
Some(Variables::Value(v)) => v.clone(),
None => Value::Undefined,
};
value::array_method(&path, "reduce", Method::ArrayReduce, "this.path").map_err(throw)?;
let (_, steps) = value::array_like_elements(&path).map_err(throw)?;
for (_, step) in steps {
if obj.is_undefined() {
obj = Value::empty_object();
}
let key = value::to_property_key(&step).map_err(throw)?;
obj = value::get(&obj, &key).map_err(throw)?;
}
Ok(obj)
}
fn path_segments(path: &Value) -> Vec<PathSegment> {
value::array_like_elements(path)
.map(|(_, steps)| {
steps
.into_iter()
.map(|(_, step)| match step {
Value::Number(n) => PathSegment::Number(n),
other => {
PathSegment::String(value::to_property_key(&other).unwrap_or_default())
}
})
.collect()
})
.unwrap_or_default()
}
pub fn resolve_function(function: &Function, config: &Config) -> Result<Value> {
let found = lookup(&config.functions, &function.name);
if let Found::Missing | Found::Own(None) = found {
return Ok(Value::Null);
}
let parameters = {
let Some(_parameters) = Nested::enter(cost::PARAMETERS, &VALUE_DEPTH, MAX_VALUE_DEPTH)
else {
return Err(overflow());
};
crate::depth::grow!(resolve_object(&function.parameters, config))?
};
call_function(found, Value::Object(Arc::new(parameters)), config)
}
fn function_resolve(this: &Value, config: &Config) -> Result<Value> {
let name = value::get(this, "name").map_err(throw)?;
let name = value::to_property_key(&name).map_err(throw)?;
let found = lookup(&config.functions, &name);
if let Found::Missing | Found::Own(None) = found {
return Ok(Value::Null);
}
let parameters = value::get(this, "parameters").map_err(throw)?;
let parameters = {
let Some(_parameters) = Nested::enter(cost::PARAMETERS, &VALUE_DEPTH, MAX_VALUE_DEPTH)
else {
return Err(overflow());
};
crate::depth::grow!(resolve_value(¶meters, config))?
};
call_function(found, parameters, config)
}
#[inline(never)]
fn call_function(
found: Found<'_, Option<schema::ConfigFunction>>,
parameters: Value,
config: &Config,
) -> Result<Value> {
match found {
Found::Own(Some(f)) => match &f.transform {
Some(transform) => transform(¶meters, config),
None => Ok(Value::Undefined),
},
_ => Ok(Value::Undefined),
}
}
fn node_resolve(this: &Value, config: &Config) -> Result<Value> {
let call = |item: &Value, expression: &str| -> Result<Value> {
match resolve_method(item)? {
Some(Ok(method)) => call_resolve(method, item, config),
Some(Err(f)) => {
match crate::next::realm::call(f, item, &[Value::empty_object()]).map_err(throw)? {
crate::next::realm::Called::Value(v)
| crate::next::realm::Called::Wrapper(v) => Ok(v),
}
}
None => Err(throw(format!(
"TypeError: {expression}.resolve is not a function"
))),
}
};
let children = value::get(this, "children").map_err(throw)?;
value::array_method(&children, "map", Method::ArrayMap, "this.children").map_err(throw)?;
value::species_check(&children).map_err(throw)?;
let (length, elements) = value::array_like_elements(&children).map_err(throw)?;
let mut resolved = Vec::with_capacity(elements.len());
for (i, child) in elements {
resolved.push((i as u32, call(&child, "child")?));
}
let children = Value::sparse_array(length as u32, resolved, IndexMap::new());
let attributes = value::get(this, "attributes").map_err(throw)?;
let attributes = resolve_value(&attributes, config)?;
let slots = value::get(this, "slots").map_err(throw)?;
let mut slots_out = JsObject::new();
for (name, slot) in value::own_entries_of(&slots).map_err(throw)? {
slots_out.insert(name, call(&slot, "slot2")?);
}
let mut node = PlainObject::with_proto(Proto::Builtin(value::BuiltinProto::NODE_PROTOTYPE));
for (k, v) in new_node_properties() {
node.assign(k, v);
}
for (k, v) in value::own_entries(this) {
node.assign(k, v);
}
node.assign("children", children);
node.assign("attributes", attributes);
node.assign("slots", Value::object(slots_out));
Ok(Value::Object(Arc::new(node.into_object())))
}
fn new_node_properties() -> Vec<(&'static str, Value)> {
vec![
("$$mdtype", Value::string("Node")),
("errors", Value::array(Vec::new())),
("lines", Value::array(Vec::new())),
("inline", Value::Boolean(false)),
("attributes", Value::empty_object()),
("children", Value::array(Vec::new())),
("type", Value::string("node")),
("tag", Value::Undefined),
("annotations", Value::array(Vec::new())),
("slots", Value::empty_object()),
]
}
#[cfg(test)]
mod tests;