use std::cell::RefCell;
use std::sync::Arc;
use indexmap::IndexMap;
use tabnas::{AltSpec, Context, Lexer, Rule, Tabnas, Tin, Token, Value, TIN_ZZ};
use crate::engine_block::{slot_of, value_get};
use crate::inline::{inline_content_blocks, linkify_autolinks, InlineParser};
use crate::node::{NodeId, Tree};
use crate::options::{Options, RefMap};
pub const INLINE_TOKENS: [&str; 12] = [
"#IBK", "#IES", "#ICS", "#IDL", "#IOB", "#IBG", "#ICB", "#IAL", "#IHT", "#IEN", "#ITX", "#ILI", ];
pub const INLINE_STATE_KEY: &str = "inl";
pub const INLINE_PREPARE: &str = "inl-reset";
struct InlineState {
parser: InlineParser,
tree: Tree,
block: NodeId,
}
thread_local! {
static INLINE_STATES: RefCell<Vec<Option<InlineState>>> = const { RefCell::new(Vec::new()) };
}
fn inline_slot_insert(state: InlineState) -> usize {
INLINE_STATES.with(|cell| {
let mut slab = cell.borrow_mut();
match slab.iter().position(Option::is_none) {
Some(i) => {
slab[i] = Some(state);
i
}
None => {
slab.push(Some(state));
slab.len() - 1
}
}
})
}
fn inline_slot_take(slot: usize) -> Option<InlineState> {
INLINE_STATES.with(|cell| cell.borrow_mut().get_mut(slot).and_then(Option::take))
}
fn with_inline_state<R>(ctx: &Context, f: impl FnOnce(&mut InlineState) -> R) -> Option<R> {
let slot = slot_of(ctx, INLINE_STATE_KEY)?;
INLINE_STATES.with(|cell| {
let mut slab = cell.borrow_mut();
slab.get_mut(slot).and_then(Option::as_mut).map(f)
})
}
type Run = fn(&mut InlineParser, &mut Tree, NodeId) -> bool;
type Name = Box<dyn Fn(&InlineParser, usize) -> (&'static str, Tin) + Send + Sync>;
fn adapt(
guard: fn(u8) -> bool,
run: Run,
name: Name,
) -> 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 start = point.site.si;
if start >= src.len() || !guard(src.as_bytes()[start]) {
return None;
}
let (token_name, tin, end) = with_inline_state(ctx, |st| {
st.parser.pos = start;
if !run(&mut st.parser, &mut st.tree, st.block) {
return None;
}
let (token_name, tin) = name(&st.parser, start);
Some((token_name, tin, st.parser.pos))
})??;
let consumed = &src[start..end];
let consumed_chars = consumed.chars().count();
let token = lexer.token(token_name, tin, Value::Undefined, consumed, point);
lexer.advance_chars(consumed_chars);
Some(token)
}
}
fn fixed(name: &'static str, tin: Tin) -> Name {
Box::new(move |_, _| (name, tin))
}
fn imperative(
name: &str,
order: f64,
matcher: impl for<'s> Fn(&mut Lexer<'s>, &mut Rule, &mut Context) -> Option<Token>
+ Send
+ Sync
+ 'static,
) -> tabnas::LexMatcher {
tabnas::LexMatcher {
name: name.to_string(),
order,
matcher: None,
imperative: Some(Arc::new(matcher)),
factory: None,
}
}
fn inline_prepare(ctx: &mut Context) {
let slot = value_get(&ctx.meta, "md")
.and_then(|md| value_get(md, INLINE_STATE_KEY))
.cloned();
if let Some(slot @ Value::Number(_)) = slot {
ctx.u.insert(INLINE_STATE_KEY.to_string(), slot);
}
}
fn inline_finish_action(_rule: &mut Rule, ctx: &mut Context) {
with_inline_state(ctx, |st| {
let block = st.block;
st.parser.finish_block(&mut st.tree, block);
});
}
pub fn make_inline_tn(opts: &Options) -> Tabnas {
let mut tn = Tabnas::new();
let mut tins: IndexMap<&'static str, Tin> = IndexMap::with_capacity(INLINE_TOKENS.len());
for name in INLINE_TOKENS {
tins.insert(name, tn.token(name));
}
let tin = |name: &str| tins[name];
tn.set_options(|o| {
o.fixed.lex = false;
o.space.lex = false;
o.line.lex = false;
o.text.lex = false;
o.string.lex = false;
o.comment.lex = false;
o.number.lex = false;
o.value.lex = false;
o.rule.start = "inline".to_string();
})
.expect("the inline engine's option set is fixed and valid");
let ibg = tin("#IBG");
let ili = tin("#ILI");
let bang_name: Name = Box::new(move |p: &InlineParser, start: usize| {
if p.pos - start == 2 {
("#IBG", ibg)
} else {
("#ILI", ili)
}
});
let mut matchers = vec![
imperative(
"inlBreak",
100_000.0,
adapt(
|c| c == b'\n',
InlineParser::parse_newline,
fixed("#IBK", tin("#IBK")),
),
),
imperative(
"inlEscape",
100_100.0,
adapt(
|c| c == b'\\',
InlineParser::parse_backslash,
fixed("#IES", tin("#IES")),
),
),
imperative(
"inlCode",
100_200.0,
adapt(
|c| c == b'`',
InlineParser::parse_backticks,
fixed("#ICS", tin("#ICS")),
),
),
imperative(
"inlDelim",
100_300.0,
adapt(
|c| c == b'*' || c == b'_',
|p, tree, block| {
let cc = p.subject.as_bytes()[p.pos];
p.handle_delim(cc, tree, block)
},
fixed("#IDL", tin("#IDL")),
),
),
imperative(
"inlOpenBracket",
100_400.0,
adapt(
|c| c == b'[',
InlineParser::parse_open_bracket,
fixed("#IOB", tin("#IOB")),
),
),
imperative(
"inlBang",
100_500.0,
adapt(|c| c == b'!', InlineParser::parse_bang, bang_name),
),
imperative(
"inlCloseBracket",
100_600.0,
adapt(
|c| c == b']',
InlineParser::parse_close_bracket,
fixed("#ICB", tin("#ICB")),
),
),
imperative(
"inlAutolink",
100_700.0,
adapt(
|c| c == b'<',
InlineParser::parse_autolink,
fixed("#IAL", tin("#IAL")),
),
),
imperative(
"inlHtmlTag",
100_800.0,
adapt(
|c| c == b'<',
InlineParser::parse_html_tag,
fixed("#IHT", tin("#IHT")),
),
),
imperative(
"inlEntity",
100_900.0,
adapt(
|c| c == b'&',
InlineParser::parse_entity,
fixed("#IEN", tin("#IEN")),
),
),
imperative(
"inlText",
101_000.0,
adapt(
|_| true,
InlineParser::parse_string,
fixed("#ITX", tin("#ITX")),
),
),
imperative(
"inlLiteral",
101_100.0,
adapt(
|_| true,
InlineParser::parse_literal_char,
fixed("#ILI", tin("#ILI")),
),
),
];
if opts.gfm {
matchers.push(imperative(
"inlTilde",
100_350.0,
adapt(
|c| c == b'~',
|p, tree, block| p.handle_delim(b'~', tree, block),
fixed("#IDL", tin("#IDL")),
),
));
}
matchers.sort_by(|a, b| a.order.total_cmp(&b.order));
for matcher in matchers {
tn.options
.lex
.matchers
.insert(matcher.name.clone(), matcher);
}
tn.options.parse.named_prepare.insert(
INLINE_PREPARE.to_string(),
tabnas::ParsePrepare::Context(Arc::new(inline_prepare)),
);
let or_set: Vec<Tin> = INLINE_TOKENS.iter().map(|name| tin(name)).collect();
tn.define_rule("inline", |rs| {
rs.clear();
rs.add_open(AltSpec {
s: vec![or_set],
r: Some("inline".to_string()),
..Default::default()
});
rs.add_open(AltSpec::default());
let mut finish = AltSpec {
s: vec![vec![TIN_ZZ]],
..Default::default()
};
finish.add_action(inline_finish_action);
rs.add_close(finish);
rs.add_close(AltSpec::default());
});
tn
}
pub fn parse_inlines_engine(
inline_tn: &Tabnas,
mut tree: Tree,
refmap: RefMap,
options: &Options,
) -> Tree {
let mut parser = InlineParser::new(refmap, *options);
for block in inline_content_blocks(&tree) {
(parser, tree) = scan_block(inline_tn, parser, tree, block);
if options.gfm {
linkify_autolinks(&mut tree, block);
}
}
tree
}
pub fn parse_block_engine(
inline_tn: &Tabnas,
parser: InlineParser,
tree: Tree,
block: NodeId,
) -> (InlineParser, Tree) {
let gfm = parser.options.gfm;
let (parser, mut tree) = scan_block(inline_tn, parser, tree, block);
if gfm {
linkify_autolinks(&mut tree, block);
}
(parser, tree)
}
fn scan_block(
inline_tn: &Tabnas,
mut parser: InlineParser,
mut tree: Tree,
block: NodeId,
) -> (InlineParser, Tree) {
if !parser.begin_block(&tree, block) {
parser.finish_block(&mut tree, block);
return (parser, tree);
}
let subject = parser.subject.clone();
let slot = inline_slot_insert(InlineState {
parser,
tree,
block,
});
let mut md = IndexMap::with_capacity(1);
md.insert(INLINE_STATE_KEY.to_string(), Value::Number(slot as f64));
let mut meta = IndexMap::with_capacity(1);
meta.insert("md".to_string(), Value::object(md));
let result = inline_tn.parse_with_meta(&subject, Value::object(meta));
let state = inline_slot_take(slot)
.expect("the inline state slot is released only here, after its parse");
if let Err(error) = result {
panic!("markdown: the inline engine rejected a block's content: {error}");
}
(state.parser, state.tree)
}