aboutsummaryrefslogtreecommitdiffstats
path: root/gcc-4.9/gcc/gengtype-state.c
blob: 0b925b539bc9ad99a4b19f9a25c6b2b622d52b86 (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
/* Gengtype persistent state serialization & de-serialization.
   Useful for gengtype in plugin mode.

   Copyright (C) 2010-2014 Free Software Foundation, Inc.

   This file is part of GCC.

   GCC is free software; you can redistribute it and/or modify it under
   the terms of the GNU General Public License as published by the Free
   Software Foundation; either version 3, or (at your option) any later
   version.

   GCC is distributed in the hope that it will be useful, but WITHOUT ANY
   WARRANTY; without even the implied warranty of MERCHANTABILITY or
   FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
   for more details.

   You should have received a copy of the GNU General Public License
   along with GCC; see the file COPYING3.  If not see
   <http://www.gnu.org/licenses/>.

   Contributed by Jeremie Salvucci <jeremie.salvucci@free.fr>
   and Basile Starynkevitch <basile@starynkevitch.net>
*/

#ifdef GENERATOR_FILE
#include "bconfig.h"
#else
#include "config.h"
#endif
#include "system.h"
#include "errors.h"	/* For fatal.  */
#include "double-int.h"
#include "hashtab.h"
#include "version.h"	/* For version_string & pkgversion_string.  */
#include "obstack.h"
#include "gengtype.h"



/* Gives the file location of a type, if any.  */
static inline struct fileloc*
type_lineloc (const_type_p ty)
{
  if (!ty)
    return NULL;
  switch (ty->kind)
    {
    case TYPE_NONE:
      gcc_unreachable ();
    case TYPE_STRUCT:
    case TYPE_UNION:
    case TYPE_LANG_STRUCT:
    case TYPE_USER_STRUCT:
    case TYPE_UNDEFINED:
      return CONST_CAST (struct fileloc*, &ty->u.s.line);
    case TYPE_PARAM_STRUCT:
      return CONST_CAST (struct fileloc*, &ty->u.param_struct.line);
    case TYPE_SCALAR:
    case TYPE_STRING:
    case TYPE_POINTER:
    case TYPE_ARRAY:
      return NULL;
    default:
      gcc_unreachable ();
    }
}

/* The state file has simplistic lispy lexical tokens.  Its lexer gives
   a linked list of struct state_token_st, through the peek_state_token
   function.  Lexical tokens are consumed with next_state_tokens.  */


/* The lexical kind of each lispy token.  */
enum state_token_en
{
  STOK_NONE,                    /* Never used.  */
  STOK_INTEGER,                 /* Integer token.  */
  STOK_STRING,                  /* String token.  */
  STOK_LEFTPAR,                 /* Left opening parenthesis.  */
  STOK_RIGHTPAR,                /* Right closing parenthesis.  */
  STOK_NAME                     /* hash-consed name or identifier.  */
};


/* Structure and hash-table used to share identifiers or names.  */
struct state_ident_st
{
  /* TODO: We could improve the parser by reserving identifiers for
     state keywords and adding a keyword number for them.  That would
     mean adding another field in this state_ident_st struct.  */
  char stid_name[1];		/* actually bigger & null terminated */
};
static htab_t state_ident_tab;


/* The state_token_st structure is for lexical tokens in the read
   state file.  The stok_kind field discriminates the union.  Tokens
   are allocated by peek_state_token which calls read_a_state_token
   which allocate them.  Tokens are freed by calls to
   next_state_tokens.  Token are organized in a FIFO look-ahead queue
   filled by peek_state_token.  */
struct state_token_st
{
  enum state_token_en stok_kind;	/* the lexical kind
					   discriminates the stok_un
					   union  */
  int stok_line;			/* the line number */
  int stok_col;				/* the column number */
  const char *stok_file;		/* the file path */
  struct state_token_st *stok_next;	/* the next token in the
					   queue, when peeked */
  union		                        /* discriminated by stok_kind! */
  {
    int stok_num;			/* when STOK_INTEGER */
    char stok_string[1];		/* when STOK_STRING, actual size is
					   bigger and null terminated */
    struct state_ident_st *stok_ident;	/* when STOK_IDENT */
    void *stok_ptr;		        /* null otherwise */
  }
  stok_un;
};




#define NULL_STATE_TOKEN (struct state_token_st*)0

/* the state_token pointer contains the leftmost current token.  The
   tokens are organized in a linked queue, using stok_next, for token
   look-ahead.  */
struct state_token_st *state_token = NULL_STATE_TOKEN;

/* Used by the reading lexer.  */
static FILE *state_file;
static const char *state_path = NULL;
static int state_line = 0;
static long state_bol = 0;	/* offset of beginning of line */

/* A class for writing out s-expressions, keeping track of newlines and
   nested indentation.  */
class s_expr_writer
{
public:
  s_expr_writer ();

  void write_new_line ();
  void write_any_indent (int leading_spaces);

  void begin_s_expr (const char *tag);
  void end_s_expr ();

private:
  int m_indent_amount;
  int m_had_recent_newline;
}; // class s_expr_writer

/* A class for writing out "gtype.state".  */
class state_writer : public s_expr_writer
{
public:
  state_writer ();

private:
  void write_state_fileloc (struct fileloc *floc);
  void write_state_fields (pair_p fields);
  void write_state_a_string (const char *s);
  void write_state_string_option (options_p current);
  void write_state_type_option (options_p current);
  void write_state_nested_option (options_p current);
  void write_state_option (options_p current);
  void write_state_options (options_p opt);
  void write_state_lang_bitmap (lang_bitmap bitmap);
  void write_state_version (const char *version);
  void write_state_scalar_type (type_p current);
  void write_state_string_type (type_p current);
  void write_state_undefined_type (type_p current);
  void write_state_struct_union_type (type_p current, const char *kindstr);
  void write_state_struct_type (type_p current);
  void write_state_user_struct_type (type_p current);
  void write_state_union_type (type_p current);
  void write_state_lang_struct_type (type_p current);
  void write_state_param_struct_type (type_p current);
  void write_state_pointer_type (type_p current);
  void write_state_array_type (type_p current);
  void write_state_gc_used (enum gc_used_enum gus);
  void write_state_common_type_content (type_p current);
  void write_state_type (type_p current);
  void write_state_pair (pair_p current);
  int write_state_pair_list (pair_p list);
  void write_state_typedefs (void);
  void write_state_structures (void);
  void write_state_param_structs (void);
  void write_state_variables (void);
  void write_state_srcdir (void);
  void write_state_files_list (void);
  void write_state_languages (void);

  friend void write_state (const char *state_path);

private:
  /* Counter of written types.  */
  int m_state_written_type_count;
}; // class state_writer


/* class s_expr_writer's trivial constructor.  */
s_expr_writer::s_expr_writer ()
  : m_indent_amount (0),
    m_had_recent_newline (0)
{
}

/* Write a newline to the output file, merging adjacent newlines.  */
void
s_expr_writer::write_new_line (void)
{
  /* Don't add a newline if we've just had one.  */
  if (!m_had_recent_newline)
    {
      fprintf (state_file, "\n");
      m_had_recent_newline = 1;
    }
}

/* If we've just had a newline, write the indentation amount, potentially
   omitting some spaces.

   LEADING_SPACES exists to support code that writes strings with leading
   spaces (e.g " foo") which might occur within a line, or could be the first
   thing on a line.  By passing leading_spaces == 1, when such a string is the
   first thing on a line, write_any_indent () swallows the successive
   leading spaces into the indentation so that the "foo" begins at the expected
   column.  */
void
s_expr_writer::write_any_indent (int leading_spaces)
{
  int i;
  int amount = m_indent_amount - leading_spaces;
  if (m_had_recent_newline)
    for (i = 0; i < amount; i++)
      fprintf (state_file, " ");
  m_had_recent_newline = 0;
}

/* Write the beginning of a new s-expresion e.g. "(!foo "
   The writer automatically adds whitespace to show the hierarchical
   structure of the expressions, so each one starts on a new line,
   and any within it will be at an increased indentation level.  */
void
s_expr_writer::begin_s_expr (const char *tag)
{
  write_new_line ();
  write_any_indent (0);
  fprintf (state_file, "(!%s ", tag);
  m_indent_amount++;
}

/* Write out the end of an s-expression: any necssessary indentation,
   a closing parenthesis, and a new line.  */
void
s_expr_writer::end_s_expr (void)
{
  m_indent_amount--;
  write_any_indent (0);
  fprintf (state_file, ")");
  write_new_line ();
}


/* class state_writer's trivial constructor.  */
state_writer::state_writer ()
  : s_expr_writer (),
    m_state_written_type_count (0)
{
}


/* Fatal error messages when reading the state.  They are extremely
   unlikely, and only appear when this gengtype-state.c file is buggy,
   or when reading a gengtype state which was not generated by the
   same version of gengtype or GCC.  */


/* Fatal message while reading state.  */
static inline void 
fatal_reading_state (struct state_token_st* tok, const char*msg)
{
  if (tok)
    fatal ("%s:%d:%d: Invalid state file; %s",
	   tok->stok_file, tok->stok_line, tok->stok_col, 
	   msg); 
  else
    fatal ("%s:%d: Invalid state file; %s", 
	   state_path, state_line, msg);
}


/* Fatal printf-like message while reading state.  This can't be a
   function, because there is no way to pass a va_arg to a variant of
   fatal.  */
#define fatal_reading_state_printf(Tok,Fmt,...) do {	\
    struct state_token_st* badtok = Tok;		\
    if (badtok)						\
      fatal ("%s:%d:%d: Invalid state file; " Fmt,	\
	      badtok->stok_file,			\
	      badtok->stok_line,			\
	      badtok->stok_col, __VA_ARGS__);		\
    else						\
      fatal ("%s:%d: Invalid state file; " Fmt,		\
	     state_path, state_line, __VA_ARGS__);	\
  } while (0)


