summaryrefslogtreecommitdiffabout
path: root/mfd/gram.y
blob: 15ee960262003c5232f45aecd9bef4fdb2c719f2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
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
%{
/* This file is part of Mailfromd.
   Copyright (C) 2005, 2006, 2007, 2008, 2009 Sergey Poznyakoff

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

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

   You should have received a copy of the GNU General Public License
   along with this program.  If not, see <http://www.gnu.org/licenses/>. */

#define MF_SOURCE_NAME  MF_SOURCE_GRAM
	
#ifdef HAVE_CONFIG_H
# include <config.h>
#endif

#include <fnmatch.h>
#include <netdb.h>
#include "mailfromd.h"
#include "prog.h"
#include "optab.h"
#define obstack_chunk_alloc malloc
#define obstack_chunk_free free	
#include "obstack.h"
	
static NODE *alloc_node(enum node_type type, const struct locus *locus);
static void free_node(NODE *node); 
static void set_poll_arg(struct poll_data *poll, int kw, NODE *expr);
static int codegen(prog_counter_t *pc, NODE *node, unsigned exmask,
		   int finalize, size_t nautos);
static void mark(NODE *node);
static void dataseg_layout(void);
static void regex_layout(void);
static int optimize_tree(NODE *node);
static void compile_tree(NODE *node);
static NODE *reverse(NODE *in);
static NODE *function_call(struct function *function, size_t count,
			   NODE *subtree);
static NODE *declare_function(struct function *func, struct locus *loc,
			      size_t nautos);
static data_type_t node_type(NODE *node);
static NODE *cast_to(data_type_t type, NODE *node);
static NODE *cast_arg_list(NODE *args, size_t parmc, data_type_t *parmtype,
			   int disable_prom);
static void add_xref(struct variable *var, const struct locus *locus);
static struct variable *vardecl(const char *name, data_type_t type,
				storage_class_t sc, struct locus *loc);
static struct variable *externdecl(const char *name, struct value *value,
				   struct locus *loc);
static int initialize_variable(struct variable *var, struct value *val,
			       const struct locus *locus);
static void apply_deferred_init(void);
static NODE *create_asgn_node(struct variable *var, NODE *expr,
			      const struct locus *loc);

NODE *defined_parm(struct variable *var, struct locus *locus);
 
static void register_auto(struct variable *var);
static void unregister_auto(struct variable *var);
static size_t forget_autos(size_t nparam, size_t prev, size_t hidden_arg);
static void optimize(NODE *node);

static NODE *root_node[smtp_state_count];
prog_counter_t entry_point[smtp_state_count];

#define PS_BEGIN 0
#define PS_END   1 
 
int regex_flags;        /* Should default to REG_NOSUB ? */
unsigned error_count;   /* Number of detected errors */
size_t variable_count = 1;  /* Offset of the next-to-be-defined variable
			       in the data segment.
			       Offset 0 is reserved for NULL symbol */
 
static enum smtp_state state_tag; /* State tag of the currently processed
				     PROG */

static struct function *func;   /* The currently compiled function */
static prog_counter_t jump_pc;  /* Pointer to the chain of jmp instructions */

/* Outermost context decides how to code exits from catches.
   Innermost context is used to access parameters. */
enum lexical_context outer_context, inner_context;

size_t catch_nesting;  /* Nesting level for catch statements */
 
/* Controls whether unquoted strings are warned about. Normally it is off
   within a `when .*:' construct. */
static int allow_unquoted_strings;

static struct stmtlist genstmt;     /* List of generated statements */
 
/* State handlers and their positional parameters */ 
struct state_parms {
	int cnt;                  /* Number or positional parameters */
	data_type_t types[4];   /* Their data types */
} state_parms[] = {
	{ 0,  }, /* smtp_state_none */
	{ 0, }, /* smtp_state_begin */
	{ 4, { dtype_string, dtype_number, dtype_number, dtype_string } },
                                  /* smtp_state_connect */
	{ 1, { dtype_string } },  /* smtp_state_helo */
	{ 2, { dtype_string, dtype_string } },  /* smtp_state_envfrom */
	{ 2, { dtype_string, dtype_string } },  /* smtp_state_envrcpt */
	{ 0, },  /* smtp_state_data */
	{ 2, { dtype_string, dtype_string } }, /* smtp_state_header */
	{ 0,  }, /* smtp_state_eoh */
	{ 2, { dtype_pointer, dtype_number } }, /* smtp_state_body */
	{ 0, }, /* smtp_state_eom */
	{ 0, }  /* smtp_state_end */
};

struct parmtype {
	struct parmtype *next;
	data_type_t type;
};

static int
parmcount_none()
{
	return 0;
}

static data_type_t
parmtype_none(int n)
{
	return dtype_unspecified;
}
 
static int
parmcount_handler()
{
	return state_parms[state_tag].cnt;
}

static data_type_t
parmtype_handler(int n)
{
	return state_parms[state_tag].types[n-1];
}

static int
parmcount_catch()
{
	return 2;
}

static data_type_t
parmtype_catch(int n)
{
	switch (n) {
	case 1:
		return dtype_number;
	case 2:
		return dtype_string;
	}
	abort();
}

static int
parmcount_function()
{
	return func->parmcount;
}

static data_type_t
parmtype_function(int n)
{
	if (func->varargs && n > func->parmcount)
		return dtype_string;
	return func->parmtype[n-1];
}

struct parminfo {
	int (*parmcount)(void);
	data_type_t (*parmtype)(int n);
} parminfo[] = {
	{ parmcount_none, parmtype_none },
	{ parmcount_handler, parmtype_handler },
	{ parmcount_catch, parmtype_catch },
	{ parmcount_function, parmtype_function },
};

#define PARMCOUNT() parminfo[inner_context].parmcount()
#define PARMTYPE(n) parminfo[inner_context].parmtype(n)
#define FUNC_HIDDEN_ARGS(f) (((f)->optcount || (f)->varargs) ? 1 : 0)

/* Loop stack */



data_type_t
string_to_type(const char *s)
{
	if (strcmp(s, "n") == 0)
		return dtype_number;
	else if (strcmp(s, "s") == 0)
		return dtype_string;
	else
		return dtype_unspecified;
}

const char *
type_to_string(data_type_t t)
{
	switch (t) {
	case dtype_number:
		return "number";
	case dtype_string:
		return "string";
	case dtype_unspecified:
		return "unspecified";
	case dtype_pointer:
		return "pointer";
	default:
		abort();
	}
}

static int
check_func_usage(struct function *fp)
{
	switch (outer_context) {
	case context_handler:
		if (fp->statemask && !(EXMASK(state_tag) & fp->statemask)) {
			parse_error(_("Function `%s' cannot be used in "
				    "prog `%s'"),
				    fp->name,
				    state_to_string(state_tag));
			return 1;
		}
		break;
		
	case context_function:
		func->statemask |= fp->statemask;
		break;

	default:
		break;
	}
	return 0;
}

static int
check_builtin_usage(const struct builtin *bp)
{
	switch (outer_context) {
	case context_handler:
		if (bp->statemask && !(EXMASK(state_tag) & bp->statemask)) {
			parse_error(_("Built-in function `%s' cannot be used in "
				      "prog `%s'"),
				    bp->name,
				    state_to_string(state_tag));
			return 1;
		}
		break;
		
	case context_function:
		func->statemask |= bp->statemask;
		break;
		
	default:
		break;
	}
			
	if (bp->flags & MFD_BUILTIN_CAPTURE)
		capture_on();
	return 0;
}

static void jump_fixup(prog_counter_t pos, prog_counter_t endpos);
static NODE *create_on_node(NODE *sel, struct case_stmt *cases);
static void register_macro(enum smtp_state tag, const char *macro);

#define LITERAL_TEXT(lit) ((lit) ? (lit)->text : NULL)
#define LITERAL_OFF(lit) ((lit) ? (lit)->off : 0)

static int
_create_alias(void *item, void *data)
{
	struct literal *lit = item;
	struct function *fun = data;
	/* FIXME: Ideally we should pass a locus of `lit' instead of
	   fun->locus. However, its only purpose is for use in redefinition
	   diagnostic messages and these are never produced, because the
	   grammar catches these errors earlier. This might change in
	   the future.  2008-09-14 */
	install_alias(lit->text, fun, &fun->locus);
	return 0;
}

%}

%error-verbose
%expect 28

%union {
	struct literal *literal;
	struct stmtlist stmtlist;
	NODE *node;
	struct return_node ret;
	struct poll_data poll;
	struct locus locus;
	struct pollarg {
		int kw;
		NODE *expr;
	} pollarg;
	struct arglist {
		NODE *head;
		NODE *tail;
		size_t count;
	} arglist;
	long number;
	const struct builtin *builtin;
	struct variable *var;
	enum smtp_state state;
	struct {
		struct locus locus;
		int qualifier;
	} matchtype;
	data_type_t type;
	struct parmtype *parm;
	struct parmlist {
		struct parmtype *head, *tail;
		size_t count;
		size_t optcount;
		int varargs;
	} parmlist;
	enum lexical_context tie_in;
	struct function *function;
	struct {
		struct valist *head, *tail;
	} valist_list;
	struct valist *valist;
	struct value value;
	struct {
		struct case_stmt *head, *tail;
	} case_list ;
	struct case_stmt *case_stmt;
	struct loop_node loop;
	struct {
		struct locus locus;
		int code;
	} progspecial;
	mu_list_t list;
};

%token <locus> ACT_ACCEPT ACT_REJECT ACT_TEMPFAIL ACT_CONTINUE ACT_DISCARD
%token <locus> ADD REPLACE DELETE
%token <locus> PROG KW_BEGIN KW_END IF FI ELSE ELIF 
%token <locus> ON HOST FROM AS DO DONE POLL MATCHES FNMATCHES
%token <locus> MXMATCHES MXFNMATCHES
%token <locus> WHEN PASS SET CATCH THROW KW_ECHO RETURNS RETURN FUNC
%token <locus> SWITCH CASE DEFAULT CONST
%token <locus> FOR LOOP WHILE BREAK NEXT ARGCOUNT ALIAS DOTS ARGX VAPTR
%token <literal> STRING
%token <literal> SYMBOL IDENTIFIER
%token <number> ARG NUMBER BACKREF
%token <builtin> BUILTIN BUILTIN_PROC BUILTIN_P
%token <locus> OR AND EQ NE LT LE GT GE NOT LOGAND LOGOR LOGXOR LOGNOT
%token <function> FUNCTION FUNCTION_PROC FUNCTION_P
%token <type> TYPE
%token <var> VARIABLE
%token BOGUS

%left CONCAT
%left OR
%left AND
%left NOT
%left LOGOR
%left LOGXOR
%left LOGAND
%nonassoc EQ NE MATCHES FNMATCHES MXMATCHES MXFNMATCHES
%nonassoc LT LE GT GE
%left '+' '-'
%left '*' '/' 
%left UMINUS
%left BUILTIN FUNCTION FUNCTION_P BUILTIN_P

%type <node> decl stmt condition action sendmail_action header_action
             if_cond else_cond on_cond atom argref paren_argref
             funcall proccall expr maybe_expr maybe_xcode_expr
             common_expr simp_expr atom_expr
             asgn catch throw return case_cond autodcl constdecl
             loopstmt opt_while jumpstmt
%type <stmtlist> stmtlist decllist
%type <ret> triplet maybe_triplet
%type <poll> pollstmt pollarglist
%type <pollarg> pollarg loop_parm
%type <loop> opt_loop_parms loop_parm_list
%type <arglist> arglist 
%type <var> variable
%type <literal> string opt_ident loop_ident alias code xcode
%type <state> state_ident
%type <matchtype> matches fnmatches
%type <type> retdecl
%type <parmlist> params parmlist fparmlist parmdecl
%type <parm> parm
%type <function> fundecl
%type <value> value
%type <valist_list> valist catchlist
%type <case_list> cond_branches branches 
%type <case_stmt> cond_branch branch
%type <locus> on
%type <progspecial> progspecial
%type <list> aliases aliasdecl

%%

input      : decllist
             {
		     if (error_count == 0) {
			     builtin_post_setup();
			     if (genstmt.head) {
				     genstmt.tail->next = $1.head;
				     genstmt.tail = $1.tail;
			     } else
				     genstmt = $1;
			     optimize_tree(genstmt.head);
			     if (error_count)
				     YYERROR;
			     mark(genstmt.head);
			     if (error_count)
				     YYERROR;
			     apply_deferred_init();
			     dataseg_layout();
			     regex_layout();
			     compile_tree(genstmt.head);
		     }
	     }
           ;

decllist   : decl
             {
		     $$.head = $$.tail = $1;
	     }
           | decllist decl
             {
		     if ($2) {
			     if ($1.tail) 
				     $1.tail->next = $2;
			     else
				     $1.head = $2;
			     $1.tail = $2;
		     }
		     $$ = $1;
	     }
           ;

