muskitty-html5-parser 0.2.1

A from-scratch HTML5 parser implementing the WHATWG HTML Living Standard
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
//! Tree construction helper algorithms.
//!
//! These functions implement the "insert a node", "create an element",
//! and related algorithms from WHATWG §13.2.6.2. They are used by the
//! insertion mode handlers in [`super::dispatch`].

use std::cell::RefCell;
use std::rc::{Rc, Weak};

use muskitty_dom::{append_child, Attribute, Node, NodeKind, NodeType};

use super::ActiveFormattingEntry;
use super::HtmlTreeConstructor;
use super::SelectSelectedcontentMemo;
use super::SelectSelectednessMemo;
use super::SelectedcontentLookup;
use crate::error::ParseError;
use muskitty_html5_tokenizer::TagToken;

/// Create an Element node for a start tag token.
///
/// Implements "create an element for the token" (§13.2.6.2) in a simplified
/// form: always uses the HTML namespace, no custom element definitions, no
/// attribute adjustment. Full foreign-attribute adjustment (§13.2.6.5) is
/// deferred to Phase 3.
///
/// Per §13.2.6.2, when creating a `<template>` element a DocumentFragment is
/// also created and attached as the template's content. All nodes inserted
/// while the template is the current node go into this content fragment.
pub fn create_element_for_token(
    parser: &HtmlTreeConstructor,
    token: &TagToken,
) -> Rc<RefCell<Node>> {
    let attrs: Vec<Attribute> = token
        .attrs
        .iter()
        .map(|(name, value)| Attribute::new(name, value))
        .collect();
    let element = Node::new_element_html(&token.name, attrs, &parser.document);
    if token.name == "template" {
        let content = Node::new_document_fragment(&parser.document);
        if let NodeKind::Element(ref mut e) = element.borrow_mut().kind {
            e.set_template_content(content);
        }
    }
    // WHATWG §4.10.10: option's selectedness is initially true if the
    // element has a `selected` attribute. (The selectedness setting
    // algorithm may later adjust this.)
    if token.name == "option" {
        let has_selected = token
            .attrs
            .iter()
            .any(|(k, _)| k.eq_ignore_ascii_case("selected"));
        if has_selected {
            if let NodeKind::Element(ref mut e) = element.borrow_mut().kind {
                e.selectedness = true;
            }
        }
    }
    element
}

/// Determine the target node for insertion per §13.2.6.2.
///
/// If the current node is a `<template>` element, returns the template's
/// content DocumentFragment; otherwise returns the current node itself.
/// Foster parenting is handled separately by the caller via `foster_parent`.
fn insertion_target(parser: &HtmlTreeConstructor) -> Rc<RefCell<Node>> {
    let current = parser.current_node();
    let target = {
        let current_ref = current.borrow();
        match &current_ref.kind {
            NodeKind::Element(e) if e.local_name == "template" => e.template_content.clone(),
            _ => None,
        }
    };
    target.unwrap_or_else(|| current.clone())
}

/// Check whether foster parenting should actually apply for the current
/// insertion. Per §13.2.6.3, foster parenting only takes effect when the
/// foster-parenting flag is enabled **and** the target (current node) is a
/// `table`, `tbody`, `tfoot`, `thead`, or `tr` element. If the current
/// node is some other element (e.g. a `<plaintext>` that was foster-parented
/// onto the stack before a table), normal insertion applies.
fn foster_parenting_active(parser: &HtmlTreeConstructor) -> bool {
    if !parser.foster_parenting {
        return false;
    }
    parser
        .open_elements
        .last()
        .and_then(|n| {
            n.borrow().kind.as_element().map(|e| {
                matches!(
                    e.local_name.as_str(),
                    "table" | "tbody" | "tfoot" | "thead" | "tr"
                )
            })
        })
        .unwrap_or(false)
}

/// A foster-parenting insertion location (§13.2.6.2).
enum FosterLocation {
    /// Append to the end of this node's children.
    Append(Rc<RefCell<Node>>),
    /// Insert before `before` within `parent`.
    Before {
        parent: Rc<RefCell<Node>>,
        before: Rc<RefCell<Node>>,
    },
}

/// Compute the foster-parenting insertion location per §13.2.6.2.
///
/// Implements the full algorithm:
/// 1. Find the last `template` and last `table` in the stack.
/// 2. If `template` exists and is above `table` (or no table): insert into
///    template's template contents.
/// 3. If no `table`: insert into the first element (html) — fragment case.
/// 4. If `table` has a parent: insert before `table`.
/// 5. Otherwise: insert into the element above `table`.
fn foster_parent_location(parser: &HtmlTreeConstructor) -> FosterLocation {
    // Find last template and last table indices (searching from top).
    let last_template_idx = parser
        .open_elements
        .iter()
        .enumerate()
        .rev()
        .find(|(_, n)| {
            n.borrow()
                .kind
                .as_element()
                .map(|e| e.local_name == "template")
                .unwrap_or(false)
        })
        .map(|(i, _)| i);

    let last_table_idx = parser
        .open_elements
        .iter()
        .enumerate()
        .rev()
        .find(|(_, n)| {
            n.borrow()
                .kind
                .as_element()
                .map(|e| e.local_name == "table")
                .unwrap_or(false)
        })
        .map(|(i, _)| i);

    // Step 2c: If last_template exists and (no last_table or last_template
    // is above last_table), insert into last_template's template contents.
    if let Some(tmpl_idx) = last_template_idx {
        let template_above_table = match last_table_idx {
            Some(tbl_idx) => tmpl_idx > tbl_idx,
            None => true,
        };
        if template_above_table {
            let template = &parser.open_elements[tmpl_idx];
            let content = template
                .borrow()
                .kind
                .as_element()
                .and_then(|e| e.template_content.clone())
                .unwrap_or_else(|| template.clone());
            return FosterLocation::Append(content);
        }
    }

    // Step 2d: If no last_table, insert into first element (html).
    // (fragment case)
    if last_table_idx.is_none() {
        let html = parser
            .open_elements
            .first()
            .cloned()
            .unwrap_or_else(|| parser.document.clone());
        return FosterLocation::Append(html);
    }

    // Step 2e: If last_table has a parent, insert before last_table.
    let table_idx = last_table_idx.unwrap();
    let table_node = parser.open_elements[table_idx].clone();
    let table_parent = table_node.borrow().parent_node.upgrade();
    if let Some(parent) = table_parent {
        return FosterLocation::Before {
            parent,
            before: table_node,
        };
    }

    // Step 2f: Insert into the element above last_table.
    if table_idx > 0 {
        let prev = parser.open_elements[table_idx - 1].clone();
        return FosterLocation::Append(prev);
    }

    // Fallback: append to current node.
    FosterLocation::Append(parser.current_node())
}

/// 将元素 push 到 open elements 栈,执行深度限制检查。
///
/// 超过 `max_open_elements` 时跳过 push 并记录 `ParseError::DomDepthExceeded`,
/// 解析继续(参考 WHATWG §13.2.6 错误恢复语义:parser 不应因资源限制而崩溃)。
///
/// 注意:跳过 push 意味着后续的 end tag 可能匹配错误节点,但这是降级可接受代价
/// ——浏览器在超深嵌套时也会进入类似的退化模式。
pub fn push_open_element(parser: &mut HtmlTreeConstructor, node: Rc<RefCell<Node>>) {
    // P-1:selectedcontent 插入树后(insert_node 先于本函数),刷新其
    // 所属 select 的查找备忘录,令 option pop 钩子的 selectedcontent
    // 查找维持 O(1)。放在深度检查前:超深跳过 push 时节点已在树中,
    // 备忘录同样需要更新。解析器只 append——树序首个 selectedcontent
    // 一旦存在即不变,故 Absent→Present 单向翻转、Present 保持首个。
    let is_selectedcontent = node
        .borrow()
        .kind
        .as_element()
        .map(|e| e.namespace == muskitty_dom::Namespace::Html && e.local_name == "selectedcontent")
        .unwrap_or(false);
    if is_selectedcontent {
        if let Some(select) = find_nearest_ancestor_select(&node) {
            let already_present = parser
                .select_selectedcontent_memo
                .as_ref()
                .and_then(|m| m.select.upgrade())
                .is_some_and(|s| Rc::ptr_eq(&s, &select))
                && matches!(
                    parser.select_selectedcontent_memo.as_ref().unwrap().lookup,
                    SelectedcontentLookup::Present(_)
                );
            if !already_present {
                parser.select_selectedcontent_memo = Some(SelectSelectedcontentMemo {
                    select: Rc::downgrade(&select),
                    lookup: SelectedcontentLookup::Present(Rc::downgrade(&node)),
                });
            }
        }
    }
    if parser.open_elements.len() >= parser.max_open_elements {
        parser.errors.push(ParseError::DomDepthExceeded {
            depth: parser.open_elements.len(),
            limit: parser.max_open_elements,
        });
        return;
    }
    parser.open_elements.push(node);
}

/// Insert a node at the appropriate place for inserting a node (§13.2.6.2).
///
/// When foster parenting is active (§13.2.6.3), the node is inserted at
/// the foster parenting position per the full algorithm in §13.2.6.2.
/// Otherwise, the node is appended to the current node (or template content
/// if current node is a `<template>`).
pub fn insert_node(parser: &HtmlTreeConstructor, node: &Rc<RefCell<Node>>) {
    if foster_parenting_active(parser) {
        match foster_parent_location(parser) {
            FosterLocation::Append(parent) => {
                let _ = append_child(&parent, node.clone());
            }
            FosterLocation::Before { parent, before } => {
                let _ = muskitty_dom::insert_before(&parent, node.clone(), Some(&before));
            }
        }
    } else {
        let target = insertion_target(parser);
        let _ = append_child(&target, node.clone());
    }
}