/* Find or allocate an identifier in our name hash table.  */
static struct state_ident_st *
state_ident_by_name (const char *name, enum insert_option optins)
{
  PTR *slot = NULL;
  int namlen = 0;
  struct state_ident_st *stid = NULL;

  if (!name || !name[0])
    return NULL;

  slot = htab_find_slot (state_ident_tab, name, optins);
  if (!slot)
    return NULL;

  namlen = strlen (name);
  stid =
    (struct state_ident_st *) xmalloc (sizeof (struct state_ident_st) +
				       namlen);
  memset (stid, 0, sizeof (struct state_ident_st) + namlen);
  strcpy (stid->stid_name, name);
  *slot = stid;

  return stid;
}

/* Our token lexer is heavily inspired by MELT's lexer, and share some
   code with the file gcc/melt-runtime.c of the GCC MELT branch!  We
   really want the gengtype state to be easily parsable by MELT.  This
   is a usual lispy lexing routine, dealing with spaces and comments,
   numbers, parenthesis, names, strings.  */
static struct state_token_st *
read_a_state_token (void)
{
  int c = 0;
  long curoff = 0;
  struct state_token_st *tk = NULL;

 again: /* Read again, e.g. after a comment or spaces.  */
  c = getc (state_file);
  if (c == EOF)
    return NULL;

  /* Handle spaces, count lines.  */
  if (c == '\n')
    {
      state_line++;
      state_bol = curoff = ftell (state_file);
      goto again;
    };
  if (ISSPACE (c))
    goto again;
  /* Skip comments starting with semi-colon.  */
  if (c == ';')
    {	
      do
	{
	  c = getc (state_file);
	}
      while (c > 0 && c != '\n');
      if (c == '\n')
	{
	  state_line++;
	  state_bol = curoff = ftell (state_file);
	}
      goto again;
    };
  /* Read signed numbers.  */
  if (ISDIGIT (c) || c == '-' || c == '+')
    {				/* number */
      int n = 0;
      ungetc (c, state_file);
      curoff = ftell (state_file);
      if (fscanf (state_file, "%d", &n) <= 0)
	fatal_reading_state (NULL_STATE_TOKEN, "Lexical error in number");
      tk = XCNEW (struct state_token_st);
      tk->stok_kind = STOK_INTEGER;
      tk->stok_line = state_line;
      tk->stok_col = curoff - state_bol;
      tk->stok_file = state_path;
      tk->stok_next = NULL;
      tk->stok_un.stok_num = n;

      return tk;
    }
  /* Read an opening left parenthesis.  */
  else if (c == '(')
    {
      curoff = ftell (state_file);
      tk = XCNEW (struct state_token_st);
      tk->stok_kind = STOK_LEFTPAR;
      tk->stok_line = state_line;
      tk->stok_col = curoff - state_bol;
      tk->stok_file = state_path;
      tk->stok_next = NULL;

      return tk;
    }
  /* Read an closing right parenthesis.  */
  else if (c == ')')
    {
      curoff = ftell (state_file);
      tk = XCNEW (struct state_token_st);
      tk->stok_kind = STOK_RIGHTPAR;
      tk->stok_line = state_line;
      tk->stok_col = curoff - state_bol;
      tk->stok_file = state_path;
      tk->stok_next = NULL;

      return tk;
    }
  /* Read identifiers, using an obstack.  */
  else if (ISALPHA (c) || c == '_' || c == '$' || c == '!' || c == '#')
    {
      struct obstack id_obstack;
      struct state_ident_st *sid = NULL;
      char *ids = NULL;
      obstack_init (&id_obstack);
      curoff = ftell (state_file);
      while (ISALNUM (c) || c == '_' || c == '$' || c == '!' || c == '#')
	{
	  obstack_1grow (&id_obstack, c);
	  c = getc (state_file);
	  if (c < 0)
	    break;
	};
      if (c >= 0)
	ungetc (c, state_file);
      obstack_1grow (&id_obstack, (char) 0);
      ids = XOBFINISH (&id_obstack, char *);
      sid = state_ident_by_name (ids, INSERT);
      obstack_free (&id_obstack, NULL);
      ids = NULL;
      tk = XCNEW (struct state_token_st);
      tk->stok_kind = STOK_NAME;
      tk->stok_line = state_line;
      tk->stok_col = curoff - state_bol;
      tk->stok_file = state_path;
      tk->stok_next = NULL;
      tk->stok_un.stok_ident = sid;

      return tk;
    }
  /* Read a string, dealing with escape sequences a la C! */
  else if (c == '"')
    {
      char *cstr = NULL;
      int cslen = 0;
      struct obstack bstring_obstack;
      obstack_init (&bstring_obstack);
      curoff = ftell (state_file);
      while ((c = getc (state_file)) != '"' && c >= 0)
	{
	  if (ISPRINT (c) && c != '\\')
	    obstack_1grow (&bstring_obstack, (char) c);
	  else if (ISSPACE (c) && c != '\n')
	    obstack_1grow (&bstring_obstack, (char) c);
	  else if (c == '\\')
	    {
	      c = getc (state_file);
	      switch (c)
		{
		case 'a':
		  obstack_1grow (&bstring_obstack, '\a');
		  c = getc (state_file);
		  break;
		case 'b':
		  obstack_1grow (&bstring_obstack, '\b');
		  c = getc (state_file);
		  break;
		case 't':
		  obstack_1grow (&bstring_obstack, '\t');
		  c = getc (state_file);
		  break;
		case 'n':
		  obstack_1grow (&bstring_obstack, '\n');
		  c = getc (state_file);
		  break;
		case 'v':
		  obstack_1grow (&bstring_obstack, '\v');
		  c = getc (state_file);
		  break;
		case 'f':
		  obstack_1grow (&bstring_obstack, '\f');
		  c = getc (state_file);
		  break;
		case 'r':
		  obstack_1grow (&bstring_obstack, '\r');
		  c = getc (state_file);
		  break;
		case '"':
		  obstack_1grow (&bstring_obstack, '\"');
		  c = getc (state_file);
		  break;
		case '\\':
		  obstack_1grow (&bstring_obstack, '\\');
		  c = getc (state_file);
		  break;
		case ' ':
		  obstack_1grow (&bstring_obstack, ' ');
		  c = getc (state_file);
		  break;
		case 'x':
		  {
		    unsigned int cx = 0;
		    if (fscanf (state_file, "%02x", &cx) > 0 && cx > 0)
		      obstack_1grow (&bstring_obstack, cx);
		    else
		      fatal_reading_state
			(NULL_STATE_TOKEN,
			 "Lexical error in string hex escape");
		    c = getc (state_file);
		    break;
		  }
		default:
		  fatal_reading_state
		    (NULL_STATE_TOKEN,
		     "Lexical error - unknown string escape");
		}
	    }
	  else
	    fatal_reading_state (NULL_STATE_TOKEN, "Lexical error...");
	};
      if (c != '"')
	fatal_reading_state (NULL_STATE_TOKEN, "Unterminated string");
      obstack_1grow (&bstring_obstack, '\0');
      cstr = XOBFINISH (&bstring_obstack, char *);
      cslen = strlen (cstr);
      tk = (struct state_token_st *)
	xcalloc (sizeof (struct state_token_st) + cslen, 1);
      tk->stok_kind = STOK_STRING;
      tk->stok_line = state_line;
      tk->stok_col = curoff - state_bol;
      tk->stok_file = state_path;
      tk->stok_next = NULL;
      strcpy (tk->stok_un.stok_string, cstr);
      obstack_free (&bstring_obstack, NULL);

      return tk;
    }
  /* Got an unexpected character.  */
  fatal_reading_state_printf
    (NULL_STATE_TOKEN,
     "Lexical error at offset %ld - bad character \\%03o = '%c'",
     ftell (state_file), c, c);
}

/* Used for lexical look-ahead.  Retrieves the lexical token of rank
   DEPTH, starting with 0 when reading the state file.  Gives null on
   end of file.  */
static struct state_token_st *
peek_state_token (int depth)
{
  int remdepth = depth;
  struct state_token_st **ptoken = &state_token;
  struct state_token_st *tok = NULL;

  while (remdepth >= 0)
    {
      if (*ptoken == NULL)
	{
	  *ptoken = tok = read_a_state_token ();
	  if (tok == NULL)
	    return NULL;
	}
      tok = *ptoken;
      ptoken = &((*ptoken)->stok_next);
      remdepth--;
    }

  return tok;
}

/* Consume the next DEPTH tokens and free them.  */
static void
next_state_tokens (int depth)
{
  struct state_token_st *n;

  while (depth > 0)
    {
      if (state_token != NULL)
	{
	  n = state_token->stok_next;
	  free (state_token);
	  state_token = n;
	}
      else
	fatal_reading_state (NULL_STATE_TOKEN, "Tokens stack empty");

      depth--;
    }
}

/* Safely retrieve the lexical kind of a token.  */
static inline enum state_token_en
state_token_kind (struct state_token_st *p)
{
  if (p == NULL)
    return STOK_NONE;
  else
    return p->stok_kind;
}

/* Test if a token is a given name i.e. an identifier.  */
static inline bool
state_token_is_name (struct state_token_st *p, const char *name)
{
  if (p == NULL)
    return false;

  if (p->stok_kind != STOK_NAME)
    return false;

  return !strcmp (p->stok_un.stok_ident->stid_name, name);
}


/* Following routines are useful for serializing datas.
 *
 * We want to serialize :
 *          - typedefs list
 *          - structures list
 *          - param_structs list
 *          - variables list
 *
 * So, we have one routine for each kind of data.  The main writing
 * routine is write_state.  The main reading routine is
 * read_state.  Most writing routines write_state_FOO have a
 * corresponding reading routine read_state_FOO.  Reading is done in a
 * recursive descending way, and any read error is fatal.
 */

/* When reading the state, we need to remember the previously seen
   types by their state_number, since GTY-ed types are usually
   shared.  */
static htab_t state_seen_types;

/* Return the length of a linked list made of pairs.  */
static int pair_list_length (pair_p list);

/* Compute the length of a list of pairs, starting from the first
   one.  */
static int
pair_list_length (pair_p list)
{
  int nbpair = 0;
  pair_p l = NULL;
  for (l = list; l; l = l->next)
    nbpair++;
  return nbpair;
}