decl       : PROG state_ident DO stmtlist DONE
             {
		     $$ = alloc_node(node_type_progdecl, &$1);
		     $$->v.progdecl.tag = $2;
		     $$->v.progdecl.auto_count = forget_autos(PARMCOUNT(),
							      0, 0);
		     $$->v.progdecl.tree = $4.head;
		     
		     outer_context = inner_context = context_none;
		     state_tag = smtp_state_none;
	     }
           | progspecial DO stmtlist DONE
             {
		     static NODE *progspecial[2];
		     NODE *np = progspecial[$1.code];
		     
		     if (!np) {
			     np = alloc_node(node_type_progdecl, &$1.locus);
			     $$ = progspecial[$1.code] = np;
			     np->v.progdecl.tag = state_tag;
			     np->v.progdecl.tree = $3.head;
			     np->v.progdecl.auto_count = 0;
		     } else {
			     NODE *cur;
			     for (cur = np->v.progdecl.tree; cur->next;
				  cur = cur->next)
				     ;
			     cur->next = $3.head;
			     $$ = NULL;
		     }
				     
		     np->v.progdecl.auto_count = forget_autos(PARMCOUNT(),
							      np->v.progdecl.auto_count,
							      0);
		     outer_context = inner_context = context_none;
		     state_tag = smtp_state_none;
	     }
           | FUNC fundecl DO stmtlist DONE
             {
		     func->node = $4.head;
		     $$ = declare_function(func, &$1,
			   forget_autos(PARMCOUNT() + FUNC_HIDDEN_ARGS(func),
					0, FUNC_HIDDEN_ARGS(func)));
		     outer_context = inner_context = context_none;
		     func = NULL;
	     }
           | vardecl
	     {
		     $$ = NULL;
	     }
	   | constdecl
	     {
		     $$ = NULL;
	     }
           ;

progspecial: KW_BEGIN
             {
		     state_tag = smtp_state_begin;
		     outer_context = inner_context = context_handler;
		     $$.locus = $1;
		     $$.code = PS_BEGIN;
	     }
           | KW_END
             {
		     state_tag = smtp_state_end;
		     outer_context = inner_context = context_handler;
		     $$.locus = $1;
		     $$.code = PS_END;
	     }
           ;

vardecl    : TYPE IDENTIFIER 
             {
		     if (!vardecl($2->text, $1, storage_extern, NULL)) 
			     YYERROR;
	     }
           | TYPE IDENTIFIER expr
             {
		     struct value value;
		     struct variable *var;
		     
		     var = vardecl($2->text, $1, storage_extern, NULL);
		     if (!var)
			     YYERROR;

		     if (optimization_level)
			     optimize($3);
		     value.type = node_type($3);
		     
		     switch ($3->type) {
		     case node_type_string:
			     value.v.literal = $3->v.literal;
			     break;

		     case node_type_number:
			     value.v.number = $3->v.number;
			     break;

		     default:
			     yyerror("initializer element is not constant");
			     YYERROR;
		     }

		     if (initialize_variable(var, &value, &$3->locus))
			     YYERROR;
	     }
           | SET IDENTIFIER expr
             {
		     struct value value;
		     
		     if (optimization_level)
			     optimize($3);
		     value.type = node_type($3);
		     
		     switch ($3->type) {
		     case node_type_string:
			     value.v.literal = $3->v.literal;
			     break;

		     case node_type_number:
			     value.v.number = $3->v.number;
			     break;

		     default:
			     yyerror("initializer element is not constant");
			     YYERROR;
		     }
		     if (!externdecl($2->text, &value, &$1))
			     YYERROR;
	     }
           ;

constdecl  : CONST IDENTIFIER expr
             {
		     struct value value;
		     struct variable *pvar;

		     /* FIXME: This is necessary because constants can be
			referred to the same way as variables. */
		     if (pvar = variable_lookup($2->text)) {
			     parse_warning(_("Constant name `%s' clashes with a variable name"),
					   $2->text);
			     parse_warning_locus(&pvar->locus,
						 _("This is the location of the "
						   "previous definition"));
		     }
			     
		     if (optimization_level)
			     optimize($3);
		     
		     switch ($3->type) {
		     case node_type_string:
			     value.type = dtype_string;
			     value.v.literal = $3->v.literal;
			     break;

		     case node_type_number:
			     value.type = dtype_number;
			     value.v.number = $3->v.number;
			     break;
			     
		     default:
			     yyerror("initializer element is not constant");
			     YYERROR;
		     }
		     define_constant($2->text, &value, &$1);
		     $$ = NULL;
	     }
           ;

fundecl    : IDENTIFIER '(' parmdecl ')' aliasdecl retdecl
 	     {
		     data_type_t *ptypes = NULL;
		     
		     if ($3.count) {
			     int i;
			     struct parmtype *p;
			     
			     ptypes = xmalloc($3.count * sizeof *ptypes);
			     for (i = 0, p = $3.head; p; i++) {
				     struct parmtype *next = p->next;
				     ptypes[i] = p->type;
				     free(p);
				     p = next;
			     }
		     }

		     $$ = func = function_install($1->text,
						  $3.count, $3.optcount,
						  $3.varargs,
						  ptypes, $6,
						  get_locus());
		     if ($5) {
			     mu_list_do($5, _create_alias, $$);
			     mu_list_destroy(&$5);
		     }
		     outer_context = inner_context = context_function;
	     }
           ;

parmdecl   : /* empty */
             {
		     $$.count = $$.optcount = 0;
		     $$.varargs = 0;
	     }
           | params
           ;

params     : fparmlist
           | DOTS
             {
		     $$.count = $$.optcount = 0;
		     $$.varargs = 1;
	     }
	   | parmlist ';' fparmlist
             {
		     $1.count += $3.count;
		     $1.optcount = $3.count;
		     $1.varargs = $3.varargs;
		     $1.tail->next = $3.head;
		     $1.tail = $3.tail;
		     $$ = $1;
	     }
           ;

parmlist   : parm
             {
		     $$.count = 1;
		     $$.varargs = 0;
		     $$.head = $$.tail = $1;
	     }
           | parmlist ',' parm
             {
		     $1.count++;
		     $1.tail->next = $3;
		     $1.tail = $3;
		     $$ = $1;
	     }
           ;

fparmlist  : parmlist
           | parmlist ',' DOTS
             {
		     $1.varargs = 1;
		     $$ = $1;
	     }
           ;

parm       : TYPE IDENTIFIER
             {
		     if (!vardecl($2->text, $1, storage_param, NULL))
			     YYERROR;
		     $$ = xmalloc(sizeof *$$);
		     $$->next = NULL;
		     $$->type = $1;
	     }
           | TYPE
             {
		     $$ = xmalloc(sizeof *$$);
		     $$->next = NULL;
		     $$->type = $1;
	     }
           | IDENTIFIER
             {
		     $$ = xmalloc(sizeof *$$);
		     $$->next = NULL;
		     if (($$->type = string_to_type($1->text)) == dtype_unspecified) 
			     parse_error(_("Unknown type specification: %s"),
					 $1->text);
	     }
           ;

aliasdecl  : /* empty */
             {
		     $$ = NULL;
	     }
           | aliases
	   ;

aliases    : alias
             {
		     mu_list_create(&$$);
		     mu_list_append($$, $1);
	     }
           | aliases alias
             {
		     mu_list_append($1, $2);
		     $$ = $1;
	     }
           ;

alias      : ALIAS IDENTIFIER
             {
		     $$ = $2;
	     }
           ;

retdecl    : /* empty */
             {
		     $$ = dtype_unspecified;
	     }
           | RETURNS TYPE
             {
		     $$ = $2;
	     }
           | RETURNS IDENTIFIER
             {
		     if (($$ = string_to_type($2->text)) == dtype_unspecified) 
			     parse_error(_("Unknown type specification: %s"),
					 $2->text);
	     }
           ;

state_ident: IDENTIFIER
             {
		     $$ = string_to_state($1->text);
		     if ($$ == smtp_state_none) 
			     parse_error(_("Unknown smtp state tag: %s"),
					 $1->text);
		     state_tag = $$;
		     outer_context = inner_context = context_handler;
	     }
           ;

stmtlist   : stmt
             {
		     if ($1) 
			     $1->next = NULL;
		     $$.head = $$.tail = $1;
	     }
           | stmtlist stmt
             {
		     if ($2) {
			     if ($1.tail) 
				     $1.tail->next = $2;
			     else
				     $1.head = $2;
			     $1.tail = $2;
		     }
		     $$ = $1;
	     }
           ;

stmt       : condition
           | action
           | asgn
           | autodcl
           | catch
           | throw
           | return
           | proccall
           | constdecl
           | loopstmt
           | jumpstmt
           ;

asgn       : SET IDENTIFIER expr
             {
		     struct variable *var;
		     data_type_t t = node_type($3);

		     if (t == dtype_unspecified) {
			     parse_error(_("Unspecified value not ignored as "
					   "it should be"));
			     YYERROR;
		     }

		     var = variable_lookup($2->text);
		     if (!var) {
			     var = vardecl($2->text, t, storage_auto, &$1);
			     if (!var) 
				     YYERROR;
		     }
		     $$ = create_asgn_node(var, $3, &$1);
		     if (!$$)
			     YYERROR;
	     }
           ;

autodcl    : TYPE IDENTIFIER
             {
		     if (!vardecl($2->text, $1, storage_auto, NULL))
			     YYERROR;
		     $$ = NULL;
	     }
           | TYPE IDENTIFIER expr
             {
		     struct variable *var = vardecl($2->text, $1,
						    storage_auto, NULL);
		     if (!var)
			     YYERROR;
		     $$ = create_asgn_node(var, $3, get_locus());
		     if (!$$)
			     YYERROR;
	     }
           ;

action     : sendmail_action
             {
		     if (inner_context == context_handler) {
			     if (state_tag == smtp_state_begin)
				     parse_error(_("Sendmail action is not "
						   "allowed in begin block"));
			     else if (state_tag == smtp_state_end)
				     parse_error(_("Sendmail action is not "
						   "allowed in end block"));
		     }
	     }
           | header_action
             {
		     if (inner_context == context_handler
			 && state_tag == smtp_state_end)
			     parse_error(_("Header action is not allowed "
					   "in end block"));
	     }
           | PASS
             {
		     $$ = alloc_node(node_type_noop, &$1);
	     }
           | KW_ECHO expr
             {
		     $$ = alloc_node(node_type_echo, &$1);
		     $$->v.node = cast_to(dtype_string, $2);
	     }
           ;

sendmail_action:
             ACT_ACCEPT maybe_triplet
             {
		     if ($2.code || $2.xcode || $2.message)
			     parse_warning(_("Arguments are ignored for accept"));
		     $$ = alloc_node(node_type_result, &$1);
		     $$->v.ret = $2;
		     $$->v.ret.stat = SMFIS_ACCEPT;
	     }
           | ACT_REJECT maybe_triplet
             {
		     $$ = alloc_node(node_type_result, &$1);
		     $$->v.ret = $2;
		     $$->v.ret.stat = SMFIS_REJECT;
	     }
           | ACT_REJECT '(' maybe_expr ',' maybe_xcode_expr ',' maybe_expr ')'
             {
		     $$ = alloc_node(node_type_result, &$1);
		     $$->v.ret.stat = SMFIS_REJECT;
		     $$->v.ret.code = $3 ? cast_to(dtype_string, $3) : NULL;
		     $$->v.ret.xcode = $5 ? cast_to(dtype_string, $5) : NULL;
		     $$->v.ret.message = $7 ? cast_to(dtype_string, $7) : NULL;
	     }
           | ACT_TEMPFAIL maybe_triplet
             {
		     $$ = alloc_node(node_type_result, &$1);
		     $$->v.ret = $2;
		     $$->v.ret.stat = SMFIS_TEMPFAIL;
	     }
           | ACT_TEMPFAIL '(' maybe_expr ',' maybe_xcode_expr ',' maybe_expr ')'
             {
		     $$ = alloc_node(node_type_result, &$1);
		     $$->v.ret.stat = SMFIS_TEMPFAIL;
		     $$->v.ret.code = $3 ? cast_to(dtype_string, $3) : NULL;
		     $$->v.ret.xcode = $5 ? cast_to(dtype_string, $5) : NULL;
		     $$->v.ret.message = $7 ? cast_to(dtype_string, $7) : NULL;
	     }
           | ACT_CONTINUE
             {
		     $$ = alloc_node(node_type_result, &$1);
		     memset(&$$->v.ret, 0, sizeof $$->v.ret);
		     $$->v.ret.stat = SMFIS_CONTINUE;
	     }
           | ACT_DISCARD
             {
		     $$ = alloc_node(node_type_result, &$1);
		     memset(&$$->v.ret, 0, sizeof $$->v.ret);
		     $$->v.ret.stat = SMFIS_DISCARD;
	     }
           ;

maybe_xcode_expr: maybe_expr
           | xcode
             {
		     $$ = alloc_node(node_type_string, get_locus());
		     $$->v.literal = $1;
	     }
           ;
           

header_action:
             ADD string expr
             {
		     $$ = alloc_node(node_type_header, &$1);
		     $$->v.hdr.opcode = header_add;
		     $$->v.hdr.name = $2;
		     $$->v.hdr.value = cast_to(dtype_string, $3);
	     }
           | REPLACE string expr
             {
		     $$ = alloc_node(node_type_header, &$1);
		     $$->v.hdr.opcode = header_replace;
		     $$->v.hdr.name = $2;
		     $$->v.hdr.value = cast_to(dtype_string, $3);
	     }
           | DELETE string
             {
		     $$ = alloc_node(node_type_header, &$1);
		     $$->v.hdr.opcode = header_delete;
		     $$->v.hdr.name = $2;
		     $$->v.hdr.value = NULL;
	     }
           ;	   

maybe_triplet: /* empty */
             {
		     memset(&$$, 0, sizeof $$);
	     }
           | triplet
	   ;