/// Create an element for the token, insert it, and push it onto the open
/// elements stack.
///
/// This is the common "insert an element" sequence used by most insertion
/// modes when they encounter a start tag. Currently unused by the skeleton
/// handlers (which use `create_and_push` for attribute-less elements); the
/// InBody batch in Phase 3.2 will route start-tag handling through this.
#[allow(dead_code)]
pub fn insert_element(parser: &mut HtmlTreeConstructor, token: &TagToken) {
    let element = create_element_for_token(parser, token);
    insert_node(parser, &element);
    push_open_element(parser, element.clone());
    // WHATWG §4.10.10: option HTML element insertion steps — run update
    // an option's nearest ancestor select, which fires the selectedness
    // setting algorithm on the ancestor select (if any).
    let is_option = element
        .borrow()
        .kind
        .as_element()
        .map(|e| e.namespace == muskitty_dom::Namespace::Html && e.local_name == "option")
        .unwrap_or(false);
    if is_option {
        on_option_inserted_with_memo(parser, &element);
    }
}

/// Insert a character token at the current node.
///
/// Per §13.2.6.2, if the current node's last child is a Text node, the
/// character is appended to that Text node's data. Otherwise, a new Text
/// node is created and inserted.
///
/// If the current node is a `<template>`, the character is inserted into
/// the template's content DocumentFragment (via `insertion_target`).
///
/// When foster parenting is active (§13.2.6.3), the character is inserted
/// at the foster parenting position per the full algorithm in §13.2.6.2.
/// If the previous sibling (for "before table") or last child (for "append")
/// is a Text node, the character is appended to it.
pub fn insert_character(parser: &HtmlTreeConstructor, c: char) {
    if foster_parenting_active(parser) {
        match foster_parent_location(parser) {
            FosterLocation::Before { parent, before } => {
                // Find the previous sibling of the table node.
                let prev_sibling = {
                    let parent_node = parent.borrow();
                    let idx = parent_node
                        .child_nodes()
                        .iter()
                        .position(|n| Rc::ptr_eq(n, &before));
                    idx.and_then(|i| {
                        if i > 0 {
                            Some(parent_node.child_nodes()[i - 1].clone())
                        } else {
                            None
                        }
                    })
                };
                if let Some(prev) = prev_sibling {
                    if prev.borrow().node_type == NodeType::Text {
                        if let NodeKind::Text(ref mut t) = prev.borrow_mut().kind {
                            t.data.push(c);
                            return;
                        }
                    }
                }
                let text = Node::new_text(&c.to_string(), &parser.document);
                let _ = muskitty_dom::insert_before(&parent, text, Some(&before));
            }
            FosterLocation::Append(parent) => {
                let last_child = parent.borrow().last_child();
                if let Some(child) = last_child {
                    if child.borrow().node_type == NodeType::Text {
                        if let NodeKind::Text(ref mut t) = child.borrow_mut().kind {
                            t.data.push(c);
                            return;
                        }
                    }
                }
                let text = Node::new_text(&c.to_string(), &parser.document);
                let _ = append_child(&parent, text);
            }
        }
        return;
    }
    let target = insertion_target(parser);
    let last_child = target.borrow().last_child();
    if let Some(child) = last_child {
        let is_text = child.borrow().node_type == NodeType::Text;
        if is_text {
            if let NodeKind::Text(ref mut t) = child.borrow_mut().kind {
                t.data.push(c);
                return;
            }
        }
    }
    let text = Node::new_text(&c.to_string(), &parser.document);
    let _ = append_child(&target, text);
}

/// Insert a comment node as a child of the current node.
///
/// Per §13.2.6.2, the exact insertion point depends on the insertion mode
/// (some modes insert comments at the Document, others at the html element).
/// This helper always inserts at the current node; insertion modes that
/// need a different target should use [`insert_comment_at`] instead.
pub fn insert_comment(parser: &HtmlTreeConstructor, data: &str) {
    let comment = Node::new_comment(data, &parser.document);
    insert_node(parser, &comment);
}

/// Insert a comment node as a child of the specified target node.
///
/// Used by insertion modes that require comments to go to a specific node
/// (e.g., Document or html element) rather than the current node.
pub fn insert_comment_at(target: &Rc<RefCell<Node>>, data: &str, document: &Rc<RefCell<Node>>) {
    let comment = Node::new_comment(data, document);
    let _ = append_child(target, comment);
}

/// Insert a ProcessingInstruction node at the adjusted insertion location
/// (§13.2.6.2 "insert a processing instruction").
///
/// Per the spec, a ProcessingInstruction node with the token's target and
/// data is created and inserted at the same location a comment would go.
/// Foster parenting applies as normal for `insert_node`.
pub fn insert_processing_instruction(parser: &HtmlTreeConstructor, target: &str, data: &str) {
    let pi = Node::new_processing_instruction(target, data, &parser.document);
    insert_node(parser, &pi);
}

/// Insert a ProcessingInstruction node as a child of the specified target
/// node (variant of `insert_comment_at` for PI tokens emitted before the
/// html element exists, e.g. in Initial/BeforeHtml modes).
pub fn insert_processing_instruction_at(
    target: &Rc<RefCell<Node>>,
    target_name: &str,
    data: &str,
    document: &Rc<RefCell<Node>>,
) {
    let pi = Node::new_processing_instruction(target_name, data, document);
    let _ = append_child(target, pi);
}

// ── Quirks mode detection (§13.2.6.4.1) ────────────────────────

/// ASCII case-insensitive "starts with" check (§13.2.6.4.1 line 3165
/// requires ASCII case-insensitive comparison of public/system IDs).
fn ascii_starts_with(haystack: &str, needle: &str) -> bool {
    if needle.len() > haystack.len() {
        return false;
    }
    haystack[..needle.len()].eq_ignore_ascii_case(needle)
}

/// Public identifiers whose exact value (ASCII case-insensitive) triggers
/// quirks mode (§13.2.6.4.1, the first list, exact-match entries).
const QUIRKS_PUBLIC_ID_EXACT: &[&str] = &[
    "-//W3O//DTD W3 HTML Strict 3.0//EN//",
    "-/W3C/DTD HTML 4.0 Transitional/EN",
    "HTML",
];

/// The single system identifier whose exact value triggers quirks mode
/// (§13.2.6.4.1, the first list).
const QUIRKS_SYSTEM_ID_EXACT: &str = "http://www.ibm.com/data/dtd/v11/ibmxhtml1-transitional.dtd";

/// Public identifier prefixes that trigger quirks mode
/// (§13.2.6.4.1, the first list, "starts with" entries).
const QUIRKS_PUBLIC_ID_PREFIX: &[&str] = &[
    "+//Silmaril//dtd html Pro v0r11 19970101//",
    "-//AS//DTD HTML 3.0 asWedit + extensions//",
    "-//AdvaSoft Ltd//DTD HTML 3.0 asWedit + extensions//",
    "-//IETF//DTD HTML 2.0 Level 1//",
    "-//IETF//DTD HTML 2.0 Level 2//",
    "-//IETF//DTD HTML 2.0 Strict Level 1//",
    "-//IETF//DTD HTML 2.0 Strict Level 2//",
    "-//IETF//DTD HTML 2.0 Strict//",
    "-//IETF//DTD HTML 2.0//",
    "-//IETF//DTD HTML 2.1E//",
    "-//IETF//DTD HTML 3.0//",
    "-//IETF//DTD HTML 3.2 Final//",
    "-//IETF//DTD HTML 3.2//",
    "-//IETF//DTD HTML 3//",
    "-//IETF//DTD HTML Level 0//",
    "-//IETF//DTD HTML Level 1//",
    "-//IETF//DTD HTML Level 2//",
    "-//IETF//DTD HTML Level 3//",
    "-//IETF//DTD HTML Strict Level 0//",
    "-//IETF//DTD HTML Strict Level 1//",
    "-//IETF//DTD HTML Strict Level 2//",
    "-//IETF//DTD HTML Strict Level 3//",
    "-//IETF//DTD HTML Strict//",
    "-//IETF//DTD HTML//",
    "-//Metrius//DTD Metrius Presentational//",
    "-//Microsoft//DTD Internet Explorer 2.0 HTML Strict//",
    "-//Microsoft//DTD Internet Explorer 2.0 HTML//",
    "-//Microsoft//DTD Internet Explorer 2.0 Tables//",
    "-//Microsoft//DTD Internet Explorer 3.0 HTML Strict//",
    "-//Microsoft//DTD Internet Explorer 3.0 HTML//",
    "-//Microsoft//DTD Internet Explorer 3.0 Tables//",
    "-//Netscape Comm. Corp.//DTD HTML//",
    "-//Netscape Comm. Corp.//DTD Strict HTML//",
    "-//O'Reilly and Associates//DTD HTML 2.0//",
    "-//O'Reilly and Associates//DTD HTML Extended 1.0//",
    "-//O'Reilly and Associates//DTD HTML Extended Relaxed 1.0//",
    "-//SQ//DTD HTML 2.0 HoTMetaL + extensions//",
    "-//SoftQuad Software//DTD HoTMetaL PRO 6.0::19990601::extensions to HTML 4.0//",
    "-//SoftQuad//DTD HoTMetaL PRO 4.0::19971010::extensions to HTML 4.0//",
    "-//Spyglass//DTD HTML 2.0 Extended//",
    "-//Sun Microsystems Corp.//DTD HotJava HTML//",
    "-//Sun Microsystems Corp.//DTD HotJava Strict HTML//",
    "-//W3C//DTD HTML 3 1995-03-24//",
    "-//W3C//DTD HTML 3.2 Draft//",
    "-//W3C//DTD HTML 3.2 Final//",
    "-//W3C//DTD HTML 3.2//",
    "-//W3C//DTD HTML 3.2S Draft//",
    "-//W3C//DTD HTML 4.0 Frameset//",
    "-//W3C//DTD HTML 4.0 Transitional//",
    "-//W3C//DTD HTML Experimental 19960712//",
    "-//W3C//DTD HTML Experimental 970421//",
    "-//W3C//DTD W3 HTML//",
    "-//W3O//DTD W3 HTML 3.0//",
    "-//WebTechs//DTD Mozilla HTML 2.0//",
    "-//WebTechs//DTD Mozilla HTML//",
];

