1use 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
73pub const LINE_TOKEN: &str = "#LB";
75
76pub const END_TOKEN: &str = "#EN";
78
79pub const MD_BLOCK_MATCHER: &str = "mdBlock";
81
82pub const MD_BLOCK_ORDER: f64 = 100_000.0;
85
86pub const MD_PREPARE: &str = "md-reset";
88
89pub const MD_STATE_KEY: &str = "md";
91
92#[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
122pub 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
154fn 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
162fn 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
177type Made = (&'static str, Value);
179
180pub(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
189pub(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
204struct BlockState {
209 bp: BlockParser,
210 keep_tree: bool,
211 inline: Option<InlineParser>,
214 made: Vec<Made>,
219 next: usize,
220 read: bool,
221 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 static KEPT_TREE: RefCell<Option<Tree>> = const { RefCell::new(None) };
239}
240
241fn 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#[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
289pub fn take_kept_tree() -> Option<Tree> {
294 KEPT_TREE.with(|cell| cell.borrow_mut().take())
295}
296
297fn 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
305struct Line {
309 text: String,
310 src: String,
311 chars: usize,
313 last: bool,
314}
315
316fn 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
380enum Out {
382 Block(Made),
384 Line,
386}
387
388pub 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 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
474fn 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 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
516fn 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 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
550fn 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
583fn 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
616fn 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
627pub 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
647fn list_push(list: &mut Value, item: Value) {
649 if let Value::Array(items) = list {
650 Arc::make_mut(items).push(item);
651 }
652}
653
654pub fn md_begin(rule: &mut Rule, _ctx: &mut Context) {
657 rule.node = Rc::new(RefCell::new(Value::array(Vec::new())));
658}
659
660pub 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 rule.node = Rc::new(RefCell::new(object(vec![
679 ("type", Value::String("document".to_string())),
680 ("children", children),
681 ])));
682 }
683}
684
685pub 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
693pub 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
713pub 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 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 #[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); 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 #[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 assert!(held <= 1, "{held} slots held across 200 aborted parses");
796
797 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}