triplet    : code
             {
		     $$.code = alloc_node(node_type_string, get_locus());
		     $$.code->v.literal = $1;
		     $$.xcode = NULL;
		     $$.message = NULL;
	     }
           | code xcode
             {
		     $$.code = alloc_node(node_type_string, get_locus());
		     $$.code->v.literal = $1;
		     $$.xcode = alloc_node(node_type_string, get_locus());
		     $$.xcode->v.literal = $2;
		     $$.message = NULL;
	     }
           | code xcode expr
             {
		     $$.code = alloc_node(node_type_string, get_locus());
		     $$.code->v.literal = $1;
		     $$.xcode = alloc_node(node_type_string, get_locus());
		     $$.xcode->v.literal = $2;
		     $$.message = cast_to(dtype_string, $3);
	     }
           | code expr
             {
		     $$.code = alloc_node(node_type_string, get_locus());
		     $$.code->v.literal = $1;
		     $$.xcode = NULL;
		     $$.message = cast_to(dtype_string, $2);
	     }
           ;

code       : NUMBER
             {
		     char buf[4];

		     if ($1 < 200 || $1 > 599) {
			     yyerror(_("Invalid SMTP reply code"));
			     buf[0] = 0;
		     } else
			     snprintf(buf, sizeof(buf), "%lu", $1);
		     $$ = string_alloc(buf, strlen(buf));
	     }
           ;

xcode      : NUMBER '.' NUMBER '.' NUMBER
             {
		     char buf[sizeof("5.999.999")];

		     /* RFC 1893:
			The syntax of the new status codes is defined as:

			status-code = class "." subject "." detail
			class = "2"/"4"/"5"
			subject = 1*3digit
			detail = 1*3digit
		     */			       
		     if (($1 != 2 && $1 != 4 && $1 !=5)
			 || $3 > 999 || $5 > 999) {
			     yyerror(_("Invalid extended reply code"));
			     buf[0] = 0;
		     } else
			     snprintf(buf, sizeof(buf), "%lu.%lu.%lu",
				      $1, $3, $5);
		     $$ = string_alloc(buf, strlen(buf));
             }
           ;

condition  : if_cond
           | case_cond 
           | on_cond
           ;

if_cond    : IF expr stmtlist else_cond FI
             {
		     $$ = alloc_node(node_type_if, &$1);
		     $$->v.cond.cond = $2;
		     $$->v.cond.if_true = $3.head;
		     $$->v.cond.if_false = $4;
	     }
           ;

else_cond  : /* empty */
             {
		     $$ = NULL;
	     }
           | ELIF expr stmtlist else_cond
             {
		     $$ = alloc_node(node_type_if, &$1);
		     $$->v.cond.cond = $2;
		     $$->v.cond.if_true = $3.head;
		     $$->v.cond.if_false = $4;
	     }
           | ELSE stmtlist
             {
		     $$ = $2.head;
	     }
           ;

case_cond  : SWITCH expr DO cond_branches DONE
             {
		     struct case_stmt *defcase = NULL, *pcase, *prev;
		     
		     $$ = alloc_node(node_type_switch, &$1);
		     $$->v.switch_stmt.node = $2;
		     
		     /* Make sure there is only one default case and
			place it at the beginning of the list */
		     pcase = $4.head;
		     if (!pcase->valist) {
			     defcase = pcase;
			     $4.head = $4.head->next;
		     }
		     prev = pcase;
		     pcase = pcase->next;
		     while (pcase) {
			     if (!pcase->valist) {
				     if (defcase) {
					     parse_error_locus(&pcase->locus,
					      _("Duplicate default statement"));
					     parse_error_locus(&defcase->locus,
					      _("Previously defined here"));
					     YYERROR;
				     }
				     defcase = pcase;
				     prev->next = pcase->next;
			     } else
				     prev = pcase;
			     pcase = pcase->next;
		     }

		     if (!defcase) {
			     defcase = xmalloc(sizeof *defcase);
			     defcase->locus = *get_locus();
			     defcase->valist = NULL;
			     defcase->node = alloc_node(node_type_noop,
							&defcase->locus);
		     }
		     defcase->next = $4.head;
		     $$->v.switch_stmt.cases = defcase;
	     }
           ;

cond_branches: cond_branch
               {
		       $$.head = $$.tail = $1;
	       }
           | cond_branches cond_branch
               {
		       $$.tail->next = $2;
		       $$.tail = $2;
	       }
           ;

cond_branch: CASE valist ':' stmtlist 
             {
		     $$ = xmalloc(sizeof *$$);
		     $$->next = NULL;
		     $$->locus = $1;
		     $$->valist = $2.head;
		     $$->node = $4.head;
	     }
           | DEFAULT ':' stmtlist
             {
		     $$ = xmalloc(sizeof *$$);
		     $$->next = NULL;
		     $$->locus = $1;
		     $$->valist = NULL;
		     $$->node = $3.head;
	     }		     
           ;

valist     : value
             {
		     $$.head = $$.tail = xmalloc(sizeof($$.head[0]));
		     $$.head->next = NULL;
		     $$.head->value = $1;
	     }
           | valist OR value
             {
		     struct valist *p = xmalloc(sizeof(*p));
		     p->value = $3;
		     p->next = NULL;
		     $1.tail->next = p;
		     $1.tail = p;
		     $$ = $1;
	     }
           ;

value      : STRING
             {
		     $$.type = dtype_string;
		     $$.v.literal = $1;
	     }
           | IDENTIFIER
             {
		     const struct value *value_ptr =
			     constant_lookup_value($1->text);
		     if (value_ptr) 
			     $$ = *value_ptr;
		     else {
			     if (!allow_unquoted_strings)
				     parse_warning(_("Unquoted identifier `%s'"),
					   $1->text);
			     $$.type = dtype_string;
			     $$.v.literal = $1;
		     }
	     }
           | NUMBER
             {
		     $$.type = dtype_number;
		     $$.v.number = $1;
	     }
           ;

string     : value
             {
		     if ($1.type != dtype_string) {
			     parse_error(_("Expected string, but found %s"),
					 type_to_string($1.type));
			     /* Make sure we return something usable: */
			     $$ = string_alloc("ERROR", 5);
		     } else
			     $$ = $1.v.literal; 
	     }
           ;

matches    : MATCHES
             {
		     $$.locus = $1;
		     $$.qualifier = 0;
	     }
           | MXMATCHES
             {
		     $$.locus = $1;
		     $$.qualifier = QUALIFIER_MX;
	     }
           ;

fnmatches  : FNMATCHES
             {
		     $$.locus = $1;
		     $$.qualifier = 0;
	     }
           | MXFNMATCHES
             {
		     $$.locus = $1;
		     $$.qualifier = QUALIFIER_MX;
	     }
           ;


/* Loop statements */

loopstmt   : LOOP loop_ident opt_loop_parms DO stmtlist DONE opt_while
             {
		     leave_loop();
		     $3.end_while = $7;
		     $$ = alloc_node(node_type_loop, &$1);
		     $3.body = $5.head;
		     $3.ident = $2;
		     $$->v.loop = $3;
	     }
           ;

loop_ident : opt_ident
             {
		     enter_loop($1, NULL, NULL);
	     }
           ;

opt_ident  : /* empty */
             {
		     $$ = NULL;
	     }
           | IDENTIFIER
           ;

opt_loop_parms: /* empty */
             {
		     memset(&$$, 0, sizeof $$);
	     }
           | loop_parm_list
	   ;

loop_parm_list: loop_parm
             {
		     memset(&$$, 0, sizeof $$);
		     switch ($1.kw) {
		     case 0:
			     $$.stmt = $1.expr;
			     break;

		     case FOR:
			     $$.for_stmt = $1.expr;
			     break;

		     case WHILE:
			     $$.beg_while = $1.expr;
			     break;

		     default:
			     abort();
		     }
	     }
           | loop_parm_list ',' loop_parm
             {
		     switch ($3.kw) {
		     case 0:
			     if ($$.stmt) 
				     parse_error(_("Duplicate loop increment"));
			     $$.stmt = $3.expr;
			     break;

		     case FOR:
			     if ($$.for_stmt) 
				     parse_error(_("Duplicate for statement"));
			     $$.for_stmt = $3.expr;
			     break;

		     case WHILE:
			     if ($$.beg_while) 
				     parse_error(_("Duplicate while statement"));
			     $$.beg_while = $3.expr;
			     break;

		     default:
			     abort();
		     }
	     }
           ;

loop_parm  : stmtlist
             {
		     $$.kw = 0;
		     $$.expr = $1.head;
	     }
           | FOR stmtlist
             {
		     $$.kw = FOR;
		     $$.expr = $2.head;
	     }
           | WHILE expr
             {
		     $$.kw = WHILE;
		     $$.expr = $2;
	     }
           ;

opt_while  : /* empty */
             {
		     $$ = NULL;
	     }
           | WHILE expr
             {
		     $$ = $2;
	     }
           ;

jumpstmt   : BREAK opt_ident
             {
		     if (!within_loop($2)) {
			     if ($2)
				     parse_error(_("No such loop: %s"), 
				                 $2->text);
			     parse_error(_("`break' used outside `loop'"));
			     YYERROR;
		     }
		     $$ = alloc_node(node_type_break, &$1);
		     $$->v.literal = $2;
	     }
           | NEXT opt_ident
             {
		     if (!within_loop($2)) {
			     if ($2) {
				     parse_error(_("No such loop: %s"), $2->text);
				     parse_error(_("`next' used outside `loop'"));
				     YYERROR;
			     } else {
				     parse_error(_("`next' is used outside `loop'; did you mean `pass'?"));
				     YYERROR;
			     }
		     } else {
			     $$ = alloc_node(node_type_next, &$1);
			     $$->v.literal = $2;
		     }
	     }
           ;


/* Expressions */
expr       : NOT expr
             {
		     $$ = alloc_node(node_type_un, &$1);
		     $$->v.un.opcode = unary_not;
		     $$->v.un.arg = cast_to(dtype_number, $2);
	     }
           | expr EQ expr
             {
		     $$ = alloc_node(node_type_bin, &$2);
		     $$->v.bin.opcode = bin_eq;
		     $$->v.bin.arg[0] = $1;
		     $$->v.bin.arg[1] = cast_to(node_type($1), $3);
	     }
           | expr NE expr
             {
		     $$ = alloc_node(node_type_bin, &$2);
		     $$->v.bin.opcode = bin_ne;
		     $$->v.bin.arg[0] = $1;
		     $$->v.bin.arg[1] = cast_to(node_type($1), $3);
	     }
           | expr LT expr
             {
		     $$ = alloc_node(node_type_bin, &$2);
		     $$->v.bin.opcode = bin_lt;
		     $$->v.bin.arg[0] = $1;
		     $$->v.bin.arg[1] = cast_to(node_type($1), $3);
	     }
	   | expr LE expr
             {
		     $$ = alloc_node(node_type_bin, &$2);
		     $$->v.bin.opcode = bin_le;
		     $$->v.bin.arg[0] = $1;
		     $$->v.bin.arg[1] = cast_to(node_type($1), $3);
	     }
	   | expr GT expr
             {
		     $$ = alloc_node(node_type_bin, &$2);
		     $$->v.bin.opcode = bin_gt;
		     $$->v.bin.arg[0] = $1;
		     $$->v.bin.arg[1] = cast_to(node_type($1), $3);
	     }
	   | expr GE expr
             {
		     $$ = alloc_node(node_type_bin, &$2);
		     $$->v.bin.opcode = bin_ge;
		     $$->v.bin.arg[0] = $1;
		     $$->v.bin.arg[1] = cast_to(node_type($1), $3);
	     }
           | expr matches expr %prec MATCHES 
             {
		     NODE *p;
		     
		     $$ = alloc_node(node_type_bin, &$2.locus);
		     $$->v.bin.opcode = bin_match;
		     $$->v.bin.qualifier = $2.qualifier;
		     $$->v.bin.arg[0] = cast_to(dtype_string, $1);
		     $$->v.bin.arg[1] = p = alloc_node(node_type_regcomp, &$2.locus);
		     p->v.regcomp_data.expr = cast_to(dtype_string, $3);
		     p->v.regcomp_data.flags = regex_flags;
	     }
           | expr fnmatches expr %prec MATCHES
             {
		     $$ = alloc_node(node_type_bin, &$2.locus);
		     $$->v.bin.opcode = bin_fnmatch;
		     $$->v.bin.qualifier = $2.qualifier;
		     $$->v.bin.arg[0] = cast_to(dtype_string, $1);
		     $$->v.bin.arg[1] = cast_to(dtype_string, $3);
	     }
           | expr OR expr
             {
		     $$ = alloc_node(node_type_bin, &$2);
		     $$->v.bin.opcode = bin_or;
		     $$->v.bin.arg[0] = cast_to(dtype_number, $1);
		     $$->v.bin.arg[1] = cast_to(dtype_number, $3);
	     }
           | expr AND expr
             {
		     $$ = alloc_node(node_type_bin, &$2);
		     $$->v.bin.opcode = bin_and;
		     $$->v.bin.arg[0] = cast_to(dtype_number, $1);
		     $$->v.bin.arg[1] = cast_to(dtype_number, $3);
	     }
           | common_expr
	   ;

maybe_expr : /* empty */
             {
		     $$ = NULL;
	     }
           | expr
	   ;

common_expr: simp_expr
	   | common_expr simp_expr %prec CONCAT
             {
		     $$ = alloc_node(node_type_concat, get_locus());
		     $$->v.concat.arg[0] = cast_to(dtype_string, $1);
		     $$->v.concat.arg[1] = cast_to(dtype_string, $2);
	     }
	   ;

