1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
|
/*
** This file contains all sources (including headers) to the LEMON
** LALR(1) parser generator. The sources have been combined into a
** single file to make it easy to include LEMON in the source tree
** and Makefile of another program.
**
** The author of this program disclaims copyright.
*/
#include <stdio.h>
#include <stdarg.h>
#include <string.h>
#include <ctype.h>
#include <stdlib.h>
extern void qsort();
extern double strtod();
extern long strtol();
extern void free();
extern int access();
extern int atoi();
#ifndef __WIN32__
# if defined(_WIN32) || defined(WIN32)
# define __WIN32__
# endif
#endif
/* #define PRIVATE static */
#define PRIVATE
#ifdef TEST
#define MAXRHS 5 /* Set low to exercise exception code */
#else
#define MAXRHS 1000
#endif
char *msort();
extern void *malloc();
/******** From the file "action.h" *************************************/
struct action *Action_new();
struct action *Action_sort();
void Action_add();
/********* From the file "assert.h" ************************************/
void myassert();
#ifndef NDEBUG
# define assert(X) if(!(X))myassert(__FILE__,__LINE__)
#else
# define assert(X)
#endif
/********** From the file "build.h" ************************************/
void FindRulePrecedences();
void FindFirstSets();
void FindStates();
void FindLinks();
void FindFollowSets();
void FindActions();
/********* From the file "configlist.h" *********************************/
void Configlist_init(/* void */);
struct config *Configlist_add(/* struct rule *, int */);
struct config *Configlist_addbasis(/* struct rule *, int */);
void Configlist_closure(/* void */);
void Configlist_sort(/* void */);
void Configlist_sortbasis(/* void */);
struct config *Configlist_return(/* void */);
struct config *Configlist_basis(/* void */);
void Configlist_eat(/* struct config * */);
void Configlist_reset(/* void */);
/********* From the file "error.h" ***************************************/
void ErrorMsg(const char *, int,const char *, ...);
/****** From the file "option.h" ******************************************/
struct s_options {
enum { OPT_FLAG=1, OPT_INT, OPT_DBL, OPT_STR,
OPT_FFLAG, OPT_FINT, OPT_FDBL, OPT_FSTR} type;
char *label;
char *arg;
char *message;
};
int OptInit(/* char**,struct s_options*,FILE* */);
int OptNArgs(/* void */);
char *OptArg(/* int */);
void OptErr(/* int */);
void OptPrint(/* void */);
/******** From the file "parse.h" *****************************************/
void Parse(/* struct lemon *lemp */);
/********* From the file "plink.h" ***************************************/
struct plink *Plink_new(/* void */);
void Plink_add(/* struct plink **, struct config * */);
void Plink_copy(/* struct plink **, struct plink * */);
void Plink_delete(/* struct plink * */);
/********** From the file "report.h" *************************************/
void Reprint(/* struct lemon * */);
void ReportOutput(/* struct lemon * */);
void ReportTable(/* struct lemon * */);
void ReportHeader(/* struct lemon * */);
void CompressTables(/* struct lemon * */);
/********** From the file "set.h" ****************************************/
void SetSize(/* int N */); /* All sets will be of size N */
char *SetNew(/* void */); /* A new set for element 0..N */
void SetFree(/* char* */); /* Deallocate a set */
int SetAdd(/* char*,int */); /* Add element to a set */
int SetUnion(/* char *A,char *B */); /* A <- A U B, thru element N */
#define SetFind(X,Y) (X[Y]) /* True if Y is in set X */
/********** From the file "struct.h" *************************************/
/*
** Principal data structures for the LEMON parser generator.
*/
typedef enum {Bo_FALSE=0, Bo_TRUE} Boolean;
/* Symbols (terminals and nonterminals) of the grammar are stored
** in the following: */
struct symbol {
char *name; /* Name of the symbol */
int index; /* Index number for this symbol */
enum {
TERMINAL,
NONTERMINAL
} type; /* Symbols are all either TERMINALS or NTs */
struct rule *rule; /* Linked list of rules of this (if an NT) */
struct symbol *fallback; /* fallback token in case this token doesn't parse */
int prec; /* Precedence if defined (-1 otherwise) */
enum e_assoc {
LEFT,
RIGHT,
NONE,
UNK
} assoc; /* Associativity if predecence is defined */
char *firstset; /* First-set for all rules of this symbol */
Boolean lambda; /* True if NT and can generate an empty string */
char *destructor; /* Code which executes whenever this symbol is
** popped from the stack during error processing */
int destructorln; /* Line number of destructor code */
char *datatype; /* The data type of information held by this
** object. Only used if type==NONTERMINAL */
int dtnum; /* The data type number. In the parser, the value
** stack is a union. The .yy%d element of this
** union is the correct data type for this object */
};
/* Each production rule in the grammar is stored in the following
** structure. */
struct rule {
struct symbol *lhs; /* Left-hand side of the rule */
char *lhsalias; /* Alias for the LHS (NULL if none) */
int ruleline; /* Line number for the rule */
int nrhs; /* Number of RHS symbols */
struct symbol **rhs; /* The RHS symbols */
char **rhsalias; /* An alias for each RHS symbol (NULL if none) */
int line; /* Line number at which code begins */
char *code; /* The code executed when this rule is reduced */
struct symbol *precsym; /* Precedence symbol for this rule */
int index; /* An index number for this rule */
Boolean canReduce; /* True if this rule is ever reduced */
struct rule *nextlhs; /* Next rule with the same LHS */
struct rule *next; /* Next rule in the global list */
};
/* A configuration is a production rule of the grammar together with
** a mark (dot) showing how much of that rule has been processed so far.
** Configurations also contain a follow-set which is a list of terminal
** symbols which are allowed to immediately follow the end of the rule.
** Every configuration is recorded as an instance of the following: */
struct config {
struct rule *rp; /* The rule upon which the configuration is based */
int dot; /* The parse point */
char *fws; /* Follow-set for this configuration only */
struct plink *fplp; /* Follow-set forward propagation links */
struct plink *bplp; /* Follow-set backwards propagation links */
struct state *stp; /* Pointer to state which contains this */
enum {
COMPLETE, /* The status is used during followset and */
INCOMPLETE /* shift computations */
} status;
struct config *next; /* Next configuration in the state */
struct config *bp; /* The next basis configuration */
};
/* Every shift or reduce operation is stored as one of the following */
struct action {
struct symbol *sp; /* The look-ahead symbol */
enum e_action {
SHIFT,
ACCEPT,
REDUCE,
ERROR,
CONFLICT, /* Was a reduce, but part of a conflict */
SH_RESOLVED, /* Was a shift. Precedence resolved conflict */
RD_RESOLVED, /* Was reduce. Precedence resolved conflict */
NOT_USED /* Deleted by compression */
} type;
union {
struct state *stp; /* The new state, if a shift */
struct rule *rp; /* The rule, if a reduce */
} x;
struct action *next; /* Next action for this state */
struct action *collide; /* Next action with the same hash */
};
/* Each state of the generated parser's finite state machine
** is encoded as an instance of the following structure. */
struct state {
struct config *bp; /* The basis configurations for this state */
struct config *cfp; /* All configurations in this set */
int index; /* Sequencial number for this state */
struct action *ap; /* Array of actions for this state */
int nTknAct, nNtAct; /* Number of actions on terminals and nonterminals */
int iTknOfst, iNtOfst; /* yy_action[] offset for terminals and nonterms */
int iDflt; /* Default action */
};
#define NO_OFFSET (-2147483647)
/* A followset propagation link indicates that the contents of one
** configuration followset should be propagated to another whenever
** the first changes. */
struct plink {
struct config *cfp; /* The configuration to which linked */
struct plink *next; /* The next propagate link */
};
/* The state vector for the entire parser generator is recorded as
** follows. (LEMON uses no global variables and makes little use of
** static variables. Fields in the following structure can be thought
** of as begin global variables in the program.) */
struct lemon {
struct state **sorted; /* Table of states sorted by state number */
struct rule *rule; /* List of all rules */
int nstate; /* Number of states */
int nrule; /* Number of rules */
int nsymbol; /* Number of terminal and nonterminal symbols */
int nterminal; /* Number of terminal symbols */
struct symbol **symbols; /* Sorted array of pointers to symbols */
int errorcnt; /* Number of errors */
struct symbol *errsym; /* The error symbol */
char *name; /* Name of the generated parser */
char *arg; /* Declaration of the 3th argument to parser */
char *tokentype; /* Type of terminal symbols in the parser stack */
char *vartype; /* The default type of non-terminal symbols */
char *start; /* Name of the start symbol for the grammar */
char *stacksize; /* Size of the parser stack */
char *include; /* Code to put at the start of the C file */
int includeln; /* Line number for start of include code */
char *error; /* Code to execute when an error is seen */
int errorln; /* Line number for start of error code */
char *overflow; /* Code to execute on a stack overflow */
int overflowln; /* Line number for start of overflow code */
char *failure; /* Code to execute on parser failure */
int failureln; /* Line number for start of failure code */
char *accept; /* Code to execute when the parser excepts */
int acceptln; /* Line number for the start of accept code */
char *extracode; /* Code appended to the generated file */
int extracodeln; /* Line number for the start of the extra code */
char *tokendest; /* Code to execute to destroy token data */
int tokendestln; /* Line number for token destroyer code */
char *vardest; /* Code for the default non-terminal destructor */
int vardestln; /* Line number for default non-term destructor code*/
char *filename; /* Name of the input file */
char *tmplname; /* Name of the template file */
char *outname; /* Name of the current output file */
char *tokenprefix; /* A prefix added to token names in the .h file */
int nconflict; /* Number of parsing conflicts */
int tablesize; /* Size of the parse tables */
int basisflag; /* Print only basis configurations */
int has_fallback; /* True if any %fallback is seen in the grammer */
char *argv0; /* Name of the program */
};
#define MemoryCheck(X) if((X)==0){ \
extern void memory_error(); \
memory_error(); \
}
/**************** From the file "table.h" *********************************/
/*
** All code in this file has been automatically generated
** from a specification in the file
** "table.q"
** by the associative array code building program "aagen".
** Do not edit this file! Instead, edit the specification
** file, then rerun aagen.
*/
/*
** Code for processing tables in the LEMON parser generator.
*/
/* Routines for handling a strings */
char *Strsafe();
void Strsafe_init(/* void */);
int Strsafe_insert(/* char * */);
char *Strsafe_find(/* char * */);
/* Routines for handling symbols of the grammar */
struct symbol *Symbol_new();
int Symbolcmpp(/* struct symbol **, struct symbol ** */);
void Symbol_init(/* void */);
int Symbol_insert(/* struct symbol *, char * */);
struct symbol *Symbol_find(/* char * */);
struct symbol *Symbol_Nth(/* int */);
int Symbol_count(/* */);
struct symbol **Symbol_arrayof(/* */);
/* Routines to manage the state table */
int Configcmp(/* struct config *, struct config * */);
struct state *State_new();
void State_init(/* void */);
int State_insert(/* struct state *, struct config * */);
struct state *State_find(/* struct config * */);
struct state **State_arrayof(/* */);
/* Routines used for efficiency in Configlist_add */
void Configtable_init(/* void */);
int Configtable_insert(/* struct config * */);
struct config *Configtable_find(/* struct config * */);
void Configtable_clear(/* int(*)(struct config *) */);
/****************** From the file "action.c" *******************************/
/*
** Routines processing parser actions in the LEMON parser generator.
*/
/* Allocate a new parser action */
struct action *Action_new(){
static struct action *freelist = 0;
struct action *new;
if( freelist==0 ){
int i;
int amt = 100;
freelist = (struct action *)malloc( sizeof(struct action)*amt );
if( freelist==0 ){
fprintf(stderr,"Unable to allocate memory for a new parser action.");
exit(1);
}
for(i=0; i<amt-1; i++) freelist[i].next = &freelist[i+1];
freelist[amt-1].next = 0;
}
new = freelist;
freelist = freelist->next;
return new;
}
/* Compare two actions */
static int actioncmp(ap1,ap2)
struct action *ap1;
struct action *ap2;
{
int rc;
rc = ap1->sp->index - ap2->sp->index;
if( rc==0 ) rc = (int)ap1->type - (int)ap2->type;
if( rc==0 ){
assert( ap1->type==REDUCE || ap1->type==RD_RESOLVED || ap1->type==CONFLICT);
assert( ap2->type==REDUCE || ap2->type==RD_RESOLVED || ap2->type==CONFLICT);
rc = ap1->x.rp->index - ap2->x.rp->index;
}
return rc;
}
/* Sort parser actions */
struct action *Action_sort(ap)
struct action *ap;
{
ap = (struct action *)msort(ap,&ap->next,actioncmp);
return ap;
}
void Action_add(app,type,sp,arg)
struct action **app;
enum e_action type;
struct symbol *sp;
char *arg;
{
struct action *new;
new = Action_new();
new->next = *app;
*app = new;
new->type = type;
new->sp = sp;
if( type==SHIFT ){
new->x.stp = (struct state *)arg;
}else{
new->x.rp = (struct rule *)arg;
}
}
/********************** New code to implement the "acttab" module ***********/
/*
** This module implements routines use to construct the yy_action[] table.
*/
/*
** The state of the yy_action table under construction is an instance of
** the following structure
*/
typedef struct acttab acttab;
struct acttab {
int nAction; /* Number of used slots in aAction[] */
int nActionAlloc; /* Slots allocated for aAction[] */
struct {
int lookahead; /* Value of the lookahead token */
int action; /* Action to take on the given lookahead */
} *aAction, /* The yy_action[] table under construction */
*aLookahead; /* A single new transaction set */
int mnLookahead; /* Minimum aLookahead[].lookahead */
int mnAction; /* Action associated with mnLookahead */
int mxLookahead; /* Maximum aLookahead[].lookahead */
int nLookahead; /* Used slots in aLookahead[] */
int nLookaheadAlloc; /* Slots allocated in aLookahead[] */
};
/* Return the number of entries in the yy_action table */
#define acttab_size(X) ((X)->nAction)
/* The value for the N-th entry in yy_action */
#define acttab_yyaction(X,N) ((X)->aAction[N].action)
/* The value for the N-th entry in yy_lookahead */
#define acttab_yylookahead(X,N) ((X)->aAction[N].lookahead)
/* Free all memory associated with the given acttab */
void acttab_free(acttab *p){
free( p->aAction );
free( p->aLookahead );
free( p );
}
/* Allocate a new acttab structure */
acttab *acttab_alloc(void){
acttab *p = malloc( sizeof(*p) );
if( p==0 ){
fprintf(stderr,"Unable to allocate memory for a new acttab.");
exit(1);
}
memset(p, 0, sizeof(*p));
return p;
}
/* Add a new action to the current transaction set
*/
void acttab_action(acttab *p, int lookahead, int action){
if( p->nLookahead>=p->nLookaheadAlloc ){
p->nLookaheadAlloc += 25;
p->aLookahead = realloc( p->aLookahead,
sizeof(p->aLookahead[0])*p->nLookaheadAlloc );
if( p->aLookahead==0 ){
fprintf(stderr,"malloc failed\n");
exit(1);
}
}
if( p->nLookahead==0 ){
p->mxLookahead = lookahead;
p->mnLookahead = lookahead;
p->mnAction = action;
}else{
if( p->mxLookahead<lookahead ) p->mxLookahead = lookahead;
if( p->mnLookahead>lookahead ){
p->mnLookahead = lookahead;
p->mnAction = action;
}
}
p->aLookahead[p->nLookahead].lookahead = lookahead;
p->aLookahead[p->nLookahead].action = action;
p->nLookahead++;
}
/*
** Add the transaction set built up with prior calls to acttab_action()
** into the current action table. Then reset the transaction set back
** to an empty set in preparation for a new round of acttab_action() calls.
**
** Return the offset into the action table of the new transaction.
*/
int acttab_insert(acttab *p){
int i, j, k, n;
assert( p->nLookahead>0 );
/* Make sure we have enough space to hold the expanded action table
** in the worst case. The worst case occurs if the transaction set
** must be appended to the current action table
*/
n = p->mxLookahead + 1;
if( p->nAction + n >= p->nActionAlloc ){
int oldAlloc = p->nActionAlloc;
p->nActionAlloc = p->nAction + n + p->nActionAlloc + 20;
p->aAction = realloc( p->aAction,
sizeof(p->aAction[0])*p->nActionAlloc);
if( p->aAction==0 ){
fprintf(stderr,"malloc failed\n");
exit(1);
}
for(i=oldAlloc; i<p->nActionAlloc; i++){
p->aAction[i].lookahead = -1;
p->aAction[i].action = -1;
}
}
/* Scan the existing action table looking for an offset where we can
** insert the current transaction set. Fall out of the loop when that
** offset is found. In the worst case, we fall out of the loop when
** i reaches p->nAction, which means we append the new transaction set.
**
** i is the index in p->aAction[] where p->mnLookahead is inserted.
*/
for(i=0; i<p->nAction+p->mnLookahead; i++){
if( p->aAction[i].lookahead<0 ){
for(j=0; j<p->nLookahead; j++){
k = p->aLookahead[j].lookahead - p->mnLookahead + i;
if( k<0 ) break;
if( p->aAction[k].lookahead>=0 ) break;
}
if( j<p->nLookahead ) continue;
for(j=0; j<p->nAction; j++){
if( p->aAction[j].lookahead==j+p->mnLookahead-i ) break;
}
if( j==p->nAction ){
break; /* Fits in empty slots */
}
}else if( p->aAction[i].lookahead==p->mnLookahead ){
if( p->aAction[i].action!=p->mnAction ) continue;
for(j=0; j<p->nLookahead; j++){
k = p->aLookahead[j].lookahead - p->mnLookahead + i;
if( k<0 || k>=p->nAction ) break;
if( p->aLookahead[j].lookahead!=p->aAction[k].lookahead ) break;
if( p->aLookahead[j].action!=p->aAction[k].action ) break;
}
if( j<p->nLookahead ) continue;
n = 0;
for(j=0; j<p->nAction; j++){
if( p->aAction[j].lookahead<0 ) continue;
if( p->aAction[j].lookahead==j+p->mnLookahead-i ) n++;
}
if( n==p->nLookahead ){
break; /* Same as a prior transaction set */
}
}
}
/* Insert transaction set at index i. */
for(j=0; j<p->nLookahead; j++){
k = p->aLookahead[j].lookahead - p->mnLookahead + i;
p->aAction[k] = p->aLookahead[j];
if( k>=p->nAction ) p->nAction = k+1;
}
p->nLookahead = 0;
/* Return the offset that is added to the lookahead in order to get the
** index into yy_action of the action */
return i - p->mnLookahead;
}
/********************** From the file "assert.c" ****************************/
/*
** A more efficient way of handling assertions.
*/
void myassert(file,line)
char *file;
int line;
{
fprintf(stderr,"Assertion failed on line %d of file \"%s\"\n",line,file);
exit(1);
}
/********************** From the file "build.c" *****************************/
/*
** Routines to construction the finite state machine for the LEMON
** parser generator.
*/
/* Find a precedence symbol of every rule in the grammar.
**
** Those rules which have a precedence symbol coded in the input
** grammar using the "[symbol]" construct will already have the
** rp->precsym field filled. Other rules take as their precedence
** symbol the first RHS symbol with a defined precedence. If there
** are not RHS symbols with a defined precedence, the precedence
** symbol field is left blank.
*/
void FindRulePrecedences(xp)
struct lemon *xp;
{
struct rule *rp;
for(rp=xp->rule; rp; rp=rp->next){
if( rp->precsym==0 ){
int i;
for(i=0; i<rp->nrhs; i++){
if( rp->rhs[i]->prec>=0 ){
rp->precsym = rp->rhs[i];
break;
}
}
}
}
return;
}
/* Find all nonterminals which will generate the empty string.
** Then go back and compute the first sets of every nonterminal.
** The first set is the set of all terminal symbols which can begin
** a string generated by that nonterminal.
*/
void FindFirstSets(lemp)
struct lemon *lemp;
{
int i;
struct rule *rp;
int progress;
for(i=0; i<lemp->nsymbol; i++){
lemp->symbols[i]->lambda = Bo_FALSE;
}
for(i=lemp->nterminal; i<lemp->nsymbol; i++){
lemp->symbols[i]->firstset = SetNew();
}
/* First compute all lambdas */
do{
progress = 0;
for(rp=lemp->rule; rp; rp=rp->next){
if( rp->lhs->lambda ) continue;
for(i=0; i<rp->nrhs; i++){
if( rp->rhs[i]->lambda==Bo_FALSE ) break;
}
if( i==rp->nrhs ){
rp->lhs->lambda = Bo_TRUE;
progress = 1;
}
}
}while( progress );
/* Now compute all first sets */
do{
struct symbol *s1, *s2;
progress = 0;
for(rp=lemp->rule; rp; rp=rp->next){
s1 = rp->lhs;
for(i=0; i<rp->nrhs; i++){
s2 = rp->rhs[i];
if( s2->type==TERMINAL ){
progress += SetAdd(s1->firstset,s2->index);
break;
}else if( s1==s2 ){
if( s1->lambda==Bo_FALSE ) break;
}else{
progress += SetUnion(s1->firstset,s2->firstset);
if( s2->lambda==Bo_FALSE ) break;
}
}
}
}while( progress );
return;
}
/* Compute all LR(0) states for the grammar. Links
** are added to between some states so that the LR(1) follow sets
** can be computed later.
*/
PRIVATE struct state *getstate(/* struct lemon * */); /* forward reference */
void FindStates(lemp)
struct lemon *lemp;
{
struct symbol *sp;
struct rule *rp;
Configlist_init();
/* Find the start symbol */
if( lemp->start ){
sp = Symbol_find(lemp->start);
if( sp==0 ){
ErrorMsg(lemp->filename,0,
"The specified start symbol \"%s\" is not \
in a nonterminal of the grammar. \"%s\" will be used as the start \
symbol instead.",lemp->start,lemp->rule->lhs->name);
lemp->errorcnt++;
sp = lemp->rule->lhs;
}
}else{
sp = lemp->rule->lhs;
}
/* Make sure the start symbol doesn't occur on the right-hand side of
** any rule. Report an error if it does. (YACC would generate a new
** start symbol in this case.) */
for(rp=lemp->rule; rp; rp=rp->next){
int i;
for(i=0; i<rp->nrhs; i++){
if( rp->rhs[i]==sp ){
ErrorMsg(lemp->filename,0,
"The start symbol \"%s\" occurs on the \
right-hand side of a rule. This will result in a parser which \
does not work properly.",sp->name);
lemp->errorcnt++;
}
}
}
/* The basis configuration set for the first state
** is all rules which have the start symbol as their
** left-hand side */
for(rp=sp->rule; rp; rp=rp->nextlhs){
struct config *newcfp;
newcfp = Configlist_addbasis(rp,0);
SetAdd(newcfp->fws,0);
}
/* Compute the first state. All other states will be
** computed automatically during the computation of the first one.
** The returned pointer to the first state is not used. */
(void)getstate(lemp);
return;
}
/* Return a pointer to a state which is described by the configuration
** list which has been built from calls to Configlist_add.
*/
PRIVATE void buildshifts(/* struct lemon *, struct state * */); /* Forwd ref */
PRIVATE struct state *getstate(lemp)
struct lemon *lemp;
{
struct config *cfp, *bp;
struct state *stp;
/* Extract the sorted basis of the new state. The basis was constructed
** by prior calls to "Configlist_addbasis()". */
Configlist_sortbasis();
bp = Configlist_basis();
/* Get a state with the same basis */
stp = State_find(bp);
if( stp ){
/* A state with the same basis already exists! Copy all the follow-set
** propagation links from the state under construction into the
** preexisting state, then return a pointer to the preexisting state */
struct config *x, *y;
for(x=bp, y=stp->bp; x && y; x=x->bp, y=y->bp){
Plink_copy(&y->bplp,x->bplp);
Plink_delete(x->fplp);
x->fplp = x->bplp = 0;
}
cfp = Configlist_return();
Configlist_eat(cfp);
}else{
/* This really is a new state. Construct all the details */
Configlist_closure(lemp); /* Compute the configuration closure */
Configlist_sort(); /* Sort the configuration closure */
cfp = Configlist_return(); /* Get a pointer to the config list */
stp = State_new(); /* A new state structure */
MemoryCheck(stp);
stp->bp = bp; /* Remember the configuration basis */
stp->cfp = cfp; /* Remember the configuration closure */
stp->index = lemp->nstate++; /* Every state gets a sequence number */
stp->ap = 0; /* No actions, yet. */
State_insert(stp,stp->bp); /* Add to the state table */
buildshifts(lemp,stp); /* Recursively compute successor states */
}
return stp;
}
/* Construct all successor states to the given state. A "successor"
** state is any state which can be reached by a shift action.
*/
PRIVATE void buildshifts(lemp,stp)
struct lemon *lemp;
struct state *stp; /* The state from which successors are computed */
{
struct config *cfp; /* For looping thru the config closure of "stp" */
struct config *bcfp; /* For the inner loop on config closure of "stp" */
struct config *new; /* */
struct symbol *sp; /* Symbol following the dot in configuration "cfp" */
struct symbol *bsp; /* Symbol following the dot in configuration "bcfp" */
struct state *newstp; /* A pointer to a successor state */
/* Each configuration becomes complete after it contibutes to a successor
** state. Initially, all configurations are incomplete */
for(cfp=stp->cfp; cfp; cfp=cfp->next) cfp->status = INCOMPLETE;
/* Loop through all configurations of the state "stp" */
for(cfp=stp->cfp; cfp; cfp=cfp->next){
if( cfp->status==COMPLETE ) continue; /* Already used by inner loop */
if( cfp->dot>=cfp->rp->nrhs ) continue; /* Can't shift this config */
Configlist_reset(); /* Reset the new config set */
sp = cfp->rp->rhs[cfp->dot]; /* Symbol after the dot */
/* For every configuration in the state "stp" which has the symbol "sp"
** following its dot, add the same configuration to the basis set under
** construction but with the dot shifted one symbol to the right. */
for(bcfp=cfp; bcfp; bcfp=bcfp->next){
if( bcfp->status==COMPLETE ) continue; /* Already used */
if( bcfp->dot>=bcfp->rp->nrhs ) continue; /* Can't shift this one */
bsp = bcfp->rp->rhs[bcfp->dot]; /* Get symbol after dot */
if( bsp!=sp ) continue; /* Must be same as for "cfp" */
bcfp->status = COMPLETE; /* Mark this config as used */
new = Configlist_addbasis(bcfp->rp,bcfp->dot+1);
Plink_add(&new->bplp,bcfp);
}
/* Get a pointer to the state described by the basis configuration set
** constructed in the preceding loop */
newstp = getstate(lemp);
/* The state "newstp" is reached from the state "stp" by a shift action
** on the symbol "sp" */
Action_add(&stp->ap,SHIFT,sp,newstp);
}
}
/*
** Construct the propagation links
*/
void FindLinks(lemp)
struct lemon *lemp;
{
int i;
struct config *cfp, *other;
struct state *stp;
struct plink *plp;
/* Housekeeping detail:
** Add to every propagate link a pointer back to the state to
** which the link is attached. */
for(i=0; i<lemp->nstate; i++){
stp = lemp->sorted[i];
for(cfp=stp->cfp; cfp; cfp=cfp->next){
cfp->stp = stp;
}
}
/* Convert all backlinks into forward links. Only the forward
** links are used in the follow-set computation. */
for(i=0; i<lemp->nstate; i++){
stp = lemp->sorted[i];
for(cfp=stp->cfp; cfp; cfp=cfp->next){
for(plp=cfp->bplp; plp; plp=plp->next){
other = plp->cfp;
Plink_add(&other->fplp,cfp);
}
}
}
}
/* Compute all followsets.
**
** A followset is the set of all symbols which can come immediately
** after a configuration.
*/
void FindFollowSets(lemp)
struct lemon *lemp;
{
int i;
struct config *cfp;
struct plink *plp;
int progress;
int change;
for(i=0; i<lemp->nstate; i++){
for(cfp=lemp->sorted[i]->cfp; cfp; cfp=cfp->next){
cfp->status = INCOMPLETE;
}
}
do{
progress = 0;
for(i=0; i<lemp->nstate; i++){
for(cfp=lemp->sorted[i]->cfp; cfp; cfp=cfp->next){
if( cfp->status==COMPLETE ) continue;
for(plp=cfp->fplp; plp; plp=plp->next){
change = SetUnion(plp->cfp->fws,cfp->fws);
if( change ){
plp->cfp->status = INCOMPLETE;
progress = 1;
}
}
cfp->status = COMPLETE;
}
}
}while( progress );
}
static int resolve_conflict();
/* Compute the reduce actions, and resolve conflicts.
*/
void FindActions(lemp)
struct lemon *lemp;
{
int i,j;
struct config *cfp;
struct symbol *sp;
struct rule *rp;
/* Add all of the reduce actions
** A reduce action is added for each element of the followset of
** a configuration which has its dot at the extreme right.
*/
for(i=0; i<lemp->nstate; i++){ /* Loop over all states */
struct state *stp;
stp = lemp->sorted[i];
for(cfp=stp->cfp; cfp; cfp=cfp->next){ /* Loop over all configurations */
if( cfp->rp->nrhs==cfp->dot ){ /* Is dot at extreme right? */
for(j=0; j<lemp->nterminal; j++){
if( SetFind(cfp->fws,j) ){
/* Add a reduce action to the state "stp" which will reduce by the
** rule "cfp->rp" if the lookahead symbol is "lemp->symbols[j]" */
Action_add(&stp->ap,REDUCE,lemp->symbols[j],cfp->rp);
}
}
}
}
}
/* Add the accepting token */
if( lemp->start ){
sp = Symbol_find(lemp->start);
if( sp==0 ) sp = lemp->rule->lhs;
}else{
sp = lemp->rule->lhs;
}
/* Add to the first state (which is always the starting state of the
** finite state machine) an action to ACCEPT if the lookahead is the
** start nonterminal. */
Action_add(&lemp->sorted[0]->ap,ACCEPT,sp,0);
/* Resolve conflicts */
for(i=0; i<lemp->nstate; i++){
struct action *ap, *nap;
struct state *stp;
stp = lemp->sorted[i];
assert( stp->ap );
stp->ap = Action_sort(stp->ap);
for(ap=stp->ap; ap && ap->next; ap=ap->next){
for(nap=ap->next; nap && nap->sp==ap->sp; nap=nap->next){
/* The two actions "ap" and "nap" have the same lookahead.
** Figure out which one should be used */
lemp->nconflict += resolve_conflict(ap,nap,lemp->errsym);
}
}
}
/* Report an error for each rule that can never be reduced. */
for(rp=lemp->rule; rp; rp=rp->next) rp->canReduce = Bo_FALSE;
for(i=0; i<lemp->nstate; i++){
struct action *ap;
for(ap=lemp->sorted[i]->ap; ap; ap=ap->next){
if( ap->type==REDUCE ) ap->x.rp->canReduce = Bo_TRUE;
}
}
for(rp=lemp->rule; rp; rp=rp->next){
if( rp->canReduce ) continue;
ErrorMsg(lemp->filename,rp->ruleline,"This rule can not be reduced.\n");
lemp->errorcnt++;
}
}
/* Resolve a conflict between the two given actions. If the
** conflict can't be resolve, return non-zero.
**
** NO LONGER TRUE:
** To resolve a conflict, first look to see if either action
** is on an error rule. In that case, take the action which
** is not associated with the error rule. If neither or both
** actions are associated with an error rule, then try to
** use precedence to resolve the conflict.
**
** If either action is a SHIFT, then it must be apx. This
** function won't work if apx->type==REDUCE and apy->type==SHIFT.
*/
static int resolve_conflict(apx,apy,errsym)
struct action *apx;
struct action *apy;
struct symbol *errsym; /* The error symbol (if defined. NULL otherwise) */
{
struct symbol *spx, *spy;
int errcnt = 0;
assert( apx->sp==apy->sp ); /* Otherwise there would be no conflict */
if( apx->type==SHIFT && apy->type==REDUCE ){
spx = apx->sp;
spy = apy->x.rp->precsym;
if( spy==0 || spx->prec<0 || spy->prec<0 ){
/* Not enough precedence information. */
apy->type = CONFLICT;
errcnt++;
}else if( spx->prec>spy->prec ){ /* Lower precedence wins */
apy->type = RD_RESOLVED;
}else if( spx->prec<spy->prec ){
apx->type = SH_RESOLVED;
}else if( spx->prec==spy->prec && spx->assoc==RIGHT ){ /* Use operator */
apy->type = RD_RESOLVED; /* associativity */
}else if( spx->prec==spy->prec && spx->assoc==LEFT ){ /* to break tie */
apx->type = SH_RESOLVED;
}else{
assert( spx->prec==spy->prec && spx->assoc==NONE );
apy->type = CONFLICT;
errcnt++;
}
}else if( apx->type==REDUCE && apy->type==REDUCE ){
spx = apx->x.rp->precsym;
spy = apy->x.rp->precsym;
if( spx==0 || spy==0 || spx->prec<0 ||
spy->prec<0 || spx->prec==spy->prec ){
apy->type = CONFLICT;
errcnt++;
}else if( spx->prec>spy->prec ){
apy->type = RD_RESOLVED;
}else if( spx->prec<spy->prec ){
apx->type = RD_RESOLVED;
}
}else{
assert(
apx->type==SH_RESOLVED ||
apx->type==RD_RESOLVED ||
apx->type==CONFLICT ||
apy->type==SH_RESOLVED ||
apy->type==RD_RESOLVED ||
apy->type==CONFLICT
);
/* The REDUCE/SHIFT case cannot happen because SHIFTs come before
** REDUCEs on the list. If we reach this point it must be because
** the parser conflict had already been resolved. */
}
return errcnt;
}
/********************* From the file "configlist.c" *************************/
/*
** Routines to processing a configuration list and building a state
** in the LEMON parser generator.
*/
static struct config *freelist = 0; /* List of free configurations */
static struct config *current = 0; /* Top of list of configurations */
static struct config **currentend = 0; /* Last on list of configs */
static struct config *basis = 0; /* Top of list of basis configs */
static struct config **basisend = 0; /* End of list of basis configs */
/* Return a pointer to a new configuration */
PRIVATE struct config *newconfig(){
struct config *new;
if( freelist==0 ){
int i;
int amt = 3;
freelist = (struct config *)malloc( sizeof(struct config)*amt );
if( freelist==0 ){
fprintf(stderr,"Unable to allocate memory for a new configuration.");
exit(1);
}
for(i=0; i<amt-1; i++) freelist[i].next = &freelist[i+1];
freelist[amt-1].next = 0;
}
new = freelist;
freelist = freelist->next;
return new;
}
/* The configuration "old" is no longer used */
PRIVATE void deleteconfig(old)
struct config *old;
{
old->next = freelist;
freelist = old;
}
/* Initialized the configuration list builder */
void Configlist_init(){
current = 0;
currentend = ¤t;
basis = 0;
basisend = &basis;
Configtable_init();
return;
}
/* Initialized the configuration list builder */
void Configlist_reset(){
current = 0;
currentend = ¤t;
basis = 0;
basisend = &basis;
Configtable_clear(0);
return;
}
/* Add another configuration to the configuration list */
struct config *Configlist_add(rp,dot)
struct rule *rp; /* The rule */
int dot; /* Index into the RHS of the rule where the dot goes */
{
struct config *cfp, model;
assert( currentend!=0 );
model.rp = rp;
model.dot = dot;
cfp = Configtable_find(&model);
if( cfp==0 ){
cfp = newconfig();
cfp->rp = rp;
cfp->dot = dot;
cfp->fws = SetNew();
cfp->stp = 0;
cfp->fplp = cfp->bplp = 0;
cfp->next = 0;
cfp->bp = 0;
*currentend = cfp;
currentend = &cfp->next;
Configtable_insert(cfp);
}
return cfp;
}
/* Add a basis configuration to the configuration list */
struct config *Configlist_addbasis(rp,dot)
struct rule *rp;
int dot;
{
struct config *cfp, model;
assert( basisend!=0 );
assert( currentend!=0 );
model.rp = rp;
model.dot = dot;
cfp = Configtable_find(&model);
if( cfp==0 ){
cfp = newconfig();
cfp->rp = rp;
cfp->dot = dot;
cfp->fws = SetNew();
cfp->stp = 0;
cfp->fplp = cfp->bplp = 0;
cfp->next = 0;
cfp->bp = 0;
*currentend = cfp;
currentend = &cfp->next;
*basisend = cfp;
basisend = &cfp->bp;
Configtable_insert(cfp);
}
return cfp;
}
/* Compute the closure of the configuration list */
void Configlist_closure(lemp)
struct lemon *lemp;
{
struct config *cfp, *newcfp;
struct rule *rp, *newrp;
struct symbol *sp, *xsp;
int i, dot;
assert( currentend!=0 );
for(cfp=current; cfp; cfp=cfp->next){
rp = cfp->rp;
dot = cfp->dot;
if( dot>=rp->nrhs ) continue;
sp = rp->rhs[dot];
if( sp->type==NONTERMINAL ){
if( sp->rule==0 && sp!=lemp->errsym ){
ErrorMsg(lemp->filename,rp->line,"Nonterminal \"%s\" has no rules.",
sp->name);
lemp->errorcnt++;
}
for(newrp=sp->rule; newrp; newrp=newrp->nextlhs){
newcfp = Configlist_add(newrp,0);
for(i=dot+1; i<rp->nrhs; i++){
xsp = rp->rhs[i];
if( xsp->type==TERMINAL ){
SetAdd(newcfp->fws,xsp->index);
break;
}else{
SetUnion(newcfp->fws,xsp->firstset);
if( xsp->lambda==Bo_FALSE ) break;
}
}
if( i==rp->nrhs ) Plink_add(&cfp->fplp,newcfp);
}
}
}
return;
}
/* Sort the configuration list */
void Configlist_sort(){
current = (struct config *)msort(current,&(current->next),Configcmp);
currentend = 0;
return;
}
/* Sort the basis configuration list */
void Configlist_sortbasis(){
basis = (struct config *)msort(current,&(current->bp),Configcmp);
basisend = 0;
return;
}
/* Return a pointer to the head of the configuration list and
** reset the list */
struct config *Configlist_return(){
struct config *old;
old = current;
current = 0;
currentend = 0;
return old;
}
/* Return a pointer to the head of the configuration list and
** reset the list */
struct config *Configlist_basis(){
struct config *old;
old = basis;
basis = 0;
basisend = 0;
return old;
}
/* Free all elements of the given configuration list */
void Configlist_eat(cfp)
struct config *cfp;
{
struct config *nextcfp;
for(; cfp; cfp=nextcfp){
nextcfp = cfp->next;
assert( cfp->fplp==0 );
assert( cfp->bplp==0 );
if( cfp->fws ) SetFree(cfp->fws);
deleteconfig(cfp);
}
return;
}
/***************** From the file "error.c" *********************************/
/*
** Code for printing error message.
*/
/* Find a good place to break "msg" so that its length is at least "min"
** but no more than "max". Make the point as close to max as possible.
*/
static int findbreak(msg,min,max)
char *msg;
int min;
int max;
{
int i,spot;
char c;
for(i=spot=min; i<=max; i++){
c = msg[i];
if( c=='\t' ) msg[i] = ' ';
if( c=='\n' ){ msg[i] = ' '; spot = i; break; }
if( c==0 ){ spot = i; break; }
if( c=='-' && i<max-1 ) spot = i+1;
if( c==' ' ) spot = i;
}
return spot;
}
/*
** The error message is split across multiple lines if necessary. The
** splits occur at a space, if there is a space available near the end
** of the line.
*/
#define ERRMSGSIZE 10000 /* Hope this is big enough. No way to error check */
#define LINEWIDTH 79 /* Max width of any output line */
#define PREFIXLIMIT 30 /* Max width of the prefix on each line */
void ErrorMsg(const char *filename, int lineno, const char *format, ...){
char errmsg[ERRMSGSIZE];
char prefix[PREFIXLIMIT+10];
int errmsgsize;
int prefixsize;
int availablewidth;
va_list ap;
int end, restart, base;
va_start(ap, format);
/* Prepare a prefix to be prepended to every output line */
if( lineno>0 ){
sprintf(prefix,"%.*s:%d: ",PREFIXLIMIT-10,filename,lineno);
}else{
sprintf(prefix,"%.*s: ",PREFIXLIMIT-10,filename);
}
prefixsize = strlen(prefix);
availablewidth = LINEWIDTH - prefixsize;
/* Generate the error message */
vsprintf(errmsg,format,ap);
va_end(ap);
errmsgsize = strlen(errmsg);
/* Remove trailing '\n's from the error message. */
while( errmsgsize>0 && errmsg[errmsgsize-1]=='\n' ){
errmsg[--errmsgsize] = 0;
}
/* Print the error message */
base = 0;
while( errmsg[base]!=0 ){
end = restart = findbreak(&errmsg[base],0,availablewidth);
restart += base;
while( errmsg[restart]==' ' ) restart++;
fprintf(stdout,"%s%.*s\n",prefix,end,&errmsg[base]);
base = restart;
}
}
/**************** From the file "main.c" ************************************/
/*
** Main program file for the LEMON parser generator.
*/
/* Report an out-of-memory condition and abort. This function
** is used mostly by the "MemoryCheck" macro in struct.h
*/
void memory_error(){
fprintf(stderr,"Out of memory. Aborting...\n");
exit(1);
}
/* The main program. Parse the command line and do it... */
int main(argc,argv)
int argc;
char **argv;
{
static int version = 0;
static int rpflag = 0;
static int basisflag = 0;
static int compress = 0;
static int quiet = 0;
static int statistics = 0;
static int mhflag = 0;
static struct s_options options[] = {
{OPT_FLAG, "b", (char*)&basisflag, "Print only the basis in report."},
{OPT_FLAG, "c", (char*)&compress, "Don't compress the action table."},
{OPT_FLAG, "g", (char*)&rpflag, "Print grammar without actions."},
{OPT_FLAG, "m", (char*)&mhflag, "Output a makeheaders compatible file"},
{OPT_FLAG, "q", (char*)&quiet, "(Quiet) Don't print the report file."},
{OPT_FLAG, "s", (char*)&statistics, "Print parser stats to standard output."},
{OPT_FLAG, "x", (char*)&version, "Print the version number."},
{OPT_FLAG,0,0,0}
};
int i;
struct lemon lem;
char *def_tmpl_name = "lempar.c";
OptInit(argv,options,stderr);
if( version ){
printf("Lemon version 1.0\n");
exit(0);
}
if( OptNArgs() < 1 ){
fprintf(stderr,"Exactly one filename argument is required.\n");
exit(1);
}
lem.errorcnt = 0;
/* Initialize the machine */
Strsafe_init();
Symbol_init();
State_init();
lem.argv0 = argv[0];
lem.filename = OptArg(0);
lem.tmplname = (OptNArgs() == 2) ? OptArg(1) : def_tmpl_name;
lem.basisflag = basisflag;
lem.has_fallback = 0;
lem.nconflict = 0;
lem.name = lem.include = lem.arg = lem.tokentype = lem.start = 0;
lem.vartype = 0;
lem.stacksize = 0;
lem.error = lem.overflow = lem.failure = lem.accept = lem.tokendest =
lem.tokenprefix = lem.outname = lem.extracode = 0;
lem.vardest = 0;
lem.tablesize = 0;
Symbol_new("$");
lem.errsym = Symbol_new("error");
/* Parse the input file */
Parse(&lem);
if( lem.errorcnt ) exit(lem.errorcnt);
if( lem.rule==0 ){
fprintf(stderr,"Empty grammar.\n");
exit(1);
}
/* Count and index the symbols of the grammar */
lem.nsymbol = Symbol_count();
Symbol_new("{default}");
lem.symbols = Symbol_arrayof();
for(i=0; i<=lem.nsymbol; i++) lem.symbols[i]->index = i;
qsort(lem.symbols,lem.nsymbol+1,sizeof(struct symbol*),
(int(*)())Symbolcmpp);
for(i=0; i<=lem.nsymbol; i++) lem.symbols[i]->index = i;
for(i=1; isupper(lem.symbols[i]->name[0]); i++);
lem.nterminal = i;
/* Generate a reprint of the grammar, if requested on the command line */
if( rpflag ){
Reprint(&lem);
}else{
/* Initialize the size for all follow and first sets */
SetSize(lem.nterminal);
/* Find the precedence for every production rule (that has one) */
FindRulePrecedences(&lem);
/* Compute the lambda-nonterminals and the first-sets for every
** nonterminal */
FindFirstSets(&lem);
/* Compute all LR(0) states. Also record follow-set propagation
** links so that the follow-set can be computed later */
lem.nstate = 0;
FindStates(&lem);
lem.sorted = State_arrayof();
/* Tie up loose ends on the propagation links */
FindLinks(&lem);
/* Compute the follow set of every reducible configuration */
FindFollowSets(&lem);
/* Compute the action tables */
FindActions(&lem);
/* Compress the action tables */
if( compress==0 ) CompressTables(&lem);
/* Generate a report of the parser generated. (the "y.output" file) */
if( !quiet ) ReportOutput(&lem);
/* Generate the source code for the parser */
ReportTable(&lem, mhflag);
/* Produce a header file for use by the scanner. (This step is
** omitted if the "-m" option is used because makeheaders will
** generate the file for us.) */
if( !mhflag ) ReportHeader(&lem);
}
if( statistics ){
printf("Parser statistics: %d terminals, %d nonterminals, %d rules\n",
lem.nterminal, lem.nsymbol - lem.nterminal, lem.nrule);
printf(" %d states, %d parser table entries, %d conflicts\n",
lem.nstate, lem.tablesize, lem.nconflict);
}
if( lem.nconflict ){
fprintf(stderr,"%d parsing conflicts.\n",lem.nconflict);
}
exit(lem.errorcnt + lem.nconflict);
}
/******************** From the file "msort.c" *******************************/
/*
** A generic merge-sort program.
**
** USAGE:
** Let "ptr" be a pointer to some structure which is at the head of
** a null-terminated list. Then to sort the list call:
**
** ptr = msort(ptr,&(ptr->next),cmpfnc);
**
** In the above, "cmpfnc" is a pointer to a function which compares
** two instances of the structure and returns an integer, as in
** strcmp. The second argument is a pointer to the pointer to the
** second element of the linked list. This address is used to compute
** the offset to the "next" field within the structure. The offset to
** the "next" field must be constant for all structures in the list.
**
** The function returns a new pointer which is the head of the list
** after sorting.
**
** ALGORITHM:
** Merge-sort.
*/
/*
** Return a pointer to the next structure in the linked list.
*/
#define NEXT(A) (*(char**)(((unsigned long)A)+offset))
/*
** Inputs:
** a: A sorted, null-terminated linked list. (May be null).
** b: A sorted, null-terminated linked list. (May be null).
** cmp: A pointer to the comparison function.
** offset: Offset in the structure to the "next" field.
**
** Return Value:
** A pointer to the head of a sorted list containing the elements
** of both a and b.
**
** Side effects:
** The "next" pointers for elements in the lists a and b are
** changed.
*/
static char *merge(a,b,cmp,offset)
char *a;
char *b;
int (*cmp)();
int offset;
{
char *ptr, *head;
if( a==0 ){
head = b;
}else if( b==0 ){
head = a;
}else{
if( (*cmp)(a,b)<0 ){
ptr = a;
a = NEXT(a);
}else{
ptr = b;
b = NEXT(b);
}
head = ptr;
while( a && b ){
if( (*cmp)(a,b)<0 ){
NEXT(ptr) = a;
ptr = a;
a = NEXT(a);
}else{
NEXT(ptr) = b;
ptr = b;
b = NEXT(b);
}
}
if( a ) NEXT(ptr) = a;
else NEXT(ptr) = b;
}
return head;
}
/*
** Inputs:
** list: Pointer to a singly-linked list of structures.
** next: Pointer to pointer to the second element of the list.
** cmp: A comparison function.
**
** Return Value:
** A pointer to the head of a sorted list containing the elements
** orginally in list.
**
** Side effects:
** The "next" pointers for elements in list are changed.
*/
#define LISTSIZE 30
char *msort(list,next,cmp)
char *list;
char **next;
int (*cmp)();
{
unsigned long offset;
char *ep;
char *set[LISTSIZE];
int i;
offset = (unsigned long)next - (unsigned long)list;
for(i=0; i<LISTSIZE; i++) set[i] = 0;
while( list ){
ep = list;
list = NEXT(list);
NEXT(ep) = 0;
for(i=0; i<LISTSIZE-1 && set[i]!=0; i++){
ep = merge(ep,set[i],cmp,offset);
set[i] = 0;
}
set[i] = ep;
}
ep = 0;
for(i=0; i<LISTSIZE; i++) if( set[i] ) ep = merge(ep,set[i],cmp,offset);
return ep;
}
/************************ From the file "option.c" **************************/
static char **argv;
static struct s_options *op;
static FILE *errstream;
#define ISOPT(X) ((X)[0]=='-'||(X)[0]=='+'||strchr((X),'=')!=0)
/*
** Print the command line with a carrot pointing to the k-th character
** of the n-th field.
*/
static void errline(n,k,err)
int n;
int k;
FILE *err;
{
int spcnt, i;
spcnt = 0;
if( argv[0] ) fprintf(err,"%s",argv[0]);
spcnt = strlen(argv[0]) + 1;
for(i=1; i<n && argv[i]; i++){
fprintf(err," %s",argv[i]);
spcnt += strlen(argv[i]+1);
}
spcnt += k;
for(; argv[i]; i++) fprintf(err," %s",argv[i]);
if( spcnt<20 ){
fprintf(err,"\n%*s^-- here\n",spcnt,"");
}else{
fprintf(err,"\n%*shere --^\n",spcnt-7,"");
}
}
/*
** Return the index of the N-th non-switch argument. Return -1
** if N is out of range.
*/
static int argindex(n)
int n;
{
int i;
int dashdash = 0;
if( argv!=0 && *argv!=0 ){
for(i=1; argv[i]; i++){
if( dashdash || !ISOPT(argv[i]) ){
if( n==0 ) return i;
n--;
}
if( strcmp(argv[i],"--")==0 ) dashdash = 1;
}
}
return -1;
}
static char emsg[] = "Command line syntax error: ";
/*
** Process a flag command line argument.
*/
static int handleflags(i,err)
int i;
FILE *err;
{
int v;
int errcnt = 0;
int j;
for(j=0; op[j].label; j++){
if( strcmp(&argv[i][1],op[j].label)==0 ) break;
}
v = argv[i][0]=='-' ? 1 : 0;
if( op[j].label==0 ){
if( err ){
fprintf(err,"%sundefined option.\n",emsg);
errline(i,1,err);
}
errcnt++;
}else if( op[j].type==OPT_FLAG ){
*((int*)op[j].arg) = v;
}else if( op[j].type==OPT_FFLAG ){
(*(void(*)())(op[j].arg))(v);
}else{
if( err ){
fprintf(err,"%smissing argument on switch.\n",emsg);
errline(i,1,err);
}
errcnt++;
}
return errcnt;
}
/*
** Process a command line switch which has an argument.
*/
static int handleswitch(i,err)
int i;
FILE *err;
{
int lv = 0;
double dv = 0.0;
char *sv = 0, *end;
char *cp;
int j;
int errcnt = 0;
cp = strchr(argv[i],'=');
*cp = 0;
for(j=0; op[j].label; j++){
if( strcmp(argv[i],op[j].label)==0 ) break;
}
*cp = '=';
if( op[j].label==0 ){
if( err ){
fprintf(err,"%sundefined option.\n",emsg);
errline(i,0,err);
}
errcnt++;
}else{
cp++;
switch( op[j].type ){
case OPT_FLAG:
case OPT_FFLAG:
if( err ){
fprintf(err,"%soption requires an argument.\n",emsg);
errline(i,0,err);
}
errcnt++;
break;
case OPT_DBL:
case OPT_FDBL:
dv = strtod(cp,&end);
if( *end ){
if( err ){
fprintf(err,"%sillegal character in floating-point argument.\n",emsg);
errline(i,((unsigned long)end)-(unsigned long)argv[i],err);
}
errcnt++;
}
break;
case OPT_INT:
case OPT_FINT:
lv = strtol(cp,&end,0);
if( *end ){
if( err ){
fprintf(err,"%sillegal character in integer argument.\n",emsg);
errline(i,((unsigned long)end)-(unsigned long)argv[i],err);
}
errcnt++;
}
break;
case OPT_STR:
case OPT_FSTR:
sv = cp;
break;
}
switch( op[j].type ){
case OPT_FLAG:
case OPT_FFLAG:
break;
case OPT_DBL:
*(double*)(op[j].arg) = dv;
break;
case OPT_FDBL:
(*(void(*)())(op[j].arg))(dv);
break;
case OPT_INT:
*(int*)(op[j].arg) = lv;
break;
case OPT_FINT:
(*(void(*)())(op[j].arg))((int)lv);
break;
case OPT_STR:
*(char**)(op[j].arg) = sv;
break;
case OPT_FSTR:
(*(void(*)())(op[j].arg))(sv);
break;
}
}
return errcnt;
}
int OptInit(a,o,err)
char **a;
struct s_options *o;
FILE *err;
{
int errcnt = 0;
argv = a;
op = o;
errstream = err;
if( argv && *argv && op ){
int i;
for(i=1; argv[i]; i++){
if( argv[i][0]=='+' || argv[i][0]=='-' ){
errcnt += handleflags(i,err);
}else if( strchr(argv[i],'=') ){
errcnt += handleswitch(i,err);
}
}
}
if( errcnt>0 ){
fprintf(err,"Valid command line options for \"%s\" are:\n",*a);
OptPrint();
exit(1);
}
return 0;
}
int OptNArgs(){
int cnt = 0;
int dashdash = 0;
int i;
if( argv!=0 && argv[0]!=0 ){
for(i=1; argv[i]; i++){
if( dashdash || !ISOPT(argv[i]) ) cnt++;
if( strcmp(argv[i],"--")==0 ) dashdash = 1;
}
}
return cnt;
}
char *OptArg(n)
int n;
{
int i;
i = argindex(n);
return i>=0 ? argv[i] : 0;
}
void OptErr(n)
int n;
{
int i;
i = argindex(n);
if( i>=0 ) errline(i,0,errstream);
}
void OptPrint(){
int i;
int max, len;
max = 0;
for(i=0; op[i].label; i++){
len = strlen(op[i].label) + 1;
switch( op[i].type ){
case OPT_FLAG:
case OPT_FFLAG:
break;
case OPT_INT:
case OPT_FINT:
len += 9; /* length of "<integer>" */
break;
case OPT_DBL:
case OPT_FDBL:
len += 6; /* length of "<real>" */
break;
case OPT_STR:
case OPT_FSTR:
len += 8; /* length of "<string>" */
break;
}
if( len>max ) max = len;
}
for(i=0; op[i].label; i++){
switch( op[i].type ){
case OPT_FLAG:
case OPT_FFLAG:
fprintf(errstream," -%-*s %s\n",max,op[i].label,op[i].message);
break;
case OPT_INT:
case OPT_FINT:
fprintf(errstream," %s=<integer>%*s %s\n",op[i].label,
(int)(max-strlen(op[i].label)-9),"",op[i].message);
break;
case OPT_DBL:
case OPT_FDBL:
fprintf(errstream," %s=<real>%*s %s\n",op[i].label,
(int)(max-strlen(op[i].label)-6),"",op[i].message);
break;
case OPT_STR:
case OPT_FSTR:
fprintf(errstream," %s=<string>%*s %s\n",op[i].label,
(int)(max-strlen(op[i].label)-8),"",op[i].message);
break;
}
}
}
/*********************** From the file "parse.c" ****************************/
/*
** Input file parser for the LEMON parser generator.
*/
/* The state of the parser */
struct pstate {
char *filename; /* Name of the input file */
int tokenlineno; /* Linenumber at which current token starts */
int errorcnt; /* Number of errors so far */
char *tokenstart; /* Text of current token */
struct lemon *gp; /* Global state vector */
enum e_state {
INITIALIZE,
WAITING_FOR_DECL_OR_RULE,
WAITING_FOR_DECL_KEYWORD,
WAITING_FOR_DECL_ARG,
WAITING_FOR_PRECEDENCE_SYMBOL,
WAITING_FOR_ARROW,
IN_RHS,
LHS_ALIAS_1,
LHS_ALIAS_2,
LHS_ALIAS_3,
RHS_ALIAS_1,
RHS_ALIAS_2,
PRECEDENCE_MARK_1,
PRECEDENCE_MARK_2,
RESYNC_AFTER_RULE_ERROR,
RESYNC_AFTER_DECL_ERROR,
WAITING_FOR_DESTRUCTOR_SYMBOL,
WAITING_FOR_DATATYPE_SYMBOL,
WAITING_FOR_FALLBACK_ID
} state; /* The state of the parser */
struct symbol *fallback; /* The fallback token */
struct symbol *lhs; /* Left-hand side of current rule */
char *lhsalias; /* Alias for the LHS */
int nrhs; /* Number of right-hand side symbols seen */
struct symbol *rhs[MAXRHS]; /* RHS symbols */
char *alias[MAXRHS]; /* Aliases for each RHS symbol (or NULL) */
struct rule *prevrule; /* Previous rule parsed */
char *declkeyword; /* Keyword of a declaration */
char **declargslot; /* Where the declaration argument should be put */
int *decllnslot; /* Where the declaration linenumber is put */
enum e_assoc declassoc; /* Assign this association to decl arguments */
int preccounter; /* Assign this precedence to decl arguments */
struct rule *firstrule; /* Pointer to first rule in the grammar */
struct rule *lastrule; /* Pointer to the most recently parsed rule */
};
/* Parse a single token */
static void parseonetoken(psp)
struct pstate *psp;
{
char *x;
x = Strsafe(psp->tokenstart); /* Save the token permanently */
#if 0
printf("%s:%d: Token=[%s] state=%d\n",psp->filename,psp->tokenlineno,
x,psp->state);
#endif
switch( psp->state ){
case INITIALIZE:
psp->prevrule = 0;
psp->preccounter = 0;
psp->firstrule = psp->lastrule = 0;
psp->gp->nrule = 0;
/* Fall thru to next case */
case WAITING_FOR_DECL_OR_RULE:
if( x[0]=='%' ){
psp->state = WAITING_FOR_DECL_KEYWORD;
}else if( islower(x[0]) ){
psp->lhs = Symbol_new(x);
psp->nrhs = 0;
psp->lhsalias = 0;
psp->state = WAITING_FOR_ARROW;
}else if( x[0]=='{' ){
if( psp->prevrule==0 ){
ErrorMsg(psp->filename,psp->tokenlineno,
"There is not prior rule opon which to attach the code \
fragment which begins on this line.");
psp->errorcnt++;
}else if( psp->prevrule->code!=0 ){
ErrorMsg(psp->filename,psp->tokenlineno,
"Code fragment beginning on this line is not the first \
to follow the previous rule.");
psp->errorcnt++;
}else{
psp->prevrule->line = psp->tokenlineno;
psp->prevrule->code = &x[1];
}
}else if( x[0]=='[' ){
psp->state = PRECEDENCE_MARK_1;
}else{
ErrorMsg(psp->filename,psp->tokenlineno,
"Token \"%s\" should be either \"%%\" or a nonterminal name.",
x);
psp->errorcnt++;
}
break;
case PRECEDENCE_MARK_1:
if( !isupper(x[0]) ){
ErrorMsg(psp->filename,psp->tokenlineno,
"The precedence symbol must be a terminal.");
psp->errorcnt++;
}else if( psp->prevrule==0 ){
ErrorMsg(psp->filename,psp->tokenlineno,
"There is no prior rule to assign precedence \"[%s]\".",x);
psp->errorcnt++;
}else if( psp->prevrule->precsym!=0 ){
ErrorMsg(psp->filename,psp->tokenlineno,
"Precedence mark on this line is not the first \
to follow the previous rule.");
psp->errorcnt++;
}else{
psp->prevrule->precsym = Symbol_new(x);
}
psp->state = PRECEDENCE_MARK_2;
break;
case PRECEDENCE_MARK_2:
if( x[0]!=']' ){
ErrorMsg(psp->filename,psp->tokenlineno,
"Missing \"]\" on precedence mark.");
psp->errorcnt++;
}
psp->state = WAITING_FOR_DECL_OR_RULE;
break;
case WAITING_FOR_ARROW:
if( x[0]==':' && x[1]==':' && x[2]=='=' ){
psp->state = IN_RHS;
}else if( x[0]=='(' ){
psp->state = LHS_ALIAS_1;
}else{
ErrorMsg(psp->filename,psp->tokenlineno,
"Expected to see a \":\" following the LHS symbol \"%s\".",
psp->lhs->name);
psp->errorcnt++;
psp->state = RESYNC_AFTER_RULE_ERROR;
}
break;
case LHS_ALIAS_1:
if( isalpha(x[0]) ){
psp->lhsalias = x;
psp->state = LHS_ALIAS_2;
}else{
ErrorMsg(psp->filename,psp->tokenlineno,
"\"%s\" is not a valid alias for the LHS \"%s\"\n",
x,psp->lhs->name);
psp->errorcnt++;
psp->state = RESYNC_AFTER_RULE_ERROR;
}
break;
case LHS_ALIAS_2:
if( x[0]==')' ){
psp->state = LHS_ALIAS_3;
}else{
ErrorMsg(psp->filename,psp->tokenlineno,
"Missing \")\" following LHS alias name \"%s\".",psp->lhsalias);
psp->errorcnt++;
psp->state = RESYNC_AFTER_RULE_ERROR;
}
break;
case LHS_ALIAS_3:
if( x[0]==':' && x[1]==':' && x[2]=='=' ){
psp->state = IN_RHS;
}else{
ErrorMsg(psp->filename,psp->tokenlineno,
"Missing \"->\" following: \"%s(%s)\".",
psp->lhs->name,psp->lhsalias);
psp->errorcnt++;
psp->state = RESYNC_AFTER_RULE_ERROR;
}
break;
case IN_RHS:
if( x[0]=='.' ){
struct rule *rp;
rp = (struct rule *)malloc( sizeof(struct rule) +
sizeof(struct symbol*)*psp->nrhs + sizeof(char*)*psp->nrhs );
if( rp==0 ){
ErrorMsg(psp->filename,psp->tokenlineno,
"Can't allocate enough memory for this rule.");
psp->errorcnt++;
psp->prevrule = 0;
}else{
int i;
rp->ruleline = psp->tokenlineno;
rp->rhs = (struct symbol**)&rp[1];
rp->rhsalias = (char**)&(rp->rhs[psp->nrhs]);
for(i=0; i<psp->nrhs; i++){
rp->rhs[i] = psp->rhs[i];
rp->rhsalias[i] = psp->alias[i];
}
rp->lhs = psp->lhs;
rp->lhsalias = psp->lhsalias;
rp->nrhs = psp->nrhs;
rp->code = 0;
rp->precsym = 0;
rp->index = psp->gp->nrule++;
rp->nextlhs = rp->lhs->rule;
rp->lhs->rule = rp;
rp->next = 0;
if( psp->firstrule==0 ){
psp->firstrule = psp->lastrule = rp;
}else{
psp->lastrule->next = rp;
psp->lastrule = rp;
}
psp->prevrule = rp;
}
psp->state = WAITING_FOR_DECL_OR_RULE;
}else if( isalpha(x[0]) ){
if( psp->nrhs>=MAXRHS ){
ErrorMsg(psp->filename,psp->tokenlineno,
"Too many symbol on RHS or rule beginning at \"%s\".",
x);
psp->errorcnt++;
psp->state = RESYNC_AFTER_RULE_ERROR;
}else{
psp->rhs[psp->nrhs] = Symbol_new(x);
psp->alias[psp->nrhs] = 0;
psp->nrhs++;
}
}else if( x[0]=='(' && psp->nrhs>0 ){
psp->state = RHS_ALIAS_1;
}else{
ErrorMsg(psp->filename,psp->tokenlineno,
"Illegal character on RHS of rule: \"%s\".",x);
psp->errorcnt++;
psp->state = RESYNC_AFTER_RULE_ERROR;
}
break;
case RHS_ALIAS_1:
if( isalpha(x[0]) ){
psp->alias[psp->nrhs-1] = x;
psp->state = RHS_ALIAS_2;
}else{
ErrorMsg(psp->filename,psp->tokenlineno,
"\"%s\" is not a valid alias for the RHS symbol \"%s\"\n",
x,psp->rhs[psp->nrhs-1]->name);
psp->errorcnt++;
psp->state = RESYNC_AFTER_RULE_ERROR;
}
break;
case RHS_ALIAS_2:
if( x[0]==')' ){
psp->state = IN_RHS;
}else{
ErrorMsg(psp->filename,psp->tokenlineno,
"Missing \")\" following LHS alias name \"%s\".",psp->lhsalias);
psp->errorcnt++;
psp->state = RESYNC_AFTER_RULE_ERROR;
}
break;
case WAITING_FOR_DECL_KEYWORD:
if( isalpha(x[0]) ){
psp->declkeyword = x;
psp->declargslot = 0;
psp->decllnslot = 0;
psp->state = WAITING_FOR_DECL_ARG;
if( strcmp(x,"name")==0 ){
psp->declargslot = &(psp->gp->name);
}else if( strcmp(x,"include")==0 ){
psp->declargslot = &(psp->gp->include);
psp->decllnslot = &psp->gp->includeln;
}else if( strcmp(x,"code")==0 ){
psp->declargslot = &(psp->gp->extracode);
psp->decllnslot = &psp->gp->extracodeln;
}else if( strcmp(x,"token_destructor")==0 ){
psp->declargslot = &psp->gp->tokendest;
psp->decllnslot = &psp->gp->tokendestln;
}else if( strcmp(x,"default_destructor")==0 ){
psp->declargslot = &psp->gp->vardest;
psp->decllnslot = &psp->gp->vardestln;
}else if( strcmp(x,"token_prefix")==0 ){
psp->declargslot = &psp->gp->tokenprefix;
}else if( strcmp(x,"syntax_error")==0 ){
psp->declargslot = &(psp->gp->error);
psp->decllnslot = &psp->gp->errorln;
}else if( strcmp(x,"parse_accept")==0 ){
psp->declargslot = &(psp->gp->accept);
psp->decllnslot = &psp->gp->acceptln;
}else if( strcmp(x,"parse_failure")==0 ){
psp->declargslot = &(psp->gp->failure);
psp->decllnslot = &psp->gp->failureln;
}else if( strcmp(x,"stack_overflow")==0 ){
psp->declargslot = &(psp->gp->overflow);
psp->decllnslot = &psp->gp->overflowln;
}else if( strcmp(x,"extra_argument")==0 ){
psp->declargslot = &(psp->gp->arg);
}else if( strcmp(x,"token_type")==0 ){
psp->declargslot = &(psp->gp->tokentype);
}else if( strcmp(x,"default_type")==0 ){
psp->declargslot = &(psp->gp->vartype);
}else if( strcmp(x,"stack_size")==0 ){
psp->declargslot = &(psp->gp->stacksize);
}else if( strcmp(x,"start_symbol")==0 ){
psp->declargslot = &(psp->gp->start);
}else if( strcmp(x,"left")==0 ){
psp->preccounter++;
psp->declassoc = LEFT;
psp->state = WAITING_FOR_PRECEDENCE_SYMBOL;
}else if( strcmp(x,"right")==0 ){
psp->preccounter++;
psp->declassoc = RIGHT;
psp->state = WAITING_FOR_PRECEDENCE_SYMBOL;
}else if( strcmp(x,"nonassoc")==0 ){
psp->preccounter++;
psp->declassoc = NONE;
psp->state = WAITING_FOR_PRECEDENCE_SYMBOL;
}else if( strcmp(x,"destructor")==0 ){
psp->state = WAITING_FOR_DESTRUCTOR_SYMBOL;
}else if( strcmp(x,"type")==0 ){
psp->state = WAITING_FOR_DATATYPE_SYMBOL;
}else if( strcmp(x,"fallback")==0 ){
psp->fallback = 0;
psp->state = WAITING_FOR_FALLBACK_ID;
}else{
ErrorMsg(psp->filename,psp->tokenlineno,
"Unknown declaration keyword: \"%%%s\".",x);
psp->errorcnt++;
psp->state = RESYNC_AFTER_DECL_ERROR;
}
}else{
ErrorMsg(psp->filename,psp->tokenlineno,
"Illegal declaration keyword: \"%s\".",x);
psp->errorcnt++;
psp->state = RESYNC_AFTER_DECL_ERROR;
}
break;
case WAITING_FOR_DESTRUCTOR_SYMBOL:
if( !isalpha(x[0]) ){
ErrorMsg(psp->filename,psp->tokenlineno,
"Symbol name missing after %destructor keyword");
psp->errorcnt++;
psp->state = RESYNC_AFTER_DECL_ERROR;
}else{
struct symbol *sp = Symbol_new(x);
psp->declargslot = &sp->destructor;
psp->decllnslot = &sp->destructorln;
psp->state = WAITING_FOR_DECL_ARG;
}
break;
case WAITING_FOR_DATATYPE_SYMBOL:
if( !isalpha(x[0]) ){
ErrorMsg(psp->filename,psp->tokenlineno,
"Symbol name missing after %destructor keyword");
psp->errorcnt++;
psp->state = RESYNC_AFTER_DECL_ERROR;
}else{
struct symbol *sp = Symbol_new(x);
psp->declargslot = &sp->datatype;
psp->decllnslot = 0;
psp->state = WAITING_FOR_DECL_ARG;
}
break;
case WAITING_FOR_PRECEDENCE_SYMBOL:
if( x[0]=='.' ){
psp->state = WAITING_FOR_DECL_OR_RULE;
}else if( isupper(x[0]) ){
struct symbol *sp;
sp = Symbol_new(x);
if( sp->prec>=0 ){
ErrorMsg(psp->filename,psp->tokenlineno,
"Symbol \"%s\" has already be given a precedence.",x);
psp->errorcnt++;
}else{
sp->prec = psp->preccounter;
sp->assoc = psp->declassoc;
}
}else{
ErrorMsg(psp->filename,psp->tokenlineno,
"Can't assign a precedence to \"%s\".",x);
psp->errorcnt++;
}
break;
case WAITING_FOR_DECL_ARG:
if( (x[0]=='{' || x[0]=='\"' || isalnum(x[0])) ){
if( *(psp->declargslot)!=0 ){
ErrorMsg(psp->filename,psp->tokenlineno,
"The argument \"%s\" to declaration \"%%%s\" is not the first.",
x[0]=='\"' ? &x[1] : x,psp->declkeyword);
psp->errorcnt++;
psp->state = RESYNC_AFTER_DECL_ERROR;
}else{
*(psp->declargslot) = (x[0]=='\"' || x[0]=='{') ? &x[1] : x;
if( psp->decllnslot ) *psp->decllnslot = psp->tokenlineno;
psp->state = WAITING_FOR_DECL_OR_RULE;
}
}else{
ErrorMsg(psp->filename,psp->tokenlineno,
"Illegal argument to %%%s: %s",psp->declkeyword,x);
psp->errorcnt++;
psp->state = RESYNC_AFTER_DECL_ERROR;
}
break;
case WAITING_FOR_FALLBACK_ID:
if( x[0]=='.' ){
psp->state = WAITING_FOR_DECL_OR_RULE;
}else if( !isupper(x[0]) ){
ErrorMsg(psp->filename, psp->tokenlineno,
"%%fallback argument \"%s\" should be a token", x);
psp->errorcnt++;
}else{
struct symbol *sp = Symbol_new(x);
if( psp->fallback==0 ){
psp->fallback = sp;
}else if( sp->fallback ){
ErrorMsg(psp->filename, psp->tokenlineno,
"More than one fallback assigned to token %s", x);
psp->errorcnt++;
}else{
sp->fallback = psp->fallback;
psp->gp->has_fallback = 1;
}
}
break;
case RESYNC_AFTER_RULE_ERROR:
/* if( x[0]=='.' ) psp->state = WAITING_FOR_DECL_OR_RULE;
** break; */
case RESYNC_AFTER_DECL_ERROR:
if( x[0]=='.' ) psp->state = WAITING_FOR_DECL_OR_RULE;
if( x[0]=='%' ) psp->state = WAITING_FOR_DECL_KEYWORD;
break;
}
}
/* In spite of its name, this function is really a scanner. It read
** in the entire input file (all at once) then tokenizes it. Each
** token is passed to the function "parseonetoken" which builds all
** the appropriate data structures in the global state vector "gp".
*/
void Parse(gp)
struct lemon *gp;
{
struct pstate ps;
FILE *fp;
char *filebuf;
size_t filesize;
int lineno;
int c;
char *cp, *nextcp;
int startline = 0;
ps.gp = gp;
ps.filename = gp->filename;
ps.errorcnt = 0;
ps.state = INITIALIZE;
/* Begin by reading the input file */
fp = fopen(ps.filename,"rb");
if( fp==0 ){
ErrorMsg(ps.filename,0,"Can't open this file for reading.");
gp->errorcnt++;
return;
}
fseek(fp,0,2);
filesize = ftell(fp);
rewind(fp);
filebuf = (char *)malloc( filesize+1 );
if( filebuf==0 ){
ErrorMsg(ps.filename,0,"Can't allocate %d of memory to hold this file.",
filesize+1);
gp->errorcnt++;
return;
}
if( fread(filebuf,1,filesize,fp)!=filesize ){
ErrorMsg(ps.filename,0,"Can't read in all %d bytes of this file.",
filesize);
free(filebuf);
gp->errorcnt++;
return;
}
fclose(fp);
filebuf[filesize] = 0;
/* Now scan the text of the input file */
lineno = 1;
for(cp=filebuf; (c= *cp)!=0; ){
if( c=='\n' ) lineno++; /* Keep track of the line number */
if( isspace(c) ){ cp++; continue; } /* Skip all white space */
if( c=='/' && cp[1]=='/' ){ /* Skip C++ style comments */
cp+=2;
while( (c= *cp)!=0 && c!='\n' ) cp++;
continue;
}
if( c=='/' && cp[1]=='*' ){ /* Skip C style comments */
cp+=2;
while( (c= *cp)!=0 && (c!='/' || cp[-1]!='*') ){
if( c=='\n' ) lineno++;
cp++;
}
if( c ) cp++;
continue;
}
ps.tokenstart = cp; /* Mark the beginning of the token */
ps.tokenlineno = lineno; /* Linenumber on which token begins */
if( c=='\"' ){ /* String literals */
cp++;
while( (c= *cp)!=0 && c!='\"' ){
if( c=='\n' ) lineno++;
cp++;
}
if( c==0 ){
ErrorMsg(ps.filename,startline,
"String starting on this line is not terminated before the end of the file.");
ps.errorcnt++;
nextcp = cp;
}else{
nextcp = cp+1;
}
}else if( c=='{' ){ /* A block of C code */
int level;
cp++;
for(level=1; (c= *cp)!=0 && (level>1 || c!='}'); cp++){
if( c=='\n' ) lineno++;
else if( c=='{' ) level++;
else if( c=='}' ) level--;
else if( c=='/' && cp[1]=='*' ){ /* Skip comments */
int prevc;
cp = &cp[2];
prevc = 0;
while( (c= *cp)!=0 && (c!='/' || prevc!='*') ){
if( c=='\n' ) lineno++;
prevc = c;
cp++;
}
}else if( c=='/' && cp[1]=='/' ){ /* Skip C++ style comments too */
cp = &cp[2];
while( (c= *cp)!=0 && c!='\n' ) cp++;
if( c ) lineno++;
}else if( c=='\'' || c=='\"' ){ /* String a character literals */
int startchar, prevc;
startchar = c;
prevc = 0;
for(cp++; (c= *cp)!=0 && (c!=startchar || prevc=='\\'); cp++){
if( c=='\n' ) lineno++;
if( prevc=='\\' ) prevc = 0;
else prevc = c;
}
}
}
if( c==0 ){
ErrorMsg(ps.filename,ps.tokenlineno,
"C code starting on this line is not terminated before the end of the file.");
ps.errorcnt++;
nextcp = cp;
}else{
nextcp = cp+1;
}
}else if( isalnum(c) ){ /* Identifiers */
while( (c= *cp)!=0 && (isalnum(c) || c=='_') ) cp++;
nextcp = cp;
}else if( c==':' && cp[1]==':' && cp[2]=='=' ){ /* The operator "::=" */
cp += 3;
nextcp = cp;
}else{ /* All other (one character) operators */
cp++;
nextcp = cp;
}
c = *cp;
*cp = 0; /* Null terminate the token */
parseonetoken(&ps); /* Parse the token */
*cp = c; /* Restore the buffer */
cp = nextcp;
}
free(filebuf); /* Release the buffer after parsing */
gp->rule = ps.firstrule;
gp->errorcnt = ps.errorcnt;
}
/*************************** From the file "plink.c" *********************/
/*
** Routines processing configuration follow-set propagation links
** in the LEMON parser generator.
*/
static struct plink *plink_freelist = 0;
/* Allocate a new plink */
struct plink *Plink_new(){
struct plink *new;
if( plink_freelist==0 ){
int i;
int amt = 100;
plink_freelist = (struct plink *)malloc( sizeof(struct plink)*amt );
if( plink_freelist==0 ){
fprintf(stderr,
"Unable to allocate memory for a new follow-set propagation link.\n");
exit(1);
}
for(i=0; i<amt-1; i++) plink_freelist[i].next = &plink_freelist[i+1];
plink_freelist[amt-1].next = 0;
}
new = plink_freelist;
plink_freelist = plink_freelist->next;
return new;
}
/* Add a plink to a plink list */
void Plink_add(plpp,cfp)
struct plink **plpp;
struct config *cfp;
{
struct plink *new;
new = Plink_new();
new->next = *plpp;
*plpp = new;
new->cfp = cfp;
}
/* Transfer every plink on the list "from" to the list "to" */
void Plink_copy(to,from)
struct plink **to;
struct plink *from;
{
struct plink *nextpl;
while( from ){
nextpl = from->next;
from->next = *to;
*to = from;
from = nextpl;
}
}
/* Delete every plink on the list */
void Plink_delete(plp)
struct plink *plp;
{
struct plink *nextpl;
while( plp ){
nextpl = plp->next;
plp->next = plink_freelist;
plink_freelist = plp;
plp = nextpl;
}
}
/*********************** From the file "report.c" **************************/
/*
** Procedures for generating reports and tables in the LEMON parser generator.
*/
/* Generate a filename with the given suffix. Space to hold the
** name comes from malloc() and must be freed by the calling
** function.
*/
PRIVATE char *file_makename(lemp,suffix)
struct lemon *lemp;
char *suffix;
{
char *name;
char *cp;
name = malloc( strlen(lemp->filename) + strlen(suffix) + 5 );
if( name==0 ){
fprintf(stderr,"Can't allocate space for a filename.\n");
exit(1);
}
/* skip directory, JK */
if (NULL == (cp = strrchr(lemp->filename, '/'))) {
cp = lemp->filename;
} else {
cp++;
}
strcpy(name,cp);
cp = strrchr(name,'.');
if( cp ) *cp = 0;
strcat(name,suffix);
return name;
}
/* Open a file with a name based on the name of the input file,
** but with a different (specified) suffix, and return a pointer
** to the stream */
PRIVATE FILE *file_open(lemp,suffix,mode)
struct lemon *lemp;
char *suffix;
char *mode;
{
FILE *fp;
if( lemp->outname ) free(lemp->outname);
lemp->outname = file_makename(lemp, suffix);
fp = fopen(lemp->outname,mode);
if( fp==0 && *mode=='w' ){
fprintf(stderr,"Can't open file \"%s\".\n",lemp->outname);
lemp->errorcnt++;
return 0;
}
return fp;
}
/* Duplicate the input file without comments and without actions
** on rules */
void Reprint(lemp)
struct lemon *lemp;
{
struct rule *rp;
struct symbol *sp;
int i, j, maxlen, len, ncolumns, skip;
printf("// Reprint of input file \"%s\".\n// Symbols:\n",lemp->filename);
maxlen = 10;
for(i=0; i<lemp->nsymbol; i++){
sp = lemp->symbols[i];
len = strlen(sp->name);
if( len>maxlen ) maxlen = len;
}
ncolumns = 76/(maxlen+5);
if( ncolumns<1 ) ncolumns = 1;
skip = (lemp->nsymbol + ncolumns - 1)/ncolumns;
for(i=0; i<skip; i++){
printf("//");
for(j=i; j<lemp->nsymbol; j+=skip){
sp = lemp->symbols[j];
assert( sp->index==j );
printf(" %3d %-*.*s",j,maxlen,maxlen,sp->name);
}
printf("\n");
}
for(rp=lemp->rule; rp; rp=rp->next){
printf("%s",rp->lhs->name);
/* if( rp->lhsalias ) printf("(%s)",rp->lhsalias); */
printf(" ::=");
for(i=0; i<rp->nrhs; i++){
printf(" %s",rp->rhs[i]->name);
/* if( rp->rhsalias[i] ) printf("(%s)",rp->rhsalias[i]); */
}
printf(".");
if( rp->precsym ) printf(" [%s]",rp->precsym->name);
/* if( rp->code ) printf("\n %s",rp->code); */
printf("\n");
}
}
void ConfigPrint(fp,cfp)
FILE *fp;
struct config *cfp;
{
struct rule *rp;
int i;
rp = cfp->rp;
fprintf(fp,"%s ::=",rp->lhs->name);
for(i=0; i<=rp->nrhs; i++){
if( i==cfp->dot ) fprintf(fp," *");
if( i==rp->nrhs ) break;
fprintf(fp," %s",rp->rhs[i]->name);
}
}
/* #define TEST */
#ifdef TEST
/* Print a set */
PRIVATE void SetPrint(out,set,lemp)
FILE *out;
char *set;
struct lemon *lemp;
{
int i;
char *spacer;
spacer = "";
fprintf(out,"%12s[","");
for(i=0; i<lemp->nterminal; i++){
if( SetFind(set,i) ){
fprintf(out,"%s%s",spacer,lemp->symbols[i]->name);
spacer = " ";
}
}
fprintf(out,"]\n");
}
/* Print a plink chain */
PRIVATE void PlinkPrint(out,plp,tag)
FILE *out;
struct plink *plp;
char *tag;
{
while( plp ){
fprintf(out,"%12s%s (state %2d) ","",tag,plp->cfp->stp->index);
ConfigPrint(out,plp->cfp);
fprintf(out,"\n");
plp = plp->next;
}
}
#endif
/* Print an action to the given file descriptor. Return FALSE if
** nothing was actually printed.
*/
int PrintAction(struct action *ap, FILE *fp, int indent){
int result = 1;
switch( ap->type ){
case SHIFT:
fprintf(fp,"%*s shift %d",indent,ap->sp->name,ap->x.stp->index);
break;
case REDUCE:
fprintf(fp,"%*s reduce %d",indent,ap->sp->name,ap->x.rp->index);
break;
case ACCEPT:
fprintf(fp,"%*s accept",indent,ap->sp->name);
break;
case ERROR:
fprintf(fp,"%*s error",indent,ap->sp->name);
break;
case CONFLICT:
fprintf(fp,"%*s reduce %-3d ** Parsing conflict **",
indent,ap->sp->name,ap->x.rp->index);
break;
case SH_RESOLVED:
case RD_RESOLVED:
case NOT_USED:
result = 0;
break;
}
return result;
}
/* Generate the "y.output" log file */
void ReportOutput(lemp)
struct lemon *lemp;
{
int i;
struct state *stp;
struct config *cfp;
struct action *ap;
FILE *fp;
fp = file_open(lemp,".out","w");
if( fp==0 ) return;
fprintf(fp," \b");
for(i=0; i<lemp->nstate; i++){
stp = lemp->sorted[i];
fprintf(fp,"State %d:\n",stp->index);
if( lemp->basisflag ) cfp=stp->bp;
else cfp=stp->cfp;
while( cfp ){
char buf[20];
if( cfp->dot==cfp->rp->nrhs ){
sprintf(buf,"(%d)",cfp->rp->index);
fprintf(fp," %5s ",buf);
}else{
fprintf(fp," ");
}
ConfigPrint(fp,cfp);
fprintf(fp,"\n");
#ifdef TEST
SetPrint(fp,cfp->fws,lemp);
PlinkPrint(fp,cfp->fplp,"To ");
PlinkPrint(fp,cfp->bplp,"From");
#endif
if( lemp->basisflag ) cfp=cfp->bp;
else cfp=cfp->next;
}
fprintf(fp,"\n");
for(ap=stp->ap; ap; ap=ap->next){
if( PrintAction(ap,fp,30) ) fprintf(fp,"\n");
}
fprintf(fp,"\n");
}
fclose(fp);
return;
}
/* Search for the file "name" which is in the same directory as
** the exacutable */
PRIVATE char *pathsearch(argv0,name,modemask)
char *argv0;
char *name;
int modemask;
{
char *pathlist;
char *path,*cp;
char c;
extern int access();
#ifdef __WIN32__
cp = strrchr(argv0,'\\');
#else
cp = strrchr(argv0,'/');
#endif
if( cp ){
c = *cp;
*cp = 0;
path = (char *)malloc( strlen(argv0) + strlen(name) + 2 );
if( path ) sprintf(path,"%s/%s",argv0,name);
*cp = c;
}else{
extern char *getenv();
pathlist = getenv("PATH");
if( pathlist==0 ) pathlist = ".:/bin:/usr/bin";
path = (char *)malloc( strlen(pathlist)+strlen(name)+2 );
if( path!=0 ){
while( *pathlist ){
cp = strchr(pathlist,':');
if( cp==0 ) cp = &pathlist[strlen(pathlist)];
c = *cp;
*cp = 0;
sprintf(path,"%s/%s",pathlist,name);
*cp = c;
if( c==0 ) pathlist = "";
else pathlist = &cp[1];
if( access(path,modemask)==0 ) break;
}
}
}
return path;
}
/* Given an action, compute the integer value for that action
** which is to be put in the action table of the generated machine.
** Return negative if no action should be generated.
*/
PRIVATE int compute_action(lemp,ap)
struct lemon *lemp;
struct action *ap;
{
int act;
switch( ap->type ){
case SHIFT: act = ap->x.stp->index; break;
case REDUCE: act = ap->x.rp->index + lemp->nstate; break;
case ERROR: act = lemp->nstate + lemp->nrule; break;
case ACCEPT: act = lemp->nstate + lemp->nrule + 1; break;
default: act = -1; break;
}
return act;
}
#define LINESIZE 1000
/* The next cluster of routines are for reading the template file
** and writing the results to the generated parser */
/* The first function transfers data from "in" to "out" until
** a line is seen which begins with "%%". The line number is
** tracked.
**
** if name!=0, then any word that begin with "Parse" is changed to
** begin with *name instead.
*/
PRIVATE void tplt_xfer(name,in,out,lineno)
char *name;
FILE *in;
FILE *out;
int *lineno;
{
int i, iStart;
char line[LINESIZE];
while( fgets(line,LINESIZE,in) && (line[0]!='%' || line[1]!='%') ){
(*lineno)++;
iStart = 0;
if( name ){
for(i=0; line[i]; i++){
if( line[i]=='P' && strncmp(&line[i],"Parse",5)==0
&& (i==0 || !isalpha(line[i-1]))
){
if( i>iStart ) fprintf(out,"%.*s",i-iStart,&line[iStart]);
fprintf(out,"%s",name);
i += 4;
iStart = i+1;
}
}
}
fprintf(out,"%s",&line[iStart]);
}
}
/* The next function finds the template file and opens it, returning
** a pointer to the opened file. */
PRIVATE FILE *tplt_open(lemp)
struct lemon *lemp;
{
char buf[1000];
FILE *in;
char *tpltname;
char *cp;
cp = strrchr(lemp->filename,'.');
if( cp ){
sprintf(buf,"%.*s.lt",(int)(cp-lemp->filename),lemp->filename);
}else{
sprintf(buf,"%s.lt",lemp->filename);
}
if( access(buf,004)==0 ){
tpltname = buf;
}else if( access(lemp->tmplname,004)==0 ){
tpltname = lemp->tmplname;
}else{
tpltname = pathsearch(lemp->argv0,lemp->tmplname,0);
}
if( tpltname==0 ){
fprintf(stderr,"Can't find the parser driver template file \"%s\".\n",
lemp->tmplname);
lemp->errorcnt++;
return 0;
}
in = fopen(tpltname,"r");
if( in==0 ){
fprintf(stderr,"Can't open the template file \"%s\".\n",lemp->tmplname);
lemp->errorcnt++;
return 0;
}
return in;
}
/* Print a string to the file and keep the linenumber up to date */
PRIVATE void tplt_print(out,lemp,str,strln,lineno)
FILE *out;
struct lemon *lemp;
char *str;
int strln;
int *lineno;
{
if( str==0 ) return;
fprintf(out,"#line %d \"%s\"\n",strln,lemp->filename); (*lineno)++;
while( *str ){
if( *str=='\n' ) (*lineno)++;
putc(*str,out);
str++;
}
fprintf(out,"\n#line %d \"%s\"\n",*lineno+2,lemp->outname); (*lineno)+=2;
return;
}
/*
** The following routine emits code for the destructor for the
** symbol sp
*/
void emit_destructor_code(out,sp,lemp,lineno)
FILE *out;
struct symbol *sp;
struct lemon *lemp;
int *lineno;
{
char *cp = 0;
int linecnt = 0;
if( sp->type==TERMINAL ){
cp = lemp->tokendest;
if( cp==0 ) return;
fprintf(out,"#line %d \"%s\"\n{",lemp->tokendestln,lemp->filename);
}else if( sp->destructor ){
cp = sp->destructor;
fprintf(out,"#line %d \"%s\"\n{",sp->destructorln,lemp->filename);
}else if( lemp->vardest ){
cp = lemp->vardest;
if( cp==0 ) return;
fprintf(out,"#line %d \"%s\"\n{",lemp->vardestln,lemp->filename);
}
for(; *cp; cp++){
if( *cp=='$' && cp[1]=='$' ){
fprintf(out,"(yypminor->yy%d)",sp->dtnum);
cp++;
continue;
}
if( *cp=='\n' ) linecnt++;
fputc(*cp,out);
}
(*lineno) += 3 + linecnt;
fprintf(out,"}\n#line %d \"%s\"\n",*lineno,lemp->outname);
return;
}
/*
** Return TRUE (non-zero) if the given symbol has a destructor.
*/
int has_destructor(sp, lemp)
struct symbol *sp;
struct lemon *lemp;
{
int ret;
if( sp->type==TERMINAL ){
ret = lemp->tokendest!=0;
}else{
ret = lemp->vardest!=0 || sp->destructor!=0;
}
return ret;
}
/*
** Generate code which executes when the rule "rp" is reduced. Write
** the code to "out". Make sure lineno stays up-to-date.
*/
PRIVATE void emit_code(out,rp,lemp,lineno)
FILE *out;
struct rule *rp;
struct lemon *lemp;
int *lineno;
{
char *cp, *xp;
int linecnt = 0;
int i;
char lhsused = 0; /* True if the LHS element has been used */
char used[MAXRHS]; /* True for each RHS element which is used */
for(i=0; i<rp->nrhs; i++) used[i] = 0;
lhsused = 0;
/* Generate code to do the reduce action */
if( rp->code ){
fprintf(out,"#line %d \"%s\"\n{",rp->line,lemp->filename);
for(cp=rp->code; *cp; cp++){
if( isalpha(*cp) && (cp==rp->code || (!isalnum(cp[-1]) && cp[-1]!='_')) ){
char saved;
for(xp= &cp[1]; isalnum(*xp) || *xp=='_'; xp++);
saved = *xp;
*xp = 0;
if( rp->lhsalias && strcmp(cp,rp->lhsalias)==0 ){
fprintf(out,"yygotominor.yy%d",rp->lhs->dtnum);
cp = xp;
lhsused = 1;
}else{
for(i=0; i<rp->nrhs; i++){
if( rp->rhsalias[i] && strcmp(cp,rp->rhsalias[i])==0 ){
fprintf(out,"yymsp[%d].minor.yy%d",i-rp->nrhs+1,rp->rhs[i]->dtnum);
cp = xp;
used[i] = 1;
break;
}
}
}
*xp = saved;
}
if( *cp=='\n' ) linecnt++;
fputc(*cp,out);
} /* End loop */
(*lineno) += 3 + linecnt;
fprintf(out,"}\n#line %d \"%s\"\n",*lineno,lemp->outname);
} /* End if( rp->code ) */
/* Check to make sure the LHS has been used */
if( rp->lhsalias && !lhsused ){
ErrorMsg(lemp->filename,rp->ruleline,
"Label \"%s\" for \"%s(%s)\" is never used.",
rp->lhsalias,rp->lhs->name,rp->lhsalias);
lemp->errorcnt++;
}
/* Generate destructor code for RHS symbols which are not used in the
** reduce code */
for(i=0; i<rp->nrhs; i++){
if( rp->rhsalias[i] && !used[i] ){
ErrorMsg(lemp->filename,rp->ruleline,
"Label %s for \"%s(%s)\" is never used.",
rp->rhsalias[i],rp->rhs[i]->name,rp->rhsalias[i]);
lemp->errorcnt++;
}else if( rp->rhsalias[i]==0 ){
if( has_destructor(rp->rhs[i],lemp) ){
fprintf(out," yy_destructor(%d,&yymsp[%d].minor);\n",
rp->rhs[i]->index,i-rp->nrhs+1); (*lineno)++;
}else{
fprintf(out," /* No destructor defined for %s */\n",
rp->rhs[i]->name);
(*lineno)++;
}
}
}
return;
}
/*
** Print the definition of the union used for the parser's data stack.
** This union contains fields for every possible data type for tokens
** and nonterminals. In the process of computing and printing this
** union, also set the ".dtnum" field of every terminal and nonterminal
** symbol.
*/
void print_stack_union(out,lemp,plineno,mhflag)
FILE *out; /* The output stream */
struct lemon *lemp; /* The main info structure for this parser */
int *plineno; /* Pointer to the line number */
int mhflag; /* True if generating makeheaders output */
{
int lineno = *plineno; /* The line number of the output */
char **types; /* A hash table of datatypes */
int arraysize; /* Size of the "types" array */
int maxdtlength; /* Maximum length of any ".datatype" field. */
char *stddt; /* Standardized name for a datatype */
int i,j; /* Loop counters */
int hash; /* For hashing the name of a type */
char *name; /* Name of the parser */
/* Allocate and initialize types[] and allocate stddt[] */
arraysize = lemp->nsymbol * 2;
types = (char**)malloc( arraysize * sizeof(char*) );
for(i=0; i<arraysize; i++) types[i] = 0;
maxdtlength = 0;
if( lemp->vartype ){
maxdtlength = strlen(lemp->vartype);
}
for(i=0; i<lemp->nsymbol; i++){
int len;
struct symbol *sp = lemp->symbols[i];
if( sp->datatype==0 ) continue;
len = strlen(sp->datatype);
if( len>maxdtlength ) maxdtlength = len;
}
stddt = (char*)malloc( maxdtlength*2 + 1 );
if( types==0 || stddt==0 ){
fprintf(stderr,"Out of memory.\n");
exit(1);
}
/* Build a hash table of datatypes. The ".dtnum" field of each symbol
** is filled in with the hash index plus 1. A ".dtnum" value of 0 is
** used for terminal symbols. If there is no %default_type defined then
** 0 is also used as the .dtnum value for nonterminals which do not specify
** a datatype using the %type directive.
*/
for(i=0; i<lemp->nsymbol; i++){
struct symbol *sp = lemp->symbols[i];
char *cp;
if( sp==lemp->errsym ){
sp->dtnum = arraysize+1;
continue;
}
if( sp->type!=NONTERMINAL || (sp->datatype==0 && lemp->vartype==0) ){
sp->dtnum = 0;
continue;
}
cp = sp->datatype;
if( cp==0 ) cp = lemp->vartype;
j = 0;
while( isspace(*cp) ) cp++;
while( *cp ) stddt[j++] = *cp++;
while( j>0 && isspace(stddt[j-1]) ) j--;
stddt[j] = 0;
hash = 0;
for(j=0; stddt[j]; j++){
hash = hash*53 + stddt[j];
}
hash = (hash & 0x7fffffff)%arraysize;
while( types[hash] ){
if( strcmp(types[hash],stddt)==0 ){
sp->dtnum = hash + 1;
break;
}
hash++;
if( hash>=arraysize ) hash = 0;
}
if( types[hash]==0 ){
sp->dtnum = hash + 1;
types[hash] = (char*)malloc( strlen(stddt)+1 );
if( types[hash]==0 ){
fprintf(stderr,"Out of memory.\n");
exit(1);
}
strcpy(types[hash],stddt);
}
}
/* Print out the definition of YYTOKENTYPE and YYMINORTYPE */
name = lemp->name ? lemp->name : "Parse";
lineno = *plineno;
if( mhflag ){ fprintf(out,"#if INTERFACE\n"); lineno++; }
fprintf(out,"#define %sTOKENTYPE %s\n",name,
lemp->tokentype?lemp->tokentype:"void*"); lineno++;
if( mhflag ){ fprintf(out,"#endif\n"); lineno++; }
fprintf(out,"typedef union {\n"); lineno++;
fprintf(out," %sTOKENTYPE yy0;\n",name); lineno++;
for(i=0; i<arraysize; i++){
if( types[i]==0 ) continue;
fprintf(out," %s yy%d;\n",types[i],i+1); lineno++;
free(types[i]);
}
fprintf(out," int yy%d;\n",lemp->errsym->dtnum); lineno++;
free(stddt);
free(types);
fprintf(out,"} YYMINORTYPE;\n"); lineno++;
*plineno = lineno;
}
/*
** Return the name of a C datatype able to represent values between
** lwr and upr, inclusive.
*/
static const char *minimum_size_type(int lwr, int upr){
if( lwr>=0 ){
if( upr<=255 ){
return "unsigned char";
}else if( upr<65535 ){
return "unsigned short int";
}else{
return "unsigned int";
}
}else if( lwr>=-127 && upr<=127 ){
return "signed char";
}else if( lwr>=-32767 && upr<32767 ){
return "short";
}else{
return "int";
}
}
/*
** Each state contains a set of token transaction and a set of
** nonterminal transactions. Each of these sets makes an instance
** of the following structure. An array of these structures is used
** to order the creation of entries in the yy_action[] table.
*/
struct axset {
struct state *stp; /* A pointer to a state */
int isTkn; /* True to use tokens. False for non-terminals */
int nAction; /* Number of actions */
};
/*
** Compare to axset structures for sorting purposes
*/
static int axset_compare(const void *a, const void *b){
struct axset *p1 = (struct axset*)a;
struct axset *p2 = (struct axset*)b;
return p2->nAction - p1->nAction;
}
/* Generate C source code for the parser */
void ReportTable(lemp, mhflag)
struct lemon *lemp;
int mhflag; /* Output in makeheaders format if true */
{
FILE *out, *in;
char line[LINESIZE];
int lineno;
struct state *stp;
struct action *ap;
struct rule *rp;
struct acttab *pActtab;
int i, j, n;
int mnTknOfst, mxTknOfst;
int mnNtOfst, mxNtOfst;
struct axset *ax;
char *name;
in = tplt_open(lemp);
if( in==0 ) return;
out = file_open(lemp,".c","w");
if( out==0 ){
fclose(in);
return;
}
lineno = 1;
tplt_xfer(lemp->name,in,out,&lineno);
/* Generate the include code, if any */
tplt_print(out,lemp,lemp->include,lemp->includeln,&lineno);
if( mhflag ){
name = file_makename(lemp, ".h");
fprintf(out,"#include \"%s\"\n", name); lineno++;
free(name);
}
tplt_xfer(lemp->name,in,out,&lineno);
/* Generate #defines for all tokens */
if( mhflag ){
char *prefix;
fprintf(out,"#if INTERFACE\n"); lineno++;
if( lemp->tokenprefix ) prefix = lemp->tokenprefix;
else prefix = "";
for(i=1; i<lemp->nterminal; i++){
fprintf(out,"#define %s%-30s %2d\n",prefix,lemp->symbols[i]->name,i);
lineno++;
}
fprintf(out,"#endif\n"); lineno++;
}
tplt_xfer(lemp->name,in,out,&lineno);
/* Generate the defines */
fprintf(out,"/* \001 */\n");
fprintf(out,"#define YYCODETYPE %s\n",
minimum_size_type(0, lemp->nsymbol+5)); lineno++;
fprintf(out,"#define YYNOCODE %d\n",lemp->nsymbol+1); lineno++;
fprintf(out,"#define YYACTIONTYPE %s\n",
minimum_size_type(0, lemp->nstate+lemp->nrule+5)); lineno++;
print_stack_union(out,lemp,&lineno,mhflag);
if( lemp->stacksize ){
if( atoi(lemp->stacksize)<=0 ){
ErrorMsg(lemp->filename,0,
"Illegal stack size: [%s]. The stack size should be an integer constant.",
lemp->stacksize);
lemp->errorcnt++;
lemp->stacksize = "100";
}
fprintf(out,"#define YYSTACKDEPTH %s\n",lemp->stacksize); lineno++;
}else{
fprintf(out,"#define YYSTACKDEPTH 100\n"); lineno++;
}
if( mhflag ){
fprintf(out,"#if INTERFACE\n"); lineno++;
}
name = lemp->name ? lemp->name : "Parse";
if( lemp->arg && lemp->arg[0] ){
i = strlen(lemp->arg);
while( i>=1 && isspace(lemp->arg[i-1]) ) i--;
while( i>=1 && (isalnum(lemp->arg[i-1]) || lemp->arg[i-1]=='_') ) i--;
fprintf(out,"#define %sARG_SDECL %s;\n",name,lemp->arg); lineno++;
fprintf(out,"#define %sARG_PDECL ,%s\n",name,lemp->arg); lineno++;
fprintf(out,"#define %sARG_FETCH %s = yypParser->%s\n",
name,lemp->arg,&lemp->arg[i]); lineno++;
fprintf(out,"#define %sARG_STORE yypParser->%s = %s\n",
name,&lemp->arg[i],&lemp->arg[i]); lineno++;
}else{
fprintf(out,"#define %sARG_SDECL\n",name); lineno++;
fprintf(out,"#define %sARG_PDECL\n",name); lineno++;
fprintf(out,"#define %sARG_FETCH\n",name); lineno++;
fprintf(out,"#define %sARG_STORE\n",name); lineno++;
}
if( mhflag ){
fprintf(out,"#endif\n"); lineno++;
}
fprintf(out,"#define YYNSTATE %d\n",lemp->nstate); lineno++;
fprintf(out,"#define YYNRULE %d\n",lemp->nrule); lineno++;
fprintf(out,"#define YYERRORSYMBOL %d\n",lemp->errsym->index); lineno++;
fprintf(out,"#define YYERRSYMDT yy%d\n",lemp->errsym->dtnum); lineno++;
if( lemp->has_fallback ){
fprintf(out,"#define YYFALLBACK 1\n"); lineno++;
}
tplt_xfer(lemp->name,in,out,&lineno);
/* Generate the action table and its associates:
**
** yy_action[] A single table containing all actions.
** yy_lookahead[] A table containing the lookahead for each entry in
** yy_action. Used to detect hash collisions.
** yy_shift_ofst[] For each state, the offset into yy_action for
** shifting terminals.
** yy_reduce_ofst[] For each state, the offset into yy_action for
** shifting non-terminals after a reduce.
** yy_default[] Default action for each state.
*/
/* Compute the actions on all states and count them up */
ax = malloc( sizeof(ax[0])*lemp->nstate*2 );
if( ax==0 ){
fprintf(stderr,"malloc failed\n");
exit(1);
}
for(i=0; i<lemp->nstate; i++){
stp = lemp->sorted[i];
stp->nTknAct = stp->nNtAct = 0;
stp->iDflt = lemp->nstate + lemp->nrule;
stp->iTknOfst = NO_OFFSET;
stp->iNtOfst = NO_OFFSET;
for(ap=stp->ap; ap; ap=ap->next){
if( compute_action(lemp,ap)>=0 ){
if( ap->sp->index<lemp->nterminal ){
stp->nTknAct++;
}else if( ap->sp->index<lemp->nsymbol ){
stp->nNtAct++;
}else{
stp->iDflt = compute_action(lemp, ap);
}
}
}
ax[i*2].stp = stp;
ax[i*2].isTkn = 1;
ax[i*2].nAction = stp->nTknAct;
ax[i*2+1].stp = stp;
ax[i*2+1].isTkn = 0;
ax[i*2+1].nAction = stp->nNtAct;
}
mxTknOfst = mnTknOfst = 0;
mxNtOfst = mnNtOfst = 0;
/* Compute the action table. In order to try to keep the size of the
** action table to a minimum, the heuristic of placing the largest action
** sets first is used.
*/
qsort(ax, lemp->nstate*2, sizeof(ax[0]), axset_compare);
pActtab = acttab_alloc();
for(i=0; i<lemp->nstate*2 && ax[i].nAction>0; i++){
stp = ax[i].stp;
if( ax[i].isTkn ){
for(ap=stp->ap; ap; ap=ap->next){
int action;
if( ap->sp->index>=lemp->nterminal ) continue;
action = compute_action(lemp, ap);
if( action<0 ) continue;
acttab_action(pActtab, ap->sp->index, action);
}
stp->iTknOfst = acttab_insert(pActtab);
if( stp->iTknOfst<mnTknOfst ) mnTknOfst = stp->iTknOfst;
if( stp->iTknOfst>mxTknOfst ) mxTknOfst = stp->iTknOfst;
}else{
for(ap=stp->ap; ap; ap=ap->next){
int action;
if( ap->sp->index<lemp->nterminal ) continue;
if( ap->sp->index==lemp->nsymbol ) continue;
action = compute_action(lemp, ap);
if( action<0 ) continue;
acttab_action(pActtab, ap->sp->index, action);
}
stp->iNtOfst = acttab_insert(pActtab);
if( stp->iNtOfst<mnNtOfst ) mnNtOfst = stp->iNtOfst;
if( stp->iNtOfst>mxNtOfst ) mxNtOfst = stp->iNtOfst;
}
}
free(ax);
/* Output the yy_action table */
fprintf(out,"static YYACTIONTYPE yy_action[] = {\n"); lineno++;
n = acttab_size(pActtab);
for(i=j=0; i<n; i++){
int action = acttab_yyaction(pActtab, i);
if( action<0 ) action = lemp->nsymbol + lemp->nrule + 2;
if( j==0 ) fprintf(out," /* %5d */ ", i);
fprintf(out, " %4d,", action);
if( j==9 || i==n-1 ){
fprintf(out, "\n"); lineno++;
j = 0;
}else{
j++;
}
}
fprintf(out, "};\n"); lineno++;
/* Output the yy_lookahead table */
fprintf(out,"static YYCODETYPE yy_lookahead[] = {\n"); lineno++;
for(i=j=0; i<n; i++){
int la = acttab_yylookahead(pActtab, i);
if( la<0 ) la = lemp->nsymbol;
if( j==0 ) fprintf(out," /* %5d */ ", i);
fprintf(out, " %4d,", la);
if( j==9 || i==n-1 ){
fprintf(out, "\n"); lineno++;
j = 0;
}else{
j++;
}
}
fprintf(out, "};\n"); lineno++;
/* Output the yy_shift_ofst[] table */
fprintf(out, "#define YY_SHIFT_USE_DFLT (%d)\n", mnTknOfst-1); lineno++;
fprintf(out, "static %s yy_shift_ofst[] = {\n",
minimum_size_type(mnTknOfst-1, mxTknOfst)); lineno++;
n = lemp->nstate;
for(i=j=0; i<n; i++){
int ofst;
stp = lemp->sorted[i];
ofst = stp->iTknOfst;
if( ofst==NO_OFFSET ) ofst = mnTknOfst - 1;
if( j==0 ) fprintf(out," /* %5d */ ", i);
fprintf(out, " %4d,", ofst);
if( j==9 || i==n-1 ){
fprintf(out, "\n"); lineno++;
j = 0;
}else{
j++;
}
}
fprintf(out, "};\n"); lineno++;
/* Output the yy_reduce_ofst[] table */
fprintf(out, "#define YY_REDUCE_USE_DFLT (%d)\n", mnNtOfst-1); lineno++;
fprintf(out, "static %s yy_reduce_ofst[] = {\n",
minimum_size_type(mnNtOfst-1, mxNtOfst)); lineno++;
n = lemp->nstate;
for(i=j=0; i<n; i++){
int ofst;
stp = lemp->sorted[i];
ofst = stp->iNtOfst;
if( ofst==NO_OFFSET ) ofst = mnNtOfst - 1;
if( j==0 ) fprintf(out," /* %5d */ ", i);
fprintf(out, " %4d,", ofst);
if( j==9 || i==n-1 ){
fprintf(out, "\n"); lineno++;
j = 0;
}else{
j++;
}
}
fprintf(out, "};\n"); lineno++;
/* Output the default action table */
fprintf(out, "static YYACTIONTYPE yy_default[] = {\n"); lineno++;
n = lemp->nstate;
for(i=j=0; i<n; i++){
stp = lemp->sorted[i];
if( j==0 ) fprintf(out," /* %5d */ ", i);
fprintf(out, " %4d,", stp->iDflt);
if( j==9 || i==n-1 ){
fprintf(out, "\n"); lineno++;
j = 0;
}else{
j++;
}
}
fprintf(out, "};\n"); lineno++;
tplt_xfer(lemp->name,in,out,&lineno);
/* Generate the table of fallback tokens.
*/
if( lemp->has_fallback ){
for(i=0; i<lemp->nterminal; i++){
struct symbol *p = lemp->symbols[i];
if( p->fallback==0 ){
fprintf(out, " 0, /* %10s => nothing */\n", p->name);
}else{
fprintf(out, " %3d, /* %10s => %s */\n", p->fallback->index,
p->name, p->fallback->name);
}
lineno++;
}
}
tplt_xfer(lemp->name, in, out, &lineno);
/* Generate a table containing the symbolic name of every symbol
*/
for(i=0; i<lemp->nsymbol; i++){
sprintf(line,"\"%s\",",lemp->symbols[i]->name);
fprintf(out," %-15s",line);
if( (i&3)==3 ){ fprintf(out,"\n"); lineno++; }
}
if( (i&3)!=0 ){ fprintf(out,"\n"); lineno++; }
tplt_xfer(lemp->name,in,out,&lineno);
/* Generate a table containing a text string that describes every
** rule in the rule set of the grammer. This information is used
** when tracing REDUCE actions.
*/
for(i=0, rp=lemp->rule; rp; rp=rp->next, i++){
assert( rp->index==i );
fprintf(out," /* %3d */ \"%s ::=", i, rp->lhs->name);
for(j=0; j<rp->nrhs; j++) fprintf(out," %s",rp->rhs[j]->name);
fprintf(out,"\",\n"); lineno++;
}
tplt_xfer(lemp->name,in,out,&lineno);
/* Generate code which executes every time a symbol is popped from
** the stack while processing errors or while destroying the parser.
** (In other words, generate the %destructor actions)
*/
if( lemp->tokendest ){
for(i=0; i<lemp->nsymbol; i++){
struct symbol *sp = lemp->symbols[i];
if( sp==0 || sp->type!=TERMINAL ) continue;
fprintf(out," case %d:\n",sp->index); lineno++;
}
for(i=0; i<lemp->nsymbol && lemp->symbols[i]->type!=TERMINAL; i++);
if( i<lemp->nsymbol ){
emit_destructor_code(out,lemp->symbols[i],lemp,&lineno);
fprintf(out," break;\n"); lineno++;
}
}
for(i=0; i<lemp->nsymbol; i++){
struct symbol *sp = lemp->symbols[i];
if( sp==0 || sp->type==TERMINAL || sp->destructor==0 ) continue;
fprintf(out," case %d:\n",sp->index); lineno++;
emit_destructor_code(out,lemp->symbols[i],lemp,&lineno);
fprintf(out," break;\n"); lineno++;
}
if( lemp->vardest ){
struct symbol *dflt_sp = 0;
for(i=0; i<lemp->nsymbol; i++){
struct symbol *sp = lemp->symbols[i];
if( sp==0 || sp->type==TERMINAL ||
sp->index<=0 || sp->destructor!=0 ) continue;
fprintf(out," case %d:\n",sp->index); lineno++;
dflt_sp = sp;
}
if( dflt_sp!=0 ){
emit_destructor_code(out,dflt_sp,lemp,&lineno);
fprintf(out," break;\n"); lineno++;
}
}
tplt_xfer(lemp->name,in,out,&lineno);
/* Generate code which executes whenever the parser stack overflows */
tplt_print(out,lemp,lemp->overflow,lemp->overflowln,&lineno);
tplt_xfer(lemp->name,in,out,&lineno);
/* Generate the table of rule information
**
** Note: This code depends on the fact that rules are number
** sequentually beginning with 0.
*/
for(rp=lemp->rule; rp; rp=rp->next){
fprintf(out," { %d, %d },\n",rp->lhs->index,rp->nrhs); lineno++;
}
tplt_xfer(lemp->name,in,out,&lineno);
/* Generate code which execution during each REDUCE action */
for(rp=lemp->rule; rp; rp=rp->next){
fprintf(out," case %d:\n",rp->index); lineno++;
emit_code(out,rp,lemp,&lineno);
fprintf(out," break;\n"); lineno++;
}
tplt_xfer(lemp->name,in,out,&lineno);
/* Generate code which executes if a parse fails */
tplt_print(out,lemp,lemp->failure,lemp->failureln,&lineno);
tplt_xfer(lemp->name,in,out,&lineno);
/* Generate code which executes when a syntax error occurs */
tplt_print(out,lemp,lemp->error,lemp->errorln,&lineno);
tplt_xfer(lemp->name,in,out,&lineno);
/* Generate code which executes when the parser accepts its input */
tplt_print(out,lemp,lemp->accept,lemp->acceptln,&lineno);
tplt_xfer(lemp->name,in,out,&lineno);
/* Append any addition code the user desires */
tplt_print(out,lemp,lemp->extracode,lemp->extracodeln,&lineno);
fclose(in);
fclose(out);
return;
}
/* Generate a header file for the parser */
void ReportHeader(lemp)
struct lemon *lemp;
{
FILE *out, *in;
char *prefix;
char line[LINESIZE];
char pattern[LINESIZE];
int i;
if( lemp->tokenprefix ) prefix = lemp->tokenprefix;
else prefix = "";
in = file_open(lemp,".h","r");
if( in ){
for(i=1; i<lemp->nterminal && fgets(line,LINESIZE,in); i++){
sprintf(pattern,"#define %s%-30s %2d\n",prefix,lemp->symbols[i]->name,i);
if( strcmp(line,pattern) ) break;
}
fclose(in);
if( i==lemp->nterminal ){
/* No change in the file. Don't rewrite it. */
return;
}
}
out = file_open(lemp,".h","w");
if( out ){
for(i=1; i<lemp->nterminal; i++){
fprintf(out,"#define %s%-30s %2d\n",prefix,lemp->symbols[i]->name,i);
}
fclose(out);
}
return;
}
/* Reduce the size of the action tables, if possible, by making use
** of defaults.
**
** In this version, we take the most frequent REDUCE action and make
** it the default. Only default a reduce if there are more than one.
*/
void CompressTables(lemp)
struct lemon *lemp;
{
struct state *stp;
struct action *ap, *ap2;
struct rule *rp, *rp2, *rbest;
int nbest, n;
int i;
for(i=0; i<lemp->nstate; i++){
stp = lemp->sorted[i];
nbest = 0;
rbest = 0;
for(ap=stp->ap; ap; ap=ap->next){
if( ap->type!=REDUCE ) continue;
rp = ap->x.rp;
if( rp==rbest ) continue;
n = 1;
for(ap2=ap->next; ap2; ap2=ap2->next){
if( ap2->type!=REDUCE ) continue;
rp2 = ap2->x.rp;
if( rp2==rbest ) continue;
if( rp2==rp ) n++;
}
if( n>nbest ){
nbest = n;
rbest = rp;
}
}
/* Do not make a default if the number of rules to default
** is not at least 2 */
if( nbest<2 ) continue;
/* Combine matching REDUCE actions into a single default */
for(ap=stp->ap; ap; ap=ap->next){
if( ap->type==REDUCE && ap->x.rp==rbest ) break;
}
assert( ap );
ap->sp = Symbol_new("{default}");
for(ap=ap->next; ap; ap=ap->next){
if( ap->type==REDUCE && ap->x.rp==rbest ) ap->type = NOT_USED;
}
stp->ap = Action_sort(stp->ap);
}
}
/***************** From the file "set.c" ************************************/
/*
** Set manipulation routines for the LEMON parser generator.
*/
static int global_size = 0;
/* Set the set size */
void SetSize(n)
int n;
{
global_size = n+1;
}
/* Allocate a new set */
char *SetNew(){
char *s;
int i;
s = (char*)malloc( global_size );
if( s==0 ){
extern void memory_error();
memory_error();
}
for(i=0; i<global_size; i++) s[i] = 0;
return s;
}
/* Deallocate a set */
void SetFree(s)
char *s;
{
free(s);
}
/* Add a new element to the set. Return TRUE if the element was added
** and FALSE if it was already there. */
int SetAdd(s,e)
char *s;
int e;
{
int rv;
rv = s[e];
s[e] = 1;
return !rv;
}
/* Add every element of s2 to s1. Return TRUE if s1 changes. */
int SetUnion(s1,s2)
char *s1;
char *s2;
{
int i, progress;
progress = 0;
for(i=0; i<global_size; i++){
if( s2[i]==0 ) continue;
if( s1[i]==0 ){
progress = 1;
s1[i] = 1;
}
}
return progress;
}
/********************** From the file "table.c" ****************************/
/*
** All code in this file has been automatically generated
** from a specification in the file
** "table.q"
** by the associative array code building program "aagen".
** Do not edit this file! Instead, edit the specification
** file, then rerun aagen.
*/
/*
** Code for processing tables in the LEMON parser generator.
*/
PRIVATE int strhash(x)
char *x;
{
int h = 0;
while( *x) h = h*13 + *(x++);
return h;
}
/* Works like strdup, sort of. Save a string in malloced memory, but
** keep strings in a table so that the same string is not in more
** than one place.
*/
char *Strsafe(y)
char *y;
{
char *z;
z = Strsafe_find(y);
if( z==0 && (z=malloc( strlen(y)+1 ))!=0 ){
strcpy(z,y);
Strsafe_insert(z);
}
MemoryCheck(z);
return z;
}
/* There is one instance of the following structure for each
** associative array of type "x1".
*/
struct s_x1 {
int size; /* The number of available slots. */
/* Must be a power of 2 greater than or */
/* equal to 1 */
int count; /* Number of currently slots filled */
struct s_x1node *tbl; /* The data stored here */
struct s_x1node **ht; /* Hash table for lookups */
};
/* There is one instance of this structure for every data element
** in an associative array of type "x1".
*/
typedef struct s_x1node {
char *data; /* The data */
struct s_x1node *next; /* Next entry with the same hash */
struct s_x1node **from; /* Previous link */
} x1node;
/* There is only one instance of the array, which is the following */
static struct s_x1 *x1a;
/* Allocate a new associative array */
void Strsafe_init(){
if( x1a ) return;
x1a = (struct s_x1*)malloc( sizeof(struct s_x1) );
if( x1a ){
x1a->size = 1024;
x1a->count = 0;
x1a->tbl = (x1node*)malloc(
(sizeof(x1node) + sizeof(x1node*))*1024 );
if( x1a->tbl==0 ){
free(x1a);
x1a = 0;
}else{
int i;
x1a->ht = (x1node**)&(x1a->tbl[1024]);
for(i=0; i<1024; i++) x1a->ht[i] = 0;
}
}
}
/* Insert a new record into the array. Return TRUE if successful.
** Prior data with the same key is NOT overwritten */
int Strsafe_insert(data)
char *data;
{
x1node *np;
int h;
int ph;
if( x1a==0 ) return 0;
ph = strhash(data);
h = ph & (x1a->size-1);
np = x1a->ht[h];
while( np ){
if( strcmp(np->data,data)==0 ){
/* An existing entry with the same key is found. */
/* Fail because overwrite is not allows. */
return 0;
}
np = np->next;
}
if( x1a->count>=x1a->size ){
/* Need to make the hash table bigger */
int i,size;
struct s_x1 array;
array.size = size = x1a->size*2;
array.count = x1a->count;
array.tbl = (x1node*)malloc(
(sizeof(x1node) + sizeof(x1node*))*size );
if( array.tbl==0 ) return 0; /* Fail due to malloc failure */
array.ht = (x1node**)&(array.tbl[size]);
for(i=0; i<size; i++) array.ht[i] = 0;
for(i=0; i<x1a->count; i++){
x1node *oldnp, *newnp;
oldnp = &(x1a->tbl[i]);
h = strhash(oldnp->data) & (size-1);
newnp = &(array.tbl[i]);
if( array.ht[h] ) array.ht[h]->from = &(newnp->next);
newnp->next = array.ht[h];
newnp->data = oldnp->data;
newnp->from = &(array.ht[h]);
array.ht[h] = newnp;
}
free(x1a->tbl);
*x1a = array;
}
/* Insert the new data */
h = ph & (x1a->size-1);
np = &(x1a->tbl[x1a->count++]);
np->data = data;
if( x1a->ht[h] ) x1a->ht[h]->from = &(np->next);
np->next = x1a->ht[h];
x1a->ht[h] = np;
np->from = &(x1a->ht[h]);
return 1;
}
/* Return a pointer to data assigned to the given key. Return NULL
** if no such key. */
char *Strsafe_find(key)
char *key;
{
int h;
x1node *np;
if( x1a==0 ) return 0;
h = strhash(key) & (x1a->size-1);
np = x1a->ht[h];
while( np ){
if( strcmp(np->data,key)==0 ) break;
np = np->next;
}
return np ? np->data : 0;
}
/* Return a pointer to the (terminal or nonterminal) symbol "x".
** Create a new symbol if this is the first time "x" has been seen.
*/
struct symbol *Symbol_new(x)
char *x;
{
struct symbol *sp;
sp = Symbol_find(x);
if( sp==0 ){
sp = (struct symbol *)malloc( sizeof(struct symbol) );
MemoryCheck(sp);
sp->name = Strsafe(x);
sp->type = isupper(*x) ? TERMINAL : NONTERMINAL;
sp->rule = 0;
sp->fallback = 0;
sp->prec = -1;
sp->assoc = UNK;
sp->firstset = 0;
sp->lambda = Bo_FALSE;
sp->destructor = 0;
sp->datatype = 0;
Symbol_insert(sp,sp->name);
}
return sp;
}
/* Compare two symbols for working purposes
**
** Symbols that begin with upper case letters (terminals or tokens)
** must sort before symbols that begin with lower case letters
** (non-terminals). Other than that, the order does not matter.
**
** We find experimentally that leaving the symbols in their original
** order (the order they appeared in the grammar file) gives the
** smallest parser tables in SQLite.
*/
int Symbolcmpp(struct symbol **a, struct symbol **b){
int i1 = (**a).index + 10000000*((**a).name[0]>'Z');
int i2 = (**b).index + 10000000*((**b).name[0]>'Z');
return i1-i2;
}
/* There is one instance of the following structure for each
** associative array of type "x2".
*/
struct s_x2 {
int size; /* The number of available slots. */
/* Must be a power of 2 greater than or */
/* equal to 1 */
int count; /* Number of currently slots filled */
struct s_x2node *tbl; /* The data stored here */
struct s_x2node **ht; /* Hash table for lookups */
};
/* There is one instance of this structure for every data element
** in an associative array of type "x2".
*/
typedef struct s_x2node {
struct symbol *data; /* The data */
char *key; /* The key */
struct s_x2node *next; /* Next entry with the same hash */
struct s_x2node **from; /* Previous link */
} x2node;
/* There is only one instance of the array, which is the following */
static struct s_x2 *x2a;
/* Allocate a new associative array */
void Symbol_init(){
if( x2a ) return;
x2a = (struct s_x2*)malloc( sizeof(struct s_x2) );
if( x2a ){
x2a->size = 128;
x2a->count = 0;
x2a->tbl = (x2node*)malloc(
(sizeof(x2node) + sizeof(x2node*))*128 );
if( x2a->tbl==0 ){
free(x2a);
x2a = 0;
}else{
int i;
x2a->ht = (x2node**)&(x2a->tbl[128]);
for(i=0; i<128; i++) x2a->ht[i] = 0;
}
}
}
/* Insert a new record into the array. Return TRUE if successful.
** Prior data with the same key is NOT overwritten */
int Symbol_insert(data,key)
struct symbol *data;
char *key;
{
x2node *np;
int h;
int ph;
if( x2a==0 ) return 0;
ph = strhash(key);
h = ph & (x2a->size-1);
np = x2a->ht[h];
while( np ){
if( strcmp(np->key,key)==0 ){
/* An existing entry with the same key is found. */
/* Fail because overwrite is not allows. */
return 0;
}
np = np->next;
}
if( x2a->count>=x2a->size ){
/* Need to make the hash table bigger */
int i,size;
struct s_x2 array;
array.size = size = x2a->size*2;
array.count = x2a->count;
array.tbl = (x2node*)malloc(
(sizeof(x2node) + sizeof(x2node*))*size );
if( array.tbl==0 ) return 0; /* Fail due to malloc failure */
array.ht = (x2node**)&(array.tbl[size]);
for(i=0; i<size; i++) array.ht[i] = 0;
for(i=0; i<x2a->count; i++){
x2node *oldnp, *newnp;
oldnp = &(x2a->tbl[i]);
h = strhash(oldnp->key) & (size-1);
newnp = &(array.tbl[i]);
if( array.ht[h] ) array.ht[h]->from = &(newnp->next);
newnp->next = array.ht[h];
newnp->key = oldnp->key;
newnp->data = oldnp->data;
newnp->from = &(array.ht[h]);
array.ht[h] = newnp;
}
free(x2a->tbl);
*x2a = array;
}
/* Insert the new data */
h = ph & (x2a->size-1);
np = &(x2a->tbl[x2a->count++]);
np->key = key;
np->data = data;
if( x2a->ht[h] ) x2a->ht[h]->from = &(np->next);
np->next = x2a->ht[h];
x2a->ht[h] = np;
np->from = &(x2a->ht[h]);
return 1;
}
/* Return a pointer to data assigned to the given key. Return NULL
** if no such key. */
struct symbol *Symbol_find(key)
char *key;
{
int h;
x2node *np;
if( x2a==0 ) return 0;
h = strhash(key) & (x2a->size-1);
np = x2a->ht[h];
while( np ){
if( strcmp(np->key,key)==0 ) break;
np = np->next;
}
return np ? np->data : 0;
}
/* Return the n-th data. Return NULL if n is out of range. */
struct symbol *Symbol_Nth(n)
int n;
{
struct symbol *data;
if( x2a && n>0 && n<=x2a->count ){
data = x2a->tbl[n-1].data;
}else{
data = 0;
}
return data;
}
/* Return the size of the array */
int Symbol_count()
{
return x2a ? x2a->count : 0;
}
/* Return an array of pointers to all data in the table.
** The array is obtained from malloc. Return NULL if memory allocation
** problems, or if the array is empty. */
struct symbol **Symbol_arrayof()
{
struct symbol **array;
int i,size;
if( x2a==0 ) return 0;
size = x2a->count;
array = (struct symbol **)malloc( sizeof(struct symbol *)*size );
if( array ){
for(i=0; i<size; i++) array[i] = x2a->tbl[i].data;
}
return array;
}
/* Compare two configurations */
int Configcmp(a,b)
struct config *a;
struct config *b;
{
int x;
x = a->rp->index - b->rp->index;
if( x==0 ) x = a->dot - b->dot;
return x;
}
/* Compare two states */
PRIVATE int statecmp(a,b)
struct config *a;
struct config *b;
{
int rc;
for(rc=0; rc==0 && a && b; a=a->bp, b=b->bp){
rc = a->rp->index - b->rp->index;
if( rc==0 ) rc = a->dot - b->dot;
}
if( rc==0 ){
if( a ) rc = 1;
if( b ) rc = -1;
}
return rc;
}
/* Hash a state */
PRIVATE int statehash(a)
struct config *a;
{
int h=0;
while( a ){
h = h*571 + a->rp->index*37 + a->dot;
a = a->bp;
}
return h;
}
/* Allocate a new state structure */
struct state *State_new()
{
struct state *new;
new = (struct state *)malloc( sizeof(struct state) );
MemoryCheck(new);
return new;
}
/* There is one instance of the following structure for each
** associative array of type "x3".
*/
struct s_x3 {
int size; /* The number of available slots. */
/* Must be a power of 2 greater than or */
/* equal to 1 */
int count; /* Number of currently slots filled */
struct s_x3node *tbl; /* The data stored here */
struct s_x3node **ht; /* Hash table for lookups */
};
/* There is one instance of this structure for every data element
** in an associative array of type "x3".
*/
typedef struct s_x3node {
struct state *data; /* The data */
struct config *key; /* The key */
struct s_x3node *next; /* Next entry with the same hash */
struct s_x3node **from; /* Previous link */
} x3node;
/* There is only one instance of the array, which is the following */
static struct s_x3 *x3a;
/* Allocate a new associative array */
void State_init(){
if( x3a ) return;
x3a = (struct s_x3*)malloc( sizeof(struct s_x3) );
if( x3a ){
x3a->size = 128;
x3a->count = 0;
x3a->tbl = (x3node*)malloc(
(sizeof(x3node) + sizeof(x3node*))*128 );
if( x3a->tbl==0 ){
free(x3a);
x3a = 0;
}else{
int i;
x3a->ht = (x3node**)&(x3a->tbl[128]);
for(i=0; i<128; i++) x3a->ht[i] = 0;
}
}
}
/* Insert a new record into the array. Return TRUE if successful.
** Prior data with the same key is NOT overwritten */
int State_insert(data,key)
struct state *data;
struct config *key;
{
x3node *np;
int h;
int ph;
if( x3a==0 ) return 0;
ph = statehash(key);
h = ph & (x3a->size-1);
np = x3a->ht[h];
while( np ){
if( statecmp(np->key,key)==0 ){
/* An existing entry with the same key is found. */
/* Fail because overwrite is not allows. */
return 0;
}
np = np->next;
}
if( x3a->count>=x3a->size ){
/* Need to make the hash table bigger */
int i,size;
struct s_x3 array;
array.size = size = x3a->size*2;
array.count = x3a->count;
array.tbl = (x3node*)malloc(
(sizeof(x3node) + sizeof(x3node*))*size );
if( array.tbl==0 ) return 0; /* Fail due to malloc failure */
array.ht = (x3node**)&(array.tbl[size]);
for(i=0; i<size; i++) array.ht[i] = 0;
for(i=0; i<x3a->count; i++){
x3node *oldnp, *newnp;
oldnp = &(x3a->tbl[i]);
h = statehash(oldnp->key) & (size-1);
newnp = &(array.tbl[i]);
if( array.ht[h] ) array.ht[h]->from = &(newnp->next);
newnp->next = array.ht[h];
newnp->key = oldnp->key;
newnp->data = oldnp->data;
newnp->from = &(array.ht[h]);
array.ht[h] = newnp;
}
free(x3a->tbl);
*x3a = array;
}
/* Insert the new data */
h = ph & (x3a->size-1);
np = &(x3a->tbl[x3a->count++]);
np->key = key;
np->data = data;
if( x3a->ht[h] ) x3a->ht[h]->from = &(np->next);
np->next = x3a->ht[h];
x3a->ht[h] = np;
np->from = &(x3a->ht[h]);
return 1;
}
/* Return a pointer to data assigned to the given key. Return NULL
** if no such key. */
struct state *State_find(key)
struct config *key;
{
int h;
x3node *np;
if( x3a==0 ) return 0;
h = statehash(key) & (x3a->size-1);
np = x3a->ht[h];
while( np ){
if( statecmp(np->key,key)==0 ) break;
np = np->next;
}
return np ? np->data : 0;
}
/* Return an array of pointers to all data in the table.
** The array is obtained from malloc. Return NULL if memory allocation
** problems, or if the array is empty. */
struct state **State_arrayof()
{
struct state **array;
int i,size;
if( x3a==0 ) return 0;
size = x3a->count;
array = (struct state **)malloc( sizeof(struct state *)*size );
if( array ){
for(i=0; i<size; i++) array[i] = x3a->tbl[i].data;
}
return array;
}
/* Hash a configuration */
PRIVATE int confighash(a)
struct config *a;
{
int h=0;
h = h*571 + a->rp->index*37 + a->dot;
return h;
}
/* There is one instance of the following structure for each
** associative array of type "x4".
*/
struct s_x4 {
int size; /* The number of available slots. */
/* Must be a power of 2 greater than or */
/* equal to 1 */
int count; /* Number of currently slots filled */
struct s_x4node *tbl; /* The data stored here */
struct s_x4node **ht; /* Hash table for lookups */
};
/* There is one instance of this structure for every data element
** in an associative array of type "x4".
*/
typedef struct s_x4node {
struct config *data; /* The data */
struct s_x4node *next; /* Next entry with the same hash */
struct s_x4node **from; /* Previous link */
} x4node;
/* There is only one instance of the array, which is the following */
static struct s_x4 *x4a;
/* Allocate a new associative array */
void Configtable_init(){
if( x4a ) return;
x4a = (struct s_x4*)malloc( sizeof(struct s_x4) );
if( x4a ){
x4a->size = 64;
x4a->count = 0;
x4a->tbl = (x4node*)malloc(
(sizeof(x4node) + sizeof(x4node*))*64 );
if( x4a->tbl==0 ){
free(x4a);
x4a = 0;
}else{
int i;
x4a->ht = (x4node**)&(x4a->tbl[64]);
for(i=0; i<64; i++) x4a->ht[i] = 0;
}
}
}
/* Insert a new record into the array. Return TRUE if successful.
** Prior data with the same key is NOT overwritten */
int Configtable_insert(data)
struct config *data;
{
x4node *np;
int h;
int ph;
if( x4a==0 ) return 0;
ph = confighash(data);
h = ph & (x4a->size-1);
np = x4a->ht[h];
while( np ){
if( Configcmp(np->data,data)==0 ){
/* An existing entry with the same key is found. */
/* Fail because overwrite is not allows. */
return 0;
}
np = np->next;
}
if( x4a->count>=x4a->size ){
/* Need to make the hash table bigger */
int i,size;
struct s_x4 array;
array.size = size = x4a->size*2;
array.count = x4a->count;
array.tbl = (x4node*)malloc(
(sizeof(x4node) + sizeof(x4node*))*size );
if( array.tbl==0 ) return 0; /* Fail due to malloc failure */
array.ht = (x4node**)&(array.tbl[size]);
for(i=0; i<size; i++) array.ht[i] = 0;
for(i=0; i<x4a->count; i++){
x4node *oldnp, *newnp;
oldnp = &(x4a->tbl[i]);
h = confighash(oldnp->data) & (size-1);
newnp = &(array.tbl[i]);
if( array.ht[h] ) array.ht[h]->from = &(newnp->next);
newnp->next = array.ht[h];
newnp->data = oldnp->data;
newnp->from = &(array.ht[h]);
array.ht[h] = newnp;
}
free(x4a->tbl);
*x4a = array;
}
/* Insert the new data */
h = ph & (x4a->size-1);
np = &(x4a->tbl[x4a->count++]);
np->data = data;
if( x4a->ht[h] ) x4a->ht[h]->from = &(np->next);
np->next = x4a->ht[h];
x4a->ht[h] = np;
np->from = &(x4a->ht[h]);
return 1;
}
/* Return a pointer to data assigned to the given key. Return NULL
** if no such key. */
struct config *Configtable_find(key)
struct config *key;
{
int h;
x4node *np;
if( x4a==0 ) return 0;
h = confighash(key) & (x4a->size-1);
np = x4a->ht[h];
while( np ){
if( Configcmp(np->data,key)==0 ) break;
np = np->next;
}
return np ? np->data : 0;
}
/* Remove all data from the table. Pass each data to the function "f"
** as it is removed. ("f" may be null to avoid this step.) */
void Configtable_clear(f)
int(*f)(/* struct config * */);
{
int i;
if( x4a==0 || x4a->count==0 ) return;
if( f ) for(i=0; i<x4a->count; i++) (*f)(x4a->tbl[i].data);
for(i=0; i<x4a->size; i++) x4a->ht[i] = 0;
x4a->count = 0;
return;
}
|