/// Public identifier prefixes that trigger quirks mode only when the system
/// identifier is missing or the empty string (§13.2.6.4.1, first list).
const QUIRKS_PUBLIC_ID_PREFIX_WHEN_SYS_MISSING: &[&str] = &[
    "-//W3C//DTD HTML 4.01 Frameset//",
    "-//W3C//DTD HTML 4.01 Transitional//",
];

/// Detect whether a DOCTYPE token puts the Document into quirks mode,
/// per §13.2.6.4.1 (the "force-quirks" / public-id / system-id checks).
///
/// Returns `true` for full quirks mode. Limited-quirks mode is not tracked
/// separately because no implemented insertion-mode rule distinguishes it
/// from no-quirks (the only current consumer — InBody `<table>` closing `<p>`
/// — treats limited-quirks as "not quirks").
pub fn detect_quirks_mode(
    force_quirks: bool,
    name: Option<&str>,
    public_id: Option<&str>,
    system_id: Option<&str>,
) -> bool {
    // force-quirks flag, or name is not "html".
    if force_quirks || name != Some("html") {
        return true;
    }
    let pid = public_id.unwrap_or("");
    let sid = system_id.unwrap_or("");
    let sid_missing_or_empty = system_id.map(|s| s.is_empty()).unwrap_or(true);

    // Exact public identifier matches.
    if QUIRKS_PUBLIC_ID_EXACT
        .iter()
        .any(|p| pid.eq_ignore_ascii_case(p))
    {
        return true;
    }
    // Exact system identifier match.
    if sid.eq_ignore_ascii_case(QUIRKS_SYSTEM_ID_EXACT) {
        return true;
    }
    // Public identifier prefix matches.
    if QUIRKS_PUBLIC_ID_PREFIX
        .iter()
        .any(|p| ascii_starts_with(pid, p))
    {
        return true;
    }
    // System identifier missing/empty + public identifier prefix.
    if sid_missing_or_empty
        && QUIRKS_PUBLIC_ID_PREFIX_WHEN_SYS_MISSING
            .iter()
            .any(|p| ascii_starts_with(pid, p))
    {
        return true;
    }
    false
}

// ── Open elements stack helpers (§13.2.6.4.2) ─────────────────

/// The default scope set per §13.2.6.4.2. An element is "in scope" if it
/// appears on the open elements stack before any of these boundary names.
///
/// Per §13.2.6.4.2, the default scope boundary set includes both HTML
/// elements and MathML/SVG integration-point elements:
/// applet, caption, html, table, td, th, marquee, object, template,
/// mi, mo, mn, ms, mtext, annotation-xml, foreignObject, desc, title.
///
/// Note: boundary matching is namespace-agnostic — the spec compares tag
/// names only. For SVG, `foreignObject`/`desc`/`title` keep their case in
/// `local_name`; the boundary check lowercases both sides.
const DEFAULT_SCOPE: &[&str] = &[
    "applet",
    "caption",
    "html",
    "table",
    "td",
    "th",
    "marquee",
    "object",
    "template",
    // MathML text integration points.
    "mi",
    "mo",
    "mn",
    "ms",
    "mtext",
    "annotation-xml",
    // HTML integration points (SVG).
    "foreignobject",
    "desc",
    "title",
];

/// The list scope set: default scope + `ol` + `ul` (§13.2.6.4.2).
const LIST_SCOPE_EXTRA: &[&str] = &["ol", "ul"];

/// Return the local name (lowercase tag name) of an open element, or `None`
/// if the node is not an HTML-namespace element.
fn html_local_name(node: &Rc<RefCell<Node>>) -> Option<String> {
    let n = node.borrow();
    if let NodeKind::Element(ref e) = n.kind {
        if e.namespace == muskitty_dom::Namespace::Html {
            return Some(e.local_name.clone());
        }
    }
    None
}

/// Return the local name of an open element regardless of namespace,
/// lowercased for boundary comparison (§13.2.6.4.2). Used by scope checks
/// so that MathML/SVG integration-point elements (mi, mo, foreignObject,
/// etc.) act as scope boundaries.
fn local_name_for_boundary(node: &Rc<RefCell<Node>>) -> Option<String> {
    let n = node.borrow();
    if let NodeKind::Element(ref e) = n.kind {
        return Some(e.local_name.to_ascii_lowercase());
    }
    None
}

/// Check whether an element with the given tag name is in scope (§13.2.6.4.2
/// "default scope").
pub fn has_element_in_scope(parser: &HtmlTreeConstructor, name: &str) -> bool {
    has_element_in_scope_with(parser, name, DEFAULT_SCOPE, &[])
}

/// Check whether an element with the given tag name is in *button scope*
/// (default scope + `button`).
pub fn has_element_in_button_scope(parser: &HtmlTreeConstructor, name: &str) -> bool {
    has_element_in_scope_with(parser, name, DEFAULT_SCOPE, &["button"])
}

/// Check whether an element with the given tag name is in *list scope*
/// (default scope + `ol` + `ul`).
pub fn has_element_in_list_scope(parser: &HtmlTreeConstructor, name: &str) -> bool {
    has_element_in_scope_with(parser, name, DEFAULT_SCOPE, LIST_SCOPE_EXTRA)
}

/// The table scope set (§13.2.6.4.2): only `html`, `table`, `template`.
const TABLE_SCOPE: &[&str] = &["html", "table", "template"];

/// Check whether an element with the given tag name is in *table scope*
/// (§13.2.6.4.2: boundary set = `html` + `table` + `template`).
pub fn has_element_in_table_scope(parser: &HtmlTreeConstructor, name: &str) -> bool {
    for node in parser.open_elements.iter().rev() {
        let local = match html_local_name(node) {
            Some(l) => l,
            None => continue,
        };
        if local == name {
            return true;
        }
        if TABLE_SCOPE.contains(&local.as_str()) {
            return false;
        }
    }
    false
}

/// Check whether an element with the given tag name is on the stack of
/// open elements (no scope boundaries — just a plain stack search).
/// Used by `</template>` handling per §13.2.6.4.5.
pub fn has_element_in_stack(parser: &HtmlTreeConstructor, name: &str) -> bool {
    parser
        .open_elements
        .iter()
        .any(|n| html_local_name(n).as_deref() == Some(name))
}

/// Close a list item (`<li>`) or definition term (`<dd>`/`<dt>`) per the
/// loop algorithm in §13.2.6.4.7.
///
/// Walks the stack of open elements from top to bottom. If any of the
/// `targets` is found, generates implied end tags except for that element,
/// then pops until that element is popped. The walk stops early if a
/// special element that is not `address`, `div`, or `p` is encountered.
///
/// For `<li>`, pass `&["li"]`. For `<dd>`/`<dt>`, pass `&["dd", "dt"]`
/// (the spec checks for both regardless of which start tag triggered it).
///
/// Returns `true` if a target was found and popped; `false` otherwise.
pub fn close_list_item(parser: &mut HtmlTreeConstructor, targets: &[&str]) -> bool {
    // Walk from top of stack downward.
    for i in (0..parser.open_elements.len()).rev() {
        let local = match html_local_name(&parser.open_elements[i]) {
            Some(l) => l,
            None => continue,
        };
        let target = targets.iter().find(|t| local == **t);
        if let Some(target) = target {
            let target = target.to_string();
            // Found the target. Generate implied end tags except for target.
            generate_implied_end_tags(parser, Some(&target));
            // If current node is not target, parse error.
            let current_is_target = parser
                .open_elements
                .last()
                .and_then(html_local_name)
                .map(|l| l == target)
                .unwrap_or(false);
            if !current_is_target {
                parser
                    .errors
                    .push(ParseError::Generic("list item not at current node"));
            }
            // Pop until target is popped.
            while let Some(top) = parser.open_elements.last() {
                let top_name = html_local_name(top);
                parser.open_elements.pop();
                if top_name.as_deref() == Some(target.as_str()) {
                    break;
                }
            }
            return true;
        }
        // If node is special but not address/div/p, stop.
        if SPECIAL_ELEMENTS.contains(&local.as_str())
            && !matches!(local.as_str(), "address" | "div" | "p")
        {
            return false;
        }
        // Otherwise: continue to previous entry.
    }
    false
}