simp_expr  : atom_expr
           | simp_expr '+' simp_expr
             {
		     $$ = alloc_node(node_type_bin, get_locus());
		     $$->v.bin.opcode = bin_add;
		     $$->v.bin.arg[0] = cast_to(dtype_number, $1);
		     $$->v.bin.arg[1] = cast_to(dtype_number, $3);
	     }		     
	   | simp_expr '-' simp_expr
             {
		     $$ = alloc_node(node_type_bin, get_locus());
		     $$->v.bin.opcode = bin_sub;
		     $$->v.bin.arg[0] = cast_to(dtype_number, $1);
		     $$->v.bin.arg[1] = cast_to(dtype_number, $3);
	     }		     
	   | simp_expr '*' simp_expr
             {
		     $$ = alloc_node(node_type_bin, get_locus());
		     $$->v.bin.opcode = bin_mul;
		     $$->v.bin.arg[0] = cast_to(dtype_number, $1);
		     $$->v.bin.arg[1] = cast_to(dtype_number, $3);
	     }		     
	   | simp_expr '/' simp_expr
             {
		     $$ = alloc_node(node_type_bin, get_locus());
		     $$->v.bin.opcode = bin_div;
		     $$->v.bin.arg[0] = cast_to(dtype_number, $1);
		     $$->v.bin.arg[1] = cast_to(dtype_number, $3);
	     }
           | simp_expr LOGAND simp_expr
             {
		     $$ = alloc_node(node_type_bin, get_locus());
		     $$->v.bin.opcode = bin_logand;
		     $$->v.bin.arg[0] = cast_to(dtype_number, $1);
		     $$->v.bin.arg[1] = cast_to(dtype_number, $3);
	     }
           | simp_expr LOGOR simp_expr
             {
		     $$ = alloc_node(node_type_bin, get_locus());
		     $$->v.bin.opcode = bin_logor;
		     $$->v.bin.arg[0] = cast_to(dtype_number, $1);
		     $$->v.bin.arg[1] = cast_to(dtype_number, $3);
	     }
           | simp_expr LOGXOR simp_expr
             {
		     $$ = alloc_node(node_type_bin, get_locus());
		     $$->v.bin.opcode = bin_logxor;
		     $$->v.bin.arg[0] = cast_to(dtype_number, $1);
		     $$->v.bin.arg[1] = cast_to(dtype_number, $3);
	     }
           ;

atom_expr  : funcall
           | '(' expr ')'
             {
		     $$ = $2;
	     }
           | atom
           | '-' simp_expr %prec UMINUS
             {
		     $$ = alloc_node(node_type_un, get_locus());
		     $$->v.un.opcode = unary_minus;
		     $$->v.un.arg = cast_to(dtype_number, $2);
	     }
           | '+' simp_expr %prec UMINUS
             {
		     $$ = $2;
	     }
           | LOGNOT simp_expr %prec UMINUS
             {
		     $$ = alloc_node(node_type_un, get_locus());
		     $$->v.un.opcode = unary_lognot;
		     $$->v.un.arg = cast_to(dtype_number, $2);
	     }
           ;

atom       : SYMBOL
             {
		     register_macro(state_tag, $1->text);
		     $$ = alloc_node(node_type_symbol, get_locus());
		     $$->v.literal = $1;
	     }
           | value
             {
		     switch ($1.type) {
		     case dtype_number:
			     $$ = alloc_node(node_type_number, get_locus());
			     $$->v.number = $1.v.number;
			     break;

		     case dtype_string:
			     $$ = alloc_node(node_type_string, get_locus());
			     $$->v.literal = $1.v.literal;
			     break;
			     
		     default:
			     abort();
		     }
	     }
           | BACKREF
             {
		     $$ = alloc_node(node_type_backref, get_locus());
		     $$->v.number = $1;
	     }
           | argref
           | ARGCOUNT
             {
		     if (outer_context == context_function) {
			     if (func->optcount || func->varargs) {
				     $$ = alloc_node(node_type_arg, &$1);
				     $$->v.arg.data_type = dtype_number;
				     $$->v.arg.number = 1;
			     } else {
				     $$ = alloc_node(node_type_number, &$1);
				     $$->v.number = parminfo[outer_context].parmcount();
			     }
		     } else {
			     $$ = alloc_node(node_type_number, &$1);
			     $$->v.number = parminfo[outer_context].parmcount();
		     }
	     }
           | '@' IDENTIFIER
             {
		     struct variable *var = variable_lookup($2->text);
		     if (!var) {
			     parse_error(_("Variable %s is not defined"),
					 $2->text);
			     YYERROR;
		     }
		     $$ = alloc_node(node_type_offset, get_locus());
		     $$->v.var_ref.variable = var;
		     $$->v.var_ref.nframes = catch_nesting;
	     }
           | VAPTR paren_argref
             {
		     $$ = alloc_node(node_type_vaptr, get_locus());
		     $$->v.node = $2;
	     }
 	   ;

argref     : variable
             {
		     $$ = alloc_node(node_type_variable, get_locus());
		     $$->v.var_ref.variable = $1;
		     $$->v.var_ref.nframes = catch_nesting;
	     }
           | ARG
             {
		     if (inner_context == context_function
			 && func->varargs)
			     ;
		     else if ($1 > PARMCOUNT()) 
			     parse_error(_("Argument number too high"));
		     $$ = alloc_node(node_type_arg, get_locus());
		     $$->v.arg.data_type = PARMTYPE($1);
		     $$->v.arg.number = $1;
		     if (inner_context == context_function)
			     $$->v.arg.number += FUNC_HIDDEN_ARGS(func);
 	     }
           | ARGX '(' expr ')'
             {
		     if (outer_context == context_function) {
			     if (func->varargs) {
				     $$ = alloc_node(node_type_argx, &$1);
				     $$->v.argx.nargs = PARMCOUNT() +
					     FUNC_HIDDEN_ARGS(func);
				     $$->v.argx.node = $3;
			     } else {
				     $$ = alloc_node(node_type_noop, &$1);
				     parse_error(_("$(expr) is allowed only "
						   "in a function with "
						   "variable number of "
						   "arguments"));
			     }
		     } else {
			     $$ = alloc_node(node_type_noop, &$1);
			     parse_error(_("$(expr) is allowed only "
					   "in a function with "
					   "variable number of "
					   "arguments"));
		     }
	     }
           ;

paren_argref: argref
           | '(' argref ')'
             {
		     $$ = $2;
	     }
           ;

funcall    : BUILTIN '(' arglist ')' 
             {
		     if (check_builtin_usage($1))
			     YYERROR;
		     if ($3.count < $1->parmcount - $1->optcount) {
			     parse_error(_("Too few arguments in call to `%s'"),
					 $1->name);
			     YYERROR;
		     } else if ($3.count > $1->parmcount
				&& !($1->flags & MFD_BUILTIN_VARIADIC)) {
			     parse_error(_("Too many arguments in call to `%s'"),
					 $1->name);
			     YYERROR;
		     } else {
			     $$ = alloc_node(node_type_builtin, get_locus());
			     $$->v.builtin.builtin = $1;
			     $$->v.builtin.args =
					     reverse(cast_arg_list($3.head,
 							       $1->parmcount,
							       $1->parmtype,
							       $$->v.builtin.builtin->flags & MFD_BUILTIN_NO_PROMOTE));
		     }
	     }
	   | BUILTIN '(' ')' 
             {
		     if (check_builtin_usage($1))
			     YYERROR;
		     if ($1->parmcount - $1->optcount) {
			     parse_error(_("Too few arguments in call to `%s'"),
					 $1->name);
			     YYERROR;
		     } else {
 			     $$ = alloc_node(node_type_builtin, get_locus());
			     $$->v.builtin.builtin = $1;
			     $$->v.builtin.args = NULL;
		     }
	     }
	   | BUILTIN_P expr
             {
		     if (check_builtin_usage($1))
			     YYERROR;
		     if ($1->parmcount - $1->optcount > 1) {
			     parse_error(_("Too few arguments in call to `%s'"),
					 $1->name);
			     YYERROR;
		     } else if ($1->parmcount == 0) {
			     parse_error(_("Too many arguments in call to `%s'"),
					 $1->name);
			     YYERROR;
		     } else {
			     $$ = alloc_node(node_type_builtin, get_locus());
			     $$->v.builtin.builtin = $1;
			     $$->v.builtin.args = cast_arg_list($2,
								$1->parmcount,
								$1->parmtype,
								0);
		     }
	     }
           | FUNCTION '(' arglist ')' 
             {
		     if (check_func_usage($1))
			     YYERROR;
		     $$ = function_call($1, $3.count, $3.head);
		     if (!$$)
			     YYERROR;
	     }
           | FUNCTION '(' ')' 
             {
		     if (check_func_usage($1))
			     YYERROR;
		     $$ = function_call($1, 0, NULL);
		     if (!$$)
			     YYERROR;
	     }
           | FUNCTION_P expr
             {
		     if (check_func_usage($1))
			     YYERROR;
		     $$ = function_call($1, 1, $2);
		     if (!$$)
			     YYERROR;
	     }
           ;

proccall   : BUILTIN_PROC '(' arglist ')' 
             {
		     if (check_builtin_usage($1))
			     YYERROR;
		     if ($3.count < $1->parmcount - $1->optcount) {
			     parse_error(_("Too few arguments in call to `%s'"),
					 $1->name);
			     YYERROR;
		     } else if ($3.count > $1->parmcount) {
			     parse_error(_("Too many arguments in call to `%s'"),
					 $1->name);
			     YYERROR;
		     } else {
			     $$ = alloc_node(node_type_builtin, get_locus());
			     $$->v.builtin.builtin = $1;
			     $$->v.builtin.args = reverse(cast_arg_list($3.head,
								$1->parmcount,
								$1->parmtype,
								0));
		     }
	     }
	   | BUILTIN_PROC '(' ')' 
             {
		     if (check_builtin_usage($1))
			     YYERROR;
		     if ($1->parmcount - $1->optcount) {
			     parse_error(_("Too few arguments in call to `%s'"),
					 $1->name);
			     YYERROR;
		     } else {
 			     $$ = alloc_node(node_type_builtin, get_locus());
			     $$->v.builtin.builtin = $1;
			     $$->v.builtin.args = NULL;
		     }
	     }
	   | BUILTIN_PROC expr 
             {
		     if (check_builtin_usage($1))
			     YYERROR;
		     if ($1->parmcount - $1->optcount > 1) {
			     parse_error(_("Too few arguments in call to `%s'"),
					 $1->name);
			     YYERROR;
		     } else if ($1->parmcount == 0) {
			     parse_error(_("Too many arguments in call to `%s'"),
					 $1->name);
			     YYERROR;
		     } else {
			     $$ = alloc_node(node_type_builtin, get_locus());
			     $$->v.builtin.builtin = $1;
			     $$->v.builtin.args = cast_arg_list($2,
								$1->parmcount,
								$1->parmtype,
								0);
		     }
	     }
           | FUNCTION_PROC '(' arglist ')' 
             {
		     if (check_func_usage($1))
			     YYERROR;
		     $$ = function_call($1, $3.count, $3.head);
		     if (!$$)
			     YYERROR;
	     }
           | FUNCTION_PROC '(' ')' 
             {
		     if (check_func_usage($1))
			     YYERROR;
		     $$ = function_call($1, 0, NULL);
		     if (!$$)
			     YYERROR;
	     }
           | FUNCTION_PROC expr 
             {
		     if (check_func_usage($1))
			     YYERROR;
		     $$ = function_call($1, 1, $2);
		     if (!$$)
			     YYERROR;
	     }
           ;

arglist    : expr
             {
		     $1->next = NULL;
		     $$.head = $$.tail = $1;
		     $$.count = 1;
	     }
           | arglist ',' expr
             {
		     $1.tail->next = $3;
		     $1.tail = $3;
		     $1.count++;
		     $$ = $1;
	     }
           ;

variable   : VARIABLE
             {
		     add_xref($1, get_locus());
	     }
           | BOGUS
             {
		     YYERROR;
	     }
           ;

catch      : CATCH catchlist DO
                 { $<tie_in>$ = inner_context;
		   inner_context = context_catch; 
 		   catch_nesting++; }
                 stmtlist DONE
              {
		      int i;
		      struct valist *p;

		      inner_context = $<tie_in>4;
		      catch_nesting--;
		      $$ = alloc_node(node_type_catch, &$1);
		      for (i = 0, p = $2.head; p; p = p->next)
			      i++;
		      $$->v.catch.count = i;
		      $$->v.catch.exmask = 0;
		      $$->v.catch.context = outer_context;/*??*/
		      for (i = 0, p = $2.head; p; p = p->next, i++) {
			      if (p->value.type != dtype_number) {
				      parse_error_locus(&$1,
							_("Expected numeric value, but found `%s'"),
							p->value.v.literal->text);
				      continue;
			      }
			      $$->v.catch.exmask |= EXMASK(p->value.v.number);
			      if (outer_context == context_function)
				      func->exmask |= EXMASK(p->value.v.number);
		      }
		      $$->v.catch.node = $5.head;
	      }
            ;

catchlist   : '*'
              {
		      int i;

		      $$.head = $$.tail = NULL;
		      for (i = 0; i < mf_exception_count; i++) {
			      struct valist *p = xmalloc(sizeof *p);
			      p->next = NULL; 
			      p->value.type = dtype_number;
			      p->value.v.number = i;
			      if (!$$.head)
				      $$.head = $$.tail = p;
			      else {
				      $$.tail->next = p;
				      $$.tail = p;
			      }
		      }
	      }
            | valist
            ; 