/* Write a file location.  Files relative to $(srcdir) are quite
   frequent and are handled specially.  This ensures that two gengtype
   state file-s produced by gengtype on the same GCC source tree are
   very similar and can be reasonably compared with diff, even if the
   two GCC source trees have different absolute paths.  */
void
state_writer::write_state_fileloc (struct fileloc *floc)
{

  if (floc != NULL && floc->line > 0)
    {
      const char *srcrelpath = NULL;
      gcc_assert (floc->file != NULL);
      /* Most of the files are inside $(srcdir) so it is worth to
         handle them specially.  */
      srcrelpath = get_file_srcdir_relative_path (floc->file);
      if (srcrelpath != NULL)
	{
	  begin_s_expr ("srcfileloc");
	  write_state_a_string (srcrelpath);
	}
      else
	{
	  begin_s_expr ("fileloc");
	  write_state_a_string (get_input_file_name (floc->file));
	}
      fprintf (state_file, " %d", floc->line);
      end_s_expr ();
    }
  else
    fprintf (state_file, "nil ");
}

/* Write a list of fields.  */
void
state_writer::write_state_fields (pair_p fields)
{
  int nbfields = pair_list_length (fields);
  int nbpairs = 0;
  begin_s_expr ("fields");
  fprintf (state_file, "%d ", nbfields);
  nbpairs = write_state_pair_list (fields);
  gcc_assert (nbpairs == nbfields);
  end_s_expr ();
}

/* Write a null-terminated string in our lexical convention, very
   similar to the convention of C.  */
void
state_writer::write_state_a_string (const char *s)
{
  char c;

  write_any_indent (1);

  fputs (" \"", state_file);
  for (; *s != 0; s++)
    {
      c = *s;
      switch (c)
	{
	case '\a':
	  fputs ("\\a", state_file);
	  break;
	case '\b':
	  fputs ("\\b", state_file);
	  break;
	case '\t':
	  fputs ("\\t", state_file);
	  break;
	case '\n':
	  fputs ("\\n", state_file);
	  break;
	case '\v':
	  fputs ("\\v", state_file);
	  break;
	case '\f':
	  fputs ("\\f", state_file);
	  break;
	case '\r':
	  fputs ("\\r", state_file);
	  break;
	case '\"':
	  fputs ("\\\"", state_file);
	  break;
	case '\\':
	  fputs ("\\\\", state_file);
	  break;
	default:
	  if (ISPRINT (c))
	    putc (c, state_file);
	  else
	    fprintf (state_file, "\\x%02x", (unsigned) c);
	}
    }
  fputs ("\"", state_file);
}

/* Our option-s have three kinds, each with its writer.  */
void
state_writer::write_state_string_option (options_p current)
{
  write_any_indent (0);
  fprintf (state_file, "string ");
  if (current->info.string != NULL)
    write_state_a_string (current->info.string);
  else
    fprintf (state_file, " nil ");
}

void
state_writer::write_state_type_option (options_p current)
{
  write_any_indent (0);
  fprintf (state_file, "type ");
  write_state_type (current->info.type);
}

void
state_writer::write_state_nested_option (options_p current)
{
  write_any_indent (0);
  fprintf (state_file, "nested ");
  write_state_type (current->info.nested->type);
  if (current->info.nested->convert_from != NULL)
    write_state_a_string (current->info.nested->convert_from);
  else
    {
      write_any_indent (1);
      fprintf (state_file, " nil ");
    }

  if (current->info.nested->convert_to != NULL)
    write_state_a_string (current->info.nested->convert_to);
  else
    {
      write_any_indent (1);
      fprintf (state_file, " nil ");
    }
}

void
state_writer::write_state_option (options_p current)
{
  begin_s_expr ("option");

  write_any_indent (0);
  if (current->name != NULL)
    fprintf (state_file, "%s ", current->name);
  else
    fprintf (state_file, "nil ");

  switch (current->kind)
    {
    case OPTION_STRING:
      write_state_string_option (current);
      break;
    case OPTION_TYPE:
      write_state_type_option (current);
      break;
    case OPTION_NESTED:
      write_state_nested_option (current);
      break;
    default:
      fatal ("Option tag unknown");
    }

  /* Terminate the "option" s-expression.  */
  end_s_expr ();
}



/* Write a list of GTY options.  */
void
state_writer::write_state_options (options_p opt)
{
  options_p current;

  if (opt == NULL)
    {
	write_any_indent (0);
	fprintf (state_file, "nil ");
      return;
    }

  begin_s_expr ("options");
  for (current = opt; current != NULL; current = current->next)
      write_state_option (current);
  end_s_expr ();
}


/* Write a bitmap representing a set of GCC front-end languages.  */
void
state_writer::write_state_lang_bitmap (lang_bitmap bitmap)
{
  write_any_indent (0);
  fprintf (state_file, "%d ", (int) bitmap);
}

/* Write version information.  */
void
state_writer::write_state_version (const char *version)
{
  begin_s_expr ("version");
  write_state_a_string (version);
  end_s_expr ();
}

/* Write a scalar type.  We have only two of these.  */
void
state_writer::write_state_scalar_type (type_p current)
{
  write_any_indent (0);
  if (current == &scalar_nonchar)
    fprintf (state_file, "scalar_nonchar ");
  else if (current == &scalar_char)
    fprintf (state_file, "scalar_char ");
  else
    fatal ("Unexpected type in write_state_scalar_type");

  write_state_common_type_content (current);
}

/* Write the string type.  There is only one such thing! */
void
state_writer::write_state_string_type (type_p current)
{
  if (current == &string_type)
    {
      write_any_indent (0);
      fprintf (state_file, "string ");
      write_state_common_type_content (current);
    }
  else
    fatal ("Unexpected type in write_state_string_type");
}

/* Write an undefined type.  */
void
state_writer::write_state_undefined_type (type_p current)
{
  DBGPRINTF ("undefined type @ %p #%d '%s'", (void *) current,
	     current->state_number, current->u.s.tag);
  write_any_indent (0);
  fprintf (state_file, "undefined ");
  gcc_assert (current->gc_used == GC_UNUSED);
  write_state_common_type_content (current);
  if (current->u.s.tag != NULL)
    write_state_a_string (current->u.s.tag);
  else
    {
      write_any_indent (0);
      fprintf (state_file, "nil");
    }

  write_state_fileloc (type_lineloc (current));
}


/* Common code to write structure like types.  */
void
state_writer::write_state_struct_union_type (type_p current,
					     const char *kindstr)
{
  DBGPRINTF ("%s type @ %p #%d '%s'", kindstr, (void *) current,
	     current->state_number, current->u.s.tag);
  write_any_indent (0);
  fprintf (state_file, "%s ", kindstr);
  write_state_common_type_content (current);
  if (current->u.s.tag != NULL)
    write_state_a_string (current->u.s.tag);
  else
    {
      write_any_indent (0);
      fprintf (state_file, "nil");
    }

  write_state_fileloc (type_lineloc (current));
  write_state_fields (current->u.s.fields);
  write_state_options (current->u.s.opt);
  write_state_lang_bitmap (current->u.s.bitmap);
}


/* Write a GTY struct type.  */
void
state_writer::write_state_struct_type (type_p current)
{
  write_state_struct_union_type (current, "struct");
  write_state_type (current->u.s.lang_struct);
  write_state_type (current->u.s.base_class);
}

/* Write a GTY user-defined struct type.  */
void
state_writer::write_state_user_struct_type (type_p current)
{
  DBGPRINTF ("user_struct type @ %p #%d '%s'", (void *) current,
	     current->state_number, current->u.s.tag);
  write_any_indent (0);
  fprintf (state_file, "user_struct ");
  write_state_common_type_content (current);
  if (current->u.s.tag != NULL)
    write_state_a_string (current->u.s.tag);
  else
    {
      write_any_indent (0);
      fprintf (state_file, "nil");
    }
  write_state_fileloc (type_lineloc (current));
  write_state_fields (current->u.s.fields);
}

/* write a GTY union type.  */
void
state_writer::write_state_union_type (type_p current)
{
  write_state_struct_union_type (current, "union");
  write_state_type (current->u.s.lang_struct);
}

/* Write a lang_struct type.  This is tricky and was painful to debug,
   we deal with the next field specifically within their lang_struct
   subfield, which points to a linked list of homonumous types.
   Change this function with extreme care, see also
   read_state_lang_struct_type.  */
void
state_writer::write_state_lang_struct_type (type_p current)
{
  int nbhomontype = 0;
  type_p hty = NULL;
  const char *homoname = 0;
  write_state_struct_union_type (current, "lang_struct");
  /* lang_struct-ures are particularly tricky, since their
     u.s.lang_struct field gives a list of homonymous struct-s or
     union-s! */
  DBGPRINTF ("lang_struct @ %p #%d", (void *) current, current->state_number);
  for (hty = current->u.s.lang_struct; hty != NULL; hty = hty->next)
    {
      nbhomontype++;
      DBGPRINTF ("homonymous #%d hty @ %p #%d '%s'", nbhomontype,
		 (void *) hty, hty->state_number, hty->u.s.tag);
      /* Every member of the homonymous list should have the same tag.  */
      gcc_assert (union_or_struct_p (hty));
      gcc_assert (hty->u.s.lang_struct == current);
      if (!homoname)
	homoname = hty->u.s.tag;
      gcc_assert (strcmp (homoname, hty->u.s.tag) == 0);
    }
  begin_s_expr ("homotypes");
  fprintf (state_file, "%d", nbhomontype);
  for (hty = current->u.s.lang_struct; hty != NULL; hty = hty->next)
    write_state_type (hty);
  end_s_expr ();
}

/* Write a parametrized structure GTY type.  */
void
state_writer::write_state_param_struct_type (type_p current)
{
  int i;

  write_any_indent (0);
  fprintf (state_file, "param_struct ");
  write_state_common_type_content (current);
  write_state_type (current->u.param_struct.stru);
  for (i = 0; i < NUM_PARAM; i++)
    {
      if (current->u.param_struct.param[i] != NULL)
	write_state_type (current->u.param_struct.param[i]);
      else
	{
	  write_any_indent (0);
	  fprintf (state_file, "nil ");
	}
    }
  write_state_fileloc (&current->u.param_struct.line);
}

