mod heap;
pub(crate) mod positions;
use self::heap::{HFound, HValue, Heap, Memo};
use self::positions::{Extent, Positions};
use crate::ast::Node;
use crate::grammar;
use crate::markdown_it::{AttrValue, Token, js};
use crate::sourcemap::LineIndex;
use crate::types::{
AttributeValue, Location, LocationEdge, MarkdocError, NodeType, Position, Result, Scalar, Span,
ValidationError, ValidationLevel, array_index, js_insert,
};
use indexmap::IndexMap;
use serde_json::{Map, Value};
use std::sync::Arc;
#[derive(Debug, Clone, PartialEq)]
pub struct ParserArgs {
pub file: Option<String>,
pub slots: bool,
pub location: bool,
pub conditional_tags: Option<Vec<String>>,
pub parse_frontmatter: bool,
pub strip_bom: bool,
pub spans: bool,
}
impl Default for ParserArgs {
fn default() -> Self {
ParserArgs {
file: None,
slots: false,
location: true,
conditional_tags: None,
parse_frontmatter: false,
strip_bom: false,
spans: false,
}
}
}
impl ParserArgs {
pub fn file(file: impl Into<String>) -> Self {
ParserArgs {
file: Some(file.into()),
..ParserArgs::default()
}
}
}
fn mapping(type_name: &str) -> Option<&'static str> {
match type_name {
"ordered_list" => Some("list"),
"bullet_list" => Some("list"),
"code_inline" => Some("code"),
"list_item" => Some("item"),
"variable" => Some("text"),
_ => None,
}
}
fn js_append<V>(object: &mut IndexMap<String, V>, name: &str, value: V) {
match object.get_mut(name) {
Some(slot) => *slot = value,
None => {
object.insert(name.to_owned(), value);
}
}
}
fn js_order<V>(object: &mut IndexMap<String, V>) {
let rank = |key: &str| array_index(key).map_or((1, 0), |n| (0, n));
if !object.keys().is_sorted_by_key(|k| rank(k)) {
object.sort_by(|a, _, b, _| rank(a).cmp(&rank(b)));
}
}
fn json_truthy(value: &Value) -> bool {
match value {
Value::Null => false,
Value::Bool(b) => *b,
Value::Number(n) => n.as_f64().is_some_and(|n| n != 0.0 && !n.is_nan()),
Value::String(s) => !s.is_empty(),
_ => true,
}
}
fn json_string(value: &Value) -> String {
let items = match value {
Value::Null => return "null".into(),
Value::Bool(b) => return b.to_string(),
Value::Number(n) => return js::number_to_string(n.as_f64().unwrap_or(f64::NAN)),
Value::String(s) => return s.clone(),
Value::Object(_) => return "[object Object]".into(),
Value::Array(items) => items,
};
let mut out = String::new();
let mut stack = vec![(items.iter(), false)];
while let Some((rest, written)) = stack.last_mut() {
let Some(item) = rest.next() else {
stack.pop();
continue;
};
if *written {
out.push(',');
}
*written = true;
match item {
Value::Null => {}
Value::Array(inner) => stack.push((inner.iter(), false)),
item => out.push_str(&json_string(item)),
}
}
out
}
pub const MAX_TOKEN_NESTING: usize = 2_914;
pub(crate) const TOKEN_COST: u64 = crate::depth::per_level(MAX_TOKEN_NESTING as u64);
pub const MAX_AST_DEPTH: usize = 4_643;
pub(crate) const AST_COST: u64 = crate::depth::per_level(MAX_AST_DEPTH as u64);
pub const MAX_VALUE_DEPTH: usize = 300;
fn check_value_depth(value: &Value) -> Result<()> {
let container = |v: &&Value| matches!(v, Value::Array(_) | Value::Object(_));
if !container(&value) {
return Ok(());
}
let mut stack = vec![(value, 1)];
while let Some((value, depth)) = stack.pop() {
if depth > MAX_VALUE_DEPTH {
return Err(stack_overflow());
}
match value {
Value::Array(items) => {
stack.extend(items.iter().filter(container).map(|v| (v, depth + 1)));
}
Value::Object(fields) => {
let own = match fields.get("$$mdtype").and_then(Value::as_str) {
Some("Function") => fields.get("parameters"),
Some("Variable") => fields.get("path"),
_ => None,
};
for field in fields.values().filter(container) {
match (own, field) {
(Some(own), Value::Object(members)) if std::ptr::eq(own, field) => {
stack
.extend(members.values().filter(container).map(|v| (v, depth + 1)));
}
(Some(own), Value::Array(items)) if std::ptr::eq(own, field) => {
stack.extend(items.iter().filter(container).map(|v| (v, depth + 1)));
}
_ => stack.push((field, depth + 1)),
}
}
}
_ => {}
}
}
Ok(())
}
pub(crate) fn stack_overflow() -> MarkdocError {
MarkdocError::ParseError("RangeError: Maximum call stack size exceeded".into())
}
fn heap_from_json(heap: &mut Heap, value: &Value) -> Result<HValue> {
if !crate::depth::can_grow() {
check_value_depth(value)?;
}
heap.alloc_json(value).map_err(MarkdocError::ParseError)
}
fn heap_from_grammar(heap: &mut Heap, value: &grammar::Value) -> Result<HValue> {
heap.alloc_grammar(value).map_err(MarkdocError::ParseError)
}
enum Annotation {
Grammar {
kind: grammar::AttributeType,
name: String,
value: HValue,
},
Raw(HValue),
}
struct Annotated<'p> {
heap: &'p mut Heap,
built: &'p mut Built,
}
impl Annotated<'_> {
fn attributes(&mut self) -> HValue {
if let Some(id) = self.built.attributes {
return HValue::Object(id);
}
let alias = self.built.class_alias.take();
let node = self.built.node_mut();
let attributes = std::mem::take(&mut node.attributes);
let annotations = std::mem::take(&mut node.annotations);
let id = self.heap.alloc(heap::Class::Object);
let mut class = None;
for (k, v) in attributes {
let v = self.heap.alloc_scalar(&v);
if k == "class" && alias.is_some() {
class = Some(v.clone());
}
self.heap.define(id, k, v);
}
for (i, a) in annotations.into_iter().enumerate() {
let value = match (alias, &class) {
(Some(alias), Some(class)) if alias == i => class.clone(),
_ => self.heap.alloc_scalar(&a.value),
};
let kind = if a.attr_type == "class" {
grammar::AttributeType::Class
} else {
grammar::AttributeType::Attribute
};
self.built.annotations.push(Annotation::Grammar {
kind,
name: a.name,
value,
});
}
self.built.attributes = Some(id);
HValue::Object(id)
}
}
fn has_prototype(value: &grammar::Value) -> bool {
if !matches!(
value,
grammar::Value::Array(_)
| grammar::Value::Object(_)
| grammar::Value::Variable(_)
| grammar::Value::Function(_)
) {
return false;
}
let mut stack = vec![value];
while let Some(v) = stack.pop() {
match v {
grammar::Value::Array(items) => stack.extend(items),
grammar::Value::Object(o) => {
if !matches!(o.prototype(), grammar::Prototype::ObjectPrototype) {
return true;
}
stack.extend(o.entries().into_iter().map(|(_, v)| v));
}
grammar::Value::Variable(var) => stack.extend(&var.path),
grammar::Value::Function(f) => {
if !matches!(
f.parameters.prototype(),
grammar::Prototype::ObjectPrototype
) {
return true;
}
stack.extend(f.parameters.entries().into_iter().map(|(_, v)| v));
}
_ => {}
}
}
false
}
fn grammar_scalar(value: &grammar::Value) -> Result<Scalar> {
let limit = if crate::depth::can_grow() {
usize::MAX
} else {
MAX_VALUE_DEPTH
};
grammar_scalar_at(value, 0, limit)
}
fn grammar_scalar_at(value: &grammar::Value, depth: usize, limit: usize) -> Result<Scalar> {
crate::depth::grow!(grammar_scalar_here(value, depth, limit))
}
#[inline(always)]
fn grammar_scalar_here(value: &grammar::Value, depth: usize, limit: usize) -> Result<Scalar> {
let depth = match value {
grammar::Value::Array(_)
| grammar::Value::Object(_)
| grammar::Value::Variable(_)
| grammar::Value::Function(_) => depth + 1,
_ => depth,
};
if depth > limit {
return Err(stack_overflow());
}
let object = |o: &grammar::Object| -> Result<IndexMap<String, Scalar>> {
let mut out = IndexMap::new();
for (k, v) in o.entries() {
js_insert(&mut out, k, grammar_scalar_at(v, depth, limit)?);
}
Ok(out)
};
Ok(match value {
grammar::Value::Null => Scalar::Null,
grammar::Value::Bool(b) => Scalar::Boolean(*b),
grammar::Value::Number(n) => Scalar::Number(*n),
grammar::Value::String(s) => Scalar::String(s.clone()),
grammar::Value::Array(items) => Scalar::Array(
items
.iter()
.map(|v| grammar_scalar_at(v, depth, limit))
.collect::<Result<_>>()?,
),
grammar::Value::Object(o) => Scalar::Object(object(o)?),
grammar::Value::Variable(v) => Scalar::Variable(crate::ast::Variable::new(
v.path
.iter()
.map(|step| match step {
grammar::Value::Number(n) => crate::ast::PathSegment::Number(*n),
grammar::Value::String(s) => crate::ast::PathSegment::String(s.clone()),
other => crate::ast::PathSegment::String(other.to_json_string()),
})
.collect(),
)),
grammar::Value::Function(f) => Scalar::Function(crate::ast::Function::new(
f.name.clone(),
object(&f.parameters)?,
)),
})
}
fn js_defined(object: &IndexMap<String, Scalar>, name: &str) -> bool {
match object.get(name) {
Some(value) => !matches!(value, Scalar::Undefined),
None => crate::next::schema::value::is_object_prototype_name(name),
}
}
fn scalar_truthy(value: &Scalar) -> bool {
match value {
Scalar::Undefined | Scalar::Null => false,
Scalar::Boolean(b) => *b,
Scalar::Number(n) => *n != 0.0 && !n.is_nan(),
Scalar::String(s) => !s.is_empty(),
_ => true,
}
}
fn annotate_plain(
node: &mut Annotated<'_>,
attribute: &grammar::Attribute,
span: Option<&Span>,
) -> Result<bool> {
if has_prototype(&attribute.value) {
return Ok(false);
}
let name = attribute.name.as_str();
match attribute.kind {
grammar::AttributeType::Attribute => {
if name == "__proto__" {
return Ok(false);
}
let value = grammar_scalar(&attribute.value)?;
let index = node.built.node().annotations.len();
let shared = matches!(
value,
Scalar::Object(_) | Scalar::Array(_) | Scalar::Variable(_) | Scalar::Function(_)
);
let n = node.built.node_mut();
n.annotations.push(AttributeValue {
attr_type: "attribute".into(),
name: name.to_string(),
value: value.clone(),
raw: None,
});
if js_defined(&n.attributes, name) {
n.errors.push(ValidationError {
id: "duplicate-attribute".into(),
level: ValidationLevel::Warning,
message: format!("Attribute '{name}' already set"),
location: None,
raw: None,
span: span.cloned(),
});
}
js_append(&mut n.attributes, name, value);
if name == "class" {
node.built.class_alias = shared.then_some(index);
}
}
grammar::AttributeType::Class => {
let alias = node.built.class_alias;
let n = node.built.node_mut();
match n.attributes.get_mut("class") {
Some(class) if scalar_truthy(class) => match class {
Scalar::Object(object) if alias.is_none() => {
if name != "__proto__" || object.contains_key(name) {
js_append(object, name, Scalar::Boolean(true));
}
}
Scalar::String(_) | Scalar::Number(_) | Scalar::Boolean(_) => {
if name != "__proto__" {
let mut heap = Heap::new();
let primitive = heap.alloc_scalar(class);
heap.set(&primitive, name, HValue::Bool(true))
.map_err(MarkdocError::ParseError)?;
}
}
_ => return Ok(false),
},
_ => {
let mut class = IndexMap::new();
class.insert(name.to_string(), Scalar::Boolean(true));
js_insert(&mut n.attributes, "class", Scalar::Object(class));
node.built.class_alias = None;
}
}
node.built.node_mut().annotations.push(AttributeValue {
attr_type: "class".into(),
name: name.to_string(),
value: Scalar::Boolean(true),
raw: None,
});
}
}
Ok(true)
}
fn annotate(
mut node: Annotated<'_>,
attributes: &Value,
values: Option<&[grammar::Attribute]>,
span: Option<&Span>,
) -> Result<()> {
let throw = MarkdocError::ParseError;
if let Some(values) = values {
for a in values {
if node.built.attributes.is_none() && annotate_plain(&mut node, a, span)? {
continue;
}
node.attributes();
let value = heap_from_grammar(node.heap, &a.value)?;
let annotation = Annotation::Grammar {
kind: a.kind,
name: a.name.clone(),
value,
};
annotate_heap(&mut node, annotation, span)?;
}
return Ok(());
}
let list: Vec<Annotation> = match attributes {
Value::Array(items) => items
.iter()
.map(|a| {
match a {
Value::Object(members) => {
if !crate::depth::can_grow() {
members.values().try_for_each(check_value_depth)?;
}
Ok(Annotation::Raw(
node.heap.alloc_json(a).map_err(MarkdocError::ParseError)?,
))
}
_ => Ok(Annotation::Raw(heap_from_json(node.heap, a)?)),
}
})
.collect::<Result<_>>()?,
Value::String(s) => s
.chars()
.map(|c| Annotation::Raw(HValue::String(c.to_string())))
.collect(),
_ => {
return Err(throw("TypeError: attributes is not iterable".into()));
}
};
node.attributes();
for annotation in list {
annotate_heap(&mut node, annotation, span)?;
}
Ok(())
}
fn annotate_heap(
node: &mut Annotated<'_>,
annotation: Annotation,
span: Option<&Span>,
) -> Result<()> {
let throw = MarkdocError::ParseError;
{
let (name, value, kind) = match &annotation {
Annotation::Grammar { kind, name, value } => (
HValue::String(name.clone()),
value.clone(),
HValue::String(kind.as_str().into()),
),
Annotation::Raw(attribute) => {
if matches!(attribute, HValue::Null) {
node.built.annotations.push(annotation);
return Err(throw(
"TypeError: Cannot destructure property 'name' of 'attribute' as it is null."
.into(),
));
}
let field = |key: &str| match node.heap.lookup(attribute, key) {
HFound::Value(v) => v,
HFound::Builtin(..) => HValue::Undefined,
};
(field("name"), field("value"), field("type"))
}
};
node.built.annotations.push(annotation);
let kind = match &kind {
HValue::String(kind) => kind.as_str(),
_ => "",
};
if kind == "attribute" {
let attributes = node.attributes();
let key = node.heap.to_property_key(&name).map_err(throw)?;
if !node.heap.lookup(&attributes, &key).is_undefined() {
let message = format!(
"Attribute '{}' already set",
node.heap.display(&name).map_err(throw)?
);
node.built.node_mut().errors.push(ValidationError {
id: "duplicate-attribute".into(),
level: ValidationLevel::Warning,
message,
location: None,
raw: None,
span: span.cloned(),
});
}
node.heap.set(&attributes, &key, value).map_err(throw)?;
} else if kind == "class" {
let attributes = node.attributes();
match node.heap.lookup(&attributes, "class") {
HFound::Value(class) if heap::truthy(&class) => {
let key = node.heap.to_property_key(&name).map_err(throw)?;
node.heap.set(&class, &key, value).map_err(throw)?;
}
_ => {
let key = node.heap.to_property_key(&name).map_err(throw)?;
let class = node.heap.alloc(heap::Class::Object);
node.heap.define(class, key, value);
node.heap
.set(&attributes, "class", HValue::Object(class))
.map_err(throw)?;
}
}
}
}
Ok(())
}
fn attrs_object(token: &Token) -> IndexMap<String, &AttrValue> {
let mut object = IndexMap::new();
for (name, value) in token.attrs.iter().flatten() {
js_insert(&mut object, name.as_str(), value);
}
object
}
fn attr_scalar(value: &AttrValue) -> Scalar {
match value {
AttrValue::Str(s) => Scalar::String(s.clone()),
AttrValue::Num(n) => Scalar::Number(*n),
}
}
fn attr_truthy(value: Option<&&AttrValue>) -> bool {
match value {
None => false,
Some(AttrValue::Str(s)) => !s.is_empty(),
Some(AttrValue::Num(n)) => *n != 0.0 && !n.is_nan(),
}
}
fn handle_attrs(
token: &Token,
type_name: &str,
heap: &mut Heap,
memo: &mut Memo,
) -> Result<IndexMap<String, Scalar>> {
let mut out = IndexMap::new();
match type_name {
"heading" => {
let level = token.tag.replacen('h', "", 1);
out.insert(
"level".into(),
Scalar::Number(js::string_to_number(&js::to_utf16(&level))),
);
}
"list" => {
let attrs = token.attrs.as_ref().map(|_| attrs_object(token));
let ordered = token.kind.starts_with("ordered");
let start = attrs.as_ref().and_then(|a| a.get("start"));
out.insert("ordered".into(), Scalar::Boolean(ordered));
if ordered && attr_truthy(start) {
out.insert("start".into(), attr_scalar(start.expect("truthy")));
}
out.insert("marker".into(), Scalar::String(token.markup.clone()));
}
"link" => {
let attrs = attrs_object(token);
out.insert(
"href".into(),
attrs
.get("href")
.map_or(Scalar::Undefined, |v| attr_scalar(v)),
);
if let Some(title) = attrs.get("title").filter(|t| attr_truthy(Some(t))) {
out.insert("title".into(), attr_scalar(title));
}
}
"image" => {
let attrs = attrs_object(token);
out.insert("alt".into(), Scalar::String(token.content.clone()));
out.insert(
"src".into(),
attrs
.get("src")
.map_or(Scalar::Undefined, |v| attr_scalar(v)),
);
if let Some(title) = attrs.get("title").filter(|t| attr_truthy(Some(t))) {
out.insert("title".into(), attr_scalar(title));
}
}
"em" | "strong" => {
out.insert("marker".into(), Scalar::String(token.markup.clone()));
}
"text" | "code" | "comment" => {
let variable = token
.meta
.as_ref()
.and_then(|m| m.get("variable"))
.filter(|v| json_truthy(v));
let content = match (&token.grammar_meta, variable) {
(Some(meta), _) => match meta.variable.as_ref().filter(|v| v.truthy()) {
Some(v) if !has_prototype(v) => grammar_scalar(v)?,
Some(v) => {
let v = heap_from_grammar(heap, v)?;
heap.snapshot(&v, memo)
}
None => Scalar::String(token.content.clone()),
},
(None, Some(v)) => {
let v = heap_from_json(heap, v)?;
heap.snapshot(&v, memo)
}
(None, None) => Scalar::String(token.content.clone()),
};
out.insert("content".into(), content);
}
"fence" => {
let language = token.info.split(' ').next().unwrap_or_default();
out.insert("content".into(), Scalar::String(token.content.clone()));
if !(language.is_empty() || language == "{%") {
out.insert("language".into(), Scalar::String(language.to_string()));
}
}
"td" | "th" if token.attrs.is_some() => {
let attrs = attrs_object(token);
let mut align = None;
if let Some(style) = attrs.get("style").filter(|s| attr_truthy(Some(s))) {
let style = style.to_js_string();
if style.contains("left") {
align = Some("left");
} else if style.contains("center") {
align = Some("center");
} else if style.contains("right") {
align = Some("right");
}
}
if let Some(align) = align {
out.insert("align".into(), Scalar::String(align.into()));
}
}
_ => {}
}
Ok(out)
}
fn strip_nesting_suffix(kind: &str) -> &str {
kind.strip_suffix("_open")
.or_else(|| kind.strip_suffix("_close"))
.unwrap_or(kind)
}
fn no_parent(property: &str) -> MarkdocError {
MarkdocError::ParseError(format!(
"TypeError: Cannot read properties of undefined (reading '{property}')"
))
}
pub(crate) fn error_from_json(value: &Value) -> Result<ValidationError> {
let value = passthrough(value)?;
let field = |name: &str| value.as_object().and_then(|o| o.get(name));
let level = field("level")
.and_then(Value::as_str)
.and_then(ValidationLevel::from_name);
let plain = match &value {
Value::Object(o) => {
let keys: Vec<&str> = o.keys().map(String::as_str).collect();
matches!(
keys.as_slice(),
["id", "level", "message"] | ["id", "level", "message", "location"]
) && o["id"].is_string()
&& o["message"].is_string()
&& level.is_some()
}
_ => false,
};
let text = |name: &str| field(name).map(json_string).unwrap_or_default();
Ok(ValidationError {
id: text("id"),
level: level.unwrap_or(ValidationLevel::Error),
message: text("message"),
location: field("location").cloned(),
raw: (!plain).then(|| Box::new(value.clone())),
span: None,
})
}
fn passthrough(value: &Value) -> Result<Value> {
let mut stack = vec![(value, 0)];
while let Some((value, depth)) = stack.pop() {
let items: Box<dyn Iterator<Item = &Value>> = match value {
Value::Array(items) => Box::new(items.iter()),
Value::Object(fields) => Box::new(fields.values()),
_ => continue,
};
if depth + 1 > MAX_VALUE_DEPTH {
return Err(stack_overflow());
}
stack.extend(items.map(|v| (v, depth + 1)));
}
Ok(js_ordered(value))
}
fn js_ordered(value: &Value) -> Value {
match value {
Value::Array(items) => Value::Array(items.iter().map(js_ordered).collect()),
Value::Object(fields) => {
let mut object: IndexMap<String, Value> = fields
.iter()
.map(|(k, v)| (k.clone(), js_ordered(v)))
.collect();
js_order(&mut object);
Value::Object(object.into_iter().collect())
}
other => other.clone(),
}
}
struct Built {
node: Option<Node>,
children: Vec<usize>,
slots: IndexMap<String, usize>,
shares: Option<usize>,
slots_proto: Option<usize>,
attributes: Option<heap::Id>,
annotations: Vec<Annotation>,
class_alias: Option<usize>,
}
impl Built {
fn new(node: Node, shares: Option<usize>) -> Built {
Built {
node: Some(node),
children: Vec::new(),
slots: IndexMap::new(),
shares,
slots_proto: None,
attributes: None,
annotations: Vec::new(),
class_alias: None,
}
}
fn node(&self) -> &Node {
self.node
.as_ref()
.expect("a node is assembled only at the end")
}
fn node_mut(&mut self) -> &mut Node {
self.node
.as_mut()
.expect("a node is assembled only at the end")
}
}
struct Walk<'t> {
children: &'t [Token],
spans: Vec<Extent>,
end: usize,
next: usize,
inline_parent: Option<usize>,
}
impl<'t> Walk<'t> {
fn next(&mut self) -> Option<(&'t Token, Extent)> {
let child = self.children.get(self.next)?;
let span = self
.spans
.get(self.next)
.copied()
.unwrap_or(Extent::at(self.end));
self.next += 1;
Some((child, span))
}
}
struct Parser<'a> {
arena: Vec<Built>,
nodes: Vec<usize>,
file: Option<String>,
shared_file: Option<Arc<str>>,
handle_slots: bool,
add_location: bool,
parse_frontmatter: bool,
positions: Option<Positions<'a>>,
index: Option<LineIndex>,
source: &'a str,
max_token_level: usize,
heap: Heap,
memo: Memo,
}
impl<'a> Parser<'a> {
fn span_of(&self, extent: Extent) -> Option<Span> {
let index = self.index.as_ref()?;
let edge = |offset: usize| {
let (line, character) = index.line_col(self.source, offset);
Position {
line,
character: Some(character),
offset,
}
};
Some(Span {
file: self.file.clone(),
start: edge(extent.start),
end: edge(extent.end.max(extent.start)),
})
}
fn lines_owner(&self, index: usize) -> usize {
self.arena[index].shares.unwrap_or(index)
}
fn location(&self, lines: &[usize], token: &Token) -> Result<Location> {
let (start, end) = match token.position.as_deref() {
None => (None, None),
Some(Value::Null) => {
return Err(MarkdocError::ParseError(
"TypeError: Cannot read properties of null (reading 'start')".into(),
));
}
Some(position) => (
position
.get("start")
.map(passthrough)
.transpose()?
.map(Box::new),
position
.get("end")
.map(passthrough)
.transpose()?
.map(Box::new),
),
};
Ok(Location {
file: self.shared_file.clone(),
start: LocationEdge {
line: lines.first().copied(),
character: start,
},
end: LocationEdge {
line: lines.get(1).copied(),
character: end,
},
})
}
fn top(&self) -> Option<usize> {
self.nodes.last().copied()
}
fn frontmatter(&self, token: &Token, span: Extent) -> (Scalar, Option<ValidationError>) {
if !self.parse_frontmatter {
return (Scalar::String(token.content.clone()), None);
}
let yaml = positions::frontmatter_text(self.source, token)
.unwrap_or_else(|| token.content.clone());
match serde_yaml::from_str::<IndexMap<String, serde_yaml::Value>>(&yaml) {
Ok(mapping) => {
let mut object = IndexMap::new();
for (k, v) in mapping {
js_append(&mut object, &k, yaml_to_scalar(v));
}
js_order(&mut object);
(Scalar::Object(object), None)
}
Err(e) => (
Scalar::String(token.content.clone()),
Some(ValidationError {
id: "frontmatter-invalid".into(),
level: ValidationLevel::Error,
message: format!("Invalid YAML frontmatter: {e}"),
location: None,
raw: None,
span: self.span_of(span),
}),
),
}
}
fn attach(&mut self, parent: usize, built: Built, slot: Option<String>) -> usize {
let index = self.arena.len();
self.arena.push(built);
let parent = &mut self.arena[parent];
match slot {
Some(name) if name == "__proto__" => parent.slots_proto = Some(index),
Some(name) => js_append(&mut parent.slots, &name, index),
None => parent.children.push(index),
}
index
}
fn handle_tree(
&mut self,
token: &Token,
span: Extent,
child_spans: Option<Vec<Extent>>,
) -> Result<()> {
let mut open: Vec<Walk> = Vec::new();
open.extend(self.handle_token(token, span, child_spans, None)?);
loop {
let level = open.len();
let Some(walk) = open.last_mut() else {
return Ok(());
};
let Some((child, child_span)) = walk.next() else {
open.pop();
self.nodes.pop();
continue;
};
let inline_parent = walk.inline_parent;
if level > self.max_token_level {
return Err(stack_overflow());
}
let grandchildren = child
.children
.as_ref()
.filter(|_| self.positions.is_some())
.map(|c| vec![Extent::at(child_span.start); c.len()]);
open.extend(self.handle_token(child, child_span, grandchildren, inline_parent)?);
}
}
fn handle_token<'t>(
&mut self,
token: &'t Token,
span: Extent,
child_spans: Option<Vec<Extent>>,
mut inline_parent: Option<usize>,
) -> Result<Option<Walk<'t>>> {
if token.kind == "frontmatter" {
let (value, error) = self.frontmatter(token, span);
let document = *self.nodes.first().ok_or_else(|| {
MarkdocError::ParseError(
"TypeError: Cannot read properties of undefined (reading 'attributes')".into(),
)
})?;
let built = &mut self.arena[document];
if let Some(id) = built.attributes {
let value = self.heap.alloc_scalar(&value);
self.heap
.set(&HValue::Object(id), "frontmatter", value)
.map_err(MarkdocError::ParseError)?;
} else {
js_insert(&mut built.node_mut().attributes, "frontmatter", value);
}
built.node_mut().errors.extend(error);
return Ok(None);
}
if token.hidden || (token.kind == "text" && token.content.is_empty()) {
return Ok(None);
}
let mut errors: Vec<ValidationError> = token
.errors
.iter()
.flatten()
.map(error_from_json)
.collect::<Result<_>>()?;
let parent = self.top();
let meta = token.meta.as_ref().and_then(Value::as_object);
let field = |name: &str| meta.and_then(|m: &Map<String, Value>| m.get(name));
let (tag, attributes, error) = (field("tag"), field("attributes"), field("error"));
let here = self.span_of(span);
let values = token
.grammar_meta
.as_ref()
.and_then(|m| m.attributes.as_ref())
.and_then(|a| a.as_deref());
if token.kind == "annotation" {
let attributes = attributes.unwrap_or(&Value::Null);
if let Some(inline_parent) = inline_parent {
annotate(
Annotated {
heap: &mut self.heap,
built: &mut self.arena[inline_parent],
},
attributes,
values,
here.as_ref(),
)?;
return Ok(None);
}
let parent = self.arena[parent.ok_or_else(|| no_parent("errors"))?].node_mut();
parent.errors.push(ValidationError {
id: "no-inline-annotations".into(),
level: ValidationLevel::Error,
message: format!(
"Can't apply inline annotations to '{}'",
parent.node_type.as_str()
),
location: None,
raw: None,
span: here,
});
return Ok(None);
}
let mut type_name = strip_nesting_suffix(&token.kind);
if let Some(mapped) = mapping(type_name) {
type_name = mapped;
}
if type_name == "error" {
let error = match error {
Some(Value::Null) => {
return Err(MarkdocError::ParseError(
"TypeError: Cannot destructure property 'message' of 'error3' as it is \
null."
.into(),
));
}
Some(error) => error,
None => {
return Err(MarkdocError::ParseError(
"TypeError: Cannot destructure property 'message' of 'error3' as it is \
undefined."
.into(),
));
}
};
let message = error.get("message").map(passthrough).transpose()?;
let location = error.get("location").map(passthrough).transpose()?;
let raw = match &message {
Some(Value::String(_)) => None,
_ => {
let mut raw = Map::new();
raw.insert("id".into(), "parse-error".into());
raw.insert("level".into(), "critical".into());
raw.extend(message.iter().map(|m| ("message".to_string(), m.clone())));
raw.extend(location.iter().map(|l| ("location".to_string(), l.clone())));
Some(Box::new(Value::Object(raw)))
}
};
errors.push(ValidationError {
id: "parse-error".into(),
level: ValidationLevel::Critical,
message: message.as_ref().map(json_string).unwrap_or_default(),
location,
raw,
span: here.clone(),
});
}
if token.nesting < 0 {
let parent = parent.ok_or_else(|| no_parent("type"))?;
let open = self.arena[parent].node();
let same_tag = match (&open.tag, tag) {
(None, None) => true,
(Some(a), Some(Value::String(b))) => a == b,
_ => false,
};
if open.node_type.as_str() == type_name && same_tag {
let is_tag = open.node_type == NodeType::Tag;
if let Some(map) = token.map {
let owner = self.lines_owner(parent);
self.arena[owner].node_mut().lines.extend(map);
}
if !is_tag
&& let (Some(closing), Some(own)) =
(here, self.arena[parent].node_mut().span.as_mut())
&& closing.end.offset > own.end.offset
{
own.end = closing.end;
}
self.nodes.pop();
return Ok(None);
}
errors.push(ValidationError {
id: "missing-opening".into(),
level: ValidationLevel::Critical,
message: format!("Node '{type_name}' is missing opening"),
location: None,
raw: None,
span: here.clone(),
});
}
let attrs = handle_attrs(token, type_name, &mut self.heap, &mut self.memo)?;
let node_tag = match tag {
Some(Value::String(s)) if !s.is_empty() => Some(s.clone()),
Some(other) if json_truthy(other) => Some(json_string(other)),
_ => None,
};
let mut node = Node::new(
NodeType::from_name(type_name),
std::iter::empty(),
Vec::new(),
node_tag,
);
node.attributes = attrs;
node.errors = errors;
let mut shares = None;
if self.add_location {
match token.map {
Some(map) => {
node.lines = map.to_vec();
node.location = Some(match token.position {
None => Location {
file: self.shared_file.clone(),
start: LocationEdge {
line: Some(map[0]),
character: None,
},
end: LocationEdge {
line: Some(map[1]),
character: None,
},
},
Some(_) => self.location(&node.lines, token)?,
});
}
None => {
let owner = self.lines_owner(parent.ok_or_else(|| no_parent("lines"))?);
node.location = Some(self.location(&self.arena[owner].node().lines, token)?);
shares = Some(owner);
}
}
}
if inline_parent.is_some() {
node.inline = true;
}
let mut built = Built::new(node, shares);
if let Some(attributes) = attributes
&& json_truthy(attributes)
&& ["tag", "fence", "image"].contains(&type_name)
{
annotate(
Annotated {
heap: &mut self.heap,
built: &mut built,
},
attributes,
values,
here.as_ref(),
)?;
}
let slot = match tag {
Some(Value::String(t)) if self.handle_slots && t == "slot" => match built.attributes {
Some(id) => match self.heap.lookup(&HValue::Object(id), "primary") {
HFound::Value(HValue::String(primary)) => Some(primary),
_ => None,
},
None => match built.node().attributes.get("primary") {
Some(Scalar::String(primary)) => Some(primary.clone()),
_ => None,
},
},
_ => None,
};
let parent =
parent.ok_or_else(|| no_parent(if slot.is_some() { "slots" } else { "push" }))?;
built.node_mut().span = here;
let index = self.attach(parent, built, slot);
if token.nesting > 0 {
self.nodes.push(index);
}
let Some(children) = &token.children else {
return Ok(None);
};
if type_name == "inline" {
inline_parent = Some(parent);
}
let is_leaf_node = type_name == "image";
if is_leaf_node {
return Ok(None);
}
self.nodes.push(index);
Ok(Some(Walk {
children,
spans: child_spans.unwrap_or_default(),
end: span.end,
next: 0,
inline_parent,
}))
}
fn assemble(mut self) -> Node {
let Parser {
arena, heap, memo, ..
} = &mut self;
for index in (0..arena.len()).rev() {
if let Some(owner) = arena[index].shares {
let lines = arena[owner].node().lines.clone();
arena[index].node_mut().lines = lines;
}
let built = &mut arena[index];
if let Some(node) = built.node.as_mut() {
if let Some(id) = built.attributes {
let (attributes, prototype) = heap.snapshot_attributes(id, memo);
node.attributes = attributes;
node.attributes_prototype = prototype;
node.annotations = std::mem::take(&mut built.annotations)
.into_iter()
.map(|a| annotation_value(heap, a, memo))
.collect();
} else {
js_order(&mut node.attributes);
if let Some(Scalar::Object(class)) = node.attributes.get_mut("class") {
js_order(class);
}
}
}
js_order(&mut built.slots);
let slots_proto = built.slots_proto.take();
if built.children.is_empty() && built.slots.is_empty() && slots_proto.is_none() {
continue;
}
let (children, slots) = (
std::mem::take(&mut built.children),
std::mem::take(&mut built.slots),
);
let children: Vec<Node> = {
let mut nodes = Vec::with_capacity(children.len());
nodes.extend(children.into_iter().filter_map(|c| arena[c].node.take()));
nodes
};
let slots: IndexMap<String, Node> = slots
.into_iter()
.filter_map(|(name, s)| arena[s].node.take().map(|n| (name, n)))
.collect();
let slots_prototype = slots_proto.and_then(|p| arena[p].node.take());
if let Some(node) = arena[index].node.as_mut() {
node.children = children;
node.slots = slots;
node.slots_prototype = slots_prototype.map(Box::new);
}
}
arena[0].node.take().expect("the document")
}
}
fn annotation_value(heap: &Heap, annotation: Annotation, memo: &mut Memo) -> AttributeValue {
match annotation {
Annotation::Grammar { kind, name, value } => AttributeValue {
attr_type: kind.as_str().into(),
name,
value: heap.snapshot(&value, memo),
raw: None,
},
Annotation::Raw(attribute) => {
if let Some((attr_type, name, value)) = heap.attribute_object(&attribute) {
return AttributeValue {
attr_type,
name,
value: heap.snapshot(&value, memo),
raw: None,
};
}
let field = |key: &str| match &attribute {
HValue::Object(_) => match heap.lookup(&attribute, key) {
HFound::Value(v) => v,
HFound::Builtin(..) => HValue::Undefined,
},
_ => HValue::Undefined,
};
let text = |v: HValue| match v {
HValue::Undefined => String::new(),
v => heap.display(&v).unwrap_or_default(),
};
AttributeValue {
attr_type: text(field("type")),
name: text(field("name")),
value: heap.snapshot(&field("value"), memo),
raw: Some(Box::new(heap.snapshot(&attribute, memo))),
}
}
}
}
fn yaml_to_scalar(value: serde_yaml::Value) -> Scalar {
match value {
serde_yaml::Value::Null => Scalar::Null,
serde_yaml::Value::Bool(b) => Scalar::Boolean(b),
serde_yaml::Value::Number(n) => {
if let Some(i) = n.as_i64() {
Scalar::Number(i as f64)
} else if let Some(f) = n.as_f64() {
Scalar::Number(f)
} else {
Scalar::Null
}
}
serde_yaml::Value::String(s) => Scalar::String(s),
serde_yaml::Value::Sequence(seq) => {
Scalar::Array(seq.into_iter().map(yaml_to_scalar).collect())
}
serde_yaml::Value::Mapping(map) => {
let mut object = IndexMap::new();
for (k, v) in map {
if let serde_yaml::Value::String(key) = k {
js_append(&mut object, &key, yaml_to_scalar(v));
}
}
js_order(&mut object);
Scalar::Object(object)
}
serde_yaml::Value::Tagged(_) => Scalar::Null,
}
}
pub fn revive(value: &Value) -> std::result::Result<Scalar, String> {
let mut heap = Heap::new();
let value = heap.alloc_json(value)?;
Ok(heap.snapshot(&value, &mut Memo::default()))
}
pub fn revive_annotation(value: &Value) -> std::result::Result<AttributeValue, String> {
let mut heap = Heap::new();
let value = heap.alloc_json(value)?;
Ok(annotation_value(
&heap,
Annotation::Raw(value),
&mut Memo::default(),
))
}
pub fn parse(tokens: &[Token], source: &str, args: &ParserArgs) -> Result<Node> {
let spans = args.spans && args.location;
let mut document = Node::new(NodeType::Document, IndexMap::new(), Vec::new(), None);
let mut parser = Parser {
arena: Vec::with_capacity(
tokens
.iter()
.map(|t| 1 + t.children.as_ref().map_or(0, Vec::len))
.sum::<usize>()
+ 1,
),
nodes: Vec::new(),
file: args.file.clone(),
shared_file: args.file.as_deref().map(Arc::from),
handle_slots: args.slots,
add_location: args.location,
parse_frontmatter: args.parse_frontmatter,
positions: spans.then(|| Positions::new(source)),
index: spans.then(|| LineIndex::new(source)),
source,
max_token_level: usize::try_from(crate::depth::left() / TOKEN_COST).unwrap_or(usize::MAX),
heap: Heap::new(),
memo: Memo::default(),
};
document.span = parser.span_of(Extent {
start: 0,
end: source.len(),
});
parser.arena.push(Built::new(document, None));
parser.nodes.push(0);
for i in 0..tokens.len() {
let (span, child_spans) = match parser.positions.as_mut() {
Some(positions) => positions.token(tokens, i),
None => (Extent::at(0), None),
};
parser.handle_tree(&tokens[i], span, child_spans)?;
}
if parser.nodes.len() > 1 {
for &index in &parser.nodes[1..] {
let node = parser.arena[index].node_mut();
let name = node
.tag
.clone()
.filter(|t| !t.is_empty())
.unwrap_or_else(|| node.node_type.as_str().to_string());
let span = node.span.clone();
node.errors.push(ValidationError {
id: "missing-closing".into(),
level: ValidationLevel::Critical,
message: format!("Node '{name}' is missing closing"),
location: None,
raw: None,
span,
});
}
}
let mut document = parser.assemble();
for transform in super::transforms::TRANSFORMS {
transform(&mut document, args.conditional_tags.as_deref())?;
}
Ok(document)
}
#[cfg(test)]
mod tests;