summaryrefslogtreecommitdiff
path: root/www/wiki/includes/tidy/Balancer.php
blob: 6671f49ba7d065eeffa493776d7b78aac8c5a22c (plain)
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
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
<?php
/**
 * An implementation of the tree building portion of the HTML5 parsing
 * spec.
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program 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 General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 * http://www.gnu.org/copyleft/gpl.html
 *
 * @file
 * @ingroup Parser
 * @since 1.27
 * @author C. Scott Ananian, 2016
 */

namespace MediaWiki\Tidy;

use ExplodeIterator;
use IteratorAggregate;
use ReverseArrayIterator;
use Sanitizer;
use Wikimedia\Assert\Assert;
use Wikimedia\Assert\ParameterAssertionException;

// A note for future librarization[1] -- this file is a good candidate
// for splitting into an independent library, except that it is currently
// highly optimized for MediaWiki use.  It only implements the portions
// of the HTML5 tree builder used by tags supported by MediaWiki, and
// does not contain a true tokenizer pass, instead relying on
// comment stripping, attribute normalization, and escaping done by
// the MediaWiki Sanitizer.  It also deliberately avoids building
// a true DOM in memory, instead serializing elements to an output string
// as soon as possible (usually as soon as the tag is closed) to reduce
// its memory footprint.

// We've been gradually lifting some of these restrictions to handle
// non-sanitized output generated by extensions, but we shortcut the tokenizer
// for speed (primarily by splitting on `<`) and so rely on syntactic
// well-formedness.

// On the other hand, I've been pretty careful to note with comments in the
// code the places where this implementation omits features of the spec or
// depends on the MediaWiki Sanitizer.  Perhaps in the future we'll want to
// implement the missing pieces and make this a standalone PHP HTML5 parser.
// In order to do so, some sort of MediaWiki-specific API will need
// to be added to (a) allow the Balancer to bypass the tokenizer,
// and (b) support on-the-fly flattening instead of DOM node creation.

// [1]: https://www.mediawiki.org/wiki/Library_infrastructure_for_MediaWiki

/**
 * Utility constants and sets for the HTML5 tree building algorithm.
 * Sets are associative arrays indexed first by namespace and then by
 * lower-cased tag name.
 *
 * @ingroup Parser
 * @since 1.27
 */
class BalanceSets {
	const HTML_NAMESPACE = 'http://www.w3.org/1999/xhtml';
	const MATHML_NAMESPACE = 'http://www.w3.org/1998/Math/MathML';
	const SVG_NAMESPACE = 'http://www.w3.org/2000/svg';

	public static $unsupportedSet = [
		self::HTML_NAMESPACE => [
			'html' => true, 'head' => true, 'body' => true, 'frameset' => true,
			'frame' => true,
			'plaintext' => true,
			'xmp' => true, 'iframe' => true, 'noembed' => true,
			'noscript' => true, 'script' => true,
			'title' => true
		]
	];

	public static $emptyElementSet = [
		self::HTML_NAMESPACE => [
			'area' => true, 'base' => true, 'basefont' => true,
			'bgsound' => true, 'br' => true, 'col' => true, 'command' => true,
			'embed' => true, 'frame' => true, 'hr' => true, 'img' => true,
			'input' => true, 'keygen' => true, 'link' => true, 'meta' => true,
			'param' => true, 'source' => true, 'track' => true, 'wbr' => true
		]
	];

	public static $extraLinefeedSet = [
		self::HTML_NAMESPACE => [
			'pre' => true, 'textarea' => true, 'listing' => true,
		]
	];

	public static $headingSet = [
		self::HTML_NAMESPACE => [
			'h1' => true, 'h2' => true, 'h3' => true,
			'h4' => true, 'h5' => true, 'h6' => true
		]
	];

	public static $specialSet = [
		self::HTML_NAMESPACE => [
			'address' => true, 'applet' => true, 'area' => true,
			'article' => true, 'aside' => true, 'base' => true,
			'basefont' => true, 'bgsound' => true, 'blockquote' => true,
			'body' => true, 'br' => true, 'button' => true, 'caption' => true,
			'center' => true, 'col' => true, 'colgroup' => true, 'dd' => true,
			'details' => true, 'dir' => true, 'div' => true, 'dl' => true,
			'dt' => true, 'embed' => true, 'fieldset' => true,
			'figcaption' => true, 'figure' => true, 'footer' => true,
			'form' => true, 'frame' => true, 'frameset' => true, 'h1' => true,
			'h2' => true, 'h3' => true, 'h4' => true, 'h5' => true,
			'h6' => true, 'head' => true, 'header' => true, 'hgroup' => true,
			'hr' => true, 'html' => true, 'iframe' => true, 'img' => true,
			'input' => true, 'li' => true, 'link' => true,
			'listing' => true, 'main' => true, 'marquee' => true,
			'menu' => true, 'meta' => true, 'nav' => true,
			'noembed' => true, 'noframes' => true, 'noscript' => true,
			'object' => true, 'ol' => true, 'p' => true, 'param' => true,
			'plaintext' => true, 'pre' => true, 'script' => true,
			'section' => true, 'select' => true, 'source' => true,
			'style' => true, 'summary' => true, 'table' => true,
			'tbody' => true, 'td' => true, 'template' => true,
			'textarea' => true, 'tfoot' => true, 'th' => true, 'thead' => true,
			'title' => true, 'tr' => true, 'track' => true, 'ul' => true,
			'wbr' => true, 'xmp' => true
		],
		self::SVG_NAMESPACE => [
			'foreignobject' => true, 'desc' => true, 'title' => true
		],
		self::MATHML_NAMESPACE => [
			'mi' => true, 'mo' => true, 'mn' => true, 'ms' => true,
			'mtext' => true, 'annotation-xml' => true
		]
	];

	public static $addressDivPSet = [
		self::HTML_NAMESPACE => [
			'address' => true, 'div' => true, 'p' => true
		]
	];

	public static $tableSectionRowSet = [
		self::HTML_NAMESPACE => [
			'table' => true, 'thead' => true, 'tbody' => true,
			'tfoot' => true, 'tr' => true
		]
	];

	public static $impliedEndTagsSet = [
		self::HTML_NAMESPACE => [
			'dd' => true, 'dt' => true, 'li' => true,
			'menuitem' => true, 'optgroup' => true,
			'option' => true, 'p' => true, 'rb' => true, 'rp' => true,
			'rt' => true, 'rtc' => true
		]
	];

	public static $thoroughImpliedEndTagsSet = [
		self::HTML_NAMESPACE => [
			'caption' => true, 'colgroup' => true, 'dd' => true, 'dt' => true,
			'li' => true, 'optgroup' => true, 'option' => true, 'p' => true,
			'rb' => true, 'rp' => true, 'rt' => true, 'rtc' => true,
			'tbody' => true, 'td' => true, 'tfoot' => true, 'th' => true,
			'thead' => true, 'tr' => true
		]
	];

	public static $tableCellSet = [
		self::HTML_NAMESPACE => [
			'td' => true, 'th' => true
		]
	];
	public static $tableContextSet = [
		self::HTML_NAMESPACE => [
			'table' => true, 'template' => true, 'html' => true
		]
	];

	public static $tableBodyContextSet = [
		self::HTML_NAMESPACE => [
			'tbody' => true, 'tfoot' => true, 'thead' => true,
			'template' => true, 'html' => true
		]
	];

	public static $tableRowContextSet = [
		self::HTML_NAMESPACE => [
			'tr' => true, 'template' => true, 'html' => true
		]
	];

	// See https://html.spec.whatwg.org/multipage/forms.html#form-associated-element
	public static $formAssociatedSet = [
		self::HTML_NAMESPACE => [
			'button' => true, 'fieldset' => true, 'input' => true,
			'keygen' => true, 'object' => true, 'output' => true,
			'select' => true, 'textarea' => true, 'img' => true
		]
	];

	public static $inScopeSet = [
		self::HTML_NAMESPACE => [
			'applet' => true, 'caption' => true, 'html' => true,
			'marquee' => true, 'object' => true,
			'table' => true, 'td' => true, 'template' => true,
			'th' => true
		],
		self::SVG_NAMESPACE => [
			'foreignobject' => true, 'desc' => true, 'title' => true
		],
		self::MATHML_NAMESPACE => [
			'mi' => true, 'mo' => true, 'mn' => true, 'ms' => true,
			'mtext' => true, 'annotation-xml' => true
		]
	];

	private static $inListItemScopeSet = null;
	public static function inListItemScopeSet() {
		if ( self::$inListItemScopeSet === null ) {
			self::$inListItemScopeSet = self::$inScopeSet;
			self::$inListItemScopeSet[self::HTML_NAMESPACE]['ol'] = true;
			self::$inListItemScopeSet[self::HTML_NAMESPACE]['ul'] = true;
		}
		return self::$inListItemScopeSet;
	}

	private static $inButtonScopeSet = null;
	public static function inButtonScopeSet() {
		if ( self::$inButtonScopeSet === null ) {
			self::$inButtonScopeSet = self::$inScopeSet;
			self::$inButtonScopeSet[self::HTML_NAMESPACE]['button'] = true;
		}
		return self::$inButtonScopeSet;
	}

	public static $inTableScopeSet = [
		self::HTML_NAMESPACE => [
			'html' => true, 'table' => true, 'template' => true
		]
	];

	public static $inInvertedSelectScopeSet = [
		self::HTML_NAMESPACE => [
			'option' => true, 'optgroup' => true
		]
	];

	public static $mathmlTextIntegrationPointSet = [
		self::MATHML_NAMESPACE => [
			'mi' => true, 'mo' => true, 'mn' => true, 'ms' => true,
			'mtext' => true
		]
	];

	public static $htmlIntegrationPointSet = [
		self::SVG_NAMESPACE => [
			'foreignobject' => true,
			'desc' => true,
			'title' => true
		]
	];

	// For tidy compatibility.
	public static $tidyPWrapSet = [
		self::HTML_NAMESPACE => [
			'body' => true, 'blockquote' => true,
			// We parse with <body> as the fragment context, but the top-level
			// element on the stack is actually <html>.  We could use the
			// "adjusted current node" everywhere to work around this, but it's
			// easier just to add <html> to the p-wrap set.
			'html' => true,
		],
	];
	public static $tidyInlineSet = [
		self::HTML_NAMESPACE => [
			'a' => true, 'abbr' => true, 'acronym' => true, 'applet' => true,
			'b' => true, 'basefont' => true, 'bdo' => true, 'big' => true,
			'br' => true, 'button' => true, 'cite' => true, 'code' => true,
			'dfn' => true, 'em' => true, 'font' => true, 'i' => true,
			'iframe' => true, 'img' => true, 'input' => true, 'kbd' => true,
			'label' => true, 'legend' => true, 'map' => true, 'object' => true,
			'param' => true, 'q' => true, 'rb' => true, 'rbc' => true,
			'rp' => true, 'rt' => true, 'rtc' => true, 'ruby' => true,
			's' => true, 'samp' => true, 'select' => true, 'small' => true,
			'span' => true, 'strike' => true, 'strong' => true, 'sub' => true,
			'sup' => true, 'textarea' => true, 'tt' => true, 'u' => true,
			'var' => true,
			// Those defined in tidy.conf
			'video' => true, 'audio' => true, 'bdi' => true, 'data' => true,
			'time' => true, 'mark' => true,
		],
	];
}

/**
 * A BalanceElement is a simplified version of a DOM Node.  The main
 * difference is that we only keep BalanceElements around for nodes
 * currently on the BalanceStack of open elements.  As soon as an
 * element is closed, with some minor exceptions relating to the
 * tree builder "adoption agency algorithm", the element and all its
 * children are serialized to a string using the flatten() method.
 * This keeps our memory usage low.
 *
 * @ingroup Parser
 * @since 1.27
 */
class BalanceElement {
	/**
	 * The namespace of the element.
	 * @var string $namespaceURI
	 */
	public $namespaceURI;
	/**
	 * The lower-cased name of the element.
	 * @var string $localName
	 */
	public $localName;
	/**
	 * Attributes for the element, in array form
	 * @var array $attribs
	 */
	public $attribs;

	/**
	 * Parent of this element, or the string "flat" if this element has
	 * already been flattened into its parent.
	 * @var BalanceElement|string|null $parent
	 */
	public $parent;

	/**
	 * An array of children of this element.  Typically only the last
	 * child will be an actual BalanceElement object; the rest will
	 * be strings, representing either text nodes or flattened
	 * BalanceElement objects.
	 * @var BalanceElement[]|string[] $children
	 */
	public $children;

	/**
	 * A unique string identifier for Noah's Ark purposes, lazy initialized
	 */
	private $noahKey;

	/**
	 * The next active formatting element in the list, or null if this is the
	 * end of the AFE list or if the element is not in the AFE list.
	 */
	public $nextAFE;

	/**
	 * The previous active formatting element in the list, or null if this is
	 * the start of the list or if the element is not in the AFE list.
	 */
	public $prevAFE;

	/**
	 * The next element in the Noah's Ark species bucket.
	 */
	public $nextNoah;

	/**
	 * Make a new BalanceElement corresponding to the HTML DOM Element
	 * with the given localname, namespace, and attributes.
	 *
	 * @param string $namespaceURI The namespace of the element.
	 * @param string $localName The lowercased name of the tag.
	 * @param array $attribs Attributes of the element
	 */
	public function __construct( $namespaceURI, $localName, array $attribs ) {
		$this->localName = $localName;
		$this->namespaceURI = $namespaceURI;
		$this->attribs = $attribs;
		$this->contents = '';
		$this->parent = null;
		$this->children = [];
	}

	/**
	 * Remove the given child from this element.
	 * @param BalanceElement $elt
	 */
	private function removeChild( BalanceElement $elt ) {
		Assert::precondition(
			$this->parent !== 'flat', "Can't removeChild after flattening $this"
		);
		Assert::parameter(
			$elt->parent === $this, 'elt', 'must have $this as a parent'
		);
		$idx = array_search( $elt, $this->children, true );
		Assert::parameter( $idx !== false, '$elt', 'must be a child of $this' );
		$elt->parent = null;
		array_splice( $this->children, $idx, 1 );
	}