/* Write a pointer type.  */
void
state_writer::write_state_pointer_type (type_p current)
{
  write_any_indent (0);
  fprintf (state_file, "pointer ");
  write_state_common_type_content (current);
  write_state_type (current->u.p);
}

/* Write an array type.  */
void
state_writer::write_state_array_type (type_p current)
{
  write_any_indent (0);
  fprintf (state_file, "array ");
  write_state_common_type_content (current);
  if (current->u.a.len != NULL)
    write_state_a_string (current->u.a.len);
  else
    {
      write_any_indent (1);
      fprintf (state_file, " nil");
    }

  write_any_indent (1);
  fprintf (state_file, " ");
  write_state_type (current->u.a.p);
}

/* Write the gc_used information.  */
void
state_writer::write_state_gc_used (enum gc_used_enum gus)
{
  write_any_indent (1);
  switch (gus)
    {
    case GC_UNUSED:
      fprintf (state_file, " gc_unused");
      break;
    case GC_USED:
      fprintf (state_file, " gc_used");
      break;
    case GC_MAYBE_POINTED_TO:
      fprintf (state_file, " gc_maybe_pointed_to");
      break;
    case GC_POINTED_TO:
      fprintf (state_file, " gc_pointed_to");
      break;
    default:
      gcc_unreachable ();
    }
}

/* Utility routine to write the common content of all types.  Notice
   that the next field is *not* written on purpose.  */
void
state_writer::write_state_common_type_content (type_p current)
{
  write_any_indent (0);
  fprintf (state_file, "%d ", current->state_number);
  /* We do not write the next type, because list of types are
     explicitly written.  However, lang_struct are special in that
     respect.  See function write_state_lang_struct_type for more.  */
  write_state_type (current->pointer_to);
  write_state_gc_used (current->gc_used);
}


/* The important and recursive routine writing GTY types as understood
   by gengtype.  Types which have a positive state_number have already
   been seen and written.  */
void
state_writer::write_state_type (type_p current)
{
  write_any_indent (0);
  if (current == NULL)
    {
      fprintf (state_file, "nil ");
      return;
    }

  begin_s_expr ("type");

  if (current->state_number > 0)
    {
      write_any_indent (0);
      fprintf (state_file, "already_seen %d", current->state_number);
    }
  else
    {
      m_state_written_type_count++;
      DBGPRINTF ("writing type #%d @%p old number %d", m_state_written_type_count,
		 (void *) current, current->state_number);
      current->state_number = m_state_written_type_count;
      switch (current->kind)
	{
	case TYPE_NONE:
	  gcc_unreachable ();
	case TYPE_UNDEFINED:
	  write_state_undefined_type (current);
	  break;
	case TYPE_STRUCT:
	  write_state_struct_type (current);
	  break;
	case TYPE_USER_STRUCT:
	  write_state_user_struct_type (current);
	  break;
	case TYPE_UNION:
	  write_state_union_type (current);
	  break;
	case TYPE_POINTER:
	  write_state_pointer_type (current);
	  break;
	case TYPE_ARRAY:
	  write_state_array_type (current);
	  break;
	case TYPE_LANG_STRUCT:
	  write_state_lang_struct_type (current);
	  break;
	case TYPE_PARAM_STRUCT:
	  write_state_param_struct_type (current);
	  break;
	case TYPE_SCALAR:
	  write_state_scalar_type (current);
	  break;
	case TYPE_STRING:
	  write_state_string_type (current);
	  break;
	}
    }

  /* Terminate the "type" s-expression.  */
  end_s_expr ();
}


/* Write a pair.  */
void
state_writer::write_state_pair (pair_p current)
{
  if (current == NULL)
    {
      write_any_indent (0);
      fprintf (state_file, "nil)");
      return;
    }

  begin_s_expr ("pair");

  if (current->name != NULL)
    write_state_a_string (current->name);
  else
    write_state_a_string ("nil");

  write_state_type (current->type);
  write_state_fileloc (&(current->line));
  write_state_options (current->opt);

  /* Terminate the "pair" s-expression.  */
  end_s_expr ();
}

/* Write a pair list and return the number of pairs written.  */
int
state_writer::write_state_pair_list (pair_p list)
{
  int nbpair = 0;
  pair_p current;

  for (current = list; current != NULL; current = current->next)
    {
      write_state_pair (current);
      nbpair++;
    }
  return nbpair;

}

/* When writing imported linked lists, like typedefs, structures,
   param_structs, ... we count their length first and write it.  These
   eases the reading, and enables an extra verification on the number
   of actually read items.  */

/* Write our typedefs.  */
void
state_writer::write_state_typedefs (void)
{
  int nbtypedefs = pair_list_length (typedefs);
  int nbpairs = 0;
  begin_s_expr ("typedefs");
  fprintf (state_file, "%d", nbtypedefs);
  nbpairs = write_state_pair_list (typedefs);
  gcc_assert (nbpairs == nbtypedefs);
  end_s_expr ();
  if (verbosity_level >= 2)
    printf ("%s wrote %d typedefs\n", progname, nbtypedefs);
}

/* Write our structures.  */
void
state_writer::write_state_structures (void)
{
  int nbstruct = 0;
  type_p current;

  for (current = structures; current != NULL; current = current->next)
    nbstruct++;

  begin_s_expr ("structures");
  fprintf (state_file, "%d", nbstruct);

  for (current = structures; current != NULL; current = current->next)
    {
      write_new_line ();
      write_state_type (current);
    }

  /* Terminate the "structures" s-expression.  */
  end_s_expr ();
  if (verbosity_level >= 2)
    printf ("%s wrote %d structures in state\n", progname, nbstruct);
}

/* Write our param_struct-s.  */
void
state_writer::write_state_param_structs (void)
{
  int nbparamstruct = 0;
  type_p current;

  for (current = param_structs; current != NULL; current = current->next)
    nbparamstruct++;

  begin_s_expr ("param_structs");
  fprintf (state_file, "%d", nbparamstruct);

  for (current = param_structs; current != NULL; current = current->next)
    write_state_type (current);

  end_s_expr ();
}

/* Write our variables.  */
void
state_writer::write_state_variables (void)
{
  int nbvars = pair_list_length (variables);
  int nbpairs = 0;
  begin_s_expr ("variables");
  fprintf (state_file, "%d", nbvars);
  nbpairs = write_state_pair_list (variables);
  gcc_assert (nbpairs == nbvars);
  end_s_expr ();
  if (verbosity_level >= 2)
    printf ("%s wrote %d variables.\n", progname, nbvars);
}

/* Write the source directory.  File locations within the source
   directory have been written specifically.  */
void
state_writer::write_state_srcdir (void)
{
  begin_s_expr ("srcdir");
  write_state_a_string (srcdir);
  end_s_expr ();
}

/* Count and write the list of our files.  */
void
state_writer::write_state_files_list (void)
{
  int i = 0;
  /* Write the list of files with their lang_bitmap.  */
  begin_s_expr ("fileslist");
  fprintf (state_file, "%d", (int) num_gt_files);
  for (i = 0; i < (int) num_gt_files; i++)
    {
      const char *cursrcrelpath = NULL;
      const input_file *curfil = gt_files[i];
      /* Most of the files are inside $(srcdir) so it is worth to
         handle them specially.  */
      cursrcrelpath = get_file_srcdir_relative_path (curfil);
      if (cursrcrelpath)
	{
	  begin_s_expr ("srcfile");
	  fprintf (state_file, "%d ", get_lang_bitmap (curfil));
	  write_state_a_string (cursrcrelpath);
	}
      else
	{
	  begin_s_expr ("file");
	  fprintf (state_file, "%d ", get_lang_bitmap (curfil));
	  write_state_a_string (get_input_file_name (curfil));
	}
      /* Terminate the inner s-expression (either "srcfile" or "file").   */
      end_s_expr ();
    }
  /* Terminate the "fileslist" s-expression.  */
  end_s_expr ();
}

/* Write the list of GCC front-end languages.  */
void
state_writer::write_state_languages (void)
{
  int i = 0;
  begin_s_expr ("languages");
  fprintf (state_file, "%d", (int) num_lang_dirs);
  for (i = 0; i < (int) num_lang_dirs; i++)
    {
      /* Languages names are identifiers, we expect only letters or
         underscores or digits in them.  In particular, C++ is not a
         valid language name, but cp is valid.  */
      fprintf (state_file, " %s", lang_dir_names[i]);
    }
  end_s_expr ();
}

/* Write the trailer.  */
static void
write_state_trailer (void)
{
  /* This test should probably catch IO errors like disk full...  */
  if (fputs ("\n(!endfile)\n", state_file) == EOF)
    fatal ("failed to write state trailer [%s]", xstrerror (errno));
}

/* The write_state routine is the only writing routine called by main
   in gengtype.c.  To avoid messing the state if gengtype is
   interrupted or aborted, we write a temporary file and rename it
   after having written it in totality.  */
