tabnas_markdown/engine_inline.rs
1/* Copyright (c) 2026 Richard Rodger, MIT License */
2
3//! The engine-facing inline driver: a second engine instance whose lexer
4//! IS the inline scanner. Port of `ts/src/engine-inline.ts` and
5//! `go/engineinline.go`.
6//!
7//! Each custom matcher is a thin adapter over one [`InlineParser`] scanner
8//! method, the same methods the engine-free path runs, so the anti-drift
9//! rule holds: recognition, node building, the delimiter stack and the
10//! bracket stack all live once, in `inline.rs`.
11//!
12//! Two engine features carry the design:
13//!
14//! * **Context-sensitive matchers.** Every adapter reaches the per-parse
15//! state through `ctx.u["inl"]`. That is what makes the `]` matcher the
16//! cursor owner: `parse_close_bracket` consumes a successful link tail
17//! directly from the subject, and because that happens at *lex* time,
18//! the engine's point advances past the tail and everything after it is
19//! lexed fresh. The corpus-blind straddle cases (a backtick inside a
20//! successful destination or title, followed by a code span; see
21//! test/spec/mixed.tsv) are correct by construction: no token is ever
22//! cut across a tail boundary, so no re-lex or resynchronization
23//! machinery exists at all.
24//!
25//! * **Matcher order as precedence.** At `<`, the autolink adapter runs
26//! before the raw-HTML adapter, exactly as the hand scanner's dispatch
27//! tries them; the text-run adapter and the single-character literal
28//! fallback come last. The registered order *is* ยง6.3's precedence
29//! table, visible in the instance's configuration instead of buried in
30//! a `match`.
31//!
32//! The one-token effects are applied at lex time on purpose. The engine's
33//! rule loop reads lookahead tokens before earlier alts' actions run, so
34//! any state a matcher consults (the tree for break trimming, the bracket
35//! stack for `]`) must be current when the *lexer* reaches it, not when
36//! the parser does. The `inline` rule therefore carries no per-token
37//! actions: the tokens are the observable record of the scan (subscribe
38//! with `Tabnas::subscribe_tokens` and watch), and the rule's close action
39//! finalizes the block exactly as the engine-free `parse` tail does.
40//!
41//! # One instance per install
42//!
43//! TypeScript builds one inline instance per plugin install; Go builds one
44//! per parse because its engine's concurrency guarantee covers
45//! construction only. The Rust engine parses through `&self` and the
46//! instance is `Send + Sync`, so this port follows TypeScript: one
47//! instance, built when the plugin installs, shared by every parse. The
48//! per-parse state it needs (the scanner, the tree, the block) travels
49//! through a thread-local slab exactly as the block phase's does, keyed by
50//! a slot index in the parse meta.
51
52use std::cell::RefCell;
53use std::sync::Arc;
54
55use indexmap::IndexMap;
56use tabnas::{AltSpec, Context, Lexer, Rule, Tabnas, Tin, Token, Value, TIN_ZZ};
57
58use crate::engine_block::{slot_of, value_get};
59use crate::inline::{inline_content_blocks, linkify_autolinks, InlineParser};
60use crate::node::{NodeId, Tree};
61use crate::options::{Options, RefMap};
62
63/// The inline token alphabet, in the order the rule's alt lists them.
64pub const INLINE_TOKENS: [&str; 12] = [
65 "#IBK", // line break (soft or hard, decided against the tree)
66 "#IES", // backslash escape
67 "#ICS", // code span (or an unmatched literal backtick run)
68 "#IDL", // emphasis/strikethrough delimiter run
69 "#IOB", // [
70 "#IBG", // ![
71 "#ICB", // ] (including a consumed inline link tail)
72 "#IAL", // angle autolink
73 "#IHT", // raw HTML tag
74 "#IEN", // entity reference
75 "#ITX", // ordinary text run
76 "#ILI", // single literal character nothing else claimed
77];
78
79/// The key under `ctx.u` (and under `meta.md`) that carries the inline
80/// state's slot index.
81pub const INLINE_STATE_KEY: &str = "inl";
82
83/// The `parse.prepare` hook's name.
84pub const INLINE_PREPARE: &str = "inl-reset";
85
86// --- the per-parse state ----------------------------------------------------
87
88/// What `ctx.u["inl"]` points at while one block's inlines are being
89/// scanned: the scanner, the tree it appends to, and the block.
90struct InlineState {
91 parser: InlineParser,
92 tree: Tree,
93 block: NodeId,
94}
95
96thread_local! {
97 static INLINE_STATES: RefCell<Vec<Option<InlineState>>> = const { RefCell::new(Vec::new()) };
98}
99
100fn inline_slot_insert(state: InlineState) -> usize {
101 INLINE_STATES.with(|cell| {
102 let mut slab = cell.borrow_mut();
103 match slab.iter().position(Option::is_none) {
104 Some(i) => {
105 slab[i] = Some(state);
106 i
107 }
108 None => {
109 slab.push(Some(state));
110 slab.len() - 1
111 }
112 }
113 })
114}
115
116fn inline_slot_take(slot: usize) -> Option<InlineState> {
117 INLINE_STATES.with(|cell| cell.borrow_mut().get_mut(slot).and_then(Option::take))
118}
119
120fn with_inline_state<R>(ctx: &Context, f: impl FnOnce(&mut InlineState) -> R) -> Option<R> {
121 let slot = slot_of(ctx, INLINE_STATE_KEY)?;
122 INLINE_STATES.with(|cell| {
123 let mut slab = cell.borrow_mut();
124 slab.get_mut(slot).and_then(Option::as_mut).map(f)
125 })
126}
127
128// --- the adapters -----------------------------------------------------------
129
130/// One scanner method, taking the tree and the block it appends to.
131type Run = fn(&mut InlineParser, &mut Tree, NodeId) -> bool;
132
133/// The token a successful run is reported as. `!` is the one whose name
134/// depends on what was consumed (`![` versus a literal `!`).
135type Name = Box<dyn Fn(&InlineParser, usize) -> (&'static str, Tin) + Send + Sync>;
136
137/// Adapt one [`InlineParser`] scanner method into a lexer matcher: sync
138/// the parser to the engine's point, run the method (which appends nodes
139/// and moves `pos`), and emit a token covering exactly what it consumed.
140///
141/// Row and column bookkeeping is observability data: a matcher that
142/// consumed line endings (soft breaks, multiline code spans or titles)
143/// moved the scan onto a later row, and later tokens must say so. The
144/// lexer's own `advance_chars` does that arithmetic, in CHARACTERS;
145/// `tests/engine_columns_test.rs` pins the positions.
146fn adapt(
147 guard: fn(u8) -> bool,
148 run: Run,
149 name: Name,
150) -> impl for<'s> Fn(&mut Lexer<'s>, &mut Rule, &mut Context) -> Option<Token> + Send + Sync + 'static
151{
152 move |lexer, _rule, ctx| {
153 let point = lexer.point();
154 let src = lexer.source();
155 let start = point.site.si;
156 if start >= src.len() || !guard(src.as_bytes()[start]) {
157 return None;
158 }
159
160 let (token_name, tin, end) = with_inline_state(ctx, |st| {
161 st.parser.pos = start;
162 if !run(&mut st.parser, &mut st.tree, st.block) {
163 return None;
164 }
165 let (token_name, tin) = name(&st.parser, start);
166 Some((token_name, tin, st.parser.pos))
167 })??;
168
169 let consumed = &src[start..end];
170 let consumed_chars = consumed.chars().count();
171 let token = lexer.token(token_name, tin, Value::Undefined, consumed, point);
172 lexer.advance_chars(consumed_chars);
173 Some(token)
174 }
175}
176
177fn fixed(name: &'static str, tin: Tin) -> Name {
178 Box::new(move |_, _| (name, tin))
179}
180
181fn imperative(
182 name: &str,
183 order: f64,
184 matcher: impl for<'s> Fn(&mut Lexer<'s>, &mut Rule, &mut Context) -> Option<Token>
185 + Send
186 + Sync
187 + 'static,
188) -> tabnas::LexMatcher {
189 tabnas::LexMatcher {
190 name: name.to_string(),
191 order,
192 matcher: None,
193 imperative: Some(Arc::new(matcher)),
194 factory: None,
195 }
196}
197
198/// The `parse.prepare` hook: the slot index arrives on the parse meta as
199/// `meta.md.inl`, and is copied to `ctx.u["inl"]` where the adapters and
200/// the close action read it.
201fn inline_prepare(ctx: &mut Context) {
202 let slot = value_get(&ctx.meta, "md")
203 .and_then(|md| value_get(md, INLINE_STATE_KEY))
204 .cloned();
205 if let Some(slot @ Value::Number(_)) = slot {
206 ctx.u.insert(INLINE_STATE_KEY.to_string(), slot);
207 }
208}
209
210/// The `inline` rule's close action on `#ZZ`: resolve emphasis over the
211/// whole delimiter stack and clear the block's raw content, exactly as
212/// the engine-free `parse` tail does.
213fn inline_finish_action(_rule: &mut Rule, ctx: &mut Context) {
214 with_inline_state(ctx, |st| {
215 let block = st.block;
216 st.parser.finish_block(&mut st.tree, block);
217 });
218}
219
220// --- the instance -----------------------------------------------------------
221
222/// Build the inline engine instance for one option set. All built-in
223/// matchers are disabled; the registered matcher set is the complete
224/// lexical description of the inline phase, in precedence order.
225///
226/// GFM strikethrough is a separate matcher registered only when the
227/// option is on: the option reshapes the registered matcher set itself,
228/// so the base dialect's lexer simply has no tilde matcher rather than a
229/// disabled branch inside one.
230pub fn make_inline_tn(opts: &Options) -> Tabnas {
231 let mut tn = Tabnas::new();
232
233 let mut tins: IndexMap<&'static str, Tin> = IndexMap::with_capacity(INLINE_TOKENS.len());
234 for name in INLINE_TOKENS {
235 tins.insert(name, tn.token(name));
236 }
237 let tin = |name: &str| tins[name];
238
239 tn.set_options(|o| {
240 o.fixed.lex = false;
241 o.space.lex = false;
242 o.line.lex = false;
243 o.text.lex = false;
244 o.string.lex = false;
245 o.comment.lex = false;
246 o.number.lex = false;
247 o.value.lex = false;
248 o.rule.start = "inline".to_string();
249 })
250 .expect("the inline engine's option set is fixed and valid");
251
252 let ibg = tin("#IBG");
253 let ili = tin("#ILI");
254 let bang_name: Name = Box::new(move |p: &InlineParser, start: usize| {
255 if p.pos - start == 2 {
256 ("#IBG", ibg)
257 } else {
258 ("#ILI", ili)
259 }
260 });
261
262 let mut matchers = vec![
263 imperative(
264 "inlBreak",
265 100_000.0,
266 adapt(
267 |c| c == b'\n',
268 InlineParser::parse_newline,
269 fixed("#IBK", tin("#IBK")),
270 ),
271 ),
272 imperative(
273 "inlEscape",
274 100_100.0,
275 adapt(
276 |c| c == b'\\',
277 InlineParser::parse_backslash,
278 fixed("#IES", tin("#IES")),
279 ),
280 ),
281 imperative(
282 "inlCode",
283 100_200.0,
284 adapt(
285 |c| c == b'`',
286 InlineParser::parse_backticks,
287 fixed("#ICS", tin("#ICS")),
288 ),
289 ),
290 imperative(
291 "inlDelim",
292 100_300.0,
293 adapt(
294 |c| c == b'*' || c == b'_',
295 |p, tree, block| {
296 let cc = p.subject.as_bytes()[p.pos];
297 p.handle_delim(cc, tree, block)
298 },
299 fixed("#IDL", tin("#IDL")),
300 ),
301 ),
302 imperative(
303 "inlOpenBracket",
304 100_400.0,
305 adapt(
306 |c| c == b'[',
307 InlineParser::parse_open_bracket,
308 fixed("#IOB", tin("#IOB")),
309 ),
310 ),
311 // `!` introduces an image only before `[`; otherwise a literal.
312 imperative(
313 "inlBang",
314 100_500.0,
315 adapt(|c| c == b'!', InlineParser::parse_bang, bang_name),
316 ),
317 // The cursor owner: on a successful inline link tail,
318 // parse_close_bracket has already consumed it when this token is
319 // emitted.
320 imperative(
321 "inlCloseBracket",
322 100_600.0,
323 adapt(
324 |c| c == b']',
325 InlineParser::parse_close_bracket,
326 fixed("#ICB", tin("#ICB")),
327 ),
328 ),
329 // At `<`: autolink first, raw HTML second. Matcher order is
330 // precedence.
331 imperative(
332 "inlAutolink",
333 100_700.0,
334 adapt(
335 |c| c == b'<',
336 InlineParser::parse_autolink,
337 fixed("#IAL", tin("#IAL")),
338 ),
339 ),
340 imperative(
341 "inlHtmlTag",
342 100_800.0,
343 adapt(
344 |c| c == b'<',
345 InlineParser::parse_html_tag,
346 fixed("#IHT", tin("#IHT")),
347 ),
348 ),
349 imperative(
350 "inlEntity",
351 100_900.0,
352 adapt(
353 |c| c == b'&',
354 InlineParser::parse_entity,
355 fixed("#IEN", tin("#IEN")),
356 ),
357 ),
358 imperative(
359 "inlText",
360 101_000.0,
361 adapt(
362 |_| true,
363 InlineParser::parse_string,
364 fixed("#ITX", tin("#ITX")),
365 ),
366 ),
367 // Nothing claimed the character: one literal char, same as the
368 // hand scanner's dispatch fallback.
369 imperative(
370 "inlLiteral",
371 101_100.0,
372 adapt(
373 |_| true,
374 InlineParser::parse_literal_char,
375 fixed("#ILI", tin("#ILI")),
376 ),
377 ),
378 ];
379
380 if opts.gfm {
381 matchers.push(imperative(
382 "inlTilde",
383 100_350.0,
384 adapt(
385 |c| c == b'~',
386 |p, tree, block| p.handle_delim(b'~', tree, block),
387 fixed("#IDL", tin("#IDL")),
388 ),
389 ));
390 }
391
392 // The lexer runs custom matchers in registration order and stops at
393 // the first whose order is past the band, so they are registered
394 // sorted by order: `inlTilde` slots in between the delimiter and the
395 // open bracket matchers.
396 matchers.sort_by(|a, b| a.order.total_cmp(&b.order));
397 for matcher in matchers {
398 tn.options
399 .lex
400 .matchers
401 .insert(matcher.name.clone(), matcher);
402 }
403
404 tn.options.parse.named_prepare.insert(
405 INLINE_PREPARE.to_string(),
406 tabnas::ParsePrepare::Context(Arc::new(inline_prepare)),
407 );
408
409 // One OR-position over the whole alphabet: any inline token loops the
410 // rule; the empty alts fall through to the close on #ZZ.
411 let or_set: Vec<Tin> = INLINE_TOKENS.iter().map(|name| tin(name)).collect();
412
413 tn.define_rule("inline", |rs| {
414 rs.clear();
415 rs.add_open(AltSpec {
416 s: vec![or_set],
417 r: Some("inline".to_string()),
418 ..Default::default()
419 });
420 rs.add_open(AltSpec::default());
421
422 let mut finish = AltSpec {
423 s: vec![vec![TIN_ZZ]],
424 ..Default::default()
425 };
426 finish.add_action(inline_finish_action);
427 rs.add_close(finish);
428 rs.add_close(AltSpec::default());
429 });
430
431 tn
432}
433
434/// The engine-path inline phase: the same block walk as `parse_inlines`,
435/// with each block's scan driven by the engine instance's lexer. An empty
436/// subject never reaches the engine (its empty-source path returns before
437/// the rules run), and finishes the block directly: a no-op resolve,
438/// exactly as the hand scanner's `parse` does.
439///
440/// Takes and returns the tree by value: while a block is being scanned
441/// the tree belongs to the per-parse slot the adapters reach through the
442/// context, and it comes back when the engine returns.
443pub fn parse_inlines_engine(
444 inline_tn: &Tabnas,
445 mut tree: Tree,
446 refmap: RefMap,
447 options: &Options,
448) -> Tree {
449 let mut parser = InlineParser::new(refmap, *options);
450
451 for block in inline_content_blocks(&tree) {
452 if !parser.begin_block(&tree, block) {
453 parser.finish_block(&mut tree, block);
454 } else {
455 let subject = parser.subject.clone();
456 let slot = inline_slot_insert(InlineState {
457 parser,
458 tree,
459 block,
460 });
461
462 let mut md = IndexMap::with_capacity(1);
463 md.insert(INLINE_STATE_KEY.to_string(), Value::Number(slot as f64));
464 let mut meta = IndexMap::with_capacity(1);
465 meta.insert("md".to_string(), Value::object(md));
466
467 let result = inline_tn.parse_with_meta(&subject, Value::object(meta));
468
469 let state = inline_slot_take(slot)
470 .expect("the inline state slot is released only here, after its parse");
471 parser = state.parser;
472 tree = state.tree;
473
474 if let Err(error) = result {
475 // CommonMark defines an output for every input; an engine
476 // error here is an internal wiring defect, not a parse
477 // result.
478 panic!("markdown: the inline engine rejected a block's content: {error}");
479 }
480 }
481 if options.gfm {
482 linkify_autolinks(&mut tree, block);
483 }
484 }
485
486 tree
487}