fn has_element_in_scope_with(
    parser: &HtmlTreeConstructor,
    name: &str,
    base_scope: &[&str],
    extra: &[&str],
) -> bool {
    for node in parser.open_elements.iter().rev() {
        // Target match: only HTML-namespace elements match the search name.
        // (All callers search for HTML element names like "p", "body",
        // "select".)
        if html_local_name(node).as_deref() == Some(name) {
            return true;
        }
        // Boundary check: namespace-agnostic. Foreign integration-point
        // elements (mi, mo, mn, ms, mtext, annotation-xml, foreignObject,
        // desc, title) act as scope boundaries per §13.2.6.4.2.
        let boundary_local = match local_name_for_boundary(node) {
            Some(l) => l,
            None => continue,
        };
        if base_scope.contains(&boundary_local.as_str()) || extra.contains(&boundary_local.as_str())
        {
            return false;
        }
    }
    false
}

/// Generate implied end tags (§13.2.6.4.1).
///
/// Pop nodes from the open elements stack while the current node's name is
/// one of the implied-end-tag names. If `except` is `Some(name)`, that name
/// is not treated as an implied end tag (used by `</p>`/`</li>`/`</dd>`/`</dt>`
/// handling to avoid popping the target element prematurely).
pub fn generate_implied_end_tags(parser: &mut HtmlTreeConstructor, except: Option<&str>) {
    const IMPLIED_END: &[&str] = &[
        "dd", "dt", "li", "optgroup", "option", "p", "rb", "rp", "rt", "rtc",
    ];
    loop {
        let top_name = parser.open_elements.last().and_then(html_local_name);
        match top_name.as_deref() {
            Some(n) if IMPLIED_END.contains(&n) && Some(n) != except => {
                pop_open_element(parser);
            }
            _ => break,
        }
    }
}

/// Pop the top element from the stack of open elements, firing the
/// "maybe clone an option into selectedcontent" hook (§4.10.10) if the
/// popped element is an `<option>`.
pub fn pop_open_element(parser: &mut HtmlTreeConstructor) -> Option<Rc<RefCell<Node>>> {
    let node = parser.open_elements.pop();
    if let Some(ref n) = node {
        let is_option = n
            .borrow()
            .kind
            .as_element()
            .map(|e| e.namespace == muskitty_dom::Namespace::Html && e.local_name == "option")
            .unwrap_or(false);
        if is_option {
            maybe_clone_option_into_selectedcontent(parser, n);
        }
    }
    node
}

/// "Close a p element" (§13.2.6.4.7).
///
/// Generate implied end tags for `p`; if the current node is not `p`, it is
/// a parse error. Pop nodes from the open elements stack until a `p` has
/// been popped. Stops at the `<html>` element as a safety net so a missing
/// `p` never empties the stack.
pub fn close_p_element(parser: &mut HtmlTreeConstructor) {
    generate_implied_end_tags(parser, Some("p"));
    // Per spec, current node should be p here; if not, parse error (ignored
    // in the skeleton — we still pop until p is gone).
    while let Some(top) = parser.open_elements.last() {
        let local = html_local_name(top);
        // Safety net: never pop past <html>.
        if local.as_deref() == Some("html") {
            break;
        }
        let is_p = local.as_deref() == Some("p");
        parser.open_elements.pop();
        if is_p {
            break;
        }
    }
}

/// "Push onto the list of active formatting elements" (§13.2.6.2).
///
/// Adds `element` to the list of active formatting elements, applying the
/// Noah's Ark clause: if there are already three entries in the list (after
/// the last marker) that are elements with the same tag name, namespace, and
/// attributes as `element`, the earliest such entry is dropped before pushing.
pub fn push_formatting_element(parser: &mut HtmlTreeConstructor, element: Rc<RefCell<Node>>) {
    // Noah's Ark clause (§13.2.4.3): if there are already 3 elements in the
    // list after the last marker (or anywhere if no marker) that have the
    // same tag name, namespace, and attributes as `element`, remove the
    // earliest such element before pushing.
    //
    // We iterate in reverse (from the end toward the last marker). The
    // first match found is the latest in list order; the third match is
    // the earliest. Per spec, we remove the earliest.
    let mut count = 0;
    let mut earliest_match_index: Option<usize> = None;
    for (i, entry) in parser.active_formatting_elements.iter().enumerate().rev() {
        match entry {
            ActiveFormattingEntry::Marker => break,
            ActiveFormattingEntry::Element(e) => {
                if elements_match_for_noahs_ark(e, &element) {
                    count += 1;
                    earliest_match_index = Some(i);
                    if count == 3 {
                        break;
                    }
                }
            }
        }
    }
    if count >= 3 {
        if let Some(idx) = earliest_match_index {
            parser.active_formatting_elements.remove(idx);
        }
    }
    // F-7(审计 P2):列表硬上限。超限移除最后一个 marker 之后的最早
    // 元素(与 Noah's Ark 同作用域;marker 之后无元素时兜底移除列表首项,
    // 保证有界性优先于 marker 保护——仅敌意输入可达)。
    if parser.active_formatting_elements.len() >= crate::parser::MAX_ACTIVE_FORMATTING_ELEMENTS {
        let section_start = parser
            .active_formatting_elements
            .iter()
            .rposition(|e| matches!(e, ActiveFormattingEntry::Marker))
            .map_or(0, |m| m + 1);
        let remove_idx = if section_start < parser.active_formatting_elements.len() {
            section_start
        } else {
            0
        };
        parser.active_formatting_elements.remove(remove_idx);
    }
    parser
        .active_formatting_elements
        .push(ActiveFormattingEntry::Element(element));
}

/// Add a marker to the list of active formatting elements (§13.2.6.2).
///
/// Markers delimit sections of the list; they are pushed when entering
/// table contexts, template content, etc. (Phase 3.4/3.5).
#[allow(dead_code)]
pub fn add_formatting_marker(parser: &mut HtmlTreeConstructor) {
    parser
        .active_formatting_elements
        .push(ActiveFormattingEntry::Marker);
}

/// "Clear the list of active formatting elements up to the last marker"
/// (§13.2.6.2).
///
/// Remove entries from the end of the list until a marker has been removed
/// (or the list is empty). Used by table/template modes (Phase 3.4/3.5).
#[allow(dead_code)]
pub fn clear_active_formatting_to_last_marker(parser: &mut HtmlTreeConstructor) {
    while let Some(entry) = parser.active_formatting_elements.pop() {
        if matches!(entry, ActiveFormattingEntry::Marker) {
            break;
        }
    }
}

/// Compare two elements for the Noah's Ark clause (§13.2.6.2).
///
/// Two elements match if they have the same tag name, namespace, and
/// attributes (count and values). This is used to limit the list to at
/// most three consecutive equivalent formatting elements.
fn elements_match_for_noahs_ark(a: &Rc<RefCell<Node>>, b: &Rc<RefCell<Node>>) -> bool {
    let a = a.borrow();
    let b = b.borrow();
    let (ea, eb) = match (a.kind.as_element(), b.kind.as_element()) {
        (Some(ea), Some(eb)) => (ea, eb),
        _ => return false,
    };
    if ea.namespace != eb.namespace {
        return false;
    }
    if ea.local_name != eb.local_name {
        return false;
    }
    if ea.attributes.len() != eb.attributes.len() {
        return false;
    }
    // Attributes are compared in order; HTML tree construction preserves
    // attribute order so this is sufficient.
    ea.attributes
        .iter()
        .zip(eb.attributes.iter())
        .all(|(x, y)| x.local_name == y.local_name && x.value == y.value)
}

/// "Reconstruct the active formatting elements" (§13.2.6.4.2).
///
/// Re-opens formatting elements (`<b>`, `<i>`, etc.) that were closed
/// implicitly when block elements were inserted, so that subsequent text or
/// inline elements inherit the formatting. The algorithm walks the list
/// from the end, finds the first entry that is either a marker or already
/// on the open elements stack, then re-inserts each formatting element
/// after that point (cloning the element with no attributes change).
pub fn reconstruct_active_formatting_elements(parser: &mut HtmlTreeConstructor) {
    // If the list is empty, nothing to do.
    if parser.active_formatting_elements.is_empty() {
        return;
    }
    // If the last entry is a marker, nothing to do.
    if matches!(
        parser.active_formatting_elements.last(),
        Some(ActiveFormattingEntry::Marker)
    ) {
        return;
    }
    // If the last entry's element is the current node (top of open elements
    // stack), nothing to do.
    if let Some(ActiveFormattingEntry::Element(el)) = parser.active_formatting_elements.last() {
        if let Some(top) = parser.open_elements.last() {
            if Rc::ptr_eq(el, top) {
                return;
            }
        }
    }

    // Walk backward from the end to find the "first" entry (in spec terms,
    // the furthest from the end) that is a marker or on the open elements
    // stack. We then re-insert everything after it.
    let mut index = parser.active_formatting_elements.len();
    loop {
        if index == 0 {
            // Reached the start of the list; all entries need reconstruction.
            break;
        }
        index -= 1;
        let on_stack_or_marker = match &parser.active_formatting_elements[index] {
            ActiveFormattingEntry::Marker => true,
            ActiveFormattingEntry::Element(el) => {
                parser.open_elements.iter().any(|o| Rc::ptr_eq(o, el))
            }
        };
        if on_stack_or_marker {
            // Step past this entry; reconstruction starts at index+1.
            index += 1;
            break;
        }
    }

    // Re-insert each entry from `index` to the end. New elements are cloned
    // (same tag, same attributes) and pushed onto both the open elements
    // stack and the active formatting list (replacing the old entry).
    while index < parser.active_formatting_elements.len() {
        let entry = parser.active_formatting_elements[index].clone();
        let old_element = match entry {
            ActiveFormattingEntry::Element(e) => e,
            ActiveFormattingEntry::Marker => {
                index += 1;
                continue;
            }
        };
        // Clone the element: same tag name and attributes, fresh node.
        let (local_name, attrs) = {
            let o = old_element.borrow();
            let e = o
                .kind
                .as_element()
                .expect("formatting entry not an element");
            (
                e.local_name.clone(),
                e.attributes
                    .iter()
                    .map(|a| Attribute::new(&a.local_name, &a.value))
                    .collect::<Vec<_>>(),
            )
        };
        let new_element = Node::new_element_html(&local_name, attrs, &parser.document);
        // §13.2.6.4.7 reconstruct step 8: "Insert an HTML element for the
        // token" — this goes through "appropriate place for inserting a
        // node" (§13.2.6.2), which applies foster parenting when active.
        // Using insert_node (not direct append_child) ensures reconstructed
        // formatting elements are foster-parented correctly when the
        // current node is a table/tbody/tr.
        insert_node(parser, &new_element);
        push_open_element(parser, new_element.clone());
        // Replace the entry with the new element.
        parser.active_formatting_elements[index] = ActiveFormattingEntry::Element(new_element);
        index += 1;
    }
}

