1#![allow(dead_code)]
2use alloc::collections::BTreeMap;
5use alloc::string::String;
6use alloc::string::ToString;
7use alloc::vec::Vec;
8
9#[path = "dom_tokenizer.rs"]
10pub mod tokenizer;
11#[path = "dom_treebuilder.rs"]
12pub mod treebuilder;
13#[path = "dom_serializer.rs"]
14pub mod serializer;
15#[path = "dom_encoding.rs"]
16pub mod encoding;
17
18pub const COMMENT_TAG: &str = "#comment";
20pub const DOCTYPE_TAG: &str = "#doctype";
21pub const NS_ATTR: &str = "#ns";
23
24#[derive(Debug, Clone, PartialEq)]
25pub enum NodeType {
26 Element {
27 tag_name: String,
28 attributes: BTreeMap<String, String>,
29 classes: Vec<String>,
30 id: Option<String>,
31 },
32 Text(String),
33}
34
35#[derive(Debug, Clone)]
36pub struct Node {
37 pub node_type: NodeType,
38 pub children: Vec<Node>,
39 pub node_idx: Option<usize>,
40 pub features_hash: (u64, u64),
44 pub children_shape_hash: (u64, u64),
46 pub subtree_hash: (u64, u64),
49}
50
51#[inline]
52fn fnv_push_u64(a: &mut u64, b: &mut u64, v: u64) {
53 for i in 0..8 {
54 let x = (v >> (i * 8)) as u8;
55 *a = (*a ^ x as u64).wrapping_mul(0x0000_0100_0000_01b3);
56 *b = (b.rotate_left(5) ^ x as u64).wrapping_mul(0x9E37_79B9_7F4A_7C15);
57 }
58}
59
60#[inline]
61fn fnv_push_bytes(a: &mut u64, b: &mut u64, s: &[u8]) {
62 for &x in s {
63 *a = (*a ^ x as u64).wrapping_mul(0x0000_0100_0000_01b3);
64 *b = (b.rotate_left(5) ^ x as u64).wrapping_mul(0x9E37_79B9_7F4A_7C15);
65 }
66 fnv_push_u64(a, b, s.len() as u64);
67}
68
69#[inline]
70fn fnv_push_node_shape(a: &mut u64, b: &mut u64, nt: &NodeType) {
71 match nt {
72 NodeType::Element { tag_name, .. } => {
73 fnv_push_u64(a, b, 1);
74 fnv_push_bytes(a, b, tag_name.as_bytes());
75 }
76 NodeType::Text(t) => {
77 fnv_push_u64(a, b, 2);
78 fnv_push_u64(a, b, u64::from(!t.is_empty()));
79 }
80 }
81}
82
83pub fn compute_children_shape_hash(children: &[Node]) -> (u64, u64) {
85 let mut a: u64 = 0xcbf2_9ce4_8422_2325;
86 let mut b: u64 = 0x6c62_272e_07bb_0142;
87 fnv_push_u64(&mut a, &mut b, children.len() as u64);
88 for c in children {
89 fnv_push_node_shape(&mut a, &mut b, &c.node_type);
90 }
91 (a, b)
92}
93
94pub fn compute_subtree_hash_shallow(features_hash: (u64, u64), children: &[Node]) -> (u64, u64) {
96 let mut a: u64 = 0xcbf2_9ce4_8422_2325;
97 let mut b: u64 = 0x6c62_272e_07bb_0142;
98 fnv_push_u64(&mut a, &mut b, features_hash.0);
99 fnv_push_u64(&mut a, &mut b, features_hash.1);
100 fnv_push_u64(&mut a, &mut b, children.len() as u64);
101 for c in children {
102 fnv_push_u64(&mut a, &mut b, c.subtree_hash.0);
103 fnv_push_u64(&mut a, &mut b, c.subtree_hash.1);
104 }
105 (a, b)
106}
107
108pub fn compute_children_and_subtree_hashes(features_hash: (u64, u64), children: &[Node]) -> ((u64, u64), (u64, u64)) {
110 (
111 compute_children_shape_hash(children),
112 compute_subtree_hash_shallow(features_hash, children),
113 )
114}
115
116pub fn compute_node_features(nt: &NodeType) -> (u64, u64) {
118 let mut a: u64 = 0xcbf2_9ce4_8422_2325;
119 let mut b: u64 = 0x6c62_272e_07bb_0142;
120 match nt {
121 NodeType::Element { tag_name, attributes, classes, id } => {
122 fnv_push_u64(&mut a, &mut b, 1);
123 fnv_push_bytes(&mut a, &mut b, tag_name.as_bytes());
124 fnv_push_bytes(&mut a, &mut b, id.as_deref().unwrap_or("").as_bytes());
125 fnv_push_u64(&mut a, &mut b, classes.len() as u64);
126 for c in classes {
127 fnv_push_bytes(&mut a, &mut b, c.as_bytes());
128 }
129 fnv_push_u64(&mut a, &mut b, attributes.len() as u64);
130 for (k, v) in attributes {
131 fnv_push_bytes(&mut a, &mut b, k.as_bytes());
132 fnv_push_bytes(&mut a, &mut b, v.as_bytes());
133 }
134 }
135 NodeType::Text(t) => {
136 fnv_push_u64(&mut a, &mut b, 2);
137 fnv_push_u64(&mut a, &mut b, u64::from(!t.is_empty()));
138 }
139 }
140 (a, b)
141}
142
143impl Node {
144 pub fn new_text(text: String) -> Self {
145 let node_type = NodeType::Text(text);
146 let features_hash = compute_node_features(&node_type);
147 let (children_shape_hash, subtree_hash) = compute_children_and_subtree_hashes(features_hash, &[]);
148 Node {
149 node_type,
150 children: Vec::new(),
151 node_idx: None,
152 features_hash,
153 children_shape_hash,
154 subtree_hash,
155 }
156 }
157
158 pub fn new_comment(text: String) -> Self {
160 let mut attrs = BTreeMap::new();
161 attrs.insert(String::from("data"), text);
162 Node::new_element(String::from(COMMENT_TAG), attrs)
163 }
164
165 pub fn new_doctype(name: Option<String>, public_id: Option<String>, system_id: Option<String>) -> Self {
167 let mut attrs = BTreeMap::new();
168 if let Some(n) = name {
169 attrs.insert(String::from("name"), n);
170 }
171 if let Some(p) = public_id {
172 attrs.insert(String::from("publicid"), p);
173 }
174 if let Some(s) = system_id {
175 attrs.insert(String::from("systemid"), s);
176 }
177 Node::new_element(String::from(DOCTYPE_TAG), attrs)
178 }
179
180 pub fn new_element(name: String, attrs: BTreeMap<String, String>) -> Self {
181 let id = attrs.get("id").cloned();
182 let classes = match attrs.get("class") {
183 Some(class_str) => class_str.split_whitespace().map(String::from).collect(),
184 None => Vec::new(),
185 };
186
187 let tag_name = if name.bytes().any(|b| b.is_ascii_uppercase()) {
188 name.to_lowercase()
189 } else {
190 name
191 };
192
193 let node_type = NodeType::Element {
194 tag_name,
195 attributes: attrs,
196 classes,
197 id,
198 };
199 let features_hash = compute_node_features(&node_type);
200 let (children_shape_hash, subtree_hash) = compute_children_and_subtree_hashes(features_hash, &[]);
201 Node {
202 node_type,
203 children: Vec::new(),
204 node_idx: None,
205 features_hash,
206 children_shape_hash,
207 subtree_hash,
208 }
209 }
210
211 pub fn new_element_direct(
212 name: String,
213 attrs: BTreeMap<String, String>,
214 id: Option<String>,
215 classes: Vec<String>,
216 ) -> Self {
217 let node_type = NodeType::Element {
218 tag_name: name.to_lowercase(),
219 attributes: attrs,
220 classes,
221 id,
222 };
223 let features_hash = compute_node_features(&node_type);
224 let (children_shape_hash, subtree_hash) = compute_children_and_subtree_hashes(features_hash, &[]);
225 Node {
226 node_type,
227 children: Vec::new(),
228 node_idx: None,
229 features_hash,
230 children_shape_hash,
231 subtree_hash,
232 }
233 }
234
235 pub fn update_dependent_hashes(&mut self) {
237 let (shape, sub) = compute_children_and_subtree_hashes(self.features_hash, &self.children);
238 self.children_shape_hash = shape;
239 self.subtree_hash = sub;
240 }
241
242 pub fn refresh_dependent_hashes(&mut self) {
244 for c in &mut self.children {
245 c.refresh_dependent_hashes();
246 }
247 self.update_dependent_hashes();
248 }
249
250 pub fn refresh_features_hash(&mut self) {
252 self.features_hash = compute_node_features(&self.node_type);
253 for c in &mut self.children {
254 c.refresh_features_hash();
255 }
256 self.update_dependent_hashes();
257 }
258
259 pub fn empty_root() -> Self {
263 Node::new_element(String::from("html"), BTreeMap::new())
264 }
265
266 pub fn get_attribute(&self, name: &str) -> Option<&str> {
268 if let NodeType::Element { attributes, id, .. } = &self.node_type {
269 if name == "id" {
270 return id.as_deref();
271 }
272 attributes.get(name).map(|s| s.as_str())
273 } else {
274 None
275 }
276 }
277
278 pub fn dataset(&self) -> BTreeMap<String, String> {
280 if let NodeType::Element { attributes, .. } = &self.node_type {
281 crate::os_lib::dom_dataset::extract_dataset(attributes)
282 } else {
283 BTreeMap::new()
284 }
285 }
286
287 pub fn set_dataset_property(
289 &mut self,
290 prop: &str,
291 value: &str,
292 ) -> Result<String, crate::os_lib::dom_dataset::DatasetError> {
293 if let NodeType::Element { attributes, .. } = &mut self.node_type {
294 let res = crate::os_lib::dom_dataset::set_dataset_property(attributes, prop, value);
295 self.features_hash = compute_node_features(&self.node_type);
296 self.update_dependent_hashes();
297 res
298 } else {
299 Ok(String::new())
300 }
301 }
302
303 pub fn remove_dataset_property(
305 &mut self,
306 prop: &str,
307 ) -> Result<Option<String>, crate::os_lib::dom_dataset::DatasetError> {
308 if let NodeType::Element { attributes, .. } = &mut self.node_type {
309 let res = crate::os_lib::dom_dataset::remove_dataset_property(attributes, prop);
310 self.features_hash = compute_node_features(&self.node_type);
311 self.update_dependent_hashes();
312 res
313 } else {
314 Ok(None)
315 }
316 }
317
318 const MAX_SEARCH_DEPTH: usize = 256;
319
320 pub fn get_element_by_id(&self, target_id: &str) -> Option<&Node> {
322 self.get_element_by_id_depth(target_id, 0)
323 }
324
325 fn get_element_by_id_depth(&self, target_id: &str, depth: usize) -> Option<&Node> {
326 if depth >= Self::MAX_SEARCH_DEPTH {
327 return None;
328 }
329 if let NodeType::Element { id: Some(id), .. } = &self.node_type {
330 if id == target_id {
331 return Some(self);
332 }
333 }
334 for child in &self.children {
335 if let Some(found) = child.get_element_by_id_depth(target_id, depth + 1) {
336 return Some(found);
337 }
338 }
339 None
340 }
341
342 pub fn get_elements_by_class_name<'a>(&'a self, target_class: &str, out: &mut Vec<&'a Node>) {
344 self.get_elements_by_class_name_depth(target_class, out, 0);
345 }
346
347 fn get_elements_by_class_name_depth<'a>(
348 &'a self,
349 target_class: &str,
350 out: &mut Vec<&'a Node>,
351 depth: usize,
352 ) {
353 if depth >= Self::MAX_SEARCH_DEPTH {
354 return;
355 }
356 if let NodeType::Element { classes, .. } = &self.node_type {
357 if classes.iter().any(|c| c == target_class) {
358 out.push(self);
359 }
360 }
361 for child in &self.children {
362 child.get_elements_by_class_name_depth(target_class, out, depth + 1);
363 }
364 }
365
366 pub fn get_elements_by_tag_name<'a>(&'a self, target_tag: &str, out: &mut Vec<&'a Node>) {
368 self.get_elements_by_tag_name_depth(target_tag, out, 0);
369 }
370
371 fn get_elements_by_tag_name_depth<'a>(
372 &'a self,
373 target_tag: &str,
374 out: &mut Vec<&'a Node>,
375 depth: usize,
376 ) {
377 if depth >= Self::MAX_SEARCH_DEPTH {
378 return;
379 }
380 if let NodeType::Element { tag_name, .. } = &self.node_type {
381 if target_tag == "*" || tag_name.eq_ignore_ascii_case(target_tag) {
382 out.push(self);
383 }
384 }
385 for child in &self.children {
386 child.get_elements_by_tag_name_depth(target_tag, out, depth + 1);
387 }
388 }
389
390 pub fn text_content(&self) -> String {
392 let mut out = String::new();
393 self.collect_text(&mut out, 0);
394 out
395 }
396
397 fn collect_text(&self, out: &mut String, depth: usize) {
398 if depth >= Self::MAX_SEARCH_DEPTH {
399 return;
400 }
401 match &self.node_type {
402 NodeType::Text(t) => out.push_str(t),
403 NodeType::Element { .. } => {
404 for child in &self.children {
405 child.collect_text(out, depth + 1);
406 }
407 }
408 }
409 }
410}
411
412fn get_tag_name(node: &Node) -> Option<&str> {
414 match &node.node_type {
415 NodeType::Element { tag_name, .. } => Some(tag_name.as_str()),
416 _ => None,
417 }
418}
419
420mod html_entities {
422 include!("html_entities_data.rs");
423}
424
425pub fn decode_entities(s: &str) -> String {
427 decode_entities_in(s, false)
428}
429
430pub fn decode_entities_attr(s: &str) -> String {
432 decode_entities_in(s, true)
433}
434
435fn decode_entities_in(s: &str, in_attr: bool) -> String {
436 let Some(first) = s.find('&') else {
437 return s.to_string();
438 };
439 let bytes = s.as_bytes();
440 let mut result = String::with_capacity(s.len());
441 result.push_str(s.get(..first).unwrap_or(""));
442 let mut i = first;
443 loop {
445 match decode_char_ref(bytes.get(i + 1..).unwrap_or(&[]), in_attr) {
446 Some((used, a, b)) => {
447 match a {
448 Some(c) => result.push(c),
449 None => result.push('\u{FFFD}'),
450 }
451 if let Some(c) = b {
452 result.push(c);
453 }
454 i += 1 + used;
455 }
456 None => {
457 result.push('&');
458 i += 1;
459 }
460 }
461 let rest = s.get(i..).unwrap_or("");
462 match rest.find('&') {
463 Some(p) => {
464 result.push_str(rest.get(..p).unwrap_or(""));
465 i += p;
466 }
467 None => {
468 result.push_str(rest);
469 return result;
470 }
471 }
472 }
473}
474
475pub(crate) fn decode_char_ref(rest: &[u8], in_attr: bool) -> Option<(usize, Option<char>, Option<char>)> {
478 let first = *rest.first()?;
479 if first == b'#' {
480 return decode_numeric_ref(rest);
481 }
482 if !first.is_ascii_alphanumeric() {
483 return None;
484 }
485 let mut run = 1;
487 while run <= html_entities::ENT_MAX_NAME && rest.get(run).is_some_and(|b| b.is_ascii_alphanumeric()) {
488 run += 1;
489 }
490 if rest.get(run) == Some(&b';') {
491 if let Some(v) = entity_lookup(rest.get(..run + 1)?) {
492 return Some(entity_value(run + 1, v));
493 }
494 }
495 let mut l = if run < 6 { run } else { 6 };
497 while l >= 2 {
498 if let Some(v) = entity_lookup(rest.get(..l)?) {
499 if in_attr {
501 if let Some(&n) = rest.get(l) {
502 if n == b'=' || n.is_ascii_alphanumeric() {
503 return None;
504 }
505 }
506 }
507 return Some(entity_value(l, v));
508 }
509 l -= 1;
510 }
511 None
512}
513
514fn entity_value(used: usize, v: &str) -> (usize, Option<char>, Option<char>) {
515 let mut it = v.chars();
516 let a = it.next();
517 (used, a, it.next())
518}
519
520fn entity_lookup(key: &[u8]) -> Option<&'static str> {
522 let names = html_entities::ENT_NAMES.as_bytes();
523 let mut lo = 0usize;
524 let mut hi = html_entities::ENT_COUNT;
525 while lo < hi {
526 let mid = (lo + hi) / 2;
527 let (no, nl, vo, vl) = *html_entities::ENT_INDEX.get(mid)?;
528 let name = names.get(no as usize..no as usize + nl as usize)?;
529 match name.cmp(key) {
530 core::cmp::Ordering::Equal => {
531 return html_entities::ENT_VALUES.get(vo as usize..vo as usize + vl as usize);
532 }
533 core::cmp::Ordering::Less => lo = mid + 1,
534 core::cmp::Ordering::Greater => hi = mid,
535 }
536 }
537 None
538}
539
540fn decode_numeric_ref(rest: &[u8]) -> Option<(usize, Option<char>, Option<char>)> {
542 let hex = matches!(rest.get(1), Some(b'x') | Some(b'X'));
543 let start = if hex { 2 } else { 1 };
544 let mut j = start;
545 let mut code: u32 = 0;
546 while let Some(&b) = rest.get(j) {
547 let d = if hex { (b as char).to_digit(16) } else { (b as char).to_digit(10) };
548 let Some(d) = d else { break };
549 if code <= 0x10FFFF {
551 code = code * if hex { 16 } else { 10 } + d;
552 }
553 j += 1;
554 }
555 if j == start {
556 return None;
557 }
558 if rest.get(j) == Some(&b';') {
559 j += 1;
560 }
561 Some((j, Some(numeric_ref_char(code)), None))
562}
563
564fn numeric_ref_char(code: u32) -> char {
567 const WIN1252: [u16; 32] = [
568 0x20AC, 0x0081, 0x201A, 0x0192, 0x201E, 0x2026, 0x2020, 0x2021, 0x02C6, 0x2030, 0x0160, 0x2039, 0x0152, 0x008D, 0x017D, 0x008F,
569 0x0090, 0x2018, 0x2019, 0x201C, 0x201D, 0x2022, 0x2013, 0x2014, 0x02DC, 0x2122, 0x0161, 0x203A, 0x0153, 0x009D, 0x017E, 0x0178,
570 ];
571 if code == 0 || code > 0x10FFFF || (0xD800..=0xDFFF).contains(&code) {
572 return '\u{FFFD}';
573 }
574 if (0x80..=0x9F).contains(&code) {
575 let c = WIN1252.get((code - 0x80) as usize).copied().unwrap_or(code as u16);
576 return char::from_u32(c as u32).unwrap_or('\u{FFFD}');
577 }
578 char::from_u32(code).unwrap_or('\u{FFFD}')
579}
580
581pub fn parse_html(html: &str) -> Node {
584 parse_html_poll(html, || false)
585}
586
587pub const PARSE_HTML_POLL_EVERY: usize = 128;
589pub const PARSE_HTML_POLL_BYTES: usize = 64 * 1024;
591
592pub fn parse_html_app(html: &str) -> Node {
601 #[cfg(target_os = "none")]
602 return parse_html_poll(html, crate::kernel::window_mgr::layout_check);
603 #[cfg(not(target_os = "none"))]
604 parse_html(html)
605}
606
607pub fn parse_html_app_flat(html: &str) -> Node {
610 let (mut doc, _) = treebuilder::build_document(html, true, true, || false);
611 let pos = doc
612 .children
613 .iter()
614 .position(|c| matches!(&c.node_type, NodeType::Element { tag_name, .. } if tag_name == "html"));
615 match pos {
616 Some(i) => doc.children.swap_remove(i),
617 None => Node::new_element(String::from("html"), BTreeMap::new()),
618 }
619}
620
621pub const MAX_DOM_DEPTH: usize = 512;
627
628pub const MAX_DOM_NODES: usize = 60_000;
636
637#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
639pub struct ParseStats {
640 pub nodes: usize,
642 pub node_limit_hit: bool,
644 pub depth_capped: usize,
646 pub polled_out: bool,
648}
649
650pub fn parse_html_poll(html: &str, poll: impl FnMut() -> bool) -> Node {
653 parse_html_poll_counted(html, poll).0
654}
655
656pub fn parse_html_poll_counted(html: &str, poll: impl FnMut() -> bool) -> (Node, ParseStats) {
659 let html = html.strip_prefix('\u{FEFF}').unwrap_or(html);
666 let (mut doc, stats) = treebuilder::build_document_keep_implicit(html, true, true, poll);
667 let pos = doc
668 .children
669 .iter()
670 .position(|c| matches!(&c.node_type, NodeType::Element { tag_name, .. } if tag_name == "html"));
671 let root = match pos {
672 Some(i) => doc.children.swap_remove(i),
673 None => Node::new_element(String::from("html"), BTreeMap::new()),
674 };
675 (root, stats)
676}
677
678pub fn parse_html_document(html: &str) -> Node {
681 parse_html_document_with(html, true)
682}
683
684pub fn parse_html_document_with(html: &str, scripting: bool) -> Node {
686 treebuilder::build_document(html, false, scripting, || false).0
687}
688
689pub fn parse_html_fragment(context: &str, html: &str) -> Vec<Node> {
692 parse_html_fragment_with(context, html, true)
693}
694
695pub fn parse_html_fragment_with(context: &str, html: &str, scripting: bool) -> Vec<Node> {
697 treebuilder::build_fragment(context, html, false, scripting)
698}
699
700fn is_void_tag_name(name: &str) -> bool {
701 matches!(
702 name,
703 "br" | "hr"
704 | "img"
705 | "input"
706 | "meta"
707 | "link"
708 | "source"
709 | "area"
710 | "base"
711 | "col"
712 | "embed"
713 | "param"
714 | "track"
715 | "wbr"
716 )
717}