use crate::ast::Node;
use crate::next::parser::{AST_COST, stack_overflow};
use crate::types::{Location, NodeType, Result, Span, ValidationError, ValidationLevel};
use indexmap::IndexMap;
fn convert_to_row(node: &mut Node, cell_type: NodeType) {
node.node_type = NodeType::Tr;
node.attributes = IndexMap::new();
node.attributes_prototype = None;
for cell in &mut node.children {
cell.node_type = cell_type.clone();
}
}
fn is_conditional_tag(node: &Node, conditional_tags: &[String]) -> bool {
node.node_type == NodeType::Tag
&& node
.tag
.as_ref()
.is_some_and(|tag| !tag.is_empty() && conditional_tags.contains(tag))
}
fn is_comment(node: &Node) -> bool {
node.node_type == NodeType::Comment
|| (node.node_type == NodeType::Tag && node.tag.as_deref() == Some("comment"))
}
fn unexpected_node_error(node: &Node) -> ValidationError {
let tag = match node.tag.as_deref() {
Some(tag) if !tag.is_empty() => format!(" {tag}"),
_ => String::new(),
};
ValidationError {
id: "table-syntax".into(),
level: ValidationLevel::Critical,
message: format!(
"Found {}{tag} where a list was expected. Make sure all content inside table cells is indented.",
node.node_type.as_str()
),
location: node.location.as_ref().map(Location::to_json),
raw: None,
span: node.span.clone(),
}
}
pub fn transform(document: &mut Node, conditional_tags: Option<&[String]>) -> Result<()> {
let default = ["if".to_string()];
let conditional_tags = conditional_tags.unwrap_or(&default);
walk(document, conditional_tags)
}
fn walk(document: &mut Node, conditional_tags: &[String]) -> Result<()> {
let limit = usize::try_from(crate::depth::left() / AST_COST).unwrap_or(usize::MAX);
let mut stack = vec![Frame::open(document)];
loop {
let depth = stack.len();
let top = stack.last_mut().expect("the document's frame");
if let Some(node) = top.next() {
transform_node(node, conditional_tags);
if depth > limit {
return Err(stack_overflow());
}
let frame = Frame::open(node);
stack.push(frame);
continue;
}
let done = stack.pop().expect("the frame just looked at");
match stack.last_mut() {
Some(parent) => done.close(parent.current()),
None => {
done.close(document);
return Ok(());
}
}
}
}
struct Frame {
slots: IndexMap<String, Node>,
children: Vec<Node>,
yielded: usize,
}
impl Frame {
fn open(node: &mut Node) -> Frame {
Frame {
slots: std::mem::take(&mut node.slots),
children: std::mem::take(&mut node.children),
yielded: 0,
}
}
fn next(&mut self) -> Option<&mut Node> {
let i = self.yielded;
self.yielded += 1;
let slots = self.slots.len();
match self.slots.get_index_mut(i) {
Some((_, slot)) => Some(slot),
None => self.children.get_mut(i - slots),
}
}
fn current(&mut self) -> &mut Node {
let i = self.yielded - 1;
let slots = self.slots.len();
match self.slots.get_index_mut(i) {
Some((_, slot)) => slot,
None => &mut self.children[i - slots],
}
}
fn close(self, node: &mut Node) {
node.slots = self.slots;
node.children = self.children;
}
}
fn transform_node(node: &mut Node, conditional_tags: &[String]) {
if node.node_type != NodeType::Tag || node.tag.as_deref() != Some("table") {
return;
}
match node.children.first() {
None => return,
Some(first) if first.node_type == NodeType::Table => return,
Some(_) => {}
}
let mut rest = std::mem::take(&mut node.children);
let mut first = rest.remove(0);
let mut thead = Node::new(NodeType::Thead, IndexMap::new(), Vec::new(), None);
let mut tbody = Node::new(NodeType::Tbody, IndexMap::new(), Vec::new(), None);
if first.node_type == NodeType::List {
convert_to_row(&mut first, NodeType::Th);
thead.push(first);
}
for mut row in rest {
if row.node_type == NodeType::List {
convert_to_row(&mut row, NodeType::Td);
} else if is_conditional_tag(&row, conditional_tags) {
let mut children = Vec::new();
for mut child in std::mem::take(&mut row.children) {
if child.node_type == NodeType::Hr {
continue;
}
if child.node_type == NodeType::List {
convert_to_row(&mut child, NodeType::Td);
} else if is_comment(&child)
|| child.tag.as_deref() == Some("else")
|| is_conditional_tag(&child, conditional_tags)
{
} else {
row.errors.push(unexpected_node_error(&child));
continue;
}
children.push(child);
}
row.children = children;
} else if row.node_type != NodeType::Hr && !is_comment(&row) {
node.errors.push(unexpected_node_error(&row));
continue;
} else {
continue;
}
tbody.push(row);
}
locate(&mut thead, node.span.as_ref(), false);
locate(&mut tbody, node.span.as_ref(), false);
let mut table = Node::new(
NodeType::Table,
node.attributes.clone(),
vec![thead, tbody],
None,
);
table.attributes_prototype = node.attributes_prototype.clone();
locate(&mut table, node.span.as_ref(), true);
node.children = vec![table];
}
fn locate(node: &mut Node, tag: Option<&Span>, from_tag: bool) {
let Some(tag) = tag else {
return;
};
let mut span: Option<Span> = from_tag.then(|| tag.clone());
for l in node.children.iter().filter_map(|c| c.span.as_ref()) {
match &mut span {
None => span = Some(l.clone()),
Some(span) => {
if l.start.offset < span.start.offset {
span.start = l.start.clone();
}
if l.end.offset > span.end.offset {
span.end = l.end.clone();
}
}
}
}
node.span = Some(span.unwrap_or_else(|| tag.clone()));
}