void
write_state (const char *state_path)
{
  long statelen = 0;
  time_t now = 0;
  char *temp_state_path = NULL;
  char tempsuffix[40];
  time (&now);

  /* We write a unique temporary file which is renamed when complete
   * only.  So even if gengtype is interrupted, the written state file
   * won't be partially written, since the temporary file is not yet
   * renamed in that case.  */
  memset (tempsuffix, 0, sizeof (tempsuffix));
  snprintf (tempsuffix, sizeof (tempsuffix) - 1, "-%ld-%d.tmp", (long) now,
	    (int) getpid ());
  temp_state_path = concat (state_path, tempsuffix, NULL);
  state_file = fopen (temp_state_path, "w");
  if (state_file == NULL)
    fatal ("Failed to open file %s for writing state: %s",
	   temp_state_path, xstrerror (errno));
  if (verbosity_level >= 3)
    printf ("%s writing state file %s temporarily in %s\n",
	    progname, state_path, temp_state_path);
  /* This is the first line of the state.  Perhaps the file utility
     could know about that, so don't change it often.  */
  fprintf (state_file, ";;;;@@@@ GCC gengtype state\n");
  /* Output a few comments for humans. */
  fprintf (state_file,
	   ";;; DON'T EDIT THIS FILE, since generated by GCC's gengtype\n");
  fprintf (state_file,
	   ";;; The format of this file is tied to a particular version of GCC.\n");
  fprintf (state_file,
	   ";;; Don't parse this file wihout knowing GCC gengtype internals.\n");
  fprintf (state_file,
	   ";;; This file should be parsed by the same %s which wrote it.\n",
	   progname);

  state_writer sw;

  /* The first non-comment significant line gives the version string.  */
  sw.write_state_version (version_string);
  sw.write_state_srcdir ();
  sw.write_state_languages ();
  sw.write_state_files_list ();
  sw.write_state_structures ();
  sw.write_state_typedefs ();
  sw.write_state_param_structs ();
  sw.write_state_variables ();
  write_state_trailer ();
  statelen = ftell (state_file);
  if (ferror (state_file))
    fatal ("output error when writing state file %s [%s]",
	   temp_state_path, xstrerror (errno));
  if (fclose (state_file))
    fatal ("failed to close state file %s [%s]",
	   temp_state_path, xstrerror (errno));
  if (rename (temp_state_path, state_path))
    fatal ("failed to rename %s to state file %s [%s]", temp_state_path,
	   state_path, xstrerror (errno));
  free (temp_state_path);

  if (verbosity_level >= 1)
    printf ("%s wrote state file %s of %ld bytes with %d GTY-ed types\n",
	    progname, state_path, statelen, sw.m_state_written_type_count);

}

/** End of writing routines!  The corresponding reading routines follow.  **/



/* Forward declarations, since some read_state_* functions are
   recursive! */
static void read_state_fileloc (struct fileloc *line);
static void read_state_options (options_p *opt);
static void read_state_type (type_p *current);
static void read_state_pair (pair_p *pair);
/* Return the number of pairs actually read.  */
static int read_state_pair_list (pair_p *list);
static void read_state_fields (pair_p *fields);
static void read_state_common_type_content (type_p current);




/* Record into the state_seen_types hash-table a type which we are
   reading, to enable recursive or circular references to it.  */
static void
record_type (type_p type)
{
  PTR *slot;

  slot = htab_find_slot (state_seen_types, type, INSERT);
  gcc_assert (slot);

  *slot = type;
}

/* Read an already seen type.  */
static void
read_state_already_seen_type (type_p *type)
{
  struct state_token_st *t0 = peek_state_token (0);

  if (state_token_kind (t0) == STOK_INTEGER)
    {
      PTR *slot = NULL;
      struct type loctype = { TYPE_SCALAR, 0, 0, 0, GC_UNUSED, {0} };

      loctype.state_number = t0->stok_un.stok_num;
      slot = htab_find_slot (state_seen_types, &loctype, NO_INSERT);
      if (slot == NULL)
	{
	  fatal_reading_state (t0, "Unknown type");
	}

      next_state_tokens (1);
      *type = (type_p) *slot;
    }
  else
    {
      fatal_reading_state (t0, "Bad seen type");
    }
}


/* Read the scalar_nonchar type.  */
static void
read_state_scalar_nonchar_type (type_p *type)
{
  *type = &scalar_nonchar;
  read_state_common_type_content (*type);
}


/* Read the scalar_char type.  */
static void
read_state_scalar_char_type (type_p *type)
{
  *type = &scalar_char;
  read_state_common_type_content (*type);
}

/* Read the string_type.  */
static void
read_state_string_type (type_p *type)
{
  *type = &string_type;
  read_state_common_type_content (*type);
}


/* Read a lang_bitmap representing a set of GCC front-end languages.  */
static void
read_state_lang_bitmap (lang_bitmap *bitmap)
{
  struct state_token_st *t;

  t = peek_state_token (0);
  if (state_token_kind (t) == STOK_INTEGER)
    {
      *bitmap = t->stok_un.stok_num;
      next_state_tokens (1);
    }
  else
    {
      fatal_reading_state (t, "Bad syntax for bitmap");
    }
}


/* Read an undefined type.  */
static void
read_state_undefined_type (type_p type)
{
  struct state_token_st *t0;

  type->kind = TYPE_UNDEFINED;
  read_state_common_type_content (type);
  t0 = peek_state_token (0);
  if (state_token_kind (t0) == STOK_STRING)
    {
      if (state_token_is_name (t0, "nil"))
	{
	  type->u.s.tag = NULL;
	  DBGPRINTF ("read anonymous undefined type @%p #%d",
		     (void *) type, type->state_number);
	}
      else
	{
	  type->u.s.tag = xstrdup (t0->stok_un.stok_string);
	  DBGPRINTF ("read undefined type @%p #%d '%s'",
		     (void *) type, type->state_number, type->u.s.tag);
	}

      next_state_tokens (1);
      read_state_fileloc (&(type->u.s.line));
    }
  else
    {
      fatal_reading_state (t0, "Bad tag in undefined type");
    }
}


/* Read a GTY-ed struct type.  */
static void
read_state_struct_type (type_p type)
{
  struct state_token_st *t0;

  type->kind = TYPE_STRUCT;
  read_state_common_type_content (type);
  t0 = peek_state_token (0);
  if (state_token_kind (t0) == STOK_STRING)
    {
      if (state_token_is_name (t0, "nil"))
	{
	  type->u.s.tag = NULL;
	  DBGPRINTF ("read anonymous struct type @%p #%d",
		     (void *) type, type->state_number);
	}
      else
	{
	  type->u.s.tag = xstrdup (t0->stok_un.stok_string);
	  DBGPRINTF ("read struct type @%p #%d '%s'",
		     (void *) type, type->state_number, type->u.s.tag);
	}

      next_state_tokens (1);
      read_state_fileloc (&(type->u.s.line));
      read_state_fields (&(type->u.s.fields));
      read_state_options (&(type->u.s.opt));
      read_state_lang_bitmap (&(type->u.s.bitmap));
      read_state_type (&(type->u.s.lang_struct));
      read_state_type (&(type->u.s.base_class));
      if (type->u.s.base_class)
	add_subclass (type->u.s.base_class, type);
    }
  else
    {
      fatal_reading_state (t0, "Bad tag in struct type");
    }
}


/* Read a GTY-ed user-provided struct TYPE.  */

static void
read_state_user_struct_type (type_p type)
{
  struct state_token_st *t0;

  type->kind = TYPE_USER_STRUCT;
  read_state_common_type_content (type);
  t0 = peek_state_token (0);
  if (state_token_kind (t0) == STOK_STRING)
    {
      if (state_token_is_name (t0, "nil"))
	{
	  type->u.s.tag = NULL;
	  DBGPRINTF ("read anonymous struct type @%p #%d",
		     (void *) type, type->state_number);
	}
      else
	{
	  type->u.s.tag = xstrdup (t0->stok_un.stok_string);
	  DBGPRINTF ("read struct type @%p #%d '%s'",
		     (void *) type, type->state_number, type->u.s.tag);
	}

      next_state_tokens (1);
      read_state_fileloc (&(type->u.s.line));
      read_state_fields (&(type->u.s.fields));
    }
  else
    {
      fatal_reading_state (t0, "Bad tag in user-struct type");
    }
}


/* Read a GTY-ed union type.  */
static void
read_state_union_type (type_p type)
{
  struct state_token_st *t0;

  type->kind = TYPE_UNION;
  read_state_common_type_content (type);
  t0 = peek_state_token (0);
  if (state_token_kind (t0) == STOK_STRING)
    {
      if (state_token_is_name (t0, "nil"))
	{
	  type->u.s.tag = NULL;
	  DBGPRINTF ("read anonymous union type @%p #%d",
		     (void *) type, type->state_number);
	}
      else
	{
	  type->u.s.tag = xstrdup (t0->stok_un.stok_string);
	  DBGPRINTF ("read union type @%p #%d '%s'",
		     (void *) type, type->state_number, type->u.s.tag);
	}
      next_state_tokens (1);
      read_state_fileloc (&(type->u.s.line));
      read_state_fields (&(type->u.s.fields));
      read_state_options (&(type->u.s.opt));
      read_state_lang_bitmap (&(type->u.s.bitmap));
      read_state_type (&(type->u.s.lang_struct));
    }
  else
    fatal_reading_state (t0, "Bad tag in union type");
}


/* Read a GTY-ed pointer type.  */
static void
read_state_pointer_type (type_p type)
{
  type->kind = TYPE_POINTER;
  read_state_common_type_content (type);
  DBGPRINTF ("read pointer type @%p #%d", (void *) type, type->state_number);
  read_state_type (&(type->u.p));
}


/* Read a GTY-ed array type.  */
static void
read_state_array_type (type_p type)
{
  struct state_token_st *t0;

  type->kind = TYPE_ARRAY;
  read_state_common_type_content (type);
  t0 = peek_state_token (0);
  if (state_token_kind (t0) == STOK_STRING)
    {
      type->u.a.len = xstrdup (t0->stok_un.stok_string);
      DBGPRINTF ("read array type @%p #%d length '%s'",
		 (void *) type, type->state_number, type->u.a.len);
      next_state_tokens (1);
    }

  else if (state_token_is_name (t0, "nil"))
    {
      type->u.a.len = NULL;
      DBGPRINTF ("read array type @%p #%d without length",
		 (void *) type, type->state_number);
      next_state_tokens (1);
    }

  else
    fatal_reading_state (t0, "Bad array name type");
  read_state_type (&(type->u.a.p));
}



/* Read a lang_struct type for GTY-ed struct-s which depends upon GCC
   front-end languages.  This is a tricky function and it was painful
   to debug.  Change it with extreme care.  See also
   write_state_lang_struct_type.  */