throw       : THROW value expr
              {
		      $$ = alloc_node(node_type_throw, &$1);
		      if ($2.type != dtype_number) 
			      parse_error(_("Exception code not a number"));
		      if ($2.v.number > mf_exception_count)
			      parse_error(_("Invalid exception number: %lu"),
					  $2.v.number);

		      $$->v.throw.code = $2.v.number;
		      $$->v.throw.expr = cast_to(dtype_string, $3);
	      }
            ;

return      : RETURN
              {
		      if (!func) 
			      parse_error(_("`return' outside of a function"));
		      else if (func->rettype != dtype_unspecified) 
			      parse_error(
				      _("`return' with no value, in function "
				      "returning non-void"));
		      $$ = alloc_node(node_type_return, &$1);
		      $$->v.node = NULL;
	      }
            | RETURN expr
              {
		      if (!func) 
			      parse_error(_("`return' outside of a function"));
		      else {
			      if (func->rettype == dtype_unspecified) 
				      parse_error(
				       _("`return' with a value, in function "
				       "returning void"));
			      $$ = alloc_node(node_type_return, &$1);
			      $$->v.node = cast_to(func->rettype, $2);
		      }
	      }
            ;

/* *************************** */
/*         ON statement        */
/* *************************** */

on_cond    : on pollstmt do branches DONE
             {
		     NODE *sel, *np;
		     NODE *head = NULL, *tail;
		     const struct builtin *bi;
		     
		     /* Build argument list */
		     if ($2.client_addr) {
			     head = tail = $2.client_addr;
			     tail = $2.email;
			     if (!tail) {
				     parse_error(_("recipient address not specified in `on poll' construct"));
				     YYERROR;
			     }
			     tail->next = NULL;
			     head->next = tail;
		     } else
			     head = tail = $2.email;

		     if ($2.ehlo)
			     np = $2.ehlo;
		     else {
			     np = alloc_node(node_type_variable, get_locus());
			     np->v.var_ref.variable =
				     variable_lookup("ehlo_domain");
			     np->v.var_ref.nframes = 0;
		     }
		     tail->next = np;
		     tail = np;

		     if ($2.mailfrom)
			     np = $2.mailfrom;
		     else {
			     np = alloc_node(node_type_variable, get_locus());
			     np->v.var_ref.variable =
				     variable_lookup("mailfrom_address");
			     np->v.var_ref.nframes = 0;
		     }
		     tail->next = np;
		     tail = np;

		     if ($2.client_addr) 
			     bi = builtin_lookup("strictpoll");
		     else
			     bi = builtin_lookup("stdpoll");
		     
		     sel = alloc_node(node_type_builtin, &$1);
		     sel->v.builtin.builtin = bi;
		     sel->v.builtin.args = reverse(head);

		     $$ = create_on_node(sel, $4.head);
	     }
           | on funcall do branches DONE
             {
		     $$ = create_on_node($2, $4.head);
	     }
           ;

on         : ON
             {
		     tie_in_onblock(1);
	     }
           ;

do         : DO
             {
		     tie_in_onblock(0);
	     }
           ;

pollstmt   : POLL expr
             {
		     struct pollarg arg;
		     
		     arg.kw = FOR;
		     arg.expr = $2;
		     memset(&$$, 0, sizeof $$);
		     set_poll_arg(&$$, arg.kw, arg.expr);
	     }
           | POLL expr pollarglist
             {
		     struct pollarg arg;
		     
		     arg.kw = FOR;
		     arg.expr = $2;
		     set_poll_arg(&$3, arg.kw, arg.expr);
		     $$ = $3;
	     }
           | POLL pollarglist
             {
		     $$ = $2;
	     }
           ;

pollarglist: pollarg
             {
		     memset(&$$, 0, sizeof $$);
		     set_poll_arg(&$$, $1.kw, $1.expr);
	     }
           | pollarglist pollarg
             {
		     set_poll_arg(&$1, $2.kw, $2.expr);
		     $$ = $1;
	     }
           ;

pollarg    : FOR expr
             {
		     $$.kw = FOR;
		     $$.expr = $2;
	     }
           | HOST expr
             {
		     $$.kw = HOST;
		     $$.expr = $2;
	     }
           | AS expr
             {
		     $$.kw = AS;
		     $$.expr = $2;
	     }
           | FROM expr
             {
		     $$.kw = FROM;
		     $$.expr = $2;
	     }
           ;


branches   : branch
             {
		     $$.head = $$.tail = $1;
	     }
           | branches branch
             {
		     $1.tail->next = $2;
		     $1.tail = $2;
		     $$ = $1;
	     }
           ;

branch     : WHEN { allow_unquoted_strings = 1; } valist ':'
                  { allow_unquoted_strings = 0; } stmtlist
             {
		     struct valist *p;

		     for (p = $3.head; p; p = p->next) {
			     if (p->value.type == dtype_string) {
				     parse_error("Invalid data type, expected number.");
				     /* Try to continue */
				     p->value.type = dtype_number;
				     p->value.v.number = 0;
			     }
		     }
		     
		     $$ = xmalloc(sizeof *$$);
		     $$->next = NULL;
		     $$->locus = $1;
		     $$->valist = $3.head;
		     $$->node = $6.head;
	     }
           ;

%%

int
yyerror(char *s)
{
	parse_error("%s", s);
	return 0;
}

int
parse_program(char *name, int ydebug)
{
	int rc;
	yydebug = ydebug;
	if (source(name))
		return -1;
	outer_context = inner_context = context_none;
	catch_nesting = 0;
	code_immediate(NULL); /* Reserve 0 slot */
	rc = yyparse() + error_count;
	return rc;
}

NODE *
alloc_node(enum node_type type, const struct locus *locus)
{
	NODE *node = malloc(sizeof(*node));
	if (!node) {
		yyerror("Not enough memory");
		abort();
	}
	node->type = type;
	node->locus = *locus;
	node->next = NULL;
	return node;
}

void
free_node(NODE *node)
{
	free(node);
}

void
copy_node(NODE *dest, NODE *src)
{
	dest->type = src->type;
	dest->locus = src->locus;
	dest->v = src->v;
}

void
free_subtree(NODE *node)
{
	/*FIXME*/
}


/* Print parse tree */

static void print_node_list(NODE *node, int indent);
static void print_node_list_reverse(NODE *node, int level);
static void print_node(NODE *node, int indent);
void print_stat(sfsistat stat);
static int dbg_setreply(void *data, char *code, char *xcode, char *message);
static void dbg_msgmod(void *data, struct msgmod_closure *clos);

static void
print_level(int level)
{
	level *= 2;
	printf("%*.*s", level, level, "");
}

static void
print_bin_op(enum bin_opcode opcode)
{
	char *p;
	switch (opcode) {
	case bin_and:
		p = "AND";
		break;
		
	case bin_or:
		p = "OR";
		break;
		
	case bin_eq:
		p = "EQ";
		break;
		
	case bin_ne:
		p = "NE";
		break;
		
	case bin_lt:
		p = "LT";
		break;
		
	case bin_le:
		p = "LE";
		break;
		
	case bin_gt:
		p = "GT";
		break;
		
	case bin_ge:
		p = "GE";
		break;
		
	case bin_match:
		p = "MATCH";
		break;
		
	case bin_fnmatch:
		p = "FNMATCH";
		break;

	case bin_add:
		p = "ADD";
		break;
		
	case bin_sub:
		p = "SUB";
		break;
		
	case bin_mul:
		p = "MUL";
		break;
		
	case bin_div:
		p = "DIV";
		break;

	case bin_logand:
		p = "LOGAND";
		break;
		
	case bin_logor:
		p = "LOGOR";
		break;
		
	case bin_logxor:
		p = "LOGXOR";
		break;
		
	default:
		p = "UNKNOWN_OP";
	}
	printf("%s", p);
}

static void
print_quoted_string(const char *str)
{
	for (; *str; str++) {
		if (c_isprint(*str))
			putchar(*str);
		else {
			putchar('\\');
			switch (*str) {
			case '\a':
				putchar('a');
				break;
			case '\b':
				putchar('b');
				break;
			case '\f':
				putchar('f');
				break;
			case '\n':
				putchar('n');
				break;
			case '\r':
				putchar('r');
				break;
			case '\t':
				putchar('t');
				break;
			default:
				printf("%03o", *str);
			}
		}
	}
}

struct node_drv {
	void (*print) (NODE *, int);
	void (*mark) (NODE *);
	void (*code) (NODE *, struct locus **);
	void (*optimize) (NODE *);
};

static void traverse_tree(NODE *node);
static void code_node(NODE *node);
static void code_node(NODE *node);
static void optimize_node(NODE *node);
static void optimize(NODE *node);
static void record_switch(struct switch_stmt *sw);

#include "drivers.c"
#include "node-tab.c"

struct node_drv *
find_node_drv(enum node_type type)
{
	if (type >= NELEMS(nodetab)) {
		parse_error(_("INTERNAL ERROR at %s:%d, "
			      "unexpected node type %d"),
			    __FILE__, __LINE__,
			    type);
		abort();
	}
	return nodetab + type;
}

static void
print_node(NODE *node, int level)
{
	struct node_drv *nd = find_node_drv(node->type);
	if (nd->print)
		nd->print(node, level);
}	

static void
print_node_list(NODE *node, int level)
{
	for (; node; node = node->next)
		print_node(node, level);
}

static void
print_node_list_reverse(NODE *node, int level)
{
	if (node) {
		print_node_list_reverse(node->next, level);
		print_node(node, level);
	}
}

int
function_enumerator(void *sym, void *data)
{
	int i;
	struct function *f = sym;
	
	printf("function %s (", f->name);
	for (i = 0; i < f->parmcount; i++) {
		printf("%s", type_to_string(f->parmtype[i]));
		if (i < f->parmcount-1)
			putchar(',');
	}
	putchar(')');
	if (f->rettype != dtype_unspecified)
		printf(" returns %s", type_to_string(f->rettype));
	printf(":\n");
	print_node_list(f->node, 0);
	printf("END function %s\n", f->name);
	return 0;
}
		
void
print_syntax_tree()
{
	enum smtp_state tag;
	printf("State handlers:\n");
	printf("---------------\n");
	for (tag = smtp_state_first; tag < smtp_state_count; tag++) {
		if (root_node[tag]) {
			printf("%s:\n", state_to_string(tag));
			print_node_list(root_node[tag], 0);
			putchar('\n');
		}
	}
	printf("User functions:\n");
	printf("---------------\n");
	symbol_enumerate(SYM_FUNC, function_enumerator, NULL);
}


/* Cross-reference support */

struct collect_data {
	struct obstack stk;
	size_t count;
};

static int
variable_enumerator(void *item, void *data)
{
	struct variable *var = item;
	struct collect_data *p = data;
	if (var->flags & (VAR_VOLATILE | VAR_REFERENCED)) {
		obstack_grow(&p->stk, &var, sizeof var);
		p->count++;
	}
	return 0;
}

int
print_locus(void *item, void *data)
{
	struct locus *loc = item;
	struct locus **prev = data;
	int c;

	if (!*prev) {
		*prev = loc;
		printf("%s", loc->file);
		c = ':';
	} else if (strcmp((*prev)->file, loc->file)) {
		*prev = loc;
		printf(", %s", loc->file);
		c = ':';
	} else
		c = ',';
	printf("%c%lu", c, (unsigned long) loc->line);
	return 0;
}

void
print_xref_var(struct variable *var)
{
        struct locus *prev = NULL;
	printf("%-32.32s %6s %lu ",
	       var->name, type_to_string(var->type), (unsigned long)var->off);
	mu_list_do(var->xref, print_locus, &prev);
	printf("\n");
}

int
vp_comp(const void *a, const void *b)
{
	struct variable * const *va = a, * const *vb = b;
	return strcmp((*va)->name, (*vb)->name);
}

void
print_xref()
{
	struct collect_data cd;
	struct variable **vp;
	size_t i;
	
	obstack_init(&cd.stk);
	cd.count = 0;
	symbol_enumerate(SYM_VARIABLE, variable_enumerator, &cd);
	printf("Cross-references:\n");
	printf("-----------------\n");
	
	vp = obstack_finish(&cd.stk);
	qsort(vp, cd.count, sizeof *vp, vp_comp);
	for (i = 0; i < cd.count; i++, vp++) 
		print_xref_var(*vp);
	obstack_free(&cd.stk, NULL);
}


static mu_list_t smtp_macro_list[gacopyz_stage_max];

static enum gacopyz_stage 
smtp_to_gacopyz_stage(enum smtp_state tag)
{
	switch (tag) {
	case smtp_state_connect:
		return gacopyz_stage_conn;
	case smtp_state_helo:
		return gacopyz_stage_helo;
	case smtp_state_envfrom:
		return gacopyz_stage_mail;
	case smtp_state_envrcpt:
		return gacopyz_stage_rcpt;
	case smtp_state_data:
	case smtp_state_header:
	case smtp_state_body:
		return gacopyz_stage_data;
	case smtp_state_eoh:
		return gacopyz_stage_eoh;
	case smtp_state_eom:
		return gacopyz_stage_eom;
	default:
		break;
	}
	return gacopyz_stage_none;
}

void
register_macro(enum smtp_state state, const char *macro)
{
	enum gacopyz_stage ind = smtp_to_gacopyz_stage(state);
	if (ind == gacopyz_stage_none)
		return;
	if (!smtp_macro_list[ind]) {
		mu_list_create(&smtp_macro_list[ind]);
		mu_list_set_comparator(smtp_macro_list[ind], compare_string);
	}
	/* FIXME: MU: 2nd arg should be const? */
	if (mu_list_locate(smtp_macro_list[ind], (void*) macro, NULL)) 
		mu_list_append(smtp_macro_list[ind], (void*) macro);
}

