use crate::converter::dom_context::DomContext;
use crate::converter::main_helpers::{is_ascii_whitespace_only, is_inline_element};
use crate::converter::metadata::is_body_content_in_head;
use crate::converter::utility::attributes::{attribute_matches_any, element_has_navigation_hint};
use crate::converter::utility::content::normalized_tag_name;
use crate::converter::utility::escaping::is_block_level_name;
use crate::options::ConversionOptions;
use crate::text::decode_html_entities_cow;
pub fn inline_ancestor_allows_block(tag_name: &str) -> bool {
matches!(tag_name, "a" | "ins" | "del")
}
#[derive(Clone, Copy)]
struct MisnestState {
inside_anchor: bool,
inside_form: bool,
form_repair_opaque: bool,
inside_preformatted: bool,
blocked_by_inline_ancestor: bool,
p_ancestor_state: bool,
parent_is_paragraph: bool,
list_item_ancestor_state: bool,
cell_ancestor_state: bool,
}
impl MisnestState {
const ROOT: Self = Self {
inside_anchor: false,
inside_form: false,
form_repair_opaque: false,
inside_preformatted: false,
blocked_by_inline_ancestor: false,
p_ancestor_state: false,
parent_is_paragraph: false,
list_item_ancestor_state: false,
cell_ancestor_state: false,
};
}
fn node_is_misnested(name: &str, is_block: bool, state: MisnestState, self_inside_preformatted: bool) -> bool {
(name == "a" && state.inside_anchor && !state.inside_preformatted)
|| (name == "form" && state.inside_form && !state.form_repair_opaque)
|| (matches!(name, "td" | "tr" | "th") && state.p_ancestor_state)
|| (is_block && !self_inside_preformatted && state.blocked_by_inline_ancestor)
|| (matches!(name, "li" | "dt" | "dd") && state.list_item_ancestor_state)
|| (name == "tr" && state.cell_ancestor_state)
}
fn child_misnest_state(name: &str, state: MisnestState, self_inside_preformatted: bool) -> MisnestState {
MisnestState {
inside_anchor: state.inside_anchor || name == "a",
inside_form: state.inside_form || name == "form",
form_repair_opaque: state.form_repair_opaque
|| name == "template"
|| crate::converter::tier1::tags::lookup(name.as_bytes()).is_some_and(|spec| spec.is_rawtext),
inside_preformatted: self_inside_preformatted,
blocked_by_inline_ancestor: state.blocked_by_inline_ancestor
|| (is_inline_element(name) && !inline_ancestor_allows_block(name)),
p_ancestor_state: p_ancestor_state_for(name, state.p_ancestor_state),
parent_is_paragraph: name == "p",
list_item_ancestor_state: list_item_ancestor_state_for(name, state.list_item_ancestor_state),
cell_ancestor_state: cell_ancestor_state_for(name, state.cell_ancestor_state),
}
}
#[cfg(any(test, feature = "testkit"))]
#[must_use]
pub fn has_inline_block_misnest(dom: &crate::dom::VDom, parser: &crate::dom::Parser) -> bool {
tree_repair_reasons(dom, parser).misnest
}
#[derive(Clone, Copy, Debug, Default)]
pub(super) struct TreeRepairReasons {
pub(super) misnest: bool,
pub(super) paragraph_close: bool,
pub(super) form_paragraph_close: bool,
}
#[must_use]
pub(super) fn tree_repair_reasons(dom: &crate::dom::VDom, parser: &crate::dom::Parser) -> TreeRepairReasons {
let mut reasons = TreeRepairReasons::default();
let mut stack: Vec<(crate::dom::NodeHandle, MisnestState)> = dom
.children()
.iter()
.map(|handle| (*handle, MisnestState::ROOT))
.collect();
while let Some((handle, state)) = stack.pop() {
let Some(crate::dom::Node::Tag(tag)) = handle.get(parser) else {
continue;
};
let name = normalized_tag_name(tag.name().as_utf8_str());
let name = name.as_ref();
let is_block = is_block_level_name(name, is_inline_element(name));
let self_inside_preformatted = state.inside_preformatted || matches!(name, "pre" | "code");
if node_is_misnested(name, is_block, state, self_inside_preformatted) {
return TreeRepairReasons {
misnest: true,
..reasons
};
}
let tag_children = tag.children();
let children = tag_children.top().as_slice();
if name == "table"
&& children
.iter()
.any(|child| is_foster_parenting_candidate(*child, parser))
{
return TreeRepairReasons {
misnest: true,
..reasons
};
}
if is_row_context_with_misplaced_content(name, children, parser) {
return TreeRepairReasons {
misnest: true,
..reasons
};
}
if state.parent_is_paragraph && !state.cell_ancestor_state && !self_inside_preformatted {
reasons.paragraph_close |= matches!(name, "dt" | "dd");
reasons.form_paragraph_close |= name == "form";
}
let child_state = child_misnest_state(name, state, self_inside_preformatted);
stack.extend(children.iter().map(|child| (*child, child_state)));
}
reasons
}
pub fn has_omitted_end_tag(dom: &crate::dom::VDom, parser: &crate::dom::Parser) -> bool {
let mut last = dom.children().last().copied();
while let Some(handle) = last {
let Some(crate::dom::Node::Tag(tag)) = handle.get(parser) else {
return false;
};
if has_end_tag(tag) {
return false;
}
let tag_children = tag.children();
let children = tag_children.top().as_slice();
let has_content = !children.is_empty();
let name = tag.name().as_bytes();
if has_content && !name.eq_ignore_ascii_case(b"html") && !name.eq_ignore_ascii_case(b"body") {
return true;
}
last = children.last().copied();
}
false
}
fn has_end_tag(tag: &crate::dom::HTMLTag<'_>) -> bool {
end_tag_offset(tag).is_some()
}
fn end_tag_offset(tag: &crate::dom::HTMLTag<'_>) -> Option<usize> {
let raw = tag.raw().as_bytes();
let body = raw.strip_suffix(b">")?;
let at = memchr::memmem::rfind(body, b"</")?;
let rest = &body[at + 2..];
let name = tag.name().as_bytes();
let spelled = rest.get(..name.len())?;
let tail = &rest[name.len()..];
(spelled.eq_ignore_ascii_case(name) && tail.iter().all(|byte| byte.is_ascii_whitespace() || *byte == b'/'))
.then_some(at)
}
struct SiblingList<'a> {
parent: Option<crate::dom::NodeHandle>,
next: usize,
previous_end: Option<usize>,
end_tag: Option<usize>,
name: Option<std::borrow::Cow<'a, [u8]>>,
}
pub fn has_discarded_end_tag(dom: &crate::dom::VDom, parser: &crate::dom::Parser, input: &str) -> bool {
let source = input.as_bytes();
let mut open: std::collections::HashMap<std::borrow::Cow<'_, [u8]>, usize> = std::collections::HashMap::new();
let mut lists = vec![SiblingList {
parent: None,
next: 0,
previous_end: None,
end_tag: None,
name: None,
}];
while let Some(list) = lists.last_mut() {
let handle = match list.parent {
Some(parent) => parent
.get(parser)
.and_then(|node| node.as_tag())
.and_then(|tag| tag.children().top().get(list.next).copied()),
None => dom.children().get(list.next).copied(),
};
let Some(handle) = handle else {
if names_open_element(source, list.previous_end, list.end_tag, &open) {
return true;
}
if let Some(count) = list.name.as_ref().and_then(|name| open.get_mut(name)) {
*count -= 1;
}
lists.pop();
continue;
};
list.next += 1;
let Some(node) = handle.get(parser) else {
list.previous_end = None;
continue;
};
let span = node_span(node, source);
if names_open_element(source, list.previous_end, span.map(|(start, _)| start), &open) {
return true;
}
list.previous_end = span.map(|(_, end)| end);
let crate::dom::Node::Tag(tag) = node else { continue };
let tag_children = tag.children();
let children = tag_children.top().as_slice();
if children.is_empty() {
continue;
}
let name = tag.name().as_bytes();
let end_tag_at = end_tag_offset(tag);
let closed = end_tag_at.is_some();
let name_in_lower_case = lower_case(name);
*open.entry(name_in_lower_case.clone()).or_insert(0) += 1;
lists.push(SiblingList {
parent: Some(handle),
next: 0,
previous_end: span.filter(|_| !closed).map(|(_, end)| end),
end_tag: span.zip(end_tag_at).map(|((start, _), at)| start + at),
name: Some(name_in_lower_case),
});
}
false
}
fn lower_case(name: &[u8]) -> std::borrow::Cow<'_, [u8]> {
if name.iter().any(u8::is_ascii_uppercase) {
std::borrow::Cow::Owned(name.to_ascii_lowercase())
} else {
std::borrow::Cow::Borrowed(name)
}
}
fn node_span(node: &crate::dom::Node<'_>, source: &[u8]) -> Option<(usize, usize)> {
let raw = match node {
crate::dom::Node::Tag(tag) => tag.raw().as_bytes(),
crate::dom::Node::Raw(bytes) | crate::dom::Node::Comment(bytes) => bytes.as_bytes(),
};
let start = (raw.as_ptr() as usize).checked_sub(source.as_ptr() as usize)?;
(!raw.is_empty() && start + raw.len() <= source.len()).then_some((start, start + raw.len()))
}
fn names_open_element(
source: &[u8],
from: Option<usize>,
to: Option<usize>,
open: &std::collections::HashMap<std::borrow::Cow<'_, [u8]>, usize>,
) -> bool {
let Some(gap) = from.zip(to).and_then(|(from, to)| source.get(from..to)) else {
return false;
};
memchr::memmem::find_iter(gap, b"</").any(|at| {
let name = &gap[at + 2..];
let end = name
.iter()
.position(|byte| byte.is_ascii_whitespace() || matches!(byte, b'/' | b'>'))
.unwrap_or(name.len());
open.get(&*lower_case(&name[..end])).is_some_and(|count| *count > 0)
})
}
pub fn readable_text_len(dom: &crate::dom::VDom<'_>) -> usize {
text_len(dom, &NO_READABLE_TEXT)
}
pub fn written_title_len(dom: &crate::dom::VDom<'_>) -> usize {
text_len(dom, &NO_READABLE_TEXT[..NO_READABLE_TEXT.len() - 1]) - readable_text_len(dom)
}
fn text_len(dom: &crate::dom::VDom<'_>, skipped: &[&[u8]]) -> usize {
let parser = dom.parser();
let mut total = 0;
let mut stack = dom.children().to_vec();
while let Some(handle) = stack.pop() {
match handle.get(parser) {
Some(crate::dom::Node::Raw(text)) => total += decoded_len(text.as_bytes()),
Some(crate::dom::Node::Tag(tag)) if holds_readable_text(tag, parser, skipped) => {
stack.extend(tag.children().top().iter().copied());
}
_ => {}
}
}
total
}
fn decoded_len(text: &[u8]) -> usize {
let characters = |bytes: &[u8]| {
bytes
.iter()
.filter(|byte| !byte.is_ascii_whitespace() && (**byte & 0xC0) != 0x80)
.count()
};
if memchr::memchr(b'&', text).is_none() {
return characters(text);
}
characters(decode_html_entities_cow(&String::from_utf8_lossy(text)).as_bytes())
}
const NO_READABLE_TEXT: [&[u8]; 5] = [b"script", b"style", b"template", b"noscript", b"title"];
fn holds_readable_text(tag: &crate::dom::HTMLTag<'_>, parser: &crate::dom::Parser<'_>, skipped: &[&[u8]]) -> bool {
let name = tag.name().as_bytes();
if name.eq_ignore_ascii_case(b"head") {
return tag.children().top().iter().any(|child| {
matches!(
child.get(parser),
Some(crate::dom::Node::Tag(child))
if is_body_content_in_head(&normalized_tag_name(child.name().as_utf8_str()))
)
});
}
!skipped.iter().any(|other| name.eq_ignore_ascii_case(other))
}
fn is_foster_parenting_candidate(child: crate::dom::NodeHandle, parser: &crate::dom::Parser) -> bool {
match child.get(parser) {
Some(crate::dom::Node::Raw(bytes)) => {
let raw = bytes.as_utf8_str();
let decoded = crate::text::decode_html_entities_cow(raw.as_ref());
!is_ascii_whitespace_only(&decoded)
}
Some(crate::dom::Node::Tag(tag)) => !is_table_structural_child(&normalized_tag_name(tag.name().as_utf8_str())),
_ => false,
}
}
fn is_table_structural_child(tag_name: &str) -> bool {
matches!(
tag_name,
"caption" | "colgroup" | "col" | "thead" | "tbody" | "tfoot" | "tr" | "row" | "style" | "script" | "template"
)
}
fn is_row_context_with_misplaced_content(
name: &str,
children: &[crate::dom::NodeHandle],
parser: &crate::dom::Parser,
) -> bool {
let valid: fn(&str) -> bool = match name {
"tr" | "row" => is_row_structural_child,
"thead" | "tbody" | "tfoot" => is_section_structural_child,
_ => return false,
};
children.iter().any(|child| match child.get(parser) {
Some(crate::dom::Node::Tag(tag)) => !valid(&normalized_tag_name(tag.name().as_utf8_str())),
Some(crate::dom::Node::Raw(bytes)) => {
let raw = bytes.as_utf8_str();
let decoded = crate::text::decode_html_entities_cow(raw.as_ref());
decoded.chars().any(|character| !character.is_whitespace())
}
_ => false,
})
}
fn is_row_structural_child(tag_name: &str) -> bool {
matches!(tag_name, "td" | "th" | "cell" | "script" | "style" | "template")
}
fn is_section_structural_child(tag_name: &str) -> bool {
matches!(tag_name, "tr" | "row" | "script" | "style" | "template")
}
fn p_ancestor_state_for(tag_name: &str, inherited: bool) -> bool {
if tag_name == "p" {
true
} else if matches!(tag_name, "table" | "body" | "html") {
false
} else {
inherited
}
}
fn list_item_ancestor_state_for(tag_name: &str, inherited: bool) -> bool {
if matches!(tag_name, "li" | "dt" | "dd") {
true
} else if matches!(tag_name, "ul" | "ol" | "dl" | "table" | "body" | "html") {
false
} else {
inherited
}
}
fn cell_ancestor_state_for(tag_name: &str, inherited: bool) -> bool {
if matches!(tag_name, "td" | "th") {
true
} else if matches!(tag_name, "table" | "thead" | "tbody" | "tfoot" | "tr") {
false
} else {
inherited
}
}
pub fn should_drop_for_preprocessing(
tag_name: &str,
tag: &crate::dom::HTMLTag,
options: &ConversionOptions,
is_page_header: bool,
) -> bool {
use crate::options::PreprocessingPreset;
if !options.preprocessing.enabled {
return false;
}
let preset = options.preprocessing.preset;
if preset == PreprocessingPreset::Minimal {
return false;
}
if options.preprocessing.remove_forms && tag_name == "form" {
return true;
}
let is_aggressive = preset == PreprocessingPreset::Aggressive;
if is_aggressive && tag_name == "noscript" {
return true;
}
if !options.preprocessing.remove_navigation {
return false;
}
let has_nav_hint = element_has_navigation_hint(tag);
if tag_name == "nav" {
return true;
}
if tag_name == "header" {
return is_page_header || has_nav_hint;
}
if tag_name == "footer" || tag_name == "aside" {
return is_aggressive || has_nav_hint;
}
if is_aggressive && has_nav_hint {
return true;
}
if is_aggressive {
if element_has_noise_hint(tag) {
return true;
}
}
false
}
pub fn is_page_header(node_handle: &crate::dom::NodeHandle, parser: &crate::dom::Parser, dom_ctx: &DomContext) -> bool {
let mut ancestor = dom_ctx.parent_of(node_handle.get_inner());
let mut in_document_body = false;
while let Some(node_id) = ancestor {
if let Some(info) = dom_ctx.tag_info(node_id, parser) {
if matches!(info.name.as_str(), "article" | "section" | "main") {
return false;
}
in_document_body |= info.name == "body";
}
ancestor = dom_ctx.parent_of(node_id);
}
in_document_body
}
fn element_has_noise_hint(tag: &crate::dom::HTMLTag) -> bool {
const NOISE_KEYWORDS: &[&str] = &[
"cookie",
"consent",
"gdpr",
"banner",
"advertisement",
"ad-container",
"advert",
"social-share",
"share-buttons",
"popup",
"modal-overlay",
"newsletter-signup",
];
attribute_matches_any(tag, "class", NOISE_KEYWORDS) || attribute_matches_any(tag, "id", NOISE_KEYWORDS)
}
#[cfg(test)]
mod tests {
use super::{has_discarded_end_tag, has_omitted_end_tag, readable_text_len};
fn discards_an_end_tag_of_an_open_element(html: &str) -> bool {
let dom = crate::dom::parse(html, crate::dom::ParserOptions).expect("parse");
has_discarded_end_tag(&dom, dom.parser(), html)
}
#[test]
fn should_leave_a_discarded_end_tag_as_source_between_two_sibling_nodes() {
let html = "<div><p>one</div>two</p>";
let dom = crate::dom::parse(html, crate::dom::ParserOptions).expect("parse");
let parser = dom.parser();
let paragraph = dom
.nodes()
.iter()
.filter_map(crate::dom::Node::as_tag)
.find(|tag| tag.name() == "p")
.expect("paragraph");
let texts: Vec<(usize, &[u8])> = paragraph
.children()
.top()
.iter()
.filter_map(|child| match child.get(parser) {
Some(crate::dom::Node::Raw(text)) => Some(text.as_bytes()),
_ => None,
})
.map(|text| (text.as_ptr() as usize - html.as_ptr() as usize, text))
.collect();
assert_eq!(texts, [(8, b"one".as_slice()), (17, b"two".as_slice())]);
assert_eq!(&html[11..17], "</div>");
}
#[test]
fn should_find_an_end_tag_that_the_first_parse_discarded_while_its_element_was_open() {
for html in [
"<div><p>one</div>two</p>",
"<div><p>one</div>two</p>rest</div>tail",
"<div><p>one<b>x</b></div>two</p>rest</div>tail",
"<div><p>one</DIV >two</p>rest</div>tail",
"<DIV><p>one</div>two</p>rest</DIV>tail",
"<ul><li>one</ul>two</li></ul>tail",
"<dl><dd>one</dl>two</dd></dl>tail",
"<table><tr><td>one</tr>two</td></tr></table>tail",
"<select><option>one</select>two</option></select>tail",
"<html><body><div><p>one</div>two</p>rest</div>tail",
] {
assert!(discards_an_end_tag_of_an_open_element(html), "{html:?}");
}
}
#[test]
fn should_find_no_discarded_end_tag_when_none_names_an_open_element() {
let deep = format!("{}x{}", "<div>".repeat(600), "</div>".repeat(600));
for html in [
"",
"<p>a</b>b",
"<p>a</p></div>tail",
"<div><p>one</p></div>tail",
"<div><p>one</p><p>two</p></span></div>tail",
"<div title='</div>'><p>x</p></div>",
"<div><p>one<!-- </div> -->two</p></div>",
"<div><p>one<!-- </div> two</p></div>",
"<!doctype html><div><p>one</p>two</div>",
"<div><pre>one\n</pre>two</div>",
deep.as_str(),
] {
assert!(!discards_an_end_tag_of_an_open_element(html), "{html:?}");
}
}
const CLOSED_IN_ANOTHER_SPELLING: [&str; 6] = [
"<div>a</DIV>tail",
"<DIV><p>a</P></div>tail",
"<p>a</p >tail",
"<div><p>a</p\n></div >tail",
"<svg><clipPath>x</CLIPPATH></svg>tail",
"<div title='</div>'><p>x</P></DIV>",
];
#[test]
fn should_find_no_omitted_end_tag_at_an_end_tag_in_another_spelling() {
for html in CLOSED_IN_ANOTHER_SPELLING {
let dom = crate::dom::parse(html, crate::dom::ParserOptions).expect("parse");
assert!(!has_omitted_end_tag(&dom, dom.parser()), "{html:?}");
}
}
#[test]
fn should_find_no_discarded_end_tag_at_an_end_tag_in_another_spelling() {
for html in CLOSED_IN_ANOTHER_SPELLING {
assert!(!discards_an_end_tag_of_an_open_element(html), "{html:?}");
}
}
#[test]
fn should_still_find_a_discarded_end_tag_inside_an_element_closed_in_another_spelling() {
assert!(discards_an_end_tag_of_an_open_element(
"<DIV><p>one</div>two</p></DIV>tail"
));
assert!(discards_an_end_tag_of_an_open_element(
"<div><p>one</DIV >two</p></div >tail"
));
assert!(discards_an_end_tag_of_an_open_element(
"<div><span><p>a</p></div></SPAN></div>"
));
assert!(discards_an_end_tag_of_an_open_element(
"<div><span><p>a</p></div></span ></div>"
));
}
fn text_len(html: &str) -> usize {
readable_text_len(&crate::dom::parse(html, crate::dom::ParserOptions).expect("parse"))
}
#[test]
fn should_count_the_characters_of_text_that_are_not_white_space() {
for (html, expected) in [
("", 0),
("<p> \n\t</p>", 0),
("<div><p>one</div>tail", 7),
("lead<DIV>one <b>two</b></DIV>", 10),
("<p>é ü</p>", 2),
("<!-- comment --><p>one<!-- two --></p>", 3),
("<p title=\"text\">one</p>", 3),
] {
assert_eq!(text_len(html), expected, "{html:?}");
}
}
#[test]
fn should_count_a_character_reference_as_the_character_it_names() {
for (html, expected) in [
("<p>A</p>", 1),
("<p>A</p>", 1),
("<p>&</p>", 1),
("<p>R&D</p>", 3),
("<p>a b c d e</p>", 8),
("<p>a\u{a0}b</p>", 3),
("<p>© 2020</p>", 5),
] {
assert_eq!(text_len(html), expected, "{html:?}");
}
}
#[test]
fn should_leave_out_the_text_that_the_converter_never_writes() {
for name in ["script", "style", "template", "noscript", "title", "TITLE", "NoScript"] {
let html = format!("<{name}>out <b>out</b></{name}><p>one</p>");
assert_eq!(text_len(&html), 3, "{html:?}");
}
for html in [
"<titles>four</titles><p>one</p>",
"<header>four</header><p>one</p>",
"<noframes>four</noframes><p>one</p>",
"<iframe>four</iframe><p>one</p>",
] {
assert_eq!(text_len(html), 7, "{html:?}");
}
}
#[test]
fn should_read_a_head_only_when_it_holds_body_content() {
for (html, expected) in [
("<head>out<noframes><b>out</b></noframes></head><p>one</p>", 3),
("<HEAD><NOFRAMES><DIV>out</NOFRAMES></HEAD>", 0),
("<head><title>t</title><div>one</div><p>two</p>", 6),
("<HEAD><TITLE>t</TITLE><BODY><p>one</p>", 3),
("<header>one</header>", 3),
] {
assert_eq!(text_len(html), expected, "{html:?}");
}
}
}