	/**
	 * Find $a in the list of children and insert $b before it.
	 * @param BalanceElement $a
	 * @param BalanceElement|string $b
	 */
	public function insertBefore( BalanceElement $a, $b ) {
		Assert::precondition(
			$this->parent !== 'flat', "Can't insertBefore after flattening."
		);
		$idx = array_search( $a, $this->children, true );
		Assert::parameter( $idx !== false, '$a', 'must be a child of $this' );
		if ( is_string( $b ) ) {
			array_splice( $this->children, $idx, 0, [ $b ] );
		} else {
			Assert::parameter( $b->parent !== 'flat', '$b', "Can't be flat" );
			if ( $b->parent !== null ) {
				$b->parent->removeChild( $b );
			}
			array_splice( $this->children, $idx, 0, [ $b ] );
			$b->parent = $this;
		}
	}

	/**
	 * Append $elt to the end of the list of children.
	 * @param BalanceElement|string $elt
	 */
	public function appendChild( $elt ) {
		Assert::precondition(
			$this->parent !== 'flat', "Can't appendChild after flattening."
		);
		if ( is_string( $elt ) ) {
			array_push( $this->children, $elt );
			return;
		}
		// Remove $elt from parent, if it had one.
		if ( $elt->parent !== null ) {
			$elt->parent->removeChild( $elt );
		}
		array_push( $this->children, $elt );
		$elt->parent = $this;
	}

	/**
	 * Transfer all of the children of $elt to $this.
	 * @param BalanceElement $elt
	 */
	public function adoptChildren( BalanceElement $elt ) {
		Assert::precondition(
			$elt->parent !== 'flat', "Can't adoptChildren after flattening."
		);
		foreach ( $elt->children as $child ) {
			if ( !is_string( $child ) ) {
				// This is an optimization which avoids an O(n^2) set of
				// array_splice operations.
				$child->parent = null;
			}
			$this->appendChild( $child );
		}
		$elt->children = [];
	}

	/**
	 * Flatten this node and all of its children into a string, as specified
	 * by the HTML serialization specification, and replace this node
	 * in its parent by that string.
	 *
	 * @param array $config Balancer configuration; see Balancer::__construct().
	 * @return string
	 *
	 * @see __toString()
	 */
	public function flatten( array $config ) {
		Assert::parameter( $this->parent !== null, '$this', 'must be a child' );
		Assert::parameter( $this->parent !== 'flat', '$this', 'already flat' );
		$idx = array_search( $this, $this->parent->children, true );
		Assert::parameter(
			$idx !== false, '$this', 'must be a child of its parent'
		);
		$tidyCompat = $config['tidyCompat'];
		if ( $tidyCompat ) {
			$blank = true;
			foreach ( $this->children as $elt ) {
				if ( !is_string( $elt ) ) {
					$elt = $elt->flatten( $config );
				}
				if ( $blank && preg_match( '/[^\t\n\f\r ]/', $elt ) ) {
					$blank = false;
				}
			}
			if ( $this->isHtmlNamed( 'mw:p-wrap' ) ) {
				$this->localName = 'p';
			} elseif ( $blank ) {
				// Add 'mw-empty-elt' class so elements can be hidden via CSS
				// for compatibility with legacy tidy.
				if ( !count( $this->attribs ) &&
					( $this->localName === 'tr' || $this->localName === 'li' )
				) {
					$this->attribs = [ 'class' => "mw-empty-elt" ];
				}
				$blank = false;
			} elseif (
				$this->isA( BalanceSets::$extraLinefeedSet ) &&
				count( $this->children ) > 0 &&
				substr( $this->children[0], 0, 1 ) == "\n"
			) {
				// Double the linefeed after pre/listing/textarea
				// according to the (old) HTML5 fragment serialization
				// algorithm (see https://github.com/whatwg/html/issues/944)
				// to ensure this will round-trip.
				array_unshift( $this->children, "\n" );
			}
			$flat = $blank ? '' : "{$this}";
		} else {
			$flat = "{$this}";
		}
		$this->parent->children[$idx] = $flat;
		$this->parent = 'flat'; // for assertion checking
		return $flat;
	}

	/**
	 * Serialize this node and all of its children to a string, as specified
	 * by the HTML serialization specification.
	 *
	 * @return string The serialization of the BalanceElement
	 * @see https://html.spec.whatwg.org/multipage/syntax.html#serialising-html-fragments
	 */
	public function __toString() {
		$encAttribs = '';
		foreach ( $this->attribs as $name => $value ) {
			$encValue = Sanitizer::encodeAttribute( $value );
			$encAttribs .= " $name=\"$encValue\"";
		}
		if ( !$this->isA( BalanceSets::$emptyElementSet ) ) {
			$out = "<{$this->localName}{$encAttribs}>";
			$len = strlen( $out );
			// flatten children
			foreach ( $this->children as $elt ) {
				$out .= "{$elt}";
			}
			$out .= "</{$this->localName}>";
		} else {
			$out = "<{$this->localName}{$encAttribs} />";
			Assert::invariant(
				count( $this->children ) === 0,
				"Empty elements shouldn't have children."
			);
		}
		return $out;
	}

	// Utility functions on BalanceElements.

	/**
	 * Determine if $this represents a specific HTML tag, is a member of
	 * a tag set, or is equal to another BalanceElement.
	 *
	 * @param BalanceElement|array|string $set The target BalanceElement,
	 *   set (from the BalanceSets class), or string (HTML tag name).
	 * @return bool
	 */
	public function isA( $set ) {
		if ( $set instanceof BalanceElement ) {
			return $this === $set;
		} elseif ( is_array( $set ) ) {
			return isset( $set[$this->namespaceURI] ) &&
				isset( $set[$this->namespaceURI][$this->localName] );
		} else {
			// assume this is an HTML element name.
			return $this->isHtml() && $this->localName === $set;
		}
	}

	/**
	 * Determine if this element is an HTML element with the specified name
	 * @param string $tagName
	 * @return bool
	 */
	public function isHtmlNamed( $tagName ) {
		return $this->namespaceURI === BalanceSets::HTML_NAMESPACE
			&& $this->localName === $tagName;
	}

	/**
	 * Determine if $this represents an element in the HTML namespace.
	 *
	 * @return bool
	 */
	public function isHtml() {
		return $this->namespaceURI === BalanceSets::HTML_NAMESPACE;
	}

	/**
	 * Determine if $this represents a MathML text integration point,
	 * as defined in the HTML5 specification.
	 *
	 * @return bool
	 * @see https://html.spec.whatwg.org/multipage/syntax.html#mathml-text-integration-point
	 */
	public function isMathmlTextIntegrationPoint() {
		return $this->isA( BalanceSets::$mathmlTextIntegrationPointSet );
	}

	/**
	 * Determine if $this represents an HTML integration point,
	 * as defined in the HTML5 specification.
	 *
	 * @return bool
	 * @see https://html.spec.whatwg.org/multipage/syntax.html#html-integration-point
	 */
	public function isHtmlIntegrationPoint() {
		if ( $this->isA( BalanceSets::$htmlIntegrationPointSet ) ) {
			return true;
		}
		if (
			$this->namespaceURI === BalanceSets::MATHML_NAMESPACE &&
			$this->localName === 'annotation-xml' &&
			isset( $this->attribs['encoding'] ) &&
			( strcasecmp( $this->attribs['encoding'], 'text/html' ) == 0 ||
			strcasecmp( $this->attribs['encoding'], 'application/xhtml+xml' ) == 0 )
		) {
			return true;
		}
		return false;
	}

	/**
	 * Get a string key for the Noah's Ark algorithm
	 * @return string
	 */
	public function getNoahKey() {
		if ( $this->noahKey === null ) {
			$attribs = $this->attribs;
			ksort( $attribs );
			$this->noahKey = serialize( [ $this->namespaceURI, $this->localName, $attribs ] );
		}
		return $this->noahKey;
	}
}

/**
 * The "stack of open elements" as defined in the HTML5 tree builder
 * spec.  This contains methods to ensure that content (start tags, text)
 * are inserted at the correct place in the output string, and to
 * flatten BalanceElements are they are closed to avoid holding onto
 * a complete DOM tree for the document in memory.
 *
 * The stack defines a PHP iterator to traverse it in "reverse order",
 * that is, the most-recently-added element is visited first in a
 * foreach loop.
 *
 * @ingroup Parser
 * @since 1.27
 * @see https://html.spec.whatwg.org/multipage/syntax.html#the-stack-of-open-elements
 */
class BalanceStack implements IteratorAggregate {
	/**
	 * Backing storage for the stack.
	 * @var BalanceElement[] $elements
	 */
	private $elements = [];
	/**
	 * Foster parent mode determines how nodes are inserted into the
	 * stack.
	 * @var bool $fosterParentMode
	 * @see https://html.spec.whatwg.org/multipage/syntax.html#foster-parent
	 */
	public $fosterParentMode = false;
	/**
	 * Configuration options governing flattening.
	 * @var array $config
	 * @see Balancer::__construct()
	 */
	private $config;
	/**
	 * Reference to the current element
	 */
	public $currentNode;

	/**
	 * Create a new BalanceStack with a single BalanceElement on it,
	 * representing the root &lt;html&gt; node.
	 * @param array $config Balancer configuration; see Balancer::_construct().
	 */
	public function __construct( array $config ) {
		// always a root <html> element on the stack
		array_push(
			$this->elements,
			new BalanceElement( BalanceSets::HTML_NAMESPACE, 'html', [] )
		);
		$this->currentNode = $this->elements[0];
		$this->config = $config;
	}

	/**
	 * Return a string representing the output of the tree builder:
	 * all the children of the root &lt;html&gt; node.
	 * @return string
	 */
	public function getOutput() {
		// Don't include the outer '<html>....</html>'
		$out = '';
		foreach ( $this->elements[0]->children as $elt ) {
			$out .= is_string( $elt ) ? $elt :
				$elt->flatten( $this->config );
		}
		return $out;
	}

	/**
	 * Insert a comment at the appropriate place for inserting a node.
	 * @param string $value Content of the comment.
	 * @return string
	 * @see https://html.spec.whatwg.org/multipage/syntax.html#insert-a-comment
	 */
	public function insertComment( $value ) {
		// Just another type of text node, except for tidy p-wrapping.
		return $this->insertText( '<!--' . $value . '-->', true );
	}

	/**
	 * Insert text at the appropriate place for inserting a node.
	 * @param string $value
	 * @param bool $isComment
	 * @return string
	 * @see https://html.spec.whatwg.org/multipage/syntax.html#appropriate-place-for-inserting-a-node
	 */
	public function insertText( $value, $isComment = false ) {
		if (
			$this->fosterParentMode &&
			$this->currentNode->isA( BalanceSets::$tableSectionRowSet )
		) {
			$this->fosterParent( $value );
		} elseif (
			$this->config['tidyCompat'] && !$isComment &&
			$this->currentNode->isA( BalanceSets::$tidyPWrapSet )
		) {
			$this->insertHTMLElement( 'mw:p-wrap', [] );
			return $this->insertText( $value );
		} else {
			$this->currentNode->appendChild( $value );
		}
	}

	/**
	 * Insert a BalanceElement at the appropriate place, pushing it
	 * on to the open elements stack.
	 * @param string $namespaceURI The element namespace
	 * @param string $tag The tag name
	 * @param string $attribs Normalized attributes, as a string.
	 * @return BalanceElement
	 * @see https://html.spec.whatwg.org/multipage/syntax.html#insert-a-foreign-element
	 */
	public function insertForeignElement( $namespaceURI, $tag, $attribs ) {
		return $this->insertElement(
			new BalanceElement( $namespaceURI, $tag, $attribs )
		);
	}

	/**
	 * Insert an HTML element at the appropriate place, pushing it on to
	 * the open elements stack.
	 * @param string $tag The tag name
	 * @param string $attribs Normalized attributes, as a string.
	 * @return BalanceElement
	 * @see https://html.spec.whatwg.org/multipage/syntax.html#insert-an-html-element
	 */
	public function insertHTMLElement( $tag, $attribs ) {
		return $this->insertForeignElement(
			BalanceSets::HTML_NAMESPACE, $tag, $attribs
		);
	}

	/**
	 * Insert an element at the appropriate place and push it on to the
	 * open elements stack.
	 * @param BalanceElement $elt
	 * @return BalanceElement
	 * @see https://html.spec.whatwg.org/multipage/syntax.html#appropriate-place-for-inserting-a-node
	 */
	public function insertElement( BalanceElement $elt ) {
		if (
			$this->currentNode->isHtmlNamed( 'mw:p-wrap' ) &&
			!$elt->isA( BalanceSets::$tidyInlineSet )
		) {
			// Tidy compatibility.
			$this->pop();
		}
		if (
			$this->fosterParentMode &&
			$this->currentNode->isA( BalanceSets::$tableSectionRowSet )
		) {
			$elt = $this->fosterParent( $elt );
		} else {
			$this->currentNode->appendChild( $elt );
		}
		Assert::invariant( $elt->parent !== null, "$elt must be in tree" );
		Assert::invariant( $elt->parent !== 'flat', "$elt must not have been previous flattened" );
		array_push( $this->elements, $elt );
		$this->currentNode = $elt;
		return $elt;
	}

	/**
	 * Determine if the stack has $tag in scope.
	 * @param BalanceElement|array|string $tag
	 * @return bool
	 * @see https://html.spec.whatwg.org/multipage/syntax.html#has-an-element-in-scope
	 */
	public function inScope( $tag ) {
		return $this->inSpecificScope( $tag, BalanceSets::$inScopeSet );
	}

	/**
	 * Determine if the stack has $tag in button scope.
	 * @param BalanceElement|array|string $tag
	 * @return bool
	 * @see https://html.spec.whatwg.org/multipage/syntax.html#has-an-element-in-button-scope
	 */
	public function inButtonScope( $tag ) {
		return $this->inSpecificScope( $tag, BalanceSets::inButtonScopeSet() );
	}

	/**
	 * Determine if the stack has $tag in list item scope.
	 * @param BalanceElement|array|string $tag
	 * @return bool
	 * @see https://html.spec.whatwg.org/multipage/syntax.html#has-an-element-in-list-item-scope
	 */
	public function inListItemScope( $tag ) {
		return $this->inSpecificScope( $tag, BalanceSets::inListItemScopeSet() );
	}