// ── Adoption agency algorithm (§13.2.6.4.7) ───────────────────

/// The "special" elements per §13.2.6.3 (HTML-namespace subset). Used by
/// the adoption agency algorithm to find the furthest block, and by the
/// "any other end tag" branch to decide when to ignore an end tag.
pub const SPECIAL_ELEMENTS: &[&str] = &[
    "address",
    "applet",
    "area",
    "article",
    "aside",
    "base",
    "basefont",
    "bgsound",
    "blockquote",
    "body",
    "br",
    "button",
    "caption",
    "center",
    "col",
    "colgroup",
    "dd",
    "details",
    "dialog",
    "dir",
    "div",
    "dl",
    "dt",
    "embed",
    "fieldset",
    "figcaption",
    "figure",
    "footer",
    "form",
    "frame",
    "frameset",
    "h1",
    "h2",
    "h3",
    "h4",
    "h5",
    "h6",
    "head",
    "header",
    "hgroup",
    "hr",
    "html",
    "iframe",
    "img",
    "input",
    "keygen",
    "li",
    "link",
    "listing",
    "main",
    "marquee",
    "menu",
    "meta",
    "nav",
    "noembed",
    "noframes",
    "noscript",
    "object",
    "ol",
    "p",
    "param",
    "plaintext",
    "pre",
    "search",
    "script",
    "section",
    "select",
    "source",
    "style",
    "summary",
    "table",
    "tbody",
    "td",
    "template",
    "textarea",
    "tfoot",
    "th",
    "thead",
    "title",
    "tr",
    "track",
    "ul",
    "wbr",
    "xmp",
];

/// Find the last entry in the active formatting list (scanning from the end
/// to the last marker) whose element has the given tag name. Returns its
/// index in the list, or `None`.
fn find_formatting_element(parser: &HtmlTreeConstructor, name: &str) -> Option<usize> {
    for (i, entry) in parser.active_formatting_elements.iter().enumerate().rev() {
        match entry {
            ActiveFormattingEntry::Marker => return None,
            ActiveFormattingEntry::Element(el) => {
                let is_match = el
                    .borrow()
                    .kind
                    .as_element()
                    .map(|e| e.local_name == name)
                    .unwrap_or(false);
                if is_match {
                    return Some(i);
                }
            }
        }
    }
    None
}

/// Find the index of a node in the open elements stack, comparing by `Rc`
/// pointer identity.
fn stack_index_of(parser: &HtmlTreeConstructor, node: &Rc<RefCell<Node>>) -> Option<usize> {
    parser
        .open_elements
        .iter()
        .position(|n| Rc::ptr_eq(n, node))
}

/// Find the index of an active-formatting entry's element in the open
/// elements stack, comparing by `Rc` pointer identity.
fn stack_index_of_afe(parser: &HtmlTreeConstructor, afe_index: usize) -> Option<usize> {
    match &parser.active_formatting_elements[afe_index] {
        ActiveFormattingEntry::Element(el) => stack_index_of(parser, el),
        ActiveFormattingEntry::Marker => None,
    }
}

/// Clone an element's tag name and attributes into a fresh node (used by the
/// adoption agency algorithm to recreate formatting elements).
fn clone_element(parser: &HtmlTreeConstructor, src: &Rc<RefCell<Node>>) -> Rc<RefCell<Node>> {
    let (local_name, attrs) = {
        let s = src.borrow();
        let e = s
            .kind
            .as_element()
            .expect("formatting entry not an element");
        (
            e.local_name.clone(),
            e.attributes
                .iter()
                .map(|a| Attribute::new(&a.local_name, &a.value))
                .collect::<Vec<_>>(),
        )
    };
    Node::new_element_html(&local_name, attrs, &parser.document)
}