static int
print_macro(void *item, void *data)
{
	int *p = data;
	if (*p) {
		printf(" ");
		*p = 0;
	} else
		printf(", ");
	printf("%s", (char*) item);
	return 0;
}

void
print_used_macros()
{
	enum gacopyz_stage i;
	
	for (i = 0; i < gacopyz_stage_max; i++) {
		if (smtp_macro_list[i]) {
			int n = 1;
			printf("%s", gacopyz_stage_name[i]);
			mu_list_do(smtp_macro_list[i], print_macro, &n);
			printf("\n");
		}
	}
}

struct macro_acc {
	size_t size;
	char *buf;
};

static int
add_macro_size(void *item, void *data)
{
	char *macro = (char*) item;
	struct macro_acc *mp = data;
	mp->size += strlen(macro) + 1;
	return 0;
}

static int
concat_macro(void *item, void *data)
{
	char *macro = (char*) item;
	struct macro_acc *mp = data;
	size_t len = strlen(macro);
	char *pbuf = mp->buf + mp->size;
	memcpy(pbuf, macro, len);
	pbuf[len++] = ' ';
	mp->size += len;
	return 0;
}

char *
get_stage_macro_string(enum gacopyz_stage i)
{
	struct macro_acc acc;
	size_t size;
	mu_list_t list = smtp_macro_list[i];
	if (!list)
		return NULL;
		
	acc.size = 0;
	mu_list_do(list, add_macro_size, &acc);
	if (!acc.size)
		return NULL;
	size = acc.size;
		
	acc.size = 0;
	acc.buf = xmalloc (size);
	mu_list_do(list, concat_macro, &acc);
	acc.buf[size-1] = 0;
	return acc.buf;
}


/* Code generation */

static void
code_node(NODE *node)
{
	if (!node) 
		error_count++;
	else {
		static struct locus *old_locus;
		struct node_drv *nd = find_node_drv(node->type);
		if (nd->code)
			nd->code(node, &old_locus);
	}
}

static void
traverse_tree(NODE *node)
{
	for (; node; node = node->next)
		code_node(node);
}

static void
optimize_node(NODE *node)
{
	if (!node) 
		error_count++;
	else {
		struct node_drv *nd = find_node_drv(node->type);
		if (nd->optimize)
			nd->optimize(node);
	}
}

static void
optimize(NODE *node)
{
	for (; node; node = node->next)
		optimize_node(node);
}

static int
optimize_tree(NODE *node)
{
	if (optimization_level)
		optimize(node);
	return error_count;
}


static struct switch_stmt *switch_root;

static void
record_switch(struct switch_stmt *sw)
{
	sw->next = switch_root;
	switch_root = sw;
}



static void
mark_node(NODE *node)
{
	if (!node) 
		error_count++;
	else {
		struct node_drv *nd = find_node_drv(node->type);
		if (nd->mark)
			nd->mark(node);
	}
}

static void
mark(NODE *node)
{
	for (; node; node = node->next)
		mark_node(node);
}
	

static int
codegen(prog_counter_t *pc, NODE *node, unsigned exmask,
	int finalize, size_t nautos)
{
	if (error_count)
		return 1;
	
	*pc = code_get_counter();
	jump_pc = 0;
	if (nautos) {
		code_op(opcode_stkalloc);
		code_immediate((void*)nautos);
	}
	if (exmask) {
		code_op(opcode_saveex);
		code_immediate((void*) exmask);
	}
	traverse_tree(node);

	jump_fixup(jump_pc, code_get_counter());
	if (exmask) 
		code_op(opcode_restex);
	
	if (finalize)
		code_op(opcode_nil);
	else
		code_op(opcode_return);
		
	return 0;
}

static void
compile_tree(NODE *node)
{
	struct node_drv *nd;
	struct locus *plocus;
	
	for (; node; node = node->next) {
		switch (node->type) {
		case node_type_progdecl:
		case node_type_funcdecl:
			nd = find_node_drv(node->type);
			if (!nd->code)
				abort();
			nd->code(node, &plocus);
			break;
			
		default:
			parse_error_locus(&node->locus,
					  _("INTERNAL ERROR at %s:%d, "
					    "unexpected node type %d"),
					  __FILE__, __LINE__,
					  node->type);
			break;
		}
	}
}
		



#define skip_ws(p) while (*(p) && c_isspace(*(p))) (p)++;
			  
static char *
getword(const char **p, char **buf, size_t *bsize)
{
	int len;
	size_t size = 0;
	char *retval = NULL;
	
	skip_ws(*p);
	if (!**p)
		return NULL;
	for (len = 0; (*p)[len] && !c_isspace((*p)[len]); len++)
		;
	if (buf) {
		if (!bsize)
			bsize = &size;
		if (len + 1 > *bsize) {
			*bsize = len + 1;
			*buf = xrealloc(*buf, *bsize);
		}
		memcpy(*buf, *p, len);
		(*buf)[len] = 0;
		retval = *buf;
	}
	*p += len;
	return retval;
}

enum regex_mode { regex_enable, regex_disable, regex_set };

static mf_stack_t regex_stack;

void
regex_push()
{
	if (!regex_stack)
		regex_stack = mf_stack_create(sizeof regex_flags, 0);
	mf_stack_push(regex_stack, &regex_flags);
}

void
regex_pop()
{
	if (!regex_stack || mf_stack_pop(regex_stack, &regex_flags))
		parse_error(_("Nothing to pop"));
}

static void
pragma_regex(int argc, char **argv, const char *text)
{
	enum regex_mode mode = regex_set;
	int i = 1;

	if (strcmp(argv[i], "push") == 0) {
		regex_push();
		i++;
	} else if (strcmp(argv[i], "pop") == 0) {
		regex_pop();
		i++;
	}

	for (; i < argc; i++) {
		int bit;
		char *p = argv[i];
		switch (p[0]) {
		case '+':
			mode = regex_enable;
			p++;
			break;

		case '-':
			mode = regex_disable;
			p++;
			break;

		case '=':
			mode = regex_set;
			p++;
			break;
		}

		if (strcmp (p, REG_EXTENDED_NAME) == 0)
			bit = REG_EXTENDED;
		else if (strcmp (p, REG_ICASE_NAME) == 0)
			bit = REG_ICASE;
		else if (strcmp (p, REG_NEWLINE_NAME) == 0)
			bit = REG_NEWLINE;
		else {
			parse_error(_("Unknown regexp flag: %s"), p);
			return;
		}

		switch (mode) {
		case regex_disable:
			regex_flags &= ~bit;
			break;
		case regex_enable:
			regex_flags |= bit;
			break;
		case regex_set:
			regex_flags = bit;
			break;
		}
	}
}	

static void
pragma_option(int argc, char **argv, const char *text)
{
	char *name = NULL;
	char *value = NULL;
	char *p;
	int len;

	getword(&text, NULL, NULL);
	if (!getword(&text, &name, NULL)) {
		parse_error(_("Invalid pragma: expected option name"));
		return;
	}

#define EXPIRE_SUFFIX 	"expire-interval"
#define EXPIRE_SUFFIX_LEN (sizeof(EXPIRE_SUFFIX)-1)

#define TIMEOUT_SUFFIX  "timeout"
#define TIMEOUT_SUFFIX_LEN (sizeof(TIMEOUT_SUFFIX)-1)

	if (strcmp(name, "mailfrom") == 0
	    || (strlen(name) >= EXPIRE_SUFFIX_LEN
		&& strcmp(name + strlen(name) - EXPIRE_SUFFIX_LEN,
			  EXPIRE_SUFFIX) == 0)
	    || (strlen(name) >= TIMEOUT_SUFFIX_LEN
		&& strcmp(name + strlen(name) - TIMEOUT_SUFFIX_LEN,
			  TIMEOUT_SUFFIX) == 0)) {
		/* Special handling for expire and timeout intervals */
		value = strdup(text);
		text += strlen(text);
	} else if (!getword(&text, &value, NULL)) {
		parse_error(_("Invalid pragma: expected option value"));
		free(name);
		return;
	}

	skip_ws(text);
	if (*text) {
		parse_error(_("Invalid pragma: junk after the arguments"));
		/* Try to handle it anyway */
	}

	p = value;
	skip_ws(p);
	len = strlen(p);
	if ((*p == '"' || *p == '\'') && p[len-1] == *p) {
		p[len-1] = 0;
		p++;
	}
		
	if (set_option(name, p, 0)) {
		if (errno == ENOENT)
			parse_error(_("Unknown pragma option"));
		else
			parse_error(_("Invalid pragma"));
	}
	
	free(name);
	free(value);
}

static int
strtosize(const char *text, size_t *psize)
{
	unsigned long n;
	size_t size;
	char *p;

	n = strtoul(text, &p, 0);
	size = n;
	switch (*p) {
	case 't':
	case 'T':
		size *= 1024;
	case 'g':
	case 'G':
		size *= 1024;
	case 'm':
	case 'M':
		size *= 1024;
	case 'k':
	case 'K':
		size *= 1024;
		p++;
		if (*p && (*p == 'b' || *p == 'B'))
			p++;
		break;

	case 0:
		break;
		
	default:
		parse_error(_("invalid size suffix (near %s)"), p);
		return 1;
	}

	if (size < n) {
		parse_error(_("invalid size: numeric overflow occurred"));
		return 2;
	}
	
	*psize = size;

	return 0;
}

static void
pragma_stacksize(int argc, char **argv, const char *text)
{
	size_t size, incr = stack_expand_incr, max_size = stack_max_size;
	enum stack_expand_policy policy = stack_expand_policy;

	switch (argc) {
	case 4:
		if (strtosize(argv[3], &max_size))
			return;
	case 3:
		if (strcmp(argv[2], "twice") == 0) 
			policy = stack_expand_twice;
		else {
			policy = stack_expand_add;
				
			if (strtosize(argv[2], &incr))
				return;
		}
	case 2:
		strtosize(argv[1], &size);
	}

	stack_size = size;
	stack_expand_incr = incr;
	stack_expand_policy = policy;
	stack_max_size = max_size;
}

static int
get_interval(const char *text, time_t *pinterval)
{
	const char *endp;
	time_t interval;

	while (*text && c_isspace(*text))
		text++;
	if (!*text) {
		parse_error(_("Invalid pragma: unexpected end of line"));
		return 1;
	}
	if (parse_time_interval(text, &interval, &endp)) {
		parse_error(_("Invalid pragma: unrecognized time format "
			      "(near `%s')"),
			    endp);
		return 1;
	}
	*pinterval = interval;
	return 0;
}

/* #pragma database FMTNAME file FILENAME
   #pragma database FMTNAME expire-interval INTERVAL
   #pragma database cache positive-expire-interval INTERVAL
   #pragma database cache negative-expire-interval INTERVAL
   #pragma database dns negative-expire-interval INTERVAL
*/
static void
pragma_database(int argc, char **argv, const char *text)
{
	char *fmtname = NULL;
	char *kw = NULL;
	struct db_format *fmt;
	
	getword(&text, NULL, NULL);
	if (!getword(&text, &fmtname, NULL)) {
		parse_error(_("Invalid pragma: expected database name"));
		return;
	}
	if ((fmt = db_format_lookup(fmtname)) == NULL) {
		parse_error(_("Unknown database format: %s"), fmtname);
		return;
	}
	if (!getword(&text, &kw, NULL)) {
		parse_error(_("Invalid pragma: expected keyword"));
		return;
	}
	if (strcmp(kw, "file") == 0) {
		char *value = NULL;
		char *p;
		int len;
		
		if (!getword(&text, &value, NULL)) {
			parse_error(_("Invalid pragma: expected file name"));
			return;
		}
		p = value;
		len = strlen(p);
		if ((*p == '"' || *p == '\'') && p[len-1] == *p) {
			p[len-1] = 0;
			p++;
		}
		fmt->dbname = strdup(p);
		free(value);
	} else if (strcmp(kw, "expire-interval") == 0) {
		get_interval(text, &fmt->expire_interval);
	} else if (strcmp(kw, "positive-expire-interval") == 0) {
		if (fmt != cache_format) {
			parse_error(_("positive-expire-interval is valid only "
				      "for cache database"));
			return;
		}
		get_interval(text, &fmt->expire_interval);
	} else if (strcmp(kw, "negative-expire-interval") == 0) {
		if (fmt == cache_format) 
			get_interval(text, &negative_expire_interval);
		else if (fmt == dns_cache_format)
			get_interval(text, &fmt->expire_interval);
		else {
			parse_error(_("negative-expire-interval is valid only "
				      "for cache and dns databases"));
			return;
		}
		
	} else {
		parse_error(_("Invalid pragma: unrecognized keyword: %s"), kw);
		return;
	}
}

void
pragma_setup()
{
	install_pragma("regex", 2, 0, pragma_regex);
	install_pragma("option", 0, 0, pragma_option);
	install_pragma("stacksize", 2, 4, pragma_stacksize);
	install_pragma("database", 0, 0, pragma_database);
}



/* Test run */
struct sfsistat_tab {
	char *name;
	sfsistat stat;
} sfsistat_tab[] = {
	{ "accept", SMFIS_ACCEPT },
	{ "continue", SMFIS_CONTINUE },
	{ "discard", SMFIS_DISCARD },
	{ "reject", SMFIS_REJECT },
	{ "tempfail", SMFIS_TEMPFAIL },
	{ NULL }
};