	/**
	 * Determine if the stack has $tag in table scope.
	 * @param BalanceElement|array|string $tag
	 * @return bool
	 * @see https://html.spec.whatwg.org/multipage/syntax.html#has-an-element-in-table-scope
	 */
	public function inTableScope( $tag ) {
		return $this->inSpecificScope( $tag, BalanceSets::$inTableScopeSet );
	}

	/**
	 * Determine if the stack has $tag in select scope.
	 * @param BalanceElement|array|string $tag
	 * @return bool
	 * @see https://html.spec.whatwg.org/multipage/syntax.html#has-an-element-in-select-scope
	 */
	public function inSelectScope( $tag ) {
		// Can't use inSpecificScope to implement this, since it involves
		// *inverting* a set of tags.  Implement manually.
		foreach ( $this as $elt ) {
			if ( $elt->isA( $tag ) ) {
				return true;
			}
			if ( !$elt->isA( BalanceSets::$inInvertedSelectScopeSet ) ) {
				return false;
			}
		}
		return false;
	}

	/**
	 * Determine if the stack has $tag in a specific scope, $set.
	 * @param BalanceElement|array|string $tag
	 * @param BalanceElement|array|string $set
	 * @return bool
	 * @see https://html.spec.whatwg.org/multipage/syntax.html#has-an-element-in-the-specific-scope
	 */
	public function inSpecificScope( $tag, $set ) {
		foreach ( $this as $elt ) {
			if ( $elt->isA( $tag ) ) {
				return true;
			}
			if ( $elt->isA( $set ) ) {
				return false;
			}
		}
		return false;
	}

	/**
	 * Generate implied end tags.
	 * @param string $butnot
	 * @param bool $thorough True if we should generate end tags thoroughly.
	 * @see https://html.spec.whatwg.org/multipage/syntax.html#generate-implied-end-tags
	 */
	public function generateImpliedEndTags( $butnot = null, $thorough = false ) {
		$endTagSet = $thorough ?
			BalanceSets::$thoroughImpliedEndTagsSet :
			BalanceSets::$impliedEndTagsSet;
		while ( $this->currentNode ) {
			if ( $butnot !== null && $this->currentNode->isHtmlNamed( $butnot ) ) {
				break;
			}
			if ( !$this->currentNode->isA( $endTagSet ) ) {
				break;
			}
			$this->pop();
		}
	}

	/**
	 * Return the adjusted current node.
	 * @param string $fragmentContext
	 * @return string
	 */
	public function adjustedCurrentNode( $fragmentContext ) {
		return ( $fragmentContext && count( $this->elements ) === 1 ) ?
			$fragmentContext : $this->currentNode;
	}

	/**
	 * Return an iterator over this stack which visits the current node
	 * first, and the root node last.
	 * @return \Iterator
	 */
	public function getIterator() {
		return new ReverseArrayIterator( $this->elements );
	}

	/**
	 * Return the BalanceElement at the given position $idx, where
	 * position 0 represents the root element.
	 * @param int $idx
	 * @return BalanceElement
	 */
	public function node( $idx ) {
		return $this->elements[ $idx ];
	}

	/**
	 * Replace the element at position $idx in the BalanceStack with $elt.
	 * @param int $idx
	 * @param BalanceElement $elt
	 */
	public function replaceAt( $idx, BalanceElement $elt ) {
		Assert::precondition(
			$this->elements[$idx]->parent !== 'flat',
			'Replaced element should not have already been flattened.'
		);
		Assert::precondition(
			$elt->parent !== 'flat',
			'New element should not have already been flattened.'
		);
		$this->elements[$idx] = $elt;
		if ( $idx === count( $this->elements ) - 1 ) {
			$this->currentNode = $elt;
		}
	}

	/**
	 * Return the position of the given BalanceElement, set, or
	 * HTML tag name string in the BalanceStack.
	 * @param BalanceElement|array|string $tag
	 * @return int
	 */
	public function indexOf( $tag ) {
		for ( $i = count( $this->elements ) - 1; $i >= 0; $i-- ) {
			if ( $this->elements[$i]->isA( $tag ) ) {
				return $i;
			}
		}
		return -1;
	}

	/**
	 * Return the number of elements currently in the BalanceStack.
	 * @return int
	 */
	public function length() {
		return count( $this->elements );
	}

	/**
	 * Remove the current node from the BalanceStack, flattening it
	 * in the process.
	 */
	public function pop() {
		$elt = array_pop( $this->elements );
		if ( count( $this->elements ) ) {
			$this->currentNode = $this->elements[ count( $this->elements ) - 1 ];
		} else {
			$this->currentNode = null;
		}
		if ( !$elt->isHtmlNamed( 'mw:p-wrap' ) ) {
			$elt->flatten( $this->config );
		}
	}

	/**
	 * Remove all nodes up to and including position $idx from the
	 * BalanceStack, flattening them in the process.
	 * @param int $idx
	 */
	public function popTo( $idx ) {
		for ( $length = count( $this->elements ); $length > $idx; $length-- ) {
			$this->pop();
		}
	}

	/**
	 * Pop elements off the stack up to and including the first
	 * element with the specified HTML tagname (or matching the given
	 * set).
	 * @param BalanceElement|array|string $tag
	 */
	public function popTag( $tag ) {
		while ( $this->currentNode ) {
			if ( $this->currentNode->isA( $tag ) ) {
				$this->pop();
				break;
			}
			$this->pop();
		}
	}

	/**
	 * Pop elements off the stack *not including* the first element
	 * in the specified set.
	 * @param BalanceElement|array|string $set
	 */
	public function clearToContext( $set ) {
		// Note that we don't loop to 0. Never pop the <html> elt off.
		for ( $length = count( $this->elements ); $length > 1; $length-- ) {
			if ( $this->currentNode->isA( $set ) ) {
				break;
			}
			$this->pop();
		}
	}

	/**
	 * Remove the given $elt from the BalanceStack, optionally
	 * flattening it in the process.
	 * @param BalanceElement $elt The element to remove.
	 * @param bool $flatten Whether to flatten the removed element.
	 */
	public function removeElement( BalanceElement $elt, $flatten = true ) {
		Assert::parameter(
			$elt->parent !== 'flat',
			'$elt',
			'$elt should not already have been flattened.'
		);
		Assert::parameter(
			$elt->parent->parent !== 'flat',
			'$elt',
			'The parent of $elt should not already have been flattened.'
		);
		$idx = array_search( $elt, $this->elements, true );
		Assert::parameter( $idx !== false, '$elt', 'must be in stack' );
		array_splice( $this->elements, $idx, 1 );
		if ( $idx === count( $this->elements ) ) {
			$this->currentNode = $this->elements[$idx - 1];
		}
		if ( $flatten ) {
			// serialize $elt into its parent
			// otherwise, it will eventually serialize when the parent
			// is serialized, we just hold onto the memory for its
			// tree of objects a little longer.
			$elt->flatten( $this->config );
		}
		Assert::postcondition(
			array_search( $elt, $this->elements, true ) === false,
			'$elt should no longer be in open elements stack'
		);
	}

	/**
	 * Find $a in the BalanceStack and insert $b after it.
	 * @param BalanceElement $a
	 * @param BalanceElement $b
	 */
	public function insertAfter( BalanceElement $a, BalanceElement $b ) {
		$idx = $this->indexOf( $a );
		Assert::parameter( $idx !== false, '$a', 'must be in stack' );
		if ( $idx === count( $this->elements ) - 1 ) {
			array_push( $this->elements, $b );
			$this->currentNode = $b;
		} else {
			array_splice( $this->elements, $idx + 1, 0, [ $b ] );
		}
	}

	// Fostering and adoption.

	/**
	 * Foster parent the given $elt in the stack of open elements.
	 * @param BalanceElement|string $elt
	 * @return BalanceElement|string
	 *
	 * @see https://html.spec.whatwg.org/multipage/syntax.html#foster-parent
	 */
	private function fosterParent( $elt ) {
		$lastTable = $this->indexOf( 'table' );
		$lastTemplate = $this->indexOf( 'template' );
		$parent = null;
		$before = null;

		if ( $lastTemplate >= 0 && ( $lastTable < 0 || $lastTemplate > $lastTable ) ) {
			$parent = $this->elements[$lastTemplate];
		} elseif ( $lastTable >= 0 ) {
			$parent = $this->elements[$lastTable]->parent;
			// Assume all tables have parents, since we're not running scripts!
			Assert::invariant(
				$parent !== null, "All tables should have parents"
			);
			$before = $this->elements[$lastTable];
		} else {
			$parent = $this->elements[0]; // the `html` element.
		}

		if ( $this->config['tidyCompat'] ) {
			if ( is_string( $elt ) ) {
				// We're fostering text: do we need a p-wrapper?
				if ( $parent->isA( BalanceSets::$tidyPWrapSet ) ) {
					$this->insertHTMLElement( 'mw:p-wrap', [] );
					$this->insertText( $elt );
					return $elt;
				}
			} else {
				// We're fostering an element; do we need to merge p-wrappers?
				if ( $elt->isHtmlNamed( 'mw:p-wrap' ) ) {
					$idx = $before ?
						array_search( $before, $parent->children, true ) :
						count( $parent->children );
					$after = $idx > 0 ? $parent->children[$idx - 1] : '';
					if (
						$after instanceof BalanceElement &&
						$after->isHtmlNamed( 'mw:p-wrap' )
					) {
						return $after; // Re-use existing p-wrapper.
					}
				}
			}
		}

		if ( $before ) {
			$parent->insertBefore( $before, $elt );
		} else {
			$parent->appendChild( $elt );
		}
		return $elt;
	}

	/**
	 * Run the "adoption agency algoritm" (AAA) for the given subject
	 * tag name.
	 * @param string $tag The subject tag name.
	 * @param BalanceActiveFormattingElements $afe The current
	 *   active formatting elements list.
	 * @return true if the adoption agency algorithm "did something", false
	 *   if more processing is required by the caller.
	 * @see https://html.spec.whatwg.org/multipage/syntax.html#adoption-agency-algorithm
	 */
	public function adoptionAgency( $tag, $afe ) {
		// 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 open
		// elements and abort these steps.
		if (
			$this->currentNode->isHtmlNamed( $tag ) &&
			!$afe->isInList( $this->currentNode )
		) {
			$this->pop();
			return true; // no more handling required
		}

		// Outer loop: If outer loop counter is greater than or
		// equal to eight, then abort these steps.
		for ( $outer = 0; $outer < 8; $outer++ ) {
			// Let the formatting element be the last element in the list
			// of active formatting elements that: is between the end of
			// the list and the last scope marker in the list, if any, or
			// the start of the list otherwise, and has the same tag name
			// as the token.
			$fmtElt = $afe->findElementByTag( $tag );

			// If there is no such node, then abort these steps and instead
			// act as described in the "any other end tag" entry below.
			if ( !$fmtElt ) {
				return false; // false means handle by the default case
			}

			// Otherwise, if there is such a node, but that node is not in
			// the stack of open elements, then this is a parse error;
			// remove the element from the list, and abort these steps.
			$index = $this->indexOf( $fmtElt );
			if ( $index < 0 ) {
				$afe->remove( $fmtElt );
				return true;   // true means no more handling required
			}

			// Otherwise, if there is such a node, and that node is also in
			// the stack of open elements, but the element is not in scope,
			// then this is a parse error; ignore the token, and abort
			// these steps.
			if ( !$this->inScope( $fmtElt ) ) {
				return true;
			}

			// Let the furthest block be the topmost node in the stack of
			// open elements that is lower in the stack than the formatting
			// element, and is an element in the special category. There
			// might not be one.
			$furthestBlock = null;
			$furthestBlockIndex = -1;
			$stackLength = $this->length();
			for ( $i = $index + 1; $i < $stackLength; $i++ ) {
				if ( $this->node( $i )->isA( BalanceSets::$specialSet ) ) {
					$furthestBlock = $this->node( $i );
					$furthestBlockIndex = $i;
					break;
				}
			}

			// If there is no furthest block, then the UA must skip the
			// subsequent steps and instead just pop all the nodes from the
			// bottom of the stack of open elements, from the current node
			// up to and including the formatting element, and remove the
			// formatting element from the list of active formatting
			// elements.
			if ( !$furthestBlock ) {
				$this->popTag( $fmtElt );
				$afe->remove( $fmtElt );
				return true;
			}

			// Let the common ancestor be the element immediately above
			// the formatting element in the stack of open elements.
			$ancestor = $this->node( $index - 1 );

			// Let a bookmark note the position of the formatting
			// element in the list of active formatting elements
			// relative to the elements on either side of it in the
			// list.
			$BOOKMARK = new BalanceElement( '[bookmark]', '[bookmark]', [] );
			$afe->insertAfter( $fmtElt, $BOOKMARK );

			// Let node and last node be the furthest block.
			$node = $furthestBlock;
			$lastNode = $furthestBlock;
			$nodeIndex = $furthestBlockIndex;
			$isAFE = false;

			// Inner loop
			for ( $inner = 1; true; $inner++ ) {
				// Let node be the element immediately above node in
				// the stack of open elements, or if node is no longer
				// in the stack of open elements (e.g. because it got
				// removed by this algorithm), the element that was
				// immediately above node in the stack of open elements
				// before node was removed.
				$node = $this->node( --$nodeIndex );

				// If node is the formatting element, then go
				// to the next step in the overall algorithm.
				if ( $node === $fmtElt ) break;

				// If the inner loop counter is greater than three and node
				// is in the list of active formatting elements, then remove
				// node from the list of active formatting elements.
				$isAFE = $afe->isInList( $node );
				if ( $inner > 3 && $isAFE ) {
					$afe->remove( $node );
					$isAFE = false;
				}

				// If node is not in the list of active formatting
				// elements, then remove node from the stack of open
				// elements and then go back to the step labeled inner
				// loop.
				if ( !$isAFE ) {
					// Don't flatten here, since we're about to relocate
					// parts of this $node.
					$this->removeElement( $node, false );
					continue;
				}

				// Create an element for the token for which the
				// element node was created with common ancestor as
				// the intended parent, replace the entry for node
				// in the list of active formatting elements with an
				// entry for the new element, replace the entry for
				// node in the stack of open elements with an entry for
				// the new element, and let node be the new element.
				$newElt = new BalanceElement(
					$node->namespaceURI, $node->localName, $node->attribs );
				$afe->replace( $node, $newElt );
				$this->replaceAt( $nodeIndex, $newElt );
				$node = $newElt;

				// If last node is the furthest block, then move the
				// aforementioned bookmark to be immediately after the
				// new node in the list of active formatting elements.
				if ( $lastNode === $furthestBlock ) {
					$afe->remove( $BOOKMARK );
					$afe->insertAfter( $newElt, $BOOKMARK );
				}

				// Insert last node into node, first removing it from
				// its previous parent node if any.
				$node->appendChild( $lastNode );

				// Let last node be node.
				$lastNode = $node;
			}

			// If the common ancestor node is a table, tbody, tfoot,
			// thead, or tr element, then, foster parent whatever last
			// node ended up being in the previous step, first removing
			// it from its previous parent node if any.
			if (
				$this->fosterParentMode &&
				$ancestor->isA( BalanceSets::$tableSectionRowSet )
			) {
				$this->fosterParent( $lastNode );
			} else {
				// Otherwise, append whatever last node ended up being in
				// the previous step to the common ancestor node, first
				// removing it from its previous parent node if any.
				$ancestor->appendChild( $lastNode );
			}

			// Create an element for the token for which the
			// formatting element was created, with furthest block
			// as the intended parent.
			$newElt2 = new BalanceElement(
				$fmtElt->namespaceURI, $fmtElt->localName, $fmtElt->attribs );

			// Take all of the child nodes of the furthest block and
			// append them to the element created in the last step.
			$newElt2->adoptChildren( $furthestBlock );

			// Append that new element to the furthest block.
			$furthestBlock->appendChild( $newElt2 );

			// Remove the formatting element from the list of active
			// formatting elements, and insert the new element into the
			// list of active formatting elements at the position of
			// the aforementioned bookmark.
			$afe->remove( $fmtElt );
			$afe->replace( $BOOKMARK, $newElt2 );

			// Remove the formatting element from the stack of open
			// elements, and insert the new element into the stack of
			// open elements immediately below the position of the
			// furthest block in that stack.
			$this->removeElement( $fmtElt );
			$this->insertAfter( $furthestBlock, $newElt2 );
		}

		return true;
	}