/// The adoption agency algorithm (§13.2.6.4.7).
///
/// Handles end tags for formatting elements (`</b>`, `</i>`, `</a>`, etc.)
/// and the special misnested-tag cases that arise when block elements
/// interleave with formatting elements. Implements the full 8-iteration
/// outer loop with the inner "reconstruct" loop.
pub fn adoption_agency(parser: &mut HtmlTreeConstructor, subject: &str) {
    // Step 2: If the current node is an HTML element whose tag name is
    // subject, and the current node is not in the list of active formatting
    // elements, then pop the current node off the stack of return.
    if let Some(top) = parser.open_elements.last() {
        let is_subject = top
            .borrow()
            .kind
            .as_element()
            .map(|e| e.local_name == subject)
            .unwrap_or(false);
        if is_subject {
            let in_afe = parser
                .active_formatting_elements
                .iter()
                .any(|e| matches!(e, ActiveFormattingEntry::Element(el) if Rc::ptr_eq(el, top)));
            if !in_afe {
                parser.open_elements.pop();
                return;
            }
        }
    }

    // Outer loop: at most 8 iterations.
    for _ in 0..8 {
        // 4.1: Find the formatting element (last AFE entry with tag=subject,
        //      between end and last marker).
        let mut formatting_afe_index = match find_formatting_element(parser, subject) {
            Some(i) => i,
            None => {
                // No formatting element: run "any other end tag" behavior.
                run_any_other_end_tag(parser, subject);
                return;
            }
        };

        // 4.2: If formatting element is not on the open elements stack,
        //      parse error, remove from list, return.
        let mut fmt_stack_index = match stack_index_of_afe(parser, formatting_afe_index) {
            Some(i) => i,
            None => {
                parser.errors.push(ParseError::Generic(
                    "adoption agency: formatting element not on stack",
                ));
                parser
                    .active_formatting_elements
                    .remove(formatting_afe_index);
                return;
            }
        };

        // 4.3: If formatting element is in the stack but not in scope,
        //      parse error, return.
        if !has_element_in_scope(parser, subject) {
            parser.errors.push(ParseError::Generic(
                "adoption agency: formatting element not in scope",
            ));
            return;
        }

        // 4.4: If formatting element is not the current node, parse error
        //      (not fatal).
        if let Some(top) = parser.open_elements.last() {
            let is_fmt = match &parser.active_formatting_elements[formatting_afe_index] {
                ActiveFormattingEntry::Element(el) => Rc::ptr_eq(el, top),
                _ => false,
            };
            if !is_fmt {
                parser.errors.push(ParseError::Generic(
                    "adoption agency: formatting element not current",
                ));
            }
        }

        // 4.5: Find the furthest block — per §13.2.6.4.7 step 5, "the topmost
        //      node in the stack of open elements that is lower in the stack
        //      than formatting element, and is an element in the special
        //      category." The stack grows downwards (root at index 0, current
        //      node at the end), so "lower than formatting element" means a
        //      HIGHER index. "Topmost" among those is the smallest such index,
        //      i.e. the first special element found scanning forward from
        //      fmt_stack_index+1.
        let furthest_block_index = parser.open_elements[fmt_stack_index + 1..]
            .iter()
            .enumerate()
            .find(|(_, n)| {
                n.borrow()
                    .kind
                    .as_element()
                    .map(|e| {
                        e.namespace == muskitty_dom::Namespace::Html
                            && SPECIAL_ELEMENTS.contains(&e.local_name.as_str())
                    })
                    .unwrap_or(false)
            })
            .map(|(i, _)| fmt_stack_index + 1 + i);

        let mut furthest_block_index = match furthest_block_index {
            Some(i) => i,
            None => {
                // No furthest block: pop elements off the stack until the
                // formatting element is popped, remove it from the AFE list,
                // and return.
                while let Some(top) = parser.open_elements.pop() {
                    let is_fmt = match &parser.active_formatting_elements[formatting_afe_index] {
                        ActiveFormattingEntry::Element(el) => Rc::ptr_eq(el, &top),
                        _ => false,
                    };
                    if is_fmt {
                        break;
                    }
                }
                parser
                    .active_formatting_elements
                    .remove(formatting_afe_index);
                return;
            }
        };

        // 4.6: Common ancestor — the element immediately below the
        //      formatting element in the stack.
        let common_ancestor = parser
            .open_elements
            .get(fmt_stack_index.wrapping_sub(1))
            .cloned();

        // 4.7: Bookmark — note the position of the formatting element in
        //      the AFE list. We track it as an index, adjusting for removals.
        let mut bookmark = formatting_afe_index;

        // 4.8: Inner loop.
        let mut node_index = furthest_block_index;
        let furthest_block_node = parser.open_elements[furthest_block_index].clone();
        let mut last_node = furthest_block_node.clone();

        let mut inner_iterations = 0;
        loop {
            inner_iterations += 1;
            if inner_iterations > 64 {
                // Safety valve against infinite loops on malformed state.
                break;
            }
            // node = element immediately above the current node in the stack.
            if node_index == 0 {
                break;
            }
            node_index -= 1;
            let node = parser.open_elements[node_index].clone();

            // If node is the formatting element, end inner loop.
            let is_fmt = match &parser.active_formatting_elements[formatting_afe_index] {
                ActiveFormattingEntry::Element(el) => Rc::ptr_eq(el, &node),
                _ => false,
            };
            if is_fmt {
                break;
            }

            // Is node in the AFE list?
            let node_afe_index = parser.active_formatting_elements.iter().position(
                |e| matches!(e, ActiveFormattingEntry::Element(el) if Rc::ptr_eq(el, &node)),
            );

            match node_afe_index {
                None => {
                    // Remove node from the stack.
                    parser.open_elements.remove(node_index);
                    // Adjust furthest_block_index / fmt_stack_index if needed.
                    if node_index < fmt_stack_index {
                        fmt_stack_index_will_decrement(&mut fmt_stack_index);
                    }
                    if node_index < furthest_block_index {
                        furthest_block_index -= 1;
                    }
                }
                Some(afe_idx) => {
                    // §13.2.6.4.7 step 13.4: If innerLoopCounter > 3 and
                    // node is in the AFE list, remove it from the AFE list
                    // (and then from the stack via the "not in AFE" path).
                    // This prevents excessive cloning of formatting elements
                    // in deeply nested misnested content.
                    if inner_iterations > 3 {
                        parser.active_formatting_elements.remove(afe_idx);
                        // Adjust bookmark if the removed entry was before it.
                        if afe_idx < bookmark {
                            bookmark -= 1;
                        }
                        // Adjust formatting_afe_index if the removed entry
                        // was before the formatting element.
                        if afe_idx < formatting_afe_index {
                            formatting_afe_index -= 1;
                        }
                        // Now treat as "not in AFE": remove from stack.
                        parser.open_elements.remove(node_index);
                        if node_index < fmt_stack_index {
                            fmt_stack_index_will_decrement(&mut fmt_stack_index);
                        }
                        if node_index < furthest_block_index {
                            furthest_block_index -= 1;
                        }
                        continue;
                    }
                    // Step 13.6: Create a new element with the same tag/attrs
                    // as node, append last_node to it, replace node in both
                    // the stack and the AFE list, set last_node = new element.
                    let new_element = clone_element(parser, &node);
                    let _ = append_child(&new_element, last_node.clone());
                    // Replace node in the open elements stack.
                    parser.open_elements[node_index] = new_element.clone();
                    // Replace node in the AFE list.
                    parser.active_formatting_elements[afe_idx] =
                        ActiveFormattingEntry::Element(new_element.clone());
                    // Step 13.7: If lastNode is furthestBlock, move the
                    // bookmark to be immediately after the new node in the
                    // AFE list.
                    if Rc::ptr_eq(&last_node, &furthest_block_node) {
                        bookmark = afe_idx + 1;
                    }
                    last_node = new_element;
                }
            }
        }

        // 4.9 (§13.2.6.4.7 steps 14-15): Let insertionLocation be
        //      commonAncestor, after its last child. Insert lastNode at the
        //      *adjusted insertion location* given insertionLocation.
        //
        //      Per §13.2.6.2, the adjusted insertion location uses
        //      commonAncestor as the override target. If foster parenting is
        //      enabled AND the override target is a `table`, `tbody`,
        //      `tfoot`, `thead`, or `tr` element, the foster parenting
        //      substeps apply (insertion happens before the last table in
        //      the stack of open elements, not inside the table).
        //      Otherwise, the insertion location is inside commonAncestor,
        //      after its last child (or inside its template content if
        //      commonAncestor is a `template` element — §13.2.6.2 step 3).
        if let Some(ancestor) = common_ancestor {
            let is_table_like = ancestor
                .borrow()
                .kind
                .as_element()
                .map(|e| {
                    matches!(
                        e.local_name.as_str(),
                        "table" | "tbody" | "tfoot" | "thead" | "tr"
                    )
                })
                .unwrap_or(false);
            if parser.foster_parenting && is_table_like {
                // §13.2.6.2 foster parenting substeps: the location is
                // determined by the last `table`/`template` in the stack
                // of open elements, not by the override target itself.
                match foster_parent_location(parser) {
                    FosterLocation::Append(parent) => {
                        let _ = append_child(&parent, last_node.clone());
                    }
                    FosterLocation::Before { parent, before } => {
                        let _ =
                            muskitty_dom::insert_before(&parent, last_node.clone(), Some(&before));
                    }
                }
            } else {
                let target = {
                    let anc_ref = ancestor.borrow();
                    match &anc_ref.kind {
                        NodeKind::Element(e) if e.local_name == "template" => e
                            .template_content
                            .clone()
                            .unwrap_or_else(|| ancestor.clone()),
                        _ => ancestor.clone(),
                    }
                };
                let _ = append_child(&target, last_node.clone());
            }
        }

        // 4.10: Create a new element with the same tag/attrs as the
        //       formatting element.
        let formatting_element = match &parser.active_formatting_elements[formatting_afe_index] {
            ActiveFormattingEntry::Element(el) => el.clone(),
            _ => unreachable!("formatting element entry is always Element here"),
        };
        let new_formatting = clone_element(parser, &formatting_element);

        // 4.11: Move all children of furthest block to new_formatting.
        let furthest_block = parser.open_elements[furthest_block_index].clone();
        let children: Vec<Rc<RefCell<Node>>> = furthest_block.borrow().child_nodes().to_vec();
        for child in &children {
            let _ = muskitty_dom::remove_child(&furthest_block, child);
            let _ = append_child(&new_formatting, child.clone());
        }

        // 4.12: Append new_formatting to furthest block.
        let _ = append_child(&furthest_block, new_formatting.clone());

        // 4.13: Remove the formatting element from the AFE list, and insert
        //       new_formatting at the bookmark position.
        parser
            .active_formatting_elements
            .remove(formatting_afe_index);
        // Adjust bookmark if it was after the removed entry.
        if bookmark > formatting_afe_index {
            bookmark -= 1;
        }
        // Insert at bookmark (clamped to list length).
        let insert_at = bookmark.min(parser.active_formatting_elements.len());
        parser.active_formatting_elements.insert(
            insert_at,
            ActiveFormattingEntry::Element(new_formatting.clone()),
        );

        // 4.14: Remove the formatting element from the stack, and insert
        //       new_formatting immediately after furthest block.
        let fmt_stack_idx = stack_index_of(parser, &formatting_element);
        if let Some(i) = fmt_stack_idx {
            parser.open_elements.remove(i);
        }
        let fb_idx = stack_index_of(parser, &furthest_block);
        if let Some(i) = fb_idx {
            parser.open_elements.insert(i + 1, new_formatting);
        }
        // Continue the outer loop.
    }
}

/// Helper: decrement `fmt_stack_index` by one (used when a node below the
/// formatting element is removed from the stack, shifting indices down).
fn fmt_stack_index_will_decrement(idx: &mut usize) {
    *idx = idx.saturating_sub(1);
}

/// The "any other end tag" algorithm (§13.2.6.4.7), used as a fallback by
/// the adoption agency algorithm when there is no matching formatting
/// element in the active formatting list.
fn run_any_other_end_tag(parser: &mut HtmlTreeConstructor, name: &str) {
    // Walk the stack from top to bottom. If a matching element is found,
    // generate implied end tags except `name`, then pop until it is popped.
    // If a special element (that is not the target) is encountered first,
    // parse error, return (ignore the end tag).
    //
    // Per §13.2.6.2, "special" elements are HTML-namespace only. Foreign
    // elements (SVG/MathML) with the same local name (e.g. svg "tr", svg
    // "input") must NOT be treated as special, and an HTML end tag should
    // not match a foreign element by local name.
    for (i, node) in parser.open_elements.iter().enumerate().rev() {
        let node_name = html_local_name(node);
        if node_name.as_deref() == Some(name) {
            generate_implied_end_tags(parser, Some(name));
            // Pop until the node at index i is popped.
            while parser.open_elements.len() > i {
                parser.open_elements.pop();
            }
            return;
        }
        if let Some(n) = node_name.as_deref() {
            if SPECIAL_ELEMENTS.contains(&n) {
                parser
                    .errors
                    .push(ParseError::UnexpectedEndTag(name.to_string()));
                return;
            }
        }
    }
}

// ── selectedcontent support (WHATWG §4.10.17, §4.10.10) ────────────
//
// The `<selectedcontent>` element mirrors the contents of a `<select>`
// element's currently selected `<option>`. The parser hook is:
//   "When an `option` element is popped off the stack of open elements
//    ... the user agent must run maybe clone an option into
//    selectedcontent given the `option` element." (§4.10.10)
//
// Selectedness is tracked on `ElementData.selectedness` and maintained by
// the selectedness setting algorithm (§4.10.10), which runs whenever an
// option is inserted into (or removed from) a select.

