use std::cell::RefCell;
use std::rc::Rc;
use std::sync::Arc;
use indexmap::IndexMap;
use tabnas::{Context, Lexer, Rule, Tin, Token, Value};
use crate::ast::to_ast;
use crate::block::{is_blank, segment_next_line, BlockParser};
use crate::node::Tree;
use crate::options::{Options, RefMap};
pub const LINE_TOKEN: &str = "#LB";
pub const MD_LINE_MATCHER: &str = "mdLine";
pub const MD_LINE_ORDER: f64 = 100_000.0;
pub const MD_PREPARE: &str = "md-reset";
pub const MD_STATE_KEY: &str = "md";
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct LineInfo<'a> {
pub text: &'a str,
pub blank: bool,
pub tbl_arm: bool,
}
impl<'a> LineInfo<'a> {
pub fn of(text: &'a str) -> LineInfo<'a> {
LineInfo {
text,
blank: is_blank(text),
tbl_arm: text.contains('|') || text.contains('-'),
}
}
pub fn from_token(token: &'a Token) -> Option<LineInfo<'a>> {
let text = match &token.val {
Value::String(s) => s.as_str(),
Value::Text(t) => t.string.as_str(),
_ => return None,
};
let flags = token.use_data().get(MD_STATE_KEY)?;
let blank = matches!(value_get(flags, "blank"), Some(Value::Bool(true)));
let tbl_arm = matches!(value_get(flags, "tblArm"), Some(Value::Bool(true)));
Some(LineInfo {
text,
blank,
tbl_arm,
})
}
fn flags_value(&self) -> Value {
let mut map = IndexMap::with_capacity(2);
map.insert("blank".to_string(), Value::Bool(self.blank));
map.insert("tblArm".to_string(), Value::Bool(self.tbl_arm));
Value::object(map)
}
}
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,
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) -> (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,
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))
)
}
pub fn make_md_line_matcher(
lb: Tin,
) -> impl for<'s> Fn(&mut Lexer<'s>, &mut Rule, &mut Context) -> Option<Token> + Send + Sync + 'static
{
move |lexer, _rule, _ctx| {
let point = lexer.point();
let src = lexer.source();
let seg = segment_next_line(src, point.site.si)?;
let raw = &src[point.site.si..seg.next];
let raw_chars = raw.chars().count();
let flags = LineInfo::of(&seg.text).flags_value();
let mut token = lexer.token(LINE_TOKEN, lb, Value::String(seg.text), raw, point);
token.use_data_mut().insert(MD_STATE_KEY.to_string(), flags);
lexer.advance_chars(raw_chars);
Some(token)
}
}
pub fn make_md_prepare(opts: Options) -> impl Fn(&mut Context) + Send + Sync + 'static {
move |ctx| {
if ctx.source.is_empty() {
return;
}
let (_, lease) = block_slot_insert(BlockParser::new(opts), keep_tree_requested(&ctx.meta));
ctx.u.insert(MD_STATE_KEY.to_string(), lease);
}
}
pub fn md_line_gfm_condition(_rule: &mut Rule, ctx: &mut Context) -> bool {
ctx.t0()
.and_then(LineInfo::from_token)
.is_some_and(|info| info.tbl_arm)
}
fn feed_line(rule: &Rule, ctx: &Context, table_armed: bool) {
let Some(info) = rule.o0().and_then(LineInfo::from_token) else {
return;
};
with_block_state(ctx, |state| {
state.bp.table_armed = table_armed;
state.bp.incorporate_line(info.text);
});
}
pub fn md_line_action(rule: &mut Rule, ctx: &mut Context) {
feed_line(rule, ctx, false);
}
pub fn md_line_gfm_action(rule: &mut Rule, ctx: &mut Context) {
feed_line(rule, ctx, true);
}
pub fn make_md_finish_action(
opts: Options,
run_inlines: impl Fn(Tree, RefMap) -> Tree + Send + Sync + 'static,
) -> impl Fn(&mut Rule, &mut Context) + Send + Sync + 'static {
move |rule, ctx| {
let Some(state) = slot_of(ctx, MD_STATE_KEY).and_then(block_slot_take) else {
return;
};
let (tree, refmap) = state.bp.finish();
let tree = run_inlines(tree, refmap);
let ast = to_ast(&tree, &opts);
if state.keep_tree {
KEPT_TREE.with(|cell| *cell.borrow_mut() = Some(tree));
}
rule.node = Rc::new(RefCell::new(ast));
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn line_info_flags() {
let info = LineInfo::of("a | b");
assert!(!info.blank);
assert!(info.tbl_arm);
let info = LineInfo::of(" \t");
assert!(info.blank);
assert!(!info.tbl_arm);
let info = LineInfo::of(":-:");
assert!(info.tbl_arm);
}
#[test]
fn slots_are_reused() {
let (a, lease_a) = block_slot_insert(BlockParser::new(Options::default()), false);
let (b, lease_b) = block_slot_insert(BlockParser::new(Options::default()), false);
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);
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);
let (b, lease_b) = block_slot_insert(BlockParser::new(Options::default()), false);
drop(lease_a); let (c, lease_c) = block_slot_insert(BlockParser::new(Options::default()), false);
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);
}
}