	/**
	 * Return the contents of the open elements stack as a string for
	 * debugging.
	 * @return string
	 */
	public function __toString() {
		$r = [];
		foreach ( $this->elements as $elt ) {
			array_push( $r, $elt->localName );
		}
		return implode( ' ', $r );
	}
}

/**
 * A pseudo-element used as a marker in the list of active formatting elements
 *
 * @ingroup Parser
 * @since 1.27
 */
class BalanceMarker {
	public $nextAFE;
	public $prevAFE;
}

/**
 * The list of active formatting elements, which is used to handle
 * mis-nested formatting element tags in the HTML5 tree builder
 * specification.
 *
 * @ingroup Parser
 * @since 1.27
 * @see https://html.spec.whatwg.org/multipage/syntax.html#list-of-active-formatting-elements
 */
class BalanceActiveFormattingElements {
	/** The last (most recent) element in the list */
	private $tail;

	/** The first (least recent) element in the list */
	private $head;

	/**
	 * An array of arrays representing the population of elements in each bucket
	 * according to the Noah's Ark clause. The outer array is stack-like, with each
	 * integer-indexed element representing a segment of the list, bounded by
	 * markers. The first element represents the segment of the list before the
	 * first marker.
	 *
	 * The inner arrays are indexed by "Noah key", which is a string which uniquely
	 * identifies each bucket according to the rules in the spec. The value in
	 * the inner array is the first (least recently inserted) element in the bucket,
	 * and subsequent members of the bucket can be found by iterating through the
	 * singly-linked list via $node->nextNoah.
	 *
	 * This is optimised for the most common case of inserting into a bucket
	 * with zero members, and deleting a bucket containing one member. In the
	 * worst case, iteration through the list is still O(1) in the document
	 * size, since each bucket can have at most 3 members.
	 */
	private $noahTableStack = [ [] ];

	public function __destruct() {
		$next = null;
		for ( $node = $this->head; $node; $node = $next ) {
			$next = $node->nextAFE;
			$node->prevAFE = $node->nextAFE = $node->nextNoah = null;
		}
		$this->head = $this->tail = $this->noahTableStack = null;
	}

	public function insertMarker() {
		$elt = new BalanceMarker;
		if ( $this->tail ) {
			$this->tail->nextAFE = $elt;
			$elt->prevAFE = $this->tail;
		} else {
			$this->head = $elt;
		}
		$this->tail = $elt;
		$this->noahTableStack[] = [];
	}

	/**
	 * Follow the steps required when the spec requires us to "push onto the
	 * list of active formatting elements".
	 * @param BalanceElement $elt
	 */
	public function push( BalanceElement $elt ) {
		// Must not be in the list already
		if ( $elt->prevAFE !== null || $this->head === $elt ) {
			throw new ParameterAssertionException( '$elt',
				'Cannot insert a node into the AFE list twice' );
		}

		// "Noah's Ark clause" -- if there are already three copies of
		// this element before we encounter a marker, then drop the last
		// one.
		$noahKey = $elt->getNoahKey();
		$table =& $this->noahTableStack[ count( $this->noahTableStack ) - 1 ];
		if ( !isset( $table[$noahKey] ) ) {
			$table[$noahKey] = $elt;
		} else {
			$count = 1;
			$head = $tail = $table[$noahKey];
			while ( $tail->nextNoah ) {
				$tail = $tail->nextNoah;
				$count++;
			}
			if ( $count >= 3 ) {
				$this->remove( $head );
			}
			$tail->nextNoah = $elt;
		}
		// Add to the main AFE list
		if ( $this->tail ) {
			$this->tail->nextAFE = $elt;
			$elt->prevAFE = $this->tail;
		} else {
			$this->head = $elt;
		}
		$this->tail = $elt;
	}

	/**
	 * Follow the steps required when the spec asks us to "clear the list of
	 * active formatting elements up to the last marker".
	 */
	public function clearToMarker() {
		// Iterate back through the list starting from the tail
		$tail = $this->tail;
		while ( $tail && !( $tail instanceof BalanceMarker ) ) {
			// Unlink the element
			$prev = $tail->prevAFE;
			$tail->prevAFE = null;
			if ( $prev ) {
				$prev->nextAFE = null;
			}
			$tail->nextNoah = null;
			$tail = $prev;
		}
		// If we finished on a marker, unlink it and pop it off the Noah table stack
		if ( $tail ) {
			$prev = $tail->prevAFE;
			if ( $prev ) {
				$prev->nextAFE = null;
			}
			$tail = $prev;
			array_pop( $this->noahTableStack );
		} else {
			// No marker: wipe the top-level Noah table (which is the only one)
			$this->noahTableStack[0] = [];
		}
		// If we removed all the elements, clear the head pointer
		if ( !$tail ) {
			$this->head = null;
		}
		$this->tail = $tail;
	}

	/**
	 * Find and return the last element with the specified tag between the
	 * end of the list and the last marker on the list.
	 * Used when parsing &lt;a&gt; "in body mode".
	 * @param string $tag
	 * @return null|Node
	 */
	public function findElementByTag( $tag ) {
		$elt = $this->tail;
		while ( $elt && !( $elt instanceof BalanceMarker ) ) {
			if ( $elt->localName === $tag ) {
				return $elt;
			}
			$elt = $elt->prevAFE;
		}
		return null;
	}

	/**
	 * Determine whether an element is in the list of formatting elements.
	 * @param BalanceElement $elt
	 * @return bool
	 */
	public function isInList( BalanceElement $elt ) {
		return $this->head === $elt || $elt->prevAFE;
	}

	/**
	 * Find the element $elt in the list and remove it.
	 * Used when parsing &lt;a&gt; in body mode.
	 *
	 * @param BalanceElement $elt
	 */
	public function remove( BalanceElement $elt ) {
		if ( $this->head !== $elt && !$elt->prevAFE ) {
			throw new ParameterAssertionException( '$elt',
				"Attempted to remove an element which is not in the AFE list" );
		}
		// Update head and tail pointers
		if ( $this->head === $elt ) {
			$this->head = $elt->nextAFE;
		}
		if ( $this->tail === $elt ) {
			$this->tail = $elt->prevAFE;
		}
		// Update previous element
		if ( $elt->prevAFE ) {
			$elt->prevAFE->nextAFE = $elt->nextAFE;
		}
		// Update next element
		if ( $elt->nextAFE ) {
			$elt->nextAFE->prevAFE = $elt->prevAFE;
		}
		// Clear pointers so that isInList() etc. will work
		$elt->prevAFE = $elt->nextAFE = null;
		// Update Noah list
		$this->removeFromNoahList( $elt );
	}

	private function addToNoahList( BalanceElement $elt ) {
		$noahKey = $elt->getNoahKey();
		$table =& $this->noahTableStack[ count( $this->noahTableStack ) - 1 ];
		if ( !isset( $table[$noahKey] ) ) {
			$table[$noahKey] = $elt;
		} else {
			$tail = $table[$noahKey];
			while ( $tail->nextNoah ) {
				$tail = $tail->nextNoah;
			}
			$tail->nextNoah = $elt;
		}
	}

	private function removeFromNoahList( BalanceElement $elt ) {
		$table =& $this->noahTableStack[ count( $this->noahTableStack ) - 1 ];
		$key = $elt->getNoahKey();
		$noahElt = $table[$key];
		if ( $noahElt === $elt ) {
			if ( $noahElt->nextNoah ) {
				$table[$key] = $noahElt->nextNoah;
				$noahElt->nextNoah = null;
			} else {
				unset( $table[$key] );
			}
		} else {
			do {
				$prevNoahElt = $noahElt;
				$noahElt = $prevNoahElt->nextNoah;
				if ( $noahElt === $elt ) {
					// Found it, unlink
					$prevNoahElt->nextNoah = $elt->nextNoah;
					$elt->nextNoah = null;
					break;
				}
			} while ( $noahElt );
		}
	}

	/**
	 * Find element $a in the list and replace it with element $b
	 *
	 * @param BalanceElement $a
	 * @param BalanceElement $b
	 */
	public function replace( BalanceElement $a, BalanceElement $b ) {
		if ( $this->head !== $a && !$a->prevAFE ) {
			throw new ParameterAssertionException( '$a',
				"Attempted to replace an element which is not in the AFE list" );
		}
		// Update head and tail pointers
		if ( $this->head === $a ) {
			$this->head = $b;
		}
		if ( $this->tail === $a ) {
			$this->tail = $b;
		}
		// Update previous element
		if ( $a->prevAFE ) {
			$a->prevAFE->nextAFE = $b;
		}
		// Update next element
		if ( $a->nextAFE ) {
			$a->nextAFE->prevAFE = $b;
		}
		$b->prevAFE = $a->prevAFE;
		$b->nextAFE = $a->nextAFE;
		$a->nextAFE = $a->prevAFE = null;
		// Update Noah list
		$this->removeFromNoahList( $a );
		$this->addToNoahList( $b );
	}

	/**
	 * Find $a in the list and insert $b after it.

	 * @param BalanceElement $a
	 * @param BalanceElement $b
	 */
	public function insertAfter( BalanceElement $a, BalanceElement $b ) {
		if ( $this->head !== $a && !$a->prevAFE ) {
			throw new ParameterAssertionException( '$a',
				"Attempted to insert after an element which is not in the AFE list" );
		}
		if ( $this->tail === $a ) {
			$this->tail = $b;
		}
		if ( $a->nextAFE ) {
			$a->nextAFE->prevAFE = $b;
		}
		$b->nextAFE = $a->nextAFE;
		$b->prevAFE = $a;
		$a->nextAFE = $b;
		$this->addToNoahList( $b );
	}

	/**
	 * Reconstruct the active formatting elements.
	 * @param BalanceStack $stack The open elements stack
	 * @see https://html.spec.whatwg.org/multipage/syntax.html#reconstruct-the-active-formatting-elements
	 */
	public function reconstruct( $stack ) {
		$entry = $this->tail;
		// If there are no entries in the list of active formatting elements,
		// then there is nothing to reconstruct
		if ( !$entry ) {
			return;
		}
		// If the last is a marker, do nothing.
		if ( $entry instanceof BalanceMarker ) {
			return;
		}
		// Or if it is an open element, do nothing.
		if ( $stack->indexOf( $entry ) >= 0 ) {
			return;
		}

		// Loop backward through the list until we find a marker or an
		// open element
		$foundIt = false;
		while ( $entry->prevAFE ) {
			$entry = $entry->prevAFE;
			if ( $entry instanceof BalanceMarker || $stack->indexOf( $entry ) >= 0 ) {
				$foundIt = true;
				break;
			}
		}

		// Now loop forward, starting from the element after the current one (or
		// the first element if we didn't find a marker or open element),
		// recreating formatting elements and pushing them back onto the list
		// of open elements.
		if ( $foundIt ) {
			$entry = $entry->nextAFE;
		}
		do {
			$newElement = $stack->insertHTMLElement(
				$entry->localName,
				$entry->attribs );
			$this->replace( $entry, $newElement );
			$entry = $newElement->nextAFE;
		} while ( $entry );
	}

	/**
	 * Get a string representation of the AFE list, for debugging
	 */
	public function __toString() {
		$prev = null;
		$s = '';
		for ( $node = $this->head; $node; $prev = $node, $node = $node->nextAFE ) {
			if ( $node instanceof BalanceMarker ) {
				$s .= "MARKER\n";
				continue;
			}
			$s .= $node->localName . '#' . substr( md5( spl_object_hash( $node ) ), 0, 8 );
			if ( $node->nextNoah ) {
				$s .= " (noah sibling: {$node->nextNoah->localName}#" .
					substr( md5( spl_object_hash( $node->nextNoah ) ), 0, 8 ) .
					')';
			}
			if ( $node->nextAFE && $node->nextAFE->prevAFE !== $node ) {
				$s .= " (reverse link is wrong!)";
			}
			$s .= "\n";
		}
		if ( $prev !== $this->tail ) {
			$s .= "(tail pointer is wrong!)\n";
		}
		return $s;
	}
}