/// Deep-clone a node subtree (DOM §4.4 "clone a node" with subtree=true).
fn deep_clone_node(
    node: &Rc<RefCell<Node>>,
    owner_document: &Rc<RefCell<Node>>,
) -> Rc<RefCell<Node>> {
    let n = node.borrow();
    let clone = match &n.kind {
        NodeKind::Element(e) => {
            Node::new_element_html(&e.local_name, e.attributes.clone(), owner_document)
        }
        NodeKind::Text(t) => Node::new_text(&t.data, owner_document),
        NodeKind::Comment(c) => Node::new_comment(&c.data, owner_document),
        _ => {
            // Fallback: shallow clone for unusual node types.
            Node::new_text("", owner_document)
        }
    };
    // Clone children recursively.
    let child_nodes: Vec<Rc<RefCell<Node>>> = n.child_nodes().to_vec();
    for child in &child_nodes {
        let child_clone = deep_clone_node(child, owner_document);
        muskitty_dom::push_child_raw(&clone, child_clone);
    }
    clone
}

/// "Get the nearest ancestor select" (§4.10.10): walk up the DOM tree
/// looking for a `<select>` ancestor, returning null if a `datalist`,
/// `hr`, or `option` element is encountered first, or if optgroup
/// nesting is invalid.
fn find_nearest_ancestor_select(element: &Rc<RefCell<Node>>) -> Option<Rc<RefCell<Node>>> {
    let mut ancestor_optgroup: Option<Rc<RefCell<Node>>> = None;
    let mut current = element.borrow().parent_node.upgrade();
    while let Some(node) = current {
        let is_element = node.borrow().node_type == NodeType::Element;
        if !is_element {
            current = node.borrow().parent_node.upgrade();
            continue;
        }
        let local_name = node
            .borrow()
            .kind
            .as_element()
            .map(|e| e.local_name.clone());
        match local_name.as_deref() {
            Some("datalist") | Some("hr") | Some("option") => return None,
            Some("optgroup") => {
                if ancestor_optgroup.is_some() {
                    return None;
                }
                ancestor_optgroup = Some(node.clone());
            }
            Some("select") => return Some(node),
            _ => {}
        }
        current = node.borrow().parent_node.upgrade();
    }
    None
}

/// "Get the list of options" given a select element (§4.10.10).
/// Walks descendants in tree order, collecting `<option>` elements.
fn get_list_of_options(select: &Rc<RefCell<Node>>) -> Vec<Rc<RefCell<Node>>> {
    let mut options: Vec<Rc<RefCell<Node>>> = Vec::new();
    // Recursive DFS in document order, skipping subtrees of certain
    // elements per the spec algorithm.
    fn walk(
        node: &Rc<RefCell<Node>>,
        select: &Rc<RefCell<Node>>,
        options: &mut Vec<Rc<RefCell<Node>>>,
    ) {
        let children: Vec<Rc<RefCell<Node>>> = {
            let n = node.borrow();
            n.child_nodes().to_vec()
        };
        for child in &children {
            let local = child
                .borrow()
                .kind
                .as_element()
                .map(|e| e.local_name.clone());
            match local.as_deref() {
                Some("option") => {
                    options.push(child.clone());
                    // Option's descendants are not traversed (per spec: skip
                    // node's descendants when node is an option).
                }
                Some("select") | Some("datalist") | Some("hr") => {
                    // Skip descendants of these.
                }
                Some("optgroup") => {
                    // Check if this optgroup has an ancestor optgroup
                    // between itself and select. If so, skip descendants.
                    let mut has_ancestor_optgroup = false;
                    let mut walker = child.borrow().parent_node.upgrade();
                    while let Some(w) = walker {
                        if Rc::ptr_eq(&w, select) {
                            break;
                        }
                        let w_local = w.borrow().kind.as_element().map(|e| e.local_name.clone());
                        if w_local.as_deref() == Some("optgroup") {
                            has_ancestor_optgroup = true;
                            break;
                        }
                        walker = w.borrow().parent_node.upgrade();
                    }
                    if has_ancestor_optgroup {
                        // Skip descendants.
                    } else {
                        walk(child, select, options);
                    }
                }
                _ => {
                    walk(child, select, options);
                }
            }
        }
    }
    walk(select, select, &mut options);
    options
}

/// "Get a select's enabled selectedcontent" (§4.10.17): if select has
/// `multiple`, return None; otherwise return the first `selectedcontent`
/// descendant in tree order.
///
/// P-1:带备忘录(见 [`SelectSelectedcontentMemo`])。`Absent` 命中直接
/// O(1) 返回 None;`Present` 升级即首个(append-only 下树序首个不变)。
/// 备忘录未命中/升级失败时全子树 DFS 并重建。`multiple` 判定恒在
/// 备忘录之前(与规范一致,备忘录只缓存节点查找)。
fn get_select_enabled_selectedcontent(
    parser: &mut HtmlTreeConstructor,
    select: &Rc<RefCell<Node>>,
) -> Option<Rc<RefCell<Node>>> {
    let has_multiple = select
        .borrow()
        .kind
        .as_element()
        .and_then(|e| e.get_attribute("multiple"))
        .is_some();
    if has_multiple {
        return None;
    }
    let memo_hits_same_select = parser
        .select_selectedcontent_memo
        .as_ref()
        .and_then(|m| m.select.upgrade())
        .is_some_and(|s| Rc::ptr_eq(&s, select));
    if memo_hits_same_select {
        match &parser.select_selectedcontent_memo.as_ref().unwrap().lookup {
            SelectedcontentLookup::Absent => return None,
            SelectedcontentLookup::Present(w) => {
                if let Some(sc) = w.upgrade() {
                    return Some(sc);
                }
                // 升级失败(解析期不应发生):落入重扫重建。
            }
        }
    }
    // 慢路径:全子树 DFS(与修复前行为一致),随后重建备忘录。
    fn find(node: &Rc<RefCell<Node>>) -> Option<Rc<RefCell<Node>>> {
        let children: Vec<Rc<RefCell<Node>>> = {
            let n = node.borrow();
            n.child_nodes().to_vec()
        };
        for child in &children {
            let is_sc = child
                .borrow()
                .kind
                .as_element()
                .map(|e| {
                    e.namespace == muskitty_dom::Namespace::Html
                        && e.local_name == "selectedcontent"
                })
                .unwrap_or(false);
            if is_sc {
                return Some(child.clone());
            }
            if let Some(found) = find(child) {
                return Some(found);
            }
        }
        None
    }
    let found = find(select);
    parser.select_selectedcontent_memo = Some(SelectSelectedcontentMemo {
        select: Rc::downgrade(select),
        lookup: match &found {
            Some(sc) => SelectedcontentLookup::Present(Rc::downgrade(sc)),
            None => SelectedcontentLookup::Absent,
        },
    });
    found
}

/// "The selectedness setting algorithm" (§4.10.10): given a select
/// element, adjust option selectedness.
///
/// 1. If multiple absent, display size 1, and no option has
///    selectedness=true → set first non-disabled option's selectedness=true.
/// 2. If multiple absent and 2+ options have selectedness=true → set all
///    but last to false.
///
/// F-8:返回 `(has_selected_after, has_non_disabled, selected_node)` 供增量
/// 备忘录维护:
/// - `has_selected_after`:算法跑完后是否仍存在 selectedness=true 的
///   option;
/// - `has_non_disabled`:是否存在非 disabled 的 option。仅当
///   `has_selected_after == false` 时可信(此时 step 1 的扫描必然执行);
///   为 true 时调用方不消费该值,固定返回 false 并在此注明。
/// - `selected_node`(P-1):算法跑完后唯一选中的 option(算法 step 2
///   恒"保树序最后一个",故至多一个);无选中为 `None`。
fn selectedness_setting_algorithm(
    select: &Rc<RefCell<Node>>,
) -> (bool, bool, Option<Rc<RefCell<Node>>>) {
    let has_multiple = select
        .borrow()
        .kind
        .as_element()
        .and_then(|e| e.get_attribute("multiple"))
        .is_some();
    if has_multiple {
        // multiple 存在时算法整体 no-op(调用方 on_option_inserted_with_memo
        // 已提前短路;此分支保留给无备忘录入口)。
        return (false, false, None);
    }
    // Display size: 1 if size attribute absent or parses to 1.
    let display_size: u32 = select
        .borrow()
        .kind
        .as_element()
        .and_then(|e| e.get_attribute("size"))
        .and_then(|s| s.parse::<u32>().ok())
        .unwrap_or(1);

    let options = get_list_of_options(select);

    // Step 1: if display size is 1 and no option has selectedness=true,
    // set first non-disabled option's selectedness to true.
    if display_size == 1 {
        let any_selected = options.iter().any(|opt| {
            opt.borrow()
                .kind
                .as_element()
                .map(|e| e.selectedness)
                .unwrap_or(false)
        });
        if !any_selected {
            for opt in &options {
                let is_disabled = opt
                    .borrow()
                    .kind
                    .as_element()
                    .and_then(|e| e.get_attribute("disabled"))
                    .is_some();
                if !is_disabled {
                    if let NodeKind::Element(ref mut e) = opt.borrow_mut().kind {
                        e.selectedness = true;
                    }
                    // step 1 命中:恰有 1 个 selected(刚设置)→ step 2
                    // 必为 no-op,可直接返回。
                    return (true, true, Some(opt.clone()));
                }
            }
            // 全部 disabled:无 selected、无非 disabled。step 2 同样无 op。
            return (false, false, None);
        }
        // 已有 selected:step 1 不动,**继续落入 step 2**(可能与本次
        // 插入的 `<option selected>` 组成 ≥2 个选中而触发取消)。
        // has_non_disabled 从此处不可信,按文档约定返回 false。
        let selected_indices: Vec<usize> = options
            .iter()
            .enumerate()
            .filter(|(_, opt)| {
                opt.borrow()
                    .kind
                    .as_element()
                    .map(|e| e.selectedness)
                    .unwrap_or(false)
            })
            .map(|(i, _)| i)
            .collect();
        // any_selected 为真 → selected_indices 非空;last 即唯一幸存的
        // 选中(≥2 时为树序最后一个)。
        let last = *selected_indices.last().unwrap();
        if selected_indices.len() >= 2 {
            for &i in &selected_indices {
                if i != last {
                    if let NodeKind::Element(ref mut e) = options[i].borrow_mut().kind {
                        e.selectedness = false;
                    }
                }
            }
        }
        return (true, false, Some(options[last].clone()));
    }

    // Step 2: if 2+ options have selectedness=true, set all but last to
    // false.(display_size != 1 时 step 1 被跳过,step 2 照常执行。)
    let selected_indices: Vec<usize> = options
        .iter()
        .enumerate()
        .filter(|(_, opt)| {
            opt.borrow()
                .kind
                .as_element()
                .map(|e| e.selectedness)
                .unwrap_or(false)
        })
        .map(|(i, _)| i)
        .collect();
    if selected_indices.len() >= 2 {
        let last = *selected_indices.last().unwrap();
        for &i in &selected_indices {
            if i != last {
                if let NodeKind::Element(ref mut e) = options[i].borrow_mut().kind {
                    e.selectedness = false;
                }
            }
        }
        return (true, false, Some(options[last].clone()));
    }
    // P-1 修正:恰有 1 个 selected 时旧实现错报 has_selected=false。旧
    // 备忘录消费方不受影响(size≠1 时 skip 恒真),但 P-1 快路径依赖
    // has_selected 判定"此前是否已有选中",错报会让两个 selected 并存。
    if let Some(&only) = selected_indices.first() {
        return (true, false, Some(options[only].clone()));
    }
    (false, false, None)
}

