use super::{Interrupt, LineStart, atx_heading, blockquote, footnote, html_block, join_lines, list, paragraph};
use crate::node::{HorizontalRule, HorizontalRuleMarker, MdxJsEsm, Node, Position};
use crate::parser::code::{fenced_code, indented_code};
use crate::parser::line::{Indent, Line};
use crate::parser::mdx_flow::{FlowOutcome, may_start_flow, mdx_flow};
use crate::parser::table;
use crate::parser::tree::Block;
pub(super) struct Cx<'a, 'l> {
pub(super) lines: &'l [Line<'a>],
pub(super) index: usize,
pub(super) line: &'l Line<'a>,
pub(super) indent: Indent,
pub(super) start: Option<LineStart<'a>>,
pub(super) rest: &'a str,
pub(super) depth: usize,
pub(super) containers: bool,
pub(super) interrupting: Interrupt,
pub(super) closed_container: bool,
pub(super) separated: bool,
}
pub(super) struct Step {
pub(super) next: usize,
pub(super) container: bool,
pub(super) interrupt: Interrupt,
}
impl Step {
fn to(next: usize) -> Self {
Self {
next,
container: false,
interrupt: Interrupt::default(),
}
}
fn container(next: usize) -> Self {
Self {
container: true,
..Self::to(next)
}
}
fn interrupt((next, interrupt): (usize, Interrupt)) -> Self {
Self {
interrupt,
..Self::to(next)
}
}
}
pub(super) trait BlockRule {
fn parse(cx: &Cx<'_, '_>, blocks: &mut Vec<Block>) -> Option<Step>;
}
impl<A: BlockRule, B: BlockRule> BlockRule for (A, B) {
fn parse(cx: &Cx<'_, '_>, blocks: &mut Vec<Block>) -> Option<Step> {
A::parse(cx, blocks).or_else(|| B::parse(cx, blocks))
}
}
pub(super) fn fallback(cx: &Cx<'_, '_>, blocks: &mut Vec<Block>) -> Step {
Step::interrupt(paragraph(cx.lines, cx.index, blocks))
}
macro_rules! chain {
($rule:ty) => { $rule };
($rule:ty, $($rest:ty),+) => { ($rule, chain!($($rest),+)) };
}
pub(super) type Rules = chain!(
IndentedCode,
FencedCode,
AtxHeading,
ThematicBreak,
Blockquote,
List,
Html,
Footnote,
Table,
Esm,
MdxFlow
);
pub(super) struct IndentedCode;
impl BlockRule for IndentedCode {
fn parse(cx: &Cx<'_, '_>, blocks: &mut Vec<Block>) -> Option<Step> {
if cx.indent.columns < cx.line.code_indent() {
return None;
}
Some(if cx.interrupting.code {
fallback(cx, blocks)
} else {
Step::to(indented_code(cx.lines, cx.index, blocks))
})
}
}
pub(super) struct FencedCode;
impl BlockRule for FencedCode {
fn parse(cx: &Cx<'_, '_>, blocks: &mut Vec<Block>) -> Option<Step> {
let Some(LineStart::Fence(fence)) = &cx.start else {
return None;
};
let own_end = cx.closed_container
&& !(cx.separated
&& matches!(blocks.last(), Some(Block::List(l)) if l.items.last().is_some_and(|i| i.children.is_empty())));
Some(Step::to(fenced_code(
cx.lines,
cx.index,
cx.indent.bytes,
fence,
own_end,
blocks,
)))
}
}
pub(super) struct AtxHeading;
impl BlockRule for AtxHeading {
fn parse(cx: &Cx<'_, '_>, blocks: &mut Vec<Block>) -> Option<Step> {
let Some(LineStart::Atx(depth)) = cx.start else {
return None;
};
blocks.push(atx_heading(cx.line, cx.indent.bytes, depth));
Some(Step::to(cx.index + 1))
}
}
pub(super) struct ThematicBreak;
impl BlockRule for ThematicBreak {
fn parse(cx: &Cx<'_, '_>, blocks: &mut Vec<Block>) -> Option<Step> {
if !matches!(cx.start, Some(LineStart::ThematicBreak)) {
return None;
}
blocks.push(Block::Node(Node::HorizontalRule(HorizontalRule {
marker: cx.rest.chars().next().and_then(HorizontalRuleMarker::from_char),
position: Some(Position {
start: cx.line.point(0),
end: cx.line.end(),
}),
})));
Some(Step::to(cx.index + 1))
}
}
pub(super) struct Blockquote;
impl BlockRule for Blockquote {
fn parse(cx: &Cx<'_, '_>, blocks: &mut Vec<Block>) -> Option<Step> {
if !cx.containers || !matches!(cx.start, Some(LineStart::Blockquote)) {
return None;
}
Some(Step::container(blockquote(
cx.lines,
cx.index,
cx.depth,
cx.interrupting,
blocks,
)))
}
}
pub(super) struct List;
impl BlockRule for List {
fn parse(cx: &Cx<'_, '_>, blocks: &mut Vec<Block>) -> Option<Step> {
let Some(LineStart::Item(marker)) = &cx.start else {
return None;
};
if !(cx.containers && (!cx.interrupting.list || marker.interrupts_paragraph())) {
return None;
}
Some(Step::container(list(
cx.lines,
cx.index,
marker,
cx.depth,
cx.interrupting,
blocks,
)))
}
}
pub(super) struct Html;
impl BlockRule for Html {
fn parse(cx: &Cx<'_, '_>, blocks: &mut Vec<Block>) -> Option<Step> {
let Some(LineStart::Html(kind)) = cx.start else {
return None;
};
Some(Step::to(html_block(cx.lines, cx.index, kind, blocks)))
}
}
pub(super) struct Footnote;
impl BlockRule for Footnote {
fn parse(cx: &Cx<'_, '_>, blocks: &mut Vec<Block>) -> Option<Step> {
let Some(LineStart::Footnote(marker)) = &cx.start else {
return None;
};
if !cx.containers {
return None;
}
Some(Step::container(footnote(
cx.lines,
cx.index,
marker,
cx.depth,
cx.interrupting,
blocks,
)))
}
}
pub(super) struct Table;
impl BlockRule for Table {
fn parse(cx: &Cx<'_, '_>, blocks: &mut Vec<Block>) -> Option<Step> {
let (items, next) = table::parse(cx.lines, cx.index, super::interrupts_paragraph, super::ends_table)?;
blocks.push(Block::Table(items));
Some(Step::to(next))
}
}
fn open_brackets(text: &str, mut depth: i32) -> i32 {
let mut chars = text.chars().peekable();
while let Some(char) = chars.next() {
match char {
'{' | '(' | '[' => depth += 1,
'}' | ')' | ']' => depth -= 1,
'\'' | '"' | '`' => {
while let Some(next) = chars.next() {
if next == '\\' {
chars.next();
} else if next == char {
break;
}
}
}
'/' if chars.peek() == Some(&'/') => break,
_ => {}
}
}
depth
}
pub(super) struct Esm;
impl BlockRule for Esm {
fn parse(cx: &Cx<'_, '_>, blocks: &mut Vec<Block>) -> Option<Step> {
let line = cx.line;
if !(line.flavor.has_jsx()
&& cx.depth == 0
&& cx.indent.bytes == 0
&& (line.text.starts_with("import ") || line.text.starts_with("export ")))
{
return None;
}
let mut depth = 0i32;
let mut end = cx.lines.len();
for (offset, line) in cx.lines[cx.index..].iter().enumerate() {
if line.is_blank() && depth <= 0 {
end = cx.index + offset;
break;
}
depth = open_brackets(line.text, depth);
}
let parts = cx.lines[cx.index..end]
.iter()
.map(|line| (line.text, line.eol))
.collect::<Vec<_>>();
blocks.push(Block::Node(Node::MdxJsEsm(MdxJsEsm {
value: join_lines(&parts).into(),
position: Some(Position {
start: line.point(0),
end: cx.lines[end - 1].end(),
}),
})));
Some(Step::to(end))
}
}
pub(super) struct MdxFlow;
impl BlockRule for MdxFlow {
fn parse(cx: &Cx<'_, '_>, blocks: &mut Vec<Block>) -> Option<Step> {
if !may_start_flow(cx.line) {
return None;
}
let FlowOutcome::Flow(next) = mdx_flow(cx.lines, cx.index, blocks) else {
return None;
};
Some(Step {
interrupt: cx.interrupting,
..Step::to(next)
})
}
}