use std::cell::RefCell;
use std::collections::HashMap;
use std::rc::Rc;
use std::sync::Arc;
use indexmap::IndexMap;
use tabnas::{Context, Lexer, Rule, Tabnas, Tin, Token, Value};
use crate::ast::{block_head, block_tail, definition_node, inline_children, leaf_block, object};
use crate::block::{BlockEvent, BlockParser};
use crate::engine_inline::{parse_block_engine, parse_inlines_engine};
use crate::inline::InlineParser;
use crate::node::{NodeId, NodeType, Tree};
use crate::options::Options;
pub const LINE_TOKEN: &str = "#LB";
pub const END_TOKEN: &str = "#EN";
pub const MD_BLOCK_MATCHER: &str = "mdBlock";
pub const MD_BLOCK_ORDER: f64 = 100_000.0;
pub const MD_PREPARE: &str = "md-reset";
pub const MD_STATE_KEY: &str = "md";
#[derive(Debug, Clone, Copy)]
pub struct NodeRule {
pub rule: &'static str,
pub token: &'static str,
pub container: bool,
pub gfm: bool,
pub desc: &'static str,
}
const fn node_rule(
rule: &'static str,
token: &'static str,
container: bool,
gfm: bool,
desc: &'static str,
) -> NodeRule {
NodeRule {
rule,
token,
container,
gfm,
desc,
}
}
pub const NODE_RULES: &[NodeRule] = &[
node_rule("blockquote", "#BQ", true, false, "block quote"),
node_rule("list", "#LS", true, false, "list"),
node_rule("listItem", "#LI", true, false, "list item"),
node_rule("paragraph", "#PA", true, false, "paragraph"),
node_rule("heading", "#HD", true, false, "ATX or setext heading"),
node_rule("table", "#TB", true, true, "GFM table"),
node_rule("tableRow", "#TR", true, true, "table row"),
node_rule("tableCell", "#TC", true, true, "table cell"),
node_rule("emphasis", "#EM", true, false, "emphasis"),
node_rule("strong", "#SG", true, false, "strong emphasis"),
node_rule("delete", "#DL", true, true, "strikethrough"),
node_rule("link", "#LK", true, false, "link"),
node_rule("linkReference", "#LR", true, false, "link reference"),
node_rule("thematicBreak", "#HR", false, false, "thematic break"),
node_rule("code", "#CD", false, false, "fenced or indented code"),
node_rule("html", "#HT", false, false, "HTML block or raw HTML"),
node_rule(
"definition",
"#DF",
false,
false,
"link reference definition",
),
node_rule("text", "#TT", false, false, "text"),
node_rule("inlineCode", "#IC", false, false, "code span"),
node_rule("break", "#BR", false, false, "hard line break"),
node_rule("image", "#IM", false, false, "image"),
node_rule("imageReference", "#IR", false, false, "image reference"),
];
fn token_of(node_type: &str) -> &'static str {
NODE_RULES
.iter()
.find(|n| n.rule == node_type)
.map_or(LINE_TOKEN, |n| n.token)
}
fn type_of<'v>(fields: &'v [(&'static str, Value)]) -> &'v str {
match fields.iter().find(|(k, _)| *k == "type") {
Some((_, Value::String(t))) => t,
_ => "",
}
}
fn node_type_of(node: &Value) -> &str {
match value_get(node, "type") {
Some(Value::String(t)) => t,
_ => "",
}
}
type Made = (&'static str, Value);
pub(crate) fn value_get<'v>(value: &'v Value, key: &str) -> Option<&'v Value> {
match value {
Value::Object(map) => map.get(key),
Value::MapRef(map) => map.value.get(key),
_ => None,
}
}
pub(crate) fn slot_of(ctx: &Context, key: &str) -> Option<usize> {
let mut value = ctx.u.get(key)?;
if let Value::Array(items) = value {
value = items.first()?;
}
match value {
Value::Number(n) if *n >= 0.0 => Some(*n as usize),
_ => None,
}
}
struct BlockState {
bp: BlockParser,
keep_tree: bool,
inline: Option<InlineParser>,
made: Vec<Made>,
next: usize,
read: bool,
lease: Arc<Vec<Value>>,
}
impl BlockState {
fn stale(&self) -> bool {
Arc::strong_count(&self.lease) == 1
}
}
thread_local! {
static BLOCK_STATES: RefCell<Vec<Option<BlockState>>> = const { RefCell::new(Vec::new()) };
static KEPT_TREE: RefCell<Option<Tree>> = const { RefCell::new(None) };
}
fn block_slot_insert(bp: BlockParser, keep_tree: bool, options: Options) -> (usize, Value) {
BLOCK_STATES.with(|cell| {
let mut slab = cell.borrow_mut();
for entry in slab.iter_mut() {
if entry.as_ref().is_some_and(BlockState::stale) {
*entry = None;
}
}
let slot = slab.iter().position(Option::is_none).unwrap_or_else(|| {
slab.push(None);
slab.len() - 1
});
let lease = Arc::new(vec![Value::Number(slot as f64)]);
slab[slot] = Some(BlockState {
bp,
keep_tree,
inline: Some(InlineParser::keeping_references(options)),
made: Vec::new(),
next: 0,
read: false,
lease: Arc::clone(&lease),
});
(slot, Value::Array(lease))
})
}
#[cfg(test)]
fn block_slots_held() -> usize {
BLOCK_STATES.with(|cell| cell.borrow().iter().filter(|s| s.is_some()).count())
}
fn block_slot_take(slot: usize) -> Option<BlockState> {
BLOCK_STATES.with(|cell| cell.borrow_mut().get_mut(slot).and_then(Option::take))
}
fn with_block_state<R>(ctx: &Context, f: impl FnOnce(&mut BlockState) -> R) -> Option<R> {
let slot = slot_of(ctx, MD_STATE_KEY)?;
BLOCK_STATES.with(|cell| {
let mut slab = cell.borrow_mut();
slab.get_mut(slot).and_then(Option::as_mut).map(f)
})
}
pub fn take_kept_tree() -> Option<Tree> {
KEPT_TREE.with(|cell| cell.borrow_mut().take())
}
fn keep_tree_requested(meta: &Value) -> bool {
matches!(
value_get(meta, MD_STATE_KEY).and_then(|md| value_get(md, "keepTree")),
Some(Value::Bool(true))
)
}
struct Line {
text: String,
src: String,
chars: usize,
last: bool,
}
fn cut_line(lexer: &mut Lexer<'_>) -> Option<Line> {
if lexer.window().is_empty() && !lexer.fill(1) {
return None;
}
let mut i = 0;
loop {
let w = lexer.window().as_bytes();
while i < w.len() && w[i] != b'\n' && w[i] != b'\r' {
i += 1;
}
if i < w.len() {
break;
}
let had = w.len();
let chars = lexer.window().chars().count();
lexer.fill(2 * chars + 1);
if lexer.window().len() == had {
break;
}
}
let text_chars = lexer.window()[..i].chars().count();
let mut next = i;
if i < lexer.window().len() {
if lexer.window().as_bytes()[i] == b'\r' {
if i + 1 >= lexer.window().len() {
lexer.fill(text_chars + 2);
}
let w = lexer.window().as_bytes();
next = if i + 1 < w.len() && w[i + 1] == b'\n' {
i + 2
} else {
i + 1
};
} else {
next = i + 1;
}
}
let chars = text_chars + (next - i);
let last = !lexer.fill(chars + 1);
let w = lexer.window();
let mut text = w[..i].to_string();
if text.contains('\0') {
text = text.replace('\0', "\u{FFFD}");
}
Some(Line {
text,
src: w[..next].to_string(),
chars,
last,
})
}
enum Out {
Block(Made),
Line,
}
pub fn make_md_block_matcher(
opts: Options,
tins: HashMap<&'static str, Tin>,
inline_tn: Arc<Tabnas>,
) -> impl for<'s> Fn(&mut Lexer<'s>, &mut Rule, &mut Context) -> Option<Token> + Send + Sync + 'static
{
move |lexer, _rule, ctx| {
let tin = |name: &str| tins.get(name).copied().unwrap_or_default();
let pending = with_block_state(ctx, |state| {
if state.next < state.made.len() {
let made = state.made[state.next].clone();
state.next += 1;
Some(made)
} else {
None
}
})?;
if let Some((name, value)) = pending {
let point = lexer.point();
return Some(lexer.token(name, tin(name), value, "", point));
}
let line = cut_line(lexer)?;
let out = with_block_state(ctx, |state| {
if !state.read {
state.bp.incorporate_line(&line.text);
if line.last {
state.bp.close_all();
}
let events = state.bp.events.take().unwrap_or_default();
state.bp.events = Some(Vec::new());
let mut made = Vec::new();
for event in events {
event_tokens(state, &opts, &inline_tn, event, &mut made);
}
for block in std::mem::take(&mut state.bp.dropped) {
if !state.keep_tree {
state.bp.release_block(block);
}
}
if let Some(first) = made.first().cloned() {
state.made = made;
state.next = 1;
state.read = true;
return Out::Block(first);
}
}
state.made.clear();
state.next = 0;
state.read = false;
Out::Line
})?;
let point = lexer.point();
match out {
Out::Block((name, value)) => Some(lexer.token(name, tin(name), value, "", point)),
Out::Line => {
let token = lexer.token(
LINE_TOKEN,
tin(LINE_TOKEN),
Value::Undefined,
line.src.as_str(),
point,
);
lexer.advance_chars(line.chars);
Some(token)
}
}
}
}
fn event_tokens(
state: &mut BlockState,
opts: &Options,
inline_tn: &Tabnas,
event: BlockEvent,
out: &mut Vec<Made>,
) {
match event {
BlockEvent::Open(id) => {
let head = block_head(&state.bp.tree, id);
out.push((token_of(type_of(&head)), object(head)));
}
BlockEvent::Row(row) => {
out.push(("#TR", object(block_head(&state.bp.tree, row))));
let mut cell = state.bp.tree.get(row).first_child;
while let Some(c) = cell {
inline_block_tokens(state, opts, inline_tn, c, out);
cell = state.bp.tree.get(c).next;
}
out.push((END_TOKEN, object(block_tail(&state.bp.tree, row))));
}
BlockEvent::Definition(def) => out.push(("#DF", definition_node(&def))),
BlockEvent::Close(id) => {
close_tokens(state, opts, inline_tn, id, out);
if !state.keep_tree
&& (state.bp.is_top_level(id) || state.bp.tree.get(id).parent.is_none())
{
state.bp.release_block(id);
}
}
}
}
fn close_tokens(
state: &mut BlockState,
opts: &Options,
inline_tn: &Tabnas,
id: NodeId,
out: &mut Vec<Made>,
) {
match state.bp.tree.get(id).node_type {
NodeType::BlockQuote | NodeType::List | NodeType::Item | NodeType::Table => {
out.push((END_TOKEN, object(block_tail(&state.bp.tree, id))));
}
NodeType::Paragraph | NodeType::Heading => {
if state.bp.tree.get(id).parent.is_some() {
inline_block_tokens(state, opts, inline_tn, id, out);
}
}
NodeType::ThematicBreak | NodeType::CodeBlock | NodeType::HtmlBlock => {
if let Some(leaf) = leaf_block(&state.bp.tree, id) {
out.push((token_of(node_type_of(&leaf)), leaf));
}
if !state.keep_tree {
release(&mut state.bp.tree, id);
}
}
_ => {}
}
}
fn inline_block_tokens(
state: &mut BlockState,
opts: &Options,
inline_tn: &Tabnas,
node: NodeId,
out: &mut Vec<Made>,
) {
let head = block_head(&state.bp.tree, node);
let tail = block_tail(&state.bp.tree, node);
let mut scratch = Tree::new(state.bp.tree.get(node).node_type);
let root = scratch.root();
scratch.get_mut(root).string_content = state.bp.tree.get(node).string_content.clone();
let parser = state
.inline
.take()
.unwrap_or_else(|| InlineParser::keeping_references(*opts));
let (parser, scratch) = parse_block_engine(inline_tn, parser, scratch, root);
state.inline = Some(parser);
out.push((token_of(type_of(&head)), object(head)));
inline_tokens(inline_children(&scratch, root, opts), out);
out.push((END_TOKEN, object(tail)));
if !state.keep_tree {
release(&mut state.bp.tree, node);
}
}
fn inline_tokens(nodes: Vec<Value>, out: &mut Vec<Made>) {
let mut stack: Vec<std::vec::IntoIter<Value>> = vec![nodes.into_iter()];
while let Some(top) = stack.last_mut() {
let Some(node) = top.next() else {
stack.pop();
if !stack.is_empty() {
out.push((END_TOKEN, object(Vec::new())));
}
continue;
};
let token = token_of(node_type_of(&node));
match value_get(&node, "children") {
Some(Value::Array(children)) => {
let children = children.as_ref().clone();
let mut head = IndexMap::new();
if let Value::Object(fields) = &node {
for (k, v) in fields.iter() {
if k != "children" {
head.insert(k.clone(), v.clone());
}
}
}
out.push((token, Value::object(head)));
stack.push(children.into_iter());
}
_ => out.push((token, node)),
}
}
}
fn release(tree: &mut Tree, node: NodeId) {
let n = tree.get_mut(node);
n.string_content = String::new();
n.literal = String::new();
n.first_child = None;
n.last_child = None;
}
pub fn make_md_prepare(opts: Options) -> impl Fn(&mut Context) + Send + Sync + 'static {
move |ctx| {
let mut bp = BlockParser::new(opts);
bp.events = Some(Vec::new());
let (_, lease) = block_slot_insert(bp, keep_tree_requested(&ctx.meta), opts);
ctx.u.insert(MD_STATE_KEY.to_string(), lease);
}
}
fn list_push(list: &mut Value, item: Value) {
if let Value::Array(items) = list {
Arc::make_mut(items).push(item);
}
}
pub fn md_begin(rule: &mut Rule, _ctx: &mut Context) {
rule.node = Rc::new(RefCell::new(Value::array(Vec::new())));
}
pub fn make_md_finish(
opts: Options,
inline_tn: Arc<Tabnas>,
) -> impl Fn(&mut Rule, &mut Context) + Send + Sync + 'static {
move |rule, ctx| {
if let Some(state) = slot_of(ctx, MD_STATE_KEY).and_then(block_slot_take) {
if state.keep_tree {
let tree = parse_inlines_engine(&inline_tn, state.bp.tree, state.bp.refmap, &opts);
KEPT_TREE.with(|cell| *cell.borrow_mut() = Some(tree));
}
}
let children = rule.node.borrow().clone();
rule.node = Rc::new(RefCell::new(object(vec![
("type", Value::String("document".to_string())),
("children", children),
])));
}
}
pub fn md_open(rule: &mut Rule, _ctx: &mut Context) {
let head = rule.o0().map_or(Value::Undefined, |t| t.val.clone());
rule.u_mut().insert("head".to_string(), head);
rule.node = Rc::new(RefCell::new(Value::array(Vec::new())));
}
pub fn md_close(rule: &mut Rule, _ctx: &mut Context) {
let mut node = IndexMap::new();
if let Some(Value::Object(head)) = rule.u.get("head") {
for (k, v) in head.iter() {
node.insert(k.clone(), v.clone());
}
}
node.insert("children".to_string(), rule.node.borrow().clone());
if let Some(Value::Object(tail)) = rule.c0().map(|t| &t.val) {
for (k, v) in tail.iter() {
node.insert(k.clone(), v.clone());
}
}
if let Some(parent) = &rule.parent_node {
list_push(&mut parent.borrow_mut(), Value::object(node));
}
}
pub fn md_leaf(rule: &mut Rule, _ctx: &mut Context) {
let value = rule.o0().map_or(Value::Undefined, |t| t.val.clone());
list_push(&mut rule.node.borrow_mut(), value);
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn slots_are_reused() {
let (a, lease_a) = block_slot_insert(
BlockParser::new(Options::default()),
false,
Options::default(),
);
let (b, lease_b) = block_slot_insert(
BlockParser::new(Options::default()),
false,
Options::default(),
);
assert_ne!(a, b);
assert!(block_slot_take(a).is_some());
assert!(block_slot_take(a).is_none());
let (c, lease_c) = block_slot_insert(
BlockParser::new(Options::default()),
true,
Options::default(),
);
assert_eq!(a, c);
assert!(block_slot_take(b).is_some());
assert!(block_slot_take(c).is_some_and(|s| s.keep_tree));
drop((lease_a, lease_b, lease_c));
}
#[test]
fn stale_slots_are_reclaimed_by_the_next_insert() {
let (a, lease_a) = block_slot_insert(
BlockParser::new(Options::default()),
false,
Options::default(),
);
let (b, lease_b) = block_slot_insert(
BlockParser::new(Options::default()),
false,
Options::default(),
);
drop(lease_a); let (c, lease_c) = block_slot_insert(
BlockParser::new(Options::default()),
false,
Options::default(),
);
assert_eq!(c, a, "the stale slot is the one reused");
assert_ne!(c, b, "the live slot is left alone");
assert!(block_slot_take(b).is_some());
assert!(block_slot_take(c).is_some());
drop((lease_b, lease_c));
}
#[test]
fn aborted_parses_do_not_accumulate_slots() {
let mut tn = crate::make();
tn.parse_budget(1, |ctx| ctx.iteration < 4);
let src = "a\nb\nc\nd\ne\nf\ng\nh\n";
let mut held = 0;
for _ in 0..200 {
let error = tn.parse(src).expect_err("the budget cancels the parse");
assert_eq!(error.code, "cancel");
held = held.max(block_slots_held());
}
assert!(held <= 1, "{held} slots held across 200 aborted parses");
let doc = crate::make()
.parse("ok")
.expect("a parse under no budget completes");
assert!(!doc.is_undefined());
assert_eq!(block_slots_held(), 0);
}
}