/// "Clone an option into a selectedcontent" (§4.10.17): deep-clone all
/// children of `option` into `selectedcontent`, replacing its existing
/// content.
fn clone_option_into_selectedcontent(
    option: &Rc<RefCell<Node>>,
    selectedcontent: &Rc<RefCell<Node>>,
    owner_document: &Rc<RefCell<Node>>,
) {
    // Clear existing children of selectedcontent ("replace all").
    let old_children = muskitty_dom::drain_children(selectedcontent);
    for c in &old_children {
        c.borrow_mut().parent_node = Weak::new();
    }
    // Deep-clone each child of option and append to selectedcontent.
    let option_children: Vec<Rc<RefCell<Node>>> = {
        let o = option.borrow();
        o.child_nodes().to_vec()
    };
    for child in &option_children {
        let clone = deep_clone_node(child, owner_document);
        muskitty_dom::push_child_raw(selectedcontent, clone);
    }
}

/// "Maybe clone an option into selectedcontent" (§4.10.10): the parser
/// hook called when an option is popped off the stack of open elements.
///
/// If the option's nearest ancestor select exists, the option's
/// selectedness is true, and the select has an enabled selectedcontent,
/// then clone the option's children into the selectedcontent.
///
/// P-1:selectedcontent 查找走备忘录(见 [`SelectSelectedcontentMemo`])。
/// `<option selected>` × 65k 时每个 option 在自身 pop 时尚未被后续插入
/// 取消选中,原全子树 DFS 查找构成残余 O(n²);Absent 命中后整体 O(n)。
pub fn maybe_clone_option_into_selectedcontent(
    parser: &mut HtmlTreeConstructor,
    option: &Rc<RefCell<Node>>,
) {
    let select = match find_nearest_ancestor_select(option) {
        Some(s) => s,
        None => return,
    };
    let selectedness = option
        .borrow()
        .kind
        .as_element()
        .map(|e| e.selectedness)
        .unwrap_or(false);
    if !selectedness {
        return;
    }
    let selectedcontent = match get_select_enabled_selectedcontent(parser, &select) {
        Some(sc) => sc,
        None => return,
    };
    let owner_document = option
        .borrow()
        .owner_document
        .upgrade()
        .unwrap_or_else(|| option.clone());
    clone_option_into_selectedcontent(option, &selectedcontent, &owner_document);
}

/// Hook called after an `<option>` element is inserted into the DOM (per
/// §4.10.10 "option HTML element insertion steps"): runs the selectedness
/// setting algorithm on the nearest ancestor select.
/// option 插入钩子(§4.10.10 "option HTML element insertion steps")的
/// 解析器内部版本:带增量备忘录(审计 F-8)。
///
/// 敌意输入 `<select>` + 65k 个 `<option>` 令每次插入都全子树扫描
/// ——O(n²) 挂起(审计 P1)。备忘录记录 `(select, has_selected,
/// all_disabled, last_selected)`,对**可证明为 no-op** 的插入直接跳过
/// 子树扫描:
///
/// - step 1(选中首个非 disabled)仅在 `display_size==1 && 无已选中 &&
///   存在非 disabled` 时可能生效;
/// - step 2(取消除最后一个外的全部选中)仅在本次插入自带选中
///   (`<option selected>`)时可能生效。
///
/// 因此对无 `selected` 属性的插入:`display_size≠1`、或已有选中、或
/// (O 自身 disabled 且此前全 disabled)时两步均不可能改变任何状态
/// → no-op。
///
/// 带 `selected` 的插入(P-1):算法跑完后至多一个选中(step 2 恒保树序
/// 最后一个),备忘录 `last_selected` 即该唯一选中。新插入 O 必为 select
/// 子树内树序**最后**的 option(解析器在 select 内只 append:select 各
/// 插入模式不做 foster parenting,foster/template 路径不可能以 select
/// 为祖先),故 step 2 等价于"定点取消旧选中、保 O"——O(1),免去全子树
/// 扫描。此前无选中时两步均 no-op,仅更新备忘录。
///
/// 备忘录以 `Weak` 持有 select 与 last_selected:升级失败或非同一
/// select 即失效,防地址复用误命中;失效时回退完整算法并重建备忘录。
pub(crate) fn on_option_inserted_with_memo(
    parser: &mut HtmlTreeConstructor,
    option: &Rc<RefCell<Node>>,
) {
    let Some(select) = find_nearest_ancestor_select(option) else {
        return;
    };
    let (has_multiple, display_size_1) = {
        let sb = select.borrow();
        let e = sb.kind.as_element();
        (
            e.and_then(|e| e.get_attribute("multiple")).is_some(),
            e.and_then(|e| e.get_attribute("size"))
                .and_then(|s| s.parse::<u32>().ok())
                .unwrap_or(1)
                == 1,
        )
    };
    if has_multiple {
        // multiple 存在时算法整体 no-op(§4.10.10 两步均以 multiple 缺失
        // 为前提)。
        return;
    }
    let (o_selected, o_disabled) = match option.borrow().kind.as_element() {
        Some(e) => (e.selectedness, e.get_attribute("disabled").is_some()),
        None => return,
    };

    let memo_hits_same_select = parser
        .select_selectedness_memo
        .as_ref()
        .and_then(|m| m.select.upgrade())
        .is_some_and(|s| Rc::ptr_eq(&s, &select));
    if memo_hits_same_select {
        if !o_selected {
            let (has_selected, all_disabled) = {
                let memo = parser.select_selectedness_memo.as_ref().unwrap();
                (memo.has_selected, memo.all_disabled)
            };
            let skip = !display_size_1 || has_selected || (o_disabled && all_disabled);
            if skip {
                let memo = parser.select_selectedness_memo.as_mut().unwrap();
                memo.all_disabled = memo.all_disabled && o_disabled;
                return;
            }
        } else {
            // P-1 快路径:本次插入自带 selected。
            let (has_selected, last_selected) = {
                let memo = parser.select_selectedness_memo.as_ref().unwrap();
                (memo.has_selected, memo.last_selected.clone())
            };
            if !has_selected {
                // 插入前无选中:插入后仅 O 选中——step 1 因 any_selected
                // =true 而 no-op,step 2 因选中数 1<2 而 no-op。
                let memo = parser.select_selectedness_memo.as_mut().unwrap();
                memo.has_selected = true;
                memo.last_selected = Rc::downgrade(option);
                return;
            }
            if let Some(prev) = last_selected.upgrade() {
                // 此前恰有一个选中 prev。O 是树序最后的 option → step 2
                // "保 last" 即保 O:定点取消 prev,O 成为唯一选中。
                if let NodeKind::Element(ref mut e) = prev.borrow_mut().kind {
                    e.selectedness = false;
                }
                let memo = parser.select_selectedness_memo.as_mut().unwrap();
                memo.last_selected = Rc::downgrade(option);
                return;
            }
            // last_selected 升级失败(解析期节点只增不删,不应发生):
            // 落入慢路径整体重建。
        }
    }

    // 慢路径:完整算法(与修复前行为一致),随后重建备忘录。
    let (has_selected_after, has_non_disabled, selected_node) =
        selectedness_setting_algorithm(&select);
    parser.select_selectedness_memo = Some(SelectSelectednessMemo {
        select: Rc::downgrade(&select),
        has_selected: has_selected_after,
        // has_non_disabled 仅在 has_selected_after==false 时可信(见算法
        // 文档);为 true 时 all_disabled 恒为 false 也无妨——该值只在
        // !has_selected 的跳过判定中被消费。
        all_disabled: !has_non_disabled,
        last_selected: selected_node
            .map(|n| Rc::downgrade(&n))
            .unwrap_or_else(Weak::new),
    });
}