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 turns the
4//! engine's scan into one `#LB` token per physical line, and the actions
5//! that feed those lines to the shared [`BlockParser`]. Port of
6//! `ts/src/engine-block.ts` and `go/engineblock.go`.
7//!
8//! This is the seam of the anti-drift rule (dx-report §42): nothing here
9//! recognizes anything. Line cutting and NUL replacement come from
10//! [`segment_next_line`], blank detection from [`is_blank`], and every
11//! block decision (continuation, starts, lazy continuation, finalization)
12//! from the same [`BlockParser`] the engine-free path runs. The engine
13//! owns tokenization, dispatch, per-parse state carriage and
14//! observability; the algorithm stays in the shared core.
15//!
16//! # State carriage
17//!
18//! The other two runtimes hang the live block parser on `ctx.u.md` as an
19//! opaque object. The Rust engine's `Context::u` holds only [`Value`]s,
20//! so the parser itself lives in a thread-local slab and `ctx.u["md"]`
21//! carries its slot index. The slot is claimed by the `parse.prepare`
22//! hook and released by the `markdown` rule's finish action, which is the
23//! last thing a parse runs. A parse the engine aborts between the two
24//! (a budget error, a panic in some other plugin's callback) never runs
25//! the finish action, so its slot is reclaimed by liveness instead: the
26//! index travels inside a one-element array whose `Arc` the slot also
27//! holds, the engine drops the context, and with it the array, when the
28//! parse ends however it ends, and the next prepare on the thread frees
29//! every slot whose `Arc` it is the last holder of. The slab therefore
30//! never holds more than the parses live on the thread plus the aborted
31//! ones since the last prepare, whatever a long-lived worker is fed.
32//!
33//! Thread-local rather than keyed by parse: a [`tabnas::Tabnas`] instance
34//! is `Send + Sync` and parses through `&self`, so one installed plugin
35//! may serve many threads at once. Each thread's slab is its own, and a
36//! parse never leaves the thread it started on.
37//!
38//! This module may import engine types: it is reachable only from
39//! `lib.rs`, never from `commonmark.rs`, so the engine-free layering rule
40//! holds (see AGENTS.md).
41
42use std::cell::RefCell;
43use std::rc::Rc;
44use std::sync::Arc;
45
46use indexmap::IndexMap;
47use tabnas::{Context, Lexer, Rule, Tin, Token, Value};
48
49use crate::ast::to_ast;
50use crate::block::{is_blank, segment_next_line, BlockParser};
51use crate::node::Tree;
52use crate::options::{Options, RefMap};
53
54/// The block phase's one token: a physical line.
55pub const LINE_TOKEN: &str = "#LB";
56
57/// The `mdLine` matcher's name in `options.lex.matchers`.
58pub const MD_LINE_MATCHER: &str = "mdLine";
59
60/// The `mdLine` matcher's order: ahead of every built-in, so a line is
61/// consumed whole before any built-in matcher sees its first character.
62pub const MD_LINE_ORDER: f64 = 100_000.0;
63
64/// The `parse.prepare` hook's name.
65pub const MD_PREPARE: &str = "md-reset";
66
67/// The key under `ctx.u` that carries the block state's slot index, and
68/// the key under a `#LB` token's `use_data` that carries its [`LineInfo`].
69pub const MD_STATE_KEY: &str = "md";
70
71/// The `#LB` token's payload: one physical line, pre-classified. A
72/// downstream dialect's alt conditions can read it back from the token
73/// with [`LineInfo::from_token`] (see the extension recipe in
74/// `doc/guide.md`).
75///
76/// On the token, the text is the token's `val` and the two flags sit
77/// under `use_data["md"]`, so a line costs one string, not two.
78#[derive(Debug, Clone, Copy, PartialEq, Eq)]
79pub struct LineInfo<'a> {
80    /// The line's text, terminator excluded, NULs already replaced.
81    pub text: &'a str,
82    /// True when the line holds nothing but spaces and tabs.
83    pub blank: bool,
84    /// GFM table arming: true when the line contains a `|` or a `-`
85    /// anywhere. A deliberate, *provable* superset of "could be a
86    /// delimiter row": every delimiter cell requires at least one `-`
87    /// (`:-:` rows open pipe-less single-column tables), and multi-column
88    /// rows carry `|`. The real decision needs the container-adjusted
89    /// offset only the block algorithm knows (a delimiter row nested in a
90    /// block quote matches after the `>` marker), so the `gfm`-tagged alt
91    /// reading this bit only *arms* the probe, and `try_open_table`
92    /// re-verifies (see test/spec/mixed.tsv).
93    pub tbl_arm: bool,
94}
95
96impl<'a> LineInfo<'a> {
97    /// Classify one line of text.
98    pub fn of(text: &'a str) -> LineInfo<'a> {
99        LineInfo {
100            text,
101            blank: is_blank(text),
102            tbl_arm: text.contains('|') || text.contains('-'),
103        }
104    }
105
106    /// Read the payload back off a `#LB` token. `None` for any other
107    /// token.
108    pub fn from_token(token: &'a Token) -> Option<LineInfo<'a>> {
109        let text = match &token.val {
110            Value::String(s) => s.as_str(),
111            Value::Text(t) => t.string.as_str(),
112            _ => return None,
113        };
114        let flags = token.use_data().get(MD_STATE_KEY)?;
115        let blank = matches!(value_get(flags, "blank"), Some(Value::Bool(true)));
116        let tbl_arm = matches!(value_get(flags, "tblArm"), Some(Value::Bool(true)));
117        Some(LineInfo {
118            text,
119            blank,
120            tbl_arm,
121        })
122    }
123
124    fn flags_value(&self) -> Value {
125        let mut map = IndexMap::with_capacity(2);
126        map.insert("blank".to_string(), Value::Bool(self.blank));
127        map.insert("tblArm".to_string(), Value::Bool(self.tbl_arm));
128        Value::object(map)
129    }
130}
131
132/// One key of an object value. Both object spellings the engine has.
133pub(crate) fn value_get<'v>(value: &'v Value, key: &str) -> Option<&'v Value> {
134    match value {
135        Value::Object(map) => map.get(key),
136        Value::MapRef(map) => map.value.get(key),
137        _ => None,
138    }
139}
140
141/// The slot index a prepare hook stored under `ctx.u[key]`: a bare
142/// number (the inline driver's form), or a number alone in an array (the
143/// block driver's form, where the array's `Arc` doubles as the lease
144/// described at the top of this module).
145pub(crate) fn slot_of(ctx: &Context, key: &str) -> Option<usize> {
146    let mut value = ctx.u.get(key)?;
147    if let Value::Array(items) = value {
148        value = items.first()?;
149    }
150    match value {
151        Value::Number(n) if *n >= 0.0 => Some(*n as usize),
152        _ => None,
153    }
154}
155
156// --- the per-parse state ----------------------------------------------------
157
158/// What `ctx.u["md"]` points at: the live block parser and the keepTree
159/// request read off the parse meta.
160struct BlockState {
161    bp: BlockParser,
162    keep_tree: bool,
163    /// The array `ctx.u["md"]` holds, shared with the context. While the
164    /// context lives the count is at least two; once the engine has
165    /// dropped it, this is the last holder and the slot is stale.
166    lease: Arc<Vec<Value>>,
167}
168
169impl BlockState {
170    fn stale(&self) -> bool {
171        Arc::strong_count(&self.lease) == 1
172    }
173}
174
175thread_local! {
176    static BLOCK_STATES: RefCell<Vec<Option<BlockState>>> = const { RefCell::new(Vec::new()) };
177
178    /// The native tree a `keepTree` parse hands back. Set by the finish
179    /// action, taken by [`take_kept_tree`] right after the parse returns.
180    static KEPT_TREE: RefCell<Option<Tree>> = const { RefCell::new(None) };
181}
182
183/// Claim a slot for a new parse and return the value `ctx.u["md"]` must
184/// carry. Slots whose parse has ended without the finish action (see the
185/// module docs) are freed first, so the slab never grows past the parses
186/// that are actually live on this thread.
187fn block_slot_insert(bp: BlockParser, keep_tree: bool) -> (usize, Value) {
188    BLOCK_STATES.with(|cell| {
189        let mut slab = cell.borrow_mut();
190        for entry in slab.iter_mut() {
191            if entry.as_ref().is_some_and(BlockState::stale) {
192                *entry = None;
193            }
194        }
195        let slot = slab.iter().position(Option::is_none).unwrap_or_else(|| {
196            slab.push(None);
197            slab.len() - 1
198        });
199        let lease = Arc::new(vec![Value::Number(slot as f64)]);
200        slab[slot] = Some(BlockState {
201            bp,
202            keep_tree,
203            lease: Arc::clone(&lease),
204        });
205        (slot, Value::Array(lease))
206    })
207}
208
209/// How many slots hold a block state right now, stale ones included.
210#[cfg(test)]
211fn block_slots_held() -> usize {
212    BLOCK_STATES.with(|cell| cell.borrow().iter().filter(|s| s.is_some()).count())
213}
214
215fn block_slot_take(slot: usize) -> Option<BlockState> {
216    BLOCK_STATES.with(|cell| cell.borrow_mut().get_mut(slot).and_then(Option::take))
217}
218
219fn with_block_state<R>(ctx: &Context, f: impl FnOnce(&mut BlockState) -> R) -> Option<R> {
220    let slot = slot_of(ctx, MD_STATE_KEY)?;
221    BLOCK_STATES.with(|cell| {
222        let mut slab = cell.borrow_mut();
223        slab.get_mut(slot).and_then(Option::as_mut).map(f)
224    })
225}
226
227/// The native tree the last `keepTree` parse on this thread produced, if
228/// any. `None` after a parse that did not ask for it, and after an empty
229/// source, which the engine answers with `lex.empty_result` before any
230/// rule runs.
231pub fn take_kept_tree() -> Option<Tree> {
232    KEPT_TREE.with(|cell| cell.borrow_mut().take())
233}
234
235/// True when the parse meta carries `{"md": {"keepTree": true}}`.
236fn keep_tree_requested(meta: &Value) -> bool {
237    matches!(
238        value_get(meta, MD_STATE_KEY).and_then(|md| value_get(md, "keepTree")),
239        Some(Value::Bool(true))
240    )
241}
242
243// --- the lexer matcher ------------------------------------------------------
244
245/// Build the `mdLine` matcher: each invocation consumes one physical line,
246/// terminator included, and emits a single `#LB` token carrying the line
247/// as a [`LineInfo`]. The matcher owns the engine's point: the byte offset
248/// advances past the terminator, the row counts line endings, and the
249/// column resets per line. (The engine's column is not used for
250/// indentation: the shared [`BlockParser`] computes spec §2.2
251/// tab-expanded columns itself.)
252///
253/// Row and column bookkeeping is observability data (`#ZZ` position,
254/// traces) and is left to the lexer's own `advance_chars`, which counts
255/// CHARACTERS and resets the column on a consumed `\n`. That is the
256/// arithmetic the Go port spells out by hand; `tests/engine_columns_test.rs`
257/// pins the resulting positions.
258pub fn make_md_line_matcher(
259    lb: Tin,
260) -> impl for<'s> Fn(&mut Lexer<'s>, &mut Rule, &mut Context) -> Option<Token> + Send + Sync + 'static
261{
262    move |lexer, _rule, _ctx| {
263        let point = lexer.point();
264        let src = lexer.source();
265        let seg = segment_next_line(src, point.site.si)?;
266        let raw = &src[point.site.si..seg.next];
267        let raw_chars = raw.chars().count();
268        let flags = LineInfo::of(&seg.text).flags_value();
269        let mut token = lexer.token(LINE_TOKEN, lb, Value::String(seg.text), raw, point);
270        token.use_data_mut().insert(MD_STATE_KEY.to_string(), flags);
271        lexer.advance_chars(raw_chars);
272        Some(token)
273    }
274}
275
276// --- the actions ------------------------------------------------------------
277
278/// The `parse.prepare` hook: fresh block-parser state for every parse,
279/// with the keepTree request captured from the parse meta.
280///
281/// An empty source is skipped on purpose. The engine runs this hook
282/// before it short-circuits `""` through `lex.empty_result`, so the finish
283/// action that would release the slot never runs for one.
284pub fn make_md_prepare(opts: Options) -> impl Fn(&mut Context) + Send + Sync + 'static {
285    move |ctx| {
286        if ctx.source.is_empty() {
287            return;
288        }
289        let (_, lease) = block_slot_insert(BlockParser::new(opts), keep_tree_requested(&ctx.meta));
290        ctx.u.insert(MD_STATE_KEY.to_string(), lease);
291    }
292}
293
294/// The `line` GFM open alt's condition (tagged `g: "gfm"`): the lookahead
295/// `#LB` token's `tblArm` bit.
296pub fn md_line_gfm_condition(_rule: &mut Rule, ctx: &mut Context) -> bool {
297    ctx.t0()
298        .and_then(LineInfo::from_token)
299        .is_some_and(|info| info.tbl_arm)
300}
301
302fn feed_line(rule: &Rule, ctx: &Context, table_armed: bool) {
303    let Some(info) = rule.o0().and_then(LineInfo::from_token) else {
304        return;
305    };
306    with_block_state(ctx, |state| {
307        state.bp.table_armed = table_armed;
308        state.bp.incorporate_line(info.text);
309    });
310}
311
312/// The `line` base open alt's action: disarm the table probe and feed the
313/// matched `#LB` line to the shared algorithm. Reaching this alt means
314/// the `gfm`-tagged alt ahead of it did not match (the line cannot
315/// contain a delimiter row), or GFM is off entirely (`rule.exclude`
316/// removed the tagged alt, and `try_open_table` is closed by the option
317/// anyway).
318pub fn md_line_action(rule: &mut Rule, ctx: &mut Context) {
319    feed_line(rule, ctx, false);
320}
321
322/// The `line` GFM open alt's action (tagged `g: "gfm"`, condition on the
323/// token's `tblArm` bit): arm the table probe for this line, then feed it
324/// to the same shared algorithm. This is the extension seam a downstream
325/// dialect would use: an alt injected ahead of the base one, gated on a
326/// group tag so `gfm: false` can subtract it wholesale.
327pub fn md_line_gfm_action(rule: &mut Rule, ctx: &mut Context) {
328    feed_line(rule, ctx, true);
329}
330
331/// The `markdown` close alt's action on `#ZZ`: finalize blocks, run the
332/// phase-2 driver, and project the public AST into the rule's node.
333/// `run_inlines` is the engine inline path from `engine_inline.rs`,
334/// injected so this module stays a block-phase concern. When the caller
335/// passed `meta.md.keepTree`, the native tree is parked for
336/// [`take_kept_tree`]: the engine-path conformance harness renders it.
337pub fn make_md_finish_action(
338    opts: Options,
339    run_inlines: impl Fn(Tree, RefMap) -> Tree + Send + Sync + 'static,
340) -> impl Fn(&mut Rule, &mut Context) + Send + Sync + 'static {
341    move |rule, ctx| {
342        let Some(state) = slot_of(ctx, MD_STATE_KEY).and_then(block_slot_take) else {
343            return;
344        };
345        let (tree, refmap) = state.bp.finish();
346        let tree = run_inlines(tree, refmap);
347
348        let ast = to_ast(&tree, &opts);
349        if state.keep_tree {
350            KEPT_TREE.with(|cell| *cell.borrow_mut() = Some(tree));
351        }
352
353        // A fresh cell, never a write through the inherited one: the
354        // engine shares node cells between a rule and its parent.
355        rule.node = Rc::new(RefCell::new(ast));
356    }
357}
358
359#[cfg(test)]
360mod tests {
361    use super::*;
362
363    #[test]
364    fn line_info_flags() {
365        let info = LineInfo::of("a | b");
366        assert!(!info.blank);
367        assert!(info.tbl_arm);
368        let info = LineInfo::of(" \t");
369        assert!(info.blank);
370        assert!(!info.tbl_arm);
371        let info = LineInfo::of(":-:");
372        assert!(info.tbl_arm);
373    }
374
375    #[test]
376    fn slots_are_reused() {
377        // The leases stand in for the contexts that would hold them.
378        let (a, lease_a) = block_slot_insert(BlockParser::new(Options::default()), false);
379        let (b, lease_b) = block_slot_insert(BlockParser::new(Options::default()), false);
380        assert_ne!(a, b);
381        assert!(block_slot_take(a).is_some());
382        assert!(block_slot_take(a).is_none());
383        let (c, lease_c) = block_slot_insert(BlockParser::new(Options::default()), true);
384        assert_eq!(a, c);
385        assert!(block_slot_take(b).is_some());
386        assert!(block_slot_take(c).is_some_and(|s| s.keep_tree));
387        drop((lease_a, lease_b, lease_c));
388    }
389
390    /// A slot whose context is gone is freed by the next insert; one
391    /// whose context still lives is not.
392    #[test]
393    fn stale_slots_are_reclaimed_by_the_next_insert() {
394        let (a, lease_a) = block_slot_insert(BlockParser::new(Options::default()), false);
395        let (b, lease_b) = block_slot_insert(BlockParser::new(Options::default()), false);
396        drop(lease_a); // the engine dropped that parse's context
397        let (c, lease_c) = block_slot_insert(BlockParser::new(Options::default()), false);
398        assert_eq!(c, a, "the stale slot is the one reused");
399        assert_ne!(c, b, "the live slot is left alone");
400        assert!(block_slot_take(b).is_some());
401        assert!(block_slot_take(c).is_some());
402        drop((lease_b, lease_c));
403    }
404
405    /// Finding 2 of the review: an engine parse that aborts before the
406    /// finish action leaves its slot behind, and a worker fed such input
407    /// repeatedly must not accumulate them. A parse budget that cancels
408    /// after a few iterations is the aborted parse; the slab is read
409    /// after each one.
410    #[test]
411    fn aborted_parses_do_not_accumulate_slots() {
412        let mut tn = crate::make();
413        tn.parse_budget(1, |ctx| ctx.iteration < 4);
414        let src = "a\nb\nc\nd\ne\nf\ng\nh\n";
415        let mut held = 0;
416        for _ in 0..200 {
417            let error = tn.parse(src).expect_err("the budget cancels the parse");
418            assert_eq!(error.code, "cancel");
419            held = held.max(block_slots_held());
420        }
421        // At most the parse that just aborted, whose context is gone but
422        // which no prepare has run since.
423        assert!(held <= 1, "{held} slots held across 200 aborted parses");
424
425        // A parse that runs to completion on this thread frees it too.
426        let doc = crate::make()
427            .parse("ok")
428            .expect("a parse under no budget completes");
429        assert!(!doc.is_undefined());
430        assert_eq!(block_slots_held(), 0);
431    }
432}