File: container_node.cc

package info (click to toggle)
chromium 138.0.7204.183-1
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 6,071,908 kB
  • sloc: cpp: 34,937,088; ansic: 7,176,967; javascript: 4,110,704; python: 1,419,953; asm: 946,768; xml: 739,971; pascal: 187,324; sh: 89,623; perl: 88,663; objc: 79,944; sql: 50,304; cs: 41,786; fortran: 24,137; makefile: 21,806; php: 13,980; tcl: 13,166; yacc: 8,925; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (1999 lines) | stat: -rw-r--r-- 74,212 bytes parent folder | download | duplicates (2)
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
/*
 * Copyright (C) 1999 Lars Knoll (knoll@kde.org)
 *           (C) 1999 Antti Koivisto (koivisto@kde.org)
 *           (C) 2001 Dirk Mueller (mueller@kde.org)
 * Copyright (C) 2004, 2005, 2006, 2007, 2008, 2009, 2013 Apple Inc. All rights
 * reserved.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public License
 * along with this library; see the file COPYING.LIB.  If not, write to
 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
 * Boston, MA 02110-1301, USA.
 */

#include "third_party/blink/renderer/core/dom/container_node.h"

#include "third_party/blink/renderer/bindings/core/v8/v8_get_html_options.h"
#include "third_party/blink/renderer/core/accessibility/ax_object_cache.h"
#include "third_party/blink/renderer/core/css/resolver/style_resolver.h"
#include "third_party/blink/renderer/core/css/selector_filter.h"
#include "third_party/blink/renderer/core/css/selector_query.h"
#include "third_party/blink/renderer/core/css/style_change_reason.h"
#include "third_party/blink/renderer/core/css/style_engine.h"
#include "third_party/blink/renderer/core/dom/child_frame_disconnector.h"
#include "third_party/blink/renderer/core/dom/child_list_mutation_scope.h"
#include "third_party/blink/renderer/core/dom/class_collection.h"
#include "third_party/blink/renderer/core/dom/document_part_root.h"
#include "third_party/blink/renderer/core/dom/element_traversal.h"
#include "third_party/blink/renderer/core/dom/events/event_dispatch_forbidden_scope.h"
#include "third_party/blink/renderer/core/dom/events/scoped_event_queue.h"
#include "third_party/blink/renderer/core/dom/flat_tree_traversal.h"
#include "third_party/blink/renderer/core/dom/layout_tree_builder_traversal.h"
#include "third_party/blink/renderer/core/dom/name_node_list.h"
#include "third_party/blink/renderer/core/dom/node.h"
#include "third_party/blink/renderer/core/dom/node_child_removal_tracker.h"
#include "third_party/blink/renderer/core/dom/node_cloning_data.h"
#include "third_party/blink/renderer/core/dom/node_lists_node_data.h"
#include "third_party/blink/renderer/core/dom/node_rare_data.h"
#include "third_party/blink/renderer/core/dom/node_traversal.h"
#include "third_party/blink/renderer/core/dom/part.h"
#include "third_party/blink/renderer/core/dom/part_root.h"
#include "third_party/blink/renderer/core/dom/shadow_root.h"
#include "third_party/blink/renderer/core/dom/slot_assignment_recalc_forbidden_scope.h"
#include "third_party/blink/renderer/core/dom/static_node_list.h"
#include "third_party/blink/renderer/core/dom/whitespace_attacher.h"
#include "third_party/blink/renderer/core/editing/serializers/serialization.h"
#include "third_party/blink/renderer/core/events/mutation_event.h"
#include "third_party/blink/renderer/core/execution_context/agent.h"
#include "third_party/blink/renderer/core/frame/deprecation/deprecation.h"
#include "third_party/blink/renderer/core/frame/local_dom_window.h"
#include "third_party/blink/renderer/core/frame/local_frame_view.h"
#include "third_party/blink/renderer/core/frame/web_feature.h"
#include "third_party/blink/renderer/core/html/forms/html_field_set_element.h"
#include "third_party/blink/renderer/core/html/forms/html_form_element.h"
#include "third_party/blink/renderer/core/html/forms/radio_node_list.h"
#include "third_party/blink/renderer/core/html/html_collection.h"
#include "third_party/blink/renderer/core/html/html_dialog_element.h"
#include "third_party/blink/renderer/core/html/html_document.h"
#include "third_party/blink/renderer/core/html/html_frame_owner_element.h"
#include "third_party/blink/renderer/core/html/html_tag_collection.h"
#include "third_party/blink/renderer/core/html/html_template_element.h"
#include "third_party/blink/renderer/core/inspector/console_message.h"
#include "third_party/blink/renderer/core/layout/layout_block_flow.h"
#include "third_party/blink/renderer/core/layout/layout_box.h"
#include "third_party/blink/renderer/core/layout/layout_inline.h"
#include "third_party/blink/renderer/core/layout/layout_text.h"
#include "third_party/blink/renderer/core/layout/layout_text_combine.h"
#include "third_party/blink/renderer/core/probe/core_probes.h"
#include "third_party/blink/renderer/core/timing/soft_navigation_heuristics.h"
#include "third_party/blink/renderer/platform/bindings/exception_state.h"
#include "third_party/blink/renderer/platform/bindings/runtime_call_stats.h"
#include "third_party/blink/renderer/platform/bindings/script_forbidden_scope.h"
#include "third_party/blink/renderer/platform/bindings/script_regexp.h"
#include "third_party/blink/renderer/platform/heap/collection_support/heap_vector.h"
#include "third_party/blink/renderer/platform/heap/member.h"
#include "third_party/blink/renderer/platform/instrumentation/use_counter.h"
#include "third_party/blink/renderer/platform/runtime_enabled_features.h"
#include "third_party/blink/renderer/platform/wtf/casting.h"
#include "third_party/blink/renderer/platform/wtf/text/strcat.h"

namespace blink {

static void DispatchChildInsertionEvents(Node&);
static void DispatchChildRemovalEvents(Node&);

namespace {

// This class is helpful to detect necessity of
// RecheckNodeInsertionStructuralPrereq() after removeChild*() inside
// InsertBefore(), AppendChild(), and ReplaceChild().
//
// After removeChild*(), we can detect necessity of
// RecheckNodeInsertionStructuralPrereq() by
//  - DOM tree version of |node_document_| was increased by at most one.
//  - If |node| and |parent| are in different documents, Document for
//    |parent| must not be changed.
class DOMTreeMutationDetector {
  STACK_ALLOCATED();

 public:
  DOMTreeMutationDetector(const Node& node, const Node& parent)
      : node_(&node),
        node_document_(&node.GetDocument()),
        parent_document_(&parent.GetDocument()),
        parent_(&parent),
        original_node_document_version_(node_document_->DomTreeVersion()),
        original_parent_document_version_(parent_document_->DomTreeVersion()) {}

  bool NeedsRecheck() {
    if (node_document_ != node_->GetDocument()) {
      return false;
    }
    if (node_document_->DomTreeVersion() > original_node_document_version_ + 1)
      return false;
    if (parent_document_ != parent_->GetDocument())
      return false;
    if (node_document_ == parent_document_)
      return true;
    return parent_document_->DomTreeVersion() ==
           original_parent_document_version_;
  }