static void
read_state_lang_struct_type (type_p type)
{
  struct state_token_st *t0 = NULL;
  struct state_token_st *t1 = NULL;
  struct state_token_st *t2 = NULL;

  type->kind = TYPE_LANG_STRUCT;
  read_state_common_type_content (type);
  t0 = peek_state_token (0);
  if (state_token_kind (t0) == STOK_STRING)
    {
      if (state_token_is_name (t0, "nil"))
	{
	  DBGPRINTF ("read anonymous lang_struct type @%p #%d",
		     (void *) type, type->state_number);
	  type->u.s.tag = NULL;
	}
      else
	{
	  type->u.s.tag = xstrdup (t0->stok_un.stok_string);
	  DBGPRINTF ("read lang_struct type @%p #%d '%s'",
		     (void *) type, type->state_number, type->u.s.tag);
	}
      next_state_tokens (1);
    }
  else
    fatal_reading_state (t0, "Bad tag in lang struct type");
  read_state_fileloc (&(type->u.s.line));
  read_state_fields (&(type->u.s.fields));
  read_state_options (&(type->u.s.opt));
  read_state_lang_bitmap (&(type->u.s.bitmap));
  /* Within lang_struct-ures, the lang_struct field is a linked list
     of homonymous types! */
  t0 = peek_state_token (0);
  t1 = peek_state_token (1);
  t2 = peek_state_token (2);
  /* Parse (!homotypes <number-types> <type-1> .... <type-n>) */
  if (state_token_kind (t0) == STOK_LEFTPAR
      && state_token_is_name (t1, "!homotypes")
      && state_token_kind (t2) == STOK_INTEGER)
    {
      type_p *prevty = &type->u.s.lang_struct;
      int nbhomotype = t2->stok_un.stok_num;
      int i = 0;
      t0 = t1 = t2 = NULL;
      next_state_tokens (3);
      for (i = 0; i < nbhomotype; i++)
	{
	  read_state_type (prevty);
	  t0 = peek_state_token (0);
	  if (*prevty)
	    prevty = &(*prevty)->next;
	  else
	      fatal_reading_state (t0,
				   "expecting type in homotype list for lang_struct");
	};
      if (state_token_kind (t0) != STOK_RIGHTPAR)
	fatal_reading_state (t0,
			     "expecting ) in homotype list for lang_struct");
      next_state_tokens (1);
    }
  else
    fatal_reading_state (t0, "expecting !homotypes for lang_struct");
}


/* Read a param_struct type for GTY parametrized structures.  */
static void
read_state_param_struct_type (type_p type)
{
  int i;
  struct state_token_st *t0;

  type->kind = TYPE_PARAM_STRUCT;
  read_state_common_type_content (type);
  DBGPRINTF ("read param_struct type @%p #%d",
	     (void *) type, type->state_number);
  read_state_type (&(type->u.param_struct.stru));

  for (i = 0; i < NUM_PARAM; i++)
    {
      t0 = peek_state_token (0);
      if (state_token_is_name (t0, "nil"))
	{
	  type->u.param_struct.param[i] = NULL;
	  next_state_tokens (1);
	}
      else
	read_state_type (&(type->u.param_struct.param[i]));
    }
  read_state_fileloc (&(type->u.param_struct.line));
}


/* Read the gc used information.  */
static void
read_state_gc_used (enum gc_used_enum *pgus)
{
  struct state_token_st *t0 = peek_state_token (0);
  if (state_token_is_name (t0, "gc_unused"))
    *pgus = GC_UNUSED;
  else if (state_token_is_name (t0, "gc_used"))
    *pgus = GC_USED;
  else if (state_token_is_name (t0, "gc_maybe_pointed_to"))
    *pgus = GC_MAYBE_POINTED_TO;
  else if (state_token_is_name (t0, "gc_pointed_to"))
    *pgus = GC_POINTED_TO;
  else
    fatal_reading_state (t0, "invalid gc_used information");
  next_state_tokens (1);
}


/* Utility function to read the common content of types.  */
static void
read_state_common_type_content (type_p current)
{
  struct state_token_st *t0 = peek_state_token (0);

  if (state_token_kind (t0) == STOK_INTEGER)
    {
      current->state_number = t0->stok_un.stok_num;
      next_state_tokens (1);
      record_type (current);
    }
  else
      fatal_reading_state_printf (t0,
				  "Expected integer for state_number line %d",
				  state_line);
  /* We don't read the next field of the type.  */
  read_state_type (&current->pointer_to);
  read_state_gc_used (&current->gc_used);
}


/* Read a GTY-ed type.  */
void
read_state_type (type_p *current)
{
  struct state_token_st *t0 = peek_state_token (0);
  struct state_token_st *t1 = peek_state_token (1);

  if (state_token_kind (t0) == STOK_LEFTPAR &&
      state_token_is_name (t1, "!type"))
    {
      next_state_tokens (2);
      t0 = peek_state_token (0);
      if (state_token_is_name (t0, "already_seen"))
	{
	  next_state_tokens (1);
	  read_state_already_seen_type (current);
	}
      else
	{
	  t0 = peek_state_token (0);

	  if (state_token_is_name (t0, "scalar_nonchar"))
	    {
	      next_state_tokens (1);
	      read_state_scalar_nonchar_type (current);
	    }
	  else if (state_token_is_name (t0, "scalar_char"))
	    {
	      next_state_tokens (1);
	      read_state_scalar_char_type (current);
	    }
	  else if (state_token_is_name (t0, "string"))
	    {
	      next_state_tokens (1);
	      read_state_string_type (current);
	    }
	  else if (state_token_is_name (t0, "undefined"))
	    {
	      *current = XCNEW (struct type);
	      next_state_tokens (1);
	      read_state_undefined_type (*current);
	    }
	  else if (state_token_is_name (t0, "struct"))
	    {
	      *current = XCNEW (struct type);
	      next_state_tokens (1);
	      read_state_struct_type (*current);
	    }
	  else if (state_token_is_name (t0, "union"))
	    {
	      *current = XCNEW (struct type);
	      next_state_tokens (1);
	      read_state_union_type (*current);
	    }
	  else if (state_token_is_name (t0, "lang_struct"))
	    {
	      *current = XCNEW (struct type);
	      next_state_tokens (1);
	      read_state_lang_struct_type (*current);
	    }
	  else if (state_token_is_name (t0, "param_struct"))
	    {
	      *current = XCNEW (struct type);
	      next_state_tokens (1);
	      read_state_param_struct_type (*current);
	    }
	  else if (state_token_is_name (t0, "pointer"))
	    {
	      *current = XCNEW (struct type);
	      next_state_tokens (1);
	      read_state_pointer_type (*current);
	    }
	  else if (state_token_is_name (t0, "array"))
	    {
	      *current = XCNEW (struct type);
	      next_state_tokens (1);
	      read_state_array_type (*current);
	    }
	  else if (state_token_is_name (t0, "user_struct"))
	    {
	      *current = XCNEW (struct type);
	      next_state_tokens (1);
	      read_state_user_struct_type (*current);
	    }
	  else
	    fatal_reading_state (t0, "bad type in (!type");
	}
      t0 = peek_state_token (0);
      if (state_token_kind (t0) != STOK_RIGHTPAR)
	fatal_reading_state (t0, "missing ) in type");
      next_state_tokens (1);
    }
  else if (state_token_is_name (t0, "nil"))
    {
      next_state_tokens (1);
      *current = NULL;
    }
  else
    fatal_reading_state (t0, "bad type syntax");
}


/* Read a file location.  Files within the source directory are dealt
   with specifically.  */
void
read_state_fileloc (struct fileloc *floc)
{
  bool issrcfile = false;
  struct state_token_st *t0 = peek_state_token (0);
  struct state_token_st *t1 = peek_state_token (1);

  gcc_assert (floc != NULL);
  gcc_assert (srcdir != NULL);

  if (state_token_kind (t0) == STOK_LEFTPAR &&
      (state_token_is_name (t1, "!fileloc")
       || (issrcfile = state_token_is_name (t1, "!srcfileloc"))))
    {
      next_state_tokens (2);
      t0 = peek_state_token (0);
      t1 = peek_state_token (1);
      if (state_token_kind (t0) == STOK_STRING &&
	  state_token_kind (t1) == STOK_INTEGER)
	{
	  char *path = t0->stok_un.stok_string;
	  if (issrcfile)
	    {
	      static const char dirsepstr[2] = { DIR_SEPARATOR, (char) 0 };
	      char *fullpath = concat (srcdir, dirsepstr, path, NULL);
	      floc->file = input_file_by_name (fullpath);
	      free (fullpath);
	    }
	  else
	    floc->file = input_file_by_name (path);
	  floc->line = t1->stok_un.stok_num;
	  next_state_tokens (2);
	}
      else
	fatal_reading_state (t0,
			     "Bad fileloc syntax, expected path string and line");
      t0 = peek_state_token (0);
      if (state_token_kind (t0) != STOK_RIGHTPAR)
	fatal_reading_state (t0, "Bad fileloc syntax, expected )");
      next_state_tokens (1);
    }
  else if (state_token_is_name (t0, "nil"))
    {
      next_state_tokens (1);
      floc->file = NULL;
      floc->line = 0;
    }
  else
    fatal_reading_state (t0, "Bad fileloc syntax");
}


/* Read the fields of a GTY-ed type.  */
void
read_state_fields (pair_p *fields)
{
  pair_p tmp = NULL;
  struct state_token_st *t0 = peek_state_token (0);
  struct state_token_st *t1 = peek_state_token (1);
  struct state_token_st *t2 = peek_state_token (2);

  if (state_token_kind (t0) == STOK_LEFTPAR
      && state_token_is_name (t1, "!fields")
      && state_token_kind (t2) == STOK_INTEGER)
    {
      int nbfields = t2->stok_un.stok_num;
      int nbpairs = 0;
      next_state_tokens (3);
      nbpairs = read_state_pair_list (&tmp);
      t0 = peek_state_token (0);
      if (nbpairs != nbfields)
	fatal_reading_state_printf
	  (t0,
	   "Mismatched fields number, expected %d got %d", nbpairs, nbfields);
      if (state_token_kind (t0) == STOK_RIGHTPAR)
	next_state_tokens (1);
      else
	fatal_reading_state (t0, "Bad fields expecting )");
    }

  *fields = tmp;
}


/* Read a string option.  */
static void
read_state_string_option (options_p opt)
{
  struct state_token_st *t0 = peek_state_token (0);
  opt->kind = OPTION_STRING;
  if (state_token_kind (t0) == STOK_STRING)
    {
      opt->info.string = xstrdup (t0->stok_un.stok_string);
      next_state_tokens (1);
    }
  else if (state_token_is_name (t0, "nil"))
    {
      opt->info.string = NULL;
      next_state_tokens (1);
    }
  else
    fatal_reading_state (t0, "Missing name in string option");
}