const char *
sfsistat_str(sfsistat stat)
{
	struct sfsistat_tab *p;
	for (p = sfsistat_tab; p->name; p++)
		if (p->stat == stat) 
			return p->name;
	return NULL;
}

void
print_stat(sfsistat stat)
{
	struct sfsistat_tab *p;
	for (p = sfsistat_tab; p->name; p++)
		if (p->stat == stat) {
			printf("%s", p->name);
			return;
		}
	printf("%d", stat);
}

const char *
msgmod_opcode_str(enum msgmod_opcode opcode)
{
	switch (opcode) {
	case header_add:
		return "ADD HEADER";
		
	case header_replace:
		return "REPLACE HEADER";

	case header_delete:
		return "DELETE HEADER";

	case header_insert:
		return "INSERT HEADER";
		
	case rcpt_add:
		return "ADD RECIPIENT";

	case rcpt_delete:
		return "DELETE RECIPIENT";

	case quarantine:
		return "QUARANTINE";

	case body_repl:
		return "REPLACE BODY";
	}
	return "UNKNOWN HEADER COMMAND";
}

static int
dbg_setreply(void *data, char *code, char *xcode, char *message)
{
	if (code) {
		printf("SET REPLY %s", code);
		if (xcode)
			printf(" %s", xcode);
		if (message)
			printf(" %s", message);
		printf("\n");
	}
	return 0;
}

static void
dbg_msgmod(void *data, struct msgmod_closure *clos)
{
	printf("%s %s: %s %u\n", msgmod_opcode_str(clos->opcode),
	       clos->name, SP(clos->value), clos->idx);
}

static const char *
dbg_dict_getsym (void *data, const char *str)
{
	return dict_getsym ((mu_assoc_t)data, str);
}

void
mailfromd_test(int argc, char **argv)
{
	int i, rc;
	mu_assoc_t dict = NULL;
	eval_environ_t env;
	char *p, *end;
	long n;
	sfsistat status;
	char *args[9] = {0,0,0,0,0,0,0,0,0};
		
	dict_init(&dict);
	env = create_environment(NULL,
				 dbg_dict_getsym, dbg_setreply, dbg_msgmod,
				 dict);
	xeval(env, smtp_state_begin);
	
	env_init(env);
	for (i = 0; i < argc; i++) {
		if (p = strchr(argv[i], '=')) {
			char *ident = argv[i];
			*p++ = 0;
			if (c_isdigit(*ident) && *ident != 0
				 && ident[1] == 0) 
				args[*ident - '0' - 1] = p;
			else 
				dict_install(dict, argv[i], p);
		}
	}

	for (i = state_parms[test_state].cnt; i--; ) {
		switch (state_parms[test_state].types[i]) {
		case dtype_string:
			env_push_string(env, args[i] ? args[i] : "");
			break;
		case dtype_number:
			if (args[i]) {
				n = strtol(args[i], &end, 0);
				if (*end) 
					mu_error(_("$%d is not a number"),
						 i+1);
			} else
				n = 0;
			env_push_number(env, n);
			break;
		default:
			abort();
		}
	}
	env_make_frame(env);

	rc = xeval(env, test_state);
	env_leave_frame(env, state_parms[test_state].cnt);
	env_final_gc(env);

	xeval(env, smtp_state_end);
	
	status = environment_get_status(env);
	printf("State %s: ", state_to_string(test_state));
	print_stat(status);
	printf("\n");
	destroy_environment(env);
}

void
mailfromd_run(prog_counter_t entry_point, int argc, char **argv)
{
	int rc, i;
	mu_assoc_t dict = NULL;
	eval_environ_t env;

	dict_init(&dict);
	env = create_environment(NULL,
				 dbg_dict_getsym, dbg_setreply, dbg_msgmod,
				 dict);

	env_init(env);

	env_push_number(env, 0);

	for (i = argc - 1; i >= 0; i--)
		env_push_string(env, argv[i]);
	env_push_number(env, argc);
	
	env_make_frame0(env);
	rc = eval_environment(env, entry_point);
	env_final_gc(env);
	rc = (int) env_get_reg(env);
	destroy_environment(env);
	exit(rc);
}

void
set_poll_arg(struct poll_data *poll, int kw, NODE *expr)
{
	switch (kw) {
	case FOR:
		poll->email = expr;
		break;
		
	case HOST:
		poll->client_addr = expr;
		break;
		
	case AS:
		poll->mailfrom = expr;
		break;
		
	case FROM:
		poll->ehlo = expr;
		break;
		
	default:
		abort();
	}
}
		
int
convert_rate(const char *arg, double *rate)
{
	double count;
	char *p;

	count = strtod(arg, &p);
	if (*p) {
		time_t div;
		const char *endp;

		while (*p && c_isspace(*p))
			p++;
		if (c_isalpha(*p)) {
			if (strlen(p) > 3
			    && memcmp(p, "per", 3) == 0 && c_isspace(p[3]))
				p += 3;
		} else if (c_ispunct(*p))
			p++;

		if (parse_time_interval(p, &div, &endp)) {
			mu_error(_("Unrecognized time format (near `%s')"),
				 endp);
			return 1;
		}
		count /= div;
	}
	*rate = count;
	return 0;
}
		
static struct tagtable {
	char *name;
	enum smtp_state tag;
} tagtable[] = {
	{ "none", smtp_state_none },
	{ "begin", smtp_state_begin },
	{ "connect", smtp_state_connect },
	{ "helo", smtp_state_helo },  
	{ "envfrom", smtp_state_envfrom }, 
	{ "envrcpt", smtp_state_envrcpt }, 
	{ "data", smtp_state_data },
	{ "header", smtp_state_header }, 
	{ "eoh", smtp_state_eoh }, 
	{ "body", smtp_state_body }, 
	{ "eom", smtp_state_eom },
	{ "end", smtp_state_end },
};

enum smtp_state
string_to_state(const char *name)
{
	struct tagtable *p;

	for (p = tagtable; p < tagtable + sizeof tagtable/sizeof tagtable[0];
	     p++)
		if (strcasecmp (p->name, name) == 0)
			return p->tag;

	return smtp_state_none;
}

const char *
state_to_string(enum smtp_state state)
{
	if (state < sizeof tagtable/sizeof tagtable[0])
		return tagtable[state].name;
	abort();
}


struct variable *
builtin_variable_install(const char *name, data_type_t type, unsigned flags)
{
	struct variable *var = variable_install(name);
	var->type = type;
	var->flags = flags;
	var->off = variable_count++;
	return var;
}

static NODE *
_reverse(NODE *list, NODE **root)
{
	NODE *next;

	if (list->next == NULL) {
		*root = list;
		return list;
	}
	next = _reverse(list->next, root);
	next->next = list;
	list->next = NULL;
	return list;
}		

NODE *
reverse(NODE *in)
{
	NODE *root;
	if (!in)
		return in;
	_reverse(in, &root);
	return root;
}


static NODE *
create_asgn_node(struct variable *var, NODE *expr, const struct locus *loc)
{
	NODE *node;
	data_type_t t = node_type(expr);

	if (t == dtype_unspecified) {
		parse_error(_("Unspecified value not ignored as it should be"));
		return NULL;
	}
	node = alloc_node(node_type_asgn, loc);
	node->v.asgn.var = var;
	node->v.asgn.nframes = catch_nesting;
	node->v.asgn.node = cast_to(var->type, expr);
	return node;
}


static NODE *
create_on_node(NODE *sel, struct case_stmt *cases)
{
	struct case_stmt *cur;
	unsigned mask = 0;
	char nbuf[NUMERIC_BUFSIZE_BOUND];
	struct function *fp;
	const char *base_name;
	char *fname;
	size_t size;
	int count = 0;
	int argc;
	NODE *args;
	data_type_t *ptypes, rettype;
	NODE *call_node, *retnode;
		     
	/* Create a list of exceptions to catch */
	for (cur = cases; cur; cur = cur->next) {
		struct valist *vp;
		for (vp = cur->valist; vp; vp = vp->next) {
			mask |= EXMASK(vp->value.v.number);
			count++;
		}
	}

	/* Check if we already have a wrapper function */
	snprintf(nbuf, sizeof nbuf, "%u", mask);
	switch (sel->type) {
	case node_type_builtin:
		base_name = sel->v.builtin.builtin->name;
		argc = sel->v.builtin.builtin->parmcount;
		args = sel->v.builtin.args;
		ptypes = sel->v.builtin.builtin->parmtype;
		rettype = sel->v.builtin.builtin->rettype;
		break;
	case node_type_call:
		base_name = sel->v.call.func->name;
		argc = sel->v.call.func->parmcount;
		args = sel->v.call.args;
		ptypes = sel->v.call.func->parmtype;
		rettype = sel->v.call.func->rettype;
		break;
	default:
		abort();
	}

	if (rettype == dtype_unspecified) {
		parse_error_locus(&sel->locus,
				  _("Function `%s' does not return any value"),
				  base_name);
		return NULL;
	}
	
	size = 2 + strlen(base_name) + 1 + strlen(nbuf) + 1;
	fname = xmalloc(size);
	strcpy(fname, "$");
	strcat(fname, base_name);
	strcat(fname, "_");
	strcat(fname, nbuf);
	strcat(fname, "$");
	
	fp = function_lookup(fname);
	if (!fp) {
		/* Build and register the function */
		NODE *np, *catch_node;
		NODE *head, *tail;
		int i;
		
		/* Create the catch statement */
		np = alloc_node(node_type_catch, get_locus());
		np->v.catch.count = count;
		np->v.catch.exmask = 0;
		np->v.catch.context = context_function;
		for (cur = cases; cur; cur = cur->next) {
			struct valist *vp;
			for (i = 0, vp = cur->valist; vp; vp = vp->next, i++)
				np->v.catch.exmask |= EXMASK(vp->value.v.number);
		}
		
		catch_node = np;
		
		np = alloc_node(node_type_return, get_locus());
		np->v.node = alloc_node(node_type_arg, get_locus());
		np->v.node->v.arg.number = 1;
		np->v.node->v.arg.data_type = PARMTYPE(1);
		catch_node->v.catch.node = np;

		/* Build call arguments */
		head = tail = NULL;
		for (i = 1; i <= argc; i++) {
			np = alloc_node(node_type_arg, get_locus());
			/* FIXME: Verify if this is always correct */
			np->v.arg.data_type = ptypes[i-1];
			np->v.arg.number = i;
			if (!head)
				head = tail = np;
			else {
				tail->next = np;
				tail = np;
			}
		}
				     
		np = alloc_node(node_type_return, get_locus());
		np->v.node = sel; /* FIXME: create a copy */
		switch (np->v.node->type) {
		case node_type_builtin:
			np->v.node->v.builtin.args = reverse(head);
			break;
		case node_type_call:
			np->v.node->v.call.args = reverse(head);
			break;
		default:
			abort();
		}
		
		catch_node->next = np;
		
		fp = function_install(fname, argc, 0, 0, ptypes,
				      rettype,
				      get_locus());
		fp->exmask = mask;
		fp->node = catch_node;

		np = declare_function(fp, &fp->locus, 0);
		if (genstmt.head == NULL)
			genstmt.head = np;
		else
			genstmt.tail->next = np;
		genstmt.tail = np;
	}
	free(fname);
	
	call_node = alloc_node(node_type_call, get_locus());
	call_node->v.call.func = fp;
	call_node->v.call.args = args;
	
	retnode = alloc_node(node_type_switch, get_locus());
	retnode->v.switch_stmt.node = call_node;
	retnode->v.switch_stmt.cases = cases;

	return retnode;
}

NODE *
function_call(struct function *function, size_t count, NODE *subtree)
{
	NODE *np = NULL;
	if (count < function->parmcount - function->optcount) {
		parse_error(_("Too few arguments in call to `%s'"),
			    function->name);
	} else if (count > function->parmcount && !function->varargs) {
		parse_error(_("Too many arguments in call to `%s'"),
			    function->name);
	} else {
		np = alloc_node(node_type_call, get_locus());
		np->v.call.func = function;
		np->v.call.args = reverse(cast_arg_list(subtree,
							function->parmcount,
							function->parmtype,
							0));
	}
	return np;
}	

data_type_t
node_type(NODE *node)
{
	switch (node->type) {
	case node_type_string:
	case node_type_symbol:
		return dtype_string;

	case node_type_number:
		return dtype_number;
		
	case node_type_if:
		return dtype_unspecified;
		
	case node_type_bin:
		return dtype_number;
		
	case node_type_un:
		return dtype_number;
		
	case node_type_builtin:
		return node->v.builtin.builtin->rettype;
		
	case node_type_concat:
		return dtype_string;
		
	case node_type_variable:
		return node->v.var_ref.variable->type;
		
	case node_type_arg:
		return node->v.arg.data_type;

	case node_type_argx:
		return dtype_string;
		
	case node_type_call:
		return node->v.call.func->rettype;
		
	case node_type_return:
		if (node->v.node)
			return node_type(node->v.node);
		break;

	case node_type_backref:
		return dtype_string;

	case node_type_cast:
		return node->v.cast.data_type;

	case node_type_offset:
		return dtype_number;

	case node_type_vaptr:
		return dtype_number;
		
	case node_type_result:
	case node_type_header:
	case node_type_asgn:
	case node_type_regex:
	case node_type_regcomp:
	case node_type_catch:
	case node_type_throw:
	case node_type_echo:
	case node_type_switch:
	case node_type_funcdecl:
	case node_type_progdecl:
	case node_type_noop:
	case node_type_next:
	case node_type_break:
	case node_type_loop:
	case max_node_type:
		break;
	}
	return dtype_unspecified;
}