 private:
  const Node* const node_;
  Document* const node_document_;
  Document* const parent_document_;
  const Node* const parent_;
  const uint64_t original_node_document_version_;
  const uint64_t original_parent_document_version_;
};

inline bool CheckReferenceChildParent(const Node& parent,
                                      const Node* next,
                                      const Node* old_child,
                                      ExceptionState& exception_state) {
  if (next && next->parentNode() != &parent) {
    exception_state.ThrowDOMException(DOMExceptionCode::kNotFoundError,
                                      "The node before which the new node is "
                                      "to be inserted is not a child of this "
                                      "node.");
    return false;
  }
  if (old_child && old_child->parentNode() != &parent) {
    exception_state.ThrowDOMException(
        DOMExceptionCode::kNotFoundError,
        "The node to be replaced is not a child of this node.");
    return false;
  }
  return true;
}

}  // namespace

// This dispatches various events; DOM mutation events, blur events, IFRAME
// unload events, etc.
// Returns true if DOM mutation should be proceeded.
static inline bool CollectChildrenAndRemoveFromOldParent(
    Node& node,
    NodeVector& nodes,
    ExceptionState& exception_state) {
  if (auto* fragment = DynamicTo<DocumentFragment>(node)) {
    GetChildNodes(*fragment, nodes);
    if (fragment->HoldsUnnotifiedChildren()) {
      fragment->ForgetChildren();
    } else {
      fragment->RemoveChildren();
    }
    return !nodes.empty();
  }
  nodes.push_back(&node);
  node.remove(exception_state);
  return !exception_state.HadException() && !nodes.empty();
}

void ContainerNode::ParserTakeAllChildrenFrom(ContainerNode& old_parent) {
  while (Node* child = old_parent.firstChild()) {
    // Explicitly remove since appending can fail, but this loop shouldn't be
    // infinite.
    old_parent.ParserRemoveChild(*child);
    ParserAppendChild(child);
  }
}

ContainerNode::~ContainerNode() {
  DCHECK(isConnected() || !NeedsStyleRecalc());
}

// Returns true if |new_child| contains this node. In that case,
// |exception_state| has an exception.
// https://dom.spec.whatwg.org/#concept-tree-host-including-inclusive-ancestor
bool ContainerNode::IsHostIncludingInclusiveAncestorOfThis(
    const Node& new_child,
    ExceptionState& exception_state) const {
  // Non-ContainerNode can contain nothing.
  if (!new_child.IsContainerNode())
    return false;

  bool child_contains_parent = false;
  if (IsInShadowTree() || GetDocument().IsTemplateDocument()) {
    child_contains_parent = new_child.ContainsIncludingHostElements(*this);
  } else {
    const Node& root = TreeRoot();
    auto* fragment = DynamicTo<DocumentFragment>(root);
    if (fragment && fragment->IsTemplateContent()) {
      child_contains_parent = new_child.ContainsIncludingHostElements(*this);
    } else {
      child_contains_parent = new_child.contains(this);
    }
  }
  if (child_contains_parent) {
    exception_state.ThrowDOMException(
        DOMExceptionCode::kHierarchyRequestError,
        "The new child element contains the parent.");
  }
  return child_contains_parent;
}

// EnsurePreInsertionValidity() is an implementation of step 2 to 6 of
// https://dom.spec.whatwg.org/#concept-node-ensure-pre-insertion-validity and
// https://dom.spec.whatwg.org/#concept-node-replace .
DISABLE_CFI_PERF
bool ContainerNode::EnsurePreInsertionValidity(
    const Node* new_child,
    const VectorOf<Node>* new_children,
    const Node* next,
    const Node* old_child,
    ExceptionState& exception_state) const {
  DCHECK(!(next && old_child));
  CHECK_NE(!new_child, !new_children);

  // Use common case fast path if possible.
  if (new_child && (new_child->IsElementNode() || new_child->IsTextNode()) &&
      IsElementNode()) {
    DCHECK(ChildTypeAllowed(new_child->getNodeType()));
    // 2. If node is a host-including inclusive ancestor of parent, throw a
    // HierarchyRequestError.
    if (IsHostIncludingInclusiveAncestorOfThis(*new_child, exception_state)) {
      return false;
    }
    // 3. If child is not null and its parent is not parent, then throw a
    // NotFoundError.
    return CheckReferenceChildParent(*this, next, old_child, exception_state);
  }

  // This should never happen, but also protect release builds from tree
  // corruption.
  if (new_child) {
    CHECK(!new_child->IsPseudoElement());
  } else {
    for (const Node* child : *new_children) {
      CHECK(!child->IsPseudoElement());
    }
  }

  if (auto* document = DynamicTo<Document>(this)) {
    // Step 2 is unnecessary. No one can have a Document child.
    // Step 3:
    if (!CheckReferenceChildParent(*this, next, old_child, exception_state))
      return false;
    // Step 4-6.
    return document->CanAcceptChild(new_child, new_children, next, old_child,
                                    exception_state);
  }

  // 2. If node is a host-including inclusive ancestor of parent, throw a
  // HierarchyRequestError.
  if (new_child) {
    if (IsHostIncludingInclusiveAncestorOfThis(*new_child, exception_state)) {
      return false;
    }
  } else {
    for (const Node* child : *new_children) {
      if (IsHostIncludingInclusiveAncestorOfThis(*child, exception_state)) {
        return false;
      }
    }
  }

  // 3. If child is not null and its parent is not parent, then throw a
  // NotFoundError.
  if (!CheckReferenceChildParent(*this, next, old_child, exception_state))
    return false;

  // 4. If node is not a DocumentFragment, DocumentType, Element, Text,
  // ProcessingInstruction, or Comment node, throw a HierarchyRequestError.
  // 5. If either node is a Text node and parent is a document, or node is a
  // doctype and parent is not a document, throw a HierarchyRequestError.
  auto is_child_allowed = [&](const Node* child) -> bool {
    if (!ChildTypeAllowed(child->getNodeType())) {
      exception_state.ThrowDOMException(
          DOMExceptionCode::kHierarchyRequestError,
          WTF::StrCat({"Nodes of type '", child->nodeName(),
                       "' may not be inserted inside nodes of type '",
                       nodeName(), "'."}));
      return false;
    }
    return true;
  };
  if (new_children) {
    for (const Node* child : *new_children) {
      if (!is_child_allowed(child)) {
        return false;
      }
    }
  } else if (auto* child_fragment = DynamicTo<DocumentFragment>(new_child)) {
    for (Node* node = child_fragment->firstChild(); node;
         node = node->nextSibling()) {
      if (!is_child_allowed(node)) {
        return false;
      }
    }
  } else {
    if (!is_child_allowed(new_child)) {
      return false;
    }
  }
  // Step 6 is unnecessary for non-Document nodes.
  return true;
}

// We need this extra structural check because prior DOM mutation operations
// dispatched synchronous events, so their handlers may have modified DOM
// trees.
bool ContainerNode::RecheckNodeInsertionStructuralPrereq(
    const NodeVector& new_children,
    const Node* next,
    ExceptionState& exception_state) {
  for (const auto& child : new_children) {
    if (child->parentNode()) {
      // A new child was added to another parent before adding to this
      // node.  Firefox and Edge don't throw in this case.
      return false;
    }
    if (auto* document = DynamicTo<Document>(this)) {
      // For Document, no need to check host-including inclusive ancestor
      // because a Document node can't be a child of other nodes.
      // However, status of existing doctype or root element might be changed
      // and we need to check it again.
      if (!document->CanAcceptChild(child, /*new_children*/ nullptr, next,
                                    /*old_child*/ nullptr, exception_state)) {
        return false;
      }
    } else {
      if (IsHostIncludingInclusiveAncestorOfThis(*child, exception_state))
        return false;
    }
  }
  return CheckReferenceChildParent(*this, next, nullptr, exception_state);
}

template <typename Functor>
void ContainerNode::InsertNodeVector(
    const NodeVector& targets,
    Node* next,
    const Functor& mutator,
    NodeVector& post_insertion_notification_targets) {
  probe::WillInsertDOMNode(this);
  {
    EventDispatchForbiddenScope assert_no_event_dispatch;
    ScriptForbiddenScope forbid_script;
    for (const auto& target_node : targets) {
      DCHECK(target_node);
      DCHECK(!target_node->parentNode());
      Node& child = *target_node;
      mutator(*this, child, next);
      ChildListMutationScope(*this).ChildAdded(child);
      if (GetDocument().MayContainShadowRoots())
        child.CheckSlotChangeAfterInserted();
      probe::DidInsertDOMNode(&child);
      NotifyNodeInsertedInternal(child, post_insertion_notification_targets);
    }
  }
}

void ContainerNode::DidInsertNodeVector(
    const NodeVector& targets,
    Node* next,
    const NodeVector& post_insertion_notification_targets) {
  Node* unchanged_previous =
      targets.size() > 0 ? targets[0]->previousSibling() : nullptr;
  const Document& document = GetDocument();
  for (const auto& target_node : targets) {
    ChildrenChanged(ChildrenChange::ForInsertion(
        *target_node, unchanged_previous, next, ChildrenChangeSource::kAPI));
    CheckSoftNavigationHeuristicsTracking(document, *target_node);
  }
  for (const auto& descendant : post_insertion_notification_targets) {
    if (descendant->isConnected())
      descendant->DidNotifySubtreeInsertionsToDocument();
  }
  for (const auto& target_node : targets) {
    if (target_node->parentNode() == this)
      DispatchChildInsertionEvents(*target_node);
  }
  DispatchSubtreeModifiedEvent();
}

class ContainerNode::AdoptAndInsertBefore {
 public:
  inline void operator()(ContainerNode& container,
                         Node& child,
                         Node* next) const {
    DCHECK(next);
    DCHECK_EQ(next->parentNode(), &container);
    container.GetTreeScope().AdoptIfNeeded(child);
    container.InsertBeforeCommon(*next, child);
  }
};

class ContainerNode::AdoptAndAppendChild {
 public:
  inline void operator()(ContainerNode& container, Node& child, Node*) const {
    container.GetTreeScope().AdoptIfNeeded(child);
    container.AppendChildCommon(child);
  }
};

void ContainerNode::InsertBefore(const VectorOf<Node>& new_children,
                                 Node* ref_child,
                                 ExceptionState& exception_state) {
  // https://dom.spec.whatwg.org/#concept-node-pre-insert

  // insertBefore(node, null) is equivalent to appendChild(node)
  if (!ref_child) {
    AppendChildren(new_children, exception_state);
    return;
  }

  if (!EnsurePreInsertionValidity(/*new_child*/ nullptr, &new_children,
                                  ref_child, /*old_child*/ nullptr,
                                  exception_state)) {
    return;
  }

  if (new_children.size() == 1u) {
    // If there's exactly one child then Node::ConvertNodeUnionsIntoNodes
    // didn't remove it from the old parent.
    Node* new_child = new_children[0];

    // 2. Let reference child be child.
    // 3. If reference child is node, set it to node’s next sibling.
    if (ref_child == new_child) {
      if (!new_child->HasNextSibling()) {
        return AppendChildren(new_children, exception_state);
      }
      ref_child = new_child->nextSibling();
    }

    DOMTreeMutationDetector detector(*new_child, *this);
    new_child->remove(exception_state);
    if (exception_state.HadException()) {
      return;
    }
    if (!detector.NeedsRecheck() &&
        !RecheckNodeInsertionStructuralPrereq(new_children, ref_child,
                                              exception_state)) {
      return;
    }
  }

  // 4. Adopt node into parent’s node document.
  // 5. Insert node into parent before reference child.
  NodeVector post_insertion_notification_targets;
  {
    SlotAssignmentRecalcForbiddenScope forbid_slot_recalc(GetDocument());
    ChildListMutationScope mutation(*this);
    InsertNodeVector(new_children, ref_child, AdoptAndInsertBefore(),
                     post_insertion_notification_targets);
  }
  DidInsertNodeVector(new_children, ref_child,
                      post_insertion_notification_targets);
}

Node* ContainerNode::InsertBefore(Node* new_child,
                                  Node* ref_child,
                                  ExceptionState& exception_state) {
  DCHECK(new_child);
  // https://dom.spec.whatwg.org/#concept-node-pre-insert

  // insertBefore(node, null) is equivalent to appendChild(node)
  if (!ref_child)
    return AppendChild(new_child, exception_state);

  // 1. Ensure pre-insertion validity of node into parent before child.
  if (!EnsurePreInsertionValidity(new_child, /*new_children*/ nullptr,
                                  ref_child, /*old_child*/ nullptr,
                                  exception_state)) {
    return new_child;
  }

  // 2. Let reference child be child.
  // 3. If reference child is node, set it to node’s next sibling.
  if (ref_child == new_child) {
    if (!new_child->HasNextSibling()) {
      return AppendChild(new_child, exception_state);
    }
    ref_child = new_child->nextSibling();
  }

  // 4. Adopt node into parent’s node document.
  NodeVector targets;
  DOMTreeMutationDetector detector(*new_child, *this);
  if (!CollectChildrenAndRemoveFromOldParent(*new_child, targets,
                                             exception_state))
    return new_child;
  if (!detector.NeedsRecheck()) {
    if (!RecheckNodeInsertionStructuralPrereq(targets, ref_child,
                                              exception_state))
      return new_child;
  }

  // 5. Insert node into parent before reference child.
  NodeVector post_insertion_notification_targets;
  {
    SlotAssignmentRecalcForbiddenScope forbid_slot_recalc(GetDocument());
    ChildListMutationScope mutation(*this);
    InsertNodeVector(targets, ref_child, AdoptAndInsertBefore(),
                     post_insertion_notification_targets);
  }
  DidInsertNodeVector(targets, ref_child, post_insertion_notification_targets);
  return new_child;
}

Node* ContainerNode::InsertBefore(Node* new_child, Node* ref_child) {
  return InsertBefore(new_child, ref_child, ASSERT_NO_EXCEPTION);
}

void ContainerNode::InsertBeforeCommon(Node& next_child, Node& new_child) {
#if DCHECK_IS_ON()
  DCHECK(EventDispatchForbiddenScope::IsEventDispatchForbidden());
#endif
  DCHECK(ScriptForbiddenScope::IsScriptForbidden());
  // Use insertBefore if you need to handle reparenting (and want DOM mutation
  // events).
  DCHECK(!new_child.parentNode());
  DCHECK(!new_child.HasNextSibling());
  DCHECK(!new_child.HasPreviousSibling());
  DCHECK(!new_child.IsShadowRoot());

  Node* prev = next_child.previousSibling();
  DCHECK_NE(last_child_, prev);
  next_child.SetPreviousSibling(&new_child);
  if (prev) {
    DCHECK_NE(firstChild(), next_child);
    DCHECK_EQ(prev->nextSibling(), next_child);
    prev->SetNextSibling(&new_child);
  } else {
    DCHECK(firstChild() == next_child);
    SetFirstChild(&new_child);
  }
  new_child.SetParentNode(this);
  new_child.SetPreviousSibling(prev);
  new_child.SetNextSibling(&next_child);
}

void ContainerNode::AppendChildCommon(Node& child) {
#if DCHECK_IS_ON()
  DCHECK(EventDispatchForbiddenScope::IsEventDispatchForbidden());
#endif
  DCHECK(ScriptForbiddenScope::IsScriptForbidden());

  child.SetParentNode(this);
  if (last_child_) {
    child.SetPreviousSibling(last_child_);
    last_child_->SetNextSibling(&child);
  } else {
    SetFirstChild(&child);
  }
  SetLastChild(&child);
}

bool ContainerNode::CheckParserAcceptChild(const Node& new_child) const {
  auto* document = DynamicTo<Document>(this);
  if (!document)
    return true;
  // TODO(esprehn): Are there other conditions where the parser can create
  // invalid trees?
  return document->CanAcceptChild(&new_child, /*new_children*/ nullptr,
                                  /*next*/ nullptr, /*old_child*/ nullptr,
                                  IGNORE_EXCEPTION_FOR_TESTING);
}

void ContainerNode::ParserInsertBefore(Node* new_child, Node& next_child) {
  DCHECK(new_child);
  DCHECK(next_child.parentNode() == this ||
         (DynamicTo<DocumentFragment>(this) &&
          DynamicTo<DocumentFragment>(this)->IsTemplateContent()));
  DCHECK(!new_child->IsDocumentFragment());
  DCHECK(!IsA<HTMLTemplateElement>(this));

  if (next_child.previousSibling() == new_child ||
      &next_child == new_child)  // nothing to do
    return;

  if (!CheckParserAcceptChild(*new_child))
    return;

  // FIXME: parserRemoveChild can run script which could then insert the
  // newChild back into the page. Loop until the child is actually removed.
  // See: fast/parser/execute-script-during-adoption-agency-removal.html
  while (ContainerNode* parent = new_child->parentNode())
    parent->ParserRemoveChild(*new_child);

  // This can happen if foster parenting moves nodes into a template
  // content document, but next_child is still a "direct" child of the
  // template.
  if (next_child.parentNode() != this)
    return;

  if (GetDocument() != new_child->GetDocument())
    GetDocument().adoptNode(new_child, ASSERT_NO_EXCEPTION);

  {
    EventDispatchForbiddenScope assert_no_event_dispatch;
    ScriptForbiddenScope forbid_script;

    AdoptAndInsertBefore()(*this, *new_child, &next_child);
    DCHECK_EQ(new_child->ConnectedSubframeCount(), 0u);
    ChildListMutationScope(*this).ChildAdded(*new_child);
  }

  NotifyNodeInserted(*new_child, ChildrenChangeSource::kParser);
}

void ContainerNode::ReplaceChild(const VectorOf<Node>& new_children,
                                 Node* old_child,
                                 ExceptionState& exception_state) {
  // https://dom.spec.whatwg.org/#concept-node-replace
  if (!old_child) {
    exception_state.ThrowDOMException(DOMExceptionCode::kNotFoundError,
                                      "The node to be replaced is null.");
    return;
  }

  if (!EnsurePreInsertionValidity(/*new_child*/ nullptr, &new_children,
                                  /*next*/ nullptr, old_child,
                                  exception_state)) {
    return;
  }

  // 7. Let reference child be child’s next sibling.
  Node* next = old_child->nextSibling();

  bool needs_recheck = false;
  if (new_children.size() == 1u) {
    // If there's exactly one child then Node::ConvertNodeUnionsIntoNodes
    // didn't remove it from the old parent.
    Node* new_child = new_children[0];

    // 8. If reference child is node, set it to node’s next sibling.
    if (next == new_child) {
      next = new_child->nextSibling();
    }

    // Though the following CollectChildrenAndRemoveFromOldParent() also calls
    // RemoveChild(), we'd like to call RemoveChild() here to make a separated
    // MutationRecord.
    DOMTreeMutationDetector detector(*new_child, *this);
    new_child->remove(exception_state);
    if (exception_state.HadException()) {
      return;
    }
    if (!detector.NeedsRecheck()) {
      needs_recheck = true;
    }
  }

  NodeVector post_insertion_notification_targets;
  {
    // 9. Let previousSibling be child’s previous sibling.
    // 11. Let removedNodes be the empty list.
    // 15. Queue a mutation record of "childList" for target parent with
    // addedNodes nodes, removedNodes removedNodes, nextSibling reference child,
    // and previousSibling previousSibling.
    ChildListMutationScope mutation(*this);

    // 12. If child’s parent is not null, run these substeps:
    //    1. Set removedNodes to a list solely containing child.
    //    2. Remove child from its parent with the suppress observers flag set.
    if (ContainerNode* old_child_parent = old_child->parentNode()) {
      DOMTreeMutationDetector detector(*old_child, *this);
      old_child_parent->RemoveChild(old_child, exception_state);
      if (exception_state.HadException()) {
        return;
      }
      if (!detector.NeedsRecheck()) {
        needs_recheck = true;
      }
    }

    if (needs_recheck && !RecheckNodeInsertionStructuralPrereq(
                             new_children, next, exception_state)) {
      return;
    }

    SlotAssignmentRecalcForbiddenScope forbid_slot_recalc(GetDocument());

    // 10. Adopt node into parent’s node document.
    // 14. Insert node into parent before reference child with the suppress
    // observers flag set.
    if (next) {
      InsertNodeVector(new_children, next, AdoptAndInsertBefore(),
                       post_insertion_notification_targets);
    } else {
      InsertNodeVector(new_children, nullptr, AdoptAndAppendChild(),
                       post_insertion_notification_targets);
    }
  }
  DidInsertNodeVector(new_children, next, post_insertion_notification_targets);
}

Node* ContainerNode::ReplaceChild(Node* new_child,
                                  Node* old_child,
                                  ExceptionState& exception_state) {
  DCHECK(new_child);
  // https://dom.spec.whatwg.org/#concept-node-replace

  if (!old_child) {
    exception_state.ThrowDOMException(DOMExceptionCode::kNotFoundError,
                                      "The node to be replaced is null.");
    return nullptr;
  }

  // Step 2 to 6.
  if (!EnsurePreInsertionValidity(new_child, /*new_children*/ nullptr,
                                  /*next*/ nullptr, old_child,
                                  exception_state)) {
    return old_child;
  }

  // 7. Let reference child be child’s next sibling.
  Node* next = old_child->nextSibling();
  // 8. If reference child is node, set it to node’s next sibling.
  if (next == new_child)
    next = new_child->nextSibling();

  bool needs_recheck = false;
  // 10. Adopt node into parent’s node document.
  // TODO(tkent): Actually we do only RemoveChild() as a part of 'adopt'
  // operation.
  //
  // Though the following CollectChildrenAndRemoveFromOldParent() also calls
  // RemoveChild(), we'd like to call RemoveChild() here to make a separated
  // MutationRecord.
  if (ContainerNode* new_child_parent = new_child->parentNode()) {
    DOMTreeMutationDetector detector(*new_child, *this);
    new_child_parent->RemoveChild(new_child, exception_state);
    if (exception_state.HadException())
      return nullptr;
    if (!detector.NeedsRecheck())
      needs_recheck = true;
  }

  NodeVector targets;
  NodeVector post_insertion_notification_targets;
  {
    // 9. Let previousSibling be child’s previous sibling.
    // 11. Let removedNodes be the empty list.
    // 15. Queue a mutation record of "childList" for target parent with
    // addedNodes nodes, removedNodes removedNodes, nextSibling reference child,
    // and previousSibling previousSibling.
    ChildListMutationScope mutation(*this);

    // 12. If child’s parent is not null, run these substeps:
    //    1. Set removedNodes to a list solely containing child.
    //    2. Remove child from its parent with the suppress observers flag set.
    if (ContainerNode* old_child_parent = old_child->parentNode()) {
      DOMTreeMutationDetector detector(*old_child, *this);
      old_child_parent->RemoveChild(old_child, exception_state);
      if (exception_state.HadException())
        return nullptr;
      if (!detector.NeedsRecheck())
        needs_recheck = true;
    }

    SlotAssignmentRecalcForbiddenScope forbid_slot_recalc(GetDocument());

    // 13. Let nodes be node’s children if node is a DocumentFragment node, and
    // a list containing solely node otherwise.
    DOMTreeMutationDetector detector(*new_child, *this);
    if (!CollectChildrenAndRemoveFromOldParent(*new_child, targets,
                                               exception_state))
      return old_child;
    if (!detector.NeedsRecheck() || needs_recheck) {
      if (!RecheckNodeInsertionStructuralPrereq(targets, next, exception_state))
        return old_child;
    }

    // 10. Adopt node into parent’s node document.
    // 14. Insert node into parent before reference child with the suppress
    // observers flag set.
    if (next) {
      InsertNodeVector(targets, next, AdoptAndInsertBefore(),
                       post_insertion_notification_targets);
    } else {
      InsertNodeVector(targets, nullptr, AdoptAndAppendChild(),
                       post_insertion_notification_targets);
    }
  }
  DidInsertNodeVector(targets, next, post_insertion_notification_targets);

  // 16. Return child.
  return old_child;
}

Node* ContainerNode::ReplaceChild(Node* new_child, Node* old_child) {
  return ReplaceChild(new_child, old_child, ASSERT_NO_EXCEPTION);
}

void ContainerNode::WillRemoveChild(Node& child) {
  DCHECK_EQ(child.parentNode(), this);
  ChildListMutationScope(*this).WillRemoveChild(child);
  child.NotifyMutationObserversNodeWillDetach();
  DispatchChildRemovalEvents(child);

  // Only disconnect subframes in the non-state-preserving-atomic-move case,
  // i.e., the traditional case where we intend to *fully* remove a node from
  // the tree, instead of atomically re-inserting it.
  if (!GetDocument().StatePreservingAtomicMoveInProgress()) {
    // TODO(crbug.com/40150299): Mutation events should be suppressed during a
    // state-preserving atomic move. Once this is implemented, enable the
    // following CHECK which asserts that during this kind of move, the child
    // node could not have moved documents during `DispatchChildRemovalEvents()`
    // above.
    //
    // CHECK_EQ(GetDocument(), child.GetDocument());
    ChildFrameDisconnector(
        child, ChildFrameDisconnector::DisconnectReason::kDisconnectSelf)
        .Disconnect();
  }

  if (GetDocument() != child.GetDocument()) {
    // |child| was moved to another document by the DOM mutation event handler.
    return;
  }

  // |nodeWillBeRemoved()| must be run after |ChildFrameDisconnector|, because
  // |ChildFrameDisconnector| may remove the node, resulting in an invalid
  // state.
  ScriptForbiddenScope script_forbidden_scope;
  EventDispatchForbiddenScope assert_no_event_dispatch;
  // e.g. mutation event listener can create a new range.
  GetDocument().NodeWillBeRemoved(child);

  if (auto* child_element = DynamicTo<Element>(child)) {
    if (auto* context = child_element->GetDisplayLockContext())
      context->NotifyWillDisconnect();
  }
}

void ContainerNode::WillRemoveChildren() {
  NodeVector children;
  GetChildNodes(*this, children);

  ChildListMutationScope mutation(*this);
  for (const auto& node : children) {
    DCHECK(node);
    Node& child = *node;
    mutation.WillRemoveChild(child);
    child.NotifyMutationObserversNodeWillDetach();
    DispatchChildRemovalEvents(child);
  }

  // Only disconnect subframes in the non-state-preserving-atomic-move case,
  // i.e., the traditional case where we intend to *fully* remove a node from
  // the tree, instead of atomically re-inserting it.
  if (!GetDocument().StatePreservingAtomicMoveInProgress()) {
    ChildFrameDisconnector(
        *this, ChildFrameDisconnector::DisconnectReason::kDisconnectSelf)
        .Disconnect(ChildFrameDisconnector::kDescendantsOnly);
  }
}

LayoutBox* ContainerNode::GetLayoutBoxForScrolling() const {
  LayoutBox* box = GetLayoutBox();
  if (box) {
    box = box->ContentLayoutBox();
  }
  return box && box->IsScrollContainer() ? box : nullptr;
}

bool ContainerNode::IsReadingFlowContainer() const {
  return GetLayoutBox() && GetLayoutBox()->IsReadingFlowContainer();
}

void ContainerNode::Trace(Visitor* visitor) const {
  visitor->Trace(first_child_);
  visitor->Trace(last_child_);
  Node::Trace(visitor);
}

static bool ShouldMergeCombinedTextAfterRemoval(const Node& old_child) {
  DCHECK(!old_child.parentNode()->GetForceReattachLayoutTree());

  auto* const layout_object = old_child.GetLayoutObject();
  if (!layout_object)
    return false;

  // Request to merge previous and next |LayoutTextCombine| of |child|.
  // See http:://crbug.com/1227066
  auto* const previous_sibling = layout_object->PreviousSibling();
  if (!previous_sibling)
    return false;
  auto* const next_sibling = layout_object->NextSibling();
  if (!next_sibling)
    return false;
  if (IsA<LayoutTextCombine>(previous_sibling) &&
      IsA<LayoutTextCombine>(next_sibling)) [[unlikely]] {
    return true;
  }

  // Request to merge combined texts in anonymous block.
  // See http://crbug.com/1233432
  if (!previous_sibling->IsAnonymousBlockFlow() ||
      !next_sibling->IsAnonymousBlockFlow()) {
    return false;
  }

  if (IsA<LayoutTextCombine>(previous_sibling->SlowLastChild()) &&
      IsA<LayoutTextCombine>(next_sibling->SlowFirstChild())) [[unlikely]] {
    return true;
  }
  return false;
}

Node* ContainerNode::RemoveChild(Node* old_child,
                                 ExceptionState& exception_state) {
  // NotFoundError: Raised if oldChild is not a child of this node.
  // FIXME: We should never really get PseudoElements in here, but editing will
  // sometimes attempt to remove them still. We should fix that and enable this
  // DCHECK.  DCHECK(!oldChild->isPseudoElement())
  if (!old_child || old_child->parentNode() != this ||
      old_child->IsPseudoElement()) {
    exception_state.ThrowDOMException(
        DOMExceptionCode::kNotFoundError,
        "The node to be removed is not a child of this node.");
    return nullptr;
  }

  Node* child = old_child;

  if (!GetDocument().StatePreservingAtomicMoveInProgress()) {
    GetDocument().RemoveFocusedElementOfSubtree(*child);
  }

  // Events fired when blurring currently focused node might have moved this
  // child into a different parent.
  if (child->parentNode() != this) {
    exception_state.ThrowDOMException(
        DOMExceptionCode::kNotFoundError,
        "The node to be removed is no longer a "
        "child of this node. Perhaps it was moved "
        "in a 'blur' event handler?");
    return nullptr;
  }

  WillRemoveChild(*child);

  // TODO(crbug.com/927646): |WillRemoveChild()| may dispatch events that set
  // focus to a node that will be detached, leaving behind a detached focused
  // node. Fix it.

  // Mutation events might have moved this child into a different parent.
  if (child->parentNode() != this) {
    exception_state.ThrowDOMException(
        DOMExceptionCode::kNotFoundError,
        "The node to be removed is no longer a "
        "child of this node. Perhaps it was moved "
        "in response to a mutation?");
    return nullptr;
  }

  if (!GetForceReattachLayoutTree() &&
      ShouldMergeCombinedTextAfterRemoval(*child)) [[unlikely]] {
    SetForceReattachLayoutTree();
  }

  {
    HTMLFrameOwnerElement::PluginDisposeSuspendScope suspend_plugin_dispose;
    TreeOrderedMap::RemoveScope tree_remove_scope;
    StyleEngine& engine = GetDocument().GetStyleEngine();
    StyleEngine::DetachLayoutTreeScope detach_scope(engine);
    Node* prev = child->previousSibling();
    Node* next = child->nextSibling();
    {
      SlotAssignmentRecalcForbiddenScope forbid_slot_recalc(GetDocument());
      StyleEngine::DOMRemovalScope style_scope(engine);
      RemoveBetween(prev, next, *child);
      NotifyNodeRemoved(*child);
    }
    ChildrenChanged(ChildrenChange::ForRemoval(*child, prev, next,
                                               ChildrenChangeSource::kAPI));
  }
  DispatchSubtreeModifiedEvent();
  return child;
}

Node* ContainerNode::RemoveChild(Node* old_child) {
  return RemoveChild(old_child, ASSERT_NO_EXCEPTION);
}

void ContainerNode::RemoveBetween(Node* previous_child,
                                  Node* next_child,
                                  Node& old_child) {
  EventDispatchForbiddenScope assert_no_event_dispatch;

  DCHECK_EQ(old_child.parentNode(), this);

  if (InActiveDocument() &&
      !GetDocument().StatePreservingAtomicMoveInProgress()) {
    old_child.DetachLayoutTree();
  }

  if (next_child)
    next_child->SetPreviousSibling(previous_child);
  if (previous_child)
    previous_child->SetNextSibling(next_child);
  if (first_child_ == &old_child)
    SetFirstChild(next_child);
  if (last_child_ == &old_child)
    SetLastChild(previous_child);

  old_child.SetPreviousSibling(nullptr);
  old_child.SetNextSibling(nullptr);
  old_child.SetParentNode(nullptr);

  GetDocument().AdoptIfNeeded(old_child);
}

void ContainerNode::ParserRemoveChild(Node& old_child) {
  DCHECK_EQ(old_child.parentNode(), this);
  DCHECK(!old_child.IsDocumentFragment());

  // This may cause arbitrary Javascript execution via onunload handlers.
  CHECK(!GetDocument().StatePreservingAtomicMoveInProgress());
  if (old_child.ConnectedSubframeCount()) {
    ChildFrameDisconnector(
        old_child, ChildFrameDisconnector::DisconnectReason::kDisconnectSelf)
        .Disconnect();
  }
  if (old_child.parentNode() != this)
    return;

  ChildListMutationScope(*this).WillRemoveChild(old_child);
  old_child.NotifyMutationObserversNodeWillDetach();

  HTMLFrameOwnerElement::PluginDisposeSuspendScope suspend_plugin_dispose;
  TreeOrderedMap::RemoveScope tree_remove_scope;
  StyleEngine& engine = GetDocument().GetStyleEngine();
  StyleEngine::DetachLayoutTreeScope detach_scope(engine);

  Node* prev = old_child.previousSibling();
  Node* next = old_child.nextSibling();
  {
    StyleEngine::DOMRemovalScope style_scope(engine);
    RemoveBetween(prev, next, old_child);
    NotifyNodeRemoved(old_child);
  }
  ChildrenChanged(ChildrenChange::ForRemoval(old_child, prev, next,
                                             ChildrenChangeSource::kParser));
}

// This differs from other remove functions because it forcibly removes all the
// children, regardless of read-only status or event exceptions, e.g.
void ContainerNode::RemoveChildren(SubtreeModificationAction action) {
  if (!first_child_)
    return;

  // Do any prep work needed before actually starting to detach
  // and remove... e.g. stop loading frames, fire unload events.
  WillRemoveChildren();

  {
    // Removing focus can cause frames to load, either via events (focusout,
    // blur) or widget updates (e.g., for <embed>).
    SubframeLoadingDisabler disabler(*this);

    // Exclude this node when looking for removed focusedElement since only
    // children will be removed.
    // This must be later than willRemoveChildren, which might change focus
    // state of a child.
    GetDocument().RemoveFocusedElementOfSubtree(*this, true);

    // Removing a node from a selection can cause widget updates.
    GetDocument().NodeChildrenWillBeRemoved(*this);
  }

  HeapVector<Member<Node>> removed_nodes;
  const bool children_changed = ChildrenChangedAllChildrenRemovedNeedsList();
  {
    HTMLFrameOwnerElement::PluginDisposeSuspendScope suspend_plugin_dispose;
    TreeOrderedMap::RemoveScope tree_remove_scope;
    StyleEngine& engine = GetDocument().GetStyleEngine();
    StyleEngine::DetachLayoutTreeScope detach_scope(engine);
    bool has_element_child = false;
    {
      SlotAssignmentRecalcForbiddenScope forbid_slot_recalc(GetDocument());
      StyleEngine::DOMRemovalScope style_scope(engine);
      EventDispatchForbiddenScope assert_no_event_dispatch;
      ScriptForbiddenScope forbid_script;

      while (Node* child = first_child_) {
        if (child->IsElementNode()) {
          has_element_child = true;
        }
        RemoveBetween(nullptr, child->nextSibling(), *child);
        NotifyNodeRemoved(*child);
        if (children_changed)
          removed_nodes.push_back(child);
      }
    }

    ChildrenChange change = {
        .type = ChildrenChangeType::kAllChildrenRemoved,
        .by_parser = ChildrenChangeSource::kAPI,
        .affects_elements = has_element_child
                                ? ChildrenChangeAffectsElements::kYes
                                : ChildrenChangeAffectsElements::kNo,
        .removed_nodes = std::move(removed_nodes)};
    ChildrenChanged(change);
  }

  if (action == kDispatchSubtreeModifiedEvent)
    DispatchSubtreeModifiedEvent();
}

void ContainerNode::AppendChildren(const VectorOf<Node>& new_children,
                                   ExceptionState& exception_state) {
  if (!EnsurePreInsertionValidity(/*new_child*/ nullptr, &new_children,
                                  /*next*/ nullptr, /*old_child*/ nullptr,
                                  exception_state)) {
    return;
  }

  if (new_children.size() == 1u) {
    // If there's exactly one child then Node::ConvertNodeUnionsIntoNodes
    // didn't remove it from the old parent.
    Node* new_child = new_children[0];
    DOMTreeMutationDetector detector(*new_child, *this);
    new_child->remove(exception_state);
    if (exception_state.HadException()) {
      return;
    }
    if (!detector.NeedsRecheck() &&
        !RecheckNodeInsertionStructuralPrereq(new_children, nullptr,
                                              exception_state)) {
      return;
    }
  }

  NodeVector post_insertion_notification_targets;
  {
    SlotAssignmentRecalcForbiddenScope forbid_slot_recalc(GetDocument());
    ChildListMutationScope mutation(*this);
    InsertNodeVector(new_children, nullptr, AdoptAndAppendChild(),
                     post_insertion_notification_targets);
  }
  DidInsertNodeVector(new_children, nullptr,
                      post_insertion_notification_targets);
}

Node* ContainerNode::AppendChild(Node* new_child,
                                 ExceptionState& exception_state) {
  DCHECK(new_child);
  // Make sure adding the new child is ok
  if (!EnsurePreInsertionValidity(new_child, /*new_children*/ nullptr,
                                  /*next*/ nullptr, /*old_child*/ nullptr,
                                  exception_state)) {
    return new_child;
  }

  NodeVector targets;
  DOMTreeMutationDetector detector(*new_child, *this);
  if (!CollectChildrenAndRemoveFromOldParent(*new_child, targets,
                                             exception_state))
    return new_child;
  if (!detector.NeedsRecheck()) {
    if (!RecheckNodeInsertionStructuralPrereq(targets, nullptr,
                                              exception_state))
      return new_child;
  }

  NodeVector post_insertion_notification_targets;
  {
    SlotAssignmentRecalcForbiddenScope forbid_slot_recalc(GetDocument());
    ChildListMutationScope mutation(*this);
    InsertNodeVector(targets, nullptr, AdoptAndAppendChild(),
                     post_insertion_notification_targets);
  }
  DidInsertNodeVector(targets, nullptr, post_insertion_notification_targets);
  return new_child;
}

Node* ContainerNode::AppendChild(Node* new_child) {
  return AppendChild(new_child, ASSERT_NO_EXCEPTION);
}

void ContainerNode::ParserAppendChild(Node* new_child) {
  DCHECK(new_child);
  DCHECK(!new_child->IsDocumentFragment());
  DCHECK(!IsA<HTMLTemplateElement>(this));

  RUNTIME_CALL_TIMER_SCOPE(GetDocument().GetAgent().isolate(),
                           RuntimeCallStats::CounterId::kParserAppendChild);

  if (!CheckParserAcceptChild(*new_child))
    return;

  // FIXME: parserRemoveChild can run script which could then insert the
  // newChild back into the page. Loop until the child is actually removed.
  // See: fast/parser/execute-script-during-adoption-agency-removal.html
  while (ContainerNode* parent = new_child->parentNode())
    parent->ParserRemoveChild(*new_child);

  if (GetDocument() != new_child->GetDocument())
    GetDocument().adoptNode(new_child, ASSERT_NO_EXCEPTION);

  {
    EventDispatchForbiddenScope assert_no_event_dispatch;
    ScriptForbiddenScope forbid_script;

    AdoptAndAppendChild()(*this, *new_child, nullptr);
    DCHECK_EQ(new_child->ConnectedSubframeCount(), 0u);
    ChildListMutationScope(*this).ChildAdded(*new_child);
  }

  NotifyNodeInserted(*new_child, ChildrenChangeSource::kParser);
}

void ContainerNode::ParserAppendChildInDocumentFragment(Node* new_child) {
  DCHECK(new_child);
  DCHECK(CheckParserAcceptChild(*new_child));
  DCHECK(!new_child->IsDocumentFragment());
  DCHECK(!IsA<HTMLTemplateElement>(this));
  DCHECK_EQ(new_child->GetDocument(), GetDocument());
  DCHECK_EQ(&new_child->GetTreeScope(), &GetTreeScope());
  DCHECK_EQ(new_child->parentNode(), nullptr);
  EventDispatchForbiddenScope assert_no_event_dispatch;
  ScriptForbiddenScope forbid_script;
  AppendChildCommon(*new_child);
  DCHECK_EQ(new_child->ConnectedSubframeCount(), 0u);
  // TODO(sky): This has to happen for every add. It seems like it should be
  // better factored.
  ChildListMutationScope(*this).ChildAdded(*new_child);
  probe::DidInsertDOMNode(this);
}

void ContainerNode::ParserFinishedBuildingDocumentFragment(
    ShouldNotifyInsertedNodes call_mode) {
  EventDispatchForbiddenScope assert_no_event_dispatch;
  ScriptForbiddenScope forbid_script;
  const bool may_contain_shadow_roots = GetDocument().MayContainShadowRoots();

  const ChildrenChange change =
      ChildrenChange::ForFinishingBuildingDocumentFragmentTree();
  for (Node& node : NodeTraversal::DescendantsOf(*this)) {
    NotifyNodeAtEndOfBuildingFragmentTree(node, change,
                                          may_contain_shadow_roots, call_mode);
  }

  if (call_mode == ShouldNotifyInsertedNodes::kNotify &&
      GetDocument().ShouldInvalidateNodeListCaches(nullptr)) {
    GetDocument().InvalidateNodeListCaches(nullptr);
  }
}

void ContainerNode::NotifyNodeAtEndOfBuildingFragmentTree(
    Node& node,
    const ChildrenChange& change,
    bool may_contain_shadow_roots,
    ShouldNotifyInsertedNodes call_mode) {
  // Fast path parser only creates disconnected nodes.
  DCHECK(!node.isConnected());

  if (may_contain_shadow_roots) {
    node.CheckSlotChangeAfterInserted();
  }

  // As an optimization we don't notify leaf nodes when when inserting
  // into detached subtrees that are not in a shadow tree, unless the
  // node has DOM Parts attached.
  if (!node.IsContainerNode() && !IsInShadowTree() && !node.GetDOMParts()) {
    return;
  }

  // NotifyNodeInserted() keeps a list of nodes to call
  // DidNotifySubtreeInsertionsToDocument() on if InsertedInto() returns
  // kInsertionShouldCallDidNotifySubtreeInsertions, but only if the node
  // is connected. None of the nodes are connected at this point, so it's
  // not needed here.
  if (call_mode == ShouldNotifyInsertedNodes::kNotify) {
    node.InsertedInto(*this);
  }

  if (ShadowRoot* shadow_root = node.GetShadowRoot()) {
    for (Node& shadow_node :
         NodeTraversal::InclusiveDescendantsOf(*shadow_root)) {
      NotifyNodeAtEndOfBuildingFragmentTree(
          shadow_node, change, may_contain_shadow_roots, call_mode);
    }
  }

  // No node-lists should have been created at this (otherwise
  // InvalidateNodeListCaches() would need to be called).
  DCHECK(!RareData() || !RareData()->NodeLists());

  if (node.IsContainerNode()) {
    DynamicTo<ContainerNode>(node)->ChildrenChanged(change);
  }
}

DISABLE_CFI_PERF
void ContainerNode::NotifyNodeInserted(Node& root,
                                       ChildrenChangeSource source) {
#if DCHECK_IS_ON()
  DCHECK(!EventDispatchForbiddenScope::IsEventDispatchForbidden());
#endif
  DCHECK(!root.IsShadowRoot());

  if (GetDocument().MayContainShadowRoots())
    root.CheckSlotChangeAfterInserted();

  probe::DidInsertDOMNode(&root);

  NodeVector post_insertion_notification_targets;
  NotifyNodeInsertedInternal(root, post_insertion_notification_targets);

  ChildrenChanged(ChildrenChange::ForInsertion(root, root.previousSibling(),
                                               root.nextSibling(), source));

  for (const auto& target_node : post_insertion_notification_targets) {
    if (target_node->isConnected())
      target_node->DidNotifySubtreeInsertionsToDocument();
  }
}

DISABLE_CFI_PERF
void ContainerNode::NotifyNodeInsertedInternal(
    Node& root,
    NodeVector& post_insertion_notification_targets) {
  const bool is_state_preserving_atomic_insert =
      GetDocument().StatePreservingAtomicMoveInProgress();
  EventDispatchForbiddenScope assert_no_event_dispatch;
  ScriptForbiddenScope forbid_script;

  for (Node& node : NodeTraversal::InclusiveDescendantsOf(root)) {
    // As an optimization we don't notify leaf nodes when inserting into
    // detached subtrees that are not in a shadow tree, unless the node has DOM
    // Parts attached.
    if (!isConnected() && !IsInShadowTree() && !node.IsContainerNode() &&
        !node.GetDOMParts()) {
      continue;
    }

    // Only tag the target as one that we need to call post-insertion steps on
    // if it is being *fully* inserted, and not re-inserted as part of a
    // state-preserving atomic move. That's because the post-insertion steps can
    // run script and modify the frame tree, neither of which are allowed in a
    // state-preserving atomic move.
    if (Node::kInsertionShouldCallDidNotifySubtreeInsertions ==
            node.InsertedInto(*this) &&
        !is_state_preserving_atomic_insert) {
      post_insertion_notification_targets.push_back(&node);
    }
    if (ShadowRoot* shadow_root = node.GetShadowRoot()) {
      NotifyNodeInsertedInternal(*shadow_root,
                                 post_insertion_notification_targets);
    }
  }
}

void ContainerNode::NotifyNodeRemoved(Node& root) {
  ScriptForbiddenScope forbid_script;
  EventDispatchForbiddenScope assert_no_event_dispatch;

  for (Node& node : NodeTraversal::InclusiveDescendantsOf(root)) {
    // As an optimization we skip notifying Text nodes and other leaf nodes
    // of removal when they're not in the Document tree, not in a shadow root,
    // and don't have DOM Parts, since the virtual call to removedFrom is not
    // needed.
    if (!node.IsContainerNode() && !node.IsInTreeScope() &&
        !node.GetDOMParts()) {
      continue;
    }
    node.RemovedFrom(*this);
    if (ShadowRoot* shadow_root = node.GetShadowRoot())
      NotifyNodeRemoved(*shadow_root);
  }
}

void ContainerNode::RemovedFrom(ContainerNode& insertion_point) {
  if (isConnected()) {
    if (NeedsStyleInvalidation()) {
      GetDocument()
          .GetStyleEngine()
          .GetPendingNodeInvalidations()
          .ClearInvalidation(*this);
      ClearNeedsStyleInvalidation();
    }
    ClearChildNeedsStyleInvalidation();
  }
  Node::RemovedFrom(insertion_point);
}

DISABLE_CFI_PERF
void ContainerNode::AttachLayoutTree(AttachContext& context) {
  for (Node* child = firstChild(); child; child = child->nextSibling())
    child->AttachLayoutTree(context);
  Node::AttachLayoutTree(context);
  ClearChildNeedsReattachLayoutTree();
}

void ContainerNode::DetachLayoutTree(bool performing_reattach) {
  for (Node* child = firstChild(); child; child = child->nextSibling())
    child->DetachLayoutTree(performing_reattach);
  Node::DetachLayoutTree(performing_reattach);
}

void ContainerNode::ChildrenChanged(const ChildrenChange& change) {
  GetDocument().IncDOMTreeVersion();
  GetDocument().NotifyChangeChildren(*this, change);
  if (change.type ==
      ChildrenChangeType::kFinishedBuildingDocumentFragmentTree) {
    // The rest of this is not necessary when building a DocumentFragment.
    return;
  }

  InvalidateNodeListCachesInAncestors(nullptr, nullptr, &change);
  if (change.IsChildRemoval() ||
      change.type == ChildrenChangeType::kAllChildrenRemoved) {
    GetDocument().GetStyleEngine().ChildrenRemoved(*this);
    return;
  }
  if (!change.IsChildInsertion())
    return;
  Node* inserted_node = change.sibling_changed;
  if (inserted_node->IsContainerNode() || inserted_node->IsTextNode()) {
    inserted_node->ClearFlatTreeNodeDataIfHostChanged(*this);
  } else {
    return;
  }
  if (!InActiveDocument())
    return;
  if (Element* element = DynamicTo<Element>(this)) {
    if (GetDocument().StatePreservingAtomicMoveInProgress()) {
      // This is always safe, since `inserted_node` is either an element or text
      // node, whose style can be dirtied.
      inserted_node->FlatTreeParentChanged();
    }
    if (!element->GetComputedStyle()) {
      // There is no need to mark for style recalc if the parent element does
      // not already have a ComputedStyle. For instance if we insert nodes into
      // a display:none subtree. If this ContainerNode gets a ComputedStyle
      // during the next style recalc, we will traverse into the inserted
      // children since the ComputedStyle goes from null to non-null.
      return;
    }
  }
  inserted_node->SetStyleChangeOnInsertion();
}

bool ContainerNode::ChildrenChangedAllChildrenRemovedNeedsList() const {
  return false;
}

void ContainerNode::CloneChildNodesFrom(const ContainerNode& node,
                                        NodeCloningData& data) {
  CHECK(data.Has(CloneOption::kIncludeDescendants));
  for (const Node& child : NodeTraversal::ChildrenOf(node)) {
    child.Clone(GetDocument(), data, this);
  }
}

PhysicalRect ContainerNode::BoundingBox() const {
  if (!GetLayoutObject())
    return PhysicalRect();
  return GetLayoutObject()->AbsoluteBoundingBoxRectHandlingEmptyInline();
}

HTMLCollection* ContainerNode::children() {
  return EnsureCachedCollection<HTMLCollection>(kNodeChildren);
}

Element* ContainerNode::firstElementChild() {
  return ElementTraversal::FirstChild(*this);
}

Element* ContainerNode::lastElementChild() {
  return ElementTraversal::LastChild(*this);
}

unsigned ContainerNode::childElementCount() {
  unsigned count = 0;
  for (Element* child = ElementTraversal::FirstChild(*this); child;
       child = ElementTraversal::NextSibling(*child)) {
    ++count;
  }
  return count;
}

Element* ContainerNode::querySelector(const AtomicString& selectors,
                                      ExceptionState& exception_state) {
  return QuerySelector(selectors, exception_state);
}

StaticElementList* ContainerNode::querySelectorAll(
    const AtomicString& selectors,
    ExceptionState& exception_state) {
  return QuerySelectorAll(selectors, exception_state);
}

unsigned ContainerNode::CountChildren() const {
  unsigned count = 0;
  for (Node* node = firstChild(); node; node = node->nextSibling())
    count++;
  return count;
}

Element* ContainerNode::QuerySelector(const AtomicString& selectors,
                                      ExceptionState& exception_state) {
  SelectorQuery* selector_query = GetDocument().GetSelectorQueryCache().Add(
      selectors, GetDocument(), exception_state);
  if (!selector_query)
    return nullptr;
  return selector_query->QueryFirst(*this);
}

Element* ContainerNode::QuerySelector(const AtomicString& selectors) {
  return QuerySelector(selectors, ASSERT_NO_EXCEPTION);
}

StaticElementList* ContainerNode::QuerySelectorAll(
    const AtomicString& selectors,
    ExceptionState& exception_state) {
  SelectorQuery* selector_query = GetDocument().GetSelectorQueryCache().Add(
      selectors, GetDocument(), exception_state);
  if (!selector_query)
    return nullptr;
  return selector_query->QueryAll(*this);
}

StaticElementList* ContainerNode::QuerySelectorAll(
    const AtomicString& selectors) {
  return QuerySelectorAll(selectors, ASSERT_NO_EXCEPTION);
}

static void DispatchChildInsertionEvents(Node& child) {
  Document& document = child.GetDocument();
  if (child.IsInShadowTree() || document.ShouldSuppressMutationEvents()) {
    return;
  }

#if DCHECK_IS_ON()
  DCHECK(!EventDispatchForbiddenScope::IsEventDispatchForbidden());
#endif

  Node* c = &child;

  if (c->parentNode() &&
      document.HasListenerType(Document::kDOMNodeInsertedListener)) {
    c->DispatchScopedEvent(
        *MutationEvent::Create(event_type_names::kDOMNodeInserted,
                               Event::Bubbles::kYes, c->parentNode()));
  }

  // dispatch the DOMNodeInsertedIntoDocument event to all descendants
  if (c->isConnected() && document.HasListenerType(
                              Document::kDOMNodeInsertedIntoDocumentListener)) {
    for (; c; c = NodeTraversal::Next(*c, &child)) {
      c->DispatchScopedEvent(*MutationEvent::Create(
          event_type_names::kDOMNodeInsertedIntoDocument, Event::Bubbles::kNo));
    }
  }
}

static void DispatchChildRemovalEvents(Node& child) {
  probe::WillRemoveDOMNode(&child);

  Document& document = child.GetDocument();
  if (child.IsInShadowTree() || document.ShouldSuppressMutationEvents()) {
    return;
  }

#if DCHECK_IS_ON()
  DCHECK(!EventDispatchForbiddenScope::IsEventDispatchForbidden());
#endif

  Node* c = &child;

  // Dispatch pre-removal mutation events.
  if (c->parentNode() &&
      document.HasListenerType(Document::kDOMNodeRemovedListener)) {
    NodeChildRemovalTracker scope(child);
    c->DispatchScopedEvent(
        *MutationEvent::Create(event_type_names::kDOMNodeRemoved,
                               Event::Bubbles::kYes, c->parentNode()));
  }

  // Dispatch the DOMNodeRemovedFromDocument event to all descendants.
  if (c->isConnected() &&
      document.HasListenerType(Document::kDOMNodeRemovedFromDocumentListener)) {
    NodeChildRemovalTracker scope(child);
    for (; c; c = NodeTraversal::Next(*c, &child)) {
      c->DispatchScopedEvent(*MutationEvent::Create(
          event_type_names::kDOMNodeRemovedFromDocument, Event::Bubbles::kNo));
    }
  }
}

void ContainerNode::SetRestyleFlag(DynamicRestyleFlags mask) {
  DCHECK(IsElementNode() || IsShadowRoot());
  EnsureRareData().SetRestyleFlag(mask);
}

void ContainerNode::RecalcDescendantStyles(
    const StyleRecalcChange change,
    const StyleRecalcContext& style_recalc_context,
    Element& host_or_element) {
  DCHECK(GetDocument().InStyleRecalc());
  DCHECK(!NeedsStyleRecalc());

  bool seen_any_child_elements = false;
  SelectorFilter& selector_filter =
      GetDocument().GetStyleResolver().GetSelectorFilter();
  SelectorFilter::Mark mark;

  for (Node* child = firstChild(); child; child = child->nextSibling()) {
    if (!change.TraverseChild(*child)) {
      continue;
    }
    if (auto* child_text_node = DynamicTo<Text>(child))
      child_text_node->RecalcTextStyle(change);

    if (auto* child_element = DynamicTo<Element>(child)) {
      if (!seen_any_child_elements) {
        // Push the parent, lazily. (We don't want to spend time
        // on this if we only have text nodes as children.)
        mark = selector_filter.SetMark();
        selector_filter.PushParent(host_or_element);
        seen_any_child_elements = true;
      }
      child_element->RecalcStyle(change, style_recalc_context);
    }
  }
  if (seen_any_child_elements) {
    selector_filter.PopTo(mark);
  }
}

void ContainerNode::RebuildLayoutTreeForChild(
    Node* child,
    WhitespaceAttacher& whitespace_attacher) {
  if (auto* child_text_node = DynamicTo<Text>(child)) {
    if (child->NeedsReattachLayoutTree())
      child_text_node->RebuildTextLayoutTree(whitespace_attacher);
    else
      whitespace_attacher.DidVisitText(child_text_node);
    return;
  }

  auto* element = DynamicTo<Element>(child);
  if (!element)
    return;

  if (element->NeedsRebuildLayoutTree(whitespace_attacher))
    element->RebuildLayoutTree(whitespace_attacher);
  else
    whitespace_attacher.DidVisitElement(element);
}

void ContainerNode::RebuildChildrenLayoutTrees(
    WhitespaceAttacher& whitespace_attacher) {
  DCHECK(!NeedsReattachLayoutTree());

  if (IsActiveSlot()) {
    if (auto* slot = DynamicTo<HTMLSlotElement>(this)) {
      slot->RebuildDistributedChildrenLayoutTrees(whitespace_attacher);
    }
    return;
  }

  // This loop is deliberately backwards because we use insertBefore in the
  // layout tree, and want to avoid a potentially n^2 loop to find the insertion
  // point while building the layout tree.  Having us start from the last child
  // and work our way back means in the common case, we'll find the insertion
  // point in O(1) time.  See crbug.com/288225
  for (Node* child = lastChild(); child; child = child->previousSibling())
    RebuildLayoutTreeForChild(child, whitespace_attacher);
}

void ContainerNode::CheckForSiblingStyleChanges(SiblingCheckType change_type,
                                                Element* changed_element,
                                                Node* node_before_change,
                                                Node* node_after_change) {
  if (!InActiveDocument() || GetDocument().HasPendingForcedStyleRecalc() ||
      GetStyleChangeType() == kSubtreeStyleChange)
    return;

  if (!HasRestyleFlag(DynamicRestyleFlags::kChildrenAffectedByStructuralRules))
    return;

  auto* element_after_change = DynamicTo<Element>(node_after_change);
  if (node_after_change && !element_after_change)
    element_after_change = ElementTraversal::NextSibling(*node_after_change);
  auto* element_before_change = DynamicTo<Element>(node_before_change);
  if (node_before_change && !element_before_change) {
    element_before_change =
        ElementTraversal::PreviousSibling(*node_before_change);
  }

  // TODO(futhark@chromium.org): move this code into StyleEngine and collect the
  // various invalidation sets into a single InvalidationLists object and
  // schedule with a single scheduleInvalidationSetsForNode for efficiency.

  // Forward positional selectors include :nth-child, :nth-of-type,
  // :first-of-type, and only-of-type. Backward positional selectors include
  // :nth-last-child, :nth-last-of-type, :last-of-type, and :only-of-type.
  if ((ChildrenAffectedByForwardPositionalRules() && element_after_change) ||
      (ChildrenAffectedByBackwardPositionalRules() && element_before_change)) {
    GetDocument().GetStyleEngine().ScheduleNthPseudoInvalidations(*this);
  }

  if (ChildrenAffectedByFirstChildRules() && !element_before_change &&
      element_after_change &&
      element_after_change->AffectedByFirstChildRules()) {
    DCHECK_NE(change_type, kFinishedParsingChildren);
    element_after_change->PseudoStateChanged(CSSSelector::kPseudoFirstChild);
    element_after_change->PseudoStateChanged(CSSSelector::kPseudoOnlyChild);
  }

  if (ChildrenAffectedByLastChildRules() && !element_after_change &&
      element_before_change &&
      element_before_change->AffectedByLastChildRules()) {
    element_before_change->PseudoStateChanged(CSSSelector::kPseudoLastChild);
    element_before_change->PseudoStateChanged(CSSSelector::kPseudoOnlyChild);
  }

  // For ~ and + combinators, succeeding siblings may need style invalidation
  // after an element is inserted or removed.

  if (!element_after_change)
    return;

  if (!ChildrenAffectedByIndirectAdjacentRules() &&
      !ChildrenAffectedByDirectAdjacentRules())
    return;

  if (change_type == kSiblingElementInserted) {
    GetDocument().GetStyleEngine().ScheduleInvalidationsForInsertedSibling(
        element_before_change, *changed_element);
    return;
  }

  DCHECK(change_type == kSiblingElementRemoved);
  GetDocument().GetStyleEngine().ScheduleInvalidationsForRemovedSibling(
      element_before_change, *changed_element, *element_after_change);
}

void ContainerNode::InvalidateNodeListCachesInAncestors(
    const QualifiedName* attr_name,
    Element* attribute_owner_element,
    const ChildrenChange* change) {
  // This is a performance optimization, NodeList cache invalidation is
  // not necessary for a text change.
  if (change && change->type == ChildrenChangeType::kTextChanged)
    return;

  if (!attr_name || IsAttributeNode()) {
    if (const NodeRareData* data = RareData()) {
      if (NodeListsNodeData* lists = data->NodeLists()) {
        if (ChildNodeList* child_node_list = lists->GetChildNodeList(*this)) {
          if (change) {
            child_node_list->ChildrenChanged(*change);
          } else {
            child_node_list->InvalidateCache();
          }
        }
      }
    }
  }

  // This is a performance optimization, NodeList cache invalidation is
  // not necessary for non-element nodes.
  if (change && change->affects_elements == ChildrenChangeAffectsElements::kNo)
    return;

  // Modifications to attributes that are not associated with an Element can't
  // invalidate NodeList caches.
  if (attr_name && !attribute_owner_element)
    return;

  if (!GetDocument().ShouldInvalidateNodeListCaches(attr_name))
    return;

  GetDocument().InvalidateNodeListCaches(attr_name);

  for (ContainerNode* node = this; node; node = node->parentNode()) {
    if (NodeListsNodeData* lists = node->NodeLists())
      lists->InvalidateCaches(attr_name);
  }
}

HTMLCollection* ContainerNode::getElementsByTagName(
    const AtomicString& qualified_name) {
  DCHECK(!qualified_name.IsNull());

  if (IsA<HTMLDocument>(GetDocument())) {
    return EnsureCachedCollection<HTMLTagCollection>(kHTMLTagCollectionType,
                                                     qualified_name);
  }
  return EnsureCachedCollection<TagCollection>(kTagCollectionType,
                                               qualified_name);
}

HTMLCollection* ContainerNode::getElementsByTagNameNS(
    const AtomicString& namespace_uri,
    const AtomicString& local_name) {
  return EnsureCachedCollection<TagCollectionNS>(
      kTagCollectionNSType, namespace_uri.empty() ? g_null_atom : namespace_uri,
      local_name);
}

// Takes an AtomicString in argument because it is common for elements to share
// the same name attribute.  Therefore, the NameNodeList factory function
// expects an AtomicString type.
NodeList* ContainerNode::getElementsByName(const AtomicString& element_name) {
  return EnsureCachedCollection<NameNodeList>(kNameNodeListType, element_name);
}

// Takes an AtomicString in argument because it is common for elements to share
// the same set of class names.  Therefore, the ClassNodeList factory function
// expects an AtomicString type.
HTMLCollection* ContainerNode::getElementsByClassName(
    const AtomicString& class_names) {
  return EnsureCachedCollection<ClassCollection>(kClassCollectionType,
                                                 class_names);
}

RadioNodeList* ContainerNode::GetRadioNodeList(const AtomicString& name,
                                               bool only_match_img_elements) {
  DCHECK(IsA<HTMLFormElement>(this) || IsA<HTMLFieldSetElement>(this));
  CollectionType type =
      only_match_img_elements ? kRadioImgNodeListType : kRadioNodeListType;
  return EnsureCachedCollection<RadioNodeList>(type, name);
}

StaticNodeList* ContainerNode::FindAllTextNodesMatchingRegex(
    const String& regex) const {
  blink::HeapVector<Member<Node>> nodes_matching_regex;
  Node* node = FlatTreeTraversal::FirstWithin(*this);
  ScriptRegexp* raw_regexp = MakeGarbageCollected<ScriptRegexp>(
      GetDocument().GetAgent().isolate(), regex, kTextCaseASCIIInsensitive);
  while (node) {
    if (node->IsTextNode()) {
      String text = To<Text>(node)->data();
      if (!text.empty()) {
        int match_offset = raw_regexp->Match(text);
        if (match_offset >= 0) {
          nodes_matching_regex.push_back(node);
        }
      }
    }
    node = FlatTreeTraversal::Next(*node, this);
  }

  return StaticNodeList::Adopt(nodes_matching_regex);
}

Element* ContainerNode::getElementById(const AtomicString& id) const {
  // According to https://dom.spec.whatwg.org/#concept-id, empty IDs are
  // treated as equivalent to the lack of an id attribute.
  if (id.empty()) {
    return nullptr;
  }

  if (IsInTreeScope()) {
    // Fast path if we are in a tree scope: call getElementById() on tree scope
    // and check if the matching element is in our subtree.
    Element* element = GetTreeScope().getElementById(id);
    if (!element)
      return nullptr;
    if (element->IsDescendantOf(this))
      return element;
  }

  // Fall back to traversing our subtree. In case of duplicate ids, the first
  // element found will be returned.
  for (Element& element : ElementTraversal::DescendantsOf(*this)) {
    if (element.GetIdAttribute() == id)
      return &element;
  }
  return nullptr;
}

NodeListsNodeData& ContainerNode::EnsureNodeLists() {
  return EnsureRareData().EnsureNodeLists();
}

// https://html.spec.whatwg.org/C/#autofocus-delegate
Element* ContainerNode::GetAutofocusDelegate() const {
  Element* element = ElementTraversal::Next(*this, this);
  while (element) {
    if (!element->IsAutofocusable()) {
      element = ElementTraversal::Next(*element, this);
      continue;
    }

    Element* focusable_area =
        element->IsFocusable() ? element : element->GetFocusableArea();
    if (!focusable_area) {
      element = ElementTraversal::Next(*element, this);
      continue;
    }

    // The spec says to continue instead of returning focusable_area if
    // focusable_area is not click-focusable and the call was initiated by the
    // user clicking. I don't believe this is currently possible, so DCHECK
    // instead.
    DCHECK(focusable_area->IsMouseFocusable());

    return focusable_area;
  }

  return nullptr;
}

// https://dom.spec.whatwg.org/#dom-parentnode-replacechildren
void ContainerNode::ReplaceChildren(const VectorOf<Node>& nodes,
                                    ExceptionState& exception_state) {
  if (!EnsurePreInsertionValidity(/*new_child*/ nullptr, &nodes,
                                  /*next*/ nullptr, /*old_child*/ nullptr,
                                  exception_state)) {
    return;
  }

  // 3. Replace all with node within this.
  ChildListMutationScope mutation(*this);
  while (Node* first_child = firstChild()) {
    RemoveChild(first_child, exception_state);
    if (exception_state.HadException()) {
      return;
    }
  }

  AppendChildren(nodes, exception_state);
}

void ContainerNode::CheckSoftNavigationHeuristicsTracking(
    const Document& document,
    Node& inserted_node) {
  if (!document.IsTrackingSoftNavigationHeuristics()) {
    return;
  }
  if (!inserted_node.isConnected()) {
    return;
  }
  LocalDOMWindow* window = document.domWindow();
  if (!window) {
    return;
  }
  if (SoftNavigationHeuristics* heuristics =
          window->GetSoftNavigationHeuristics()) {
    // When a child node, which is an HTML-element, is modified within a parent
    // (added, moved, etc), mark that child as modified by soft navigation.
    // Otherwise, if the child is not an HTML-element, mark the parent instead.
    // TODO(crbug.com/1521100): This does not filter out updates from isolated
    // worlds. Should it?
    Node* updated_node = inserted_node.IsHTMLElement() ? &inserted_node : this;
    heuristics->ModifiedDOM(updated_node);
  }
}

String ContainerNode::getHTML(const GetHTMLOptions* options,
                              ExceptionState& exception_state) const {
  DCHECK(options && options->hasSerializableShadowRoots())
      << "Should have IDL default";
  DCHECK(options->hasShadowRoots()) << "Should have IDL default";
  DCHECK(IsShadowRoot() || IsElementNode());
  ShadowRootInclusion shadow_root_inclusion{
      options->serializableShadowRoots()
          ? ShadowRootInclusion::Behavior::kIncludeAnySerializableShadowRoots
          : ShadowRootInclusion::Behavior::kOnlyProvidedShadowRoots};
  for (auto& shadow_root : options->shadowRoots()) {
    shadow_root_inclusion.include_shadow_roots.insert(shadow_root);
  }
  return CreateMarkup(this, kChildrenOnly, kDoNotResolveURLs,
                      shadow_root_inclusion);
}

}  // namespace blink