use std::cell::{OnceCell, RefCell};
use std::collections::{HashMap, HashSet};
use crate::converter::main_helpers::is_inline_element;
use crate::converter::utility::content::normalized_tag_name;
use crate::converter::utility::escaping::is_block_level_name;
use crate::converter::utility::white_space::{TextClass, classify_text};
use crate::text;
pub struct TagInfo {
pub(crate) name: String,
pub(crate) is_inline_like: bool,
pub(crate) is_block: bool,
}
#[derive(Clone, Copy, Default)]
pub struct TableContentSummary {
pub(crate) has_text: bool,
pub(crate) link_count: usize,
pub(crate) has_header: bool,
pub(crate) has_caption: bool,
}
impl TableContentSummary {
pub(crate) const fn merge(&mut self, other: Self) {
self.has_text |= other.has_text;
self.link_count += other.link_count;
self.has_header |= other.has_header;
self.has_caption |= other.has_caption;
}
pub(crate) const fn is_empty(&self) -> bool {
!self.has_text && self.link_count == 0 && !self.has_header && !self.has_caption
}
}
#[derive(Clone, Copy, PartialEq, Eq)]
pub enum LineEndOwner {
Code,
Del,
}
pub struct DomContext {
pub(crate) parent_map: Vec<Option<u32>>,
pub(crate) literal_pre_map: Vec<bool>,
pub(crate) line_end_owner_map: Vec<Option<LineEndOwner>>,
pub(crate) children_map: Vec<Option<Vec<tl::NodeHandle>>>,
pub(crate) sibling_index_map: Vec<Option<usize>>,
pub(crate) root_children: Vec<tl::NodeHandle>,
pub(crate) node_map: Vec<Option<tl::NodeHandle>>,
pub(crate) tag_info_map: Vec<OnceCell<Option<TagInfo>>>,
pub(crate) next_inline_like_map: Vec<OnceCell<bool>>,
pub(crate) prev_tag_map: Vec<OnceCell<Option<u32>>>,
pub(crate) next_tag_map: Vec<OnceCell<Option<u32>>>,
pub(crate) following_content_map: Vec<crate::converter::utility::siblings::FollowingContent>,
pub(crate) next_whitespace_map: Vec<OnceCell<bool>>,
pub(crate) table_content_summary_cache: RefCell<HashMap<u32, TableContentSummary>>,
pub(crate) datalist_content_cache: RefCell<HashMap<u32, bool>>,
pub(crate) holds_text_cache: RefCell<HashMap<u32, bool>>,
pub(crate) silent_heading_images: RefCell<HashSet<u32>>,
pub(crate) blank_passthrough_renders: RefCell<HashSet<u32>>,
pub(crate) authored_break_cache: RefCell<HashMap<u32, bool>>,
pub(crate) omitted_break_owners: RefCell<HashSet<u32>>,
}
#[cfg(test)]
thread_local! {
pub(crate) static HOLDS_TEXT_NODE_READS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
pub(crate) static AUTHORED_BREAK_CACHE_STATS: std::cell::Cell<(usize,usize)> = const { std::cell::Cell::new((0,0)) };
pub(crate) static FONT_RENDER_BYTE_READS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
pub(crate) static FONT_RENDER_GUARD_CALLS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
pub(crate) static FONT_RENDER_SET_STATS: std::cell::Cell<(usize, usize)> = const { std::cell::Cell::new((0, 0)) };
}
#[cfg(test)]
fn count_node_read() {
HOLDS_TEXT_NODE_READS.with(|total| total.set(total.get() + 1));
}
#[cfg(not(test))]
const fn count_node_read() {}
enum Held {
Yes,
No,
Inside,
}
fn recorded(record: &RefCell<HashMap<u32, bool>>, id: u32) -> Option<bool> {
record.borrow().get(&id).copied()
}
impl DomContext {
pub(crate) fn ensure_capacity(&mut self, id: u32) {
let idx = id as usize;
if self.parent_map.len() <= idx {
let new_len = idx + 1;
self.parent_map.resize(new_len, None);
self.literal_pre_map.resize(new_len, false);
self.line_end_owner_map.resize(new_len, None);
self.children_map.resize_with(new_len, || None);
self.sibling_index_map.resize_with(new_len, || None);
self.node_map.resize(new_len, None);
self.tag_info_map.resize_with(new_len, OnceCell::new);
self.next_inline_like_map.resize_with(new_len, OnceCell::new);
self.prev_tag_map.resize_with(new_len, OnceCell::new);
self.next_tag_map.resize_with(new_len, OnceCell::new);
self.next_whitespace_map.resize_with(new_len, OnceCell::new);
self.following_content_map
.resize(new_len, crate::converter::utility::siblings::FollowingContent::Absent);
}
}
pub(crate) fn parent_of(&self, id: u32) -> Option<u32> {
self.parent_map.get(id as usize).copied().flatten()
}
pub(crate) fn node_handle(&self, id: u32) -> Option<&tl::NodeHandle> {
self.node_map.get(id as usize).and_then(|node| node.as_ref())
}
pub(crate) fn children_of(&self, id: u32) -> Option<&Vec<tl::NodeHandle>> {
self.children_map
.get(id as usize)
.and_then(|children| children.as_ref())
}
pub(crate) fn sibling_index(&self, id: u32) -> Option<usize> {
self.sibling_index_map.get(id as usize).copied().flatten()
}
pub(crate) fn tag_info(&self, id: u32, parser: &tl::Parser) -> Option<&TagInfo> {
self.tag_info_map
.get(id as usize)
.and_then(|cell| cell.get_or_init(|| self.build_tag_info(id, parser)).as_ref())
}
pub(crate) fn tag_name_for<'a>(
&'a self,
node_handle: tl::NodeHandle,
parser: &'a tl::Parser,
) -> Option<std::borrow::Cow<'a, str>> {
if let Some(info) = self.tag_info(node_handle.get_inner(), parser) {
return Some(std::borrow::Cow::Borrowed(info.name.as_str()));
}
if let Some(tl::Node::Tag(tag)) = node_handle.get(parser) {
return Some(normalized_tag_name(tag.name().as_utf8_str()));
}
None
}
pub(crate) fn next_tag_name<'a>(&'a self, node_handle: tl::NodeHandle, parser: &'a tl::Parser) -> Option<&'a str> {
let next_id = self.next_tag_id(node_handle.get_inner(), parser)?;
self.tag_info(next_id, parser).map(|info| info.name.as_str())
}
pub(crate) fn next_inline_like(&self, node_handle: tl::NodeHandle, parser: &tl::Parser) -> bool {
let id = node_handle.get_inner();
self.next_inline_like_map.get(id as usize).is_some_and(|cell| {
*cell.get_or_init(|| {
let parent = self.parent_of(id);
let siblings = if let Some(parent_id) = parent {
if let Some(children) = self.children_of(parent_id) {
children
} else {
return false;
}
} else {
&self.root_children
};
let Some(position) = self
.sibling_index(id)
.or_else(|| siblings.iter().position(|handle| handle.get_inner() == id))
else {
return false;
};
for sibling in siblings.iter().skip(position + 1) {
if let Some(info) = self.tag_info(sibling.get_inner(), parser) {
return info.is_inline_like;
}
if let Some(tl::Node::Raw(raw)) = sibling.get(parser) {
if raw.as_utf8_str().trim().is_empty() {
continue;
}
return false;
}
}
false
})
})
}
pub(crate) fn next_whitespace_text(&self, node_handle: tl::NodeHandle, parser: &tl::Parser) -> bool {
let id = node_handle.get_inner();
self.next_whitespace_map.get(id as usize).is_some_and(|cell| {
*cell.get_or_init(|| {
let parent = self.parent_of(id);
let siblings = if let Some(parent_id) = parent {
if let Some(children) = self.children_of(parent_id) {
children
} else {
return false;
}
} else {
&self.root_children
};
let Some(position) = self
.sibling_index(id)
.or_else(|| siblings.iter().position(|handle| handle.get_inner() == id))
else {
return false;
};
for sibling in siblings.iter().skip(position + 1) {
if let Some(node) = sibling.get(parser) {
match node {
tl::Node::Raw(raw) => return raw.as_utf8_str().trim().is_empty(),
tl::Node::Tag(_) => return false,
tl::Node::Comment(_) => {}
}
}
}
false
})
})
}
pub(crate) fn next_tag_id(&self, id: u32, parser: &tl::Parser) -> Option<u32> {
self.next_tag_map
.get(id as usize)
.and_then(|cell| {
cell.get_or_init(|| {
let parent = self.parent_of(id);
let siblings = if let Some(parent_id) = parent {
self.children_of(parent_id)?
} else {
&self.root_children
};
let position = self
.sibling_index(id)
.or_else(|| siblings.iter().position(|handle| handle.get_inner() == id))?;
for sibling in siblings.iter().skip(position + 1) {
if self.tag_info(sibling.get_inner(), parser).is_some() {
let sibling_id = sibling.get_inner();
return Some(sibling_id);
}
if let Some(tl::Node::Raw(raw)) = sibling.get(parser) {
if !raw.as_utf8_str().trim().is_empty() {
return None;
}
}
}
None
})
.as_ref()
})
.copied()
}
pub(crate) fn build_tag_info(&self, id: u32, parser: &tl::Parser) -> Option<TagInfo> {
let node_handle = self.node_handle(id)?;
match node_handle.get(parser) {
Some(tl::Node::Tag(tag)) => {
let name = normalized_tag_name(tag.name().as_utf8_str()).into_owned();
let is_inline = is_inline_element(&name);
let is_inline_like = is_inline || matches!(name.as_str(), "script" | "style");
let is_block = is_block_level_name(&name, is_inline);
Some(TagInfo {
name,
is_inline_like,
is_block,
})
}
_ => None,
}
}
pub(crate) fn text_content(&self, node_handle: tl::NodeHandle, parser: &tl::Parser) -> String {
self.text_content_uncached(node_handle, parser)
}
pub(crate) fn text_content_uncached(&self, node_handle: tl::NodeHandle, parser: &tl::Parser) -> String {
let mut text = String::with_capacity(64);
let mut stack = vec![node_handle];
while let Some(handle) = stack.pop() {
let Some(node) = handle.get(parser) else {
continue;
};
match node {
tl::Node::Raw(bytes) => {
let raw = bytes.as_utf8_str();
let decoded = text::decode_html_entities_cow(raw.as_ref());
text.push_str(decoded.as_ref());
}
tl::Node::Tag(tag) => {
if let Some(children) = self.children_of(handle.get_inner()) {
for child_handle in children.iter().rev() {
stack.push(*child_handle);
}
} else {
let children = tag.children();
let mut child_handles: Vec<_> = children.top().iter().copied().collect();
child_handles.reverse();
for child_handle in child_handles {
stack.push(child_handle);
}
}
}
tl::Node::Comment(_) => {}
}
}
text
}
pub(crate) fn holds_text(&self, id: u32, parser: &tl::Parser) -> bool {
self.holds(id, parser, &self.holds_text_cache, |node, _| match node {
tl::Node::Raw(raw) => {
let raw = raw.as_utf8_str();
let decoded = text::decode_html_entities_cow(raw.as_ref());
if matches!(classify_text(decoded.as_ref()), TextClass::WhiteSpaceOnly(_)) {
Held::No
} else {
Held::Yes
}
}
tl::Node::Tag(_) => Held::Inside,
tl::Node::Comment(_) => Held::No,
})
}
pub(crate) fn holds_content(&self, id: u32, parser: &tl::Parser) -> bool {
let record = RefCell::new(HashMap::new());
self.holds(id, parser, &record, |node, child| match node {
tl::Node::Raw(raw) => {
let raw = raw.as_utf8_str();
let decoded = text::decode_html_entities_cow(raw.as_ref());
let parent = self.parent_tag_name(child, parser);
let owner = self.line_end_owner_map.get(child as usize).copied().flatten();
let line_ends_only = match owner {
Some(LineEndOwner::Code) => decoded.trim_matches('\n').is_empty(),
Some(LineEndOwner::Del) => {
decoded.trim_matches(['\n', '\r']).is_empty()
&& (parent == Some("del") || decoded.contains('\n'))
}
None => false,
};
if line_ends_only && !self.literal_pre_map.get(child as usize).copied().unwrap_or(false) {
Held::No
} else {
Held::Yes
}
}
tl::Node::Tag(_) if self.writes_void_content(child, parser) => Held::Yes,
tl::Node::Tag(_) => Held::Inside,
tl::Node::Comment(_) => Held::No,
})
}
pub(crate) fn begin_passthrough_render(
&self,
id: u32,
output_len: usize,
handler: crate::converter::block::container::HandlerContext<'_>,
) -> Option<usize> {
let ctx = handler.ctx;
#[cfg(feature = "visitor")]
let observer_suppressed = ctx.skip_visitor_hooks && ctx.has_observer();
#[cfg(not(feature = "visitor"))]
let observer_suppressed = false;
(!observer_suppressed
&& !ctx.code_element_is_transparent()
&& !ctx.in_code_block
&& handler.options.whitespace_mode != crate::WhitespaceMode::Strict)
.then(|| {
self.blank_passthrough_renders.borrow_mut().remove(&id);
output_len
})
}
pub(crate) fn record_blank_passthrough_render(&self, id: u32, written: &str) {
#[cfg(test)]
FONT_RENDER_GUARD_CALLS.with(|calls| calls.set(calls.get() + 1));
let blank = written.is_empty()
|| (written.len() == 1 && {
#[cfg(test)]
FONT_RENDER_BYTE_READS.with(|reads| reads.set(reads.get() + 1));
matches!(written.as_bytes()[0], b' ' | b'\t')
});
if blank {
let mut fonts = self.blank_passthrough_renders.borrow_mut();
fonts.insert(id);
#[cfg(test)]
FONT_RENDER_SET_STATS.with(|stats| {
let (entries, capacity) = stats.get();
stats.set((entries.max(fonts.len()), capacity.max(fonts.capacity())));
});
}
}
pub(crate) fn holds_authored_break(&self, id: u32, parser: &tl::Parser) -> bool {
let found = self.holds(id, parser, &self.authored_break_cache, |node, child| match node {
tl::Node::Tag(_) if self.tag_info(child, parser).is_some_and(|info| info.name == "br") => {
if recorded(&self.authored_break_cache, child) == Some(false) {
Held::No
} else {
Held::Yes
}
}
tl::Node::Tag(_) => Held::Inside,
tl::Node::Raw(_) | tl::Node::Comment(_) => Held::No,
});
#[cfg(test)]
AUTHORED_BREAK_CACHE_STATS.with(|stats| {
let cache = self.authored_break_cache.borrow();
let (entries, capacity) = stats.get();
stats.set((entries.max(cache.len()), capacity.max(cache.capacity())));
});
found
}
pub(crate) fn record_absent_breaks(&self, id: u32, skipped: bool) {
let changed = if skipped {
self.omitted_break_owners.borrow_mut().insert(id)
} else {
self.omitted_break_owners.borrow_mut().remove(&id)
};
if !changed {
return;
}
let mut cache = self.authored_break_cache.borrow_mut();
if skipped {
cache.insert(id, false);
} else {
cache.remove(&id);
}
let mut parent = self.parent_of(id);
while let Some(id) = parent {
cache.remove(&id);
parent = self.parent_of(id);
}
}
pub(crate) fn passthrough_boundary_has_content(&self, id: u32, parser: &tl::Parser) -> bool {
let record = RefCell::new(HashMap::new());
self.holds(id, parser, &record, |node, child| match node {
tl::Node::Raw(raw) => {
let raw = raw.as_utf8_str();
let decoded = text::decode_html_entities_cow(raw.as_ref());
if matches!(classify_text(decoded.as_ref()), TextClass::WhiteSpaceOnly(_)) {
Held::No
} else {
Held::Yes
}
}
tl::Node::Tag(_)
if self.writes_void_content(child, parser)
|| self
.tag_info(child, parser)
.is_some_and(|info| matches!(info.name.as_str(), "code" | "del" | "pre")) =>
{
Held::Yes
}
tl::Node::Tag(_) => Held::Inside,
tl::Node::Comment(_) => Held::No,
})
}
fn writes_void_content(&self, id: u32, parser: &tl::Parser) -> bool {
self.tag_info(id, parser).is_some_and(|info| match info.name.as_str() {
"br" | "hr" => true,
"img" => !self.silent_heading_images.borrow().contains(&id),
_ => false,
})
}
fn holds(
&self,
id: u32,
parser: &tl::Parser,
record: &RefCell<HashMap<u32, bool>>,
held: impl Fn(&tl::Node, u32) -> Held,
) -> bool {
if let Some(known) = recorded(record, id) {
return known;
}
let mut open = vec![(id, 0_usize)];
while let Some((element, position)) = open.last_mut() {
let child = self
.children_of(*element)
.and_then(|children| children.get(*position))
.copied();
*position += 1;
let Some(child) = child else {
record.borrow_mut().insert(*element, false);
open.pop();
continue;
};
count_node_read();
let found = match child.get(parser).map(|node| held(node, child.get_inner())) {
Some(Held::Yes) => true,
Some(Held::Inside) => {
let known = recorded(record, child.get_inner());
if known.is_none() {
open.push((child.get_inner(), 0));
}
known.unwrap_or(false)
}
Some(Held::No) | None => false,
};
if found {
for (element, _) in &open {
record.borrow_mut().insert(*element, true);
}
return true;
}
}
false
}
pub(crate) fn parent_tag_name<'s>(&'s self, node_id: u32, parser: &tl::Parser) -> Option<&'s str> {
let parent_id = self.parent_of(node_id)?;
self.tag_info(parent_id, parser).map(|info| info.name.as_str())
}
pub(crate) fn has_raw_text_ancestor(&self, node_id: u32, parser: &tl::Parser) -> bool {
let mut current_id = node_id;
while let Some(parent_id) = self.parent_of(current_id) {
if self.tag_info(parent_id, parser).is_some_and(|info| {
crate::converter::tier1::tags::lookup(info.name.as_bytes()).is_some_and(|spec| spec.is_rawtext)
}) {
return true;
}
current_id = parent_id;
}
false
}
#[cfg_attr(not(feature = "visitor"), allow(dead_code))]
pub(crate) fn get_sibling_index(&self, node_id: u32) -> Option<usize> {
self.sibling_index(node_id)
}
pub(crate) fn cached_table_content_summary(&self, table_id: u32) -> Option<TableContentSummary> {
self.table_content_summary_cache.borrow().get(&table_id).copied()
}
pub(crate) fn cache_table_content_summary(&self, table_id: u32, summary: TableContentSummary) {
self.table_content_summary_cache.borrow_mut().insert(table_id, summary);
}
}
#[cfg(test)]
mod tests;