/* Read a type option.  */
static void
read_state_type_option (options_p opt)
{
  opt->kind = OPTION_TYPE;
  read_state_type (&(opt->info.type));
}


/* Read a nested option.  */
static void
read_state_nested_option (options_p opt)
{
  struct state_token_st *t0;

  opt->info.nested = XCNEW (struct nested_ptr_data);
  opt->kind = OPTION_NESTED;
  read_state_type (&(opt->info.nested->type));
  t0 = peek_state_token (0);
  if (state_token_kind (t0) == STOK_STRING)
    {
      opt->info.nested->convert_from = xstrdup (t0->stok_un.stok_string);
      next_state_tokens (1);
    }
  else if (state_token_is_name (t0, "nil"))
    {
      opt->info.nested->convert_from = NULL;
      next_state_tokens (1);
    }
  else
    fatal_reading_state (t0, "Bad nested convert_from option");

  t0 = peek_state_token (0);
  if (state_token_kind (t0) == STOK_STRING)
    {
      opt->info.nested->convert_to = xstrdup (t0->stok_un.stok_string);
      next_state_tokens (1);
    }
  else if (state_token_is_name (t0, "nil"))
    {
      opt->info.nested->convert_to = NULL;
      next_state_tokens (1);
    }
  else
    fatal_reading_state (t0, "Bad nested convert_from option");
}


/* Read an GTY option.  */
static void
read_state_option (options_p *opt)
{
  struct state_token_st *t0 = peek_state_token (0);
  struct state_token_st *t1 = peek_state_token (1);

  if (state_token_kind (t0) == STOK_LEFTPAR &&
      state_token_is_name (t1, "!option"))
    {
      next_state_tokens (2);
      t0 = peek_state_token (0);
      if (state_token_kind (t0) == STOK_NAME)
	{
	  *opt = XCNEW (struct options);
	  if (state_token_is_name (t0, "nil"))
	    (*opt)->name = NULL;
	  else
	    (*opt)->name = t0->stok_un.stok_ident->stid_name;
	  next_state_tokens (1);
	  t0 = peek_state_token (0);
	  if (state_token_kind (t0) == STOK_NAME)
	    {
	      if (state_token_is_name (t0, "string"))
		{
		  next_state_tokens (1);
		  read_state_string_option (*opt);
		}
	      else if (state_token_is_name (t0, "type"))
		{
		  next_state_tokens (1);
		  read_state_type_option (*opt);
		}
	      else if (state_token_is_name (t0, "nested"))
		{
		  next_state_tokens (1);
		  read_state_nested_option (*opt);
		}
	      else
		fatal_reading_state (t0, "Bad option type");
	      t0 = peek_state_token (0);
	      if (state_token_kind (t0) != STOK_RIGHTPAR)
		fatal_reading_state (t0, "Bad syntax in option, expecting )");

	      next_state_tokens (1);
	    }
	  else
	    fatal_reading_state (t0, "Missing option type");
	}
      else
	fatal_reading_state (t0, "Bad name for option");
    }
  else
    fatal_reading_state (t0, "Bad option, waiting for )");
}

/* Read a list of options.  */
void
read_state_options (options_p *opt)
{
  options_p head = NULL;
  options_p previous = NULL;
  options_p current_option = NULL;
  struct state_token_st *t0 = peek_state_token (0);
  struct state_token_st *t1 = peek_state_token (1);

  if (state_token_kind (t0) == STOK_LEFTPAR &&
      state_token_is_name (t1, "!options"))
    {
      next_state_tokens (2);
      t0 = peek_state_token (0);
      while (state_token_kind (t0) != STOK_RIGHTPAR)
	{
	  read_state_option (&current_option);
	  if (head == NULL)
	    {
	      head = current_option;
	      previous = head;
	    }
	  else
	    {
	      previous->next = current_option;
	      previous = current_option;
	    }
	  t0 = peek_state_token (0);
	}
      next_state_tokens (1);
    }
  else if (state_token_is_name (t0, "nil"))
    {
      next_state_tokens (1);
    }
  else
    fatal_reading_state (t0, "Bad options syntax");

  *opt = head;
}


/* Read a version, and check against the version of the gengtype.  */
static void
read_state_version (const char *version_string)
{
  struct state_token_st *t0 = peek_state_token (0);
  struct state_token_st *t1 = peek_state_token (1);

  if (state_token_kind (t0) == STOK_LEFTPAR &&
      state_token_is_name (t1, "!version"))
    {
      next_state_tokens (2);
      t0 = peek_state_token (0);
      t1 = peek_state_token (1);
      if (state_token_kind (t0) == STOK_STRING &&
	  state_token_kind (t1) == STOK_RIGHTPAR)
	{
	  /* Check that the read version string is the same as current
	     version.  */
	  if (strcmp (version_string, t0->stok_un.stok_string))
	    fatal_reading_state_printf (t0,
					"version string mismatch; expecting %s but got %s",
					version_string,
					t0->stok_un.stok_string);
	  next_state_tokens (2);
	}
      else
	fatal_reading_state (t0, "Missing version or right parenthesis");
    }
  else
    fatal_reading_state (t0, "Bad version syntax");
}


/* Read a pair.  */
void
read_state_pair (pair_p *current)
{
  struct state_token_st *t0 = peek_state_token (0);
  struct state_token_st *t1 = peek_state_token (1);
  if (state_token_kind (t0) == STOK_LEFTPAR &&
      state_token_is_name (t1, "!pair"))
    {
      *current = XCNEW (struct pair);
      next_state_tokens (2);
      t0 = peek_state_token (0);
      if (state_token_kind (t0) == STOK_STRING)
	{
	  if (strcmp (t0->stok_un.stok_string, "nil") == 0)
	    {
	      (*current)->name = NULL;
	    }
	  else
	    {
	      (*current)->name = xstrdup (t0->stok_un.stok_string);
	    }
	  next_state_tokens (1);
	  read_state_type (&((*current)->type));
	  read_state_fileloc (&((*current)->line));
	  read_state_options (&((*current)->opt));;
	  t0 = peek_state_token (0);
	  if (state_token_kind (t0) == STOK_RIGHTPAR)
	    {
	      next_state_tokens (1);
	    }
	  else
	    {
	      fatal_reading_state (t0, "Bad syntax for pair, )");
	    }
	}
      else
	{
	  fatal_reading_state (t0, "Bad name for pair");
	}
    }
  else if (state_token_kind (t0) == STOK_NAME &&
	   state_token_is_name (t0, "nil"))
    {
      next_state_tokens (1);
      *current = NULL;
    }
  else
    fatal_reading_state_printf (t0, "Bad syntax for pair, (!pair %d",
				state_token->stok_kind);
}


/* Return the number of pairs actually read.  */
int
read_state_pair_list (pair_p *list)
{
  int nbpair = 0;
  pair_p head = NULL;
  pair_p previous = NULL;
  pair_p tmp = NULL;
  struct state_token_st *t0 = peek_state_token (0);
  while (t0 && state_token_kind (t0) != STOK_RIGHTPAR)
    {
      read_state_pair (&tmp);
      if (head == NULL)
	{
	  head = tmp;
	  previous = head;
	}
      else
	{
	  previous->next = tmp;
	  previous = tmp;
	}
      t0 = peek_state_token (0);
      nbpair++;
    }

  /* don't consume the ); the caller will eat it.  */
  *list = head;
  return nbpair;
}

/* Read the typedefs.  */
static void
read_state_typedefs (pair_p *typedefs)
{
  int nbtypedefs = 0;
  pair_p list = NULL;
  struct state_token_st *t0 = peek_state_token (0);
  struct state_token_st *t1 = peek_state_token (1);
  struct state_token_st *t2 = peek_state_token (2);

  if (state_token_kind (t0) == STOK_LEFTPAR
      && state_token_is_name (t1, "!typedefs")
      && state_token_kind (t2) == STOK_INTEGER)
    {
      int nbpairs = 0;
      nbtypedefs = t2->stok_un.stok_num;
      next_state_tokens (3);
      nbpairs = read_state_pair_list (&list);
      t0 = peek_state_token (0);
      if (nbpairs != nbtypedefs)
	fatal_reading_state_printf
	  (t0,
	   "invalid number of typedefs, expected %d but got %d",
	   nbtypedefs, nbpairs);
      if (state_token_kind (t0) == STOK_RIGHTPAR)
	next_state_tokens (1);
      else
	fatal_reading_state (t0, "Bad typedefs syntax )");
    }
  else
    fatal_reading_state (t0, "Bad typedefs syntax (!typedefs");

  if (verbosity_level >= 2)
    printf ("%s read %d typedefs from state\n", progname, nbtypedefs);
  *typedefs = list;
}


/* Read the structures.  */
static void
read_state_structures (type_p *structures)
{
  type_p head = NULL;
  type_p previous = NULL;
  type_p tmp;
  int nbstruct = 0, countstruct = 0;
  struct state_token_st *t0 = peek_state_token (0);
  struct state_token_st *t1 = peek_state_token (1);
  struct state_token_st *t2 = peek_state_token (2);

  if (state_token_kind (t0) == STOK_LEFTPAR
      && state_token_is_name (t1, "!structures")
      && state_token_kind (t2) == STOK_INTEGER)
    {
      nbstruct = t2->stok_un.stok_num;
      next_state_tokens (3);
      t0 = peek_state_token (0);
      while (t0 && state_token_kind (t0) != STOK_RIGHTPAR)
	{
	  tmp = NULL;
	  read_state_type (&tmp);
	  countstruct++;
	  if (head == NULL)
	    {
	      head = tmp;
	      previous = head;
	    }
	  else
	    {
	      previous->next = tmp;
	      previous = tmp;
	    }
	  t0 = peek_state_token (0);
	}
      next_state_tokens (1);
    }
  else
    fatal_reading_state (t0, "Bad structures syntax");
  if (countstruct != nbstruct)
    fatal_reading_state_printf (NULL_STATE_TOKEN, 
				"expected %d structures but got %d",
				nbstruct, countstruct);
  if (verbosity_level >= 2)
    printf ("%s read %d structures from state\n", progname, nbstruct);
  *structures = head;
}