/**
 * An implementation of the tree building portion of the HTML5 parsing
 * spec.
 *
 * This is used to balance and tidy output so that the result can
 * always be cleanly serialized/deserialized by an HTML5 parser.  It
 * does *not* guarantee "conforming" output -- the HTML5 spec contains
 * a number of constraints which are not enforced by the HTML5 parsing
 * process.  But the result will be free of gross errors: misnested or
 * unclosed tags, for example, and will be unchanged by spec-complient
 * parsing followed by serialization.
 *
 * The tree building stage is structured as a state machine.
 * When comparing the implementation to
 * https://www.w3.org/TR/html5/syntax.html#tree-construction
 * note that each state is implemented as a function with a
 * name ending in `Mode` (because the HTML spec refers to them
 * as insertion modes).  The current insertion mode is held by
 * the $parseMode property.
 *
 * The following simplifications have been made:
 * - We handle body content only (ie, we start `in body`.)
 * - The document is never in "quirks mode".
 * - All occurrences of < and > have been entity escaped, so we
 *   can parse tags by simply splitting on those two characters.
 *   (This also simplifies the handling of < inside <textarea>.)
 *   The character < must not appear inside comments.
 *   Similarly, all attributes have been "cleaned" and are double-quoted
 *   and escaped.
 * - All null characters are assumed to have been removed.
 * - The following elements are disallowed: <html>, <head>, <body>, <frameset>,
 *   <frame>, <plaintext>, <xmp>, <iframe>,
 *   <noembed>, <noscript>, <script>, <title>.  As a result,
 *   further simplifications can be made:
 *   - `frameset-ok` is not tracked.
 *   - `head element pointer` is not tracked (but presumed non-null)
 *   - Tokenizer has only a single mode. (<textarea> wants RCDATA and
 *     <style>/<noframes> want RAWTEXT modes which we only loosely emulate.)
 *
 *   We generally mark places where we omit cases from the spec due to
 *   disallowed elements with a comment: `// OMITTED: <element-name>`.
 *
 *   The HTML spec keeps a flag during the parsing process to track
 *   whether or not a "parse error" has been encountered.  We don't
 *   bother to track that flag, we just implement the error-handling
 *   process as specified.
 *
 * @ingroup Parser
 * @since 1.27
 * @see https://html.spec.whatwg.org/multipage/syntax.html#tree-construction
 */
class Balancer {
	private $parseMode;
	/** @var \Iterator */
	private $bitsIterator;
	private $allowedHtmlElements;
	/** @var BalanceActiveFormattingElements */
	private $afe;
	/** @var BalanceStack */
	private $stack;
	private $strict;
	private $allowComments;
	private $config;

	private $textIntegrationMode;
	private $pendingTableText;
	private $originalInsertionMode;
	private $fragmentContext;
	private $formElementPointer;
	private $ignoreLinefeed;
	private $inRCDATA;
	private $inRAWTEXT;

	/** @var callable|null */
	private $processingCallback;
	/** @var array */
	private $processingArgs;

