Skip to main content

tabnas_markdown/
engine_block.rs

1/* Copyright (c) 2026 Richard Rodger, MIT License */
2
3//! The engine-facing block driver: a custom lexer matcher that cuts the
4//! source one physical line at a time, runs the shared block algorithm over
5//! each line, and hands the engine the blocks that line opened and closed
6//! as tokens; and the rule actions that build the AST from those tokens.
7//! Port of `ts/src/engine-block.ts` and `go/engineblock.go`.
8//!
9//! The grammar's rules open and close every block (`lib.rs`): a
10//! container's rule opens on the token that opens it (`#BQ` for a block
11//! quote, `#LS` for a list, ...) and closes on `#EN`, and a leaf's rule
12//! opens and closes on its one token (`#HR`, `#CD`, `#DF`, ...). A block's
13//! inline content is parsed when the block closes, since the block bounds
14//! it, and its inline nodes are tokens and rules too, so the rule passes
15//! carry the whole tree, a block at a time, and the value the rules build
16//! is that tree.
17//!
18//! The block decisions themselves are the shared [`BlockParser`]'s, the
19//! same code the engine-free path runs (the anti-drift rule, dx-report
20//! ยง42). This driver turns what it decided into tokens in the order it
21//! decided it ([`BlockParser::events`]), and nothing here recognizes any
22//! Markdown of its own.
23//!
24//! Each line is one `#LB` token, cut through the lexer's window, so a
25//! grammar that declares `lex.window` is read a window at a time. The
26//! tokens of the blocks the line closed and opened come first, of no
27//! width, where the line starts, one each time the lexer asks, and then the
28//! line itself: the tokens are in source order, and the last line's tokens
29//! also close every block still open, since no token follows the last line
30//! but the end.
31//!
32//! # State carriage
33//!
34//! The other two runtimes hang the live block parser on `ctx.u.md` as an
35//! opaque object. The Rust engine's `Context::u` holds only [`Value`]s,
36//! so the parser itself lives in a thread-local slab and `ctx.u["md"]`
37//! carries its slot index. The slot is claimed by the `parse.prepare`
38//! hook and released by the `markdown` rule's finish action, which is the
39//! last thing a parse runs. A parse the engine aborts between the two
40//! (a budget error, a panic in some other plugin's callback) never runs
41//! the finish action, so its slot is reclaimed by liveness instead: the
42//! index travels inside a one-element array whose `Arc` the slot also
43//! holds, the engine drops the context, and with it the array, when the
44//! parse ends however it ends, and the next prepare on the thread frees
45//! every slot whose `Arc` it is the last holder of. The slab therefore
46//! never holds more than the parses live on the thread plus the aborted
47//! ones since the last prepare, whatever a long-lived worker is fed.
48//!
49//! Thread-local rather than keyed by parse: a [`tabnas::Tabnas`] instance
50//! is `Send + Sync` and parses through `&self`, so one installed plugin
51//! may serve many threads at once. Each thread's slab is its own, and a
52//! parse never leaves the thread it started on.
53//!
54//! This module may import engine types: it is reachable only from
55//! `lib.rs`, never from `commonmark.rs`, so the engine-free layering rule
56//! holds (see AGENTS.md).
57
58use std::cell::RefCell;
59use std::collections::HashMap;
60use std::rc::Rc;
61use std::sync::Arc;
62
63use indexmap::IndexMap;
64use tabnas::{Context, Lexer, Rule, Tabnas, Tin, Token, Value};
65
66use crate::ast::{block_head, block_tail, definition_node, inline_children, leaf_block, object};
67use crate::block::{BlockEvent, BlockParser};
68use crate::engine_inline::{parse_block_engine, parse_inlines_engine};
69use crate::inline::InlineParser;
70use crate::node::{NodeId, NodeType, Tree};
71use crate::options::Options;
72
73/// One physical line, read: the blocks it made precede it.
74pub const LINE_TOKEN: &str = "#LB";
75
76/// A container's end: its value is the fields that follow its children.
77pub const END_TOKEN: &str = "#EN";
78
79/// The `mdBlock` matcher's name in `options.lex.matchers`.
80pub const MD_BLOCK_MATCHER: &str = "mdBlock";
81
82/// The `mdBlock` matcher's order: ahead of every built-in, so a line is
83/// consumed whole before any built-in matcher sees its first character.
84pub const MD_BLOCK_ORDER: f64 = 100_000.0;
85
86/// The `parse.prepare` hook's name.
87pub const MD_PREPARE: &str = "md-reset";
88
89/// The key under `ctx.u` that carries the block state's slot index.
90pub const MD_STATE_KEY: &str = "md";
91
92/// A node of the AST, its rule and the token its rule opens on. A
93/// container's token carries its head (the fields before its `children`,
94/// `type` first), and its `#EN` its tail; a leaf's token carries the whole
95/// node. The rule is named for the node's type. The GFM nodes are the
96/// `gfm` group's.
97#[derive(Debug, Clone, Copy)]
98pub struct NodeRule {
99    pub rule: &'static str,
100    pub token: &'static str,
101    pub container: bool,
102    pub gfm: bool,
103    pub desc: &'static str,
104}
105
106const fn node_rule(
107    rule: &'static str,
108    token: &'static str,
109    container: bool,
110    gfm: bool,
111    desc: &'static str,
112) -> NodeRule {
113    NodeRule {
114        rule,
115        token,
116        container,
117        gfm,
118        desc,
119    }
120}
121
122/// Every node's rule, as `ts/src/engine-block.ts` lists them.
123pub const NODE_RULES: &[NodeRule] = &[
124    node_rule("blockquote", "#BQ", true, false, "block quote"),
125    node_rule("list", "#LS", true, false, "list"),
126    node_rule("listItem", "#LI", true, false, "list item"),
127    node_rule("paragraph", "#PA", true, false, "paragraph"),
128    node_rule("heading", "#HD", true, false, "ATX or setext heading"),
129    node_rule("table", "#TB", true, true, "GFM table"),
130    node_rule("tableRow", "#TR", true, true, "table row"),
131    node_rule("tableCell", "#TC", true, true, "table cell"),
132    node_rule("emphasis", "#EM", true, false, "emphasis"),
133    node_rule("strong", "#SG", true, false, "strong emphasis"),
134    node_rule("delete", "#DL", true, true, "strikethrough"),
135    node_rule("link", "#LK", true, false, "link"),
136    node_rule("linkReference", "#LR", true, false, "link reference"),
137    node_rule("thematicBreak", "#HR", false, false, "thematic break"),
138    node_rule("code", "#CD", false, false, "fenced or indented code"),
139    node_rule("html", "#HT", false, false, "HTML block or raw HTML"),
140    node_rule(
141        "definition",
142        "#DF",
143        false,
144        false,
145        "link reference definition",
146    ),
147    node_rule("text", "#TT", false, false, "text"),
148    node_rule("inlineCode", "#IC", false, false, "code span"),
149    node_rule("break", "#BR", false, false, "hard line break"),
150    node_rule("image", "#IM", false, false, "image"),
151    node_rule("imageReference", "#IR", false, false, "image reference"),
152];
153
154/// The token a node of each AST type opens with.
155fn token_of(node_type: &str) -> &'static str {
156    NODE_RULES
157        .iter()
158        .find(|n| n.rule == node_type)
159        .map_or(LINE_TOKEN, |n| n.token)
160}
161
162/// The `type` of an AST node's fields, or of an AST node.
163fn type_of<'v>(fields: &'v [(&'static str, Value)]) -> &'v str {
164    match fields.iter().find(|(k, _)| *k == "type") {
165        Some((_, Value::String(t))) => t,
166        _ => "",
167    }
168}
169
170fn node_type_of(node: &Value) -> &str {
171    match value_get(node, "type") {
172        Some(Value::String(t)) => t,
173        _ => "",
174    }
175}
176
177/// A token the line matcher makes: its name and its value.
178type Made = (&'static str, Value);
179
180/// One key of an object value. Both object spellings the engine has.
181pub(crate) fn value_get<'v>(value: &'v Value, key: &str) -> Option<&'v Value> {
182    match value {
183        Value::Object(map) => map.get(key),
184        Value::MapRef(map) => map.value.get(key),
185        _ => None,
186    }
187}
188
189/// The slot index a prepare hook stored under `ctx.u[key]`: a bare
190/// number (the inline driver's form), or a number alone in an array (the
191/// block driver's form, where the array's `Arc` doubles as the lease
192/// described at the top of this module).
193pub(crate) fn slot_of(ctx: &Context, key: &str) -> Option<usize> {
194    let mut value = ctx.u.get(key)?;
195    if let Value::Array(items) = value {
196        value = items.first()?;
197    }
198    match value {
199        Value::Number(n) if *n >= 0.0 => Some(*n as usize),
200        _ => None,
201    }
202}
203
204// --- the per-parse state ----------------------------------------------------
205
206/// What `ctx.u["md"]` points at: the live block parser, the keepTree
207/// request read off the parse meta, and the line matcher's own state.
208struct BlockState {
209    bp: BlockParser,
210    keep_tree: bool,
211    /// The inline parse a block's AST is made with: references kept. Held
212    /// in an option so that it can travel with the nested inline parse.
213    inline: Option<InlineParser>,
214    /// The tokens the line at the cursor made, handed out one a call
215    /// before the line's own token (`next` the one due), and whether that
216    /// line has been read: its blocks are decided, and its `#LB` is what is
217    /// left.
218    made: Vec<Made>,
219    next: usize,
220    read: bool,
221    /// The array `ctx.u["md"]` holds, shared with the context. While the
222    /// context lives the count is at least two; once the engine has
223    /// dropped it, this is the last holder and the slot is stale.
224    lease: Arc<Vec<Value>>,
225}
226
227impl BlockState {
228    fn stale(&self) -> bool {
229        Arc::strong_count(&self.lease) == 1
230    }
231}
232
233thread_local! {
234    static BLOCK_STATES: RefCell<Vec<Option<BlockState>>> = const { RefCell::new(Vec::new()) };
235
236    /// The native tree a `keepTree` parse hands back. Set by the finish
237    /// action, taken by [`take_kept_tree`] right after the parse returns.
238    static KEPT_TREE: RefCell<Option<Tree>> = const { RefCell::new(None) };
239}
240
241/// Claim a slot for a new parse and return the value `ctx.u["md"]` must
242/// carry. Slots whose parse has ended without the finish action (see the
243/// module docs) are freed first, so the slab never grows past the parses
244/// that are actually live on this thread.
245fn block_slot_insert(bp: BlockParser, keep_tree: bool, options: Options) -> (usize, Value) {
246    BLOCK_STATES.with(|cell| {
247        let mut slab = cell.borrow_mut();
248        for entry in slab.iter_mut() {
249            if entry.as_ref().is_some_and(BlockState::stale) {
250                *entry = None;
251            }
252        }
253        let slot = slab.iter().position(Option::is_none).unwrap_or_else(|| {
254            slab.push(None);
255            slab.len() - 1
256        });
257        let lease = Arc::new(vec![Value::Number(slot as f64)]);
258        slab[slot] = Some(BlockState {
259            bp,
260            keep_tree,
261            inline: Some(InlineParser::keeping_references(options)),
262            made: Vec::new(),
263            next: 0,
264            read: false,
265            lease: Arc::clone(&lease),
266        });
267        (slot, Value::Array(lease))
268    })
269}
270
271/// How many slots hold a block state right now, stale ones included.
272#[cfg(test)]
273fn block_slots_held() -> usize {
274    BLOCK_STATES.with(|cell| cell.borrow().iter().filter(|s| s.is_some()).count())
275}
276
277fn block_slot_take(slot: usize) -> Option<BlockState> {
278    BLOCK_STATES.with(|cell| cell.borrow_mut().get_mut(slot).and_then(Option::take))
279}
280
281fn with_block_state<R>(ctx: &Context, f: impl FnOnce(&mut BlockState) -> R) -> Option<R> {
282    let slot = slot_of(ctx, MD_STATE_KEY)?;
283    BLOCK_STATES.with(|cell| {
284        let mut slab = cell.borrow_mut();
285        slab.get_mut(slot).and_then(Option::as_mut).map(f)
286    })
287}
288
289/// The native tree the last `keepTree` parse on this thread produced, if
290/// any. `None` after a parse that did not ask for it, and after an empty
291/// source, which the engine answers with `lex.empty_result` before any
292/// rule runs.
293pub fn take_kept_tree() -> Option<Tree> {
294    KEPT_TREE.with(|cell| cell.borrow_mut().take())
295}
296
297/// True when the parse meta carries `{"md": {"keepTree": true}}`.
298fn keep_tree_requested(meta: &Value) -> bool {
299    matches!(
300        value_get(meta, MD_STATE_KEY).and_then(|md| value_get(md, "keepTree")),
301        Some(Value::Bool(true))
302    )
303}
304
305// --- the lexer matcher ------------------------------------------------------
306
307/// One physical line at the cursor.
308struct Line {
309    text: String,
310    src: String,
311    /// The characters the line takes, its terminator included.
312    chars: usize,
313    last: bool,
314}
315
316/// One physical line at the cursor, read through the lexer's window: up to
317/// (not including) the next `\n`, `\r` or `\r\n`, with section 2.3's NUL
318/// replacement. `last` says whether the source ends after it (which is why
319/// a final line ending does not make a trailing blank line). The window is
320/// filled past the line's end, so a token never ends at the window's end,
321/// where the lexer would cut it again over a wider one, and a line longer
322/// than the window is read on in doubling steps. A line is read twice, once
323/// to decide its blocks and once for its own token, and gives the same both
324/// times. Every byte compared is ASCII; [`Lexer::fill`] counts characters.
325fn cut_line(lexer: &mut Lexer<'_>) -> Option<Line> {
326    if lexer.window().is_empty() && !lexer.fill(1) {
327        return None;
328    }
329
330    let mut i = 0;
331    loop {
332        let w = lexer.window().as_bytes();
333        while i < w.len() && w[i] != b'\n' && w[i] != b'\r' {
334            i += 1;
335        }
336        if i < w.len() {
337            break;
338        }
339        let had = w.len();
340        let chars = lexer.window().chars().count();
341        lexer.fill(2 * chars + 1);
342        if lexer.window().len() == had {
343            break;
344        }
345    }
346
347    let text_chars = lexer.window()[..i].chars().count();
348    let mut next = i;
349    if i < lexer.window().len() {
350        if lexer.window().as_bytes()[i] == b'\r' {
351            if i + 1 >= lexer.window().len() {
352                lexer.fill(text_chars + 2);
353            }
354            let w = lexer.window().as_bytes();
355            next = if i + 1 < w.len() && w[i + 1] == b'\n' {
356                i + 2
357            } else {
358                i + 1
359            };
360        } else {
361            next = i + 1;
362        }
363    }
364
365    let chars = text_chars + (next - i);
366    let last = !lexer.fill(chars + 1);
367    let w = lexer.window();
368    let mut text = w[..i].to_string();
369    if text.contains('\0') {
370        text = text.replace('\0', "\u{FFFD}");
371    }
372    Some(Line {
373        text,
374        src: w[..next].to_string(),
375        chars,
376        last,
377    })
378}
379
380/// What one invocation of the matcher hands out.
381enum Out {
382    /// A token of a block, of no width.
383    Block(Made),
384    /// The line itself.
385    Line,
386}
387
388/// Build the `mdBlock` matcher. Each invocation returns one token. At a
389/// line not yet read, it reads the line, feeds it to the shared
390/// [`BlockParser`] (and, for the last line, closes every block still
391/// open), and gathers the tokens of the blocks the line closed and opened;
392/// those are handed out first, of no width, where the line starts, and then
393/// the line itself as a `#LB` token. Row and column bookkeeping is left to
394/// the lexer's own `advance_chars`, which counts CHARACTERS and resets the
395/// column on a consumed `\n`; `tests/engine_columns_test.rs` pins the
396/// resulting positions. Nothing reads the source but [`cut_line`], through
397/// the window.
398pub fn make_md_block_matcher(
399    opts: Options,
400    tins: HashMap<&'static str, Tin>,
401    inline_tn: Arc<Tabnas>,
402) -> impl for<'s> Fn(&mut Lexer<'s>, &mut Rule, &mut Context) -> Option<Token> + Send + Sync + 'static
403{
404    move |lexer, _rule, ctx| {
405        let tin = |name: &str| tins.get(name).copied().unwrap_or_default();
406
407        let pending = with_block_state(ctx, |state| {
408            if state.next < state.made.len() {
409                let made = state.made[state.next].clone();
410                state.next += 1;
411                Some(made)
412            } else {
413                None
414            }
415        })?;
416        if let Some((name, value)) = pending {
417            let point = lexer.point();
418            return Some(lexer.token(name, tin(name), value, "", point));
419        }
420
421        let line = cut_line(lexer)?;
422
423        let out = with_block_state(ctx, |state| {
424            if !state.read {
425                state.bp.incorporate_line(&line.text);
426                if line.last {
427                    state.bp.close_all();
428                }
429                let events = state.bp.events.take().unwrap_or_default();
430                state.bp.events = Some(Vec::new());
431                let mut made = Vec::new();
432                for event in events {
433                    event_tokens(state, &opts, &inline_tn, event, &mut made);
434                }
435                // The blocks the line took out of the tree with no close
436                // of their own are written by nothing; a parse that keeps
437                // no tree gives their slots back.
438                for block in std::mem::take(&mut state.bp.dropped) {
439                    if !state.keep_tree {
440                        state.bp.release_block(block);
441                    }
442                }
443                if let Some(first) = made.first().cloned() {
444                    state.made = made;
445                    state.next = 1;
446                    state.read = true;
447                    return Out::Block(first);
448                }
449            }
450            state.made.clear();
451            state.next = 0;
452            state.read = false;
453            Out::Line
454        })?;
455
456        let point = lexer.point();
457        match out {
458            Out::Block((name, value)) => Some(lexer.token(name, tin(name), value, "", point)),
459            Out::Line => {
460                let token = lexer.token(
461                    LINE_TOKEN,
462                    tin(LINE_TOKEN),
463                    Value::Undefined,
464                    line.src.as_str(),
465                    point,
466                );
467                lexer.advance_chars(line.chars);
468                Some(token)
469            }
470        }
471    }
472}
473
474/// The tokens one block event makes, appended to `out`.
475fn event_tokens(
476    state: &mut BlockState,
477    opts: &Options,
478    inline_tn: &Tabnas,
479    event: BlockEvent,
480    out: &mut Vec<Made>,
481) {
482    match event {
483        BlockEvent::Open(id) => {
484            let head = block_head(&state.bp.tree, id);
485            out.push((token_of(type_of(&head)), object(head)));
486        }
487
488        BlockEvent::Row(row) => {
489            out.push(("#TR", object(block_head(&state.bp.tree, row))));
490            let mut cell = state.bp.tree.get(row).first_child;
491            while let Some(c) = cell {
492                inline_block_tokens(state, opts, inline_tn, c, out);
493                cell = state.bp.tree.get(c).next;
494            }
495            out.push((END_TOKEN, object(block_tail(&state.bp.tree, row))));
496        }
497
498        BlockEvent::Definition(def) => out.push(("#DF", definition_node(&def))),
499
500        BlockEvent::Close(id) => {
501            close_tokens(state, opts, inline_tn, id, out);
502            // Its tokens are written: a parse that keeps no tree lets go of
503            // a block at the top of the document, with everything below it,
504            // and of a paragraph that held nothing but definitions, which
505            // is out of the tree already. Without this the arena kept every
506            // block to the document's end (tabnas/markdown#100).
507            if !state.keep_tree
508                && (state.bp.is_top_level(id) || state.bp.tree.get(id).parent.is_none())
509            {
510                state.bp.release_block(id);
511            }
512        }
513    }
514}
515
516/// The tokens a block's `Close` makes, appended to `out`.
517fn close_tokens(
518    state: &mut BlockState,
519    opts: &Options,
520    inline_tn: &Tabnas,
521    id: NodeId,
522    out: &mut Vec<Made>,
523) {
524    match state.bp.tree.get(id).node_type {
525        NodeType::BlockQuote | NodeType::List | NodeType::Item | NodeType::Table => {
526            out.push((END_TOKEN, object(block_tail(&state.bp.tree, id))));
527        }
528
529        NodeType::Paragraph | NodeType::Heading => {
530            // A paragraph that held nothing but definitions is gone:
531            // its definitions were written as they were read.
532            if state.bp.tree.get(id).parent.is_some() {
533                inline_block_tokens(state, opts, inline_tn, id, out);
534            }
535        }
536
537        NodeType::ThematicBreak | NodeType::CodeBlock | NodeType::HtmlBlock => {
538            if let Some(leaf) = leaf_block(&state.bp.tree, id) {
539                out.push((token_of(node_type_of(&leaf)), leaf));
540            }
541            if !state.keep_tree {
542                release(&mut state.bp.tree, id);
543            }
544        }
545
546        _ => {}
547    }
548}
549
550/// A block whose content is inline nodes (a paragraph, a heading, a table
551/// cell), parsed now: its head, its inline nodes, its end. The block's raw
552/// text is parsed in a tree of its own, so the native tree keeps it when
553/// the caller wants that tree back, which is parsed again, references
554/// resolved, once the document ends.
555fn inline_block_tokens(
556    state: &mut BlockState,
557    opts: &Options,
558    inline_tn: &Tabnas,
559    node: NodeId,
560    out: &mut Vec<Made>,
561) {
562    let head = block_head(&state.bp.tree, node);
563    let tail = block_tail(&state.bp.tree, node);
564
565    let mut scratch = Tree::new(state.bp.tree.get(node).node_type);
566    let root = scratch.root();
567    scratch.get_mut(root).string_content = state.bp.tree.get(node).string_content.clone();
568    let parser = state
569        .inline
570        .take()
571        .unwrap_or_else(|| InlineParser::keeping_references(*opts));
572    let (parser, scratch) = parse_block_engine(inline_tn, parser, scratch, root);
573    state.inline = Some(parser);
574
575    out.push((token_of(type_of(&head)), object(head)));
576    inline_tokens(inline_children(&scratch, root, opts), out);
577    out.push((END_TOKEN, object(tail)));
578    if !state.keep_tree {
579        release(&mut state.bp.tree, node);
580    }
581}
582
583/// The tokens of a run of inline nodes, in document order: a container's
584/// head, its children's, its end; a leaf whole. Iterative, since inline
585/// nesting is the input's to choose.
586fn inline_tokens(nodes: Vec<Value>, out: &mut Vec<Made>) {
587    let mut stack: Vec<std::vec::IntoIter<Value>> = vec![nodes.into_iter()];
588    while let Some(top) = stack.last_mut() {
589        let Some(node) = top.next() else {
590            stack.pop();
591            if !stack.is_empty() {
592                out.push((END_TOKEN, object(Vec::new())));
593            }
594            continue;
595        };
596        let token = token_of(node_type_of(&node));
597        match value_get(&node, "children") {
598            Some(Value::Array(children)) => {
599                let children = children.as_ref().clone();
600                let mut head = IndexMap::new();
601                if let Value::Object(fields) = &node {
602                    for (k, v) in fields.iter() {
603                        if k != "children" {
604                            head.insert(k.clone(), v.clone());
605                        }
606                    }
607                }
608                out.push((token, Value::object(head)));
609                stack.push(children.into_iter());
610            }
611            _ => out.push((token, node)),
612        }
613    }
614}
615
616/// Drop what a written block holds that nothing reads again: its raw text,
617/// its literal and its inline nodes. The block itself stays in the native
618/// tree, whose later lines still read its flags.
619fn release(tree: &mut Tree, node: NodeId) {
620    let n = tree.get_mut(node);
621    n.string_content = String::new();
622    n.literal = String::new();
623    n.first_child = None;
624    n.last_child = None;
625}
626
627// --- the actions ------------------------------------------------------------
628
629/// The `parse.prepare` hook: fresh block-parser state for every parse,
630/// with the keepTree request captured from the parse meta.
631///
632/// The engine runs this hook before it short-circuits an empty source
633/// through `lex.empty_result`, and in a parse from a reader before it knows
634/// whether the source is empty (`ctx.source` is empty in every such
635/// parse), so a slot is claimed for an empty source too. Its finish action
636/// never runs, and the next prepare on the thread reclaims the slot by its
637/// lease (see the module docs).
638pub fn make_md_prepare(opts: Options) -> impl Fn(&mut Context) + Send + Sync + 'static {
639    move |ctx| {
640        let mut bp = BlockParser::new(opts);
641        bp.events = Some(Vec::new());
642        let (_, lease) = block_slot_insert(bp, keep_tree_requested(&ctx.meta), opts);
643        ctx.u.insert(MD_STATE_KEY.to_string(), lease);
644    }
645}
646
647/// A list value with `item` added at its end.
648fn list_push(list: &mut Value, item: Value) {
649    if let Value::Array(items) = list {
650        Arc::make_mut(items).push(item);
651    }
652}
653
654/// `markdown` open: the document's children gather here, in a cell of the
655/// rule's own, which the children's rules share.
656pub fn md_begin(rule: &mut Rule, _ctx: &mut Context) {
657    rule.node = Rc::new(RefCell::new(Value::array(Vec::new())));
658}
659
660/// `markdown` close (`#ZZ`): the document. When the caller passed
661/// `meta.md.keepTree`, the native tree, with its references resolved, is
662/// parked for [`take_kept_tree`]: the engine-path conformance harness
663/// renders it.
664pub fn make_md_finish(
665    opts: Options,
666    inline_tn: Arc<Tabnas>,
667) -> impl Fn(&mut Rule, &mut Context) + Send + Sync + 'static {
668    move |rule, ctx| {
669        if let Some(state) = slot_of(ctx, MD_STATE_KEY).and_then(block_slot_take) {
670            if state.keep_tree {
671                let tree = parse_inlines_engine(&inline_tn, state.bp.tree, state.bp.refmap, &opts);
672                KEPT_TREE.with(|cell| *cell.borrow_mut() = Some(tree));
673            }
674        }
675        let children = rule.node.borrow().clone();
676        // A fresh cell, never a write through the inherited one: the
677        // engine shares node cells between a rule and its parent.
678        rule.node = Rc::new(RefCell::new(object(vec![
679            ("type", Value::String("document".to_string())),
680            ("children", children),
681        ])));
682    }
683}
684
685/// A container node's open action: its children gather in a cell of its
686/// own, and its head waits in `u` for its close.
687pub fn md_open(rule: &mut Rule, _ctx: &mut Context) {
688    let head = rule.o0().map_or(Value::Undefined, |t| t.val.clone());
689    rule.u_mut().insert("head".to_string(), head);
690    rule.node = Rc::new(RefCell::new(Value::array(Vec::new())));
691}
692
693/// A container node's close action on `#EN`: its node is its head, its
694/// children and its tail, in that order, added to its parent's children.
695pub fn md_close(rule: &mut Rule, _ctx: &mut Context) {
696    let mut node = IndexMap::new();
697    if let Some(Value::Object(head)) = rule.u.get("head") {
698        for (k, v) in head.iter() {
699            node.insert(k.clone(), v.clone());
700        }
701    }
702    node.insert("children".to_string(), rule.node.borrow().clone());
703    if let Some(Value::Object(tail)) = rule.c0().map(|t| &t.val) {
704        for (k, v) in tail.iter() {
705            node.insert(k.clone(), v.clone());
706        }
707    }
708    if let Some(parent) = &rule.parent_node {
709        list_push(&mut parent.borrow_mut(), Value::object(node));
710    }
711}
712
713/// A leaf node's open action: the token's value is the node.
714pub fn md_leaf(rule: &mut Rule, _ctx: &mut Context) {
715    let value = rule.o0().map_or(Value::Undefined, |t| t.val.clone());
716    list_push(&mut rule.node.borrow_mut(), value);
717}
718
719#[cfg(test)]
720mod tests {
721    use super::*;
722
723    #[test]
724    fn slots_are_reused() {
725        // The leases stand in for the contexts that would hold them.
726        let (a, lease_a) = block_slot_insert(
727            BlockParser::new(Options::default()),
728            false,
729            Options::default(),
730        );
731        let (b, lease_b) = block_slot_insert(
732            BlockParser::new(Options::default()),
733            false,
734            Options::default(),
735        );
736        assert_ne!(a, b);
737        assert!(block_slot_take(a).is_some());
738        assert!(block_slot_take(a).is_none());
739        let (c, lease_c) = block_slot_insert(
740            BlockParser::new(Options::default()),
741            true,
742            Options::default(),
743        );
744        assert_eq!(a, c);
745        assert!(block_slot_take(b).is_some());
746        assert!(block_slot_take(c).is_some_and(|s| s.keep_tree));
747        drop((lease_a, lease_b, lease_c));
748    }
749
750    /// A slot whose context is gone is freed by the next insert; one
751    /// whose context still lives is not.
752    #[test]
753    fn stale_slots_are_reclaimed_by_the_next_insert() {
754        let (a, lease_a) = block_slot_insert(
755            BlockParser::new(Options::default()),
756            false,
757            Options::default(),
758        );
759        let (b, lease_b) = block_slot_insert(
760            BlockParser::new(Options::default()),
761            false,
762            Options::default(),
763        );
764        drop(lease_a); // the engine dropped that parse's context
765        let (c, lease_c) = block_slot_insert(
766            BlockParser::new(Options::default()),
767            false,
768            Options::default(),
769        );
770        assert_eq!(c, a, "the stale slot is the one reused");
771        assert_ne!(c, b, "the live slot is left alone");
772        assert!(block_slot_take(b).is_some());
773        assert!(block_slot_take(c).is_some());
774        drop((lease_b, lease_c));
775    }
776
777    /// Finding 2 of the review: an engine parse that aborts before the
778    /// finish action leaves its slot behind, and a worker fed such input
779    /// repeatedly must not accumulate them. A parse budget that cancels
780    /// after a few iterations is the aborted parse; the slab is read
781    /// after each one.
782    #[test]
783    fn aborted_parses_do_not_accumulate_slots() {
784        let mut tn = crate::make();
785        tn.parse_budget(1, |ctx| ctx.iteration < 4);
786        let src = "a\nb\nc\nd\ne\nf\ng\nh\n";
787        let mut held = 0;
788        for _ in 0..200 {
789            let error = tn.parse(src).expect_err("the budget cancels the parse");
790            assert_eq!(error.code, "cancel");
791            held = held.max(block_slots_held());
792        }
793        // At most the parse that just aborted, whose context is gone but
794        // which no prepare has run since.
795        assert!(held <= 1, "{held} slots held across 200 aborted parses");
796
797        // A parse that runs to completion on this thread frees it too.
798        let doc = crate::make()
799            .parse("ok")
800            .expect("a parse under no budget completes");
801        assert!(!doc.is_undefined());
802        assert_eq!(block_slots_held(), 0);
803    }
804}