NODE *
cast_to(data_type_t type, NODE *node)
{
	NODE *np;
	data_type_t ntype = node_type(node);
	
	switch (ntype) {
	case dtype_string:
	case dtype_number:
		if (type == ntype)
			return node;
		break;
		
	case dtype_pointer:
		if (type == ntype)
			return node;
		break;
		
	case dtype_unspecified:
		parse_error(_("Cannot convert %s to %s"), type_to_string(ntype),
			    type_to_string(type));
		return NULL;

	default:
		abort();
	}
	np = alloc_node(node_type_cast, get_locus());
	np->v.cast.data_type = type;
	np->v.cast.node = node;
	node->next = NULL;
	return np;
}

NODE *
cast_arg_list(NODE *args, size_t parmc, data_type_t *parmtype, int disable_prom)
{
	NODE *head = NULL, *tail = NULL;
	
	while (args) {
		NODE *next = args->next;
		NODE *p;
		data_type_t type;
		
		if (parmc) {
			type = *parmtype++;
			parmc--;
		} else if (disable_prom)
			type = node_type(args);
		else
			type = dtype_string;
		
		p = cast_to(type, args);

		if (head)
			tail->next = p;
		else
			head = p;
		tail = p;
		args = next;
	}
	return head;
}

void
add_xref(struct variable *var, const struct locus *locus)
{
	if (script_dump_xref) {
		struct locus *elt = xmalloc(sizeof *elt);
		if (!var->xref)
			mu_list_create(&var->xref);
		*elt = *locus;
		mu_list_append(var->xref, elt);
	}
}

struct variable *
vardecl(const char *name, data_type_t type, storage_class_t sc,
	struct locus *loc)
{
	struct variable *var;
	const struct constant *cptr;

	if (type == dtype_unspecified) {
		parse_error(_("Cannot define variable of unspecified type"));
		return NULL;
	}
	var = variable_install(name);
	if (var->type == dtype_unspecified) {
		/* the variable has just been added: go straight to
		   initializing it */;
	} else if (sc != var->storage_class) {
		struct variable *vp;
		
		switch (sc) {
		case storage_extern:
			parse_error(_("INTERNAL ERROR at %s:%d, declaring %s %s"),
				    __FILE__, __LINE__,
				    storage_class_str(sc), name);
			abort();

		case storage_auto:
			if (var->storage_class == storage_param) {
				parse_warning(_("Automatic variable `%s' "
					        "is shadowing a parameter"),
					      var->name);
			} else
				parse_warning(_("Automatic variable `%s' "
					        "is shadowing a global"), 
					      var->name);
			unregister_auto(var);
			break;

		case storage_param:
			parse_warning(_("Parameter `%s' is shadowing a "
				        "global"),
				      name);
		}

		/* Do the shadowing */
		vp = variable_replace(var, NULL);
		vp->shadowed = var;
		var = vp;
	} else {
		switch (sc) {
		case storage_extern:
			if (var->type != type) {
				parse_error(_("Redeclaring `%s' as different "
					      "data type"),
					    name);
				parse_error_locus(&var->locus,
					    _("This is the location of the "
					      "previous definition"));
				return NULL;
			}
			break;

		case storage_auto:
			if (var->type != type) {
				parse_error(_("Redeclaring `%s' as different "
					      "data type"),
					    name);
				parse_error_locus(&var->locus,
					    _("This is the location of the "
					      "previous definition"));
				return NULL;
			} else {
				parse_error(_("Duplicate variable: %s"), name);
				return NULL;
			}
			break;

		case storage_param:
			parse_error(_("Duplicate parameter: %s"), name);
			return NULL;
		}
	}

	/* FIXME: This is necessary because constants can be
	   referred to the same way as variables. */
	if (cptr = constant_lookup(name)) {
		parse_warning(_("Variable name `%s' clashes with a constant name"),
			      name);
		parse_warning_locus(&cptr->locus,
				    _("This is the location of the "
				      "previous definition"));
	}
	
	var->type = type;
	var->storage_class = sc;
	switch (sc) {
	case storage_extern:
		add_xref(var, loc ? loc : get_locus());
		break;
	case storage_auto:
	case storage_param:
		register_auto(var);
	}
	var->locus = *get_locus();
	return var;
}

static int
cast_value(data_type_t type, struct value *value)
{
	if (type != value->type) {
		char buf[NUMERIC_BUFSIZE_BOUND];
		char *p;
		
		switch (type) {
		default:
			abort();
			
		case dtype_string:
			snprintf(buf, sizeof buf, "%ld", value->v.number);
			value->v.literal = string_alloc(buf, strlen(buf));
			break;

		case dtype_number:
			value->v.number = strtol(value->v.literal->text,
						 &p, 10);
			if (*p) {
				parse_error(_("Cannot convert `%s' to number"),
					    value->v.literal->text);
				return 1;
			}
			break;
		}
		value->type = type;
	}
	return 0;
}

static struct variable *
externdecl(const char *name, struct value *value, struct locus *loc)
{
	struct variable *var = vardecl(name, value->type, storage_extern, loc);
	if (!var)
		return NULL;
	if (initialize_variable(var, value, loc))
		return NULL;
	return var;
}


struct deferred_decl {
	struct deferred_decl *next;
	struct literal *name;
	struct value value;
};

struct deferred_decl *deferred_decl;

void
defer_initialize_variable(const char *arg, const char *val)
{
	struct deferred_decl *p;
	struct literal *name = literal_lookup(arg);
	for (p = deferred_decl; p; p = p->next)
		if (p->name == name) {
			parse_warning_locus(NULL, _("Redefining variable %s"),
				            name->text);
			p->value.type = dtype_string;
			p->value.v.literal = literal_lookup(val);
			return;
		}
	p = xmalloc(sizeof *p);
	p->name = name;
	p->value.type = dtype_string;
	p->value.v.literal = literal_lookup(val);
	p->next = deferred_decl;
	deferred_decl = p;
}

static void
apply_deferred_init()
{
	struct deferred_decl *p;
	for (p = deferred_decl; p; p = p->next) {
		struct variable *var = variable_lookup(p->name->text);
		if (!var) {
			mu_error(_("<command line>: Warning: no such variable: %s"),
				 p->name->text);
			continue;
		}
		if (initialize_variable(var, &p->value, get_locus()))
			mu_error(_("Error initialising variable %s: incompatible types"),
				 p->name->text);
	}
}


struct declvar {
	struct declvar *next;
	struct locus locus;
	struct variable *var;
	struct value val;
};

static struct declvar *declvar;

int
initialize_variable(struct variable *var, struct value *val,
		    const struct locus *locus)
{
	struct declvar *dv;

	if (cast_value(var->type, val))
		return 1;
	for (dv = declvar; dv; dv = dv->next)
		if (dv->var == var) {
			parse_warning(_("Variable `%s' already initialized"),
				      var->name);
			dv->locus = *locus;
			dv->val = *val;
			return 0;
		}

	dv = xmalloc(sizeof *dv);
	dv->next = declvar;
	dv->var = var;
	dv->locus = *locus;
	dv->val = *val;
	declvar = dv;
	return 0;
}


void
ensure_initialized_variable(const char *name, struct value *val)
{
	struct declvar *dv;	
	struct variable *var = variable_lookup(name);

	if (!var)
		mu_error(_("INTERNAL ERROR at %s:%d: variable to be "
			   "initialized is not declared"),
			 __FILE__, __LINE__);
	if (var->type != val->type)
		mu_error(_("INTERNAL ERROR at %s:%d: variable to be "
			   "initialized has wrong type"),
			 __FILE__, __LINE__);
	for (dv = declvar; dv; dv = dv->next)
		if (dv->var == var)
			return;
	dv = xmalloc(sizeof *dv);
	dv->var = var;
	dv->val = *val;
	dv->next = declvar;
	declvar = dv;
}

static int
_ds_variable_fun(void *sym, void *data)
{
	struct variable *var = sym;

	if (!(var->flags & VAR_VOLATILE) && (var->flags & VAR_REFERENCED)) 
		var->off = variable_count++;
	if ((var->flags & (VAR_VOLATILE | VAR_REFERENCED))
		 && var->type == dtype_string) 
		dataseg_reloc_count++;
	return 0;
}

static int
_ds_reloc_fun(void *sym, void *data)
{
	struct variable *var = sym;
	size_t *pi = data;
	
	if (var->flags & (VAR_VOLATILE | VAR_REFERENCED)
	    && var->type == dtype_string)
		dataseg_reloc[(*pi)++] = var->off;
	return 0;
}

static int
_ds_literal_count_fun(void *sym, void *data)
{
	struct literal *lit = sym;
	size_t *offset = data;
	if (!(lit->flags & VAR_VOLATILE) && (lit->flags & VAR_REFERENCED)) {
		lit->off = *offset;
		*offset += B2STACK(strlen(lit->text) + 1);
	}
	return 0;
}

static int
_ds_literal_copy_fun(void *sym, void *data)
{
	struct literal *lit = sym;
	if (!(lit->flags & VAR_VOLATILE) && (lit->flags & VAR_REFERENCED)) 
		strcpy((char*)(dataseg + lit->off), lit->text);
	return 0;
}

static void
dataseg_layout()
{
	struct declvar *dv;
	size_t i;
	struct switch_stmt *sw;
	
	/* Count used variables and estimate the number of relocations
	   needed */
	dataseg_reloc_count = 0;
	symbol_enumerate(SYM_VARIABLE, _ds_variable_fun, NULL);
	
	/* Mark literals used to initialize variables as referenced */
	for (dv = declvar; dv; dv = dv->next) {
		if ((dv->var->flags & (VAR_VOLATILE | VAR_REFERENCED))
		    && dv->var->type == dtype_string) {
			dv->val.v.literal->flags |= VAR_REFERENCED;
		}
	}

	datasize = variable_count;
	/* Count referenced literals and adjust the data size */
	symbol_enumerate(SYM_LITERAL, _ds_literal_count_fun, &datasize);

	/* Account for switch translation tables */
	for (sw = switch_root; sw; sw = sw->next) {
		sw->off = datasize;
		datasize += sw->tabsize;
	}
	
	/* Allocate data segment and relocation table */
	dataseg = xcalloc(datasize, sizeof(STKVAL));
	dataseg_reloc = xcalloc(dataseg_reloc_count, sizeof *dataseg_reloc);

	/* Fill relocation table */
	i = 0;
	symbol_enumerate(SYM_VARIABLE, _ds_reloc_fun, &i);
	
	/* Initialize variables */
	for (dv = declvar; dv; dv = dv->next) {
		if (dv->var->flags & (VAR_VOLATILE | VAR_REFERENCED)) {
			switch (dv->var->type) {
			case dtype_string:
				dataseg[dv->var->off] =
					(STKVAL) dv->val.v.literal->off;
				break;

			case dtype_number:
				dataseg[dv->var->off] =
					(STKVAL) dv->val.v.number;
				break;

			default:
				abort();
			}
		}
	}	

	/* Place literals */
	symbol_enumerate(SYM_LITERAL, _ds_literal_copy_fun, NULL);
}


static int
_regex_compile_fun(void *sym, void *data)
{
	struct literal *lit = sym;
	if (lit->regex) {
		struct sym_regex *rp;
		for (rp = lit->regex; rp; rp = rp->next) 
			register_regex(rp);
	}
	return 0;
}

void
regex_layout()
{
	symbol_enumerate(SYM_LITERAL, _regex_compile_fun, NULL);
	finalize_regex();
}


static struct variable *auto_list;

static void
register_auto(struct variable *var)
{
	var->next = auto_list;
	auto_list = var;
}

static void
unregister_auto(struct variable *var)
{
	struct variable *p = auto_list, *prev = NULL;
	while (p) {
		struct variable *next = p->next;
		if (p == var) {
			if (prev)
				prev->next = next;
			else
				auto_list = next;
			p->next = NULL;
			return;
		}
		prev = p;
		p = next;
	}
}

static size_t
forget_autos(size_t nparam, size_t auto_count, size_t hidden_arg)
{
	size_t param_count = 0;
	struct variable *var = auto_list;
	while (var) {
		struct variable *next = var->next;
		switch (var->storage_class) {
		case storage_auto:
			var->off = auto_count++;
			break;
		case storage_param:
			var->off = nparam - param_count++;
			var->ord = var->off - (hidden_arg ? 1 : 0) - 1;
			break;
		default:
			abort();
		}
		while (var->storage_class != storage_extern) {
			struct variable *shadowed = var->shadowed;
			if (!shadowed) {
				find_and_remove(SYM_VARIABLE, var->name);
				break;
			}
			var->shadowed = NULL;
			var = variable_replace(var, shadowed);
		}
		var = next;
	}
	auto_list = NULL;
	return auto_count;
}

const char *
storage_class_str(storage_class_t sc)
{
	switch (sc) {
	case storage_extern:
		return "extern";
	case storage_auto:
		return "auto";
	case storage_param:
		return "param";
	}
	return "unknown?";
}


const char *
function_name()
{
	switch (outer_context) {
	case context_function:
		return func->name;
	case context_handler:
		return state_to_string(state_tag);
	default:
		return "";
	}
}

NODE *
declare_function(struct function *func, struct locus *loc, size_t nautos)
{
	NODE *node = alloc_node(node_type_funcdecl, loc);
	node->v.funcdecl.func = func;
	node->v.funcdecl.auto_count = nautos;
	node->v.funcdecl.tree = func->node; 
	return node;
}

Return to:

Send suggestions and report system problems to the System administrator.