summaryrefslogtreecommitdiff
path: root/libs/litehtml/src/gumbo/tokenizer.c
blob: 71b5d32ad48b1c354203160571997220e1dee827 (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
// Copyright 2010 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Author: jdtang@google.com (Jonathan Tang)
//
// Coding conventions specific to this file:
//
// 1. Functions that fill in a token should be named emit_*, and should be
// followed immediately by a return from the tokenizer (true if no error
// occurred, false if an error occurred).  Sometimes the emit functions
// themselves return a boolean so that they can be combined with the return
// statement; in this case, they should match this convention.
// 2. Functions that shuffle data from temporaries to final API structures
// should be named finish_*, and be called just before the tokenizer exits the
// state that accumulates the temporary.
// 3. All internal data structures should be kept in an initialized state from
// tokenizer creation onwards, ready to accept input.  When a buffer's flushed
// and reset, it should be deallocated and immediately reinitialized.
// 4. Make sure there are appropriate break statements following each state.
// 5. Assertions on the state of the temporary and tag buffers are usually a
// good idea, and should go at the entry point of each state when added.
// 6. Statement order within states goes:
//    1. Add parse errors, if appropriate.
//    2. Call finish_* functions to build up tag state.
//    2. Switch to new state.  Set _reconsume flag if appropriate.
//    3. Perform any other temporary buffer manipulation.
//    4. Emit tokens
//    5. Return/break.
// This order ensures that we can verify that every emit is followed by a
// return, ensures that the correct state is recorded with any parse errors, and
// prevents parse error position from being messed up by possible mark/resets in
// temporary buffer manipulation.

#include "tokenizer.h"

#include <assert.h>
#include <stdbool.h>
#include <string.h>

#include "attribute.h"
#include "char_ref.h"
#include "error.h"
#include "gumbo.h"
#include "parser.h"
#include "string_buffer.h"
#include "string_piece.h"
#include "token_type.h"
#include "tokenizer_states.h"
#include "utf8.h"
#include "util.h"
#include "vector.h"

// Compared against _script_data_buffer to determine if we're in double-escaped
// script mode.
const GumboStringPiece kScriptTag = {"script", 6};

// An enum for the return value of each individual state.
typedef enum {
  RETURN_ERROR,    // Return false (error) from the tokenizer.
  RETURN_SUCCESS,  // Return true (success) from the tokenizer.
  NEXT_CHAR        // Proceed to the next character and continue lexing.
} StateResult;

// This is a struct containing state necessary to build up a tag token,
// character by character.
typedef struct GumboInternalTagState {
  // A buffer to accumulate characters for various GumboStringPiece fields.
  GumboStringBuffer _buffer;

  // A pointer to the start of the original text corresponding to the contents
  // of the buffer.
  const char* _original_text;

  // The current tag enum, computed once the tag name state has finished so that
  // the buffer can be re-used for building up attributes.
  GumboTag _tag;

  // The starting location of the text in the buffer.
  GumboSourcePosition _start_pos;

  // The current list of attributes.  This is copied (and ownership of its data
  // transferred) to the GumboStartTag token upon completion of the tag.  New
  // attributes are added as soon as their attribute name state is complete, and
  // values are filled in by operating on _attributes.data[attributes.length-1].
  GumboVector /* GumboAttribute */ _attributes;

  // If true, the next attribute value to be finished should be dropped.  This
  // happens if a duplicate attribute name is encountered - we want to consume
  // the attribute value, but shouldn't overwrite the existing value.
  bool _drop_next_attr_value;

  // The state that caused the tokenizer to switch into a character reference in
  // attribute value state.  This is used to set the additional allowed
  // character, and is switched back to on completion.  Initialized as the
  // tokenizer enters the character reference state.
  GumboTokenizerEnum _attr_value_state;

  // The last start tag to have been emitted by the tokenizer.  This is
  // necessary to check for appropriate end tags.
  GumboTag _last_start_tag;

  // If true, then this is a start tag.  If false, it's an end tag.  This is
  // necessary to generate the appropriate token type at tag-closing time.
  bool _is_start_tag;

  // If true, then this tag is "self-closing" and doesn't have an end tag.
  bool _is_self_closing;
} GumboTagState;

// This is the main tokenizer state struct, containing all state used by in
// tokenizing the input stream.
typedef struct GumboInternalTokenizerState {
  // The current lexer state.  Starts in GUMBO_LEX_DATA.
  GumboTokenizerEnum _state;

  // A flag indicating whether the current input character needs to reconsumed
  // in another state, or whether the next input character should be read for
  // the next iteration of the state loop.  This is set when the spec reads
  // "Reconsume the current input character in..."
  bool _reconsume_current_input;

  // A flag indicating whether the current node is a foreign element.  This is
  // set by gumbo_tokenizer_set_is_current_node_foreign and checked in the
  // markup declaration state.
  bool _is_current_node_foreign;

  // A flag indicating whether the tokenizer is in a CDATA section.  If so, then
  // text tokens emitted will be GUMBO_TOKEN_CDATA.
  bool _is_in_cdata;

  // Certain states (notably character references) may emit two character tokens
  // at once, but the contract for lex() fills in only one token at a time.  The
  // extra character is buffered here, and then this is checked on entry to
  // lex().  If a character is stored here, it's immediately emitted and control
  // returns from the lexer.  kGumboNoChar is used to represent 'no character
  // stored.'
  //
  // Note that characters emitted through this mechanism will have their source
  // position marked as the character under the mark, i.e. multiple characters
  // may be emitted with the same position.  This is desirable for character
  // references, but unsuitable for many other cases.  Use the _temporary_buffer
  // mechanism if the buffered characters must have their original positions in
  // the document.
  int _buffered_emit_char;

  // A temporary buffer to accumulate characters, as described by the "temporary
  // buffer" phrase in the tokenizer spec.  We use this in a somewhat unorthodox
  // way: we record the specific character to go into the buffer, which may
  // sometimes be a lowercased version of the actual input character.  However,
  // we *also* use utf8iterator_mark() to record the position at tag start.
  // When we start flushing the temporary buffer, we set _temporary_buffer_emit
  // to the start of it, and then increment it for each call to the tokenizer.
  // We also call utf8iterator_reset(), and utf8iterator_next() through the
  // input stream, so that tokens emitted by emit_char have the correct position
  // and original text.
  GumboStringBuffer _temporary_buffer;

  // The current cursor position we're emitting from within
  // _temporary_buffer.data.  NULL whenever we're not flushing the buffer.
  const char* _temporary_buffer_emit;

  // The temporary buffer is also used by the spec to check whether we should
  // enter the script data double escaped state, but we can't use the same
  // buffer for both because we have to flush out "<s" as emits while still
  // maintaining the context that will eventually become "script".  This is a
  // separate buffer that's used in place of the temporary buffer for states
  // that may enter the script data double escape start state.
  GumboStringBuffer _script_data_buffer;

  // Pointer to the beginning of the current token in the original buffer; used
  // to record the original text.
  const char* _token_start;

  // GumboSourcePosition recording the source location of the start of the
  // current token.
  GumboSourcePosition _token_start_pos;

  // Current tag state.
  GumboTagState _tag_state;

  // Doctype state.  We use the temporary buffer to accumulate characters (it's
  // not used for anything else in the doctype states), and then freshly
  // allocate the strings in the doctype token, then copy it over on emit.
  GumboTokenDocType _doc_type_state;

  // The UTF8Iterator over the tokenizer input.
  Utf8Iterator _input;
} GumboTokenizerState;

// Adds an ERR_UNEXPECTED_CODE_POINT parse error to the parser's error struct.
static void tokenizer_add_parse_error(
    GumboParser* parser, GumboErrorType type) {
  GumboError* error = gumbo_add_error(parser);
  if (!error) {
    return;
  }
  GumboTokenizerState* tokenizer = parser->_tokenizer_state;
  utf8iterator_get_position(&tokenizer->_input, &error->position);
  error->original_text = utf8iterator_get_char_pointer(&tokenizer->_input);
  error->type = type;
  error->v.tokenizer.codepoint = utf8iterator_current(&tokenizer->_input);
  switch (tokenizer->_state) {
    case GUMBO_LEX_DATA:
      error->v.tokenizer.state = GUMBO_ERR_TOKENIZER_DATA;
      break;
    case GUMBO_LEX_CHAR_REF_IN_DATA:
    case GUMBO_LEX_CHAR_REF_IN_RCDATA:
    case GUMBO_LEX_CHAR_REF_IN_ATTR_VALUE:
      error->v.tokenizer.state = GUMBO_ERR_TOKENIZER_CHAR_REF;
      break;
    case GUMBO_LEX_RCDATA:
    case GUMBO_LEX_RCDATA_LT:
    case GUMBO_LEX_RCDATA_END_TAG_OPEN:
    case GUMBO_LEX_RCDATA_END_TAG_NAME:
      error->v.tokenizer.state = GUMBO_ERR_TOKENIZER_RCDATA;
      break;
    case GUMBO_LEX_RAWTEXT:
    case GUMBO_LEX_RAWTEXT_LT:
    case GUMBO_LEX_RAWTEXT_END_TAG_OPEN:
    case GUMBO_LEX_RAWTEXT_END_TAG_NAME:
      error->v.tokenizer.state = GUMBO_ERR_TOKENIZER_RAWTEXT;
      break;
    case GUMBO_LEX_PLAINTEXT:
      error->v.tokenizer.state = GUMBO_ERR_TOKENIZER_PLAINTEXT;
      break;
    case GUMBO_LEX_SCRIPT:
    case GUMBO_LEX_SCRIPT_LT:
    case GUMBO_LEX_SCRIPT_END_TAG_OPEN:
    case GUMBO_LEX_SCRIPT_END_TAG_NAME:
    case GUMBO_LEX_SCRIPT_ESCAPED_START:
    case GUMBO_LEX_SCRIPT_ESCAPED_START_DASH:
    case GUMBO_LEX_SCRIPT_ESCAPED:
    case GUMBO_LEX_SCRIPT_ESCAPED_DASH:
    case GUMBO_LEX_SCRIPT_ESCAPED_DASH_DASH:
    case GUMBO_LEX_SCRIPT_ESCAPED_LT:
    case GUMBO_LEX_SCRIPT_ESCAPED_END_TAG_OPEN:
    case GUMBO_LEX_SCRIPT_ESCAPED_END_TAG_NAME:
    case GUMBO_LEX_SCRIPT_DOUBLE_ESCAPED_START:
    case GUMBO_LEX_SCRIPT_DOUBLE_ESCAPED:
    case GUMBO_LEX_SCRIPT_DOUBLE_ESCAPED_DASH:
    case GUMBO_LEX_SCRIPT_DOUBLE_ESCAPED_DASH_DASH:
    case GUMBO_LEX_SCRIPT_DOUBLE_ESCAPED_LT:
    case GUMBO_LEX_SCRIPT_DOUBLE_ESCAPED_END:
      error->v.tokenizer.state = GUMBO_ERR_TOKENIZER_SCRIPT;
      break;
    case GUMBO_LEX_TAG_OPEN:
    case GUMBO_LEX_END_TAG_OPEN:
    case GUMBO_LEX_TAG_NAME:
    case GUMBO_LEX_BEFORE_ATTR_NAME:
      error->v.tokenizer.state = GUMBO_ERR_TOKENIZER_TAG;
      break;
    case GUMBO_LEX_SELF_CLOSING_START_TAG:
      error->v.tokenizer.state = GUMBO_ERR_TOKENIZER_SELF_CLOSING_TAG;
      break;
    case GUMBO_LEX_ATTR_NAME:
    case GUMBO_LEX_AFTER_ATTR_NAME:
    case GUMBO_LEX_BEFORE_ATTR_VALUE:
      error->v.tokenizer.state = GUMBO_ERR_TOKENIZER_ATTR_NAME;
      break;
    case GUMBO_LEX_ATTR_VALUE_DOUBLE_QUOTED:
    case GUMBO_LEX_ATTR_VALUE_SINGLE_QUOTED:
    case GUMBO_LEX_ATTR_VALUE_UNQUOTED:
    case GUMBO_LEX_AFTER_ATTR_VALUE_QUOTED:
      error->v.tokenizer.state = GUMBO_ERR_TOKENIZER_ATTR_VALUE;
      break;
    case GUMBO_LEX_BOGUS_COMMENT:
    case GUMBO_LEX_COMMENT_START:
    case GUMBO_LEX_COMMENT_START_DASH:
    case GUMBO_LEX_COMMENT:
    case GUMBO_LEX_COMMENT_END_DASH:
    case GUMBO_LEX_COMMENT_END:
    case GUMBO_LEX_COMMENT_END_BANG:
      error->v.tokenizer.state = GUMBO_ERR_TOKENIZER_COMMENT;
      break;
    case GUMBO_LEX_MARKUP_DECLARATION:
    case GUMBO_LEX_DOCTYPE:
    case GUMBO_LEX_BEFORE_DOCTYPE_NAME:
    case GUMBO_LEX_DOCTYPE_NAME:
    case GUMBO_LEX_AFTER_DOCTYPE_NAME:
    case GUMBO_LEX_AFTER_DOCTYPE_PUBLIC_KEYWORD:
    case GUMBO_LEX_BEFORE_DOCTYPE_PUBLIC_ID:
    case GUMBO_LEX_DOCTYPE_PUBLIC_ID_DOUBLE_QUOTED:
    case GUMBO_LEX_DOCTYPE_PUBLIC_ID_SINGLE_QUOTED:
    case GUMBO_LEX_AFTER_DOCTYPE_PUBLIC_ID:
    case GUMBO_LEX_BETWEEN_DOCTYPE_PUBLIC_SYSTEM_ID:
    case GUMBO_LEX_AFTER_DOCTYPE_SYSTEM_KEYWORD:
    case GUMBO_LEX_BEFORE_DOCTYPE_SYSTEM_ID:
    case GUMBO_LEX_DOCTYPE_SYSTEM_ID_DOUBLE_QUOTED:
    case GUMBO_LEX_DOCTYPE_SYSTEM_ID_SINGLE_QUOTED:
    case GUMBO_LEX_AFTER_DOCTYPE_SYSTEM_ID:
    case GUMBO_LEX_BOGUS_DOCTYPE:
      error->v.tokenizer.state = GUMBO_ERR_TOKENIZER_DOCTYPE;
      break;
    case GUMBO_LEX_CDATA:
      error->v.tokenizer.state = GUMBO_ERR_TOKENIZER_CDATA;
      break;
  }
}

static bool is_alpha(int c) {
  // We don't use ISO C isupper/islower functions here because they
  // depend upon the program's locale, while the behavior of the HTML5 spec is
  // independent of which locale the program is run in.
  return (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z');
}

static int ensure_lowercase(int c) {
  return c >= 'A' && c <= 'Z' ? c + 0x20 : c;
}

static GumboTokenType get_char_token_type(bool is_in_cdata, int c) {
  if (is_in_cdata && c > 0) {
    return GUMBO_TOKEN_CDATA;
  }

  switch (c) {
    case '\t':
    case '\n':
    case '\r':
    case '\f':
    case ' ':
      return GUMBO_TOKEN_WHITESPACE;
    case 0:
      gumbo_debug("Emitted null byte.\n");
      return GUMBO_TOKEN_NULL;
    case -1:
      return GUMBO_TOKEN_EOF;
    default:
      return GUMBO_TOKEN_CHARACTER;
  }
}

// Starts recording characters in the temporary buffer.
// Because this needs to reset the utf8iterator_mark to the beginning of the
// text that will eventually be emitted, it needs to be called a couple of
// states before the spec says "Set the temporary buffer to the empty string".
// In general, this should be called whenever there's a transition to a
// "less-than sign state".  The initial < and possibly / then need to be
// appended to the temporary buffer, their presence needs to be accounted for in
// states that compare the temporary buffer against a literal value, and
// spec stanzas that say "emit a < and / character token along with a character
// token for each character in the temporary buffer" need to be adjusted to
// account for the presence of the < and / inside the temporary buffer.
static void clear_temporary_buffer(GumboParser* parser) {
  GumboTokenizerState* tokenizer = parser->_tokenizer_state;
  assert(!tokenizer->_temporary_buffer_emit);
  utf8iterator_mark(&tokenizer->_input);
  gumbo_string_buffer_clear(parser, &tokenizer->_temporary_buffer);
  // The temporary buffer and script data buffer are the same object in the
  // spec, so the script data buffer should be cleared as well.
  gumbo_string_buffer_clear(parser, &tokenizer->_script_data_buffer);
}

// Appends a codepoint to the temporary buffer.
static void append_char_to_temporary_buffer(
    GumboParser* parser, int codepoint) {
  gumbo_string_buffer_append_codepoint(
      parser, codepoint, &parser->_tokenizer_state->_temporary_buffer);
}

// Checks to see if the temporary buffer equals a certain string.
// Make sure this remains side-effect free; it's used in assertions.
#ifndef NDEBUG
static bool temporary_buffer_equals(GumboParser* parser, const char* text) {
  GumboStringBuffer* buffer = &parser->_tokenizer_state->_temporary_buffer;
  // TODO(jdtang): See if the extra strlen is a performance problem, and replace
  // it with an explicit sizeof(literal) if necessary.  I don't think it will
  // be, as this is only used in a couple of rare states.
  int text_len = strlen(text);
  return text_len == buffer->length &&
         memcmp(buffer->data, text, text_len) == 0;
}
#endif

static void doc_type_state_init(GumboParser* parser) {
  GumboTokenDocType* doc_type_state =
      &parser->_tokenizer_state->_doc_type_state;
  // We initialize these to NULL here so that we don't end up leaking memory if
  // we never see a doctype token.  When we do see a doctype token, we reset
  // them to a freshly-allocated empty string so that we can present a uniform
  // interface to client code and not make them check for null.  Ownership is
  // transferred to the doctype token when it's emitted.
  doc_type_state->name = NULL;
  doc_type_state->public_identifier = NULL;
  doc_type_state->system_identifier = NULL;
  doc_type_state->force_quirks = false;
  doc_type_state->has_public_identifier = false;
  doc_type_state->has_system_identifier = false;
}

// Sets the token original_text and position to the current iterator position.
// This is necessary because [CDATA[ sections may include text that is ignored
// by the tokenizer.
static void reset_token_start_point(GumboTokenizerState* tokenizer) {
  tokenizer->_token_start = utf8iterator_get_char_pointer(&tokenizer->_input);
  utf8iterator_get_position(&tokenizer->_input, &tokenizer->_token_start_pos);
}

// Sets the tag buffer original text and start point to the current iterator
// position.  This is necessary because attribute names & values may have
// whitespace preceeding them, and so we can't assume that the actual token
// starting point was the end of the last tag buffer usage.
static void reset_tag_buffer_start_point(GumboParser* parser) {
  GumboTokenizerState* tokenizer = parser->_tokenizer_state;
  GumboTagState* tag_state = &tokenizer->_tag_state;

  utf8iterator_get_position(&tokenizer->_input, &tag_state->_start_pos);
  tag_state->_original_text = utf8iterator_get_char_pointer(&tokenizer->_input);
}

// Moves the temporary buffer contents over to the specified output string,
// and clears the temporary buffer.
static void finish_temporary_buffer(GumboParser* parser, const char** output) {
  GumboTokenizerState* tokenizer = parser->_tokenizer_state;
  *output =
      gumbo_string_buffer_to_string(parser, &tokenizer->_temporary_buffer);
  clear_temporary_buffer(parser);
}

// Advances the iterator past the end of the token, and then fills in the
// relevant position fields.  It's assumed that after every emit, the tokenizer
// will immediately return (letting the tree-construction stage read the filled
// in Token).  Thus, it's safe to advance the input stream here, since it will
// bypass the advance at the bottom of the state machine loop.
//
// Since this advances the iterator and resets the current input, make sure to
// call it after you've recorded any other data you need for the token.
static void finish_token(GumboParser* parser, GumboToken* token) {
  GumboTokenizerState* tokenizer = parser->_tokenizer_state;
  if (!tokenizer->_reconsume_current_input) {
    utf8iterator_next(&tokenizer->_input);
  }

  token->position = tokenizer->_token_start_pos;
  token->original_text.data = tokenizer->_token_start;
  reset_token_start_point(tokenizer);
  token->original_text.length =
      tokenizer->_token_start - token->original_text.data;
  if (token->original_text.length > 0 &&
      token->original_text.data[token->original_text.length - 1] == '\r') {
    // The UTF8 iterator will ignore carriage returns in the input stream, which
    // means that the next token may start one past a \r character.  The pointer
    // arithmetic above results in that \r being appended to the original text
    // of the preceding token, so we have to adjust its length here to chop the
    // \r off.
    --token->original_text.length;
  }
}

// Records the doctype public ID, assumed to be in the temporary buffer.
// Convenience method that also sets has_public_identifier to true.
static void finish_doctype_public_id(GumboParser* parser) {
  GumboTokenDocType* doc_type_state =
      &parser->_tokenizer_state->_doc_type_state;
  gumbo_parser_deallocate(parser, (void*) doc_type_state->public_identifier);
  finish_temporary_buffer(parser, &doc_type_state->public_identifier);
  doc_type_state->has_public_identifier = true;
}

// Records the doctype system ID, assumed to be in the temporary buffer.
// Convenience method that also sets has_system_identifier to true.
static void finish_doctype_system_id(GumboParser* parser) {
  GumboTokenDocType* doc_type_state =
      &parser->_tokenizer_state->_doc_type_state;
  gumbo_parser_deallocate(parser, (void*) doc_type_state->system_identifier);
  finish_temporary_buffer(parser, &doc_type_state->system_identifier);
  doc_type_state->has_system_identifier = true;
}

// Writes a single specified character to the output token.
static void emit_char(GumboParser* parser, int c, GumboToken* output) {
  output->type = get_char_token_type(parser->_tokenizer_state->_is_in_cdata, c);
  output->v.character = c;
  finish_token(parser, output);
}

// Writes a replacement character token and records a parse error.
// Always returns RETURN_ERROR, per gumbo_lex return value.
static StateResult emit_replacement_char(
    GumboParser* parser, GumboToken* output) {
  // In all cases, this is because of a null byte in the input stream.
  tokenizer_add_parse_error(parser, GUMBO_ERR_UTF8_NULL);
  emit_char(parser, kUtf8ReplacementChar, output);
  return RETURN_ERROR;
}

// Writes an EOF character token.  Always returns RETURN_SUCCESS.
static StateResult emit_eof(GumboParser* parser, GumboToken* output) {
  emit_char(parser, -1, output);
  return RETURN_SUCCESS;
}

// Writes the current input character out as a character token.
// Always returns RETURN_SUCCESS.
static bool emit_current_char(GumboParser* parser, GumboToken* output) {
  emit_char(
      parser, utf8iterator_current(&parser->_tokenizer_state->_input), output);
  return RETURN_SUCCESS;
}

// Writes out a doctype token, copying it from the tokenizer state.
static void emit_doctype(GumboParser* parser, GumboToken* output) {
  output->type = GUMBO_TOKEN_DOCTYPE;
  output->v.doc_type = parser->_tokenizer_state->_doc_type_state;
  finish_token(parser, output);
  doc_type_state_init(parser);
}

// Debug-only function that explicitly sets the attribute vector data to NULL so
// it can be asserted on tag creation, verifying that there are no memory leaks.
static void mark_tag_state_as_empty(GumboTagState* tag_state) {
#ifndef NDEBUG
  tag_state->_attributes = kGumboEmptyVector;
#endif
}

// Writes out the current tag as a start or end tag token.
// Always returns RETURN_SUCCESS.
static StateResult emit_current_tag(GumboParser* parser, GumboToken* output) {
  GumboTagState* tag_state = &parser->_tokenizer_state->_tag_state;
  if (tag_state->_is_start_tag) {
    output->type = GUMBO_TOKEN_START_TAG;
    output->v.start_tag.tag = tag_state->_tag;
    output->v.start_tag.attributes = tag_state->_attributes;
    output->v.start_tag.is_self_closing = tag_state->_is_self_closing;
    tag_state->_last_start_tag = tag_state->_tag;
    mark_tag_state_as_empty(tag_state);
    gumbo_debug(
        "Emitted start tag %s.\n", gumbo_normalized_tagname(tag_state->_tag));
  } else {
    output->type = GUMBO_TOKEN_END_TAG;
    output->v.end_tag = tag_state->_tag;
    // In end tags, ownership of the attributes vector is not transferred to the
    // token, but it's still initialized as normal, so it must be manually
    // deallocated.  There may also be attributes to destroy, in certain broken
    // cases like </div</th> (the "th" is an attribute there).
    for (unsigned int i = 0; i < tag_state->_attributes.length; ++i) {
      gumbo_destroy_attribute(parser, tag_state->_attributes.data[i]);
    }
    gumbo_parser_deallocate(parser, tag_state->_attributes.data);
    mark_tag_state_as_empty(tag_state);
    gumbo_debug(
        "Emitted end tag %s.\n", gumbo_normalized_tagname(tag_state->_tag));
  }
  gumbo_string_buffer_destroy(parser, &tag_state->_buffer);
  finish_token(parser, output);
  gumbo_debug("Original text = %.*s.\n", output->original_text.length,
      output->original_text.data);
  assert(output->original_text.length >= 2);
  assert(output->original_text.data[0] == '<');
  assert(output->original_text.data[output->original_text.length - 1] == '>');
  return RETURN_SUCCESS;
}

// In some states, we speculatively start a tag, but don't know whether it'll be
// emitted as tag token or as a series of character tokens until we finish it.
// We need to abandon the tag we'd started & free its memory in that case to
// avoid a memory leak.
static void abandon_current_tag(GumboParser* parser) {
  GumboTagState* tag_state = &parser->_tokenizer_state->_tag_state;
  for (unsigned int i = 0; i < tag_state->_attributes.length; ++i) {
    gumbo_destroy_attribute(parser, tag_state->_attributes.data[i]);
  }
  gumbo_parser_deallocate(parser, tag_state->_attributes.data);
  mark_tag_state_as_empty(tag_state);
  gumbo_string_buffer_destroy(parser, &tag_state->_buffer);
  gumbo_debug("Abandoning current tag.\n");
}

// Wraps the consume_char_ref function to handle its output and make the
// appropriate TokenizerState modifications.  Returns RETURN_ERROR if a parse
// error occurred, RETURN_SUCCESS otherwise.
static StateResult emit_char_ref(GumboParser* parser,
    int additional_allowed_char, bool is_in_attribute, GumboToken* output) {
  GumboTokenizerState* tokenizer = parser->_tokenizer_state;
  OneOrTwoCodepoints char_ref;
  bool status = consume_char_ref(
      parser, &tokenizer->_input, additional_allowed_char, false, &char_ref);
  if (char_ref.first != kGumboNoChar) {
    // consume_char_ref ends with the iterator pointing at the next character,
    // so we need to be sure not advance it again before reading the next token.
    tokenizer->_reconsume_current_input = true;
    emit_char(parser, char_ref.first, output);
    tokenizer->_buffered_emit_char = char_ref.second;
  } else {
    emit_char(parser, '&', output);
  }
  return status ? RETURN_SUCCESS : RETURN_ERROR;
}

// Emits a comment token.  Comments use the temporary buffer to accumulate their
// data, and then it's copied over and released to the 'text' field of the
// GumboToken union.  Always returns RETURN_SUCCESS.
static StateResult emit_comment(GumboParser* parser, GumboToken* output) {
  output->type = GUMBO_TOKEN_COMMENT;
  finish_temporary_buffer(parser, &output->v.text);
  finish_token(parser, output);
  return RETURN_SUCCESS;
}

// Checks to see we should be flushing accumulated characters in the temporary
// buffer, and fills the output token with the next output character if so.
// Returns true if a character has been emitted and the tokenizer should
// immediately return, false if we're at the end of the temporary buffer and
// should resume normal operation.
static bool maybe_emit_from_temporary_buffer(
    GumboParser* parser, GumboToken* output) {
  GumboTokenizerState* tokenizer = parser->_tokenizer_state;
  const char* c = tokenizer->_temporary_buffer_emit;
  GumboStringBuffer* buffer = &tokenizer->_temporary_buffer;

  if (!c || c >= buffer->data + buffer->length) {
    tokenizer->_temporary_buffer_emit = NULL;
    return false;
  }

  assert(*c == utf8iterator_current(&tokenizer->_input));
  // emit_char also advances the input stream.  We need to do some juggling of
  // the _reconsume_current_input flag to get the proper behavior when emitting
  // previous tokens.  Basically, _reconsume_current_input should *never* be set
  // when emitting anything from the temporary buffer, since those characters
  // have already been advanced past.  However, it should be preserved so that
  // when the *next* character is encountered again, the tokenizer knows not to
  // advance past it.
  bool saved_reconsume_state = tokenizer->_reconsume_current_input;
  tokenizer->_reconsume_current_input = false;
  emit_char(parser, *c, output);
  ++tokenizer->_temporary_buffer_emit;
  tokenizer->_reconsume_current_input = saved_reconsume_state;
  return true;
}

// Sets up the tokenizer to begin flushing the temporary buffer.
// This resets the input iterator stream to the start of the last tag, sets up
// _temporary_buffer_emit, and then (if the temporary buffer is non-empty) emits
// the first character in it.  It returns true if a character was emitted, false
// otherwise.
static bool emit_temporary_buffer(GumboParser* parser, GumboToken* output) {
  GumboTokenizerState* tokenizer = parser->_tokenizer_state;
  assert(tokenizer->_temporary_buffer.data);
  utf8iterator_reset(&tokenizer->_input);
  tokenizer->_temporary_buffer_emit = tokenizer->_temporary_buffer.data;
  return maybe_emit_from_temporary_buffer(parser, output);
}

// Appends a codepoint to the current tag buffer.  If
// reinitilize_position_on_first is set, this also initializes the tag buffer
// start point; the only time you would *not* want to pass true for this
// parameter is if you want the original_text to include character (like an
// opening quote) that doesn't appear in the value.
static void append_char_to_tag_buffer(
    GumboParser* parser, int codepoint, bool reinitilize_position_on_first) {
  GumboStringBuffer* buffer = &parser->_tokenizer_state->_tag_state._buffer;
  if (buffer->length == 0 && reinitilize_position_on_first) {
    reset_tag_buffer_start_point(parser);
  }
  gumbo_string_buffer_append_codepoint(parser, codepoint, buffer);
}

// (Re-)initialize the tag buffer.  This also resets the original_text pointer
// and _start_pos field to point to the current position.
static void initialize_tag_buffer(GumboParser* parser) {
  GumboTokenizerState* tokenizer = parser->_tokenizer_state;
  GumboTagState* tag_state = &tokenizer->_tag_state;

  gumbo_string_buffer_init(parser, &tag_state->_buffer);
  reset_tag_buffer_start_point(parser);
}

// Initializes the tag_state to start a new tag, keeping track of the opening
// positions and original text.  Takes a boolean indicating whether this is a
// start or end tag.
static void start_new_tag(GumboParser* parser, bool is_start_tag) {
  GumboTokenizerState* tokenizer = parser->_tokenizer_state;
  GumboTagState* tag_state = &tokenizer->_tag_state;
  int c = utf8iterator_current(&tokenizer->_input);
  assert(is_alpha(c));
  c = ensure_lowercase(c);
  assert(is_alpha(c));

  initialize_tag_buffer(parser);
  gumbo_string_buffer_append_codepoint(parser, c, &tag_state->_buffer);

  assert(tag_state->_attributes.data == NULL);
  // Initial size chosen by statistical analysis of a corpus of 60k webpages.
  // 99.5% of elements have 0 attributes, 93% of the remainder have 1.  These
  // numbers are a bit higher for more modern websites (eg. ~45% = 0, ~40% = 1
  // for the HTML5 Spec), but still have basically 99% of nodes with <= 2 attrs.
  gumbo_vector_init(parser, 1, &tag_state->_attributes);
  tag_state->_drop_next_attr_value = false;
  tag_state->_is_start_tag = is_start_tag;
  tag_state->_is_self_closing = false;
  gumbo_debug("Starting new tag.\n");
}

// Fills in the specified char* with the contents of the tag buffer.
static void copy_over_tag_buffer(GumboParser* parser, const char** output) {
  GumboTokenizerState* tokenizer = parser->_tokenizer_state;
  GumboTagState* tag_state = &tokenizer->_tag_state;
  *output = gumbo_string_buffer_to_string(parser, &tag_state->_buffer);
}

// Fills in:
// * The original_text GumboStringPiece with the portion of the original
// buffer that corresponds to the tag buffer.
// * The start_pos GumboSourcePosition with the start position of the tag
// buffer.
// * The end_pos GumboSourcePosition with the current source position.
static void copy_over_original_tag_text(GumboParser* parser,
    GumboStringPiece* original_text, GumboSourcePosition* start_pos,
    GumboSourcePosition* end_pos) {
  GumboTokenizerState* tokenizer = parser->_tokenizer_state;
  GumboTagState* tag_state = &tokenizer->_tag_state;

  original_text->data = tag_state->_original_text;
  original_text->length = utf8iterator_get_char_pointer(&tokenizer->_input) -
                          tag_state->_original_text;
  if (original_text->length > 0
      && original_text->data[original_text->length - 1] == '\r') {
    // Since \r is skipped by the UTF-8 iterator, it can sometimes end up
    // appended to the end of original text even when it's really the first part
    // of the next character.  If we detect this situation, shrink the length of
    // the original text by 1 to remove the carriage return.
    --original_text->length;
  }
  *start_pos = tag_state->_start_pos;
  utf8iterator_get_position(&tokenizer->_input, end_pos);
}

// Releases and then re-initializes the tag buffer.
static void reinitialize_tag_buffer(GumboParser* parser) {
  gumbo_parser_deallocate(
      parser, parser->_tokenizer_state->_tag_state._buffer.data);
  initialize_tag_buffer(parser);
}

// Moves some data from the temporary buffer over the the tag-based fields in
// TagState.
static void finish_tag_name(GumboParser* parser) {
  GumboTokenizerState* tokenizer = parser->_tokenizer_state;
  GumboTagState* tag_state = &tokenizer->_tag_state;

  tag_state->_tag =
      gumbo_tagn_enum(tag_state->_buffer.data, tag_state->_buffer.length);
  reinitialize_tag_buffer(parser);
}

// Adds an ERR_DUPLICATE_ATTR parse error to the parser's error struct.
static void add_duplicate_attr_error(GumboParser* parser, const char* attr_name,
    int original_index, int new_index) {
  GumboError* error = gumbo_add_error(parser);
  if (!error) {
    return;
  }
  GumboTagState* tag_state = &parser->_tokenizer_state->_tag_state;
  error->type = GUMBO_ERR_DUPLICATE_ATTR;
  error->position = tag_state->_start_pos;
  error->original_text = tag_state->_original_text;
  error->v.duplicate_attr.original_index = original_index;
  error->v.duplicate_attr.new_index = new_index;
  copy_over_tag_buffer(parser, &error->v.duplicate_attr.name);
  reinitialize_tag_buffer(parser);
}

// Creates a new attribute in the current tag, copying the current tag buffer to
// the attribute's name.  The attribute's value starts out as the empty string
// (following the "Boolean attributes" section of the spec) and is only
// overwritten on finish_attribute_value().  If the attribute has already been
// specified, the new attribute is dropped, a parse error is added, and the
// function returns false.  Otherwise, this returns true.
static bool finish_attribute_name(GumboParser* parser) {
  GumboTokenizerState* tokenizer = parser->_tokenizer_state;
  GumboTagState* tag_state = &tokenizer->_tag_state;
  // May've been set by a previous attribute without a value; reset it here.
  tag_state->_drop_next_attr_value = false;
  assert(tag_state->_attributes.data);
  assert(tag_state->_attributes.capacity);

  GumboVector* /* GumboAttribute* */ attributes = &tag_state->_attributes;
  for (unsigned int i = 0; i < attributes->length; ++i) {
    GumboAttribute* attr = attributes->data[i];
    if (strlen(attr->name) == tag_state->_buffer.length &&
        memcmp(attr->name, tag_state->_buffer.data,
            tag_state->_buffer.length) == 0) {
      // Identical attribute; bail.
      add_duplicate_attr_error(parser, attr->name, i, attributes->length);
      tag_state->_drop_next_attr_value = true;
      return false;
    }
  }

  GumboAttribute* attr = gumbo_parser_allocate(parser, sizeof(GumboAttribute));
  attr->attr_namespace = GUMBO_ATTR_NAMESPACE_NONE;
  copy_over_tag_buffer(parser, &attr->name);
  copy_over_original_tag_text(
      parser, &attr->original_name, &attr->name_start, &attr->name_end);
  attr->value = gumbo_copy_stringz(parser, "");
  copy_over_original_tag_text(
      parser, &attr->original_value, &attr->name_start, &attr->name_end);
  gumbo_vector_add(parser, attr, attributes);
  reinitialize_tag_buffer(parser);
  return true;
}

// Finishes an attribute value.  This sets the value of the most recently added
// attribute to the current contents of the tag buffer.
static void finish_attribute_value(GumboParser* parser) {
  GumboTagState* tag_state = &parser->_tokenizer_state->_tag_state;
  if (tag_state->_drop_next_attr_value) {
    // Duplicate attribute name detected in an earlier state, so we have to
    // ignore the value.
    tag_state->_drop_next_attr_value = false;
    reinitialize_tag_buffer(parser);
    return;
  }

  GumboAttribute* attr =
      tag_state->_attributes.data[tag_state->_attributes.length - 1];
  gumbo_parser_deallocate(parser, (void*) attr->value);
  copy_over_tag_buffer(parser, &attr->value);
  copy_over_original_tag_text(
      parser, &attr->original_value, &attr->value_start, &attr->value_end);
  reinitialize_tag_buffer(parser);
}

// Returns true if the current end tag matches the last start tag emitted.
static bool is_appropriate_end_tag(GumboParser* parser) {
  GumboTagState* tag_state = &parser->_tokenizer_state->_tag_state;
  assert(!tag_state->_is_start_tag);
  return tag_state->_last_start_tag != GUMBO_TAG_LAST &&
         tag_state->_last_start_tag == gumbo_tagn_enum(tag_state->_buffer.data,
                                           tag_state->_buffer.length);
}

void gumbo_tokenizer_state_init(
    GumboParser* parser, const char* text, size_t text_length) {
  GumboTokenizerState* tokenizer =
      gumbo_parser_allocate(parser, sizeof(GumboTokenizerState));
  parser->_tokenizer_state = tokenizer;
  gumbo_tokenizer_set_state(parser, GUMBO_LEX_DATA);
  tokenizer->_reconsume_current_input = false;
  tokenizer->_is_current_node_foreign = false;
  tokenizer->_is_in_cdata = false;
  tokenizer->_tag_state._last_start_tag = GUMBO_TAG_LAST;

  tokenizer->_buffered_emit_char = kGumboNoChar;
  gumbo_string_buffer_init(parser, &tokenizer->_temporary_buffer);
  tokenizer->_temporary_buffer_emit = NULL;

  mark_tag_state_as_empty(&tokenizer->_tag_state);

  gumbo_string_buffer_init(parser, &tokenizer->_script_data_buffer);
  tokenizer->_token_start = text;
  utf8iterator_init(parser, text, text_length, &tokenizer->_input);
  utf8iterator_get_position(&tokenizer->_input, &tokenizer->_token_start_pos);
  doc_type_state_init(parser);
}

void gumbo_tokenizer_state_destroy(GumboParser* parser) {
  GumboTokenizerState* tokenizer = parser->_tokenizer_state;
  assert(tokenizer->_doc_type_state.name == NULL);
  assert(tokenizer->_doc_type_state.public_identifier == NULL);
  assert(tokenizer->_doc_type_state.system_identifier == NULL);
  gumbo_string_buffer_destroy(parser, &tokenizer->_temporary_buffer);
  gumbo_string_buffer_destroy(parser, &tokenizer->_script_data_buffer);
  gumbo_parser_deallocate(parser, tokenizer);
}

void gumbo_tokenizer_set_state(GumboParser* parser, GumboTokenizerEnum state) {
  parser->_tokenizer_state->_state = state;
}

void gumbo_tokenizer_set_is_current_node_foreign(
    GumboParser* parser, bool is_foreign) {
  if (is_foreign != parser->_tokenizer_state->_is_current_node_foreign) {
    gumbo_debug("Toggling is_current_node_foreign to %s.\n",
        is_foreign ? "true" : "false");
  }
  parser->_tokenizer_state->_is_current_node_foreign = is_foreign;
}

// http://www.whatwg.org/specs/web-apps/current-work/complete5/tokenization.html#data-state
static StateResult handle_data_state(GumboParser* parser,
    GumboTokenizerState* tokenizer, int c, GumboToken* output) {
  switch (c) {
    case '&':
      gumbo_tokenizer_set_state(parser, GUMBO_LEX_CHAR_REF_IN_DATA);
      // The char_ref machinery expects to be on the & so it can mark that
      // and return to it if the text isn't a char ref, so we need to
      // reconsume it.
      tokenizer->_reconsume_current_input = true;
      return NEXT_CHAR;
    case '<':
      gumbo_tokenizer_set_state(parser, GUMBO_LEX_TAG_OPEN);
      clear_temporary_buffer(parser);
      append_char_to_temporary_buffer(parser, '<');
      return NEXT_CHAR;
    case '\0':
      tokenizer_add_parse_error(parser, GUMBO_ERR_UTF8_NULL);
      emit_char(parser, c, output);
      return RETURN_ERROR;
    default:
      return emit_current_char(parser, output);
  }
}

// http://www.whatwg.org/specs/web-apps/current-work/complete5/tokenization.html#character-reference-in-data-state
static StateResult handle_char_ref_in_data_state(GumboParser* parser,
    GumboTokenizerState* tokenizer, int c, GumboToken* output) {
  gumbo_tokenizer_set_state(parser, GUMBO_LEX_DATA);
  return emit_char_ref(parser, ' ', false, output);
}

// http://www.whatwg.org/specs/web-apps/current-work/complete5/tokenization.html#rcdata-state
static StateResult handle_rcdata_state(GumboParser* parser,
    GumboTokenizerState* tokenizer, int c, GumboToken* output) {
  switch (c) {
    case '&':
      gumbo_tokenizer_set_state(parser, GUMBO_LEX_CHAR_REF_IN_RCDATA);
      tokenizer->_reconsume_current_input = true;
      return NEXT_CHAR;
    case '<':
      gumbo_tokenizer_set_state(parser, GUMBO_LEX_RCDATA_LT);
      clear_temporary_buffer(parser);
      append_char_to_temporary_buffer(parser, '<');
      return NEXT_CHAR;
    case '\0':
      return emit_replacement_char(parser, output);
    case -1:
      return emit_eof(parser, output);
    default:
      return emit_current_char(parser, output);
  }
}

// http://www.whatwg.org/specs/web-apps/current-work/complete5/tokenization.html#character-reference-in-rcdata-state
static StateResult handle_char_ref_in_rcdata_state(GumboParser* parser,
    GumboTokenizerState* tokenizer, int c, GumboToken* output) {
  gumbo_tokenizer_set_state(parser, GUMBO_LEX_RCDATA);
  return emit_char_ref(parser, ' ', false, output);
}

// http://www.whatwg.org/specs/web-apps/current-work/complete5/tokenization.html#rawtext-state
static StateResult handle_rawtext_state(GumboParser* parser,
    GumboTokenizerState* tokenizer, int c, GumboToken* output) {
  switch (c) {
    case '<':
      gumbo_tokenizer_set_state(parser, GUMBO_LEX_RAWTEXT_LT);
      clear_temporary_buffer(parser);
      append_char_to_temporary_buffer(parser, '<');
      return NEXT_CHAR;
    case '\0':
      return emit_replacement_char(parser, output);
    case -1:
      return emit_eof(parser, output);
    default:
      return emit_current_char(parser, output);
  }
}

// http://www.whatwg.org/specs/web-apps/current-work/complete5/tokenization.html#script-data-state
static StateResult handle_script_state(GumboParser* parser,
    GumboTokenizerState* tokenizer, int c, GumboToken* output) {
  switch (c) {
    case '<':
      gumbo_tokenizer_set_state(parser, GUMBO_LEX_SCRIPT_LT);
      clear_temporary_buffer(parser);
      append_char_to_temporary_buffer(parser, '<');
      return NEXT_CHAR;
    case '\0':
      return emit_replacement_char(parser, output);
    case -1:
      return emit_eof(parser, output);
    default:
      return emit_current_char(parser, output);
  }
}

// http://www.whatwg.org/specs/web-apps/current-work/complete5/tokenization.html#plaintext-state
static StateResult handle_plaintext_state(GumboParser* parser,
    GumboTokenizerState* tokenizer, int c, GumboToken* output) {
  switch (c) {
    case '\0':
      return emit_replacement_char(parser, output);
    case -1:
      return emit_eof(parser, output);
    default:
      return emit_current_char(parser, output);
  }
}

// http://www.whatwg.org/specs/web-apps/current-work/complete5/tokenization.html#tag-open-state
static StateResult handle_tag_open_state(GumboParser* parser,
    GumboTokenizerState* tokenizer, int c, GumboToken* output) {
  assert(temporary_buffer_equals(parser, "<"));
  switch (c) {
    case '!':
      gumbo_tokenizer_set_state(parser, GUMBO_LEX_MARKUP_DECLARATION);
      clear_temporary_buffer(parser);
      return NEXT_CHAR;
    case '/':
      gumbo_tokenizer_set_state(parser, GUMBO_LEX_END_TAG_OPEN);
      append_char_to_temporary_buffer(parser, '/');
      return NEXT_CHAR;
    case '?':
      gumbo_tokenizer_set_state(parser, GUMBO_LEX_BOGUS_COMMENT);
      clear_temporary_buffer(parser);
      append_char_to_temporary_buffer(parser, '?');
      tokenizer_add_parse_error(parser, GUMBO_ERR_TAG_STARTS_WITH_QUESTION);
      return NEXT_CHAR;
    default:
      if (is_alpha(c)) {
        gumbo_tokenizer_set_state(parser, GUMBO_LEX_TAG_NAME);
        start_new_tag(parser, true);
        return NEXT_CHAR;
      } else {
        tokenizer_add_parse_error(parser, GUMBO_ERR_TAG_INVALID);
        gumbo_tokenizer_set_state(parser, GUMBO_LEX_DATA);
        emit_temporary_buffer(parser, output);
        return RETURN_ERROR;
      }
  }
}

// http://www.whatwg.org/specs/web-apps/current-work/complete5/tokenization.html#end-tag-open-state
static StateResult handle_end_tag_open_state(GumboParser* parser,
    GumboTokenizerState* tokenizer, int c, GumboToken* output) {
  assert(temporary_buffer_equals(parser, "</"));
  switch (c) {
    case '>':
      tokenizer_add_parse_error(parser, GUMBO_ERR_CLOSE_TAG_EMPTY);
      gumbo_tokenizer_set_state(parser, GUMBO_LEX_DATA);
      return NEXT_CHAR;
    case -1:
      tokenizer_add_parse_error(parser, GUMBO_ERR_CLOSE_TAG_EOF);
      gumbo_tokenizer_set_state(parser, GUMBO_LEX_DATA);
      return emit_temporary_buffer(parser, output);
    default:
      if (is_alpha(c)) {
        gumbo_tokenizer_set_state(parser, GUMBO_LEX_TAG_NAME);
        start_new_tag(parser, false);
      } else {
        tokenizer_add_parse_error(parser, GUMBO_ERR_CLOSE_TAG_INVALID);
        gumbo_tokenizer_set_state(parser, GUMBO_LEX_BOGUS_COMMENT);
        clear_temporary_buffer(parser);
        append_char_to_temporary_buffer(parser, c);
      }
      return NEXT_CHAR;
  }
}

// http://www.whatwg.org/specs/web-apps/current-work/complete5/tokenization.html#tag-name-state
static StateResult handle_tag_name_state(GumboParser* parser,
    GumboTokenizerState* tokenizer, int c, GumboToken* output) {
  switch (c) {
    case '\t':
    case '\n':
    case '\f':
    case ' ':
      finish_tag_name(parser);
      gumbo_tokenizer_set_state(parser, GUMBO_LEX_BEFORE_ATTR_NAME);
      return NEXT_CHAR;
    case '/':
      finish_tag_name(parser);
      gumbo_tokenizer_set_state(parser, GUMBO_LEX_SELF_CLOSING_START_TAG);
      return NEXT_CHAR;
    case '>':
      finish_tag_name(parser);
      gumbo_tokenizer_set_state(parser, GUMBO_LEX_DATA);
      return emit_current_tag(parser, output);
    case '\0':
      tokenizer_add_parse_error(parser, GUMBO_ERR_UTF8_NULL);
      append_char_to_tag_buffer(parser, kUtf8ReplacementChar, true);
      return NEXT_CHAR;
    case -1:
      tokenizer_add_parse_error(parser, GUMBO_ERR_TAG_EOF);
      abandon_current_tag(parser);
      gumbo_tokenizer_set_state(parser, GUMBO_LEX_DATA);
      return NEXT_CHAR;
    default:
      append_char_to_tag_buffer(parser, ensure_lowercase(c), true);
      return NEXT_CHAR;
  }
}

// http://www.whatwg.org/specs/web-apps/current-work/complete.html#rcdata-less-than-sign-state
static StateResult handle_rcdata_lt_state(GumboParser* parser,
    GumboTokenizerState* tokenizer, int c, GumboToken* output) {
  assert(temporary_buffer_equals(parser, "<"));
  if (c == '/') {
    gumbo_tokenizer_set_state(parser, GUMBO_LEX_RCDATA_END_TAG_OPEN);
    append_char_to_temporary_buffer(parser, '/');
    return NEXT_CHAR;
  } else {
    gumbo_tokenizer_set_state(parser, GUMBO_LEX_RCDATA);
    tokenizer->_reconsume_current_input = true;
    return emit_temporary_buffer(parser, output);
  }
}

// http://www.whatwg.org/specs/web-apps/current-work/complete.html#rcdata-end-tag-open-state
static StateResult handle_rcdata_end_tag_open_state(GumboParser* parser,
    GumboTokenizerState* tokenizer, int c, GumboToken* output) {
  assert(temporary_buffer_equals(parser, "</"));
  if (is_alpha(c)) {
    gumbo_tokenizer_set_state(parser, GUMBO_LEX_RCDATA_END_TAG_NAME);
    start_new_tag(parser, false);
    append_char_to_temporary_buffer(parser, c);
    return NEXT_CHAR;
  } else {
    gumbo_tokenizer_set_state(parser, GUMBO_LEX_RCDATA);
    return emit_temporary_buffer(parser, output);
  }
  return true;
}

// http://www.whatwg.org/specs/web-apps/current-work/complete.html#rcdata-end-tag-name-state
static StateResult handle_rcdata_end_tag_name_state(GumboParser* parser,
    GumboTokenizerState* tokenizer, int c, GumboToken* output) {
  assert(tokenizer->_temporary_buffer.length >= 2);
  if (is_alpha(c)) {
    append_char_to_tag_buffer(parser, ensure_lowercase(c), true);
    append_char_to_temporary_buffer(parser, c);
    return NEXT_CHAR;
  } else if (is_appropriate_end_tag(parser)) {
    switch (c) {
      case '\t':
      case '\n':
      case '\f':
      case ' ':
        finish_tag_name(parser);
        gumbo_tokenizer_set_state(parser, GUMBO_LEX_BEFORE_ATTR_NAME);
        return NEXT_CHAR;
      case '/':
        finish_tag_name(parser);
        gumbo_tokenizer_set_state(parser, GUMBO_LEX_SELF_CLOSING_START_TAG);
        return NEXT_CHAR;
      case '>':
        finish_tag_name(parser);
        gumbo_tokenizer_set_state(parser, GUMBO_LEX_DATA);
        return emit_current_tag(parser, output);
    }
  }
  gumbo_tokenizer_set_state(parser, GUMBO_LEX_RCDATA);
  abandon_current_tag(parser);
  return emit_temporary_buffer(parser, output);
}

// http://www.whatwg.org/specs/web-apps/current-work/complete5/tokenization.html#rawtext-less-than-sign-state
static StateResult handle_rawtext_lt_state(GumboParser* parser,
    GumboTokenizerState* tokenizer, int c, GumboToken* output) {
  assert(temporary_buffer_equals(parser, "<"));
  if (c == '/') {
    gumbo_tokenizer_set_state(parser, GUMBO_LEX_RAWTEXT_END_TAG_OPEN);
    append_char_to_temporary_buffer(parser, '/');
    return NEXT_CHAR;
  } else {
    gumbo_tokenizer_set_state(parser, GUMBO_LEX_RAWTEXT);
    tokenizer->_reconsume_current_input = true;
    return emit_temporary_buffer(parser, output);
  }
}

// http://www.whatwg.org/specs/web-apps/current-work/complete5/tokenization.html#rawtext-end-tag-open-state
static StateResult handle_rawtext_end_tag_open_state(GumboParser* parser,
    GumboTokenizerState* tokenizer, int c, GumboToken* output) {
  assert(temporary_buffer_equals(parser, "</"));
  if (is_alpha(c)) {
    gumbo_tokenizer_set_state(parser, GUMBO_LEX_RAWTEXT_END_TAG_NAME);
    start_new_tag(parser, false);
    append_char_to_temporary_buffer(parser, c);
    return NEXT_CHAR;
  } else {
    gumbo_tokenizer_set_state(parser, GUMBO_LEX_RAWTEXT);
    return emit_temporary_buffer(parser, output);
  }
}

// http://www.whatwg.org/specs/web-apps/current-work/complete5/tokenization.html#rawtext-end-tag-name-state
static StateResult handle_rawtext_end_tag_name_state(GumboParser* parser,
    GumboTokenizerState* tokenizer, int c, GumboToken* output) {
  assert(tokenizer->_temporary_buffer.length >= 2);
  gumbo_debug("Last end tag: %*s\n", (int) tokenizer->_tag_state._buffer.length,
      tokenizer->_tag_state._buffer.data);
  if (is_alpha(c)) {
    append_char_to_tag_buffer(parser, ensure_lowercase(c), true);
    append_char_to_temporary_buffer(parser, c);
    return NEXT_CHAR;
  } else if (is_appropriate_end_tag(parser)) {
    gumbo_debug("Is an appropriate end tag.\n");
    switch (c) {
      case '\t':
      case '\n':
      case '\f':
      case ' ':
        finish_tag_name(parser);
        gumbo_tokenizer_set_state(parser, GUMBO_LEX_BEFORE_ATTR_NAME);
        return NEXT_CHAR;
      case '/':
        finish_tag_name(parser);
        gumbo_tokenizer_set_state(parser, GUMBO_LEX_SELF_CLOSING_START_TAG);
        return NEXT_CHAR;
      case '>':
        finish_tag_name(parser);
        gumbo_tokenizer_set_state(parser, GUMBO_LEX_DATA);
        return emit_current_tag(parser, output);
    }
  }
  gumbo_tokenizer_set_state(parser, GUMBO_LEX_RAWTEXT);
  abandon_current_tag(parser);
  return emit_temporary_buffer(parser, output);
}

// http://www.whatwg.org/specs/web-apps/current-work/complete5/tokenization.html#script-data-less-than-sign-state
static StateResult handle_script_lt_state(GumboParser* parser,
    GumboTokenizerState* tokenizer, int c, GumboToken* output) {
  assert(temporary_buffer_equals(parser, "<"));
  if (c == '/') {
    gumbo_tokenizer_set_state(parser, GUMBO_LEX_SCRIPT_END_TAG_OPEN);
    append_char_to_temporary_buffer(parser, '/');
    return NEXT_CHAR;
  } else if (c == '!') {
    gumbo_tokenizer_set_state(parser, GUMBO_LEX_SCRIPT_ESCAPED_START);
    append_char_to_temporary_buffer(parser, '!');
    return emit_temporary_buffer(parser, output);
  } else {
    gumbo_tokenizer_set_state(parser, GUMBO_LEX_SCRIPT);
    tokenizer->_reconsume_current_input = true;
    return emit_temporary_buffer(parser, output);
  }
}

// http://www.whatwg.org/specs/web-apps/current-work/complete5/tokenization.html#script-data-end-tag-open-state
static StateResult handle_script_end_tag_open_state(GumboParser* parser,
    GumboTokenizerState* tokenizer, int c, GumboToken* output) {
  assert(temporary_buffer_equals(parser, "</"));
  if (is_alpha(c)) {
    gumbo_tokenizer_set_state(parser, GUMBO_LEX_SCRIPT_END_TAG_NAME);
    start_new_tag(parser, false);
    append_char_to_temporary_buffer(parser, c);
    return NEXT_CHAR;
  } else {
    gumbo_tokenizer_set_state(parser, GUMBO_LEX_SCRIPT);
    return emit_temporary_buffer(parser, output);
  }
}

// http://www.whatwg.org/specs/web-apps/current-work/complete5/tokenization.html#script-data-end-tag-name-state
static StateResult handle_script_end_tag_name_state(GumboParser* parser,
    GumboTokenizerState* tokenizer, int c, GumboToken* output) {
  assert(tokenizer->_temporary_buffer.length >= 2);
  if (is_alpha(c)) {
    append_char_to_tag_buffer(parser, ensure_lowercase(c), true);
    append_char_to_temporary_buffer(parser, c);
    return NEXT_CHAR;
  } else if (is_appropriate_end_tag(parser)) {
    switch (c) {
      case '\t':
      case '\n':
      case '\f':
      case ' ':
        finish_tag_name(parser);
        gumbo_tokenizer_set_state(parser, GUMBO_LEX_BEFORE_ATTR_NAME);
        return NEXT_CHAR;
      case '/':
        finish_tag_name(parser);
        gumbo_tokenizer_set_state(parser, GUMBO_LEX_SELF_CLOSING_START_TAG);
        return NEXT_CHAR;
      case '>':
        finish_tag_name(parser);
        gumbo_tokenizer_set_state(parser, GUMBO_LEX_DATA);
        return emit_current_tag(parser, output);
    }
  }
  gumbo_tokenizer_set_state(parser, GUMBO_LEX_SCRIPT);
  abandon_current_tag(parser);
  return emit_temporary_buffer(parser, output);
}

// http://www.whatwg.org/specs/web-apps/current-work/complete5/tokenization.html#script-data-escape-start-state
static StateResult handle_script_escaped_start_state(GumboParser* parser,
    GumboTokenizerState* tokenizer, int c, GumboToken* output) {
  if (c == '-') {
    gumbo_tokenizer_set_state(parser, GUMBO_LEX_SCRIPT_ESCAPED_START_DASH);
    return emit_current_char(parser, output);
  } else {
    gumbo_tokenizer_set_state(parser, GUMBO_LEX_SCRIPT);
    tokenizer->_reconsume_current_input = true;
    return NEXT_CHAR;
  }
}

// http://www.whatwg.org/specs/web-apps/current-work/complete5/tokenization.html#script-data-escape-start-dash-state
static StateResult handle_script_escaped_start_dash_state(GumboParser* parser,
    GumboTokenizerState* tokenizer, int c, GumboToken* output) {
  if (c == '-') {
    gumbo_tokenizer_set_state(parser, GUMBO_LEX_SCRIPT_ESCAPED_DASH_DASH);
    return emit_current_char(parser, output);
  } else {
    gumbo_tokenizer_set_state(parser, GUMBO_LEX_SCRIPT);
    tokenizer->_reconsume_current_input = true;
    return NEXT_CHAR;
  }
}

// http://www.whatwg.org/specs/web-apps/current-work/complete5/tokenization.html#script-data-escaped-state
static StateResult handle_script_escaped_state(GumboParser* parser,
    GumboTokenizerState* tokenizer, int c, GumboToken* output) {
  switch (c) {
    case '-':
      gumbo_tokenizer_set_state(parser, GUMBO_LEX_SCRIPT_ESCAPED_DASH);
      return emit_current_char(parser, output);
    case '<':
      gumbo_tokenizer_set_state(parser, GUMBO_LEX_SCRIPT_ESCAPED_LT);
      clear_temporary_buffer(parser);
      append_char_to_temporary_buffer(parser, c);
      return NEXT_CHAR;
    case '\0':
      return emit_replacement_char(parser, output);
    case -1:
      tokenizer_add_parse_error(parser, GUMBO_ERR_SCRIPT_EOF);
      return emit_eof(parser, output);
    default:
      return emit_current_char(parser, output);
  }
}

// http://www.whatwg.org/specs/web-apps/current-work/complete5/tokenization.html#script-data-escaped-dash-state
static StateResult handle_script_escaped_dash_state(GumboParser* parser,
    GumboTokenizerState* tokenizer, int c, GumboToken* output) {
  switch (c) {
    case '-':
      gumbo_tokenizer_set_state(parser, GUMBO_LEX_SCRIPT_ESCAPED_DASH_DASH);
      return emit_current_char(parser, output);
    case '<':
      gumbo_tokenizer_set_state(parser, GUMBO_LEX_SCRIPT_ESCAPED_LT);
      clear_temporary_buffer(parser);
      append_char_to_temporary_buffer(parser, c);
      return NEXT_CHAR;
    case '\0':
      gumbo_tokenizer_set_state(parser, GUMBO_LEX_SCRIPT_ESCAPED);
      return emit_replacement_char(parser, output);
    case -1:
      tokenizer_add_parse_error(parser, GUMBO_ERR_SCRIPT_EOF);
      gumbo_tokenizer_set_state(parser, GUMBO_LEX_DATA);
      return NEXT_CHAR;
    default:
      gumbo_tokenizer_set_state(parser, GUMBO_LEX_SCRIPT_ESCAPED);
      return emit_current_char(parser, output);
  }
}

// http://www.whatwg.org/specs/web-apps/current-work/complete5/tokenization.html#script-data-escaped-dash-dash-state
static StateResult handle_script_escaped_dash_dash_state(GumboParser* parser,
    GumboTokenizerState* tokenizer, int c, GumboToken* output) {
  switch (c) {
    case '-':
      return emit_current_char(parser, output);
    case '<':
      gumbo_tokenizer_set_state(parser, GUMBO_LEX_SCRIPT_ESCAPED_LT);
      clear_temporary_buffer(parser);
      append_char_to_temporary_buffer(parser, c);
      return NEXT_CHAR;
    case '>':
      gumbo_tokenizer_set_state(parser, GUMBO_LEX_SCRIPT);
      return emit_current_char(parser, output);
    case '\0':
      gumbo_tokenizer_set_state(parser, GUMBO_LEX_SCRIPT_ESCAPED);
      return emit_replacement_char(parser, output);
    case -1:
      tokenizer_add_parse_error(parser, GUMBO_ERR_SCRIPT_EOF);
      gumbo_tokenizer_set_state(parser, GUMBO_LEX_DATA);
      return NEXT_CHAR;
    default:
      gumbo_tokenizer_set_state(parser, GUMBO_LEX_SCRIPT_ESCAPED);
      return emit_current_char(parser, output);
  }
}

// http://www.whatwg.org/specs/web-apps/current-work/complete5/tokenization.html#script-data-escaped-less-than-sign-state
static StateResult handle_script_escaped_lt_state(GumboParser* parser,
    GumboTokenizerState* tokenizer, int c, GumboToken* output) {
  assert(temporary_buffer_equals(parser, "<"));
  assert(!tokenizer->_script_data_buffer.length);
  if (c == '/') {
    gumbo_tokenizer_set_state(parser, GUMBO_LEX_SCRIPT_ESCAPED_END_TAG_OPEN);
    append_char_to_temporary_buffer(parser, c);
    return NEXT_CHAR;
  } else if (is_alpha(c)) {
    gumbo_tokenizer_set_state(parser, GUMBO_LEX_SCRIPT_DOUBLE_ESCAPED_START);
    append_char_to_temporary_buffer(parser, c);
    gumbo_string_buffer_append_codepoint(
        parser, ensure_lowercase(c), &tokenizer->_script_data_buffer);
    return emit_temporary_buffer(parser, output);
  } else {
    gumbo_tokenizer_set_state(parser, GUMBO_LEX_SCRIPT_ESCAPED);
    return emit_temporary_buffer(parser, output);
  }
}

// http://www.whatwg.org/specs/web-apps/current-work/complete5/tokenization.html#script-data-escaped-end-tag-open-state
static StateResult handle_script_escaped_end_tag_open_state(GumboParser* parser,
    GumboTokenizerState* tokenizer, int c, GumboToken* output) {
  assert(temporary_buffer_equals(parser, "</"));
  if (is_alpha(c)) {
    gumbo_tokenizer_set_state(parser, GUMBO_LEX_SCRIPT_ESCAPED_END_TAG_NAME);
    start_new_tag(parser, false);
    append_char_to_temporary_buffer(parser, c);
    return NEXT_CHAR;
  } else {
    gumbo_tokenizer_set_state(parser, GUMBO_LEX_SCRIPT_ESCAPED);
    return emit_temporary_buffer(parser, output);
  }
}

// http://www.whatwg.org/specs/web-apps/current-work/complete5/tokenization.html#script-data-escaped-end-tag-name-state
static StateResult handle_script_escaped_end_tag_name_state(GumboParser* parser,
    GumboTokenizerState* tokenizer, int c, GumboToken* output) {
  assert(tokenizer->_temporary_buffer.length >= 2);
  if (is_alpha(c)) {
    append_char_to_tag_buffer(parser, ensure_lowercase(c), true);
    append_char_to_temporary_buffer(parser, c);
    return NEXT_CHAR;
  } else if (is_appropriate_end_tag(parser)) {
    switch (c) {
      case '\t':
      case '\n':
      case '\f':
      case ' ':
        finish_tag_name(parser);
        gumbo_tokenizer_set_state(parser, GUMBO_LEX_BEFORE_ATTR_NAME);
        return NEXT_CHAR;
      case '/':
        finish_tag_name(parser);
        gumbo_tokenizer_set_state(parser, GUMBO_LEX_SELF_CLOSING_START_TAG);
        return NEXT_CHAR;
      case '>':
        finish_tag_name(parser);
        gumbo_tokenizer_set_state(parser, GUMBO_LEX_DATA);
        return emit_current_tag(parser, output);
    }
  }
  gumbo_tokenizer_set_state(parser, GUMBO_LEX_SCRIPT_ESCAPED);
  abandon_current_tag(parser);
  return emit_temporary_buffer(parser, output);
}

// http://www.whatwg.org/specs/web-apps/current-work/complete5/tokenization.html#script-data-double-escape-start-state
static StateResult handle_script_double_escaped_start_state(GumboParser* parser,
    GumboTokenizerState* tokenizer, int c, GumboToken* output) {
  switch (c) {
    case '\t':
    case '\n':
    case '\f':
    case ' ':
    case '/':
    case '>':
      gumbo_tokenizer_set_state(
          parser, gumbo_string_equals(&kScriptTag,
                      (GumboStringPiece*) &tokenizer->_script_data_buffer)
                      ? GUMBO_LEX_SCRIPT_DOUBLE_ESCAPED
                      : GUMBO_LEX_SCRIPT_ESCAPED);
      return emit_current_char(parser, output);
    default:
      if (is_alpha(c)) {
        gumbo_string_buffer_append_codepoint(
            parser, ensure_lowercase(c), &tokenizer->_script_data_buffer);
        return emit_current_char(parser, output);
      } else {
        gumbo_tokenizer_set_state(parser, GUMBO_LEX_SCRIPT_ESCAPED);
        tokenizer->_reconsume_current_input = true;
        return NEXT_CHAR;
      }
  }
}

// http://www.whatwg.org/specs/web-apps/current-work/complete5/tokenization.html#script-data-double-escaped-state
static StateResult handle_script_double_escaped_state(GumboParser* parser,
    GumboTokenizerState* tokenizer, int c, GumboToken* output) {
  switch (c) {
    case '-':
      gumbo_tokenizer_set_state(parser, GUMBO_LEX_SCRIPT_DOUBLE_ESCAPED_DASH);
      return emit_current_char(parser, output);
    case '<':
      gumbo_tokenizer_set_state(parser, GUMBO_LEX_SCRIPT_DOUBLE_ESCAPED_LT);
      return emit_current_char(parser, output);
    case '\0':
      return emit_replacement_char(parser, output);
    case -1:
      tokenizer_add_parse_error(parser, GUMBO_ERR_SCRIPT_EOF);
      gumbo_tokenizer_set_state(parser, GUMBO_LEX_DATA);
      return NEXT_CHAR;
    default:
      return emit_current_char(parser, output);
  }
}

// http://www.whatwg.org/specs/web-apps/current-work/complete5/tokenization.html#script-data-double-escaped-dash-state
static StateResult handle_script_double_escaped_dash_state(GumboParser* parser,
    GumboTokenizerState* tokenizer, int c, GumboToken* output) {
  switch (c) {
    case '-':
      gumbo_tokenizer_set_state(
          parser, GUMBO_LEX_SCRIPT_DOUBLE_ESCAPED_DASH_DASH);
      return emit_current_char(parser, output);
    case '<':
      gumbo_tokenizer_set_state(parser, GUMBO_LEX_SCRIPT_DOUBLE_ESCAPED_LT);
      return emit_current_char(parser, output);
    case '\0':
      gumbo_tokenizer_set_state(parser, GUMBO_LEX_SCRIPT_DOUBLE_ESCAPED);
      return emit_replacement_char(parser, output);
    case -1:
      tokenizer_add_parse_error(parser, GUMBO_ERR_SCRIPT_EOF);
      gumbo_tokenizer_set_state(parser, GUMBO_LEX_DATA);
      return NEXT_CHAR;
    default:
      gumbo_tokenizer_set_state(parser, GUMBO_LEX_SCRIPT_DOUBLE_ESCAPED);
      return emit_current_char(parser, output);
  }
}

// http://www.whatwg.org/specs/web-apps/current-work/complete5/tokenization.html#script-data-double-escaped-dash-dash-state
static StateResult handle_script_double_escaped_dash_dash_state(
    GumboParser* parser, GumboTokenizerState* tokenizer, int c,
    GumboToken* output) {
  switch (c) {
    case '-':
      return emit_current_char(parser, output);
    case '<':
      gumbo_tokenizer_set_state(parser, GUMBO_LEX_SCRIPT_DOUBLE_ESCAPED_LT);
      return emit_current_char(parser, output);
    case '>':
      gumbo_tokenizer_set_state(parser, GUMBO_LEX_SCRIPT);
      return emit_current_char(parser, output);
    case '\0':
      gumbo_tokenizer_set_state(parser, GUMBO_LEX_SCRIPT_DOUBLE_ESCAPED);
      return emit_replacement_char(parser, output);
    case -1:
      tokenizer_add_parse_error(parser, GUMBO_ERR_SCRIPT_EOF);
      gumbo_tokenizer_set_state(parser, GUMBO_LEX_DATA);
      return NEXT_CHAR;
    default:
      gumbo_tokenizer_set_state(parser, GUMBO_LEX_SCRIPT_DOUBLE_ESCAPED);
      return emit_current_char(parser, output);
  }
}

// http://www.whatwg.org/specs/web-apps/current-work/complete5/tokenization.html#script-data-double-escaped-less-than-sign-state
static StateResult handle_script_double_escaped_lt_state(GumboParser* parser,
    GumboTokenizerState* tokenizer, int c, GumboToken* output) {
  if (c == '/') {
    gumbo_tokenizer_set_state(parser, GUMBO_LEX_SCRIPT_DOUBLE_ESCAPED_END);
    gumbo_string_buffer_clear(parser, &tokenizer->_script_data_buffer);
    return emit_current_char(parser, output);
  } else {
    gumbo_tokenizer_set_state(parser, GUMBO_LEX_SCRIPT_DOUBLE_ESCAPED);
    tokenizer->_reconsume_current_input = true;
    return NEXT_CHAR;
  }
}

// http://www.whatwg.org/specs/web-apps/current-work/complete5/tokenization.html#script-data-double-escape-end-state
static StateResult handle_script_double_escaped_end_state(GumboParser* parser,
    GumboTokenizerState* tokenizer, int c, GumboToken* output) {
  switch (c) {
    case '\t':
    case '\n':
    case '\f':
    case ' ':
    case '/':
    case '>':
      gumbo_tokenizer_set_state(
          parser, gumbo_string_equals(&kScriptTag,
                      (GumboStringPiece*) &tokenizer->_script_data_buffer)
                      ? GUMBO_LEX_SCRIPT_ESCAPED
                      : GUMBO_LEX_SCRIPT_DOUBLE_ESCAPED);
      return emit_current_char(parser, output);
    default:
      if (is_alpha(c)) {
        gumbo_string_buffer_append_codepoint(
            parser, ensure_lowercase(c), &tokenizer->_script_data_buffer);
        return emit_current_char(parser, output);
      } else {
        gumbo_tokenizer_set_state(parser, GUMBO_LEX_SCRIPT_DOUBLE_ESCAPED);
        tokenizer->_reconsume_current_input = true;
        return NEXT_CHAR;
      }
  }
}

// http://www.whatwg.org/specs/web-apps/current-work/complete5/tokenization.html#before-attribute-name-state
static StateResult handle_before_attr_name_state(GumboParser* parser,
    GumboTokenizerState* tokenizer, int c, GumboToken* output) {
  switch (c) {
    case '\t':
    case '\n':
    case '\f':
    case ' ':
      return NEXT_CHAR;
    case '/':
      gumbo_tokenizer_set_state(parser, GUMBO_LEX_SELF_CLOSING_START_TAG);
      return NEXT_CHAR;
    case '>':
      gumbo_tokenizer_set_state(parser, GUMBO_LEX_DATA);
      return emit_current_tag(parser, output);
    case '\0':
      tokenizer_add_parse_error(parser, GUMBO_ERR_UTF8_NULL);
      gumbo_tokenizer_set_state(parser, GUMBO_LEX_ATTR_NAME);
      append_char_to_temporary_buffer(parser, 0xfffd);
      return NEXT_CHAR;
    case -1:
      tokenizer_add_parse_error(parser, GUMBO_ERR_ATTR_NAME_EOF);
      gumbo_tokenizer_set_state(parser, GUMBO_LEX_DATA);
      abandon_current_tag(parser);
      return NEXT_CHAR;
    case '"':
    case '\'':
    case '<':
    case '=':
      tokenizer_add_parse_error(parser, GUMBO_ERR_ATTR_NAME_INVALID);
    // Fall through.
    default:
      gumbo_tokenizer_set_state(parser, GUMBO_LEX_ATTR_NAME);
      append_char_to_tag_buffer(parser, ensure_lowercase(c), true);
      return NEXT_CHAR;
  }
}

// http://www.whatwg.org/specs/web-apps/current-work/complete5/tokenization.html#attribute-name-state
static StateResult handle_attr_name_state(GumboParser* parser,
    GumboTokenizerState* tokenizer, int c, GumboToken* output) {
  switch (c) {
    case '\t':
    case '\n':
    case '\f':
    case ' ':
      finish_attribute_name(parser);
      gumbo_tokenizer_set_state(parser, GUMBO_LEX_AFTER_ATTR_NAME);
      return NEXT_CHAR;
    case '/':
      finish_attribute_name(parser);
      gumbo_tokenizer_set_state(parser, GUMBO_LEX_SELF_CLOSING_START_TAG);
      return NEXT_CHAR;
    case '=':
      finish_attribute_name(parser);
      gumbo_tokenizer_set_state(parser, GUMBO_LEX_BEFORE_ATTR_VALUE);
      return NEXT_CHAR;
    case '>':
      finish_attribute_name(parser);
      gumbo_tokenizer_set_state(parser, GUMBO_LEX_DATA);
      return emit_current_tag(parser, output);
    case '\0':
      tokenizer_add_parse_error(parser, GUMBO_ERR_UTF8_NULL);
      append_char_to_tag_buffer(parser, kUtf8ReplacementChar, true);
      return NEXT_CHAR;
    case -1:
      gumbo_tokenizer_set_state(parser, GUMBO_LEX_DATA);
      abandon_current_tag(parser);
      tokenizer_add_parse_error(parser, GUMBO_ERR_ATTR_NAME_EOF);
      return NEXT_CHAR;
    case '"':
    case '\'':
    case '<':
      tokenizer_add_parse_error(parser, GUMBO_ERR_ATTR_NAME_INVALID);
    // Fall through.
    default:
      append_char_to_tag_buffer(parser, ensure_lowercase(c), true);
      return NEXT_CHAR;
  }
}

// http://www.whatwg.org/specs/web-apps/current-work/complete5/tokenization.html#after-attribute-name-state
static StateResult handle_after_attr_name_state(GumboParser* parser,
    GumboTokenizerState* tokenizer, int c, GumboToken* output) {
  switch (c) {
    case '\t':
    case '\n':
    case '\f':
    case ' ':
      return NEXT_CHAR;
    case '/':
      gumbo_tokenizer_set_state(parser, GUMBO_LEX_SELF_CLOSING_START_TAG);
      return NEXT_CHAR;
    case '=':
      gumbo_tokenizer_set_state(parser, GUMBO_LEX_BEFORE_ATTR_VALUE);
      return NEXT_CHAR;
    case '>':
      gumbo_tokenizer_set_state(parser, GUMBO_LEX_DATA);
      return emit_current_tag(parser, output);
    case '\0':
      tokenizer_add_parse_error(parser, GUMBO_ERR_UTF8_NULL);
      gumbo_tokenizer_set_state(parser, GUMBO_LEX_ATTR_NAME);
      append_char_to_temporary_buffer(parser, 0xfffd);
      return NEXT_CHAR;
    case -1:
      tokenizer_add_parse_error(parser, GUMBO_ERR_ATTR_NAME_EOF);
      gumbo_tokenizer_set_state(parser, GUMBO_LEX_DATA);
      abandon_current_tag(parser);
      return NEXT_CHAR;
    case '"':
    case '\'':
    case '<':
      tokenizer_add_parse_error(parser, GUMBO_ERR_ATTR_NAME_INVALID);
    // Fall through.
    default:
      gumbo_tokenizer_set_state(parser, GUMBO_LEX_ATTR_NAME);
      append_char_to_tag_buffer(parser, ensure_lowercase(c), true);
      return NEXT_CHAR;
  }
}

// http://www.whatwg.org/specs/web-apps/current-work/complete5/tokenization.html#before-attribute-value-state
static StateResult handle_before_attr_value_state(GumboParser* parser,
    GumboTokenizerState* tokenizer, int c, GumboToken* output) {
  switch (c) {
    case '\t':
    case '\n':
    case '\f':
    case ' ':
      return NEXT_CHAR;
    case '"':
      gumbo_tokenizer_set_state(parser, GUMBO_LEX_ATTR_VALUE_DOUBLE_QUOTED);
      reset_tag_buffer_start_point(parser);
      return NEXT_CHAR;
    case '&':
      gumbo_tokenizer_set_state(parser, GUMBO_LEX_ATTR_VALUE_UNQUOTED);
      tokenizer->_reconsume_current_input = true;
      return NEXT_CHAR;
    case '\'':
      gumbo_tokenizer_set_state(parser, GUMBO_LEX_ATTR_VALUE_SINGLE_QUOTED);
      reset_tag_buffer_start_point(parser);
      return NEXT_CHAR;
    case '\0':
      tokenizer_add_parse_error(parser, GUMBO_ERR_UTF8_NULL);
      gumbo_tokenizer_set_state(parser, GUMBO_LEX_ATTR_VALUE_UNQUOTED);
      append_char_to_tag_buffer(parser, kUtf8ReplacementChar, true);
      return NEXT_CHAR;
    case -1:
      tokenizer_add_parse_error(parser, GUMBO_ERR_ATTR_UNQUOTED_EOF);
      gumbo_tokenizer_set_state(parser, GUMBO_LEX_DATA);
      abandon_current_tag(parser);
      tokenizer->_reconsume_current_input = true;
      return NEXT_CHAR;
    case '>':
      tokenizer_add_parse_error(parser, GUMBO_ERR_ATTR_UNQUOTED_RIGHT_BRACKET);
      gumbo_tokenizer_set_state(parser, GUMBO_LEX_DATA);
      emit_current_tag(parser, output);
      return RETURN_ERROR;
    case '<':
    case '=':
    case '`':
      tokenizer_add_parse_error(parser, GUMBO_ERR_ATTR_UNQUOTED_EQUALS);
    // Fall through.
    default:
      gumbo_tokenizer_set_state(parser, GUMBO_LEX_ATTR_VALUE_UNQUOTED);
      append_char_to_tag_buffer(parser, c, true);
      return NEXT_CHAR;
  }
}

// http://www.whatwg.org/specs/web-apps/current-work/complete5/tokenization.html#attribute-value-double-quoted-state
static StateResult handle_attr_value_double_quoted_state(GumboParser* parser,
    GumboTokenizerState* tokenizer, int c, GumboToken* output) {
  switch (c) {
    case '"':
      gumbo_tokenizer_set_state(parser, GUMBO_LEX_AFTER_ATTR_VALUE_QUOTED);
      return NEXT_CHAR;
    case '&':
      tokenizer->_tag_state._attr_value_state = tokenizer->_state;
      gumbo_tokenizer_set_state(parser, GUMBO_LEX_CHAR_REF_IN_ATTR_VALUE);
      tokenizer->_reconsume_current_input = true;
      return NEXT_CHAR;
    case '\0':
      tokenizer_add_parse_error(parser, GUMBO_ERR_UTF8_NULL);
      append_char_to_tag_buffer(parser, kUtf8ReplacementChar, false);
      return NEXT_CHAR;
    case -1:
      tokenizer_add_parse_error(parser, GUMBO_ERR_ATTR_DOUBLE_QUOTE_EOF);
      gumbo_tokenizer_set_state(parser, GUMBO_LEX_DATA);
      abandon_current_tag(parser);
      tokenizer->_reconsume_current_input = true;
      return NEXT_CHAR;
    default:
      append_char_to_tag_buffer(parser, c, false);
      return NEXT_CHAR;
  }
}

// http://www.whatwg.org/specs/web-apps/current-work/complete5/tokenization.html#attribute-value-single-quoted-state
static StateResult handle_attr_value_single_quoted_state(GumboParser* parser,
    GumboTokenizerState* tokenizer, int c, GumboToken* output) {
  switch (c) {
    case '\'':
      gumbo_tokenizer_set_state(parser, GUMBO_LEX_AFTER_ATTR_VALUE_QUOTED);
      return NEXT_CHAR;
    case '&':
      tokenizer->_tag_state._attr_value_state = tokenizer->_state;
      gumbo_tokenizer_set_state(parser, GUMBO_LEX_CHAR_REF_IN_ATTR_VALUE);
      tokenizer->_reconsume_current_input = true;
      return NEXT_CHAR;
    case '\0':
      tokenizer_add_parse_error(parser, GUMBO_ERR_UTF8_NULL);
      append_char_to_tag_buffer(parser, kUtf8ReplacementChar, false);
      return NEXT_CHAR;
    case -1:
      tokenizer_add_parse_error(parser, GUMBO_ERR_ATTR_SINGLE_QUOTE_EOF);
      gumbo_tokenizer_set_state(parser, GUMBO_LEX_DATA);
      abandon_current_tag(parser);
      tokenizer->_reconsume_current_input = true;
      return NEXT_CHAR;
    default:
      append_char_to_tag_buffer(parser, c, false);
      return NEXT_CHAR;
  }
}

// http://www.whatwg.org/specs/web-apps/current-work/complete5/tokenization.html#attribute-value-unquoted-state
static StateResult handle_attr_value_unquoted_state(GumboParser* parser,
    GumboTokenizerState* tokenizer, int c, GumboToken* output) {
  switch (c) {
    case '\t':
    case '\n':
    case '\f':
    case ' ':
      gumbo_tokenizer_set_state(parser, GUMBO_LEX_BEFORE_ATTR_NAME);
      finish_attribute_value(parser);
      return NEXT_CHAR;
    case '&':
      tokenizer->_tag_state._attr_value_state = tokenizer->_state;
      gumbo_tokenizer_set_state(parser, GUMBO_LEX_CHAR_REF_IN_ATTR_VALUE);
      tokenizer->_reconsume_current_input = true;
      return NEXT_CHAR;
    case '>':
      gumbo_tokenizer_set_state(parser, GUMBO_LEX_DATA);
      finish_attribute_value(parser);
      return emit_current_tag(parser, output);
    case '\0':
      tokenizer_add_parse_error(parser, GUMBO_ERR_UTF8_NULL);
      append_char_to_tag_buffer(parser, kUtf8ReplacementChar, true);
      return NEXT_CHAR;
    case -1:
      tokenizer_add_parse_error(parser, GUMBO_ERR_ATTR_UNQUOTED_EOF);
      gumbo_tokenizer_set_state(parser, GUMBO_LEX_DATA);
      tokenizer->_reconsume_current_input = true;
      abandon_current_tag(parser);
      return NEXT_CHAR;
    case '<':
    case '=':
    case '"':
    case '\'':
    case '`':
      tokenizer_add_parse_error(parser, GUMBO_ERR_ATTR_UNQUOTED_EQUALS);
    // Fall through.
    default:
      append_char_to_tag_buffer(parser, c, true);
      return NEXT_CHAR;
  }
}

// http://www.whatwg.org/specs/web-apps/current-work/complete5/tokenization.html#character-reference-in-attribute-value-state
static StateResult handle_char_ref_in_attr_value_state(GumboParser* parser,
    GumboTokenizerState* tokenizer, int c, GumboToken* output) {
  OneOrTwoCodepoints char_ref;
  int allowed_char;
  bool is_unquoted = false;
  switch (tokenizer->_tag_state._attr_value_state) {
    case GUMBO_LEX_ATTR_VALUE_DOUBLE_QUOTED:
      allowed_char = '"';
      break;
    case GUMBO_LEX_ATTR_VALUE_SINGLE_QUOTED:
      allowed_char = '\'';
      break;
    case GUMBO_LEX_ATTR_VALUE_UNQUOTED:
      allowed_char = '>';
      is_unquoted = true;
      break;
    default:
      // -Wmaybe-uninitialized is a little overzealous here, and doesn't
      // get that the assert(0) means this codepath will never happen.
      allowed_char = ' ';
      assert(0);
  }

  // Ignore the status, since we don't have a convenient way of signalling that
  // a parser error has occurred when the error occurs in the middle of a
  // multi-state token.  We'd need a flag inside the TokenizerState to do this,
  // but that's a low priority fix.
  consume_char_ref(parser, &tokenizer->_input, allowed_char, true, &char_ref);
  if (char_ref.first != kGumboNoChar) {
    tokenizer->_reconsume_current_input = true;
    append_char_to_tag_buffer(parser, char_ref.first, is_unquoted);
    if (char_ref.second != kGumboNoChar) {
      append_char_to_tag_buffer(parser, char_ref.second, is_unquoted);
    }
  } else {
    append_char_to_tag_buffer(parser, '&', is_unquoted);
  }
  gumbo_tokenizer_set_state(parser, tokenizer->_tag_state._attr_value_state);
  return NEXT_CHAR;
}

// http://www.whatwg.org/specs/web-apps/current-work/complete5/tokenization.html#after-attribute-value-quoted-state
static StateResult handle_after_attr_value_quoted_state(GumboParser* parser,
    GumboTokenizerState* tokenizer, int c, GumboToken* output) {
  finish_attribute_value(parser);
  switch (c) {
    case '\t':
    case '\n':
    case '\f':
    case ' ':
      gumbo_tokenizer_set_state(parser, GUMBO_LEX_BEFORE_ATTR_NAME);
      return NEXT_CHAR;
    case '/':
      gumbo_tokenizer_set_state(parser, GUMBO_LEX_SELF_CLOSING_START_TAG);
      return NEXT_CHAR;
    case '>':
      gumbo_tokenizer_set_state(parser, GUMBO_LEX_DATA);
      return emit_current_tag(parser, output);
    case -1:
      tokenizer_add_parse_error(parser, GUMBO_ERR_ATTR_AFTER_EOF);
      gumbo_tokenizer_set_state(parser, GUMBO_LEX_DATA);
      abandon_current_tag(parser);
      tokenizer->_reconsume_current_input = true;
      return NEXT_CHAR;
    default:
      tokenizer_add_parse_error(parser, GUMBO_ERR_ATTR_AFTER_INVALID);
      gumbo_tokenizer_set_state(parser, GUMBO_LEX_BEFORE_ATTR_NAME);
      tokenizer->_reconsume_current_input = true;
      return NEXT_CHAR;
  }
}

// http://www.whatwg.org/specs/web-apps/current-work/complete.html#self-closing-start-tag-state
static StateResult handle_self_closing_start_tag_state(GumboParser* parser,
    GumboTokenizerState* tokenizer, int c, GumboToken* output) {
  switch (c) {
    case '>':
      gumbo_tokenizer_set_state(parser, GUMBO_LEX_DATA);
      tokenizer->_tag_state._is_self_closing = true;
      return emit_current_tag(parser, output);
    case -1:
      tokenizer_add_parse_error(parser, GUMBO_ERR_SOLIDUS_EOF);
      gumbo_tokenizer_set_state(parser, GUMBO_LEX_DATA);
      abandon_current_tag(parser);
      return NEXT_CHAR;
    default:
      tokenizer_add_parse_error(parser, GUMBO_ERR_SOLIDUS_INVALID);
      gumbo_tokenizer_set_state(parser, GUMBO_LEX_BEFORE_ATTR_NAME);
      tokenizer->_reconsume_current_input = true;
      return NEXT_CHAR;
  }
}

// http://www.whatwg.org/specs/web-apps/current-work/complete.html#bogus-comment-state
static StateResult handle_bogus_comment_state(GumboParser* parser,
    GumboTokenizerState* tokenizer, int c, GumboToken* output) {
  while (c != '>' && c != -1) {
    if (c == '\0') {
      c = 0xFFFD;
    }
    append_char_to_temporary_buffer(parser, c);
    utf8iterator_next(&tokenizer->_input);
    c = utf8iterator_current(&tokenizer->_input);
  }
  gumbo_tokenizer_set_state(parser, GUMBO_LEX_DATA);
  return emit_comment(parser, output);
}

// http://www.whatwg.org/specs/web-apps/current-work/complete.html#markup-declaration-open-state
static StateResult handle_markup_declaration_state(GumboParser* parser,
    GumboTokenizerState* tokenizer, int c, GumboToken* output) {
  if (utf8iterator_maybe_consume_match(
          &tokenizer->_input, "--", sizeof("--") - 1, true)) {
    gumbo_tokenizer_set_state(parser, GUMBO_LEX_COMMENT_START);
    tokenizer->_reconsume_current_input = true;
  } else if (utf8iterator_maybe_consume_match(
                 &tokenizer->_input, "DOCTYPE", sizeof("DOCTYPE") - 1, false)) {
    gumbo_tokenizer_set_state(parser, GUMBO_LEX_DOCTYPE);
    tokenizer->_reconsume_current_input = true;
    // If we get here, we know we'll eventually emit a doctype token, so now is
    // the time to initialize the doctype strings.  (Not in doctype_state_init,
    // since then they'll leak if ownership never gets transferred to the
    // doctype token.
    tokenizer->_doc_type_state.name = gumbo_copy_stringz(parser, "");
    tokenizer->_doc_type_state.public_identifier =
        gumbo_copy_stringz(parser, "");
    tokenizer->_doc_type_state.system_identifier =
        gumbo_copy_stringz(parser, "");
  } else if (tokenizer->_is_current_node_foreign &&
             utf8iterator_maybe_consume_match(
                 &tokenizer->_input, "[CDATA[", sizeof("[CDATA[") - 1, true)) {
    gumbo_tokenizer_set_state(parser, GUMBO_LEX_CDATA);
    tokenizer->_is_in_cdata = true;
    tokenizer->_reconsume_current_input = true;
  } else {
    tokenizer_add_parse_error(parser, GUMBO_ERR_DASHES_OR_DOCTYPE);
    gumbo_tokenizer_set_state(parser, GUMBO_LEX_BOGUS_COMMENT);
    tokenizer->_reconsume_current_input = true;
    clear_temporary_buffer(parser);
  }
  return NEXT_CHAR;
}

// http://www.whatwg.org/specs/web-apps/current-work/complete.html#comment-start-state
static StateResult handle_comment_start_state(GumboParser* parser,
    GumboTokenizerState* tokenizer, int c, GumboToken* output) {
  switch (c) {
    case '-':
      gumbo_tokenizer_set_state(parser, GUMBO_LEX_COMMENT_START_DASH);
      return NEXT_CHAR;
    case '\0':
      tokenizer_add_parse_error(parser, GUMBO_ERR_UTF8_NULL);
      gumbo_tokenizer_set_state(parser, GUMBO_LEX_COMMENT);
      append_char_to_temporary_buffer(parser, kUtf8ReplacementChar);
      return NEXT_CHAR;
    case '>':
      tokenizer_add_parse_error(parser, GUMBO_ERR_COMMENT_INVALID);
      gumbo_tokenizer_set_state(parser, GUMBO_LEX_DATA);
      emit_comment(parser, output);
      return RETURN_ERROR;
    case -1:
      tokenizer_add_parse_error(parser, GUMBO_ERR_COMMENT_EOF);
      gumbo_tokenizer_set_state(parser, GUMBO_LEX_DATA);
      emit_comment(parser, output);
      return RETURN_ERROR;
    default:
      gumbo_tokenizer_set_state(parser, GUMBO_LEX_COMMENT);
      append_char_to_temporary_buffer(parser, c);
      return NEXT_CHAR;
  }
}

// http://www.whatwg.org/specs/web-apps/current-work/complete.html#comment-start-dash-state
static StateResult handle_comment_start_dash_state(GumboParser* parser,
    GumboTokenizerState* tokenizer, int c, GumboToken* output) {
  switch (c) {
    case '-':
      gumbo_tokenizer_set_state(parser, GUMBO_LEX_COMMENT_END);
      return NEXT_CHAR;
    case '\0':
      tokenizer_add_parse_error(parser, GUMBO_ERR_UTF8_NULL);
      gumbo_tokenizer_set_state(parser, GUMBO_LEX_COMMENT);
      append_char_to_temporary_buffer(parser, '-');
      append_char_to_temporary_buffer(parser, kUtf8ReplacementChar);
      return NEXT_CHAR;
    case '>':
      tokenizer_add_parse_error(parser, GUMBO_ERR_COMMENT_INVALID);
      gumbo_tokenizer_set_state(parser, GUMBO_LEX_DATA);
      emit_comment(parser, output);
      return RETURN_ERROR;
    case -1:
      tokenizer_add_parse_error(parser, GUMBO_ERR_COMMENT_EOF);
      gumbo_tokenizer_set_state(parser, GUMBO_LEX_DATA);
      emit_comment(parser, output);
      return RETURN_ERROR;
    default:
      gumbo_tokenizer_set_state(parser, GUMBO_LEX_COMMENT);
      append_char_to_temporary_buffer(parser, '-');
      append_char_to_temporary_buffer(parser, c);
      return NEXT_CHAR;
  }
}

// http://www.whatwg.org/specs/web-apps/current-work/complete.html#comment-state
static StateResult handle_comment_state(GumboParser* parser,
    GumboTokenizerState* tokenizer, int c, GumboToken* output) {
  switch (c) {
    case '-':
      gumbo_tokenizer_set_state(parser, GUMBO_LEX_COMMENT_END_DASH);
      return NEXT_CHAR;
    case '\0':
      tokenizer_add_parse_error(parser, GUMBO_ERR_UTF8_NULL);
      append_char_to_temporary_buffer(parser, kUtf8ReplacementChar);
      return NEXT_CHAR;
    case -1:
      tokenizer_add_parse_error(parser, GUMBO_ERR_COMMENT_EOF);
      gumbo_tokenizer_set_state(parser, GUMBO_LEX_DATA);
      emit_comment(parser, output);
      return RETURN_ERROR;
    default:
      append_char_to_temporary_buffer(parser, c);
      return NEXT_CHAR;
  }
}

// http://www.whatwg.org/specs/web-apps/current-work/complete.html#comment-end-dash-state
static StateResult handle_comment_end_dash_state(GumboParser* parser,
    GumboTokenizerState* tokenizer, int c, GumboToken* output) {
  switch (c) {
    case '-':
      gumbo_tokenizer_set_state(parser, GUMBO_LEX_COMMENT_END);
      return NEXT_CHAR;
    case '\0':
      tokenizer_add_parse_error(parser, GUMBO_ERR_UTF8_NULL);
      gumbo_tokenizer_set_state(parser, GUMBO_LEX_COMMENT);
      append_char_to_temporary_buffer(parser, '-');
      append_char_to_temporary_buffer(parser, kUtf8ReplacementChar);
      return NEXT_CHAR;
    case -1:
      tokenizer_add_parse_error(parser, GUMBO_ERR_COMMENT_EOF);
      gumbo_tokenizer_set_state(parser, GUMBO_LEX_DATA);
      emit_comment(parser, output);
      return RETURN_ERROR;
    default:
      gumbo_tokenizer_set_state(parser, GUMBO_LEX_COMMENT);
      append_char_to_temporary_buffer(parser, '-');
      append_char_to_temporary_buffer(parser, c);
      return NEXT_CHAR;
  }
}

// http://www.whatwg.org/specs/web-apps/current-work/complete.html#comment-end-state
static StateResult handle_comment_end_state(GumboParser* parser,
    GumboTokenizerState* tokenizer, int c, GumboToken* output) {
  switch (c) {
    case '>':
      gumbo_tokenizer_set_state(parser, GUMBO_LEX_DATA);
      return emit_comment(parser, output);
    case '\0':
      tokenizer_add_parse_error(parser, GUMBO_ERR_UTF8_NULL);
      gumbo_tokenizer_set_state(parser, GUMBO_LEX_COMMENT);
      append_char_to_temporary_buffer(parser, '-');
      append_char_to_temporary_buffer(parser, '-');
      append_char_to_temporary_buffer(parser, kUtf8ReplacementChar);
      return NEXT_CHAR;
    case '!':
      tokenizer_add_parse_error(
          parser, GUMBO_ERR_COMMENT_BANG_AFTER_DOUBLE_DASH);
      gumbo_tokenizer_set_state(parser, GUMBO_LEX_COMMENT_END_BANG);
      return NEXT_CHAR;
    case '-':
      tokenizer_add_parse_error(
          parser, GUMBO_ERR_COMMENT_DASH_AFTER_DOUBLE_DASH);
      append_char_to_temporary_buffer(parser, '-');
      return NEXT_CHAR;
    case -1:
      tokenizer_add_parse_error(parser, GUMBO_ERR_UTF8_NULL);
      gumbo_tokenizer_set_state(parser, GUMBO_LEX_DATA);
      emit_comment(parser, output);
      return RETURN_ERROR;
    default:
      tokenizer_add_parse_error(parser, GUMBO_ERR_COMMENT_INVALID);
      gumbo_tokenizer_set_state(parser, GUMBO_LEX_COMMENT);
      append_char_to_temporary_buffer(parser, '-');
      append_char_to_temporary_buffer(parser, '-');
      append_char_to_temporary_buffer(parser, c);
      return NEXT_CHAR;
  }
}

// http://www.whatwg.org/specs/web-apps/current-work/complete.html#comment-end-bang-state
static StateResult handle_comment_end_bang_state(GumboParser* parser,
    GumboTokenizerState* tokenizer, int c, GumboToken* output) {
  switch (c) {
    case '-':
      gumbo_tokenizer_set_state(parser, GUMBO_LEX_COMMENT_END_DASH);
      append_char_to_temporary_buffer(parser, '-');
      append_char_to_temporary_buffer(parser, '-');
      append_char_to_temporary_buffer(parser, '!');
      return NEXT_CHAR;
    case '>':
      gumbo_tokenizer_set_state(parser, GUMBO_LEX_DATA);
      return emit_comment(parser, output);
    case '\0':
      tokenizer_add_parse_error(parser, GUMBO_ERR_UTF8_NULL);
      gumbo_tokenizer_set_state(parser, GUMBO_LEX_COMMENT);
      append_char_to_temporary_buffer(parser, '-');
      append_char_to_temporary_buffer(parser, '-');
      append_char_to_temporary_buffer(parser, '!');
      append_char_to_temporary_buffer(parser, kUtf8ReplacementChar);
      return NEXT_CHAR;
    case -1:
      tokenizer_add_parse_error(parser, GUMBO_ERR_COMMENT_END_BANG_EOF);
      gumbo_tokenizer_set_state(parser, GUMBO_LEX_DATA);
      emit_comment(parser, output);
      return RETURN_ERROR;
    default:
      gumbo_tokenizer_set_state(parser, GUMBO_LEX_COMMENT);
      append_char_to_temporary_buffer(parser, '-');
      append_char_to_temporary_buffer(parser, '-');
      append_char_to_temporary_buffer(parser, '!');
      append_char_to_temporary_buffer(parser, c);
      return NEXT_CHAR;
  }
}

// http://www.whatwg.org/specs/web-apps/current-work/complete5/tokenization.html#doctype-state
static StateResult handle_doctype_state(GumboParser* parser,
    GumboTokenizerState* tokenizer, int c, GumboToken* output) {
  assert(!tokenizer->_temporary_buffer.length);
  switch (c) {
    case '\t':
    case '\n':
    case '\f':
    case ' ':
      gumbo_tokenizer_set_state(parser, GUMBO_LEX_BEFORE_DOCTYPE_NAME);
      return NEXT_CHAR;
    case -1:
      tokenizer_add_parse_error(parser, GUMBO_ERR_DOCTYPE_EOF);
      gumbo_tokenizer_set_state(parser, GUMBO_LEX_DATA);
      tokenizer->_doc_type_state.force_quirks = true;
      emit_doctype(parser, output);
      return RETURN_ERROR;
    default:
      tokenizer_add_parse_error(parser, GUMBO_ERR_DOCTYPE_SPACE);
      gumbo_tokenizer_set_state(parser, GUMBO_LEX_BEFORE_DOCTYPE_NAME);
      tokenizer->_reconsume_current_input = true;
      tokenizer->_doc_type_state.force_quirks = true;
      return NEXT_CHAR;
  }
}

// http://www.whatwg.org/specs/web-apps/current-work/complete5/tokenization.html#before-doctype-name-state
static StateResult handle_before_doctype_name_state(GumboParser* parser,
    GumboTokenizerState* tokenizer, int c, GumboToken* output) {
  switch (c) {
    case '\t':
    case '\n':
    case '\f':
    case ' ':
      return NEXT_CHAR;
    case '\0':
      tokenizer_add_parse_error(parser, GUMBO_ERR_UTF8_NULL);
      gumbo_tokenizer_set_state(parser, GUMBO_LEX_DOCTYPE_NAME);
      tokenizer->_doc_type_state.force_quirks = true;
      append_char_to_temporary_buffer(parser, kUtf8ReplacementChar);
      return NEXT_CHAR;
    case '>':
      tokenizer_add_parse_error(parser, GUMBO_ERR_DOCTYPE_RIGHT_BRACKET);
      gumbo_tokenizer_set_state(parser, GUMBO_LEX_DATA);
      tokenizer->_doc_type_state.force_quirks = true;
      emit_doctype(parser, output);
      return RETURN_ERROR;
    case -1:
      tokenizer_add_parse_error(parser, GUMBO_ERR_DOCTYPE_EOF);
      gumbo_tokenizer_set_state(parser, GUMBO_LEX_DATA);
      tokenizer->_doc_type_state.force_quirks = true;
      emit_doctype(parser, output);
      return RETURN_ERROR;
    default:
      gumbo_tokenizer_set_state(parser, GUMBO_LEX_DOCTYPE_NAME);
      tokenizer->_doc_type_state.force_quirks = false;
      append_char_to_temporary_buffer(parser, ensure_lowercase(c));
      return NEXT_CHAR;
  }
}

// http://www.whatwg.org/specs/web-apps/current-work/complete5/tokenization.html#doctype-name-state
static StateResult handle_doctype_name_state(GumboParser* parser,
    GumboTokenizerState* tokenizer, int c, GumboToken* output) {
  switch (c) {
    case '\t':
    case '\n':
    case '\f':
    case ' ':
      gumbo_tokenizer_set_state(parser, GUMBO_LEX_AFTER_DOCTYPE_NAME);
      gumbo_parser_deallocate(parser, (void*) tokenizer->_doc_type_state.name);
      finish_temporary_buffer(parser, &tokenizer->_doc_type_state.name);
      return NEXT_CHAR;
    case '>':
      gumbo_tokenizer_set_state(parser, GUMBO_LEX_DATA);
      gumbo_parser_deallocate(parser, (void*) tokenizer->_doc_type_state.name);
      finish_temporary_buffer(parser, &tokenizer->_doc_type_state.name);
      emit_doctype(parser, output);
      return RETURN_SUCCESS;
    case '\0':
      tokenizer_add_parse_error(parser, GUMBO_ERR_UTF8_NULL);
      append_char_to_temporary_buffer(parser, kUtf8ReplacementChar);
      return NEXT_CHAR;
    case -1:
      tokenizer_add_parse_error(parser, GUMBO_ERR_DOCTYPE_EOF);
      gumbo_tokenizer_set_state(parser, GUMBO_LEX_DATA);
      tokenizer->_doc_type_state.force_quirks = true;
      gumbo_parser_deallocate(parser, (void*) tokenizer->_doc_type_state.name);
      finish_temporary_buffer(parser, &tokenizer->_doc_type_state.name);
      emit_doctype(parser, output);
      return RETURN_ERROR;
    default:
      gumbo_tokenizer_set_state(parser, GUMBO_LEX_DOCTYPE_NAME);
      tokenizer->_doc_type_state.force_quirks = false;
      append_char_to_temporary_buffer(parser, ensure_lowercase(c));
      return NEXT_CHAR;
  }
}

// http://www.whatwg.org/specs/web-apps/current-work/complete.html#after-doctype-name-state
static StateResult handle_after_doctype_name_state(GumboParser* parser,
    GumboTokenizerState* tokenizer, int c, GumboToken* output) {
  switch (c) {
    case '\t':
    case '\n':
    case '\f':
    case ' ':
      return NEXT_CHAR;
    case '>':
      gumbo_tokenizer_set_state(parser, GUMBO_LEX_DATA);
      emit_doctype(parser, output);
      return RETURN_SUCCESS;
    case -1:
      tokenizer_add_parse_error(parser, GUMBO_ERR_DOCTYPE_EOF);
      gumbo_tokenizer_set_state(parser, GUMBO_LEX_DATA);
      tokenizer->_doc_type_state.force_quirks = true;
      emit_doctype(parser, output);
      return RETURN_ERROR;
    default:
      if (utf8iterator_maybe_consume_match(
              &tokenizer->_input, "PUBLIC", sizeof("PUBLIC") - 1, false)) {
        gumbo_tokenizer_set_state(
            parser, GUMBO_LEX_AFTER_DOCTYPE_PUBLIC_KEYWORD);
        tokenizer->_reconsume_current_input = true;
      } else if (utf8iterator_maybe_consume_match(&tokenizer->_input, "SYSTEM",
                     sizeof("SYSTEM") - 1, false)) {
        gumbo_tokenizer_set_state(
            parser, GUMBO_LEX_AFTER_DOCTYPE_SYSTEM_KEYWORD);
        tokenizer->_reconsume_current_input = true;
      } else {
        tokenizer_add_parse_error(
            parser, GUMBO_ERR_DOCTYPE_SPACE_OR_RIGHT_BRACKET);
        gumbo_tokenizer_set_state(parser, GUMBO_LEX_BOGUS_DOCTYPE);
        tokenizer->_doc_type_state.force_quirks = true;
      }
      return NEXT_CHAR;
  }
}

// http://www.whatwg.org/specs/web-apps/current-work/complete.html#after-doctype-public-keyword-state
static StateResult handle_after_doctype_public_keyword_state(
    GumboParser* parser, GumboTokenizerState* tokenizer, int c,
    GumboToken* output) {
  switch (c) {
    case '\t':
    case '\n':
    case '\f':
    case ' ':
      gumbo_tokenizer_set_state(parser, GUMBO_LEX_BEFORE_DOCTYPE_PUBLIC_ID);
      return NEXT_CHAR;
    case '"':
      tokenizer_add_parse_error(parser, GUMBO_ERR_DOCTYPE_INVALID);
      assert(temporary_buffer_equals(parser, ""));
      gumbo_tokenizer_set_state(
          parser, GUMBO_LEX_DOCTYPE_PUBLIC_ID_DOUBLE_QUOTED);
      return NEXT_CHAR;
    case '\'':
      tokenizer_add_parse_error(parser, GUMBO_ERR_DOCTYPE_INVALID);
      assert(temporary_buffer_equals(parser, ""));
      gumbo_tokenizer_set_state(
          parser, GUMBO_LEX_DOCTYPE_PUBLIC_ID_SINGLE_QUOTED);
      return NEXT_CHAR;
    case '>':
      tokenizer_add_parse_error(parser, GUMBO_ERR_DOCTYPE_RIGHT_BRACKET);
      gumbo_tokenizer_set_state(parser, GUMBO_LEX_DATA);
      tokenizer->_doc_type_state.force_quirks = true;
      emit_doctype(parser, output);
      return RETURN_ERROR;
    case -1:
      tokenizer_add_parse_error(parser, GUMBO_ERR_DOCTYPE_EOF);
      gumbo_tokenizer_set_state(parser, GUMBO_LEX_DATA);
      tokenizer->_doc_type_state.force_quirks = true;
      emit_doctype(parser, output);
      return RETURN_ERROR;
    default:
      tokenizer_add_parse_error(parser, GUMBO_ERR_DOCTYPE_INVALID);
      gumbo_tokenizer_set_state(parser, GUMBO_LEX_BOGUS_DOCTYPE);
      tokenizer->_doc_type_state.force_quirks = true;
      emit_doctype(parser, output);
      return RETURN_ERROR;
  }
}

// http://www.whatwg.org/specs/web-apps/current-work/complete.html#before-doctype-public-identifier-state
static StateResult handle_before_doctype_public_id_state(GumboParser* parser,
    GumboTokenizerState* tokenizer, int c, GumboToken* output) {
  switch (c) {
    case '\t':
    case '\n':
    case '\f':
    case ' ':
      return NEXT_CHAR;
    case '"':
      assert(temporary_buffer_equals(parser, ""));
      gumbo_tokenizer_set_state(
          parser, GUMBO_LEX_DOCTYPE_PUBLIC_ID_DOUBLE_QUOTED);
      return NEXT_CHAR;
    case '\'':
      assert(temporary_buffer_equals(parser, ""));
      gumbo_tokenizer_set_state(
          parser, GUMBO_LEX_DOCTYPE_PUBLIC_ID_SINGLE_QUOTED);
      return NEXT_CHAR;
    case '>':
      tokenizer_add_parse_error(parser, GUMBO_ERR_DOCTYPE_END);
      gumbo_tokenizer_set_state(parser, GUMBO_LEX_DATA);
      tokenizer->_doc_type_state.force_quirks = true;
      emit_doctype(parser, output);
      return RETURN_ERROR;
    case -1:
      tokenizer_add_parse_error(parser, GUMBO_ERR_DOCTYPE_EOF);
      gumbo_tokenizer_set_state(parser, GUMBO_LEX_DATA);
      tokenizer->_doc_type_state.force_quirks = true;
      emit_doctype(parser, output);
      return RETURN_ERROR;
    default:
      tokenizer_add_parse_error(parser, GUMBO_ERR_DOCTYPE_INVALID);
      gumbo_tokenizer_set_state(parser, GUMBO_LEX_BOGUS_DOCTYPE);
      tokenizer->_doc_type_state.force_quirks = true;
      emit_doctype(parser, output);
      return RETURN_ERROR;
  }
}

// http://www.whatwg.org/specs/web-apps/current-work/complete.html#doctype-public-identifier-(double-quoted)-state
static StateResult handle_doctype_public_id_double_quoted_state(
    GumboParser* parser, GumboTokenizerState* tokenizer, int c,
    GumboToken* output) {
  switch (c) {
    case '"':
      gumbo_tokenizer_set_state(parser, GUMBO_LEX_AFTER_DOCTYPE_PUBLIC_ID);
      finish_doctype_public_id(parser);
      return NEXT_CHAR;
    case '\0':
      tokenizer_add_parse_error(parser, GUMBO_ERR_UTF8_NULL);
      append_char_to_temporary_buffer(parser, kUtf8ReplacementChar);
      return NEXT_CHAR;
    case '>':
      tokenizer_add_parse_error(parser, GUMBO_ERR_DOCTYPE_END);
      gumbo_tokenizer_set_state(parser, GUMBO_LEX_DATA);
      tokenizer->_doc_type_state.force_quirks = true;
      finish_doctype_public_id(parser);
      emit_doctype(parser, output);
      return RETURN_ERROR;
    case -1:
      tokenizer_add_parse_error(parser, GUMBO_ERR_DOCTYPE_EOF);
      gumbo_tokenizer_set_state(parser, GUMBO_LEX_DATA);
      tokenizer->_doc_type_state.force_quirks = true;
      finish_doctype_public_id(parser);
      emit_doctype(parser, output);
      return RETURN_ERROR;
    default:
      append_char_to_temporary_buffer(parser, c);
      return NEXT_CHAR;
  }
}

// http://www.whatwg.org/specs/web-apps/current-work/complete.html#doctype-public-identifier-(single-quoted)-state
static StateResult handle_doctype_public_id_single_quoted_state(
    GumboParser* parser, GumboTokenizerState* tokenizer, int c,
    GumboToken* output) {
  switch (c) {
    case '\'':
      gumbo_tokenizer_set_state(parser, GUMBO_LEX_AFTER_DOCTYPE_PUBLIC_ID);
      finish_doctype_public_id(parser);
      return NEXT_CHAR;
    case '\0':
      tokenizer_add_parse_error(parser, GUMBO_ERR_UTF8_NULL);
      append_char_to_temporary_buffer(parser, kUtf8ReplacementChar);
      return NEXT_CHAR;
    case '>':
      tokenizer_add_parse_error(parser, GUMBO_ERR_DOCTYPE_END);
      gumbo_tokenizer_set_state(parser, GUMBO_LEX_DATA);
      tokenizer->_doc_type_state.force_quirks = true;
      finish_doctype_public_id(parser);
      emit_doctype(parser, output);
      return RETURN_ERROR;
    case -1:
      tokenizer_add_parse_error(parser, GUMBO_ERR_DOCTYPE_EOF);
      gumbo_tokenizer_set_state(parser, GUMBO_LEX_DATA);
      tokenizer->_doc_type_state.force_quirks = true;
      finish_doctype_public_id(parser);
      emit_doctype(parser, output);
      return RETURN_ERROR;
    default:
      append_char_to_temporary_buffer(parser, c);
      return NEXT_CHAR;
  }
}

// http://www.whatwg.org/specs/web-apps/current-work/complete.html#after-doctype-public-identifier-state
static StateResult handle_after_doctype_public_id_state(GumboParser* parser,
    GumboTokenizerState* tokenizer, int c, GumboToken* output) {
  switch (c) {
    case '\t':
    case '\n':
    case '\f':
    case ' ':
      gumbo_tokenizer_set_state(
          parser, GUMBO_LEX_BETWEEN_DOCTYPE_PUBLIC_SYSTEM_ID);
      return NEXT_CHAR;
    case '>':
      gumbo_tokenizer_set_state(parser, GUMBO_LEX_DATA);
      emit_doctype(parser, output);
      return RETURN_SUCCESS;
    case '"':
      tokenizer_add_parse_error(parser, GUMBO_ERR_DOCTYPE_INVALID);
      assert(temporary_buffer_equals(parser, ""));
      gumbo_tokenizer_set_state(
          parser, GUMBO_LEX_DOCTYPE_SYSTEM_ID_DOUBLE_QUOTED);
      return NEXT_CHAR;
    case '\'':
      tokenizer_add_parse_error(parser, GUMBO_ERR_DOCTYPE_INVALID);
      assert(temporary_buffer_equals(parser, ""));
      gumbo_tokenizer_set_state(
          parser, GUMBO_LEX_DOCTYPE_SYSTEM_ID_SINGLE_QUOTED);
      return NEXT_CHAR;
    case -1:
      tokenizer_add_parse_error(parser, GUMBO_ERR_DOCTYPE_EOF);
      gumbo_tokenizer_set_state(parser, GUMBO_LEX_DATA);
      tokenizer->_reconsume_current_input = true;
      tokenizer->_doc_type_state.force_quirks = true;
      emit_doctype(parser, output);
      return RETURN_ERROR;
    default:
      tokenizer_add_parse_error(parser, GUMBO_ERR_DOCTYPE_INVALID);
      gumbo_tokenizer_set_state(parser, GUMBO_LEX_BOGUS_DOCTYPE);
      tokenizer->_doc_type_state.force_quirks = true;
      return NEXT_CHAR;
  }
}

// http://www.whatwg.org/specs/web-apps/current-work/complete.html#between-doctype-public-and-system-identifiers-state
static StateResult handle_between_doctype_public_system_id_state(
    GumboParser* parser, GumboTokenizerState* tokenizer, int c,
    GumboToken* output) {
  switch (c) {
    case '\t':
    case '\n':
    case '\f':
    case ' ':
      return NEXT_CHAR;
    case '>':
      gumbo_tokenizer_set_state(parser, GUMBO_LEX_DATA);
      emit_doctype(parser, output);
      return RETURN_SUCCESS;
    case '"':
      assert(temporary_buffer_equals(parser, ""));
      gumbo_tokenizer_set_state(
          parser, GUMBO_LEX_DOCTYPE_SYSTEM_ID_DOUBLE_QUOTED);
      return NEXT_CHAR;
    case '\'':
      assert(temporary_buffer_equals(parser, ""));
      gumbo_tokenizer_set_state(
          parser, GUMBO_LEX_DOCTYPE_SYSTEM_ID_SINGLE_QUOTED);
      return NEXT_CHAR;
    case -1:
      tokenizer_add_parse_error(parser, GUMBO_ERR_DOCTYPE_EOF);
      gumbo_tokenizer_set_state(parser, GUMBO_LEX_DATA);
      tokenizer->_doc_type_state.force_quirks = true;
      emit_doctype(parser, output);
      return RETURN_ERROR;
    default:
      tokenizer_add_parse_error(parser, GUMBO_ERR_DOCTYPE_INVALID);
      gumbo_tokenizer_set_state(parser, GUMBO_LEX_BOGUS_DOCTYPE);
      tokenizer->_doc_type_state.force_quirks = true;
      emit_doctype(parser, output);
      return RETURN_ERROR;
  }
}

// http://www.whatwg.org/specs/web-apps/current-work/complete.html#after-doctype-system-keyword-state
static StateResult handle_after_doctype_system_keyword_state(
    GumboParser* parser, GumboTokenizerState* tokenizer, int c,
    GumboToken* output) {
  switch (c) {
    case '\t':
    case '\n':
    case '\f':
    case ' ':
      gumbo_tokenizer_set_state(parser, GUMBO_LEX_BEFORE_DOCTYPE_SYSTEM_ID);
      return NEXT_CHAR;
    case '"':
      tokenizer_add_parse_error(parser, GUMBO_ERR_DOCTYPE_INVALID);
      assert(temporary_buffer_equals(parser, ""));
      gumbo_tokenizer_set_state(
          parser, GUMBO_LEX_DOCTYPE_SYSTEM_ID_DOUBLE_QUOTED);
      return NEXT_CHAR;
    case '\'':
      tokenizer_add_parse_error(parser, GUMBO_ERR_DOCTYPE_INVALID);
      assert(temporary_buffer_equals(parser, ""));
      gumbo_tokenizer_set_state(
          parser, GUMBO_LEX_DOCTYPE_SYSTEM_ID_SINGLE_QUOTED);
      return NEXT_CHAR;
    case '>':
      tokenizer_add_parse_error(parser, GUMBO_ERR_DOCTYPE_END);
      gumbo_tokenizer_set_state(parser, GUMBO_LEX_DATA);
      tokenizer->_doc_type_state.force_quirks = true;
      emit_doctype(parser, output);
      return RETURN_ERROR;
    case -1:
      tokenizer_add_parse_error(parser, GUMBO_ERR_DOCTYPE_EOF);
      gumbo_tokenizer_set_state(parser, GUMBO_LEX_DATA);
      tokenizer->_doc_type_state.force_quirks = true;
      emit_doctype(parser, output);
      return RETURN_ERROR;
    default:
      tokenizer_add_parse_error(parser, GUMBO_ERR_DOCTYPE_INVALID);
      gumbo_tokenizer_set_state(parser, GUMBO_LEX_BOGUS_DOCTYPE);
      tokenizer->_doc_type_state.force_quirks = true;
      return NEXT_CHAR;
  }
}

// http://www.whatwg.org/specs/web-apps/current-work/complete.html#before-doctype-system-identifier-state
static StateResult handle_before_doctype_system_id_state(GumboParser* parser,
    GumboTokenizerState* tokenizer, int c, GumboToken* output) {
  switch (c) {
    case '\t':
    case '\n':
    case '\f':
    case ' ':
      return NEXT_CHAR;
    case '"':
      assert(temporary_buffer_equals(parser, ""));
      gumbo_tokenizer_set_state(
          parser, GUMBO_LEX_DOCTYPE_SYSTEM_ID_DOUBLE_QUOTED);
      return NEXT_CHAR;
    case '\'':
      assert(temporary_buffer_equals(parser, ""));
      gumbo_tokenizer_set_state(
          parser, GUMBO_LEX_DOCTYPE_SYSTEM_ID_SINGLE_QUOTED);
      return NEXT_CHAR;
    case '>':
      tokenizer_add_parse_error(parser, GUMBO_ERR_DOCTYPE_END);
      gumbo_tokenizer_set_state(parser, GUMBO_LEX_DATA);
      tokenizer->_doc_type_state.force_quirks = true;
      emit_doctype(parser, output);
      return RETURN_ERROR;
    case -1:
      tokenizer_add_parse_error(parser, GUMBO_ERR_DOCTYPE_EOF);
      gumbo_tokenizer_set_state(parser, GUMBO_LEX_DATA);
      tokenizer->_doc_type_state.force_quirks = true;
      emit_doctype(parser, output);
      return RETURN_ERROR;
    default:
      tokenizer_add_parse_error(parser, GUMBO_ERR_DOCTYPE_INVALID);
      gumbo_tokenizer_set_state(parser, GUMBO_LEX_BOGUS_DOCTYPE);
      tokenizer->_doc_type_state.force_quirks = true;
      return NEXT_CHAR;
  }
}

// http://www.whatwg.org/specs/web-apps/current-work/complete.html#doctype-system-identifier-(double-quoted)-state
static StateResult handle_doctype_system_id_double_quoted_state(
    GumboParser* parser, GumboTokenizerState* tokenizer, int c,
    GumboToken* output) {
  switch (c) {
    case '"':
      gumbo_tokenizer_set_state(parser, GUMBO_LEX_AFTER_DOCTYPE_SYSTEM_ID);
      finish_doctype_system_id(parser);
      return NEXT_CHAR;
    case '\0':
      tokenizer_add_parse_error(parser, GUMBO_ERR_UTF8_NULL);
      append_char_to_temporary_buffer(parser, kUtf8ReplacementChar);
      return NEXT_CHAR;
    case '>':
      tokenizer_add_parse_error(parser, GUMBO_ERR_DOCTYPE_END);
      gumbo_tokenizer_set_state(parser, GUMBO_LEX_DATA);
      tokenizer->_doc_type_state.force_quirks = true;
      finish_doctype_system_id(parser);
      emit_doctype(parser, output);
      return RETURN_ERROR;
    case -1:
      tokenizer_add_parse_error(parser, GUMBO_ERR_DOCTYPE_EOF);
      gumbo_tokenizer_set_state(parser, GUMBO_LEX_DATA);
      tokenizer->_doc_type_state.force_quirks = true;
      finish_doctype_system_id(parser);
      emit_doctype(parser, output);
      return RETURN_ERROR;
    default:
      append_char_to_temporary_buffer(parser, c);
      return NEXT_CHAR;
  }
}

// http://www.whatwg.org/specs/web-apps/current-work/complete.html#doctype-system-identifier-(single-quoted)-state
static StateResult handle_doctype_system_id_single_quoted_state(
    GumboParser* parser, GumboTokenizerState* tokenizer, int c,
    GumboToken* output) {
  switch (c) {
    case '\'':
      gumbo_tokenizer_set_state(parser, GUMBO_LEX_AFTER_DOCTYPE_SYSTEM_ID);
      finish_doctype_system_id(parser);
      return NEXT_CHAR;
    case '\0':
      tokenizer_add_parse_error(parser, GUMBO_ERR_UTF8_NULL);
      append_char_to_temporary_buffer(parser, kUtf8ReplacementChar);
      return NEXT_CHAR;
    case '>':
      tokenizer_add_parse_error(parser, GUMBO_ERR_DOCTYPE_END);
      gumbo_tokenizer_set_state(parser, GUMBO_LEX_DATA);
      tokenizer->_doc_type_state.force_quirks = true;
      finish_doctype_system_id(parser);
      emit_doctype(parser, output);
      return RETURN_ERROR;
    case -1:
      tokenizer_add_parse_error(parser, GUMBO_ERR_DOCTYPE_INVALID);
      gumbo_tokenizer_set_state(parser, GUMBO_LEX_DATA);
      tokenizer->_doc_type_state.force_quirks = true;
      finish_doctype_system_id(parser);
      emit_doctype(parser, output);
      return RETURN_ERROR;
    default:
      append_char_to_temporary_buffer(parser, c);
      return NEXT_CHAR;
  }
}

// http://www.whatwg.org/specs/web-apps/current-work/complete.html#after-doctype-system-identifier-state
static StateResult handle_after_doctype_system_id_state(GumboParser* parser,
    GumboTokenizerState* tokenizer, int c, GumboToken* output) {
  switch (c) {
    case '\t':
    case '\n':
    case '\f':
    case ' ':
      return NEXT_CHAR;
    case '>':
      gumbo_tokenizer_set_state(parser, GUMBO_LEX_DATA);
      emit_doctype(parser, output);
      return RETURN_SUCCESS;
    case -1:
      tokenizer_add_parse_error(parser, GUMBO_ERR_DOCTYPE_EOF);
      gumbo_tokenizer_set_state(parser, GUMBO_LEX_DATA);
      tokenizer->_doc_type_state.force_quirks = true;
      emit_doctype(parser, output);
      return RETURN_ERROR;
    default:
      tokenizer_add_parse_error(parser, GUMBO_ERR_DOCTYPE_INVALID);
      gumbo_tokenizer_set_state(parser, GUMBO_LEX_BOGUS_DOCTYPE);
      return NEXT_CHAR;
  }
}

// http://www.whatwg.org/specs/web-apps/current-work/complete.html#bogus-doctype-state
static StateResult handle_bogus_doctype_state(GumboParser* parser,
    GumboTokenizerState* tokenizer, int c, GumboToken* output) {
  if (c == '>' || c == -1) {
    gumbo_tokenizer_set_state(parser, GUMBO_LEX_DATA);
    emit_doctype(parser, output);
    return RETURN_ERROR;
  }
  return NEXT_CHAR;
}

// http://www.whatwg.org/specs/web-apps/current-work/complete.html#cdata-section-state
static StateResult handle_cdata_state(GumboParser* parser,
    GumboTokenizerState* tokenizer, int c, GumboToken* output) {
  if (c == -1 || utf8iterator_maybe_consume_match(
                     &tokenizer->_input, "]]>", sizeof("]]>") - 1, true)) {
    tokenizer->_reconsume_current_input = true;
    reset_token_start_point(tokenizer);
    gumbo_tokenizer_set_state(parser, GUMBO_LEX_DATA);
    tokenizer->_is_in_cdata = false;
    return NEXT_CHAR;
  } else {
    return emit_current_char(parser, output);
  }
}

typedef StateResult (*GumboLexerStateFunction)(
    GumboParser*, GumboTokenizerState*, int, GumboToken*);

static GumboLexerStateFunction dispatch_table[] = {handle_data_state,
    handle_char_ref_in_data_state, handle_rcdata_state,
    handle_char_ref_in_rcdata_state, handle_rawtext_state, handle_script_state,
    handle_plaintext_state, handle_tag_open_state, handle_end_tag_open_state,
    handle_tag_name_state, handle_rcdata_lt_state,
    handle_rcdata_end_tag_open_state, handle_rcdata_end_tag_name_state,
    handle_rawtext_lt_state, handle_rawtext_end_tag_open_state,
    handle_rawtext_end_tag_name_state, handle_script_lt_state,
    handle_script_end_tag_open_state, handle_script_end_tag_name_state,
    handle_script_escaped_start_state, handle_script_escaped_start_dash_state,
    handle_script_escaped_state, handle_script_escaped_dash_state,
    handle_script_escaped_dash_dash_state, handle_script_escaped_lt_state,
    handle_script_escaped_end_tag_open_state,
    handle_script_escaped_end_tag_name_state,
    handle_script_double_escaped_start_state,
    handle_script_double_escaped_state, handle_script_double_escaped_dash_state,
    handle_script_double_escaped_dash_dash_state,
    handle_script_double_escaped_lt_state,
    handle_script_double_escaped_end_state, handle_before_attr_name_state,
    handle_attr_name_state, handle_after_attr_name_state,
    handle_before_attr_value_state, handle_attr_value_double_quoted_state,
    handle_attr_value_single_quoted_state, handle_attr_value_unquoted_state,
    handle_char_ref_in_attr_value_state, handle_after_attr_value_quoted_state,
    handle_self_closing_start_tag_state, handle_bogus_comment_state,
    handle_markup_declaration_state, handle_comment_start_state,
    handle_comment_start_dash_state, handle_comment_state,
    handle_comment_end_dash_state, handle_comment_end_state,
    handle_comment_end_bang_state, handle_doctype_state,
    handle_before_doctype_name_state, handle_doctype_name_state,
    handle_after_doctype_name_state, handle_after_doctype_public_keyword_state,
    handle_before_doctype_public_id_state,
    handle_doctype_public_id_double_quoted_state,
    handle_doctype_public_id_single_quoted_state,
    handle_after_doctype_public_id_state,
    handle_between_doctype_public_system_id_state,
    handle_after_doctype_system_keyword_state,
    handle_before_doctype_system_id_state,
    handle_doctype_system_id_double_quoted_state,
    handle_doctype_system_id_single_quoted_state,
    handle_after_doctype_system_id_state, handle_bogus_doctype_state,
    handle_cdata_state};

bool gumbo_lex(GumboParser* parser, GumboToken* output) {
  // Because of the spec requirements that...
  //
  // 1. Tokens be handled immediately by the parser upon emission.
  // 2. Some states (eg. CDATA, or various error conditions) require the
  // emission of multiple tokens in the same states.
  // 3. The tokenizer often has to reconsume the same character in a different
  // state.
  //
  // ...all state must be held in the GumboTokenizer struct instead of in local
  // variables in this function.  That allows us to return from this method with
  // a token, and then immediately jump back to the same state with the same
  // input if we need to return a different token.  The various emit_* functions
  // are responsible for changing state (eg. flushing the chardata buffer,
  // reading the next input character) to avoid an infinite loop.
  GumboTokenizerState* tokenizer = parser->_tokenizer_state;

  if (tokenizer->_buffered_emit_char != kGumboNoChar) {
    tokenizer->_reconsume_current_input = true;
    emit_char(parser, tokenizer->_buffered_emit_char, output);
    // And now that we've avoided advancing the input, make sure we set
    // _reconsume_current_input back to false to make sure the *next* character
    // isn't consumed twice.
    tokenizer->_reconsume_current_input = false;
    tokenizer->_buffered_emit_char = kGumboNoChar;
    return true;
  }

  if (maybe_emit_from_temporary_buffer(parser, output)) {
    return true;
  }

  while (1) {
    assert(!tokenizer->_temporary_buffer_emit);
    assert(tokenizer->_buffered_emit_char == kGumboNoChar);
    int c = utf8iterator_current(&tokenizer->_input);
    gumbo_debug(
        "Lexing character '%c' (%d) in state %d.\n", c, c, tokenizer->_state);
    StateResult result =
        dispatch_table[tokenizer->_state](parser, tokenizer, c, output);
    // We need to clear reconsume_current_input before returning to prevent
    // certain infinite loop states.
    bool should_advance = !tokenizer->_reconsume_current_input;
    tokenizer->_reconsume_current_input = false;

    if (result == RETURN_SUCCESS) {
      return true;
    } else if (result == RETURN_ERROR) {
      return false;
    }

    if (should_advance) {
      utf8iterator_next(&tokenizer->_input);
    }
  }
}

void gumbo_token_destroy(GumboParser* parser, GumboToken* token) {
  if (!token) return;

  switch (token->type) {
    case GUMBO_TOKEN_DOCTYPE:
      gumbo_parser_deallocate(parser, (void*) token->v.doc_type.name);
      gumbo_parser_deallocate(
          parser, (void*) token->v.doc_type.public_identifier);
      gumbo_parser_deallocate(
          parser, (void*) token->v.doc_type.system_identifier);
      return;
    case GUMBO_TOKEN_START_TAG:
      for (unsigned int i = 0; i < token->v.start_tag.attributes.length; ++i) {
        GumboAttribute* attr = token->v.start_tag.attributes.data[i];
        if (attr) {
          // May have been nulled out if this token was merged with another.
          gumbo_destroy_attribute(parser, attr);
        }
      }
      gumbo_parser_deallocate(
          parser, (void*) token->v.start_tag.attributes.data);
      return;
    case GUMBO_TOKEN_COMMENT:
      gumbo_parser_deallocate(parser, (void*) token->v.text);
      return;
    default:
      return;
  }
}