Skip to main content

atmos/os_lib/
dom.rs

1#![allow(dead_code)]
2// &str バイト境界スライス禁止はクレート全体で施錠済み(main.rs の deny(clippy::string_slice))。
3
4use 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
18/// `parse_html_document` が使う、コメント・DOCTYPE を表すノードのタグ名(`NodeType` に変種を足さない代わり)。
19pub const COMMENT_TAG: &str = "#comment";
20pub const DOCTYPE_TAG: &str = "#doctype";
21/// `parse_html_document` の木で、SVG / MathML の要素に付ける名前空間の印(属性名。値は `svg` か `math`)。
22pub 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    /// スタイル計算メモ化(`css::style_memo`)用の要素単体の特徴ハッシュ(タグ・id・class・属性)。
41    /// 生成時および属性書き換え時に計算しておき、`style_memo::node_features` が
42    /// 1 回の再レイアウトで要素あたり 3〜4 回 BTreeMap を再走査するのを防ぐ(TODO P5a)。
43    pub features_hash: (u64, u64),
44    /// 直接の子ノード列の形状(タグ・テキスト空判定・要素数)の 128 ビットハッシュ(TODO P5a)。
45    pub children_shape_hash: (u64, u64),
46    /// 自身の `features_hash` と子孫全体の `subtree_hash` を畳み込んだ 128 ビットハッシュ(TODO P5a)。
47    /// `:has()` や部分木スタイルメモ(`SubtreeStyleMemo`)の O(1) ルックアップに使用する。
48    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
83/// 直接の `children` 列から `children_shape_hash` を計算する(TODO P5a)。
84pub 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
94/// 自身の `features_hash` と直接の `children` が持つ `subtree_hash` から部分木ハッシュを計算する(TODO P5a)。
95pub 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
108/// 子が無い葉ノード時の `children_shape_hash` と `subtree_hash` を一括計算する。
109pub 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
116/// 要素 1 個の特徴(タグ・id・class・全属性)の 128 ビットハッシュ(FNV-1a 2 本)を計算する(TODO P5a)。
117pub 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    /// コメントを表すノード(`#comment` 要素。文字は属性 `data`)。`parse_html_document` の木だけに現れる。
159    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    /// DOCTYPE を表すノード(`#doctype` 要素。属性 `name`・`publicid`・`systemid`。無いものは属性なし)。
166    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    /// 直接の子ノードが最新ハッシュを持つ前提で自身の `children_shape_hash` と `subtree_hash` を O(children.len()) で更新する。
236    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    /// 子孫からボトムアップで `children_shape_hash` と `subtree_hash` を再計算する。
243    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    /// `node_type` の属性等を直接書き換えた後に自身と全子孫の `features_hash` / `children_shape_hash` / `subtree_hash` を再計算する。
251    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    /// 子を持たない `html` ルート要素を返す。`parse_html` が返すルートと同じ形状で、
260    /// DOM ブリッジを真実源とするインクリメンタル再レイアウト時、HTML パースを
261    /// 省略するためのプレースホルダとして使う(描画ツリーはブリッジから再構築される)。
262    pub fn empty_root() -> Self {
263        Node::new_element(String::from("html"), BTreeMap::new())
264    }
265
266    /// 要素の属性値を取得する。
267    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    /// W3C HTML5 §3.2.6.2 / DOMStringMap: `data-*` 属性から camelCase の dataset マップを抽出する。
279    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    /// W3C HTML5 §3.2.6.2: dataset プロパティを設定し、対応する `data-*` 属性を更新する。
288    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    /// W3C HTML5 §3.2.6.2: dataset プロパティを削除し、対応する `data-*` 属性を削除する。
304    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    /// ID による要素探索(深さ優先・最初に一致した参照を返す)。
321    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    /// クラス名による要素収集(深さ優先・ゼロアロケーション走査)。
343    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    /// タグ名による要素収集(大文字小文字無視)。
367    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    /// ツリー内の全テキストを連結して取得する(単一バッファ追記方式)。
391    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
412/// タグ名を取得するヘルパー
413fn 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
420// 文字参照の表(WHATWG HTML §13.5。生成物。`tests/html5lib_host/gen_entities.py` が作る)。2026-11-19
421mod html_entities {
422    include!("html_entities_data.rs");
423}
424
425/// 文字参照を復号する(データ状態・RCDATA の文字。WHATWG HTML §13.2.5.72〜80)。2026-11-19
426pub fn decode_entities(s: &str) -> String {
427    decode_entities_in(s, false)
428}
429
430/// 属性値の中の文字参照を復号する。§13.2.5.72 の「属性の中では、`;` なしの名前の直後が `=` か英数字なら復号しない」を含む。2026-11-19
431pub 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    // `&` の位置 i から 1 つずつ見る。`&` はいつも文字の境目にある(ASCII)ので、文字列の切り出しは安全。
444    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
475/// `&` の次のバイト列から文字参照を読む。戻り値は (読んだバイト数, 1 文字目, 2 文字目)。参照でなければ None(`&` をそのまま出す)。
476/// 1 文字目の None は使わない(常に Some)。
477pub(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    // §13.2.5.73 Named character reference state: 英数字の連なりを取り、`;` が続けば `;` つきの名前を試す。
486    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    // `;` なしの旧来の名前(最長 6 文字)の最長一致。`&noti;` → `¬` + `i;`。
496    let mut l = if run < 6 { run } else { 6 };
497    while l >= 2 {
498        if let Some(v) = entity_lookup(rest.get(..l)?) {
499            // 属性の中で、`;` なしの名前の直後が `=` か英数字なら復号しない(§13.2.5.73)。
500            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
520/// 表を二分探索する(名前は `;` つきなら `;` まで含む)。
521fn 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
540/// §13.2.5.75〜80 の数値文字参照。`&#` と `&#x` の後ろの数字を読み、`;` はあってもなくてもよい。数字が 1 つも無ければ参照ではない。
541fn 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        // 0x10FFFF を超えたら止める(あふれの防止。超えた値は U+FFFD になる)
550        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
564/// §13.2.5.80 Numeric character reference end state: 0・範囲外・サロゲートは U+FFFD、0x80〜0x9F は Windows-1252 の表で置き換える。
565/// 制御文字と非文字はそのまま(構文エラーだが文字は変えない)。
566fn 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
581// HTMLパーサ(WHATWG §13.2.5 トークナイザ + スタックベース木構築)
582/// 止める確かめを呼ばない版(錠を持ったまま呼ぶ所・背景のスレッド・自己試験で使う)。
583pub fn parse_html(html: &str) -> Node {
584    parse_html_poll(html, || false)
585}
586
587/// [`parse_html_poll`] が `poll` を呼ぶ間隔(ループの回数。2 の冪)。1 回はタグ 1 つか文字の塊 1 つ。
588pub const PARSE_HTML_POLL_EVERY: usize = 128;
589/// [`parse_html_poll`] が `poll` を呼ぶ間隔(読み進めたバイト数)。長い文字の塊・コメントが続くとき用。
590pub const PARSE_HTML_POLL_BYTES: usize = 64 * 1024;
591
592/// アプリのスレッドで、錠を持っていない所から呼ぶ HTML の解析(2026-11-18、TODO R2 (b) ②)。
593///
594/// 解析の途中で止める確かめ(`window_mgr::layout_check`)を呼ぶ。ウィンドウごと止める要求ならその中で終わる(戻らない)。
595/// このタブだけ止める合図なら、そこまでの木を返す(タブごと捨てられる。呼び出し側は合図を見てやめてよい)。
596/// 呼んでよい所: `parse_and_layout`(入口で `kill_checkpoint` を呼んでいる)と、JS の組み込み関数
597/// (`innerHTML`・`outerHTML`・`insertAdjacentHTML`・`createContextualFragment`・`DOMParser`。
598/// JS の処理系は同じ所で 32,768 ステップごとに `kill_checkpoint` を呼んでいる。持っているのは DOM の `RefCell` の借用だけ)。
599/// ローダーのスレッド(`ASYNC_LOAD` の錠の中)は確かめない [`parse_html`] を使う。ホストの試験では確かめない。
600pub 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
607/// `innerHTML`・`outerHTML`・`insertAdjacentHTML`・`createContextualFragment` の断片を、文書として解析して根の子を取る経路用
608/// (2026-11-28)。補った `head` / `body` の殻を外す(従来の形。[`parse_html_app`] は文書用で殻を残す)。
609pub 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
621/// 要素の入れ子の深さの上限(2026-11-18、TODO R5 (c))。Blink の HTML の木の組み立てと同じ 512。
622///
623/// これより深い開始タグは、開かずに(子を持たない要素として)今いちばん深い要素の子に付ける。中の文字は
624/// その深い要素の子になる。深さに比例して再帰する処理(木の解放・ハッシュの計算・DOM ブリッジ・スタイル・レイアウト)
625/// がスタックを使い切らないようにするため。
626pub const MAX_DOM_DEPTH: usize = 512;
627
628/// 1 回の解析で作るノード(要素と文字)の数の上限(2026-11-18、TODO R5 (c))。
629///
630/// 1 ノードは解析の木・DOM ブリッジ・描画用の木の写し・スタイルの木で合わせて約 2〜3KB を使う(属性の表 `BTreeMap` の葉だけで
631/// 約 540 バイト)。2MB の入れ子の多い HTML は約 27 万ノードになり、ヒープを 400MB 以上使っていた。20 万ノードでも
632/// スタイルの計算に 60 秒より長くかかり、ヒープは 590MB まで増えた(QEMU)。描く要素は `MAX_RENDER_ELEMENTS`(2 万個)で
633/// 打ち切るので、それより先のノードは画面に出ない。上限を超えたらそこで読むのをやめ、そこまでの木を返す
634/// (ページの後ろが表示されない。ブラウザは落ちない)。ふつうのページ(大きなニュース・百科事典の記事でも 1〜5 万ノード)は届かない。
635pub const MAX_DOM_NODES: usize = 60_000;
636
637/// [`parse_html_poll_counted`] の結果の数。
638#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
639pub struct ParseStats {
640    /// 作ったノードの数(根の `html` は数えない)。
641    pub nodes: usize,
642    /// [`MAX_DOM_NODES`] に届いて、残りを読まなかったか。
643    pub node_limit_hit: bool,
644    /// [`MAX_DOM_DEPTH`] より深いために開かなかった開始タグの数。
645    pub depth_capped: usize,
646    /// `poll` が真を返して途中でやめたか。
647    pub polled_out: bool,
648}
649
650/// [`parse_html`] に、[`PARSE_HTML_POLL_EVERY`] 回か [`PARSE_HTML_POLL_BYTES`] バイトごとに `poll` を呼ぶ口を付けたもの
651/// (2026-11-18、TODO R2 (b) ②)。`poll` が `true` を返したら、そこまでの木(開いたままのタグは閉じたものとして扱う)を返す。
652pub fn parse_html_poll(html: &str, poll: impl FnMut() -> bool) -> Node {
653    parse_html_poll_counted(html, poll).0
654}
655
656/// [`parse_html_poll`] に、作ったノードの数・上限に届いたかを添えて返す版(2026-11-18、TODO R5 (c))。
657/// 深さの上限 [`MAX_DOM_DEPTH`] とノードの数の上限 [`MAX_DOM_NODES`] はどの呼び出しにも効く。
658pub fn parse_html_poll_counted(html: &str, poll: impl FnMut() -> bool) -> (Node, ParseStats) {
659    // 【2026-11-19 TODO S3】WHATWG §13.2.6 の木構築(`dom_treebuilder.rs`)。暗黙の html / head / body を補い、
660    // 書式要素の養子縁組・表の foster parenting を行う。ブラウザ用の整形(文字の空白のたたみ・コメント / DOCTYPE を
661    // 木に入れない)を `compat = true` で行う。返す根は文書の `html` 要素。
662    // 先頭の BOM(U+FEFF)は文字にしない(Encoding Standard の decode は BOM を取り除く。HTML §13.2.3.1)。
663    // 【2026-11-28】本文は UTF-8 の文字列として受け取るので BOM が残り、文書の最初に文字があるものとして組まれて
664    // body の既定の余白が消えていた(WPT css の 454 件が BOM 付き。css-flexbox align-content-001 ほか)。
665    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
678/// 文書全体を仕様どおり(文字・コメント・DOCTYPE をそのまま残して)解析し、`#document` ノードを返す。
679/// 子は DOCTYPE・コメント・`html` 要素。html5lib / WPT の木構築試験用(ブラウザは [`parse_html`] を使う)。
680pub fn parse_html_document(html: &str) -> Node {
681    parse_html_document_with(html, true)
682}
683
684/// [`parse_html_document`] の、スクリプトが無効(`<noscript>` の中身を木にする)かどうかを選べる版。
685pub fn parse_html_document_with(html: &str, scripting: bool) -> Node {
686    treebuilder::build_document(html, false, scripting, || false).0
687}
688
689/// 断片の解析(WHATWG §13.4)。`context` は文脈要素名(`td`・`svg path` など)。文脈要素の子になるノード列を返す。
690/// 仕様どおりの木(文字・コメントをそのまま残す)。html5lib / WPT の `#document-fragment` 試験用。
691pub fn parse_html_fragment(context: &str, html: &str) -> Vec<Node> {
692    parse_html_fragment_with(context, html, true)
693}
694
695/// [`parse_html_fragment`] の、スクリプトが無効かどうかを選べる版。
696pub 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}