	/**
	 * Valid HTML5 comments.
	 * Regex borrowed from Tim Starling's "remex-html" project.
	 */
	const VALID_COMMENT_REGEX = "~ !--
		(                           # 1. Comment match detector
			> | -> | # Invalid short close
			(                         # 2. Comment contents
				(?:
					(?! --> )
					(?! --!> )
					(?! --! \z )
					(?! -- \z )
					(?! - \z )
					.
				)*+
			)
			(                         # 3. Comment close
				--> |   # Normal close
				--!> |  # Comment end bang
				(                       # 4. Indicate matches requiring EOF
					--! |                   # EOF in comment end bang state
					-- |                    # EOF in comment end state
					-  |                    # EOF in comment end dash state
					(?#nothing)             # EOF in comment state
				)
			)
		)
		([^<]*) \z                  # 5. Non-tag text after the comment
		~xs";

	/**
	 * Create a new Balancer.
	 * @param array $config Balancer configuration.  Includes:
	 *     'strict' : boolean, defaults to false.
	 *         When true, enforces syntactic constraints on input:
	 *         all non-tag '<' must be escaped, all attributes must be
	 *         separated by a single space and double-quoted.  This is
	 *         consistent with the output of the Sanitizer.
	 *     'allowedHtmlElements' : array, defaults to null.
	 *         When present, the keys of this associative array give
	 *         the acceptable HTML tag names.  When not present, no
	 *         tag sanitization is done.
	 *     'tidyCompat' : boolean, defaults to false.
	 *         When true, the serialization algorithm is tweaked to
	 *         provide historical compatibility with the old "tidy"
	 *         program: <p>-wrapping is done to the children of
	 *         <body> and <blockquote> elements, and empty elements
	 *         are removed.  The <pre>/<listing>/<textarea> serialization
	 *         is also tweaked to allow lossless round trips.
	 *         (See: https://github.com/whatwg/html/issues/944)
	 *     'allowComments': boolean, defaults to true.
	 *         When true, allows HTML comments in the input.
	 *         The Sanitizer generally strips all comments, so if you
	 *         are running on sanitized output you can set this to
	 *         false to get a bit more performance.
	 */
	public function __construct( array $config = [] ) {
		$this->config = $config = $config + [
			'strict' => false,
			'allowedHtmlElements' => null,
			'tidyCompat' => false,
			'allowComments' => true,
		];
		$this->allowedHtmlElements = $config['allowedHtmlElements'];
		$this->strict = $config['strict'];
		$this->allowComments = $config['allowComments'];
		if ( $this->allowedHtmlElements !== null ) {
			// Sanity check!
			$bad = array_uintersect_assoc(
				$this->allowedHtmlElements,
				BalanceSets::$unsupportedSet[BalanceSets::HTML_NAMESPACE],
				function ( $a, $b ) {
					// Ignore the values (just intersect the keys) by saying
					// all values are equal to each other.
					return 0;
				}
			);
			if ( count( $bad ) > 0 ) {
				$badstr = implode( ',', array_keys( $bad ) );
				throw new ParameterAssertionException(
					'$config',
					'Balance attempted with sanitization including ' .
					"unsupported elements: {$badstr}"
				);
			}
		}
	}

	/**
	 * Return a balanced HTML string for the HTML fragment given by $text,
	 * subject to the caveats listed in the class description.  The result
	 * will typically be idempotent -- that is, rebalancing the output
	 * would result in no change.
	 *
	 * @param string $text The markup to be balanced
	 * @param callable $processingCallback Callback to do any variable or
	 *   parameter replacements in HTML attributes values
	 * @param array|bool $processingArgs Arguments for the processing callback
	 * @return string The balanced markup
	 */
	public function balance( $text, $processingCallback = null, $processingArgs = [] ) {
		$this->parseMode = 'inBodyMode';
		$this->bitsIterator = new ExplodeIterator( '<', $text );
		$this->afe = new BalanceActiveFormattingElements();
		$this->stack = new BalanceStack( $this->config );
		$this->processingCallback = $processingCallback;
		$this->processingArgs = $processingArgs;

		$this->textIntegrationMode =
			$this->ignoreLinefeed =
			$this->inRCDATA =
			$this->inRAWTEXT = false;

		// The stack is constructed with an <html> element already on it.
		// Set this up as a fragment parsed with <body> as the context.
		$this->fragmentContext =
			new BalanceElement( BalanceSets::HTML_NAMESPACE, 'body', [] );
		$this->resetInsertionMode();
		$this->formElementPointer = null;
		for ( $e = $this->fragmentContext; $e != null; $e = $e->parent ) {
			if ( $e->isHtmlNamed( 'form' ) ) {
				$this->formElementPointer = $e;
				break;
			}
		}

		// First element is text not tag
		$x = $this->bitsIterator->current();
		$this->bitsIterator->next();
		$this->insertToken( 'text', str_replace( '>', '&gt;', $x ) );
		// Now process each tag.
		while ( $this->bitsIterator->valid() ) {
			$this->advance();
		}
		$this->insertToken( 'eof', null );
		$result = $this->stack->getOutput();
		// Free memory before returning.
		$this->bitsIterator = null;
		$this->afe = null;
		$this->stack = null;
		$this->fragmentContext = null;
		$this->formElementPointer = null;
		return $result;
	}

	/**
	 * Pass a token to the tree builder.  The $token will be one of the
	 * strings "tag", "endtag", or "text".
	 */
	private function insertToken( $token, $value, $attribs = null, $selfClose = false ) {
		// validate tags against $unsupportedSet
		if ( $token === 'tag' || $token === 'endtag' ) {
			if ( isset( BalanceSets::$unsupportedSet[BalanceSets::HTML_NAMESPACE][$value] ) ) {
				// As described in "simplifications" above, these tags are
				// not supported in the balancer.
				Assert::invariant(
					!$this->strict,
					"Unsupported $token <$value> found."
				);
				return false;
			}
		} elseif ( $token === 'text' && $value === '' ) {
			// Don't actually inject the empty string as a text token.
			return true;
		}
		// Support pre/listing/textarea by suppressing initial linefeed
		if ( $this->ignoreLinefeed ) {
			$this->ignoreLinefeed = false;
			if ( $token === 'text' ) {
				if ( $value[0] === "\n" ) {
					if ( $value === "\n" ) {
						// Nothing would be left, don't inject the empty string.
						return true;
					}
					$value = substr( $value, 1 );
				}
			}
		}
		// Some hoops we have to jump through
		$adjusted = $this->stack->adjustedCurrentNode( $this->fragmentContext );

		// The spec calls this the "tree construction dispatcher".
		$isForeign = true;
		if (
			$this->stack->length() === 0 ||
			$adjusted->isHtml() ||
			$token === 'eof'
		) {
			$isForeign = false;
		} elseif ( $adjusted->isMathmlTextIntegrationPoint() ) {
			if ( $token === 'text' ) {
				$isForeign = false;
			} elseif (
				$token === 'tag' &&
				$value !== 'mglyph' && $value !== 'malignmark'
			) {
				$isForeign = false;
			}
		} elseif (
			$adjusted->namespaceURI === BalanceSets::MATHML_NAMESPACE &&
			$adjusted->localName === 'annotation-xml' &&
			$token === 'tag' && $value === 'svg'
		) {
			$isForeign = false;
		} elseif (
			$adjusted->isHtmlIntegrationPoint() &&
			( $token === 'tag' || $token === 'text' )
		) {
			$isForeign = false;
		}
		if ( $isForeign ) {
			return $this->insertForeignToken( $token, $value, $attribs, $selfClose );
		} else {
			$func = $this->parseMode;
			return $this->$func( $token, $value, $attribs, $selfClose );
		}
	}

	private function insertForeignToken( $token, $value, $attribs = null, $selfClose = false ) {
		if ( $token === 'text' ) {
			$this->stack->insertText( $value );
			return true;
		} elseif ( $token === 'comment' ) {
			$this->stack->insertComment( $value );
			return true;
		} elseif ( $token === 'tag' ) {
			switch ( $value ) {
				case 'font':
					if ( isset( $attribs['color'] )
						|| isset( $attribs['face'] )
						|| isset( $attribs['size'] )
					) {
						break;
					}
					// otherwise, fall through
				case 'b':
				case 'big':
				case 'blockquote':
				case 'body':
				case 'br':
				case 'center':
				case 'code':
				case 'dd':
				case 'div':
				case 'dl':
				case 'dt':
				case 'em':
				case 'embed':
				case 'h1':
				case 'h2':
				case 'h3':
				case 'h4':
				case 'h5':
				case 'h6':
				case 'head':
				case 'hr':
				case 'i':
				case 'img':
				case 'li':
				case 'listing':
				case 'menu':
				case 'meta':
				case 'nobr':
				case 'ol':
				case 'p':
				case 'pre':
				case 'ruby':
				case 's':
				case 'small':
				case 'span':
				case 'strong':
				case 'strike':
				case 'sub':
				case 'sup':
				case 'table':
				case 'tt':
				case 'u':
				case 'ul':
				case 'var':
					if ( $this->fragmentContext ) {
						break;
					}
					while ( true ) {
						$this->stack->pop();
						$node = $this->stack->currentNode;
						if (
							$node->isMathmlTextIntegrationPoint() ||
							$node->isHtmlIntegrationPoint() ||
							$node->isHtml()
						) {
							break;
						}
					}
					return $this->insertToken( $token, $value, $attribs, $selfClose );
			}
			// "Any other start tag"
			$adjusted = ( $this->fragmentContext && $this->stack->length() === 1 ) ?
				$this->fragmentContext : $this->stack->currentNode;
			$this->stack->insertForeignElement(
				$adjusted->namespaceURI, $value, $attribs
			);
			if ( $selfClose ) {
				$this->stack->pop();
			}
			return true;
		} elseif ( $token === 'endtag' ) {
			$first = true;
			foreach ( $this->stack as $i => $node ) {
				if ( $node->isHtml() && !$first ) {
					// process the end tag as HTML
					$func = $this->parseMode;
					return $this->$func( $token, $value, $attribs, $selfClose );
				} elseif ( $i === 0 ) {
					return true;
				} elseif ( $node->localName === $value ) {
					$this->stack->popTag( $node );
					return true;
				}
				$first = false;
			}
		}
	}

	/**
	 * Grab the next "token" from $bitsIterator.  This is either a open/close
	 * tag or text or a comment, depending on whether the Sanitizer approves.
	 */
	private function advance() {
		$x = $this->bitsIterator->current();
		$this->bitsIterator->next();
		$regs = [];
		// Handle comments.  These won't be generated by mediawiki (they
		// are stripped in the Sanitizer) but may be generated by extensions.
		if (
			$this->allowComments &&
			!( $this->inRCDATA || $this->inRAWTEXT ) &&
			preg_match( self::VALID_COMMENT_REGEX, $x, $regs, PREG_OFFSET_CAPTURE ) &&
			// verify EOF condition where necessary
			( $regs[4][1] < 0 || !$this->bitsIterator->valid() )
		) {
			$contents = $regs[2][0];
			$rest = $regs[5][0];
			$this->insertToken( 'comment', $contents );
			$this->insertToken( 'text', str_replace( '>', '&gt;', $rest ) );
			return;
		}
		// $slash: Does the current element start with a '/'?
		// $t: Current element name
		// $attribStr: String between element name and >
		// $brace: Ending '>' or '/>'
		// $rest: Everything until the next element from the $bitsIterator
		if ( preg_match( Sanitizer::ELEMENT_BITS_REGEX, $x, $regs ) ) {
			list( /* $qbar */, $slash, $t, $attribStr, $brace, $rest ) = $regs;
			$t = strtolower( $t );
			if ( $this->strict ) {
				// Verify that attributes are all properly double-quoted
				Assert::invariant(
					preg_match(
						'/^( [:_A-Z0-9][-.:_A-Z0-9]*="[^"]*")*[ ]*$/i', $attribStr
					),
					"Bad attribute string found"
				);
			}
		} else {
			Assert::invariant(
				!$this->strict, "< found which does not start a valid tag"
			);
			$slash = $t = $attribStr = $brace = $rest = null;
		}
		$goodTag = $t;
		if ( $this->inRCDATA ) {
			if ( $slash && $t === $this->inRCDATA ) {
				$this->inRCDATA = false;
			} else {
				// No tags allowed; this emulates the "rcdata" tokenizer mode.
				$goodTag = false;
			}
		}
		if ( $this->inRAWTEXT ) {
			if ( $slash && $t === $this->inRAWTEXT ) {
				$this->inRAWTEXT = false;
			} else {
				// No tags allowed, no entity-escaping done.
				$goodTag = false;
			}
		}
		$sanitize = $this->allowedHtmlElements !== null;
		if ( $sanitize ) {
			$goodTag = $t && isset( $this->allowedHtmlElements[$t] );
		}
		if ( $goodTag ) {
			if ( is_callable( $this->processingCallback ) ) {
				call_user_func_array( $this->processingCallback, [ &$attribStr, $this->processingArgs ] );
			}
			if ( $sanitize ) {
				$goodTag = Sanitizer::validateTag( $attribStr, $t );
			}
		}
		if ( $goodTag ) {
			if ( $sanitize ) {
				$attribs = Sanitizer::decodeTagAttributes( $attribStr );
				$attribs = Sanitizer::validateTagAttributes( $attribs, $t );
			} else {
				$attribs = Sanitizer::decodeTagAttributes( $attribStr );
			}
			$goodTag = $this->insertToken(
				$slash ? 'endtag' : 'tag', $t, $attribs, $brace === '/>'
			);
		}
		if ( $goodTag ) {
			$rest = str_replace( '>', '&gt;', $rest );
			$this->insertToken( 'text', str_replace( '>', '&gt;', $rest ) );
		} elseif ( $this->inRAWTEXT ) {
			$this->insertToken( 'text', "<$x" );
		} else {
			// bad tag; serialize entire thing as text.
			$this->insertToken( 'text', '&lt;' . str_replace( '>', '&gt;', $x ) );
		}
	}

	private function switchMode( $mode ) {
		Assert::parameter(
			substr( $mode, -4 ) === 'Mode', '$mode', 'should end in Mode'
		);
		$oldMode = $this->parseMode;
		$this->parseMode = $mode;
		return $oldMode;
	}

	private function switchModeAndReprocess( $mode, $token, $value, $attribs, $selfClose ) {
		$this->switchMode( $mode );
		return $this->insertToken( $token, $value, $attribs, $selfClose );
	}

	private function resetInsertionMode() {
		$last = false;
		foreach ( $this->stack as $i => $node ) {
			if ( $i === 0 ) {
				$last = true;
				if ( $this->fragmentContext ) {
					$node = $this->fragmentContext;
				}
			}
			if ( $node->isHtml() ) {
				switch ( $node->localName ) {
					case 'select':
						$stackLength = $this->stack->length();
						for ( $j = $i + 1; $j < $stackLength - 1; $j++ ) {
							$ancestor = $this->stack->node( $stackLength - $j - 1 );
							if ( $ancestor->isHtmlNamed( 'template' ) ) {
								break;
							}
							if ( $ancestor->isHtmlNamed( 'table' ) ) {
								$this->switchMode( 'inSelectInTableMode' );
								return;
							}
						}
						$this->switchMode( 'inSelectMode' );
						return;
					case 'tr':
						$this->switchMode( 'inRowMode' );
						return;
					case 'tbody':
					case 'tfoot':
					case 'thead':
						$this->switchMode( 'inTableBodyMode' );
						return;
					case 'caption':
						$this->switchMode( 'inCaptionMode' );
						return;
					case 'colgroup':
						$this->switchMode( 'inColumnGroupMode' );
						return;
					case 'table':
						$this->switchMode( 'inTableMode' );
						return;
					case 'template':
						$this->switchMode(
							array_slice( $this->templateInsertionModes, -1 )[0]
						);
						return;
					case 'body':
						$this->switchMode( 'inBodyMode' );
						return;
					// OMITTED: <frameset>
					// OMITTED: <html>
					// OMITTED: <head>
					default:
						if ( !$last ) {
							// OMITTED: <head>
							if ( $node->isA( BalanceSets::$tableCellSet ) ) {
								$this->switchMode( 'inCellMode' );
								return;
							}
						}
				}
			}
			if ( $last ) {
				$this->switchMode( 'inBodyMode' );
				return;
			}
		}
	}

	private function stopParsing() {
		// Most of the spec methods are inapplicable, other than step 2:
		// "pop all the nodes off the stack of open elements".
		// We're going to keep the top-most <html> element on the stack, though.

		// Clear the AFE list first, otherwise the element objects will stay live
		// during serialization, potentially using O(N^2) memory. Note that
		// popping the stack will never result in reconstructing the active
		// formatting elements.
		$this->afe = null;
		$this->stack->popTo( 1 );
	}

	private function parseRawText( $value, $attribs = null ) {
		$this->stack->insertHTMLElement( $value, $attribs );
		$this->inRAWTEXT = $value;
		$this->originalInsertionMode = $this->switchMode( 'inTextMode' );
		return true;
	}

	private function inTextMode( $token, $value, $attribs = null, $selfClose = false ) {
		if ( $token === 'text' ) {
			$this->stack->insertText( $value );
			return true;
		} elseif ( $token === 'eof' ) {
			$this->stack->pop();
			return $this->switchModeAndReprocess(
				$this->originalInsertionMode, $token, $value, $attribs, $selfClose
			);
		} elseif ( $token === 'endtag' ) {
			$this->stack->pop();
			$this->switchMode( $this->originalInsertionMode );
			return true;
		}
		return true;
	}

	private function inHeadMode( $token, $value, $attribs = null, $selfClose = false ) {
		if ( $token === 'text' ) {
			if ( preg_match( '/^[\x09\x0A\x0C\x0D\x20]+/', $value, $matches ) ) {
				$this->stack->insertText( $matches[0] );
				$value = substr( $value, strlen( $matches[0] ) );
			}
			if ( strlen( $value ) === 0 ) {
				return true; // All text handled.
			}
			// Fall through to handle non-whitespace below.
		} elseif ( $token === 'tag' ) {
			switch ( $value ) {
				case 'meta':
					// OMITTED: in a full HTML parser, this might change the encoding.
					// falls through
				// OMITTED: <html>
				case 'base':
				case 'basefont':
				case 'bgsound':
				case 'link':
					$this->stack->insertHTMLElement( $value, $attribs );
					$this->stack->pop();
					return true;
				// OMITTED: <title>
				// OMITTED: <noscript>
				case 'noframes':
				case 'style':
					return $this->parseRawText( $value, $attribs );
				// OMITTED: <script>
				case 'template':
					$this->stack->insertHTMLElement( $value, $attribs );
					$this->afe->insertMarker();
					// OMITTED: frameset_ok
					$this->switchMode( 'inTemplateMode' );
					$this->templateInsertionModes[] = $this->parseMode;
					return true;
				// OMITTED: <head>
			}
		} elseif ( $token === 'endtag' ) {
			switch ( $value ) {
				// OMITTED: <head>
				// OMITTED: <body>
				// OMITTED: <html>
				case 'br':
					break; // handle at the bottom of the function
				case 'template':
					if ( $this->stack->indexOf( $value ) < 0 ) {
						return true; // Ignore the token.
					}
					$this->stack->generateImpliedEndTags( null, true /* thorough */ );
					$this->stack->popTag( $value );
					$this->afe->clearToMarker();
					array_pop( $this->templateInsertionModes );
					$this->resetInsertionMode();
					return true;
				default:
					// ignore any other end tag
					return true;
			}
		} elseif ( $token === 'comment' ) {
			$this->stack->insertComment( $value );
			return true;
		}

		// If not handled above
		$this->inHeadMode( 'endtag', 'head' ); // synthetic </head>
		// Then redo this one
		return $this->insertToken( $token, $value, $attribs, $selfClose );
	}

	private function inBodyMode( $token, $value, $attribs = null, $selfClose = false ) {
		if ( $token === 'text' ) {
			$this->afe->reconstruct( $this->stack );
			$this->stack->insertText( $value );
			return true;
		} elseif ( $token === 'eof' ) {
			if ( !empty( $this->templateInsertionModes ) ) {
				return $this->inTemplateMode( $token, $value, $attribs, $selfClose );
			}
			$this->stopParsing();
			return true;
		} elseif ( $token === 'tag' ) {
			switch ( $value ) {
				// OMITTED: <html>
				case 'base':
				case 'basefont':
				case 'bgsound':
				case 'link':
				case 'meta':
				case 'noframes':
				// OMITTED: <script>
				case 'style':
				case 'template':
				// OMITTED: <title>
					return $this->inHeadMode( $token, $value, $attribs, $selfClose );
				// OMITTED: <body>
				// OMITTED: <frameset>

				case 'address':
				case 'article':
				case 'aside':
				case 'blockquote':
				case 'center':
				case 'details':
				case 'dialog':
				case 'dir':
				case 'div':
				case 'dl':
				case 'fieldset':
				case 'figcaption':
				case 'figure':
				case 'footer':
				case 'header':
				case 'hgroup':
				case 'main':
				case 'nav':
				case 'ol':
				case 'p':
				case 'section':
				case 'summary':
				case 'ul':
					if ( $this->stack->inButtonScope( 'p' ) ) {
						$this->inBodyMode( 'endtag', 'p' );
					}
					$this->stack->insertHTMLElement( $value, $attribs );
					return true;

				case 'menu':
					if ( $this->stack->inButtonScope( "p" ) ) {
						$this->inBodyMode( 'endtag', 'p' );
					}
					if ( $this->stack->currentNode->isHtmlNamed( 'menuitem' ) ) {
						$this->stack->pop();
					}
					$this->stack->insertHTMLElement( $value, $attribs );
					return true;

				case 'h1':
				case 'h2':
				case 'h3':
				case 'h4':
				case 'h5':
				case 'h6':
					if ( $this->stack->inButtonScope( 'p' ) ) {
						$this->inBodyMode( 'endtag', 'p' );
					}
					if ( $this->stack->currentNode->isA( BalanceSets::$headingSet ) ) {
						$this->stack->pop();
					}
					$this->stack->insertHTMLElement( $value, $attribs );
					return true;

				case 'pre':
				case 'listing':
					if ( $this->stack->inButtonScope( 'p' ) ) {
						$this->inBodyMode( 'endtag', 'p' );
					}
					$this->stack->insertHTMLElement( $value, $attribs );
					$this->ignoreLinefeed = true;
					// OMITTED: frameset_ok
					return true;

				case 'form':
					if (
						$this->formElementPointer &&
						$this->stack->indexOf( 'template' ) < 0
					) {
						return true; // in a form, not in a template.
					}
					if ( $this->stack->inButtonScope( "p" ) ) {
						$this->inBodyMode( 'endtag', 'p' );
					}
					$elt = $this->stack->insertHTMLElement( $value, $attribs );
					if ( $this->stack->indexOf( 'template' ) < 0 ) {
						$this->formElementPointer = $elt;
					}
					return true;

				case 'li':
					// OMITTED: frameset_ok
					foreach ( $this->stack as $node ) {
						if ( $node->isHtmlNamed( 'li' ) ) {
							$this->inBodyMode( 'endtag', 'li' );
							break;
						}
						if (
							$node->isA( BalanceSets::$specialSet ) &&
							!$node->isA( BalanceSets::$addressDivPSet )
						) {
							break;
						}
					}
					if ( $this->stack->inButtonScope( 'p' ) ) {
						$this->inBodyMode( 'endtag', 'p' );
					}
					$this->stack->insertHTMLElement( $value, $attribs );
					return true;

				case 'dd':
				case 'dt':
					// OMITTED: frameset_ok
					foreach ( $this->stack as $node ) {
						if ( $node->isHtmlNamed( 'dd' ) ) {
							$this->inBodyMode( 'endtag', 'dd' );
							break;
						}
						if ( $node->isHtmlNamed( 'dt' ) ) {
							$this->inBodyMode( 'endtag', 'dt' );
							break;
						}
						if (
							$node->isA( BalanceSets::$specialSet ) &&
							!$node->isA( BalanceSets::$addressDivPSet )
						) {
							break;
						}
					}
					if ( $this->stack->inButtonScope( 'p' ) ) {
						$this->inBodyMode( 'endtag', 'p' );
					}
					$this->stack->insertHTMLElement( $value, $attribs );
					return true;

				// OMITTED: <plaintext>

				case 'button':
					if ( $this->stack->inScope( 'button' ) ) {
						$this->inBodyMode( 'endtag', 'button' );
						return $this->insertToken( $token, $value, $attribs, $selfClose );
					}
					$this->afe->reconstruct( $this->stack );
					$this->stack->insertHTMLElement( $value, $attribs );
					return true;

				case 'a':
					$activeElement = $this->afe->findElementByTag( 'a' );
					if ( $activeElement ) {
						$this->inBodyMode( 'endtag', 'a' );
						if ( $this->afe->isInList( $activeElement ) ) {
							$this->afe->remove( $activeElement );
							// Don't flatten here, since when we fall
							// through below we might foster parent
							// the new <a> tag inside this one.
							$this->stack->removeElement( $activeElement, false );
						}
					}
					// Falls through
				case 'b':
				case 'big':
				case 'code':
				case 'em':
				case 'font':
				case 'i':
				case 's':
				case 'small':
				case 'strike':
				case 'strong':
				case 'tt':
				case 'u':
					$this->afe->reconstruct( $this->stack );
					$this->afe->push( $this->stack->insertHTMLElement( $value, $attribs ) );
					return true;

				case 'nobr':
					$this->afe->reconstruct( $this->stack );
					if ( $this->stack->inScope( 'nobr' ) ) {
						$this->inBodyMode( 'endtag', 'nobr' );
						$this->afe->reconstruct( $this->stack );
					}
					$this->afe->push( $this->stack->insertHTMLElement( $value, $attribs ) );
					return true;

				case 'applet':
				case 'marquee':
				case 'object':
					$this->afe->reconstruct( $this->stack );
					$this->stack->insertHTMLElement( $value, $attribs );
					$this->afe->insertMarker();
					// OMITTED: frameset_ok
					return true;

				case 'table':
					// The document is never in "quirks mode"; see simplifications
					// above.
					if ( $this->stack->inButtonScope( 'p' ) ) {
						$this->inBodyMode( 'endtag', 'p' );
					}
					$this->stack->insertHTMLElement( $value, $attribs );
					// OMITTED: frameset_ok
					$this->switchMode( 'inTableMode' );
					return true;

				case 'area':
				case 'br':
				case 'embed':
				case 'img':
				case 'keygen':
				case 'wbr':
					$this->afe->reconstruct( $this->stack );
					$this->stack->insertHTMLElement( $value, $attribs );
					$this->stack->pop();
					// OMITTED: frameset_ok
					return true;

				case 'input':
					$this->afe->reconstruct( $this->stack );
					$this->stack->insertHTMLElement( $value, $attribs );
					$this->stack->pop();
					// OMITTED: frameset_ok
					// (hence we don't need to examine the tag's "type" attribute)
					return true;

				case 'param':
				case 'source':
				case 'track':
					$this->stack->insertHTMLElement( $value, $attribs );
					$this->stack->pop();
					return true;

				case 'hr':
					if ( $this->stack->inButtonScope( 'p' ) ) {
						$this->inBodyMode( 'endtag', 'p' );
					}
					if ( $this->stack->currentNode->isHtmlNamed( 'menuitem' ) ) {
						$this->stack->pop();
					}
					$this->stack->insertHTMLElement( $value, $attribs );
					$this->stack->pop();
					return true;

				case 'image':
					// warts!
					return $this->inBodyMode( $token, 'img', $attribs, $selfClose );

				case 'textarea':
					$this->stack->insertHTMLElement( $value, $attribs );
					$this->ignoreLinefeed = true;
					$this->inRCDATA = $value; // emulate rcdata tokenizer mode
					// OMITTED: frameset_ok
					return true;

				// OMITTED: <xmp>
				// OMITTED: <iframe>
				// OMITTED: <noembed>
				// OMITTED: <noscript>

				case 'select':
					$this->afe->reconstruct( $this->stack );
					$this->stack->insertHTMLElement( $value, $attribs );
					switch ( $this->parseMode ) {
						case 'inTableMode':
						case 'inCaptionMode':
						case 'inTableBodyMode':
						case 'inRowMode':
						case 'inCellMode':
							$this->switchMode( 'inSelectInTableMode' );
							return true;
						default:
							$this->switchMode( 'inSelectMode' );
							return true;
					}

				case 'optgroup':
				case 'option':
					if ( $this->stack->currentNode->isHtmlNamed( 'option' ) ) {
						$this->inBodyMode( 'endtag', 'option' );
					}
					$this->afe->reconstruct( $this->stack );
					$this->stack->insertHTMLElement( $value, $attribs );
					return true;

				case 'menuitem':
					if ( $this->stack->currentNode->isHtmlNamed( 'menuitem' ) ) {
						$this->stack->pop();
					}
					$this->afe->reconstruct( $this->stack );
					$this->stack->insertHTMLElement( $value, $attribs );
					return true;

				case 'rb':
				case 'rtc':
					if ( $this->stack->inScope( 'ruby' ) ) {
						$this->stack->generateImpliedEndTags();
					}
					$this->stack->insertHTMLElement( $value, $attribs );
					return true;

				case 'rp':
				case 'rt':
					if ( $this->stack->inScope( 'ruby' ) ) {
						$this->stack->generateImpliedEndTags( 'rtc' );
					}
					$this->stack->insertHTMLElement( $value, $attribs );
					return true;

				case 'math':
					$this->afe->reconstruct( $this->stack );
					// We skip the spec's "adjust MathML attributes" and
					// "adjust foreign attributes" steps, since the browser will
					// do this later when it parses the output and it doesn't affect
					// balancing.
					$this->stack->insertForeignElement(
						BalanceSets::MATHML_NAMESPACE, $value, $attribs
					);
					if ( $selfClose ) {
						// emit explicit </math> tag.
						$this->stack->pop();
					}
					return true;

				case 'svg':
					$this->afe->reconstruct( $this->stack );
					// We skip the spec's "adjust SVG attributes" and
					// "adjust foreign attributes" steps, since the browser will
					// do this later when it parses the output and it doesn't affect
					// balancing.
					$this->stack->insertForeignElement(
						BalanceSets::SVG_NAMESPACE, $value, $attribs
					);
					if ( $selfClose ) {
						// emit explicit </svg> tag.
						$this->stack->pop();
					}
					return true;

				case 'caption':
				case 'col':
				case 'colgroup':
				// OMITTED: <frame>
				case 'head':
				case 'tbody':
				case 'td':
				case 'tfoot':
				case 'th':
				case 'thead':
				case 'tr':
					// Ignore table tags if we're not inTableMode
					return true;
			}

			// Handle any other start tag here
			$this->afe->reconstruct( $this->stack );
			$this->stack->insertHTMLElement( $value, $attribs );
			return true;
		} elseif ( $token === 'endtag' ) {
			switch ( $value ) {
				// </body>,</html> are unsupported.

				case 'template':
					return $this->inHeadMode( $token, $value, $attribs, $selfClose );

				case 'address':
				case 'article':
				case 'aside':
				case 'blockquote':
				case 'button':
				case 'center':
				case 'details':
				case 'dialog':
				case 'dir':
				case 'div':
				case 'dl':
				case 'fieldset':
				case 'figcaption':
				case 'figure':
				case 'footer':
				case 'header':
				case 'hgroup':
				case 'listing':
				case 'main':
				case 'menu':
				case 'nav':
				case 'ol':
				case 'pre':
				case 'section':
				case 'summary':
				case 'ul':
					// Ignore if there is not a matching open tag
					if ( !$this->stack->inScope( $value ) ) {
						return true;
					}
					$this->stack->generateImpliedEndTags();
					$this->stack->popTag( $value );
					return true;

				case 'form':
					if ( $this->stack->indexOf( 'template' ) < 0 ) {
						$openform = $this->formElementPointer;
						$this->formElementPointer = null;
						if ( !$openform || !$this->stack->inScope( $openform ) ) {
							return true;
						}
						$this->stack->generateImpliedEndTags();
						// Don't flatten yet if we're removing a <form> element
						// out-of-order. (eg. `<form><div></form>`)
						$flatten = ( $this->stack->currentNode === $openform );
						$this->stack->removeElement( $openform, $flatten );
					} else {
						if ( !$this->stack->inScope( 'form' ) ) {
							return true;
						}
						$this->stack->generateImpliedEndTags();
						$this->stack->popTag( 'form' );
					}
					return true;

				case 'p':
					if ( !$this->stack->inButtonScope( 'p' ) ) {
						$this->inBodyMode( 'tag', 'p', [] );
						return $this->insertToken( $token, $value, $attribs, $selfClose );
					}
					$this->stack->generateImpliedEndTags( $value );
					$this->stack->popTag( $value );
					return true;

				case 'li':
					if ( !$this->stack->inListItemScope( $value ) ) {
						return true; // ignore
					}
					$this->stack->generateImpliedEndTags( $value );
					$this->stack->popTag( $value );
					return true;

				case 'dd':
				case 'dt':
					if ( !$this->stack->inScope( $value ) ) {
						return true; // ignore
					}
					$this->stack->generateImpliedEndTags( $value );
					$this->stack->popTag( $value );
					return true;

				case 'h1':
				case 'h2':
				case 'h3':
				case 'h4':
				case 'h5':
				case 'h6':
					if ( !$this->stack->inScope( BalanceSets::$headingSet ) ) {
						return true; // ignore
					}
					$this->stack->generateImpliedEndTags();
					$this->stack->popTag( BalanceSets::$headingSet );
					return true;

				case 'sarcasm':
					// Take a deep breath, then:
					break;

				case 'a':
				case 'b':
				case 'big':
				case 'code':
				case 'em':
				case 'font':
				case 'i':
				case 'nobr':
				case 's':
				case 'small':
				case 'strike':
				case 'strong':
				case 'tt':
				case 'u':
					if ( $this->stack->adoptionAgency( $value, $this->afe ) ) {
						return true; // If we did something, we're done.
					}
					break; // Go to the "any other end tag" case.

				case 'applet':
				case 'marquee':
				case 'object':
					if ( !$this->stack->inScope( $value ) ) {
						return true; // ignore
					}
					$this->stack->generateImpliedEndTags();
					$this->stack->popTag( $value );
					$this->afe->clearToMarker();
					return true;

				case 'br':
					// Turn </br> into <br>
					return $this->inBodyMode( 'tag', $value, [] );
			}

			// Any other end tag goes here
			foreach ( $this->stack as $i => $node ) {
				if ( $node->isHtmlNamed( $value ) ) {
					$this->stack->generateImpliedEndTags( $value );
					$this->stack->popTo( $i ); // including $i
					break;
				} elseif ( $node->isA( BalanceSets::$specialSet ) ) {
					return true; // ignore this close token.
				}
			}
			return true;
		} elseif ( $token === 'comment' ) {
			$this->stack->insertComment( $value );
			return true;
		} else {
			Assert::invariant( false, "Bad token type: $token" );
		}
	}

	private function inTableMode( $token, $value, $attribs = null, $selfClose = false ) {
		if ( $token === 'text' ) {
			if ( $this->textIntegrationMode ) {
				return $this->inBodyMode( $token, $value, $attribs, $selfClose );
			} elseif ( $this->stack->currentNode->isA( BalanceSets::$tableSectionRowSet ) ) {
				$this->pendingTableText = '';
				$this->originalInsertionMode = $this->parseMode;
				return $this->switchModeAndReprocess( 'inTableTextMode',
					$token, $value, $attribs, $selfClose );
			}
			// fall through to default case.
		} elseif ( $token === 'eof' ) {
			$this->stopParsing();
			return true;
		} elseif ( $token === 'tag' ) {
			switch ( $value ) {
				case 'caption':
					$this->afe->insertMarker();
					$this->stack->insertHTMLElement( $value, $attribs );
					$this->switchMode( 'inCaptionMode' );
					return true;
				case 'colgroup':
					$this->stack->clearToContext( BalanceSets::$tableContextSet );
					$this->stack->insertHTMLElement( $value, $attribs );
					$this->switchMode( 'inColumnGroupMode' );
					return true;
				case 'col':
					$this->inTableMode( 'tag', 'colgroup', [] );
					return $this->insertToken( $token, $value, $attribs, $selfClose );
				case 'tbody':
				case 'tfoot':
				case 'thead':
					$this->stack->clearToContext( BalanceSets::$tableContextSet );
					$this->stack->insertHTMLElement( $value, $attribs );
					$this->switchMode( 'inTableBodyMode' );
					return true;
				case 'td':
				case 'th':
				case 'tr':
					$this->inTableMode( 'tag', 'tbody', [] );
					return $this->insertToken( $token, $value, $attribs, $selfClose );
				case 'table':
					if ( !$this->stack->inTableScope( $value ) ) {
						return true; // Ignore this tag.
					}
					$this->inTableMode( 'endtag', $value );
					return $this->insertToken( $token, $value, $attribs, $selfClose );

				case 'style':
				// OMITTED: <script>
				case 'template':
					return $this->inHeadMode( $token, $value, $attribs, $selfClose );

				case 'input':
					if ( !isset( $attribs['type'] ) || strcasecmp( $attribs['type'], 'hidden' ) !== 0 ) {
						break; // Handle this as "everything else"
					}
					$this->stack->insertHTMLElement( $value, $attribs );
					$this->stack->pop();
					return true;

				case 'form':
					if (
						$this->formElementPointer ||
						$this->stack->indexOf( 'template' ) >= 0
					) {
						return true; // ignore this token
					}
					$this->formElementPointer =
						$this->stack->insertHTMLElement( $value, $attribs );
					$this->stack->popTag( $this->formElementPointer );
					return true;
			}
			// Fall through for "anything else" clause.
		} elseif ( $token === 'endtag' ) {
			switch ( $value ) {
				case 'table':
					if ( !$this->stack->inTableScope( $value ) ) {
						return true; // Ignore.
					}
					$this->stack->popTag( $value );
					$this->resetInsertionMode();
					return true;
				// OMITTED: <body>
				case 'caption':
				case 'col':
				case 'colgroup':
				// OMITTED: <html>
				case 'tbody':
				case 'td':
				case 'tfoot':
				case 'th':
				case 'thead':
				case 'tr':
					return true; // Ignore the token.
				case 'template':
					return $this->inHeadMode( $token, $value, $attribs, $selfClose );
			}
			// Fall through for "anything else" clause.
		} elseif ( $token === 'comment' ) {
			$this->stack->insertComment( $value );
			return true;
		}
		// This is the "anything else" case:
		$this->stack->fosterParentMode = true;
		$this->inBodyMode( $token, $value, $attribs, $selfClose );
		$this->stack->fosterParentMode = false;
		return true;
	}

	private function inTableTextMode( $token, $value, $attribs = null, $selfClose = false ) {
		if ( $token === 'text' ) {
			$this->pendingTableText .= $value;
			return true;
		}
		// Non-text token:
		$text = $this->pendingTableText;
		$this->pendingTableText = '';
		if ( preg_match( '/[^\x09\x0A\x0C\x0D\x20]/', $text ) ) {
			// This should match the "anything else" case inTableMode
			$this->stack->fosterParentMode = true;
			$this->inBodyMode( 'text', $text );
			$this->stack->fosterParentMode = false;
		} else {
			// Pending text is just whitespace.
			$this->stack->insertText( $text );
		}
		return $this->switchModeAndReprocess(
			$this->originalInsertionMode, $token, $value, $attribs, $selfClose
		);
	}

	// helper for inCaptionMode
	private function endCaption() {
		if ( !$this->stack->inTableScope( 'caption' ) ) {
			return false;
		}
		$this->stack->generateImpliedEndTags();
		$this->stack->popTag( 'caption' );
		$this->afe->clearToMarker();
		$this->switchMode( 'inTableMode' );
		return true;
	}

	private function inCaptionMode( $token, $value, $attribs = null, $selfClose = false ) {
		if ( $token === 'tag' ) {
			switch ( $value ) {
				case 'caption':
				case 'col':
				case 'colgroup':
				case 'tbody':
				case 'td':
				case 'tfoot':
				case 'th':
				case 'thead':
				case 'tr':
					if ( $this->endCaption() ) {
						$this->insertToken( $token, $value, $attribs, $selfClose );
					}
					return true;
			}
			// Fall through to "anything else" case.
		} elseif ( $token === 'endtag' ) {
			switch ( $value ) {
				case 'caption':
					$this->endCaption();
					return true;
				case 'table':
					if ( $this->endCaption() ) {
						$this->insertToken( $token, $value, $attribs, $selfClose );
					}
					return true;
				case 'body':
				case 'col':
				case 'colgroup':
				// OMITTED: <html>
				case 'tbody':
				case 'td':
				case 'tfoot':
				case 'th':
				case 'thead':
				case 'tr':
					// Ignore the token
					return true;
			}
			// Fall through to "anything else" case.
		}
		// The Anything Else case
		return $this->inBodyMode( $token, $value, $attribs, $selfClose );
	}

	private function inColumnGroupMode( $token, $value, $attribs = null, $selfClose = false ) {
		if ( $token === 'text' ) {
			if ( preg_match( '/^[\x09\x0A\x0C\x0D\x20]+/', $value, $matches ) ) {
				$this->stack->insertText( $matches[0] );
				$value = substr( $value, strlen( $matches[0] ) );
			}
			if ( strlen( $value ) === 0 ) {
				return true; // All text handled.
			}
			// Fall through to handle non-whitespace below.
		} elseif ( $token === 'tag' ) {
			switch ( $value ) {
				// OMITTED: <html>
				case 'col':
					$this->stack->insertHTMLElement( $value, $attribs );
					$this->stack->pop();
					return true;
				case 'template':
					return $this->inHeadMode( $token, $value, $attribs, $selfClose );
			}
			// Fall through for "anything else".
		} elseif ( $token === 'endtag' ) {
			switch ( $value ) {
				case 'colgroup':
					if ( !$this->stack->currentNode->isHtmlNamed( 'colgroup' ) ) {
						return true; // Ignore the token.
					}
					$this->stack->pop();
					$this->switchMode( 'inTableMode' );
					return true;
				case 'col':
					return true; // Ignore the token.
				case 'template':
					return $this->inHeadMode( $token, $value, $attribs, $selfClose );
			}
			// Fall through for "anything else".
		} elseif ( $token === 'eof' ) {
			return $this->inBodyMode( $token, $value, $attribs, $selfClose );
		} elseif ( $token === 'comment' ) {
			$this->stack->insertComment( $value );
			return true;
		}

		// Anything else
		if ( !$this->stack->currentNode->isHtmlNamed( 'colgroup' ) ) {
			return true; // Ignore the token.
		}
		$this->inColumnGroupMode( 'endtag', 'colgroup' );
		return $this->insertToken( $token, $value, $attribs, $selfClose );
	}

	// Helper function for inTableBodyMode
	private function endSection() {
		if ( !(
			$this->stack->inTableScope( 'tbody' ) ||
			$this->stack->inTableScope( 'thead' ) ||
			$this->stack->inTableScope( 'tfoot' )
		) ) {
			return false;
		}
		$this->stack->clearToContext( BalanceSets::$tableBodyContextSet );
		$this->stack->pop();
		$this->switchMode( 'inTableMode' );
		return true;
	}
	private function inTableBodyMode( $token, $value, $attribs = null, $selfClose = false ) {
		if ( $token === 'tag' ) {
			switch ( $value ) {
				case 'tr':
					$this->stack->clearToContext( BalanceSets::$tableBodyContextSet );
					$this->stack->insertHTMLElement( $value, $attribs );
					$this->switchMode( 'inRowMode' );
					return true;
				case 'th':
				case 'td':
					$this->inTableBodyMode( 'tag', 'tr', [] );
					$this->insertToken( $token, $value, $attribs, $selfClose );
					return true;
				case 'caption':
				case 'col':
				case 'colgroup':
				case 'tbody':
				case 'tfoot':
				case 'thead':
					if ( $this->endSection() ) {
						$this->insertToken( $token, $value, $attribs, $selfClose );
					}
					return true;
			}
		} elseif ( $token === 'endtag' ) {
			switch ( $value ) {
				case 'table':
					if ( $this->endSection() ) {
						$this->insertToken( $token, $value, $attribs, $selfClose );
					}
					return true;
				case 'tbody':
				case 'tfoot':
				case 'thead':
					if ( $this->stack->inTableScope( $value ) ) {
						$this->endSection();
					}
					return true;
				// OMITTED: <body>
				case 'caption':
				case 'col':
				case 'colgroup':
				// OMITTED: <html>
				case 'td':
				case 'th':
				case 'tr':
					return true; // Ignore the token.
			}
		}
		// Anything else:
		return $this->inTableMode( $token, $value, $attribs, $selfClose );
	}

	// Helper function for inRowMode
	private function endRow() {
		if ( !$this->stack->inTableScope( 'tr' ) ) {
			return false;
		}
		$this->stack->clearToContext( BalanceSets::$tableRowContextSet );
		$this->stack->pop();
		$this->switchMode( 'inTableBodyMode' );
		return true;
	}
	private function inRowMode( $token, $value, $attribs = null, $selfClose = false ) {
		if ( $token === 'tag' ) {
			switch ( $value ) {
				case 'th':
				case 'td':
					$this->stack->clearToContext( BalanceSets::$tableRowContextSet );
					$this->stack->insertHTMLElement( $value, $attribs );
					$this->switchMode( 'inCellMode' );
					$this->afe->insertMarker();
					return true;
				case 'caption':
				case 'col':
				case 'colgroup':
				case 'tbody':
				case 'tfoot':
				case 'thead':
				case 'tr':
					if ( $this->endRow() ) {
						$this->insertToken( $token, $value, $attribs, $selfClose );
					}
					return true;
			}
		} elseif ( $token === 'endtag' ) {
			switch ( $value ) {
				case 'tr':
					$this->endRow();
					return true;
				case 'table':
					if ( $this->endRow() ) {
						$this->insertToken( $token, $value, $attribs, $selfClose );
					}
					return true;
				case 'tbody':
				case 'tfoot':
				case 'thead':
					if (
						$this->stack->inTableScope( $value ) &&
						$this->endRow()
					) {
						$this->insertToken( $token, $value, $attribs, $selfClose );
					}
					return true;
				// OMITTED: <body>
				case 'caption':
				case 'col':
				case 'colgroup':
				// OMITTED: <html>
				case 'td':
				case 'th':
					return true; // Ignore the token.
			}
		}
		// Anything else:
		return $this->inTableMode( $token, $value, $attribs, $selfClose );
	}

	// Helper for inCellMode
	private function endCell() {
		if ( $this->stack->inTableScope( 'td' ) ) {
			$this->inCellMode( 'endtag', 'td' );
			return true;
		} elseif ( $this->stack->inTableScope( 'th' ) ) {
			$this->inCellMode( 'endtag', 'th' );
			return true;
		} else {
			return false;
		}
	}
	private function inCellMode( $token, $value, $attribs = null, $selfClose = false ) {
		if ( $token === 'tag' ) {
			switch ( $value ) {
				case 'caption':
				case 'col':
				case 'colgroup':
				case 'tbody':
				case 'td':
				case 'tfoot':
				case 'th':
				case 'thead':
				case 'tr':
					if ( $this->endCell() ) {
						$this->insertToken( $token, $value, $attribs, $selfClose );
					}
					return true;
			}
		} elseif ( $token === 'endtag' ) {
			switch ( $value ) {
				case 'td':
				case 'th':
					if ( $this->stack->inTableScope( $value ) ) {
						$this->stack->generateImpliedEndTags();
						$this->stack->popTag( $value );
						$this->afe->clearToMarker();
						$this->switchMode( 'inRowMode' );
					}
					return true;
				// OMITTED: <body>
				case 'caption':
				case 'col':
				case 'colgroup':
				// OMITTED: <html>
					return true;

				case 'table':
				case 'tbody':
				case 'tfoot':
				case 'thead':
				case 'tr':
					if ( $this->stack->inTableScope( $value ) ) {
						$this->stack->generateImpliedEndTags();
						$this->stack->popTag( BalanceSets::$tableCellSet );
						$this->afe->clearToMarker();
						$this->switchMode( 'inRowMode' );
						$this->insertToken( $token, $value, $attribs, $selfClose );
					}
					return true;
			}
		}
		// Anything else:
		return $this->inBodyMode( $token, $value, $attribs, $selfClose );
	}

	private function inSelectMode( $token, $value, $attribs = null, $selfClose = false ) {
		if ( $token === 'text' ) {
			$this->stack->insertText( $value );
			return true;
		} elseif ( $token === 'eof' ) {
			return $this->inBodyMode( $token, $value, $attribs, $selfClose );
		} elseif ( $token === 'tag' ) {
			switch ( $value ) {
				// OMITTED: <html>
				case 'option':
					if ( $this->stack->currentNode->isHtmlNamed( 'option' ) ) {
						$this->stack->pop();
					}
					$this->stack->insertHTMLElement( $value, $attribs );
					return true;
				case 'optgroup':
					if ( $this->stack->currentNode->isHtmlNamed( 'option' ) ) {
						$this->stack->pop();
					}
					if ( $this->stack->currentNode->isHtmlNamed( 'optgroup' ) ) {
						$this->stack->pop();
					}
					$this->stack->insertHTMLElement( $value, $attribs );
					return true;
				case 'select':
					$this->inSelectMode( 'endtag', $value ); // treat it like endtag
					return true;
				case 'input':
				case 'keygen':
				case 'textarea':
					if ( !$this->stack->inSelectScope( 'select' ) ) {
						return true; // ignore token (fragment case)
					}
					$this->inSelectMode( 'endtag', 'select' );
					return $this->insertToken( $token, $value, $attribs, $selfClose );
				case 'script':
				case 'template':
					return $this->inHeadMode( $token, $value, $attribs, $selfClose );
			}
		} elseif ( $token === 'endtag' ) {
			switch ( $value ) {
				case 'optgroup':
					if (
						$this->stack->currentNode->isHtmlNamed( 'option' ) &&
						$this->stack->length() >= 2 &&
						$this->stack->node( $this->stack->length() - 2 )->isHtmlNamed( 'optgroup' )
					) {
						$this->stack->pop();
					}
					if ( $this->stack->currentNode->isHtmlNamed( 'optgroup' ) ) {
						$this->stack->pop();
					}
					return true;
				case 'option':
					if ( $this->stack->currentNode->isHtmlNamed( 'option' ) ) {
						$this->stack->pop();
					}
					return true;
				case 'select':
					if ( !$this->stack->inSelectScope( $value ) ) {
						return true; // fragment case
					}
					$this->stack->popTag( $value );
					$this->resetInsertionMode();
					return true;
				case 'template':
					return $this->inHeadMode( $token, $value, $attribs, $selfClose );
			}
		} elseif ( $token === 'comment' ) {
			$this->stack->insertComment( $value );
			return true;
		}
		// anything else: just ignore the token
		return true;
	}

	private function inSelectInTableMode( $token, $value, $attribs = null, $selfClose = false ) {
		switch ( $value ) {
			case 'caption':
			case 'table':
			case 'tbody':
			case 'tfoot':
			case 'thead':
			case 'tr':
			case 'td':
			case 'th':
				if ( $token === 'tag' ) {
					$this->inSelectInTableMode( 'endtag', 'select' );
					return $this->insertToken( $token, $value, $attribs, $selfClose );
				} elseif ( $token === 'endtag' ) {
					if ( $this->stack->inTableScope( $value ) ) {
						$this->inSelectInTableMode( 'endtag', 'select' );
						return $this->insertToken( $token, $value, $attribs, $selfClose );
					}
					return true;
				}
		}
		// anything else
		return $this->inSelectMode( $token, $value, $attribs, $selfClose );
	}

	private function inTemplateMode( $token, $value, $attribs = null, $selfClose = false ) {
		if ( $token === 'text' || $token === 'comment' ) {
			return $this->inBodyMode( $token, $value, $attribs, $selfClose );
		} elseif ( $token === 'eof' ) {
			if ( $this->stack->indexOf( 'template' ) < 0 ) {
				$this->stopParsing();
			} else {
				$this->stack->popTag( 'template' );
				$this->afe->clearToMarker();
				array_pop( $this->templateInsertionModes );
				$this->resetInsertionMode();
				$this->insertToken( $token, $value, $attribs, $selfClose );
			}
			return true;
		} elseif ( $token === 'tag' ) {
			switch ( $value ) {
				case 'base':
				case 'basefont':
				case 'bgsound':
				case 'link':
				case 'meta':
				case 'noframes':
				// OMITTED: <script>
				case 'style':
				case 'template':
				// OMITTED: <title>
					return $this->inHeadMode( $token, $value, $attribs, $selfClose );

				case 'caption':
				case 'colgroup':
				case 'tbody':
				case 'tfoot':
				case 'thead':
					return $this->switchModeAndReprocess(
						'inTableMode', $token, $value, $attribs, $selfClose
					);

				case 'col':
					return $this->switchModeAndReprocess(
						'inColumnGroupMode', $token, $value, $attribs, $selfClose
					);

				case 'tr':
					return $this->switchModeAndReprocess(
						'inTableBodyMode', $token, $value, $attribs, $selfClose
					);

				case 'td':
				case 'th':
					return $this->switchModeAndReprocess(
						'inRowMode', $token, $value, $attribs, $selfClose
					);
			}
			return $this->switchModeAndReprocess(
				'inBodyMode', $token, $value, $attribs, $selfClose
			);
		} elseif ( $token === 'endtag' ) {
			switch ( $value ) {
				case 'template':
					return $this->inHeadMode( $token, $value, $attribs, $selfClose );
			}
			return true;
		} else {
			Assert::invariant( false, "Bad token type: $token" );
		}
	}
}