/* Read the param_struct-s.  */
static void
read_state_param_structs (type_p *param_structs)
{
  int nbparamstructs = 0;
  int countparamstructs = 0;
  type_p head = NULL;
  type_p previous = NULL;
  type_p tmp;
  struct state_token_st *t0 = peek_state_token (0);
  struct state_token_st *t1 = peek_state_token (1);
  struct state_token_st *t2 = peek_state_token (2);

  if (state_token_kind (t0) == STOK_LEFTPAR
      && state_token_is_name (t1, "!param_structs")
      && state_token_kind (t2) == STOK_INTEGER)
    {
      nbparamstructs = t2->stok_un.stok_num;
      next_state_tokens (3);
      t0 = t1 = t2 = NULL;
      t0 = peek_state_token (0);
      while (state_token_kind (t0) != STOK_RIGHTPAR)
	{
	  tmp = NULL;
	  read_state_type (&tmp);
	  if (head == NULL)
	    {
	      head = tmp;
	      previous = head;
	    }
	  else
	    {
	      previous->next = tmp;
	      previous = tmp;
	    }
	  t0 = peek_state_token (0);
	  countparamstructs++;
	}
      next_state_tokens (1);
    }
  else
    fatal_reading_state (t0, "Bad param_structs syntax");
  t0 = peek_state_token (0);
  if (countparamstructs != nbparamstructs)
    fatal_reading_state_printf
      (t0,
       "invalid number of param_structs expected %d got %d",
       nbparamstructs, countparamstructs);
  *param_structs = head;
}


/* Read the variables.  */
static void
read_state_variables (pair_p *variables)
{
  pair_p list = NULL;
  int nbvars = 0;
  struct state_token_st *t0 = peek_state_token (0);
  struct state_token_st *t1 = peek_state_token (1);
  struct state_token_st *t2 = peek_state_token (2);

  if (state_token_kind (t0) == STOK_LEFTPAR
      && state_token_is_name (t1, "!variables")
      && state_token_kind (t2) == STOK_INTEGER)
    {
      int nbpairs = 0;
      nbvars = t2->stok_un.stok_num;
      next_state_tokens (3);
      nbpairs = read_state_pair_list (&list);
      t0 = peek_state_token (0);
      if (nbpairs != nbvars)
	fatal_reading_state_printf
	  (t0, "Invalid number of variables, expected %d but got %d",
	   nbvars, nbpairs);
      if (state_token_kind (t0) == STOK_RIGHTPAR)
	next_state_tokens (1);
      else
	fatal_reading_state (t0, "Waiting for ) in variables");
    }
  else
    fatal_reading_state (t0, "Bad variables syntax");
  *variables = list;
  if (verbosity_level >= 2)
    printf ("%s read %d variables from state\n", progname, nbvars);
}


/* Read the source directory.  */
static void
read_state_srcdir (void)
{
  struct state_token_st *t0 = peek_state_token (0);
  struct state_token_st *t1 = peek_state_token (1);
  if (state_token_kind (t0) == STOK_LEFTPAR &&
      state_token_is_name (t1, "!srcdir"))
    {
      next_state_tokens (2);
      t0 = peek_state_token (0);
      t1 = peek_state_token (1);
      if (state_token_kind (t0) == STOK_STRING &&
	  state_token_kind (t1) == STOK_RIGHTPAR)
	{
	  srcdir = xstrdup (t0->stok_un.stok_string);
	  srcdir_len = strlen (srcdir);
	  next_state_tokens (2);
	  return;
	}
    }

  fatal_reading_state (t0, "Bad srcdir in state_file");
}


/* Read the sequence of GCC front-end languages.  */
static void
read_state_languages (void)
{
  struct state_token_st *t0 = peek_state_token (0);
  struct state_token_st *t1 = peek_state_token (1);
  struct state_token_st *t2 = peek_state_token (2);
  if (state_token_kind (t0) == STOK_LEFTPAR
      && state_token_is_name (t1, "!languages")
      && state_token_kind (t2) == STOK_INTEGER)
    {
      int i = 0;
      num_lang_dirs = t2->stok_un.stok_num;
      lang_dir_names = XCNEWVEC (const char *, num_lang_dirs);
      next_state_tokens (3);
      t0 = t1 = t2 = NULL;
      for (i = 0; i < (int) num_lang_dirs; i++)
	{
	  t0 = peek_state_token (0);
	  if (state_token_kind (t0) != STOK_NAME)
	    fatal_reading_state (t0, "expecting language name in state file");
	  lang_dir_names[i] = t0->stok_un.stok_ident->stid_name;
	  next_state_tokens (1);
	}
      t0 = peek_state_token (0);
      if (state_token_kind (t0) != STOK_RIGHTPAR)
	fatal_reading_state (t0, "missing ) in languages list of state file");
      next_state_tokens (1);
    }
  else
    fatal_reading_state (t0, "expecting languages list in state file");

}

/* Read the sequence of files.  */
static void
read_state_files_list (void)
{
  struct state_token_st *t0 = peek_state_token (0);
  struct state_token_st *t1 = peek_state_token (1);
  struct state_token_st *t2 = peek_state_token (2);

  if (state_token_kind (t0) == STOK_LEFTPAR
      && state_token_is_name (t1, "!fileslist")
      && state_token_kind (t2) == STOK_INTEGER)
    {
      int i = 0;
      num_gt_files = t2->stok_un.stok_num;
      next_state_tokens (3);
      t0 = t1 = t2 = NULL;
      gt_files = XCNEWVEC (const input_file *, num_gt_files);
      for (i = 0; i < (int) num_gt_files; i++)
	{
	  bool issrcfile = FALSE;
	  t0 = t1 = t2 = NULL;
	  t0 = peek_state_token (0);
	  t1 = peek_state_token (1);
	  t2 = peek_state_token (2);
	  if (state_token_kind (t0) == STOK_LEFTPAR
	      && (state_token_is_name (t1, "!file")
		  || (issrcfile = state_token_is_name (t1, "!srcfile")))
	      && state_token_kind (t2) == STOK_INTEGER)
	    {
	      lang_bitmap bmap = t2->stok_un.stok_num;
	      next_state_tokens (3);
	      t0 = t1 = t2 = NULL;
	      t0 = peek_state_token (0);
	      t1 = peek_state_token (1);
	      if (state_token_kind (t0) == STOK_STRING
		  && state_token_kind (t1) == STOK_RIGHTPAR)
		{
		  const char *fnam = t0->stok_un.stok_string;
		  /* Allocate & fill a gt_file entry with space for the lang_bitmap before! */
		  input_file *curgt = NULL;
		  if (issrcfile)
		    {
		      static const char dirsepstr[2] =
			{ DIR_SEPARATOR, (char) 0 };
		      char *fullpath = concat (srcdir, dirsepstr, fnam, NULL);
		      curgt = input_file_by_name (fullpath);
		      free (fullpath);
		    }
		  else
		    curgt = input_file_by_name (fnam);
		  set_lang_bitmap (curgt, bmap);
		  gt_files[i] = curgt;
		  next_state_tokens (2);
		}
	      else
		fatal_reading_state (t0,
				     "bad file in !fileslist of state file");
	    }
	  else
	    fatal_reading_state (t0,
				 "expecting file in !fileslist of state file");
	};
      t0 = peek_state_token (0);
      if (state_token_kind (t0) != STOK_RIGHTPAR)
	fatal_reading_state (t0, "missing ) for !fileslist in state file");
      next_state_tokens (1);
    }
  else
    fatal_reading_state (t0, "missing !fileslist in state file");
}


/* Read the trailer.  */
static void
read_state_trailer (void)
{
  struct state_token_st *t0 = peek_state_token (0);
  struct state_token_st *t1 = peek_state_token (1);
  struct state_token_st *t2 = peek_state_token (2);

  if (state_token_kind (t0) == STOK_LEFTPAR
      && state_token_is_name (t1, "!endfile")
      && state_token_kind (t2) == STOK_RIGHTPAR)
    next_state_tokens (3);
  else
    fatal_reading_state (t0, "missing !endfile in state file");
}


/* Utility functions for the state_seen_types hash table.  */
static unsigned
hash_type_number (const void *ty)
{
  const struct type *type = (const struct type *) ty;

  return type->state_number;
}

static int
equals_type_number (const void *ty1, const void *ty2)
{
  const struct type *type1 = (const struct type *) ty1;
  const struct type *type2 = (const struct type *) ty2;

  return type1->state_number == type2->state_number;
}

static int
string_eq (const void *a, const void *b)
{
  const char *a0 = (const char *)a;
  const char *b0 = (const char *)b;

  return (strcmp (a0, b0) == 0);
}


/* The function reading the state, called by main from gengtype.c.  */
void
read_state (const char *path)
{
  state_file = fopen (path, "r");
  if (state_file == NULL)
    fatal ("Failed to open state file %s for reading [%s]", path,
	   xstrerror (errno));
  state_path = path;
  state_line = 1;

  if (verbosity_level >= 1)
    {
      printf ("%s reading state file %s;", progname, state_path);
      if (verbosity_level >= 2)
	putchar ('\n');
      fflush (stdout);
    }

  state_seen_types =
    htab_create (2017, hash_type_number, equals_type_number, NULL);
  state_ident_tab =
    htab_create (4027, htab_hash_string, string_eq, NULL);
  read_state_version (version_string);
  read_state_srcdir ();
  read_state_languages ();
  read_state_files_list ();
  read_state_structures (&structures);
  if (ferror (state_file))
    fatal_reading_state_printf
      (NULL_STATE_TOKEN, "input error while reading state [%s]",
       xstrerror (errno));
  read_state_typedefs (&typedefs);
  read_state_param_structs (&param_structs);
  read_state_variables (&variables);
  read_state_trailer ();

  if (verbosity_level >= 1)
    {
      printf ("%s read %ld bytes.\n", progname, ftell (state_file));
      fflush (stdout);
    };

  if (fclose (state_file))
    fatal ("failed to close read state file %s [%s]",
	   path, xstrerror (errno));
  state_file = NULL;
  state_path = NULL;
}

/* End of file gengtype-state.c.  */